e8ccfffc0b51440fabfc7a0596410ac8e94de59b
184 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e240d617e8 |
feat(sessions): refresh-prompts lets continuing sessions adopt updated prompt sources
A continuing session replays its stored system prompt verbatim on every turn so the provider prefix cache stays warm. The gateway restores that prompt from the session row on each fresh agent, and warm cached agents keep it in memory, so SOUL.md edits, new or edited skills and project-context changes never reach a long-running conversation until /new, which also drops the history. Operators who push profile updates and restart the gateway had no way to make existing conversations pick them up. `hermes sessions refresh-prompts [--session ID] [--json]` records a refresh epoch in the profile's state.db (state_meta, one counter orders profile-wide and per-session requests). At the start of a continuing session's next turn, _restore_or_build_system_prompt compares that epoch with the one stamped in the session's model_config when its prompt was built. When the stored prompt is older it follows the Bot Chat capability-refresh precedent in the same function: tools[] pin restored first, skills prompt cache and snapshot cleared, prompt rebuilt through _build_system_prompt (memory reloaded and plugin sections re-rendered, as at a compaction boundary), cache break recorded, on_session_start not fired, new bytes and epoch persisted so the following turns restore them verbatim. One cache break per request. Warm agents (gateway agent cache, TUI/Desktop) run the same check from build_turn_context against the epoch they saw when their prompt was set, so the verb works with the gateway running. A session first built after a request is stamped with it and does not rebuild again. With no request recorded, the stored prompt is reused byte-identically. The only added work per continuing turn is one state_meta point read. No file scanning, no config key, no watcher, no mid-turn mutation. The tools[] pin is kept on purpose: the refresh is about instructions, and tool changes already reach long sessions at the compaction boundary. The cache break is recorded as the existing system_prompt_rebuild cause rather than a new one, which would change the shared-metrics contract and schemas. Related: #141154 (per-turn source hashing, alternative design), #74622. |
||
|
|
49f5de617e |
fix(left-core): only a turn someone sees claims kept migration notices
Every AIAgent's _load_tools ran recover_at_startup(say=agent._emit_startup_warning), which claimed the home's kept notices. Cron runs, subagents, the curator, kanban workers and background-review forks have no notice_callback, so the notices were parked on an agent nobody watches and dropped; a cron tick after a gateway start usually beat the user's next message. Agent init now only runs the migration and keeps its outcomes in the home. The turn start (deliver_kept_startup_notices) claims them when the turn has a real sink: the CLI's print sink, or a driver's notice_callback (gateway chat, Desktop/TUI), and not for an unattended turn (side_question_lease.is_unattended_turn: fork, cron, delegated child) or suppress_status_output. The restart-the-gateway hint was gated on having a sink; it is now gated on not being the gateway's own start (recover_at_startup(gateway_start=True)), so an agent-start install still carries it. |
||
|
|
70d31a5a5d |
fix(agent): only the first attempt of a user turn carries user attribution (billing parity)
|
||
|
|
7298f46b7d |
fix(agent): a gateway-hosted CLI session prints its startup warnings on the first turn
LIVE-1 (r4 live s10gh/s10v), part 2. The left-core notice is kept in the home and claimed by the first agent in any process, but for `hermes chat` that agent is the session the gateway hosts for the CLI viewer: built (platform "cli") before the turn wires the viewer's print sink, so the startup line went to the gateway's own stdout log. A CLI agent built with a gateway session key now holds the line and prints it on its first turn (turn_context already replays startup notices there); an in-process CLI agent still prints at once. |
||
|
|
53a51a49cc |
fix(agent): per-request provider headers reach the wire
A provider's request_headers(user_initiated=True) answer (turn attribution, e.g. a premium-billing initiator header) was consumed when the first attempt's payload was built. A 429/5xx retry or a fallback activation rebuilds the payload for the SAME API call, so the retried attempt went out with the route's default (agent) attribution instead of the user's. The route now claims the call's api_call_count; every attempt of that call re-applies the headers, tool-loop follow-ups (higher count) do not, and a new turn / session reset clears the claim. Repro (fake profile + local HTTP stand-in, scratch probe_xinit.py): first attempt carries the header, the retry did not (codex_responses 500 retry, chat_completions 429 retry); both attempts carry it after this change. The turn flag is consumed exactly once per user turn, before the route is asked: a route with no attribution, or a request_headers hook that fails (route_answer swallows plugin errors), no longer leaves it set, which billed the next tool-loop call as user-initiated (r4-review P2-5). |
||
|
|
0ae220ff4e |
refactor(providers): generic endpoint seams for Responses quirks, reasoning payloads and carriers
Core no longer branches on the Copilot/GitHub Models hosts in the Responses adapter, transports, reasoning params or reasoning-carrier replay. A provider profile claims its backend through ProviderProfile.serves_endpoint(base_url) (default False) and fills generic L3 fields/hooks: responses_replay_item_ids, responses_prompt_cache_key, responses_issuer_kind, responses_trusts_completed_status, responses_native_compaction, responses_profile_reasoning, message_carrier_opaque/_text, replays_tool_call_signatures, reasoning_payload(), replay_message_carriers(), replays_function_thought_signature(). The in-tree copilot plugin fills them from plugins/model-providers/copilot/responses.py, keeping the persisted "github_responses" issuer stamp and hermes.native_assistant record keys. Persisted carrier records whose declaring plugin is gone are stripped by their own keys. Parity: an offline oracle over 2079 Copilot cases (main request kwargs incl. preflight, aux Responses, carrier shaping/capture, reasoning gate, native compaction) is byte-identical to the base on the agent paths in both registry states. |
||
|
|
552f735368 |
feat(delegation): /delegation saves for the next session; --now rebuilds this session's tools
The delegate_task schema is built from the active backend and is cached prompt, so a session-only /delegation switch changed routing but not the schema. - Remove the session-only backend override (get/set_session_backend, session_delegation_config, the /new boundary clear). delegate_task routes on delegation.backend. - set_global_backend(name, *, session_key='', apply_now=False): saves config; apply_now rebuilds that session's tools at its next turn (after the pin restore, so fresh agents rebuild too) and re-pins them, one opt-in cache break. - The undeclared-parameter refusal names the fix: /delegation <b> --now or /new. - Docs: delegation guide + provider-plugin API table. |
||
|
|
dfc2cbeaa1 |
refactor(memory): move memory-context fencing into agent/memory_context.py
agent/memory_manager.py mixes provider fan-out, background work and the text formatting that fences recalled memory for the model. The formatting half (sanitize_context, StreamingContextScrubber, build_memory_context_block and their regexes) is pure text work with no provider calls or profile state, so it moves unchanged to its own module. Callers import it from there; nothing in plugins/ imported it, so no re-export is kept. The only visible difference is the logger name on the "pre-wrapped context" warning (agent.memory_context). This leaves the manager room for the profile-ownership checks the next commit adds without crossing its line cap. Refs #134889 (PLG-11) Refs #140208 |
||
|
|
eb8a135063 |
fix(lsp): type errors reach the model inline or before the turn ends; writes stay under ~0.1s
With 88107d448c the write never waited on the language server: a verdict slower than ~50ms rode the session's next tool result or next user turn. Live, a planted TypeScript error made by the turn's last edit was lost: tsserver pushed its verdict 0.4s after the final tool result, and a one-shot `hermes chat -q` has no next turn (the model answered TYPE_ERROR_SEEN=no; origin/main saw it, at 10s per write). - agent/lsp/sync_diagnostics.py: typescript-language-server answers `typescript.tsserverRequest` syntactic/semanticDiagnosticsSync for the synced text (measured ~10-30ms warm), so the edit check asks it directly instead of waiting for a push that may never come. pyright already answers the document pull in ~10-90ms. The inline window is now the whole 80ms write budget, so the warm common case is reported in the write's own result. Servers without a synchronous request keep the push wait. - agent/lsp/deferred.py + agent/turn_stop_gates.py: checks still running are tracked per session. When the model gives a final answer, the stop gate waits for them (at most 5s) and hands any undelivered verdict to the model as a new user-role message, continuing the turn (max 3 per turn). The message is a durable row appended after the answer, so no earlier byte changes and the prompt cache holds. |
||
|
|
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.
|
||
|
|
17c691fd7b |
Merge pull request #140062 from NousResearch/fix/forward-port-0.22.2
v0.22.2's eight fixes now land on main too (forward-port for #139099) |
||
|
|
c1b4b62a49 |
fix(agent): follow-up turns rebuilt from the session DB see the user's image again (#136216)
The session DB stores user rows as text: session_persistence._durable_content turns each image
part into a trailing "[screenshot]" line. Every turn rebuilt from state.db (API-server requests
continuing a session with X-Hermes-Session-Id, hermes chat --resume, gateway restarts) therefore
sent the model that placeholder instead of the photo the user asked about one message earlier.
The bytes were never lost: every native attach path already retains them under the profile's
content-addressed cache/documents/native-inputs/<sha256>/<name> and names that path in the same
row ("[Image attached at: <path>]"). build_api_messages now re-attaches the
vision.replay_recent_images newest images (default 3, 0 = off) on the wire copy when the turn's
model takes images natively, encoding them with the same _file_to_data_url the live turn used, so
the rebuilt row is byte-identical to the original request and the prompt-cache prefix holds.
Only retained native-inputs bytes whose digest still matches are replayed. Remote URLs, missing or
changed files, images outside the window, and a user-typed "[screenshot]" line (no paired attach
hint) keep their text. A non-integer config value warns and disables the replay. No new store,
DB column or retention path.
Co-authored-by: Alexbob0 <190955252+Alexbob0@users.noreply.github.com>
|
||
|
|
4bc2efbeb3 |
fix(local): keep long local-model turns alive on laptops
A press reviewer ran Qwen 27B on a 64 GB RTX Spark and saw single queries take hours. The
causes, and what each part of this change does about them:
- llama-server reads a long prompt for minutes before the first token. Local requests now
always stream and ask for prompt-reading progress, so the stall timers see the server
working and the router notices a hang-up within seconds. They no longer fall back to a
non-streamed request, which the router can't cancel. The status line shows how much of
the prompt the server has read.
- A laptop that sleeps mid-request froze the request, and the stall timer cut it on wake.
Stall timers for a server on the same machine now skip time the process was stopped
(sleep or Modern Standby). Background-call watchdogs run on the awake clock.
- After repeated stalls the breaker failed every later message at once, even after the local
server recovered. At turn start, a local server that answers its health check gets one more
attempt; one more stall shuts the breaker again.
- On Windows unified memory, the GPU carve-out is invisible to Windows, and the model plus
llama-server's default 8 GiB prompt cache overran commit. Free commit now narrows the launch
window (never refusing a model the pool can hold), caps how many models the router holds at
once, and sizes the prompt cache, split across those models.
- Hermes's status reads named the model, and the router loads any model a request names, so
Eject and the idle unload reloaded the model at once. Status reads pass autoload=false; an
unloaded model counts as idle, and the context probe reads the router's launch args.
- The smart-approval verdict has a 16-token budget, and a thinking model spent all of it
thinking (45 of 45 verdicts came back empty). The verdict asks for no thinking unless the
operator set auxiliary.approval.reasoning_effort.
- Compression's 600 s limit counted the time the server spent reading a 150K-token
conversation, which alone can exceed it on a laptop GPU. Prompt reading now pushes the fence
deadline back (CompressionCommitFence.extend_deadline), only while the server reports newly read
tokens, and never past a fence the host closed or one a commit holds. The agent and gateway
hygiene waits read the moved deadline after every slice.
- Desktop keep-awake defaults to "while working". When a timed sleep interrupts a turn with
keep-awake off, the next wake offers it once per computer; the offer survives the next prompt.
(cherry picked from commit
|
||
|
|
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) |
||
|
|
336b11584c |
fix: replay prior reasoning to every chat-completions route that can read it
Every model reasons and intends that reasoning to be replayed, but the chat-completions wire echoed reasoning_content only to DeepSeek/Kimi/MiMo/ Ollama (plus a hardcoded Portal stealth model) and reasoning_details only to OpenRouter; turn_context popped `reasoning` everywhere, so Ollama's /v1 (reads only `reasoning`) never saw any. - message_sanitization owns one route->carrier table (_REASONING_CARRIER_ROUTES): strict schemas (Mistral, Groq, Cerebras, SambaNova) get nothing, Fireworks reasoning_content only, OpenRouter-format gateways (OpenRouter, Kilo, Vercel AI Gateway, Nous Portal) all three, Novita/MiniMax /v1/TokenHub + reasoning_details, local/Ollama/Upstage + reasoning, everyone else reasoning_content. - The " " pad stays limited to the must-echo tier (DeepSeek, Kimi, MiMo); Ollama leaves it (no echo requirement) and the stealth hardcode is gone. - Reactive recovery: a 4xx unknown-field rejection that NAMES a reasoning key this request carried is recorded per (provider, host, model) and the retry re-shapes api_messages without it. Generic upstream errors never count; a recorded key falls through, so no loop. History is untouched. - Nous Portal reads reasoning_details again: the #118182 "replay budget" does not exist in the Portal and does not reproduce live. - Gemini thought_signature survives on Gemini hosts/providers even when the model id is an alias. - Vendor keep-reasoning flags (docs-only): GLM thinking.clear_thinking=false, DashScope preserve_thinking / clear_thinking, Kimi K2.x thinking.keep=all. - stale_thinking_reaches_wire follows the same table, so compaction trigger and tail walks agree with what is sent. |
||
|
|
097fcaa1de |
fix(skills): every turn announces skill changes once, on every surface
#118661's note only fired on the stored-prompt restore path, which a long-lived agent (classic CLI, TUI, Desktop) runs once per conversation: those surfaces never saw a mid-conversation skill change. The check now runs from build_turn_context every turn against the prompt the turn actually sends. - What was told is kept on the agent for its prompt; a fresh agent (gateway, -q --resume) reads the newest note back from the WHOLE transcript instead of the last 200 rows, so a long session no longer re-announces an unchanged delta (review by @kvnloo). - A compaction rebuild that now lists the announced skills stays quiet. - Index rows split on ": ", so qualified plugin skills (plugin:skill) parse. - The plugin go-live note drops its own skills list: the per-turn note covers plugin skills like any other, so a plugin install no longer announces its skills twice. |
||
|
|
ec78ae2211 |
feat(prompt): skills installed mid-session reach the model without a prompt rebuild (port cloudflare/cloudflare-os#267)
The persisted <available_skills> index is reused byte-for-byte across turns so the provider prefix cache stays warm (#104414). A skill that lands after the prompt was built (hub install, skill_manage from another session, org sync, curator) therefore never reached the index the model actually routes on until compaction rebuilt the prompt: skills_list is live, but the prompt tells the model to scan the index, not to call it. cloudflare-os#267 found the same fault in their chat-cached catalog ("a catalog states what a session can reach now, which is not a fact a chat can hold"). Hermes' idiom for stored-prompt drift is a one-shot note behind the cached prefix, not a rebuild, so agent/skills_index_delta.py stages the delta on the same per-turn user-message channel the surface-switch note rides: the added skills' own index lines (name + description, the routing signal), the removed names, cumulative against the stored prompt and re-staged only when the delta changes (read back from the api_content sidecar, so the gateway's fresh agent per turn does not stack copies). An undone delta retires the stale note once. The current index comes from the same cached builder the prompt did, so an unchanged turn costs one LRU hit. |
||
|
|
d76cce4f11 | ci: apply all automatic linter fixes available | ||
|
|
3724ace0c8 |
Merge remote-tracking branch 'origin/main' into feat/store-guest-onboarding
# Conflicts: # apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts # apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts # apps/desktop/src/app/session/hooks/use-message-stream/index.ts |
||
|
|
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. |
||
|
|
4efdfb6d84 |
Merge remote-tracking branch 'origin/onboarding/next' into feat/store-guest-onboarding
# Conflicts: # apps/desktop/electron/window-focus-policy.ts # apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx # apps/desktop/src/lib/chat-messages/parts.ts # apps/desktop/src/plugins/hermes-bots/types.ts # apps/desktop/src/sdk/index.ts # hermes_cli/plugins_cmd_install.py # hermes_cli/profile_distribution.py # plugins/web/keyless_mcp.py # tui_gateway/methods_profiles.py # tui_gateway/server.py # website/docs/developer-guide/relay-shared-metrics.md # website/docs/user-guide/features/web-search.md |
||
|
|
a5144c71e9 |
fix(memory): show every memory-provider migration outcome, ask once per update
Agent-start recovery (recover_at_startup) reported installed / refused / failed / not-in-catalog only to agent.log, and so did a selected provider that reports unavailable, so a user with security.allow_lazy_installs: false, offline, or who declined the dependency prompt silently ran without external memory (#119769). - Startup outcomes go through _emit_startup_warning: printed in the CLI; other drivers get a sticky warn AgentNotice (Desktop toasts notices but drops warn-kind status.update), and the messaging gateway, which wires notice_callback per turn, receives it on turn 1. - hermes update labels each line with the profile it is about and gives the exact `hermes -p <profile> plugins install <name>` command for non-active homes. - Profiles sharing one environment get one set of dependency answers per provider (shared_dependency_answers): the first install asks the normal Python/Node questions, later homes reuse them; a decline or failure names the remaining profiles once instead of failing (or re-prompting) one by one; Ctrl-C ends the migration with a message (#125794). - The success line no longer names memory.<name> (#124038); docs follow. Co-authored-by: chelsealong <chelsealong@126.com> |
||
|
|
6403dd325c | fix(anthropic): simplify recovery and make accounting explicit | ||
|
|
1fd41d8770 | fix(anthropic): exclude rejected thinking from preflight | ||
|
|
ec26994742 | fix(anthropic): align canonical preflight accounting | ||
|
|
582750e3f9 | fix(anthropic): make preserved-thinking replay coherent | ||
|
|
08f3a7209f |
First-run intro no longer plays hearts; usage-stats bar waits out the tour (#129636)
* fix(desktop): no hearts during the intro, no stats bar during the tour The hidden /initiate-setup turn expands to the skill body, and reaction detection matched words like "thank you" in that text, so hearts played on the first-run intro. Reactions now skip hidden prompts and expanded skill bodies; only typed text counts. The usage-stats offer waited for guided onboarding but not for the handoff tour, so the bar appeared under the tour overlay. A reactive $tourActive atom, cleared from the tour engine on every exit path, now holds the offer until no tour is on screen. * fix(tour): a closed one-off highlight clears the tour-active flag The show path built its driver without onDestroyed, so closing a highlight with Esc, the X or an overlay click left tourActive set and blocked the usage-stats offer for the session. |
||
|
|
6776a429b5 |
fix: use original gateway text for automatic session titles
Gateway turns reach the agent enriched with channel-bound skill payloads, sender metadata and other model context, so the first user message the titler saw could be thousands of characters of skill text ahead of the actual question, and new sessions were named after the skill instead of the request. The gateway now captures the inbound event text before that enrichment and passes it as a turn-local title_user_message through TurnContext, the turn runner, AIAgent.run_conversation and the conversation prologue. Only the titler reads it: the main model, persisted history and relay metadata still receive the full enriched message. An explicit empty or whitespace override suppresses titling for that turn, None keeps the existing model-facing fallback (attachment-only turns, paste previews), and the override cannot enable model titling for cron or subagent runs. The value is a per-call argument, so a cached agent never reuses a previous turn's override. Rebased onto current main: the gateway call keeps main's pinned channel prompt for internal events, and the integration fixture's context-prompt stub accepts main's internal= keyword. Ritvik Gautam made this change with Doryani AI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
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. |
||
|
|
a5bd246865 |
Old pre-decomposition import paths are gone: plugin compat layer removed on schedule (#126164)
* refactor(plugins): remove the Sep 2026 decomposition compat layer on schedule The PLUGIN-COMPAT layer ( |
||
|
|
b90b7ae7ed | fix(delegate): title subagent sessions after their goal without a model call | ||
|
|
444066b82c |
fix: exclude display-only message fields from token estimates
Edit tool rows now carry display_metadata.tool_result_metadata.inline_diff
(~9KB of ANSI per edit) on the live message dict. build_api_messages strips
display_kind/display_metadata/_row_id before the wire, but the local
estimator's wire shadow only dropped PERSISTENCE_ONLY_MESSAGE_FIELDS
({"timestamp"}), so estimate_messages_tokens_rough and
estimate_request_tokens_rough priced the diff: one edit row went from 32 to
2527 estimated tokens (100 edits: 3100 -> 252600). That inflates compaction
preflight, post-tool checks and turn-overflow scoring, compacts early and
breaks the prompt cache.
PERSISTENCE_ONLY_MESSAGE_FIELDS (agent/message_metadata.py) is now the single
set of local-only fields: timestamp, display_kind, display_metadata, _row_id.
build_api_messages pops exactly that set and the estimator shadow drops it,
so the two can no longer drift. The iteration-limit summary path
(_iteration_summary_api_messages) hand-builds its wire messages and stripped
timestamp but not display_*; its key set now unions the same constant, so
the inline diff never reaches the provider there either (strict gateways
reject unknown keys). The tail-budget walk (_estimate_msg_budget_tokens) is
allowlist-based and already ignored these fields.
|
||
|
|
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> |
||
|
|
bb87e6abce |
fix(agent): persist the multimodal pre_llm_call text part and stop double injection (#71998)
Builds on #72026 (@PRATHAMESH75): list content carries the turn's memory-prefetch / pre_llm_call context as a durable text part appended once in the prologue, in every api mode (MoA and codex_app_server included), so the request, the persisted row, compaction and a later resume all see the message the model saw. Persistence gap from the #72026 review: in-place preflight compaction (and a close/early flush that races the prologue) writes the current user row BEFORE the part exists and the crash persist identity-skips that dict, so a resumed session replayed the turn without the context. The list branch now pushes the appended part into that row via set_user_message_content under the same _row_id-under-lock protocol as the string sidecar backfill, keeping the writer's shape (compaction: raw parts; flush: text projection). Titling moves before the injection step so a list turn's title is derived from the user's ask, not the injected tail. Tests trimmed to one invariant per layer: hook edit reaches the wire on a list turn and replays after reload; in-place compaction + reload keeps the part (red without the backfill); memory query flattens parts. |
||
|
|
d1267d8045 |
fix(agent): run memory prefetch on multimodal turns by flattening the query (#71998)
The delivery half of this PR lets a multimodal (list) turn carry the memory /
pre_llm_call context via a durable text part. But the execution half never ran
on those turns: `_memory_turn_start_and_prefetch` keyed the query off
`isinstance(str)`, so a list turn collapsed to `_query = ""` — `on_turn_start`
saw an empty turn and `is_trivial_prompt("")` skipped `prefetch_all` entirely.
So on an image+text turn recall never fired and the sidecar had nothing to
deliver, silently (no `recall` audit rows, no `prefetch failed` warning).
Flatten str/list content to its text via `flatten_message_text` before building
the query. An image-only turn still flattens to "" and is correctly treated as
trivial (no semantic text to query on); a text+image turn now runs prefetch on
its text. Adds unit coverage for the flattening and the trivial-prompt gate.
Reported by @albert748 on #72026.
|
||
|
|
b8b519c398 |
fix(agent): deliver pre_llm_call/memory context on multimodal turns (#71998)
compose_user_api_content returns None for non-string (multimodal) user
content, so the pre_llm_call plugin context and memory-prefetch block —
which ride the string api_content sidecar — were silently dropped on
image-only/attachment turns. A profile plugin's pre_llm_call {"context":
...} return could route text turns but never image-only turns.
Deliver the composed context as a durable text part on multimodal turns
via the existing append_notes_to_multimodal_content channel (the same one
gateway must-deliver notes already use), so the injected context reaches
the model and the wire stays byte-identical to the persisted/replayed
transcript. String turns keep the api_content sidecar path unchanged; the
MoA/codex_app_server guards are preserved. Extract the shared injection
composition into _context_injection_parts so both paths inject byte-
identical context.
|
||
|
|
1ae6f650f9 | fix(compaction): invalidate pre-checkpoint usage anchors | ||
|
|
28a75285c4 |
refactor: drop the dead _vision_supported flag
Image rejections are now tracked per (provider, model) in agent._image_rejecting_models, and recover_before_classification gates on that set. Nothing reads agent._vision_supported any more, so the write in turn_recovery and the per-turn reset entry in turn_context are dead state. Remove both so the next reader doesn't assume a turn-global vision gate still exists; update the two tests that asserted or seeded the attribute. |
||
|
|
afc3b7c6f3 |
feat(connectors): one backend-owned connection operation, with a setup card on Desktop, TUI and CLI (#111008)
* feat(connectors): the desktop connects apps through one backend-owned operation Re-based onto main after #109517, #110368, #110574 and #110843 landed as squash merges ( |
||
|
|
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.
|
||
|
|
d03d6c2b39 |
fix(compression): an over-window session that cannot shrink ends the turn with /new guidance and waits one idle budget, not the ceiling
A session far above the model window (~356k tokens on a 131k window in #116472) re-ran context compression on every turn: a preflight pass that reclaimed nothing still let the request go to the provider (400 -> overflow handler -> another pass), and a summary stream that kept emitting tokens while never committing held the pre-commit wait to the full 600s ceiling. On the Desktop that blocked the gateway event loop for 10-20 minutes per turn and the renderer was eventually killed. - agent/turn_context.py::_fail_closed_on_insufficient_progress: when a preflight pass makes no (or sub-5%) progress and the request provably exceeds the model window, raise PreflightCompressionTimedOut with "start a new session (/new)" guidance so no provider call is sent. An unknown window or a fitting request keeps the send-as-is behaviour; a pass that no-op'd on a transient guard (summary-failure cooldown) keeps its typed cooldown result. Called from both insufficient-progress branches of turn_context_compaction._run_preflight_passes. - agent/conversation_compression.py::run_compress_context_with_progress_timeout: an over-window request's pre-commit wait is bounded by one inactivity budget (compression.context_timeout_seconds) instead of context_total_ceiling_seconds; the existing first-stall deterministic fallback then carries the compaction. Config-derived, no new knob. Slim slice of #116592's Python half. Co-authored-by: Chukuwebuka-2003 <ebulamicheal@gmail.com> |
||
|
|
e85cb94da1 | chore: merge origin/main (resolve agent/error_classifier.py,tests/agent/test_error_classifier.py) | ||
|
|
c8ecc3db64 |
fix: drop replayed reasoning_details on every chat-completions route that does not read it
OpenRouter and the Nous Portal replay reasoning_details for multi-turn reasoning continuity; every other OpenAI-compatible route either ignores the field or, when its schema is strict (Groq, Mistral, Cerebras, opencode relays), rejects the whole request with 400/422 once an earlier reasoning turn is in history — wedging the session after an in-session model switch (#70233). Strip the field from the wire copy in ChatCompletionsTransport.convert_messages (keyed on the target base_url), mirror it in the auxiliary wire boundary and the iteration-summary path; state.db history keeps the field so switching back to OpenRouter/Nous replays it again. |
||
|
|
f7567a62af |
fix: hand Codex reasoning-only stalls to the fallback provider instead of the incomplete sentinel
Three consecutive Codex Responses answers that carry only (encrypted) reasoning — no visible text, no tool call — used to exhaust the 3-continuation budget and end the turn on "Codex response remained incomplete after 3 continuation attempts", never touching configured fallback_providers (#67321). Encrypted reasoning items replay byte-for-byte, so a bare retry deterministically repeats the stall. - Track a per-turn `_codex_reasoning_only_streak` apart from the aggregate `_codex_incomplete_retries`: a visible partial resets the streak, so the mixed partial-then-stall variant still reaches its own recovery threshold while the turn-wide iteration budget stays the hard bound. - At streak 3, `continue_codex_incomplete` activates the next fallback with the semantic `FailoverReason.incomplete_response`, grants exactly one grace call when the trigger consumed the last iteration, and returns `CODEX_FALLBACK_ACTIVATED`; the intake re-syncs the Model:/Provider: identity on the system prompt. - Off the Codex wire the synthetic continuation nudge is stripped alongside the opaque replay state (`drop_nudge_marker`) so the Chat Completions payload keeps valid role ordering and no Codex-only control text. - No fallback configured: unchanged terminal sentinel, still bounded at 3 calls. Ported from PR #67336 by @PRATHAMESH75 onto the decomposed agent/turn_*.py siblings. |
||
|
|
8d25e69b6e | fix(desktop): use generated paste previews for titles | ||
|
|
303bcd804a |
fix(compression): a timed-out preflight compaction sends a fitting request and prune-commits an over-window one
A turn-start preflight pass whose summary stalled had no deterministic exit: the wrapper handed the transcript back unchanged, _fail_closed_after_preflight_timeout raised for ANY over-threshold request (even one that fits the model window — #113646: 99K of a 120K window), the loop labelled it compression_exhausted, the messaging gateway auto-reset the session (#114594), and the existing deterministic escalation (DETERMINISTIC_SUMMARY_ROUTE, #112420) was gated on a PRIOR stall in the same session — unreachable once the first stall had already wiped it. /compress rode the same wrapper, so the suggested recovery reproduced the same loop. - request_exceeds_model_window(agent, tokens): one predicate, two consumers. - Fits the window: the request is sent uncompressed this turn (the cooldown-blocked path already does exactly this every turn); the summary-failure cooldown stops the retry from repeating. - Above the window: the stall retry ladder escalates to the deterministic fallback summary on the FIRST stall (old tool results pruned, static handoff committed through the normal lease/fence pipeline). compression_exhausted / auto-reset is the last resort, when even that cannot shrink the transcript. - Per-attempt observable: one INFO line when the summary call is dispatched (model, prompt chars, prompt build ms) so a stalled attempt is distinguishable from a slow prompt build. - Deterministic-rung wording no longer claims "again after a stall backoff". Live repro (real AIAgent + SessionDB + local OpenAI-compatible stand-in whose summariser never answers within the idle budget): before — FITS(73K/200K) and OVER(73K/64K) both end failed=True, compression_exhausted=True, main_calls=0; after — FITS completes with the request sent uncompressed (main_calls=1), OVER commits the deterministic fallback (103->25 rows) and completes. |
||
|
|
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. |
||
|
|
6f8389d67b |
fix(aux): keep the /btw and title snapshots duck-typed; make the out-of-turn header tests discriminating
Follow-up on the salvaged #112721 commits (@fangliquanflq): - agent/turn_context.py, tui_gateway/methods_prompt.py: add ``session_id`` to the explicit snapshot dicts instead of switching them to ``agent._current_main_runtime()``. The titling prologue is duck-typed (its tests drive a minimal stub) and the snapshot values feed the ``runtime_validator`` equality checks, where ``_current_main_runtime()``'s ``"" `` for a missing attribute would no longer match the live ``None``. Same outcome — the background request inherits the conversation's ``x-opencode-session`` — without changing what the callers read. - tests/agent/test_opencode_session_affinity.py: the salvaged title test passed on an unfixed tree because the titler thread republishes the conversation contextvar (``set_conversation_context``) and the affinity header falls back to it. Replace it with two invariant tests (sync + async ``call_llm(main_runtime=...)`` with EVERY ambient source unset via the ``out_of_turn`` fixture): red on origin/main, green here; both also pin that the explicit binding does not leak past the call. - website/docs/integrations/providers.md: name the background/out-of-turn auxiliary calls the header now covers. Fixes #112717 |
||
|
|
de03c34233 | fix(auxiliary): preserve session in out-of-turn snapshots | ||
|
|
24ae31f7e7 | fix(gateway): retain pre-admission interrupted input |