Commit Graph

505 Commits

Author SHA1 Message Date
Teknium
e612fbedc6 fix(cache): profile ceiling is keyword-only; tolerate agent stubs without base_url
CI: a new positional ProviderProfile field shifts plugin subclasses' positional slots, and
the redecoration path is driven by stub agents that carry no base_url.
2026-11-15 12:04:54 -08:00
Teknium
4a89bc6c02 feat(cache): one prompt-cache clock per session; Nous 5m ceiling as data
Every consumer that needs "when does this session's cached prompt expire?" now reads one
answer, agent/prompt_cache_clock.py:cache_window(), instead of re-deriving it from _cache_ttl.

- Per successful attempt the clock records the tier actually on the wire (cache_control ttl,
  prompt_cache_options.ttl, prompt_cache_retention, read from the sent payload), the send time,
  and the tier the response proved: Anthropic cache_creation.ephemeral_5m/1h_input_tokens,
  OpenAI Responses cache_write_tokens_details.ttl_30m/12h_tokens. normalize_usage keeps that
  split as CanonicalUsage.cache_write_by_ttl instead of dropping it.
- Per-route rules are a dict of small handlers: native Anthropic proves via the split;
  OpenRouter Claude is declared (live-probed to honour 1h); routes with a ceiling are clamped;
  other Anthropic-wire gateways assume 5m; OpenAI GPT-5.6+ proves via ttl_30m/12h or declares
  the documented 30m minimum; pre-5.6 assumes ~30m (5m on in_memory); implicit caches are
  unknown. expires = latest read-or-write send time + the written tier. A route switch,
  fallback, session rotation or compaction makes it unknown.
- Route TTL ceiling is data: ProviderProfile.prompt_cache_max_ttl (Nous ships "5m", because
  the Portal's upstream drops 1h after ~7 min and bills 5m), overridden per provider by config
  prompt_caching.route_ttl_ceilings. effective_cache_ttl uses the same helper, so Hermes stops
  asking Nous for 1h. A custom endpoint at the Portal host gets the Nous ceiling.
- Persisted as nullable sessions.prompt_cache_clock (JSON) through the existing token batch;
  restored lazily on resume, falling back to the newest assistant row (assumed).
- Codex app-server: read cacheWriteInputTokens instead of hard-coding cache_write_tokens=0.
- /context shows "Prompt cache: warm until HH:MM (…; 1h, proven)", "expired … ago" or
  "unknown (…)". The surface is absorbed from #142387 (render/duration helpers, the
  SessionContextBreakdownResult.prompt_cache contract and translations), reworked onto the clock.

Co-authored-by: Teknium <127238744+teknium1@users.noreply.github.com>
2026-11-15 12:04:54 -08:00
yoniebans
0566a81101 docs(fallback): say when the held transform does not see the primary's sign-in lead
After a truncated partial the transform already ran on the partial and settle_held_final returns early, so the comment overstated the guarantee. The same bypass reaches main's backup error body; making settle_held_final cover text added after the recorded transform is a separate fix.

Reported-by: BearHuddleston
2026-11-15 01:58:38 +01:00
yoniebans
9bb39e8f01 fix(fallback): lead a failed turn with the primary's sign-in before the held transform runs
A hold_stream plugin must see the whole reply before it leaves the agent. The lead was added after settle_held_final, so its text, including the primary's own error, skipped the plugin's rewrite. It now joins the reply first.

Reported-by: greptile-apps[bot]
2026-11-15 01:58:38 +01:00
Jim Jones
2baaeeba9d fix(fallback): surface the primary provider's expired login when the backup fails
Darling, "you're out of credits" is not the whole story when the real
problem is that your Claude login expired an hour ago. Resolution-time
fallback quietly swapped the dead Anthropic login for the backup and then
let the backup's billing error do all the talking.

- resolve_runtime_with_fallback stamps a PrimaryAuthFailure (provider,
  error, exact re-login command) on the fallback runtime when the primary's
  AuthError is one a re-login fixes (not quota/entitlement/retryable).
- The gateway (messaging + launch-policy routes), API server and oneshot
  carry it onto the agent; the gateway clears it per turn so a cached
  agent never keeps a login failure that has since resolved.
- run_conversation leads any failed turn on the backup with "<primary>
  needs you to sign in again: run `hermes auth add anthropic`" and still
  names the backup's problem ("the backup is out of credits"), with the
  backup's own copy underneath.

Fixes #147212
2026-11-15 01:58:38 +01:00
Maciej Lisiewski
c6f6de65b4 fix(memory): fence echoed memory-context out of completed replies
A model can echo the fenced <memory-context> recall block it was given.
Streamed deltas pass StreamingContextScrubber, but a non-streamed reply left
run_conversation raw in final_response, and adapters that never stream (the
email gateway) mailed it, memory notes and tokens included, to the sender.
Interim commentary had the same gap.

Apply the streaming scrubber's grammar once to final_response at the
run_conversation exit and to interim/commentary text. It drops only
block-shaped spans, so prose mentioning the tag inline survives (the reason
the old regex scrub was removed from these paths in 4a9ac5c355). The
persisted transcript row is unchanged; reloads already sanitize it.

