hermes-agent/tools
victor-kyriazakos 6a7cf19302
fix(gateway,relay): stop frozen-preview finals and dropped idle-session delegation callbacks (#82592)
* fix(gateway): stop frozen-preview finals and dropped idle-session delegation callbacks

Two relay-plane delivery losses from the 2026-08-09 staging incident:

1. stream_consumer: the skip-redundant-finalize branch recorded _accumulated
   as the delivered turn-final payload even when the last ACKED edit was an
   earlier throttled preview snapshot, so delivered_final_matches reconciled
   True and the gateway suppressed the corrective final send — the user was
   left with a cut-off message ending in the streaming cursor. Extracted
   _mark_skip_redundant_finalize(): records the last acked wire payload
   (cursor-stripped), so a preview/final mismatch now returns False and the
   normal final send fires.

2. run.py: _classify_completion_target classified every ended parent session
   terminal unless it ended by compression. Idle/timeout session ends are the
   norm on scale-to-zero relay deployments and the chat route remains valid;
   completed async delegation results were terminally dropped. Ended parents
   now classify deliver unless the end was an explicit user boundary
   (session_reset / user_exit / session_switch).

* fix(relay): drain in-flight outbound frames before transport teardown

disconnect() failed every pending outbound future immediately with
'relay transport closed', so a trailing finalize edit racing turn
teardown was lost even though the connector socket could still serve
it. Bounded drain grace (5s) lets in-flight requests resolve; silent
connectors still tear down promptly. asyncio.wait (not gather+wait_for)
so a timeout doesn't cancel futures owned by the fail-remaining loop.

* fix(gateway): route completion injection through the alias-aware transport resolver

Third relay-plane delivery loss from the 2026-08-09 staging incidents: a
delegation batch completed while the gateway was up, the watcher drained
the event, and delivery vanished with no log line. _inject_watch_notification
resolved its adapter with a literal p.value == platform_name scan of
self.adapters — a relay-fronted gateway registers ONE adapter under
Platform.RELAY fronting N logical platforms, so 'slack' never matched and
the injection returned None ('no gateway route'), silently dropping the
completion. The handoff path already documents this exact trap and uses
resolve_delivery_transport; the injection path now does the same (native
wins; relay eligible only when it fronts the logical platform), with the
literal scan kept as fallback for stub runners and exotic platforms.

* fix(relay): clamp disconnect drain grace to the runner's adapter-disconnect budget

Review finding (JoaoMarcos44, #82592): a fixed 5.0s drain in front of the
three 1.0s sequential teardown awaits gives an 8.0s worst case inside the
runner's 5.0s asyncio.wait_for(adapter.disconnect()) — tripping it cancels
teardown mid-drain, skips the fail-pending loop, and leaves outbound
callers blocked until _OUTBOUND_TIMEOUT_S (30s). The effective grace is
now budget - 3*TEARDOWN - margin (env-aware via the same
HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT the runner reads), so the drain
can never push teardown past its caller's budget; a budget too small for
any drain disables it cleanly.

* test(gateway): pin the final-send suppression contract across a behaviour matrix

The gateway skips its own final send when the stream consumer claims the turn
final already reached the user. Every incident in that family — #71643 (stale
finalize snapshot), #78541 (payload-less multi-message split), #82656 (frozen
preview left with a visible cursor) — is the same failure: the consumer claimed
delivery for text the platform never rendered, so the corrective send was
suppressed and the answer was lost with no retry.

Each was fixed with a scenario test pinned to one branch of
GatewayStreamConsumer.run(). The got_done handler now has five sibling branches
that each set the suppression flags and record a turn-final payload, and nothing
checks them as a group: a new branch, or a new early `return True` in
_send_or_edit, can reintroduce the class without failing a test.

Pin the invariant instead of the branch — if the consumer offers the gateway any
signal it would trust, the complete final text must have reached the wire — and
assert it across {edit always / dies / never / lies} x {send always / never} x
{fresh-final on / off} x {clean / interrupted stream}.

