Repository navigation
Description
Preflight Checklist
- I have searched existing requests and this feature hasn't been requested yet
- This is a single feature request (not multiple features)
Problem Statement
I maintain a cache-keepalive mod: when the session sits idle (waiting on the user, a long tool call, or a background agent), it sends a heartbeat just before the 5-minute prompt cache lapses, so the next real request reads the prefix instead of re-writing it.
The only primitive that can reproduce the main thread's prefix is $.model.fork({ prompt }), but it forks the post-sampling snapshot: the last request's messages plus that request's response (with tool_use blocks stripped), and with skipCacheWrite the message marker lands on that response. So every heartbeat:
- Writes the last response into the cache. The response is output, not input; ideally it gets cached on the next real request together with the user's input / tool results, not by a keepalive that may never be followed by another request.
- In the tool-running case, writes a tail that can never be reused. The fork strips
tool_usefrom the trailing assistant message, so the cached "response" differs from what the next real request will send (which includes thetool_useblock). That write is pure waste.
What a keepalive actually needs is to touch exactly what the last request cached, i.e. the request as sent, with its marker where the main thread put it: a pure cache read, zero cache write.
Nothing else in the mod API can do this:
$.model.forktakes onlyprompt; there is no way to choose the snapshot or the marker position.- Forks raise no
turn.step, so a hook cannot adjust them. $.model.completecarries no tools, history or session system prompt, so it can never hit the main thread's prefix.- Inside a
turn.stephook, a secondnext(e)does resend the exact pinned messages, but only while that step is running, not minutes later when the heartbeat is due. - No event exposes the rendered request body, so a mod cannot record and replay it either. The only workaround today is an external HTTP proxy in front of the API, which is a lot of machinery (and credential handling) for a mod.
Proposed Solution
A mod primitive that re-sends the main thread's last request as sent, for cache warming only. For example:
// Re-sends the main thread's last API request unchanged (model, system, tools,
// messages, cache_control markers and TTL, thinking/effort, betas) as a pre-warm:
// max_tokens: 0, no transcript append, no tools run, no hooks.
const r = await $.model.prewarm() // or: $.model.fork({ prompt, from: 'request' })
// r: { usage: ModelUsage } | { reason: 'nothing-to-warm' | 'api-error' | 'aborted', ... }Desired properties:
- The snapshot is the request before its response, captured when the request is sent (not the post-sampling snapshot).
- Byte-identical cache-relevant content, so the result is
cache_read ≈ prefix, cache_creation = 0. - Uses the official
max_tokens: 0pre-warm, so no output tokens and no model reply to steer. - Optionally an
agentIdto warm a subagent's last request, since subagents keep their own prefix. usagein the result, so the mod can log what the heartbeat read.
Scheduling, caps and policy (idle vs. busy, how many beats, on/off) stay in the mod; the engine only needs to expose the replay.
Alternative Solutions
$.model.forkas it is today: it works, but it writes the response tail on every first heartbeat (wasted if the session is abandoned), and in the tool-running case it writes a tail that is never reused.- Exposing the rendered request on
turn.step(read-only) plus a raw "send this body" call: more general, but it leaks credentials and wire details into mods. A dedicated replay call is safer. - A local HTTP proxy via
ANTHROPIC_BASE_URLthat records and replays requests: exact, but heavy, outside the mod system, and it has to hold auth headers. - Feature request: prompt-cache keepalive while background tasks or permission prompts are pending #95728 asks for a harness-owned keepalive. This request is complementary: it is the primitive that would let mods implement that policy (and variants such as capped idle beats, per-agent warming, logging) without the harness owning the policy.
Priority
Medium - Would be very helpful
Feature Category
Developer tools/SDK
Use Case Example
- A turn ends with a final answer, or starts a 20-minute test run in the foreground.
- At 270 s idle, the mod calls
$.model.prewarm(). - The API reads the full prefix the last request cached and writes nothing. The response and the next user input / tool result are cached once, by the next real request.
- The mod repeats up to its cap and logs
read 120k, wrote 0per beat.
Additional Context
Claude Code 2.1.296, Windows. Observed with a mod on the plugin API ($.model.fork, turn.step, $.clock.after).
Activity
blucca commentedon Oct 13, 2026
Addendum: please support the API's
max_tokens: 0cache pre-warm in the plugin model calls.The Messages API officially supports
max_tokens: 0(prompt caching docs). The request reads the prompt, writes the cache at itscache_controlbreakpoints, and returns immediately with emptycontent,stop_reason: "max_tokens"and a fullusageblock. No output tokens are generated or billed. The docs describe keeping a cache warm exactly this way: re-send the previous request unchanged, withmax_tokens: 0and withoutstream.The plugin API can't express this today:
$.model.forkhas no token cap, so every heartbeat generates a real reply. In my runs, each keepalive fork produced 160–530 output tokens (mostly thinking) to say ".". When the model tried to call a tool instead, the denial cost a second full request. The prompt has to be engineered just to keep the reply short.$.model.completerejectsmaxTokens: 0; it takes a positive integer only.Requested:
$.model.prewarm()/fork({ from: 'request' })) should sendmax_tokens: 0withstreamdropped. That makes it a pure cache operation with no reply to steer.maxTokens: 0on$.model.forkand$.model.completeand treat it as a pre-warm. Returnusagewith an empty text, as a distinct arm such as{ isAnswered: false, reason: 'prewarmed', usage }or aprewarm: trueflag. Even with today's post-sampling fork snapshot, this removes the output cost and the tool-attempt retries from every heartbeat.The API rejects a
max_tokens: 0request when it sets manual extended thinking (thinking.type: "enabled"), structured outputs, a forcedtool_choice, orstream: true; adaptive thinking is fine. The engine knows which of these its rendered request carries, so it can dropstreamand either adjust the rest or resolve with a clear reason. A mod can't do either.Ben-Home commentedon Oct 13, 2026
The addendum is right that max_tokens: 0 is the correct primitive for this: it reads the full prompt, writes cache entries at the cache_control breakpoints, and returns immediately with empty content plus a usage block, so a keepalive pays reads at 0.1x and writes at 1.25x, and never generates output that would need steering.
For the replay call itself, three requirements make the difference between a warm prefix and a write-only heartbeat:
Byte-identical prefix. Cache entries are keyed on the exact token prefix. Model, system prompt, tools (including their order), messages, effort/thinking settings, betas, and the cache_control markers with their TTL values all have to match. Any serialization difference makes it a different entry, and the heartbeat then writes a new copy instead of extending the real one.
Marker position. The write marker must land where the main thread put it, which is why the request as sent (the pre-sampling snapshot) is the correct capture point. The current fork captures the post-sampling state, so the marker attaches after the response block, producing both problems in the report: a cached response tail, and in the tool-running case a tail the next real request will never match.
The pure-read case needs one caveat. cache_read = prefix with cache_creation = 0 holds only while the entry is still warm. If the heartbeat fires after the TTL lapsed, the pre-warm pays the full write, and the next real request reads what the heartbeat just wrote. That is still the right trade (the prefix gets rewritten either way, and the heartbeat chooses when), but the mod should log both cases from the usage block, because the read-only assumption is quietly false in exactly the long-gap scenario heartbeats exist for.
The ANTHROPIC_BASE_URL proxy alternative deserves to stay on the list, but as noted it puts credential handling and full wire bytes in the mod. A dedicated replay primitive that deliberately cannot diverge from the main thread's serialization is the safer engine-side shape.
rayyichen310 commentedon Nov 14, 2026
Additional data point: the fork writes the replayed reply with the 5-minute TTL even when the main thread uses the 1-hour TTL (main-thread usage shows only
ephemeral_1h_input_tokens). Claude Code 2.1.321, Opus 5.5.The main thread's last turn read 90,970, wrote 1,291, and its reply was 5,257 output tokens long. Every fork's write equals that reply's length:
So a keep-alive sent shortly before a 1-hour cache lapses always rewrites the whole last reply, which the 5-minute entry cannot carry to the next keep-alive. After a long reply that is most of each keep-alive's cost: here 5,257 × 1.25 against 92,261 × 0.05 read. The plugin-authoring docs also say a fork's own tail is never cached, which does not match this.
gvonnessi commentedon Nov 15, 2026
Data point from Bedrock, which limits what a fork-based keepalive can do there until a replay like this one exists.
Claude Code 2.1.325, Opus 5.5 (first-party Max, and
eu.anthropic.claude-opus-5-5on Bedrock). Main thread on the 1h TTL,subagentPromptCacheTtl: "5m".$.model.forkis sent with the subagent TTL, sincehook_promptisn't one of the main query sources. With these settings a fork therefore reads the main thread's 1h entry with a 5m marker. Whether that read renews the entry for an hour depends on the provider:invoke-modelcalls on ~6k-token prefixes, each written withttl: "1h"at T0:So on Bedrock a fork-based keepalive buys at most five minutes per ping. The only way to make it hold today is
CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL=1h, which moves every subagent onto 1h writes, and that costs more than the keepalive saves.Request, alongside the replay primitive above: whatever re-sends the main thread's prefix to warm it should carry the main thread's cache TTL, not the subagent one. That applies to this primitive, and to
$.model.forkuntil the primitive exists.CadeCarlson commentedon Nov 26, 2026
+1 from another keep-alive plugin (wfl). Our measurements on 2.1.332, in case they help prioritise:
What would be enough for us: a heartbeat call that reads the main thread's current prefix and returns no completion.