Every consumer that needs "when does this session's cached prompt expire?" now reads one
answer, agent/prompt_cache_clock.py:cache_window(), instead of re-deriving it from _cache_ttl.
- Per successful attempt the clock records the tier actually on the wire (cache_control ttl,
prompt_cache_options.ttl, prompt_cache_retention, read from the sent payload), the send time,
and the tier the response proved: Anthropic cache_creation.ephemeral_5m/1h_input_tokens,
OpenAI Responses cache_write_tokens_details.ttl_30m/12h_tokens. normalize_usage keeps that
split as CanonicalUsage.cache_write_by_ttl instead of dropping it.
- Per-route rules are a dict of small handlers: native Anthropic proves via the split;
OpenRouter Claude is declared (live-probed to honour 1h); routes with a ceiling are clamped;
other Anthropic-wire gateways assume 5m; OpenAI GPT-5.6+ proves via ttl_30m/12h or declares
the documented 30m minimum; pre-5.6 assumes ~30m (5m on in_memory); implicit caches are
unknown. expires = latest read-or-write send time + the written tier. A route switch,
fallback, session rotation or compaction makes it unknown.
- Route TTL ceiling is data: ProviderProfile.prompt_cache_max_ttl (Nous ships "5m", because
the Portal's upstream drops 1h after ~7 min and bills 5m), overridden per provider by config
prompt_caching.route_ttl_ceilings. effective_cache_ttl uses the same helper, so Hermes stops
asking Nous for 1h. A custom endpoint at the Portal host gets the Nous ceiling.
- Persisted as nullable sessions.prompt_cache_clock (JSON) through the existing token batch;
restored lazily on resume, falling back to the newest assistant row (assumed).
- Codex app-server: read cacheWriteInputTokens instead of hard-coding cache_write_tokens=0.
- /context shows "Prompt cache: warm until HH:MM (…; 1h, proven)", "expired … ago" or
"unknown (…)". The surface is absorbed from #142387 (render/duration helpers, the
SessionContextBreakdownResult.prompt_cache contract and translations), reworked onto the clock.
Co-authored-by: Teknium <127238744+teknium1@users.noreply.github.com>
Hermes' own background review (fork the live agent after a turn, run a
bounded multi-step prompt with a narrow tool list, cancel on the next live
turn) is now open to plugins as ctx.fork_session(token, prompt, *, tools=(),
max_iterations=8, input_budget=None, task=None, timeout=None), gated by the
new consent-only capability llm.session_fork.
Reused, not copied:
- Lease: post_llm_call's side_question_token backs a side question OR a fork
(side_question_lease.take_lease; same TTL, turn_moved_on, profile fence,
no token for unattended turns, one redemption per turn). The payload field
keeps its name for compatibility.
- Fork: build_cache_parity_fork(write_origin="plugin_fork:<id>") on a
context-bound thread in the captured turn context; same-model forks replay
the captured system prompt and tools[] byte-for-byte; routed forks get the
history digest. Persistence stays fully detached.
- Guardrails: the thread tool whitelist is the requested names (each must
already be in the session's tools[]); approvals auto-deny; the review's
input budget (a plugin can only lower it) and iteration cap (<= 16);
_BackgroundReviewRun admission so cancel_background_review_for_live_turn
interrupts plugin forks with the review under one bounded wait;
review_idle_queue deferral on the managed local runtime (enqueue takes a
dispatch callable; a newer fork of the same plugin supersedes the queued
one).
- Routing: task must be one of the plugin's register_auxiliary_task lanes,
resolved like auxiliary.background_review.
- Usage and hooks: release_cache_parity_fork bills the parent session as
plugin_fork:<id>; each fork loop request reports pre/post_auxiliary_call
(aux_task="plugin_fork", plugin_id) instead of pre/post_api_request.
Tool handlers inside the fork receive turn_origin="plugin_fork:<id>"
(live calls get no new kwarg), so a plugin can refuse calls from the live
agent. The handle exposes done/cancelled/outcome/result/actions/wait/cancel,
never the fork agent. Fails closed (None) without the capability, on a bad,
expired, spent or foreign token, a tool the session does not advertise, or
a task the plugin does not own.
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.
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).
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).
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.
Core no longer branches on the Copilot/GitHub Models hosts in the Responses adapter, transports,
reasoning params or reasoning-carrier replay. A provider profile claims its backend through
ProviderProfile.serves_endpoint(base_url) (default False) and fills generic L3 fields/hooks:
responses_replay_item_ids, responses_prompt_cache_key, responses_issuer_kind,
responses_trusts_completed_status, responses_native_compaction, responses_profile_reasoning,
message_carrier_opaque/_text, replays_tool_call_signatures, reasoning_payload(),
replay_message_carriers(), replays_function_thought_signature().
The in-tree copilot plugin fills them from plugins/model-providers/copilot/responses.py, keeping the
persisted "github_responses" issuer stamp and hermes.native_assistant record keys. Persisted carrier
records whose declaring plugin is gone are stripped by their own keys.
Parity: an offline oracle over 2079 Copilot cases (main request kwargs incl. preflight, aux Responses,
carrier shaping/capture, reasoning gate, native compaction) is byte-identical to the base on the agent
paths in both registry states.
The side request fired the turn-scoped pre_api_request/post_api_request
after its turn had already closed, so trace-per-turn observers (and the
relay metrics keyed on them) counted a plugin's side call as a model call
of a finished turn. Every other side call (titling, compression, MoA,
vision, ...) reports through pre/post_auxiliary_call instead.
- turn_api_request: build_request_payload() is the payload build through
the LLM request middleware with no hook; build_api_request() wraps it
with pre_api_request, the debug dump and the MoA handshake, unchanged
for the turn loop.
- auxiliary_hooks: start_aux_call_hooks()/finish_aux_call_hooks() expose
the pre/post pair for callers that drive the provider call themselves;
post accepts an already-normalized (message, finish_reason, usage) view
for a transport-native reply.
- side_question_request: build_request_payload + aux hooks with
aux_task="side_question"; a request refused for server-side tools now
fires nothing.
Test: a real plugin observing all four events sees pre/post_api_request
for the turn only and pre/post_auxiliary_call (with usage) for the side
request (red before).
Six opt-in, bucketed shared-metrics counters (schema + contract + docs in `v5 efficiency` blocks):
- hermes.task_cost.count {provider, model, tokens_bucket, tool_calls_bucket, api_calls_bucket,
outcome}: one row per user turn the user saw end (pre_llm_call-started, attended; forks, delegated
children and session-close aborts excluded). Tokens = prompt+completion over the turn's primary
calls. Tool/API call buckets reach gte_101 (TURN_ACTIVITY_BUCKETS; COUNT_BUCKETS untouched).
- hermes.wasted_tokens.count {provider, model, reason in undo/retry/interrupt, tokens_bucket}:
emitted from the v4 friction sites (no re-detection). /undo N counts N turns; an interrupted turn
later undone counts once; turns this process never saw read unknown.
- hermes.tool_output_truncation.count {tool, truncated, original_size_bucket}: one row per tool
result, judged after the per-turn budget; covers the per-result spill, the turn budget, and the
shared head/tail notice tools write when they cut their own output (original size reported).
- hermes.tool_overhead.count {enabled_tool_count_bucket, tool_schema_tokens_bucket,
execution_surface} + hermes.tool_enabled_unused.count {toolset (shipped TOOLSETS else custom),
used}: once per closed interactive conversation (merged across compression lineage).
- hermes.cache_break.count {provider, model, cause}: compression (committed), model_switch /
system_prompt_rebuild (continuing conversation rebuilt its prompt), toolset_change (tool array
changed mid-conversation, Bot Chat capability rebuild), provider_reported_miss (cold read after a
warm read on the same route with no Hermes-known cause), cache_expired (same after >=5 min idle).
A Hermes-known break suppresses the miss it causes. No prompt hashing.
Live-proven against a fake OpenAI-compatible server (chat -q, --resume -m, TUI gateway JSON-RPC
undo/retry/interrupt); disabled => zero telemetry files.
Drop the duplicate chunk-reading helper, run_agent facade forward and
_last_serving_provider agent state; the chat-completions loop already captures
chunk.provider, so stamp it on the per-attempt diag there and read the hook's
upstream_provider from the assembled response.provider.
Relay routing is re-rolled per request and the winning downstream is reported only
inside the delta chunk bodies, so the header snapshot in agent/stream_diag.py could
not attribute a mid-stream drop to a provider. The per-attempt diag now carries
serving_provider (first non-empty chunk-body provider), log_stream_retry prints it,
and the post_api_request payload exposes it as upstream_provider for plugins auditing
route compliance. Fixes#90216.
(cherry picked from commit f0cf4fe4f4b47e384532008b1bf56ad259c87dc2)
turn_api_request already imports from agent.message_sanitization at the
top of the module, so the function-local import added by the salvage is
an inconsistency, not a cycle guard. Hoist it onto the existing import
line; `python -c 'import agent.turn_api_request'` confirms no cycle.
When a provider 4xx's on image content, recover_before_classification
ran _strip_images_from_messages on the canonical `messages` list and
reset _db_flush_scan_prefix. Since #117569 that function pops
_db_persisted on every rewritten dict, so the next flush rewrote those
rows: every image in the session — and every image-only message, which
the stripper deletes outright — was removed from state.db for good.
The rejection describes what the CURRENT model accepts, not what the
conversation holds. An automatic fallback to a text-only provider, or a
single /model switch, was enough to erase images the user had sent to a
vision model, and switching back found them gone. It is the same failure
as the ASCII strip in #117802, on the image path; neither open fix for
that issue touches this branch.
Keep the repair on the send path, where the per-call copy already lives
(_clone_message_for_send exists so send-path rewrites never reach the
persisted transcript, #80498):
- record the rejecting (provider, model) on the agent, a session-scoped
flag initialised beside _force_ascii_payload;
- strip the in-flight api_messages copy for the immediate retry;
- build_api_request calls strip_images_for_rejecting_model() on each
attempt's api_messages BEFORE provider conversion. The stripper knows
Hermes's own part types; a converted payload would slip past it
(Bedrock Converse image blocks carry no `type`). Keyed on the model,
so one that accepts images gets them again.
_strip_images_from_messages itself is unchanged, so its role-alternation
and sidecar guarantees still hold on the wire copy. The notice no longer
claims "text-only mode for this session" (_vision_supported resets every
turn) or that images were stripped from history.
(cherry picked from commit cbdb184c27f915ab138b2087f878aed7fcc7c76b)
The summary path had grown a verbatim copy of turn_api_request's 3-line
surrogate/ASCII chokepoint — the same drift class this PR removes for the
hand-rolled kwargs builder. Move the two lines and the #50959 rationale into
`message_sanitization.sanitize_outbound_kwargs` and call it from both sites,
so the next sanitizer step added to the main loop cannot miss the summary.
Tighten two comments: "same kwargs builder" (cache_control redecoration is
not re-applied here) and a `_summary_text` note that is true for all three
summary branches, not just the chat one.
For each issue anchor present in BASE 63279301bc non-test .py and absent on HEAD, the BASE comment/docstring block was re-attached at the HEAD location of the code it explained (matched by the distinctive code line / enclosing def). Sentences already covered by an existing HEAD comment were deduped; the issue number always survives. Insert-only: no code lines changed.