Commit Graph

7372 Commits

Author SHA1 Message Date
Teknium
882482b58a fix(compression): the active-request bridge obeys the post-handoff progress floor
When the first post-handoff tool group ends right before the active user
request, the progress floor lands on that request, and _compress_window's
assistant/tool bridge then pulled the cut back onto the group's assistant:
the window held only the handoff and compress() no-oped with
empty_post_handoff_window. The bridge now moves the cut back only down to
tail_cut_progress_floor (one rule); when the floor sits on the active request
the summary merges into that row through the existing merge path.
2026-10-28 20:39:24 -07:00
Teknium
f6a84fd6d9 fix(compression): a tail cut inside the first post-handoff tool group still compacts
After a compaction the transcript opens with the handoff followed by a tool
group. When the raw tail budget broke inside that group, the cut was aligned
back onto the group's assistant, leaving a window that held only the handoff.
The handoff scan drops standalone handoff rows, so compress() returned the
empty_post_handoff_window no-op and the session stayed over the trigger with
no warning. Since #144824 priced pre-handoff rows at zero, the whole-transcript
re-cut takes this path routinely.

The progress floor now requires one row the scan keeps: when every row before
the cut is a handoff, the cut moves past the next tool group, unless that
would take the newest row or the active user request out of the tail.

Found on the C4 e2e suite: test_good_summarizer_compacts_and_keeps_every_invariant[11]
failed deterministically since 52a01bd2f2.
2026-10-28 20:39:24 -07:00
Victor Kyriazakos
a8b987aaa1 fix(bedrock): apply configured request timeouts to Bedrock clients
providers.bedrock.request_timeout_seconds and
providers.bedrock.models.<model>.timeout_seconds resolved correctly through
hermes_cli.timeouts.get_provider_request_timeout, but no Bedrock client was
built with the result. The cached boto3 bedrock-runtime client (ambient and
profile-scoped) was created with no botocore Config, so it kept botocore's
60s read / 60s connect, and the AnthropicBedrock SDK client was built with
_client_timeout(None), i.e. a fixed 900s read. The resolver (3143d32330)
landed after the cached Converse client (0cb8c51fa5) and was wired only into
the OpenAI-wire and native Anthropic builders; 611657487f documented Bedrock
as not covered instead of wiring it.

- _get_bedrock_runtime_client(region, model) resolves the model's timeout
  (model over provider) and passes Config(read_timeout=..., connect_timeout=60)
  only when one is configured; unset or invalid builds the exact
  no-Config client used before.
- Both client caches (ambient and per-profile-home) key on the effective read
  timeout, so models with different overrides in one region never share a
  client, and the same timeout reuses one client. Stale-connection eviction
  drops every timeout slot of the region.
- converse/converse_stream dispatch picks the client from the request's
  modelId, so a /model switch or a fallback to another Bedrock model uses
  that model's timeout. call_converse and the context probe pass their model.
- AnthropicBedrock: build_anthropic_bedrock_client takes the timeout; the
  bound client and the per-request client key carry the active model's
  value (connect stays 10s, unset stays 900s).
- Docs: replace "not currently wired for AWS Bedrock" with what is wired.

This closes a configuration gap only. A socket read timeout bounds each read,
not the whole call; retry policy and the stale detector are unchanged.
2026-10-28 19:51:15 -07:00
yliu325
b81e71addd feat(cron): optional per-job grace_minutes override
The catch-up window (how late a missed cron occurrence may run instead of being skipped) was
half the job's period, clamped to 120s-2h, for every job. A job can now override it outright:
0-1440 minutes, `0` meaning never catch up.

`grace_minutes` is a real 0, not "unset" — and the obvious write pattern would eat it:
`v in {None, "", False}` (the `workdir` update lambda) and `if value:` both treat `0` as
False in Python. Both doors therefore share `jobs_time.normalize_grace_minutes`, reads test
`is None`, and the renderer formats before testing truthiness.

The override moves the dispatch stamp too: `_classify_dispatch_lateness` and the dispatch
health metric read the same window, so a job the scheduler calls "late" is never reported
overdue by the dashboard.

Refused on `once`/`interval` schedules: the window describes a missed wall clock, and a
duration has none.

Split from the timezone commit so it can be reverted alone.
2026-10-28 19:40:40 -07:00
Victor Kyriazakos
47ec37e427 fix(sessions): a Bot Chat capability rebuild also satisfies a pending prompt refresh
The Bot Chat capability-refresh branch rebuilt and persisted the prompt
without recording the refresh epoch, so a pending `refresh-prompts`
request rebuilt the prompt a second time on the next turn, and a warm
agent restored through that branch never adopted a later request.

Read the requested epoch before that build and stamp it after the
persist, the same read-before-build contract as the first-build path.

Tests: a Bot Chat rebuild with a request pending is the only rebuild,
a warm agent rebuilt through Bot Chat adopts a later request, a warm
agent that restored its prompt from the row adopts a later request, and
a warm agent with no request never rebuilds across turns.
2026-10-28 19:30:48 -07:00
Victor Kyriazakos
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.
2026-10-28 19:30:48 -07:00
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
Victor Kyriazakos
93286ffd87 fix(bedrock): an unresolved application-profile ARN issuer is unknown, not foreign
A Claude configured by application-profile ARN stamps its Converse turns with the ARN. Without
bedrock:GetInferenceProfile the ARN stays unresolved, names no model, and was treated as a non-Claude
issuer, so a switch to a plain Claude id dropped Claude's own signed thinking on both Bedrock wires.
2026-10-28 19:21:51 -07:00
Victor Kyriazakos
e34d84897a fix(bedrock): Claude never gets a GPT turn's sealed reasoning on the Anthropic Messages path
A Bedrock session that switches from a reasoning GPT (Converse) to Claude with /model, or falls back
from one to the other, failed every Claude turn with
`HTTP 400: messages.N.content.M: Invalid `data` in `redacted_thinking` block` and then failed over to
GPT ("Fallback activated: <claude> -> <gpt> (bedrock)"). The only workaround was /new.

#142139 filters reasoning by issuing model on the Converse path only: a turn stamped by a non-Claude
model (CONVERSE_ISSUER_TYPE) replays no reasoning to Claude there. Claude on Bedrock runs on the
AnthropicBedrock (anthropic_messages) path, whose converter copied every thinking/redacted_thinking
block out of reasoning_details, GPT's sealed blob included. The classifier did not help either: the
rejection names none of the signature words, so it landed as format_error (non-retryable, fallback)
and never reached the existing thinking_signature strip-and-retry.

Two layers:

- Root: assistant_replay_carrier's reasoning_details carrier (_extract_preserved_thinking_blocks) yields
  nothing for a turn a non-Claude Converse model stamped, on every route and inside the in-flight tool
  loop. The predicate is #142139's, shared as bedrock_adapter.reasoning_minted_outside_claude (Converse's
  _reasoning_filter now calls the same helper). Claude's own turns (unstamped on AnthropicBedrock, or
  stamped by a Claude model on Converse) replay as before. Unstamped turns keep replaying, as on
  Converse: Claude mints redacted_thinking itself and its AnthropicBedrock turns carry no stamp, so
  "unstamped" cannot mean "foreign".
- Safety net: a 400 naming an invalid `redacted_thinking` block classifies as thinking_signature, so
  turn_recovery's one-shot strip (remember_rejected_thinking on signed-replay routes) removes the blob,
  persists the suppression for the session and retries on Claude. This covers unstamped GPT turns from
  sessions older than the stamp. It runs after the OpenAI Responses thinking_signature_invalid rule, so
  that class and invalid_encrypted_content keep winning.

Refs #142139
2026-10-28 19:21:51 -07:00
Teknium
81985c6bd4 fix(vault): keep the fill's nonce-stamped selector; collect shadow roots once 2026-10-28 19:00:07 -07:00
Teknium
b79946d2ee fix(vault): shadow-root fills reach host listeners and shadow login tabs
The fill events now cross the shadow boundary (composed), so a component tracking its value on the
host sees the password; tab selection finds a form inside an open shadow root; the fill script
collects the stamped controls once instead of walking the page per field.
2026-10-28 19:00:07 -07:00
Teknium
5a4c234a9c fix(vault): shadow-root forms keep their form grouping and shadow-tree labels
document.forms misses a <form> inside a shadow root, so its controls had no formIndex and split OTP
boxes from two such forms counted as one group; aria-labelledby ids inside the shadow tree were not
resolved. Forms are collected in the same walk and labels resolve against the control's root first.
2026-10-28 19:00:07 -07:00
Teknium
0a93a2341f fix(vault): fill saved logins on Camofox pages through a browser page backend seam
browser_vault reached pages only through the task's CDP supervisor. Camofox (now a plugin) has no
CDP endpoint, so every fill on a Camofox tab ended with "Could not determine the current page
origin": the username from browser_vault list worked, the password never filled.

ctx.register_browser_page_backend lets a plugin browser carry the vault's origin read, form
inspection and fill script to its own page. Core keeps the secret contract: the exact-origin
pre-check and in-page re-check, the Bot Desktop takeover check, an in-page try/catch around the
secret script, and fixed failure text on that path. Registration follows the login-backend
provenance rule (bundled, or catalog verified/official at its pin) and is refused under
plugins.isolation: host.

Consolidates the core half of #127179 and #135204 (the Camofox halves already shipped in the
official plugin); the in-page wrapper follows #114414.

Co-authored-by: Jonathan Bruce <jonathan.bruce369@gmail.com>
Co-authored-by: clsferguson <cferguson@live.ca>
Co-authored-by: Benjamin PERRY <benjaminperry6@yahoo.fr>
2026-10-28 19:00:07 -07:00
clsferguson
63b82d209e fix(vault): find login fields inside open shadow roots
Login forms rendered inside a shadow root (Home Assistant, custom-element SPAs) were invisible to
document.querySelectorAll, so the vault found no password field. The inspection and fill scripts now
walk open shadow roots.

