Commit Graph

1449 Commits

Author SHA1 Message Date
Victor Kyriazakos
fa2befeed7 fix(gateway): join delegations in the turn when interim messages are off
On a messaging chat with display.interim_assistant_messages off, a top-level
delegate_task still produced two messages: a "checks are running, I don't have
the findings yet" reply and, later, the real answer. Top-level model
delegations always run in the background (ea8a8b4af8), and the tool text tells
the model to "give a one-line status and END YOUR TURN" (c89f3b8800). That
status is the turn's final answer, not interim text, so no display setting
held it back.

New key delegation.gateway_mode: auto | inline | background (alias async).
auto (default) joins the children inside the turn on a messaging chat whose
resolved interim setting is off (global, display.platforms.<p> override or
platform default). The parent waits in the tool call, gets the results there
and sends one answer. API, local and webhook surfaces keep the background
path under auto. Chats with interim messages on are unchanged: same schema
bytes, same async dispatch.

How it works:
- The gateway resolves the mode from the turn's own profile-scoped config
  when it builds a session's agent (gateway/session_execution.py), and the
  agent's first tool build freezes it (like the one-shot pin).
- An inline session carries the joined delegate_task variant the one-shot
  path already uses: "results return in this tool call", no live-control
  parameters, no END YOUR TURN.
- Dispatch follows the delegate_task schema the session carries
  (session_joins_delegation), so schema and behaviour cannot disagree. The
  schema rides the session's tools[] pin: a config change applies from the
  next session (/new), as delegation.backend does, and a cache eviction or
  restart never flips a running chat.
- Inline children run on the existing synchronous path: attached to the
  parent, so /stop and an interrupting follow-up stop them; the per-child
  heartbeat keeps the parent's activity fresh for the inactivity watchdog;
  the async completion registry is not used. Nested and one-shot delegation
  are unchanged.

Refs #95522.
2026-10-28 19:35:16 -07:00
Teknium
fbb1b417e2 fix(providers): one guarded api_mode_for_model for resolution, /model and resume
Runtime resolution caught a raising api_mode_for_model hook and kept the
profile's declared api_mode, but /model (model_derived_api_mode, also the
resume re-derivation in the TUI, CLI and gateway), the stale
codex_responses check in resolution, the agent's Responses routing check
and the auxiliary client asked the same hook unguarded: a model could
resolve and then fail building the switch result.

agent.provider_route_hooks.model_api_mode is now the one call: a raise
answers the profile's declared api_mode, logged with its traceback once per
provider. A None answer keeps each caller's existing meaning.
2026-10-26 01:34:59 -07:00
Teknium
1c4cbb2222 Merge remote-tracking branch 'origin/main' into copilot-seams/integration 2026-10-26 00:40:32 -07:00
Teknium
857e29d4cc fix(agent): provider hook failures are per session and reported per agent
A failed per-request profile hook stays on the generic answer for the agent's session so request
bytes never flip, but the failure memory survived /new and /resume (reset_session_state reuses the
agent), and the warning was logged once per process, so in a multiplex process every later home's
agent degraded silently. The memory is now cleared at a session boundary and a scoped (agent)
failure is logged once per session; scopeless one-shot callers keep the once-per-process warning.
2026-10-26 00:32:20 -07:00
Teknium
70d31a5a5d fix(agent): only the first attempt of a user turn carries user attribution (billing parity)
53a51a49cc made every attempt of a user turn's first API call (429/5xx retries, fallback
activations) re-send the provider's user_initiated request headers. Hermes has always sent them
on the first attempt only (retries went out with the route's default), and that difference is
billing-visible (premium-request initiator headers), so it is reverted: the first payload built
in a user turn consumes the flag and is the only user-initiated one.

Kept from 53a51a49cc: the flag is consumed exactly once whatever the route answers, so a route
without attribution or a failing request_headers hook never leaves it set for a tool-loop
follow-up.
2026-10-26 00:32:11 -07:00
Teknium
77af0690a8 fix(compression): one-shot runs start no wasted pass; releasing an agent cancels its pass
The live matrix on real processes found two ways a prepared-compaction pass was paid for and never
usable:

- `hermes chat -q` / `-z` runs end with their turn (the gateway evicts the agent right after the
  reply), so a turn-end pass there was always cancelled ~0.5 s later. One-shot sessions now join
  cron runs and delegated children in skipping turn-end passes.
- Releasing an agent without a session boundary (gateway cache eviction, a Desktop rewind,
  managed-worker retire, close()) left a running pass billed to completion. release_clients() and
  close() now discard it (shared-metrics reason `agent_released`).

Pass log lines now carry the session id, so concurrent sessions in one gateway are attributable.
2026-10-25 22:55:11 -07:00
Teknium
3562023300 fix(agent): bounded per-request profile hooks and one deterministic failure policy
R4 P2-5 (wire W2).
- replay_message_carriers was asked once per carrier-bearing assistant message
  on every request (O(history) calls, each an IPC round trip under
  plugins.isolation: host). Its answer is now kept per (route, carrier key set)
  as a key mapping and applied to every message with that key set; a hook whose
  answer rewrites values is still asked per message. Contract documented on the
  hook in providers/base.py.
- reasoning_payload and replays_function_thought_signature join request_headers
  / max_tokens_param as memoized pure hooks (argument values frozen, answers
  deep-copied).
- ONE failure policy for every per-request profile hook
  (provider_route_hooks.ask_profile, also behind route_answer): a raising hook is
  logged once per (profile, hook) and answers the generic value; the agent (scope)
  remembers it, so the rest of the session keeps the generic answer and request
  bytes never flip between turns. Before: _supports_reasoning_extra_body
  swallowed per request, _endpoint_reasoning_payload / replay_message_carriers /
  replays_function_thought_signature raised out of the kwargs build, route_answer
  swallowed per call. A failure mid-request reshapes the whole request so it
  matches every later one. One-shot auxiliary calls (no agent) ask again.
- x-initiator turn flag: already consumed before asking the route (53a51a49cc).
2026-10-25 22:22:47 -07:00
Teknium
53a51a49cc fix(agent): per-request provider headers reach the wire
A provider's request_headers(user_initiated=True) answer (turn attribution,
e.g. a premium-billing initiator header) was consumed when the first
attempt's payload was built. A 429/5xx retry or a fallback activation
rebuilds the payload for the SAME API call, so the retried attempt went out
with the route's default (agent) attribution instead of the user's.

