_ship_file_to_remote was _remote_write(..., check=True) under another
name; its five call sites (code_execution_tool, code_kernel_remote) call
_remote_write with check=True directly. code_kernel_remote now imports
_remote_write, _execute_checked and _private_dirs_cmd from
code_execution_rpc at module top, which drops two function-level imports
back into the tool file.
_kill_process_group lived in code_execution_tool but its one caller is
SessionKernel.teardown in code_kernel, which always passed escalate=True.
It moves to code_kernel without the parameter (always SIGTERM, wait 5s,
SIGKILL), with signal and agent.deadline imported at module top. The
escalate=False branch was reached only by tests.
Tests patch _remote_write in both modules where they patched the wrapper.
test_code_kernel_owned_group stubs the teardown kill to a SIGTERM-only
tree kill for its precondition instead of passing escalate=False.
The footgun lint requires BOM-tolerant reads. The runner writes the spill
without a BOM, so the only change is that output starting with U+FEFF loses
that character in the spill. The bare skipif decorators hid the POSIX-only
spill tests from the macOS lane; platforms("posix") lets it import them.
Refs #122024
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
The runner caps its spill at 5,000,000 characters written as UTF-8, but the
host read cap compared that count against st_size in bytes. Multibyte cell
output past ~1.67M CJK / ~2.5M accented characters was refused as a swapped
file and lost its full spill. Derive the read cap from the shared character
cap at 4 bytes per character.
The salvaged _sanitize_cell_spill swallowed every exception with a
noqa'd blind except, which the health ratchet rejects; keep the
fail-closed return but log the traceback at debug.
Fixes#122024
Oversized execute_code stdout is spilled to disk so the model can page it
with read_file, but both spill emitters wrote raw output: the host-side
_spill_full_stdout spilled before _clean_output's ANSI strip + secret
redaction, and the session-kernel runner wrote cell stdout into its tmpdir
with a plain open() that follows symlinks. The result warning then directs
the model to read the file, so the on-disk copy kept credentials the inline
result masked.
- _spill_full_stdout now ANSI-strips and redacts (code_file=True) before
writing, and uses ensure_spill_dir + default-private
write_text_exclusive: 0700 dir, 0600 file, symlink-safe create/replace.
The stale bind-mount rationale is corrected: cache/exec is not in
credential_files._CACHE_DIRS and is never mounted into remote backends.
- The generated kernel runner spills via O_CREAT|O_EXCL|O_NOFOLLOW at 0600,
so a cell squatting cell_NNNNNN_stdout.txt with a symlink cannot redirect
the write onto a host file.
- _cell_result re-publishes runner-side spills through _spill_full_stdout
instead of advertising the tmpdir path. _sanitize_cell_spill confines the
read to a resolved direct child of the kernel tmpdir (dir_fd-anchored,
realpath gate, O_NONBLOCK, regular-file and size cap), so a forged reply
frame or swapped-in FIFO/huge file cannot block the host under kernel.lock
or redirect the read/unlink outside the sandbox. The raw tmpdir copy is
removed on every outcome, and the published cache/exec path survives the
kernel teardown that follows sys.exit() cells.
- On republish failure the warning names the host-side partial spill
explicitly rather than leaving a path it contradicts.
- Shared _sanitize_output_text helper replaces four open-coded copies of
the ANSI-strip + redact pipeline.
Tests: real-kernel e2e for both emitters (masked on disk, ANSI-stripped,
0600 in 0700), symlink-squat e2e proving a planted link is not followed,
sys.exit() teardown survival, FIFO/link/../ confinement, oversized swap
rejection, and fail-closed fallback semantics. The kernel e2e places the
secret past the runner's 1MB clip so the published file can only come from
the runner spill, not the host-side fallback.
execute_code redacted stdout/stderr with code_file=True, which skips the
ENV-assignment pass, so a script printing .env-style lines
(MY_SERVICE_TOKEN=<opaque>) returned prefix-less credentials raw. The
terminal tool picks the pass from the command line; execute_code has no
command, so classify by output shape instead: whole lines of
[export ]NAME=value get the ENV-assignment pass, everything else keeps
code_file=True (MAX_TOKENS = 100, indented source, f-strings unchanged,
per #43025). Applied to the shared remote pipeline and the local kernel.
Fixes#95509
Nested calls from execute_code carried the outer session_id/turn_id but
not conversation_id, so pre/post_tool_call, transform_tool_result and the
tool middleware saw conversation_id="" for them -- the field the hooks docs
tell plugins to key per-conversation state on. Thread it through the same
sites as session_id/turn_id (handler, local CellAuthority, both remote RPC
routes). Adds a test driving both remote routes (persistent kernel and
per-call fallback) through handle_function_call.
Refs #145870
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
Tool calls made from inside execute_code reached pre_tool_call hooks with an empty session_id: the RPC dispatchers called handle_function_call with only task_id. In a gateway serving several conversations from one process, a hook could therefore attribute a nested call to whichever conversation bound a turn most recently.
Thread the outer call session_id and turn_id from the execute_code dispatch through the handler, the local session kernel CellAuthority, and both remote RPC paths (per-call poll loop and remote session kernel), so nested calls fire hooks with the same identity as direct calls.
Closes#145870.
- The scan cannot tell whether the cell used the edited module, so the
warning says "if this cell used it without reloading" instead of
asserting the old code ran.
- Docs name both result fields (`warning` local, `kernel.warning` remote).
- Tests cover a non-ASCII module name and a cell that replaces
sys.modules, the two cases fixed in the previous commit.
- Both scan calls in run_cell are wrapped, so a cell that leaves
sys.modules or its keys in an unusable shape cannot end the kernel.
- The host accepts any dotted identifier (`str.isidentifier` per part),
so an edited `módulo` is named again.
Review of the first version.
- The scan ran outside the cell's try and touched module attributes, so a
lazy module whose attribute access raises, a non-module entry in
sys.modules or an unusable __file__ killed the kernel. It now reads the
module dict directly (no lazy import is triggered) and skips any entry
it cannot read.
- A module edited and reloaded in one cell was named in the next. The
record keeps the import spec next to the mtime: a reload or re-import
installs a new spec, so only a module still loaded from the old source
is named.
- The warning is built from cell-controlled names. The host keeps only
plain dotted identifiers from a real list and redacts them like stdout.
- Path filters match whole path components.
A session kernel keeps every imported module loaded, so after the agent
patches a project file the next execute_code call still runs the old code
and a correct fix looks like it failed. Nothing told the model why.
The kernel runner now records the source mtime of each imported project
module (stdlib and site-packages are skipped) and, before each cell, names
the modules whose file changed since. The result carries a warning that
says the cell ran the old code and how to pick up the edit
(importlib.reload, or reset=true). Each edit is named once. No state is
discarded: variables, imports and open handles survive.
Reported in #127819, which reset the whole kernel on any Python edit under
the working folder; this keeps the session and tells the model instead.
Works for local and remote kernels (the check lives in the shared cell
runner).
A session shutdown now derives the sandbox-qualified owner for the CURRENT
hosted scope (or the bare session key locally) and disposes exactly that
owner, instead of suffix-matching every kernel whose owner ends in the
session key. Two hosted agents sharing a session key therefore never tear
down each other's kernels at a session boundary: the suffix predicate let
one agent's close run pkill/kill/rm -rf in the other agent's sandbox.
Locally the match is exact again, so closing session "room" no longer
also disposes "telegram:room". Cross-agent eviction and atexit teardown
remain separate trusted operations.
Kernel owners are sandbox-qualified inside a hosted scope, but the session
boundary shut down by the bare key and found nothing. The boundary now matches
the sandbox-qualified owner too. And kernel maintenance (idle reap, cap
eviction, shutdown) may run on another agent's thread or none: remote kernels
capture their owning scope at spawn and run their commands under it, so another
agent's eviction still stops the service instead of losing the record and
leaving the process running.
Hosted Hermes serves many tenants' agents from one process, and each agent's
commands, code, background processes and files must live in that agent's own
remote sandbox. Until now the environment a tool reached was keyed by task id,
session key or profile path, so nothing tied it to the agent the bound scope
names, and a hosted scope could fall back to running on this host.
The sandbox an operation reaches is now derived from the bound scope's
(tenant, agent) alone (tools/environments/sandbox_scope.py). In a hosted scope:
- every environment key is the agent's sandbox key, whatever task id a call
carries; the terminal.backend provider must declare serves_hosted_scopes
(built-ins are refused) and receives scope= and sandbox= at creation, with
task_id set to the identity's key;
- core wraps the returned environment in ScopedEnvironment, which refuses any
call made under another agent's scope (or none) and passes the bound scope
to execute/fetch_* when the backend declares it; a cached environment that is
not the agent's own is refused at lookup;
- terminal, execute_code (always the remote kernel), background processes and
read/write/patch/search go through that environment; file-tool bookkeeping
never stats or opens the requested path on the host;
- background processes carry the sandbox key they were started under, and
another agent's process is indistinguishable from a missing one (get, list,
prefix lookup, kill sweeps).
Environments gain start_process/attach_process/stop_process with a
bidirectional byte stream (ProcessStream), implemented for the local backend
and exec-prefix backends; a ProcessRef naming another sandbox is refused.
Credentials are typed as broker references only (CredentialRef); no broker
exists yet, so none are passed.
Local installs are unchanged: with no hosted scope bound every branch keeps
today's keying and backends. A conformance module with a recording stub
backend runs the isolation checks through the real tool registry, so a hosted
backend plugin can run the same checks against its own provider.
process_registry.py's handoff handler moves to process_registry_handoff.py to
keep the facade under its size cap.
A read_file call made from inside an execute_code cell was answered with the
conversation's "unchanged since last read" stub when the same region had been
read before (by the model or earlier in the cell), so result["content"] raised
KeyError; a few more repeats hit the BLOCKED refusal. The stub exists to keep
duplicate text out of the model's context, and a cell's read never enters it.
Both cell dispatch paths (one-shot RPC and the session kernel) now mark their
tool calls as programmatic. Such a read always carries content, does not count
toward the consecutive-read/search loop guard, and is not remembered as shown
to the model, so the model's own later read still gets the text. It still
counts for the read-before-overwrite guard: a cell that reads then writes a
file works as before.
Fixes#82711Fixes#44843
Co-authored-by: Pluviobyte <94058511+Pluviobyte@users.noreply.github.com>
Co-authored-by: Reginald Jeeves <jeeves@og.ly>
Co-authored-by: Elisa Martinez Abad <elisam@nvidia.com>
LSP, the code kernel and the slash worker each had their own "release the group once nothing in
it is left" (a killpg(pgid, 0) probe; the kernel's version also waited for reaps). They are now
one helper, process_identity.release_process_group_once_empty(pgid, proc=, timeout=). It polls
the leader so a zombie leader does not keep the group alive, waits up to `timeout` for killed
members to be reaped by init, and keeps covering a group that still has a member. LSP's async
close path probes once (timeout=0), as before.
The slash worker used to probe exactly once right after SIGKILL. On a loaded macOS host (load
25+) init had not reaped the killed members yet, so a group that was about to be empty stayed
registered (test_close_stops_the_whole_group_then_releases_it, flaky). It now waits up to 1 s,
like the kernel did.
The kernel survivor test raced too: under load the cell child's `trap '' TERM` could land after
the teardown's SIGTERM, and the 5 s escalation could SIGKILL it. The child now signals once its
trap is installed, and the test turns escalation off (the escalation is not what it pins).
New tests/hermes_cli/test_process_identity_release_once_empty.py: an unreaped empty group is
released, a live member keeps it covered, a late exit is waited for, and Windows never releases.
Teeth: forcing the helper to always release, or to never release, turns 5 tests red in the 4
touched files. macOS: the 9 owned-child files, 78 tests, 3 runs in a row, 0 flaky.
Symptom: the POSIX death pipe (365e2835d4) only told the KERNEL its host had died. Every subprocess a
cell starts (a dev server, a `sleep`, a training job) shares the kernel's process group and never sees
that pipe, so a SIGKILLed / OOM-killed host left them running on init indefinitely. Measured on Linux
against origin/main 7770e397f3 (ck_probe: host spawns a kernel, the cell Popen()s `sleep 300`, host
gets kill -9, check at +10 s): kernel 0/3 alive, cell child 3/3 alive.
Change: _spawn starts the kernel through process_identity.spawn_owned(purpose="code-kernel"): it leads
its own group (as before, via start_new_session), that group goes to the per-process owner-death
supervisor, which killpg()s it the moment the host dies by any cause, and the kernel is recorded in
the spawn ledger. teardown() releases the group once it is empty (waiting up to 1 s for SIGTERMed
cell children to exit); a cell child that survives the teardown's SIGTERM keeps the group registered
until it exits. The kernel-only death pipe (runner watchdog thread, pipe plumbing,
HERMES_KERNEL_PARENT_DEATH_FD) is deleted: the supervisor kills the kernel too. Windows keeps its
SYNCHRONIZE-handle watchdog unchanged; atexit graceful shutdown, the idle reaper and the
stale-staging-dir sweep stay (they cover a live host and disk, not owner death).
Result: same probe, 3/3 runs: kernel 0 alive, cell child 0 alive. tools/code_kernel.py +25/-57.
New tests/tools/test_code_kernel_owned_group.py (kill -9 owner vs live control owner, graceful
release, surviving-child coverage): 3/3 green x10 runs, all 3 red on the pre-change spawn, each red
on its own mutation (no registration / no release / unconditional release). Family files on main
75 passed; on this branch 78 passed (75 + 3 new).
A script that calls hermes_tools.write_file/patch and never prints the
returned {"error": ...} got status=success with empty output, so the
model believed the write happened. In a cross-agent bench this cost 3 of
18 Opus runs 4-6 extra turns (write_file refused by the read-before-write
guard, then re-probing and re-emitting whole files). The result now
carries tool_errors for that cell, and the in-script write_file doc says
existing files must be read first.
The idle sweep lives inside _acquire_kernel, so it only fires when the next
kernel request arrives. A host that stays alive but stops executing anything
(a pids-exhausted container fail-closing every tool call) never acquires
again: idle kernels, their runners and thread pools survive indefinitely,
which is how four orphaned runners helped exhaust pids_limit=256 for hours
(#117169). A low-frequency daemon reaper — started on the first kernel
spawn, using the acquire-path criteria verbatim — retires idle kernels on
its own schedule, independent of tool traffic.
The same pass sweeps hermes_kernel_* staging dirs untouched for over a
week: a live host rmtrees each dir within one idle timeout of the kernel's
last use, so a week-old dir belongs to a host that died without cleanup
(SIGKILL / container restart). Younger dirs are left alone because a
concurrently running host's live kernel may own one; rmtree rejects
symlinks rather than following them.
Chrome puts its SingletonSocket under $TMPDIR and AF_UNIX paths cap at 104/108 bytes, so a
deep HERMES_HOME (profile homes, test homes) made the new scratch TMPDIR kill Chrome at
startup ("Socket path too long") — two browser test files went red on the branch and green
on main. hermes_constants.socket_safe_tmpdir() keeps the scratch root when it fits and falls
back to the OS root for sockets only; the browser env and the code kernel RPC socket use it.
check_no_tmp_literals walked git-ignored runner artifacts (test_durations.json) and failed on
whatever the last test run wrote; it now skips `git ls-files --others --ignored` paths.
run_tests_parallel created its per-file temp roots in the system temp dir and exported no
TMPDIR, so a full-suite run wrote gigabytes of fixtures to tmpfs (3,225 leftover roots, 9.9 GB,
were sitting in /tmp on the dev box). Roots now live under HERMES_HOME/cache/scratch/pytest and
the test process inherits TMPDIR=<root>, so the existing cleanup removes every temp file.
The seventeen remaining literals are container-side paths, AF_UNIX socket-path-limit
candidates on darwin, detection needles, guard regexes and guidance text that tells the
model to avoid /tmp. Each carries an inline `no-tmp: ok — <why>` so the reason lives
next to the line; the baseline keeps only a fenced tree listing where a marker would render.
A delegated child's execute_code kernel was keyed correctly
(<owner>:🧒:<session>) but counted against the process-wide
max_session_kernels LRU cap (default 4) like any other kernel. In a fan-out
wider than the cap every child's first cell spawned a kernel and evicted the
oldest sibling's, so the sibling's next cell started a fresh interpreter and
NameError'd on state its own previous cell had set — while the tool schema
promised "variables, imports, and loaded data survive across execute_code
calls". Finished children's kernels also squatted the cap for
kernel_idle_timeout (1800 s) after the child was gone. 48 NameErrors across 28
subagent lanes in the Sep 10-14 retrospective.
A live child's kernel (local and remote) is now pinned: exempt from LRU
eviction while the child runs, disposed by the delegation cleanup path
(shutdown_kernels_for_delegated_child) as soon as the child finishes. Top-level
sessions keep the existing cap and idle reaping unchanged.
_callback_api() now yields (getter, setter) pairs for every per-thread prompt
(approval, sudo, vault unlock); the kernel cell captured and restored the old
fixed 4-tuple. Iterate the table so a cell carries every callback and a future
addition needs no change here. Test recorder unpacks the new shape.
Also: perfectionist import order in ui-tui interfaces.ts (CI lint).
For each issue anchor present in BASE 63279301bc non-test .py and absent on HEAD, the BASE comment/docstring block was re-attached at the HEAD location of the code it explained (matched by the distinctive code line / enclosing def). Sentences already covered by an existing HEAD comment were deduped; the issue number always survives. Insert-only: no code lines changed.
Widens the Windows parent-death fix to the class: the kernel inherits
the read end of a pipe whose only write end lives in the host, so host
death by any means (SIGKILL, OOM, crash) is EOF and the kernel exits.
Stdin EOF alone only reaches the runner between cells, so a kernel
SIGKILLed mid-cell used to outlive its host indefinitely. The
integration test now runs on every platform and is trimmed to the
contract (kill host mid-cell, kernel gone), not the handle plumbing.
Session kernels: a kernel mid-spawn (proc=None) read as dead, so every
concurrent cell for one owner replaced the registry entry and the
winner's process leaked outside the registry (110 live kernels, 1.1 GB,
330 threads under one 4-capped process). Reap/evict also tore down
kernels with cells attached, rmtree-ing the staging dir under the
spawner. Kernels now track attached cells: only settled kernels are
reaped/evicted, a kernel dropped while busy is torn down by its last
cell, and in-cell registry pops never remove a replacement.
LSP: a directory holding __init__.py is a package, not a project root.
hermes_cli/setup.py matched the python marker list and gave every
worktree a second pyright rooted at hermes_cli/ (70 of 105 reaped
clients in one session, ~40 servers / 8.7 GB live).
* feat(tools): session-persistent kernels for execute_code (kernel_mode: session)
execute_code spawns a fresh Python process per call, so every multi-step
data task re-loads its inputs: a CSV parsed in call one is gone by call
two, and scripts route state through temp files to survive. Hermes
already rewards programmatic tool calling (execute_code-only turns
refund the iteration budget), which makes the missing half — state that
survives between calls — the bottleneck.
Add opt-in `code_execution.kernel_mode: session`: one persistent kernel
per (task, mode, interpreter, cwd, tool-set). Variables, imports, and
loaded data persist across calls; `reset=true` discards state on demand.
The default `per-call` keeps today's behavior byte-for-byte.
Safety posture is unchanged by design: the child env comes from the same
builder as the per-call path (extracted, not duplicated, so the secret
scrubbing / PYTHONPATH hygiene cannot drift), the RPC server is the same
`_rpc_server_loop` with the same token and a per-cell tool budget, and
output passes the same ANSI strip + secret redaction. A timed-out or
interrupted cell kills the whole kernel tree and the next call respawns
— a wedged kernel can never hang the agent. The kernel env is frozen at
spawn; the schema and config comment say so.
Wire protocol: NDJSON requests on the kernel's stdin; responses framed
on stdout behind a per-kernel random sentinel, with unframed bytes
(fd-level output from user-spawned subprocesses) attributed to the
serialized current cell. The generated RPC client reconnects once when
HERMES_RPC_PERSISTENT=1, because a kernel legitimately outlives the RPC
server's 300s idle window between cells.
Tested on macOS 15 (Apple Silicon), Python 3.11: 13 new tests in
tests/tools/test_code_kernel.py (persistence, reset, error-keeps-kernel,
timeout-kills-kernel, sys.exit ends kernel, subprocess fd passthrough,
schema surface, mode fallback) plus the existing
test_code_execution.py / test_code_execution_modes.py suites (81 passed).
* fix(tools): session kernels get a stable owner, bounded lifetime, and per-cell RPC authority
Addresses the blocking review on the session-kernel design: two
authority/lifecycle boundaries were wrong.
1. Ownership and bounded lifetime. The kernel key's first component is
now the conversation's approval session key (_resolve_owner), not the
per-turn task id run_agent mints per top-level invocation — so state
genuinely survives across user turns of one conversation, and delegated
subagent sessions isolate naturally under their own keys (the task id
remains only the last-resort owner for embeds/tests with no session
context). Lifetime is bounded on four edges: kernels are disposed at the
same session boundary that clears the owner's approval/yolo state
(tools.approval.clear_session -> shutdown_kernels_for_owner), reaped
after code_execution.kernel_idle_timeout seconds idle (default 1800,
swept on every entry), capped process-wide at
code_execution.max_session_kernels live children (default 4, LRU
evicted), and still torn down by reset/death/atexit as before. The
ownership + disposal + idle-reap + cap shape deliberately carries
forward the lifecycle invariants of the earlier session-persistent
implementation in #88637 by @z80dev.
2. Per-cell RPC authority. The serving thread no longer freezes the
spawning cell's context/callbacks for the kernel's life. Each cell
installs a CellAuthority — captured on the calling thread exactly as
propagate_context_to_thread would for a per-call RPC thread — before its
request is written, and retires it on every settle path; _rpc_server_loop
gains a dispatch hook the kernel uses to route each tool call through
the CURRENT cell's context, callbacks, and task id. A call arriving with
no active cell is refused. Interpreter state persists; RPC authority
does not.
Composition with the per-script static guard (see the config note): a
persistent namespace lets cell N+1 invoke objects cell N created, which
a single-cell static scan cannot see — the runtime RPC boundary
(allow-list by name, per-cell budget, per-cell authority) is the
operative cross-cell enforcement in this mode, and the adversarial
alias test pins exactly that.
Tests (9 new): state survives across turns of one conversation;
sessions isolate; clear_session disposes the owner's kernels (and the
next turn starts fresh); the live-kernel cap LRU-evicts with evicted
children proven dead; idle kernels are reaped; a later cell's RPC runs
under that cell's approval callback; a cross-cell alias dispatches under
the CURRENT cell's authority; a settled cell's authority refuses
dispatch; each cell installs a fresh authority. 22/22 kernel tests, 81
code-execution tests, ruff clean. The 7 test-order failures in the
tools/-k-approval selection reproduce identically on the clean branch
base (pre-existing pollution, not this change).
* fix(code-kernel): delegated children get their own kernels — child contexts inherit the parent approval key, so qualify the owner with the delegation session id (live-verified leak, both directions)
---------
Co-authored-by: Teknium <127238744+teknium1@users.noreply.github.com>