Salvaged from #135204.
2026-10-28 19:00:07 -07:00
Teknium
b3c2c35e91 fix(models-dev): an abandoned download keeps its slot until it ends
run_bounded_sync stops waiting at the deadline but cannot stop the
requests download, which runs until the server stops sending. A forced
refresh skips the 5-minute backoff, so repeated attempts on a trickling
link could stack transfers. The one live download (abandoned or not) now
holds a module lock; an attempt that finds it held fails fast through the
normal failure path instead of opening a second transfer.

The deadline test also drops its 0.2 s wall-clock bound (tests/AGENTS.md
asks for >= 2 s) and checks the request count instead.
2026-10-28 07:23:10 -07:00
Teknium
8469e34161 fix(model-metadata): cap every metadata probe's whole exchange too
The same per-op-only timeout sits on the shared model-metadata transport
(agent/model_metadata_http.py), and it is on the same request path: a new
session resolves its context window through fetch_model_metadata (the
OpenRouter catalog) and fetch_endpoint_model_metadata (a custom endpoint's
/models). With DNS for openrouter.ai stalled, the first session.create
blocked for the whole stall even after the models.dev cap.

stream() now sends and, for a 2xx, reads the body under
run_bounded_sync with a 15 s cap. A rejection still returns on its
headers without reading the body, so the auth-failure early close keeps
working; get() rides on stream(). On expiry it raises DeadlineExpired,
which every caller already treats as a failed probe.
2026-10-28 07:23:10 -07:00
Teknium
4df354dba8 fix(models-dev): cap the whole registry download, not just each read
fetch_models_dev downloads models.dev/api.json with timeout=(5, 10). That
bounds each socket operation, so a body that trickles in slower than 10 s
per read (or a DNS lookup that hangs) has no total bound. With no disk
cache, the fetch runs in the foreground of whatever asked for the registry;
in a fresh HERMES_HOME that is the first session.create (tool availability
-> vision check -> provider lookup), which blocked for as long as the
download took.

Run the exchange under agent.deadline.run_bounded_sync with a 15 s cap.
On expiry the fetch raises DeadlineExpired, which the existing failure path
already handles: arm the 5-minute backoff and serve the stale disk cache,
or {} when there is none.
2026-10-28 07:23:10 -07:00
kshitijk4poor
c91bd232c0 fix(kanban): drop the worker.adopt handshake retry from the lost-worker salvage
The salvaged commit raised the managed worker's owner-link open timeout from 5 s to 60 s
(with a HERMES_WORKER_RPC_OPEN_TIMEOUT override) and retried a timed-out handshake three
times. Those retries cannot succeed against a real owner: WorkerRPC._connection mints ONE
worker-adoption ticket and every attempt resent it, while the gateway's bootstrap tickets
are single-use and expire after 30 s (gateway/runtime_bootstrap.py TTL_SECONDS, redeem()
deletes the entry). An attempt past 30 s, or any retry, is refused, and the same path
serves every idle redial during a turn, so a failing redial now took about 3 minutes
instead of 5 s while holding WorkerRPC.lock. The env knob also went against the
repo's no-new-HERMES_*-config rule.

The lost-worker disposition (worker_lost event, settled-admission reclaim) does not depend
on the handshake budget: a worker that dies in worker.adopt is now booked within one tick
either way. Sizing the handshake needs a fresh ticket per attempt and a budget within the
ticket TTL, which is its own change.
2026-10-28 17:06:43 +05:30
SanLuis-AI-Solutions
2432f9c29a fix(kanban): dispose of a lost managed worker within one tick
A managed worker that dies in the worker.adopt handshake writes no
worker_bound/worker_result: the gateway logged "Managed worker lost" and
returned, nothing failed the run, and the card said "running" for 49
minutes on a corpse (2026-10-22, t_f5fad63f, run 730: claim_expires 2067 s
past, last_heartbeat_at NULL, consecutive_failures 0).

D1 detection without disposition: gateway/session_kanban.record_worker_loss
writes a run-scoped worker_lost event on the board (dropped when the card
moved past that run) and session_managed_worker calls it on every loss
except a deliberate stop / stale generation.

D2 an elapsed claim lock read as "still running":
- owner_attempt_provably_over treats a SETTLED owner admission as proof the
  attempt ended, instead of demanding the owner PROCESS be gone (the owner
  is the live gateway, alive by design) - the reason every reclaim path
  declined for 49 minutes;
- the reclaim's kill step reads a bare OSError on an absent pid as Windows
  does (WinError 87), so "already gone" no longer means "termination not
  proven";
- reclaims/reaps name the loss in the run error via owner_attempt_note;
- a loss charges consecutive_failures like any other crash (A3), so the
  failure_limit breaker covers this class.

