Two per-call WARNING surfaces were still outside the warn-once reporter:
- agent/plugin_stream_hooks.py::_worker — the on_stream_start/on_stream_delta/
on_stream_end consumer, which fires once per streaming delta (far more often than
per tool call). A mis-declared callback (signature naming tool_data) logged
"Hook ... raised" at WARNING on every delta: 20 deltas -> 20 WARNING lines.
- hermes_cli/plugins_dispatch.py::_deliver_event — plugin event subscribers that
raise identically were warned on every emit.
Both now go through PluginManager._report_hook_failure (keyed by module/qualname,
cleared on unload): the first failure warns and names the fields the hook/event
provides, identical repeats are DEBUG. Skip-and-continue semantics are unchanged.
Part of #111922
Review follow-up on the sibling refresher path (_refresh_oauth_token), which
the PR title already claimed but only the pool path delivered:
- A refresh token the endpoint rejected terminally (invalid_grant etc.) is
fingerprinted in a process-local set; later attempts skip the POST and log
at DEBUG instead of replaying the dead token and re-firing the WARNING on
every resolve. A rotated token (user re-logs into Claude Code) has a new
fingerprint and is tried normally.
- claude_code_credentials_path() honours CLAUDE_CONFIG_DIR (blank = unset,
same rule as hermes_cli.foreign_sessions), so the opt-out the PR body
documents actually exists and matches the Claude CLI's own relocation.
- The three remaining 're-run claude setup-token' hints inside the refresher
now say 'hermes auth add anthropic' like the rest of the PR; setup-token
does not repair the Claude Code file anyway.
A terminally rejected refresh token (invalid_grant / invalid_token /
refresh_token_reused) is the moment a login is lost. Three gaps remained
after #113197 (which added the WARNING for Codex/xAI/Nous):
- Anthropic: the token endpoint's HTTPError carried no classifiable code,
so a dead Anthropic / Claude Code grant fell through to a transient
'exhausted' bench at DEBUG and was replayed every hour. The endpoint
error is now a structured AnthropicOAuthError (status + OAuth error
code); _recover_failed_refresh logs one WARNING with the repair command
and marks the row DEAD. A dead grant is not replayed at the fallback
endpoint. The auxiliary Claude Code refresher (sibling path) warns the
same way. Claude Code's own credentials file is never touched.
- Codex/xAI/Nous: _quarantine_sources drops only singleton-seeded rows, so
an independent `hermes auth add` (manual:*) login survived unmarked and
re-fired the WARNING on every later refresh attempt. The survivor is now
marked DEAD (leaves rotation until a write-side re-auth clears it).
- Hints on live Hermes paths (anthropic 401 troubleshooting block, the
no-credentials error) recommended an external CLI's login command,
which cannot repair Hermes' own login; they now say
`hermes auth add anthropic` / `hermes auth list anthropic`.
Docs: credential-pools.md documents the dead-login behaviour.
Part of #113023.
A first stalled summary stream keeps today's behaviour: the transcript is left
alone, the stall-class cooldown (floored at the idle window) is armed and the
LLM route retries after it lapses. When the route stalls AGAIN while a
stall-class failure is still on the ladder, the stall retry ladder now ends
with a deterministic rung: the worker is re-run with the summary LLM skipped
(DETERMINISTIC_SUMMARY_ROUTE pin, consumed in _summarize_window) and
compress() commits its static fallback summary through the ordinary
lease/fence/watermark pipeline — the same degrade a failed summary call gets
(abort_on_summary_failure still aborts).
WHY: after "made no progress … continuing without compression" the context
stays oversized, so the next turn after the cooldown re-enters the same silent
stream and burns another full idle window; the reporter saw this every ~2 min
for hours (#112420). A route that has proven unhealthy twice must degrade once
instead of looping. The prune-on-stall hunk from #112504 was declined because
it committed outside the lease/fence; this rung reuses the same-turn fallback
worker (bypass_cooldown) and the commit path the fallback_chain retry already
uses, so no new commit surface is introduced.
Also: a pinned fallback_chain route whose summary call FAILS still commits the
static fallback summary (default abort_on_summary_failure=false); the host log
said "recovered on fallback_chain[0]" for that. It now logs "committed a
deterministic fallback summary on …" at WARNING (#112387 review caveat), keyed
on the post-commit fallback_compression_streak bump.
Docs: developer-guide failure-cooldown section + agent/AGENTS.md.
A keyless `provider: ollama|vllm|llamacpp` aux lane ran through the anonymous
`custom` key chain, so with OPENAI_API_KEY in the environment (or a main key on
the same host) the lane sent that secret as `Authorization: Bearer` to whatever
host `base_url` named. The alias means "this is my own server": only an explicit
`api_key` or the `no-key-required` placeholder is ever sent. `provider: custom`
keeps its documented OPENAI_BASE_URL + OPENAI_API_KEY contract.
Review follow-up on #113961; extends the existing parametrized invariant with the
OPENAI_API_KEY-set case (red on the previous head).
Follow-up to the cherry-picked #106018 (@liuhao1024). The alias-table fix resolved the
keyless lane, but the reporter's second variant (provider: ollama + bare base_url +
explicit api_key → 404) still failed through the real config path:
_resolve_task_provider_model collapses "base_url + api_key" lanes to "custom" before
resolve_provider_client runs, so the custom branch never saw the ollama alias and
skipped the /v1 tail. Keep the local-server alias identity on both base_url paths
(config lane and explicit kwargs via _preserve_provider_with_base_url) so the tail
applies whenever the user wrote provider: ollama/vllm/llamacpp.
Shape: inline the 5-line _bare_host_base_url helper (urlparse never raises on str;
no new facade helper), trim the five contributor tests to two invariants that drive
the reporter's lane through _resolve_task_provider_model, and document the alias
group under the auxiliary provider list.
Live: stand-in mirroring Ollama's /v1 OpenAI-compatible surface — before: RuntimeError
"no API key was found" (keyless) / 404 on /chat/completions (explicit key); after: both
POST /v1/chat/completions and return OK, sync and async; provider: custom + /v1 unchanged.
An auxiliary lane with an explicit `provider: ollama` + local base_url + empty
api_key kept the ollama identity, matched no PROVIDER_REGISTRY entry (the aux-side
alias table lacks the local-server alias group hermes_cli.auth has), and raised
"Provider 'ollama' is set in config.yaml but no API key was found" on every call
(#106010) — while `provider: custom` against the same server worked.
- Mirror the hermes_cli.auth local-server alias group (ollama/vllm/llamacpp/
llama.cpp → custom) in the aux-side _PROVIDER_ALIASES.
- Append the /v1 tail to bare host base_urls coming through those aliases: the
OpenAI-compatible surface of these servers lives under /v1, so without it the
first call 404s on the native API.
Fixes#106010
Review follow-up. The vision capability gate in _try_main_agent_model_fallback
said "main agent model %s" but formatted main_provider, so operators reading
the INFO line would take a provider name for a model name. Reword to "main
agent provider" and keep logging only the provider, matching the sibling
_vision_main_provider_client (model names can trip the clear-text-logging
scanner).
test_upstream_capacity_429_is_not_a_credential_to_bench only checked the
_is_overloaded_error predicate, so a regression that re-added the pool
rotation for a capacity 429 would still have passed. Parametrize it over a
capacity 429 (must not call pool.mark_exhausted_and_rotate) and a plain
per-key "rate limit exceeded" 429 (must rotate) against a stub pool routed
through _recover_provider_pool. Verified red by temporarily dropping the
`not _is_overloaded_error` guard: the capacity case fails.
Three auxiliary error-classification defects with one shared cause: the aux
ladder kept its own copies of the classifier's phrase tables and its own
fixed log wording, and they drifted.
- `_PAYMENT_KEYWORDS` is now `error_classifier._BILLING_PATTERNS` plus the
aux-only phrasings, and `_BILLING_PATTERNS` gains OpenRouter's org cap
"budget limit exceeded". A 403 "Budget limit exceeded (monthly limit)" (or
"Key limit exceeded") is billing for the main loop AND a payment error for
the aux ladder, so compression/title/vision fall through to the configured
fallback instead of raising while the main model is served elsewhere.
- `_mark_provider_unhealthy` takes the caller's reason and level; the skip
line echoes it. Absent credentials (no OPENROUTER_API_KEY, no Nous auth)
are DEBUG with the real reason; the confirmed-402 rungs keep the WARNING
payment wording. Local-only users no longer read "payment / credit error"
for providers they never configured.
- `_try_main_agent_model_fallback` applies the auto-route's vision capability
gate, so a transient 429 on the pinned vision lane no longer hands an image
to a text-only main model (guaranteed 400 "content.type is invalid").
`_recover_provider_pool` no longer benches a pool entry on an
upstream-capacity 429 ("at capacity", same `_OVERLOADED_PATTERNS` table).
Fixes#107166, #64144, #108349.
Co-authored-by: KoNit-K <124019182+KoNit-K@users.noreply.github.com>
Co-authored-by: awizemann <319078+awizemann@users.noreply.github.com>
Co-authored-by: kokhlo <47825603+kokhlo@users.noreply.github.com>
Issue #112649 atom 4: a core (`_HERMES_CORE_TOOLS`) tool whose check_fn returns
False leaves neither the schema nor the tool_search catalog (it is not
deferrable), so the model's "no such tool" is accurate and nothing in the log
points at the probe. ae5666f7fc made the False verdict INFO for optional,
unconfigured toolsets — that stays; the core-tool drop is now a WARNING that
names the dropped tool(s), once per probe per process (the 30 s TTL re-probe
would otherwise re-warn every turn), reset by invalidate_check_fn_cache().
Review minor: `catalog_provider: deepsek` was accepted silently and the typo
leaked into ModelInfo.provider_id. An alias that is neither a Hermes provider
id nor a models.dev id (loaded catalog, no network) now warns once, mirroring
the unknown-key warning, and the row keeps its own slug.
A metadata-only model_overrides entry on a custom provider (only context_window set) took the
unknown-model branch of get_model_capabilities and reported max_output_tokens=8192 from the
_UNKNOWN_MODEL_BASE template; /model info showed "Max output: 8,192 tokens" for a model nobody
knows. The output limit is now left unknown (ModelCapabilities.max_output_tokens=None,
ModelInfo.max_output=0), matching the fail-open treatment #113146 gave supports_vision and
supports_reasoning. Consumers already handle a missing value: the dashboard only renders a
positive limit and the /model card only prints a truthy max_output.
There was also no way for a custom provider that resells a catalogued vendor's models (a
gateway/proxy) to reach _BUILTIN_MODEL_METADATA or the models.dev catalog, which is what forced
the metadata-only override in the first place. providers.<name>.catalog_provider (also honoured
on legacy custom_providers[] rows) names that vendor; models_dev resolves the catalog id through
it for capabilities, context, model info and provider info. It affects metadata lookups only,
never routing or credentials, and an explicit model_overrides entry still wins.
Closes the remaining atoms of #112649 (docs: providers page).
A reasoning-only clean stop with tools offered and zero tool calls whose
reasoning ENDS on a first-person plan ("Let me batch the terminal calls and
run them in parallel.", "I need to check the log.") was promoted to the
final answer: the turn reported "complete" while the model had done nothing,
masking a stalled model and aborting multi-step tool loops (#111761,
KushBeaverTTV / Iman-Sharif). The existing stall-guard tail detector only
matched "let me now" / "I'll now" / "next, I" and caps at 400 chars, so these
verbatim tails sailed through.
Add promoted_reasoning_announces_action(): a broader, tail-only first-person
plan detector applied ONLY on the promoted-reasoning path (content empty,
tools offered, no tool call). It feeds the SAME stall-guard continuation
(interim row with api_content sidecar + nudge) under the SAME 2-continuation
cap, so a model that never acts still ends after two nudges. Visible-content
replies keep the narrow trailing_continue_intent() shape, and reasoning that
states an answer ("The answer is 42.", plan-then-answer) still promotes on
the first call.
Part of #111761
`_resolve_named_custom_branch` lifted a `providers:` entry's `extra_headers`
onto both OpenAI-wire clients but built the anthropic_messages client without
them, so a gateway that needs a header on an Anthropic-style relay still
dropped it on aux calls. `with_options(default_headers=...)` merges the entry
headers onto the beta / credential-Omit headers the builder installs, so the
one-credential invariant is unchanged.
Review follow-up on #113969; the existing anthropic_messages named-custom test
now asserts the header (red on the previous head).
An `auxiliary.<task>.provider` pinned to a bare-named `providers:` entry with
`key_cmd` sent every async aux request (async_call_llm, async vision, the
async fallback ladder) with NO Authorization header: the OpenAI SDK parks a
callable api_key in `_api_key_provider` and leaves `.api_key` == "", and
`_to_async_client` rebuilt AsyncOpenAI from that empty snapshot alone, so the
SDK's auth_headers came back empty. The entry's `extra_headers` were never
lifted onto the aux client at all (sync or async), unlike the main runtime.
- agent/auxiliary_async_rebuild.py: carry the sync client's token provider
(wrapped for await, run off-loop) and its configured default_headers onto
the async twin.
- _to_async_client uses both; covers the primary async route and every
fallback-candidate rebuild.
- _resolve_named_custom_branch lifts the entry's extra_headers onto the
OpenAI-wire client (both call sites).
key_env (static string) was not affected on main; key_cmd was.
Fixes#109595
Salvages #109626
Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
Review follow-up on #113790. _pool_credential_digest hashed every pool
entry, so rotating a sibling account's token churned the cached client of
the selected, unchanged entry (multi-account pools rebuilt every aux client
on every account's refresh). Digest only the peeked entry's key when peek()
names one; keep the all-entries digest solely for the '<provider>::'
cooldown case so a rotation during a per-model cooldown still changes the
key (#113022 point 5).
Also migrate the six remaining literal 7-tuple cache keys in
test_async_httpx_del_neuter.py to _client_cache_key() so no test encodes
the positional key layout, as the PR body claims.
The pool cache hint keyed cached auxiliary clients by `<provider>:<entry id>` only. The entry
id survives a token rotation/refresh, so a long-running gateway kept serving the client built
with the old (revoked) OAuth token after a short-lived process refreshed the shared grant, and
every compression first died with a 401 before the fallback chain served it (#113022 points
1/2). When a per-model cooldown hid the only entry from peek(), the hint degraded to "" and
could not distinguish a rotation at all (point 5).
The hint now carries a blake2b digest over the runtime keys of ALL pool entries, taken without
availability filters: `<provider>:<entry id>:<digest>`, or `<provider>::<digest>` when peek()
returns nothing but keyed entries exist. A rotated token changes the digest, the next call
builds a fresh client from the new credentials, and the stale entry retires through the
existing non-closing FIFO cap. Only the digest enters the key; the secret never does.
_peek_pool_entry accepts an already-loaded pool so the hint costs a single disk read.
tests/agent/test_async_httpx_del_neuter.py no longer seeds the pre-multiplex 7-tuple layout;
keys are built via _client_cache_key so no test encodes the positional layout.
Live probe (temp HERMES_HOME, one OAuth entry, token rotated on disk between two builds):
before: anthropic/openai-codex sync+async all returned the SAME client with the old token,
cooldown hint '' -> ''. after: NEW client with the new token in all four cases, cooldown hint
anthropic::<digest-a> -> anthropic::<digest-b>, unchanged token still a cache hit.
Fixes#113022
A title request against a slow local model (a reasoning model on modest
hardware) hit `auxiliary.title_generation.timeout`, was retried on the same
provider twice more with backoff, and only then fell back — roughly four
configured windows, exactly the 3x30s the reporter read off the Ollama access
log — while the auto-title thread outlived the deadline the user thought they
had set. The failure was logged at INFO as a "connection error", the same
label as an unreachable endpoint, so the only WARNING the operator saw came
from the fallback provider complaining about a model it never had, which reads
as "your base_url was ignored".
Title generation joins compression and vision in the existing
critical-path rung that skips the same-provider retry after a full-budget
timeout, and the fallback ladder now classifies a timeout before the
connection-error rung and logs it at WARNING with the endpoint, the budget
and the config key to raise. The route carries its effective timeout so the
message can say how long it waited. Docs list the title default and the
one-window rule.
Slim redo of the retry/fallback half of #100013 on the existing rung; its
10s default and concurrency change are not carried.
Fixes#89445
Part of #66251
Co-authored-by: AJ Fasano <ajfasano@gmail.com>
The api.x.ai host row mapped every auto-routed api.x.ai client to
xai-oauth, including an aux client the auto route had tagged with the
API-key `xai` backend (XAI_API_KEY). A 401/403 on that key then ran the
xai-oauth refresher: with a stale grant on disk the refresh rotation was
spent and the retry silently switched the call onto xai-oauth.
`_auth_refresh_provider_for_route` now takes the client's effective
provider (already recorded on auto clients) and skips the host row when
that provider is the row's API-key sibling; the ladder passes it through.
The auto/oauth path that #84845 fixed is unchanged.
An auxiliary call_llm() with no provider override (plugin hooks, title/compression on a
gateway whose main provider is xai-oauth) reaches the recovery ladder as resolved_provider
"auto". _auth_refresh_provider_for_route infers the concrete backend from the client host,
but _AUTH_REFRESH_PROVIDER_BY_HOST had no api.x.ai row, so the refresh rung was skipped
and the pool rung marked the single device_code grant exhausted and walked to fallbacks
that were never configured. The main agent loop refreshed the same token a second later.
Adding the host row lets the existing rung refresh, evict the "auto"-labelled cached client
and retry once on xai-oauth before any fallback. Live against a stand-in replaying xAI's
documented 403 body: before 403 -> pool exhausted -> re-raised; after 403 -> refresh POST
-> retry with the new bearer -> 200.
Fixes#84845
Co-authored-by: andyylin <51783311+andyylin@users.noreply.github.com>
`_try_nous()` resolves Nous runtime credentials on every auto-route discovery
walk before it checks stored auth, so users who never logged into Nous Portal
got a new "Auxiliary Nous client unavailable: ... not logged into Nous Portal.
Run `hermes model`" WARNING on every pass, on top of the ladder's existing
"no Nous authentication found" summary. record_nous_credential_failure now
logs at WARNING only when a credential exists that failed (a coded AuthError
such as invalid_grant / a quarantine marker, or persisted Nous auth state)
and at DEBUG for the uncoded never-logged-in case. The detail is still
remembered either way so the goal judge keeps naming the cause (#42177).
Also sentence-terminate the AuthError message before format_auth_error
appends the remediation ("Invalid refresh token. Run `hermes model`..."
instead of "Invalid refresh token Run ..."), and assert the contract (code +
remediation present) instead of the literal string in the test.
With auxiliary.goal_judge.provider pinned to nous and a dead refresh token
(invalid_grant), the status line read "judge error: RuntimeError": the ladder's
_resolve_nous_runtime_api swallowed the resolver's AuthError at DEBUG and the
generic "no API key" RuntimeError was reduced to its type name by judge_goal.
Users were sent to context-length / model debugging instead of `hermes model`.
Now the failure is remembered in agent/auxiliary_unavailable.py (one WARNING per
distinct message, preferring the persisted quarantine marker because the pool
rung wipes the dead tokens before the auth-store resolver runs), the ladder
raises AuxiliaryClientUnavailable carrying that detail for provider=nous, and
judge_goal maps it to
"goal_judge auxiliary client unavailable: Nous Portal runtime credentials
unavailable: Invalid refresh token. Run `hermes model` to re-authenticate.
(code: invalid_grant)" while still failing open with the same 5-tuple contract.
Slim redo of #42179 for the current call_llm-based judge_goal.
Fixes#42177
Co-authored-by: Harry Riddle <ntconguit@gmail.com>
The per-action schema made the delete branch `additionalProperties: false`
with no `absorbed_into`, so a schema-validating or grammar-constrained
backend could no longer emit the curator's consolidation delete and
`_curator_consolidation_delete_guard` fail-closed every consolidation.
Advertise `absorbed_into` on the delete branch and cover the batch path
that forwards it to the guard.
Also fold the two remaining patch shape checks (missing new_string,
content mixed with old_string/new_string) into `_op_shape_error`, so a
batch rejects them before applying any sibling instead of creating op[0]
and rolling it back. Drop the stale `edit` vocabulary from skills.md:440
and the curator prompt, and move the schema-diet test helpers above the
`__main__` guard.
_concat_content joined two string user contents into one "a\nb" string when
_merge_consecutive_roles collapsed adjacent user turns for the Anthropic
Messages wire. For a MoA aggregator on that wire, iteration 1 of a turn ends
[user(task), user(guidance)] and was sent as user("task\n<guidance>"), while
iteration 2 replays user("task") alone, so the prompt-cache prefix diverged
at the first user block and the #112358 collapse persisted there (the
first-pass fix in #113175 only covered the OpenAI-compatible wire).
Merged turns are now always a block list with each side's blocks intact (a
string becomes one text block), matching what the list+list and list+str
shapes already did. The task block is byte-identical to the standalone turn
later iterations replay, a cache_control marker on it stays put, and the
guidance follows as its own text block. Assistant merges are unaffected
(assistant content is already a block list).
Bedrock Converse and native Gemini already merge at block/part granularity,
so the docs' Anthropic/Converse/Gemini fold caveat is replaced with the
accurate statement and the byte-identical-extension claim no longer needs
the OpenAI-compatible scope.
Part of #112358
The rung table refused to re-send an unchanged request, but the Codex Responses
route translates the caller cap away and gateways inject their own: the 400 names
max_tokens while the kwargs show none, and the identical retry is what completes
(tests/agent/test_injected_param_strip_retry_registry.py, red in CI on 99ff3b9).
The pre-ladder max_tokens rung accepted payment|connection|rate_limit errors on
its retry, so a 429 after a stripped retry reached the credential and
provider-fallback rungs. The ladder's shared `_param_rung_accepts` dropped
rate_limit: a 429 on the retry raised out of the primary call and skipped the
whole fallback chain. Accept it there too, with a rung-level test that the
stripped kwargs and the 429 are handed on rather than raised.
The body claimed `Fixes #109774` while the aux client still sent the generic
`extra_body.reasoning` to Fireworks on every call and only recovered
reactively (an extra 400 round-trip per request). Port @huklaa's profile
override from #109807: Fireworks documents top-level `reasoning_effort`
(`none` disables thinking), and overriding `build_api_kwargs_extras` marks the
profile reasoning-aware so the transport omits the generic fallback on this
route. Extends the salvage with the effort mapping so enabled-with-effort takes
the same wire, with a control that a profile-less route keeps the fallback.
Salvages #109807 (@huklaa).
Co-authored-by: Hukla <129692708+huklaa@users.noreply.github.com>
base_info is the endpoint identity every rung reads for per-route bookkeeping; the
fallback ladder left it empty. The test mirrored the positional construction that
broke under a wider tuple.
A positional _LadderRoute(...) in auxiliary_fallback_recovery breaks as soon as the
route tuple gains a field (#113968 adds timeout); construct by name so fields the
parameter ladder never reads default to None regardless of tuple width.
Reasoning models reject several request fields at once (gpt-5: temperature AND
max_tokens, #78273), a reasoning-strip retry can then 400 on temperature
(#72351), and strict-schema gateways such as Fireworks reject the generic
extra_body.reasoning fallback with "Extra inputs are not permitted, field:
'reasoning'" (#109774) — a phrasing none of the unsupported-parameter predicates
recognised, so the reasoning rung never fired and every title call 400'd.
The parameter rungs were a fixed single-pass order (temperature → structured
output → reasoning → max_tokens): a field rejected AFTER an earlier rung had
already run was never stripped, and _param_rung_accepts did not admit a
temperature 400 raised by a later retry. They now form a table walked until no
rung matches, each field stripped at most once, so N rejected fields recover in
N retries in whatever order the provider raises them.
Fallback candidates (per-task chain, main chain, discovery) got a single shot
with the caller's temperature/max_tokens/reasoning fields and raised on the
first parameter 400; agent/auxiliary_fallback_recovery.py now runs the same
parameter rungs around a candidate's request (sync + async), leaving auth /
payment / connection errors to the caller's existing handling.
Live: real gpt-5-mini title_generation call (reasoning_effort 400 → temperature
400 → 200), real gpt-5-mini fallback candidate sync+async (temperature 400 →
200), and a stand-in replaying Fireworks' documented 400 (reasoning stripped →
200) — all failed on origin/main.
Title generation hardcoded temperature=0.3 in its call_llm() call.
Models like GPT-5.6 only accept their server-side default temperature
and reject explicit values with "Unsupported value: 'temperature'".
While call_llm() has a retry that strips temperature on error, the
daemon thread races with session cleanup in short-lived CLI sessions,
causing the retry to fail with a connection error.
Fix: pass temperature=None so the provider uses its own default. This
avoids the unsupported-temperature error entirely and eliminates the
need for the retry path.
Fixes#72351
The gate also sat inside `generate_title`, so the explicit operator repair
command `hermes sessions retitle-skills` returned None for every row when the
toggle was off, although the operator asked for a model call. The toggle's
contract is "never spend a model call upgrading the instant title": only
`maybe_auto_title` (the background path) is gated now; a direct
`generate_title` call still asks the model. Docs sentence adjusted.
Review follow-up on #113955; the existing toggle test now also asserts the
explicit path still titles (red on the previous head).
`auxiliary.title_generation.enabled: false` turned off both title stages, so an
operator who only wanted to stop the background model call (unavailable or
metered endpoint) also lost the instant derived title. `model_upgrade_enabled:
false` keeps the derived title and starts no `auto-title` thread; missing keeps
the two-stage default and `enabled: false` still disables both.
Salvaged from #85401 onto current main: the gate reuses `_title_config()` and
sits before `spawn_context_thread` (the thread seam moved off `threading.Thread`).
The memo had its own (mtime_ns, size, inode, device) tuple and documented a
same-length/same-inode/pinned-mtime rewrite as an accepted gap. utils.file_signature is the
repo's change-detection key (config.load_env, skill_utils, prompt_builder already use it) and
includes ctime_ns, which user space cannot backdate — so the gap closes and one helper goes.
load_env_file() is now the canonical .env tokenizer after c849bc383a collapsed
six hand parsers onto it. Profile scopes, dashboard boundary discovery, skill
secret capture, managed .env and setup readers share the same decoding and
parsing rules, but direct calls still re-read and re-parse the whole file.
build_profile_secret_scope() puts that work on the gateway's hottest paths:
every turn, every cron job, MCP and browser lifecycle adoption, the TUI prompt
turn, and the 60s housekeeping drain of the durable cron delivery queue.
Memoising the shared tokenizer now removes redundant work for the consolidated
readers as well as the motivating profile-scope path.
config.load_env() keeps its existing outer memo over a call that is now itself
memoised; this leaves its menu-render shortcut intact without redesigning it.
Freshness is the hard part, because a stale credential map is a far worse
failure than a slow one. Every load_env_file() call still OPENS the file and
keys on os.fstat() of that descriptor rather than os.stat() of the path:
* the open preserves close-to-open revalidation on NFS;
* an open or read failure returns {} without caching it, and drops any warm
entry so a transient EACCES cannot become a persistent empty profile;
* the descriptor pins one inode, so a symlink repointed mid-read cannot file
one file's contents under another file's identity.
The key is (mtime_ns, size, inode, device), re-checked on the same descriptor
after reading. A rewrite through that inode is not stored under the pre-read
fingerprint. Unavailable metadata means "do not cache", never "cannot read".
A generation counter checked under the lock prevents a slow reader from
repopulating an entry that a writer invalidated while the read was in flight.
Read bytes from the open descriptor and preserve upstream's decoding exactly:
strip a UTF-8 BOM before trying UTF-8, then fall back to latin-1 for invalid
UTF-8. Both the cached reader and the uncached reference use that decoder and
the shared text parser. Invalid UTF-8 is a cacheable result, not a read error.
The value and inline-comment helpers remain local to secret_scope.
invalidate_env_cache() clears this memo too, so save_env_value,
remove_env_value and sanitize_env_file invalidate both layers. The per-path
LRU holds at most 64 entries and every caller gets its own dict.
Accepted limitation: a write keeping length, inode and nanosecond mtime all
identical is not detected without explicit invalidation. This is a new
limitation for previously uncached readers. Parsed secrets also remain
reachable in memory between use and eviction for up to 64 paths, where the
outer config memo holds one.
The pre-rebase measurement on a 508-line, 25432-byte .env was 0.868 ms ->
0.011 ms per call. That measurement predates the shared binary decoder.
Add decode/cache invariants for BOM and plain files, latin-1 fallback,
same-size writes switching UTF-8 -> latin-1 -> UTF-8, and agreement with the
uncached reference. All eight decoding, cache and freshness mutations fail
the new tests, and all 40 cache tests pass after restoration.
The requested agent, CLI, cron and gateway suites report 30,168 passed,
479 failed and 303 skipped in the restricted local environment. All 140
failing files were checked against upstream/main at 5eb99eb284: all 479
failed-test IDs and 210 collection/setup/teardown error IDs match exactly.
Upstage /v1/models carries no context field, so Solar ids resolve through
DEFAULT_CONTEXT_LENGTHS, whose keys are substring matches. solar-mini4 hit
the legacy solar-mini key (32K, below the 64K minimum), so the agent refused
to start; solar-pro4 matched nothing and got the 256K fallback. The same
substring deny-list in the Upstage profile also treated solar-mini4 as
non-reasoning, silently dropping reasoning_effort for a model that reasons.
Solar keys now match only on an id boundary (key followed by end or one of
"-:.@"), after folding aggregator slugs such as solar-pro-3 into the native
solar-pro3. Legacy keys keep covering their dated, quant and variant ids
(solar-mini-250422, solar-pro3@q4) but not later generations. A "solar-"
family key gives Solar lineup ids (bare name "solar-<letter>...", org/
prefix allowed) 524288 tokens, per Upstage /v1/solar/models max_model_len;
open-weight ids like solar-10.7b-instruct keep the generic fallback, and an
explicit key still wins by longest-key-first order. The boundary-matched
prefixes are a module constant, so non-Solar keys are unchanged.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`_image_payload` ran `json.dumps` over every image part on every request (pass runs on
each API call, before the HTTP client serializes the same bytes again). Measured per
request on the send-path clone, 20 images:
per image json.dumps len(data)
256 KB 50 ms 0.02 ms
1 MB 226 ms 0.01 ms
5 MB ~1.0 s 0.03 ms
origin/main's keep-3 walk was 0.4 ms. The image payload is ASCII base64, so the data-URL
(or Anthropic `source.data`) length is the byte count within ~17 bytes of JSON framing
per part — noise against a 24 MB budget with 8 MB of headroom.
The floor cut-back (`step > total - floor` -> `step = total - floor`) fires whenever an
eight-carrier batch is wider than the fit window: tool results carrying several images,
or user uploads filling most of the ceiling. `total - floor` tracks the total, so the
retire count stopped being a step function and the frontier moved on every turn again —
the per-image prefix rewrite this policy exists to prevent.
Replay over 24 turns (prefix collapses; issue #113517 script):
carrier shape before after
1 image / tool_result 2 2
2 images / tool_result 3 3
3 images / tool_result 13 7
4 images / tool_result 16 11
15 uploads + 1 / tool_result 15 10
The quantum is now `min(batch, window - floor)` where `window` is how many newest
carriers fit. Each advance keeps at least `floor + 1` frames, so the cut-back clause is
gone; holding for `window - floor` turns per advance is the most the floor allows. The
one-image case (#113517's report) is unchanged: 21/29/37 -> 8/16/24 retired.
Regression test: test_frontier_holds_when_tool_results_carry_several_images — red on
the previous loop shape, green here.
The compressor pass and the Anthropic wire pass each carried their own copy of the
limit/batch/floor constants (under different names) and of the retire-count loop.
Retuning one alone would make the wire pass re-evict on a second frontier after the
compressor pass — the exact prefix-rewrite class #113517 fixes.
- agent/image_eviction_policy.py: stdlib-only leaf holding the constants and
outbound_image_retire_count(); the wire converter stays a leaf (no compaction import).
- evict_stale_outbound_tool_images loses `keep_newest`: no caller passed it, and its
default was the COMPACTION window constant the comments say the send path must not use.
- _retire_stale_tool_result_images (compaction) back to its main body; behaviour was
unchanged, so the rewrite was churn.
- One `_tool_result_parts` unwrap instead of three copies; one `_image_payload` walk
per message instead of two.
- Wire pass counts blocks via `_block_type` (non-dict inner blocks no longer raise).
Tests import the constants from the policy module; the two "stops at the floor" tests
assert the invariant (newest floor survives, request under the limit) instead of the
exact frontier. test_user_uploads_are_not_evicted now builds a request that actually
trips eviction — at 6 blocks it never fired and proved nothing.
Both eviction passes retire the oldest image-bearing tool results in whole
batches (8) and let the floor shelter a breach only when reserved uploads alone
exceed the ceiling. When uploads fill most of the ceiling without exceeding it,
the first batch step overshoots past the newest frames: fifteen uploads plus six
one-frame tool results retired all six (the model blind on the frame it had just
asked for) although keeping the newest three already clears the 20-block limit.
The batch step is now cut back to `total - floor` when it would cross the floor
and keeping the floor fits; a floor that does not fit (one 25-block tool_result,
byte pressure) still retires past it, and uploads alone over the ceiling still
shelter the floor. Pure-screenshot sessions are unchanged: same batch-aligned
frontier at 21/29/37 images.
Review-fix on #113519 (found while checking @ehz0ah's mixed-session boundary on
the sibling PR #113619).
267d42b3 made the compressor pass shelter the keep-newest floor only when
retiring every tool image still cannot bring the request inside the ceiling.
The Anthropic wire pass (_evict_old_screenshots) kept the unconditional
`len(carriers) - _MAX_KEEP_SCREENSHOTS` floor, so a single tool_result
carrying 25 image blocks retired nothing there. The compressor pass masks it
on the main loop, but auxiliary_wire.py reaches convert_messages_to_anthropic
without that pass, so the wire pass has to hold the invariant on its own.
Mirror the rule: when reserved uploads alone fit the ceiling the breach is
fixable and every carrier is retireable; only reserved uploads over the
ceiling keep the floor. One invariant test, red on 267d42b3.
Three residual witnesses from review on this branch and #113619.
W1 (@ehz0ah): reserved user uploads were counted against the BLOCK ceiling but
not against the byte budget, so five 5 MB uploads plus three 3 MB tool images
serialized to 34.0 MB against Anthropic's 32 MB Messages limit and eviction
returned pruned=0. The API answers 413 request_too_large.
W2/W3 (@andrexibiza, @teknium1): the floor applied unconditionally, so it
sheltered breaches the tool content itself caused. One tool_result carrying 25
image blocks left retire=0 because only one carrier existed against a floor of
three; four 10-block results retired one and kept 30 blocks.
Reserve upload bytes alongside blocks, and make the floor conditional on
satisfiability: it shelters a violation only when retiring every removable tool
image still cannot bring the request inside the ceiling, and never when bytes
are the breach, since the request-size limit is hard. Uploads are still never
rewritten, and the unsatisfiable case still keeps the newest frames.
W1 34.0 MB -> 25.0 MB, pruned=3
W2 25 blocks -> 0, pruned=1
W3 40 blocks -> 0, pruned=4
floor intact: 21 uploads + 5 screenshots keeps 3
Ref: https://platform.claude.com/docs/en/api/overview#request-size-limits
Parallel tool calls land as sibling tool_result blocks inside one user
message, oldest first. The outer walk is newest-first but the inner walk
was forward, so a batch boundary that fell inside a message retired that
message's NEWEST frames instead of its oldest (21 siblings in one message:
survivors were t0..t12, the frames the model was just asked about were
the ones removed). Reverse the inner walk so the carrier list honours the
newest-first contract the batch tail relies on.
Same defect and fix as #103217 (credit @Maero47).
Two gaps in the limit-triggered eviction, both found by review on #113517.
The ceiling is a count of API image blocks, but the send path counted tool
MESSAGES. Eight tool results carrying three screenshots each are 24 blocks
against a 20-block ceiling; counting messages saw 8 and evicted nothing.
User uploads occupy the same per-request budget and were not counted at all, so
a mixed session sailed past the limit. They must be reserved against the ceiling
while never being rewritten -- the user attached them by hand.
Reserving uploads introduces a failure of its own: once uploads alone reach the
ceiling, a pure limit rule retires every screenshot and leaves the model blind
on the frames it was just asked about, which is worse than the stricter
dimension cap the limit exists to avoid. keep_newest therefore becomes a FLOOR
rather than a trigger.
Both stages now weight by image-part count and reserve non-tool image blocks.
Three regression tests cover the block accounting, the reserved-upload
accounting, and the floor; all three fail when either fix is reverted.
Review fix on top of the limit-triggered eviction. Both send-path stages ran
statelessly on a fresh clone every request, and each retired a FIXED single
batch (`min(batch, count - keep)`) once over the limit. That caps total
eviction at 8 per stage forever: once a session passes 20 + 8 (+ 8 from the
adapter) images, the outbound request grows unbounded again (24 image blocks
at 40 vision calls, 44 at 60 in the issue's own replay), so the documented
20-image threshold and the 24 MB byte budget were not enforced above the
first window. The PR's 40/60-row "3 collapses" result was this saturation,
not a held frontier under the limit.
Retire `ceil(overshoot / batch) * batch` instead, extending by whole batches
while the surviving payload still exceeds the byte budget. The frontier is
still a step function of the image count (one move per batch), and the
request now stays at or below the limit at every size:
images collapses max outbound images (PR head -> fixed)
40 3 -> 4 24 -> 20
60 3 -> 6 44 -> 20
2 MB x 30 3 -> 4 40 MB -> 22 MB
Both frontier tests now span three batch windows and assert the outbound
count never exceeds the limit; both are red on the previous head.
Both send-path image evictions retired the oldest payload as soon as more than
three images were present. Retiring an image edits a message the provider has
already cached, and Anthropic matches its prompt cache on an exact byte prefix,
so each retirement re-wrote the entire conversation. Because the window was a
count, one more message retired on every new image and nearly every turn became
a full-prefix miss.
Observed on a real 104-request session: requests reported cache_read=16,076 --
system prompt plus tool schemas and nothing else -- with cache_write up to
127,720, against a steady-state read of ~145,000. Those requests produced 62
percent of the session's entire cache-write volume.
Trigger eviction on the API's own per-request image and byte limits instead, and
retire a batch when it fires. Under the limit nothing is rewritten and the
request is append-only, so the cached prefix survives; over it, the cost is one
slower turn per batch rather than one per image. This matches the documented
behaviour of the reference Anthropic client.
Simulated across session sizes, prefix collapses fall from 3/8/18/38/58 to
1/1/1/3/3 at 5/10/20/40/60 vision calls.
Compaction keeps the count-based window: it commits its rewrite into the
canonical transcript once and has no prefix to preserve.
A named credential that reaches the welcome host got the terminal "needs to reconnect. Run
/model..." copy immediately, though the same credential re-read that already heals the
mirror case (anon_on_paid_host) moves it to the paid host. Run that one-shot heal for both
wrong-host refusals; when the store yields the same route (a user-set
NOUS_INFERENCE_BASE_URL) the refresh reports False and the copy stands.
build_error_surface_from_exception classified without the credential, so an anonymous
session's gate refusal that escaped the turn loop read as a retryable rate limit. Thread
api_key from the TUI gateway's terminal-error path. Provider-gate the named welcome-host
400 like the 403 branch, and drop the provider conjunct the anonymous gate already implies.
The same two-getattr expression was spelled three ways across turn_recovery, turn_api_call
and turn_response_check. Pass _Ctx.anonymous by keyword, and rename the guard's flag now
that it means "anonymous", not "welcome route".
Skipping the provider-wide health marker for an anonymous cooldown made every auxiliary
client build (titles, memory, compression) re-resolve Nous credentials — pool read, auth
store lock, a fresh httpx client — for the cooldown's whole length, since get_client never
caches a miss. Mark the provider unhealthy for at most 60s instead: aux calls stay O(1)
during the cooldown and a sign-in mid-cooldown waits under a minute rather than inheriting
the anonymous allowance's full wait.
The identity gate made the gateway's mirror 400 ("serves anonymous Hermes Agent accounts
only") fall through to the generic format_error copy ("malformed request... hermes doctor"),
which is wrong for it. It is the one welcome-tier refusal a signed-in credential receives,
so classify it before the gate and keep "This Nous account needs to reconnect. Run /model
and pick the Nous row again"; only the free_tier sign-in card is withheld, since its single
action is a sign-in the user has already done.