Commit Graph

501 Commits

Author SHA1 Message Date
Teknium
c98e8dc63a fix(terminal): restore the exit status without re-firing the user's ERR trap
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.
2026-10-24 18:48:01 -07:00
Teknium
812c4bb044 fix(terminal): run heredocs and trailing-backslash commands without the PIPESTATUS capture
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.
2026-10-24 18:48:01 -07:00
Teknium
a615a56096 fix(terminal): default the pipe marker so env fixtures built without __init__ keep working
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.
2026-10-24 18:48:01 -07:00
BrokeSkill
2b7ab93711 fix(agent): keep shell exit codes when recording pipelines
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.
2026-10-24 18:48:01 -07:00
BrokeSkill
22f3c027be fix(agent): record piped verification runs and stop double nudges
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.
2026-10-24 18:48:01 -07:00
Teknium
72fc7dfe9b feat(tools): terminal backends can declare that file tools go through the sandbox
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.
2026-10-23 15:33:14 -07:00
Maciej Lisiewski
8edc5ea255 Merge pull request #143456 from NousResearch/bulk-update
chore(deps): bump Python dependencies to latest minor/patch releases
2026-10-23 12:25:56 +02:00
Maciej Lisiewski
7528243600 fix(vercel): retry httpx2 transport errors from the sandbox SDK
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.
2026-10-23 11:51:27 +02:00
Teknium
127d782e6f fix(browser): a sandbox browser relaunched on the same port is re-checked within 30 s
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.
2026-10-23 01:43:15 -07:00
Teknium
e5aee7e8dc fix(browser): a failed sandbox liveness exec no longer kills the live browser
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.
2026-10-23 01:42:34 -07:00
Teknium
b87977cadd refactor(api): remove browser-extension control (its browser tools are gone)
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.
2026-10-23 01:42:27 -07:00
Teknium
68500d9ff9 refactor(browser)!: delete the built-in browser_* tools, agent-browser and bundled Camofox
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).
2026-10-23 01:41:24 -07:00
Teknium
d99af4187b refactor: move the Singularity terminal backend out of core into the singularity catalog plugin
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.
2026-10-22 05:26:10 -07:00
Teknium
0b8dee00fa fix(terminal): no poll() fallback for a macOS PTY
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.
2026-10-20 17:41:05 -07:00
Teknium
cb67cb3521 fix(terminal): never report a selector setup failure as EOF
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.
2026-10-20 17:41:05 -07:00
Teknium
355910814a fix(terminal): wait on a selector so PTY reads stay correct on macOS
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>
2026-10-20 17:41:05 -07:00
Anthony Holten
0910e488d4 Update base_output.py 2026-10-20 17:41:05 -07:00
Anthony Holten
9b6b243762 fix(terminal): drain stdout with poll() to survive fd >= FD_SETSIZE
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>
2026-10-20 17:41:05 -07:00
unsupportedpastels
71633f762d fix(terminal): review follow-ups for plugin cwd and stream hooks
- 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).
2026-10-20 16:17:56 -04:00
unsupportedpastels
e166392fec feat(terminal): let plugin backends set their start dir and host Bot Desktop
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.
2026-10-20 16:17:56 -04: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
073a3af503 fix(platforms): the terminal secret blocklist reads no plugin files at import (safe mode)
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.
2026-10-16 19:42:34 -07:00
Teknium
b95c4861b2 fix(platforms): bundled authorization env names hold when the live entry lacks them
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.
2026-10-16 19:42:34 -07:00
Teknium
3c3f85a0d0 refactor(gateway): plugin platforms declare their env->config rows on PlatformEntry
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.
2026-10-16 19:42:34 -07:00
unsupportedpastels
979c08e35d fix(tools): run a CLI/TUI session's tools with its client's toolchain environment
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
2026-10-16 17:49:54 -04:00
Teknium
389bd5a2b0 fix(terminal): confirm terminal-cache removal with an explicit lstat, not lexists — match the scratch half (review on #139850) 2026-10-16 14:19:22 -07:00
Teknium
16365682dd fix(terminal): terminal-cache cleanup re-checks each bg group before deleting and counts only real removals (#132401)
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.
2026-10-16 14:19:22 -07:00
Maciej Lisiewski
40158fa616 fix: address pr comments pt1 2026-10-15 22:25:22 +02:00
Maciej Lisiewski
85e2711c5a fix(environments): sandbox snapshot stores are updated under a file lock
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.
2026-10-15 22:12:27 +02:00
Maciej Lisiewski
88472b8e6e fix(environments): remote file sync re-uploads same-size same-tick rewrites
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.
2026-10-15 22:12:27 +02:00
ethernet
84e2250b10 fix(windows): packaged-npx install failures degrade to plain npx; payload venv must be real
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.
2026-10-13 22:51:07 -04:00
ethernet
162b457c8e fix(terminal): the user's own tools come before Hermes's in the terminal
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.
2026-10-13 16:31:45 -04:00
ethernet
671996b152 fix(terminal): strip a sealed payload's venv from child PYTHONPATH
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.
2026-10-13 15:54:55 -04:00
Teknium
89963452ee fix(terminal): make persistent_shell / TERMINAL_*_PERSISTENT actually work
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.
2026-10-11 16:53:57 -07:00
Maciej Lisiewski
0006a5e229 ci: fix PLW1509, PLW1510, PLW2101 linter errors 2026-10-10 15:20:13 +02:00
Teknium
a274d3388f fix: core modules import again on Python 3.11-3.13 (re-quote eager forward references)
#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).
2026-10-09 14:25:07 -07:00
Maciej Lisiewski
2ff58849f4 ci: ruff UP037 fixes 2026-10-09 17:34:38 +02:00
Maciej Lisiewski
9eab688b42 ci: ruff UP017 fixes 2026-10-09 17:34:36 +02:00
Maciej Lisiewski
32b70e9733 ci: FURB188, FURB192 linter fixes 2026-10-09 17:31:52 +02:00
Maciej Lisiewski
4278b6aa24 ci: RUF013, RUF015 2026-10-08 21:29:48 +02:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
alt-glitch
73133c88c0 fix(bundle): packaged installs run their own hermes and name their own app (review)
The agent's terminal puts a sealed payload's launcher dir first on PATH even when the inherited PATH already lists it behind another install.
The macOS removal instructions name the running .app bundle and its folder instead of a fixed Hermes.app.
A manifest.json with a mistyped runtime, commands, venv or store reads as not a payload, and a missing venv or store is treated as unset, so startup no longer raises.
2026-10-07 01:29:02 +05:30
alt-glitch
3383a1d8b3 fix(bundle): the agent's terminal runs a working hermes inside the desktop payload
Inside a packaged desktop build, bare `hermes` in the terminal tool resolved
to <payload>/venv/Scripts/hermes.exe. That venv was built on CI, and its
Windows redirector reads pyvenv.cfg `home`, which still names the CI path,
so every call failed with "did not find executable at C:\a\hermes-agent\...".
The working launcher in <payload>/bin carries the channel name and was never
on the agent's PATH.

- activate_dependencies puts the payload's own launcher dir (from the
  manifest's runtime.commands) first on PATH, and on Windows no longer adds
  the shipped venv's Scripts dir: every redirector in it names the CI
  interpreter.
- _resolve_hermes_bin_dir answers with that launcher dir in a sealed payload,
  so terminal and cron children do not depend on PATH order.
- stageDesktopLaunchers copies the canonical launchers to their qualified
  names instead of renaming them. Only the qualified names are published.
- The "plugin already exists" hint names the real CLI command.
- Every manifest-relative path (venv, store, hermes launcher) goes through one
  resolve-and-contain check, and a manifest.json that is unreadable or not a
  payload manifest reads as "not a payload" instead of raising, since every
  install now asks.

Source and dev installs are unchanged: they have no payload manifest.
2026-10-07 01:29:02 +05:30
teknium1
9d66f96340 fix: HASS_TOKEN stays out of child processes when the Home Assistant plugin is absent
Moving HA out of core dropped HASS_TOKEN/HASS_URL from the static provider blocklist and HASS_TOKEN
from the Tier-1 always-strip set. Once installed, the plugin's manifest declares them, but with the
plugin absent (migration pending, declined or failed) the token reached every terminal/subprocess
child. Each left-core row now names the env core stripped while it shipped the feature
(secret_env -> Tier 1, private_env -> provider blocklist) and local_env_policy keeps stripping it.
2026-10-04 00:08:20 -07:00
teknium1
fb9fc8a3dd refactor: move Home Assistant out of core into the homeassistant catalog plugin
The Home Assistant gateway platform (plugins/platforms/homeassistant) and the
homeassistant toolset (tools/homeassistant_tool.py) now ship as the official
catalog plugin `homeassistant` (NousResearch/hermes-homeassistant), with the
same platform name, toolset/tool names, config keys and env vars.

Migration (hermes_cli/left_core_migration.py, a generic "left core" table
reusing the memory-provider migration's helpers): every profile home that
used Home Assistant (HASS_TOKEN in its .env, platforms.homeassistant enabled
or holding a token, or the homeassistant toolset selected) gets the plugin
installed from the catalog at its reviewed pin by `hermes update`, and lazily
once per process at agent start / gateway start (honours
security.allow_lazy_installs). Every outcome reaches terminal, Desktop and
chat; a gateway-start outcome is handed to that home's first agent.

Core HA special cases become generic PlatformEntry seams the plugin uses:
trusted_inbound (allowlist bypass for event-bus platforms), display_tier
(built-in display defaults) and shared_env_prefixes (profile-clone ownership
rule for env shared with the plugin's tools). Cron delivery uses the existing
cron_deliver_env_var seam; HASS_TOKEN stays stripped from subprocesses via the
installed plugin's manifest secrets.
2026-10-04 00:08:20 -07:00
teknium1
d526f14714 fix(mcp): a dead MCP server's grandchildren are reaped again (main e2e red since #131910)
#131910 refused to signal a process group whenever its leader's start time
no longer matched the spawn-time baseline, and a REAPED leader reads as None,
so "leader gone" was treated as "PGID recycled". POSIX never reuses a PGID
while any member of the group lives, so a gone leader still leaves the group
ours, and its reparented grandchildren (an MCP server's pipe holder, a
terminal command's daemon) leaked past host shutdown.

Only a LIVE leader with a different start time (drift-tolerant since
a5e7df27) proves recycling now; the recycled-PID skip is unchanged.
a5e7df27 kept "gone leader refuses" and asserted it in
test_pgid_starttime_drift.py; that assertion now expects the kill. Same fix in the terminal
environment's twin guard (tools/environments/local.py::_leader_is_ours).

Red on main: tests/e2e/core/parity/test_mcp_lifecycle.py::
test_mcp_server_death_mid_call_fails_fast_and_the_turn_completes and
test_entrypoint_parity[*] zero_mcp_orphans (e2e lane on eaecc99c).
2026-10-02 20:59:36 -07:00