D3 adopt handshake budget: 60 s default, HERMES_WORKER_RPC_OPEN_TIMEOUT
override, and a TimeoutError is retried with backoff (auth/protocol errors
never are).

Tests: tests/hermes_cli/test_kanban_managed_worker_loss.py (A1-A3, D1
write side, kill-step semantics) and tests/agent/test_worker_rpc_adopt_timeout.py
(A4). 16 passed under the production interpreter.
2026-10-28 17:06:43 +05:30
Teknium
f09d03dfe2 fix(cache): signatures stored and compared later always hash
Review of #145651, item 3: the hook-consent signature, free-tier inventory stamp, onboarding due
stamp and skills manifest are kept and compared on a later tick or by the next process, so they use
always_digest=True like the PR's other stored signatures; a racy digest turning empty no longer
costs one recompute after a fresh write settles.
2026-10-27 12:57:09 -07:00
Teknium
76f2fdb794 fix(cache): a rotated key, token or same-size edit is never served stale from a file cache
Every cache keyed on a file's stat signature had the bug the config caches had: a same-size
in-place rewrite in one coarse timestamp tick keeps mtime, ctime, size and inode, so the older
parse was served for the rest of the process. Move the helper to utils.file_cache_version
(file_signature + content digest while the file is under 2 s old; always_digest for signatures
compared much later, where the racy digest going empty would read as a change) and key every
cache that can hold a secret, token, pairing/allowlist, route or config on it:

- auth.py: global auth-store memo, Nous auth-status memo (was mtime only)
- gateway/pairing.py approved-users cache (a revocation kept access)
- run_profile_reconcile: served-profile signature (always_digest: a false change reconnects
  adapters) and the hook-consent signature
- webhook dynamic routes (route HMAC secrets), Feishu comment pairing/rules cache (mtime only)
- MCP OAuth tokens-file reload check (mtime only; always_digest: a reload tears the session down)
- config parse-failure record (always_digest), named-custom-provider memo, model aliases,
  gateway.standalone memo, profile model read, MoA preset, agent raw config,
  tui_gateway raw config cache, onboarding due stamp, free-tier inventory stamp,
  provider model-list credential fingerprint, git safe.directory key, skills prompt
  manifest

config_cache_version takes its stat through config_version, so its errors and seams are unchanged.
Left alone: the tool-definition cache key and the platform manifest stamp (a safe worker must
never open config.yaml or a plugin file; the MoA preset cache is skipped in one instead) and the
CLI MCP watcher seed (pinned to file_signature by a main test).
2026-10-27 12:57:09 -07:00
Teknium
f29772123f test: pin the stopped mark on the interrupt close and the authority turn's reply stamps
Direct tests for close_interrupted_tool_sequence(stopped=...) and
TurnRunner._stamp_segment through _publish_execution (red on main). The
stopped docstring now says every interrupt gets the mark, as main already
marks interrupted partial replies.
2026-10-27 11:50:16 -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
Teknium
2d8d7e2519 chore(state): name the weak claim at both rewind sites; hoist the per-message import; replay through substitute_api_content
Review round (kshitijk4poor) on #144938 (reviewed at b0fad87a; B1-B4 fixed by 7df4b2df):
- The comment at both rewind sites said "a row claimed by identity alone". Since 7df4b2df no
  claim is by identity alone: a weak claim is a rewritten carry naming the row (_row_id, else
  uid). The comment now says that.
- resolve_and_repair_transcript_batch imported _PERSIST_AFTER_ADMISSION_INTERRUPT inside the
  per-message loop. It is now imported once per call, still late because
  agent.session_persistence imports this module at load time.
- The replay helper in test_compaction_carried_tail_not_cloned.py now builds each provider
  message through the turn's own substitute_api_content, so the B1-B3 assertions check the
  bytes the next request sends instead of re-implementing the sidecar rule.
2026-10-27 11:49:40 -07:00
Teknium
3745ea63bb fix(state): a dedupe claim needs the occurrence, its version and its replay bytes
Review round 5 (unsupportedpastels) on #144938, three findings:

- Compaction claims no longer accept matching text: the identity+timestamp and
  bare-identity claims are gone. Only a dict naming the row (_row_id, else
  message_uid) may stand for a tail row, so an identical message another
  surface appended after the watermark keeps its model-visible row (as main).
- A rewritten-carry (containment) claim needs the stored-row digest to equal
  the row's current version; a _row_id without a digest no longer proves it,
  so a row shortened in place after a row-addressed load keeps its new text.
  (A loader-stamped version witness would add an underscore key to
  row-addressed projections, which test_message_reactions pins to _row_id and
  _db_persisted; such carries are cloned as on main instead.)
