Skip to content

[FEATURE] Plugin API: replay the main thread's last request as sent (cache pre-warm) for keepalive mods #101755

Open

Description

@blucca

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:

  1. 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.
  2. In the tool-running case, writes a tail that can never be reused. The fork strips tool_use from the trailing assistant message, so the cached "response" differs from what the next real request will send (which includes the tool_use block). 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.fork takes only prompt; there is no way to choose the snapshot or the marker position.
  • Forks raise no turn.step, so a hook cannot adjust them.
  • $.model.complete carries no tools, history or session system prompt, so it can never hit the main thread's prefix.
  • Inside a turn.step hook, a second next(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: 0 pre-warm, so no output tokens and no model reply to steer.
  • Optionally an agentId to warm a subagent's last request, since subagents keep their own prefix.
  • usage in 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.fork as 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_URL that 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

  1. A turn ends with a final answer, or starts a 20-minute test run in the foreground.
  2. At 270 s idle, the mod calls $.model.prewarm().
  3. 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.
  4. The mod repeats up to its cap and logs read 120k, wrote 0 per beat.

Additional Context

Claude Code 2.1.296, Windows. Observed with a mod on the plugin API ($.model.fork, turn.step, $.clock.after).

Activity

  1. blucca commented on Oct 13, 2026

    @blucca
    Author

    Addendum: please support the API's max_tokens: 0 cache 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 its cache_control breakpoints, and returns immediately with empty content, stop_reason: "max_tokens" and a full usage block. No output tokens are generated or billed. The docs describe keeping a cache warm exactly this way: re-send the previous request unchanged, with max_tokens: 0 and without stream.

    The plugin API can't express this today:

    • $.model.fork has 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.complete rejects maxTokens: 0; it takes a positive integer only.

    Requested:

    1. The replay call proposed above ($.model.prewarm() / fork({ from: 'request' })) should send max_tokens: 0 with stream dropped. That makes it a pure cache operation with no reply to steer.
    2. Independently, accept maxTokens: 0 on $.model.fork and $.model.complete and treat it as a pre-warm. Return usage with an empty text, as a distinct arm such as { isAnswered: false, reason: 'prewarmed', usage } or a prewarm: true flag. 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: 0 request when it sets manual extended thinking (thinking.type: "enabled"), structured outputs, a forced tool_choice, or stream: true; adaptive thinking is fine. The engine knows which of these its rendered request carries, so it can drop stream and either adjust the rest or resolve with a clear reason. A mod can't do either.

  2. Ben-Home commented on Oct 13, 2026

    @Ben-Home

    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:

    1. 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.

    2. 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.

    3. 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.

  3. rayyichen310 commented on Nov 14, 2026

    @rayyichen310

    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:

    • Fork 35 min later: read 92,261, wrote 5,257.
    • Fork 25 s after that: read 97,518 (92,261 + 5,257), wrote 0.
    • Fork 6.9 min after that: read 92,261, wrote 5,257 again.

    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.

  4. gvonnessi commented on Nov 15, 2026

    @gvonnessi

    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-5 on Bedrock). Main thread on the 1h TTL, subagentPromptCacheTtl: "5m".

    $.model.fork is sent with the subagent TTL, since hook_prompt isn'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:

    • First-party: it renews, for at least 55 minutes. Multi-turn sessions with a question pending. A fork at +50 min read 57,870 tokens, and the answer at +63 read 57,870 and wrote 368. Two more sessions were forked at +10 and +35 and answered at +65, 55 and 30 minutes after their forks: both read the whole conversation (57,866 and 57,873) and rewrote only the last turn. A control session with no fork was cold at +63, reading only the 26,768-token system prompt.
    • Bedrock: it doesn't. Direct invoke-model calls on ~6k-token prefixes, each written with ttl: "1h" at T0:
      • pinged at +50 with a 5m marker: missed at +63 and again at +70
      • pinged at +50 with a 1h marker: hit at +63
      • never pinged: missed at +63 and at +70

    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.fork until the primitive exists.

  5. CadeCarlson commented on Nov 26, 2026

    @CadeCarlson

    +1 from another keep-alive plugin (wfl). Our measurements on 2.1.332, in case they help prioritise:

    • Fork keep-alives ($.model.fork) do keep the cache warm: after two forks over 10 minutes the person's next message read the whole prefix (41,019 tokens) and wrote 53, in every run on Haiku and Sonnet 5.5.
    • But each fork pays for a reply we throw away, and forks take no max-tokens option, so we cannot ask for a zero- or one-token answer. A primitive that only refreshes the cache entry (replay the prefix with max_tokens 0, or a $.cache.touch()) would remove that cost entirely.
    • Keep-alives are the largest saving our plugin has: on the 1-hour cache a cold return re-writes the whole session at about 40 times the read price (Sonnet 5.5), so every avoided cold return is worth far more than the heartbeat.

    What would be enough for us: a heartbeat call that reads the main thread's current prefix and returns no completion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:costarea:pluginsenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions