Commit Graph

6348 Commits

Author SHA1 Message Date
Ben Barclay
06bcbc2ab7 fix(tui_gateway): hold foreign owners through the post-turn drain; keep owners across agent rebuilds
The post-turn safety-net drain took every event off the shared queue but held only the draining
session's owners. Idle session A's completion, sitting in session B's hands while B checked
ownership, left A in neither the queue nor a hold, so a reaper could close A and the requeued notice
was then dropped as unowned. The drain now dequeues through drained_for(), which holds every
dequeued event's owner until the foreign events are requeued and its own are routed.

_rebuild_session_agent (Bot Chat capability refresh) installed a replacement agent without the old
one's raw spawning ids, so a process started before a compression rotation stopped pinning its
session and fell outside the new agent's close kill set. The replacement now inherits them.
2026-10-20 02:24:45 -07:00
Ben Barclay
5694f8f733 fix(process): hold a notice's owner through routing, keep unpublished exits out of pruning
Three gaps in the live-state keepalive:

- Dequeue is not delivery. The poller takes events off the shared queue before routing them, so
  between get() and turn admission the owner was in neither the queue nor running, and a reaper could
  close it; a foreign profile's poller holding the event then dropped it as unowned. Pollers now
  dequeue through take_ready(), which records an in-flight hold per owner in the same queue-mutex
  critical section as the dequeue, released only after routing (admit, requeue or drop) returns. The
  post-turn safety-net drain holds the session's owners the same way.
- An exit recorded but not yet published could be pruned by a concurrent spawn, erasing the only
  record that a notice was coming. _prune_if_needed now skips finish-claimed entries whose
  completion event is unset.
- Stop only ignored queued notices, so a running watch kept a stopped, disconnected session alive
  forever. A stopped session can admit no notification turn until the user's next prompt, so it is
  never pinned by pending notices.
2026-10-20 02:24:45 -07:00
Ben Barclay
79055ee5ed fix(process): read notify-pending from live state instead of a post-exit timer
The keepalive held an owner for 60s after exit by reading retained process history. Pruning drops
that history by start time and a process cap on every spawn, so a long job lost the protection the
moment it finished; and entries closed without a collected exit (recovered PID gone, exited_at=0)
restarted the grace on every query and pinned their owner forever. Recovered entries were never
refreshed either, so a dead recovered PID read as running.

awaits_notification() now asks the three states that actually precede delivery: a notifying process
still running (via _any_running, which refreshes recovered entries outside the lock), an exit recorded
but not yet published (_completion_event unset), or an owner's event still in completion_queue. Each
ends on its own, so there is no timer to tune. Notices the poller holds after the user's Stop do not
count, since only the user's next prompt releases them.
2026-10-20 02:24:45 -07:00
Ben Barclay
9d32d3f2cd refactor(process): move the notify-await check into a sibling so the registry facade does not grow 2026-10-20 02:24:45 -07:00
Ben Barclay
7b37ac4191 fix(tui_gateway): key the notify keepalive on the process owner and hold it through delivery
The keepalive matched processes by the session's current key, which compression rotates while the
process keeps its original owner id, so a pre-compression watcher stopped pinning its session even
though agent close still kills it. It also released the session the instant the process exited,
before the completion was queued and dequeued, so a reaper in that window still lost the notice.

ProcessRegistry.awaits_notification() now matches on owner_task_id (the same field close() kills by,
via the agent's _process_owner_task_ids) and keeps the owner awaited for a bounded grace after exit.
A watch that was disabled no longer pins anything.
2026-10-20 02:24:45 -07:00
Teknium
650cbf3014 Merge pull request #141493 from NousResearch/fix/pkg13-browser-edges
fix(browser): close the per-profile browser scope edges on a multiplexed gateway (GW-23)
2026-10-19 11:48:28 -07:00
Teknium
fe78f95bbb fix(plugins): settings MCP reload is serialized, borrow-aware, one schema reader
Review fixes on the portable plugin settings change:

- Two key saves in quick succession: the reconnect is serialized and returns
  only once the server is connected again, so the second save compares against
  the first one's connection instead of skipping a server that was mid-start.
- A profile borrowing another profile's identical connection now detaches and
  connects its own when its key changes; the owner keeps its server.
- One reader for extensions.com.nousresearch.hermes.config_schema
  (agent_plugins.manifest_config_schema) feeds the form, the loader and
  plugins validate; portable entries go through the same warn-and-filter
  parser as plugin.yaml instead of being dropped silently.
- The worker thread uses spawn_context_thread; the test uses the platforms
  marker and no sleep loop.
2026-10-19 07:27:50 -07:00
Teknium
2d35f6184b feat(plugins): portable plugins get the Settings > Plugins form, live
A portable Agent Plugins v1 package (plugin.json) had no way into Settings >
Plugins: the schema reader only looked at plugin.yaml, and v1 rejects unknown
top-level fields. It now reads extensions.com.nousresearch.hermes.config_schema
(the vendor namespace that already carries server trust and timeouts) for the
form, the save, the loader's schema warnings and catalog admission.

Two gaps any plugin with settings hit once the form existed:

- The plugin's Desktop half had no way to learn a save happened. Every
  plugins.manage settings save now broadcasts plugin.<id>.settings.changed
  ({written}); a secret-only save still makes the (empty) settings call so the
  event fires for a new API key too.
- A secret the form stored never reached the plugin's running MCP server (its
  env ${VAR} was rendered at spawn). After a save, Hermes reconnects the plugin's
  servers whose resolved launch inputs changed (identity digest, rendered the way
  the connect path renders it); a toggle-only save leaves them alone.
2026-10-19 07:27:50 -07:00
Teknium
0d067c91f9 fix(browser): harness dir policy in its own module; socket length judged on the resolved path
Three review points on the served-profile harness dirs:

- The length check measured BH_RUNTIME_DIR as supplied, but the harness
  binds `Path(BH_RUNTIME_DIR).expanduser().resolve()`
  (browser_harness/_ipc.py:23). A short relative (`BH_RUNTIME_DIR=rt`
  from a deep cwd) or symlinked spelling skipped the short-dir fallback
  while the real socket exceeded sun_path. The candidate is now expanded
  and resolved before measuring, on Linux and macOS alike; a dir that
  fits is still returned exactly as given.

