Commit Graph

493 Commits

Author SHA1 Message Date
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
Eva
c2e2150d78 fix(sessions): close the identity gaps the review found and prove the recovery paths
- Strip persistence-only fields from a select_context() selection: the request copy was stripped before
  the hook, but an engine handing back the conversation_messages clones put timestamp, _row_id and the
  new ids on the wire (pre-existing for the old fields).
- Every row carries a message_uid whoever wrote it: an AFTER INSERT trigger mints one for a row inserted
  without it (an older build writing into a v31 store); the one-time backfill is gated by its own
  state_meta marker so a store whose schema version cannot advance (no FTS5) never rescans.
- One merge-witness helper (record_absorbed_message) for every fold of a durable message: alternation
  repair's user and assistant merges, the compressor's in-flight restatement onto the carrier, the real
  user anchor folded into a scaffolding turn (the anchor's uid leads), micro-compaction's adjacent-user
  merge.
- tool_call_uids follows tool_calls: it is a payload column, so an assistant merge's unioned map is
  rewritten with the row instead of being overwritten by the stale stored map on adoption.
- A result pairs with the nearest call naming its provider id: each assistant row's ids shadow earlier
  occurrences in the batch, restore and live-list indexes, a call row without a map leaves its result
  unpaired, and nothing pairs across a user turn.
- A composite rewind returns and installs the replacement row's uid on the live scaffold.
- Tests: import_foreign_history, hermes sessions recover and backup import carry the ids; the ACP
  restore test accounts for the uid on restored rows.

(cherry picked from commit b30636a49cb29fdd21ba4100eef9d810897338be)
2026-09-29 04:15:21 +05:30
teknium1
607dff390a feat(telemetry): v5 efficiency metrics — turn cost, wasted tokens, tool output truncation, tool overhead, prompt-cache breaks
Six opt-in, bucketed shared-metrics counters (schema + contract + docs in `v5 efficiency` blocks):

- hermes.task_cost.count {provider, model, tokens_bucket, tool_calls_bucket, api_calls_bucket,
  outcome}: one row per user turn the user saw end (pre_llm_call-started, attended; forks, delegated
  children and session-close aborts excluded). Tokens = prompt+completion over the turn's primary
  calls. Tool/API call buckets reach gte_101 (TURN_ACTIVITY_BUCKETS; COUNT_BUCKETS untouched).
- hermes.wasted_tokens.count {provider, model, reason in undo/retry/interrupt, tokens_bucket}:
  emitted from the v4 friction sites (no re-detection). /undo N counts N turns; an interrupted turn
  later undone counts once; turns this process never saw read unknown.
- hermes.tool_output_truncation.count {tool, truncated, original_size_bucket}: one row per tool
  result, judged after the per-turn budget; covers the per-result spill, the turn budget, and the
  shared head/tail notice tools write when they cut their own output (original size reported).
- hermes.tool_overhead.count {enabled_tool_count_bucket, tool_schema_tokens_bucket,
  execution_surface} + hermes.tool_enabled_unused.count {toolset (shipped TOOLSETS else custom),
  used}: once per closed interactive conversation (merged across compression lineage).
- hermes.cache_break.count {provider, model, cause}: compression (committed), model_switch /
  system_prompt_rebuild (continuing conversation rebuilt its prompt), toolset_change (tool array
  changed mid-conversation, Bot Chat capability rebuild), provider_reported_miss (cold read after a
  warm read on the same route with no Hermes-known cause), cache_expired (same after >=5 min idle).
  A Hermes-known break suppresses the miss it causes. No prompt hashing.

Live-proven against a fake OpenAI-compatible server (chat -q, --resume -m, TUI gateway JSON-RPC
undo/retry/interrupt); disabled => zero telemetry files.
2026-09-28 12:43:03 -07:00
Teknium
a5bd246865 Old pre-decomposition import paths are gone: plugin compat layer removed on schedule (#126164)
* refactor(plugins): remove the Sep 2026 decomposition compat layer on schedule

The PLUGIN-COMPAT layer (2776813df3 + d63e380324 + 0a5164cebe) kept pre-#102117 import paths
alive for external plugins until 2026-09-14. That window closed two weeks ago; since then the loader
has already been skipping plugins that use the old paths. This removes the layer itself:

- 328 appended `PLUGIN-COMPAT` blocks (lazy `__getattr__` pointer tables, re-exported third-party
  names, restored dead definitions) and the three re-export stub modules
  (gateway/startup_watchdog, hermes_cli/observability/relay_runtime, tools/environments/modal_utils)
- COMPAT_MANIFEST.md, compat_manifest.json, scripts/check_compat_pointers.py and its lint step
- the reporting surfaces: CLI banner notice, `hermes plugins compat`, the `hermes doctor` section,
  the post-update notice, the Desktop one-time dialog, the loader's pre-import skip and the
  `plugins.allow_deprecated_imports` escape hatch

An external plugin that still imports an old path now fails to load with its ImportError as the
reason in `hermes plugins list`, the same path as any broken plugin.

hermes_cli/plugin_compat.py stays as three inert stubs (compat_report, removal_in_effect,
summary_lines): an already-running pre-removal `hermes update` lazy-imports them after the checkout
swap (tests/compat/old_updater_surface.json).

In-tree fallout, both already dead: hermes_cli/setup.py::_check_espeak_ng (no callers; its
`shutil` came from a compat block) and gateway/config.py::SessionResetPolicy ("retained solely for
the scheduled plugin-compat window"). Two test_run_agent patches targeted the removed
`run_agent.handle_function_call` pointer; they now patch `model_tools.handle_function_call`, the
seam production reads, like every sibling test in that file.

* chore: retrigger CI (zero-job startup_failure phantom)

* test: drop resolution allowlist rows for the two deleted which() sites

hermes_cli/setup.py::_check_espeak_ng (dead) and tools/skillevaluator_scan.py::scanner_available
(a restored definition inside a PLUGIN-COMPAT block) no longer exist; the stale-row gate requires
their allowlist entries go with them.
2026-09-28 10:21:41 -07:00
teknium1
10708bc117 fix(bot-chat): rebuild a stale Bot Chat's tools through the surface builder (#124211, salvage #124307)
Trim the salvaged detector/delivery pair to the salvage bar and fix the
delivery half. The PR resolved the refresh selection as
platform_toolsets.<surface> (desktop/tui), a key no config path writes,
so _get_platform_tools fell back to the constructed hermes-<surface>
composite that resolves to 0 tools (a cold resume went 30 -> 1 tool).

Delivery now goes through the builder new desktop/TUI sessions use
(tui_gateway.server._load_enabled_toolsets(platform) +
_load_disabled_toolsets) as an explicit refresh_agent_mcp_tools
override, so the refreshed set equals a fresh session's on that surface;
only desktop/tui agents are long-lived, every other surface builds a
fresh agent per process/turn and is left alone. Drops the
toolsets.py/tui_gateway policy relocation and the raw-value fallback in
the fingerprint; keeps the detector (platform_toolsets +
agent.disabled_toolsets replace the dead tools.enabled_toolsets key)
and the tools re-pin after the refresh.

Tests: 2 invariants in tests/agent/test_bot_chat_toolset_refresh.py
(desktop -> builder consulted, disabled override passed, re-pinned;
cli -> untouched) and the existing fingerprint axis test now edits
the key `hermes tools enable/disable` writes.
2026-09-28 06:06:17 -07:00
finn763
fcda937c5d fix(bot-chat): deliver toolset changes to the canonical Bot Chat
The capability epoch watched tools.enabled_toolsets, a key no surface
writes; real hermes tools enable/disable edits (platform_toolsets.* plus
agent.disabled_toolsets) never flipped it. Even when stale, the refresh
rebuilt only the prompt and never tools[]. Watch the real keys and
rebuild + re-pin the tool snapshot on Bot Chat capability refresh.
Closes #124211
2026-09-28 06:06:17 -07:00
kshitijk4poor
a4db03cee9 fix(prompt): stored Model/Provider line with an empty live value is a stale route
Route commits no longer NULL the stored prompt, so _stored_prompt_matches_runtime is the
only rebuild trigger. A model-only request that clears agent.provider skipped the compare
and replayed the previous route's prompt verbatim. The builder omits empty trailer lines,
so the rebuilt prompt matches from the next turn (no rebuild loop); prompts without
identity lines keep reusing.
2026-09-27 02:22:23 +05:30
Richard McKinney
f762b96bfd fix(agent): keep prompt-cache redecoration returns consistent
_redecorate_prompt_cache_for_provider returned a 2-tuple when
tools_for_api was None but a 3-tuple otherwise, while its only production
caller (agent/turn_api_request.py) always unpacks three values. Passing
None raised "not enough values to unpack (expected 3, got 2)". The path is
latent today (agent.tools is always a list), but the union return type
invited exactly this mismatch.

Always return (messages, prepared, planned_tools); planned_tools falls
back to agent.tools when tools_for_api is None, as it already did
internally. Update the two tests that unpacked two values and add one
parametrized invariant over None / [] / list x cache-off / native.

Salvaged from #122441, rebuilt on current main with only the redecorate
hunks: the original commit was made on a stale conversation_loop.py and
would have reverted the continuation-overlap dedupe, the legacy
length-continuation stub, the tools-available stub wording and the Bot
Chat NULL guard.
2026-09-27 00:33:45 +05:30
kshitijk4poor
b7f91258b9 fix(agent): tools-available note on dropped-tools continuation; keep legacy stub recognized (#74990)
The dropped-tools partial-stream continuation now also states the cut was a
transport interruption and tools remain available. The pre-rewording
network-stub text stays in the compressor's synthetic-turn set so
crash-persisted nudges from older sessions are not mistaken for user turns.
2026-09-24 22:27:18 +05:30
Ugo Enyioha
eaf0fd95cb fix(agent): re-assert tool availability on partial-stream continuation
Re-port of 6f01f7476b (PR #72273) onto the _LENGTH_CONTINUATION_NETWORK_STUB
constant that _get_continuation_prompt now returns: state the cut was a
transport interruption, that tools remain available, and drop 'Finish the
answer directly' which read as a text-only instruction.
2026-09-24 22:27:18 +05:30
kshitijk4poor
6979cb9bab refactor(gateway): apply shutdown-notice interim marker once in _send_notice_logged
Also type continuation parts as (text, is_stub) tuples end-to-end and bound
the overlap scan to the tail of the joined text.
2026-09-24 22:26:11 +05:30
fangliquanflq
d98deef030 fix(agent): scope continuation dedupe to stream stubs
(cherry picked from commit 82acba16e08cce9f613598325d7c566838fb002e)
2026-09-24 22:26:11 +05:30
fangliquanflq
3814aab269 fix(agent): dedupe repeated stream continuation tails
(cherry picked from commit 87c93960cd9e8dd502ffe82a10febdefa3cf64c4)
2026-09-24 22:26:11 +05:30