Commit Graph

12660 Commits

Author SHA1 Message Date
kshitijk4poor
e8ccfffc0b fix(browser): a shared daemon is owned only by the Hermes whose command started it
Two same-user Hermes processes can reach one daemon. Both read bu-default.pid on the default
Browser Use name, and every Hermes shares the real-profile attach session. The identity checks (uid,
module, session leader, socket-dir binding) prove what the daemon is, not who started it, so both
Hermes registered its group. Killing either one then killed the browser the other was still using.
The real-profile attach's before/after pid-file diff had the same hole: two concurrent attaches
both see the file change.

Each agent-browser and browser-harness command now carries this process's spawn tag (spawn_env:
pid plus create time). The daemon it forks inherits the tag, and _own_local_daemon /
_own_harness_daemon register a daemon only when its tag names this process
(process_identity.spawned_by_this_process; an unreadable environment fails closed). The pid-file
diff is gone. Probed on macOS against agent-browser 0.26.0: the forked daemon carries the tag.

New tests start a verified daemon tagged with another live process. Each fails with its check
removed (the daemon gets registered) and passes with it.

Reported by Greptile on #137057 (two threads).
2026-10-29 16:58:09 +05:30
kshitijk4poor
57644ec000 fix(process): a family's stop path releases its group only once the group is empty
Same class as the router fix: nine stop paths released their group from the owner-death supervisor
as soon as the leader exited, but members that ignore TERM or outlive the leader keep the group
alive. Releasing it let those members survive a later kill -9 of this process.

Lightpanda, real-profile Chrome, embedded cua-driver, the TTS command provider, dashboard WhatsApp
pairing, the raft and WhatsApp bridges, verify's app server, agent-browser session groups, and
Browser Use harness daemons stopped by --reload now go through release_process_group_once_empty.

New test stops a raft bridge whose TERM-ignoring helper survives. It fails when raft releases
unconditionally, and the group stays covered with the fix. Test seams moved from the per-module
release_process_groups name to the shared helper.

Reported by Greptile on #137057 (thread on the router).
2026-10-29 16:58:09 +05:30
kshitijk4poor
8bc78140fc fix(local-runtime): stop() after a router crash stops its surviving model children and keeps them covered
The watcher's restart backoff: llama-server crashed, its model children still run in its group.
stop() skipped _terminate_tree (the leader was dead) and then unregistered the group anyway, so the
model children were neither stopped nor covered by the owner-death supervisor: they kept their VRAM
after Hermes exited.

stop() now ends with process_identity.stop_owned_group_survivors: for a group this process still
owns it TERMs what is left, waits, KILLs, and releases the group only once it is empty. A group it
fails to empty stays registered. New test crashes a stand-in router with a live model child and
calls stop(); it fails without the fix (the child survives, timed out after 10 s).

The router-tree test's sleep loop now uses tests.waiting.wait_until.

Reported by Greptile on #137057.
2026-10-29 16:58:09 +05:30
kshitijk4poor
41d0a947f4 fix(mcp): an owned spawn racing MCP discovery no longer hands MCP the owner-death supervisor
The supervisor starts lazily, on the first owned spawn of any family (slash worker, terminal job,
...). When that lands between an MCP stdio connect's before/after child snapshots, the delta holds
the supervisor and _filter_mcp_children kept it: MCP tracked it as its own server, and teardown or
the orphan sweep would group-kill it, leaving every other owned child unreaped if Hermes then died.

_filter_mcp_children now drops this process's supervisor, matched by its live pid and its script
argv (process_identity.is_owner_death_supervisor). New test drives the race with a real owned spawn
and a real supervisor; it fails with the check removed (supervisor pid in the adopted set).

Reported by Greptile on #137057.
2026-10-29 16:58:09 +05:30
kshitijk4poor
dd9e087a19 ci(process): mark the three detached spawns main gained since the ratchet
Rebasing onto main brought three new detached spawns the ratchet flags:
- gateway exec quick commands: awaited, and the timeout/cancel path kills the group (_stop_exec_tree);
- managed session workers: covered, the worker kills its own group when its owner dies (_die_with_owner);
- runtime gateway start: a gateway daemon launch that must outlive its launcher.
2026-10-29 16:58:09 +05:30
kshitijk4poor
c2b1e4391c refactor(process): one release-once-empty helper; the kernel and slash-worker tests stop racing a loaded host
LSP, the code kernel and the slash worker each had their own "release the group once nothing in
it is left" (a killpg(pgid, 0) probe; the kernel's version also waited for reaps). They are now
one helper, process_identity.release_process_group_once_empty(pgid, proc=, timeout=). It polls
the leader so a zombie leader does not keep the group alive, waits up to `timeout` for killed
members to be reaped by init, and keeps covering a group that still has a member. LSP's async
close path probes once (timeout=0), as before.

The slash worker used to probe exactly once right after SIGKILL. On a loaded macOS host (load
25+) init had not reaped the killed members yet, so a group that was about to be empty stayed
registered (test_close_stops_the_whole_group_then_releases_it, flaky). It now waits up to 1 s,
like the kernel did.

The kernel survivor test raced too: under load the cell child's `trap '' TERM` could land after
the teardown's SIGTERM, and the 5 s escalation could SIGKILL it. The child now signals once its
trap is installed, and the test turns escalation off (the escalation is not what it pins).

New tests/hermes_cli/test_process_identity_release_once_empty.py: an unreaped empty group is
released, a live member keeps it covered, a late exit is waited for, and Windows never releases.
Teeth: forcing the helper to always release, or to never release, turns 5 tests red in the 4
touched files. macOS: the 9 owned-child files, 78 tests, 3 runs in a row, 0 flaky.
2026-10-29 16:58:09 +05:30
kshitijk4poor
d1cb5d5cbd ci(process): no new detached spawn outside spawn_owned without a reason
A child started in its own session or group (start_new_session, os.setsid /
setpgid / setpgrp, windows_detach_popen_kwargs) does not die with a SIGKILLed
Hermes: it reparents to init and runs forever. That is how every family this PR
migrates leaked. With the families on spawn_owned, this keeps the class closed.