The adapter records only frames that actually rendered, so an ACK the platform
drops does not count as delivery. 24 honest-transport scenarios hold the
invariant as a hard assertion. The 16 lying-transport scenarios are checked too;
the single combination that still violates it is reported as an expected
failure documenting the open exposure rather than asserting it away.

Refs #82656

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(gateway,relay): prime relay egress routing for synthetic injections + cap stale completion replay

Defect #4 from the 2026-08-09 staging incidents (upgrade-robustness):
after every gateway restart the durable async-delegation replay injected
completions correctly (post-741663cf1) but their replies bounced at the
connector — 'slack egress declined: target not routed to an onboarded
tenant'. The relay adapter re-attaches tenant discriminators
(metadata.scope_id / metadata.user_id) from per-chat caches warmed ONLY by
inbound traffic; synthetic turns race those cold caches on every deploy,
scale-to-zero wake, and crash recovery.

- relay adapter: prime_routing_cache() — feeds a synthetic event's
  session-store origin through the same _capture_scope used for real
  inbound (never raises).
- run.py injection path: prime the resolved adapter before handle_message
  (duck-typed; native adapters unaffected).
- async_delegation: 48h staleness cap in restore_undelivered_completions —
  a pending completion older than the cap is terminally dropped (payload
  stays queryable) instead of re-run as a fresh full-context turn; the
  post-restart replay of a July session burned a 102K-token context.