Fixes #81312
2026-11-12 23:25:28 +01:00
Teknium
10cee93ada fix(prompt-cache): join only the planner's own three-part system split
Review findings from kshitijk4poor on 494ddcb:

- The failover stripper joined any plain three-part system message. A context
  engine's own three parts would then reach a cache-off destination with their
  boundaries removed. The planner marks part 0 in every split it produces, so
  three parts are joined only when part 0 carried a marker (two-part handling is
  unchanged from main).
- Pin the blank-session-rest guard with a test: a whitespace-only text block is
  rejected by Anthropic.
- Direct attribute access for _cached_system_prompt, as the surrounding code asks.
2026-11-11 18:30:54 -08:00
Teknium
3f05542b8b perf(prompt-cache): put the second system breakpoint before the ephemeral tail
A subagent's per-task text (and a personality) is appended to the session's
system prompt at API time, and the second system breakpoint sat after it. Every
child whose task text differed therefore re-wrote the skills index and footer
to the cache on its first call, although those bytes are identical for all of
them.

The breakpoint now sits at the end of the session prompt. The tail keeps a
breakpoint of its own on calls that have one to spare (a first call has a
single message to mark), so sessions with an identical tail still share it. A
session with no ephemeral tail is planned exactly as before, and the bytes on
the wire do not change for anyone.

Envelope layout and the native layout without a tool breakpoint; the
direct-Anthropic tool-cache layout is unchanged.
2026-11-11 18:30:54 -08:00
Teknium
5864341f2d fix(agent): hand a refused turn the clean pre-turn history, not the compaction-poisoned baseline
Greptile #149708 P1 4486245731.

After an in-place compaction this turn, the loop's conversation_history flush baseline is
rewritten to list(messages) — the whole working set including the refused request + tool
rounds. Returning that as result["messages"] re-poisoned CLI/TUI/ACP in-memory history, so
the next prompt re-tripped the deterministic safety filter even after the durable transcript
was cleaned. Both refusal paths (handle_content_policy_refusal and the exception-path
nonretryable_client_error_result) now rebuild the clean history from the real turn boundary
(history_before_current_turn via current_turn_user_idx) and carry the refused run's durable
boundary row (refused_turn_boundary_row_id) for the owner to drop the exact turn.
2026-11-05 22:23:44 -08:00
Teknium
ab3afc0b89 feat: erase a safety-refused turn across every surface, both refusal shapes
Teknium's directive: erase the whole chat history from the refused user message
onward (user row + any tool rounds + the refusal) out of the model's conversation,
while the user keeps SEEING their message in the chat. Extends the Bot-Chat-only fix
to the two gaps the review found:

- Exception-shaped refusals (M1): a refusal that arrives as an HTTP 400 / APIError
  (not an HTTP-200 finish_reason) now returns the pre-refusal history and skips
  persistence, exactly like the HTTP-200 handler. Previously it persisted and
  returned the refused request, re-poisoning the next prompt on CLI/ACP.

