Symptom: ProcessRegistry.spawn_local starts every terminal(background=true) job in its own session, and
the agent-lifecycle sweeps that stop jobs (kill_all on release, agent_close, a turn timeout) only run
while the owner is alive. A CLI, TUI or worker that is SIGKILLed / OOM-killed / crashes left every job
running on init. Measured on Linux (tbg_probe, kill -9 the owner, check at +10 s, 2/2 runs): pipe job
1/1 alive, pipe job with a child 2/2 alive. A PTY job's hangup stops only jobs that keep the default
SIGHUP action: a HUP-ignoring PTY job (`nohup`'d server, trap '' HUP) and its child 2/2 alive.
Change (tools/process_registry_ownership.py, a new ProcessRegistry mixin; process_registry.py is at its
size cap and shrinks by 10 lines): a local background job's process group goes to the owner-death
supervisor (process_identity layer 4) for as long as the job's own process runs: pipe jobs start through spawn_owned
(purpose="terminal-background", recorded in the spawn ledger), PTY jobs hand their pty.fork group to
own_process_groups. The group is released when the job leaves _running (exit, kill, reconcile) and by
_reap_untracked after a failed setup, so a job's deliberate `server &` survivors keep today's
behaviour once the job ends. A foreground command that yields to background (adopt_local) hands its
supervised group to the job instead of releasing it.
Deliberately NOT owned (they must outlive the owner):
- persist_on_release jobs (#41225, ec5c9c738a): the user asked for them to outlive the agent.
- every job of a gateway (a host that ran recover_from_checkpoint, or a supervised gateway): it
re-adopts the jobs a crashed predecessor left running, so its own jobs must survive its crash the
same way. Its clean shutdown still kills them (kill_all(source="gateway_shutdown")).
- Windows: the layer-3 job object covers ownership; the spawn path there is unchanged.
The systemd-scope, TERM->KILL tree kill, start-time PID-reuse guards and post-kill survivor checks stay:
they cover a live owner.
Result: same probe, 3/3 runs: pipe 0/1, pipe+child 0/2, HUP-ignoring PTY job + child 0/2 alive; the
persist_on_release job 1/1 alive (as intended). tests/tools/test_terminal_owned_jobs.py now also covers
jobs: kill -9 owner vs live control owner (jobs + PTY job + command die, persist_on_release job lives,
control untouched), a recovering host's jobs outlive its kill -9, finished job releases, yielded
command keeps its group until the job ends, unowned jobs never reach the supervisor. 5/5 green x3, 5/5
red on the pre-change code, each red on its own mutation (8 mutations). Two existing tests build
sessions by hand or fake Popen + os.killpg; they now carry the new field / stub the supervisor.
_reap_untracked moves into the mixin unchanged apart from the release.
Symptom: LocalEnvironment._run_bash starts every terminal command in its own session
(start_new_session=True, so the TERM->KILL group teardown reaches its children). Nothing reaps that
group when the Hermes process dies without running its cleanup (SIGKILL, OOM killer, crash): the
command and everything it started reparent to init and keep running. Measured on Linux (tbg_probe:
an owner runs `sleep 305` in env.execute() on a thread, owner gets kill -9, check at +10 s): bash and
sleep 2/2 alive, 2/2 runs.
Change: _run_bash hands the command's group to the owner-death supervisor
(process_identity.own_process_groups; pipe EOF -> TERM, 3 s, KILL). LocalEnvironment._wait_for_process
releases it once the wait returns, by any path (exit, timeout, interrupt), so what a command
deliberately leaves in the background after it returns (`server &`) keeps its current behaviour, the
same as a graceful exit. Not spawn_owned: an awaited command needs no spawn-ledger entry. Windows is
unchanged (the layer-3 job object). The existing TERM->KILL teardown, the setsid-escapee sweep and the
start-time PID-reuse guards stay: they cover a live owner.
Result: same probe, 3/3 runs: 0/2 alive. Per-command cost with the supervisor resident: own+release is
0.02 ms (3.4 ms when it has to start the supervisor); env.execute("true") 20.8-24.2 ms on the base vs
22.4-23.4 ms here, inside load noise. New tests/tools/test_terminal_owned_jobs.py (kill -9 owner vs live
control owner; a returned command releases its group): green x3, both red on the pre-change code and red
on their own mutation (no own / no release). test_local_env_cwd_recovery fakes subprocess.Popen, so its
class now stubs the supervisor calls.
They resolve against the terminal's cwd, so checking them with isdir from
the Python process's cwd dropped a project's 'bin' whenever the two
differed. Only absolute entries are checked for existence now.
Background terminal commands run `bash -lic` with no env snapshot, so a
~/.profile or distro /etc/profile that resets PATH dropped every parent-only
dir (bare `hermes` / the venv's tools: command not found), while the same
command in the foreground now resolved. spawn_local gains an opt-in
restore_login_path that prepends the SAME _append_dropped_path_entries
prelude the foreground snapshot uses, fed from the spawn env's PATH; the
terminal tool's local background spawn turns it on. The registry's shell
argv shape is unchanged.
The terminal tool's env snapshot is captured by `bash -l`, and Debian's
/etc/profile resets PATH for every login shell, so the snapshot pinned the
reset PATH over the spawn env for every later command. In the Docker image
that dropped /opt/hermes/bin and bare `hermes` exited 127 (#56634).
The snapshot bootstrap now re-appends, in parent order, every spawn-env PATH
dir the login shell dropped (not only Hermes' bin dir: the gateway's pm
runtime dirs and `docker run -e PATH=` additions too). They go after the
login PATH, so a command that resolved before resolves to the same binary
and the user's ~/.profile additions keep precedence.
The image also ships /etc/profile.d/hermes.sh, which re-adds the ENV PATH
dirs for login shells the snapshot never covers: the terminal tool's
background `bash -lic`, `docker exec <c> bash -l` and ssh.
Found on Hermes Cloud staging.
Debian's /etc/profile unconditionally resets PATH for non-root shells
before sourcing /etc/profile.d/*.sh, so the login-shell env snapshot
serialised the reset PATH and dropped the venv dir the process env put
there (#56634) — bare python3/pip then resolved to the system
interpreter.
The previous approach wrapped the command with a save/restore pair,
but the restore landed after the bootstrap's export -p, so the snapshot
kept the reset PATH anyway. Restore now runs between the init-file
prelude and the command, via idempotent per-entry case guards for
_resolve_hermes_bin_dir() + _managed_runtime_path_entries(), so
restored entries survive into the snapshot and reruns stay
duplicate-free. Tests read the PATH back from a real init_session
snapshot instead of asserting on injected markers.
Rebased onto current main (the branch had gone CONFLICTING).
HERMES_GATEWAY_EXTERNAL_SUPERVISOR is the only profile pin an
--external-supervisor gateway holds: the agent's own `hermes ...` commands
read it (_under_gateway_supervisor) to skip the sticky active_profile.
Stripping it from tool children sent a default gateway's agent onto another
profile after `hermes profile use work` (#74872 shape), and the auto-started
daemon lost HERMES_SUPERVISED_CHILD's pin the same way.
Both strip points now carry the pin as HERMES_GATEWAY_PROFILE_PIN, which
_under_gateway_supervisor and the dashboard's fixed-identity check read and
is_gateway_supervisor_process / is_supervised_gateway_launch never do, so a
gateway an agent starts still answers unsupervised.
Reported by @kshitijk4poor in the #145930 review.
Every child env the agent builds (terminal tool, background processes,
cron scripts, hermes_subprocess_env helpers, build_subprocess_env with or
without the secret scrub) inherited HERMES_LAUNCHD_LABEL, which the
stderr-timestamp wrapper forwards to the ONE gateway launchd starts
(#120087). A gateway an agent then starts from its terminal read the
parent's label: _detect_supervisor() answered "launchd",
is_gateway_supervisor_process() was true, /restart took the exit-75 route
no supervisor answers, and the drain cap logged and probed the parent's
job. HERMES_GATEWAY_EXTERNAL_SUPERVISOR, which `gateway run
--external-supervisor` stamps into its own environ, leaked the same way,
and so did systemd's NOTIFY_SOCKET / WATCHDOG_USEC / WATCHDOG_PID, which
name the unit's main process only.
Strip those names in the shared child-env guards (_finalize_child_env and
the unscrubbed build_subprocess_env branch). Kept on purpose:
XPC_SERVICE_NAME (launchd's per-process stamp; `hermes update` compares it
to tell it runs inside a job), INVOCATION_ID / JOURNAL_STREAM (systemd
sets them for the whole unit and the gateway-child dispatch reads them),
and the launch markers HERMES_SUPERVISED_CHILD / HERMES_S6_SUPERVISED_CHILD.
Reported by @kshitijk4poor on #144648.
Co-authored-by: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com>
A pinned delegation.command used to force provider "copilot-acp" whenever the selected
provider was not external_process. It now resolves the external_process profile whose
process_command names the same binary, else the profile flagged with the new
ProviderProfile.process_command_fallback (copilot-acp sets it, so every Copilot setup
resolves as before), else the spawn fails loudly. A kimchi binary now lands on kimchi-acp.
The env-writer denylist's hardcoded HERMES_COPILOT_ACP_* pair becomes
hermes_cli.auth_external_process.external_process_launch_env_names(): every registered
external_process profile's process_command_env_vars + process_args_env_var. This also
closes the gap for out-of-tree providers (KIMCHI_ACP_COMMAND/ARGS) and COPILOT_CLI_PATH,
which select the executable too.
Review finding "Error traps run twice": the PIPESTATUS capture restored the
command's status with `(exit $__hermes_rc)` as the last command inside the
eval. A non-zero restore is itself a failing command, so a user's ERR trap
ran a second time (`trap 'echo T' ERR; false` printed T twice; main prints
it once).
The restore now sits on the left of `&& :`. The list keeps the status, and
bash fires neither ERR nor errexit for a command on the left of &&, so the
eval returns exactly what main's plain eval returns.
The capture line is appended inside the command's eval. An unterminated
heredoc read it as body text (written into the user's file or printed),
and a trailing backslash joined onto it, so `echo hi \` printed `hi`
instead of `hi \`. Those commands now run exactly as before; their runs
stay unattributed, as on main. The wrapper test now asserts the exit code
and output the model sees, not only the exit code.
Environments built with __new__ (tests, plugin shims) have no per-session
_pipe_marker; a class-level empty default makes the wrapper emit no
PIPESTATUS line for them instead of raising AttributeError. Reverts the
fixture edits that papered over it.
Capture $? and PIPESTATUS together inside the eval, restore $? as the
wrapper's exit code, and trust a one-element PIPESTATUS only as side data.
Fixes the exit-code regression for if/while/!, pipefail and syntax errors.
Also initialize _pipe_marker in the two hand-built test fixtures, replace
the source-order assertion with exit-code behaviour tests, and drop the
stale claim that a piped run cannot count as evidence.
The bash wrapper now reports PIPESTATUS, so a verifier at the head of a
pipeline is scored by its own exit status instead of the last filter's.
Command matching also collapses interpreter paths to their family and skips
the flags that leave ``-m <module>`` intact (-I, -B, -u, -O, -W/-X with their
value, py -3.x), so ``pytest | tail`` and ``.venv/bin/python -u -m pytest``
count as the runs they are. Flags that exit before the module runs stay
unmatched.
The file tools answered reads, writes, patches and searches on the host whenever the
terminal environment was a LocalEnvironment (isinstance gates in file_operations_lint,
file_operations_search, file_tools and tool_result_storage). A backend that subclasses
LocalEnvironment to confine its commands (the bubblewrap plugin) could not opt out except
through the process-wide HERMES_NATIVE_FILE_READ=0, so the file tools read and wrote paths
its sandbox hides or mounts read-only.
BaseEnvironment.uses_host_filesystem (False; True on LocalEnvironment) now drives every one
of those gates through env_uses_host_filesystem(). A subclass that sets it False gets every
file operation through env.execute. Each bundled backend evaluates the gates exactly as
before; the attribute is documented in the terminal-backend plugin guide.
vercel 0.12 moved the sandbox client from httpx to httpx2, whose exceptions do not
subclass httpx's. Connection, protocol and read errors from the new transport carry no
status code and matched none of the classifier's names, so sandbox create/restore/write
calls stopped retrying them. Classify both stacks' transport errors as transient.
The confirmed-alive cache now expires after _CONFIRMED_TTL_S (30 s) and the port forward counts an
HTTP 404 on /devtools/browser/<id> as a forward failure, so a session cached on a relaunched sandbox
Chromium is rebuilt instead of kept. Healthy calls inside the TTL still spend no exec.
N1 (re-review of #143146). sandbox_browser_alive read any non-zero exec exit (a docker/ssh
transport error) as "Chromium dead": the session was rebuilt and, as the last user, its
teardown SIGTERMed a browser that was still running. A probe timeout raised TimeoutExpired
out of get_session_info, so browser_exec failed. Every browser call also paid one exec in
the sandbox.
- The probe script exits 3 only when the sandbox itself answers "not running" (no
DevToolsActivePort, or nothing listens on its port). Any other failure, including a
timeout, is "unknown" and keeps the session.
- Creating a session refuses to launch on an unknown answer instead of wiping a live
browser's DevToolsActivePort and losing to its singleton.
- A confirmed endpoint is cached. The port forward now counts connections that never
reached the target, and the session is re-probed only after that count changes (or the
sandbox was replaced), so a healthy call spends no exec.
The broker's capability allowlist named only the deleted browser_navigate/click/type/... tools, so a
bound extension controller silently did nothing (review P1-1); owner ruling: remove the feature.
Drops the broker, artifact store, extension router, /v1/browser-control + /v1/artifacts routes,
browser.controller.* RPCs/events (contracts regenerated) and the per-request controller identity.
The authenticated-identity helpers bot relay and session ownership still use move to
gateway/session_identity.py; persisted API admissions carrying 'browser_control' still recover.
browser_exec is the only core browser tool (plus browser_cdp, browser_dialog,
browser_vault, all CDP). Deleted: browser_navigate/snapshot/click/type/
scroll/back/press/get_images/vision/console and every module that served
them (browser_tool_session/_lifecycle/_cloud/_cdp/_real_profile/
_lightpanda_fallback/_eval_policy/_origin/_snapshot/_vision) plus
browser_camofox*.py (Camofox ships as the catalog plugin 'camofox').
tools/browser_tool.py and tools/browser_tool_install.py shrink to the
frozen old-updater stub warm_agent_browser_npx_cache.
toolsets: _HERMES_CORE_TOOLS / browser toolset list only the CDP tools.
model_tools: browser_tools legacy alias and the browser_navigate /
browser_type schema rewriters removed. Cloud providers no longer request an
install post_setup hook (nothing to install).
The Singularity/Apptainer backend (tools/environments/singularity.py) now ships
as the official 'singularity' plugin in NousResearch/hermes-official-plugins,
registered through the terminal-environment provider seam under the same
backend name and config keys (terminal.backend: singularity,
terminal.singularity_image / TERMINAL_SINGULARITY_IMAGE, terminal.container_*).
- 'singularity' leaves BUILTIN_BACKEND_NAMES so the plugin can register it;
every hardcoded classification set drops it (the provider declares
is_remote/is_container/supports_streams instead).
- LEFT_CORE gains a singularity row: homes whose terminal.backend (or .env
TERMINAL_ENV) is singularity get the catalog plugin once, on hermes update
or agent/gateway start. An unknown-backend error for 'singularity' names
the install command (new row field terminal_backend).
- A plugin backend receives its per-task '<backend>_image' override; batch
runs register one for the active backend.
- BaseEnvironment's sudo-probe knob is renamed _passwordless_sudo_probe_supported:
plugin backends set it, and the old spelling trips the install scanner.
- Core's scratch-dir disk warning and process-exit sweep were Singularity-only
and move to the plugin; the singularity setup row, dashboard probe/row and
config defaults/bridges go too. Docs point at the plugin.
Review follow-up: the EMFILE fallback handed a PTY master a PollSelector,
and macOS poll() reports devices as always ready, so an idle terminal
would busy-loop. On macOS a character-device fd now re-raises the setup
error instead; PtyBridge.spawn closes the child and raises, so the
terminal open fails visibly rather than spinning. Pipes keep the poll
fallback on every OS. The PTY test forces selector creation to fail and
asserts the bridge either still waits on idle reads or refuses to spawn.
Review follow-up: epoll/kqueue need an fd of their own, so at the fd
limit (EMFILE) open_fd_waiter returned None and the drain dropped live
output. None is now reserved for a closed/invalid fd (EBADF/ValueError);
any other setup failure falls back to PollSelector, which needs no fd.
The high-fd test fixture also releases fds acquired before a failed open.
Follow-up to the poll() drain fix: macOS poll() does not support device
fds and reports a PTY master as POLLNVAL, i.e. "ready" at once, so
PtyBridge.read() would return b"" without waiting and the dashboard /
Desktop terminal pane's read loop would spin a core on every Mac.
fd_wait now wraps selectors.DefaultSelector (epoll on Linux, kqueue on
macOS; kqueue supports ptys since 10.9), which has no FD_SETSIZE ceiling
either. Each reader owns one waiter for its lifetime and closes it: the
foreground drain, the background reader and the PtyBridge (opened in
__init__, closed in close()). The background reader marks itself
selectable only when the waiter actually registered.
Tests: one case drives the real terminal drain and the background reader
above fd 1024; the other drives a real PTY above fd 1024 and asserts an
idle read waits for its timeout (the macOS-poll spin). Both are
platforms("posix"), so the macOS lane runs them. The existing PTY
EAGAIN-race test now stubs the waiter instead of select.select.
Co-authored-by: Mohamad Kanso <91088196+MohamadKanso@users.noreply.github.com>
select.select() raises ValueError "filedescriptor out of range in select()"
once a watched fd reaches FD_SETSIZE (1024), which a long-lived gateway or
desktop process hits as it accumulates open fds. Every drain caught that
ValueError as "fd already closed" and silently dropped output with no error
signal (issue #94928).
Introduce a shared poll()-based fd waiter (tools/environments/fd_wait.py) and
use it in all three drain sites: tools/environments/base_output.py (terminal
and read_file), tools/process_registry.py (background processes), and
hermes_cli/pty_bridge.py (PTY terminal sessions). poll() has no FD_SETSIZE
ceiling, and POLLHUP/POLLERR read as ready so the caller's read observes the
real EOF.
Regression tests hold more than 1024 fds and assert the drain and the terminal
path still capture output (tests/tools/test_drain_high_fd.py).
Fixes#94928
Signed-off-by: Anthony Holten <anthony.holten1@gmail.com>
- A declared absolute default_cwd is stamped as the sandbox home even
when terminal.cwd starts the environment elsewhere, so a cd under that
home survives to the next command (Greptile).
- The file tools' plugin-home lookup shares _ssh_remote_home's guarded
bring-up: a failed connect is remembered for 30s instead of being
retried by every path resolution in one tool call (Greptile). When it
can't connect, relative paths fall back to the process cwd and the file
operation itself fails on the same connection (Teknium).
- streams.sandbox_temp_dir(): Bot Desktop and the sandboxed browser use
the environment's get_temp_dir() when it has one, else the BaseEnvironment
default, so a plugin environment that doesn't subclass BaseEnvironment can
host the screen (Greptile).
- A plugin exec_prefix() that returns a string, not a list, is refused as
"can't stream" instead of being split into one-character argv words
(Teknium).
- The missing-desktop-stack messages no longer name a terminal.<plugin>_image
key for plugin backends; they point at the plugin's own image setting
(Teknium).
Two opt-in additions to TerminalEnvironmentProvider; plugins that set
neither behave exactly as before.
- default_cwd: where commands start when terminal.cwd is unset, or is a
host path the container guard discards, instead of the generic /root.
Either an absolute in-sandbox path, or "~" for each sandbox's own home:
it stays "~" (never expanded on the host), create_environment receives
cwd="~", and the home the environment resolved is stamped on that
environment. A recorded cwd under that home is kept for later commands
instead of being dropped as a host /home/... path, and the file tools
anchor relative paths at the same home.
- supports_streams: the backend's environments implement
exec_prefix(*, user=None, interactive=True), a local argv that runs
its remainder inside the sandbox with stdio open. streams.exec_prefix
uses it for non-built-in environments, and bot_desktop placement
treats such a backend like docker/ssh/singularity instead of refusing,
so the screen, computer_use and the browser follow the terminal in.
Under plugins.isolation: host the environment reaches Hermes as an
opaque placeholder, so placement refuses with a reason naming the
setting.
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.
* 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.
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
* 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.
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
Reverts the config_env_table_keys() / local_env_policy part of 17601067c2d to its cc51fbfbfca
form. Including bundled gateway_env rows there scanned plugins/platforms at local_env_policy
import, which runs inside the isolated safe-mode worker after its audit hook: 807 opens under
plugins/ (main and this commit: 0). The three plugin-only secrets stay hand-listed, pinned by
tests/gateway/test_platform_env_overrides.py; the blocklist is the same 48 names.
Independent review found the allowlist, the open-policy startup refusal, the pairing-noise
rule and `hermes pairing revoke` reading only the live PlatformEntry: a user plugin overriding a
bundled platform without the fields, safe mode or a disabled plugin then gated on nothing
(looser than main, whose core tables always applied).
Each bundled plugin now declares them once as `gateway_env.AUTHZ` (passed to register() with
**), and `gateway.platform_env.authz_field` answers from the entry, else from that file (read
without the plugin package). Probed main vs head: 208/208 authz decisions identical in normal,
safe-mode, plugin-disabled and user-override modes; revoke drops the user in all four.
The terminal secret blocklist and config_env_table_keys() read the same files, which removes the
three hand-listed plugin secrets in local_env_policy.
Move the per-platform `_Cred` rows of `_ENV_STEPS`, their helper steps and the
`_ENV_ENABLE_CREDENTIALS` rows for every plugin-backed platform (telegram, discord,
slack, whatsapp, whatsapp_cloud, signal, mattermost, matrix, email, sms, dingtalk,
feishu, wecom, wecom_callback, weixin, bluebubbles, qqbot, yuanbao) out of
gateway/config_env.py into each plugin's `gateway_env.py`, attached via two new
PlatformEntry fields: `env_overrides` (ordered steps) and `env_enable_credentials`.
`gateway/platform_env.py` holds the declarative `EnvCred` row and shared parsers.
`_apply_env_overrides` runs the rows of entries with activation evidence (same gate
as the plugin enable pass, computed once). Core-only rows (api_server, webhook,
msgraph_webhook, relay) stay in config_env. profile_channels reads the rows from
registry entries; the import-time terminal secret blocklist lists the three secrets
only those rows read, pinned by a new invariant test.
Resulting GatewayConfig and explicit-disable warnings are identical (differential
oracle, 100 fixtures); only env-created insertion order of api_server/webhook/
msgraph_webhook relative to plugin platforms changes.
On main the terminal tool, its background processes and execute_code ran
with the launching shell's environment: an activated venv, nvm/pyenv
shims, PATH. Under the one gateway they ran with the daemon's
environment, so `python`, `node` and friends resolved to whatever the
gateway was started with.
The allowlisted toolchain part of a session's client_env (PATH,
VIRTUAL_ENV, CONDA_*/NODE_*/NVM_*/PYENV_*, GOPATH, GOROOT, CARGO_HOME,
RUSTUP_HOME, JAVA_HOME, plus names a profile lists in the new
terminal.client_env_passthrough) now replaces the daemon's values for that
session's local terminal commands, background processes and execute_code
children only, including execute_code's project-mode interpreter choice.
PATH stays the gateway's when the client sent none. The backend's own
terminal.env still wins. No full shell snapshot is taken. Messaging, cron
and Desktop sessions keep the gateway's environment.
Credential-looking names are never sent, stored or bound: one predicate,
is_secret_env_name, now shared with execute_code's secret policy, drops
them on the client, before the policy is stored and again before binding
(secrets keep using terminal.env_passthrough). execute_code applies its
whole scrub, including the delegated-child restrictions, after merging the
client's toolchain, and its list now also strips *COOKIE* names.
Refs #134889 (T3)
Refs #139523
The sibling of the scratch mid-prune rescue: cleanup_terminal_temp_cache cached the
newest .log/.pid/.exit mtime per hermes_bg_* group once, then deleted members off that
snapshot, so a session that wrote its .log after the snapshot lost all three files.
Each group is now re-stat'ed right before each member delete (unreadable = kept), and
a directory that rmtree(ignore_errors=True) left behind is no longer counted as removed.
Docs: configuration.md notes the scratch re-check and scratch-prune.log.
Two persistent sandboxes torn down at once each loaded the snapshot store,
added their id and wrote it back, so the later write dropped the other's
entry (and a plain write_text could be read torn as {}). The next session
then started from the base image. Snapshot stores (modal, vercel,
singularity) now go through base._update_json_store: a cross-process
lock around re-read/mutate/atomic write.
_file_lock's holder hint no longer names "a dashboard or a slow credential
refresh": it serves many stores and the caller's message names which.
tests/lock_contention.py lets serialization tests wait for "the other
writer finished or is blocked on the lock" instead of a fixed timeout.
An OAuth refresh atomically replaces a token with same-size bytes within the
mtime tick of the last sync; the (mtime, size) key matched, so the sandbox kept
the stale credential. Key synced files on utils.file_signature (adds inode and
ctime) so replaces are detected. A key whose mtime is still racy is recorded
as never-matching, and the next sync confirms the bytes against the pushed
hash: an in-place rewrite inside one coarse tick (ctime ticks just as
coarsely) is re-uploaded, unchanged bytes are not.
Planning sits inside the sync failure boundary: the content check reads
the file, and one removed after its stat must fail the cycle (retried
next time), not the terminal command that triggered the sync.
Review follow-ups on the packaged-npx and payload-venv commits.
_packaged_npx_entry promised "None for a failed install" but only handled a
non-zero exit: a TimeoutExpired (10-minute hang) or an OSError (unwritable
prefix, AV lock, node not startable) escaped into the MCP connect loop and
burned the server's retry budget. Both now log and return None.
_validated_runtime_venv returned whatever the adjacent manifest.json declared,
unchecked, ahead of the VIRTUAL_ENV branch that requires a real pyvenv.cfg. A
stray manifest beside a checkout could hand back a phantom path that shadowed
the user's own venv, or raise from payload_venv per child spawn. The payload
venv now needs pyvenv.cfg (the shipped payload venv has one) and a manifest
that escapes its root reads as "not a payload".
The packaged-npx test stood in for node with an extensionless #!/bin/sh file,
which win32's PATHEXT lookup never finds, so the test was red on the platform
it targets. It now uses a real node(.exe) fixture and a fake install, and the
failure shapes and _outside_package have their own tests.
The packaged-npx cache now follows npx: only an exact version is reused as
installed; any other spec re-resolves on each start and keeps the previous
install when npm cannot run (offline). A git, URL or path spec returns None
before installing, because npm installs those under a name the spec does not
show, so the manifest lookup missed and every start reinstalled.
pm.install.activate puts the store's tool dirs first on the backend's
PATH, so Hermes's own code finds the pinned binaries. The terminal built
its PATH from the same environment, so every command the user or the
agent ran got Hermes's node, npm, python and rg ahead of the ones the
user installed. On the Windows Store build that was worse than a version
surprise. cmd.exe cannot start the packaged node.exe, so `npx` failed
with "Access is denied" even with Node.js installed.
pm/user_facing.py moves the store's tool dirs behind the user's own
entries for terminal commands, foreground and background. Hermes's
tools stay as the fallback for a machine without them. Two exceptions:
- Hermes's Python stops just before the Windows app-alias dir when that
dir holds only the Microsoft Store stub (no python3.N.exe), so a
machine without Python still runs a real one.
- On Windows, Git Bash's dirs stay first. They are store dirs too, and
a non-login `bash -c` needs its coreutils ahead of System32's.
Hermes's own operations keep the pinned tools: pm.install.activate is
unchanged, and file search resolves PM's ripgrep (previous commit).
Linux, through LocalEnvironment: `type -ap node python3 rg` lists the
user's Nix copies first and ~/.hermes/tools second. Before this commit
it listed ~/.hermes/tools first.
activate_dependencies exports PYTHONPATH=<repo>:<payload>/venv/<site-packages>.
Before PM commits a generation, the sanitizer never recognised the second
entry as Hermes-owned. The payload boots its store interpreter, which is not
a venv, so _in_venv is false. There is no facts.json yet. VIRTUAL_ENV was
popped at boot and is never <repo>/venv on a payload. The terminal child of
an MSIX install therefore inherited Hermes's 3.14 site-packages, and a
different Python started from there (uv's 3.12 in the field report) crashed
importing pydantic's compiled core.
_validated_runtime_venv now accepts payload_venv(root) as provenance after
the committed-generation check. That is the venv activate_dependencies
selects on the same path.
Live repro: a fake payload (git archive of this tree plus a manifest.json
and a venv beside it), real modules, no mocks. Before: the child
PYTHONPATH kept <payload>/venv/lib/python3.14/site-packages. After: only
the user entry remains.
Since the spawn-per-call rewrite (d684d7ee7e) the persistence knobs were read
into config but never reached the environment: SSHEnvironment took no such
param and _create_environment dropped local_config. Every local and SSH
session carried cwd + exported env across commands regardless of the setting.
BaseEnvironment gains persist_env (default True). When False the per-command
wrapper still sources the login-time snapshot and still emits the cwd marker,
but skips the post-command export re-dump, so exports from one command do not
reach the next. SSHEnvironment/LocalEnvironment accept persistent=...;
_build_ssh_env forwards ssh_config['persistent'] and every local construction
path (terminal, file tools, execute_code, ensure_task_env) now forwards
TERMINAL_LOCAL_PERSISTENT via _local_config_from_config.
Defaults equal today's real behaviour: TERMINAL_LOCAL_PERSISTENT now defaults
to true (it was documented false but ignored), SSH keeps following
terminal.persistent_shell (true). Only users who explicitly set the knob to
false see a change: they get the isolation they asked for.
Docs: the Persistent Shell section claimed plain shell vars persist and that
local was non-persistent; rewritten to state exactly what carries over.
#135348 ran ruff's UP037 autofix with ruff.strict.toml's target-version = "py314". On 3.14
annotations are lazy (PEP 649), so stripping quotes is safe there; on 3.11-3.13 a function or
variable annotation is evaluated when the def or statement runs. Every unquoted annotation that
names the enclosing class (`def clone_for_agent(self) -> ContextEngine`), a class bound later in
the module, or a TYPE_CHECKING-only import now raises NameError on import: 300 modules on main
(gateway.config, run_agent, hermes_state, cron.jobs, the Telegram adapter, ...) fail to import
under 3.11, the update path crashes mid-`hermes update` on any install whose interpreter is
older than 3.14, and the e2e-upgrade suite's retry leg fails with
`NameError: name 'ContextEngine' is not defined`.
- Re-quote exactly the 79 annotations (36 files) that name something unbound when they are
evaluated (including tui_gateway/server.py's `_TurnScopes`, which only reaches that module's
globals through register() after import); no other text changes.
- agent/turn_scripted_prelude.py: `Generator[...]` gets its third argument back. d76cce4f11
applied UP043 (default type args, valid only from 3.13) to a module-level alias, so
`Generator[Y, S]` raises TypeError on 3.11/3.12 and takes gateway.run, agent.conversation_loop
and tui_gateway.{server,ws,entry} down with it.
- ruff.strict.toml target-version = "py311", the requires-python floor. With it UP037 leaves
these quotes alone and only strips the two that are genuinely redundant, which this commit
strips; any future version-gated fix stays valid on every supported Python.
- tests/ci/test_strict_ruff_target.py pins the target to the requires-python floor (red on main).