The route now claims the call's api_call_count; every attempt of that call
re-applies the headers, tool-loop follow-ups (higher count) do not, and a new
turn / session reset clears the claim.

Repro (fake profile + local HTTP stand-in, scratch probe_xinit.py): first
attempt carries the header, the retry did not (codex_responses 500 retry,
chat_completions 429 retry); both attempts carry it after this change.

The turn flag is consumed exactly once per user turn, before the route is
asked: a route with no attribution, or a request_headers hook that fails
(route_answer swallows plugin errors), no longer leaves it set, which billed
the next tool-loop call as user-initiated (r4-review P2-5).
2026-10-25 21:28:27 -07:00
Teknium
4ba300b51b refactor(run_agent): delete dead _is_copilot_url/_is_copilot_provider
Nothing in production called them. Their tests now pin the owners of the
behaviour with the same inputs and assertions: the copilot profile's
request_headers (x-initiator hosts) and providers.profile_for_host (host-anchored
identity), in tests/plugins/model_providers/test_copilot_hosts.py.
2026-10-25 19:26:49 -07:00
Teknium
b9712a0c9f refactor(providers): generic wire seams for per-model api_mode, endpoint headers, max-tokens param
Core branched on the Copilot slug/host for four wire decisions. Replace them with
generic ProviderProfile hooks (providers/base.py L1 block) and move the Copilot
logic into plugins/model-providers/copilot/wire.py:

- api_mode_for_model(model, *, api_key=None): run_agent Responses routing, aux
  CodexAuxiliaryClient wrap, model_switch.model_derived_api_mode (copilot rows
  of _PROVIDER_API_MODE_OVERRIDES removed).
- client_headers(*, base_url, api_key, has_images): agent_init/_client_lifecycle
  host tables, the client-kwargs chokepoint guard (_ensure_route_client_headers),
  the image request-client header swap, both aux header branches.
- request_headers(*, base_url, model, user_initiated): first-call-of-a-user-turn
  attribution in turn_api_request and MoA reference slots.
- max_tokens_param(*, base_url, model): run_agent._max_tokens_param and
  auxiliary_max_tokens_param.