- Durable erase on CLI and ACP (finding #3): those surfaces own a direct SessionDB,
  so the agent flushed the refused turn before the refusal was known. Each owner now
  erases it owner-side after the turn (new hermes_state_rewind.erase_refused_turn_
  from_transcript — placed outside the agent core so the worker-store parity scan
  doesn't demand it of RuntimeSessionStore). ACP gates on the owning agent, since a
  non-owning agent's replace_messages already wrote the clean history. Without this a
  /resume or a fresh ACP session load restored the refused request and re-locked.

Per Teknium's ruling the WHOLE turn is erased, tool rounds included (overrides the
review's "keep tool evidence" note) — corrects the stale "ran no tool" comment.

Tests (red on base): the rewind erase primitive; ACP durable-erase + reload; ACP
exception-shaped refusal recovery.
2026-11-05 22:23:44 -08:00
Teknium
a07afee37c fix(agent): exclude content_policy_blocked from the failed-turn closer
A content-policy-refused turn is dropped whole (gateway soft-deletes it owner-side;
in-memory surfaces return the pre-refusal history), so _close_durable_failed_turn
should not write a closing boundary for it — the boundary would only be written to be
rewound, and it leaked a stray assistant row into the in-memory result["messages"].
A refused turn ran no tool, so it has no side effect for the #107070 open-tail replay
to carry. Mirrors the context_overflow exclusion. (Review finding P2.)
2026-11-05 22:23:44 -08:00
Teknium
ad9229c843 feat(hooks): pre_llm_call can block a turn before any inference request
A pre_llm_call callback (Python plugin or shell hook) may now return
{"action": "block", "message": "..."} to veto the turn: no model call is made,
the message is the reply the user sees and the transcript keeps a normal
user -> assistant pair, and the result carries
turn_exit_reason=blocked_by_plugin_pre_llm_call. This is the supported seam for
DLP / privacy / policy plugins that previously had to patch core (#57364).

The vetoed prompt also stays on the host for that turn: no session titling call,
no external-memory prefetch or sync, no background memory review. Its user row
gets an api_content placeholder for the main-loop replay. That alone does not
keep the prompt out of later turns (compaction, session_search and memory
providers read the row's content); the next commit stores the placeholder as
the content.

First valid block wins; a Python block without a message is ignored (same as
pre_tool_call). Shell hooks accept both the Hermes {"action": "block"} and the
{"decision": "block", "reason": ...} shapes, mirroring pre_tool_call.
2026-10-31 22:59:20 -07:00
Victor Kyriazakos
47ec37e427 fix(sessions): a Bot Chat capability rebuild also satisfies a pending prompt refresh
The Bot Chat capability-refresh branch rebuilt and persisted the prompt
without recording the refresh epoch, so a pending `refresh-prompts`
request rebuilt the prompt a second time on the next turn, and a warm
agent restored through that branch never adopted a later request.

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

Tests: a Bot Chat rebuild with a request pending is the only rebuild,
a warm agent rebuilt through Bot Chat adopts a later request, a warm
agent that restored its prompt from the row adopts a later request, and
a warm agent with no request never rebuilds across turns.
2026-10-28 19:30:48 -07:00
Victor Kyriazakos
e240d617e8 feat(sessions): refresh-prompts lets continuing sessions adopt updated prompt sources
A continuing session replays its stored system prompt verbatim on every turn
so the provider prefix cache stays warm. The gateway restores that prompt from
the session row on each fresh agent, and warm cached agents keep it in memory,
so SOUL.md edits, new or edited skills and project-context changes never
reach a long-running conversation until /new, which also drops the history.
Operators who push profile updates and restart the gateway had no way to make
existing conversations pick them up.

`hermes sessions refresh-prompts [--session ID] [--json]` records a refresh
epoch in the profile's state.db (state_meta, one counter orders profile-wide
and per-session requests). At the start of a continuing session's next turn,
_restore_or_build_system_prompt compares that epoch with the one stamped in
the session's model_config when its prompt was built. When the stored prompt
is older it follows the Bot Chat capability-refresh precedent in the same
function: tools[] pin restored first, skills prompt cache and snapshot
cleared, prompt rebuilt through _build_system_prompt (memory reloaded and
plugin sections re-rendered, as at a compaction boundary), cache break
recorded, on_session_start not fired, new bytes and epoch persisted so the
following turns restore them verbatim. One cache break per request.

Warm agents (gateway agent cache, TUI/Desktop) run the same check from
build_turn_context against the epoch they saw when their prompt was set, so
the verb works with the gateway running. A session first built after a
request is stamped with it and does not rebuild again.

With no request recorded, the stored prompt is reused byte-identically. The
only added work per continuing turn is one state_meta point read. No file
scanning, no config key, no watcher, no mid-turn mutation.

The tools[] pin is kept on purpose: the refresh is about instructions, and
tool changes already reach long sessions at the compaction boundary. The
cache break is recorded as the existing system_prompt_rebuild cause rather
than a new one, which would change the shared-metrics contract and schemas.

Related: #141154 (per-turn source hashing, alternative design), #74622.
2026-10-28 19:30:48 -07:00
Teknium
a4a992645b refactor(providers): one memoized endpoint->profile lookup; drop duplicated api_mode helpers
- providers.profile_for_host is the single host->profile lookup (declared hostnames, exact or
  subdomain), memoized per (hermes_home_key, host, metadata) and invalidated by a registry
  generation counter bumped on every registration (process-wide or per-home layer).
- agent/provider_route_hooks.route_profiles = named profile, then profile_for_host(base_url);
  replaces L1's every-profile scan, L2's conversation_loop._credential_refresh_profile host scan
  and L3's agent/endpoint_profile.py + ProviderProfile.serves_endpoint (deleted).
- Copilot hostnames gain models.github.ai (the L3 Responses/reasoning gate host); per-site
  differences (carriers, editor headers, initiator) stay in the plugin hooks keyed on base_url.
- Pure per-request hooks (request_headers, max_tokens_param) are memoized per argument set so a
  plugins.isolation: host proxy pays one IPC call per request shape.
- hermes_cli/models.py: delete _should_use_copilot_responses_api / copilot_model_api_mode;
  runtime_provider routes per-model providers through api_mode_for_model generically.
- credential_refresh_notice seam restores main's Copilot refresh status lines.
- auth._env_key_auto_detected: ambient-credential check reads list_providers once instead of a
  per-pid get_provider_profile miss that walked the provider ladder (welcome_trial regression).
2026-10-25 19:00:01 -07:00
Teknium
2e30ce41c9 refactor(copilot): move credential logic behind generic ProviderProfile seams
GitHub->Copilot token exchange (hermes_cli/copilot_auth.py) moves into the
in-tree copilot plugin (plugins/model-providers/copilot/credentials.py), and
core's Copilot credential branches become generic profile hooks the plugin
fills: resolve_api_key_secret, runtime_base_url, prepare_pool_entry,
seed_pool_credentials, remove_credential_source, refresh_runtime_credentials,
is_stale_credential_error, request_rejection_hint, external_auth_evidence and
the ambient_credentials field. Behaviour-preserving (gh auth token fallback kept).
2026-10-25 18:04:13 -07:00
Teknium
e2ec5e7060 fix(hold-stream): every exit of a held turn runs its transform snapshot
A held turn (hold_stream=True transform_llm_output) only ran the transform
on the paths that reach finish_text_response / finalize_turn. Other exits
returned model text the plugin never saw:

- A reply that hit finish_reason="length" on every continuation: the
  ceiling exit (_continue_text -> _Trunc.end_turn) stitched the raw
  fragments into the final and the stored row and returned without
  finalize_turn. collapse_continuation_trail now runs the turn's held
  transform snapshot on the stitched text before it appends the row, so
  the user and the stored row get the rewrite (or the withheld notice if
  the transform fails). The same seam covers a provider error that ends
  the turn after a capped fragment (settle_delivered_partial prepends that
  fragment to the error copy).
- The iteration-budget summary appends its own assistant row; finalize
  transformed the returned text but the row kept the raw summary, so
  history showed it. A recovery tail row that still holds the untouched
  text now stores the rewrite before its first flush
  (_store_rewrite_on_tail, the #44239 contract).
- Every remaining exit (non-retryable / exhausted provider errors,
  interrupts, compression and overflow failures, invalid-response caps,
  preflight timeouts, ...) returns through run_conversation, which now
  calls settle_held_final: a held turn whose final_response no seam
  transformed runs the snapshot there, so no path hands the user text the
  plugin did not see first. The hold snapshot is taken before
  build_turn_context, so an early exit never reads the previous turn's
  hold.

Tests (tests/agent/test_hold_stream_exits.py, real AIAgent + SessionDB on
the loopback model, red on 3a5b54d980): four capped responses, a capped
fragment then a 400, the budget summary, and a 400 with a tagging plugin.

Review: https://github.com/NousResearch/hermes-agent/pull/144266#discussion_r4370678627
2026-10-25 06:18:48 -07:00
Teknium
6030e77121 fix(hold-stream): no side path delivers a held turn's original text
Independent review of the hold_stream feature found four paths that still
let the untransformed reply or commentary reach the user:

- History loads showed held commentary. The tool-call assistant row of a
  held turn is now typed display_kind="hidden" before its first flush
  (withhold_held_commentary), so TUI/Desktop display_projection, the
  dashboard and classic CLI resume skip it. display_kind never reaches the
  wire: the model's context and cached prefix are unchanged (test replays
  the resumed session and compares the request bytes). The TUI projection
  still labels the hidden row's tool cards from its calls. Codex held turns
  type their earlier agentMessages hidden the same way.
- A plugin reload mid-turn could empty the hook registry before the final
  transform. The held turn now snapshots its transform_llm_output callbacks
  together with the hold decision under the discovery lock
  (held_stream_transforms) and runs that snapshot at the final. If no
  callback rewrote and one raised or timed out, the user gets a fixed
  "reply withheld" notice instead of the original (fail closed).
- Classic CLI replay-gap recovery painted and spoke pre_transform_response.
  A held turn's result (generic and codex) no longer carries the original
  at all (public_pre_transform), so receipts, recovery and post-stream
  suffix painting only ever see the rewrite.
- Codex error-after-text returned the raw agentMessage. The codex reply is
  now transformed whenever it has text, also when the turn errored (and,
  when held, when interrupted).

Same class, also fixed: the end-of-stream scrubber flush recorded a held
tail as streamed text (an interrupted turn could return it as an
untransformed partial final), and quiet-mode CLI printed held commentary
via _vprint.
2026-10-25 06:18:48 -07:00
Teknium
53b086aee8 fix(codex): run transform_llm_output on codex app-server replies
The codex app-server runtime returns before finalize_turn, so
transform_llm_output never ran there (pre-existing): a rewriting
plugin's change never reached the user or the stored assistant row,
and with hold_stream the user waited only to get the raw reply.
Apply the transform before the projected rows are persisted and return
response_transformed / pre_transform_response like the generic loop.

Review: https://github.com/NousResearch/hermes-agent/pull/144266#discussion_r4369515509
2026-10-25 06:18:48 -07:00
Teknium
83b4128032 feat: hold a held session's reply until transform_llm_output rewrites it
When a plugin loaded in the session's profile registered transform_llm_output
with hold_stream=True, the reply is not streamed on any surface:

- agent: no text delta, post-tool-call text or interim commentary leaves the
  agent's display/TTS callbacks for the turn (resolved per turn), so messaging,
  local viewers (TUI, Desktop, classic CLI, ACP), the API server and managed
  workers all fall through to their existing "nothing streamed" path and
  deliver the rewritten final once.
- gateway: TurnRunner builds no stream consumer for a held turn, so no draft,
  edit, native stream frame (WeCom's empty seed + closing frame) or commentary
  bubble is sent; the final is one plain send (split like any long reply) while
  the typing indicator runs.

Commentary is model text the hook never sees, so a held turn drops it; tool
progress and reasoning keep their own display settings.
2026-10-25 06:18:48 -07:00
Teknium
e3fff39ec7 fix(usage-window): name the allowance that stopped this model
Greptile: "Regular models get monthly resets". A full Large-model allowance
won the limit line, retry time and pool bench even when the refused model
is not top tier and its daily allowance is also full, so the line said
"monthly large-model limit · resets in 30 days" while limit_hit (the card)
said "daily". The stop line, window_stop_resets_at_ms and the pool's
reset_at now take the gauge from plan_limits.blocking_gauge with the
model's top-tier mark, the same rule limit_hit reads; a refusal no
all-scope allowance explains still falls back to the top-tier one.
2026-10-22 13:50:10 -07:00
Teknium
c00f999ba4 Merge origin/main into window-plans
Resolves the desktop i18n conflicts: main moved en/ru errorCodes into
en_error_codes.ts / ru_error_codes.ts, so usage_window moves there; ar/ja/zh/
zh-hant keep both usage_window and main's workspace_unavailable. _keys.desktop.json
regenerated.
2026-10-22 12:53:41 -07:00
alt-glitch
c13d6885a1 fix: a failed onboarding turn shows the beat answer once
After an onboarding turn failed, a transcript refresh painted the user's
beat answer twice: once from storage and once in the kept local error
bubble, which still held the setup_beat tool part.

Desktop: a stored assistant sharing a tool call with the local error
bubble is that bubble's stored copy, so the error folds onto it instead of
re-appending the bubble (the hidden opening row left no visible turn to
anchor the existing match on). Hydration no longer merges a failed-turn
boundary row into the tool-call reply it follows, so its error card
survives and its notice is not painted as model text.

Backend: both failed-turn closers (agent/conversation_loop.py and
gateway/run_turn_persistence.py) also close a durable tail that is a tool
row, so a reload carries the error card. OPEN_TURN_TAIL_ROLES in
agent/turn_failure_copy.py names the open tails once for both.
2026-10-22 14:47:33 +05:30
rob-maron
0e29e8a25a fix tests 2026-10-20 22:18:49 -04:00
rob-maron
15307dece7 Usage-window plan support 2026-10-20 21:04:30 -04:00
Teknium
5f95fac626 fix(tool_search): drop the managed-worker delegation diagnostic now that workers delegate
there and to use kanban_create instead. With owner-reserved children that
is false, so the 'delegation' entry and its helper go: a turn whose
toolsets leave delegation off now gets the generic 'not available in this
execution context' answer, in a worker or not, and a turn that has
delegate_task keeps the ordinary 'call it directly' guidance.

Part of #141793
2026-10-20 03:22:11 -07:00
Teknium
f62ad7f676 fix(kanban): a managed worker explains why delegate_task is absent
Every Kanban card runs in a managed worker, and the worker subtracts the
delegation toolset on purpose (ef52a09a55, review r4230769955): a child
needs its own owner-registered execution that a single-turn worker cannot
reserve, and _open_child_session_db refuses with
worker_child_registration_required. Asking for delegate_task anyway got
"call it directly" from tool_call, the same from tool_describe (which never
passed the session's names), or a bare "does not exist" from a direct call,
so the model kept trying another door.

In a registered worker process all three now say the tool is not offered
in a managed worker turn, why, and the supported alternative: child cards
via kanban_create (parents=[<this task>]) or doing the subtask inline.
Outside a worker the wording is unchanged. The worker boundary itself is
untouched.

Part of #141793
2026-10-20 03:08:38 -07:00
Teknium
607a23e858 Merge origin/main (#30: 54 commits to 1744a19e0d) into feat/unified-gateway-runtime
8 conflicts, all from main's lint sweep (#135281 "Harder linter fixes" + the RUF series:
implicit-Optional, unused-unpacked-variable, next(...) for [...][0]). No other main commit touches
a conflicted file. Resolution: the branch side of each file plus main's exact autofix
(ruff 0.15.10, main's ruff.strict.toml, --fix --unsafe-fixes) on it. ruff.strict.toml takes main's
copy (the newly enabled rules). tests/cron/test_bot_chat_delivery_child_env.py stays deleted
(1cc9cb9199 retired its lane).
2026-10-08 21:38:54 -07:00
Maciej Lisiewski
4278b6aa24 ci: RUF013, RUF015 2026-10-08 21:29:48 +02:00
Teknium
65bec86e37 Merge origin/main (#27: 19 commits to 517b5e10fe) into feat/unified-gateway-runtime
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
2026-10-08 12:09:24 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
b09c202d9e Merge origin/main (#21: 191 commits to e675225af2) into feat/unified-gateway-runtime
Brings #134209 onboarding (setup chat, /initiate-setup, setup_choose/start_chat cards) and
889eddcd86 (/yolo survives a gateway restart).

Conflicts (6):
- gateway/run_turn.py, tui_gateway/server.py: the branch moved these blocks into siblings;
  main's edits ported there (run_turn_prepare: first-contact `message`/setup_command, the
  _restore_session_yolo call after _hmwa_open_session; agent_factory: coding_selection
  session-platform toolsets, setup_choose/start_chat lifecycle tools; session_registry:
  _lazy_resume_info default route).
- tests/gateway/test_yolo_command.py: both tests kept.
- Desktop composer submit / slash / wiring: main's parked-card answering and submitWhileBusy
  with the branch's busy-input policy in its steer branch; slash `hidden` folds into the
  prepared-submission journal; wiring keeps main's onboarding chain without the removed pool.

Semantic fixes:
- gateway/session_busy_controls.yolo_config writes main's persisted SessionEntry.yolo before
  the live flag, so an owner `/yolo` OFF is not revived by _restore_session_yolo next turn
  (new test test_owner_yolo_off_is_not_revived_by_the_persisted_restore).
- wiring runKickoffSlash awaits the branch's Promise<boolean> slash dispatcher.
- de/es/fr/ja/zh-hant: translate the branch's composer keys main's overlay-completeness test
  now requires.
2026-10-07 17:09:40 -07:00
Teknium
b178d9098c Merge origin/main (#18: 76 commits to 3569fba6a6) into feat/unified-gateway-runtime
No conflicts. Overlapping auto-merges: agent/conversation_loop.py, agent/credential_pool.py,
cron/{executions,jobs,scheduler}.py, hermes_cli/{main,update_cmd}.py, Desktop i18n en/types,
locales/_keys.desktop.json, tests/fixtures/resolution_allowlist.json, cron docs.
2026-10-07 07:33:34 -07:00
alt-glitch
2c8df45ee5 Merge remote-tracking branch 'origin/main' into sid/onboarding
# Conflicts:
#	agent/conversation_loop.py
#	tui_gateway/prompt_turn.py
2026-10-07 19:29:35 +05:30
Teknium
ca38632fc0 Merge origin/main (#17: 454 commits to e6757f2029) into feat/unified-gateway-runtime
12 conflicted files, resolved in three lanes:
- gateway/run.py: take the branch split; main's tirith removal and spool-replay
  ordering ported into run_runtime_init.py / run_bootstrap.py.
- config migrations: main keeps v50 (tirith); the branch's bot-chat timeout removal
  becomes v51 (_config_version 51, template + test updated).
- hermes_state_usage.py: main's voice_chat task route threaded through the branch's
  owner transaction; worker.persist usage allowlist accepts task.
- tui_gateway/server.py: branch side; main's edits applied where the code now lives
  (agent_factory, session_registry). Desktop sessions get the catalog toolset on the
  authority path; daemon-run finite CLI turns are not watched turns; lazy session info
  reports nous/welcome on the free tier.
- Desktop/Ink: one branch-child spinner fix (main's route-token check); main's
  uninstall i18n keys kept, pool keys stay removed; voice_turn forwarded and accepted
  by the authority submit (surface_v1.voice_turn).
- chat_ws / PTY keepalive test: main's stricter test kept.
2026-10-07 06:48:09 -07:00
kshitijk4poor
70dcdd640f refactor(agent): hoist the hidden placeholder row import and say why a timeout carries no message
Gate rQ quality Lows: the placeholders module imports nothing, so conversation_loop can import it at module level like turn_api_call; the terminal-approval comment now says callers re-queue _interrupt_message, so a system stop must not set one.
2026-10-07 18:15:29 +05:30
kshitijk4poor
714fc8071c refactor(agent): share the hidden interrupt placeholder row
message_sanitization.close_interrupted_tool_sequence and the
turn_api_call repetition-loop exit each spelled the same hidden
assistant row literal (content "", display_kind hidden, api_content
_INTERRUPTED_PLACEHOLDER), and the conversation loop's redirect built it
field by field. Add hidden_interrupt_placeholder_row() to the leaf
placeholders module and use it at all three sites so the shape cannot
drift between them.

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

- _INTERRUPTED_PLACEHOLDER / _LEGACY_INTERRUPTED_PLACEHOLDER (and their
  rationale comment) move byte-identically into the leaf sibling
  agent/agent_runtime_helpers_placeholders.py. Every importer (runtime
  helpers via late import, conversation_loop, message_sanitization,
  turn_api_call, turn_iteration_prep and five test files) now reads the
  sibling; no shim is left in the facade. Nothing patches the old path.
- test_keyboard_interrupt_emits_cancelled_post_tool_hook moves unchanged
  into tests/agent/test_run_agent_interrupt_hook.py, reusing the facade's
  agent fixture.
2026-10-07 18:15:29 +05:30
Teknium
6cc1efd8f9 feat(voice): auxiliary.voice_chat routes spoken voice turns to their own model
Voice replies had to come from the session's main model, so a heavy model made every spoken
answer slow (#83894). A new auxiliary slot, voice_chat, picks the model for voice turns:

- CLI/TUI voice mode, the Desktop voice conversation (prompt.submit voice_turn) and messaging
  voice notes mark the turn; agent/voice_turn_route.py binds the route after the prompt, row and
  preflight compaction were settled against the main model and undoes it before memory sync and
  background review, so the next typed turn and the review run on the main model.
- A turn larger than the voice model's compression threshold stays on the main model with a
  one-time notice: switching to voice never compacts the conversation.
- Usage lands in session_model_usage under task voice_chat; it never rewrites the session's
  recorded model/route, so resume keeps the model the user picked.
- Slot appears in Desktop Settings -> Models, the dashboard, and `hermes model`; GPT-Live
  delegations keep using the session model.
2026-10-07 01:35:11 -07:00
alt-glitch
995bc1c0e7 feat(free-tier): offer sign-in after finished tasks, backing off
A free-tier user is offered sign-in 3 minutes after their first finished
task, whether or not they send another prompt. Later offers each need
another finished task after the previous one, come 3 minutes after that
task, and never sooner than 1h, 4h, then 24h after the previous offer, so
a user who keeps saying "Not now" hears it less often.

- hermes_cli/free_tier_offer.py: the policy. One install-wide record
  (<default root>/free_tier/sign_in_offer.json, file lock + atomic write);
  claim_offer() is compare-and-set so two windows never both show it.
  Nothing is due off the free tier.
- tui_gateway/free_tier_task_done.py: a "finished task" is a completed
  turn with a reply, on the free-tier agent, not a crash resume, and with
  no steer/redirect/interrupt/busy-typing while it ran. Called from
  prompt_turn after a complete turn, before message.complete goes out, so
  a status read prompted by that event already sees the record. Intervention is reported by the agent
  (result["user_intervened"], reset per turn) and marked on the session by
  the steer/redirect/interrupt RPCs and busy submits.
- Wire: free_tier.status gains nudge_due_in (seconds, 0 = now, absent when
  none is pending); new free_tier.claim_nudge -> {claimed}.
2026-10-07 12:26:42 +05:30
Teknium
d6b44a83c4 fix: Bot Chat tool refresh re-pins the frozen session policy's toolsets
10708bc117 rebuilds a stale Bot Chat's tools[] from tui_gateway's live-config
loaders. Under the session authority a local session's toolsets are frozen in
its LocalSessionPolicy, so that rebuild let a later `hermes tools` edit drift a
running gateway-owned session (and pulled tui_gateway.server into owner turns).
policy_scope now publishes the active policy; the refresh uses its toolsets and
keeps the live loaders only for standalone serve.

(cherry picked from commit 9bf4b067591ada729060d8ba9bb7bfee00f4072b)
2026-10-06 16:21:13 -07:00
alt-glitch
4d99e0a9fd onboarding: bring the Python side under the code-health ratchets
The setup_choose tool boundary and the two onboarding RPC handlers log their traceback before returning the error. The optional first-message note and the best-effort guest mint keep their quiet logs with a BLE001 waiver. The prelude decision and the codex app-server hand-off move out of _run_conversation_turn into helpers, and /initiate-setup's handler moves to methods_onboarding.py.
2026-10-07 04:01:05 +05:30
ethernet
4efdfb6d84 Merge remote-tracking branch 'origin/onboarding/next' into feat/store-guest-onboarding
# Conflicts:
#	apps/desktop/electron/window-focus-policy.ts
#	apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx
#	apps/desktop/src/lib/chat-messages/parts.ts
#	apps/desktop/src/plugins/hermes-bots/types.ts
#	apps/desktop/src/sdk/index.ts
#	hermes_cli/plugins_cmd_install.py
#	hermes_cli/profile_distribution.py
#	plugins/web/keyless_mcp.py
#	tui_gateway/methods_profiles.py
#	tui_gateway/server.py
#	website/docs/developer-guide/relay-shared-metrics.md
#	website/docs/user-guide/features/web-search.md
2026-10-03 17:41:14 -04:00
FroRaut
40aa83919e fix(agent): count restarts since the last response toward the redirect cap
The refunding-restart cap (#106108) counted every redirect for the whole
turn, so a normal interactive turn -- the user answering clarify cards or
sending follow-ups while the model works -- ended as
redirect_restart_limit_exceeded on the (api_max_retries + 1)th mid-turn
message, even though a response completed between each of them.

The cap exists for requests that are cancelled over and over with nothing
completing. Reset restart_count whenever a response reaches processing, so
back-to-back cancelled requests still hit the bound and release the turn
lease, while corrections separated by real progress no longer kill the turn.

Fixes #128000

(cherry picked from commit 3a286a2201ee055b2eb6904523934f60e5e1344c)
2026-10-02 00:50:20 +05:30
Brooklyn Nicholson
4e7403130e fix(agent): redact the failed-turn error card before it reaches the durable store
_failed_turn_display_metadata stored result["error"] and the error_surface
raw into the boundary row's display_metadata, which SessionDB persists
without redaction — a secret echoed by a provider or tool error reached the
'store' and 'export' sinks verbatim (test_secret_redaction_gateway
[tool_reads_env_file-store/export]). Force-redact every string in the
payload (nested dicts/lists included) at the producer, matching the
compressor's persistence boundary.
2026-10-01 03:27:39 -05:00
Adolan
86ef1afc40 fix(desktop): keep failed-turn error cards after a restart 2026-10-01 03:27:39 -05:00
Siddharth Balyan
fc6a0a1a39 P18a: the backend plays the desktop setup opening (hello, name, accent) as real setup_choose calls (#129346)
* feat(setup): the backend plays the desktop opening (hello, name, accent) as real setup_choose calls

A desktop /initiate-setup turn whose history has no setup_choose call now runs a
scripted prelude before its first model call: the intro text with the name card,
then a line with the name and the accent card. Each step goes through the unchanged
run_tool_round (row persisted before the tool runs, interim text and tool events
emitted, tool hooks fired); the same turn then continues with the model, whose first
words start at the apps card. No system prompt change, no user row added, no API call
counted. CLI, TUI and the messaging gateway keep the model-only opening.

Also: the first-contact note never fires in the marked setup profile, and a stored
[/initiate-setup] row projects as /initiate-setup instead of the whole skill body.

* fix(setup): a relaunch mid-opening replays only the unanswered cards, with one recovery owner

The desktop intro sends /initiate-setup again when a relaunch cut the opening off. The prelude
used to skip as soon as the history held any setup_choose call, so the model had to ask the rest
(after the name answer it skipped the accent card). Now the prelude plays only the opening cards
with no answer, and does not repeat a line already in the chat. It matches lines by text because
a resumed history keeps an unanswered card's row but drops its call.

The same relaunch also scheduled the desktop auto-continue of the cut-off turn. That continuation
raced the app's resend: the resend became a redirect, its row lost display_kind hidden (a visible
/initiate-setup bubble after reload) and a "resumed interrupted turn" row appeared. While the
setup intro is unseen the app owns recovery of that turn, so auto-continue clears its marker.

Docs: the setup offer line never fires in the setup profile; the desktop app asks the opening
questions itself.
2026-09-30 20:01:49 +05:30
Ritvik Gautam
6776a429b5 fix: use original gateway text for automatic session titles
Gateway turns reach the agent enriched with channel-bound skill payloads,
sender metadata and other model context, so the first user message the
titler saw could be thousands of characters of skill text ahead of the
actual question, and new sessions were named after the skill instead of
the request.

The gateway now captures the inbound event text before that enrichment and
passes it as a turn-local title_user_message through TurnContext, the turn
runner, AIAgent.run_conversation and the conversation prologue. Only the
titler reads it: the main model, persisted history and relay metadata still
receive the full enriched message. An explicit empty or whitespace override
suppresses titling for that turn, None keeps the existing model-facing
fallback (attachment-only turns, paste previews), and the override cannot
enable model titling for cron or subagent runs. The value is a per-call
argument, so a cached agent never reuses a previous turn's override.

Rebased onto current main: the gateway call keeps main's pinned channel
prompt for internal events, and the integration fixture's context-prompt
stub accepts main's internal= keyword.

Ritvik Gautam made this change with Doryani AI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:57:52 -05:00
kshitijk4poor
2be9fa5f9d refactor(sessions): simplify-code pass over the identity helpers
- without_persistence_fields() replaces the two hand-written strips (context-engine selection,
  token-estimate fingerprint).
- mint_uid() is the one uid minter; uid_list() the one uid-list normalizer (message_metadata's
  _absorbed_uids and the codec's _uid_list share it).
- _live_or_column() replaces four copies of 'live key first, column name second'; the absorbed
  list writer takes the dict, not a (live_key, column) pair its one caller always passed the same.
- _restore_row_identity() is the one stored-identity-onto-live-dict step, shared by restore and
  the row-addressed rewrite (transcript_repair had a hand copy). Restore skips the decoders for
  NULL columns (the common row).
- index_tool_call_uids() returns the variants it named, so the flush walk stops computing them
  twice; tool_call_uid_from_history drops guards its one caller can't trip.
- rewind returns the replacement dict (the insert already stamps _row_id and message_uid)
  instead of re-querying last_insert_rowid.
- _remember_absorbed_row's folded is required, so every call site states the witness rule.
- The backfill reads/deletes state_meta through _meta_row/_delete_meta; chat_completions strips
  MESSAGE_UID by constant.
No behaviour change.
2026-09-29 04:15:21 +05:30
kshitijk4poor
30050851f7 perf(sessions): pair tool-call uids in O(K) on flush and only when needed on restore
- The flush walk memoizes each assistant's named ids and uid index across one collect,
  so K parallel results no longer recompute K assistants' variants (O(K^2) -> O(K)).
- Restore indexes assistant maps lazily: only a result without a stored uid (an older
  build's) needs the index; rows this build wrote never pay for it. Same order, same
  shadowing. One decoder (_restore_identity_columns) for both restore paths.
- The token-estimate memo key skips persistence-only fields the estimate never reads.
- Context-engine selection strip: isdisjoint instead of per-key scans.
2026-09-29 04:15:21 +05:30