Commit Graph

372 Commits

Author SHA1 Message Date
Teknium
0615c90df8 fix(agent): the "on <X> via acpx" ack cue names only ACP agents
The pronounless-action detector's "relaunching it on <provider> [via acpx]"
transition cue matched every registered provider name and alias, so a final
answer like "Launching it on Nous." kept the turn going. Restrict it to
external_process (ACP agent) profiles: their name, aliases and binary
(process_command), which is how agents refer to an ACP CLI ("on Copilot via
acpx" names the `copilot` binary). Main's answers for the ACP announcements
are unchanged.
2026-10-25 20:44:30 -07:00
Teknium
58cf3ee9ac refactor(agent): derive provider-named core sets from registered profiles
- auxiliary_client: the catalog-unavailable fallback of _builtin_provider_present
  no longer lists copilot/copilot-acp; a registered profile (canonical name) whose
  credentials the anonymous custom downgrade cannot carry (ambient_credentials or
  auth_type external_process) keeps its identity. Comments reworded generically.
- agent_runtime_helpers: the ack detector's "on <provider>( via acpx)" transition
  cue matches any registered provider name or alias instead of a hard-coded one.
- message_metadata: UNPRICED_REPLAY_FIELDS becomes unpriced_replay_fields(), the
  core carriers plus every declared ProviderProfile.message_carrier_* key
  (resolved lazily); model_metadata resolves it once per message.

Same answers for every Copilot input with the in-tree plugin present.
2026-10-25 19:26:48 -07:00
Teknium
b9712a0c9f refactor(providers): generic wire seams for per-model api_mode, endpoint headers, max-tokens param
Core branched on the Copilot slug/host for four wire decisions. Replace them with
generic ProviderProfile hooks (providers/base.py L1 block) and move the Copilot
logic into plugins/model-providers/copilot/wire.py:

- api_mode_for_model(model, *, api_key=None): run_agent Responses routing, aux
  CodexAuxiliaryClient wrap, model_switch.model_derived_api_mode (copilot rows
  of _PROVIDER_API_MODE_OVERRIDES removed).
- client_headers(*, base_url, api_key, has_images): agent_init/_client_lifecycle
  host tables, the client-kwargs chokepoint guard (_ensure_route_client_headers),
  the image request-client header swap, both aux header branches.
- request_headers(*, base_url, model, user_initiated): first-call-of-a-user-turn
  attribution in turn_api_request and MoA reference slots.
- max_tokens_param(*, base_url, model): run_agent._max_tokens_param and
  auxiliary_max_tokens_param.

agent/provider_route_hooks.py asks the named provider's profile first, then any
registered profile overriding the hook, so custom routes at a provider's host
keep its quirks. Plugin absent = generic behaviour.
2026-10-25 18:23:40 -07:00
rob-maron
cafa03f7f4 PR review comments 2026-10-21 23:05:11 -04:00
rob-maron
0e29e8a25a fix tests 2026-10-20 22:18:49 -04:00
rob-maron
15307dece7 Usage-window plan support 2026-10-20 21:04:30 -04:00
unsupportedpastels
0b5cf74487 fix(gateway): settle a queued steer by its admission, not by searching its text
Settlement withdrew a transfer by finding its text between newlines in the
agent's combined steer buffer. Those newlines also occur inside another
submission, so withdrawing a consumed 'alpha' stripped it out of a later
'alpha\nbeta': the consumed prompt was queued again and ran twice, the unread
one was recorded steered, and 'beta' leaked into a later turn. Identical text
on both sides of a drain had the same swap.

The agent's steer buffer now keeps each submission as a (ticket, text) part,
with _pending_steer still their newline join. The gateway hands a transfer
over with its admission id as the ticket. A drain records each ticket it took
as consumed, a hard stop records it as dropped unread, and a drained text put
back undelivered (_requeue_pending_steer) gets its tickets back.
withdraw_steer(ticket) settles exactly that submission: True while it is still
buffered (only its part is removed) or was dropped unread, False once a drain
consumed it.

Refs #134889 (RT-35)
Refs #140208
2026-10-17 14:25:35 -04:00
unsupportedpastels
e948784466 fix(providers): restore a custom primary from the entry its snapshot recorded
Restoring the primary after a fallback rebuilt credential ownership from
live config.yaml, not from the config the session resolved on. Two edits
made mid-session moved it onto another account:
- alpha and beta share one URL and the session runs on custom:beta. Once
  beta's live endpoint moves, the named lookup misses, load_runtime_pool
  falls back to URL-only matching, and the session resumes on alpha's
  `hermes auth add` key.
- the session runs on custom:deepseek with a declared key_env. Once the
  declaration is removed from live config, the entry looks credential-less,
  so the built-in's env row is no longer foreign and restore swaps to
  DEEPSEEK_API_KEY and api.deepseek.com.

Both `_primary_runtime` builders (agent construction and a model switch)
now record the owning entry's provenance (`custom_entry`), matched the way
resolution matched it, in the frozen scope when one is active. The record
holds the entry's name, provider_key, base_url, key_env names and whether
it declares a credential; it never holds a secret. Restore takes the pool
key and the ownership filter from that record, so live edits can't
reassign the endpoint or drop the declaration. A named identity whose
snapshot recorded no owner, including a snapshot from an older builder,
keeps its snapshot credential instead of borrowing by URL. A genuinely bare
`custom` snapshot without a recorded owner still matches by URL, as
before.

The two builders move unchanged into agent/primary_runtime_snapshot.py, so
agent_init.py and agent_runtime_helpers.py, both over the file-size
target, shrink instead of growing. test_primary_runtime_restore's
named-pool test now builds its agent under the config it restores with,
as a real session does; built without that config, its snapshot
correctly records no owner.

Refs #140297
2026-10-17 13:29:00 -04:00
unsupportedpastels
ed6414fd6d fix(providers): keep a built-in's key off a custom entry that shares its name
A `providers:` entry keyed like a built-in (`providers.deepseek` with
`key_env: DEEPSEEK_ENTRY_KEY`) has the durable pool slug `deepseek`, which
is also the built-in's pool id. `load_pool("deepseek")` seeds that pool
from the built-in's own env vars (`env:DEEPSEEK_API_KEY`), and the
named-custom rung reads the pool before the entry's key_env. Every turn
to the entry's endpoint therefore carried the built-in provider's key,
sending a credential to a host it was never configured for. Seen live on
v0.22.1 and main. The same slug pool was also loaded unfiltered by a
bare `provider: custom` route whose URL matches the entry, by restoring
the primary after a cross-provider fallback (which then swapped in the
built-in row's key and base_url), and by a delegated child's pool. With
the declared variable unset, the host-derived `DEEPSEEK_API_KEY` stood in
for it on DeepSeek's own host.

Credential ownership now holds on every pool acquisition for the entry's
runtime. agent/custom_entry_pool.py defines it by provenance: for an
entry that declares a credential (api_key, key_env/api_key_env or
key_cmd), a slug pool contributes only its manual (`hermes auth add`)
rows and rows seeded from the entry's own key_env; `custom:<name>` pools
stay whole. The entry-scoped view is applied on:
- main, frozen and auxiliary resolution, and URL-matched bare custom
  routes (the owning entry comes from the frozen config when present);
- primary restore, keyed on the snapshot's runtime identity (`custom` /
  `custom:<name>`), never on the shared slug: no owned rows keeps the
  entry's fixed credential;
- a delegated child's pool.
A bare custom route to an entry with a declared credential now gets that
credential, and a declared credential that resolves to nothing gets no
implicit host-gated env key (the key_env warning says so truthfully).

Unchanged: explicit built-in picks still use their env keys; the
built-in loads and persists its whole pool (persisting a view leaves the
omitted rows on disk); entries that declare no credential resolve as
before; manual rows keep their precedence on the main path, and aux
resolution stays configured-key-first.

Refs #140297
2026-10-17 13:29:00 -04:00
Teknium
52ccae4740 refactor: move the Codex recovery rungs out of turn_recovery
turn_recovery.py crossed the 2,000-line gate once the reasoning-replay recovery
landed beside it. The stale-encrypted-reasoning rungs and the replay-verdict
reset are one topic; they move verbatim to agent/turn_recovery_codex.py.
2026-10-10 19:22:07 -07:00
Teknium
208fd6e43d refactor: move the stream tool-call accumulator out of the chat-completions facade
Offsets the facade growth from the carrier capture (code-health FILE_LINES/CC
ratchets): _ToolCallAccumulator moves to chat_completion_helpers_tool_calls.py,
the Copilot reasoning_text fallback folds into StreamCarriers.feed, and the
reasoning_text display rides NormalizedResponse.reasoning instead of a new
branch in agent_runtime_helpers.extract_reasoning.
2026-10-10 19:22:07 -07:00
Teknium
2b2e4d908d fix: Gemini and Copilot keep their reasoning carriers across turns
Gemini text-turn thought signatures (native thoughtSignature on a text or
trailing empty-text part; OpenAI-compat/Vertex message-level
extra_content.google.thought_signature) were discarded at capture, and the
Copilot /chat/completions reasoning_text / reasoning_opaque fields and the
Gemini-3 function.thought_signature were never read. Replaying the Gemini
text-turn signature makes the server rehydrate the turn's thoughts (live:
31 -> 237/250 prompt tokens).

