get_read_block_error is the path check plugins are told to call, but only
read_file consulted the device/proc table, so a plugin following the docs
could still read /proc/<pid>/environ (process secrets) or hang on /dev/zero.
The path-only table and is_blocked_device_path move into agent/file_safety;
get_read_block_error checks the literal and resolved path; read_file keeps
its symlink-hop walk and imports the table from there.
With a backend whose default directory is `~` and a sandbox that declares no
usable home, no in-sandbox anchor is known. A hosted relative path was then
joined to this process's working directory, and that host path was sent to
the sandbox and returned as `resolved_path`.
In a hosted scope the base directory is now never the process cwd: with no
absolute in-sandbox anchor, resolution fails and each file tool sends the
path as written, as patch headers already were. write_file, patch and
search_files do so through their existing fallbacks; read_file gains the
same one, in a small helper that keeps the device check ahead of resolution.
An absolute path is unaffected, and nothing changes outside a hosted scope.
Refs #146503
_expand_tilde used this host's profile home, so a hosted write_file or patch
of ~/x went to a host-HOME-shaped sandbox path while read_file sent '~/x'.
In a hosted scope ~ now expands to the home the caller's sandbox declared;
read and search use the same expansion, and in a V4A patch only a `~` header
is expanded. With no declared home, or for ~user, a `~` path is refused
before anything is sent. A `~` working directory recorded for the session
or set as a task override anchors relative paths under the declared home,
and with none declared it is not an anchor. With none declared a `~`
TERMINAL_CWD still falls back to the terminal config's own expansion, which
this change does not touch.
Refs #146503
browser_exec ran the model's Python in a host subprocess (a cloud browser
moves Chromium, not the interpreter), and it was not the only tool the
sandbox routing never reached. Tools with no route through the agent's
environment yet now fail closed in a hosted scope, before any setup, file or
process, with an error naming why (tools/hosted_tool_policy.py):
- by toolset, at ToolRegistry.dispatch: the browser tools, computer use and
desktop UI, desktop projects, image and video generation, text to speech,
skills, cron jobs, delegation, kanban, catalog and connection management,
onboarding, and every MCP server's tools (they come from the profile's
config and run for it);
- directly, on the paths the registry never sees: the browser_exec entry,
checkpoint take and restore, inline skill shell, @-references, the
workspace git probe in the system prompt, cron scripts, MCP stdio spawns,
media delivery by host path, connector file inputs, document extraction in
read_file, voice transcription and delegate_task's inline dispatch.
Routing each of these through the sandbox is follow-up work; refusing them
keeps the hosted guarantee that nothing tenant-supplied runs or is read here.
Local installs are unchanged (every check is a no-op with no hosted scope),
which a permanent test now pins: env maps and built-in backend constructor
arguments are byte-identical, unscoped and under the local scope, to the
same calls with the hosted machinery switched off.
The developer guide describes the hosted operation interface, what runs in
the sandbox, and what is refused.
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>
The content-search refusal stripped the pattern, so a search for a tab or
for spaces was refused where main runs it. It also keyed on the literal
"content" target, so an unknown or null target with no pattern still
returned every line. Refuse an empty pattern on every target but files.
Independent review found three calls that work on main and were refused:
vision_analyze and video_analyze without a question (the native-image
route loads the image as-is), react_to_message without an emoji (that
retracts the reaction) and search_files listing files without a pattern.
Those required keys are now self-checked. search_files itself refuses a
content search without a pattern, since an empty pattern matches every
line and returns the whole tree as "results".
A tool's own structured _warning is no longer overwritten by the
unknown-argument note.
A call such as search_files without `pattern` ran anyway and returned matches, and a
typo'd or invented argument was dropped with no signal, so the model assumed an option
had taken effect. One check now sits in front of every tool Hermes ships
(registry dispatch and the agent's inline executors; model_tools.py is untouched):
- a missing `required` argument is refused before the handler runs, naming the field
(with its allowed values when the schema enumerates them) and the valid parameters;
- an argument the schema does not declare still reaches the handler exactly as sent;
the result gains a `_warning` naming it. Nothing is stripped.
Slim redo of #142503. What differs from it, and why:
- scope is built-in tools only. MCP and plugin tools, and schemas that are open or
union-shaped at the root, pass through untouched: a third-party `properties` list is
not a promise about what the handler accepts.
- nothing is stripped, so handlers that read an undeclared key and execution middleware
that rewrites arguments keep main's contract.
- legacy call shapes and tool-owned guidance are declared by each tool at registration
(`compat_args`, `self_checked_args`) instead of a central table: skill_manage and memory
flat shapes, delegate_task's single-task shape, patch's V4A mode, terminal(code=...),
video_generate(video_url=...), and the handlers whose own missing-argument message says
more than a generic refusal can.
- the dynamic schema is only built when the registered one reports a finding.
Co-authored-by: Elisa Martinez Abad <elisam@nvidia.com>
Co-authored-by: James Nolan <jnolan@nvidia.com>
search_files, memory, manage_connections, execute_code, browser_exec,
skill_manage and terminal repeated the same rule in the tool description
and again in a parameter description (or only restated the JSON schema:
"default: 50" beside "default": 50). Every model call pays for both
copies. Each rule now appears once, on the parameter it governs where
there is one. Parameter names, types, enums, defaults and required lists
are unchanged; with descriptions stripped the seven schemas are identical
to main.
Measured on anthropic/claude-fable-5.2 (provider prompt tokens, one tool
per request): search_files 732 -> 557, memory 885 -> 767,
manage_connections 1,563 -> 1,333, execute_code 1,165 -> 1,085,
browser_exec 1,187 -> 1,145, skill_manage 1,340 -> 1,313, terminal
919 -> 895. All seven together: 8,077 -> 7,381 (-696 per call).
memory: the user/memory store meanings moved from the description to the
`target` parameter, so the single-store narrowing now rewrites only that
parameter. A disabled store is still never named in the schema (new test).
browser_exec keeps page_info() and fill_input() in the helper list: the
"work text-first" sentence that also names them is absent from the
native-vision and Lightpanda variants.
manage_connections keeps its two short opening sentences: the tool_search
catalog line is the first sentence and must not be clipped.
memory also keeps "Reusable procedures belong in a skill, not memory" at the
end of its SKIP list although the WHEN paragraph says the same: with the
sentence gone a weak model stored a procedure in memory in 1 of 9 runs (0 of
9 on main).
Prompt-surface snapshot re-rendered.
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.
Measured on origin/main with the default LSP config (enabled, document, wait_timeout 5.0), real
handle_function_call, warm servers:
- a clean .ts edit took 10.1s: the pre-write baseline wait and the post-write wait each ran to the
full 5.0s, because typescript-language-server publishes nothing when a file's diagnostics stay
empty and its first push after didOpen is a seed that never counts as fresh;
- wait_for_diagnostics re-sent textDocument/diagnostic in a tight loop on push-only servers
(~326k iterations per 15s of waiting on the LSP loop thread);
- a 16k-line .py edit took 2.9s (pyright's analysis time, paid inline, plus a baseline round trip);
- even with LSP off every write paid ~100ms for three bash spawns (probe, atomic write, sha256sum),
and patch ran the syntax lint twice.
Now:
- the write never waits on the language server. One coroutine per edit (agent/lsp/edit_check.py)
syncs the written file and waits for its verdict; only when that verdict has diagnostics does it
fetch (or reuse) the verdict on the pre-edit text the write already holds, so a clean edit costs
one round trip. The write waits for that verdict only while it stays under ~80ms; otherwise the
verdict is queued for the editing session (agent/lsp/deferred.py) and attached to its NEXT tool
result, or the next user turn, via the plugin live-notes channel: a new row, never a rewrite of an
earlier message, so the prompt cache is untouched.
- checks of one file are serialized and coalesced; a newer check inherits an older one's baseline,
so errors an earlier edit introduced are still reported unless a later edit fixed them.
- wait_for_diagnostics sends the pull once and stops pulling on servers that reject it.
- the local POSIX backend writes, probes and hashes in-process (tools/file_operations_native.py),
under the native-read gate (HERMES_NATIVE_FILE_READ=0 restores the shell path).
- patch reuses write_file's lint result instead of re-linting.
- gateway/run.py: fold spillover back into the housekeeping table with
max_age_hours=None (session retention window) instead of a separate
chore, so the file stays at its main line cap.
- referenced_spillover_names: catch sqlite3.Error/OSError, not Exception.
- _spillover_retention_hours: reviewed BLE001 waiver (any config failure
means the legacy 24h floor).
- _unlink_dead_spillover: log the swallowed exception with exc_info.
- read_file_tool: the expired-archive hint merges a dict, no new branch
(CC stays at main's cap).
(cherry picked from commit 69a498664176dd49506c8b7edff90b78f70daae2)
The last atom of #126351 named in triage: a read_file miss on a
persisted-tool-result path (cache/spillover/<name> or the sandbox
hermes-results/<name>) returned a generic "File not found", which a
model reads as a typo. It now keeps the not-found error and adds
expired=true plus a hint that the archive was pruned and that the
producing call may already have taken effect.
Co-authored-by: FroRaut <79215537+Froraut@users.noreply.github.com>
(cherry picked from commit 432d4e48625a3be6521c860a3f5af5ea067ed46d)
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.
A deployment reported that write_file -> read_file (full) -> patch ->
write_file refuses the last write with stale_write_blocked and "exists
but this task has not seen its full current content", in 50 of 50 trials.
No other writer took part. When the model does not reread before the turn
ends, the refusal surfaces as the "File-mutation verifier: N file edit(s)
FAILED" footer.
Mechanism. The write_file baseline is an exact file version: (st_dev,
st_ino, st_size, st_mtime_ns, st_ctime_ns, sha256)
(tools/file_tools_read_tracking.py _file_version, _mark_full_write_baseline,
_has_full_write_baseline). write_file_tool marks a fresh baseline from the
bytes it wrote. patch_tool only ran _note_edited and
_reset_patch_failures, so the task's own patch changed the version and
left the baseline it held stale. _stale_overwrite_blocker then treated the
task like an external writer.
Invariant: after a task's own successful patch, the task may replace the
file whole exactly when it held a current full baseline for the bytes the
patch read and the bytes the patch wrote are what is on disk.
Lineage. a8af57fcd2 added the guard. dddefaefae counted paged, extracted
and post-compaction reads. e636aedebf kept a baseline across narrower
rereads of unchanged bytes and bound it to the sha256. That is the change
that made this sequence refuse (its parent lets the write through). Own
patches are the missing case of e636aedebf's principle that unchanged
knowledge survives.
Shape:
- Under the per-path locks, before the patch reads, patch_tool records
the sha256 of each path whose baseline still matches disk
(_known_full_content_sha256).
- read_file_raw and patch_replace report the sha256 of the exact bytes
they read, BOM included. Each file write records (path, read sha256,
written sha256) in PatchResult._writes for replace, V4A Update and V4A
Add.
- _carry_full_write_baselines marks the baseline only when the read
sha256 equals the known one (or the patch created the file). The mark
goes through _mark_full_write_baseline with the written sha256 as
expected_sha256. A writer that lands before the patch reads leaves a read
sha256 the task never knew. One that lands after the patch writes fails
the expected-sha check. Neither case gets a baseline. Several operations
on one file in one V4A patch chain in order.
- A blind patch (no baseline, or a partial view) is noted per task in
blind_patches. While disk still holds exactly those bytes, the refusal
says "Your patch changed this file after a partial view. Read the
current file in full before a whole-file overwrite, or continue with
targeted patches." Sibling, external and never-read refusals keep their
wording.
Remote backends: the baseline logic already stats the host path. On a
sandbox backend (non-LocalEnvironment env, verified with the
remote-binary-guard transport double), read_file records no baseline,
and _stale_overwrite_blocker lets the write through because the host path
does not exist. The carry hashes the same host path, so it records
nothing there. Paths the backend rewrites (translated mounts) do not match
the resolved host path and are skipped. Behaviour on those backends is
byte-identical to before.
Hint contradiction: after three failed replace patches, option (3) said
"use write_file to replace the entire file", which is the call the guard
refuses after a patch. It now says "re-read the file in full, then use
write_file to replace it".
Out of scope: enforcing recovery from a stale_write_blocked refusal
before a turn ends. The stale_write_blocked receipt and the file-mutation
footer are unchanged.
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.
* 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.
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.
patch_tool rewrites every V4A header to the path _resolve_path_for_task
returns, and on a host backend that is Path.resolve(), which follows a
symlink in the last component. For Update/Add that is harmless: the shell
layer reads and writes the target through the link either way. Delete and
Move act on the directory entry, so "*** Delete File: config/local.yaml"
(a link to base.yaml) deleted base.yaml and left the link dangling, and
"*** Move File: current.txt -> previous.txt" renamed the link's target,
both reported as success.
Delete headers and both Move endpoints now resolve their parent directory
only (_resolve_entry_for_task), keeping the final component, so the link
is removed or renamed. The same paths are locked and reported in
files_modified. Update/Add headers are unchanged.
(cherry picked from commit 7b1fe43d30db6015155349b67ca814b340df0e18)
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)
Resolved toward the branch: PM provisions uv/python (main's install.ps1 uv-shim
salvage + its test and workflow steps dropped), the shim re-exec stays retired,
package.json carries no electron-builder block (afterExtract identity stamp wired
into electron-builder.config.cjs instead; after-pack.mjs keeps signing only),
Desktop workspace-deps helpers stay retired. Main's scratch-dir bootstrap
(export_scratch_tmp_env) is taken and re-run after profile resolution.
Three small gaps from the OMP comparison (#77367) that the existing tools
almost covered:
- read_file on .db/.sqlite/.sqlite3 was refused as binary. It now extracts a
schema overview (CREATE per table, row count, first 5 rows, indexes/views)
through the same document-extraction path as .docx/.xlsx, opened read-only
and immutable so a live database is never locked. A .db whose magic bytes are
not SQLite is refused with that reason. The Hermes read denylist now runs
before extraction so protected stores cannot be reached through an extractor.
- read_file reports conflict_blocks: N (plus a hint) when the served range has
balanced <<<<<<< / >>>>>>> marker lines, so the model resolves the conflict
instead of editing around it. A lone marker in prose is not counted.
- web_extract returned 824K chars of raw SQLite bytes as page "content" for a
.sqlite URL (live: Chinook_Sqlite.sqlite via the configured backend). Bodies
starting with an unambiguous file signature (SQLite, ZIP, gzip, xz, 7z, ELF,
Mach-O, PNG/JPEG/GIF/TIFF, FLAC/Ogg) become a typed error pointing at
terminal + read_file. Backends drop NUL bytes, so signatures are compared
NUL-stripped; two-letter signatures (BM, MZ, ID3) are excluded on purpose.
Sibling of the previous commit: read_file_tool returned the unchanged-stub
before _record_read, and only _record_read calls
mark_background_review_skill_read. A skill file the parent had already read
left the fork with a stub and a refused skill_manage write. Same rule as
skill_view: no dedup stub when is_background_review().
Also: is_background_review hoisted to module level in skills_tool (no cycle —
skill_provenance imports only contextvars), comment reworded to the two real
reasons, test renamed to the shipped design, fixture seeds a fresh read-mark
store so the mark cannot leak between tests.
The salvaged commit adds the `guardrail_refusal` marker to the read-dedup block
and exempts it in `classify_tool_failure`. That classifier is only the fallback:
the executor (`agent/tool_executor.py::_commit_tool_result`) passes
`failed=_detect_tool_failure(...)` from `agent/display.py` into
`after_call`, so on the real path the refusal was still counted and the
escalation to `repeated_exact_failure_block` still fired (live probe: block at
call 8 of an identical read after 5 refusals, on the salvaged head as on main).
- `agent/tool_result_classification.py`: `GUARDRAIL_REFUSAL_KEY` +
`is_guardrail_refusal()` so the marker has one definition and both
classifiers share the predicate.
- `agent/display.py::_detect_tool_failure`: exempt refusals (the live seam).
- `tools/file_tools.py`: the two sibling loop refusals -- the consecutive-read
BLOCK in `read_file_tool` and the repeated-search BLOCK in `search_tool` --
carry the same marker; they are emitted via `tool_error` too and escalated
the same way.
- Tests trimmed to two invariants covering all three refusals on both
classifiers, plus the negative (a genuine error still counts; a non-boolean
marker is ignored).
Approval-denied write blocks (`file_tools_write_guards`) deliberately keep
counting: a user's denial retried unchanged is exactly the loop the streak
exists to stop.
The read-dedup block in `_dedup_stub_or_block` returns its message through
`tool_error`, so the body carries `"error"` for the model's benefit. That is
exactly the substring `classify_tool_failure` keys on, so the guardrail counted
its own refusal as a failed call: refusing a repeated read raised the failure
streak that produces the next, harder refusal, and the resulting
`repeated_exact_failure_block` told the model N identical calls had failed when
none had.
Observed on a real session (55 patches, 73 reads, 13 searches, 14 terminals):
13 of the 14 results the classifier called failures were this block. One tool
genuinely failed -- a `gh` call with exit 8. The model was told to change
strategy over a count the harness had produced itself, and could not diagnose it
because the message did not describe anything that had happened.
The block now carries `guardrail_refusal`, and the classifier exempts a body
marked that way. The exemption is keyed on the marker rather than on wording, so
a body that genuinely failed still counts and the streak that stops a real loop
is unchanged.
Signed-off-by: rlaope <piyrw9754@gmail.com>
(cherry picked from commit b3b09822f3db5e70a181e7dd19725afe1b1583a7)
Reconcile plugin declarations and validation through PM's atomic generation publication; preserve external runtimes, target markers, and conflict refusal. Keep one source-update completion owner and port upstream lifecycle changes to the PM desktop/runtime paths.
The #112424 normalisation used `not isinstance(path, str) or not
path.strip()`, which also silently mapped a non-null wrong-typed path
(e.g. 5 or a list) to "." and searched the whole cwd instead of reporting
the bad argument — wider than the issue (blank/null) asked for. Restrict
the predicate to `path is None or (isinstance(path, str) and not
path.strip())` so any other type falls through to search_tool's existing
error path, exactly as on main.
Test: test_handler_preserves_nonblank_path now also covers 5 and ["src"];
those two cases fail on the previous commit (path became ".") and pass here.
The model can send `"path": null` as easily as `"path": ""`; on base a
None path reached search_tool and surfaced as an os.PathLike TypeError
instead of the documented current-directory default. Widen the blank-path
normalisation in _handle_search_files to any non-string and pin it in the
existing parametrized test.
Co-authored-by: joaomarcos <joaomarcosdias444@gmail.com>
read_file/search_files passed file_read=True, which folded into code_file=True and skipped
the ENV/JSON/YAML assignment passes, so an opaque prefix-less credential under a
credential-shaped key reached the model in cleartext from a secret-bearing file — the
file-read half of the #110228 gate (#110567).
Two defects on that path, both fixed here:
- The rendered line-number gutter ("5| ADS_API_TOKEN: ..." from read_file,
"6: ADS_API_TOKEN: ..." from grep -n / cat -n) defeated the line-anchored patterns,
so the real rendered read leaked exactly what the raw text masked. A gutter-free fixture
cannot see this, which is why the tool-level tests carry the real render shape.
- _is_secret_file_arg() could not see the RESOLVED Hermes home: the default home's basename
is an installation detail (".hermes" on POSIX, "hermes" under AppData/Local on Windows) and
a resolved path never spells $HERMES_HOME, so the managed Windows home's config.yaml was
classified as ordinary YAML on both the file-read and the terminal surface.
Changes:
- redact_sensitive_text(): secret_file= re-enables the assignment passes for content the
caller classified with _is_secret_file_arg, keeping code_file behaviour everywhere else.
It is authoritative over code_file, so a caller cannot be fail-open on the security flag
by setting both.
- _redact_assignments(): mask_nonreusable selects the non-reusable sentinel for file reads,
so the #35519 write-back hazard stays closed.
- _should_redact_assignment(): no longer re-masks an already-masked value, which was erasing
the vendor label the sentinel deliberately keeps.
- _is_secret_file_arg(): consult the resolved Hermes home for the config.yaml arm.
- _CFG_ANCHORED_RE / _YAML_ASSIGN_RE: tolerate a rendered line-number gutter.
- file_tools.py: classify the resolved path at all three file-read call sites.
Closes#110567
Claude Code v2.1.234 (Aug 17, 2026) hardened its pre-approval file
accesses to reject Windows NT-namespace (\??\) paths against the NTLM
credential-leak vector. Port the same guard into Hermes file safety:
- agent/file_safety.py: is_nt_namespace_path() / get_nt_namespace_error()
raw-string check (never resolves — resolving IS the leak trigger).
Wired as the first check in get_read_block_error() and the write
denial classifier.
- tools/file_tools.py: raw-string guard at read_file_tool entry and in
_check_sensitive_path (covers write_file_tool + patch_tool), before
the task-base join can anchor the prefix under a POSIX base dir.
- Blocks \??\, \\.\, \\?\UNC\, \\?\GLOBALROOT. Extended-length
local drive paths (\\?\C:\...) and plain UNC shares stay allowed.
- tests/agent/test_nt_namespace_guard.py: 10 blocked forms, 11 allowed
forms, no-resolve proof, tool-layer chokepoint coverage.
- docs: protected-paths table in user-guide/security.md
The stale-overwrite refusal made write_file permanently unusable for any
existing file it could not show in one read_file page: every >2000-line
(or >100K-char) page was recorded as partial, no full baseline ever
existed, and the refusal told the model to "re-read the whole file", which
the tool cannot do. Track the line ranges each task pages through per path
at one mtime; contiguous pages from line 1 to total_lines are a full read
(a new mtime between pages restarts the coverage). The same gap hit two
siblings: the extracted-document branch (.ipynb, text-authorable) returned
before any read bookkeeping, so an existing notebook could never be
overwritten; and reset_file_dedup dropped every baseline on compaction
while keeping read_timestamps, so every write after compaction was refused
even for files unchanged on disk. Baselines now survive compaction exactly
like the dedup mtime map does — only while the recorded mtime still matches.
Refusal texts no longer embed the pre-PR "Warning: … Consider re-reading"
copy inside "Refusing to overwrite", and every refusal names a recovery the
model can perform: read the remaining pages, or use patch.
Require an explicit full-file baseline before replacing existing host-visible files with write_file, and fail closed when that baseline is stale. This prevents stale conversation context from clobbering manual or external edits.\n\nRefs #65604
Under `gateway.multiplex_profiles` one gateway process serves every profile
under ~/.hermes/profiles/NAME/; each routed turn runs with a context-local
HERMES_HOME override while `os.environ` still holds the DEFAULT profile's
values. Anything evaluated once at import, or memoised in a single unkeyed
module slot, therefore freezes the LAUNCH profile's value and leaks it into
every other profile's turns. This lands the tools-side half of that class:
- tools/process_registry.py, tools/environments/{modal,singularity}.py:
`_checkpoint_path()` / `_snapshot_store()` resolve `get_hermes_home()` at
call time (same seam as `tools/skills_tool._skills_dir`, so the existing
`monkeypatch.setattr(CHECKPOINT_PATH)` test sites keep working). Completes
the checkpoint_manager / sticker_cache half cherry-picked from #56315.
- plugins/platforms/feishu/feishu_comment_rules.py: `_MtimeCache` is now
path-keyed (accepts a Path or a zero-arg resolver, one (mtime, data) slot
per resolved path) with `invalidate()`; `_rules_file()` / `_pairing_file()`
resolve the routed profile's files. Proposed in #63962.
- tools/tool_output_limits.py, tools/browser_tool.py, tools/browser_camofox.py:
the process-lifetime config caches are dicts keyed by `hermes_home_key()`;
the `_X_resolved` flags and the lifecycle reset keep their shape.
tools/file_tools.py drops its private `file_read_max_chars` memo and reads
the already mtime+path-cached `load_config_readonly()`.
- hermes_time.py: `get_timezone_name()`; when `is_multiplex_active()` the
env `HERMES_TIMEZONE` (bridged from the default profile's config at gateway
startup) is ignored in favour of the routed profile's config.yaml. Both
sandbox TZ sites (code_execution_env/_tool) now use it.
- tools/cronjob_tools.py, tools/tts_tool.py, tools/skill_manager_tool.py:
the static schema text is profile-neutral and `dynamic_schema_overrides=`
rebuilds the `display_hermes_home()` / create-dir hint per
`get_definitions()`, so a routed profile's model sees its own paths.
Refs #95685.
Co-authored-by: Nathan Shan <nathanielcrush51@gmail.com>
(cherry picked from commit 6d3fc6b07b3155c6196b1fd61a829283f1d7855c)
When results were truncated, search_files appended the pagination hint
as plain text after the serialized payload ("{...}\n\n[Hint: ...]"),
so the tool result was no longer parseable JSON — downstream tool-message
handling on providers strict about tool-content formatting could reject
or mishandle it, contributing to 400 upstream errors in sessions with
truncated search output (#90322).
Move the hint into the payload as a structured _hint field, matching the
existing _omitted/_warning side-channel convention in the same function.
The model-facing guidance (explicit next offset) is unchanged.
Fixes#90322
#76996 raised DEFAULT_READ_LIMIT, the read_file_tool signature and the schema
default from 500 to 2000, but the registry dispatch handler `_handle_read_file`
kept its own literal `args.get("limit", 500)`. Since models omit `limit` on most
reads, every dispatched read still stopped at 500 lines with `truncated: true`,
so the default flip never reached production traffic.
All three sites now read the single DEFAULT_READ_LIMIT constant, so the schema,
the Python default and the dispatch fallback cannot drift again.
Live probe (registry.dispatch on a 1500-line file, no limit): before 501 lines /
truncated=true; after 1501 lines / truncated=false.
Independent review: the hint read the HOST path even for remote/sandbox
backends (a different file), blocked forever on a host FIFO while holding
the write lock, and used SequenceMatcher, which is quadratic on repeated
lines (a 460 KB same-line file took ~22 s). It now reads the old content via
the task's file ops read_file_raw (regular files only, correct backend),
skips files above 400 K chars, and compares line multisets (Counter
intersection, linear).
Reviewer's own probe on this head: 460 KB repeated-line file 22.3 s -> 0.0 s
(skipped), 230 KB 46 ms, remote backend gets no host-derived hint, FIFO write
returns at once.
_create_terminal_env_for_file_ops tested the static _CONTAINER_BACKENDS set while the
terminal tool's sibling sites already go through _is_container_backend(), which also
honours plugin backends declaring is_container. A host cwd override on such a plugin
backend therefore reached the sandbox as its workdir from the file-tools path only.
Salvaged from #101389 by @RelaxJonh.
In the 1,393-agent refactor run write_file carried 92.8M chars of content
(23.2M output tokens, ~$580, 20% of all output tokens). 661 of those calls
were read -> whole-file rewrite of an existing file >20k chars (24.9M
chars, ~$155): 130k-char agent/model_metadata.py, 109k
model_setup_flows.py, 107k google_chat/adapter.py, re-sent in full to
change a few lines. Meanwhile patch succeeded 4,602/4,617 (99.7%) at 1.3k
chars per call. The tool result is the only place the model reads, so the
cost signal goes there.
When an overwrite targets an existing file and both old and new content
are >=20k chars, write_file diffs them by line (difflib, autojunk off)
and, if >=80% of lines are unchanged, adds a `hint` naming the unchanged
count, the changed count, the size, and "use patch". The write itself is
unchanged and still happens; new files, small files and genuine rewrites
get no hint. 300 ms on the 119k-char model_metadata.py.
Tests (2): a 40k-char file with 2 lines changed gets the hint and is
written; a new file, a small file and a wholly rewritten file get none.