Commit Graph

193 Commits

Author SHA1 Message Date
Teknium
0112948301 refactor(agent): move the deadline-floor helpers into agent/tool_executor_deadline.py
Keeps agent/tool_executor.py under its 2,000-line cap on current main; the
behaviour is unchanged.
2026-11-15 11:49:27 -08:00
huanshan5195
e1ac37eba1 fix(agent): generic tool deadline no longer clips a tool's own timeout
Both runners bound one call at timeouts.tools.sequential_call /
.concurrent_batch, 420s by default. Several tools are handed a longer budget by
their own schema and config: `terminal` advertises a 600s foreground cap
(FOREGROUND_MAX_TIMEOUT) and honours TERMINAL_TIMEOUT, `process_manage
action=wait` blocks for its `timeout` clamped by that same setting.

So a foreground `terminal(timeout=600)` — explicitly allowed, and below the cap
that would have promoted it to a background process — died at 420s with
"Error executing tool 'terminal': timed out after 420.0s" and no output at all,
where the tool's own timeout would have returned the partial output it had
collected plus exit code 124. `process_manage action=wait` is worse: the
background process keeps running, so the model gets nothing back and re-issues
the identical call.

A tool can now declare what one call may legitimately block for
(ToolEntry.deadline_floor, a fn(args) -> seconds | None, resolved through
registry.get_deadline_floor). Both runners raise their generic deadline to the
longest floor any member of the batch declared, plus a small grace so the
tool's own timeout is the one that fires. A tool that declares nothing keeps
exactly the bound it has today, and a floor never introduces a deadline where
the generic one is disabled.

Same shape as the instances already tracked in #110035 (wait_for_human asks for
600s) and #109089 (a2a_call ignores a2a_agents.<peer>.timeout); this fixes the
two terminal-toolset ones and gives those a mechanism to declare through.

The TERMINAL_TIMEOUT clamp that ProcessRegistry.wait() applies now lives in
process_registry_wait.py next to process_manage's floor, so the two read one
rule and process_registry.py, already past the 2,000-line target, shrinks
instead of growing.
2026-11-15 11:49:27 -08:00
Teknium
b8aecc63ba fix(mcp): form elicitation asks the user for the requested fields on every surface
An MCP server that elicits a form (strings, numbers, enums, booleans) got a
yes/no approval card and then `accept` with empty content, which fails the
server's own schema. Form-mode elicitation now asks the user for each field
through the turn's clarify callback, which the classic CLI, Ink TUI, Desktop
and every messaging platform already render, validates the answers against
the requested schema (types, enum values, min/max, length, email/uri/date
formats), re-asks a wrong answer up to twice, and returns accept with typed
content, decline or cancel.

- The executor binds the agent's clarify callback per dispatched tool call
  (ContextVar); the elicitation reads it inside the call's contextvars
  snapshot on the MCP worker thread.
- A form with no fields is asked as the server's own question with Yes / No
  (the intent of #140136, delivered through the clarify surface so no
  gateway facade grows).
- No clarify callback, or a session nobody can answer (cron, -q, unattended
  platforms): the existing approval path runs and declines headless; an
  approval there fills only the consent content it can honestly fill (#105496).
- Answers go to the MCP server only; they reach the model only when the
  server echoes them in its tool result.

Co-authored-by: David Lepaux <d.lepaux@gmail.com>
2026-11-14 11:26:33 -08:00
Victor Kyriazakos
71acf56cc1 fix(plugins): a session fork holds only names that dispatch to its plugin's handler
Fork ownership came from the plugin registration ledger by exact name, but
the dispatcher serves some names before the tool registry: connector names
(connectors__<connector>__<tool>), the session's memory-provider tools, its
context-engine tools, agent-level tools, legacy aliases and the Tool Search
bridge. A plugin that registered such a name had it admitted to its fork
while the call reached a connector, memory provider or context engine.

pre_registry_route() in agent/inline_tool_executors.py now answers which
seam serves a name before the registry, using the dispatcher's own checks;
the sequential and concurrent paths read the memory-provider and
context-engine membership through the same helpers. The fork allowlist
admits a name only when that predicate returns None and the plugin owns
the live registration: at request time against the lease's session agent
(token unspent on refusal), and when the fork starts against both the
session agent and the fork that dispatches.
2026-11-13 15:30:30 -08:00
Ben Barclay
0a4a3368bd fix(sandbox): an allowed hosted tool leaves nothing on this host; skills and shell hooks are host features
- execute_code: an oversized remote stdout spills into the agent's own
  sandbox (as the generic result spill does) or is truncated inline; it is
  never written to cache/exec.
- skills: one host feature consulted by the shared loader, preload,
  auto-load, the skills index prompt, slash-command scans and skill_view /
  skills_list for direct callers. No host skill file is read in a hosted scope.
- shell hooks: a host feature, off in a hosted scope at the callback and at
  the one subprocess site. A refused hosted call is decided before Relay and
  every request/execution middleware, so no host-side callback sees it.
- background processes: a hosted record is never written to the host
  checkpoint (whoever triggers the write) and gets no host completion
  receipt; its live state stays in memory.
- other per-call artifacts of allowed tools (terminal output spill, saved
  blocked scripts, the verification ledger) are off in a hosted scope.
2026-11-11 10:22:54 -05:00
Ben Barclay
4fd509e4e0 fix(sandbox): a hosted scope is deny-by-default: one tool allowlist, one host-feature switch
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.
2026-11-11 10:22:54 -05:00
Teknium
b1c9f938e3 fix(tools): flag unknown delegate_task arguments on the sequential path too
Review follow-up:
- the sequential executor called the delegate handler directly, so an unknown
  delegate_task argument was still dropped silently there while the concurrent path
  and registry dispatch flagged it;
- the unknown-argument warning was skipped whenever the handler's error text happened
  to contain the argument's name (an action list naming `log` hid a stray `log=`
  argument). The warning is now always attached;
- the MCP control in the test used a handler defined in the test module, which the
  built-in check already excludes; it now registers a `tools` handler under an `mcp-*`
  toolset so it fails if that exemption is removed (checked).
2026-11-10 22:29:30 -08:00
Siddharth Balyan
660eb55fc8 feat(plugins): pass a compression-stable conversation_id to plugin tools and tool hooks
Plugin tool handlers, pre_tool_call / post_tool_call / transform_tool_result
hooks, tool middleware and system-prompt sections receive conversation_id
next to session_id. It is the compression-lineage root of the session (the
walk prompt_cache_scope already uses), so a rotating compression keeps it
while /new and /branch start a new one. A delegated subagent and a
background-review fork report their parent's conversation, stamped at spawn.
Memoized per physical session id: one lineage walk per segment, none per
tool call.

Plugins that keyed per-conversation state had to call the internal
SessionDB.get_compression_lineage (and walk _delegate_from markers) to
find the conversation.
2026-11-06 10:41:13 -05:00
Victor Kyriazakos
9b839d815e fix(tools): expire the tool-definitions memo with its check_fn verdicts
Operators reported MCP servers that stayed missing from tool_search and
tool_describe in a long-running gateway after the servers were healthy
again. Starting a new session did not bring them back.

get_tool_definitions(quiet_mode=True) memoizes the definitions it built
after filtering on check_fn verdicts. The memo key covers registry
generation, config fingerprint, selection and scope, but nothing about
how long those verdicts are valid. A hit returns the stored list without
calling the checks again, so the registry's 30 s verdict TTL never takes
effect. The comment above the memo says check_fn drift is handled by that
TTL, which a hit skips.