agent/reasoning_carriers.py captures them (stream + non-stream), stores
them top-level on the live dict plus one private
hermes.native_assistant reasoning_details record (persisted in the
existing column, so resume/gateway replay keep them), and lifts each one
onto the wire only for the route that reads it: extra_content on the
same Gemini gate as tool-call extra_content, reasoning_opaque/text and
function.thought_signature only to githubcopilot.com. The private record
is never forwarded (no profile declares that type). Copilot reasoning_text
is shown as the turn's reasoning.
2026-10-10 19:22:07 -07:00
Teknium
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.
2026-10-10 19:22:07 -07:00
Maciej Lisiewski
32b70e9733 ci: FURB188, FURB192 linter fixes 2026-10-09 17:31:52 +02:00
Maciej Lisiewski
4278b6aa24 ci: RUF013, RUF015 2026-10-08 21:29:48 +02:00
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
184a83de33 refactor(agent): import the interrupt placeholder at module level
agent_runtime_helpers (two sites) and message_sanitization imported
_INTERRUPTED_PLACEHOLDER inside the function body. The placeholders
module is a leaf with no imports, so there is no cycle to dodge; import
it once at module level (each module still imports cleanly in a fresh
interpreter). conversation_loop keeps its local import.

Gate rP finding 7 (quality).
2026-10-07 18:15:29 +05:30
kshitijk4poor
2bbb37b973 refactor(agent): move interrupt placeholders into agent_runtime_helpers_placeholders to keep files under the size cap
Code-health ratchet: agent/agent_runtime_helpers.py was 3787 > 3776 and
tests/agent/test_run_agent.py 7014 > 7012 (both over the 2,000 target, so
they may only shrink vs main).

