Commit Graph

94 Commits

Author SHA1 Message Date
Victor Kyriazakos
5cba2718c0 fix(agent): preserve completed replies before terminal silence
Reuse an eligible housekeeping reply before output transforms, persistence
and receipt generation when the local host requires a reply. Keep permitted
silence and marker-only warnings unchanged.

Reconcile recovered stream finals with their own delivered segment,
including transformed text and split previews. Treat short recovered
answers as successful replies and sanitize them before persistence.

Cover local gateway composition, output hooks, recovery, receipt identity,
stream transports and the unchanged silence controls.
2026-10-28 19:29:23 -07:00
Teknium
674f2d680d fix(desktop): a turn stopped during its tool run keeps its stopped mark once stored
A Stop during a tool run leaves no reply: the finalizer closes the tool tail with
the empty hidden placeholder row and wrote no stopped mark anywhere, so once the
stored copy replaced the live one (the refresh after the stop in a short chat, a
later turn's refresh in a long one, every reload) "Response stopped" was gone.

The user-stop callers of close_interrupted_tool_sequence (the finalizer's
interrupted close and abort_turn_on_interrupt) now record interrupted on the
closing row, as turn_api_call.py does on a partial reply; truncation/overflow
closes stay unmarked. Hydration lends that empty row's mark to the bubble it
closes, the same rule as a reply folded into its tool bubble.
2026-10-27 11:50:16 -07:00
Hugo Alves Pereira
32a636bc8d feat(agent): opt-in prepared compaction (compression.prepare_ahead)
With compression.prepare_ahead (default false), once the provider-reported
prompt size is within 12% of the context window below the compaction
trigger, the turn loop starts a background pass before a tool batch runs
and at turn end. The pass plans the same window compress() plans and runs
the same summariser on a copy of the compressor and of the window rows.
The pass itself never rewrites the live transcript, system prompt or
prompt cache; the transcript keeps growing normally meanwhile.

At the next automatic threshold compaction, compress() splices the
finished candidate when the head boundary is unchanged, its boundary is no
later than the fresh tail cut, and the transcript up to that boundary is
unchanged (ignoring what the no-LLM prune rewrites). Messages after the
candidate boundary stay outside the summarized region and go through the
existing tail handling. Everything else, including a pass that has not
finished, manual/focus compaction, overflow recovery and memory-provider
summary context, compacts inline as before. A running pass is never
waited on and loses the right to publish once compaction or a session
boundary overtakes it. A failed pass backs off further passes without
touching the live failure cooldown.

State is per compressor and in memory only. Plugin context engines, Codex
app-server, native Responses compaction, micro-compaction and
background-review forks are not prepared. With the flag off no state is
created and compress() takes its existing path.
2026-10-25 22:55:11 -07:00
Teknium
ad249d9cac fix(hold-stream): a held reply kept as the budget fallback, and its codex commentary, in history
Two more ways a held turn (hold_stream=True transform_llm_output) left history
out of step with what the user got:

- When verify-on-stop or pre_verify sent the answer back on the last allowed
  call, _append_interim_answer had already flushed it as a hidden row. The
  finalizer reused it as the budget fallback and transformed it, but the row
  was settled: _store_rewrite_on_tail skipped it and _close_transcript_tail
  added nothing (the tail already held assistant text), so reopening the
  session lost the reply. A held turn's sent-back answer now flushes with the
  turn instead of at once (the user never saw it), and when the turn ends on
  it _store_rewrite_on_tail publishes that row: visible, content = the
  rewrite, api_content = the bytes the model wrote and already saw, so the
  wire and the cached prefix stay unchanged. One row, so role alternation
  holds.
- A codex_responses reply can carry commentary and the final answer in
  codex_message_items. Publishing the held final unhid the whole row, and
  project_history_commentary rebuilt display_commentary from those items on
  reload. publish_held_final_row now stamps display_metadata
  commentary_withheld on such a row; the projection then shows no
  commentary for it, while the items stay for model replay.

Also: the plugin-reload hold test waited 0.5 s for a negative check; it now
signals that the read started and waits 2 s (tests/AGENTS.md).

Tests (red on 72fd611fef): a pre_verify fallback ending a held turn (history
shows the rewrite, the resumed request replays the original bytes), and a
held codex_responses final with a commentary item (FakeResponsesServer
Message gains an optional phase).

Review: https://github.com/NousResearch/hermes-agent/pull/144266#discussion_r4370905634
Review: https://github.com/NousResearch/hermes-agent/pull/144266#discussion_r4370905635
Review: https://github.com/NousResearch/hermes-agent/pull/144266#discussion_r4370905636
2026-10-25 06:18:48 -07:00
Teknium
e2ec5e7060 fix(hold-stream): every exit of a held turn runs its transform snapshot
A held turn (hold_stream=True transform_llm_output) only ran the transform
on the paths that reach finish_text_response / finalize_turn. Other exits
returned model text the plugin never saw:

- A reply that hit finish_reason="length" on every continuation: the
  ceiling exit (_continue_text -> _Trunc.end_turn) stitched the raw
  fragments into the final and the stored row and returned without
  finalize_turn. collapse_continuation_trail now runs the turn's held
  transform snapshot on the stitched text before it appends the row, so
  the user and the stored row get the rewrite (or the withheld notice if
  the transform fails). The same seam covers a provider error that ends
  the turn after a capped fragment (settle_delivered_partial prepends that
  fragment to the error copy).
- The iteration-budget summary appends its own assistant row; finalize
  transformed the returned text but the row kept the raw summary, so
  history showed it. A recovery tail row that still holds the untouched
  text now stores the rewrite before its first flush
  (_store_rewrite_on_tail, the #44239 contract).
- Every remaining exit (non-retryable / exhausted provider errors,
  interrupts, compression and overflow failures, invalid-response caps,
  preflight timeouts, ...) returns through run_conversation, which now
  calls settle_held_final: a held turn whose final_response no seam
  transformed runs the snapshot there, so no path hands the user text the
  plugin did not see first. The hold snapshot is taken before
  build_turn_context, so an early exit never reads the previous turn's
  hold.

Tests (tests/agent/test_hold_stream_exits.py, real AIAgent + SessionDB on
the loopback model, red on 3a5b54d980): four capped responses, a capped
fragment then a 400, the budget summary, and a 400 with a tagging plugin.

Review: https://github.com/NousResearch/hermes-agent/pull/144266#discussion_r4370678627
2026-10-25 06:18:48 -07:00
Teknium
6030e77121 fix(hold-stream): no side path delivers a held turn's original text
Independent review of the hold_stream feature found four paths that still
let the untransformed reply or commentary reach the user:

- History loads showed held commentary. The tool-call assistant row of a
  held turn is now typed display_kind="hidden" before its first flush
  (withhold_held_commentary), so TUI/Desktop display_projection, the
  dashboard and classic CLI resume skip it. display_kind never reaches the
  wire: the model's context and cached prefix are unchanged (test replays
  the resumed session and compares the request bytes). The TUI projection
  still labels the hidden row's tool cards from its calls. Codex held turns
  type their earlier agentMessages hidden the same way.
- A plugin reload mid-turn could empty the hook registry before the final
  transform. The held turn now snapshots its transform_llm_output callbacks
  together with the hold decision under the discovery lock
  (held_stream_transforms) and runs that snapshot at the final. If no
  callback rewrote and one raised or timed out, the user gets a fixed
  "reply withheld" notice instead of the original (fail closed).
- Classic CLI replay-gap recovery painted and spoke pre_transform_response.
  A held turn's result (generic and codex) no longer carries the original
  at all (public_pre_transform), so receipts, recovery and post-stream
  suffix painting only ever see the rewrite.
- Codex error-after-text returned the raw agentMessage. The codex reply is
  now transformed whenever it has text, also when the turn errored (and,
  when held, when interrupted).

Same class, also fixed: the end-of-stream scrubber flush recorded a held
tail as streamed text (an interrupted turn could return it as an
untransformed partial final), and quiet-mode CLI printed held commentary
via _vprint.
2026-10-25 06:18:48 -07:00
Cleo
a8db83446f feat(plugins): ctx.side_question asks the session's own agent after a turn
post_llm_call now carries a single-use side_question_token when a loaded
plugin holds the new llm.side_question capability. ctx.side_question(token,
prompt) redeems it: ONE text-only request on a cache-parity fork through
the turn loop's own request phases (assemble_api_request, build_api_request,
perform_api_call), never the tool loop. The parent's system prompt, tools[],
reasoning config and max_tokens are replayed verbatim, so the request reads
the warm prompt cache. Tool calls in the reply are dropped, nothing is
persisted, and usage lands on the session as side_question.

