Commit Graph

335 Commits

Author SHA1 Message Date
unsupportedpastels
ebb840e8cd refactor(terminal): move _call_in_flight into the lifecycle sibling
Its only consumer is the idle reaper in terminal_tool_lifecycle, so it
belongs beside it. Like the rest of that module it reads the env cache
state (_calls_in_flight, _env_lock, _last_activity) from terminal_tool at
call time, so that state stays where tests patch it and no import cycle is
added; terminal_tool re-exports the helper and _execute_remote imports it
from the sibling. No behaviour change.

Refs #143547
2026-10-25 19:14:26 -04:00
unsupportedpastels
e24c9a5086 fix(terminal): keep the idle reaper off an environment with a call in flight
_cleanup_inactive_envs reaped any key whose _last_activity was older than
lifetime_seconds (default 300 s). Only background processes refresh that
stamp, while a foreground command may run for 600 s, so a long build or
test suite had its Docker workspace container stopped (exit 137), its
Modal sandbox terminated or its SSH control master closed mid-command.

terminal_tool and the remote execute_code path now hold the env keys they
were stamped under (_call_in_flight, refcounted, released in finally) from
acquisition through the approval wait and execution; the reaper skips held
keys, and release restamps so the idle countdown starts at call end.

Refs #143547

Co-authored-by: Genesis Guerrero Martinez <2824293+gengue@users.noreply.github.com>
2026-10-25 19:14:26 -04:00
Teknium
95505c60e9 docs(tools): lead every tool description with its key capability
The deferred tool_search catalog shows each tool's first sentence clipped to
60 chars, so lines like 'image_generate: Generate high-quality images from
text prompts, or edit /…' hid that it edits with reference images on the
user's configured model. An agent skipped it and called FAL directly with a
hardcoded model.

- catalog line cap 60 -> 80 (CATALOG_SUMMARY_MAX_CHARS); every built-in
  tool's first sentence now fits and leads with what it does
- image_generate/video_generate say they use the configured model;
  image_generate says to use it rather than direct API calls/scripts
- web_search/web_extract/browser_exec name when to use each other
- drop a duplicated cronjob sentence and filler in skill_view/video_generate
- regenerate tests/fixtures/prompt_surface
2026-10-23 16:04:50 -07:00
Teknium
c68b1847ba fix(delegation): a child routed back to the launch profile uses its container
Persistent Docker keys a session-bound container by profile. _container_profile
took the bound home's profile only when that home is a routed (non-launch) one,
else the session's HERMES_SESSION_PROFILE. A coder chat on a default-launched
gateway routing a child to default binds the launch home, which is not routed,
so the child fell back to the parent chat's profile and ran in profile:coder's
container instead of default's (Greptile on #143126, relayed in #142563).

The bound home's profile now decides whenever it differs from the session's
own; a session with no profile name is still the launch profile's, so the
launch home's own turns keep their key. The sibling per-profile keys
(_routed_home_task_key, _qualify_task_key) already key the launch home as the
default profile does and were right.
2026-10-22 14:37:10 -07:00
Teknium
5b9387a627 fix(delegation): a profile child uses the target profile's persistent container
Persistent Docker keys a session-bound container by HERMES_SESSION_PROFILE,
which delegated_profile_scope leaves on the parent: a child routed to coder
inside a default-profile gateway/TUI session reused the default profile's
cached container, without coder's image, mounts and env (Greptile).

The container profile now follows the bound HERMES_HOME override when there is
one, else the session's profile. HERMES_SESSION_PROFILE itself is untouched: it
is also the delivery identity notifications read, which stays the parent's.
Gateway routed turns bind both to the same profile, so their key is unchanged.
2026-10-22 14:37:10 -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
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
2b8cd0519b fix(terminal): keep delegates in the parent's workspace container; make the key idempotent
Two regressions from the per-workspace persistent Docker key:

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

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

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

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

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

Refs #134889 (CLI-39)
Refs #140665
Refs #140719
2026-10-18 03:27:52 -07:00
Teknium
390b1e38d2 fix(terminal): trailing-& conversion never tells the model to re-launch the process
The conversion note was patched onto the finished spawn JSON, and the
silent-background hint was removed only when it was the sole hint. When
another hint was appended (e.g. the homebrew CI-poller hint for
`gh pr view --json statusCheckRollup &`) the result said both "re-launch
with notify_on_complete" and "Do NOT re-run it", inviting a second copy.

spawn_background_process now takes auto_backgrounded and builds the note
where hints are assembled, skipping only the silent-background hint, so
the finished result is no longer decoded and rewritten.
2026-10-17 04:23:31 -07:00
Teknium
d5c74fc185 fix(terminal): a foreground command ending in a lone trailing & runs as a tracked background process instead of being refused
`cmd &` in a foreground terminal call was refused with "Re-send WITHOUT the
'&' as terminal(command=..., background=true)". The tool already knew the
fix, and the model's only move was a resend of the same command: 488 such
refusals in one user's last 30 days, each a full model turn.

When the trailing `&` is the command's ONLY backgrounding (one line, one
and-or list or pipeline, no `;`, no inline `a & b`, no nohup/disown/setsid,
quoted/heredoc `&` ignored), the `&` is stripped and the call continues as
terminal(background=true) for the stripped command: the same lifecycle,
workdir, self-repo and dangerous-command approval guards run on what
actually executes, and the normal background result comes back with an
`auto_backgrounded` note naming process_manage. notify_on_complete stays
off, matching a plain background=true call (servers are the common case);
the silent-background "re-launch with notify" hint is dropped from this
result because acting on it would start a second copy.

Ambiguous shapes keep the old refusal text unchanged: inline `&`, `;`
sequences, multi-line scripts, nohup/disown/setsid wrappers, long-lived
servers without `&`, and any command whose approval verdict depends on the
`&` itself (`hermes gateway run &`). The desktop approval batch keys its
pre-made decision on the stripped command so it matches what runs.
2026-10-17 04:23:31 -07:00
Teknium
3bf97898ac perf(prompt): fixed prefix back under the post-diet size (-2.1k tokens per request)
The stock prompt surface regrew ~3.4k tokens after the August diet, almost
all from features added straight into the never-deferred core. This takes
back the biggest pieces:

- browser_vault: the five eager browser_vault_* tools (list, fill, unlock,
  save_login, enter_code) become one browser_vault tool with an action enum,
  deferred behind tool_search by default. It still rides with the browser
  (an empty vault keeps save_login reachable), so discovery holds; only a
  catalog line is paid per request. Results and errors name the new actions;
  the input-tool password note points at it through tool_call.
- terminal: schema re-dieted (1,136 -> 651 Qwen tokens). Description and
  param docs no longer repeat each other; heartbeat / persist_on_release keep
  their rules in one line each; process(...) references name process_manage.
- tool_search / tool_call: the keyword-query rule lives once, in the queries
  param; description and connector hint trimmed.
- system prompt: the "Async handoff" block is removed. Its rule ships in the
  delegate_task description and in the background dispatch result the model
  reads at the moment it matters, and the polling loop it targeted is guarded
  structurally (#124724).

Stock CLI surface (prompt-surface render, chars/4): 18,612 -> 16,524.
Fresh install, Qwen3 tokenizer: 14,962 -> 13,120 (Sep 7 post-diet: 11,595).

Live A/B harness: evals/prefix_rediet/.
2026-10-12 03:18:48 -07: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
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
cb6ffe6cdd fix(terminal): foreground heartbeat is dropped, not refused; notify intent still is
Follow-up to the cherry-picked #119201 (@KoNit-K): keep main's relocated
test file, flip the one invariant that pinned the refusal (a foreground
call with heartbeat>0 now runs with heartbeat=0 while notify=true stays
refused), reword the refusal so it no longer names heartbeat, and say in
the schema that heartbeat is ignored on foreground commands.

Why: the schema fix (4317ed0e71) only helps providers that materialize the
schema default. Models that copy a background call shape still send
heartbeat=60 on ordinary commands; this week 46 subagent sessions hit the
refusal 4 times each (173 refusals), 38 of them never ran a single shell
command, and the agents burned $316 / 1,498 model calls on retries.
2026-10-07 06:33:47 -07:00
KoNit-K
4d8024d0a1 fix(tools): normalize foreground terminal heartbeat 2026-10-07 06:33:47 -07:00
Teknium
911da42e9e refactor(security): remove the bundled tirith scanner from core
tirith ran `tirith check` on every terminal command, default-on with fail-open, as a
pinned PM binary auto-downloaded at startup. Measured against the shipped 0.4.2 binary
it caught 14/16 attack commands but flagged 12/24 everyday agent commands
(`echo $((6*7))`, `"$VAR/x.sh"`, `gh api | python3`, LAN curls, `.dev` hosts,
`pip install` via analysis_incomplete), and in cron/-q deny mode each of those is a
hard block. It only ever saw terminal strings (execute_code, writes and the browser
bypass it), fail-open meant no protection wherever the binary could not install
(Windows, Termux, x64 musl), and it produced a steady issue/PR stream (fail_open
semantics four times, install loops filling disks, a SIGSEGV hang, session-approval
scoping, third-party promo text on approval cards).

Removed: tools/tirith_security.py, the tirith branches of the command guard (the
is_tirith tuple, session-only "always" downgrade, import-error/fail-open paths,
unattended tirith pass), the CLI and gateway startup installers, the PM package and
lock pins, the nix runtime dep, security.tirith_* defaults, the CLI warning string
and three tirith tips (gaps refilled from the tail so translations survive), plus
the gateway's "no automated assessor" warning that only existed to point at tirith.

Config v50 drops security.tirith_* and enables nothing in its place. Hermes ships
no tirith plugin; if tirith upstream publishes one, it goes through normal catalog
admission under their name.
2026-10-06 14:22:13 -07:00
Gille
a789f874e2 fix(tools): coerce restored SSH session working directories 2026-10-03 16:30:40 +02:00
teknium1
6cc2f4ab92 fix(telemetry): terminal.outcome=timeout comes only from Hermes' deadline
_run_foreground recorded outcome=timeout whenever a backend exception's
text contained "timeout" (an SSH connect timeout, a sandbox API timeout).
That command never reached an exit status, and the doc says timeout comes
only from Hermes' own deadline flag (hermes_timed_out), which
terminal_outcome() already reads. Owner ruling: never from exception text.
The exception path now records nothing; the model-facing result (exit 124)
is unchanged.

Probe (code-read finding; the new test drives the real terminal_tool with a
backend raising "... Connection timeout"):
  before: terminal.outcome {backend: local, command_kind: shell_builtin, outcome: timeout} x1
  after:  no terminal.outcome row; tool result still exit_code 124
test_backend_exception_mentioning_timeout_is_not_a_terminal_timeout is RED on
base, green here.
2026-09-28 12:43:03 -07:00
teknium1
8d8836ddb1 feat(telemetry): harness-accuracy shared metrics for the agent loop
Five opt-in counters that tune the agent loop itself, recorded through
record_process_mark (disabled config => zero rows, zero files):

- hermes.file_edit.count: tool, mode, outcome, match_strategy. The fuzzy
  matcher reports the strategy that landed (or no_match / ambiguous) into a
  context-local probe opened only around the patch/write_file handlers, so we
  learn which strategies earn their keep without counting internal callers.
- hermes.loop_guard.count: provider, model, signal, detector. Hooked where
  the guardrail already warns/blocks/halts and at turn end for the iteration
  budget; latched once per turn per (signal, detector).
- hermes.tool_recovery.count: provider, model, tool, next_tool,
  next_outcome. One row per failed tool call, resolved against the model's
  next round (same tool first) or the turn end (no_tool_call / gave_up).
- hermes.terminal.outcome.count: backend, command_kind, outcome. The kind is
  a table lookup on the first program word, never the text. Hermes' own
  deadline/interrupt now set hermes_timed_out / hermes_interrupted on the
  backend result, so a command's own `exit 124` reads nonzero, not timeout.
  Disjoint dims from hermes.execution_backend.count (served vs not).
- hermes.model_reply_issue.count: provider, model, issue. Refusal and
  truncation only from the structured finish reason; empty/reasoning_only
  from the normalized message; issue=none per response as the denominator
  (model_route counts attempts and files empty replies as failures).

Background review / curator loops and _host_local / unmetered terminal
calls never count. Helpers live in shared_metrics_harness.py; call sites
are one or two lines each.
2026-09-28 12:43:03 -07:00
teknium1
25c1b008c8 feat(telemetry): wire memory, curator, delegation and backend call sites
- memory tool: one row per operation (a batch counts each op); gate/validation
  refusals are "rejected", store-level non-application "failed". Memory provider
  tools are counted in MemoryManager.handle_tool_call with the op read from the
  action arg or tool-name verb.
- curator: run_curator_review records one row per pass (dry run = skipped) with
  the before/after diff bucketed; a scheduled pass whose claim is held by another
  process counts as skipped. The home is captured before the review thread starts.
- delegate_task: _run_batch opens the call, each joined unit folds its results in,
  and the last unit emits the call's single row, so group-split background calls
  are not counted per unit.
- terminal / execute_code / browser: counted per call that reached the backend;
  the backend is resolved from the owning profile at call time (terminal plan
  env_type, code local/remote, browser CDP > Camofox > cloud provider > engine, or
  "extension" when the extension controller served the call). Guard refusals and
  Hermes' own _host_local commands are not counted.

Tests read rows back from the real store; each call-site group is red with its
source reverted.
2026-09-28 12:43:03 -07:00
Teknium
7c799a6565 feat(vercel): fresh sandboxes use a managed image (universal:latest); runtime presets deprecated, migration 49 (#126741)
* feat(vercel): start fresh sandboxes from a managed image instead of the deprecated runtime

Vercel deprecated Sandbox runtimes (node24/node22/python3.13) in Aug 2026 in favour of
images, and rejects runtime+image together and runtime with a snapshot source. New
terminal.vercel_image (default vercel/sandbox/universal:latest, Node 24 + Python 3.14)
picks the image for fresh sandboxes; a pinned terminal.vercel_runtime still works, wins
over the image and logs a deprecation warning; snapshot restores send neither.

Setup wizard prompts for the image, dashboard exposes both keys, status/config show the
effective choice, TERMINAL_VERCEL_IMAGE bridges config to the tool like its siblings.

* feat(config): migration 49 drops the seeded node24 Vercel runtime pin

Every pre-49 config.yaml carries terminal.vercel_runtime: node24 (the template default) and
the setup wizard mirrored it into .env as TERMINAL_VERCEL_RUNTIME. Both are the default
copied, not a choice, so the migration drops them and fresh sandboxes follow vercel_image;
node22 / python3.13 pins are the user's and survive. Persisted sandboxes are unaffected:
a snapshot restore never sends a runtime or an image.
2026-09-28 12:33:01 -07:00
Teknium
a5bd246865 Old pre-decomposition import paths are gone: plugin compat layer removed on schedule (#126164)
* refactor(plugins): remove the Sep 2026 decomposition compat layer on schedule

The PLUGIN-COMPAT layer (2776813df3 + d63e380324 + 0a5164cebe) kept pre-#102117 import paths
alive for external plugins until 2026-09-14. That window closed two weeks ago; since then the loader
has already been skipping plugins that use the old paths. This removes the layer itself:

- 328 appended `PLUGIN-COMPAT` blocks (lazy `__getattr__` pointer tables, re-exported third-party
  names, restored dead definitions) and the three re-export stub modules
  (gateway/startup_watchdog, hermes_cli/observability/relay_runtime, tools/environments/modal_utils)
- COMPAT_MANIFEST.md, compat_manifest.json, scripts/check_compat_pointers.py and its lint step
- the reporting surfaces: CLI banner notice, `hermes plugins compat`, the `hermes doctor` section,
  the post-update notice, the Desktop one-time dialog, the loader's pre-import skip and the
  `plugins.allow_deprecated_imports` escape hatch

An external plugin that still imports an old path now fails to load with its ImportError as the
reason in `hermes plugins list`, the same path as any broken plugin.

hermes_cli/plugin_compat.py stays as three inert stubs (compat_report, removal_in_effect,
summary_lines): an already-running pre-removal `hermes update` lazy-imports them after the checkout
swap (tests/compat/old_updater_surface.json).

In-tree fallout, both already dead: hermes_cli/setup.py::_check_espeak_ng (no callers; its
`shutil` came from a compat block) and gateway/config.py::SessionResetPolicy ("retained solely for
the scheduled plugin-compat window"). Two test_run_agent patches targeted the removed
`run_agent.handle_function_call` pointer; they now patch `model_tools.handle_function_call`, the
seam production reads, like every sibling test in that file.

* chore: retrigger CI (zero-job startup_failure phantom)

* test: drop resolution allowlist rows for the two deleted which() sites

hermes_cli/setup.py::_check_espeak_ng (dead) and tools/skillevaluator_scan.py::scanner_available
(a restored definition inside a PLUGIN-COMPAT block) no longer exist; the stale-row gate requires
their allowlist entries go with them.
2026-09-28 10:21:41 -07:00
teknium1
124b5c7d45 fix(review): key cwd/override records by the session's own profile home; keep /p/<launch>/ ids stable
Independent-review minors on #126157 (#123989 class):

- session.create is a plain @method, so tui_gateway/session_workdir.py::_register_session_cwd
  wrote the cwd record under the RAW session key while the scoped turn read
  profile:<p>:<key> and missed it until the first `cd`. The writer now binds the
  session's own profile_home around register_task_env_overrides.
- tools/terminal_tool.py::_task_env_overrides stayed raw-keyed, so two profiles
  registering the same task id (docker_image / cwd) still collided. Writer, clear
  and both readers (_has_isolation_overrides, resolve_task_overrides) now use
  _qualify_task_key; the isolation-override branch of _resolve_container_task_id
  returns the qualified key so the env cache and the override record agree.
- gateway/platforms/api_server.py::_derive_chat_session_id prefixed the seed for
  the NAMED LAUNCH profile addressed via /p/<launch>/, so prefixed and
  un-prefixed requests on one profile derived different ids. The prefix is now
  skipped when the routed name is the process's launch profile
  (_names_launch_profile vs get_routing_process_hermes_home()).

Tests (red on 3720519199c, green here):
  tests/tui_gateway/test_session_cwd_profile_key.py::test_secondary_profile_session_cwd_is_found_inside_its_scope
  tests/gateway/test_api_server.py::TestDeriveChatSessionId::test_launch_profile_prefix_keeps_the_unprefixed_id
2026-09-28 04:34:30 -07:00
teknium1
24b1c32bd2 fix(terminal,api-server): trim profile qualification of session-derived sandbox keys (#123989, salvage #124057 + #123991)
Fold the two salvaged fixes to the class and the salvage bar:

- tools/terminal_tool.py: `_qualify_task_key` reuses `_routed_home_task_key`
  instead of a duplicate qualifier; branch 2 (session-isolated sandboxes) AND
  branch 3's `session:<key>` (SSH-style backends) carry the routed profile, so a
  session id two profiles share (header-less API fingerprint, a DM chat id served
  by two bots) never resolves to one `_active_environments` slot. Cwd records
  keep the symmetric qualification. No routed home → raw key, unchanged.
- gateway/platforms/api_server.py: `_derive_chat_session_id` namespaces only
  named routed profiles, so default/standalone ids are byte-identical and live
  Open WebUI conversations survive the upgrade.
- Tests trimmed to two invariants: A→B→A across two temp profile homes under
  multiplex (distinct sandbox keys, alias follows the qualified parent, cwd
  isolated per profile), and derived-id namespacing without moving default.
  Both fail on 5912ed81ed, pass here.
2026-09-28 04:34:30 -07:00
Nabil Ahmed Ameena
a6706b5c1b fix(terminal): qualify session-isolated container keys and cwd records under a routed profile scope (#123989)
A multiplexed host serves every profile in one process, and header-less API-server
clients derive their session id from a fingerprint of the system prompt + first
user message. Under per-session isolation (docker + container_persistent: false,
plus plugin backends declaring session_isolated_when_nonpersistent) branch 2 of
_resolve_container_task_id keyed the raw id, so two profiles whose conversations
open with the same text shared one _active_environments slot: the second profile's
turn attached to the first profile's sandbox, with the first profile's image,
mounts and exported environment. Verified live against real docker (both
directions on unmodified main; isolated after the fix).

Routed scopes (HERMES_HOME override: multiplex turns named AND default,
per-profile TUI/desktop RPC, cron ticks) now qualify the key with the profile
name or home realpath; CLI and single-profile gateways keep the historical raw
key. The session-cwd record/get/clear trio gets the same qualification so the
fingerprint collision cannot carry one profile's cd state into another's.

Regression tests in TestRoutedScopeQualification fail on pre-fix code (4/6) and
pass with the fix; persistent-Docker behavior is byte-identical (labels stay
profile:<name> / default).
2026-09-28 04:34:30 -07:00
Teknium
399d956903 feat(bot_desktop): Bot Screen, computer_use and the browser run inside the terminal backend (#121169)
* feat(docker): publish nousresearch/hermes-sandbox:desktop for terminal backends

The terminal backends (docker, modal, daytona, singularity) all default to
nikolaik/python-nodejs:python3.11-nodejs20, a bare Python+Node base. For Bot
Screen, computer_use and the browser to run INSIDE that sandbox instead of on
the gateway host, the sandbox image needs the display stack.

docker/sandbox-desktop.Dockerfile is that base plus:
  - the everyday tools it lacked (jq, ripgrep, fd, tmux, less, nano, vim,
    zip, rsync, tree, procps, htop, sudo for the base's uid-1000 `pn`)
  - the exact package set the Hermes -desktop image installs (TigerVNC,
    Xfce components, dbus, xauth, fonts)
  - Playwright's headed Chromium (same build as the -desktop image)
  - cua-driver 0.28.2 from its pinned release tarball

No Hermes inside; the default user stays root like the base so nothing
changes for people who just switch docker_image. Desktop processes run as
`pn`. 4.27 GB on amd64.

docker.yml gains a `sandbox` variant with its own cache scope and repository
(nousresearch/hermes-sandbox:desktop, :main-desktop, :<release>-desktop);
the docker-integration suite is skipped for it (no Hermes to test) and
docker/sandbox-desktop-smoke.sh runs instead: as `pn`, every launcher and
cua-driver binary resolves, the real launcher.sh publishes :20, the RFB
socket completes the 3.8 handshake relayed over `docker exec -i` stdio, and
a headed Chromium maps a window on that display. hadolint lints the new
Dockerfile in docker-lint.yml.

* feat(docker): sandbox desktop base on python3.13-nodejs26

Matches the Hermes image (Python 3.13 / Node 26) and the top of requires-python;
the default docker_image tag it inherited was Python 3.11 / Node 20. Same pn
uid 1000, Debian 13; smoke (launcher, RFB relay, headed Chromium) passes.

* feat(docker): bake agent-browser into hermes-sandbox:desktop

The browser tools drive the agent-browser CLI; when the browser follows the
terminal backend that CLI has to exist inside the sandbox. Pinned to the same
^0.26.0 range the gateway resolves, --ignore-scripts like the gateway's npx path.

* feat(bot_desktop): the screen, computer_use and the browser follow the terminal backend

A user who sandboxes `terminal` (docker/ssh/singularity) had the agent's
screen, cua-driver and Chromium running on the gateway HOST beside that
sandbox: Bot Screen gave a headless host a display, the Xfce panel carries
xfce4-terminal, and `computer_use` could open a shell outside the boundary
the sandbox exists for.

Now the desktop lives where the terminal lives:

- tools/environments/streams.py: one primitive per spawn-per-call backend, the
  local argv prefix that runs its remainder inside the sandbox with stdio open
  (`docker exec -i`, `ssh`, `apptainer exec`). SDK backends (modal, daytona,
  vercel) have none and report so.
- tools/bot_desktop/sandbox_host.py: launcher.sh runs inside the sandbox as
  the image's `pn`; the pane's RFB bytes ride a 12-line python relay over that
  prefix; `cua-driver mcp` is the prefix + the sandbox image's own driver.
- tools/bot_desktop/placement.py + `bot_desktop.placement` (auto|terminal|
  gateway). `auto` follows the backend; a sandbox that cannot host a screen
  REFUSES with the opt-in named instead of silently using the host.
- runtime.start/stop/status/published_env branch on placement; the pane,
  lease, epoch fencing and CLI are unchanged.
- cua_backend: the MCP invocation is the sandbox one when the screen is
  there; the host driver's runtime contract is irrelevant then; check_fn is
  true under a terminal placement without a host binary.
- browser_tool_session: agent-browser invocations are wrapped in the prefix
  with the daemon, socket dir and profile inside the sandbox; screenshots are
  fetched back so MEDIA: paths keep working; recycle closes the sandbox
  daemon.
- web_routers/display.py: the bridge pumps a relay's stdio when the screen is
  in a sandbox, a unix socket otherwise.

Live on docker with nousresearch/hermes-sandbox:desktop: start/observe/RFB
handshake through the dashboard bridge, human takeover fences the agent
(HumanHasControl) and keystrokes reach the sandbox Xvnc, handback restores,
three start/stop rounds leave zero desktop processes; computer_use capture
and list_windows see only the sandbox's Xfce; browser_navigate/snapshot/
vision run with Chromium and agent-browser inside the container and zero
host processes on the bot profile; modal + auto refuses naming the opt-in.

* feat(desktop): Screen pane shows where a sandbox-placed screen runs; Install is host-only

DesktopStatus gains placement ('gateway' | 'terminal:<backend>'). A sandbox
image lacking the stack is a blocker naming hermes-sandbox:desktop, shown in
place of Start; install_command stays None there because the pane's Install
button runs the package manager on the gateway host, the wrong machine, and
display.install refuses for the same reason. The pane header carries
'Screen runs inside the docker sandbox, with the terminal' (4 locales).

* fix(bot_desktop): "is the screen in the sandbox" is a disk check on hot paths, never a config read

Every browser command and CUA spawn asked in_sandbox(), which resolves placement by
loading config, which initializes HERMES_HOME. Under a test's fake home that raised
HomeInitializationError from _run_browser_command; on a real host it read config per
click. Hot paths now ask sandbox_screen_running(): the start marker on disk, written
only by a sandbox start. Policy (in_sandbox) stays for start/install, where config is
the question. display.observe gates on "an RFB endpoint exists" for either placement.

* test(moa): late-accounting sink test asserts the wedged slot's row, not sink order

Under CI load the poll loop can see the interrupt before collecting the fast slot, so the
fast slot also arrives late and first; the test then failed on sink_calls[0]. The
contract is that the wedged slot's real usage reaches the sink.

* chore: retrigger CI (zero-job dispatch failure, auto-heal)

* fix(bot_desktop): a sandbox that died under a live screen fails loudly, never falls to the host

sandbox_screen_running() drops a start marker whose terminal environment is no longer
registered (stale after a process restart). When the environment object outlives its
container, the browser's sandbox wrap now checks the published DISPLAY and raises
"the screen inside the terminal backend's sandbox is gone; start it again" instead of
KeyError('AGENT_BROWSER_PROFILE'). Live: fresh sandbox navigate ok; docker rm -f the
container; next navigate returns that error; zero host Chromium either way.

* feat(terminal): nousresearch/hermes-sandbox:desktop is the default container sandbox

Every container backend (docker, modal, daytona, singularity) now defaults to the
sandbox image with the desktop stack, so Bot Screen, computer_use and the browser
run inside the sandbox for everyone who never chose an image; Python 3.13 / Node 26
match the Hermes image. One constant (DEFAULT_SANDBOX_IMAGE) replaces six copies of
the old literal. Migration 47 moves saved configs still holding the OLD default and
never touches an image the user pinned. Docker reuse recreates a container built
from another image, or the flip would silently never take effect for anyone with a
persisted container (live: old container removed, new one on 3.13 / Node 26 with
Xvnc, cua-driver, agent-browser present).

* chore: retrigger CI (zero-job dispatch failure)

* chore: retrigger CI (zero-job dispatch failure, auto-heal)

* chore: retrigger CI (zero-job dispatch failure, auto-heal)

* chore(config): template stamps v47 and shows the new default sandbox image

The template is what install.sh / docker / doctor --fix seed; a stamp behind
DEFAULT_CONFIG makes every fresh install migrate on first run.

* feat(sandbox): the default image change is a decision, not a surprise

A persisted Docker sandbox on another image is kept when docker_image is unset;
only a written docker_image (an explicit pin) recreates it. The pin verdict
travels as TERMINAL_DOCKER_IMAGE_PINNED through both terminal bridges (process
env and per-profile scope) and the container-config allowlist.

Approval surfaces, all through hermes_cli.sandbox_image_switch: the interactive
CLI asks once at startup (y = pin the new image, n = pin the current one, Enter =
ask later); the Screen pane shows the same choice with Switch / Keep buttons via
display.switchSandboxImage; `hermes config set terminal.docker_image …` is the
same answer from any shell. Gateways and cron never decide: they keep the sandbox
and log the notice.

Migration 47 now unsets a saved image equal to the OLD default instead of
rewriting it to the new one — that value was the template copied, not a pin, and
rewriting it would have made the runtime recreate existing sandboxes unasked.

Modal restores its snapshot and Daytona reuses its labeled sandbox regardless of
the configured image, so existing sandboxes there were already untouched.

* fix(config): both plain defaults that preceded the desktop sandbox image are template copies

main pinned nikolaik/python-nodejs:python3.14-nodejs22 (cd0f97f833) without a migration;
a saved config holding either literal is unset by migration 47, so it follows the default
and existing sandboxes get the keep-or-switch decision instead of a silent recreate.

* ci(docker): build the sandbox image on release/dispatch, not every main push

Leaves docker.yml exactly as on main. The sandbox image carries no Hermes code,
so two 4 GB multi-arch builds per merge bought nothing. sandbox-image.yml builds
and smokes on a PR that edits its own Dockerfile/smoke, and publishes only on a
release or a manual dispatch with publish=true. Stable tag stays :desktop.

* fix(config): keep main's config.py/config_defaults.py edits under the sandbox-image delta

The rebase resolved both files wholesale with the branch side, dropping main's move to
hermes_yaml (the 3.14 runtime venv has no PyYAML) and the 3.14 base pin. This is main's
version plus exactly the branch's own changes: DEFAULT_SANDBOX_IMAGE, the pin verdict in the
env bridge, placement defaults and the v47 stamp.

* test: sandbox-image tests read config.yaml through hermes_yaml (no PyYAML on the 3.14 runtime)

* fix(bot_desktop): read the sandbox marker BOM-tolerantly (windows footgun lint)

* fix(bot_desktop): placement is the authority; sandbox screen survives restarts

Review findings on the sandbox-hosted Bot Screen, each reproduced live first.

Authority. The browser preflight and the CUA invocation keyed off screen
LIVENESS, so `placement: terminal` with the screen not yet up handed the tool an
unchanged host command. `runtime.tool_placement()` is now the one resolver:
terminal placement starts the sandbox screen on demand (no auto_start opt-in
inside the user's own sandbox), refused placement raises its reason, and neither
ever yields the host. placement.resolve() answers a local backend from env alone
so the common case costs no config load on the spawn path.

Restart. sandbox_screen_running() deleted the marker whenever the process-local
terminal registry was empty, i.e. after every gateway restart, while Xvnc kept
running in the container; stop() then returned False and left it. The marker
now records the owning container; liveness comes from `docker inspect` on it,
stop/status re-attach to the recorded owner (even after the placement setting
moved), and only a container that is gone drops the marker.

SSH. remote_argv emitted `bash -c <script>` as three words; OpenSSH joins them
and the remote login shell ran `bash -c export` and the rest itself. The script
travels as one quoted word for ssh (remote_command knows the backend); docker
and apptainer keep argv.

CDP reach. agent-browser inside the sandbox reports the sandbox's loopback;
the Browser Use harness, browser_exec and the vault supervisor connect from the
host and got connection refused. streams.forward_port() proxies a local port
over the exec stream (same relay as the RFB bridge) and the CDP URL is rewritten
to the local end.

pids limit. --pids-limit 256 counts threads; measured on the desktop image the
desktop stack is 44, one Chromium tab 212, the agent's browser with two tabs
488. Past the cap every further docker exec died with "procReady not received".
Default is 2048 with the measurements in the comment.

Replacement. An approved image switch force-removed the old container before
`docker run` tried the new image; a private tag or registry outage left nothing.
The image is inspected/pulled first and the old container kept on failure.

Desktop integration. The sandbox start never passed the dock's browser launcher
(no Browser icon) and the thumbnail needed a host launcher pid + host ImageGrab
(always None). The dock runs the sandbox's Playwright Chromium on the shared
profile; the thumbnail is grabbed inside the sandbox (Pillow baked into the
image). The browser profile moves from /tmp — a 512 MB tmpfs emptied on every
container stop — to the desktop user's home, so logins follow the container.

Pin provenance. A TERMINAL_DOCKER_IMAGE written in a routed profile's .env is a
pin even when it spells the default; the scope compared values before.

* docs(bot-screen): no literal tmp path in the profile-location note

* fix(bot_desktop): docker inspect liveness probe closes stdin (TUI subprocess guard)

* fix(bot_desktop): adopting a screen the sandbox kept records the marker

Live ssh probe: after the host's state was lost while the sandbox kept its
Xvnc, start() took the idempotent early return (display already published)
and never wrote the host marker, so status/thumbnail/stop lost the screen.
Record the adopted display like a fresh launch.

Docs: what an ssh host of your own must carry, and why a Dockerfile ENV is
not enough for a login session (PLAYWRIGHT_BROWSERS_PATH via /etc/environment).

* docker(sandbox-desktop): login sessions find the browser (PLAYWRIGHT_BROWSERS_PATH via /etc/environment)

* docs(bot-screen): what the Apptainer path inherits from the image and what it does not

* chore(config): sandbox-image migration is 47→48 (main took 47 for compression.threshold_tokens)

* chore: retrigger CI (zero-job dispatch failure, auto-heal)
2026-09-28 03:34:07 -07:00
kshitijk4poor
e6f0966b01 fix(terminal): heartbeat error text matches the 0-disables schema
Since 4317ed0e71 the heartbeat schema allows 0 (disabled) and clamps
positive values to 60, but the validation error still said "min 60",
steering models away from the valid 0. Flagged on #119202.
2026-09-27 18:17:27 +05:30
kur4i
4317ed0e71 fix(terminal): make disabled heartbeat schema-valid
(cherry picked from commit b746557577832c1ac1fac5e54088623d1b239f2f)
2026-09-26 22:19:53 -05:00
brooklyn!
b686f1b40b fix(docker): do not invent a workspace mount for a raw Windows override
The mount flag is off in that case. The override must fall back to the
sanitized config cwd, not docker run -w /workspace.
2026-09-26 18:27:10 -05:00
brooklyn!
1a72042115 fix(docker): bind a Windows workspace when /workspace is already claimed
A volume that already owns /workspace skipped the configured working
directory, so tools treated that host path as unmounted. Bind it at a
second mount, or point tools at the volume that already has it, for any
drive path.
2026-09-26 18:27:10 -05:00
brooklyn!
b9d5e4d17f fix(docker): remap a mounted host session cwd to /workspace
A Desktop Docker session that registers an absolute host directory
such as /mnt/... or /srv/... as its cwd skipped the /Users|/home/
drive-letter heuristic, so the mount check never ran and commands
were wrapped with cd to that host path. Classify the mounted host
directory as unusable before that heuristic, and remap it to
/workspace in the live-env write and the per-command resolver.
2026-09-26 17:34:46 -05:00
xxxigm
666681cbf3 fix(terminal): do not cd an ssh session into the container home
The session cwd can already be the Hermes host's /opt/data/home. That
path is not on the SSH target, so the implicit cd exits 126 and the
command never runs.

(cherry picked from commit 4e99397bb4e18416b6a3e0b850d51604c0ad0d1d)
2026-09-26 06:20:21 +05:30
Hermes Agent
ec5c9c738a fix(processes): persist_on_release keeps background jobs alive across lifecycle kill sweeps (#41225)
Background processes spawned with terminal(background=true) are killed from
three agent-lifecycle sweeps: agent release()'s kill_all, a gateway turn
timeout's kill_started_since, and agent close's owned-process loop. Jobs the
user explicitly wants to outlive the session (overnight batches, watchful
daemons) had no way to opt out.

Add terminal(background=true, persist_on_release=true):
- ProcessSession.persist_on_release, stamped by spawn_local/spawn_via_env,
  carried in crash-recovery checkpoints and exposed via list_sessions()
- kill_all skips persisted sessions only for lifecycle sources
  (_LIFECYCLE_KILL_SOURCES: kill_all, gateway_turn_timeout, agent_close);
  explicit operator stops (process_manage kill, /stop slash + RPC mirror,
  CLI /stop) now pass distinct sources so they still reach persisted jobs
- the agent_close owned-process loop in _close_task_resources skips
  persisted sessions the same way
- gateway shutdown keeps killing persisted jobs (source=gateway_shutdown):
  the host is going away and survivors would become PPID=1 orphans

Co-authored-by: salvaged from #109846 (persist_on_release plumbing) and
extended to the turn-timeout and agent_close paths.
2026-09-25 13:49:31 -05:00
teknium1
bd14eb1c93 fix(terminal): persistent Docker keys a routed profile's cron work to its profile container
Under persistent Docker, profile B's session-bound work keys profile:B but its
session-less (cron) work keyed home:<path>, so the same profile ran two
long-lived containers. The routed no-session branch now returns the same
profile key as branch 3 when Docker is persistent (profile-scoped); other
backends keep the per-home key.
2026-09-23 16:58:12 -07:00
teknium1
551497dcbf fix(terminal): session-less work for a routed profile keys its own terminal environment
A multiplexed host runs every profile's cron jobs without a session key, and
_resolve_container_task_id collapsed all of them onto the shared "default"
environment. Profile B's cron tool calls therefore reused the LocalEnvironment
the launch profile's job created: B's terminal subprocess saw the launch
profile's .env residue and bridged TERMINAL_* (TERMINAL_CWD, backend policy).

Found by tests/e2e/core/tenancy/test_two_tenant_gateway.py (C7 canary): alpha's
cron env snapshot carried default's TENANT_MARKER and TERMINAL_CWD. Session-less
work under a routed home override now keys home:<realpath>; the launch profile
and single-profile processes keep "default". The unit test that pinned the
shared key for a routed profile is updated.
2026-09-23 16:58:12 -07:00
teknium1
edff33853a chore(terminal): diet the heartbeat schema description
Every tool schema rides every API call; the first draft read like docs (111 est. tokens).
Kept the two facts the model needs — when to use it and what it delivers — the rest lives in
tools-reference.md.
2026-09-21 15:02:49 -07:00
teknium1
65b0ff38ea feat(terminal): heartbeat notifications for long background processes
`terminal(background=true, heartbeat=N)` emits a `heartbeat` event every N seconds
(floor 60) carrying only the output produced since the previous one, plus the usual
completion notice. The agent stays current on a long bounded job (merge train, full
test suite, deploy) and reacts to a failure within N seconds instead of at exit.

Why: `notify=true` fires once at exit, so multi-hour merge trains ran silently — the
parent's prompt cache went cold and every "what's up" cost 5–10 rediscovery calls;
30 days of batch sessions show 4,930 hand status polls (14% of all tool calls).
`notify=[pattern]` cannot serve this: its lifetime cap (8) exists precisely to stop
periodic output from flooding the agent.

Mechanism: one daemon timer thread for every heartbeat session (reader threads block
on the pipe and cannot keep time); delta output via a total-ingested counter over the
rolling buffer; heartbeats only where the completion notice can be delivered (same
async-support/subagent gates), never after exit. `heartbeat_seconds` is checkpointed.
Rendered on CLI, gateway and TUI through the existing process-notification paths.
2026-09-21 15:02:49 -07:00
John Paul Soliva
eccc9ab49a fix(bot-mode): a teammate's reply reaches the sender whole, and a cut completion says so
A bot DM's reply comes back as the delivery process's completion notification,
which carried the last 2000 characters of that process's output — the right
tail for a build log, but a bot may send 16,000 characters (MESSAGE_MAX_CHARS)
and its teammate's answer routinely runs longer than 2000. The sender got the
tail of the reply, header included in the cut, with nothing saying so, and
relayed it as the whole answer.

The registry now sizes a completion per process (ProcessSession
.completion_output_chars, checkpointed) and declares a cut (output_cut) when
the output did not fit; the notice names the cut and the process log that has
the rest. tools/bot_mode_dm._spawn_delivery — the one spawn point for every
DM lane (local, live-owner, Desktop relay waiter) — asks for MESSAGE_MAX_CHARS
plus header room. Everything else keeps the 2000-char tail.

Fixes #115334
2026-09-20 10:23:28 -07:00
kokhlo
b911b9794e fix(tools): sanitize cwd overrides written into live container envs
A cwd override registered by a desktop/TUI surface is a raw host path. On
container backends it was written verbatim into the cached live env's cwd,
so every file-tools command wrapper did `builtin cd -- <host path> || exit 126`
and all writes outside the mapped workspace failed with an unrelated `cd:`
error while terminal commands kept working (their per-command resolver
already sanitizes).

The live-env write now mirrors the creation-path guards: a host/relative cwd
is remapped to /workspace when it is the directory mounted there (docker cwd
passthrough), otherwise not applied to the live env at all. The session cwd
record keeps the raw path and non-container backends apply overrides
verbatim, so ACP project-root switching is unchanged.

Fixes #113894

(cherry picked from commit d712c6b47d28f213773f40ebac81dd9a45c6e94f)
2026-09-18 09:54:45 -07:00
brooklyn!
dd68d17567 feat(approval): prepare GUI terminal asks before ordered execution 2026-09-16 06:27:23 -05:00
teknium1
30b22b54ae fix(tools): bound execute_code's lifecycle probe and keep the terminal guard answerable to /stop
execute_code ran the same unbounded _is_supervised_gateway_process() probe
ahead of every cell, so the wedge #111922 bounds in terminal_tool still hung
an execute_code call (and its cron slot) forever: share the cell's deadline
and fail closed with a retryable error when the probe renders no verdict.

Moving the terminal pre-exec guard onto a deadline worker made it blind to
/stop, which keys on the tool thread's ident: record the acting-for tid in a
contextvar (copied into the worker by run_bounded_sync) so is_interrupted()
on the worker honours the tool thread's bit too.

Floor the guard's share of the deadline at 30s so a short command timeout
does not turn the guard's own cold-start cost (imports, git probes under
load) into a refusal — tests/tools/test_terminal_error_redaction.py was red
on the branch for exactly that.
2026-09-15 19:09:29 -07:00
teknium1
c832920275 fix(tools): pre-exec guard that misses the deadline refuses the command
The salvaged commit put `_pre_exec_block` behind the command's
`run_bounded_sync` deadline but let a timed-out guard fall through into
execution. The gateway-lifecycle, dangerous-workdir and self-repo checks
apply unconditionally (`force=True` cannot bypass them), so a guard that
never rendered a verdict must not let the command run unguarded: return
the terminal error envelope (`status: error`, "did not finish ... Retry
the call") instead, mirroring how the bounded `env.execute` path reports
its own expiry as a result rather than continuing.

Tests trimmed to the two invariants: a wedged guard returns a bounded
error without executing; a completed guard keeps its verdict (pass ->
execution, rejection -> its own blocked result).
2026-09-15 19:09:29 -07:00
KoNit-K
c1e749d679 fix(tools): bound terminal pre-exec guards 2026-09-15 19:09:29 -07:00
teknium1
23036e20a6 fix(ux): plain-language, actionable user-facing messages (core)
Squashed integration of the user-facing message audit for this surface set.
Full per-finding receipts: /tmp/ux-audit/lanes/*-receipt.md (campaign artifacts).
2026-09-15 04:12:13 -07:00
Teknium
325d73ce07 docs(tools): clarify terminal background waits
Port from Kilo-Org/kilocode#13224: fixed waits belong in foreground terminal calls, while background mode is reserved for independently running processes.
2026-09-15 03:52:24 -07:00
infinitycrew39
a5c801c8dc fix(tools): never ambient-bridge TERMINAL_* under a profile home override
A multiplexed dashboard can call _ensure_terminal_env_bridged while a
secondary profile's HERMES_HOME override is active. The one-shot latch then
wrote that profile's docker policy into process-global os.environ and poisoned
later unscoped launch-profile tool calls (#107422).

Skip the ambient bridge whenever a context-local home override is set —
ambient env is launch-profile authority only; routed profiles must use
terminal_scope (same rule as env_loader._reapply_terminal_config_bridge).

(cherry picked from commit 2050efb24fdc9d54a282b24d0042b90f47486c5a)
2026-09-11 15:29:15 -07:00
Teknium
6d9c166455 Merge pull request #103529 from NousResearch/fix/terminal-auto-background
fix(terminal): an over-cap foreground timeout runs as a tracked background process instead of being refused (454 refusals in one run)
2026-09-06 12:06:04 -07:00
Teknium
463292351f fix: mid-turn user message no longer waits behind a foreground terminal command
A message typed while the agent runs (CLI busy_input_mode=interrupt, gateway
priority redirect, ACP redirect) goes through AIAgent.redirect(). During tool
execution redirect() degrades to steer(), whose delivery rides the tool result
— so a long foreground command (a `sleep 285` CI poller, a build) parked the
user's message until it exited. The UI printed "Redirected current turn" while
nothing happened for minutes.

redirect() now also asks the tool workers to YIELD (tools/interrupt.request_yield).
The local terminal backend's wait loop honours it: the drain thread is stopped, the
still-running Popen is adopted by the process registry as a notify_on_complete
background session (ProcessRegistry.adopt_local — output so far seeds the buffer,
the registry reader continues from the pipe), and the tool returns immediately with
status "yielded_to_background" + session_id. The command is never killed; the
completion notification arrives as usual and process(poll/wait/log/kill) work on it.

Non-local backends and internal env.execute() consumers pass no yield_handler and
are unaffected; a stale yield bit is cleared with the interrupt bit per worker tid.
2026-09-05 13:51:06 -07:00
PRATHAMESH75
84b70e473e fix(docker): teardown workers of reaper-detached containers are drained at exit (#86317)
DockerEnvironment.cleanup() runs docker stop + docker rm -f on a daemon thread and
keeps the handle on the env. The idle reaper pops the env out of _active_environments
BEFORE calling cleanup(), and the atexit drain only iterated that registry — so a
detached env's worker was unreachable and died with the interpreter, leaving a
stopped (or, if the exit came fast enough, still running) labeled container behind
while the log said the environment was cleaned.

Every teardown worker is now also recorded in a module-level set in docker.py;
_atexit_cleanup joins that set after the registry pass via
DockerEnvironment.wait_for_all_teardowns (re-snapshotting each pass, since the
reaper can start a worker while the drain runs). Finished workers are dropped from
the set on each drain so it cannot grow across a long gateway life.

Mechanism from #86344 by @PRATHAMESH75; this is the slim redo — one shared set
plus one static drain hooked into the existing terminal_tool atexit, instead of a
second atexit registration in docker.py.
2026-09-05 21:07:14 +05:30