Why: for an old WebSocket client that never advertised server→client requests,
send_async already failed fast (on_result(None)) but _emit_approval_request ignored
it, so the approval wait — owned by tools.approval's queue, not server_requests —
still idled for the whole approvals.timeout (300s) with no prompt anywhere. The
same held for a -32601 error frame. on_result(None) now withdraws the queue entry
(withdraw_gateway_approval: cancelled cause, never a user deny) so
_await_gateway_decision returns at once; the agent sees a withdrawn prompt.
resolve_gateway_approval committed entry.result/reason/event.set() AFTER
releasing _lock, so _drop_entry (which reads result and leaves the queue under
the lock) could still pop-and-lose a choice the client was acked for. Every
committer (resolve, clear_session, unregister_gateway_notify) now commits inside
the same critical section that pops the entry, which is what _drop_entry's
docstring promised.
_drop_entry mapped a withdrawn wait to settle("set") — the raw poll-state token
went out as the request.cancel reason. It is now session_closed, and a choice
from another surface is resolved (both RequestCancelReason values).
Tests: restore test_server_request_error_response_fails_fast (an error frame
settles send() to None promptly); the approval fail-fast probe from the review
(silent WS peer, timeout 3 -> was 3.2s, now immediate); a lock-instrumented
resolve test; a settle-reason test. The test_protocol `server` fixture imports
server_requests before its sys.modules patch window so the module server.py binds
its sinks on is the one tests import — the PR's fail-fast test only passed in a
full-file run before (order dependency).
Part of #112548
Item 2 of #112548: a Desktop/dashboard build that predates server→client
requests has no response path, so every clarify/approval/sudo/secret/vault/
connection/bridge request sat for the full deadline (clarify: 300s). Only the
tour probed. Clients now advertise once per connection
(`client.capabilities {server_requests: true}`, sent by the shared TypeScript
channel on `gateway.ready`); `send()` / `send_async()` return the
error-response shape (None) at once when every WebSocket peer of the session
is a build that never advertised. Sessions with no client attached still wait
so the reconnect replay (`open_requests`) keeps working; the stdio TUI ships
with the backend and is not gated. The advertisement is dropped on disconnect.
Reviewer minors from #113227:
- tools/approval_gateway_wait.py: the verdict is the choice committed under
the approval lock while leaving the queue, so an /approve that lands after
the deadline check but before the entry is dropped is an answer, not a
timeout (the client was already acked "ok").
- tests/tui_gateway/test_protocol.py: the error-fails-fast test that only
restated pre-existing behaviour is replaced by the two capability
invariants (never advertised → fails fast; advertised → frame written,
waits, forgotten on disconnect).
- server_requests.send try/finally around event.wait already landed on main
(4371ed34a9); nothing to change.
Docs: programmatic-integration.md (advertise once per connection; method
list), tui_gateway/AGENTS.md; contracts regenerated.
repeat_refusal checked the counter and record_embed incremented it in separate
lock sections, so a concurrent tool batch on the same image (the incident issued
4 at once) all passed a check taken before any of them recorded and the cap of 3
let 6 embeds through. Reserve the slot inside the check's lock section and
release it when the embed then fails.
A delegate_task child asked to transcribe five screenshots called vision_analyze 158
times on those files (full loads alternating with region crops) until its provider
quota ran out; every native load bakes the image into history and is re-sent on each
later API call, and nothing refused the repeat (#112095).
tools/vision_tools_history_budget.py now keeps a per-(session id, resolved source)
embed counter. Region crops share their file's key. When the cap is reached
_vision_analyze_native returns a tool error that says the image has already been loaded
N times and to answer from what is visible or ask the user, instead of another embed.
Only successful embeds count, so a failed read never eats the budget.
Default: `vision.max_calls_per_image` unset caps only delegated subagents
(agent.delegation_context.is_delegated_child_process_context) at 3 — they run
unattended and CLI /steer targets the parent — while the main agent stays unlimited;
an explicit value applies everywhere and 0 means unlimited.
Co-authored-by: Evi Nova <66773372+Tranquil-Flow@users.noreply.github.com>
Co-authored-by: gumclaw <gumclaw@gumroad.com>
The native vision_analyze fast path (and the browser screenshot twins) downscaled every
embed to a fixed _EMBED_TARGET_BYTES = 256 KB. That is fine for photos but turns a
1080x2340 phone screenshot of a table into 540x1170, which the model then reads as
"unreadable" and re-requests (#112095).
The budget is now `vision.embed_target_bytes` in config.yaml (default unchanged: 256 KB,
clamped to 64 KiB..4 MiB so one setting cannot make every later request a multi-megabyte
resend), resolved in the new topical sibling tools/vision_tools_history_budget.py and read
by vision_analyze, browser_vision and browser_exec screenshots alike.
Ported from #112947 by @MohamadKanso (resolver + clamp), relocated out of the facade.
The live pass on a stock home counted 13 new WARNINGs per process: every
unconfigured core-gated tool (browser, image_gen, HA) warned on its first
probe. The actionable case is a core tool that was available earlier in
this process and then got dropped; never-configured stays INFO.
Issue #112649 atom 4: a core (`_HERMES_CORE_TOOLS`) tool whose check_fn returns
False leaves neither the schema nor the tool_search catalog (it is not
deferrable), so the model's "no such tool" is accurate and nothing in the log
points at the probe. ae5666f7fc made the False verdict INFO for optional,
unconfigured toolsets — that stays; the core-tool drop is now a WARNING that
names the dropped tool(s), once per probe per process (the 30 s TTL re-probe
would otherwise re-warn every turn), reset by invalidate_check_fn_cache().
Review minor: `catalog_provider: deepsek` was accepted silently and the typo
leaked into ModelInfo.provider_id. An alias that is neither a Hermes provider
id nor a models.dev id (loaded catalog, no network) now warns once, mirroring
the unknown-key warning, and the row keeps its own slug.
tests/tools/test_terminal_yield_to_background.py went red after the parent-first
teardown (f11499fdb3a): kill_process() returned {'status': 'error'} instead of
'killed' for a live backgrounded `bash -c 'echo started; sleep 60; echo done'`.
Root cause is the test harness, not the registry. _terminate_host_pid() now
SIGTERMs the shell before its descendants; a non-interactive bash dies at once
and `sleep 60` is reparented to init before the registry reaps it from the
descendant snapshot. tests/conftest.py's live-system guard allowlists a PID by
walking its parent chain up to the test process, so the reparented orphan looks
foreign and the guard raises RuntimeError inside psutil.Process.terminate().
That is not a psutil/OSError, so `suppress(gone)` lets it escape and
kill_process() wraps it as 'error'. Outside pytest the same path returns
'killed' and the orphan is gone (verified with a standalone probe).
Opt the test into real signal delivery with the established
@pytest.mark.live_system_guard_bypass (it already spawns and kills a real
process) and tighten it: capture the shell's descendants before the kill and
assert none survives, so the anti-orphan snapshot cleanup is covered end to end
instead of being hidden behind the harness. Assertions are unchanged otherwise.
Adds the real-process invariant behind the parent-first teardown salvaged from
#111603 (#111598): a bash supervisor that reaps its own child on SIGTERM must
receive the only SIGTERM and exit 0, with the child never signalled by the
registry. Red on origin/main (the child logged a registry TERM before the parent
and the parent's own kill found no such process); green on the salvaged head.
Documents the teardown order in tools/AGENTS.md, including why scope teardown
(_stop_systemd_unit) never precedes the PID signal for a live parent — the
issue's cgroup-split concern (Electron migrating only the browser PID into its
own scope) cannot make the registry stop the scope first.
The reconnecting exemption keyed only on `_ever_connected`, so a server that
connected once and then parked on a PERMANENT error (revoked credentials,
endpoint gone: `_park_and_rearm('from parked state (permanent error)')`) looked
identical to a router-reboot park. Its self-probe fails the same way every
interval, so the job ran tool-less on every tick forever with only a gateway
WARNING and never received the one-shot blocked_config alert it used to get.
Record the revival reason `_park` was given on MCPServerTask (`_park_reason`,
cleared when a session proves healthy) and have `mcp_server_reconnecting`
return False for a permanent-error park, restoring the block and its alert.
Transient parks (network blip, rapid-drop budget exhausted) still return True.
Also dedupe the exemption's WARNING per job+server for the length of one
outage, like the one-shot blocked_config alert, instead of logging every tick;
the entry drops once the server resolves tools again so the next outage warns.
The no-keepalive proof branch ran on ANY timeout wake. With idle_timeout_seconds=60 the wait is min(180, 60); an overlapping RPC hides the recycle deadline so _recycle_if_due() is False and the session was marked proven after 60 s, clearing the #62212 rapid-drop budget early. Fix a proof_at deadline before the loop and gate the branch on it; the unproven timeout is the remaining distance to proof_at. Tests: the stdio test now shows the first (idle-limit) wake does not prove; the interval test covers an explicit keepalive_interval on stdio.
WHAT: drop the idle-vs-lifetime parametrize on
`test_stdio_recycle_wakes_after_active_rpc`, keeping the idle case, and drop
its `_recycled_reason == reason` assertion.
WHY: both parameters exercised the same new invariant (releasing the RPC lock
wakes the lifecycle loop so the now-visible deadline recycles the server); the
reason assertion pinned pre-existing `_stdio_recycle_reason` behaviour that is
not this stack's concern. The stack now adds exactly two test functions.
After the stdio keepalive default became None, the lifecycle loop's
`if keepalive_interval is None: continue` skipped the only idle path to
`_mark_session_proven()`. `_session_proven` is otherwise set only on a
tool-call success or a suspect health-check pass, and each new session
resets it, so an idle default-config stdio server never became proven:
every later child death/reconnect charged the rapid-drop budget that a
180 s idle survival used to clear (#62212 regression).
While the session is unproven, keep the `asyncio.wait` timeout at
`_DEFAULT_KEEPALIVE_INTERVAL` for stdio too; when it fires with the child
still alive, mark the session proven without pinging. Once proven the
stdio timeout returns to None, so a healthy idle pipe is never probed.
Shutdown/reconnect precedence and the rpc_idle waiter are untouched.
Test: `_captured_interval` now runs two lifecycle cycles (first times
out, second shuts down) through a shared helper so the stdio test asserts
timeouts [180, None], zero pings and `_session_proven` set, instead of
copy-pasting the fake `asyncio.wait`. Docstring/comment updated to the
new rule.
The test trim dropped the headline case: text written over an EXISTING .db. Sidecar paths return at is_sqlite_sidecar before the overwrite branch, so a mutant that drops has_binary_extension from the overwrite condition survived every remaining test. Add a third parametrize case that targets the held-open WAL database file itself and asserts the binary refusal with bytes unchanged.
Same commit: the _check_binary_document_write docstring now names SQLite sidecars (always) and every BINARY_EXTENSIONS suffix (on overwrite), and the suffix is computed once at the top instead of three times.
_make_wal_db claimed sqlite keeps the -wal until checkpoint, but SQLite
deletes -wal/-shm on last-connection close, so the fake-bytes fallback was
what actually ran. Make the fixture a context manager that holds the
connection open across the tool call so the sidecar is a real WAL, and drop
the PRAGMA integrity_check assertion (SQLite ignores a garbage WAL, so it
passed either way); keep the byte-identity check.
In the patch test assert "binary" in the error so the no-baseline guard
cannot mask a regression in sidecar detection.
The refactor that moved sidecar detection into binary_extensions dropped the
contributor's unconditional refusal for the db family and made every binary
extension a plain overwrite guard. That is right for the MAIN .db/.sqlite
(text fixtures named *.db exist), but a -wal/-shm/-journal path is never a
legitimate text target: a checkpointed database has no sidecar on disk, so
write_file("kanban.db-wal", text) silently dropped a garbage WAL next to a
live database.
Add is_sqlite_sidecar(path) and refuse such paths in
_check_binary_document_write regardless of is_file(). Scope the marker
stripping in _has_extension_in to SQLite suffixes so report.docx-wal no
longer counts as an opaque document. Hoist the duplicated is_pdf_path call.
Parametrize the write_file WAL test over sidecar existing/absent.
Any error would also be produced by the no-baseline overwrite guard on
main, so the test could not detect a regression of the sidecar
detection. Asserting the binary-file refusal makes it fail when
binary_extensions stops recognising .db-wal.
Move the .db-wal/-shm/-journal detection from a write-guard-local regex
into tools/binary_extensions._has_extension_in so has_binary_extension
(read guard AND write guard) agree: a sidecar counts as its database's
extension. read_file now refuses sidecars instead of returning lossy
text, which also gives write_file the no-baseline overwrite refusal.
Behaviour change vs the contributor's commit: creating a NEW .db /
.sqlite file via write_file stays allowed (main allows it and text
fixtures named *.db exist) — only overwriting an existing binary is
refused. The generic has_binary_extension overwrite branch is kept and
merged with the PDF branch because patch has no full-read baseline
check: on main, patch on an existing .db with a matching old_string
rewrites the header in place.
Tests folded into the existing guard test classes (one write_file, one
patch refusal on a real WAL sidecar); the PR's 12-test file and its
private-regex assertions are dropped.
The text tools' read->modify->write round-trip re-encodes binary bytes
lossily: the terminal transport decodes stdout with errors=replace, so
a patch on a SQLite database reads mojibake and writes it back, silently
destroying the file (observed in the wild: a kanban board DB lost 550k
bytes / 26 days of history this way on 2026-09-15).
read_file already refuses to display binary files (extension + byte
sniffing), but write_file/patch had no write-side equivalent, and
patch_replace reads via plain cat so the read-side guard never fires
for it.
Guard rules (extends _check_binary_document_write, the existing
binary-document write guard):
- .db/.sqlite/.sqlite3 and their -wal/-shm/-journal sidecars: ALWAYS
refused (even new-file creation) — plain text can never be a valid
database, mirroring the opaque-document rule. The sidecars need a
basename regex because os.path.splitext('x.db-wal') yields '.db-wal',
which is not in BINARY_EXTENSIONS.
- Other BINARY_EXTENSIONS (.png, .zip, ...): refused when OVERWRITING an
existing file, mirroring the existing .pdf-overwrite rule — the model
can only have read mojibake, so writing back destroys it. Creating a
NEW file with such an extension stays allowed.
Tests: new test_binary_db_write_guard.py covers the regex (main names,
sidecars, non-db names), the guard function, and the write_file/patch
tool paths against real SQLite files (integrity_check still ok, bytes
untouched). 29 new+existing guard tests pass; file-tools/patch suites
green (196 tests).
The per-action schema made the delete branch `additionalProperties: false`
with no `absorbed_into`, so a schema-validating or grammar-constrained
backend could no longer emit the curator's consolidation delete and
`_curator_consolidation_delete_guard` fail-closed every consolidation.
Advertise `absorbed_into` on the delete branch and cover the batch path
that forwards it to the guard.
Also fold the two remaining patch shape checks (missing new_string,
content mixed with old_string/new_string) into `_op_shape_error`, so a
batch rejects them before applying any sibling instead of creating op[0]
and rolling it back. Drop the stale `edit` vocabulary from skills.md:440
and the curator prompt, and move the schema-diet test helpers above the
`__main__` guard.
The operations[] item schema was one flat object with four coexisting text
slots (content / new_string / file_content / file_path). A 27B local model
that had just used write_file's file_content kept emitting it on create and
patch ops; the call validated against the advertised schema, the handler
failed on "content is required", and the whole batch rolled back — eight
identical retries until the tool-loop guardrail tripped (#112677).
- items is now an anyOf of self-contained per-action op objects (create,
patch targeted, patch full-rewrite, write_file, remove_file, delete), each
with additionalProperties: false. The wire shape of a correct call is
unchanged (still a flat op with name/action/...), so transcripts, staging
and replay are untouched; grammar-constrained backends can no longer emit
another action's slot, and schema-validating providers reject it up front.
Nested (non-top-level) anyOf survives every sanitizer (schema_sanitizer,
Gemini legacy translator). Cost: parameters JSON 1352 -> 2414 bytes.
- _validate_batch_ops runs the per-op argument-shape check (_op_shape_error)
before any op is applied, so a misfiled op[1] no longer applies op[0] and
then rolls the batch back; the error carries the same misplaced-key hint.
- The hint is attached to argument-shape misses only: a patch whose real
problem is an unmatched old_string is no longer told to "move that text to
'content' (full rewrite)", the escape the patch error itself warns against.
- Shape tables (_REQUIRED_ARGS, text-slot maps, _misplaced_text_hint,
_op_shape_error) move out of the facade into skill_manager_batch.py, the
op-validation sibling; _patch_skill shares the old_string guidance text.
- Docs: skills.md Actions table states the one-slot-per-action contract.
The #112568 coverage exercised _cached_redirect and get_client_info in
isolation; the issue promised a flow-level case. This drives the login
path's actual sequence -- _configure_callback_port(cfg, storage) then the
SDK's storage.get_client_info() -- with the issue's exact bad-port payload
and a non-dict client.json, asserting a freshly parked ephemeral port and
"no registration", so a regression on either step fails the caller path,
not just the private helper. Red before f8f89b20d2 (both cases) and
before e166791f9f (non-dict case); green on main.
Closes the remaining atom of #112568.
A bare `python -c` resolves `tools` through the venv's editable install (the
primary clone), not the worktree pytest runs in, so the regression guard could
silently test a different tree. Pass cwd + PYTHONPATH like
tests/tools/test_async_delegation.py does.
_command_detection_variants yielded one FULL-LENGTH variant per quoted or
escaped command word. A heredoc body of quoted lines ("key": "value", …) is
hundreds of quoted command words, so both detection passes scanned
O(words * len) characters: on a 16 KB / 460-line command the hardline pass
alone took 7.8 s and the dangerous pass 15 s even with the launchctl lookahead
anchored (33 KB: 36 s hardline), all while holding the GIL on the gateway loop.
Build a single variant with every command word deobfuscated instead. The
obfuscation catch ($(echo rm), r''m, ${0/x/r}m …) is unchanged — the same
deobfuscated words appear, in one string — and the variant count on the
issue's input drops from 923 to 4 (36 s -> 0.26 s hardline, verdict
unchanged). detect_hardline_command needs no bound and keeps its YOLO
semantics: a benign heredoc is neither blocked nor prompted.
Root cause identified in #113943 by @Tranquil-Flow (variant explosion as the
second compounding factor); its cumulative-work budget is superseded by
removing the explosion.
Co-authored-by: Tranquil-Flow <66773372+Tranquil-Flow@users.noreply.github.com>
Drop the `sys.platform = "darwin"` fake (this file's own convention is
`@pytest.mark.macos_only` for dispatch) and exercise `_macos_osascript`
directly, which is where the furl gate now lives. Parametrize the
has-image contract over an image and a non-image Finder copy so the
extension gate — the fix's false-positive risk — is bound by a test.
The compressor pass and the Anthropic wire pass each carried their own copy of the
limit/batch/floor constants (under different names) and of the retire-count loop.
Retuning one alone would make the wire pass re-evict on a second frontier after the
compressor pass — the exact prefix-rewrite class #113517 fixes.
- agent/image_eviction_policy.py: stdlib-only leaf holding the constants and
outbound_image_retire_count(); the wire converter stays a leaf (no compaction import).
- evict_stale_outbound_tool_images loses `keep_newest`: no caller passed it, and its
default was the COMPACTION window constant the comments say the send path must not use.
- _retire_stale_tool_result_images (compaction) back to its main body; behaviour was
unchanged, so the rewrite was churn.
- One `_tool_result_parts` unwrap instead of three copies; one `_image_payload` walk
per message instead of two.
- Wire pass counts blocks via `_block_type` (non-dict inner blocks no longer raise).
Tests import the constants from the policy module; the two "stops at the floor" tests
assert the invariant (newest floor survives, request under the limit) instead of the
exact frontier. test_user_uploads_are_not_evicted now builds a request that actually
trips eviction — at 6 blocks it never fired and proved nothing.
Both eviction passes retire the oldest image-bearing tool results in whole
batches (8) and let the floor shelter a breach only when reserved uploads alone
exceed the ceiling. When uploads fill most of the ceiling without exceeding it,
the first batch step overshoots past the newest frames: fifteen uploads plus six
one-frame tool results retired all six (the model blind on the frame it had just
asked for) although keeping the newest three already clears the 20-block limit.
The batch step is now cut back to `total - floor` when it would cross the floor
and keeping the floor fits; a floor that does not fit (one 25-block tool_result,
byte pressure) still retires past it, and uploads alone over the ceiling still
shelter the floor. Pure-screenshot sessions are unchanged: same batch-aligned
frontier at 21/29/37 images.
Review-fix on #113519 (found while checking @ehz0ah's mixed-session boundary on
the sibling PR #113619).
267d42b3 made the compressor pass shelter the keep-newest floor only when
retiring every tool image still cannot bring the request inside the ceiling.
The Anthropic wire pass (_evict_old_screenshots) kept the unconditional
`len(carriers) - _MAX_KEEP_SCREENSHOTS` floor, so a single tool_result
carrying 25 image blocks retired nothing there. The compressor pass masks it
on the main loop, but auxiliary_wire.py reaches convert_messages_to_anthropic
without that pass, so the wire pass has to hold the invariant on its own.
Mirror the rule: when reserved uploads alone fit the ceiling the breach is
fixable and every carrier is retireable; only reserved uploads over the
ceiling keep the floor. One invariant test, red on 267d42b3.
Parallel tool calls land as sibling tool_result blocks inside one user
message, oldest first. The outer walk is newest-first but the inner walk
was forward, so a batch boundary that fell inside a message retired that
message's NEWEST frames instead of its oldest (21 siblings in one message:
survivors were t0..t12, the frames the model was just asked about were
the ones removed). Reverse the inner walk so the carrier list honours the
newest-first contract the batch tail relies on.
Same defect and fix as #103217 (credit @Maero47).
Review fix on top of the limit-triggered eviction. Both send-path stages ran
statelessly on a fresh clone every request, and each retired a FIXED single
batch (`min(batch, count - keep)`) once over the limit. That caps total
eviction at 8 per stage forever: once a session passes 20 + 8 (+ 8 from the
adapter) images, the outbound request grows unbounded again (24 image blocks
at 40 vision calls, 44 at 60 in the issue's own replay), so the documented
20-image threshold and the 24 MB byte budget were not enforced above the
first window. The PR's 40/60-row "3 collapses" result was this saturation,
not a held frontier under the limit.
Retire `ceil(overshoot / batch) * batch` instead, extending by whole batches
while the surviving payload still exceeds the byte budget. The frontier is
still a step function of the image count (one move per batch), and the
request now stays at or below the limit at every size:
images collapses max outbound images (PR head -> fixed)
40 3 -> 4 24 -> 20
60 3 -> 6 44 -> 20
2 MB x 30 3 -> 4 40 MB -> 22 MB
Both frontier tests now span three batch windows and assert the outbound
count never exceeds the limit; both are red on the previous head.
Both send-path image evictions retired the oldest payload as soon as more than
three images were present. Retiring an image edits a message the provider has
already cached, and Anthropic matches its prompt cache on an exact byte prefix,
so each retirement re-wrote the entire conversation. Because the window was a
count, one more message retired on every new image and nearly every turn became
a full-prefix miss.
Observed on a real 104-request session: requests reported cache_read=16,076 --
system prompt plus tool schemas and nothing else -- with cache_write up to
127,720, against a steady-state read of ~145,000. Those requests produced 62
percent of the session's entire cache-write volume.
Trigger eviction on the API's own per-request image and byte limits instead, and
retire a batch when it fires. Under the limit nothing is rewritten and the
request is append-only, so the cached prefix survives; over it, the cost is one
slower turn per batch rather than one per image. This matches the documented
behaviour of the reference Anthropic client.
Simulated across session sizes, prefix collapses fall from 3/8/18/38/58 to
1/1/1/3/3 at 5/10/20/40/60 vision calls.
Compaction keeps the count-based window: it commits its rewrite into the
canonical transcript once and has no prefix to preserve.
Folds the backend half of #113396 (#89720) into this branch so there is ONE
friendly-name resolver: `_display_name` reads the Bot Mode title, then the
profile.yaml `display_name` written by `hermes profile rename` (the Desktop's
botFriendlyNames order), then the @handle — so the renamed primary signs
`Maia (@hermes)` instead of `hermes (@hermes)`. Reaching it by `maia` /
`@maia` already works through `_resolve_local_name`, which stays the single
resolver (fail-closed on ambiguity, punctuated names accepted).
`local_alias_map` docstring now states what the code does: an exact folder
id wins by design; a friendly name colliding with another folder id never
steals it, and ambiguity is only between friendly names.
Docs: the Direct-messages bullet lists the accepted target forms (profile
name, friendly name, Desktop @-slug) and the fail-closed ambiguity rule.
Review follow-up for #113410 / #113396.
message_agent keyed local targets on the profile FOLDER id only, while the Desktop
autocompletes the bot's friendly name (profile.yaml display_name, or the Bot Mode
title) as its @-slug. "@scribe" for folder `writer`, or "Dr. Foo" for folder `foo`,
came back "No teammate named …" (a punctuated name was even "Invalid target"), and
the model went hunting for the teammate under ~/.hermes/profiles/ instead.
- tools/bot_mode_probe.py: alias_forms() mirrors the Desktop's mentionNameForms
(slug + collapsed, reserved tokens dropped); local_alias_map() builds
form → {folder ids} from every local profile's display_name / title.
- tools/bot_mode_dm.py::_resolve_local_name: exact folder id first, then a unique
alias; two bots sharing a friendly name fail closed (never the one that sorts
first). The handle-shape check no longer rejects a friendly name that resolves.
- The protocol roster line leads with a display_name that differs from the folder
id and title, so an untagged "talk to Scribe" maps to `@writer` from the prompt.
Closes#100671
ensure_message_agent_tool() returned True on the schema-present branch without
re-adding message_agent to agent.valid_tool_names. A long-lived Bot Chat whose
tool surface was rebuilt (compaction / MCP refresh republishes the allowlist from
the registry snapshot, which never contains the injected tool) then advertised
message_agent while the executor rejected every call, and the model fell back to
hermes -p shellouts that time out. Success now means both halves hold.
Re-applied onto the current any()-shaped gate; semantic change and test are the
contributor's (#96109).
Closes#96105
A stray profiles/default/ directory shadowed the reserved root-home entry when
the roster was collapsed into a dict (last-key-wins), sending bot-mode DMs to a
lifeless profiles/default/state.db. Skip the reserved name in the scan, matching
the container_boot precedent.
Fixes#108564
test_eviction_skips_kernels_with_a_running_cell polled `_REMOTE_KERNELS.values()`
while the worker thread was inserting into the same dict, so the poll itself
raised "dictionary changed size during iteration" (seen on main and on PR runs
that never touch the file). Iterate a snapshot and yield between polls.
_should_skip_container_guards documented fail-soft (unknown or raising
backend keeps the guards on) but only provider_flag's inner lookups were
covered: a raising registry.get_provider propagated out of the approval
predicate instead of defaulting to guards-on. Wrap the lookup so any
exception means "not isolated enough" and the dangerous-command prompts
stay in place.
Review follow-up on #113257.
Two fd-redirection spellings of the exact class 260f3e79fff70 closes still
reached a bare shell unscanned, while real bash executes the body in each:
- `cat <<EOF 2>&1 | bash` (and `&>/dev/null | bash`): `_pipeline_end` read
the `&` of the fd-dup as a top-level list operator and ended the pipeline
walk before `bash`, so the consumer was never a candidate.
- `cat <<EOF | bash 2>/dev/null` / `| bash 2>&1`: `_read_shell_word` stops
at `>`, so the fd number `2` came back as a word of its own and
`_executes_heredoc_body` took it for a script operand ("bash 2" runs a
script named 2), so the shell was not bare.
`_pipeline_end` now skips a `&` glued to a redirect angle bracket (`>&`,
`<&`, `&>`), and `_shell_words_at` treats an all-digit word immediately
followed by `<`/`>` as the fd prefix of that redirection and stops there,
exactly as it already stops at a bare `>`. `nice` joins the wrapper table
(`| nice bash` was allowed; same one-entry mechanism as nohup/setsid).
Controls unchanged: `| bash >/dev/null` blocked, `| bash run.sh 2>/dev/null`
and `cat <<EOF > notes.md` allowed. The new parametrized test fails on the
previous guard for the four evading shapes and passes on this one.
`cat <<'EOF' | bash` (and `| sh`, `| sudo bash`, `| bash -s`, `| (bash)`,
`| { bash; }`, `|& bash`, `| tee f | bash`, `cat <<EOF |` + consumer after
the terminator, `\`-joined lines) walked around the running-checkout guard:
`_heredoc_specs` decided "does a shell execute this body" from the text
BEFORE the `<<` opener only, so a shell downstream of the pipe never counted
and the body was masked as data before `_find_mutation` walked the command.
A `git checkout`/`reset --hard` in such a body rewrote the live checkout.
The consumer is now decided on the MASKED command (bodies blanked, so the
text is the structure the shell parses): `_pipeline_end` walks the opener's
pipeline with quote/escape state to the first list operator or bare newline
at its nesting level — newlines right after `|` continue it, `)`/`}` closing
the owner's own group end it unless a pipe follows — and every command start
in that span (pipe segments, and the groups/substitutions inside them, all
inherit the pipe as stdin) is checked with the bare-shell predicate.
`_join_continued_line` folds backslash-newline before opener detection, as
the shell does, so `bash \` + `<<EOF` and `cat <<EOF | \` + `bash` read as one
command line. `_shell_words_at` stops at a trailing `# comment` so `bash #
note` is still a bare shell.
Real-bash ground truth drove the shapes: `cat <<EOF |` followed by a newline
makes the NEXT LINE the heredoc body (the consumer comes after the terminator
or the pipeline is a syntax error), which is why the consumer walk runs over
the masked command rather than per physical line. `&&`/`||`/`;`/newline end
the pipeline, so `cat <<EOF && bash`, `| grep x`, `| bash -c 'cmd'`,
`| bash run.sh`, `| python3`, `| xargs` stay data.
Reported and analysed in #112441; supersedes the approach in #112442.
Co-authored-by: beardthelion <56458543+beardthelion@users.noreply.github.com>
Closes the residual left open by the previous commit for gateway-ready
installs (#113017 review). _get_backend() and check_firecrawl_api_key()
already use read_selection semantics, but _get_firecrawl_client() still
keyed its "stored vendor selection: direct only" branch on
selection_exists("web"), which is true for a lone per-capability key. So
with only web.extract_backend set and the Nous Tool Gateway ready (no
FIRECRAWL keys), the search ladder resolved to firecrawl via the managed
slot and the client then refused it with a misleading "web is configured
to use firecrawl (set via hermes tools)" error — the other capability
still lost its normal cascade.
The direct-only branch is now keyed on an explicit firecrawl selection
(shared web.backend via read_selection, or a per-capability key that names
firecrawl via _is_explicit_firecrawl_selection). A per-capability key
naming another vendor is not a firecrawl selection, so a ladder-derived
firecrawl resolves exactly like a never-configured install: direct when
credentials exist, else managed. Explicit firecrawl selections keep their
direct-only (keyless-unlocking) behaviour; "nous" is untouched.
Test: test_ladder_derived_firecrawl_takes_managed_path_on_gateway_ready_install
— red on the previous commit (ValueError), green with this change.
Fixes#113017. _get_backend() treated any web selection — including
per-capability keys (web.search_backend / web.extract_backend) — as a stored
shared selection and short-circuited to firecrawl with no ladder. Setting only
web.extract_backend therefore silently rerouted web_search off autodetect.
The no-ladder firecrawl branch now requires a shared selection
(read_selection: use_gateway); per-capability keys name only their own
capability, and the other keeps its normal cascade.
Test: new tests/tools/test_web_backend_capability_isolation.py — red on base
(search resolved to firecrawl), green after fix; managed use_gateway still
resolves firecrawl with no ladder.