Commit Graph

428 Commits

Author SHA1 Message Date
alt-glitch
458a0046ad refactor(agent): six checkpoint files move from tools/ to agent/checkpoints/
tools/ holds model tools. These six files register none: they snapshot and
restore a working directory for the agent loop, /rollback, /undo's
changed-files line and `hermes checkpoints`. They move next to the agent
loop that takes the checkpoints:

  tools/checkpoint_manager.py                -> agent/checkpoints/manager.py
  tools/checkpoint_maintenance.py            -> agent/checkpoints/maintenance.py
  tools/checkpoint_pruning.py                -> agent/checkpoints/pruning.py
  tools/checkpoint_refs.py                   -> agent/checkpoints/refs.py
  tools/checkpoint_undo_hint.py              -> agent/checkpoints/undo_hint.py
  tools/checkpoint_manager_profile_rename.py -> agent/checkpoints/manager_profile_rename.py

agent/checkpoints/__init__.py is a docstring only. Nine test files move to
tests/agent/checkpoints/. Every importer changes its import line in place,
inside the same function. Nothing stays at the old paths: none of the six
names is on the plugin API list, the shipped-release list or the
old-updater list.

Behaviour is unchanged. The four loggers keep their tools.checkpoint_*
names, so the lines stay under `hermes logs --component tools`. The folder
is not a root checkpoints/ package because the checkpoint store is
HERMES_HOME/checkpoints, which is the same directory as such a package on an
install whose checkout root is HERMES_HOME. agent.* is already packaged, so
pyproject.toml and the lists of root packages do not change.

The import and docs rewrites were made by scripts/move/rewrite_imports.py
and rewrite_docs.py.
2026-11-16 19:21:55 -06:00
Maciej Lisiewski
a3cb0c62a2 fix(providers): never fill a Foundry anthropic client with the OAuth token
Follow-up to the Foundry pool skip:
- The explicit --base-url Foundry shortcut raised nothing without an Azure
  key and returned "", which agent init, fallback activation and model
  switch then filled with resolve_anthropic_token(). It now raises the
  Azure-key AuthError, and the three fill sites go through
  native_anthropic_fallback_token(), which returns "" for azure.com hosts.
- Aux _try_anthropic used the raw `model:` section's key for any Foundry
  URL, so another provider's inline model.api_key went to Azure. It now
  uses anthropic_foundry_key(): the model section and the pool row count
  only when model.provider is anthropic at that same URL.
- The pool skip on a Foundry URL now drops only non-manual/OAuth rows, so
  an Azure key stored via `hermes auth add anthropic --api-key` still works.

