Commit Graph

617 Commits

Author SHA1 Message Date
Maciej Lisiewski
ca3cdb83cd Merge pull request #155509 from NousResearch/sec3/146750-summarizer-role-typed
fix(compression): send role-typed turns to the compaction summarizer (salvage #154891)
2026-11-14 22:26:18 +01:00
fangliquanflq
652fd7e21e fix(session-search): redact derived metadata 2026-11-14 15:11:44 +01:00
Maciej Lisiewski
5712312f1f fix(compression): keep the typed summarizer input bounded and user-role-only
- A record the sampler cut stays assistant text: rebuilding its native
  tool_calls restored the uncut arguments and sent ~2x the 160k input cap.
- Split the assistant body on the LAST "[Tool calls:" block, so assistant
  text quoting the marker is kept.
- Only real user turns go out as role=user: typed rows (async-delegation
  results, process/internal notices; /steer kept) and flag-stamped
  scaffolding (verification nudges) become [INTERNAL CONTEXT] assistant text,
  via the existing _is_real_user_turn + is_user_role_scaffolding checks.
- Close the typed turns with an assistant marker when they end on a user
  turn, so the request keeps strict role alternation before the pointer.

Refs #146750

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-14 12:24:25 +01:00
Teknium
54a95b679c fix(compression): send compacted turns to the summarizer in their real roles
A flattened [USER]: transcript lets tool output that prints a fake user
turn pass for the user, so the summary carries a forged approval forward
as the user's (arXiv:2610.29869, #146750). Lean mode now sends real user
turns as role=user, assistant tool calls as tool_calls and tool output as
role=tool messages (pairing repaired, no tools param), with the
instructions in the system slot and a final user pointer.

The summary-input sampler moves to context_compressor_sampling.py
(unchanged) to keep context_compressor.py under its line ratchet; it
now also reports which record runs it kept so the typed builder sends
exactly the sampled records.
2026-11-14 12:24:25 +01:00
teknium1
9048c4685e Port from OpenHands/software-agent-sdk#5143: send the compaction summarizer instructions as system + turns as user
The context-compression summarizer built one giant user message: preamble,
turns, structure template and focus guidance all in a single slot. Every other
auxiliary caller in the repo (title generator, smart approval, MCP sampling,
TTS) already sends [system, user].

Why: providers train the instruction hierarchy on the role split, so a
directive smuggled inside a compacted turn now competes with a *user* message
rather than sitting beside the summarizer's own instructions; it is the
canonical shape for Chat Completions and for the Responses instructions/input
pair; and the static instruction block becomes a stable, cacheable prefix
across compactions instead of being interleaved with per-call content.

Prompt prose is byte-identical (the section instructions are pinned for Azure
content filters); only the data blocks (PREVIOUS SUMMARY / TURNS TO SUMMARIZE /
memory-provider context) move to the user message. Tests that read the
summarizer request now join every message rather than slot 0, which is also
the correct redaction assertion (secrets must be absent from the WHOLE request).
2026-11-14 12:24:24 +01:00
Teknium
a4e024bb6e fix(gateway): the cron reply pointer survives compaction and Telegram partial quotes
Review follow-up:
- The cron pointer keeps the "[Replying to…: "…"]" shape and context_compressor's
  _GATEWAY_REPLY_POINTER_RE recognises it, so a long quoted report is stripped from the
  authored request and the compaction snapshot keeps what the user actually asked.
- A Telegram native partial quote of a wrapped delivery (selecting "Deploy prod now")
  is now led by the delivery's header line, so it is framed as part of a past report
  instead of reaching the model as a bare actionable line.
2026-11-12 02:37:17 -08:00
Teknium
69677b5829 fix(delegation): pin the child's brief through compaction; context first as a cacheable prefix
Review findings from unsupportedpastels and kshitijk4poor:

- A steered child lost its brief at its second compaction. The compactor stops
  protecting early turns after the first pass and restates the newest real user
  turn, which after a steer is the steer. A delegated child's first user turn
  is its whole brief (goal, context, output contract), so it is now always
  protected (ContextCompressor.pin_task_turn, set on every child). The head
  window methods move to context_compressor_window.py with it.
- Siblings given one context stopped reading it from cache: the goal came
  first, so the shared bytes started after the first difference. The first user
  turn is now "CONTEXT: ... TASK: <goal>", and the context is registered as the
  message's stable prefix, which gives it its own cache breakpoint on marker
  routes. Every brief is registered: a parent often sends one brief in separate
  calls, which a per-call "shared" test cannot see.
- Stale docs and comments that still placed the context in the system prompt.

Co-authored-by: unsupportedpastels <unsupportedpastels@users.noreply.github.com>
Co-authored-by: kshitijk4poor <kshitijk4poor@users.noreply.github.com>
2026-11-11 18:29:48 -08:00
Teknium
88319a6a67 fix: each row carries its own response's reasoning count, and only what conversion keeps is charged
Review findings on the replayed-reasoning pricing:

1. A truncated (finish_reason=length) fragment or Codex incomplete interim is built
   before record_response_usage runs, so it inherited the PREVIOUS response's count.
   The count is now noted from the current response in check_api_response, before any
   row is built.
2. Replacing a row's reasoning with an unstamped payload kept the old positive stamp.
   A zero/unknown stamp now clears it.
3. Claude: signed thinking was charged in full even where the converter demotes it
   (orphaned tool call) or drops it (second of two merged assistant rows). The
   projection now applies the same survival rules over the whole list.
4. build_api_messages drops display_metadata from request copies, so the request
   estimate lost the stamps. The count rides the copy as a private key and is popped
   after measurement, before the request (or MoA prepare) is sent.

The native Anthropic tail pricer moves to context_compressor_tail (file-size ratchet).
2026-11-09 23:23:46 -08:00
Teknium
709748aeca fix: count replayed reasoning at the provider's billed size so compression sees it
Codex/xAI encrypted reasoning and Claude signed thinking from earlier turns are
resent on every request and billed as input at the reasoning count the provider
reported for that turn (live A/B: gpt-5.6-sol 2,765 -> +2,767, grok-4.7 73 -> +76,
claude-opus-5.5 3,959 -> +3,959). Hermes priced the ciphertext at 0 (and Claude
at its ~1/4-size summary), so long reasoning-heavy sessions looked small:
compression found nothing to cut while the real bill sat over the window.

Each assistant row now records its response's reported reasoning count in
display_metadata, and the preflight trigger, tail-budget walk and native
Anthropic projection charge it. Compaction checkpoints still cost 0. Anthropic's
output_tokens_details.thinking_tokens is now read (it was always 0).

Fixes #125920
2026-11-09 23:23:46 -08:00
kshitijk4poor
49165bcaff fix(aux): retry, fallback and refresh decisions come from classify_api_error
The auxiliary client decided every recovery step (same-provider retry,
credential refresh, pool rotation, unhealthy mark, provider fallback)
with private substring predicates and consulted classify_api_error only
to label telemetry. The logged reason and the action taken could
disagree, plugin transform_api_error_classification hooks and
ProviderProfile.classify_api_error overrides never steered an aux
decision, and the tables had drifted from the main loop's.

What changed:
- Each failed request is classified once, on the backend, model,
  endpoint and credential it was sent with (_classify_failure): the
  primary, a same-provider retry (its rebuilt client and model), a
  refreshed Nous client or healed
  model, a parameter-rung or backoff re-send, and a fallback candidate
  (its effective provider or destination; an async candidate classifies
  on the sync client it was converted from). The streamed-negotiation
  and affordable-402 checks classify on the same attempted provider,
  passed in by the caller. Every later rung reads the
  resulting Failure (error, verdict, whether a parameter rung's detector
  names the rejected field). A request boundary that already classified
  (a rebuilt same-provider retry, a judged stream negotiation) raises the
  typed _ClassifiedAttempt carrying its Failure, and recovery reads that
  instead of classifying again. The relay logical call records each
  failed attempt with the ladder's Failure for it and reports that
  verdict at close (one classification only when no verdict exists):
  classifier hooks fire once per failed request.
- The primary's retries, the candidates' parameter rungs and the ladder
  driver handle a failure after its except block ends, so a retry's own
  failure is classified as itself instead of through the previous
  error's context. The stream watchdogs raise their timeout from None.
- agent/auxiliary_error_policy.py (new): small pure functions over the
  verdict (same_provider_retry, auth_refresh, same_key_retry,
  benches_provider, fallback_label, ladder_accepts,
  stream_negotiation_reraises).
- The sync and async fallback-candidate helpers share one generator.
- context_compressor classifies a summary failure once; its
  session-preserving abort keys on the verdict's transport fact.
- The parameter rungs return a _ParameterRepair NamedTuple whose
  repaired flag tells provider fallback a rung changed the request.
- Deleted: the private _is_*_error predicates, _credential_rung_accepts,
  _FALLBACK_REASONS, the keyword tables, fallback_candidate_unavailable_
  reason and agent/auxiliary_error_shapes.py.

Behaviour changes:
- Transient failures (5xx, 408, overload, timeouts, connection failures
  incl. DNS/ECONNREFUSED and SDK transport classes) retry the same
  provider, then fall back.
- A missing model falls back on every route; a 404 free-tier body falls
  back; 400-coded billing and rate-limit bodies bench / rotate and fall
  back.
- RESOURCE_EXHAUSTED on a 429 is a rate limit unless it names a daily or
  weekly window, which is billing and benches the provider.
- An OpenRouter-wrapped upstream 429 and a 429 "overloaded" do not rotate
  a healthy key; a 429 naming a rate limit and a billing phrase stays a
  rate limit.
- A generic 403 falls back (auto routes; an explicit provider only with
  its task fallback_chain) without a credential refresh.
- Account gating of the model rotates (model-scoped) before falling back;
  a feature restriction falls back without touching the key.
- A rejection naming a request parameter with no applicable rung
  re-raises (primary and candidates); after a spent rung it falls back.
- A verdict with retryable=False skips the same-provider retry and the
  same-key rate-limit backoff; a plugin or profile verdict with
  should_fallback=False never reaches provider fallback. A verdict that
  is neither retryable nor should_fallback (data_policy_denied, the
  model's malformed tool-call arguments) re-raises even after a
  parameter rung changed the request: another provider would get the
  same content.
- An InterruptedError (a cancelled Codex stream) stops the call: no
  retry, no fallback.
- A missing or route-refused model on a fallback candidate quarantines
  that model only (model-scoped unhealthy key); siblings on the same
  provider stay eligible. The key holds the provider-normalized model,
  so a configured name and its resolved form (gpt-x / openai/gpt-x)
  match, and the discovery chain skips a hidden resolved model too.
- Aux pool selection (_select_pool_entry, _peek_pool_entry and the
  OpenRouter, Codex, Anthropic, xAI OAuth, plugin OAuth, named custom
  and API-key builders) passes the requested model, so a model-scoped cooldown on a key does not hide
  it from sibling models; CredentialPool.peek takes model= like
  select.
- 429 then a generic 403 on an explicit provider with no task chain
  re-raises the 403.
- Plugin and provider-profile classifiers steer every aux decision.

Tests: tests/agent/test_auxiliary_error_policy.py drives call_llm end to
end over one table of the behaviour decisions, plus regressions for a
failure after a 401 refresh, 429-then-403, retryable=False, OpenCode Go
classification (sync and async), a refreshed candidate's bad answer, a
Nous SSE error after refresh, a terminal verdict after a spent
parameter rung, one hook call per failed request (primary, retry and
candidate; streamed and plain, sync and async), TLS failure and a 502 connection reset in
compression, plugin overrides, an interrupt, a pinned custom provider's
model-scoped rotation, a candidate's model-scoped quarantine under its
resolved name, a sibling model keeping a pooled key, and a rebuilt
retry classified on its own model. Tests of
the removed predicates are deleted; ladder-internals tests are adapted
to the Failure tuple.

Part of the Code Health plan.
2026-11-08 13:18:54 +05:30
kshitijk4poor
16f70a2b33 fix(memory): previous_message is the typed ask after a multimodal turn
On a turn with an image, Hermes appends the injected context (recalled
memory, pre_llm_call and gateway notes) to the message as a text part
(#71998, bb87e6abce). The next turn's previous_message, added in
#150569, read that part back as part of the ask. The stored row keeps
the parts as one flattened string, so after a restart nothing in content
separates the ask from the injection.

The turn now records its ask in display_metadata under typed_ask before
the first part is appended. That is a persistence-only field, so it
never reaches the wire. The ask is the human-authored view of what the
row will persist (durable_user_row_content, so a TUI list override's
dropped API-only parts stay out), with a todo snapshot that turn-start
compaction folded onto the turn stripped, so a turn already wrapped in a
summary still stamps just the ask. previous_message reads the stamp and
normalises it the same way as unstamped text (gateway timestamp, memory
fence), and gateway replay carries that one key through
(replay_metadata_fields, next to the scaffolding flags), so a resumed
gateway, CLI and TUI all see the clean ask. A row written before this
change falls back to stripping the memory fence; its notes stay, and the
docs say so.

The in-place backfill writes the stamp (only that key) with the part,
also when only gateway notes landed on the parts. That row can exist
before the turn (a TUI submit row) and take a reaction meanwhile, so the
row-addressed rewrite (set_user_message_content, direct and through the
runtime worker) now JSON-merge-patches the given metadata into the row's
instead of replacing it (a null deletes a key); the veto passes
typed_ask: null to remove a backfilled stamp. Its existing api_content
clear is unchanged and only ever sees list rows here, which carry no
string sidecar.

A later compaction that only wraps the row keeps the stamp, including
when the next compaction restates the still-unanswered turn on its own
(copied whole, or rebuilt from the task text of an earlier
restatement).
Any fold (record_absorbed_message, the merge witness every host fold
calls: repair, micro-compaction, a summary carrier absorbing the
in-flight turn, an anchor led into a scaffolding turn) that brings
content drops it, because the row then holds more than that one ask; an
empty turn folded in changes nothing, so the stamp stays. Such a row
reads as it does on main, after a restart too: the transcript flush
rewrites only the columns a turn owns, keeping metadata other writers
add, so when it writes new content for a row whose live dict no longer
carries the stamp it removes that one key (a reaction stays), and hands
the row's metadata back as written. A pre_llm_call veto and the
expired-confirmation redaction drop the stamp too, keeping vetoed or
redacted text away from providers.

The display_metadata set/read idiom this would copy again in
message_metadata.py becomes two private helpers, which stamp_data_use,
mark_inflight_restatement and withheld_prompt_text there now use too.

Reported by Greptile on #150569.
2026-11-08 00:41:35 +05:30
unsupportedpastels
936f3465f8 refactor(cli): remove the unused one-shot agent that ran outside the gateway
`hermes -z` has run through the gateway (`_run_oneshot_from_args` ->
`launch_gateway_chat`) at every dispatch site for a while, but the old
in-process runner stayed behind: `hermes_cli.oneshot.run_oneshot` /
`_run_agent` built a bare AIAgent outside the session authority, and
`hermes_cli.main._run_and_exit_oneshot` (with its
`_cleanup_oneshot_runtime` cleanup table) was its only caller. Nothing
outside tests reached any of it.

Delete that path. `hermes_cli.main._exit_after_oneshot` stays exactly as
it is: `--cpu-profile` names it as the one-shot hard-exit path and it
writes the profile before `os._exit`; only its docstring loses the
pointer to the removed cleanup helper. `hermes_cli/oneshot.py` keeps
only what the gateway path and gateway CLI turns still import: the
exit-code mapping, the `--usage-file` ledger with its auxiliary-usage
delta, and `--toolsets` normalization. The process-receipt eval probe
now calls `process_registry.wait_for_pending_completions` directly.

Tests that only exercised the deleted runner are removed; the exit-code
and usage-file tests now call the kept helpers directly; the cost-guard
test patches the gateway launcher instead of the removed function. A new
test pins that `hermes -z` dispatches to `launch_gateway_chat`.

Refs #145171 (EP-11a)
2026-11-05 17:59:21 -05:00
Teknium
be765e31d8 fix(compression): scope the summary-abort to Gemini prompt blocks only
Other providers' content-policy refusals of the summary call keep main's fallback-summary
path; only the Gemini prompt block (which used to arrive as empty content) stays terminal.
2026-11-04 21:47:30 -08:00
Teknium
9c1799ed1a fix(compression): a safety-blocked summary request aborts with the transcript intact
Review finding: when Gemini blocks a compression summary request, compression
now drops the middle turns. The native adapter raises the prompt block as a
content-policy GeminiAPIError instead of returning empty content, so
_classify_summary_failure no longer put it in the terminal (refusal) class.
Count the classifier's content_policy_blocked verdict as that class, which also
aborts on other providers' content-policy refusals of the summary call.
2026-11-04 21:47:30 -08:00
Teknium
73bfb9ce7e feat(compression): keep uncertain claims labelled UNVERIFIED through compaction
Summaries shed qualifier words first, so "I suspect X" either hardens into
"X" (a fact the resumed agent acts on) or drops out entirely. The summarizer
prompt now asks for each uncertain claim as an explicit labelled line
("UNVERIFIED: <claim> — <basis>") under a new "## Unverified / Working
Hypotheses" section, on both the first-compaction and iterative-update paths.

The text lives in the new agent/context_compressor_prompt_rules.py sibling
(which also takes _today_for_prompt off the facade); the facade only
interpolates it. Summarizer prompt only: system prompt, cached
prefix and the persisted handoff prefix are unchanged. Cost: +288 chars per
summary call (~+79 prompt tokens measured live), down from +756 in the
first version of this change.
2026-11-04 21:31:47 -08:00
unsupportedpastels
a212421dbd fix(context): keep the fallback source on the compressor, and through MoA presets
The per-route record held only the latest lookup, so a second session that
detected the same window on a route cleared the label of an agent still
running on its earlier default. The compressor now keeps the source of its
own lookup (last_defaulted_context_length, read right after it resolves) and
the agent label reads that.

A nested lookup that defaults (a MoA preset's aggregator) now marks the outer
resolution too, so the preset's window keeps "fallback".

Addresses Greptile review on #148801 (f6e7d756).
2026-11-04 12:56:04 -05:00
Teknium
967c73a104 chore(compression): fold the post-compression trim comment so the compressor facade does not grow 2026-11-01 22:07:56 -08:00
ygd58
01af9039df fix(compression): stop the post-compression trim from stalling the dashboard loop
Fixes #146375.

agent/context_compressor.py calls trim_memory(reason="post-compression")
after every successful compaction, and trim_memory() always ran a full
gc.collect() before malloc_trim(0). With dashboard.turn_isolation: false
(still the default), the agent turn runs in the same process as the
dashboard's event loop, so a gc.collect() over a large heap holds the
GIL for seconds -- the reporter measured 11 trims over 5s (5-11.6s) in
one week, 8 of them coinciding with "event loop stalled" warnings, with
WebSocket frames queuing and the UI not streaming for the duration.

Verified the proposed fix #2 ("run the trim off the agent thread") would
not help: the reporter's own stack dump already shows trim_memory
running inside a background compaction thread (_run_summary_dispatch),
and gc.collect() is stop-the-world across the whole interpreter
regardless of which thread calls it -- confirmed directly by measuring
a heartbeat on one thread while gc.collect() ran on another: the
heartbeat's worst gap matched the collection's own duration almost
exactly, whichever thread held the GIL. Moving the call to a different
thread changes nothing; the GIL is process-wide.

Implemented the issue's proposed fix #1: added an opt-out collect
parameter to trim_memory(), reviving the same signature already
designed (and apparently working) in #139798 -- closed unmerged by its
author "to stay under the open-PR limit" for a different call site
(gateway housekeeping) that this change does not touch. #139798's own
design note said pressure lanes like post-compression should "keep the
default" (collect=True), reasoning that a collection is what makes the
trim return anything measurable. Measured directly, with the same
reference-cycle heap construction #139798 itself profiled against:
malloc_trim(0) alone (collect=False) still returned real pages in ~3.5ms
versus ~129ms with the collection, and the compacted-away message dicts
this trim targets (replaced list entries, not deliberately-cyclic
structures) are typically already reclaimed by Python's own reference
counting before the trim runs -- so the full collection's marginal
benefit here is smaller than #139798's note implies, and the stall cost
on the default (in-process) configuration is severe. Only the
post-compression call site is changed; #139798's existing gateway
housekeeping path is untouched by this PR, so no conflict with either
reviving that closed PR separately or merging this one standalone.

Scope note: the issue's secondary suggestion (apply the same to the
forced agent-close trim in run_agent.py) is not included here, to keep
this change targeted at the specific, stack-trace-confirmed call site.

Verified directly: measured trim_memory() against a real reference-cycle
heap with a concurrent heartbeat thread standing in for the dashboard
event loop. collect=True: 129.2ms duration, 77.2ms worst heartbeat gap.
collect=False: 3.5ms duration, 13.1ms worst heartbeat gap -- roughly a
37x reduction in both the trim's own duration and its stall on a
concurrent thread.

Added 3 regression tests to the existing tests/hermes_cli/test_mem_trim.py,
following its established gc.collect/_malloc_trim monkeypatch pattern
from the adjacent test_success_collects_then_trims: collect=False skips
gc but still trims; every existing caller (no collect= argument) keeps
the full collection, confirming this is additive, not a behavior change
for anyone else; and the log line surfaces collected=False, matching
Verified as a genuine regression by reverting just the trim_memory()
signature change and confirming both new collect=False tests fail with
TypeError (the parameter genuinely doesn't exist without the fix).

11/11 pass in the modified test file; 299/299 pass in the full
tests/agent/test_context_compressor.py (no regression).
2026-11-01 22:07:56 -08:00
Teknium
4061818385 fix(hooks): /retry and /undo after a block use the typed text, not the placeholder
A vetoed user row stores the withheld placeholder as its content, so /retry
(CLI, TUI, gateway, ACP, Desktop) re-sent the placeholder as a new prompt and
/undo pre-filled it into the composer. A rewind's live view and its receipt now
swap the placeholder back for display_metadata.withheld_prompt: /retry
re-submits what the user typed, so the hook decides on it again, and /undo
restores it. Stored rows, compaction and search are unchanged.
2026-10-31 22:59:20 -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
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
c2383a6806 feat(compression): one prepared summary per compaction, newer messages join the tail
Maintainer ruling on the prepared-compaction design, plus the review findings
(ours and Greptile's) on #144684:

- One pass per compaction. The extension passes (a new summary call every ~8k
  tokens of growth) and the "stale after one tail budget" check are gone: the
  summary splices at its own boundary and every message after it, however
  many, stays verbatim in the tail. No second summary is ever paid for.
- The splice check compares message structure, not text: role, tool call
  ids/names, tool result ids, plus the durable message_uid where both sides
  carry one. Plugins that rewrite text in place (redaction, pre-compaction
  notes) no longer throw the summary away; a dropped/inserted message or a
  rewind into the window (new message_uids) still misses. This also settles
  the fingerprint gap on input_text/output_text parts: text is not compared.
- A pass that recovered on the main model after the summary model failed now
  hands that over on a splice, as an inline call would: summary_model goes
  sticky to the main model, and the "configured compression model failed"
  warning reaches the user. The attempt telemetry carries the pass's aux call
  (model, tokens, duration, fallback) and a new prepared_summary flag.
- The first compaction that needs memory-provider context stops further
  passes for the agent; each would have been discarded and paid twice.
- Turn-end passes are skipped for cron runs and delegated children, whose
  sessions end with the turn.
2026-10-25 22:55:11 -07:00
kshitijk4poor
2a0e464c27 fix(compression): keep the overload-budget reset when a summary lands
Rebasing #120603 onto main lost a line in the conflict resolution: main's
summary success path (86bf8886c2 / 4f134d4c37) resets the sustained-overload
budget, but the extracted _record_summary_success() did not. Two overload
aborts, then a healthy summary whose compaction is refused (would-grow), left
the strikes armed, so one isolated overload later escalated straight to the
destructive fallback. The helper now clears terminal failures with the shared
helper and restarts the overload budget, exactly as main does.

The overload tests move to tests/agent/test_context_compressor_overload.py
(unchanged) so the new case fits the test-file size cap.
2026-10-25 22:55:11 -07:00
kshitijk4poor
b03d642fef refactor(compression): plan the compaction window in context_compressor_window
_compress_window moves unchanged, with _plan_compaction_window and the
prepared-summary splice (_take_prepared_summary), into CompactionWindowMixin
in agent/context_compressor_window.py: the window that compress() and the
prepared-compaction pass both plan now lives in one place, and
context_compressor.py stays under its file-size ratchet. config_defaults
comments in the compression section are tightened to keep that file at its
cap. The pre-existing summary catch-all in _generate_summary gets a health
waiver: the ratchet re-flags it only because the success block above it was
extracted into _record_summary_success.
2026-10-25 22:55:11 -07:00
Hugo Alves Pereira
9212396c4e fix(agent): bound prepared-compaction staleness, size band from trigger, discard on rebind
- A candidate only splices when the messages between its boundary and the
  fresh tail cut fit in one more tail budget; a staler candidate misses and
  compaction summarizes inline.
- The preparation band is 12% of threshold_tokens, not of the context
  window, so a small absolute trigger on a large window no longer starts a
  pass on every turn.
- bind_session_state() discards the candidate and any running pass when it
  binds a different session id (/resume, /branch); same-session rebinds
  keep it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 22:55:11 -07:00
Hugo Alves Pereira
32a636bc8d feat(agent): opt-in prepared compaction (compression.prepare_ahead)
With compression.prepare_ahead (default false), once the provider-reported
prompt size is within 12% of the context window below the compaction
trigger, the turn loop starts a background pass before a tool batch runs
and at turn end. The pass plans the same window compress() plans and runs
the same summariser on a copy of the compressor and of the window rows.
The pass itself never rewrites the live transcript, system prompt or
prompt cache; the transcript keeps growing normally meanwhile.

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

State is per compressor and in memory only. Plugin context engines, Codex
app-server, native Responses compaction, micro-compaction and
background-review forks are not prepared. With the flag off no state is
created and compress() takes its existing path.
2026-10-25 22:55:11 -07:00
Hugo Alves Pereira
ee54798360 refactor(agent): extract the compaction window plan from compress()
Phases 1-2 of compress() (prune old tool results, drop blank echoes, pick
the head/middle/tail boundaries) move into _plan_compaction_window so a
second caller can plan exactly the same window. No behaviour change.
2026-10-25 22:55:11 -07:00
Teknium
3a5407ac73 fix(compression): report a summary call_llm recovered on the main model as a fallback
With auxiliary.compression on a dead endpoint (connection refused, quota), call_llm's own
recovery ladder answers the summary with the main agent model. The compressor only saw a
successful response, so the "configured compression model failed" warning never fired and
attempt telemetry read method=llm_summary, fallback_used=false: the user never learns their
compression endpoint is down. The compressor's own main-model fallback (#116472) already
reports both; only the ladder's recovery was invisible.

The ladder now records the route that failed and why in the caller's route_info when a
fallback candidate answers, and the compressor treats that like its own fallback: telemetry
fallback_used=true (failure_class aux_model_fallback) for any fallback route, and the
existing user warning plus method=aux_fallback_main when the main model answered (the
warning names the main model, so a configured fallback_chain entry gets telemetry only).

Live, real AIAgent._compress_context with auxiliary.compression on a closed port and a
reachable main model: base compacts with no warning and fallback_used=false; head shows
"Configured compression model 'slow-summarizer' failed, so Hermes summarised with your main
model instead" once and fallback_used=true, method=aux_fallback_main on both compactions.
2026-10-25 22:39:49 -07:00
Teknium
52a01bd2f2 fix(compression): a handoff row no longer collapses the tail cut onto itself
The tail-cut walk charged in-transcript handoff rows as protected-tail
candidates, but the handoff scan folds every row up to the newest handoff
into the summary window: none of them can stay in the tail. When the
handoff row alone pushed the transcript over the soft ceiling, the walk
stopped on it and the planned window held only the handoff, so compress()
returned the empty_post_handoff_window structural no-op at every trigger.

Live on main (gemini-2.5-flash, context_length 64000, prepare_ahead off):
a Desktop manual compress, then one automatic compaction (handoff now at
index 0), then four consecutive empty_post_handoff_window no-ops while the
prompt grew 47,085 -> 57,143 -> 66,716 tokens, past the 64k window.

The tail-cut walk now prices rows at or before the newest handoff at zero,
so the cut is decided by the rows that can really stay in the tail and the
window covers the old handoff plus the turns after it. Same scenario on
this branch: the second automatic compaction summarises 17 rows and the
next prompt is 18,156 tokens.
2026-10-25 22:29:15 -07:00
Teknium
8373d67547 fix(compression): hold only the floor when the trigger cannot fit a summary
At or below _MIN_SUMMARY_TOKENS (2K) the summary alone fills the trigger, so
no tail size leaves room under it; clamping the 2.5%-of-window term there only
drops recency context (a 1K test trigger on a 256K window merged the handoff
into a tail row). Keep #144177's floor-only clamp in that regime. The lean
budget moves to context_compressor_tail.lean_tail_budget.
2026-10-24 18:45:02 -07:00
Teknium
0668851519 fix(compression): prune-only then full compaction keeps one Skill Safety Rule
Prune-only rules a skill_view stub row (count-protected tail); a later full
compaction keeps that row in its token-budget tail and appended the rule to the
handoff too. Compaction now moves a kept stub's copy onto the handoff, so the
transcript carries exactly one copy while a marker remains.

Follow-up to #144177 (independent review D4).
2026-10-24 18:45:02 -07:00
Teknium
a56af5699f fix(compression): the trigger cap covers the whole lean tail budget
#144177 capped only the 10K floor at half a configured trigger; the
2.5%-of-window term still kept 25K at 1M, so the tail stayed at 123%/216%/86%
of a 12K/12K/30K trigger on 400K/1M windows and the refusal loop remained.
Clamp the final lean budget instead. Default-config budgets are unchanged on
every window from 16K to 1M (threshold_percent 0.5 already exceeds 5%).

Follow-up to #144177 (independent review D3).
2026-10-24 18:45:02 -07:00
Teknium
29c0179d64 fix(compression): the Skill Safety Rule survives prune-only and salvage rewrites
Greptile "History rewrites lose skill guidance": the rule only rode the handoff
built in _assemble_compressed, so two rewrites left [SKILL_PRUNED: markers in
context without the "one reload is enough, ignore older markers" rule:
- prune_tool_results_only turns skill_view results into marker stubs and has no
  handoff: the rule now rides the first row it turned into a marker (once per
  transcript), and _is_summary_stub ignores that suffix so a later prune leaves
  the ruled stub alone;
- anti-growth salvage cut a long handoff to its head, dropping the rule at its
  end: the elision now keeps an attached rule.
2026-10-24 17:31:52 -07:00
Teknium
44e9779659 fix(compression): lean tail floor never claims more than half a configured trigger
The prompt trims shrank the CLI system prompt by 531 chars, which moved the
loopback overflow in test_worker_compression_admission / test_journey_compress
_restart_fifo from turn 4 to turn 5. Main fails identically at turn 5 (proved by
shifting the stub's 50,000-char overflow line to 50,300 on an origin/main tree):
with compression.threshold_tokens=12000 on a 64K window the lean tail floor
(10K) kept 11.8K of verbatim tail, so the rebuilt head + summary + tail stayed
over the trigger, the overflow compaction went 9->9 messages and every pre-API
pass refused as "would grow"; the turn died with no post-summary inference.

The lean floor is now min(10K, threshold_tokens * 0.50), the trigger-side twin
of TAIL_MAX_CONTEXT_FRACTION. Default percent triggers never bind it (the
75% small-window floor puts half the trigger above the 20% window cap); only a
configured threshold_tokens or aux ceiling far below the window does.
2026-10-24 17:31:52 -07:00
Teknium
c422d69189 fix(prompt): one-shot runs drop steering, clarify and delegate live-control; skill-safety rule moves to compaction
Maintainer-approved prompt-footprint trims (measured on the Nous endpoint, anthropic/claude-opus-5.5):

All sessions
- The [SKILL_PRUNED] "Skill Safety Rule" (126 tok) left the system prompt: markers only exist after a
  compaction, so the compaction handoff now carries the rule whenever a marker survives in the
  compacted transcript (context_compressor_tail.with_skill_safety_rule, applied in
  _assemble_compressed for LLM and fallback summaries alike). The "## Pruned Skills" block drops
  its own parenthetical, which the rule now covers. `hermes sessions repair-prompts` keyed its
  "full build" detector on the rule's heading; it now keys on SKILLS_GUIDANCE (present in prompts
  built before and after this change).
- The CLI/TUI cron "LOCAL-ONLY" caveat (154 tok) moved from the platform hints into
  cronjob_manage's deliver description (a deferred tool: paid only when loaded).
- The Hermes help pointer no longer restates identity ("You run on Hermes Agent (by Nous
  Research)") after SOUL.md's "You are Hermes Agent, built by Nous Research."; it now opens "For
  help with Hermes Agent itself — ...", which still tells a custom persona what it runs on (22 tok).

One-shot sessions only (-q/--oneshot/-z, and gateway-owned `oneshot` policy sessions)
- No "## Mid-turn user steering" note (253 tok): nobody can steer a one-shot.
- No clarify tool (590 tok): ONESHOT_DISABLED_TOOLSETS is folded into session_disabled_toolsets
  (oneshot=...), so the agent tool build, MCP refresh, the tool_search bridge, delegate children and
  the gateway's session inventory / tool listings all drop it together. skill_manage stays.
- delegate_task without live control (425 tok): action/subagent_id/message and the
  background-delivery paragraph are removed (children are joined inside the call), applied via
  toolsets.agent_tool_surface at load and MCP refresh. The one-shot fact is frozen on the agent at
  its first tool build so refreshes stay byte-stable.

Interactive tool schemas are byte-identical to main.
2026-10-24 17:31:52 -07:00
defurniture2025
20acba0376 fix(sessions): proactive prune rewrites only the changed rows, in place (#124273)
* fix(sessions): proactive prune rewrites only the changed rows, in place

A prune edits the content of a few existing messages and never adds, drops or
reorders one, yet every commit went through archive_and_compact, which
archives all active rows and re-inserts the full list: state.db grew by the
whole live transcript per commit (#124102).

SessionDB.rewrite_pruned_rows resolves each changed message to its live row
(_row_id, else its tool call id or tool-call ids, else the single active row
with the same role and stored content), checks the row still holds the
original, inserts one archived twin of the pre-prune row (active=0,
compacted=1, still searchable) and updates the changed columns under the same
id. The prune tries it after the stale-history watermark check and falls back
to archive_and_compact when a row cannot be named exactly or an unwritten
message sits before durable ones.

Fixes #124102

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sessions): in-place prune twin keeps the live row's display slot

The content UPDATE fires messages_display_identity_update, which nulls
display_identity/display_order on the live row and on its freshly inserted
twin. The lazy backfill then gives the twin its own id as display_order, so
every demoted full body renders at the END of the transcript page, after the
newest user turn (3 x 24 KB bodies below "from desktop" in the probe).

Re-stamp both rows with the pre-update identity and order inside the same
transaction: the page projection shows one row per display_order (the live
stub, in place) and the twin stays a searchable archive. This is the same
stored-identity shape #117824 proposes for the archive writer (#117750), so
the resume projection collapses the pair once that lands.

Review-fix for #124273; one assertion added to the growth invariant
(red on the PR head: 20 page rows for 17 messages).

* fix(sessions): in-place prune keeps each display slot through later compaction and backfill

Review follow-up (ehz0ah): the rewritten live row kept the archived body's
identity, so a later archive_and_compact gave its copy a fresh slot and the
full body resurfaced in the old one. The live row now takes the identity of
what it stores and keeps the slot; the twin and any earlier generation's
copies (all nulled by the identity trigger) are restamped with their own
identity and slot, and the display backfill keeps a row's stored slot when
its stored identity is still correct. The prune pre-fills slots for legacy
rows so it never carries a missing one.

* fix(agent): fail closed when an in-place prune finds the row rewritten

rewrite_pruned_rows raised one PruneRowUnresolvedError for two different
conditions: the row cannot be named (ambiguity — the full writer handles it)
and the row IS named but its stored body changed. The second means another
surface already rewrote this generation, which is what StaleHeldHistory
exists to catch; the in-place prune preserves row ids, so
_archive_watermark_for cannot see it. Returning None there handed the stale
pruned_msgs to archive_and_compact, which archives rows it never compared
and republished the held text over a newer durable edit.

Split the stale case into a PruneRowStaleError subclass and raise
StaleHeldHistory from the in-place helper so the existing handler skips the
pass instead of committing. Ambiguity keeps the fallback.

Replaces the prune-fallback regression with the two cases review asked for:
a changed stored body skips the prune and leaves the newer body active; a
genuine ambiguity over current content still commits through the full writer.

* fix(agent): make an in-place prune visible to the other lease-less writer

rewrite_pruned_rows keeps every row id and activity flag, so the id/activity
staleness gate in held_archive_watermark cannot see that a prune already
committed. A second lease-less surface (micro-compaction) holding the pre-prune
transcript passes the gate and archive_and_compact republishes the pruned-away
bodies over the winner, undoing the prune.

stale_raises now also compares the held bodies against the stored ones via the
new SessionDB.rewritten_held_row_ids, so every lease-less writer sees the
in-place generation change, not just the prune caller that owns the exception.

* fix(state): compare durable row versions, not raw content, in the in-place stale guard

Reviewers on 631c897b converged on one root defect: the stale-write guard compared
raw SQLite bytes against a loaded/normalized view, which both missed real rewrites
and invented phantom ones.

- rewrite_pruned_rows._resolve: the staleness check is now the repo's stored-row CAS
  digest (transcript_row_snapshot over a SELECT * row, covering every owned column
  including assistant tool_calls arguments) when the held dict carries DB_ROW_SNAPSHOT,
  and the loader-lens identity compare (_row_identity, the same representation
  _stamp_kept_live_prefix uses) otherwise. Raw storage bytes are never compared
  against a loaded view.
- The rewritten row's replacement dict is stamped with the row's new digest, and the
  commit runs under _execute_transcript_write so a rollback restores the stamps.
- rewritten_held_row_ids takes full held dicts and applies the same two-leg compare;
  only tool/assistant rows (the roles the in-place writer touches) are compared.
- held_archive_watermark(stale_raises=True) checks the durable prefix BEFORE the
  ids[-1] is None early return, so an unstamped trailing message caps the watermark
  but can no longer suppress version checks for the rows the caller holds exactly.

Closes the P0 stale tool_calls path, the P2 false-stale on freshly resumed
whitespace-padded rows, and the unstamped-tail blind spot (#124102).

* fix(state): gate the lease-less stale check on every role the fallback republishes

The staleness gate behind held_archive_watermark (rewritten_held_row_ids)
compared only tool/assistant held rows, but the fallback it guards —
archive_and_compact, reached whenever the in-place rewrite refuses (an
unwritten message before later durable rows, an unnamed row) — re-inserts
held rows of every model-transcript role verbatim. A user row another view
rewrote in place (set_user_message_content, the repair batch's in-place
rewrite) slipped the gate: the stale pre-edit body was republished active
and the newer edit left with zero active copies.

Compare every model-transcript role (user/assistant/tool); the per-row
comparison (DB_ROW_SNAPSHOT CAS, else the loader-lens identity) is already
role-agnostic. Bookkeeping roles stay excluded — they never reach the
model-facing list. Covers the prune fallback and micro-compaction, the two
lease-less callers of _archive_watermark_for (#124102).

Sabotage-run: reverting the role filter makes
test_a_concurrent_user_edit_stays_active_when_the_prune_falls_back fail
(stale body published); restored, the file is 22/22 green.

* style: use builtin generics in the in-place prune commit annotations

* refactor(compression): split the proactive prune and its commit into topical siblings

The code-health ratchet (CI) flags this PR's own growth: hermes_state_messages.py
(2190 > 2000), agent/context_compressor.py (5911 > its main value 5852) and
agent/conversation_compression.py (4585 > 4564). The remedy the repo prescribes:
move the PR's own code into topical siblings, keeping the facade as the seam.

- agent/context_compressor_prune.py: ProactivePruneMixin (prune_tool_results_only
  + _rewrite_pruned_rows_in_place), bound into ContextCompressor; origin-module
  symbols read through _cc() at call time (the micro_compaction.py pattern) so
  tests patching agent.context_compressor.X stay effective; logger keeps the
  agent.context_compressor name for caplog parity.
- agent/conversation_compression_watermark.py: held_archive_watermark; the origin
  module imports it and keeps _held_watermark (its only caller).
- hermes_state_prune_rewrite.py: SessionPruneRewriteMixin (rewrite_pruned_rows +
  rewritten_held_row_ids), bound into SessionDB; every SessionDB call site and
  test patch seam (db.rewrite_pruned_rows / db.rewritten_held_row_ids) unchanged.

Verified: scripts/check --only health --base origin/main -> 0 blocking; ruff clean;
prune/compaction batches green (test_proactive_prune_restart_safety 22/22,
test_micro_compaction 48/48, five proactive-prune files 25/25). The 4 failures in
test_compaction_prompt_rebuild / test_compression_review reproduce identically on
origin/main (pre-existing).

* fix(state): re-verify held rows inside the full writer's commit transaction

The lease-less stale gate (rewritten_held_row_ids) runs outside the write
transaction, so a second SessionDB connection that rewrites a covered row
AFTER the precheck but BEFORE archive_and_compact's BEGIN IMMEDIATE was
invisible to it: the commit archived the newer row and republished the stale
held text, leaving the newer edit with zero active copies (#124102, review
finding on 8c6da464).

- archive_and_compact takes held_for_cas: the caller's held dicts,
  re-verified against the live rows INSIDE the commit's transaction before
  any row moves; a mismatch raises HeldRowRewrittenError, which the two
  lease-less callers (proactive prune fallback, micro-compaction sync)
  treat exactly like StaleHeldHistory - nothing written, the pass is a
  no-op and the newer generation keeps the session. The lease path leaves
  it None: its lease rules out an overlapping rewrite.
- held_row_mismatches(conn, ...) is the compare lifted out of
  rewritten_held_row_ids so both the read-path precheck and the
  in-transaction fence share one implementation. It now chunks the id IN
  query via _id_chunks (a history past SQLite's host-parameter limit
  failed the pass instead of reclaiming) and resolves rows that have no
  _row_id but do carry the persist marker + CAS snapshot by their logical
  message_uid (idx_messages_session_uid) - the unaddressed live-replay
  loader shape, whose rows were previously exempt from the fence entirely.
- regression: test_a_user_edit_landing_after_the_precheck_stays_active_in_the_commit
  drives a second SessionDB connection's set_user_message_content at the
  archive_and_compact call boundary; sabotage (gate disabled) makes it
  fail exactly as the finding predicts.

* refactor(compression): drop the duplicate _held_watermark from the module split

The 8c6da464 sibling extraction left two identical _held_watermark
definitions back to back in agent/conversation_compression.py; Python
silently kept only the second, so editing the first had no effect (dead
code, root AGENTS.md). Remove the added copy.

* refactor(state): split the api_content sidecar writers into a topical sibling

hermes_state_messages.py crossed the FILE_LINES ratchet (2010 > 2000) after
the commit-window fence landed in it. Move set_latest_user_api_content /
set_message_api_content into hermes_state_api_content.py
(SessionApiContentMixin, bound into SessionDB in the same MRO slot): the
two row-addressed api_content sidecar UPDATEs are one topic, no behaviour
change, every call site and test patch seam unchanged.

* fix(state): flatten _archive_and_compact_on_conn onto the caller's transaction after the main merge

Main flattened this helper to run directly on the caller's write connection
(no nested _execute_transcript_write); the merge resolution had kept the old
nested shape, which opened a second BEGIN IMMEDIATE inside the live one and
deadlocked every archive_and_compact. Re-flattened while keeping the #124102
held_for_cas in-transaction CAS fence.

* fix(state): carry the held-row CAS fence through the worker RPC path

RuntimeSessionCompressionMixin.archive_and_compact rejected held_for_cas,
so a worker-side micro-compaction commit raised TypeError inside the mixin's
generic except and silently skipped the whole persist (unstamped marker,
durable transcript left un-compacted). Accept held_for_cas, project it onto
the closed handoff fields plus the persistence marker the CAS compare reads,
validate it in worker_archive, and thread it into
archive_on_connection -> _archive_and_compact_on_conn (#124102).

* test(micro): a stale held generation without row ids aborts the micro-compact

Review follow-up (ehz0ah/greptile-apps, PR #124273): ACP restore and OpenAI
session continuation load through the unaddressed live-replay projection
(get_messages_as_conversation without include_row_ids=True) — the persist
marker, durable message_uid and the stored-row CAS digest, but no _row_id.
held_row_mismatches already resolves that shape by logical message_uid, so
the lease-less fence still sees another surface's in-place prune. Pin it with
the regression both reviewers asked for: after another surface prunes in
place, micro-compaction from that stale no-row-id history is a true no-op —
the pruned stubs stay the only live generation and the pre-prune bodies are
not republished (#124102).

Sabotage: disabling the by-uid branch in held_row_mismatches fails this
test (the sync republishes the stale bodies); restored, 49/49 pass.

Co-authored-by: ehz0ah <ehz0ah@users.noreply.github.com>

* fix(sessions): the uid-resolved stale fence CASes the newest active row

held_row_mismatches resolved an id-less held dict by its logical
message_uid with a bare fetchone(): when a carried or concurrent
compaction has cloned the row back beside its archived twin, one uid
names several active physical rows, and the uid index returns them
oldest-first. The fence then CASed the oldest copy — which still held
the payload the held digest was stamped from — and cleared a held
generation as current although another writer had rewritten the newest
row; the lease-less fallback republished the stale held payload over
that newer generation (#124102).

Resolve with the same newest-active rule as the loader's
_active_logical_message_row (ORDER BY id DESC LIMIT 1). Two
regressions pin it: two active rows sharing a uid where only the
newest was rewritten in place must abort the micro-compact naming the
newest row id, and where only an older duplicate moved the held
digest must stay current.

Review follow-up to greptile-apps' 2026-10-17 P1 on PR #124273.

---------

Co-authored-by: defurniture2025 <301948806+defurniture2025@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: teknium1 <127238744+teknium1@users.noreply.github.com>
Co-authored-by: Austin Pickett <pickett.austin@gmail.com>
Co-authored-by: Austin Pickett <austinpickett@users.noreply.github.com>
Co-authored-by: ehz0ah <ehz0ah@users.noreply.github.com>
2026-10-18 19:44:32 -04:00
Teknium
ed9fb3cf56 fix(plugins): fire post_compaction on every committed compaction path
The salvaged hook fired from ContextCompressor.compress(), which is not where
a compaction commits: compress_context can still refuse or roll back the
candidate (snapshot stale, commit fence, split failure), the gateway's
/compress runs its own compressor and commits elsewhere, and Codex-native,
micro-compaction and proactive-prune rewrites never call compress() at all.
session_id was also the compressor's bound id, which is stale after rotation.

Fire it from the compaction-record seam (agent/compaction_events.py) that
already sees exactly one committed record per rewrite on every agent path,
and from the gateway session.mutate compress commit. Payload: session_id (the
session holding the compacted transcript), old_session_id, kind, reason,
before/after token estimates, messages_removed. Bounded by
plugins.hook_callback_timeout, since it runs inside the commit window.

Tests trimmed to one invariant (fires once per committed compaction, never
for an aborted one, raising plugin isolated); docs in hooks.md and the
plugin guide.
2026-10-18 02:31:09 -07:00
Baophan00
35948f22ad feat(plugins): add post_compaction hook (#118382)
Fires once after a successful context compaction so plugins/providers
can react (re-inject context, update indices, etc.). Gated on has_hook
for zero-cost when no listener. Observer-only, returns ignored.
2026-10-18 02:31:09 -07:00
Teknium
899b7df621 fix(gateway): replay the compactor's restated in-flight task unstamped too
A compaction that restates the unfinished request as a standalone user row
sends it unstamped; the next gateway turn reloaded it and stamped it like a
message someone sent, so the request diverged from the cached prefix at that
row exactly as the summary row did. The compressor now marks that row with a
producer-owned display_metadata flag (persisted by SessionDB, popped from
every wire copy) and gateway replay skips the stamp for any compaction
scaffolding; the helpers live in agent/message_metadata.py beside the
persistence-only field set.
Human-pasted header text carries no flag and keeps its timestamp.

Ported (trimmed) from #130909's restatement-provenance commits; the merged
carrier layout already carries _compressed_summary so needs no flag.

Co-authored-by: Yuan Li <dskwelmcy@163.com>
Co-authored-by: Ofir Flaisher <6105216+ofirf@users.noreply.github.com>
2026-10-16 14:35:30 -07:00
Teknium
837213a054 fix(agent): latch retired screenshots per session across replay-window rollover
Once the replay window dropped an oversized upload, the request relaxed to the
100-image ceiling and the from-scratch per-request decision restored all eight
retired screenshots into already-sent history. The main loop and the summary
request builder now pass a session-keyed set of retired tool-call ids; every
carrier up to the newest previously retired one stays retired.
2026-10-16 14:21:39 -07:00
Teknium
ac97c307b0 refactor(agent): carry image sources once in the send-path eviction walk
_image_payload returned (blocks, bytes, sources) where blocks and bytes are
derivable from sources; return the sources list alone and derive both at the
call site. Keeps context_compressor.py under its code-health file cap after
the dimension-gating change, with no facade module.

Part of #133999
2026-10-16 14:21:39 -07:00
salch-cred
8b1ccb67d3 fix(agent): gate the 20-image eviction trigger on the request's dimensions
Mechanism: `agent/image_eviction_policy.outbound_image_retire_count` retired a
batch of 8 once a request carried more than 20 image blocks, for every provider
and every request. 20 is where Anthropic starts holding EVERY image in the
request to a stricter per-side cap -- it is not a count limit, so crossing it
only constrains a request that actually contains an image over that cap. Hermes
already embeds its own tool images well under it (`vision_analyze` and browser
screenshots at 1568 px, `computer_use` at 1456 px by default), and user uploads
are reserved and never rewritten. So on an all-tool-image request the 21st
screenshot crossed no provider constraint, and the batch retire rewrote a cached
prefix for nothing -- on the preserved-thinking models that also invalidates
every later thinking block (Anthropic's computer-use guidance now says to keep
screenshots at or under 2000 px and NOT to prune them client-side).

Seam: the block ceiling becomes conditional. `outbound_image_retire_count` takes
`many_image_safe` and derives `limit` from `outbound_image_block_limit()`, the
strict 20 unless every image in the request is within `MANY_IMAGE_DIMENSION_LIMIT`
(2000 px). Both passes classify from the same module so the #113517 invariant
holds: `context_compressor.evict_stale_outbound_tool_images` (OpenAI shape,
`image_url`) and `anthropic_message_convert._evict_old_screenshots` (wire shape,
`source.data`). Classification is header-only -- `image_max_side_from_data`
decodes just the leading base64 prefix, never a whole payload -- and fails
closed: a missing, unreadable or non-image source keeps today's strict 20.

`image_dimensions_from_bytes` moves into the policy leaf (which the wire
converter already imports and which must not import `tools/`) and is re-exported
from `tools/computer_use/backend.py`, so the tool layer's min-size guard and the
two send-path passes share one PNG/JPEG header reader.

Repro (real passes, pre-change code): 21 tool results carrying one 1568 px image
each -> `evict_stale_outbound_tool_images` returned 8 rewrites; 30 -> 16. Same
fixtures after the change -> 0, and 0 on the wire pass. A 20-carrier request
plus one 2001 px user upload still retires exactly `IMAGE_EVICTION_BATCH` (8),
byte-identical to before.
2026-10-16 14:21:39 -07:00
Teknium
297552a9d6 fix(compression): fallback summaries, multiline setup notes and parallel loads keep skill markers right
Independent review follow-up:

- The deterministic fallback summary re-summarizes Phase-1 stubs, and
  _sum_skill_view re-decided the marker from the stub text, so a failed view's
  stub gained a reload marker there. A stub now keeps its own verdict (marker
  only if it already carries one), and a failed stub keeps FAILED.
- The auto-load describer ended a setup note at its first newline, so a
  multiline setup hint leaked into the recovered request. The note now ends
  at "]" followed by the blank line that separates generated blocks.
- _collect_ghosted_skill_names mapped every parallel skill_view call on one
  assistant row to the row's last skill, so two raw loads listed only one. It
  now uses the per-call mapping the lean-tail demotion already had.
- Fallback "User asked" anchors render a /skill turn as typed, like the other
  summary sections.
2026-10-14 14:56:35 -07:00
Teknium
a36fb64f28 fix(compression): failed skill views and auto-load file lists are not reloaded or quoted
Review follow-up (Greptile, two P2s):

- A failed skill_view stub kept no failure outcome, so a later compaction
  counted it as a lost skill and asked the model to reload a skill that never
  loaded. The stub now carries " FAILED: <error>" like skills_list and
  skill_manage, failed raw payloads and stubs are both skipped when collecting
  pruned skills, and the lean tail adds no reload marker to a failed view.
- The auto-load describer took everything after the last directory footer as
  the typed request, which included the config, setup-note and supporting-file
  blocks _build_skill_message appends after that footer. Those blocks are now
  skipped by their fixed openings and endings, so previews, titles and the
  compaction quotes show only what the user typed.
2026-10-14 14:56:35 -07:00
Teknium
d602082868 fix(compression): a slash-skill body's example paths stay out of the anchor index
The lean Anchor Index harvested identifiers from the whole /skill scaffold, so
the footer's example paths (scripts/foo.js, templates/config.yaml) were listed
as files the session touched. User rows now contribute what the user typed.
2026-10-14 14:56:35 -07:00
Teknium
71e815def8 fix(compression): small and slash-invoked skills keep their reload marker across compaction
Compaction stubbed every skill_view body over 200 chars but only bodies over
5,000 chars got the [SKILL_PRUNED: ...] reload marker, so a small skill (about
a quarter of bundled SKILL.md files) lost its instructions with nothing telling
the model to reload it. Skills loaded inline by /skill, bundles, stacked
invocations and the gateway channel auto-load were invisible to the defence:
no marker, no "## Pruned Skills" entry, and lean mode quoted the first 4K of
the skill body as "the user's actual words" while cutting the request the user
typed after it.

- Every stubbed skill_view result gets the marker; a failed view (success:
  false) loaded nothing and stays unmarked.
- _collect_ghosted_skill_names counts any skill_view row in the compacted
  region regardless of size (plain stubs from earlier compactions included)
  and the skills a scaffold turn carried inline.
- skill_commands.skills_loaded_by_scaffold names those skills from a complete
  activation header only, so typed text that starts like one is not matched.
- The lean verbatim user block, the historical task snapshot and the auto
  focus render a scaffold turn as typed (/skill do X) via
  describe_skill_invocation, the approach @100yenadmin took in #136541.

Two existing assertions pinned the old size gate and are updated per the
maintainer's ruling that small skills must be maintained too.

Co-authored-by: Eva <239388517+100yenadmin@users.noreply.github.com>
2026-10-14 14:56:35 -07:00
Eva
036c31d24c fix(compression): a demoted tail skill_view result keeps its reload marker 2026-10-14 14:56:35 -07:00
Teknium
994759f4c4 Merge origin/main (#39: 29 commits to d4d2ab7b5d) into feat/unified-gateway-runtime
No conflicts. Brings in main's reasoning-replay series, holographic memory leaving core
(run_profile_reconcile now imports it through import_provider_module), and the update
main-channel fix.
2026-10-10 23:38:42 -07:00
Teknium
37d6492474 fix: encrypted reasoning items are never deleted from retained history
Compaction pruned every earlier-turn codex_reasoning_items on routes assumed not
to read them (a cost choice, #71058), and the first invalid_encrypted_content
rung deleted foreign-issuer items the failing request never sent, then retried a
byte-identical request. Compaction now drops only shadowed checkpoints, and the
rung strips only unverified items that were actually replayed. The request
builder already filters items per issuer and model on the wire.
2026-10-10 19:22:07 -07:00
Teknium
86aa201bba fix: compaction salvage no longer strips reasoning from retained turns
salvage_grown_transcript (the anti-growth pass at the compaction commit site)
popped reasoning / reasoning_content / reasoning_details from every assistant
turn but the newest, and pruned every prior-turn codex_reasoning_items, before
the result was committed as canonical history. With replay on by default that
is a permanent continuity loss on exactly the long sessions compaction serves.
Reasoning text is now never a salvage shrink target (tool output and summaries
still are), and codex items follow compress()'s route rule
(route_reads_prior_turn_reasoning).
2026-10-10 19:22:07 -07:00