An MCP check_fn is false while the session reconnects. On reconnect the
transport skips registration when the server still has registered names,
so the registry generation does not change. A memo entry computed during
that window kept the omission until something else bumped the generation
or config. The memo is process-global, so a new session hit the same
entry. invalidate_check_fn_cache() (declaration.on_change, hermes tools)
cleared the verdicts but not the memo.

Changes:
- tools/registry.py: check_fn_verdict_window() collects the earliest
  expiry among the cached verdicts consulted inside it. A grace-served
  True expires at once, because the registry re-probes it on the next
  call. no_cache_check_fn probes are config-backed and set no expiry.
  invalidate_check_fn_cache() bumps check_fn_cache_epoch().
- model_tools.py: a memo entry expires at the earliest verdict expiry it
  was filtered on. The epoch is part of the key. Hits are unchanged.
- agent/tool_executor.py: _tool_search_scoped_names() reads the memo
  instead of a per-agent copy keyed only on registry generation, which
  kept a recovered tool uncallable through tool_call for the agent's
  lifetime.

Tests: tests/tools/test_tool_defs_memo_availability.py covers the
reporter's reproducer, natural TTL recovery, true-to-false with TTL and
failure grace, memo hits within the TTL, restricted toolset and profile
scope, and a composed AIAgent run over a loopback provider where the
bridge recovers between turns.
2026-11-02 14:54:42 -08:00
Teknium
78f7db6349 fix(middleware): preserve pre-Relay tool request snapshot
When Relay rewrites a tool call before Hermes' own pipeline runs,
tool_request middleware received the Relay-rewritten args as
original_args, while tool_execution middleware already got the model's
call (function_args). Pass function_args through as original_args so both
middleware kinds see the same pre-Relay snapshot.

