Keeps agent/auxiliary_client.py at its line cap: the call sites pass the
client that produced the response and the validation chokepoint derives
the pricing credential from it.
Pricing re-resolved the saved config key for the configured main
endpoint, so a call served by a client with a different static key
looked up the endpoint's /models with the wrong key and lost the price.
call_llm and async_call_llm now hand the successful primary attempt's
client credential, bound to that client's URL, to the accounting hook:
a static key prices with that key, a token source prices keyless
without minting. Config resolution remains the fallback when no serving
credential matches. The hint is never written to the usage row.
The probe helper re-encoded only the model block's api_key / key_env, so
it disagreed with resolve_runtime_provider wherever another source owns
the route: a providers: entry model.provider names (the named route
never reads model.key_env), and a credential pool owning model.base_url
(consulted before model.api_key / key_env on the named and the bare
custom routes). The vision fingerprint, context-length, aux pricing and
catalog probes then sent a stale key_env value and got 401 where turns
worked.
main_endpoint_key_for walks the runtime's own rungs through its helpers:
the pool pick is shared with _try_resolve_from_custom_pool (read with
peek, so a probe never counts or rotates a row) and the named entry's
key with _resolve_named_custom_runtime. It still answers only for
model.base_url. The vision probe takes its answer as final there,
instead of falling back to the raw model.api_key.
model_block_key_for took any nonempty model.api_key, so a template value
(your-api-key) masked a working key_env: the runtime authenticated turns
with the key_env value while context-length, vision fingerprint, aux
pricing and catalog probes sent the placeholder and got 401. Filter both
rungs with the runtime's has_usable_secret, route the catalog probe key
through the same helper, and let the vision probe prefer the model
block's usable key over its raw api_key read.
ConfigBackendUnavailable is a SystemExit on purpose, so the optional
pricing-key lookup's except Exception let a config-plane outage abort an
already successful auxiliary call. Catch that exception by name; the
estimate then runs keyless as before.
Preserve known auxiliary pricing when a temporarily unreadable config blocks
model-block credential lookup. Regression added at the accounting seam.
Follow-up to jquesnelle's credential probe fix in NousResearch/hermes-agent#156730.
The previous commit made the vision route's local-server fingerprint and
the aux pricing lookup fall back to the model block's api_key / key_env.
Both did so even while a credential source (a key_cmd callable) was the
live runtime's credential. Such a source owns its endpoint's authentication
even when its mint fails, and main sends no bearer then; the fallback sent
the saved key instead whenever model.base_url was the probed URL.
_resolve_inference_api_key() now returns what the credential source yields,
"" when it cannot mint, and record_aux_usage() passes no model-block key
while the runtime's api_key is a callable.
This corrects one sentence of that commit's message: "each probe sends it"
holds for the fingerprint and the pricing lookup only when no credential
source is the runtime's credential. The GET /api/model/info probe reads
config only and is unchanged.
A bare `provider: custom` model with `key_env` (or `api_key`) authenticates
every turn, but three metadata probes of the same endpoint went out without
it, and a keyed endpoint (for example llama-server with --api-key) answered
each with 401:
- the context-length probe behind GET /api/model/info passed no key;
- the vision route's local-server fingerprint read model.api_key but not
model.key_env;
- aux-usage pricing fetched the endpoint's /models without a key.
model_block_key_for(model_cfg, base_url) returns the block's own credential
only for its own configured base_url, so it never reaches another host, and
each probe sends it.
The fourth probe of this kind, the model picker's bare custom-endpoint
row, already sends the block's key on main since #154593.
Copy only _codex_output_index onto split child ToolCalls in
expand_local_tool_batches so stable sort keeps every child at the
parent batch's provider output position instead of moving later
children behind subsequent reasoning or calls. Do not inherit call_id,
response_item_id, or extra_content.
Return early in _OutputScan._message when every extracted text part is
empty so empty assistant message items are neither stored nor replayed
before tool calls or in place of the non-empty lone-reasoning follower.
Preserve whitespace-only parts and mixed non-empty/empty part lists.
Addresses review feedback from @teknium1 on #157216.
Persist the response-local output position alongside reasoning, message parts and calls, and strip it when constructing wire items. Keep legacy rows stable and place retained checkpoints ahead of items from a later partial response.
Persist each text part before applying display trimming. Cover the next request after SQLite hydration, including ID hygiene and call/output pairing.
On docker, modal, ssh, daytona and vercel_sandbox the cold prune and the compaction
offload kept every result whole (no saving) or dropped it without an archive, because
cache/pruned was not published into the sandbox and the stub named a host-only path.
cache/pruned now joins the cache dirs docker bind-mounts and the synced backends push,
the stub names the path the sandbox reads (to_agent_visible_cache_path), and read_file
forces a sync before opening an archive on a file-synced backend. Plugin backends and a
hosted scope still keep results whole.
NanoGPT's plain /models omits every context window; the same list with
?detailed=true publishes them. Hermes only read the plain one, so NanoGPT
users got the static table: 1,310,720 for GLM-5.3 on main, and after the
vendor-doc correction 1M for x-ai/grok-4.20 although NanoGPT serves 2M.
Ask that host for the detailed list so its own number wins, both ways.
A persisted pre-fix 2M xAI context window short-circuits the
corrected 1M vendor fallback in carrier PR #154658. Invalidate only
the exact legacy value on api.x.ai, preserving OpenRouter's 2M route.
Add an upgrade-path regression and reseller-cache guard.
Thanks to teknium1 for #154658 and myonza for #154406.
Zhipu's docs round to "1M"; the Nous Portal, OpenRouter and NanoGPT
detailed /models (z-ai/glm-5.3 and z-ai/glm-5.3:thinking) all publish
1,048,576 with a separate 131,072 output cap. NanoGPT's plain /models
omits the window, so its users get this table value.
The #154406 audit found more DEFAULT_CONTEXT_LENGTHS rows that disagree with
the vendor's own docs:
- gpt-5.6 (bare alias of Sol) fell to the 400K gpt-5 catch-all; OpenAI documents 1,050,000.
- grok-4.7 fell to the 256K grok-4 catch-all; docs.x.ai documents 500,000.
- grok-4.20 (+ -multi-agent/-non-reasoning) listed 2M; docs.x.ai documents 1,000,000.
- glm-5.3 / -flash listed 1,310,720 and -flashx 1,048,576; Zhipu documents 1M
(OpenRouter and Nous now list 1,048,576, so the 1.31M source is gone too).
Keys whose window rises over a catch-all join _PRE_CATALOG_STALE_KEYS so a
cached catch-all value from an older build is re-resolved.
Fixes#154406
DEFAULT_CONTEXT_LENGTHS lists the rest of the Claude 5 family at 1M but had
no claude-haiku-5 key, so claude-haiku-5-5 fell through to the 200K "claude"
catch-all. Every route without a live window (custom Anthropic-compatible
endpoints, discover_models providers, Bedrock's catalog fall-through)
compacted Haiku 5.5 sessions at about a fifth of the real window.
Fixes#154406
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Starting with GPT-6.2, OpenAI's Responses API appends top-level
`instructions` after `input` and bills those tokens at the uncached
input rate on every turn (both api.openai.com and ChatGPT/Codex OAuth).
Moving reusable instructions into a leading `developer` message inside
`input` makes the system prompt eligible for prompt caching again.
- Move top-level `instructions` into a typed leading `developer` input
item and omit `instructions` for GPT-6.2+ models (bare or
vendor-prefixed, excluding xAI) on both the main Responses transport
and the auxiliary `_CodexCompletionsAdapter` path, preserving
`prompt_cache_key` derivation and explicit turn-scoped `instructions`
overrides.
- Insert the `developer` item after any leading `compaction` checkpoint
run so server-side compaction never discards the system prompt.
- Accept `role="developer"` and optional `instructions` (when a developer
message is present) in `_preflight_codex_api_kwargs`, keeping Harmony
token sanitization intact.
- Teach main and auxiliary observability hooks to recover the system
prompt from a leading `developer` input item.
- Leave pre-6.2 models and xAI unchanged.
Refs #157124, #157129
Greptile on c9c7c838: the three helpers imported inside _sum_terminal,
_sum_delegate_task and _summarize_tool_result_unguarded bypass the
module header. context_compressor_prune does not import this module,
so there is no cycle to avoid; they join the existing top-level import.
- Hot reload applied proactive_prune_min_result_chars with a minimum of
0, below the 200 the constructor enforces, and did not treat 0 as "use
the default". It now matches a fresh build.
- The post-archive no-op logged prune:archive_write_failed even when no
write failed and only the added pointer text pushed the reclaim under
the gate. That case now logs prune:reclaim_below_minimum.
(cherry picked from commit d0a0f9d8cbd9f3db0250e88a20a112343bbab86c)
- terminal: the line count was taken on the JSON envelope, where newlines
are escaped, so every stub said "1 lines output". It is now counted on
the decoded output. A failed command keeps its last non-empty output
line (" | last: ..."), sized so the whole stub stays under the 200-char
prune floor and is never summarised a second time.
- delegate_task: a batch call (tasks=[...]) produced "[delegate_task] ''".
It now reads "N tasks, first: '<goal>'".
- generic stubs kept the first two arguments only, so
mcp_github_get_issue lost its issue number. Arguments are now kept in
order up to 120 characters in total (each value still cut at 40).
- _is_summary_stub also recognises the "(N chars result)" form these
stubs use, so a long one is not summarised again.
Also changed: line breaks inside a command, goal or argument value are
collapsed to spaces, and a single line reads "1 line".
(cherry picked from commit eee9b2a7af90e1bb87a29a4ed5a1e2b53195486a)
Review follow-up. The compat layer now keeps exactly the old imports the
catalog's OpenViking 2.1.2 and Honcho 1.2.0 pins make at load time, and
says so:
- agent.context_compressor_retry is no longer aliased (no catalog plugin
imports it), and agent.skill_commands re-exports only
extract_user_instruction_from_skill_message (neither pin imports
register_auto_load_scaffold).
- moves.py admits a folded module only when a catalog-pinned plugin
imports it.
- plugins/AGENTS.md and the plugin guide record the exception: which
names, where they live now, and that they follow the hermes_state
stand-in's window (removed no earlier than v0.27.0).
The storage interface (#149567, db4d50b9e7) folded agent/message_content.py and
agent/context_compressor_retry.py into session_rules/turns.py, and moved
extract_user_instruction_from_skill_message / register_auto_load_scaffold from
agent/skill_commands.py to the same module. Catalog plugins still import the old
paths at module top level, so they never registered: OpenViking 2.1.2 (the pinned
memory provider) and hermes-council fail with "No module named
'agent.message_content'", OpenViking then with "cannot import name
'extract_user_instruction_from_skill_message' from 'agent.skill_commands'", and
Hermes silently ran on built-in memory.
- MOVES gains agent.message_content and agent.context_compressor_retry ->
session_rules.turns; the target defines every name each published, byte-identical.
No other module the stack deleted is aliased: the 35 hermes_state_* modules were
mixins or SQLite-backend helpers whose functions now take a store holder instead of
a SessionDB (an alias would import and then fail on call), and
gateway.session_admission's admission_fingerprint has no catalog importer.
- agent.skill_commands re-exports the two skill-scaffolding helpers it published.
- A plugin package whose __init__.py raises now propagates that exception from
load_plugin_module instead of returning None, so the memory, context-engine,
cron and computer-use loaders' one WARNING line names the real error rather than
"loaded but no provider instance found". The bundled delegation fallback and
import_provider_module keep their contracts (None / ImportError) and carry the text.
Fixes#157438
Part of #157077
The managed llama-server's idle-unload wait starts when the model goes idle,
but _managed_unload_end counted it from the request's sent_at, so a long reply
read as cold up to its decode time early and the cold prune could shorten a
still-warm prompt. The estimate now starts at the response's completion (the
fold time).
PromptCacheWarmer._record normalized only message.usage; OpenAI reports the
served service_tier on the response, so an Ultrafast replay was booked at
Standard prices. Fold it in with with_served_service_tier, as
record_response_usage does.
Main removed the old session store: hermes_state is a stand-in carrying only the plugin
guide's methods. The compaction hook probe and the stand-in imported the summary
helper by its old private name (renamed accepts_keyword_argument here), so hygiene
compaction failed with ImportError. The lifecycle's real-store tests now open the
storage interface (open_persistence + tests/fixtures/storage_seed) instead of SessionDB,
and the per-call clock comparison drops the deadlines measured from sent_at.
Valid JSON decodes 1e999 to infinity (and NaN to NaN); _well_formed accepted both, so
rule_for's int() raised OverflowError at agent construction. Counters, gap lists and the
timestamp must now be finite, or the entry is dropped like any other malformed one.
Main's persistence interface makes the agent's store a storage handle with no
queue_token_counts; the warmer's keep-alive accounting called it on
agent._session_db directly and silently lost every refresh's usage. It now goes
through turn_usage.queue_usage, which takes the handle's usage repository (and
the worker store otherwise) with the session id and surface the keep-alive
captured when it was scheduled.
Greptile on 37f847a1: the retry deadline was rebuilt from run.ttl_s, the
tier the clock assumed. When this miss supplies the second session's
sample and learned_window returns a shorter learned lifetime (say 10 min
under a 1h tier), the retry still waited on the tier, so the next
keep-alive landed after the entry was gone, paid a second rewrite and
disabled warming. The retry now warms on the learned lifetime.
Greptile on 2a51baab:
- An automatic-cache miss reports no write, so the clock did not move and the retry was scheduled off the
old deadline (about 8 min after the miss on a 30m window, at once near its end). The retry now waits a
full window from the miss it follows.
- A summarized tool result whose archive write fails (disk full, read-only home) is now logged at WARNING;
the compaction still commits (refusing would re-pay the summary every turn while the disk stays full).
Docs say where the bytes remain (summary + state.db).
- The claim-race barrier waits up to 5 s (tests/AGENTS.md wall-clock floor).
alt-glitch's review of 893b54f9:
- Hermes' own managed llama-server unloads an idle model (and its prompt cache) after 15 min (+ two
120 s sweeps): its clock now ends there, so /context and the cold offload see it; a user's own local
server still never expires on the clock. The guarantee is capped at the estimated end.
- A malformed entry in cache/prompt_cache_routes.json (non-numeric timestamp, counters or gap lists) is
dropped instead of raising into agent build and usage accounting.
- The route key keeps the port (normalized base URL): two local servers on one host learn apart.
- The classic CLI's idle cache hook never ran: `hermes chat --cli` drives a GatewayAgent and the gateway
owns the warmer and its housekeeping. The hook, its test and its helper are removed (the two CLI
files are main's again).
- A due-scan's claimed action is handed to a release job that registered for the same chat while the
scan ran, instead of being dropped.
- Keep-alive log lines carry the chat's session tag (set on the timer thread).
- Tests that could not fail now can: the claim race pauses after the decision, the late-miss branch with
no successor, and the compaction hand-off through carry_compression_automation (each red when its fix
is reverted).
- Follow-ups folded in: a finite admission arms no idle keep-alive; delegate cost folding takes the
session-totals lock; the docs say the gateway offload lands on its 5-minute tick.
Teknium approved every improvement the usage backtest found:
- A keep-alive miss served by another upstream than the reply that cached the prefix (Nous serves one
Claude model from chatcmpl-* and gen-* upstreams; 70 switches broke a warm cache in the window), or
one that still read the stable system prefix, is routing, not lifetime. Real misses end warming only
on the second in a row (three misses of any kind end it too). The upstream key is data
(prompt_cache_clock.response_upstream: a gateway's upstream field, else the response id family),
stored on the clock event; a retried miss's rewrite is not charged to the money limit.
- cache_ttl auto: a person's chat starts on 5m and asks for 1h from the first message after an idle gap
past five minutes, for the rest of the session (kept per session id, carried to the compaction child,
re-derived from a stored clock that asked for 1h). The upgrade fires only when the clock holds no
guarantee and the last cache touch is over 300 s old, so markers never change on a warm prefix. No
idle keep-alives before the upgrade. /context names the pending tier. Explicit pins and machine
sessions unchanged. Wire snapshot regenerated: fresh cli agents now send 5m markers.
- Route store: a downgrade needs samples from two different sessions, an upstream switch is never a
sample, and a learned lifetime never undercuts the longest hit ever seen (kept outside the trimmed
recent gaps).
Tests pinning the single-miss stop and the 1h start are rewritten to the new ruling (assertions only).
agent/prompt_cache_lifecycle.py (1,200 lines) splits along its topics, per root AGENTS.md
§ Packages and Python shape: replay.py (which requests replay, with which output cap, through
which client), economics.py (a keep-alive's cost against the rewrite it prevents), edge.py (the
cache-edge gates claim_edge asks), warmer.py (PromptCacheWarmer and the agent-facing seams).
__init__ is the facade (__all__, no behaviour); topic modules import one another, never the
facade. Callers keep importing the public names from agent.prompt_cache_lifecycle; tests mirror
the folder under tests/agent/prompt_cache_lifecycle/ and patch where each name is looked up.
Co-authored-by: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com>
- Keep-alive totals go through turn_usage.add_session_usage, the same fold a response uses
(it now also counts reasoning tokens, as a response does).
- PromptCacheWarmer._with_aux_hooks is auxiliary_hooks.run_with_aux_hooks with a lazy
normalized= view; _rough_tokens is conversation_compression_manual.estimate_request_tokens.
- prompt_cache_is_cold lives in prompt_cache_clock (its only inputs), ending the
turn_proactive_prune -> turn_preflight -> turn_proactive_prune circle; the read-dedup reset
after a committed prune happens once, in _proactive_tool_result_prune, not at three call sites.
- Public names for the helpers other modules import: turn_usage.cache_clock_column /
agent_session_source, context_compressor_summary.accepts_keyword_argument.
- archive_pruned_originals / archive_compaction_drops lose the never-passed skip= parameter.
Co-authored-by: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com>
The miss lived only on the PromptCacheWarmer, but the gateway evicts and rebuilds the agent after
a cache-edge compaction or an idle eviction, and compaction continues the chat in a child session:
the next message re-armed warming in the same conversation. The miss is now also remembered per
session id (bounded LRU) and carried to the compaction child; /new still starts afresh.
- PromptCacheWarmer.claim_edge(*, releasing=False, now=None) -> "compact" | "offload" | None
replaces compaction_due / release_compaction_due / offload_due and the three claim_* functions.
It decides and latches under the warmer lock (two owners racing on one chat get one action),
ends the live run on a release claim, and its answer is passed to each job as an argument:
the `_cache_edge_action` tag and its "compact" default are gone, and no owner touches
_spent/_compacted/_lock. edge_decision() is the read-only view.
- Gateway: the 300 s due scan and the release-time claim run in asyncio.to_thread (the claim reads
state.db). An evicted agent is released exactly once by a release-once guard: the job's
done-callback (runs even when shutdown cancels the task before its first step), the loop-closed
fallback, and a shutdown drain for callbacks the stopped loop never ran.
- TUI: the ticker and the reapers queue jobs on at most three daemon workers instead of one
thread per due session.
- CLI adopts a cache-edge compaction on CompressResult.committed, not status == "compressed".
- Removed _Run.started_at and _Spent.deadline_at (never read).
- Greptile on d42bea43: /new clears the old chat's budget and latches, and a miss from before a
reset no longer disables the new session; an idle budget that runs out of money ends like one
that runs out of count, so step 2/3 still decides; the reservation includes a per-request fee
and the replay's real output cap in the known-price check.
Co-authored-by: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com>
Equal read and write counts on an ordinary turn just mean it appended about as much as it read;
two such tool rounds disabled warming for every chat on the route. Only a keep-alive re-sends
the prefix unchanged, so only its sizes can show a hit that re-wrote the prefix.
_agent_cache_opts carried only _cache_ttl, so both MoA planners called
effective_cache_ttl without auto=. Under the default `auto` tier an
interactive agent holds "1h"; the main loop clamps that to 5m on Bedrock
(auto=True), but the advisor fan-out and the aggregator plan sent 1h
markers to the same route, so MoA turns on Bedrock asked for (and paid
for) a tier the main path deliberately refuses.
_agent_cache_opts now returns _cache_ttl_auto alongside the tier and both
_maybe_apply_moa_cache_control (advisors) and
plan_cache_sections_for_destination (aggregator) pass it as auto=, so MoA
mirrors the main path: auto on Bedrock -> 5m, an explicit 1h pin -> 1h.
Co-authored-by: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com>
After the API-spec refactor, classify_route/_rule_openai_spec stopped reading the request's
prompt_cache_retention, so estimated_until equalled the 30-minute warming deadline on every
OpenAI-spec route. prompt_cache_is_cold() then turned True at 31 minutes, and turn-start prune,
owner offload and route-change offload rewrote history on routes whose cache was still warm:
api.meta.ai and Bedrock Mantle GPT-5.x/4.1 (Hermes asks those for 24h retention), and local
llama.cpp / vLLM / Ollama boxes, which evict on memory pressure, not on a clock. Each needless
rewrite costs a full prefix re-process.
Only the expiry estimate changes (_estimated_end). The 30m stays the guarantee and warming
deadline for every OpenAI-spec route, a 24h request included (warm at 25 min, first miss
disables). A request that asked for 24h is estimated to live read + 24h, and the estimate
survives a read renewal. An is_local_endpoint host has no estimated end (estimated_until None
with a known confidence), so it is never certainly cold on the clock, while route_changed and
compaction still invalidate the window and offload. chatgpt.com Codex gets no retention from
Hermes, so its 30m stands.
Co-authored-by: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com>
The compaction window only archived results the size demoter shortened, plus structured
bodies; small strings (receipts, duplicate stubs) were replaced by the summary with no
archive. Existing archive pointers are still left alone.
Co-authored-by: unsupportedpastels <theoldwizard123@pm.me>
evaluate_economics priced every refresh as one output token, but bounded_chat_replay
sends 16 to OpenAI reasoning models, so the first o3 refresh could cost more than the
miss it prevented before reconciliation noticed.
Co-authored-by: unsupportedpastels <theoldwizard123@pm.me>