Commit Graph

19933 Commits

Author SHA1 Message Date
Sergey Prontsevich
89f0b63da4 perf(mcp): non-blocking startup via background MCP discovery + TUI fast path
Fire-and-forget MCP server connections on a daemon thread so the
gateway / CLI / ACP process becomes interactive immediately instead
of blocking on slow remote MCP servers (HTTP timeouts, sluggish
stdio boot).  Previously `hermes --tui` waited 2-5 s after the splash
screen before rendering the UI while `discover_mcp_tools()` ran
synchronously on the critical path.

Changes:
- tools/mcp_tool.py: add `discover_mcp_tools_background()` — thin
  wrapper that spawns `discover_mcp_tools()` on a named daemon thread
- tui_gateway/entry.py: call `discover_mcp_tools_background()` before
  sending gateway.ready (replaces inline call that blocked the JSON-RPC
  pipe for the TUI Ink app)
- hermes_cli/main.py:
  - skip `\_prepare_agent_startup()` for TUI path — plugins, MCP, and
    shell hooks are only needed by the CLI agent loop; the TUI's
    gateway subprocess discovers them independently (~370 ms saved)
  - fast-path in `\_make_tui_argv()`: when `dist/entry.js` exists and
    is fresh, skip npm install / rebuild checks entirely (~350 ms saved)
- cli.py (`\_prepare_deferred_agent_startup`): same background pattern
  for deferred startup (Termux interactive CLI)
- acp_adapter/entry.py: same pattern so ACP server launches asyncio
  immediately while MCP connects in parallel

Result:
- TUI Python wrapper: ~730 ms → ~80 ms (9× faster)
- gateway.ready: ~2700 ms → ~400 ms (7× faster)
- Total TUI cold start: ~3400 ms → ~480 ms

Related: #29726, #29184, #19326 (closed stale)