- The dir selection, socket budget and private-dir claim move from
  tools/browser_use_cli.py (which had grown past 1,000 lines) to a new
  tools/browser_harness_dirs.py, together with the daemon identity
  (HARNESS_DIR_KEYS, daemon_identity, daemon_env).
  _base_subprocess_env applies namespace_harness_dirs; browser_use_cli.py
  is back to 1,000 lines.

- The budget is a pure function of the platform
  (`socket_dir_budget(platform)`, `fits_socket_budget(dir, budget)`), so
  the macOS length rule is tested with macOS data and no longer patches
  sys.platform. The real-platform bind tests stay marked
  platforms("macos") / platforms("linux").

Red on the previous head: the relative and symlink cases of the new
Linux test (resolved socket 249/246 bytes > 107).

Refs #134889 (GW-23)
2026-10-19 07:14:08 -07:00
Teknium
71f009b5e2 fix(browser): a session found stale after creation is closed by object, never published
_get_session_info put a freshly created session into _active_sessions,
checked whether its profile had published a new live endpoint meanwhile,
and only then (after releasing _cleanup_lock) closed it by key. A
concurrent caller for the same key could take that session through the
existing-session path while the creating thread closed the browser
underneath it, and the by-key close could also hit a replacement another
thread had published in the gap.

The staleness check now runs under the lock before the session is
published. A stale candidate is never put in the shared map: it is
closed by object (its backend `close` dispatched on the session_info
itself, then _release_session_backend, the by-object tail split out of
_release_session_resources), and a fresh one is built. The second
lookup and its replacement race are gone.

Red on the previous head: the new test sees the stale session in
_active_sessions while its backend `close` runs.

Refs #134889 (GW-23)
2026-10-19 07:05:54 -07:00
kshitijk4poor
310bcf444a refactor(memory): move tool-schema plumbing into agent/memory_manager_tools.py
The stall/registry work pushed agent/memory_manager.py past 1,000 lines.
The memory-provider tool-schema helpers (normalize_tool_schema,
memory_provider_tools_enabled, memory_provider_tools_exposed,
inject_memory_provider_tools) are a self-contained topic with no
dependency on MemoryManager, so they move verbatim to a
memory_manager_tools sibling and every in-tree caller imports from the
new module. agent.memory_manager is a public plugin module
(hermes_cli/plugin_validate_private_imports.py), so it re-exports the
four names, as it already does for the helpers that moved to
agent.memory_context.
2026-10-19 19:15:44 +05:30
Teknium
403856e943 fix(browser): a served profile's harness socket fits Linux sun_path for any session name
On Linux a served profile's harness runtime dir ~/.config/browser-harness/runtime/p-<12hex> left
room for only 38-character session names at /home/teknium (30 at /home/alexander.smith) under the
108-byte sun_path, while BU_NAME may be 64; the daemon could not bind for longer names.

_socket_fit_runtime_dir now applies the macOS short private dir claim on Linux too, with Linux's
budget (107 - len("/bu-.sock") - 64 = 34 bytes): hbh-<12hex> under socket_safe_tmpdir(), else under
the sticky system temp root, claimed only through _claim_private_dir (mkdir 0700, or an existing
real dir owned by this uid with no group/other bits). A dir that already fits is kept unchanged, and
an unclaimable one keeps the long path. Windows (loopback TCP) is unchanged.

Refs #134889 (GW-23)
2026-10-19 04:46:27 -07:00
Teknium
a9c68fff78 fix(browser): a browser_exec that routed during /browser connect does not keep the old browser
browser_exec resolves the live endpoint into BU_CDP_URL in _route_exec, and records its harness
daemon only inside dispatch(). A /browser connect landing between the two reaped nothing, the CLI
spawned the daemon on the old endpoint, and the daemon (which latches BU_CDP_* at spawn) kept
driving the old browser for every later call in that profile.

browser_exec now snapshots the profile's live CDP generation before routing and re-routes (at most
3 attempts) when it moved during routing; after dispatch, a moved generation reloads this call's
daemon through the existing --reload path so the next call respawns on the current endpoint.