agent/provider_route_hooks.py asks the named provider's profile first, then any
registered profile overriding the hook, so custom routes at a provider's host
keep its quirks. Plugin absent = generic behaviour.
2026-10-25 18:23:40 -07:00
Teknium
20d4a80d69 fix(background-review): never requeue a preempted /refine for idle
_maybe_requeue_preempted_review skipped only focused reviews, so a bare
/refine cancelled by a live turn on the managed local runtime went to the
idle queue, whose dispatch-time enabled re-check then dropped it when
automatic reviews are off. Requeue is for automatic reviews only.
2026-10-24 07:13:08 -07:00
fangliquanflq
2db3fba0c6 fix(background-review): preserve bare manual refine
auxiliary.background_review.enabled: false must stop only automatic
post-turn forks (#87250). _spawn_background_review keyed the delegate and
enabled gates on `focus is None`, so a bare /refine (explicit=True, no
focus) replied "Reviewing this conversation in the background" and spawned
nothing. Gate on `not explicit and focus is None` instead.

Fixes #100762
2026-10-24 07:13:08 -07:00
Teknium
d6a5251d93 refactor(browser): callers import the browser_session layer
- run_agent / gateway shutdown / cli + hermes -q atexit / /browser and the
  browser.manage RPC import cleanup_*, emergency_cleanup_all_sessions,
  get_cloud_provider, get_browser_engine, the lightpanda status pair and the
  CDP override + supervisor helpers from tools.browser_session_{lifecycle,
  cloud,cdp} and tools.browser_lightpanda;
- per-turn cleanup reads browser.headed through is_headed_mode() only (the
  AGENT_BROWSER_HEADED fallback is gone with agent-browser);
- tests repointed; tests that only covered browser_vision / the built-in
  tool wrapper are dropped, the browser child env is credential-free per
  the session layer, and the codex MCP list must name core tools only.
2026-10-23 01:41:24 -07:00
kshitijk4poor
1f502aded8 fix(agent): close() also releases a prompt-caching split system prompt from the token memo
With prompt caching on, the request carries the system prompt as two text parts (the static prefix and
a per-request suffix slice), so the memo entry pins those strings, not the stored full prompt, and
forgetting _cached_system_prompt alone missed it. close() now also forgets _cached_system_prompt_static;
its pin evicts the split entry.

Repro on 75941667aa: real apply_anthropic_cache_control split -> prefix still pinned after close().
Found by the #137087 round-2 re-gate (second-model reviewer).
2026-10-20 18:08:50 +05:30
kshitijk4poor
26e2a21d02 fix(agent): the summary prompt and the system prompt leave the token memo too
Two strings reach _MSG_TOKENS_CACHE without ever sitting in the conversation history, so neither close()
nor the post-compression release could forget them:
- compression telemetry estimates the freshly built summary prompt (a serialized transcript, 520 KB in
  the probe) once per attempt; it stayed pinned until FIFO eviction.
- the per-session system prompt enters the memo via api_messages only; close() now forgets it alongside
  the history.

Repro on bcf6981878: both strings still pinned after telemetry / close(). Found by the #137087 pre-arm
gate (second-model reviewer), probe-confirmed.
2026-10-20 18:08:50 +05:30
kshitijk4poor
9b5698f87d docs(agent): _trim_process_memory's docstring matches the every-platform gc
trim_memory now runs gc.collect() on every platform and only the page release is glibc-only, so "safe
no-op elsewhere" was no longer true.

Found by the #137087 pre-arm gate (2c review).
2026-10-20 18:08:50 +05:30
kshitijk4poor
1b6877e2aa perf(agent): a closed agent's message bodies leave the token-estimate memo
_MSG_TOKENS_CACHE pins every string it fingerprints, so after AIAgent.close() a long-lived serve kept
each closed session's message bodies resident until 4096 newer messages pushed them out (tracemalloc on
a macOS serve: 200 x 256 KB replies, 50 MB, still pinned by the memo after every session closed).
2026-10-20 18:08:50 +05:30
kshitijk4poor
2df9823856 fix(memory): flush queued writes before a soft release shuts providers down
shutdown_all() gives the single mem-sync worker ~5 s and then cancels whatever
is still queued. Before this PR, release_clients() left the executor alone, so
a retired agent's last sync_turn/queue_prefetch writes still ran in the
background. With the soft-release shutdown they were abandoned instead
(measured: 4 queued 2 s writes -> 2 written, 1 abandoned).