Lease rules: one attempt per turn shared by every plugin (consumed even on
failure), 60 s, invalid once the parent starts its next turn, prompt capped
at 4096 chars, timeout capped at 60 s. The lease holds its parent weakly and
runs under the turn's captured contextvars (profile and secret scope).
Refused with None: MoA, agent-as-provider runtimes, requests that carry
provider-executed tools.

has_capability moves with side_question into a PluginContext mixin
(hermes_cli/plugins_capability_ctx.py) so hermes_cli/plugins.py shrinks.

Fixes #143788
2026-10-24 19:56:21 -07:00
unsupportedpastels
94458ebba1 fix(gateway): a late queued steer goes back to its queue, never into a follow-up
An empty steer buffer at settlement did not prove the turn read a transfer.
The turn finalizer drained a steer that arrived after the last tool batch into
result['pending_steer'], and the gateway's follow-up handling discards that
follow-up while it drains for a restart. Settlement still recorded the
transferred admission steered, so the prompt neither reached a model call nor
stayed queued for the next owner.

The finalizer now uses the agent's _drain_leftover_steer: it hands back only
ticketless steers (a /steer typed into the turn still becomes the next user
turn) and keeps each ticketed transfer buffered. The claim's settlement then
withdraws the transfer by its ticket and puts the admission back in its own
FIFO place. It runs once as its own turn, or waits queued for the next owner
when this one is draining. A transfer never rides a follow-up, so no restart
can drop one. An agent without the method keeps the old full drain.