Closes #29726
2026-08-01 13:27:58 +05:30
brooklyn!
9b1d8341b2 Merge pull request #75988 from NousResearch/bb/cwd-focus-and-display
Session workspace tracks focus — and paints as ~/…
2026-08-01 02:53:44 -05:00
brooklyn!
1a25214364 Merge pull request #75998 from NousResearch/bb/pane-size-remember
fix(desktop): keep ⌘G/files rails at their default size
2026-08-01 02:52:43 -05:00
kshitij
3d5f3967d5 Merge pull request #75984 from kshitijk4poor/chore/contributor-emails-prontsevich
chore: add contributor email mappings for @Prontsevich
2026-08-01 13:20:30 +05:30
Brooklyn Nicholson
5657c4a541 fix(desktop): sort display-path import for eslint 2026-08-01 02:46:40 -05:00
Brooklyn Nicholson
47d7b7fb1d fix(desktop): keep review/files rails at their declared size
All-fixed splits used to promote the last track to flex-grow and drop its
max clamp. Review and files both declare maxWidth, so ⌘G/⌘J ballooned them
and sash overrides only set a basis that grow still expanded past.
2026-08-01 02:45:47 -05:00
HeLLGURD
d109138ef5 fix(mcp): avoid replaying historical events on startup (#13414)
EventBridge initialized each session's last_seen timestamp to 0.0, so
the first poll after 'hermes mcp serve' starts treated every saved
user/assistant message in state.db as a fresh events_poll event.

The fix establishes a per-session timestamp baseline on startup via
_establish_baseline(), recording the latest existing message timestamp
without emitting events. Only messages written after the baseline are
delivered on subsequent polls.

Also hoists _ts_float to module-level (needed by _establish_baseline)
and adds ImportError fallbacks for hermes_constants imports so the
bridge works in environments where the module isn't on the path.

Salvage of #13414 by @afurm, re-applied by @HeLLGURD in #41239.

Co-authored-by: afurm <afurm@users.noreply.github.com>
2026-08-01 13:13:30 +05:30
Brooklyn Nicholson
883076ccd7 feat(desktop): ⌘N/⌘T keep the focused session's project
resolveNewSessionCwd now inherits the focused chat's workspace when you
aren't drilled into a sidebar project, so a new tab or draft stays in
the same repo as the chat you were looking at.
2026-08-01 02:32:28 -05:00
Brooklyn Nicholson
3707741d9f fix(desktop): statusbar cwd follows the focused session
Workspace indicator was stuck on the primary $currentCwd while timers
and context already tracked focus. Resolve from the focused runtime
slice, then the stored session row, with a mid-switch ownership gate.
Path tips across chrome use displayPath (~/).
2026-08-01 02:32:28 -05:00
Brooklyn Nicholson
5b4c57a7ff feat(desktop): shared path display collapses home to ~
One paint helper for UI chrome: /Users/x/y → ~/y (also /home and
C:\Users). Copy/reveal still use the real absolute path.
2026-08-01 02:32:28 -05:00
brooklyn!
57b1eb8c4d Merge pull request #75975 from NousResearch/bb/terminal-session-link
Link terminal tabs to the session you're working in
2026-08-01 02:22:30 -05:00
brooklyn!
bfc014e3a8 Merge pull request #75966 from NousResearch/bb/dither-tail-only
fix(desktop): thinking indicator can no longer appear mid-transcript
2026-08-01 02:18:12 -05:00
Brooklyn Nicholson
c450fb931d feat(desktop): switching sessions re-selects the terminal tab in its cwd
A $currentCwd listener in the terminal store picks the user tab whose
live shell cwd (restoreCwd, falling back to launch dir) matches the
session's workspace. Selection only: no tab is created, closed, or
revealed; detached sessions and unmatched cwds leave the rail alone,
and an already-matching active tab keeps focus.
2026-08-01 02:15:02 -05:00
Brooklyn Nicholson
eb545ddea9 feat(desktop): ⌘-click closes a terminal rail tab
Same gesture the pane tabs already carry — isMetaClose hoists from
pane-tab.tsx into lib/middle-click.ts beside its sibling middle-click
gesture, so the two surfaces share one predicate instead of drifting.
2026-08-01 02:15:02 -05:00
Brooklyn Nicholson
ba75633334 fix(desktop): never show the thinking indicator anywhere but the thread tail
A turn that ended without its message.complete (turn crash, reconnect gap,
steer race) left its streaming bubble pending:true forever. The next user
message then landed after it, stranding a live dither indicator
mid-transcript.

Three layers:
- session.info running=false (the agent loop's finally-block signal, the
  only settle edge those paths still emit) now finalizes the streaming
  bubble via the same math as Stop.
- A fresh submit settles any leftover pending bubble before appending the
  new user message, and drops a stale streamId so the new turn seeds fresh.
- AssistantMessage renders the loading/stall indicator only on the thread's
  last message, so no upstream state bug can ever paint one mid-transcript.
2026-08-01 02:10:56 -05:00
kshitij
151e72a5fc refactor: simplify pairing check return and drop over-defensive getattr
Follow-up cleanup from /simplify-code review:
- Replace 'if X: return True / return False' with 'return X'
- Replace 'getattr(source, "chat_type", None) or ""' with 'source.chat_type'
  (SessionSource.chat_type is a non-optional str field)
2026-08-01 12:38:38 +05:30
xxxigm
29b3adf902 test(telegram): cover allowlist + unauthorized_dm_behavior pair pass-through
Guard the early-auth pairing gap: unknown DMs must reach the gateway when
pairing is the effective unauthorized-DM behavior, while ignore mode and
unauthorized group senders stay rejected.
2026-08-01 12:38:38 +05:30
xxxigm
dae4cf6bb6 fix(telegram): let pairing-bound DMs past early auth with allowlist
The #40863 intake prefilter rejected unauthorized DMs whenever an allowlist
existed, so gateway pairing never ran even when the operator set
telegram.unauthorized_dm_behavior: pair (which must win over the #9337
allowlist silence default). Pass those DMs through; groups stay blocked.
2026-08-01 12:38:38 +05:30
kshitijk4poor
e5ba319a5c chore: add contributor email mappings for @Prontsevich 2026-08-01 12:37:17 +05:30
brooklyn!
18627ff009 Merge pull request #75931 from NousResearch/bb/tui-slash-priority
The TUI slash menu leads with the skills you actually use
2026-08-01 02:01:44 -05:00
kshitij
3572d4bca1 fix(mcp): ensure MCP discovery completes before agent build in non-interactive sessions
Non-interactive sessions (hermes chat -q, hermes -z) snapshot the tool
registry at AIAgent construction time. If background MCP discovery hasn't
finished, MCP tools are invisible for the entire session — and unlike
interactive mode, there is no between-turns late-binding refresh to recover.

Root cause: wait_for_mcp_discovery() only joins an already-created discovery
thread, so it no-ops if a direct/single-query path reaches agent construction
before MCP startup created that thread. Oneshot._run_agent() didn't call it
at all.

Fix:
- Add ensure_mcp_discovery_before_agent_build() helper to mcp_startup.py:
  idempotently starts discovery if needed + bounded wait. Fail-open on errors.
- Add single_query parameter to _resolve_discovery_timeout/wait_for_mcp_discovery:
  uses mcp_single_query_discovery_timeout (default 15s) instead of the
  interactive mcp_discovery_timeout (1.5s) because one-shot sessions have no
  second turn to recover.
- Wire into CLI _init_agent (single_query from _single_query_mode flag set
  in cli.py's single-query path) and oneshot._run_agent (single_query=True).
- Interactive sessions unchanged: keep 1.5s bound (between-turns refresh covers).

Closes #38448, #51316, #37013, #68137
Composite salvage of #60017 (chrishart0), #51322 (Bartok9), #38620 (buptwz),
#43544 (halonke), #36882 (vanhoof).
2026-08-01 12:27:31 +05:30
brooklyn!
d1c40a731d Merge pull request #75949 from NousResearch/bb/fix-copy-with-reactions
fix(desktop): copy selected chat text again
2026-08-01 01:56:43 -05:00
Brooklyn Nicholson
90e6fe4f55 fix(desktop): terminal selection mirror yields to chat copy
mirrorSelection called textarea.select() whenever xterm had a scrap,
which replaced any chat highlight so ⌘C copied the wrong thing. Only
claim the document selection while the terminal is focused and nothing
outside it is highlighted.
2026-08-01 01:49:38 -05:00
Brooklyn Nicholson
1d97c035ef fix(desktop): drag-select and ⌘C work on user bubbles again
User bubbles are buttons, so the global user-select:none rule killed
text selection. Right-click-to-react and click-to-edit also ate a live
highlight. Prefer selection when one exists.
2026-08-01 01:49:38 -05:00
brooklyn!
85148f79f7 Merge pull request #75937 from NousResearch/bb/win-icon-size
fix(desktop): make the Windows app icon match native icon size
2026-08-01 01:41:24 -05:00
webtecnica
4be138eb03 fix(config): skip URL alias without extra_headers instead of returning early (#74465)
get_custom_provider_extra_headers() was returning the result of
normalize_extra_headers() on the first matching base_url, even when
that entry had no extra_headers configured. A later providers.<name>
entry sharing the same URL but with headers set was therefore ignored.

Fix: store the normalized headers and only return when non-empty,
otherwise continue searching the remaining entries.

Fixes #74465
2026-07-31 23:33:12 -07:00
Baophan00
595be544c0 test(config): add regression tests for broken-YAML config preservation
Verify that set_config_value and unset_config_value refuse to write
when config.yaml contains YAML syntax errors, and the original file
is left intact.
2026-07-31 23:33:12 -07:00
Baophan00
df09a90cd6 fix(config): refuse to write when config.yaml has YAML syntax errors
set_config_value() and unset_config_value() silently replaced the
entire config with an empty dict when config.yaml could not be
parsed. A single YAML syntax error would cause 'hermes config set'
to wipe all settings and write only the new key. Now exits with
error and preserves the existing file.
2026-07-31 23:33:12 -07:00
Brooklyn Nicholson
e524310118 fix(desktop): render the ico truly full-bleed
The first regeneration kept a ~5% transparent margin around the icon
plate (94.9% coverage). Windows expects the plate itself to be the icon
edge — scale the artwork's rounded plate to span the canvas exactly.
2026-08-01 01:33:05 -05:00
brooklyn!
41e55679ee Merge pull request #75848 from NousResearch/bb/toggle-terminal-persist
Toggle any pane wherever you put it, and keep the header hidden
2026-08-01 01:32:36 -05:00
brooklyn!
d41d9e4faa Merge pull request #75935 from NousResearch/bb/card-retire
The changed-files card stops at five rows
2026-08-01 01:31:30 -05:00
Brooklyn Nicholson
80c86c4949 fix(desktop): make the Windows app icon match native icon size
The shipped artwork bakes in the macOS-style ~10% transparent margin
(content covered only ~80% of the canvas), so the taskbar/titlebar icon
rendered visibly smaller than neighboring Windows apps, which draw
full-bleed.

- Regenerate assets/icon.ico full-bleed (~95% coverage) from the same
  art, with the standard 16-256px frames. This feeds both the exe stamp
  (set-exe-identity via rcedit) and the installer.
- On Windows, resolve the BrowserWindow icon from the full-bleed ico
  (resources/icon.ico, shipped via extraResources) before falling back
  to the padded apple-touch PNG.

macOS is untouched: the dock icon and icon.icns keep the padded art,
which is correct there.
2026-08-01 01:26:46 -05:00
Brooklyn Nicholson
feaa325033 Merge origin/main into bb/toggle-terminal-persist
main reworked the same surface while this was open, so three hunks needed
deciding rather than accepting.

Logs became summon-only (#75862): the contribution only exists while $logsOpen
is on, docked as its OWN zone beside the terminal instead of a tab in its
strip. That supersedes the static logs pane and the bindToolPaneCollapse call
here — main already registers logs' closer/opener directly, so both were
dropped in favour of its version.

main also added a ⌘K "Toggle terminal" row reading $terminalTakeover, and
gave logs back a 7.5rem minHeight under a comment claiming the terminal's
sizing rule. Both are the bugs this branch fixes, so they move onto the
shared behaviour: the palette row reads isPaneVisible/togglePaneVisible like
every other pane toggle, and logs loses the floor so the comment is true —
the sash folds its zone to the rail instead of stranding a sliver.
2026-08-01 01:25:33 -05:00
Brooklyn Nicholson
0b8a3582c6 fix(desktop): cap the changed-files card and fade its overflow
A turn that rewrote twenty files grew a twenty-row card, so the summary
that is supposed to close the turn became the thing you scroll past to
reach the composer. Cap the rows at ~5 and let the clipped edge fade,
the way every other overflow in the app reads.

The horizontal padding moves onto the scroller so a row's hover fill
still bleeds to the card's edge instead of stopping at a scroll gutter.
2026-08-01 01:24:05 -05:00
Brooklyn Nicholson
15b0b95413 refactor(desktop): one edge-faded scroller for the whole app
The kanban drawer had grown the only edge-aware masked scroller in the
tree, and the next surface that wants one would have copied it. Lift it
to components/ui as FadeScroll, export it on the plugin SDK, and leave
kanban's ScrollFade as a name its call sites already pass `max` to.

The mask math comes out as two pure functions. jsdom's CSS parser drops
any gradient containing calc(), so a rendered mask-image can't be read
back off the style attribute -- edgeMask/scrollEdges are testable for
real where the component's inline style is not.
2026-08-01 01:23:59 -05:00
kshitijk4poor
4773e965c0 chore: add hans@groupg.org → hansai-art to AUTHOR_MAP
Contributor email mapping for PR #66011 (model-switch marker dedup).
2026-08-01 11:53:03 +05:30
Eugeniusz Gilewski
64dd865912 fix(deps): repair Google transitive security floors (#72108)
Google API and authentication packages permit vulnerable httplib2 and pyasn1
transitives, while the Workspace and Google Chat runtime installers previously
treated any importable version as sufficient. Existing environments could
therefore remain vulnerable after the project dependency pins were repaired.

Carry the fixed versions through the Google and Vertex extras, lazy feature
requirements, lockfile, and both runtime installers. Route the documented
Google Chat installation path through its maintained secure requirements
instead of an unconstrained direct pip command.

Detect stale distributions, install only unsatisfied requirements, and verify
the result before continuing. Behavioral tests cover those repair invariants
without freezing manifests, lockfiles, or complete package sets.

Related #72108
Extracted from #72840
Co-authored-by: Teknium <127238744+teknium1@users.noreply.github.com>
2026-07-31 23:18:38 -07:00
Teknium
e008b62a72 fix(state): route no-more-rows retries through the shared patience helper; add contributor mappings
The rebase onto main's extracted _sleep_before_write_retry() method left
three call sites pointing at the dropped local helper; rewire them.
Also adds contributors/emails mappings (Dannou, trippyogi, spfcraze).
2026-07-31 23:18:12 -07:00
RelaxJonh
b6ca4fc856 fix(state): heal session_model_usage PK unconditionally to restore token/cost accounting
Installs whose state.db reached schema_version >= 22 before the task
dimension was added carry a 5-column PRIMARY KEY on
session_model_usage. The column reconciler ADDs task as a bare
nullable, but SQLite cannot ALTER a primary key, and the version-gated
v22 rebuild is unreachable (current_version < 22 already false), so
the composite 6-column key never lands. Every upsert in
_record_model_usage then fails with 'ON CONFLICT clause does not match
any PRIMARY KEY or UNIQUE constraint', aborting the enclosing write
transaction — token/cost accounting permanently dead (#73823).

Add an idempotent _heal_session_model_usage_pk() modeled on
_heal_gateway_routing_pk(), run unconditionally from _init_schema on
every open. Salvaged from #73838 with fix-ups:

- ported to SessionSchemaMixin in hermes_state_schema.py (the schema
  code moved out of hermes_state.py in 21c7ae8563; the PR targeted the
  old location)
- rebuild wrapped in a PRAGMA foreign_keys=OFF/ON window: the
  connection enables FKs before _init_schema and OR IGNORE does NOT
  suppress FK violations, so a single orphaned usage row (session
  pruned while accounting was broken) would have aborted the heal
- COALESCE('') on the nullable reconciler-added task column (and the
  billing columns) during the copy
- stale-v22+ regression tests: rebuilt PK + restored upsert, orphan
  rows survive the FK window, healthy-DB no-op, no legacy leftover

Fixes #73823
2026-07-31 23:18:12 -07:00
Dannoob
14eca89779 fix(state): retry transient 'no more rows available' across all sqlite3.Error classes
Under dual gateway/agent WAL contention (FTS5 trigram sync holding the
write lock on large appends) the SQLite engine can raise a transient
'no more rows available' error. The exception CLASS varies with the
build — some surface it as InterfaceError, a SIBLING of DatabaseError —
so it escaped both existing retry branches in _execute_write on attempt
0 and killed the turn as session_persistence_failed even though the
identical write succeeds standalone.

Port of #74934 onto the deadline-patience rewrite (8da8a7887d): the
PR's attempt-counted constants (60 retries / 300ms jitter / 2.0s engine
timeout) predate that rewrite and are superseded by the patience
budget, so they are intentionally NOT carried over. Instead the check
is message-scoped and rides the existing deadline/patience loop:

- extract the jittered-sleep-within-deadline logic into a shared
  _sleep_before_retry helper (behavior-preserving for locked/busy)
- retry 'no more rows available' from OperationalError, DatabaseError
  (checked BEFORE the FTS-corruption rebuild path so it is not
  misrouted), and a message-scoped sqlite3.Error catch-all
- any other error in any class propagates untouched on attempt 0

Tests: transient InterfaceError retried to success; unrelated
InterfaceError propagates immediately; DatabaseError variant retried;
exhausted patience surfaces the original error.
2026-07-31 23:18:12 -07:00
Teknium
d5463e5f6d fix(agent): invalidate flush-scan cursor at the defrag marker-pop sibling site
The micro-compaction defrag pass (_defrag_rolling_summary) rewrites the
newest MICRO marker's content and pops _DB_PERSISTED_MARKER from the
LIVE dict in place — the same in-place pop class finalize_turn's fill
site was fixed for in #75170. Without invalidation the bounded
flush-scan cursor identity-skips the rewritten marker row and the
defragged rolling summary never reaches state.db (resume rehydrates a
stale summary).

The compressor holds no agent reference, so the pop site raises
_flush_scan_cursor_invalidated and the finalize_turn micro-compaction
block consumes it, setting agent._db_flush_scan_prefix = None.

The module-scope pop sites (context_compressor.py:175/224) operate on
fresh copies — identity-breaking by construction — and need no flag.

Follow-up to #75170 (fix-the-class sweep of _DB_PERSISTED_MARKER
in-place pops).
2026-07-31 23:18:12 -07:00
spfcraze
2aaeee2ee5 fix(agent): invalidate flush-scan cursor when finalizer pops db marker
The bounded flush-scan in _flush_messages_to_session_db_unlocked skips
the identity-matched prefix of its previous snapshot, on the documented
assumption that no code path pops _DB_PERSISTED_MARKER from a live dict
in place. finalize_turn's pure-tool-call-tail fill is exactly that path:
it pops the marker so the filled content gets re-persisted — but the
cursor then skips the row anyway, so the delivered final response never
reaches state.db and /resume replays content="" (the #43849/#44100
class resurfacing via the perf cursor). Invalidate the cursor at the
pop site so the filled row is re-examined.
2026-07-31 23:18:12 -07:00
Jeremy
a266155cc4 fix(cli): untrack sqlite connections only after close succeeds
A failed close left the FD open while the byte-probe guard thought
nothing was live. Keep the registry entry until close actually works.
2026-07-31 23:18:12 -07:00
Baophan00
05103c6bde test(config): add regression test for scalar model sub-key preservation
Verify that setting model.provider/model.api_key after a scalar model
assignment preserves the original model id as model.default.
2026-07-31 23:18:09 -07:00
Baophan00
3ba67fd7bd fix(config): preserve scalar model id when setting model sub-keys
When model is a bare scalar (e.g. 'model: gpt-4o'), running
'hermes config set model.provider openai' silently destroyed the
model id because _set_nested replaced the scalar with an empty dict
before writing the sub-key. Now the scalar is normalized to
{default: <id>} first, preserving the model id.
2026-07-31 23:18:09 -07:00
Brooklyn Nicholson
73b8847d7b fix(desktop): toggle every pane off the tree, not off its own boolean
The terminal fix was only one instance. An audit of the other pane toggles
found ⌘G and ⌘J diverging the same way, proven with a probe: with review
stacked behind files in the right column, or either pane inside a minimized
zone, the store reads open while nothing is on screen, so the press
re-asserts a value it already held and the key does nothing.

isPaneVisible / togglePaneVisible replace the tool-panel-only pair and now
back every toggle. Close still routes through closeTreePane, so each pane
keeps its own semantics: a tool panel collapses to its rail, files and
review close through their store, anything else is dismissed.

files and review were bound with a closer and no opener, so the boolean went
stale as soon as anything but the toggle revealed them. bindPaneVisibility
moves into the tree store beside bindToolPaneCollapse, documents the two as a
pair, and both panes now pass both halves. Keeping the binding in the store
also means the tests drive the real function — the earlier copy in the test
file passed with the fix reverted, which is how the missing opener survived
the first pass.

setTreePaneHidden keeps its quiet path: a reactive unhide (a cwd arriving)
must not front or un-minimize over what the user is looking at. Only user
intent goes through the reveal path.
2026-08-01 01:17:45 -05:00
Brooklyn Nicholson
40ec9834b2 fix(tui): keep slash completion alive after a leading command
Typing a second slash command went dead whenever the message started with
one: `/work /cle` offered nothing while `do /work then /cle` completed
fine, which reads as an intermittent glitch rather than a rule.

Only the first slash can be an invocation, so detect the inline shape
first. The leading-command branch claimed the whole line and handed it to
the backend's completer, which has nothing to say about a slash sitting in
a command's argument tail. The inline trigger requires a whitespace-preceded
slash at the caret, so ordinary argument completion (`/cron ad`,
`/personality alic`) is untouched — it fires only where completion was
already dead.
2026-08-01 01:17:41 -05:00
Brooklyn Nicholson
609cd28b17 feat(tui): rank the slash menu by the skills you actually use
The `/` menu was a flat first-30 slice of the completer's output, and the
completer emits every registry command before the first skill. On a
230-skill install that meant a bare `/` filled all 30 rows with commands
and offered no skill at all, while `/p` cut off inside the alphabetical
skill block — dropping /proving-a-fix-works (471 invocations) and
/pr-update (160) but keeping /pretext (2).

Spend the limit per kind and rank the skill block by recorded usage
(the same .usage.json count Capabilities shows), most-used first and A-Z
within a tie. A bare `/` is browsing, so bundled skills that shipped with
Hermes and were never opened are dropped as noise; a typed query is a
search, and a search that hides a match is broken, so there nothing is
pruned and the ranking only reorders. An argument stage keeps the order
its own command chose.
2026-08-01 01:17:41 -05:00
Teknium
6989a79745 chore: contributor email mappings (rkfshakti, x7peeps) 2026-07-31 23:16:58 -07:00
Teknium
3b9cf56aff fix(agent): exclude reasoning_details envelope from tail-budget walk (#73298)
Companion to the preflight fix: _estimate_msg_budget_tokens charged
reasoning_details at chars/4 via _REPLAY_BUDGET_KEYS, so the signed/base64
envelope (measured 72% of the reasoning mass on Anthropic-wire sessions)
consumed the tail budget and _find_tail_cut_by_tokens summarized away real
transcript to make room for tokens that are never sent (69 messages on the
measured session; up to ~4.8x budget inflation on thinking-heavy histories).

Per the #51800 counter-argument, actual thinking TEXT stays visible to the
budget: _reasoning_details_text_chars counts thinking/text/summary fields
and skips signature/data/encrypted blobs, and the text is skipped entirely
when reasoning/reasoning_content already carries the identical prose (so it
is charged once, not twice). codex_reasoning_items remains fully charged —
Codex Responses genuinely replays it every request (#55572).

Sabotage-verified: restoring reasoning_details to _REPLAY_BUDGET_KEYS fails
the new envelope and double-charge tests.
2026-07-31 23:16:58 -07:00