MemoryManager.release_soft() now claims the teardown, flushes (bounded, like
the CLI exit, gateway cleanup and managed-worker paths), then shuts down.
release_clients() calls it, which also moves the soft-release policy out of
the run_agent.py facade (back to main's line count).
2026-10-19 19:15:44 +05:30
kshitijk4poor
3af00c8429 fix(memory): claim memory teardown on the manager, before the /new cleanup flush
The /new cleanup job took the teardown claim only inside
shutdown_memory_provider(), after a flush_pending() that can take up
to 10 s. When /new stops waiting (_RESET_CLEANUP_TIMEOUT_S) it evicts
the agent, and that soft release took the claim and shut the providers
down while the cleanup was still flushing. The cleanup then lost the
claim and skipped on_session_end(), so the session's end-of-session
extraction was dropped. On main release_clients() never touched memory,
so the extraction always ran.

The claim now lives on MemoryManager (claim_teardown(), under the lock
it already has), and _cleanup_agent_resources takes it before the
flush. A session-end caller may re-claim (the cleanup claims, then
shutdown_memory_provider() claims again); a soft release is once-only
and also loses to a manager another owner is already draining, which
replaces the _shutting_down peek in release_clients(). The module lock
and _memory_teardown_claimed attribute in run_agent.py go away, and the
release_clients() comment shrinks to the why.

Claiming earlier than the pool submission is not needed: when /new's
wait_for times out before the job starts, asyncio cancels the queued
job, so it never runs on main or here.

The hand-rolled _MockMM soft-evict test is dropped: its stub manager has
no claim_teardown(), and the real-manager writer-thread test already
asserts the same thing (shutdown, no extraction).
2026-10-19 19:15:44 +05:30
kshitijk4poor
859b999db5 fix(memory): one teardown claim shared by session-end shutdown and soft release
/new waits 30 s for its cleanup worker and then evicts the same agent. A
worker still inside on_session_end() had not set the manager's
_shutting_down yet, so release_clients() ran shutdown_all() under the
extraction, and the worker shut the providers down a second time when it
returned. Both paths now take the same once-only claim before extraction
or shutdown; the loser skips. This replaces the release-only
_memory_providers_released flag, which only covered close() racing a
release that had already started.
2026-10-19 19:15:44 +05:30
kshitijk4poor
512a6c4a5d fix(memory): claim soft-release memory teardown before draining
release_clients() set _memory_providers_released only after
shutdown_all() returned, so a close() arriving during the bounded drain
(up to ~5 s, plus provider writer joins) still ran on_session_end()
against providers mid-shutdown and called shutdown() on them again.
Set the flag before starting the teardown.
2026-10-19 19:15:44 +05:30
kshitijk4poor
efc8d91fb2 fix(memory): close() after a soft release skips extraction and re-shutdown
release_clients() now shuts the memory providers down but leaves the
agent's own _memory_provider_shutdown flag unset, so a later close() on
the same agent would run on_session_end() against shut-down providers
and call provider shutdown() a second time (MemoryProvider.shutdown()
has no idempotency contract). release_clients() records
_memory_providers_released on the agent when it shuts the providers
down, and shutdown_memory_provider() skips extraction and shutdown when
it is set; the context-engine session-end notification still fires.

The flag lives on the agent rather than reading the manager's private
_shutting_down, so test doubles that hand the agent a MagicMock manager
keep their close() -> shutdown_all() contract.
2026-10-19 19:15:44 +05:30
kshitijk4poor
a4a1a334dc refactor(memory): drop the redundant catch-all around soft-evict shutdown
getattr() with a default cannot raise and _quietly() already swallows a
failing shutdown_all(), so the outer try/except/pass only hid nothing and
tripped the code-health ratchet (BLE001/S110).
2026-10-19 19:15:44 +05:30
Jay Stothard
be67c299c1 fix(memory): correct release_clients comment on extraction-commit coverage
R2 review: the soft-eviction comment claimed _commit_then_release_soft()
universally commits extraction before release, but only the sweep paths
(LRU cap, idle TTL, RSS pressure) do; direct eviction paths (/new,
/model, /login, cross-process) release via _release_evicted_agent_soft
with no pre-commit. Reword the comment to state the per-path coverage
and note that the direct paths' uncommitted final-turn extraction is
pre-existing behavior unchanged by this PR.
2026-10-19 19:15:44 +05:30
Jay Stothard
99e56ba0ed fix(memory): terminate provider writer threads on soft eviction
release_clients() never shut down memory providers: every gateway
eviction path (LRU cap, idle TTL, RSS-pressure sweep, cross-process
evict) soft-releases the agent while its providers' background writer
threads keep running. Each soft-evicted agent leaked one writer daemon
(plus the references it pins), and under cache turnover from 429 retry
storms they accumulated into the 2026-07-30 gateway crash dump: 57
leaked writer threads out of 99 total, driving memory to the peak that
killed the liveness watchdog (exit 75).

Fix: release_clients() now calls MemoryManager.shutdown_all() directly,
which bounded-drains the sync executor and calls each provider's
shutdown() (sentinel + join) — without on_session_end(), whose
end-of-session extraction must stay the gateway's pre-evict commit's
job (_commit_then_release_soft() -> commit_memory_session() before
release) and which a resumed session would otherwise duplicate. Guarded
on the manager's _shutting_down flag; a resumed session's freshly-built
AIAgent creates a new manager with fresh providers.

Follow-up to #74785: the writer-thread leak was split out as separate
and not covered, with an invitation to open a focused PR.

Regression: TestAgentCacheIdleResume.
test_release_clients_shuts_down_memory_provider asserts shutdown_all()
fires on soft eviction and on_session_end() does not.
2026-10-19 19:15:44 +05:30
Siddharth Balyan
d33d7c6f3a Merge pull request #137807 from NousResearch/refactor/delete-guest-onboarding-flag
feat(free-tier): free model only on a first desktop install
2026-10-14 02:00:52 +05:30
kshitijk4poor
e6370f4004 fix(gemini): bound long decode by hops; scale the non-stream stale budget; first-hop context buckets
Review follow-ups on #137955 (long decode):

- Non-streaming stale watchdog: one timer spans every unary hop of a long decode, so an
  xhigh/max turn (8 / 32 hops of 32,768) was killed at the 600s gemini-4 floor and retried
  from hop 1, re-billing the hops already done. The implicit non-stream stale budget now
  scales by the request's hop count (explicit config still wins; the run-budget cap still
  applies after). Covers both the worker and the inline cron/subagent path, which read the
  same resolver.