- Both claim passes and the flush re-insert guard now compare what the next
  request replays: the guard compares _REPLAY_COLUMNS (owned columns +
  api_content + codex_reasoning_items) instead of the CAS ownership columns,
  and claims check api_content and the reasoning carriers through the
  writer's serializer. A newer sidecar or encrypted reasoning item is stored
  / kept instead of being dropped as "the same message".
2026-10-27 11:49:40 -07:00
Teknium
33db60eefe fix(state): the re-insert guard compares through the restore lens; a rewritten carry keeps its uid claim
The durable-uid guard compared a restored dict with the RAW stored row, but restore sanitizes and strips
user/assistant text (context blocks, edge whitespace), drops the compaction-summary flag by default, and a
wire strip loses the underscore identity maps. Those restored copies never matched, so they were
inserted again: the #134799 duplicate survived for ~2% of user rows, summary rows, and every tool-call
assistant row behind a full underscore strip.

_same_as_stored now views the stored content through SessionMessagesMixin._loaded_view_content (the
function restore uses) and takes the row's value for token_count, the summary flag, tool_call_uids and
absorbed_message_uids when the dict carries none. The dict's own content is never normalized, and
content/tool_calls/reasoning are still compared, so an edited restored dict still inserts.

A compaction uid claim with different content (the compressor merged the summary into a carried message or
stripped its images) now claims the tail row when no active row outside the tail carries that uid. It is a
weak claim: the original is archived as compacted history and stays visible. When the dict's original sits
below the watermark, the tail row is another version and is still cloned (B3 unchanged).
2026-10-27 11:49:40 -07:00
Teknium
a995b69417 fix(state,codex): a dedupe claim never drops a different message; a cut codex stream retries
Review H on #144938:

- Codex: the narration recovery for an announced answer item now needs a terminal frame. A stream that
  ends mid-turn (answer announced, partial text, a call announced, no terminal frame) raises "did not
  emit a terminal response" and retries, as on main, instead of completing on the cut-off sentence with
  the call lost. Text deltas follow the phase of the item they name, so commentary that arrives after a
  call announcement is no longer fused into the recovered answer.
- Compaction carry: a dict that names its row by _row_id claims only that row; a message_uid claim needs
  the same identity (a same-uid row with newer content is kept and cloned); an identity+timestamp claim
  is refused when the dict's uid differs from the row's. Rows claimed by identity alone are archived as
  compacted history instead of rewound, so a wrong claim stays visible in display.
- Flush guard: a restored dict whose uid is ACTIVE is skipped only when it serializes to that row's owned
  columns; an edit since the restore inserts, as on main.