Also carried: JoaoMarcos44's suppression behaviour-matrix harness
(cherry-picked from #82676, authorship preserved) — 39 passed + 1 xfail
(the documented ACK-then-drop transport-honesty residue).

* test: use recent timestamps in restored-ownership fixtures

test_restore_stamps_restored_flag persisted its completion with epoch-era
toy timestamps (dispatched_at=1.0), which the new 48h replay staleness cap
correctly classifies as stale — the fixture then exercised the cap instead
of the restored-flag contract (CI slice 4 failure). Timestamps are now
now-relative; the staleness behavior itself is pinned separately in
test_relay_injection_egress_priming.py.

* fix(gateway,relay): close four review findings on the relay delivery fixes

Review follow-ups on this branch (NousResearch#82592):

1. HIGH — classifier/resolver mismatch (falsely-acknowledged loss).
   _classify_completion_target now returns "deliver" for idle-ended
   parents, but _resolve_async_delegation_session still dropped every
   non-compression-ended pin: the durable row was acked at adapter
   acceptance, then the injection died inside the pipeline with no
   retry — strictly worse than the honest terminal drop on main, and
   the delivery leg defect #2's fix depends on did not exist. The
   resolver now retargets non-user-boundary ends (idle/timeout/
   lifecycle) to the chat's current session — session_entry already IS
   the routing key's current session for the same chat — while user
   boundaries (session_reset / new_session / user_exit /
   session_switch) stay fail-closed. Both sides share one module-level
   _USER_BOUNDARY_END_REASONS so the verdict and the routing decision
   cannot drift again; a coherence test asserts deliver-verdicts
   resolve non-None across representative end reasons.

2. HIGH — drain clamp missed adapter-level spend. The effective drain
   grace budgeted drain + 3x teardown, but RelayAdapter.disconnect
   spends revocation-monitor teardown + go_idle time BEFORE the
   transport drain inside the same runner wait_for; worst case still
   blew the budget and cancelled teardown mid-drain (skipping the
   fail-pending loop). The adapter now measures its own elapsed time
   and threads the REMAINING budget into
   transport.disconnect(budget_s=...); legacy/stub transports without
   the keyword fall back to the no-arg signature.

3. P1 — _request_response racing disconnect() could register a future
   after the fail-pending loop already ran, stranding the caller for
   the full _OUTBOUND_TIMEOUT_S (30s). Fail fast with the same
   "relay transport closed" error once _closing is set.

4. P1 — _build_process_event_source's last-resort reconstruction
   dropped scope_id, so a scoped relay completion whose session-store
   origin was unavailable primed no tenant discriminator and could
   still bounce off the connector's fail-closed egress guard.
   scope_id now threads through the reconstructed SessionSource, with
   a warning when a scoped chat reconstructs without one.

All four: RED reproduced with the fix reverted, GREEN after; relay/
delegation delivery families pass (43 + 71 + 179 across the touched
suites); full tests/gateway run shows only failures already failing
identically on merge base 2446c8bb6 (env/dep issues).

* fix(gateway,relay): make pending-frame failure cancellation-safe; persist completion routing origin

Two remaining review findings on this branch (NousResearch#82592):

1. Cancellation could strand outbound waiters past the fail-pending
   loop. transport.disconnect() failed pending futures only at the END
   of the drain + three teardown awaits; a cancellation landing
   mid-drain (the runner's wait_for budget, an outer cleanup deadline)
   skipped the loop entirely and left registered futures unresolved —
   their callers blocked until _OUTBOUND_TIMEOUT_S (30s). The budget
   threading added earlier shrinks the window but is not a hard
   guarantee. The fail-pending loop (and the going_idle ack failure)
   now run in a `finally`, so no exit path — normal, error, or
   cancelled — can leave a registered future unresolved. Idempotent:
   done futures are skipped, a second disconnect() pass is a no-op.

2. Durable completions did not persist their routing origin, so the
   scope_id threading in the fallback SessionSource reconstruction had
   nothing to carry on the exact path it exists for (restart replay
   with session store + source cache gone): the async-delegation event
   producers never populated scope_id and the durable rows never
   stored it. Dispatch now snapshots the originating turn's
   scope_id/user_id/user_name from the session context
   (_capture_routing_origin — a new HERMES_SESSION_SCOPE_ID contextvar
   bound by the gateway at session-bind time alongside the existing
   vars), stores them in the existing task_json payload (no schema
   migration), and re-attaches them to all three completion-event
   shapes (live single, live batch, crash-recovery rebuild). The
   gateway's fallback reconstruction then primes both discriminators
   after a restart.

Tests: cancellation mid-drain -> every pending future resolves with
"relay transport closed" (mutation: moving the loop out of the finally
goes RED); second-pass disconnect idempotence; end-to-end
dispatch -> owner-death recovery -> event carries scope_id -> fallback
SessionSource primes it (mutations: dropping the dispatch capture or
the task_json persistence both go RED); live completion event carries
the origin. 94 passed + 1 xfailed across the delivery/delegation
suites; tests/tools delegation family 73 passed (2 collection errors
pre-existing on merge base 2446c8bb6).

---------

Co-authored-by: joaomarcos <joaomarcosdias444@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Ben Barclay <ben@nousresearch.com>
2026-08-11 09:56:13 +10:00
..
computer_use feat(vision): disclose downscale factor and crop offset for coordinate mapping 2026-08-10 01:23:38 -07:00
environments fix(attribution): correct AI_AGENT id to registry value and carry harness markers into all terminal backends 2026-08-10 11:07:22 -07:00
neutts_samples
wakewords feat(voice): bundle the trained "hey hermes" model as the out-of-the-box default 2026-07-28 07:58:16 -07:00
__init__.py
ansi_strip.py
approval.py fix(tools): harden live source checkout guard 2026-08-08 14:56:38 +05:30
async_delegation.py fix(gateway,relay): stop frozen-preview finals and dropped idle-session delegation callbacks (#82592) 2026-08-11 09:56:13 +10:00
audio_container.py refactor: extract shared audio container sniffer to tools/audio_container.py 2026-07-28 11:52:44 -07:00
binary_extensions.py
blueprints.py fix(cron): surface initial scheduler registration failures 2026-08-07 17:45:06 +05:30
browser_camofox.py fix(browser): scope Camofox session identity 2026-08-02 00:11:50 -07:00
browser_camofox_state.py
browser_cdp_tool.py fix(browser): stop stale cdp_url from stalling every startup by 10+ seconds 2026-07-27 14:32:05 -07:00
browser_dialog_tool.py
browser_supervisor.py perf(imports): lazy-load heavy SDKs off the cold-start waterfall 2026-07-29 10:54:04 -07:00
browser_tool.py fix(browser): apply safety checks to browser_exec URLs 2026-08-10 10:45:44 -07:00
browser_use_cli.py feat(browser): make Browser Use mode the default browser backend 2026-08-10 12:28:10 -07:00
budget_config.py
checkpoint_manager.py refactor: single build_subprocess_env() factory for all child-process spawns (profile + secret-scrub single owner) 2026-07-29 10:14:11 -07:00
clarify_gateway.py feat(clarify): extend multi-select to gateway text fallback and TUI bridge 2026-07-26 17:46:55 -07:00
clarify_tool.py refactor: migrate hand-rolled error envelopes to shared tool_error() 2026-07-29 10:14:00 -07:00
close_terminal_tool.py fix(agent): the desktop's tools reach it on remote and cloud backends too 2026-08-06 19:35:47 -06:00
code_execution_tool.py fix(docker): per-session container isolation and session-scoped workspace mounts 2026-08-09 14:35:02 -07:00
computer_use_tool.py feat(computer_use): align cua-driver 0.10 permission modes 2026-07-29 12:19:37 -07:00
credential_files.py fix(docker): close the cold-container and multi-backend gaps in attachment delivery 2026-08-08 05:44:18 -07:00
cronjob_tools.py fix: use is_job_runnable/effective_job_state in remaining pause-check sites 2026-08-08 13:48:00 +05:30
daemon_pool.py
debug_helpers.py
delegate_tool.py fix(docker): per-session container isolation and session-scoped workspace mounts 2026-08-09 14:35:02 -07:00
delegation_live_log.py
delegation_output_schema.py feat(delegation): optional structured-output schema on delegate_task 2026-08-07 09:07:42 -07:00
desktop_ui.py
discord_tool.py fix(tools): isolate model tools by multiplex profile 2026-08-02 00:11:50 -07:00
env_passthrough.py fix(security): scope passthrough env to routed profile 2026-08-02 00:36:03 -07:00
env_probe.py fix(runtime): resolve Hermes-managed Node and uv before bare PATH 2026-08-01 21:17:51 -04:00
fal_common.py
feishu_doc_tool.py
feishu_drive_tool.py
file_operations.py feat(file-ops): name the binary type in read_file refusals (magic-byte sniff) 2026-08-10 12:07:50 -07:00
file_state.py
file_tools.py feat(file-ops): name the binary type in read_file refusals (magic-byte sniff) 2026-08-10 12:07:50 -07:00
flux3_video_tool.py Portal free user vision fix + flux3 polling improvements (#75448) 2026-07-31 10:17:55 -04:00
focus_pane_tool.py fix(agent): the desktop's tools reach it on remote and cloud backends too 2026-08-06 19:35:47 -06:00
fuzzy_match.py feat(patch): list match locations in ambiguous old_string errors 2026-08-02 15:51:43 -07:00
homeassistant_tool.py fix(tools): isolate model tools by multiplex profile 2026-08-02 00:11:50 -07:00
hook_output_spill.py fix: route stray HERMES_HOME hardcodes through get_hermes_home() (profile + native-Windows safety) 2026-07-29 09:33:48 -07:00
image_generation_tool.py Add more FAL models to nous portal (#82019) 2026-08-08 19:59:12 -04:00
image_source.py fix(image_gen): confine generation source images to the terminal backend 2026-08-08 04:19:38 -07:00
interrupt.py
kanban_tools.py fix(kanban): guard request_review against live-claim theft 2026-08-10 12:43:46 -07:00
lazy_deps.py fix(deps): mirror aiohttp 3.14.3 pin into lazy_deps feature specs 2026-08-08 14:06:48 -07:00
managed_tool_gateway.py fix(gateway): read auth.json as UTF-8 in _read_nous_provider_state 2026-08-08 12:32:23 -07:00
mcp_dashboard_oauth.py
mcp_oauth.py perf: lazy mcp SDK import + tool-discovery mtime cache + browser_tool import diet 2026-07-29 10:02:03 -07:00
mcp_oauth_manager.py fix(mcp): make Figma remote OAuth work via DCR allowlist defaults 2026-07-28 00:53:16 -05:00
mcp_schema_cache.py polish(mcp): simplify-pass folds on the lazy-startup salvage 2026-08-03 14:24:37 +05:30
mcp_stdio_watchdog.py
mcp_tool.py perf(cli): sub-400ms warm startup — probe-mode check_fns, lazy MCP SDK, banner snapshot, parallel worktree add 2026-08-10 10:40:19 -07:00
memory_tool.py fix: finish the missing-encoding sweep — BOM-tolerant reads for user-edited stores 2026-08-08 12:32:23 -07:00
microsoft_graph_auth.py
microsoft_graph_client.py refactor: single shared Retry-After parser 2026-07-29 10:13:50 -07:00
neutts_synth.py fix(voice): reconcile NeuTTS backbone/codec GPU device strings 2026-07-28 14:07:21 -07:00
open_preview_tool.py fix(agent): the desktop's tools reach it on remote and cloud backends too 2026-08-06 19:35:47 -06:00
openrouter_client.py fix(secrets): scope-aware credential reads in core tool/gateway/web-server paths 2026-08-02 10:02:33 -07:00
osv_check.py fix(security): cache OSV malware preflight verdicts and stop double component discovery (#75485) 2026-08-01 10:47:20 -07:00
patch_parser.py refactor(file-ops): fold simplify-pass findings 2026-08-04 14:34:24 +05:30
path_security.py refactor: migrate hand-rolled error envelopes to shared tool_error() 2026-07-29 10:14:00 -07:00
process_registry.py fix(process): reject non-positive wait timeouts; distinguish log offset=0 from default 2026-08-10 00:23:41 -07:00
project_tools.py
react_to_message_tool.py fix(agent): the desktop's tools reach it on remote and cloud backends too 2026-08-06 19:35:47 -06:00
read_extract.py feat(read): jq retrieval hint in notebook output truncation marker 2026-08-10 01:28:57 -07:00
read_preview_tool.py fix(agent): the desktop's tools reach it on remote and cloud backends too 2026-08-06 19:35:47 -06:00
read_terminal_tool.py fix(agent): the desktop's tools reach it on remote and cloud backends too 2026-08-06 19:35:47 -06:00
read_window_tool.py fix(desktop): say why read_window_below cannot see the windows 2026-08-08 22:17:38 -05:00
registry.py fix(tools): bound the exception text dispatch writes into its own log line 2026-08-08 14:56:38 +05:30
schema_sanitizer.py feat(mcp): collapse const-only anyOf/oneOf unions to property enums 2026-08-07 08:58:25 -07:00
self_repo_guard.py fix(tools): keep non-bash -c invocations covered by the shell guard 2026-08-08 14:56:38 +05:30
send_message_tool.py fix(qqbot): scope the authz, startup-validation, and direct-send QQ reads 2026-08-02 10:01:16 -07:00
session_search_tool.py perf(session-search): project fields before enrichment 2026-08-03 17:50:58 +05:30
skill_linter.py fix: suppress windows-footgun false positives in linter pattern list 2026-08-08 11:12:27 -07:00
skill_manager_tool.py feat(skills): advisory SKILL.md convention linter on create 2026-08-08 11:12:27 -07:00
skill_provenance.py
skill_usage.py Merge updated tool metrics into skill metrics 2026-07-31 07:30:30 -07:00
skills_ast_audit.py
skills_guard.py perf(agent): precompile response and skill-scan regexes (#33208) 2026-08-03 09:56:36 +05:30
skills_hub.py feat(skills-hub): fall back to live repo for optional skills missing from local checkout 2026-08-09 23:14:18 -07:00
skills_sync.py fix(skills): avoid redundant bind-mount scans (#72622) 2026-07-28 04:24:50 -05:00
skills_sync_client.py fix(sync): read org state from the org endpoints, not the personal ones (#75237) 2026-07-30 22:31:42 -07:00
skills_tool.py fix: finish the missing-encoding sweep — BOM-tolerant reads for user-edited stores 2026-08-08 12:32:23 -07:00
slash_confirm.py
terminal_hints.py feat(terminal): output-pattern failure hints for common error classes 2026-08-02 15:08:35 -07:00
terminal_tool.py fix(docker): per-session container isolation and session-scoped workspace mounts 2026-08-09 14:35:02 -07:00
thread_context.py
threat_patterns.py
tirith_security.py fix(secrets): scope tier-3 credential reads (teams_pipeline, deepinfra models, FAL/XAI/VERCEL/DAYTONA/GITHUB presence, HERMES_API_KEY display) 2026-08-02 10:04:48 -07:00
todo_tool.py
tool_backend_helpers.py fix(secrets): scope tier-3 credential reads (teams_pipeline, deepinfra models, FAL/XAI/VERCEL/DAYTONA/GITHUB presence, HERMES_API_KEY display) 2026-08-02 10:04:48 -07:00
tool_output_limits.py
tool_result_storage.py
tool_search.py refactor(tool-search): drop dead fallback ladder in _available_source_summary 2026-08-03 19:11:30 +05:30
transcription_tools.py fix(stt): close idle-unload races — strong model ref, single long-lived watcher 2026-08-07 19:26:12 +05:30
tts_streaming.py fix(tts): route streaming-provider secrets through resolve_provider_secret; bound per-sentence stream bodies at 16 MiB 2026-07-28 22:31:40 -07:00
tts_text_normalize.py fix(tts): unify TTS text preprocessing behind one shared cleaner 2026-07-28 11:55:01 -07:00
tts_tool.py perf(cli): sub-400ms warm startup — probe-mode check_fns, lazy MCP SDK, banner snapshot, parallel worktree add 2026-08-10 10:40:19 -07:00
url_safety.py fix: scope private URL policy per profile 2026-07-28 14:17:45 -07:00
video_generation_tool.py Add more FAL models to nous portal (#82019) 2026-08-08 19:59:12 -04:00
vision_tools.py perf(cli): sub-400ms warm startup — probe-mode check_fns, lazy MCP SDK, banner snapshot, parallel worktree add 2026-08-10 10:40:19 -07:00
voice_mode.py fix(voice): early-exit sliding window on match, clear barge phase in finally, fix test helper 2026-08-07 14:38:02 +05:30
wake_word.py fix(wake-word): capture at native input rate 2026-08-08 13:49:24 +05:30
web_tools.py chore: remove unused imports and dead locals (ruff F401/F841 sweep) 2026-07-29 11:53:39 -07:00
website_policy.py
working_diff.py fix(tools): decode git output as UTF-8 in working_diff on Windows 2026-08-08 12:34:46 -07:00
write_approval.py
x_search_tool.py docs(xai): clarify x_search vs xurl routing without schema cross-refs 2026-07-23 21:06:47 -07:00
xai_http.py fix(auth): cover remaining auth.json readers across modules 2026-08-08 12:32:23 -07:00
xai_video_tools.py
yuanbao_tools.py