scripts/check_detached_spawns.py (AST) flags those shapes in the production trees
unless the line, or the line above it, says `detached-spawn: ok — <why>`. It runs
in scripts/check ("detached-spawns") and as a blocking lint.yml step. The baseline
is empty: every remaining site is on spawn_owned / own_process_groups, or carries
its reason. The reasons this commit adds are the census verdicts:
- must outlive the starter on purpose: restart watchers, /update and the updater
  hand-offs, dashboard/desktop/service launches, cron and kanban workers
  (restart-safe), the update-custody watchdog itself;
- awaited with a group kill on timeout: cron scripts, rg search, the Browser Use
  CLI, update completion (holds the checkout lock fd);
- covered by its own parent guard: the compute host (compute_host._parent_guard_loop
  flushes sessions; a supervisor KILL could cut that short);
- not a spawn: the wake-word `start_new_session` config key and event field.

tests/scripts/test_check_detached_spawns.py: each shape flagged, non-detached and
commented/string shapes not, the marker opts out on its line or the line above
and nowhere else, tests and the helper are out of scope, main() fails on a new
unmarked spawn, and the repository scan is empty. Teeth: appending an unmarked
start_new_session Popen to tools/file_operations_search.py turns
`scripts/check --only detached-spawns` red (rc 1); restoring it turns it green.
2026-10-29 16:58:09 +05:30
kshitijk4poor
bcf275a675 fix(dashboard): the WhatsApp pairing bridge dies with the dashboard that started it
The dashboard's WhatsApp onboarding starts `node bridge.js --pair-only` detached
(start_new_session) and stops it on cancel, expiry or supersession. A SIGKILLed or
OOM-killed dashboard skipped all of that, so the pairing bridge kept running and kept
the session directory busy until it timed out on its own.

It now starts through process_identity.spawn_owned (purpose "whatsapp-pairing"): it
still leads its own group, and that group dies with the dashboard however the
dashboard dies. _terminate_whatsapp_pairing and the watcher release the group once the
process has exited; one it failed to stop stays covered.