2026-10-27 11:49:40 -07:00
Teknium
4186899a6f fix(sessions): skip a re-handed uid only when the agent saw it durable
The salvaged #134799 guard skipped any no-snapshot, no-row-id dict whose
message_uid was ACTIVE, so SessionDB.append_messages_batch dropped a fresh
message carrying a copied uid — the exact case main's contract
test_fresh_identical_message_is_never_adopted_by_payload pins ("even a copied
message_uid is not proof").

Narrow the trigger to provenance: the agent flush records the uids it itself
saw durable in its current session (rows it flushed, history it scanned as
already persisted) and marks a later marker-stripped copy of one of them
RESTORED_FROM_STORE on its batch row. The write transaction skips only those
marked rows whose uid is still ACTIVE. A direct append with a bare copied uid
inserts as on main.
2026-10-27 11:49:40 -07:00
Teknium
7d1c2dc612 fix(codex): recover answer text only from an announced answer message item
The narration fix synthesized a message from any buffered output_text deltas
whenever no answer message item completed. That also promoted bare
output_text beside a commentary item, which main's completion contract
(test_auxiliary_codex_completion_status
[tool-call-like-output-text-beside-commentary]) keeps as narration with
finish_reason=length. Beside calls/commentary, synthesize only when an
assistant answer message (not commentary/analysis) was announced via
output_item.added and its done event never arrived; the no-output plain-text
synthesis is unchanged.
2026-10-27 11:49:40 -07:00
Teknium
5f799922c1 refactor(sessions): let a failed durable-uid probe fail the write it runs in
The probe is one SELECT on the write transaction's own connection. A blind catch that logs and
skips the guard would hide a broken transaction and silently restore the duplicate insert; an error
there now fails the flush like any other statement in it (code-health BLE001). Builtin generics
for the new helper's annotations (ruff UP006).
2026-10-27 11:49:40 -07:00
Teknium
e4347f96b1 fix(codex): keep answer text sent beside a tool call when its message item never completes
_CodexResponseAssembler.result() synthesized a message from buffered output_text deltas only when the
stream carried no tool call. A backend that announces a call, streams narration in a message item and
never sends that item's done event (the relay shapes in #143893) lost the narration whenever a
commentary item was also present, because the normalizer's output_text fallback is skipped once a
commentary phase is seen. The turn then stored an empty assistant row and showed no bubble.

result() now synthesizes the message whenever no answer-phase message item exists, tool calls or
not, and places it before the first call. Commentary and analysis deltas never enter text_deltas, so
they are unaffected.

Live (real tui_gateway.entry + scripted codex_responses stub): base stores '' for the narration
turn and the resumed transcript lacks it; head stores and paints it.
2026-10-27 11:49:40 -07:00
Sharpe
42abc9e2ed fix(sessions): durable-uid dedupe joins the repair transaction — a live rewrite is never dropped
Review (PRATHAMESH75, 134799): the flush-side guard stamped-and-skipped
restored dicts BEFORE resolve_and_repair_transcript_batch could see them,
so a snapshot-carrying dict's live edit never reached its row — reproduced
live (restored[-1]['content']='new answer' -> final active rows read
['q', 'old answer'], the edit silently lost). It also probed the durable
uid set OUTSIDE the write transaction (a concurrent writer could flip the
active set between read and INSERT) and built candidate_uids from the
WHOLE transcript (O(N) per flush, past SQLite's bound-variable limit the
probe throws and the guard fails open silently.

Move the no-snapshot uid dedupe into resolve_and_repair_transcript_batch
(the reviewer's sturdier option, which closes all three):
- _active_uid_dedupe runs inside the caller's BEGIN IMMEDIATE — the same
  transactional guarantee the CAS repair already relies on, no TOCTOU.
- Candidates exclude dicts that still carry DB_ROW_SNAPSHOT or _row_id:
  the CAS path rewrites their active row in place; a live edit must land.
- Candidates are chunked via hermes_state_common._id_chunks (the repair
  code's own pattern), so no bound-variable limit and no whole-transcript
  cost per flush.
- Fail-open stays: a probe error logs and returns an empty set.

The flush-side pre-guard in _db_flush_collect comes out (the marker,
history-identity and scaffolding guards remain untouched there).

Regression: test_restored_snapshot_rewrite_still_lands pins the reviewer's
exact repro — red on this PR's parent head (edit lost), green with the fix.

Validation (this commit): new suite 4/4; red/green confirmed by file-scoped
revert of the two source files (1 failed -> 4 passed); repair-path battery
(test_append_messages_batch, test_restore_alternation_repair,
test_repaired_history_commit_coverage, test_compression_watermark_commit)
35/35; scratch battery (test_scratch_dir, test_scratch_scan_failures)
22 passed + 2 platform skips; -k 'flush or persist or transcript' A/B vs
PR head: fixed 30 failed / 401 passed, baseline 31 failed / 400 passed —
fixed failures a strict subset of baseline (all pre-existing environmental
failures: tests spawning PATH-resolved hermes trip the real-home IO guard);
the single delta is the new regression test, red on base, green here.

Co-Authored-By: Viiy <viiy@mediaplural>
EOF
)
2026-10-27 11:49:40 -07:00
Sharpe
fc6d7edc75 fix(sessions): durable-uid flush guard — restored rows must not be re-inserted
Production receipts (estate state.db, 2026-10-07): 24k+ re-inserted shadow
rows across 47 sessions (Oct 1-7), each preserving the original message_uid
while landing at a later timestamp with display metadata lost. Signature
reproduced end-to-end in test_flush_uid_reinsert_guard.py: a dict rebuilt
from durable rows (crash/failed-turn history restore, resume, repaired
sequence, wire-crossing handoff) carries its durable message_uid but NOT
the _DB_PERSISTED_MARKER (underscore-prefixed, stripped before the wire)
nor _row_id — the flush's identity guards can't see it and INSERT a second
copy of an already-active logical message.

Fix (fail-open, append-only): SessionDB.active_message_uid_exists() probes
the durable uid set in one statement; _db_flush_collect consults it once
per flush and stamps durable candidates _DB_PERSISTED_MARKER + skip.

Validation: new suite 3/3 PASS; red-run confirmed on stashed patch (fails
with the exact defect); A/B mass run (-k flush/persist/transcript/session,
9519 deselected): baseline 30 failed/683 passed vs patched 27/685 — patch
fixes 2, breaks 0; all 30 fail-then-pass-in-isolation (shared-machine
test-ordering pollution, pre-existing).

Co-Authored-By: Viiy <viiy@mediaplural>
2026-10-27 11:49:40 -07:00
Teknium
41e5a82e60 test(agent): keep two invariant tests for the reasoning relay, drop the defensive try
The salvaged relay fix shipped nine tests; keep the two that pin the
invariant (a plain reply is never relayed as reasoning, inline thinking is
relayed without the reply text). Both fail on origin/main. The extractor
call needs no try/except: agent._extract_reasoning does not raise.
2026-10-27 11:49:40 -07:00
webtecnica
4c08c0d407 fix(agent): stop _relay_thinking re-emitting plain reply text as reasoning.available (132477) 2026-10-27 11:49:40 -07:00
kshitijk4poor
fa59cb998a test(deadline): pin review cases for poll_until callers and the sweep
From review: document that poll_until bounds only its sleeps, not time
spent in the predicate; pin that unlink_files_older_than keeps sweeping
after one unlink raises PermissionError; pin that
_wait_for_user_dbus_socket exports the systemd env exactly once when
the socket appears only on the final check, made at the deadline after
a cut last sleep. Both new tests fail against a mutated implementation
(the per-file suppress removed; main's loop shape).
2026-10-27 16:30:14 +05:30
kshitijk4poor
de5f56c92a refactor(deadline): one poll_until for check-until-deadline loops
Twenty loops across 17 files hand-wrote the same thing:

    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if condition(): return ...
        time.sleep(interval)

with small drifts between copies: some re-checked once after the loop,
some did not, one slept before its first check, and update_cmd_windows
kept a private _poll_until. A copy without the final check can miss a
condition that becomes true during the last sleep.

agent/deadline.py (already the home of clamp_timeout / run_bounded_*)
gains poll_until(predicate, timeout, interval): checks at once, cuts the
last sleep to the time left, checks again at the deadline, and returns
the predicate's last value so callers that wait for a pid / row /
identity get it back directly. timeout <= 0 is one check.

Converted: outbound_webhooks.flush, cron delivery wait and jobs flock,
host_attach channel wait, browser profile unlock, data-cleanup drain,
gateway dbus/bus waits, launchd fresh-pid and supervision waits,
supervised restart, gateway_migrate live-gateway wait, Windows
drain/absent waits, kanban init lock, local-runtime boot wait,
update_cmd_windows (private helper deleted), bot desktop start/stop
waits, TUI browser connect.

Left as is: loops whose body does more than check (progress callbacks,
interrupt handling, two distinct exits) and one site whose blind except
the health gate would reject once moved.

Behaviour changes, all small:
- loops that stopped at the deadline without re-checking now make one
  more check there;
- loops that already re-checked after a full last sleep now cut that
  sleep to the time left, so the check lands at the deadline (up to one
  interval sooner);
- a timeout <= 0 now means one check (some loops made none);
- the local-runtime boot wait checks before its first sleep instead of
  after it;
- _wait_for_user_dbus_socket also exports the user systemd env when the
  socket appears on that final check (before, that path returned True
  without it).

update_cmd_windows is imported by update_cmd on every OS, so the
fresh-source-install acceptance fixture (which keeps agent/ out of the
update path) now copies the stdlib-only agent/deadline.py too.

Tests: 4 pins for poll_until (two red against the classic
no-final-check variant), plus the existing suites for every touched
module.
2026-10-27 16:30:14 +05:30
Teknium
a382af23f4 feat(models): list gpt-6.1-terra on OpenRouter and Nous Portal
openai/gpt-6.1-terra is served by both OpenRouter's and the Nous Portal's
/v1/models (1.05M context). Adds it to the curated OpenRouter list (the
Nous list derives from it), a 1.05M offline context fallback, and
regenerates the published model-catalog manifest. No older Terra slug was
on either list, so nothing is removed.
2026-10-26 19:05:08 -07:00
Teknium
fbb1b417e2 fix(providers): one guarded api_mode_for_model for resolution, /model and resume
Runtime resolution caught a raising api_mode_for_model hook and kept the
profile's declared api_mode, but /model (model_derived_api_mode, also the
resume re-derivation in the TUI, CLI and gateway), the stale
codex_responses check in resolution, the agent's Responses routing check
and the auxiliary client asked the same hook unguarded: a model could
resolve and then fail building the switch result.

agent.provider_route_hooks.model_api_mode is now the one call: a raise
answers the profile's declared api_mode, logged with its traceback once per
provider. A None answer keeps each caller's existing meaning.
2026-10-26 01:34:59 -07:00
Teknium
51e731f57a fix(agent): a failing credential-refresh hook falls back instead of escaping
refresh_runtime_credentials, is_stale_credential_error and
credential_refresh_notice run inside the API-error handler, outside the
retry loop's try. A raise there (a plugin bug, or a plugin host that
disconnected or timed out) escaped the handler before the fallback walk.

ask_on_error_path is that boundary: a raise answers "not refreshed" (or no
stale verdict / no notice), logged with its traceback once per provider and
hook, and the hook is asked again on the next error since a lost host may
be back. A malformed refresh answer is "not refreshed" too. The original
API error then walks the fallback chain. Same policy as the
missing_credentials_suffix boundary.
2026-10-26 01:30:54 -07:00
Teknium
1c4cbb2222 Merge remote-tracking branch 'origin/main' into copilot-seams/integration 2026-10-26 00:40:32 -07:00
Teknium
857e29d4cc fix(agent): provider hook failures are per session and reported per agent
A failed per-request profile hook stays on the generic answer for the agent's session so request
bytes never flip, but the failure memory survived /new and /resume (reset_session_state reuses the
agent), and the warning was logged once per process, so in a multiplex process every later home's
agent degraded silently. The memory is now cleared at a session boundary and a scoped (agent)
failure is logged once per session; scopeless one-shot callers keep the once-per-process warning.
2026-10-26 00:32:20 -07:00
Teknium
ceefcf5f97 fix(acp): a CLI that closes its input but keeps running fails fast
129f205a0e made a broken pipe on a request write wait up to 5 s for the CLI to exit, so its exit
text is reported. A CLI that closes stdin but stays alive then fell through to the reply loop and
hung for the whole request timeout (900 s default) before a TimeoutError; main failed at once.
After the wait, a still-running CLI now re-raises the broken pipe. Windows reports a write to a
closed pipe as EINVAL rather than EPIPE; both take the same path.
2026-10-26 00:32:19 -07:00
Teknium
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.
2026-10-26 00:32:14 -07:00
Teknium
70d31a5a5d fix(agent): only the first attempt of a user turn carries user attribution (billing parity)
53a51a49cc made every attempt of a user turn's first API call (429/5xx retries, fallback
activations) re-send the provider's user_initiated request headers. Hermes has always sent them
on the first attempt only (retries went out with the route's default), and that difference is
billing-visible (premium-request initiator headers), so it is reverted: the first payload built
in a user turn consumes the flag and is the only user-initiated one.

Kept from 53a51a49cc: the flag is consumed exactly once whatever the route answers, so a route
without attribution or a failing request_headers hook never leaves it set for a tool-loop
follow-up.
2026-10-26 00:32:11 -07:00
Teknium
99cf3a6358 fix(providers): seed_pool_credentials takes plain values; hosted ambient tokens reach the host
Under plugins.isolation: host, profile_call encodes kwargs without callable refs, so the
is_suppressed / explicitly_configured lambdas arrived in the host as non-callable Opaque values
and a hosted provider seeded nothing (while _profile_seeds_pool still disabled generic env
seeding). The seam now passes data: suppressed_sources (frozenset) and explicitly_configured
(bool), computed only for profiles that override the seam.

Shell-exported GH_TOKEN-style names are always stripped from child envs, so a hosted provider
that declares them (env_vars + ambient_credentials) never saw a shell-only token. The plugin host
env now re-adds exactly those names through get_secret under the host home's scope: the launch
home keeps its shell value, a routed home gets only its own .env value, never the launch one.
2026-10-26 00:32:10 -07:00
Teknium
765933299d fix(compression): a prepared summary is never redone over a moved tail cut
With compression.prepare_ahead, compress() re-planned the tail cut and threw the
completed background summary away whenever the fresh cut landed before the
summary's boundary (the no-LLM prune made tail rows cheaper, tool-group
alignment moved the cut), then wrote a second summary inline while the user
waited. That breaks the one-summary rule: once the background summary exists it
is used, and everything after its boundary is the tail.

The splice check no longer consults the fresh cut at all. A summary is still
discarded only when the messages it covers changed (rewind, shape change, other
session, moved head). The pass planned its own window with a full tail, so the
tail is never empty. The now-unreachable inside_tail reason leaves the
(unreleased) prepared-compaction metric contract.
2026-10-26 00:10:23 -07:00
Teknium
129f205a0e fix(acp): a CLI that stops reading before the first request reports its exit text
The union run flaked test_alias_keeps_the_former_gh_extension_diagnosis: a CLI that dies at once
(the old `gh copilot` extension) can close its stdin before ACPClient writes `initialize`, and the
write raised a bare BrokenPipeError, skipping the early-exit path that reports the CLI's stderr
(and the alias's gh-extension diagnosis). Pre-existing on main's CopilotACPClient. A broken pipe on
a request write now waits briefly for the exit and falls into that path. Test drives the race
deterministically (the fake CLI closes stdin before the client's first write).
2026-10-25 23:01:26 -07:00
Teknium
7f64198bc1 fix(compression): a publish-then-discard race and a cancelled splice are counted right
Greptile on 815681917c3:
- a boundary landing after the pass published (and cleared its pending token) but before the
  waiting compaction read the summary still read as a failed pass; take() now notices a discard
  that happened during its wait and leaves the boundary's row as the only one;
- compaction_failed was lost when a pre-commit cancel restored the compressor's attempt telemetry
  (and its prepared_summary flag) before the record was emitted; the spliced attempt id now lives
  on the prepared-compaction state, outside the restored snapshot;
- the deadline-extension test starts its 2 s deadline only once the pass is running.
2026-10-25 22:55:11 -07:00
Teknium
d773589f7c fix(compression): every prepared summary ends counted as used or discarded
Re-review findings:
- a summary take() handed to compress() that the compaction then aborted or no-opped before
  adopt() spliced it was counted nowhere; it is now counted once at the next touch as
  discarded/compaction_aborted;
- a session boundary landing after the pass published but before the waiting compaction woke
  read as a failed pass (a second discarded row); the wake now reads the entry and the cancel flag
  under one lock, so the boundary's row is the only one.
2026-10-25 22:55:11 -07:00