Refs #134889 (GW-23)
2026-10-19 04:42:44 -07:00
Teknium
37e36cda32 fix(browser): a session that resolved the old endpoint during /browser connect is closed, not kept
/browser connect reaps the profile's browsers, publishes the new live
endpoint, then reaps again. A tool call in the same profile that resolved the
old endpoint before the publish but registered its session after the second
reap kept driving the old browser (tui_gateway/methods_browser.py
_browser_connect / _browser_disconnect; predates #106742).

set_live_cdp_override now bumps a per-profile generation. _get_session_info
reads it before building a session and again under the lock when it registers
the session; if this profile published in between, the session is closed
through the normal teardown and rebuilt on the endpoint published now (at most
two rebuilds, so a flapping connect cannot loop a tool call). Another
profile's publish has its own generation and never invalidates this one.

Refs #134889 (GW-23)
Refs #134889 only
2026-10-19 03:10:30 -07:00
Teknium
a4362ae610 fix(browser): each served profile's harness screenshots and logs stay in its own tmp dir
The harness writes shot.png, debug-click overlays and bu-<NAME>.log under
BH_TMP_DIR (browser_harness/paths.py tmp_dir, else <home>/tmp). A served
profile already had its own BH_RUNTIME_DIR but still shared that tmp dir, so
one profile's screenshots and daemon logs sat beside another's.

_namespace_harness_daemons now also sets BH_TMP_DIR to <tmp root>/p-<hash>
(nested inside an inherited BH_TMP_DIR when one is set) with
BH_TMP_DIR_SHARED=1 so log names keep the bu-<name> stem. The runtime dir
still derives from the inherited value, as before. The driven-daemon identity
now carries the tmp keys too, so an unscoped shutdown --reload reaches the
daemon with its own tmp dir. Single-profile processes are unchanged.

Refs #134889 (GW-23)
Refs #134889 only
2026-10-19 03:10:29 -07:00
Teknium
f1273978cf fix(browser): a served profile's harness socket fits macOS sun_path for any session name
A served profile's Browser Use daemons get their own BH_RUNTIME_DIR
(~/.config/browser-harness/runtime/p-<hash>), shared by several BU_NAMEs, so
the installed harness names each socket <dir>/bu-<BU_NAME>.sock
(browser_harness/_ipc.py _runtime_stem/_sock_path). On macOS sun_path is 104
bytes; with a default HOME that path is 63 bytes on a 9-letter account, which
left room for only ~31-character session names although BU_NAME may be 64.

When the per-profile dir is over the 30-byte budget on macOS, the profile now
gets a private dir under the short socket root (/private/tmp/hbh-<12 hex>,
keyed by uid, harness root and profile). An existing dir is accepted only when
it is a real directory owned by this uid with no group/other bits; otherwise
the long path stays. Linux and single-profile processes are unchanged.

Refs #134889 (GW-23)
Refs #134889 only
2026-10-19 03:10:24 -07:00
Teknium
bf9dbbe53b fix(browser): an unscoped thread on a multiplexed gateway never resolves the launch profile's live CDP endpoint
live_cdp_override() keyed the per-profile map by hermes_home_key(), which in a
context with no profile bound (a bare threading.Thread or stdlib executor that
did not copy the caller's context) is the launch home. On a multiplexed gateway
that handed the launch profile's /browser connect endpoint to whatever profile
the thread was working for. It now answers "" there, the way get_secret fails
closed; env_cdp_url() already reads only the (absent) bound scope. A bound
scope and single-profile processes are unchanged.

Refs #134889 (GW-23)
Refs #134889 only
2026-10-19 03:09:06 -07:00
Teknium
045b4fd437 fix(mcp): re-render a missed env ref from scratch every time
Greptile: a var unset at load and set by connect to text equal to its own
placeholder kept the stale unset_ref flag and was dropped. Any templated
string is now re-rendered with fresh flags.
2026-10-19 02:10:20 -07:00
Teknium
caa1ea8d92 fix(mcp): an unset ${VAR} env entry counts as absent; set values pass verbatim
Follow-up to #141379 from an independent post-merge review:
- the MCP SDK re-adds its inherited set (PATH, HOME, TERM, ...) at spawn,
  so popping an unset override never unset those keys. Treat the entry as
  absent instead: the key keeps its baseline value, one rule for every key,
  matching what the child actually receives.
- carry resolution provenance from interpolation (_RenderedStr) instead of
  guessing from the rendered text, so a set variable whose value is
  literally '${OTHER}' is passed through, not dropped.
2026-10-19 02:10:20 -07:00
Teknium
bc3cbd50db fix(image_gen,video_gen): poll the FAL queue every 2 s instead of every 0.1 s (#141368)
fal_client's SyncRequestHandle.get() drains iter_events() at its default
interval=0.1, i.e. a status GET every ~0.3-0.5 s including RTT. Through the
Nous tool gateway (200 requests per fixed one-minute window) a single 12 s
image cost 42 requests (~208 req/min), so a second concurrent job — or the
same user's video job — trips RATE_LIMIT_EXCEEDED on submit, status and
result calls.

Add tools.fal_common.wait_fal_queue_result(): drain iter_events() at
FAL_QUEUE_POLL_SECONDS (2 s), then call get(), whose first status check now
sees Completed and goes straight to the result GET. Public SDK API only, no
monkeypatching. The image tool's interrupt-aware _wait_fal_result and both
FAL video waits (generation + SeedVR upscale) use it.

Live, one gpt-image-2.5 flare image via the gateway: 42 -> 9 requests,
12.1 s -> 12.5 s wall clock.

Test fakes that modelled the handle with only get() gain an empty
iter_events(); two touched test files also get encoding="utf-8" on their
config write_text (windows-footguns).
2026-10-19 01:31:31 -07:00
Teknium
eea83bb603 Merge pull request #141357 from NousResearch/fix/pkg12-decided-gw
fix(gateway): lost automation turns settle; discard on every surface; classic /browser via browser.manage; pause holds interactive turns
2026-10-19 01:15:48 -07:00
Teknium
d2d3fa1c1d Merge pull request #141335 from NousResearch/fix/pkg12-estimates
fix(estimates): keep main's ~ context marker after Ctrl+C and price cold no-op /compress like main
2026-10-19 01:14:00 -07:00
Teknium
7e0966ace4 Merge pull request #141334 from NousResearch/fix/pkg12-kb2
fix(worker): persist activity and aux usage off Relay's event loop (KB-2)
2026-10-19 01:13:49 -07:00
Teknium
45b15aac70 fix(browser): after a disconnect a profile falls back to its own BROWSER_CDP_URL
The BROWSER_CDP_URL tier under the live override read os.environ in
_get_cdp_override_raw, the /browser status resolver and the Camofox
selection gate. On a multiplexed gateway os.environ holds the launch
profile's value, so after B disconnected (or for a served profile that
never connected) B resolved the launch profile's browser and ignored its
own .env and browser.cdp_url.

browser_tool_cdp.env_cdp_url() reads the key the way _build_browser_env
reads the browser passthrough keys: a routed profile reads only its bound
secret scope; otherwise get_secret, which falls through to os.environ as
before. The three readers use it. The old test that asserted the launch
env reaches profile B now asserts it does not.

Test: B with BROWSER_CDP_URL in its own .env resolves :7777 after
disconnect (red on the previous head: the launch env's :6666); A without
one resolves nothing and stays on Camofox; outside a profile scope the
process env still applies.

Refs #134889 (CLI-9)
2026-10-18 22:59:00 -07:00
Teknium
b71c73ea0f fix(browser): each profile drives and reaps its own Browser Use daemon
The harness names a daemon by BU_NAME alone (an unnamed browser_exec is
"default") inside one runtime dir and reuses any live daemon of that name.
On a multiplexed gateway profile B's unnamed exec therefore reused the
daemon A had spawned on A's /browser connect endpoint and drove A's
logged-in browser. The owner map was keyed by BU_NAME and last-writer-wins,
so A's reap stopped nothing after B touched the daemon, or killed the one B
was using.

Under a served-profile scope _base_subprocess_env now points
BH_RUNTIME_DIR at a per-home subdirectory (sha256 of the home key) of the
harness runtime dir, with BH_RUNTIME_DIR_SHARED=1 so names keep their
bu-<name> stems. _driven_daemons is keyed by (runtime dir, shared flag,
BU_NAME), and stop_harness_daemons reloads each daemon in the dir it was
started in. Outside a served-profile scope the env is unchanged.

Test: A and B unnamed execs get different daemons on their own endpoints;
A's reap stops only A's daemon, B keeps its browser and A respawns on its
new endpoint (red on the previous head: B got A's endpoint).

Refs #134889 (CLI-9)
2026-10-18 22:56:10 -07:00
Teknium
e52d48c433 fix(browser): a live CDP override and its reap belong to one profile
/browser connect wrote the process-wide BROWSER_CDP_URL and reaped every
task's browser, so on a multiplexed gateway one profile's live browser
reached every other profile's sessions.

- tools/browser_tool_cdp: live overrides are a lock-protected map keyed by
  hermes_home_key() (set_live_cdp_override / live_cdp_override).
  Precedence: this profile's live connect, then the operator's
  BROWSER_CDP_URL env, then browser.cdp_url. Camofox yields to it too.
- Browser sessions record the home_key that created them; CDP supervisors
  and Browser Use harness daemons remember theirs.
- cleanup_profile_browsers(home_key) closes only that profile's sessions,
  supervisors (SUPERVISOR_REGISTRY.stop_home) and harness daemons, and
  drops its per-home config cache slots. cleanup_all_browsers is unchanged.

Refs #134889 (CLI-9)
2026-10-18 21:49:43 -07:00
Teknium
5fc490e2b3 fix(mcp): an unset ${VAR} override also clears the inherited baseline value
Greptile: a key in the safe baseline (XDG_*, secret-source names) kept the
parent value when the server env override was an unset ${VAR}, so the child
saw the parent setting instead of the key being unset.
2026-10-18 21:16:12 -07:00
Teknium
43c9e0ae52 fix(mcp): leave an unset ${VAR} env entry out of a stdio server's environment
A stdio MCP server env entry like "GHIDRA_INSTALL_DIR": "${GHIDRA_INSTALL_DIR}"
was passed to the child as the literal text "${GHIDRA_INSTALL_DIR}" when the
variable was unset. Servers that validate the value refuse to start (REA:
"GHIDRA_INSTALL_DIR must be absolute"), so a portable plugin could not forward
an optional variable, and Hermes' filtered MCP env means forwarding is the only
way a user's variable reaches the server.

_build_safe_env now drops an env entry whose whole value is still one
unresolved ${VAR}/${env:VAR} reference. Partial references, context vars and
url/headers keep their existing behaviour. Applies to config.yaml mcp_servers
and plugin mcp.json alike (same launch path).

Co-authored-by: Rodrigo Gomes <2362425+rodrigogs@users.noreply.github.com>
2026-10-18 21:16:12 -07:00
Teknium
df08578643 fix(worker): route the async-delegation ledger's dispatch writes off Relay's loop
External review of #141334: `_persist_dispatch` -> `WorkerDelegationLedger.dispatch`
(and the `unscheduled` mark) run inside a tool callback on Relay's loop, so the
`synchronous_rpc_on_event_loop` guard still fired and left the store failed. Both now
go through `call_off_event_loop`, like the activity and aux-usage writers.

Tests: a red/green test drives `_persist_dispatch` + `unscheduled` inside
`relay_tools.execute`; one more drives the real `tool_executor._begin_tool_execution`
frame from the reporter's ThreadPoolExecutor stack (passes at the prior head, guards
against new store calls on that frame). The label-clear test's docstring now says it
is defence in depth, not a reproduced caller.

Refs #139029
Refs #134889 (KB-2)
2026-10-18 20:50:03 -07:00
Teknium
fd905d2926 fix: delegation manifest records the model children actually ran on
manifest.json took its model from the dispatch-time delegation.model
override, which is None whenever children inherit the parent model, so
every inherited delegation recorded model: null. Record each task's
model from its result and fill the top-level field from them when the
override was blank.

Part of #123452.
2026-10-18 20:48:21 -07:00
Teknium
bc2475bdf8 fix(gateway): price a cold /compress's legacy name-list tool pin like the restored agent
The cold-session estimate read only dict-shaped `tools` from the stored pin,
but restore_agent_tool_prefix also accepts a legacy name list and resolves
each name to its current definition. A legacy-pinned cold session priced the
prompt alone (260 tokens) while the resident agent built from the same pin
sent 1,714.

Pull the restoration's pin interpretation into a shared helper and use it for
the cold estimate: pinned definitions keep their bytes, names resolve to the
registry's current schema.

Refs #134889 (T15)
Refs #141321
2026-10-18 20:36:13 -07:00
Teknium
71fa6e176a fix: async delegation completions name the inherited child model
With delegation.model blank (children inherit the parent model), the
completion header read creds["model"] (None) and printed "Model: ?".
Fall back to the model the built children actually run on.
2026-10-18 20:17:19 -07:00
Teknium
9d817db0c4 Merge origin/main into fix/pkg10-creds-b
Resolves tools/environments/docker.py against #141086: the orphan sweep strips sandbox privileges before sparing an idle-stopped workspace container, and stop_idle runs on main's _start_teardown helper and strips privileges once the container has stopped, like a persist-mode cleanup.
2026-10-18 10:53:07 -07:00
Teknium
b0be65c30a Docker sandbox files can no longer carry setuid/setgid or file caps back to the host, persistent sandboxes included (#141086)
* fix(docker): strip setuid/setgid and file caps from every sandbox file, persistent sandboxes too

#141033 hands root-owned sandbox files back to the host user when a root
container is removed; chown clears setuid/setgid and file capabilities on
the files it touches. Two paths still let a root sandbox leave a file in its
host bind dirs that the host user then runs with raised privileges (proved
on real Docker):

1. The walk only selects root-owned entries. A host-user-owned, group-root
   setgid file (host egid 0) or file capabilities on a host-user-owned file
   (when SETFCAP is granted through docker_extra_args) are never touched.
2. In the default docker_persist_across_processes mode the container is
   never removed, so no handback (and no strip) ever runs.

Every root pass now first re-chowns each setuid/setgid regular file under the
sandbox mounts to its own uid (one find per distinct owner; chown to the same
owner clears the bits and security.capability and changes no owner). find
cannot test xattrs, so when the container was granted SETFCAP / ALL or is
privileged, every regular file is re-chowned the same way (~1-2s per 20k
files measured; the base args drop SETFCAP, so the default path stays
`-perm /6000`). Device nodes/FIFOs keep #141033's filter.

The strip-only pass also runs for persistent containers: on session detach
(cleanup in persist mode, on the atexit-drained teardown thread), before
the first command on reattach, and in reap_orphan_containers before an
exited container is removed. It runs in a throwaway of the image with only
the sandbox dirs bind-mounted (not --volumes-from), so a running container
swapping paths mid-walk can only steer it at sandbox files or the throwaway
rootfs. Same gates as the handback: Linux, Hermes not root, no rootless /
userns-remap, root-run container; bounded at 10s, best-effort.

* fix(docker): one-scan privilege strip that runs on any image, after the handback, from the container's own binds

- Strip setuid/setgid with one `find -perm /6000 -exec chmod ug-s` (no stat, so images without
  /bin/stat such as bullseye-slim are covered; GNU and busybox verified). Only a container that
  could set file caps (SETFCAP/ALL/privileged) re-chowns every file to its own uid, one throwaway.
- Teardown hands ownership back first, then strips on its own 10s budget, so a huge SETFCAP tree
  can no longer starve the handback.
- The strip reads its targets from the container's existing sandbox binds (realpath on both
  sides; the creator's sandbox root is labeled), so a profile attaching to a shared container
  strips the creator's dirs and a symlinked HERMES_HOME/TERMINAL_SANDBOX_DIR still matches.
- Binds with `--mount` and skips missing sources: a deleted task dir is never recreated root-owned.
- A strip that cannot run warns once per sandbox dir instead of logging at debug.

* fix(docker): strip only sandbox dirs this host derives, never from container labels

The root strip trusted a hermes-sandbox container label to pick which host
binds it mounts and chmods. Labels are settable by docker_extra_args (which
override Hermes's own) and inherited from any image LABEL, so a sandbox could
point the strip at host files outside its sandbox (setuid bits stripped from
a project dir; label "/" matched "/", "/usr", "~/.ssh" binds).

Drop the label. A bind source is kept only if its realpath sits under a
<sandbox>/docker root this process computes itself: its own sandbox dir, or
the default one of any profile of the same Hermes root (shared containers
across profiles). The strip mounts the resolved path, so a symlink swapped
in after the check is never followed.
2026-10-18 10:49:17 -07:00
Teknium
f2e178388b fix(docker): identify idle-stopped workspace containers by a dedicated label
The orphan reaper spared a container the idle reaper had stopped on purpose
only if its hermes-task-id label ended in `_ws_<16 hex>`. That label is
truncated to 63 chars, so any profile name of 36+ chars (valid names reach
64) cut the digest. The next process's sweep then ran `docker rm` on the
stopped workspace container, losing everything installed outside the mounts
(apt/pip, /opt, /etc). That contradicts stop_idle's contract.

Now the create path stamps per-workspace containers (task key
`<base>:ws:<digest>`) with `hermes-workspace=<digest>`, taken from the
untruncated task id, and _is_idle_workspace_container reads that label.
This is option (a): label parsing no longer decides what gets deleted, so
it cannot break under truncation or sanitization. Option (b), keeping the
suffix through truncation, would still tie the reaper to the task label's
format. The old regex fallback is dropped. Only this unreleased branch
created containers without the label, and if such a container is reaped it
is just recreated on next use.

Test: a real-create-path label round trip for `default` and a 40+ char
profile (red on 4fe7ca4d71 for the long profile), plus a non-workspace
negative case.

Review finding (package 10 independent review) on #140970
Refs #134889 (CLI-39)
Refs #140719
2026-10-18 05:58:44 -07:00
Teknium
220270d10e Docker sandbox files written as root are handed back to your user at teardown (#141033)
* fix(docker): hand root-written sandbox files back to the host user at teardown

The Docker backend runs the image's default user (root) unless docker_run_as_host_user
is set. In persistent-filesystem mode it bind-mounts <sandbox>/docker/<task>/home at
/root and .../workspace at /workspace, so everything the container writes there lands
on the host as uid 0. The user cannot delete those files, and that is what broke
scratch cleanup. The prompt-backend probe container alone left a root-owned
home/.hermes tree in every temporary HERMES_HOME.

Root stays the default inside the container: many images need it for apt and s6. When
Hermes stops and removes a root container, the teardown worker first runs
`docker exec -u 0 find /root /workspace -xdev -user 0 ... chown uid:gid` in the
still-running container. It prunes every other bind mount nested underneath
(read-only skills, credentials, caches, user volumes), so host data outside the
sandbox dir is never touched. The step is bounded (10s), best-effort, and logs only
at debug.

It is skipped when the container already runs as the host user, on non-Linux hosts
(Docker Desktop bind mounts are not root-owned on the host), when Hermes itself runs
as root, and when the daemon remaps users. Remapping is detected via `docker info`
SecurityOptions (rootless/userns), cached per process. If the query fails, the step
is skipped.

The sandbox dirs outlive the container, and root refuses some host-owned files: git
reports "dubious ownership" and ssh reports "Bad owner" on ~/.ssh/config. So the
handback records the exact paths it changed next to the dirs. The next container that
mounts them gives those paths back to root before its first command, filtered to its
own sandbox mounts, so a real host dir now mounted at /workspace is never chowned.

_remove_bind_dirs no longer drops failures silently. A dir that survives rmtree logs
one warning with the path and the `sudo rm -rf` fix.

* fix(docker): keep the ownership handback inside the sandbox dir

Review of the handback found four ways it could touch the wrong files.

- Extra binds were not pruned. Mounts from docker_extra_args were missing from the
  prune list, and `find -xdev` does cross a bind that sits on the same filesystem. The
  prune list now comes from `docker inspect .Mounts` (every real destination). If
  inspect fails, the walk is skipped.
- Symlinks could redirect the reclaim. The reclaim checked recorded paths by string
  prefix, so a directory later replaced by a symlink sent chown outside the sandbox. It
  now chowns only recorded paths that a fresh `find -P` walk (no symlinks followed,
  nested mounts pruned) still finds under the sandbox mounts, owned by the host uid.
- A host-user container got root files. When the next container runs as the host user,
  the handed-back owner is already right. Reclaim now just drops the record.
- A timeout lost the record. Handback used to record only after the whole find/chown
  finished. It now walks first, records every path, then chowns, so a timeout part-way
  through the chown still leaves a complete record.

* fix(docker): hand back after stop, by the container's real user, and keep failed records

Independent review of d4de406 found four gaps:

- Reclaim keyed on run_as_host_user only, so a later session running as
  uid 1000 via docker_extra_args --user or an image USER had its saved
  files forced back to root and lost write access. Both handback and
  reclaim now read the container's actual Config.User from docker inspect
  and act only when it is root.
- A nonzero find or chown during reclaim still deleted the record, the
  only way to recover. The record is now kept unless discovery and chown
  both succeed, so the next container retries.
- The handback ran before SIGTERM, so files a process writes on shutdown
  stayed root-owned. It now runs after docker stop and before rm, in a
  throwaway `--rm --pull never --network none --user 0:0 --volumes-from`
  container of the same local image id; the pre-stop exec pass is gone.
- The leftover-dir warning sat on a path that only runs for
  non-persistent sandboxes, where no bind dirs exist. Removed with its
  test; persistent sandbox dirs are kept on purpose.

* fix(docker): confine the ownership handback container and remove it on timeout

The post-stop handback ran find/xargs/chown as root with Docker's default
capabilities, resolved through the image PATH. An image with
PATH=/root/.local/bin:... ran a binary the agent planted in its own
writable home at teardown, with MKNOD, and could make a world-writable host
block device. The throwaway now drops every capability except CHOWN,
DAC_OVERRIDE and FOWNER, sets no-new-privileges and a pids limit, resets
PATH/LD_PRELOAD/LD_LIBRARY_PATH, uses -w /, and calls /usr/bin/find,
/usr/bin/xargs and /bin/chown by absolute path. If an image lacks them,
the pass fails and is skipped, as on main. The pre-run reclaim (docker
exec) gets the same env reset and absolute paths.

A subprocess timeout kills only the docker CLI, so a slow handback left
its --rm container running with the sandbox volumes. The throwaway is now
named hermes-handback-<cid>-<rand>, labelled hermes-handback=1, and
removed with docker rm -f on timeout. Concurrent handbacks no longer
append entries the record already holds.

* fix(docker): pin stdin for handback docker calls

The stdin guard flags subprocess.run calls without stdin=; the shared
_docker helper now defaults stdin to DEVNULL unless input is fed.

* fix(docker): never hand device nodes back to the host user

The handback walk matched every root-owned entry. A sandbox granted MKNOD
(docker_extra_args or --privileged) could leave a block device node that
became host-user-owned, giving raw disk access on the host. Match only
regular files, directories and symlinks; device nodes and FIFOs stay
root-owned as on main. chown already strips setuid/setgid/file caps.
2026-10-18 04:42:56 -07:00
Teknium
6b1c09691a fix(terminal): stop idle per-workspace persistent containers instead of leaving them running
Keying persistent Docker per (profile, workspace) meant one RUNNING container
for every folder a user ever chatted in (default container_memory 5 GB each):
the idle reaper's DockerEnvironment.cleanup only drops the handle in persist
mode, and the startup orphan reaper only removes exited containers.

Decision: idle stop, not a cap. The reaper now `docker stop`s an idle
`<base>:ws:<digest>` container (DockerEnvironment.stop_idle); its writable
layer and /root sandbox stay, and the next use re-attaches through
_attach_existing_container, which `docker start`s it. A container that still
hosts a running background process is kept. The profile container keeps
main's always-running contract. The startup orphan reaper skips these stopped
workspace containers (they are that workspace's sandbox, not orphans). An LRU
cap was not added: idle stop already bounds running containers to the
workspaces active within terminal.lifetime_seconds, and a cap would stop a
container that a live session is using.

Review finding by @kshitijk4poor on #140970
Refs #134889 (CLI-39)
Refs #140719
2026-10-18 03:27:58 -07:00
Teknium
2b8cd0519b fix(terminal): keep delegates in the parent's workspace container; make the key idempotent
Two regressions from the per-workspace persistent Docker key:

- A delegate_task child has only a container alias to its parent, and the
  persistent branch never followed it, so the child ran in the profile's
  `default` container (no parent packages, /tmp or services) and children of
  two workspaces shared one. _workspace_container_key now follows the alias.
- ensure_task_env handed the resolved `<base>:ws:<h>` key to get_active_env,
  which resolved it again back to the profile key and returned whatever
  profile container existed. A resolved key now maps to itself.

The digest is computed once at bind time and stored in the override
(`workspace_key`), so lookups no longer realpath the live filesystem; the dead
`except OSError` around realpath is gone.

Review finding by @kshitijk4poor on #140970
Review finding by @dokterdok on #140970
Refs #134889 (CLI-39)
Refs #140719
2026-10-18 03:27:52 -07:00
Teknium
d8835ab3a8 fix(terminal): mount each gateway session's own workspace into its Docker container
Since #106742 a `hermes chat` turn runs in the gateway, not in its own
process, so the client's cwd (or `--in DIR`), frozen into the session policy
at admission, never reached `resolve_task_overrides(task_id)['cwd']`, the
Docker backend's per-session mount source. With container_persistent: false
every session container got no /workspace bind ("No such file or
directory"); with true every session of the profile shared one container
bound to whichever session's cwd created it first.

- gateway/session_policy.py: bind_turn_workspace() registers the frozen
  policy cwd as the session's terminal cwd override (cwd_source "session")
  inside the turn's routed scope. Docker mounting the host cwd only; it
  re-registers only when the workspace changed, so an agent's `cd` survives
  later turns and a workspace move takes effect on the next one.
- gateway/run_turn_runner.py: the turn runner calls it under policy_scope.
- tools/terminal_tool.py: persistent Docker keys one container per
  (profile, workspace) for a session with a registered workspace; sessions
  in the same folder still share one, and keyless runs keep the profile key.

Live: a real gateway, two concurrent `hermes chat -q` from two folders, a
real Docker container and a loopback LLM. Both persistent=false and true now
read their own marker (main: "No such file" / both read marker-2), and so
does --in DIR.

Refs #134889 (CLI-39)
Refs #140665
Refs #140719
2026-10-18 03:27:52 -07:00
yoniebans
354ad3d487 refactor(gateway): share the connection card's answer step and refusals between both handlers
The session authority's handler and the legacy connector handlers each carried the answer/settle/close step and the connector refusal table. tools.connectors.run.respond now owns the step and tui_gateway/connector_refusals.py the (code, reason, message) entries; both handlers use them, so a change lands once.
2026-10-18 12:27:21 +02:00
funky-xamarin
7f258a1c99 fix(tools): address reactions by the durable session id 2026-10-18 12:27:21 +02:00
Teknium
93fafc4d6f feat(plugins): public names for the skills tool's discovery and lookup helpers
Plugins that show the agent's skills (catalog views, "open this skill", drift checks against the
installed copy) need the same walk, order, search roots and lookup gate the skills_list / skill_view
tools use, plus the package hash the bundled-skill sync stores. All seven were private.

Rename, with every internal caller moved and no underscore aliases (same shape as the platform
helpers in e6cf2a9):
- tools/skills_tool.py: find_all_skills, sort_skills, skill_search_dirs, locate_skill,
  skill_lookup_path_error
- tools/skills_sync.py: dir_hash
- tools/skill_usage.py: read_skill_name

The names join _PUBLIC in the private-import lint and are documented under "Read the skill catalog"
in the plugin developer guide.

Builds on #129698 by @nekwo, which proposed the same names with legacy aliases kept.

Closes #129696

Co-authored-by: nekwo <beastant1@gmail.com>
2026-10-18 00:47:38 -07:00
Teknium
06671b7075 fix: worktree removal treats ignored files as disposable
Ignored files in a worktree (.env copies, caches, build and test output,
launcher scripts) are never meant to be preserved: removing a worktree
deletes them, the same as every other worktree tool. The keep-ignored-work
rule kept 461 of 574 real trees forever, so it is removed with its
regenerable-dir list and main-checkout byte comparison.

Kept: keep-large-untracked, keep-unarchivable (embedded repos, including
ones inside ignored dirs, whose commits may exist nowhere else; an
over-budget ignored walk now reports keep-unarchivable), keep-worktree-refs,
the submodule rule, the showUntrackedFiles=no and skip-worktree fixes, and
the staged-edit recheck.
2026-10-17 21:49:14 -07:00
Teknium
ab1c29d8bb fix: worktree sweep keeps any tree holding work an archive cannot restore
The second review found trees deleted with bytes or commits that were in
neither git nor the archive: untracked files over archive_max_file_mb
(skipped from the snapshot, tree still removed), gitignored embedded
repositories (ls-files --exclude-standard never lists them) and every
ignored file (.env edits, *.secret, info/exclude notes). The classic
pruner had three older gaps of the same class: status.showUntrackedFiles=no
made new files invisible, skip-worktree/assume-unchanged edits read clean,
and commits held only by refs/worktree/* or refs/bisect/* died with the
tree's admin dir.

Rule now enforced at one decision point (worktree_retention.removal_blocker)
used by archive_preflight, the post-snapshot removal boundary in
archive_then_remove (sweep, exit Archive, subagent finalize), the classic
clean-tree pruner, the attended `hermes worktree prune` and the clean exit
path: a tree is removed only when everything irreproducible is in git or the
archive. Kept: keep-large-untracked (archive ref stays), keep-unarchivable
(embedded repo, ignored or not), keep-worktree-refs, keep-ignored-work
(ignored files outside a regenerable-dir allowlist that are not
byte-identical to the main checkout's copy, so .worktreeinclude .env copies
never block). Exit Archive and the subagent note name the reason. Every
dirty check forces --untracked-files=normal and counts flagged-index edits.
The ignored-path walk skips dependency stores without descending and is
capped per tree (unverifiable -> keep).
2026-10-17 21:49:14 -07:00
Teknium
d413d8b1b7 fix: worktree sweep never archives or removes a tree with a submodule
An archive records a submodule only as its 160000 gitlink, and removing a
worktree deletes its per-worktree modules/ repositories. The selective check
on d70ebda missed two cases an independent review reproduced with real git:
- `git submodule deinit` keeps the module repository (private branches
  included) under <worktree gitdir>/modules/ while the checkout has no .git,
  so the tree was archived and removed and the private commit was lost;
- an edit to an existing file inside a submodule during capture moves no
  superproject path mtime and no index entry, so the post-snapshot guards
  passed and the edit was deleted.

Until recursive submodule preservation exists, use the conservative rule
the original human review proposed: a tree with any gitlink in its index or
a non-empty modules/ dir is unarchivable (keep-submodule-work). Enforced in
archive_preflight and snapshot_worktree (sweep, exit Archive, subagent
finalize) and re-checked at the shared removal boundary right before
`git worktree remove`. Clean merged trees are also kept unless modules/ is
absent and the gitlink was never initialized (classic pruner, sweep plan,
subagent no-work prune). The selective dirty/local-commit submodule probe is
removed: the blanket rule subsumes it.
2026-10-17 21:49:14 -07:00
Teknium
ccb3c9a4e8 fix: worktree archive keeps submodule work and late staged edits, reports retained trees
A snapshot records a submodule only as its 160000 gitlink, so `git worktree
remove --force` after archiving deleted an initialized submodule's uncommitted
edits (and its per-worktree modules/ repo) with nothing in the archive to
restore them. The shared snapshot_worktree entry point and archive_preflight
now refuse any tree whose populated submodule is dirty (tracked or untracked,
recursively), checked out at another commit than recorded, or holds commits/
stashes no remote-tracking ref has; the planner shows it as
keep-submodule-work. Uninitialized or clean-at-recorded-commit submodules
still archive. Refusing in snapshot_worktree covers exit-time Archive and
subagent finalization, which do not go through the planner.

The post-snapshot removal gate used file/HEAD/reflog mtimes, which an
index-only change (git apply --cached) never moves. snapshot_worktree now
digests the semantic staged entries (ls-files --stage) of exactly the index
it captured; archive_then_remove compares them right before removal and keeps
the tree if they differ. A stat-only refresh by git status does not count.

execute_plan dropped archive_then_remove's removed flag, so a tree kept by the
safety gate was reported as "archived + removed"; the exit path and subagent
note said "removed" too. The flag now propagates: `hermes worktree prune`
prints "archived, kept (changed during the sweep)", the exit Archive prints
archived_kept, and the subagent note says the tree was kept (all locales).

Reported by @unsupportedpastels in review of #140603.
2026-10-17 21:49:14 -07:00
Teknium
71a83d74d5 fix: worktree sweep honours --older-than, re-gates each tree, archives exact bytes
Review of the snapshot-then-delete sweep found paths where it could remove
work it should keep or store bytes that differ from the working files:

- `hermes worktree prune --older-than N` ran the sweep before applying N; the
  plan now marks any tree idle < N days skip-young before anything runs.
- execute_plan checked liveness once per batch, then archived trees one by one.
  Each tree is now re-gated (lock, /proc cwd/fds, fresh activity) right before
  it is touched, and archive_then_remove re-checks after the snapshot, keeping
  the tree when a process entered or a file changed during capture.
- _last_activity ignored deleted paths; it now stats each changed path's
  nearest surviving folder, so a fresh deletion counts as activity.
- `--attr-source` does not cover info/attributes or core.attributesFile, so
  eol rules still rewrote bytes. Every blob is re-hashed with
  `hash-object --no-filters` and restore writes blob bytes directly.
- The classic CLI applied the exit Archive answer in atexit, after the exit
  watchdog was armed; it is now applied synchronously in _tui_shutdown, with
  a progress line, before _run_cleanup. A failed or interrupted archive keeps
  the tree.
- web_git.worktree_add's existingBranch path skipped the repo registry.
- subagent-* trees got the 72h named-tree tier; one prune_tier_hours helper
  now gives hermes-* and subagent-* the 24h tier in both planners.
- worktree_sweep.py had a text=True git call without encoding="utf-8" (CI red).
2026-10-17 21:49:14 -07:00
Teknium
3882113085 feat: archive stale dirty worktrees before removing them, sweep every repo, ask on dirty exit
The worktree pruner never removed a dirty or unpushed tree at any age, so leftovers of finished
lanes (stray probe files, WIP commits on closed PRs) accumulated forever: 658 trees / ~1 TB on
one machine, 553 of them named lane trees. Approved design (Teknium, 2026-10-17):

- Snapshot-then-delete: an idle tree past its tier (hermes-*/subagent-* 24h, named 72h) with
  uncommitted changes or unpushed commits is archived to refs/hermes/archive/<tree> (HEAD +
  staged + unstaged + non-ignored untracked bytes, built with a temporary index; large untracked
  files skipped and listed) and then removed. A failed archive keeps the tree. Branch kept when
  published on a remote, otherwise the archive anchors its commits.
- Never touched at any age or budget: live hermes lock owners, any live process whose cwd/open fd
  is inside the tree (/proc on Linux, psutil cwd elsewhere), trees with recent file/ref activity,
  Kanban t_<hex> trees.
- No count cap; optional worktrees.max_total_gb evicts the oldest idle trees first.
- Per-profile registry (<HERMES_HOME>/worktree_repos.json) of every repo Hermes made a worktree
  in (hermes -w, /worktree new, subagent isolation, Desktop git pane); the 6h cron sweep unions
  it with its existing sources, scoped and throttled per profile.
- Subagent worktrees with commits/edits are archived and removed at child finish (branch kept).
- Interactive `hermes -w` (CLI and --tui) exit with a dirty/unpushed tree asks Keep (default) /
  Archive & remove / Remove and discard; non-interactive exits never ask.
- `hermes worktree restore <name> [--path]`, archives in `hermes worktree list`, a full
  decision table in `hermes worktree prune --dry-run`, archive retention (30 days).
- worktrees.archive_dirty: false restores the classic never-delete-dirty pruner exactly.
2026-10-17 21:49:14 -07:00
Teknium
53de7ff326 feat(clarify): public get_pending() query replaces _lock/_entries reads
Adapters rendering native clarify buttons (core Discord/Telegram, base
send_clarify, the community QQ plugin) read tools.clarify_gateway._entries
under _lock to learn whether a request is still pending and its choices.
get_pending(clarify_id) returns the entry while it awaits an answer, else
None; internal readers move to it.
2026-10-17 14:51:46 -07:00
unsupportedpastels
a096c025cd refactor(gateway): one helper answers a Bot Chat id's existing receipt; share the held reason
_deliver repeated the "admitted receipt -> same-delivery check ->
authorize -> _maybe_retry -> _publish_result / refused receipt ->
answer" block before and after _migrate, and _settle carried a third
copy without the retry. _receipt_answer now holds it once; _settle
calls it without a retry path, as before, and still answers an
unadmitted pin with unknown_execution.

The owner (_not_sent_record, _held_by_another_writer) and the Bot DM
tool (LiveTargetHeldError, _held_disposition, the admitted:false check)
each hard-coded 'runtime_coordination_required' to recognise the
settled no-send. Both now read HELD_NOT_SENT from
tools/bot_failure_reasons.py, kept out of ALL_REASONS so the bot-turn
vocabulary and its passthrough are unchanged. The DM tool imports it
lazily: its top level stays stdlib-only for the direct runner.

No behaviour change; the existing held-writer, receipt and migration
tests cover every branch.

Refs #134889 (MSG-19)
Refs #140208
2026-10-17 14:11:42 -04:00