- Hop ceiling: the unary and streaming loops stop at ceil(maxOutputTokens / 32,768) + 1 hops
  and end the turn as `length`, so a server that keeps answering CONTINUATION can't bill
  forever.
- Context-engine buckets: input_tokens / cache_read_tokens now follow the same first-hop
  split as prompt_tokens, so engines reading the canonical buckets don't see the summed
  prefix (or cache_read > prompt). Billing, the log line and session totals keep the sum.
2026-10-13 12:44:39 -07:00
alt-glitch
3a867a9e65 refactor: delete the initiate-setup turn core, keep the scripted prelude
Salvage of 058b5c8158 from the static-onboarding stack, adapted: the
initiate-setup prompt, its facts builder and the first-task prompt go with
the setup_choose server request and callback, the initiate-setup branch of
the prelude wiring in prompt_turn and the intro auto-continue skip. Unlike
058b5c8158 the scripted prelude seam (agent/turn_scripted_prelude.py and
the prelude parameter on run_conversation) and gui_tour's preset stay: the
default-profile onboarding opening plays through them, and prompt_turn now
asks only _onboarding_prelude for one.

(cherry picked from commit 058b5c8158, adapted)
2026-10-14 00:29:11 +05:30
alt-glitch
72e7085e9e feat: set_theme replaces apply_layout and reports what the desktop applied
set_theme (desktop_ui, deferred like apply_layout was) sets the accent,
light/dark mode and layout preset, or with `picker` shows an accent or
layout card and waits up to 300 s. apply_layout emitted a layout.apply
event and returned success whether or not the renderer applied anything;
set_theme asks the renderer through the theme.apply server request and
returns its answer, so an unknown preset or a chat that is not on screen
comes back as an error with the available ids.

theme.pick waits for a person; the backend tells a dismissed card
({cancelled}) from an expired one ({timed_out}). The tool description
lists the Simple and Advanced preset ids from one constant, which fixes
the old description that named neither sidebar preset. The layout.apply
event and its renderer handler are deleted with the tool.
2026-10-13 23:55:10 +05:30
alt-glitch
d8cefac352 feat(onboarding): setup_beat, the one onboarding-only tool
tools/setup_beat_tool.py shows a beat's card and blocks until the user
answers (the card callback is a server request, like clarify), then
returns their answer with a reminder of the next beat. beat=next shows
the first open beat; value and skip record an answer given in words
without a card; beat=done ends the run once the build card was reached,
and beat=done with skip=true ends it early when the user asks to stop.
Words typed while the name card waits are the name. The account's full
name goes to the name card only.

The tool lives in a new desktop-only "onboarding" toolset, which nothing
enables by default; the gateway folds it in for the onboarding chat only
(next commit). It runs inline in the agent loop (inline_tool_executors)
with the session's store and the agent's setup_beat_callback, and never
in parallel with another tool.

Two loop seams:
- tool_executor passes every successful tool result to
  onboarding.observe_tool_result, so set_theme, manage_connections
  display and gui_tour (also when reached through tool_call, which the
  executor unwraps first) settle their beat.
- turn_tool_round treats a setup_beat round like a housekeeping round
  for the empty follow-up: the line written with the card becomes the
  reply instead of an empty-response nudge (not muted).
2026-10-13 22:08:20 +05:30
Teknium
a274d3388f fix: core modules import again on Python 3.11-3.13 (re-quote eager forward references)
#135348 ran ruff's UP037 autofix with ruff.strict.toml's target-version = "py314". On 3.14
annotations are lazy (PEP 649), so stripping quotes is safe there; on 3.11-3.13 a function or
variable annotation is evaluated when the def or statement runs. Every unquoted annotation that
names the enclosing class (`def clone_for_agent(self) -> ContextEngine`), a class bound later in
the module, or a TYPE_CHECKING-only import now raises NameError on import: 300 modules on main
(gateway.config, run_agent, hermes_state, cron.jobs, the Telegram adapter, ...) fail to import
under 3.11, the update path crashes mid-`hermes update` on any install whose interpreter is
older than 3.14, and the e2e-upgrade suite's retry leg fails with
`NameError: name 'ContextEngine' is not defined`.

- Re-quote exactly the 79 annotations (36 files) that name something unbound when they are
  evaluated (including tui_gateway/server.py's `_TurnScopes`, which only reaches that module's
  globals through register() after import); no other text changes.