Fixes #154242
2026-11-14 15:35:25 +01:00
Siddharth Balyan
33e9504e93 fix(agent): external-process providers are not local servers (#129153)
is_local_endpoint() reads process://<name> as an unqualified LAN host, so
DirectSDK and every other external_process provider took the single-slot
local-server branches: a "prompt is too long" with no token count failed the
turn with "wait and /retry" instead of compressing (the session stayed stuck
until /new), and init/context resolution ran the Ollama/llama.cpp probe
waterfall against a child process.

agent/process_transport.py adds two predicates keyed on the provider
profile's auth_type, never on the URL:
- is_local_server(base_url, provider): a local HTTP server. Used where the
  call site means one request slot, a local server to probe, or local-server
  copy (overflow rejection, stream load notice, Ollama num_ctx, local context
  probes, minimum-context remedy copy, reasoning carriers, Ollama vision
  probe, stale-aux pins, the dashboard local_endpoint flag, the local-model
  metrics bucket, the CLI banner fix hint).
- waits_like_local(base_url, provider): silent before the first token. Used
  where the call site means patience (stream stale ceiling, stream read
  timeout, aux first-token window), so external-process providers keep the
  900 s budget they had by accident, now on purpose.

Builds on the salvaged C#129157 (dskwe), which added the process:// string
check at the overflow site; that check is replaced by the auth_type rule and
its test now covers acp:// too.
2026-11-14 05:44:33 +05:30
Ben Barclay
4fd509e4e0 fix(sandbox): a hosted scope is deny-by-default: one tool allowlist, one host-feature switch
Two review rounds each found ~8 new host routes because the policy listed what to refuse.
tools/hosted_tool_policy.py now lists what is allowed, and the denylist is gone.

- hosted_tool_refusal: a tool runs in a hosted scope only if it is on HOSTED_TOOL_ALLOWLIST
  (terminal, process_manage, execute_code, read_file, write_file, patch, search_files), the
  tools that act only through the agent's sandbox. The agent loop asks once per call in
  _dispatch_authorized_once, which every sequential, concurrent and batched call goes
  through whatever its executor (inline, memory provider, context engine, registry). The
  primitives ask too, for callers outside the loop: ToolRegistry.dispatch, the inline
  executor table, handle_function_call (connectors, bridges) and the browser_exec direct
  entry. Memory, session_search, todo, vision, web, browser, MCP, connectors, catalog,
  delegation, skills and cron are refused before any handler (round-2 findings 9, 10, 11,
  13, 14).
- host_feature_enabled: agent features outside tool calls that read or write this host's
  profile state are off in a hosted scope. Context files and SOUL.md, subdirectory hints,
  @-references, workspace snapshot, backend probe, built-in memory init/load/writes and
  providers, recall DB, background review, trajectory export, failed-write bookkeeping,
  checkpoints, image/video processing, inline skill shell, cron scripts, MCP stdio, media
  delivery, transcription and /review delegation each ask the one function (findings 4,
  12, 13, 15).
- Per-site refusals that the allowlist covers are removed (connector file inputs).
- Local mode is unchanged. A test shows the allowlist is never consulted unscoped or
  locally and every registered tool reaches its handler. The local byte-parity test is
  kept.
2026-11-11 10:22:54 -05:00
kshitijk4poor
6b41bdf2ec docs(agent): route verdicts last until the route changes, not the session
The reasoning-effort, reasoning-disable, floor-effort and Codex replay notices
and comments said the setting held for the session; it now resets when the
route changes. The route_verdicts module docstring names the Codex replay pair
and the refresh and transport-recovery resets, and _reapply_route_client_config
names reset_route_verdicts_if_moved as the other path for a base_url move.
2026-11-08 17:34:10 +05:30
kshitijk4poor
bff4ba1ce0 fix(agent): a route that refused streaming no longer turns it off for the next route
_disable_streaming is set when a provider answers that it cannot stream,
which is a fact about that route, yet it survived fallback activation,
switch_model and primary restore, so a route that streams fine never
streamed again in that session. It is now a route verdict: saved and
restored with the others, and reset to the model.streaming seed recorded
at init (not to False), so a configured streaming: false still holds
across route changes.
2026-11-08 17:34:10 +05:30
kshitijk4poor
344de92b59 fix(agent): rejection verdicts learned on one route no longer follow the session to the next
Four agent flags record that the CURRENT route refused something:
- _reasoning_effort_rejected: the route 400'd an enabled reasoning effort, so
  every later request omits the reasoning fields (teknium1, 2026-09-19,
  64dceb9c26, #115736);
- _reasoning_disable_rejected: the route refused a reasoning disable, so
  disables are dropped (Teknium, 2026-09-03, f6bd1633f7, #102108);
- _reasoning_floor_required: the route requires a minimum effort, so
  disables become effort low (teknium1, 2026-09-19, 2768f31628, #115935);
- _stream_options_unsupported: the endpoint 400/422'd stream_options, so
  streams stop asking for usage (DavidMetcalfe, 2026-06-26, 6527af2286,
  #109143).

None was ever reset. After a /model switch, a fallback activation, a primary
restore, or a credential rotation that moved the endpoint, the new route kept
the old route's verdicts: a model that
takes reasoning effort fine had its reasoning stripped for the rest of the
session because a different model had rejected it, and a provider that
reports streaming usage lost token accounting because a different endpoint
had refused stream_options. The voice route already treated the reasoning
three as "facts about one route" and saved/cleared/restored them by hand,
and the encrypted-reasoning replay verdict already resets on every route change (#61552).

New agent/route_verdicts.py holds the per-route flag list and
reset_route_verdicts(), which clears them and the encrypted-reasoning replay verdict. It
replaces the replay-only reset at the route-change sites:
switch_model (agent_runtime_helpers), fallback activation (bind_route_entry),
snapshot reinstall (reinstall_runtime_snapshot), and now also
_reapply_route_client_config when route_changed (credential-pool rotation and
the .env credential refresh, which can point the agent at another base URL).

Verdicts are kept with the route rather than thrown away:
- the hop that leaves the primary saves its verdicts into the primary's
  _primary_runtime snapshot and reinstall_primary_runtime puts them back, so
  a fallback episode does not make the primary re-learn each one with a
  failed request. Living in that snapshot, they go away when /model rebuilds
  it, so one primary's verdicts never reach the next. They are stamped with
  the endpoint that earned them and put back only after the primary's
  credential pool is rebound and only if it landed on that same endpoint (a
  pool rotation can move the primary to another base URL);
- a /model X --once restore (CLI and TUI) snapshots the primary together
  with its current verdicts (primary_runtime_for_restore), so the original
  primary comes back with its own verdicts even when X failed over;
- a .env credential adoption whose client rebuild fails rolls the verdicts
  back with the old route;
- a switch_model whose client rebuild fails rolls the verdicts back with the
  rest of the old route (_SWITCH_SNAPSHOT_FIELDS);
- the voice route saves/restores the full list (ROUTE_VERDICT_FIELDS) and
  drops its own clearing loop, which bind_route_entry now does. That also
  fixes main losing its encrypted-reasoning replay verdict (and the voice model inheriting
  main's stream_options verdict) on every voice turn.

_oauth_1m_beta_disabled is left alone: the Anthropic OAuth long-context
beta is refused per account, not per route, and a switch rebuilds the client
anyway.

Tests: fallback clears and primary restore returns the primary's own verdicts
(test_primary_runtime_restore.py, the #61552 replay test updated to match); a
/model switch clears them and a failed switch keeps them
(test_switch_model_context.py); rotation to another base URL clears them and
same-URL rotation keeps them (test_credential_rotation_route_settings.py);
/model --once restores the original primary's verdicts even after X failed
over, a /model switch made while on a fallback starts the new primary clean,
a primary that rotated to another base URL before failing over does not
bring that endpoint's verdicts back to its own, and a failed .env adoption
keeps the verdicts
(test_route_verdicts_once_restore.py); a voice turn leaves main's stream_options and replay verdicts intact and sends
stream_options to the voice endpoint (test_voice_turn_route.py). Removing
each piece fails its test.
2026-11-08 17:34:10 +05:30
kshitijk4poor
6b21d0564d feat(memory): initialize() is told whether the agent continues a stored session
A memory provider could not tell a fresh session from one the agent is continuing (a CLI
--resume, a gateway chat picked up after a restart, a Desktop/TUI session reopened), so it
could not skip re-seeding or reconcile against what it already holds. Agent builds now pass
resumed (an earlier turn of this session id ran: an assistant row is stored) and
message_count (messages stored for it). Keying resumed on an answered turn, not the count,
keeps a fresh TUI/Desktop chat not-resumed: it stores the submitted prompt before the build.
A new session id (subagent, cron run) or no session store reads False; a /branch child
seeded with copied history reports the copy. Mid-process /resume still goes through
on_session_switch. The developer guide lists both, and on_turn_start's model.
2026-11-07 01:23:45 +05:30
BearHuddleston
95516763d5 refactor(agent): move the codex app-server checkpoint refusal beside the gate
_refuse_checkpoint_required_on_codex_app_server() moves from agent_init.py
into agent/conversation_compression_checkpoint.py unchanged, with a late
import at its one call site and the contract test's import repointed.
agent_init.py is over its FILE_LINES target, and the fork commits before
this one grow it from 2262 to 2272 lines; the move brings it to 2254.

The same move was part of 484a9d7e6c on #149265, which also carries the
context-engine refusal this branch leaves out.

Co-authored-by: Jan-Stefan Janetzky <git@gottz.de>
2026-11-05 19:55:33 -06:00
Jan-Stefan Janetzky
14525b539c fix(memory): keep MEMORY.md/USER.md out of a checkpoint fork's prompt
Arming compression.checkpoint_required flips the four fork sites to
skip_memory=False so the child can reach the checkpoint provider. In
_init_memory that flag does two things: it loads the external provider
(what the gate needs) and it takes the built-in store branch, which reads
memory.memory_enabled / memory.user_profile_enabled (both default true)
and loads MEMORY.md and USER.md into agent._memory_store;
system_prompt._memory_parts then renders both. The MemoryManager fork scope
does not reach this, because the store is not a provider. So with the gate
armed a delegate child routed to another provider, a batch_runner
trajectory and the Feishu comment responder all carried the user's notes
and profile in their prompt; gate off (and on main) none of them did.
Found in review (BearHuddleston, #94983).

- agent_init._init_memory: right after the flags are read, a fork labelled
  memory_agent_context="subagent" that did not request the memory toolset
  gets both flags cleared, so no store is built and nothing renders. The
  toolset request still wins (#65429: enabled_toolsets=["memory"] must get
  a store), exactly as it does for a skip_memory=True fork with the gate
  off. mem_config stays defined for the provider branch below. The memory
  nudge is already gated on agent._memory_store (_tick_memory_nudge), so
  gate on and gate off now agree on every observable of the built-in store.
- memory-provider-plugin.md, "Forks under an armed gate": the prompt stays
  as with skip_memory=True; the toolset exception is named.

Tests (tests/agent/test_fork_memory_under_checkpoint_gate.py): the probe
builds a fork and a primary agent through a real AIAgent init with the
recording provider and MEMORY.md/USER.md in the sandboxed home, then renders
build_system_prompt for both. Red against the previous commit ("parent-only"
in the fork's prompt, a MemoryStore on the fork); the primary is the
control. A second test pins the toolset exception. The helper grows a
builtin_memory switch that sets both store flags.

(cherry picked from commit b4cf44d6544c1aa1d9b8ece6e4f3061d08e3652b)
(cherry picked from commit 3acd933faba7c17dec2e0047fc6792e90e614ac8)
2026-11-05 19:55:33 -06:00
Jan-Stefan Janetzky
b1b321363d fix(memory): thread parent_session_id into provider initialize()
MemoryProvider.initialize documents parent_session_id among the kwargs a
provider may receive, and the fork docs rely on it to tell the fork shapes
apart, but _memory_provider_init_kwargs never sent it: parent_session_id
lived on agent._parent_session_id and never reached initialize(). Every
provider.initialize() takes **kwargs, so pass it through when set -- a no-op
for providers that ignore it, and the documented behaviour for those that
don't. Pinned with the recording provider through a real AIAgent init (red
without the change), with the unset case as the control.

(cherry picked from commit a69ce3b5a078dc30fe8a1f197fe4d2e8c4b0d1f6)
(cherry picked from commit bc96063187d562845a2beb7bceea133e91c2db13)
2026-11-05 19:55:33 -06:00
Jan-Stefan Janetzky
f02ba87b8c feat(agent): fork sub-agents inherit the memory provider under checkpoint_required
Four call sites fork a second agent with skip_memory=True, which leaves the
child with _memory_manager = None: a fork is not the user, and its scratch
transcript is not the user's memory. With compression.checkpoint_required
armed that saving turns into a kill. The gate is armed globally per agent
instance from config, not from whether the agent has a provider, so the child
arms the same gate its parent did and then meets its first compaction with
nothing to checkpoint against. It raises CompressionCheckpointUnavailable --
"no active provider implements checkpoint API v2" -- and the delegate turn
dies with status=error and a null summary while the parent runs on. The gate
is not bypassed there; it is armed against a provider that was never loaded.

- The four sites (delegate_tool, curator, batch_runner, feishu_comment) pass
  skip_memory=not checkpoint_required_from_config(). Gate off is the default
  and stays byte-identical: skip_memory=True, no provider init, no hook. Same
  shape and the same reason as the two gateway disposable-agent sites that
  already read the key this way (run_turn_hygiene.py,
  slash_commands_session.py). delegate_tool reads it inside the delegated
  profile scope, where the child reads it.
- The detached review and /btw forks (build_cache_parity_fork) are not
  touched: they persist nothing, and _pre_compress_memory_context already
  exempts exactly that shape (decabd79f1), so the gate never fails them.
- checkpoint_required_from_config() in conversation_compression_checkpoint,
  next to the gate's init refusals. One resolver rather than four parses, and
  the call sites need it before an agent exists:
  agent.compression_checkpoint_required is assigned inside the child's own
  init, and the parent's says nothing about the child. It reads
  load_config_readonly() -- the call init_agent makes to arm the gate on that
  child, so parent and child answer from one source and a fork is given a
  provider precisely when the child would refuse to compact without one. An
  unreadable config reads as "not armed", matching init_agent's own except
  around the same load.
- New memory_agent_context kwarg on AIAgent/init_agent, handed to the
  provider's initialize() as agent_context; unset, the platform rule decides
  as before (cron/subagent, else "primary"). The platform rule alone cannot
  scope these forks: the curator runs as platform "curator", the batch runner
  takes its platform from the caller's config, and the Feishu responder sets
  none, so each would file its transcript as the user's own memory in every
  provider that scopes writes by that key. All four pass "subagent" -- the
  value memory_provider.py documents and supermemory gates on. A fresh
  per-site string ("curator", "batch", ...) would drop out of every
  provider's non-primary membership test and re-enable writes the provider
  had deliberately disabled, which is a fail-open on the one path this commit
  opens. platform still separates the shapes.

Costs, taken deliberately rather than hidden: one provider initialize() per
fork (a round trip for a network-backed store, on a path that made none), and
fork transcripts reaching the archive as checkpoints. Both are named at the
call site and in the contract doc, where a provider author reads them.

Ten tests (tests/agent/test_fork_memory_under_checkpoint_gate.py). The
four site probes drive the real spawn functions with the smallest parent stub
they accept and record the child constructor kwargs -- red at all four against
the previous commit with the literal skip_memory=True. The gate-off probes are
the control in the other direction: without them "inherit the provider" could
have shipped as "always inherit". The recorder aborts with a BaseException
because the sites wrap the spawn in except Exception and would have swallowed
an ordinary failure into a green test. The provider-initialize test drives a
real AIAgent init, the only way to observe the keyword at initialize().

Live probe (on the August base), isolated HERMES_HOME with a stub API-v2
provider and the gate armed: before, the child aborts with failure_class
"exception:CompressionCheckpointUnavailable" and delegate_task returns
status=error, summary=null. After, the child initializes the provider
(agent_context "subagent", platform "subagent"), its own session fires
on_pre_compress, no CompressionCheckpointUnavailable appears, and the parent
returns the subagent's answer.

(cherry picked from commit 31af59c54ebff4c6c1861961111700b8e42dba76)
(cherry picked from commit 9bf3feaf8c98dff6e90eadf0f533204adc150a8c)
2026-11-05 19:55:33 -06:00
Victor Kyriazakos
b9e983665c fix(tools): key the tools[] freeze on generation and selection, hold flips on pin restore
Review fixes for the check_fn-verdict memo expiry.

- The between-turns freeze gate held only registered names, and only on an
  unchanged registry generation. With Tool Search on, a session built while
  its only deferrable tools were down gained tool_search / tool_describe /
  tool_call when they recovered, and a selection widened with the
  generation unchanged (adopt_late_connections against a server already
  connected in this process, refresh_plugin_sessions) had its new tools
  held. The agent now records its toolset selection next to
  _tool_snapshot_generation (agent_init and every publish), and the gate
  holds every name availability alone can add (registered tools and the
  bridge) only while both are unchanged.
- The hold decision reads the generation after the build, so a
  registration that lands during a refresh appends in that refresh.
- A rebuild from the session pin in the process that wrote it (agent-cache
  eviction, /model, a fresh agent per turn) applies the same rule: the
  pin write records (generation, selection) per session in-process, and
  restore_agent_tool_prefix holds a tool that is new only because its
  check_fn flipped. Another process has no record and appends as before.
- A list built on a grace-served True is reused for 5 s
  (_CHECK_FN_GRACE_REUSE_SECONDS), never past the grace window, instead of
  expiring at once, so a failing or timing-out probe no longer re-runs on
  every catalog read and tool_call during the 60 s grace.
2026-11-02 14:54:42 -08:00
Teknium
1c4cbb2222 Merge remote-tracking branch 'origin/main' into copilot-seams/integration 2026-10-26 00:40:32 -07:00
Teknium
49f5de617e fix(left-core): only a turn someone sees claims kept migration notices
Every AIAgent's _load_tools ran recover_at_startup(say=agent._emit_startup_warning), which claimed the
home's kept notices. Cron runs, subagents, the curator, kanban workers and background-review forks have
no notice_callback, so the notices were parked on an agent nobody watches and dropped; a cron tick
after a gateway start usually beat the user's next message.

Agent init now only runs the migration and keeps its outcomes in the home. The turn start
(deliver_kept_startup_notices) claims them when the turn has a real sink: the CLI's print sink, or a
driver's notice_callback (gateway chat, Desktop/TUI), and not for an unattended turn
(side_question_lease.is_unattended_turn: fork, cron, delegated child) or suppress_status_output.
The restart-the-gateway hint was gated on having a sink; it is now gated on not being the gateway's
own start (recover_at_startup(gateway_start=True)), so an agent-start install still carries it.
2026-10-26 00:32:14 -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
kshitijk4poor
fb4cc3bd68 refactor(agent): move the compression banner and Codex autoraise notice into a sibling
_emit_compression_summary and the once-per-profile Codex gpt-5.x autoraise
notice helpers move unchanged from agent/agent_init.py to
agent/agent_init_compression_notice.py, so the prepared-compaction flag can
land in agent_init without growing the file past its ratchet cap.
2026-10-25 22:55:11 -07:00
Hugo Alves Pereira
32a636bc8d feat(agent): opt-in prepared compaction (compression.prepare_ahead)
With compression.prepare_ahead (default false), once the provider-reported
prompt size is within 12% of the context window below the compaction
trigger, the turn loop starts a background pass before a tool batch runs
and at turn end. The pass plans the same window compress() plans and runs
the same summariser on a copy of the compressor and of the window rows.
The pass itself never rewrites the live transcript, system prompt or
prompt cache; the transcript keeps growing normally meanwhile.

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

State is per compressor and in memory only. Plugin context engines, Codex
app-server, native Responses compaction, micro-compaction and
background-review forks are not prepared. With the flag off no state is
created and compress() takes its existing path.
2026-10-25 22:55:11 -07:00
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
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
e75f6675ac fix(agent): a memory provider that is installed but fails to load says so
Agent init resolves the configured provider in one sibling: a parked
provider gets its notice and is never re-installed, an installed provider
that fails to import (a broken install, missing packages) now tells the user
external memory is off instead of only logging, and the unavailable warning
keeps its once-per-home dedup.

Co-authored-by: AIalliAI <285906080+AIalliAI@users.noreply.github.com>
Co-authored-by: Mani Saint-Victor, MD <drmani215@gmail.com>
2026-10-25 03:01:26 -07:00
Teknium
0147e44161 refactor(agent): move memory-provider startup warnings into a sibling
Offsets the agent_init.py growth from the parked-provider notice and the
config-load warnings; mark the three config-fallback handlers as reviewed.
2026-10-25 03:01:26 -07:00
Youngseok Oh
438f19ee9b fix(agent): report independent configuration-reader failures
Cover cache, reasoning echo and section reads with real initialization tests.
Preserve fallback semantics and omit exception values from diagnostics.

Zero × Youngseok Oh
2026-10-25 03:01:26 -07:00
Youngseok Oh
cfe79177a3 fix(agent): warn when agent configuration cannot be loaded 2026-10-25 03:01:26 -07:00
Teknium
ffe2f6411c fix(pm): an update that disables a plugin keeps memory.provider and retries it
When an update had to disable a plugin it also cleared memory.provider, so
the memory provider stayed lost even after the plugin was re-enabled, and
nothing ever retried the plugin: one transient failure (a TLS proxy, a mirror
outage, a since-fixed resolver bug) left it off for good.

- The dependency union now honours plugins.disabled for memory.provider the
  same way the provider loader already does, so eviction no longer has to
  blank the selection. Re-enabling the plugin brings the provider back.
- The eviction is recorded in the home's config under
  plugins.disabled_by_update (was it enabled, and why). Every later update
  retries recorded plugins after the enabled ones and undoes exactly the
  edit once a plugin fits again.
- A user's own enable/disable/remove takes the decision back: PM's selection
  publication forgets the record for the plugin the user settled, and
  `hermes plugins disable` on an update-disabled plugin now writes that.
- Spellings come from the plugin's own manifest instead of a plugin scan of
  the PM process's home, so a profile's plugins are matched in that profile.
- A parked provider is reported, not re-installed: agent init tells the
  user once why external memory is off (naming the update's reason), and
  `hermes memory status` and `hermes doctor` show it instead of "plugin not
  found" or "All checks passed". Doctor lists every update-disabled plugin.
2026-10-25 03:01:26 -07:00
Teknium
8bbf95c85b fix(tools): a one-shot resume still honours a configured clarify disable
Greptile "Disabled `clarify` returns on resume": disabled_toolsets mixes the
caller's configured disables with the automatic session gates, so stripping
every one-shot gate name to carry a pinned clarify also undid a user's explicit
`clarify` disable. The agent now keeps the configured list
(_configured_disabled_toolsets, set at load and on an explicit reload), and only
the one-shot gate's own addition is ignored when judging a carried tool.
2026-10-24 17:31:52 -07:00
Teknium
c422d69189 fix(prompt): one-shot runs drop steering, clarify and delegate live-control; skill-safety rule moves to compaction
Maintainer-approved prompt-footprint trims (measured on the Nous endpoint, anthropic/claude-opus-5.5):

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

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

Interactive tool schemas are byte-identical to main.
2026-10-24 17:31:52 -07:00
Teknium
d7094033f6 fix(oneshot): one-shot runs keep skill_manage
Maintainer ruling: a finite `hermes chat -q` / `--oneshot` / `-z` run may author
skills. Drop the one-shot strip of skill_manage (ONESHOT_HIDDEN_TOOLS /
prune_oneshot_tools) from both places that applied it: the agent's tool build
(agent/agent_init.py) and the gateway's session tool inventory
(gateway/session_local_inventory.py). The one-shot skills prompt (domain skills
only) and the delegation cap are unchanged.

Before this, the two paths disagreed in the field: a gateway-owned one-shot on an
installed build still pinned skill_manage while getting the one-shot prompt. With
no strip there is nothing left to disagree about.

Tests: the two assertions that pinned "no skill_manage in one-shot" now pin the
opposite, per the ruling; docs updated.
2026-10-24 07:12:47 -07:00
Teknium
4b6c7f68d9 feat(delegation): a session routes on the backend its delegate_task was built from
A plain /delegation save (or a config.yaml edit) now changes nothing in a running
chat: routing and schema switch together at /new or on a --now rebuild.

- agent._delegation_backend is captured with the tools (agent_init, ACP rebuild,
  refresh_agent_mcp_tools rebuilds incl. --now and compaction) and pinned with
  them to the session row; a fresh agent restoring the pin restores the backend.
- resolve_task_routes routes on it (config.yaml only for agent-less callers).
- set_global_backend(name, *, session_key, apply_now) is unchanged.
2026-10-23 00:37:14 -07:00
kshitijk4poor
310bcf444a refactor(memory): move tool-schema plumbing into agent/memory_manager_tools.py
The stall/registry work pushed agent/memory_manager.py past 1,000 lines.
The memory-provider tool-schema helpers (normalize_tool_schema,
memory_provider_tools_enabled, memory_provider_tools_exposed,
inject_memory_provider_tools) are a self-contained topic with no
dependency on MemoryManager, so they move verbatim to a
memory_manager_tools sibling and every in-tree caller imports from the
new module. agent.memory_manager is a public plugin module
(hermes_cli/plugin_validate_private_imports.py), so it re-exports the
four names, as it already does for the helpers that moved to
agent.memory_context.
2026-10-19 19:15:44 +05:30
unsupportedpastels
e948784466 fix(providers): restore a custom primary from the entry its snapshot recorded
Restoring the primary after a fallback rebuilt credential ownership from
live config.yaml, not from the config the session resolved on. Two edits
made mid-session moved it onto another account:
- alpha and beta share one URL and the session runs on custom:beta. Once
  beta's live endpoint moves, the named lookup misses, load_runtime_pool
  falls back to URL-only matching, and the session resumes on alpha's
  `hermes auth add` key.
- the session runs on custom:deepseek with a declared key_env. Once the
  declaration is removed from live config, the entry looks credential-less,
  so the built-in's env row is no longer foreign and restore swaps to
  DEEPSEEK_API_KEY and api.deepseek.com.

Both `_primary_runtime` builders (agent construction and a model switch)
now record the owning entry's provenance (`custom_entry`), matched the way
resolution matched it, in the frozen scope when one is active. The record
holds the entry's name, provider_key, base_url, key_env names and whether
it declares a credential; it never holds a secret. Restore takes the pool
key and the ownership filter from that record, so live edits can't
reassign the endpoint or drop the declaration. A named identity whose
snapshot recorded no owner, including a snapshot from an older builder,
keeps its snapshot credential instead of borrowing by URL. A genuinely bare
`custom` snapshot without a recorded owner still matches by URL, as
before.

The two builders move unchanged into agent/primary_runtime_snapshot.py, so
agent_init.py and agent_runtime_helpers.py, both over the file-size
target, shrink instead of growing. test_primary_runtime_restore's
named-pool test now builds its agent under the config it restores with,
as a real session does; built without that config, its snapshot
correctly records no owner.

Refs #140297
2026-10-17 13:29:00 -04:00
unsupportedpastels
4007e7b76f fix(memory): tell the user when a shared provider instance is dropped for their profile
When initialize_all refuses a provider instance another profile already
bound, it drops the provider, but the agent build still logged "Memory
provider '<name>' activated" and kept a manager with no external provider,
and nothing reached the user. With a singleton-style plugin, which profile
keeps its memory depends on whose message arrives first after boot.

Agent builds now call MemoryManager.initialize_for_agent, which runs
initialize_all, reports each dropped provider through the agent's startup
warning sink (as the unavailable-provider path does) and returns whether an
external provider is still served. The build logs "activated" only then;
otherwise it drops the empty manager like the not-available path. The
warning names the provider, never a home path; the check's code and the
homes stay in the log.

Refs #134889 (PLG-11)
Refs #140208
2026-10-17 13:28:18 -04:00
unsupportedpastels
dfc2cbeaa1 refactor(memory): move memory-context fencing into agent/memory_context.py
agent/memory_manager.py mixes provider fan-out, background work and the
text formatting that fences recalled memory for the model. The formatting
half (sanitize_context, StreamingContextScrubber, build_memory_context_block
and their regexes) is pure text work with no provider calls or profile
state, so it moves unchanged to its own module. Callers import it from
there; nothing in plugins/ imported it, so no re-export is kept.

The only visible difference is the logger name on the "pre-wrapped
context" warning (agent.memory_context). This leaves the manager room for
the profile-ownership checks the next commit adds without crossing its
line cap.

Refs #134889 (PLG-11)
Refs #140208
2026-10-17 13:28:18 -04:00
Teknium
e7a81e7520 fix(cli): label a callable API key by its credential source, not by "is it callable"
/config (cli.py show_config) and the agent's key banner (_print_key_banner)
printed "Microsoft Entra ID" for every callable api_key, so a custom
provider's key_cmd bearer or MiniMax OAuth read as Azure. /config also
picked Vertex out with a __module__ string compare, and the banner had no
Vertex case at all.

Each builder now tags the callable it returns with a source
(agent/credential_source.py): build_token_provider -> entra-id,
vertex_access_token -> vertex-oauth, CommandTokenSource -> key-cmd,
build_minimax_oauth_token_provider -> minimax-oauth. Both surfaces resolve
the label through one source-to-label table. An untagged callable gets the
neutral "Token provider" label. The tag is read with getattr, so no display
path calls the callable (no token minted just to mask it).

New catalog keys key_cmd_token, minimax_oauth and token_provider in every
locale (English text, matching the brand-name convention of the existing
microsoft_entra_id / google_vertex_oauth keys).

Tests: tests/agent/test_credential_source_labels.py, one red/green case per
label on each surface (7 red before: key_cmd/minimax/unknown on /config,
vertex/key_cmd/minimax/unknown on the banner). Each case's callable raises
if invoked. The old "any other callable is Entra" pin now uses a real
Entra-tagged provider.

Review finding by @unsupportedpastels on #140469
Review finding by @alt-glitch on #140469
Refs #134889 (T6)
Refs #140337
2026-10-17 07:23:06 -07:00
Teknium
848fc0ad8b fix(gateway): keep an accepted /steer across the exhaustion deferral; drop checkpoint re-exports
Follow-up to #139923 (salvage of #105100), from its review:

- When a compression-exhausted turn left a queued event, _run_agent_drain_pending returned before
  _merge_leftover_steer, so a /steer the agent had already taken out of its buffer
  (result["pending_steer"]) vanished. _defer_past_exhaustion_reset now queues it ahead of the
  deferred event, the same steer-first order as the normal path.
- conversation_compression re-exported every helper moved to conversation_compression_checkpoint.
  Internal moves get no re-export shims: callers and tests import from the new module, and the
  facade keeps only the two names it uses.
- test_total_ceiling_exhaustion_does_not_start_fallback used a 0.3 s budget; raised to the 2 s
  floor from tests/AGENTS.md.

Reported-by: greptile-apps
2026-10-16 08:38:51 -07:00
Teknium
0715474bfd Merge origin/main into feat/unified-gateway-runtime
375 commits from main (0e427d788d). 24 files conflicted; the resolutions that carry a decision:

- /initiate-setup: main removed the command (25bf722063). Its gateway rewrite, CLI handler and the
  Desktop kickoff go with main; this branch's command-layer admission of it is dropped too
  (gateway/session_commands.py _PROMPT_COMMANDS, its slash.exec test row, the parity doc row), and
  the Desktop slash dispatcher loses the `hidden` option that only the kickoff used.
- Code this branch moved out of its old file, carrying main's edits to the moved copy:
  first-contact notes (gateway/run_turn.py -> run_turn_prepare.py: no message/setup_command),
  the TUI agent factory (tui_gateway/server.py -> agent_factory.py: onboarding toolsets at build,
  setup_beat/set_theme lifecycle cards, no cli platform extras on a coding selection), the serve
  lifespan (web_server.py -> web_server_app.py standalone_lifespan: first-install probe before the
  state.db reconcile, onboarding due answer after the setup bootstrap), and the compression child
  publish (the shared _publish_compression_child_on_conn reads the parent's model_config).
- agent/auxiliary_client.py: both import changes (_route_key from main; this branch's move of
  _without_structured_output_format).
- Desktop: main's onboarding run (decideOnboarding, OnboardingEnd, card-waiting Send) replaces the
  kickoff; this branch's prepared-submission slash path, request_id on session.create and
  PreparedImageRecovery stay. Pool-limits imports are dropped (this branch removed the pool).
  createBackendSessionForSend takes main's (preview, overrides) signature.
- ci.yaml detect job: main's `ref: inputs.commit` plus this branch's sparse checkout.
- package.json / lock: main's vitest 4.1.11 plus this branch's ws 8.21.1.
- Generated: gateway-contract.openrpc.json regenerated; parity doc regenerated.
2026-10-14 05:52:49 -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
37f9a0f480 refactor: move constructor param tables and clarify copy into siblings
The code health ratchet failed on this branch: agent_init.py grew past its
main size, handleInputRequestEvent went over its complexity, and the locale
files grew by the theme picker import. The constructor param name tables
move to agent/agent_init_params.py, the clarify card copy moves to
<locale>_clarify.ts files, and theme-pick cancellation becomes a helper.
2026-10-13 23:55: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
994759f4c4 Merge origin/main (#39: 29 commits to d4d2ab7b5d) into feat/unified-gateway-runtime
No conflicts. Brings in main's reasoning-replay series, holographic memory leaving core
(run_profile_reconcile now imports it through import_provider_module), and the update
main-channel fix.
2026-10-10 23:38:42 -07:00
Teknium
336b11584c fix: replay prior reasoning to every chat-completions route that can read it
Every model reasons and intends that reasoning to be replayed, but the
chat-completions wire echoed reasoning_content only to DeepSeek/Kimi/MiMo/
Ollama (plus a hardcoded Portal stealth model) and reasoning_details only to
OpenRouter; turn_context popped `reasoning` everywhere, so Ollama's /v1
(reads only `reasoning`) never saw any.

- message_sanitization owns one route->carrier table
  (_REASONING_CARRIER_ROUTES): strict schemas (Mistral, Groq, Cerebras,
  SambaNova) get nothing, Fireworks reasoning_content only, OpenRouter-format
  gateways (OpenRouter, Kilo, Vercel AI Gateway, Nous Portal) all three,
  Novita/MiniMax /v1/TokenHub + reasoning_details, local/Ollama/Upstage +
  reasoning, everyone else reasoning_content.
- The " " pad stays limited to the must-echo tier (DeepSeek, Kimi, MiMo);
  Ollama leaves it (no echo requirement) and the stealth hardcode is gone.
- Reactive recovery: a 4xx unknown-field rejection that NAMES a reasoning
  key this request carried is recorded per (provider, host, model) and the
  retry re-shapes api_messages without it. Generic upstream errors never
  count; a recorded key falls through, so no loop. History is untouched.
- Nous Portal reads reasoning_details again: the #118182 "replay budget"
  does not exist in the Portal and does not reproduce live.
- Gemini thought_signature survives on Gemini hosts/providers even when the
  model id is an alias.
- Vendor keep-reasoning flags (docs-only): GLM thinking.clear_thinking=false,
  DashScope preserve_thinking / clear_thinking, Kimi K2.x thinking.keep=all.
- stale_thinking_reaches_wire follows the same table, so compaction trigger
  and tail walks agree with what is sent.
2026-10-10 19:22:07 -07:00
Teknium
408cc0d12e Merge origin/main (#32: 36 commits to cf23a1a5cc) into feat/unified-gateway-runtime
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); 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). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
2026-10-09 10:24:04 -07:00
Maciej Lisiewski
2ff58849f4 ci: ruff UP037 fixes 2026-10-09 17:34:38 +02: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
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
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
b4e436c115 ci: don't cast int to int 2026-10-08 19:28:23 +02:00