tests/hermes_cli/test_owned_agent_subprocs.py: a real kill -9 owner and a live control
owner through _spawn_whatsapp_pairing_process (child + same-group grandchild gone, the
live owner's tree untouched), plus terminate releasing the group. Reverting spawn_owned
to Popen turns the kill -9 case red.
2026-10-29 16:58:09 +05:30
kshitijk4poor
dd7a47917b chore(process): mark the browser/desktop spawns that must stay detached, with the reason
The detached-spawn check flags every start_new_session outside spawn_owned. Three in this family are
deliberate, and each line now says why:

- tools/bot_desktop/runtime.py (Bot Desktop launcher: Xvnc + Xfce per profile). The screen outlives
  whichever CLI or gateway started it. `hermes computer-use screen start` exits right after start(),
  launcher.pid records (pid, create_time) so any later process reports or stops it, and the gateway's
  display watcher idle-stops it (b41c8ddfc4, 71971e9205). Owning it would kill every CLI-started screen
  the moment the CLI exits.
- hermes_cli/browser_connect.py (/browser connect launching the user's debug Chrome). It is the user's
  browser: the connection persists in BROWSER_CDP_URL and a later session re-attaches to it, and Hermes
  never stops it (d1ee4915f3 made the detach explicit on both platforms).
- tools/bot_desktop/install.py (apt/dnf under sudo). Short-lived and awaited. The group exists only so
  the timeout kill reaches the package manager.

Comments only; no behaviour change.
2026-10-29 16:58:09 +05:30
kshitijk4poor
f3ebdfadbd fix(tui): the slash worker's process group dies with the gateway that owns it (orphans_after_30s 1 -> 0)
Symptom: when a TUI/Desktop gateway was SIGKILLed or OOM-killed while a slash worker ran a quick
command (`type: exec`, shell=True, up to 30 s), the command's shell and its children outlived
everything. The worker's own ppid watchdog (slash_worker._start_parent_death_watchdog, firefly
8b6a8f667d) only ends the worker: it polls for 2 s, waits up to 5 s for the in-flight command, then
os._exit()s, leaving the worker's group members to init. A normal close had the same hole:
_SlashWorker.close() signalled the worker pid alone, so closing a session mid-command left the
shell running too.

Change:
- _SlashWorker spawns the worker through process_identity.spawn_owned(purpose="slash-worker"): the
  worker still leads its own session (the reason it had start_new_session=True: mcp_tool's orphan
  sweep must never killpg the gateway's group), and the group now goes to the gateway's owner-death
  supervisor, so it dies the moment the gateway dies by any cause.
- close() TERMs, waits 1 s, then KILLs the worker's whole group, and releases it from the supervisor
  once the group is empty. A group is only signalled while its leader was alive on entry, so a dead
  worker's recycled pgid is never signalled; a group with survivors stays covered.
- The worker's ppid watchdog, its env knobs (HERMES_SLASH_WATCHDOG_POLL_S/_GRACE_S), --parent-pid
  plumbing and the in-flight event go: the supervisor reaps the worker AND its group, at the moment
  of death instead of 2-7 s later, with no thread per worker. --parent-pid is still accepted
  (suppressed) so a gateway started before an update can spawn the updated worker.
- Windows keeps its existing path (terminate/kill on the Popen; the layer-3 job object covers
  ownership).

Measured on Linux, real _SlashWorker + real worker, owner kill -9, survivors at t+30 s:
  idle worker:            main 0, branch 0
  worker running a quick: main 1 (`sleep 300`, alive at +30 s), branch 0 (gone by +2 s; the worker
                          itself took 5-10 s on main)
  close() mid-command:    main 1 survivor, branch 0

Tests: test_slash_worker_owned.py (live kill -9 of a real owner, with a live-owner control whose
worker must survive; close() stops a TERM-ignoring group then releases it; a dead worker's group is
never signalled; legacy --parent-pid accepted). Reverting spawn_owned to Popen fails the kill -9
test; reverting close() to signal the leader only fails the close test. The watchdog's unit tests
(test_slash_worker_watchdog.py) go with the watchdog; the cli-before-MCP-discovery ordering test
moves to the new file.
2026-10-29 16:58:09 +05:30
kshitijk4poor
7da67cfac1 refactor(process): spawn_owned is the one way to own a child; own/release replace the verb string
Names the owned-child API in process_identity layer 4:

- spawn_owned(argv, purpose=..., **popen_kwargs): starts the child as a session/group leader,
  hands the group to the owner-death supervisor and records it in the spawn ledger.
- own_process_groups(pgids) / release_process_groups(pgids): for groups something else spawned
  (MCP SDK servers, agent-browser's Chromium, harness daemons) and for children the owner stopped
  itself.

The stringly update_supervised_pgids("register"/"unregister", ...) becomes the private protocol
writer. llama-server's spawn_server(owned=True) now goes through spawn_owned instead of
re-spelling it. Adds a contract test for spawn_owned (group leader, supervisor registration,
ledger entry, release); it goes red when the registration is removed.
2026-10-29 16:58:09 +05:30
kshitijk4poor
bcec3f8a2f fix(process): the owner-death supervisor's control pipe pins encoding=utf-8
text=True without encoding= decodes with the ANSI code page on Windows (#55658); CI's
test_text_mode_subprocess_calls_pin_utf8 caught it on process_identity.py.
2026-10-29 16:58:09 +05:30
kshitijk4poor
9857b35c22 fix(process): log a supervisor that will not exit on release; the SIGKILL daemon test waits on the condition
Narrow the release-time wait to subprocess.TimeoutExpired and log it, instead of a silent blind
except (health BLE001/S110). subprocess becomes a top-level import. The Browser Use kill -9 test
polls with tests.waiting.wait_until rather than a hand-rolled sleep loop (HX013).
2026-10-29 16:58:09 +05:30
kshitijk4poor
97bef249ac fix(local-runtime): the llama-server tree dies with its owner on POSIX too (orphans_after_30s 2 -> 0)
On Windows the router lives in a KILL_ON_JOB_CLOSE job, so an owner crash takes the router and its
multi-GB model children down with it. On macOS/Linux spawn_server was a plain Popen: SIGKILL or
OOM of the owner left the whole tree resident on launchd/systemd until the next boot's recovery
pass (#126631). The idle sweeper and the crash watchdog both live inside the owner, so nothing
that could unload the model survives it.

spawn_server(owned=True) is the POSIX counterpart of the job: the router leads its own process
group (llama.cpp's router spawns model children with posix_spawn and no setpgid, so they stay in
it) and the group goes to the per-process owner-death supervisor, which killpg()s it the moment
the owner dies, by any cause. stop() releases the group after it has terminated the tree. No
extra process per router: the supervisor is shared with every other owned child of the process.

Same goal as #126657 (liuhao1024, a per-owner psutil poller re-checking (pid, create_time) every
2 s), reached through the shared supervisor instead: measured +6.6 MB USS per owner there, one
shared ~0.5 MB sh here, and the reap is immediate instead of up to one poll late.
PR_SET_PDEATHSIG is not an option: it fires when the spawning THREAD exits, and the router is
spawned from short-lived threads (lr-on-demand-boot, watchdog restarts).
2026-10-29 16:58:09 +05:30
kshitijk4poor
d66b9cd9ce refactor(process): one owner-death supervisor per Hermes process, in sh, owned by process_identity
The parent-death supervisor that only stdio MCP servers could use (tools/mcp_death_supervisor.py
+ the client in tools/mcp_tool.py) becomes layer 4 of hermes_cli/process_identity.py, next to the
spawn ledger and the Windows job object, so every long-lived child family can use the same path
instead of shipping its own reaper. MCP's three call sites now call
process_identity.update_supervised_pgids; the protocol (register/unregister <pgid>, EOF = owner
died, TERM -> 3 s -> KILL, unsafe targets refused, replay on respawn, release when empty) is
unchanged and every existing contract test moves with it.

The supervisor itself is now POSIX sh (hermes_cli/process_supervisor.sh) instead of a second
CPython: it stays resident for the life of any Hermes process with a supervised child, and an
idle sh is 0.5 MB USS against 8.1 MB for the Python supervisor (Linux, py3.14, measured).
Malformed and over-long lines are skipped exactly as before; the only protocol difference is
that a line is no longer length-capped while being read (sh's read has no cap), which only a
writer inside Hermes could exploit.
2026-10-29 16:58:09 +05:30
kshitijk4poor
679ec082c8 refactor(cli): one builder for a turn the owner never saw; pin the unretrieved-future fix
The pre-submit notice and the never-sent submit return the same unadmitted
result. GatewayAgent._unadmitted now builds it for both: it gives the
/model --once pick back, writes no history row and sets admitted=False.
The notice path had nothing to give back, so behaviour there is unchanged.

New test: a send that raises after the reader has failed its request logs
no 'Future exception was never retrieved'. It fails without the
future.exception() call in rpc's finally. The comment on that line now
says what it is for.
2026-10-29 16:30:39 +05:30
kshitijk4poor
d72b65595e fix(cli): a closing socket refuses before the send, and an unsent prompt keeps its turn
Three fixes from review:

- A keepalive timeout fails the socket into CLOSING. websockets then waits
  up to close_timeout (10 s) for the peer before the reader ends. A send in
  that window is never written, but it used to block the caller for that
  long and then report DISCONNECTED. GatewayClient.rpc now refuses with
  NOT_SENT whenever the socket isn't OPEN. Live probe with a silent peer: it
  now answers in 0.0 s with NOT_SENT; the previous head took 5.4 s, reported
  DISCONNECTED and logged "Future exception was never retrieved".
- When prompt.submit gets NOT_SENT, the turn is handled like a pre-submit
  notice: the /model --once pick goes back, no history row is written, and
  the result carries admitted=False. "Nothing was sent" is then true for the
  resend too.
- rpc reads the exception of a future the reader failed while the send was
  raising, so asyncio no longer logs it as never retrieved.

The test fakes for GatewayClient sockets now carry `state = State.OPEN`,
which every real websockets connection has.
2026-10-29 16:30:39 +05:30
kshitijk4poor
7303b01fd6 fix(cli): a request after the gateway socket closed is reported as not sent
When the keepalive times out, the socket closes and GatewayClient's reader
ends before the dock's next poll. websockets refuses any later send on that
socket without writing it, so the frame never leaves. GatewayClient.rpc now
raises NOT_SENT once the reader has ended, instead of DISCONNECTED ("turn
outcome is unknown; do not resend"). A prompt.submit that hits this path
tells the user nothing was sent, so they know to send it again. A send that
fails while the reader is still alive stays DISCONNECTED, because the frame
may already have left.

NOT_SENT moves next to DISCONNECTED in gateway_client; gateway_connection
imports it, so gateway_queue's `str(exc) == NOT_SENT` check is unchanged.
2026-10-29 16:30:39 +05:30
Teknium
2a5aa2a406 refactor(cli): one copy of the gateway-disconnected text
The salvaged fix added a second copy of the "turn outcome is unknown" text in
gateway_client next to gateway_connection's DISCONNECTED. Keep the one
definition in gateway_client (the lower module) and import it into
gateway_connection, so the send-side, read-side and connection-loss errors
cannot drift apart.
2026-10-29 16:30:39 +05:30
Turgut Kural
7e7d9a043d fix(cli): a send on a dead gateway socket no longer kills the spinner thread
GatewayClient.rpc let websockets' ConnectionClosedError escape from send():
after a keepalive ping timeout the dock's subagent.list poll raised it past
callers that catch GatewayClientError, and the bare spinner loop died with it,
leaving the spinner and live-work dock frozen for the rest of the session.

rpc now reports a failed send as the same unknown-outcome GatewayClientError a
lost answer already gets, and the monitor tick skips a beat on a failure
instead of ending the thread that runs it.

(cherry picked from commit ea136305ac597dcd62bc569426321d9d601034aa)
(cherry picked from commit cedb79f9a691f9ef9b8f3d9c04fdfefb63d9fb94)
(cherry picked from commit f5c1b54199dc02e9654a6d11ba6ee5e0e2a84cc4)
2026-10-29 16:30:39 +05:30
Teknium
ef75bc7088 fix(plugins): quoted /proc redirects stay writes; own-module from-imports stop warning
Greptile on #146352: `printf x > "/proc/self/comm"` slipped past the write check because the
redirect form required an unquoted path, and `from plugins.memory.<name> import _db` still warned
because only the module part was matched against the plugin's own files. Both now covered, with
attack/false-positive twins red on the previous head.
2026-10-28 23:07:47 -07:00
Teknium
0040f02b5c fix(plugins): clear catalog sweep 1028 scanner false positives and close three validator gaps
Install scanner (tools/plugin_guard*, PLUGIN_SCANNER_VERSION bumped once):
- hardcoded_secret: a PostHog project key (phc_, write-only ingest key) joins the
  Google installed-app secret as a public client key -> high (caution), only
  when every matched literal on the line has a public prefix (telesec
  telemetry.py:27 was dangerous). phx_ personal keys and any other token stay
  critical.
- proc_access: reads of /proc/self|<pid>/{cgroup,mountinfo,stat,status,...}
  (container placement, pid start time) land at low instead of high
  (hermes-lcm-x cpu_capacity.py was caution). environ, cmdline, mem, maps, fd,
  root/cwd, ns, bare /proc/self, any unlisted leaf and any write keep high.
  Generalises #144304's cgroup/mountinfo allowance and keeps the finding
  visible instead of dropping it.
- bytecode_file: a committed .pyc/.pyo (git ls-files; plus any bytecode outside
  __pycache__) is a high structural finding, the binary_file tier (rule 17;
  hermes-emotion shipped tests/__pycache__/*.pyc and scanned safe). Untracked
  caches the validate run writes are not flagged.

Validator (hermes plugins validate, warnings only):
- private imports: gateway.session_context.get_session_env is the documented
  route (plugins/index.md) and a plugin's fallback import of its own install
  path (plugins.memory.openltm._db) is not a core import.
- new warning for private-method calls on core handles (SessionDB, AIAgent,
  GatewayRunner, PluginContext) the plugin does not define itself
  (opencode-sync db._execute_write, runner._evict_cached_agent).
- desktop surface review warning for raw window.hermesDesktop calls and app
  markup selectors ([data-slot], [data-tree-*], [data-pane-host]) in CSS text
  or closest() (squad-hub, novel-reader, search-sources).
2026-10-28 23:07:47 -07:00
Teknium
fbb0d63a92 fix(gateway): drop a silence marker that ends a real reply
A model that answers and then closes the same message with a marker line
("Here is the answer.\n\nNO_REPLY") had the marker delivered as text: the
silence filters only match a response that is exactly a marker. Strip a
marker on the reply's last line at every delivery door (final send, stream
previews and final edit, crash-left replay, Bot Mode relays). A bare marker
still goes through the silence verdict, a marker inside a line is prose, and
stored history keeps the model's text.
2026-10-28 21:22:34 -07:00
kshitijk4poor
c73b595460 fix: register approvals.discord_prompt_timeout in the default config
The Discord adapter reads `approvals.discord_prompt_timeout` (default
300). The Discord docs tell users to raise it, but the key was missing
from DEFAULT_CONFIG. `hermes config` never showed it, and migration
never added it.

It is now registered with its 300 s default, next to
`approvals.timeout`. The reader, its clamping and its behaviour are
unchanged. config_defaults.py may not grow, so a three-line comment
that repeated the block comment above (why `timeout` defaults to 300)
is dropped. The approvals key table in the security guide gains a row
for it.

New invariant test: the default appears through `load_config`, and a
value written to the profile's config.yaml reaches both `load_config`
and the Discord views' reader. It fails before this commit.

Raised by review of #145948.
2026-10-29 09:45:17 +05:30
Teknium
dbde5a991a fix(kanban): the owner refuses a worker that dials into a restart wait opened after discovery
connect_gateway's restart-wait refusal read the state discovery returned. A restart that began
between discovery and the WebSocket dial still admitted the Kanban worker on its interactive
ticket into the after-turn wait, where each prompt.receipt answer refreshed its silence budget
and held `hermes update` until the forced-restart deadline.

The policy now rides the ticket: inside outside_restart_wait() the session-ticket request carries
`restart_wait: "refuse"`, the ticket store records it on the grant, and GatewayRuntimeAPI decides
admission from the grant at redeem time, so the owner closes the socket (1013) whenever its
restart wait is open by the time the worker connects. Interactive clients still attach (#139041).
An owner older than the client refuses the unknown parameter; the client re-mints without it and
keeps the pre-dial check rather than stranding the worker until that owner restarts.
2026-10-28 20:40:14 -07:00
Teknium
eace3e056e fix(kanban): a worker cut by a restart's after-turn wait waits for the next owner outside it
`hermes update` with a Kanban card in flight sat in "still draining ... waiting on 1 active
work unit(s): managed run" until agent.restart_after_turn_timeout. The restart wait cuts every
socket opened before it (d710b2e346) so its client goes to the next owner. Since c480d67e5f
the worker redials on any transport loss, and connect_gateway attaches to an owner in its
restart wait (that window admits clients so a human can answer a parked prompt, #139041).
The worker re-entered the wait and kept polling prompt.receipt. Every answer refreshed its
silence budget, so the worker never exited, `_watch_submitter` never ended the card's
managed turn, and the drain waited on that turn until its cap.

connect_gateway now refuses an owner in restart wait as `draining`/`restart_wait` inside
`outside_restart_wait()`, and the Kanban worker dials inside it. The worker waits outside the
wait like any other transient owner state. Either the turn finishes and the next owner holds
its receipt, or OWNER_WAIT_S of silence ends the worker, which ends the turn and releases the
restart. Interactive clients still attach to the wait.

Found on CI E2E dispatch (tests/e2e/core/upgrade/handoff/test_handoff_from_head.py).
2026-10-28 20:40:14 -07:00
Teknium
01dfee9a41 fix(webapp): a Webapp tab installs a desktop plugin from any source the CLI takes
Private plugins live behind ssh keys or in local folders. The Webapp's
host-side desktop install accepted https only; it now takes git@/ssh://,
file:// and http:// like the agent installer and native Desktop, per the
maintainer ruling on #146189.
2026-10-28 19:53:28 -07:00
Teknium
43ee1b0872 revert(plugins): Desktop, Webapp and dashboard installs take every source the CLI takes
Maintainer ruling: Desktop and the Webapp must keep installing private
plugins. The https-only source rule this branch added
(guiInstallSourceRefusal in the native install IPC, gui_install_source_refusal
in plugins.manage install and POST /api/dashboard/agent-plugins/install)
refused git@/ssh:// private repos, http:// and file:// local folders. It
goes, with its tests, and the user guide says Install from Git takes any
git source `hermes plugins install` accepts.

The symlink / plain-tree / 64 MB refusal in publishDesktopTree, the
reconcile refusal report in the install dialog and the forced-reinstall
fix stay.
2026-10-28 19:53:28 -07:00
Teknium
12944611f0 fix(plugins): Desktop and Webapp agent-plugin installs clone https only
plugins.manage install (native Desktop, the Webapp) and the dashboard's
POST /api/dashboard/agent-plugins/install handed any identifier to
dashboard_install_plugin, so a click could clone a file:// folder, an
ssh/git@ source through the host's ssh-agent, or plain http://. Both GUI
doors now refuse a non-https custom source before cloning, through one
helper (gui_install_source_refusal). A catalog_name install clones the
catalog's own source and is unchanged; `hermes plugins install` keeps
every scheme it documents.
2026-10-28 19:53:28 -07:00
Teknium
c70876b9fe fix(dashboard): cron create accepts timezone/grace_minutes
CronJobCreate had no such fields, so POST /api/cron/jobs silently dropped them (a bad zone returned 200 and stored an unpinned job) while PATCH validated them. Pass both to create_job, which validates.
2026-10-28 19:40:40 -07:00
yliu325
b81e71addd feat(cron): optional per-job grace_minutes override
The catch-up window (how late a missed cron occurrence may run instead of being skipped) was
half the job's period, clamped to 120s-2h, for every job. A job can now override it outright:
0-1440 minutes, `0` meaning never catch up.

`grace_minutes` is a real 0, not "unset" — and the obvious write pattern would eat it:
`v in {None, "", False}` (the `workdir` update lambda) and `if value:` both treat `0` as
False in Python. Both doors therefore share `jobs_time.normalize_grace_minutes`, reads test
`is None`, and the renderer formats before testing truthiness.

The override moves the dispatch stamp too: `_classify_dispatch_lateness` and the dispatch
health metric read the same window, so a job the scheduler calls "late" is never reported
overdue by the dashboard.

Refused on `once`/`interval` schedules: the window describes a missed wall clock, and a
duration has none.

Split from the timezone commit so it can be reverted alone.
2026-10-28 19:40:40 -07:00
yliu325
bfa67878cd fix(cron): per-job timezone drives schedule compute and due-scan
A job may pin its own IANA timezone; its cron expression is then that zone's wall clock,
independent of the profile's configured timezone. Absent/None inherits the profile, so an
existing jobs.json keeps byte-identical behaviour and needs no migration.

The dispatch path needs the pin as much as the compute does. `compute_next_run()` resolves
the zone as job pin -> profile zone -> base offset, and every site that writes `next_run_at`
now passes it (advance, claim, resume, re-arm, recovery, and the quota/unreachable
planners); one missed site re-fires or skips a slot because the stored instant and the
expression would be read in different zones.

`_evaluate_due_job()` normalizes the stored instant into the JOB's zone, which hands every
downstream cron predicate the job's clock, and a pinned job skips
`_repair_timezone_shifted_cron` outright. That repair exists for jobs that FOLLOW the profile
zone across a zone change: on a pinned job its wall-clock comparison reads a due occurrence
as still-in-the-future and re-anchors past it.

Failing shape this fixes (profile America/Los_Angeles, job 0 9 * * 1-5 pinned to
America/New_York, scanned at 09:00 New York): `get_due_jobs()` returned [] and the job was
re-anchored to the next day, i.e. job zones east of the profile zone silently never fired.
The regression test drives the public store API and asserts both the fire and the absence of
the repair, and is proven red on main ([] and a rewritten instant).

Knobs live in the new sibling `cron/jobs_time.py`; `cron/jobs.py` stays over the file-lines
ratchet and only gained the call-site plumbing.
2026-10-28 19:40:40 -07:00
Victor Kyriazakos
fa2befeed7 fix(gateway): join delegations in the turn when interim messages are off
On a messaging chat with display.interim_assistant_messages off, a top-level
delegate_task still produced two messages: a "checks are running, I don't have
the findings yet" reply and, later, the real answer. Top-level model
delegations always run in the background (ea8a8b4af8), and the tool text tells
the model to "give a one-line status and END YOUR TURN" (c89f3b8800). That
status is the turn's final answer, not interim text, so no display setting
held it back.

New key delegation.gateway_mode: auto | inline | background (alias async).
auto (default) joins the children inside the turn on a messaging chat whose
resolved interim setting is off (global, display.platforms.<p> override or
platform default). The parent waits in the tool call, gets the results there
and sends one answer. API, local and webhook surfaces keep the background
path under auto. Chats with interim messages on are unchanged: same schema
bytes, same async dispatch.

How it works:
- The gateway resolves the mode from the turn's own profile-scoped config
  when it builds a session's agent (gateway/session_execution.py), and the
  agent's first tool build freezes it (like the one-shot pin).
- An inline session carries the joined delegate_task variant the one-shot
  path already uses: "results return in this tool call", no live-control
  parameters, no END YOUR TURN.
- Dispatch follows the delegate_task schema the session carries
  (session_joins_delegation), so schema and behaviour cannot disagree. The
  schema rides the session's tools[] pin: a config change applies from the
  next session (/new), as delegation.backend does, and a cache eviction or
  restart never flips a running chat.
- Inline children run on the existing synchronous path: attached to the
  parent, so /stop and an interrupting follow-up stop them; the per-child
  heartbeat keeps the parent's activity fresh for the inactivity watchdog;
  the async completion registry is not used. Nested and one-shot delegation
  are unchanged.

Refs #95522.
2026-10-28 19:35:16 -07:00
Teknium
0216b1a320 fix(sessions): refresh epoch survives compression rotation; --session targets the tip
With compression.in_place: false a rotation creates a child whose
model_config did not carry prompt_refresh_epoch, so after any past
profile-wide refresh-prompts request the child looked stale and rebuilt its
prompt (an extra prefix-cache break) on the first restore after eviction or
restart. Carry the key as conversation-wide state.

--session with a compressed conversation's original id wrote the request
for the ended root, which the live tip never reads: the CLI reported
success and nothing refreshed. Resolve to the compression tip first.
2026-10-28 19:30:48 -07:00
Victor Kyriazakos
e240d617e8 feat(sessions): refresh-prompts lets continuing sessions adopt updated prompt sources
A continuing session replays its stored system prompt verbatim on every turn
so the provider prefix cache stays warm. The gateway restores that prompt from
the session row on each fresh agent, and warm cached agents keep it in memory,
so SOUL.md edits, new or edited skills and project-context changes never
reach a long-running conversation until /new, which also drops the history.
Operators who push profile updates and restart the gateway had no way to make
existing conversations pick them up.

`hermes sessions refresh-prompts [--session ID] [--json]` records a refresh
epoch in the profile's state.db (state_meta, one counter orders profile-wide
and per-session requests). At the start of a continuing session's next turn,
_restore_or_build_system_prompt compares that epoch with the one stamped in
the session's model_config when its prompt was built. When the stored prompt
is older it follows the Bot Chat capability-refresh precedent in the same
function: tools[] pin restored first, skills prompt cache and snapshot
cleared, prompt rebuilt through _build_system_prompt (memory reloaded and
plugin sections re-rendered, as at a compaction boundary), cache break
recorded, on_session_start not fired, new bytes and epoch persisted so the
following turns restore them verbatim. One cache break per request.

Warm agents (gateway agent cache, TUI/Desktop) run the same check from
build_turn_context against the epoch they saw when their prompt was set, so
the verb works with the gateway running. A session first built after a
request is stamped with it and does not rebuild again.

With no request recorded, the stored prompt is reused byte-identically. The
only added work per continuing turn is one state_meta point read. No file
scanning, no config key, no watcher, no mid-turn mutation.

The tools[] pin is kept on purpose: the refresh is about instructions, and
tool changes already reach long sessions at the compaction boundary. The
cache break is recorded as the existing system_prompt_rebuild cause rather
than a new one, which would change the shared-metrics contract and schemas.

Related: #141154 (per-turn source hashing, alternative design), #74622.
2026-10-28 19:30:48 -07:00
Teknium
50f259a83f fix(webapp): refuse an unbound profile ticket and bind explicit profiles on launch sockets
Follow-up to the Webapp socket profile scope fix (#146097):

- chat_ws.gateway_ws: a ticket that names a profile while the gateway has
  no session authority bound (the listener unbinding window) closes 1013
  instead of serving the socket as the launch profile.
- ws_legacy_fallback.dispatch_legacy: on a launch-profile socket, a legacy
  verb with an explicit `profile` now runs in that profile's runtime scope
  (refused 4064 when the name does not resolve), as it already did on a
  non-launch ticket. Now that the socket runs in the launch scope, a
  handler that ignores `profile` would otherwise read the launch
  profile's secrets instead of refusing the unscoped read.
- test_webapp_socket_profile_scope: drive the real gateway_ws + handle_ws
  + session authorities + legacy billing.state over the socket (only the
  upgrade gate and HTTP substituted) instead of a stubbed handle_ws.
2026-10-28 19:09:39 -07:00
Teknium
62f79a434d docs(security): allow_private_urls guards cloud browsers and web tools, not the local sidecar
security.allow_private_urls: false refuses private URLs for web_extract, vision/media
fetches and cloud/CDP browsers, but browser_exec under a cloud provider routes them to
a local Chromium sidecar (browser.auto_local_for_private_urls, default true), and the
plain local Chromium with a local terminal skips the guard by design. Say so in the
security and browser docs, configuration reference, DEFAULT_CONFIG comments and
cli-config.yaml.example, and name auto_local_for_private_urls: false as the way to
refuse. Also correct browser.md's claim that redirects to private hosts are blocked:
routing is decided from URL literals, and a redirect stays on the cloud browser.
2026-10-28 19:07:59 -07:00
Teknium
669df020d9 fix(cli,tui): a stalled event loop no longer submits a held Enter ahead of a waiting paste chunk
The held trailing Enter decides on a 250 ms timer. When the event loop
stalls past that window with the next paste chunk already in stdin, the
timer ran before the chunk was read and submitted the first line alone:

- Ink: Node runs the timers phase before the poll phase, and
  stdin.readableLength cannot see bytes libuv has not read yet. The flush
  now hops to setImmediate (after this turn's poll) and runs only if no
  read replaced keyParseState in between.
- Classic: a signal handler that interrupts the selector past its deadline
  returns no events (PEP 475), so the due call_later ran before the reader.
  The settle now runs two call_soon hops later, after the next selector
  pass's readers. Text arriving while an Enter is held also keeps the paste
  burst alive however late it is read, so the paste's own trailing Enter
  stays a newline instead of submitting the joined text.
2026-10-28 19:05:57 -07:00
Teknium
7745fa7f92 fix(cli,tui): a paste still arriving keeps its trailing newline
Paste detection expired BURST_END_QUIET_S after the last pasted newline,
not after input went quiet. A non-bracketed paste delivered in reads
100 ms apart, with newlines only in the first and last read, therefore
treated its trailing Enter as a scripted text+Enter and submitted (and
cleared) the multi-line draft. Any input inside the quiet window now
keeps the paste burst alive, in the classic CLI (note_text_change) and
the Ink parser (pasteBurstAt). One-write text+Enter and a lone Enter
still submit.
2026-10-28 19:05:57 -07:00
Teknium
4889361215 fix(cli,tui): keep the draft and split pastes intact in the burst-Enter submit
Review round on the one-write text + Enter submit:

- Classic: the provisional newline goes in at the cursor, so settling restores
  the exact pre-Enter document (text + cursor) instead of dropping the last
  character. A scripted edit inside a draft now submits the whole draft.
- Ink: the decision is kept across stdin reads. A single-line read ending in CR
  emits its text and holds the CR in the parser state; App's flush timer
  releases it as return after BURST_END_QUIET_MS (250 ms) of no input, and any
  read inside the window turns it into paste content. A CR-ending read within
  250 ms of a pasted line break stays content. A paste split across reads (both
  directions) no longer submits itself. The textInput submit re-sync is no
  longer needed (text and return land in separate batches) and is reverted.
- Tests: injected clock (cli_enter_burst.monotonic, also read by
  _tui_on_text_changed); the single-write test proves the delayed callback
  path; new mid-draft and split-read cases.
2026-10-28 19:05:57 -07:00
Teknium
2432e31e2b fix(cli,tui): text + Enter in one write submits instead of inserting a newline
Scripted drivers deliver the text and its Enter in ONE read (`tmux send-keys
'text' Enter`, a PTY write of `text\r`). The classic CLI's #10994 guard treats
every Enter within 50 ms of a buffer change as a pasted newline, so the burst
never submitted; the Ink TUI routed the CR-carrying token through the paste path
and dropped it.

Classic: an Enter with more keys of the same read queued, or the tail Enter of a
burst that already held one, stays a newline (unbracketed multi-line paste is
unchanged). The lone Enter that ends a burst inserts a provisional newline and
submits once input stays quiet for 250 ms; input in that window (a paste split
across reads) keeps the newline. New sibling hermes_cli/cli_enter_burst.py.

Ink: a single-line text token ending in CR peels the CR into its own return key;
multi-line tokens keep it as paste content. TextInput re-syncs its local draft on
every submit, since text + submit in one React batch left the parent value
unchanged and the submitted text stuck in the composer.
2026-10-28 19:05:57 -07:00
Teknium
0a93a2341f fix(vault): fill saved logins on Camofox pages through a browser page backend seam
browser_vault reached pages only through the task's CDP supervisor. Camofox (now a plugin) has no
CDP endpoint, so every fill on a Camofox tab ended with "Could not determine the current page
origin": the username from browser_vault list worked, the password never filled.

ctx.register_browser_page_backend lets a plugin browser carry the vault's origin read, form
inspection and fill script to its own page. Core keeps the secret contract: the exact-origin
pre-check and in-page re-check, the Bot Desktop takeover check, an in-page try/catch around the
secret script, and fixed failure text on that path. Registration follows the login-backend
provenance rule (bundled, or catalog verified/official at its pin) and is refused under
plugins.isolation: host.

Consolidates the core half of #127179 and #135204 (the Camofox halves already shipped in the
official plugin); the in-page wrapper follows #114414.

Co-authored-by: Jonathan Bruce <jonathan.bruce369@gmail.com>
Co-authored-by: clsferguson <cferguson@live.ca>
Co-authored-by: Benjamin PERRY <benjaminperry6@yahoo.fr>
2026-10-28 19:00:07 -07:00
skyeyesec333
32633eb963 fix(billing): bind RPC profile scope and honor scoped Portal routing 2026-10-28 18:55:56 -07:00
Teknium
8b55721189 fix(webapp): run the Webapp's gateway socket in the served profile's scope
A browser tab's /api/ws reaches a gateway through the dashboard mount
(chat_ws.gateway_ws), not the native ticket path (gateway/run_api.py) that wraps
the socket in owner_scope(authority). Legacy handlers the socket falls back to
(billing.state, subscription.state, usage.bars, and the account reads they spawn
on worker threads) bind no scope of their own, so on a multiplexed gateway every
Webapp billing/usage read resolved the Nous Portal override with no profile
secret scope: errors.log logged "HERMES_PORTAL_BASE_URL/NOUS_PORTAL_BASE_URL
unreadable — no profile secret scope on a multiplexed call", the override was
dropped, the stored non-production portal_base_url was then refused by the
allowlist ("ignoring invalid portal_base_url ... using default") and the token
resolution fell back to the production Portal.

gateway_ws now binds owner_scope() of the authority it serves (the ticket's
profile when the tab named one), exactly as the native ticket path does, so
every handler on the socket (and every thread it copies its context into) reads
the right profile's secrets.

Found on Hermes Cloud staging.
2026-10-28 18:55:56 -07:00
Teknium
a4b2ba62dc fix(update): a checkout-lock probe never reads another probe as a running update
After a killed update, the first launch could refuse with "Gateway draining:
update_paused" although nothing was updating. A killed update always leaves a
dead .hermes-update-in-progress marker; while it is there, every ensure poll
probes the checkout kernel lock, and the gateway that ensure just started
probes the same lock while it boots (its launch reclaims that marker). The
probe took the lock exclusively, so two probes in the same instant read each
other as a holder, and the client's single sample fenced the launch.

checkout_lock_held now takes a SHARED lock (POSIX flock LOCK_SH; Windows
LockFileEx without LOCKFILE_EXCLUSIVE_LOCK over the owner byte and the 16
lease bytes). Holders still lock exclusively, so a real holder (or a leased
child of a dead one) still fences; probes never conflict with each other.
2026-10-28 18:53:42 -07:00
Teknium
e0c52c4fbf fix(plugins): catalog installs keep the inspected commit; older backends ask; partial installs need Force
Three follow-ups to the install dialog holding an install to the commit it showed.

- Catalog picks. The backend reloads the live catalog entry at Install, so a
  re-pin between the dialog's inspection and the click installed (and, through
  the one checkout, published the desktop half of) a tree nobody reviewed;
  the renderer sent no inspected_sha for catalog sources and neither the
  catalog install nor reuse of a disabled tree read it. Now the catalog
  install compares the commit it actually checked out with the inspected sha
  peeled through the clone (annotated-tag pins still install), a disabled tree
  is reused only at that commit (or its recorded tag pin), and catalog dialogs
  send it: the backend's inspect sha in the Webapp, the shown reviewed pin on
  native Desktop (whose Electron probe reads the branch tip). After a re-pin
  refusal the native dialog re-reads the catalog for the new pin. The record
  stays the catalog's pinned record. Electron's desktop clone uses the same
  reviewed commit and peels a tag pin.
- Older backends. A backend that refuses inspected_sha at admission is no
  longer retried without it behind the user's back: the dialog explains that
  this backend cannot guarantee the reviewed version is what gets installed
  (update it for that guarantee) and installs only on an explicit
  "Install anyway" (profile kept); Cancel installs nothing.
- Partial installs. Native Desktop on a remote backend could install the agent
  half at commit A, fail the desktop half (source moved), re-review to B and
  let a second Install put the desktop half down at B beside the agent half at
  A. That is now reported as a partial install (agent half in at A, desktop
  half not); Install stays disabled until Force reinstall, which replaces both
  halves with the version shown.
2026-10-28 17:21:32 -07:00
Teknium
e4b0ab2365 fix(plugins): retry only a real admission refusal; re-review a moved source
Two follow-ups to the install dialog holding an install to the commit it
inspected.

- An install is resent without `inspected_sha` only for an older backend's
  admission refusal: a JsonRpcGatewayError with code 4000 whose message
  opens with `validate_params`' prefix. Matching the text anywhere also
  matched a 5026 install failure that forwards a git server's clone error,
  so that server could get the reviewed commit dropped.
- A refusal because the source moved past the reviewed commit now carries a
  structured marker: the backend raises PluginSourceMoved and
  `plugins.manage` answers 5026 with `data.reason == "source_moved"` (agent
  install and `install_desktop`); Electron's desktop install returns
  `sourceMoved: true` when the reviewed commit cannot be checked out. The
  dialog answers it by dropping its inspection, reading the source again
  and naming the new commit; Install waits for it. Retry used to resend the
  old commit and fail the same way every time. A pin the user typed is not
  re-reviewed, and nothing from the stale review installs (the desktop half
  is skipped when the agent half was refused).
2026-10-28 17:21:32 -07:00
Teknium
2c64c7fdb7 fix(plugins): an install dialog installs only the commit it inspected
The dialog inspects a source and shows its commit, but the agent half
cloned the branch tip at Install time: a branch that moved in between put
down a tree nobody reviewed, and the desktop half copied out of that
checkout followed it. Native Electron's probe returned no commit at all, so
its desktop clone had the same gap.

- plugins.manage install takes `inspected_sha` (custom sources without a
  pin). The clone stays an ordinary branch checkout and is refused when its
  tip is not that commit: "The source changed since you reviewed it ...
  Re-open the install dialog". Not `ref`, which records a pin that refuses
  every later `update`; not a detached checkout at the old commit, which
  `git pull` cannot update. Catalog picks keep their pin.
- That install drops inspect's kept answer for the source, so re-opening
  the dialog reads the moved branch instead of the stale commit.
- Electron: probePluginRepo returns the commit it read; installDesktopPlugin
  takes it and installs exactly that tree (fetch + verify) or refuses.
2026-10-28 17:21:32 -07:00
Teknium
ccba14cb75 fix(desktop-plugins): real copies of linked root checkouts; desktop success from disk; layout moves need no consent
- A dev checkout linked at plugins/<name> with a root plugin.js: Electron's
  publish copied the link itself (fs.cp keeps a top-level link), so the
  "copy" was the checkout, the marker was written into it, and the prune
  (which skipped linked folders) left a ghost after the link went. Copy from
  the resolved folder; never keep or stamp a link at <root>/<name>; the prune
  follows links and drops only the link. The host twin gets the same
  link-target and prune handling (its copytree already copied the files).
- The install dialog decided desktop success from the reconcile's touched
  list, which also names folders the pass deleted: a force reinstall whose
  new tree dropped its desktop entry read as installed. Read the folder
  (Electron fs bridge, or the host's /api/desktop-plugins) instead.
- Re-pin consent: the desktop half is a presence surface, so moving it
  between plugin.js and desktop/plugin.js widens nothing.
2026-10-28 17:21:32 -07:00
Teknium
990bfbdf6c fix(plugins): re-pin consent sees a root-layout desktop half too
plugin_surface only recognised desktop/plugin.js, so a catalog re-pin
that added a root plugin.js (a layout every installer accepts) was not
reported as a widened desktop surface. Read the installers' shared
desktop_source rule instead.
2026-10-28 17:21:32 -07:00