- agent/turn_scripted_prelude.py: `Generator[...]` gets its third argument back. d76cce4f11
  applied UP043 (default type args, valid only from 3.13) to a module-level alias, so
  `Generator[Y, S]` raises TypeError on 3.11/3.12 and takes gateway.run, agent.conversation_loop
  and tui_gateway.{server,ws,entry} down with it.
- ruff.strict.toml target-version = "py311", the requires-python floor. With it UP037 leaves
  these quotes alone and only strips the two that are genuinely redundant, which this commit
  strips; any future version-gated fix stays valid on every supported Python.
- tests/ci/test_strict_ruff_target.py pins the target to the requires-python floor (red on main).
2026-10-09 14:25:07 -07:00
Maciej Lisiewski
2ff58849f4 ci: ruff UP037 fixes 2026-10-09 17:34:38 +02:00
Maciej Lisiewski
9d9a3840d1 ci: address code review 2026-10-08 22:16:26 +02:00
Maciej Lisiewski
4278b6aa24 ci: RUF013, RUF015 2026-10-08 21:29:48 +02:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
b1a39a1b1b refactor(approval): one session /yolo contract for CLI, TUI/Desktop and the messaging gateway
The persist / restore / carry logic for session YOLO had grown three copies
(the CLI mixin, tui_gateway, the gateway runner), each with its own key choice,
ordering and error handling. tools/approval_yolo.py now owns it:

- toggle_session_yolo: flip or set, persist BEFORE the live flip (a racing
  restore never revives an OFF), stored-copy-aware so a toggle after a restart
  turns it OFF; a failed write logs a warning and never blocks the flip.
- restore_session_yolo: re-arm a persisted flag in a fresh process; skipped
  under the frozen process --yolo.
- transfer_session_yolo: move the live flag to a continuation id.
- with_session_yolo: a row being created records a live flag (lazy first row,
  compression child, /branch).

Each surface keeps only its storage: the session row for CLI/TUI/Desktop, the
routing entry for the gateway. Removed: HermesCLI._transfer_session_yolo /
_persist_session_yolo, GatewayRunner._restore_session_yolo, the TUI-only
restore helper, and the TUI's post-publish set_session_yolo carry (the
compression publish now writes the child row with the flag).