- _INTERRUPTED_PLACEHOLDER / _LEGACY_INTERRUPTED_PLACEHOLDER (and their
  rationale comment) move byte-identically into the leaf sibling
  agent/agent_runtime_helpers_placeholders.py. Every importer (runtime
  helpers via late import, conversation_loop, message_sanitization,
  turn_api_call, turn_iteration_prep and five test files) now reads the
  sibling; no shim is left in the facade. Nothing patches the old path.
- test_keyboard_interrupt_emits_cancelled_post_tool_hook moves unchanged
  into tests/agent/test_run_agent_interrupt_hook.py, reusing the facade's
  agent fixture.
2026-10-07 18:15:29 +05:30
alrcatraz
703200b803 fix(agent): stop the interrupt placeholder echoing back as a reply
A hidden assistant row is hidden from the transcript, not from the request:
the projection substitutes its api_content sidecar into content on every call.
The value chosen for that slot in #88955 was "[response interrupted]" - a short
natural-language phrase sitting in the model's own prior-turn position, which
models reproduce verbatim: an ordinary instruction answered with clean
finish_reason=stop and nothing but the placeholder (#132949). The same hazard
was already recognised twice in this codebase - the redirect scaffold is
barred from assistant text because "the model echoes it" (#81841), and a
runaway repetition partial is replaced by a self-describing label rather than
replayed (#112764) - but the placeholder was never given the same treatment.

Change the placeholder to a structural label the model has no reason to say,
and retire rows already persisted under the pre-change spellings: the prep
filter that dropped scaffold ghosts now also drops hidden rows carrying the
legacy placeholder or the scaffold marker.

Dropping is not always safe. A hidden close appended after a tool result is
the only thing separating that tool message from the next user turn; removing
it recreates the tool -> user alternation violation that makes strict providers
ignore prior context (#48879) - the exact failure the close exists to prevent,
and one repair_message_sequence deliberately leaves alone. When the neighbours
would form that pair, rewrite the row's text instead of dropping it. The
rewrite targets the current placeholder, so a neutralised row never re-triggers
the filter.

(cherry picked from commit 227e9a1ed64e0d75594d031423ecd2f5c74cd0b9)
2026-10-07 18:15:29 +05:30
Teknium
1541036775 refactor(agent): extract the fallback route swap and primary restore into route_binding
try_activate_fallback's in-place swap (client, pool, compressor, reasoning, extra_body) and
restore_primary_runtime's reinstall are now agent/route_binding.py::bind_route_entry and
::reinstall_primary_runtime / ::reinstall_runtime_snapshot, so a per-turn route can reuse the
same binder instead of a third copy. No behaviour change.
2026-10-07 01:35:11 -07:00
Brooklyn Nicholson
82732650a1 refactor(agent): move dead-connection sweep into a runtime-helpers sibling
Keeps agent_runtime_helpers.py within its code-health line cap and logs the
best-effort probe/cleanup failures with their traceback (BLE001).
2026-10-07 00:07:02 -05:00
Kenshi
cf6fada002 fix(agent): clean cached request pool sockets (#91286) 2026-10-07 00:07:02 -05:00
kshitijk4poor
2f0efe8f66 refactor(agent): derive reasoning-promotion trust live in agent/reasoning_promotion
The code-health ratchet blocks growth of agent_runtime_helpers.py
(3909), agent_init.py (2527), chat_completion_helpers.py (4122) and
finish_text_response (309 lines); the gate added 60+ lines to those
facades.

Move answer_in_reasoning_capability into a topical sibling and evaluate
it from the agent's live route at the promotion site instead of caching
the decision in runtime_capabilities. That removes the plumbing at
startup, primary snapshot/restore, switch_model and fallback activation:
a live check cannot go stale across a route change, so the whole
sibling-site class is covered by construction. The unused constructor
`capabilities={"answer_in_reasoning": ...}` hook goes too (no caller
sets it); an explicit runtime_capabilities bool and the
custom_providers per-model opt-in still work.
2026-10-06 13:01:39 +05:30
kshitijk4poor
806b1e99c9 refactor(agent): drop defensive capability try/except and dead reasoning_only copy
get_custom_provider_model_capability already returns None when the
config cannot be read, so the try/except around it in
answer_in_reasoning_capability only hid real bugs.

_terminal_empty no longer returns site_copy("reasoning_only") with a
reasoning preview, and nothing else references that entry, so remove it
instead of leaving dead copy behind.
2026-10-06 13:01:39 +05:30
Mohamad Kanso
71c1669404 fix(agent): gate reasoning-only answer promotion by route
A clean-stop response with empty content and a reasoning payload was
promoted to the visible answer on every route. A field name is not
provenance: OpenRouter, DeepSeek and other adapters put private
chain-of-thought in `reasoning`, so users saw the model's private
thoughts as the reply (#111761, #114082). Exhausted recovery also echoed
a 500-char reasoning preview.

Promotion now requires a trusted route: an explicit
`answer_in_reasoning` runtime capability, a custom_providers per-model
opt-in, or the local Nemotron-3.5-Lightning parser route from #109205.
The decision lives in runtime_capabilities and is re-derived at startup,
fallback activation, primary restore and model switch. Exhausted
recovery returns the empty sentinel without a reasoning preview.

Rebuilt by hand on current main (keeps the Anthropic signed-thinking
skip and the _refund_api_call import added since the PR's base).

Salvaged from #112833 (a339569d77, 15a19b2fc0, 1d240e7b24).
2026-10-06 13:01:39 +05:30
Teknium
22bc7eac71 refactor(solstice): rebuild the provider as a standard model-provider plugin
The whole provider now lives in plugins/model-providers/solstice/ on the
generic seams:
- auth.py: NAS config discovery plus the brokered exchange/refresh, given
  to the generic PKCE flow as token_request. A refresh that NAS rejects
  (it folds every Google failure into 502) is treated as a dead grant
  needing re-login.
- transport.py: a GeminiNativeClient subclass on the
  generateContentPerUserQuota methods with Bearer auth (~30 lines, where
  the PR duplicated a 257-line adapter).
- __init__.py: a hidden profile (create_client, fallback models,
  default_aux_model).

Removed from core: hermes_cli/solstice.py, agent/solstice_adapter.py, and
the provider's branches in main.py, auth_commands.py, models.py,
runtime_provider.py, model_setup_flows.py and agent_runtime_helpers.py.
The unused SOLSTICE_CLIENT_ID env read is gone too.
2026-10-05 23:33:41 -07:00
Ben Barclay
8e015f483f feat(providers): add Solstice as a secret-launch OAuth inference provider
Per-user-quota OAuth inference for Hermes Agent, hidden by default until
public launch is cleared. Auth (OAuth2 + PKCE with the user's account) is
brokered by nous-account-service, which holds the confidential client secret;
inference goes direct to the per-user-quota endpoint.

Built fresh on current main; commit history carries only the codename.

Provider surface:
- plugins/model-providers/solstice/ — profile + hidden enable gate
- hermes_cli/solstice.py — PKCE loopback login, NAS-brokered config/exchange/
  refresh, token store, quarantine; callback path unchanged
- agent/solstice_adapter.py — per-user-quota transport over the native
  adapter's OpenAI-compatible facade
- providers/: _HIDDEN_GATES + register_hidden_provider_gate + a hidden filter
  in list_providers (kept out of the picker/registry/doctor until enabled)
- wired into main.py (_PROVIDER_MODEL_FLOWS), auth_commands.py (_PROVIDER_ALIASES,
  _OAUTH_ADD_SPECS, _is_known_provider allowlist), models.py (catalog fetcher),
  runtime_provider.py (resolution rung), model_setup_flows.py, agent_runtime_helpers.py

Kept verbatim (the live wire contract, until the broker is renamed): the
inference host, the OAuth scope, the deployed broker routes, and the
registered redirect callback path.

The enable gate is unchanged (open item: gate on stored credentials).
Verified: 226 focused tests pass; runtime resolution, client construction
and auth-add all exercise the real paths.
2026-10-05 23:33:41 -07:00
Brooklyn Nicholson
3a009f97c1 fix(agent): detect pronounless action acknowledgements (#72692)
Port of #72710 by @foma-agent onto current main.

With provider: copilot-acp the model sometimes announces its next action
and ends the turn without emitting a tool call, in terse log style with
no first-person lead-in: "Brief written. Creating the session now."
The intent-ack detector only matched first-person future acks
(_ACK_FUTURE_RE), so the task stalled until the user sent another
message.

looks_like_codex_intermediate_ack now also accepts a narrowly bounded
pronounless action clause: a present-participle action verb that begins
the response or follows a sentence/status/newline boundary, plus an
explicit transition cue ("now", "on Copilot via acpx", "the actual log",
"with corrected arguments", "whether ... healthy", ...). Questions,
completed reports ("Testing complete."), bare status counters, retry
counters and numbered/option lists stay final.

The 16-commit PR branch predates main's agent_runtime_helpers refactor
(dead-predicate prune eb67765c58, module-level _ACK_* constants), so the
final state is re-applied by hand: main's constants are kept, the
pronounless detector folds into the guardrail chain, and the PR's test
corpus (21 announcements that continue, 70 finals/questions/status
lists that do not) is restored minus the test for the pruned
intent_ack_continuation_enabled helper.

Co-authored-by: foma <foma@bokonon.ai>
Fixes #72692
2026-10-05 16:41:57 -05:00
loulanyue
52189fd65f fix(runtime): normalize dual-surface base URLs for OpenAI chat-completions (#102247)
- Normalize dual-surface endpoints (e.g. api.kimi.com/coding -> /v1) in create_openai_client
- Prevents HTTP 404 when OpenAI SDK appends /chat/completions to bare /coding endpoints
- Preserves native Anthropic wire endpoints when hitting Messages API
- Add unit tests in tests/agent/test_kimi_coding_openai_base_url.py
2026-10-05 16:40:46 -05:00
unsupportedpastels
3f04ecb789 fix(compression): preserve exact coverage through composed repairs
(cherry picked from commit ff3e655f1e9cc8182dbb06df3922fb3b341225b2)
2026-10-03 18:17:35 +05:30
unsupportedpastels
da88c23c02 fix(compression): a row the repair drops is named, not a reason to fall back to the watermark
On a reload without row ids, a dict that stood for rows the alternation repair
dropped or folded made coverage_for_commit return (None, None). The watermark
path then archived every active row below it, including rows another surface
appended that the compressor never saw: they left the model's history without
being in the summary (the unseen-gap contract of 1674499d00).

The repair now records role, content and tool-call ids of each row it retires
without an id, and of an assistant survivor before a fold rewrites its text.
The commit matches each to exactly one active row at or below the watermark and
keeps exact coverage; a retired row widens the carried-tail rewind like a merged
row. An ambiguous or missing match, or a count the recorded rows do not cover,
still takes the watermark path.

The approach of stashing id-less dropped rows as unresolved held coverage comes
from #129162.

Co-authored-by: JerryLiu369 <953639086@qq.com>
(cherry picked from commit 312474b424ede18f01433860309d23526c08e6b3)
2026-10-03 18:17:35 +05:30
John Paul Soliva
6eb90cac31 fix(compression): a row the repair drops ahead of the first survivor is accounted for
The repair retires a dropped row onto the survivor before it. With nothing kept
before it (a stray tool result or an unanswered tool call as the first active row)
the row stayed unnamed, and an in-place compaction cloned it behind the compacted
set. The first dict the pass keeps now stands for the rows dropped ahead of it, by
row id or by count.

The leading-drop case comes from #129162.

Co-authored-by: JerryLiu369 <953639086@qq.com>
(cherry picked from commit 2facd175120acfd99b3e566bd1647e0f4b7767fb)
(cherry picked from commit 90faa5025ba4fd88a8cce967856c592f23776f27)
2026-10-03 18:17:35 +05:30
John Paul Soliva
63c34ec442 fix(compression): the repair counts every durable row it retires without an id
Two more shapes reached the in-place commit with rows nothing named:

- Two killed tool calls in a row. The repair merges the two assistant rows,
  which pops the persist marker, and then drops the merged dict. The drop
  was gated on that marker, so neither row was retired and carried
  messages were recalled twice on every reload shape.
- Two assistant rows in a row on a reload without row ids. The merged dict
  equals neither row and has no marker, so the commit read it as a turn
  that was never persisted: the gateway hid a summarized message and the
  CLI restore recalled the oldest carried message twice.

A dropped dict's row ids are now retired whatever its marker says, as
assistant turn as well as a dropped one, and a dict that carries a count
is known to have been loaded. The key is renamed _unnamed_durable_rows to
say what it counts.

(cherry picked from commit 9bf1653471ecceed23794f09f7659986c43b7404)
(cherry picked from commit 7f4c8f540ea035d68a8cb1696b5da39deeba5f37)
2026-10-03 18:17:35 +05:30
John Paul Soliva
7e3bc5b60d fix(compression): in-place compaction accounts for the rows the repair drops
A turn killed after its tool call was saved leaves a call with no result in
state.db, and the alternation repair drops that row from every reload (a
result it cannot pair goes the same way). The in-place commit then had a
durable row nobody named:

- with row ids (--resume, TUI, Desktop) it was taken for a row another
  surface appended and re-sequenced behind the running turn, again at
  every later compaction;
- without row ids (gateway, ACP) it was either re-sequenced the same way
  or took a slot of the positional tail rewind, so the oldest carried
  message stayed compacted=1 beside its live copy and was recalled twice.

The repair now retires a dropped durable row onto the survivor before it:
its row id joins _absorbed_row_ids, and a reload without ids counts it in
_dropped_durable_rows, which the gateway replay entry carries. A held dict
with such a count keeps the commit on the watermark path, and the tail
rewind widens by it.

On that path _uncounted_merged_rows skipped any dict that listed absorbed
ids. A merged dict can list some of its rows and not others (two unanswered
prompts from a reload without ids, then a persisted one), so it now widens
by the stamp less the ids listed.

(cherry picked from commit d27dec2be6a8e371ff5370e3e0fa5d3f2548622c)
(cherry picked from commit 4f74851c1aa7412d9ac5129ec8e52ca9fcf50798)
2026-10-03 18:17:35 +05:30
John Paul Soliva
3154ccfe76 fix(compression): a merged user dict names rows by provenance, not by text
The commit resolved a marker-less user dict to a run of active rows whose
joined text equals it. A prompt that was never persisted can carry the same
text as a user;user pair another surface appended after the snapshot, so
those unseen rows were archived as summarized instead of being cloned after
the compacted set.

The alternation repair now stamps the dict with how many durable rows it
folded, the gateway replay entry carries that stamp, and the commit resolves
a run only for a stamped dict of that exact width. Folding an unpersisted
turn into the dict drops the stamp.

(cherry picked from commit 13bbb4d1c4c13874bd825d212503f9d9539060f0)
(cherry picked from commit df3fca28cba8a2758c5c711cc0ee582a8e374d51)
2026-10-03 18:17:35 +05:30
kshitijk4poor
06be0643c9 refactor(codex): share response socket walk and simplify post-terminal drain
_post_terminal_socket duplicated the response -> network_stream/stream ->
connection-candidate walk from _shutdown_stale_attempt_socket. Hoist it into
agent_runtime_helpers._socket_from_response (next to _socket_from_candidate)
and use it from both sites; each caller keeps its own error handling. Drop
the dead event_stream argument: ManagedLlmStream has no .response, only the
raw SDK stream does.

Fold watchdog.start() into the drain try so cancel/join lives once in the
finally (join only when a thread was actually started), replacing the
duplicate start-failure branch and its suppress-wrapped join.

Close guard: relay_llm.stream is ManagedLlmStream, whose close() always
exists and owns the provider stream, so the raw stream only needs closing
when construction failed (event_stream is None). Behaviour-equivalent to the
callable(close) probe.
2026-10-03 16:31:39 +05:30
kshitijk4poor
c7ffe6e7de refactor(agent): trim the sentinel-decode pre-pass and its test
Lead-verified lows from the B07 gate: _normalize_sentinel_encoded_content's
restored counter was never read, so it now returns None; the call-site
comment repeated the docstring; the marker-keep and _plain_text comments
are cut to the reason. In the test, the "base64" not-in assert was implied
by the exact-equality assert above it, and AIAgent is already imported at
module level. No behaviour change.
2026-10-03 16:30:08 +05:30
kshitijk4poor
0243427bef fix(agent): refuse to weld a corrupt sentinel row; decode via SessionDB
The decode pre-pass leaves a \x00json: body that no longer parses as a
string, and _merge_consecutive_users then concatenated the next user
turn onto it, burying the undecodable base64 deeper. Treat a str that
still starts with the sentinel as non-plain-text so the merge skips it,
like native multimodal lists.

Decode through SessionDB._decode_content (lazy import) instead of a
copied "\x00json:" literal + json.loads, so the persistence layer stays
the single owner of the codec. Its behaviour matches: scalars and
unparseable bodies come back unchanged.

Co-authored-by: Yuan Li <dskwelmcy@163.com>
2026-10-03 16:30:08 +05:30
PRATHAMESH75
790d6eaf39 fix(agent): keep the durable marker on a storage-equivalent sentinel decode (#125331)
The pre-call sentinel decode restores a multimodal row's structured content in place, but the
decode is representation-only: `SessionDB._encode_content(decoded)` reproduces the exact
`\x00json:` scalar already stored, so the durable row is not stale. Dropping its `_db_persisted`
marker made the append-only flush treat the historical user turn as new (user `_row_id` values are
never update targets in `resolve_and_repair_transcript_batch`), re-appending a duplicate user turn
on the durable transcript (review: ehz0ah).

Keep the marker on decode and document why; the merge/prune passes still drop it only when the
durable bytes actually change. Add a real SessionDB + `_persist_session` regression that decodes a
stamped durable sentinel row and asserts the stored row count and role order do not change after the
flush — a duplicate the content-only repair tests cannot catch.

(cherry picked from commit a2617d687aed0df057eb27cf81168ff605579b25)
2026-10-03 16:30:08 +05:30
PRATHAMESH75
9d7b78f0c6 fix(agent): decode sentinel-encoded multimodal turns before the alternation repair (#125299)
After a proactive prune re-inserts a session's history, a multimodal user
message (text + image) can return stored as its persistence-encoded string
("\x00json:[...]") instead of a content list. The message-alternation repair
guards multimodal content by checking isinstance(content, str), so the encoded
string slipped through as plain text: _merge_consecutive_users concatenated the
base64 image onto the neighbouring text turn, producing a ~426K-char blob that
the model received and that no longer decoded as JSON.

Decode any "\x00json:"-prefixed row content back to its structured form at the
top of repair_message_sequence, before the passes run. The restored list then
hits the existing multimodal guard and is left un-merged. A body that no longer
parses (already merged / corrupted) is left untouched rather than crashing the
pre-call repair. The sentinel is mirrored as a module constant so the repair
layer need not import the persistence class.

(cherry picked from commit a7ec929316b750636ef73be718a8e428c839a490)
2026-10-03 16:30:08 +05:30
dsad
1798b335c4 fix(agent): reasoning replay verdict resets when the route changes
The Responses replay kill switch (_codex_reasoning_replay_enabled) was
session state that nothing reset, so a route that tripped it kept replay
off on every route the session moved to afterwards: a /model switch,
fallback activation, or the turn-start restore back to the primary.

The verdict now belongs to the route that earned it: all three route
changes reset it, and the switch rollback snapshot covers it.

Salvage of #61552 (reapplied on current main; the original's
switch_model / restore hunks no longer apply).
2026-10-01 12:08:13 -07:00
kshitijk4poor
105e876586 perf(fallback): stamp the early-reopen throttle before loading the pool
Stamped only on a benched pool, a cooling-down session whose pool was not benched (backoff without a reset, the exhausted-chain cooldown) reloaded auth.json on every turn, where main returned without I/O. Stamping as soon as the interval admits a check caps that at one pool load per probe interval; a check sooner could only replay the probe's cached verdict.
2026-10-02 00:03:01 +05:30
kshitijk4poor
74449250c7 docs(fallback): fold the stranded #20465 comment into its branch; keep the pool docstring caller-free
The comment explains the index reset in the not-activated branch, which already carries a two-line version of it; the rate-limit check that used to sit under the long copy moved. The new pool method's docstring named its one caller.
2026-10-02 00:03:01 +05:30
kshitijk4poor
a3512a527f fix(fallback): one early-reopen restore per probe interval, not one per turn
The Codex usage probe caches its verdict per token for five minutes and a
fresh 429 does not clear it. When the endpoint reports quota left while
requests still 429, a fallback-pinned session restored the primary, failed,
and fell back again on every turn of that window, each turn costing a failed
request and two notices.

Lift at most once per probe interval per agent, stamped only when the pool
is actually benched. A genuine reopen is still picked up within one interval,
and benched turns between checks return before touching auth.json again.
2026-10-02 00:03:01 +05:30
xxxigm
c5a68f0777 fix(fallback): lift a reopened Codex quota window before gating the primary restore
A Codex 429 benches the pool entry and arms the session cooldown until a resets_at that can be days out. The pool's throttled usage probe notices an early reopen (redeemed reset, top-up), but only on select(); a session pinned to its fallback gates on the cooldown and next_available_at, which never probe, so it stayed on the fallback for the whole declared window.
2026-10-02 00:03:01 +05:30
liuhao1024
696f6e9ff9 fix(agent): keep marker-merged user rows addressable after alternation repair
A model-switch marker is persisted as role=user on purpose (#48338), so
the next real user row forms a user;user pair that repair_message_sequence
Pass 2 merges into the earlier (marker) row — keeping its display_kind and
dropping the plain row's _row_id from the repaired view. Every rewind /
prompt.submit addressing surface indexes non-display user turns, so the
merged pair became unaddressable and the client's next submit with
truncate_before_row_id failed closed with the input silently dropped
(#94486).

Keep the merged pair addressable: drop the display classification and
carry the plain row's durable id. display_kind never reaches providers
(stripped from every outgoing copy), so the wire payload is unchanged.

Fixes #94486
2026-09-30 23:18:06 -05:00
kshitijk4poor
0cabdf3f64 fix(sessions): an assistant fold ignores a non-dict uid map on the surviving turn too
The absorbed turn's map already had the dict guard; a plugin-built survivor carrying a malformed
map still raised in the per-occurrence expansion. Pre-existing (the old merge raised the same way).
2026-09-29 04:15:21 +05:30
kshitijk4poor
dd66c132f2 fix(sessions): keep tool-call uids paired through rewrites, folds of repeated ids and chunked copies
Found by the pre-merge correctness and hermes-specific review of this stack:
- A fold after a row whose one response repeated a provider id (one shared uid) appended the
  absorbed turn's uid in the wrong slot. The shared uid now fills each of the row's own
  occurrences before the fold appends (per_occurrence_tool_call_uids). A single response keeps one
  shared uid for a repeated id: every result carries it, so no call looks unanswered.
- A digest-less re-flush of a restored fold (replay heal, adopt after a digest mismatch) let the
  stored pre-fold map overwrite the longer live list, so the later occurrence's results paired
  with nothing. A live list that starts with every stored occurrence is kept (stored uid or list).
- A dict that lost its uid map (a clone) rewrote tool_call_uids to NULL. The row-addressed
  rewrite now fills stored uids for the calls the dict still names; a call it dropped keeps none.
- append_messages_batch(chunk_rows=...) reset the pairing index per chunk, so a result in the chunk
  after its call was stored without tool_call_uid (branch/seed copies). The whole batch is paired
  before it is chunked.
- _merge_assistant_into keeps its dict guard on the absorbed turn's map (a plugin-built dict with a
  non-dict map no longer raises).
2026-09-29 04:15:21 +05:30
kshitijk4poor
2be9fa5f9d refactor(sessions): simplify-code pass over the identity helpers
- without_persistence_fields() replaces the two hand-written strips (context-engine selection,
  token-estimate fingerprint).
- mint_uid() is the one uid minter; uid_list() the one uid-list normalizer (message_metadata's
  _absorbed_uids and the codec's _uid_list share it).
- _live_or_column() replaces four copies of 'live key first, column name second'; the absorbed
  list writer takes the dict, not a (live_key, column) pair its one caller always passed the same.
- _restore_row_identity() is the one stored-identity-onto-live-dict step, shared by restore and
  the row-addressed rewrite (transcript_repair had a hand copy). Restore skips the decoders for
  NULL columns (the common row).
- index_tool_call_uids() returns the variants it named, so the flush walk stops computing them
  twice; tool_call_uid_from_history drops guards its one caller can't trip.
- rewind returns the replacement dict (the insert already stamps _row_id and message_uid)
  instead of re-querying last_insert_rowid.
- _remember_absorbed_row's folded is required, so every call site states the witness rule.
- The backfill reads/deletes state_meta through _meta_row/_delete_meta; chat_completions strips
  MESSAGE_UID by constant.
No behaviour change.
2026-09-29 04:15:21 +05:30