The move had turned the function-level imports of agent.provider_route_hooks
in agent/auxiliary_client.py and run_agent.py into module-top imports. That
module imports providers.base at top, so importing agent.auxiliary_client
began to need the providers package. The update child's check of configured
features runs in a target tree where that import fails, and it stopped naming
Feishu (tests/hermes_cli/test_update_missing_configured_deps.py).
Both callers already import route_answer from that module inside the function.
The rule now rides on the same line, so neither module's import-time
dependencies differ from main.
The rule knows OpenAI model family names, which utils (a product-agnostic helper module) should
not, and only agent code calls it. It now sits beside the provider profile max_tokens_param answer
it backs up in both callers. No re-export is left in utils.
agent/auxiliary_client.py imports route_answer at module top with the moved rule and drops its two
function-local imports of it, keeping the file at its line cap.
The test file moves to tests/agent/test_provider_route_hooks_max_completion_tokens.py.
* fix(trajectory): redact secrets before persistence
* fix(batch_runner): redact trajectories at the batch_*.jsonl append too
batch_runner saves trajectories itself (save_trajectories=False on the
agent), so the save_trajectory redaction never ran for the main dataset
path. Redact the conversations leaf-wise before _append_jsonl, and make
--resume match the redacted human turn so redacted prompts are not
re-run on every restart.
Fixes#108495
* fix(trajectory): redact embedded tool-call/response JSON decoded
The text pass ran over turns that already hold json.dumps'd <tool_call>/<tool_response>
bodies; whitespace-delimited rules (KEY=..., --password=..., Bearer ...) swallowed the
closing quote/braces, leaving unparseable tool calls in saved and batch trajectories.
Decode each block, redact its values, re-serialize; values the plain pass leaves unchanged
are retried on a one-field document so key-driven rules (api_key, x-api-key, Cookie) still
apply after decoding.
Refs #108495
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
* fix(run_agent): redact --save_sample trajectory before writing
_save_sample_trajectory wrote the converter output and query raw to sample_<id>.json,
the same persistence boundary save_trajectory and batch_runner now redact.
Refs #108495
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
---------
Co-authored-by: joaomarcos <joaomarcosdias444@gmail.com>
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
f787b61 removed the implicit wall-clock kill for every external-process buffered
call, trusting the process client's own deadline. ACPClient._request writes the whole
prompt to blocking stdin before it checks that deadline, so a child that answers
session/new and then stops reading hung Hermes until something killed the child
(reproduced: a 2 s request was still blocked at 30 s).
The implicit bound is now the request timeout the client is already given
(providers.<id>.request_timeout_seconds, else 1800 s), for every model and capped by
the run budget. That is longer than main's 240 s opus floor, and it is the bound the
client already had, so no model is less patient than on main in practice; the
reasoning floors stay out because they model HTTP gateways that idle-kill (#149555).
An explicit stale timeout still wins. DirectSDK streams, so this path is its rare
fallback; the stream budget stays the 900 s local ceiling.
Greptile 4513158607 on #151932.
The stream resolver compared the configured value to 180 to decide "unset", so an
explicit providers.<id>.stale_timeout_seconds: 180 on an external-process profile got
the 900 s local ceiling instead. The check is now presence, not value. The buffered
path had the same shape one layer down: the context-size tier raised an explicit 180
to 240 s on a large request, so an explicit value is now used as-is there too, as the
stream path already does (#115024).
Greptile 4513003702 on #151932.
DirectSDK's stall patience came from is_local_endpoint() misreading
process://, and only for some paths: the stream got the 900 s local
ceiling, but a buffered (non-stream) call got 240 s for opus and sonnet
(their reasoning floors count as "explicit" and skip the local branch) and
no limit for haiku or sonnet-5[1m]. One ~320K-token opus turn was killed and
re-sent four times in 15 minutes this way (#149555).
non_stream_stale_disabled() now decides by auth_type: an external-process
provider has no implicit wall-clock kill on a buffered call, whatever the
model, and the process client's own per-event deadline still bounds a dead
child. The stream keeps the 900 s ceiling (agent.local_stream_stale_timeout)
through waits_like_local(). An explicit providers.<id>.stale_timeout_seconds
or HERMES_API_CALL_STALE_TIMEOUT still wins. No path gets less patient than
it was on main; opus and sonnet buffered calls get more.
61 call sites counted directories up from their own __file__ to find the
install folder. They now call hermes_cli._startup_fast.project_root_str(),
so the layout move changes one line instead of 61.
Kept with a reason in the lint baseline: files that cannot import Hermes
code (bootstrap, update path, pm/) and the sys.path bootstraps left for
part 2b. The baseline drops from 89 to 28 root_from_file sites.
Six existing tests that patched a module __file__ now patch the owner.
Two review rounds each found ~8 new host routes because the policy listed what to refuse.
tools/hosted_tool_policy.py now lists what is allowed, and the denylist is gone.
- hosted_tool_refusal: a tool runs in a hosted scope only if it is on HOSTED_TOOL_ALLOWLIST
(terminal, process_manage, execute_code, read_file, write_file, patch, search_files), the
tools that act only through the agent's sandbox. The agent loop asks once per call in
_dispatch_authorized_once, which every sequential, concurrent and batched call goes
through whatever its executor (inline, memory provider, context engine, registry). The
primitives ask too, for callers outside the loop: ToolRegistry.dispatch, the inline
executor table, handle_function_call (connectors, bridges) and the browser_exec direct
entry. Memory, session_search, todo, vision, web, browser, MCP, connectors, catalog,
delegation, skills and cron are refused before any handler (round-2 findings 9, 10, 11,
13, 14).
- host_feature_enabled: agent features outside tool calls that read or write this host's
profile state are off in a hosted scope. Context files and SOUL.md, subdirectory hints,
@-references, workspace snapshot, backend probe, built-in memory init/load/writes and
providers, recall DB, background review, trajectory export, failed-write bookkeeping,
checkpoints, image/video processing, inline skill shell, cron scripts, MCP stdio, media
delivery, transcription and /review delegation each ask the one function (findings 4,
12, 13, 15).
- Per-site refusals that the allowlist covers are removed (connector file inputs).
- Local mode is unchanged. A test shows the allowlist is never consulted unscoped or
locally and every registered tool reaches its handler. The local byte-parity test is
kept.
* fix(delegation): keep _delegate_from on reserved subagent rows
A reserved child row (_reserve_child_transcript) carried no model_config.
On the child's first turn stamp_prompt_epoch patched model_config before
_ensure_db_session ran, and the keep-existing constructor upsert then kept
that patch and dropped the whole constructor config, _delegate_from
included. resolve_resume_session_id then walked the parent into the child
as a continuation, so reopening the parent in Desktop showed the subagent
transcript.
- the reservation writes the _delegate_from marker
- the first-turn create of a reserved row merges the constructor config
beside keys written earlier
- v33 re-tags subagent rows that already lost the marker
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(state): skip subagent compression continuations and malformed configs in v33
A misrouted child resumed as the chat could compress, leaving a source='subagent'
continuation without the marker. v33 tagged it as a delegate of the child, hiding
the turns typed after the compression. Skip continuations of compression-ended
subagent rows.
json_set raised on one malformed model_config, the suppressed error dropped the
whole UPDATE, and the version still reached 33, so the store never healed. Only
touch rows whose model_config is valid JSON.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(tui): keep parent completions out of delegate sessions
Exercise real child reservation and first-turn metadata writes against SessionDB, then drive notification routing with both parent and delegate UI sessions live. Cover process and async-delegation completions with and without parent compression. Assert the child cannot emit or start a turn and the parent still receives the retained event.
* chore(contributors): map n0ctx's commit email
* fix(kanban): reclaim TUI subscriptions bound to the parent's own subagent
Before the reserved child kept its _delegate_from marker, kanban_create
resolved the parent's key to the unmarked child and saved the card's
subscription under the child's id. v33 re-tags the session row but never
touches kanban.db, so those cards kept notifying the subagent.
On its first kanban poll a live TUI session now re-keys tui subscriptions
bound to its own marked delegate descendants (and those of the compression
segments it continues) back onto itself, keeping the cursor. A subagent tab
never claims its parent's or siblings' subscriptions.
* fix(kanban): retry stray-sub reclaim after DB errors; cover child continuations
Review on #150198 reproduced two gaps in the reclaim:
- a transient SQLite error (locked board/store) was cached as 'nothing to
reclaim', so that live session never retried. Failures now stay uncached
and are logged; only a pass where every board reclaimed clears the keys.
- a misrouted child resumed as the chat can have compression continuations
that v33 leaves unmarked (correctly), and the pre-fix resolver subscribed
cards under those tips. The descendant walk now includes each delegate
child's compression chain.
---------
Co-authored-by: n0ctx <yzwang0408@proton.me>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: teknium1 <127238744+teknium1@users.noreply.github.com>
Sixteen guards decide "this module is absent, fall back" by comparing
ImportError.name with a hand-written list of names. When a guarded
module moves into a package, a missing parent reports only the
parent's name, so the guard re-raises and the fallback never runs.
Each guard now names its import target once and treats the target or
any of its parent packages as absence. A failure inside the target
still re-raises.
Four call sites fork a second agent with skip_memory=True, which leaves the
child with _memory_manager = None: a fork is not the user, and its scratch
transcript is not the user's memory. With compression.checkpoint_required
armed that saving turns into a kill. The gate is armed globally per agent
instance from config, not from whether the agent has a provider, so the child
arms the same gate its parent did and then meets its first compaction with
nothing to checkpoint against. It raises CompressionCheckpointUnavailable --
"no active provider implements checkpoint API v2" -- and the delegate turn
dies with status=error and a null summary while the parent runs on. The gate
is not bypassed there; it is armed against a provider that was never loaded.
- The four sites (delegate_tool, curator, batch_runner, feishu_comment) pass
skip_memory=not checkpoint_required_from_config(). Gate off is the default
and stays byte-identical: skip_memory=True, no provider init, no hook. Same
shape and the same reason as the two gateway disposable-agent sites that
already read the key this way (run_turn_hygiene.py,
slash_commands_session.py). delegate_tool reads it inside the delegated
profile scope, where the child reads it.
- The detached review and /btw forks (build_cache_parity_fork) are not
touched: they persist nothing, and _pre_compress_memory_context already
exempts exactly that shape (decabd79f1), so the gate never fails them.
- checkpoint_required_from_config() in conversation_compression_checkpoint,
next to the gate's init refusals. One resolver rather than four parses, and
the call sites need it before an agent exists:
agent.compression_checkpoint_required is assigned inside the child's own
init, and the parent's says nothing about the child. It reads
load_config_readonly() -- the call init_agent makes to arm the gate on that
child, so parent and child answer from one source and a fork is given a
provider precisely when the child would refuse to compact without one. An
unreadable config reads as "not armed", matching init_agent's own except
around the same load.
- New memory_agent_context kwarg on AIAgent/init_agent, handed to the
provider's initialize() as agent_context; unset, the platform rule decides
as before (cron/subagent, else "primary"). The platform rule alone cannot
scope these forks: the curator runs as platform "curator", the batch runner
takes its platform from the caller's config, and the Feishu responder sets
none, so each would file its transcript as the user's own memory in every
provider that scopes writes by that key. All four pass "subagent" -- the
value memory_provider.py documents and supermemory gates on. A fresh
per-site string ("curator", "batch", ...) would drop out of every
provider's non-primary membership test and re-enable writes the provider
had deliberately disabled, which is a fail-open on the one path this commit
opens. platform still separates the shapes.
Costs, taken deliberately rather than hidden: one provider initialize() per
fork (a round trip for a network-backed store, on a path that made none), and
fork transcripts reaching the archive as checkpoints. Both are named at the
call site and in the contract doc, where a provider author reads them.
Ten tests (tests/agent/test_fork_memory_under_checkpoint_gate.py). The
four site probes drive the real spawn functions with the smallest parent stub
they accept and record the child constructor kwargs -- red at all four against
the previous commit with the literal skip_memory=True. The gate-off probes are
the control in the other direction: without them "inherit the provider" could
have shipped as "always inherit". The recorder aborts with a BaseException
because the sites wrap the spawn in except Exception and would have swallowed
an ordinary failure into a green test. The provider-initialize test drives a
real AIAgent init, the only way to observe the keyword at initialize().
Live probe (on the August base), isolated HERMES_HOME with a stub API-v2
provider and the gate armed: before, the child aborts with failure_class
"exception:CompressionCheckpointUnavailable" and delegate_task returns
status=error, summary=null. After, the child initializes the provider
(agent_context "subagent", platform "subagent"), its own session fires
on_pre_compress, no CompressionCheckpointUnavailable appears, and the parent
returns the subagent's answer.
(cherry picked from commit 31af59c54ebff4c6c1861961111700b8e42dba76)
(cherry picked from commit 9bf3feaf8c98dff6e90eadf0f533204adc150a8c)
The housekeeping tick and the TUI idle reaper now call trim_memory_when_idle: allocator trim
only, plus one full gc.collect() once no turn has run in this process for 5 minutes (again
after a later agent close re-arms it). Nobody is waiting then, so the pause harms no one, and
whatever cyclic garbage remains (openai SDK resource cycles) is still reclaimed. The quiet
clock is the existing process-wide live-turn counter in review_idle_queue.
On a long-lived gateway every agent close (idle-cache eviction, /new, session end) forced
trim_memory(force=True), and its gc.collect() walks the whole shared heap with the GIL held:
264-760 ms on the live 3.6M-object gateway, about once a minute, freezing every other
session's thread, adapters and streams. The TUI turn-completion trim runs in the same
process after every TUI/Desktop turn.
Both now pass collect=False: what an agent close or a finished turn drops goes by reference
counting, cycles are left to CPython's automatic collection, and the next trim returns their
pages. The forced collection stays on the idle reaper (runs only when every session is
quiescent) and agent-cache pressure eviction (memory is the emergency there).
On a messaging chat with display.interim_assistant_messages off, a top-level
delegate_task still produced two messages: a "checks are running, I don't have
the findings yet" reply and, later, the real answer. Top-level model
delegations always run in the background (ea8a8b4af8), and the tool text tells
the model to "give a one-line status and END YOUR TURN" (c89f3b8800). That
status is the turn's final answer, not interim text, so no display setting
held it back.
New key delegation.gateway_mode: auto | inline | background (alias async).
auto (default) joins the children inside the turn on a messaging chat whose
resolved interim setting is off (global, display.platforms.<p> override or
platform default). The parent waits in the tool call, gets the results there
and sends one answer. API, local and webhook surfaces keep the background
path under auto. Chats with interim messages on are unchanged: same schema
bytes, same async dispatch.
How it works:
- The gateway resolves the mode from the turn's own profile-scoped config
when it builds a session's agent (gateway/session_execution.py), and the
agent's first tool build freezes it (like the one-shot pin).
- An inline session carries the joined delegate_task variant the one-shot
path already uses: "results return in this tool call", no live-control
parameters, no END YOUR TURN.
- Dispatch follows the delegate_task schema the session carries
(session_joins_delegation), so schema and behaviour cannot disagree. The
schema rides the session's tools[] pin: a config change applies from the
next session (/new), as delegation.backend does, and a cache eviction or
restart never flips a running chat.
- Inline children run on the existing synchronous path: attached to the
parent, so /stop and an interrupting follow-up stop them; the per-child
heartbeat keeps the parent's activity fresh for the inactivity watchdog;
the async completion registry is not used. Nested and one-shot delegation
are unchanged.
Refs #95522.
Runtime resolution caught a raising api_mode_for_model hook and kept the
profile's declared api_mode, but /model (model_derived_api_mode, also the
resume re-derivation in the TUI, CLI and gateway), the stale
codex_responses check in resolution, the agent's Responses routing check
and the auxiliary client asked the same hook unguarded: a model could
resolve and then fail building the switch result.
agent.provider_route_hooks.model_api_mode is now the one call: a raise
answers the profile's declared api_mode, logged with its traceback once per
provider. A None answer keeps each caller's existing meaning.
A failed per-request profile hook stays on the generic answer for the agent's session so request
bytes never flip, but the failure memory survived /new and /resume (reset_session_state reuses the
agent), and the warning was logged once per process, so in a multiplex process every later home's
agent degraded silently. The memory is now cleared at a session boundary and a scoped (agent)
failure is logged once per session; scopeless one-shot callers keep the once-per-process warning.
53a51a49cc made every attempt of a user turn's first API call (429/5xx retries, fallback
activations) re-send the provider's user_initiated request headers. Hermes has always sent them
on the first attempt only (retries went out with the route's default), and that difference is
billing-visible (premium-request initiator headers), so it is reverted: the first payload built
in a user turn consumes the flag and is the only user-initiated one.
Kept from 53a51a49cc: the flag is consumed exactly once whatever the route answers, so a route
without attribution or a failing request_headers hook never leaves it set for a tool-loop
follow-up.
The live matrix on real processes found two ways a prepared-compaction pass was paid for and never
usable:
- `hermes chat -q` / `-z` runs end with their turn (the gateway evicts the agent right after the
reply), so a turn-end pass there was always cancelled ~0.5 s later. One-shot sessions now join
cron runs and delegated children in skipping turn-end passes.
- Releasing an agent without a session boundary (gateway cache eviction, a Desktop rewind,
managed-worker retire, close()) left a running pass billed to completion. release_clients() and
close() now discard it (shared-metrics reason `agent_released`).
Pass log lines now carry the session id, so concurrent sessions in one gateway are attributable.
R4 P2-5 (wire W2).
- replay_message_carriers was asked once per carrier-bearing assistant message
on every request (O(history) calls, each an IPC round trip under
plugins.isolation: host). Its answer is now kept per (route, carrier key set)
as a key mapping and applied to every message with that key set; a hook whose
answer rewrites values is still asked per message. Contract documented on the
hook in providers/base.py.
- reasoning_payload and replays_function_thought_signature join request_headers
/ max_tokens_param as memoized pure hooks (argument values frozen, answers
deep-copied).
- ONE failure policy for every per-request profile hook
(provider_route_hooks.ask_profile, also behind route_answer): a raising hook is
logged once per (profile, hook) and answers the generic value; the agent (scope)
remembers it, so the rest of the session keeps the generic answer and request
bytes never flip between turns. Before: _supports_reasoning_extra_body
swallowed per request, _endpoint_reasoning_payload / replay_message_carriers /
replays_function_thought_signature raised out of the kwargs build, route_answer
swallowed per call. A failure mid-request reshapes the whole request so it
matches every later one. One-shot auxiliary calls (no agent) ask again.
- x-initiator turn flag: already consumed before asking the route (53a51a49cc).
A provider's request_headers(user_initiated=True) answer (turn attribution,
e.g. a premium-billing initiator header) was consumed when the first
attempt's payload was built. A 429/5xx retry or a fallback activation
rebuilds the payload for the SAME API call, so the retried attempt went out
with the route's default (agent) attribution instead of the user's.
The route now claims the call's api_call_count; every attempt of that call
re-applies the headers, tool-loop follow-ups (higher count) do not, and a new
turn / session reset clears the claim.
Repro (fake profile + local HTTP stand-in, scratch probe_xinit.py): first
attempt carries the header, the retry did not (codex_responses 500 retry,
chat_completions 429 retry); both attempts carry it after this change.
The turn flag is consumed exactly once per user turn, before the route is
asked: a route with no attribution, or a request_headers hook that fails
(route_answer swallows plugin errors), no longer leaves it set, which billed
the next tool-loop call as user-initiated (r4-review P2-5).
Nothing in production called them. Their tests now pin the owners of the
behaviour with the same inputs and assertions: the copilot profile's
request_headers (x-initiator hosts) and providers.profile_for_host (host-anchored
identity), in tests/plugins/model_providers/test_copilot_hosts.py.
Core branched on the Copilot slug/host for four wire decisions. Replace them with
generic ProviderProfile hooks (providers/base.py L1 block) and move the Copilot
logic into plugins/model-providers/copilot/wire.py:
- api_mode_for_model(model, *, api_key=None): run_agent Responses routing, aux
CodexAuxiliaryClient wrap, model_switch.model_derived_api_mode (copilot rows
of _PROVIDER_API_MODE_OVERRIDES removed).
- client_headers(*, base_url, api_key, has_images): agent_init/_client_lifecycle
host tables, the client-kwargs chokepoint guard (_ensure_route_client_headers),
the image request-client header swap, both aux header branches.
- request_headers(*, base_url, model, user_initiated): first-call-of-a-user-turn
attribution in turn_api_request and MoA reference slots.
- max_tokens_param(*, base_url, model): run_agent._max_tokens_param and
auxiliary_max_tokens_param.
agent/provider_route_hooks.py asks the named provider's profile first, then any
registered profile overriding the hook, so custom routes at a provider's host
keep its quirks. Plugin absent = generic behaviour.
_maybe_requeue_preempted_review skipped only focused reviews, so a bare
/refine cancelled by a live turn on the managed local runtime went to the
idle queue, whose dispatch-time enabled re-check then dropped it when
automatic reviews are off. Requeue is for automatic reviews only.
auxiliary.background_review.enabled: false must stop only automatic
post-turn forks (#87250). _spawn_background_review keyed the delegate and
enabled gates on `focus is None`, so a bare /refine (explicit=True, no
focus) replied "Reviewing this conversation in the background" and spawned
nothing. Gate on `not explicit and focus is None` instead.
Fixes#100762
- run_agent / gateway shutdown / cli + hermes -q atexit / /browser and the
browser.manage RPC import cleanup_*, emergency_cleanup_all_sessions,
get_cloud_provider, get_browser_engine, the lightpanda status pair and the
CDP override + supervisor helpers from tools.browser_session_{lifecycle,
cloud,cdp} and tools.browser_lightpanda;
- per-turn cleanup reads browser.headed through is_headed_mode() only (the
AGENT_BROWSER_HEADED fallback is gone with agent-browser);
- tests repointed; tests that only covered browser_vision / the built-in
tool wrapper are dropped, the browser child env is credential-free per
the session layer, and the codex MCP list must name core tools only.
With prompt caching on, the request carries the system prompt as two text parts (the static prefix and
a per-request suffix slice), so the memo entry pins those strings, not the stored full prompt, and
forgetting _cached_system_prompt alone missed it. close() now also forgets _cached_system_prompt_static;
its pin evicts the split entry.
Repro on 75941667aa: real apply_anthropic_cache_control split -> prefix still pinned after close().
Found by the #137087 round-2 re-gate (second-model reviewer).
Two strings reach _MSG_TOKENS_CACHE without ever sitting in the conversation history, so neither close()
nor the post-compression release could forget them:
- compression telemetry estimates the freshly built summary prompt (a serialized transcript, 520 KB in
the probe) once per attempt; it stayed pinned until FIFO eviction.
- the per-session system prompt enters the memo via api_messages only; close() now forgets it alongside
the history.
Repro on bcf6981878: both strings still pinned after telemetry / close(). Found by the #137087 pre-arm
gate (second-model reviewer), probe-confirmed.
trim_memory now runs gc.collect() on every platform and only the page release is glibc-only, so "safe
no-op elsewhere" was no longer true.
Found by the #137087 pre-arm gate (2c review).
_MSG_TOKENS_CACHE pins every string it fingerprints, so after AIAgent.close() a long-lived serve kept
each closed session's message bodies resident until 4096 newer messages pushed them out (tracemalloc on
a macOS serve: 200 x 256 KB replies, 50 MB, still pinned by the memo after every session closed).
shutdown_all() gives the single mem-sync worker ~5 s and then cancels whatever
is still queued. Before this PR, release_clients() left the executor alone, so
a retired agent's last sync_turn/queue_prefetch writes still ran in the
background. With the soft-release shutdown they were abandoned instead
(measured: 4 queued 2 s writes -> 2 written, 1 abandoned).
MemoryManager.release_soft() now claims the teardown, flushes (bounded, like
the CLI exit, gateway cleanup and managed-worker paths), then shuts down.
release_clients() calls it, which also moves the soft-release policy out of
the run_agent.py facade (back to main's line count).
The /new cleanup job took the teardown claim only inside
shutdown_memory_provider(), after a flush_pending() that can take up
to 10 s. When /new stops waiting (_RESET_CLEANUP_TIMEOUT_S) it evicts
the agent, and that soft release took the claim and shut the providers
down while the cleanup was still flushing. The cleanup then lost the
claim and skipped on_session_end(), so the session's end-of-session
extraction was dropped. On main release_clients() never touched memory,
so the extraction always ran.
The claim now lives on MemoryManager (claim_teardown(), under the lock
it already has), and _cleanup_agent_resources takes it before the
flush. A session-end caller may re-claim (the cleanup claims, then
shutdown_memory_provider() claims again); a soft release is once-only
and also loses to a manager another owner is already draining, which
replaces the _shutting_down peek in release_clients(). The module lock
and _memory_teardown_claimed attribute in run_agent.py go away, and the
release_clients() comment shrinks to the why.
Claiming earlier than the pool submission is not needed: when /new's
wait_for times out before the job starts, asyncio cancels the queued
job, so it never runs on main or here.
The hand-rolled _MockMM soft-evict test is dropped: its stub manager has
no claim_teardown(), and the real-manager writer-thread test already
asserts the same thing (shutdown, no extraction).
/new waits 30 s for its cleanup worker and then evicts the same agent. A
worker still inside on_session_end() had not set the manager's
_shutting_down yet, so release_clients() ran shutdown_all() under the
extraction, and the worker shut the providers down a second time when it
returned. Both paths now take the same once-only claim before extraction
or shutdown; the loser skips. This replaces the release-only
_memory_providers_released flag, which only covered close() racing a
release that had already started.
release_clients() set _memory_providers_released only after
shutdown_all() returned, so a close() arriving during the bounded drain
(up to ~5 s, plus provider writer joins) still ran on_session_end()
against providers mid-shutdown and called shutdown() on them again.
Set the flag before starting the teardown.
release_clients() now shuts the memory providers down but leaves the
agent's own _memory_provider_shutdown flag unset, so a later close() on
the same agent would run on_session_end() against shut-down providers
and call provider shutdown() a second time (MemoryProvider.shutdown()
has no idempotency contract). release_clients() records
_memory_providers_released on the agent when it shuts the providers
down, and shutdown_memory_provider() skips extraction and shutdown when
it is set; the context-engine session-end notification still fires.
The flag lives on the agent rather than reading the manager's private
_shutting_down, so test doubles that hand the agent a MagicMock manager
keep their close() -> shutdown_all() contract.
getattr() with a default cannot raise and _quietly() already swallows a
failing shutdown_all(), so the outer try/except/pass only hid nothing and
tripped the code-health ratchet (BLE001/S110).
R2 review: the soft-eviction comment claimed _commit_then_release_soft()
universally commits extraction before release, but only the sweep paths
(LRU cap, idle TTL, RSS pressure) do; direct eviction paths (/new,
/model, /login, cross-process) release via _release_evicted_agent_soft
with no pre-commit. Reword the comment to state the per-path coverage
and note that the direct paths' uncommitted final-turn extraction is
pre-existing behavior unchanged by this PR.
release_clients() never shut down memory providers: every gateway
eviction path (LRU cap, idle TTL, RSS-pressure sweep, cross-process
evict) soft-releases the agent while its providers' background writer
threads keep running. Each soft-evicted agent leaked one writer daemon
(plus the references it pins), and under cache turnover from 429 retry
storms they accumulated into the 2026-07-30 gateway crash dump: 57
leaked writer threads out of 99 total, driving memory to the peak that
killed the liveness watchdog (exit 75).
Fix: release_clients() now calls MemoryManager.shutdown_all() directly,
which bounded-drains the sync executor and calls each provider's
shutdown() (sentinel + join) — without on_session_end(), whose
end-of-session extraction must stay the gateway's pre-evict commit's
job (_commit_then_release_soft() -> commit_memory_session() before
release) and which a resumed session would otherwise duplicate. Guarded
on the manager's _shutting_down flag; a resumed session's freshly-built
AIAgent creates a new manager with fresh providers.
Follow-up to #74785: the writer-thread leak was split out as separate
and not covered, with an invitation to open a focused PR.
Regression: TestAgentCacheIdleResume.
test_release_clients_shuts_down_memory_provider asserts shutdown_all()
fires on soft eviction and on_session_end() does not.
Review follow-ups on #137955 (long decode):
- Non-streaming stale watchdog: one timer spans every unary hop of a long decode, so an
xhigh/max turn (8 / 32 hops of 32,768) was killed at the 600s gemini-4 floor and retried
from hop 1, re-billing the hops already done. The implicit non-stream stale budget now
scales by the request's hop count (explicit config still wins; the run-budget cap still
applies after). Covers both the worker and the inline cron/subagent path, which read the
same resolver.
- Hop ceiling: the unary and streaming loops stop at ceil(maxOutputTokens / 32,768) + 1 hops
and end the turn as `length`, so a server that keeps answering CONTINUATION can't bill
forever.
- Context-engine buckets: input_tokens / cache_read_tokens now follow the same first-hop
split as prompt_tokens, so engines reading the canonical buckets don't see the summed
prefix (or cache_read > prompt). Billing, the log line and session totals keep the sum.
Salvage of 058b5c8158 from the static-onboarding stack, adapted: the
initiate-setup prompt, its facts builder and the first-task prompt go with
the setup_choose server request and callback, the initiate-setup branch of
the prelude wiring in prompt_turn and the intro auto-continue skip. Unlike
058b5c8158 the scripted prelude seam (agent/turn_scripted_prelude.py and
the prelude parameter on run_conversation) and gui_tour's preset stay: the
default-profile onboarding opening plays through them, and prompt_turn now
asks only _onboarding_prelude for one.
(cherry picked from commit 058b5c8158, adapted)
set_theme (desktop_ui, deferred like apply_layout was) sets the accent,
light/dark mode and layout preset, or with `picker` shows an accent or
layout card and waits up to 300 s. apply_layout emitted a layout.apply
event and returned success whether or not the renderer applied anything;
set_theme asks the renderer through the theme.apply server request and
returns its answer, so an unknown preset or a chat that is not on screen
comes back as an error with the available ids.
theme.pick waits for a person; the backend tells a dismissed card
({cancelled}) from an expired one ({timed_out}). The tool description
lists the Simple and Advanced preset ids from one constant, which fixes
the old description that named neither sidebar preset. The layout.apply
event and its renderer handler are deleted with the tool.
tools/setup_beat_tool.py shows a beat's card and blocks until the user
answers (the card callback is a server request, like clarify), then
returns their answer with a reminder of the next beat. beat=next shows
the first open beat; value and skip record an answer given in words
without a card; beat=done ends the run once the build card was reached,
and beat=done with skip=true ends it early when the user asks to stop.
Words typed while the name card waits are the name. The account's full
name goes to the name card only.
The tool lives in a new desktop-only "onboarding" toolset, which nothing
enables by default; the gateway folds it in for the onboarding chat only
(next commit). It runs inline in the agent loop (inline_tool_executors)
with the session's store and the agent's setup_beat_callback, and never
in parallel with another tool.
Two loop seams:
- tool_executor passes every successful tool result to
onboarding.observe_tool_result, so set_theme, manage_connections
display and gui_tour (also when reached through tool_call, which the
executor unwraps first) settle their beat.
- turn_tool_round treats a setup_beat round like a housekeeping round
for the empty follow-up: the line written with the card becomes the
reply instead of an empty-response nudge (not muted).
#135348 ran ruff's UP037 autofix with ruff.strict.toml's target-version = "py314". On 3.14
annotations are lazy (PEP 649), so stripping quotes is safe there; on 3.11-3.13 a function or
variable annotation is evaluated when the def or statement runs. Every unquoted annotation that
names the enclosing class (`def clone_for_agent(self) -> ContextEngine`), a class bound later in
the module, or a TYPE_CHECKING-only import now raises NameError on import: 300 modules on main
(gateway.config, run_agent, hermes_state, cron.jobs, the Telegram adapter, ...) fail to import
under 3.11, the update path crashes mid-`hermes update` on any install whose interpreter is
older than 3.14, and the e2e-upgrade suite's retry leg fails with
`NameError: name 'ContextEngine' is not defined`.
- Re-quote exactly the 79 annotations (36 files) that name something unbound when they are
evaluated (including tui_gateway/server.py's `_TurnScopes`, which only reaches that module's
globals through register() after import); no other text changes.
- agent/turn_scripted_prelude.py: `Generator[...]` gets its third argument back. d76cce4f11
applied UP043 (default type args, valid only from 3.13) to a module-level alias, so
`Generator[Y, S]` raises TypeError on 3.11/3.12 and takes gateway.run, agent.conversation_loop
and tui_gateway.{server,ws,entry} down with it.
- ruff.strict.toml target-version = "py311", the requires-python floor. With it UP037 leaves
these quotes alone and only strips the two that are genuinely redundant, which this commit
strips; any future version-gated fix stays valid on every supported Python.
- tests/ci/test_strict_ruff_target.py pins the target to the requires-python floor (red on main).
The persist / restore / carry logic for session YOLO had grown three copies
(the CLI mixin, tui_gateway, the gateway runner), each with its own key choice,
ordering and error handling. tools/approval_yolo.py now owns it:
- toggle_session_yolo: flip or set, persist BEFORE the live flip (a racing
restore never revives an OFF), stored-copy-aware so a toggle after a restart
turns it OFF; a failed write logs a warning and never blocks the flip.
- restore_session_yolo: re-arm a persisted flag in a fresh process; skipped
under the frozen process --yolo.
- transfer_session_yolo: move the live flag to a continuation id.
- with_session_yolo: a row being created records a live flag (lazy first row,
compression child, /branch).
Each surface keeps only its storage: the session row for CLI/TUI/Desktop, the
routing entry for the gateway. Removed: HermesCLI._transfer_session_yolo /
_persist_session_yolo, GatewayRunner._restore_session_yolo, the TUI-only
restore helper, and the TUI's post-publish set_session_yolo carry (the
compression publish now writes the child row with the flag).
Closes a gap the unification exposed: a CLI manual /compress that rotated the
session dropped YOLO (the next dangerous command prompted, and a --resume of
the continuation came back with it off).
Brings the onboarding branch up to main 0c2ff854a5. Where a Wave A PR
already landed a reviewed version of a piece of this branch (free tier
#134049, keyless web #134048, app resolver #134050, bundle and uninstall
#134051, catalog card and toolsets #134052, built-in tour #134054, stdin
guard #134055, retired key #126146), main's version wins. The PM long-path
files also take main's version: that work lands through #130430.
Kept from the branch on top of main:
- the setup and start_chat toolsets, declared with main's platforms key
(desktop only), and the setup_choose server request contract;
- the setup-profile marker file (.setup-profile.json) instead of the
profile.yaml role, as c3f85bc54f decided;
- the first-contact note's message argument beside main's internal flag;
- the setup-profile gate on the shared-metrics consent dialog;
- window sizing (window-growth) in place of chat-onboarding-window.
Desktop i18n follows main's per-section sibling files. The onboarding
strings go into them (modelMenu.localSetup, handoffTour.localTitle and
localText) and setupChoose/startChat stay in en.ts. guidedGreeting is
gone. The shared-metrics copy uses the branch's rewrite in English, with
the pre-opt-in sentence corrected for the fresh-install note
(d3674513c8); locales keep main's translations, with installId and
consentWindow folded into the new sending key.
The built-in tour reads local-model eligibility from the local-setup
offer store, the one place that rule lives on this branch. The gateway
contract and the onboarding skill docs pages are regenerated.