Refs #134889 (RT-35)
Refs #140208
2026-10-17 14:25:35 -04:00
mnajafian-nv
814cde892a fix(relay): mark a micro-compaction in a rotated child on the turn it ran in
The micro-compaction publisher resolved its Relay parent from the
compressor's current session only. After a rotating compaction earlier in
the turn that session is a child with no Relay scope, so the pass the
finalizer runs before the turn ends lost its mark, while the attempt, prune
and provider-native publishers already fall back to the session the turn
started in.

The finalizer now passes that session to the pass, and its mark takes the
same fallback.

Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 3519c942fad6ba2dce3b4475ca7ff56a02c7410f)
2026-10-10 04:27:27 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
6cc1efd8f9 feat(voice): auxiliary.voice_chat routes spoken voice turns to their own model
Voice replies had to come from the session's main model, so a heavy model made every spoken
answer slow (#83894). A new auxiliary slot, voice_chat, picks the model for voice turns:

- CLI/TUI voice mode, the Desktop voice conversation (prompt.submit voice_turn) and messaging
  voice notes mark the turn; agent/voice_turn_route.py binds the route after the prompt, row and
  preflight compaction were settled against the main model and undoes it before memory sync and
  background review, so the next typed turn and the review run on the main model.
- A turn larger than the voice model's compression threshold stays on the main model with a
  one-time notice: switching to voice never compacts the conversation.
- Usage lands in session_model_usage under task voice_chat; it never rewrites the session's
  recorded model/route, so resume keeps the model the user picked.
- Slot appears in Desktop Settings -> Models, the dashboard, and `hermes model`; GPT-Live
  delegations keep using the session model.
2026-10-07 01:35:11 -07:00
kshitijk4poor
f33d817404 fix(agent): name a final that reuses an already-delivered response
When the model answers beside a housekeeping tool call (memory, todo_list,
skill_manage, session_search) and the follow-up is empty, the turn ends on
that pre-tool answer (fallback_prior_turn_content, since #10472). The final
then repeats text the client already streamed before the tool, but nothing on
the wire says so: message.complete looks like a new response.

Record the reuse where it happens (the housekeeping fallback and the
budget-exhaustion reuse of a previewed verification candidate), report
response_reused only when the final still equals that text (a footer or
explanation appended later drops it), and carry it on message.complete.
Never inferred from equal text: "Done." / tool / "Done." are two responses.
2026-10-04 18:04:17 -07:00
Brooklyn Nicholson
f10a763d9b fix(agent): stamp the activity clock at turn end and dump thread stacks on watchdog fire
The #131740 residual: a Desktop turn wedged between the 'Turn ended' log
line and run_conversation returning. The liveness watchdog fired ~600s
later naming 'API call #8 completed' as the last activity - a stamp from
the last provider response - so the stall surface read like a hung API
call, nothing pinned the blocking frame, and the abort hit a turn whose
loop had already finished.

- finalize_turn stamps the activity clock at 'Turn ended'
  (_log_turn_exit): a stall in the post-loop tail is measured from when
  the loop actually ended, and the watchdog's 'last activity' names the
  finalizer instead of a stale API call. Guarded: a broken
  activity-clock seam never raises into the finalizer.
- TurnLivenessWatchdog._surface_stall dumps every thread's stack (turn
  thread marked, 40-thread cap) at the moment it fires, so the wedged
  frame lands in errors.log on the next occurrence without py-spy.

Refs #131740
2026-10-03 16:18:04 -05: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
429f319d45 refactor(agent): one builder for the interrupted_during_api_call exit reason
The summary-interrupt path added a second copy of the string the loop's
interrupt path builds; turn_explainers matches its prefix, so both now
share interrupted_during_api_call_reason().
2026-09-27 02:02:41 +05:30
kshitijk4poor
578bcd2349 fix(agent): end the turn as interrupted when the iteration summary is cancelled
An InterruptedError from the now-interruptible max-iteration summary was
swallowed by handle_max_iterations' broad except and delivered as the
max_iterations_no_summary fallback with interrupted=False, so finalize_turn
cleared the pending interrupt message and CLI/gateway had nothing to requeue.

Propagate the cancellation, drop the unanswered summary nudge, and surface it
in the finalizer exactly like an interrupted loop API call: interrupted=True,
interrupted_during_api_call exit reason, INTERRUPT_WAITING_FOR_MODEL_PREFIX
text, and result["interrupt_message"] preserved.
2026-09-27 02:02:41 +05:30
MongLong0214
22127999be fix(agent): reset read dedup caches when micro-compaction or a native checkpoint drops the bodies they point at
skill_view, read_file and the computer_use screenshot dedup answer a
repeat of unchanged content with an "unchanged" stub that points at the
earlier result. Compaction and a committed proactive prune already
advance all three to a fresh generation through
_reset_read_dedup_caches, so the first repeat after the boundary serves
content again (#32106, #84857, #112763).

Two rewrites never reached that reset:

- post-turn micro-compaction splices older exchanges into the rolling
  summary (_micro_compact_after_turn), taking their tool results with
  them;
- a replayable native Responses compaction checkpoint makes the next
  request drop every item before it (build_assistant_message).

After either, a repeat read got a stub for a body the model could no
longer see. Both now call _reset_read_dedup_caches for the turn's task
and session. Micro-compaction resets only on a real splice: no-op and
defrag passes return the input list and leave the caches alone. The
checkpoint reset no longer depends on the context engine exposing
note_native_compaction_checkpoint, and it is skipped without a task id,
where the helper would clear every task's caches.

No message, tool schema or system-prompt bytes change.

(cherry picked from commit b7c8ecbbc20cd95e70003dce8120b02dbd2ab581)
2026-09-27 00:19:50 +05:30
Hermes Agent
a3a85a3143 fix(agent): close non-interrupted tool-tail turns with a visible response
A turn that falls out of the loop after a tool result with no follow-up
assistant text left the durable transcript ending at a raw tool row and
returned a silent result: Desktop/TUI showed a ready composer (or kept
spinning) with no final message. The pending_tool_result explainer copy
already existed but nothing minted the exit reason.

finalize_turn now detects the non-interrupted tool tail, fails the turn
with turn_exit_reason=pending_tool_result, and synthesizes the visible
assistant close before persistence so the durable tail is alternation-
safe. Stream-recovered turns (#95514) and interrupted tails keep their
existing paths.

Fixes #55316
Fixes #54756

Co-authored-by: blakehermes9 <blakehermes9@users.noreply.github.com>
2026-09-25 12:27:24 -05:00
ahrazzle
afa0ddeaab fix(agent): tag background-review fork turns in logs and pin supersede interrupt scoping
Fork turns (background review, side questions) reuse the parent's session_id
and, when unrouted, the model, so their `conversation turn:` and `Turn ended:`
lines are indistinguishable from live turns. In #118693 this made the fork's
own superseded exit read as a killed foreground stream.

- build_cache_parity_fork stamps _turn_origin on fork agents
- _log_turn_exit and the conversation-turn line append origin=<write_origin>
  for fork turns only; live turns are byte-identical
- new invariant test: cancel_background_review_for_live_turn flags only the
  fork (parent instance flags and thread bit untouched) via the real
  InterruptControlMixin path
- new regression test: fork turn-exit lines carry origin=background_review
  (red on base)

Related to #118693

Co-authored-by: CommandCodeBot <noreply@commandcode.ai>
2026-09-23 15:00:46 -05:00
teknium1
a28890a4c8 fix: transform_llm_output result is what the session stores and replays
A plugin's transform_llm_output replacement reached final_response only.
agent/turn_finalizer.py::finalize_turn fired the hook after the assistant
row had already been persisted — and the row is first written even earlier,
in agent/turn_final_response.py::finish_text_response's durable flush — so
messages[-1], the SQLite/JSON session, /resume and the next turn's replay all
kept the raw model text while the user had seen the rewritten one.

Writing the transformed text back after that flush cannot work: SQLite treats
a non-blank assistant row as settled (resolve_and_repair_transcript_batch
adopts the stored content instead of overwriting it), so the only correct seam
is BEFORE the row is first persisted. apply_llm_output_transform (new, in
turn_finalizer) fires the hook once per turn_id and records the outcome;
finish_text_response calls it ahead of append+flush and writes the result into
the row (api_content for the promoted-reasoning sidecar), finalize_turn's
_persist_step calls it ahead of the recovery-path tail close, and
_apply_output_hooks reads the recorded outcome (firing only when no earlier
seam saw a response) before post_llm_call. Only the current turn's not-yet-
written text changes — earlier turns and the system prompt are untouched.

post_llm_call is unchanged: it is an observer whose return is ignored by
contract, so there is nothing of it to persist (#14913/#44253's premise).

Fixes #44239
Slim redo of #44244 (AIalliAI, earliest; same sync-then-persist idea, moved to
the pre-flush seam) — also supersedes #65921 (SingleVirgin, sibling fix).

Co-authored-by: AIalliAI <285906080+AIalliAI@users.noreply.github.com>
(cherry picked from commit 5fe02a0aeecef422a4ffb4ff4385015f6a1528a0)
2026-09-21 23:56:25 -07:00
teknium1
efc947d72a fix: send the title model call after the turn on a shared custom endpoint
On a `custom` main route (llama.cpp, Ollama, vLLM, ...) whose
auxiliary.title_generation is not pinned elsewhere, the turn prologue fired the
`response_format: json_schema` title request on a daemon thread at the same
instant as the turn's own streaming request, against the same self-hosted
server. A single-slot server can decode the title grammar/completion into the
main reply: the user then receives `{"title": ...}` as the assistant turn, the
main loop persists it as a genuine assistant row, replays it, and the model
adopts the format (#117296). No Hermes writer routes the aux response into the
transcript; the leaked JSON is the main completion itself.

`maybe_auto_title` now returns the upgrade thread and leaves it UNSTARTED when
`title_upgrade_must_wait_for_turn(main_runtime)`; the prologue parks it on
`agent._deferred_title_upgrade` and `finalize_turn` starts it once the model
has answered. Hosted providers keep the turn-start timing. Usage accounting
(`task='title_generation'`) and `sessions.title` are unchanged.
2026-09-20 14:09:57 -07:00
teknium1
bafb778edc feat(gateway): opt-in served_model footer field shows the model that really answered
What: a new opt-in gateway runtime-footer field `served_model` rendered as
`alias → served`. It is populated from the `x-litellm-model-id` response header
(fallback `x-litellm-model-api-base`) that routing proxies send on every chat
completion, captured through an httpx response hook installed on the agent's
OpenAI client (agent/served_model.py, wired in create_openai_client), and from
Hermes' own provider fallback (primary runtime model → active model) when no
header is present. The turn result carries `requested_model` / `served_model`;
gateway/run_turn.py passes them to the footer. Off unless listed in
`display.runtime_footer.fields`; the default field set renders exactly as before.

Why: behind a routing proxy (or during a silent Hermes fallback) every reply
shows the configured alias, so operators cannot see which deployment actually
served a request (#54864). The SDK's parsed objects drop response headers, so
the capture has to sit on the transport.
2026-09-19 10:38:30 -07:00
Victor Kyriazakos
cd3de040ab feat(notifications): opt-in suppression of user-channel warning notifications
Squash of the 54 commits on victor-kyriazakos:feat/user-channel-warning-suppression
(PR #112302, head f45c640e55) so the contributor's authorship survives a rebase-merge;
the commits interleave with a cron delivery-ledger rework that the salvage removes in
follow-up commits, so per-commit cherry-picks were not practical.

Adds display.suppress_warning_notifications (global + per-platform, default false):
one resolver (gateway/warning_notifications.py), BasePlatformAdapter.emit_warning /
emit_media_warning / warning_text, a notification_category classification carried
through wakes, queues and persistence, and render/present boundaries for CLI/TUI.
2026-09-18 01:43:35 +05:30
teknium
9977df914d fix(kanban): delegate_task children never act on the parent's HERMES_KANBAN_TASK
In-process delegate_task children (and cron runs fired from a worker) inherit
the dispatcher worker's HERMES_KANBAN_TASK via os.environ. Three readers still
gated on the bare env var instead of is_dispatcher_owned_worker_context():

- agent/turn_finalizer.py: a child exhausting ITS iteration budget recorded
  `timed_out` against the parent's task and released the parent's claim.
- tools/kanban_tools.py::inject_new_comments_from_env: a child polled operator
  notes addressed to the worker, steered itself with them, and advanced the
  shared per-task watermark so the worker never saw them.
- agent/title_generator.py::_kanban_task_title: a child's session was titled
  after the parent's card.

Each now uses the single identity predicate. Dispatcher-owned workers are
unchanged (existing #87096 tests still pass).

Fixes #112817
2026-09-16 10:43:48 -07:00
kshitijk4poor
532b6d1cb1 fix(state): pin the session-db-unavailable fallbacks to the failing profile
format_session_db_unavailable consumes the now-pinned cause table but its own
two fallbacks (no recorded cause; network-drive gloss) still printed a bare
`hermes doctor`. Same class; one test covers both fallbacks.

Also: spell the corrupt action as plain concatenation instead of an f-string
with escaped braces, and fix the finalizer comment to state the invariant
(final_response is never rebound) rather than describe a local that no longer
exists.
2026-09-16 21:15:30 +05:30
kshitijk4poor
b6bba97f7b fix(state): pin the shared storage-failure action copy to the failing profile
hermes_state_user_copy.py is the one table feeding the CLI banner, gateway
warning and TUI/Desktop RPC errors, and its action strings were still bare
(`hermes doctor --fix`, `hermes gateway stop`, `hermes sessions recover`).
Substitute {profile_arg} once in describe_storage_failure so those surfaces
get the same pin as the turn explainer.

Also keep final_response unbound in the turn_finalizer error fallback: it
feeds the external-memory sync and the background-review gate, which must
still see an empty response on a persistence-failed turn. One test binds the
fallback (explainer stubbed empty) and the untouched final_response.
2026-09-16 21:15:30 +05:30
kshitijk4poor
9c093c83e4 fix(gateway): pin the remaining persistence-failure commands to the failing profile
gateway/run_notifications.py::_send_session_db_warning_notifications already
computed profile_arg but left `hermes doctor` (fts_index branch) and
`hermes gateway restart` (default branch) bare; agent/turn_finalizer.py had a
bare `hermes doctor` in the error fallback used when the explainer produced
no text. Same class as the previous commit. Also reflows the explainer
strings so continuation lines break at clause boundaries.
2026-09-16 21:15:30 +05:30
teknium1
ee49b7d25d fix(agent): file-mutation footer states failed edits, not "files were NOT modified"
The turn-end file-mutation verifier only sees write_file/patch receipts. It
asserted "N file(s) were NOT modified this turn" whenever a call had failed,
which is wrong when the file was in fact changed afterwards through a path
that leaves no receipt (terminal redirect, execute_code) or when the
successful retry used another spelling of the same path (relative vs
absolute, separator/case variants on Windows): the state dict was keyed on
the model's raw `path` argument, so the pop never matched.

- Header now says what the recorder knows: "N file edit(s) FAILED this turn",
  and asks the user to confirm what actually landed.
- Failure entries carry the task-resolved, normcase'd on-disk identity plus a
  (mtime_ns, size) snapshot; a later success clears every entry with the same
  identity regardless of spelling.
- At turn end `_file_mutations_still_failed` re-stats each target and drops
  entries whose file changed since the failed call, so a receipt-less
  mutation no longer produces a false footer.
- `tool_executor` passes the effective task id so relative paths resolve the
  way the file tools resolved them.

Kept the deliberate first-error-per-path semantics (the pinned test says why);
did not add an "unverified" bucket for receipt-less non-error results, since
the built-in tools always return a receipt on success and it would only add
noise.

Co-authored-by: KoNit. <124019182+KoNit-K@users.noreply.github.com>
2026-09-15 18:22:12 -07:00
teknium1
0a6c7b7fa3 fix(agent,gateway): report interrupted and unfinished turns truthfully
An interrupted turn left `finalize_turn` with a diagnostic `final_response`
("Operation interrupted: waiting for model response") and no failure, so the
result said `completed=True` — the only producer that did; `turn_recovery`
and `codex_runtime` already return `completed=False` for an interrupt and the
gateway stream gate documents that contract. `completed` now also requires
`not interrupted`.

The API server then hard-coded the terminal status: the session chat stream
emitted `assistant.completed {completed: true, interrupted: false}` and
`run.completed` for every turn that did not raise, and `/v1/runs` booked any
non-`failed` result as `completed` — including an interrupt that did not come
through `/stop` and a turn that ran out of iteration budget. Automation that
reads the run status or the terminal event saw unfinished work as delivered,
and `partial: true` could sit next to `completed: true` in one payload.

`api_server_runs.terminal_run_status()` is now the single mapping for both
surfaces: interrupted -> `cancelled`, failed/partial/`completed=False` ->
`failed` (with `turn_exit_reason` and the fallback text as `output`),
otherwise `completed`; the terminal event is always `run.<status>` and a
late `pending_steer` rides on every terminal status instead of only on
`completed`.

CLI exit codes (`-q` quiet mode, `-z` one-shot) are deliberately unchanged
here: `hermes -z` returning 0 whenever text was produced was a stated design
choice (093f567f0d) and scripts depend on it, so that flip needs a
maintainer decision.

Fixes the gateway/producer half of #111770; slimmer redo of #111785 by
@KoNit-K (same mapping idea, one helper instead of three ladders).

Co-authored-by: KoNit-K <124019182+KoNit-K@users.noreply.github.com>
2026-09-15 18:21:44 -07:00
teknium1
23036e20a6 fix(ux): plain-language, actionable user-facing messages (core)
Squashed integration of the user-facing message audit for this surface set.
Full per-finding receipts: /tmp/ux-audit/lanes/*-receipt.md (campaign artifacts).
2026-09-15 04:12:13 -07:00
kshitijk4poor
4bd38ec9fd fix(plugins): give output-transform hooks a call identity for the callback gate
Hook callbacks are gated per (hook, callback, call identity). Two hooks
on the tool-loop path fired without any identity, so concurrent terminal
calls in one turn, or overlapping turns, still collapsed onto a single
gate key and the second invocation was skipped as if a callback had hung.

transform_terminal_output now forwards the tool_call_id bound in the
approval context around dispatch (only when set); transform_llm_output
forwards the turn_id already in scope. Payloads are additive: the
dispatcher withholds unknown fields from narrow-signature callbacks.
2026-09-15 10:48:49 +05:30
teknium1
16e4496d90 fix(agent): corrupt-session recovery guidance names the session's own state.db
The corruption explainer filled `{db_path}` from `_default_db_path()`, the
process default. A Desktop `serve` backend launched on the root home hosts
named-profile sessions whose SessionDB is `profiles/<name>/state.db`, so the
operator was told to inspect/repair a different profile's database. Pass the
agent's own `_session_db.db_path` from the turn finalizer; the process
default remains the fallback for agents without a bound store.

Reported in #105887.
2026-09-11 06:24:11 -07:00
fangliquanflq
77f2ce853f fix(agent): suppress detached fork session-end hooks 2026-09-10 13:23:00 +02:00
fangliquanflq
feb03196a2 fix(agent): isolate detached forks from lifecycle hooks 2026-09-10 13:23:00 +02:00
Teknium
04767e7aaa fix(display): distinguish estimated context from provider usage 2026-09-07 08:13:01 -07:00
Teknium
e3ab65fe80 simplify(compat): kanban_db — drop 73 re-exports/aliases, repoint 794 callers 2026-09-03 13:48:14 -07:00
Teknium
c65aebccf0 review-fix(conversation-loop): finalize_turn binds stream-recovered final_response before fallible persist sub-steps (BASE order)
On BASE the #95514 stream-recovery rebound final_response inline, before
the tail-closing / persist-override / micro-compaction / _persist_session
calls inside the guarded persist try-block, so a raise in any of them left
the caller with the streamed text (cleanup_errors reported the failure).
HEAD's _close_transcript_tail returned the recovered value only on normal
completion; an exception in the same block dropped it and the user-visible
answer regressed to the pre-recovery '' (then rewritten by the explainer).

Split the helper into _drop_transcript_scaffolding / _recover_final_from_stream
/ _close_transcript_tail and rebind final_response in the guarded step as soon
as it is computed, restoring BASE ordering. Adds a regression test.
2026-09-03 09:54:04 -07:00
Teknium
e83816a4d1 review-fix(comments): restore lost #NNNN rationale comments across non-test source (mechanical sweep, condensed, code unchanged)
For each issue anchor present in BASE 63279301bc non-test .py and absent on HEAD, the BASE comment/docstring block was re-attached at the HEAD location of the code it explained (matched by the distinctive code line / enclosing def). Sentences already covered by an existing HEAD comment were deduped; the issue number always survives. Insert-only: no code lines changed.
2026-09-03 09:44:26 -07:00
Teknium
05f4d4b94b refactor(agent/turn_finalizer,turn_stop_gates): session counter keys table, tighten nudge counters 2026-09-02 19:30:27 -07:00
Teknium
c449a340b6 refactor(agent/turn): comment/docstring pass — keep WHYs, drop narrative and restated code 2026-09-02 19:26:50 -07:00
Teknium
6ea48570c3 refactor(agent/turn_finalizer): fold budget-fallback predicate and kanban gate, tighten cleanup calls 2026-09-02 19:12:18 -07:00
Teknium
8e923c8ea1 refactor(agent/turn): facade outcome ternary + suppress, summary pluralize table, liveness/finalizer docstring trims 2026-09-02 19:08:57 -07:00
Teknium
a3fda4a44a refactor(agent/turn_finalizer): persist step via _guarded_cleanup, output-hook helper, inline single-use tail helpers 2026-09-02 18:16:58 -07:00
Teknium
c94ced6225 refactor(agent/turn): AST-neutral bracket/signature packing across r3-08 slice 2026-09-02 18:01:27 -07:00
Teknium
629e6eb1b5 refactor(turn): split finalize_turn into phase helpers (576 -> 264 LOC) 2026-09-02 16:46:33 -07:00
Teknium
4e548ce7a0 refactor(agent): compact turn-loop comments/docstrings to invariant statements (AST-identical) 2026-09-02 13:29:46 -07:00
kshitijk4poor
2adb1a4ea6 refactor(agent): clone the review snapshot once at the spawn chokepoint
Move the structural clone from the four call sites (auto review, codex
runtime, CLI /refine, gateway /refine) into AIAgent._spawn_background_review,
which every review path — immediate, idle-queue deferred, requeued — passes
through. Callers can no longer forget it, and the private helper is no longer
imported across hermes_cli/ and gateway/ package boundaries.

Tests now bind the real chokepoint (capturing at _spawn_background_review_now)
so they still fail if the clone is removed.
2026-09-02 13:28:41 +05:30
notkisk
619ca3011e fix(agent): isolate background review snapshots 2026-09-02 13:28:41 +05:30
rainbowgits
71256dfd01 fix(state): fail loudly when state.db is replaced under a live process
Detect same-inode cp via a generation stamp, halt FTS repair, and divert
unwritten transcripts to sessions/<id>.jsonl plus the gateway pending spool.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 14:02:55 -07:00
StanleyStetson
24e54b55f5 fix(desktop): preserve streamed assistant text and unify atomic persistence (#95514)
- Preserve streamed assistant text in Desktop UI when message.complete delivers empty text.

- Prevent destructive hydration in Desktop useMessageStream over rendered text on empty completion.

- Recover stream buffer in finalize_turn when final_response is empty on healthy turns.

- Unify in-place blank assistant repair, watermark clone resolution, non-blank concurrent winner adoption, and batch row appends into a single atomic guarded SessionDB transaction.

- Synchronize canonical committed content to live in-memory messages dicts and preserve all-or-nothing rollback semantics on persistence failure.
2026-08-29 11:33:05 +05:30