Closes a gap the unification exposed: a CLI manual /compress that rotated the
session dropped YOLO (the next dangerous command prompted, and a --resume of
the continuation came back with it off).
2026-10-08 00:49:32 -07:00
alt-glitch
8b89b68fb4 Merge origin/main into sid/onboarding
Brings the onboarding branch up to main 0c2ff854a5. Where a Wave A PR
already landed a reviewed version of a piece of this branch (free tier
#134049, keyless web #134048, app resolver #134050, bundle and uninstall
#134051, catalog card and toolsets #134052, built-in tour #134054, stdin
guard #134055, retired key #126146), main's version wins. The PM long-path
files also take main's version: that work lands through #130430.

Kept from the branch on top of main:
- the setup and start_chat toolsets, declared with main's platforms key
  (desktop only), and the setup_choose server request contract;
- the setup-profile marker file (.setup-profile.json) instead of the
  profile.yaml role, as c3f85bc54f decided;
- the first-contact note's message argument beside main's internal flag;
- the setup-profile gate on the shared-metrics consent dialog;
- window sizing (window-growth) in place of chat-onboarding-window.

Desktop i18n follows main's per-section sibling files. The onboarding
strings go into them (modelMenu.localSetup, handoffTour.localTitle and
localText) and setupChoose/startChat stay in en.ts. guidedGreeting is
gone. The shared-metrics copy uses the branch's rewrite in English, with
the pre-opt-in sentence corrected for the fresh-install note
(d3674513c8); locales keep main's translations, with installId and
consentWindow folded into the new sending key.

The built-in tour reads local-model eligibility from the local-setup
offer store, the one place that rule lives on this branch. The gateway
contract and the onboarding skill docs pages are regenerated.
2026-10-07 03:27:01 +05:30
Siddharth Balyan
de1626d666 Free tier: a rate limit ends a watched turn at once with the reset time (#134049)
* fix(agent): free-tier rate limits end an attended turn at once

A free-tier (no sign-in) session that hit the service-wide rate limit slept
up to 600 s, retried into the same refusal, slept again, and then sent its
third attempt on a guest JWT that had expired during the wait. The welcome
host answered 403 "invalid jwt", which read as the tier being switched off.
The user watched a spinner for about 18 minutes and then saw the wrong card.

- An attended session (desktop, TUI, the interactive CLI, ACP) on the free
  model ends the attempt cycle at once when the cooldown is longer than
  60 s: fallback first, else the reset time and the sign-in / model doors.
  "Attended" is keyed on the session source, so `hermes chat -q`, cron and
  messaging sessions keep the long wait. The source vocabulary moves from
  run_agent.py into agent/session_source.py, which adds is_attended().
- on_free_model() (welcome host + anonymous credential) is the one free-tier
  check, used by the cutoff, the "free model is busy" wait copy and the
  outage copy.
- A welcome-host 403 "invalid jwt" is its own route kind, session_expired:
  the existing one-shot route heal re-exchanges the credential and retries;
  if that fails the card is the retryable outage card.
- interruptible_backoff_sleep adopts a fresh Nous key after each wait.
  _adopt_nous_key_before_expiry owns its refresh failure, so both call
  sites drop their try/except.
- A retry wait over 60 s is announced in the transcript when it starts, for
  every provider; shorter waits stay buffered. Every wait line names the
  attempt that runs after it.
- max_retries_exhausted_result's max_retries becomes attempts (what it
  carries); a one-attempt rate-limit end gets its own lead.
- One Retry-After reader, retry_utils.provider_retry_after_seconds, shared
  by compute_error_backoff and the recovery ladder.
- _session_default_route replaces _session_default_model everywhere in
  tui_gateway, so a not-yet-built free-tier session reports nous/welcome on
  create, reuse, resume, branch and row persist, not the silent default.

* fix(agent): free-tier cutoff no longer ends subagent or library turns, paid waits look like main (review)

A delegated child of a TUI/Desktop session and a library caller (no platform) are unattended, so they keep waiting.
Rate-limit wait lines keep main's attempt numbers and stay buffered for every provider; only a non-rate-limit Retry-After over 60 s is announced, as on main.
The unattended free-tier wait line keeps the reset time beside "The free model is busy".
The free-tier cutoff names the reset time for any cooldown it fires on (over 60 s), not only from 120 s.
session.info for an env-seeded model off the free tier carries the model alone again, as on main.
Behaviour tests for the cutoff, the subagent and unattended waits, and a paid long wait.
2026-10-06 12:31:21 -07:00
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
teknium1
9c82eab919 fix(agent): one rejected reasoning blob no longer ends replay for the session
An invalid_encrypted_content 400 (or the Codex 401 token_expired twin)
used to strip every cached codex_reasoning_items blob AND turn
replay off for the rest of the agent's life, so a single rotated
sealing key cost all cross-turn reasoning continuity in a long CLI
session or a cached gateway agent.

The first rejection now only strips the stale blobs (persisted messages
and the request copy the retry is rebuilt from); blobs the route mints
afterwards are sealed with its current key and keep replaying. A second
rejection means the route cannot round-trip its own fresh blobs, so
replay is disabled for the session as before: a hostile route costs one
extra 400 compared to main.

The request-copy strip is required: main's global kill switch hid that
the retry was rebuilt from api_messages, which still carried the blob.
2026-10-01 12:08:13 -07:00
alt-glitch
16bec86daa feat(setup): setup_choose asks one question or picker card in the setup chat
The setup profile needs one tool to ask the user a question or show a
picker (accent, theme, layout, connectors, plugins) as a card. Today the
runbook emits ::onboarding and ::ask directives that the app parses out
of the model's text.

setup_choose joins the setup toolset, so it is desktop-only and direct
(never deferred unless a defer list names it). It validates kind,
question and up to 12 {id, label, detail?} options, and passes
options=null through so the app can show its own list. It reaches the
renderer as a setup_choose server request, bridged in
tui_gateway/agent_callbacks.py with the clarify wait timeout. The result
reports submitted (picked, plus intent now/later/save per row for
connectors and plugins), cancelled, or no_answer. It stores nothing.

The wire contract is in tui_gateway/contracts/server_requests.py and the
apps/shared contract files are regenerated. The desktop card and fixed
lists come later. The ::onboarding/::ask directives stay for now.
2026-09-30 11:59:14 +05:30
teknium1
8d8836ddb1 feat(telemetry): harness-accuracy shared metrics for the agent loop
Five opt-in counters that tune the agent loop itself, recorded through
record_process_mark (disabled config => zero rows, zero files):

- hermes.file_edit.count: tool, mode, outcome, match_strategy. The fuzzy
  matcher reports the strategy that landed (or no_match / ambiguous) into a
  context-local probe opened only around the patch/write_file handlers, so we
  learn which strategies earn their keep without counting internal callers.
- hermes.loop_guard.count: provider, model, signal, detector. Hooked where
  the guardrail already warns/blocks/halts and at turn end for the iteration
  budget; latched once per turn per (signal, detector).
- hermes.tool_recovery.count: provider, model, tool, next_tool,
  next_outcome. One row per failed tool call, resolved against the model's
  next round (same tool first) or the turn end (no_tool_call / gave_up).
- hermes.terminal.outcome.count: backend, command_kind, outcome. The kind is
  a table lookup on the first program word, never the text. Hermes' own
  deadline/interrupt now set hermes_timed_out / hermes_interrupted on the
  backend result, so a command's own `exit 124` reads nonzero, not timeout.
  Disjoint dims from hermes.execution_backend.count (served vs not).
- hermes.model_reply_issue.count: provider, model, issue. Refusal and
  truncation only from the structured finish reason; empty/reasoning_only
  from the normalized message; issue=none per response as the denominator
  (model_route counts attempts and files empty replies as failures).

Background review / curator loops and _host_local / unmetered terminal
calls never count. Helpers live in shared_metrics_harness.py; call sites
are one or two lines each.
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
kshitijk4poor
6d88dc1fe5 fix(agent): harden the todo predicate and import the TUI server once in the test
is_todo_tool_name returns False for non-string names (a malformed list/dict
name used to raise TypeError where the old check returned False), and the
kept regression test imports tui_gateway.server at module level so it no
longer depends on another test importing it first. Docstrings updated.

Co-authored-by: JoaoMarcos44 <joaomarcosdias444@gmail.com>
2026-09-27 18:34:12 +05:30
kshitijk4poor
622a296f7a fix(agent): keep the todo predicate off the model_tools/executor import path
is_todo_tool_call lived in agent/tool_executor.py and went through
canonical_tool_name, which imports model_tools. TUI resume calls it from
_todo_state_from_history on the RPC path, so the first resume in a
gateway loaded ~405 modules (2-3s) synchronously. tui_gateway/server.py
and run_agent.py also imported agent.tool_executor at module level,
adding ~142 modules to every TUI/desktop launch and breaking run_agent's
lazy-forward rule.

The predicate now lives in tools/todo_tool.py, which both startup paths
already load. It matches TODO_TOOL_NAMES ({TODO_SCHEMA name} + the legacy
aliases) and imports the bridge parser only when a tool_call entry's
args mention "todo". model_tools._LEGACY_TOOL_ALIASES derives its todo
entry from TODO_LEGACY_ALIASES, so there is one source of truth ("todo"
is the only alias mapping to todo_list). The live tool.complete path in
tool_progress uses is_todo_tool_name and the hand-kept _TODO_TOOL_NAMES
tuple is gone. The server.py noqa import is replaced by a function-local
import next to MAX_TODO_RESULT_CHARS, so a pruned name can't be swallowed
by the broad except. run_agent imports lazily. The dead TypeError arm is
dropped, and field reads use message_sanitization._tc_field.
agent/tool_executor.py is back to its pre-stack state.

Co-authored-by: JoaoMarcos44 <joaomarcosdias444@gmail.com>
2026-09-27 18:34:12 +05:30
kshitijk4poor
3d3c1c1223 fix(agent): pair bridged tool_call todo results via one shared predicate
todo_list is in the default tool_search defer list, so with tool search
active the model calls it through the tool_call bridge and the transcript
keeps function.name == "tool_call". The canonical-name pairing check never
matched those, so todos were still dropped across turns (#124960) in every
tool-search-active session, and the TUI resume snapshot had the same gap.

Add agent.tool_executor.is_todo_tool_call: canonicalizes legacy aliases and
peels the bridge from the recorded arguments with normalize_tool_call_entries
(exactly one entry required). It deliberately does not use
resolve_underlying_call, which reads live config and could disagree with the
defer list in force when the history was written. run_agent and
tui_gateway's _todo_state_from_history now share it; the canonicalizer is
public (canonical_tool_name) since it is now used across modules.

Co-authored-by: JoaoMarcos44 <joaomarcosdias444@gmail.com>
2026-09-27 18:34:12 +05:30
JoaoMarcos44
031e3296a5 fix(agent): canonicalize todo history pairing
(cherry picked from commit e8900249ad4bfad39e7944bd62825b10930a29c0)
2026-09-27 18:34:12 +05:30
kshitijk4poor
65a3f97622 refactor(agent): share one run-budget stale-timeout cap across stream and non-stream (#97968) 2026-09-25 21:28:32 +05:30
ethernet
0f65d698d0 Merge remote-tracking branch 'origin/main' into ethie/pm-clean 2026-09-24 13:10:14 -04:00
kshitijk4poor
144e9711b8 fix(agent): treat jiter SSE parse ValueErrors as transient provider errors (#65147)
Extends PROVIDER_STREAM_PARSE_MARKERS (single home) with jiter's serde
vocabulary and excludes those ValueErrors from _is_local_validation_error so
the turn-level retry/fallback path runs instead of aborting as a local bug.
Grafted from #65154 (its conversation_loop regex is superseded by the markers).

Co-authored-by: Simplicio, Wesley (ext) <wesley.simplicio.ext@siemens-energy.com>
2026-09-24 22:26:23 +05:30