Sequential chaining of request rewrites itself landed in f67d490f71
(#133159); this keeps only the remaining pre-Relay delta of #82092.
2026-10-31 22:07:49 -07:00
Teknium
614fddb694 fix(agent): persist the turn budget's spill stubs onto the flushed tool rows
Every tool result is flushed to state.db as it lands
(_flush_session_db_after_tool_progress), then _finalize_tool_batch runs
enforce_turn_budget, which swaps the largest results for
<persisted-output> previews in memory only. The gateway, TUI resume and
`--resume` rebuild history from state.db, so the next turn reloads every
spilled body in full: the request grows by everything the budget removed
and its cached prefix diverges at the first spilled row.

Live on c2c5eef149 (gui session, openrouter gemini-2.5-flash,
context_length 64000, prepare_ahead off, 6 parallel read_file of ~28.6k
chars): burst call in=41,908 with 4 stubs, then "Reply OK" went out at
in=78,255, past context_length. Preflight logged "rough estimate ~64,889
... not anchored on real usage" and deferred; that deferral is intended
(e9313f6458: provider evidence adjudicates even past-window estimates),
so the defect is the durable row, not the gate.

sync_rewritten_tool_rows carries the end-of-batch rewrite onto the rows
through the existing in-place writer (rewrite_pruned_rows): row-addressed
by _row_id, CAS-fenced on the stored row, the full body kept as an
archived searchable twin. A store without the writer or a row another
writer moved keeps today's row. Same live repro on head: in=41,649 then
in=41,685, no deferral line; CLI --resume 60,431 -> 27,153.
2026-10-25 22:28:45 -07:00
Siddharth Balyan
086984caf5 refactor(data-use): carry the requirement on the dispatch result, not a global store
The process-global _PENDING dict keyed by (turn_id, tool_call_id), its lock
and its 512 cap existed only to move a value from connector dispatch to
_commit_tool_result. _dispatch_authorized_once already owns the one real
dispatch and returns _ManagedToolResult to both executors, so it now binds a
per-call ContextVar sink around the dispatch and stores what connector
dispatch recorded on that result (and on _ToolOutcome for the concurrent
path). A batch's entries add to the wrapper's sink, so the union needs no
take/re-record. Callers that bind no sink (execute_code RPC, MCP serve)
record nothing, which removes the unbounded-growth case the cap guarded.
2026-10-21 15:46:19 +05:30
Siddharth Balyan
22fc809869 feat(data-use): route connector results that need no-training to qualifying Nous endpoints
The tool gateway now tags execute results with dataUse.requires (no_training,
zero_retention). Hermes keeps that as `data_use` metadata on the tool message
(content unchanged; a batch carries the union), persists it inside the existing
display_metadata column (no migration; /branch, resume and compaction copies
keep it), and strips it from every provider request. The Nous profile reads the
union over the outgoing messages and sends provider.data_collection=deny (+ zdr
for zero_retention) on both the chat-completions and Anthropic Messages paths;
no other provider sees it. A 403 data_policy_denied classifies as its own
non-retryable reason with no fallback and copy that tells the user to switch
model, compress, or start a new session.
2026-10-21 15:46:19 +05:30
Teknium
60affe7fe2 feat(mcp): forward MCP notifications/progress as live tool.progress events
MCP tool calls now send _meta.progressToken, so servers that emit
notifications/progress (Meshy refine, creative-lab) report live progress.
The executor binds a per-call relay; the MCP handler forwards each
notification to tool_progress_callback as a throttled (<=1 per 500 ms,
final always) tool.progress event. Surfaces:
- gateway event stream + legacy TUI gateway: tool.progress
  {tool_id, name, progress, total, percent, message} (contract registered)
- Desktop: running tool row shows '42% · <message>' beside its timer;
  plugins subscribe with ctx.onEvent('tool.progress')
- CLI: the running tool spinner shows the same text
Documented in the Desktop plugin SDK guide.
2026-10-20 04:41:58 -07:00
Teknium
4388913e20 fix(tool_search): a core tool absent from the session never says "use tool_search"
Availability is a property of the session and deferral one of the tool. With
defer: [delegate_task], a session without delegate_task was told "Use
tool_search" by tool_call and "Re-run tool_search" by tool_describe, a search
that can never surface it. A registered core tool missing from the session is
now reported through the unavailability reason (managed-worker alternative
included) before the deferral check, in tool_call, tool_describe and the
executor unwrap. MCP/plugin names keep the refresh hint (a stale catalog).
2026-10-20 03:08:38 -07:00
KoNit-K
a6f574bbce fix(memory): retain caller identity for provider tools
(cherry picked from commit 70c0fa9ccbe848d567de790296775b1aa19db3af)
2026-10-17 13:28:18 -04:00
Teknium
fb55eb6d34 fix(file-tools): patch/write_file return in milliseconds; LSP diagnostics no longer block the write
Measured on origin/main with the default LSP config (enabled, document, wait_timeout 5.0), real
handle_function_call, warm servers:
  - a clean .ts edit took 10.1s: the pre-write baseline wait and the post-write wait each ran to the
    full 5.0s, because typescript-language-server publishes nothing when a file's diagnostics stay
    empty and its first push after didOpen is a seed that never counts as fresh;
  - wait_for_diagnostics re-sent textDocument/diagnostic in a tight loop on push-only servers
    (~326k iterations per 15s of waiting on the LSP loop thread);
  - a 16k-line .py edit took 2.9s (pyright's analysis time, paid inline, plus a baseline round trip);
  - even with LSP off every write paid ~100ms for three bash spawns (probe, atomic write, sha256sum),
    and patch ran the syntax lint twice.

Now:
  - the write never waits on the language server.  One coroutine per edit (agent/lsp/edit_check.py)
    syncs the written file and waits for its verdict; only when that verdict has diagnostics does it
    fetch (or reuse) the verdict on the pre-edit text the write already holds, so a clean edit costs
    one round trip.  The write waits for that verdict only while it stays under ~80ms; otherwise the
    verdict is queued for the editing session (agent/lsp/deferred.py) and attached to its NEXT tool
    result, or the next user turn, via the plugin live-notes channel: a new row, never a rewrite of an
    earlier message, so the prompt cache is untouched.
  - checks of one file are serialized and coalesced; a newer check inherits an older one's baseline,
    so errors an earlier edit introduced are still reported unless a later edit fixed them.
  - wait_for_diagnostics sends the pull once and stops pulling on servers that reject it.
  - the local POSIX backend writes, probes and hashes in-process (tools/file_operations_native.py),
    under the native-read gate (HERMES_NATIVE_FILE_READ=0 restores the shell path).
  - patch reuses write_file's lint result instead of re-linting.
2026-10-17 04:23:04 -07:00
Teknium
f30020ed5e fix(mcp): preserve server deadlines through outer tool execution 2026-10-14 14:09:29 -07:00
alt-glitch
57fa33675f fix(agent): a plugin that goes live mid-turn is told in the next tool result, once
An install while a chat runs (the onboarding plugins card, Settings, a terminal
install through the serve backend) made the plugin's MCP tools callable at once,
but its notice waited on the one-shot turn-note channel for the next USER
message. Onboarding is one long turn, so in a live run the notice arrived six
minutes late, after the model had already failed to use the plugin.

Notices are now queued per plugin key (agent/plugin_live_notes.py; a reinstall
or update replaces the plugin's older notice) and popped onto the next tool
result before it is appended and flushed: a new row, so no cached byte moves.
The notice goes after the content, outside the untrusted-data wrapper web, MCP
and browser results get. A turn-budget spill of that result keeps the notice on
the inline row. When no tool runs again this turn, the next user message still
carries it, and a delivered notice is never sent twice.

(cherry picked from commit 41cbb879a98a5bbcf57018a5c03d6207b57b819c)
2026-10-14 00:06:58 +05:30
alt-glitch
6bcc2d4053 fix(onboarding): set_theme settling a beat tells the model the next step 2026-10-13 23:55:11 +05:30
alt-glitch
d8cefac352 feat(onboarding): setup_beat, the one onboarding-only 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).
2026-10-13 22:08:20 +05:30
Maciej Lisiewski
74f1f17a7e ci: fix RUF017, RUF018, RUF022 2026-10-08 19:54:07 +02:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
kshitijk4poor
299a1327b2 docs(agent): say skipped-result content uses str.replace for {name}
The _append_skipped_tool_results docstring still said content "is
formatted with {name}", but the body substitutes with str.replace so a
recorded interrupt reason containing braces renders verbatim. State
that, so nobody "simplifies" it back to str.format.

Gate rP finding 8 (quality).
2026-10-07 18:15:29 +05:30
kshitijk4poor
15855870b2 fix(agent): only relabel a prepared-batch abort as a batch timeout on timeout
The batch-guard tail after _poll_sequential_future is shared by the
"timeout" and "interrupted" outcomes. On a user stop (Ctrl-C, /stop, a
new message) whose prepared terminal worker had not settled after the 3s
grace, the unconditional agent.interrupt(tool_reason="terminal batch
timeout") republished the interrupt: the turn was booked
interrupted_by_system(terminal_batch_timeout), _interrupt_message (the
user's queued next message) and _pending_redirect were nulled, and the
wrong reason was re-fanned to workers.

Keep batch.close() unconditional, but only call interrupt() on the
timeout branch; on the interrupted branch the stop is already published.

Public review blocker on #133271 (@ahrazzle, executed repro; @Enough1122).
2026-10-07 18:15:29 +05:30
kshitijk4poor
764938ed74 fix(agent): publish the Ctrl-C reason before the sequential cancel hook
Gate r2 finding 3: in _run_sequential_call's KeyboardInterrupt handler,
ref.emit_cancelled() ran before agent.interrupt(..., tool_reason=user
interrupt), so the post_tool_call hook rendered its wording from an unset
reason and reported "Tool execution cancelled. Turn interrupted" while the
concurrent handler (and 47db3231e2's intent) report "User interrupt".
Publish the interrupt first, matching the concurrent handler.

The existing cancelled-hook test now pins the hook's error_message.
2026-10-07 18:15:29 +05:30
kshitijk4poor
c8634c7b64 refactor(agent): tidy the interrupt-placeholder fold-ups
Fold finding 4 (B02 gate, low): behaviour-neutral cleanups.
- close_interrupted_tool_sequence: the hidden branch only runs when the
  stripped text is empty or already the placeholder, so `stripped or
  _INTERRUPTED_PLACEHOLDER` is always the placeholder; say so.
- tool_executor: compute interrupt_skip_wording once for the cancelled
  outcome instead of twice.
- move _neutralise_replay_echo_ghosts out of prepare_iteration to module
  level (lazy imports kept inside to avoid the conversation_loop cycle).
- the finalizer test asserts the exact placeholder, not just non-empty.
2026-10-07 18:15:29 +05:30
kshitijk4poor
7112b1abc2 fix(agent): attribute Ctrl-C tool cancellation to a user interrupt
Fold finding 2 (B02 gate, sibling of #130207): both KeyboardInterrupt
handlers in tool_executor call agent.interrupt("keyboard interrupt").
With a message and no tool_reason, interrupt() records "user sent a new
message", so the skipped-call notices for a Ctrl-C claimed the user had
sent a new message. Pass tool_reason=_REASON_USER_INTERRUPT so the
recorded reason (and the rendered wording) is "User interrupt"; the
issuer stays None, so attribution to the human is unchanged.
2026-10-07 18:15:29 +05:30
kshitijk4poor
c77fc2c06f fix(agent): drop the diagnostic message from the batch-guard interrupt
The terminal batch-timeout guard still passed "terminal batch tool did not
complete" as the interrupt message. That text lands in _interrupt_message,
which the gateway (_run_agent_drain_pending) and the CLI
(_chat_resolve_interrupt) re-queue as the user's next turn, so a guard abort
injected a fake user message. Call interrupt(tool_reason=...) with no
message, and use a slug-safe reason so the issuer reads
interrupted_by_system(terminal_batch_timeout) rather than
terminal_batch_aborted:_call_timed_out.

Message-less guard shape from #130209.

Co-authored-by: Yuan Li <dskwelmcy@163.com>
2026-10-07 18:15:29 +05:30
alrcatraz
e8a478d155 fix(agent): render concurrent skip notices from the recorded reason
The sequential path was converted to interrupt_skip_wording() but the
concurrent batch kept three hardcoded user-blaming strings: the pre-batch
skip (execute_tool_calls_concurrent), the unfilled-slot notice
(_unfinished_tool_result) and emit_cancelled's hook message. A system
producer that stops a parallel batch — watchdog, lease loss, SSE
disconnect, or any segment routed through execute_tool_calls_segmented —
still told the model "skipped due to user interrupt" while
interrupt_issuer() booked the same turn as interrupted_by_system. Render
all three from the recorded reason like the sequential siblings; the
observability enums (error_type/hook_error_type) stay untouched.

Also harden the interpolation the wording rides on: _append_skipped_tool_results
substitutes {name} with str.replace instead of str.format, and
interrupt_skip_wording escapes braces in caller-supplied reasons, so a
free-form tool_reason can never raise KeyError/IndexError mid-turn.

(cherry picked from commit b785bccbca6fd997921411198d277c39d3d93261)
2026-10-07 18:15:29 +05:30
alrcatraz
3336c96b87 fix(agent): render skipped-call notices from the recorded reason
Both sequential skip sites hardcoded a user-initiated cause ("User sent a new
message" / "skipped due to user interrupt"), so any system abort that reached
them asserted an action the user never took.

Render the notice from the published reason instead: a system issuer describes
itself, and only the genuinely user-initiated reasons keep the user-facing
wording.

(cherry picked from commit 8efe429e2a485a183c7ad46522d9a5c99cef6a9c)
2026-10-07 18:15:29 +05:30
alrcatraz
1e26d03291 fix(agent): attribute the terminal batch-timeout abort to the guard
The sequential-batch timeout guard stopped the turn with a bare
interrupt(message), which the soft-path heuristic read as "user sent a new
message". The abort was therefore recorded as interrupted_by_user and the
skipped calls told the user they had sent a message they never wrote.

Pass the guard's own tool_reason so the exit reason names the real issuer and
the skipped-call notice can describe it.

(cherry picked from commit a756f781b2630ea3059c8e56df132c5d8ba35844)
2026-10-07 18:15:29 +05:30
Teknium
13eb190479 fix(tools): image-bearing tool results stay inside the turn budget; spills and refusals keep their content (review)
Greptile on b17398db089:
- `enforce_turn_budget` took `len(content)` of every tool message. An
  image-bearing result reaches it as a part list, so it counted parts,
  not characters: six 60K-char MCP results with screenshots totalled
  ~18 "chars" and nothing was spilled. Part lists now count their text
  characters and spill their largest text part (images stay inline).
- `_persist_multimodal_text_parts` spilled every text part under the same
  tool_call_id, so with a small `tool_budget.mcp_result_size_chars` the
  notes part overwrote the tool text's spill file. Each spilled part now
  gets its own id.
- When `vision.max_calls_per_image` refused every image, the refusal lines
  were appended after the handler's JSON closing brace. They now go into
  the envelope's `result`.
2026-10-06 22:54:13 -07:00
teknium1
20e25850a2 Revert "docs(agent): the authorization-gate bound follows the turn's approval window"
This reverts commit 214998ecc0.
2026-10-01 13:23:12 -07:00
Brooklyn Nicholson
214998ecc0 docs(agent): the authorization-gate bound follows the turn's approval window 2026-10-01 03:50:55 -05:00
finn763
c8d61bbc60 fix(tools): tool_call scope gate names the missing GUI surface for preview tools
Related to #120413
2026-09-30 23:07:09 -05:00
teknium1
607dff390a feat(telemetry): v5 efficiency metrics — turn cost, wasted tokens, tool output truncation, tool overhead, prompt-cache breaks
Six opt-in, bucketed shared-metrics counters (schema + contract + docs in `v5 efficiency` blocks):

- hermes.task_cost.count {provider, model, tokens_bucket, tool_calls_bucket, api_calls_bucket,
  outcome}: one row per user turn the user saw end (pre_llm_call-started, attended; forks, delegated
  children and session-close aborts excluded). Tokens = prompt+completion over the turn's primary
  calls. Tool/API call buckets reach gte_101 (TURN_ACTIVITY_BUCKETS; COUNT_BUCKETS untouched).
- hermes.wasted_tokens.count {provider, model, reason in undo/retry/interrupt, tokens_bucket}:
  emitted from the v4 friction sites (no re-detection). /undo N counts N turns; an interrupted turn
  later undone counts once; turns this process never saw read unknown.
- hermes.tool_output_truncation.count {tool, truncated, original_size_bucket}: one row per tool
  result, judged after the per-turn budget; covers the per-result spill, the turn budget, and the
  shared head/tail notice tools write when they cut their own output (original size reported).
- hermes.tool_overhead.count {enabled_tool_count_bucket, tool_schema_tokens_bucket,
  execution_surface} + hermes.tool_enabled_unused.count {toolset (shipped TOOLSETS else custom),
  used}: once per closed interactive conversation (merged across compression lineage).
- hermes.cache_break.count {provider, model, cause}: compression (committed), model_switch /
  system_prompt_rebuild (continuing conversation rebuilt its prompt), toolset_change (tool array
  changed mid-conversation, Bot Chat capability rebuild), provider_reported_miss (cold read after a
  warm read on the same route with no Hermes-known cause), cache_expired (same after >=5 min idle).
  A Hermes-known break suppresses the miss it causes. No prompt hashing.

Live-proven against a fake OpenAI-compatible server (chat -q, --resume -m, TUI gateway JSON-RPC
undo/retry/interrupt); disabled => zero telemetry files.
2026-09-28 12:43:03 -07:00
teknium1
8d8836ddb1 feat(telemetry): harness-accuracy shared metrics for the agent loop
Five opt-in counters that tune the agent loop itself, recorded through
record_process_mark (disabled config => zero rows, zero files):

- hermes.file_edit.count: tool, mode, outcome, match_strategy. The fuzzy
  matcher reports the strategy that landed (or no_match / ambiguous) into a
  context-local probe opened only around the patch/write_file handlers, so we
  learn which strategies earn their keep without counting internal callers.
- hermes.loop_guard.count: provider, model, signal, detector. Hooked where
  the guardrail already warns/blocks/halts and at turn end for the iteration
  budget; latched once per turn per (signal, detector).
- hermes.tool_recovery.count: provider, model, tool, next_tool,
  next_outcome. One row per failed tool call, resolved against the model's
  next round (same tool first) or the turn end (no_tool_call / gave_up).
- hermes.terminal.outcome.count: backend, command_kind, outcome. The kind is
  a table lookup on the first program word, never the text. Hermes' own
  deadline/interrupt now set hermes_timed_out / hermes_interrupted on the
  backend result, so a command's own `exit 124` reads nonzero, not timeout.
  Disjoint dims from hermes.execution_backend.count (served vs not).
- hermes.model_reply_issue.count: provider, model, issue. Refusal and
  truncation only from the structured finish reason; empty/reasoning_only
  from the normalized message; issue=none per response as the denominator
  (model_route counts attempts and files empty replies as failures).

Background review / curator loops and _host_local / unmetered terminal
calls never count. Helpers live in shared_metrics_harness.py; call sites
are one or two lines each.
2026-09-28 12:43:03 -07:00
kshitijk4poor
622a296f7a fix(agent): keep the todo predicate off the model_tools/executor import path
is_todo_tool_call lived in agent/tool_executor.py and went through
canonical_tool_name, which imports model_tools. TUI resume calls it from
_todo_state_from_history on the RPC path, so the first resume in a
gateway loaded ~405 modules (2-3s) synchronously. tui_gateway/server.py
and run_agent.py also imported agent.tool_executor at module level,
adding ~142 modules to every TUI/desktop launch and breaking run_agent's
lazy-forward rule.

The predicate now lives in tools/todo_tool.py, which both startup paths
already load. It matches TODO_TOOL_NAMES ({TODO_SCHEMA name} + the legacy
aliases) and imports the bridge parser only when a tool_call entry's
args mention "todo". model_tools._LEGACY_TOOL_ALIASES derives its todo
entry from TODO_LEGACY_ALIASES, so there is one source of truth ("todo"
is the only alias mapping to todo_list). The live tool.complete path in
tool_progress uses is_todo_tool_name and the hand-kept _TODO_TOOL_NAMES
tuple is gone. The server.py noqa import is replaced by a function-local
import next to MAX_TODO_RESULT_CHARS, so a pruned name can't be swallowed
by the broad except. run_agent imports lazily. The dead TypeError arm is
dropped, and field reads use message_sanitization._tc_field.
agent/tool_executor.py is back to its pre-stack state.

Co-authored-by: JoaoMarcos44 <joaomarcosdias444@gmail.com>
2026-09-27 18:34:12 +05:30
kshitijk4poor
3d3c1c1223 fix(agent): pair bridged tool_call todo results via one shared predicate
todo_list is in the default tool_search defer list, so with tool search
active the model calls it through the tool_call bridge and the transcript
keeps function.name == "tool_call". The canonical-name pairing check never
matched those, so todos were still dropped across turns (#124960) in every
tool-search-active session, and the TUI resume snapshot had the same gap.

Add agent.tool_executor.is_todo_tool_call: canonicalizes legacy aliases and
peels the bridge from the recorded arguments with normalize_tool_call_entries
(exactly one entry required). It deliberately does not use
resolve_underlying_call, which reads live config and could disagree with the
defer list in force when the history was written. run_agent and
tui_gateway's _todo_state_from_history now share it; the canonicalizer is
public (canonical_tool_name) since it is now used across modules.

Co-authored-by: JoaoMarcos44 <joaomarcosdias444@gmail.com>
2026-09-27 18:34:12 +05:30
Hermes Agent
c42c90552e fix(agent): re-gate later terminal approvals after an earlier batch failure (#113158)
Desktop terminal batching pre-collects the approval for every command in
a run before any of them executes, so the user consents to a batch in
which all commands are expected to run. When an earlier command then
fails (or is denied/blocked), that informed consent no longer describes
the world the later commands will run in — yet the executor still
consumed the pre-made decision as though nothing had happened.

- _TerminalBatch.failure_seen: set by the sequential publisher after a
  slot's failed (or blocked) result is committed — i.e. after the failure
  the model actually sees, never from a wedged worker's late result.
- consume_prepared_guard drops the prepared decision for any later slot
  once a failure is published and returns None, so the guard runs its
  live flow again: tirith scan, allowlist, and a fresh human approval
  request when the command still warrants one. Nothing is auto-denied
  and an explicit denial of the failing command remains authoritative.
- The flag is sticky for the batch: a later success must not un-stale an
  approval collected before an even earlier failure.

Success-path batching is unchanged: with no failure, prepared decisions
are consumed exactly as before (byte-for-byte the same flow).
2026-09-26 21:00:46 -05:00
kshitijk4poor
94119759c6 refactor(agent): derive the pruned-args recovery hint from the marker prefix
Final-gate reuse/quality: the refusal message re-typed the marker prefix
the new compression_marker leaf exists to own. Also pin that the bare
prefix alone is not an artifact (a prefix-only matcher now fails a test).
2026-09-24 16:29:19 +05:30
kshitijk4poor
b969fdadfb refactor(agent): carry one blocked-call body through the pruned-arg check
One block decision travelled as block_message + block_error_type +
block_payload, with _blocked_tool_result re-deriving the message from the
payload it was also handed, and _pruned_tool_arguments_block existing only to
package two module constants for its single caller. Replace message+payload
with a single block_body dict: scope/plugin blocks become {"error": msg}
(byte-identical to before), the pruned-arg block is built inline, and
_blocked_tool_result serialises whatever it is given. What the model sees is
unchanged.

Also: the _dispatch_authorized_once docstring now lists the pruned-arg check
between pre-hooks and guardrails where it actually runs, and the refusal text
gains one static sentence telling the model how to legitimately remove a
marker that already landed on disk (match the HERMES-CONTEXT-COMPRESSION
prefix instead of quoting the full marker, which the guard would refuse).
2026-09-24 16:29:19 +05:30
kshitijk4poor
81561552f2 refactor(agent): check pruned tool args once, after plugin arg rewrites
Two identical checks (before and after pre_tool_call hooks) doubled the
traversal for no extra safety: whatever reaches dispatch is the
post-hook argument set, so a single check placed after _pre_tool_block
covers both copied markers in the model's original arguments and
markers introduced by plugin modify hooks.

Co-authored-by: Kevin Rajan <7121943+kvnloo@users.noreply.github.com>
2026-09-24 16:29:19 +05:30
Kevin Rajan
ce2a747be9 fix(agent): block pruned content before effectful dispatch
(cherry picked from commit ff9acb30510389561a2706653ad9f7f2aef99895)
2026-09-24 16:29:19 +05:30
BearHuddleston
6828ffa70f fix(desktop): persist edit previews before tool-result flush 2026-09-23 22:45:56 -07:00
Siddharth Balyan
70f5dc5f46 feat(connectors): the backend API for the desktop Connectors page; connect an app without a chat session (#115191)
* feat(connectors): the backend serves a connector's tool list, cached for 24 hours

The Connectors page opens one app and shows every tool it has. The backend
had no way to read that list.

- `tools/connectors/portal/`: a client for the portal's tool-list route and a
  JSON cache under the Hermes home, one file per portal origin and connector.
  An entry is fresh for 24 hours. After that the read revalidates with the
  stored ETag: 304 keeps the list, 404 deletes the entry, an upstream failure
  serves the stored list marked stale, and a 401 never serves the cache.
- `connectors.tools {slug, refresh}`: account-level, routed by `profile`, no
  chat session. Errors carry a fixed `reason` from one closed set on the rail.
- Every connector model that is not operation state moves into
  `tui_gateway/contracts/connectors.py`. Handlers that no chat session owns
  live in `tui_gateway/methods_connectors_account.py`.

The wire model is tolerant: an unknown facet reads as unclassified and one odd
tool never blanks a connector.

* feat(connectors): catalog, accounts and member tool rules by RPC

The Connectors page needs the app catalog, the connected account of one app,
a way to disconnect it, and the member's own on/off rules. None had an RPC.

- `connectors.catalog`: name, description, category and logo of each app.
- `connectors.accounts`, `connectors.accounts.remove`: read the accounts at
  the tool gateway and remove one by id.
- `connectors.policy.get`: the rule layers that apply to the member, widest
  first. The body is a union on `mode`, so a reader can name who turned a
  tool off.
- `connectors.policy.set`: one change, a union on `type` (the tools of one
  connector, or one connector on or off), with the revision the user saw. A
  stale revision answers `POLICY_CONFLICT`. The backend composes the upstream
  write in one pure function, so no renderer learns the upstream rules.
- Bundled MCP manifests can name their hosted twin with `connector:`, so the
  page can show one card per app.

* feat(connectors): connect an app without a chat session

Every connector RPC took a `session_id`, and a connect that did not come from
the model's tool call minted a link with no watcher. The Connectors page has
no chat session, and its card must flip to connected by itself.

- `connectors.list`, `connectors.connect`, `connectors.operation.status`,
  `connectors.operation.wake` and `connection.respond` take `owner`, a union
  on `type`: `session` (today's behaviour and authorization) or `account`
  (routed by `profile`, authorized by the live transport like `mcp.*`).
  `session_id` is gone from these params; every desktop caller sends `owner`.
- An account connect runs the same operation lifecycle on a background
  thread, under the profile's scope, so the watcher reads the account and
  settles the operation. A second connect for an app that is already
  connecting returns the open operation and mints nothing.
- `connection.update` carries `owner`. An account operation has no session to
  address, so its updates go out on the session-less broadcast path.

* feat(mcp-catalog): eighteen more bundled entries name their hosted connector

A bundled MCP entry and a hosted connector for the same app are one card
on the Connectors page only when the manifest names its hosted twin.
Linear and Notion had the field. These entries get it too: airtable,
asana, attio, calendly, dropbox, figma, railway, supabase, todoist,
betterstack, canva, cloudflare, datadog, intercom, neon, sentry, stripe
and vercel. Atlassian maps to two hosted connectors and Prisma Postgres
is not clearly the same app, so both stay without one.

* refactor(connectors): the account handlers share one gate, one params model and one write table

The six account-level handlers each repeated the availability gate, the
auth catch and the catch-all reply. One decorator now owns that, and each
handler validates its params with its contract model instead of a ladder
of isinstance checks. The five connection RPCs share one guard for the
unexpected-failure reply.

The four write composers for the member rules were the same function
with a different list key and polarity. They are one table now.

The owner union lives in contracts/common.py, so the params side and the
event side stop declaring it twice and the import cycle is gone.

An account operation start carries one event and a flag, so the wait for
the sign-in link blocks instead of polling every 50 ms. run_operation
loses its two account-only parameters; drive_operation is the second
entry point.

Tests: four deleted (they exercised pydantic or the mock), three merged
into tables, two added (a client that still sends the old top-level
session_id is refused; all six account RPCs run off the server loop).
The shared reply helper and the HTTP and managed-client fakes move to
one place each. Comments are one line or gone.

* fix(connectors): a missing tool-list route reads as "unavailable", not "connector gone"

The tool-list read treated every 404 as the portal's "this connector is
not in the catalog" answer. It deleted the cache entry and answered
CONNECTOR_NOT_FOUND, so a page would offer to remove an app that is
connected and works. A portal that does not serve the route yet answers
a bare 404 for every app.

Only the portal's own {"error": "connector_not_found"} means the
connector is gone. Any other 404 is now a tool-list outage: the cached
list is served as stale, or the RPC answers TOOLS_UNAVAILABLE.

* fix(connectors): a connect from the page returns to the app after sign-in

The sign-in link carries a return target only when the session's surface
is the desktop. A chat session binds that surface. An account-owned call
has no chat session, so nothing bound it: the link was minted without a
return target and the browser ended on the portal's done page instead of
coming back to Hermes.

Every account-owned call now runs with the process's own surface bound,
next to its profile scope. The operation thread copies that context, so
the first link and every reissued link carry the return target and the
operation id.

* test(connectors): defer the new connector RPC coverage

The tests for the new account RPCs, the portal client, the tool-list cache
and the rule composer leave this PR and come back in one later change, after
the API is settled. The same was done for #111008.

Kept: the edits that existing tests need because the five connection RPCs
now take `owner` instead of `session_id`, and the rename of the managed
client seam.

Removed: six new test files, their two fakes and the gateway conftest, and
the new cases in test_mcp_catalog.py, test_connectors_gateway_client.py,
gateway-rpc.test.ts and notifications.test.ts. Reverting this commit restores
all of them.

* fix(cli): the connection panel hands the tool thread back at once

The classic CLI's connection callback waited on a queue for the user's first
decision. The operation's watcher starts only after the callback returns, and
the watcher is what polls a hosted account, runs the 300-second deadline and
sees Ctrl+C.

For a hosted connector the panel opens on the sign-in link, where the only
key that filled the queue was Cancel. The account was never polled: the user
signed in, the panel never changed, and Esc reported the app as skipped.
Ctrl+C set the interrupt flag but left the thread parked on the queue, so the
turn never ended.

The callback now opens the panel and returns, as the gateway's callback does
for the desktop and the Ink TUI. The panel's actions already reach the
operation through apply_answer on the UI thread, so the queue is removed. An
install with a form still waits for Connect, because the backend starts no
work for a pending row. Ctrl+C now settles the operation as `interrupt`, and
open rows become `not_connected`.

Checked on the e2e rig with the fake tool gateway: hosted connect completes on
the third status read; Ctrl+C ends the turn and the polling stops; an MCP
install with a plain and a secret field still saves config and both values.

* fix(connectors): "run it again" lives in the library, so the classic CLI can use it

Making a new sign-in link for a failed or expired hosted connector was
implemented only in the JSON-RPC layer (`_reissue`). The classic CLI does not
go through JSON-RPC: its Connect button on a failed row called apply_answer,
which does nothing for a hosted operation because it has no MCP runner. The
panel showed "Waiting…" until the deadline.

`tools.connectors.run.reissue(operation, names)` now holds the checks and the
per-kind action, and returns a refusal reason or None. The gateway maps each
reason to the same JSON-RPC error as before. The CLI calls it for a hosted
row; a refusal is shown on the row. MCP rows keep their path, because Connect
on a failed MCP row re-sends the form values.

Checked on the e2e rig: a scripted failed sign-in, then Connect: a second mint
with `reinitiate: true`, a new link with a new connection id, then connected.

* feat(connectors): the account list and disconnect go through the portal

`connectors.accounts` and `connectors.accounts.remove` called the tool
gateway. They now call the portal's account-management routes
(`GET /api/v1/connectors/accounts`, `DELETE /api/v1/connectors/accounts/{id}`),
which apply the organisation membership checks and write the disconnect audit
row. There is no fallback to the gateway when the portal is unavailable, and a
removal is never retried.

The read of ONE account stays on the gateway (`GET v1/connectors/accounts/{id}`):
the portal has no such route, and the operation watcher polls it once per second.

`ConnectorClient.list_accounts` and `delete_account` are removed. The removed
account's reply model carries `connector`, which both services send.

* fix(connectors): the account RPCs answer what the portal really sends

Checked against the portal source and against the staging and production
services.

- Errors are read from the upstream error code, not the HTTP status. A rule
  write answered 409 for a stale revision and for a user with no organisation;
  both read as "the policy changed". `org_required` is now `ORG_REQUIRED` and
  403 `no_access` is `ORG_ACCESS_DENIED` on every account RPC; only a rejected
  sign-in is `NEEDS_NOUS_AUTH`. `connectors.list` and `connectors.connect` with
  the account owner map these too.
- `connectors.policy.get` and `connectors.policy.set` carry `effective`: the
  portal's own result for this user, with its stamp and without provider or
  subject ids. Nothing is recomputed locally.
- A rule write needs the revision the user saw: `expected_revision` is required
  and must be a revision string; a bad one is refused before any HTTP call.
- A tool row carries `no_auth`; a list without the upstream flag is an invalid
  answer, not `false`.
- `connectors.accounts.remove` returns the app of the removed account. An
  invalid id is `INVALID_PARAMS`.
- The tool-list cache is per signed-in member (a hash of the token's `sub`),
  so two Nous accounts on one profile do not share entries.
- A malformed slug is a local error, not a 404 from a server nobody called.

Live, staging: no revision and a malformed revision refused locally; a good
revision wrote one disabled Gmail tool and returned it in `effective`; the
same revision again answered `POLICY_CONFLICT`; the list row showed the tool;
the restore brought the member rules back to the start. Live, staging and
production, read-only: all 60 tool lists (5483 tools) parse.

* fix(connectors): the operation RPCs match their contract; a settled card cannot start a new link

Found by two adversarial reviews of the RPC layer and its types.

- `connectors.connect` from a chat session with no open operation is refused
  (`UNKNOWN_OPERATION`). It used to call `manage_connections` through the tool
  registry with no card: it made a link nobody watched, returned a reply
  without the required `settled` field, and named an operation that was never
  registered. There is one way into an operation: the agent's call, or the
  account owner's `connectors.connect`. "Run it again" inside an open
  operation is unchanged.
- `connection.update` for a session is routed by session key AND profile; two
  profiles with the same key no longer cross-deliver a sign-in link. The event
  payload gets the same redaction as the RPC replies.
- `connection.respond` runs on the long-handler pool: an approval can start MCP
  OAuth discovery, which blocked every RPC of the gateway while it ran.
- `connectors.list` rows are a closed snake_case model: `connector`, `enabled`,
  `connected`, `connection_status`, `status_reason`, `gateway_disabled_tools`.
  The last one is display data: the gateway enforces the rules, the backend
  only passes the list on. The phantom `name` and `description` are gone, and
  the desktop uses the generated types instead of hand-written copies.
- `tools_listing` (model-only data) no longer rides on `connectors.operation.status`.
- `unavailable` is removed from the target states and settle reasons: nothing
  produces it. The contract generator now fails when a contract enum and its
  domain enum differ.
- `ConnectorErrorReason` is part of the generated TypeScript and OpenRPC.
- The desktop sends `connection.respond` on the socket that holds the session,
  as wake and reissue already did.
- Contract violations are logged every time, at error level.
- An account connect whose prepare step is slow returns the live operation
  instead of an error while the operation keeps running.
- The MCP-manifest `connector` field leaves this PR (it moves to a later one
  on top of the catalog-reader change). `hermes_cli/mcp_catalog.py` and
  `optional-mcps/` are untouched by this PR again.

anti-slop: no net-new findings (15 touched files).

* fix(connectors): the model gets no sign-in link wherever a card exists; side agents cannot connect

The flag that tells the model "a connection card exists" was the session
platform (`== "desktop"`). The Ink TUI and the classic CLI also draw a card,
so there a connector call on an unconnected app handed the model the raw
`connect_url` and told it to pass the link to the user.

- The agent turn now declares how a link can reach the user
  (`tools/connectors/turn.py`): CARD when the agent was built with a
  connection callback, SIDE for a subagent or a background turn, LINK for a
  headless run (`-q`, cron, ACP, api_server, messaging). It is set once per
  tool batch in the agent loop and read by the connector dispatch path, which
  never sees the agent. The session platform decides return-to-app only.
- CARD: the result carries `connect_card_available` and our hint, never the
  link and never the gateway's own hint.
- SIDE: subagents (`delegate_tool`), gateway background turns and the classic
  CLI `/bg` are built with `side_agent=True`. They hold no `manage_connections`
  tool on any path that derives the tool list, and a connector call on an
  unconnected app gets no link, only "report this to the main agent".
- LINK is unchanged.
- The hosted path with no card builds a detached operation, as the MCP path
  does, so no `connection.update` is emitted for an operation no client asked
  for. Names and docstrings that said "off desktop" now say "no card".
- A settled card is dead on the desktop: `reissueConnectionTarget` and
  `respondToConnectionRequest` share one guard and send nothing for a settled
  or unknown operation.
- The model-facing settled result no longer carries `connection_id`; the model
  repeated it to the user.

Shown on the real clients with a real model (rig, fake tool gateway): Ink TUI
and classic CLI get `connect_card_available` and no link, the model opens the
card, the account connects, the retried call succeeds; `-q` still gets the
link; a subagent and a background turn have no `manage_connections` and get
the no-link hint; on the desktop a card settled with Continue has no enabled
control and sends no RPC.

* feat(tools): every call made through tool_search + tool_call shows a real label on all three clients

A bridged call showed as a generic `tool_call` row in the Ink TUI and as
`⚡ tool_call` in the classic CLI, because the display looked the name up in
the tool registry and bridged names are made at run time. The desktop labelled
only batches that were all hosted connector calls, by parsing names itself.

- `tools/tool_labels.py` is the one place that turns a bridged call into a
  label: kind, app, action, emoji and text. Hosted: `connectors__gmail__GMAIL_SEND_EMAIL`
  → "Gmail · send email". MCP: "Linear · list issues". A local deferred tool
  keeps its own emoji, verb and primary-argument preview. A batch gets exactly
  one label per entry, always; an entry with no name gets a generic label.
- Classic CLI: one row per inner call; the duration on the last row; the
  failure text on the row of the call that failed. With friendly labels off
  it prints what it printed before.
- Gateway: tool start, progress and complete events and stored transcript rows
  carry a typed `labels` field. It does not depend on the classic CLI's
  display setting. Clients no longer parse tool names.
- Ink TUI: rows from the labels; the verbose trail keeps Args and Result.
- Desktop: `ConnectorExecution` renders hosted, MCP and mixed turns from the
  labels, one row per call. The labels reach the row under a key no tool
  argument can use. The connect card it drew under a failed tool result is
  gone: after `CONNECTION_REQUIRED` the one way in is the agent's own
  `manage_connections` call.
- `tool_search` and `tool_describe` rows read "Searching tools · <query>" and
  "Reading tool details · N tools".

Shown on the real desktop (video and screenshots), the Ink TUI and the classic
CLI with the rig: hosted rows, MCP rows, a two-entry batch, a failed entry, a
`CONNECTION_REQUIRED` row with no card under it, labels after a reload, and the
desktop rows with the classic CLI setting off.

* fix(connectors): the model can tell "hosted tools unavailable" from "no such tool"; manage_connections routes MCP names correctly

- A failed hosted search or describe used to return nothing, by design, so the
  model saw only local tools and told the user that a connected app was
  missing. The local results are unchanged; when the hosted leg failed, the
  `tool_search` and `tool_describe` results carry
  `connectors: {status: "unavailable", reason: "unreachable" | "sign_in_expired"}`
  and one hint line. A rejected token is `sign_in_expired`; an entitlement
  refusal or a shut gate adds nothing. `tool_describe` no longer lists those
  names under `not_found` next to "search again".
- NS-932. The description now says which side a name belongs to: a bare name
  is a hosted connector account; `mcp: true` only when the user asks for an MCP
  server, a local server or an install, or when the name exists only in the
  catalog; connect and reconnect are hosted verbs, install, enable and
  authorize are MCP verbs. It names the three clients that draw a card.
- A misrouted target is refused with the call that works. Only when the
  gateway does not know the connector (confirmed on that failure path) and the
  name is a catalog entry does the target fail with "X is a local MCP server.
  Call manage_connections with action install ...". It is a per-target
  outcome: other targets of the same call keep their links and their card. A
  vendor failure on a name both sides know stays an ordinary failed row. The
  MCP side mirrors it, and never for an entry that is only not installed.
- "Do not re-ask after a skip or a timeout" no longer stops the model when the
  USER asks for that app again; the description and the settled-result notes
  say so. A builder saw the model refuse a direct user request.

Shown on the Ink TUI and the classic CLI with a real model: a dead gateway and
a 401; "connect fxmail" goes hosted; "install the fx-noauth MCP server" goes
MCP; "connect fx-noauth" reaches the MCP install card in one corrective round
with no hosted mint; a two-target call where one is misrouted still connects
the other with exactly one mint.

* fix(tui): the connection card answers every key, shows what is happening, and is dead once settled

Reproduced on the real Ink TUI with the rig, then fixed:

- The keyboard was dead during the sign-in wait: the card kept a `submitting`
  flag that the normal OAuth path never cleared, and Esc went through the same
  guard. The in-flight state now belongs to the answered row and clears when
  that row moves, when any later frame of the operation arrives, or after
  five seconds. Esc skips the row in every phase; Ctrl+C interrupts the turn
  (the input handler had no branch for this overlay); Shift+arrows scroll the
  transcript and the card ignores them; arrow keys no longer move the text
  cursor and the field focus at once.
- The card was lost at turn idle: the overlay flag was cleared while the
  operation stayed in the store, and a resume dropped the pending card. The
  flag survives idle, a resume shows the pending card again, a session switch
  clears it.
- States with no branch: `not_connected` and a row with no link fell into the
  credential form; `expired` vanished with no note. The title and the row text
  now name the action (connect, reconnect, install, enable, authorize); a
  failed or expired row with no fields offers Try again / Skip; a failed row
  WITH fields reopens the form over the typed draft, with the failure above it.
- A settled card is dead: at settle the overlay closes and one transcript line
  per app states the outcome. A settled or dismissed operation id is
  remembered, so no replay or resume can reopen its card. Esc in the last
  "Finishing…" moment hides the card and still writes the outcome lines.
- A failed `connection.respond` and a browser that did not open are shown on
  the card in one sentence.

Also: `tui_gateway/connector_payload.py` redacted the BOOLEAN `secret` flag of
a credential field to the string "[REDACTED]". On the desktop every credential
field therefore rendered as a password and lost its prefilled default. A
boolean is no longer redacted.

* chore(connectors): remove the comments and docstrings this branch added

Deletions only. Kept: tool directives (`# noqa`, `// eslint-disable`, ...),
`// SAFETY:` lines, and the docstrings of the contract models under
`tui_gateway/contracts/`, which become the descriptions in the generated
OpenRPC and TypeScript.

Checked that no code changed: every Python file has the same AST as before
once docstrings and `pass` are ignored (62 files), and every TypeScript file
prints the same with comments stripped by the TypeScript printer (32 files).
The generated contract files are unchanged.

* fix(connectors): a card restored after a reload answers again; every account RPC names auth and org failures

Found by the end-to-end runs on the pushed head.

- Desktop: after a window reload, Continue on the restored card sent nothing.
  The answer looked up the backend that holds the session with the runtime
  session id, the lookup wants the stored id, and a failed lookup returned
  silently. When the lookup gives no owner the answer now goes out on the
  window's active socket, which is what main does.
- `connectors.policy.get` answered `POLICY_UNAVAILABLE` for a rejected sign-in,
  a refused scope, a non-member and a missing organisation alike: the handler
  runs with the gateway's globals and did not import the reason enum, so its
  own error mapping raised. `connectors.accounts.remove` caught auth failures
  in its generic branch. `org_required` was mapped on `policy.set` only. All
  six account RPCs now answer `NEEDS_NOUS_AUTH`, `FORBIDDEN_SCOPE`,
  `ORG_ACCESS_DENIED` and `ORG_REQUIRED` for those four upstream answers.
2026-09-22 13:57:51 +05:30
thomasscottbeck-sudo
188f0d4251 fix(plugins): fire transform_tool_result for agent-runtime tools
Agent-runtime tools (todo_list, session_search, memory, clarify,
delegate_task, the preview/terminal readers, context-engine and
memory-provider tools) are dispatched inline and never reach
handle_function_call, which is the only place transform_tool_result ran.
A registered transform silently did nothing for them, although the hook
is documented as applying to every tool.

Apply the same helper on both runtime executor paths, after the terminal
post_tool_call so the observer still sees the untransformed result:
the concurrent path in invoke_tool's inline branch, and the sequential
path in _publish_sequential_result. The sequential registry dispatch
marks itself transform_applied so handle_function_call stays the single
invocation for registry tools and nothing double-fires.

The sequential result classification (failure detection and the logged
result length) moves below the transform so it reads the result the
model actually sees, matching the registry and concurrent paths.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit bc31efff0a6e2fd8177edd73cfe1a7112df9f78d)

Fixes #72836
Salvages #115397 (thomasscottbeck-sudo); supersedes #72860 (webtecnica, earliest — sequential path only).

(cherry picked from commit d6b5e969b3e08a557a62ed85c8b828537857b3d8)
2026-09-21 23:56:25 -07:00
kshitijk4poor
a8a81f4cb9 refactor: log the dead compression worker's exception once; trim guard comments
_await_worker_within_budget now emits one INFO line with future.exception()
when it takes the stall path for a worker that already died, so the log shows
WHY the fallback chain was entered instead of silently returning (False, None)
— previously the only trace was the absence of "still streaming" lines.

The three 5-7-line comment blocks added by the #117261 pick restated the same
alias fact each time; each is now 2 lines citing #63892 and the 3.11 alias once.
No behaviour change beyond the log line.
2026-09-21 21:34:44 +05:30
Trevor Nash-Keller
8305113328 fix(compression): don't mistake a worker's TimeoutError for a poll timeout
On Python 3.11+ concurrent.futures.TimeoutError IS the builtin TimeoutError
(asyncio.TimeoutError and socket.timeout alias it too). Poll loops shaped like

    try:
        return future.result(timeout=slice)
    except concurrent.futures.TimeoutError:
        ...keep waiting...

therefore cannot distinguish "the wait slice expired" (worker alive) from "the
worker raised TimeoutError" (worker dead). auxiliary_client raises a bare
TimeoutError when a summary stream stalls, so this is reachable in production.

When it happened the host re-waited on an already-settled future. result() then
returned instantly every iteration, spinning at ~2k iterations/sec and logging
"Context compression still streaming" about a dead worker, until the entire idle
budget elapsed. One session burned 535s and wrote ~90k duplicate log lines
(15.6MiB) before failing with context_compression_timeout, and every later turn
re-entered the same path.

Guard each loop with future.done(): a settled future never becomes unsettled.
- _await_worker_within_budget: take the stall path at once, so the configured
  fallback chain is actually reached instead of after a 120s false stall.
- _await_in_flight_commit: re-raise the worker's exception. This loop had no
  ceiling, so a dead worker spun forever.
- tool_executor._poll_sequential_future: same, and with deadline=None it also
  span indefinitely.

Non-timeout worker exceptions still propagate unchanged, and a live worker still
polls exactly as before.

Regression tests pin all three. Against unpatched code the two wait tests fail
and the commit-wait test hangs until the 300s harness SIGKILL, reproducing the
infinite loop directly.

(cherry picked from commit 274457304ce0393407574fe4e43c4a450f20bac3)
2026-09-21 21:34:44 +05:30