agentmemory icon indicating copy to clipboard operation
agentmemory copied to clipboard

Token input cache rate dropped ~10pp due to per-turn system prompt mutation

Open HWliao opened this issue 6 months ago • 4 comments

Token input cache rate dropped ~10pp due to per-turn system prompt mutation

Severity: Medium (performance degradation, not functional breakage)
Affected versions: v0.9.20+ (opencode plugin)
Environment: OpenCode + agentmemory MCP + opencode plugin

Problem

Token input cache rate (prompt caching hit ratio) has dropped by approximately 10 percentage points when using agentmemory via the opencode plugin. The degradation is visible in daily aggregate statistics and accumulates over an entire day of usage.

Root Cause

The opencode plugin's experimental.chat.system.transform hook injects the result of /agentmemory/enrich into the system prompt on every model request where files have been read or edited (plugin/opencode/agentmemory-capture.ts:639-656).

// Current behavior — changes system prompt EVERY turn
"experimental.chat.system.transform": async (input, output) => {
  // ...
  const stash = stashFor(sid);
  if (stash.size === 0) return;
  const files = [...stash].slice(0, 10);
  const enrichResult = await postJson("/enrich", { sessionId: sid, files });
  output.system.push(enrichCtx);  // ❌ Mutates system prompt
}

Why this breaks caching

LLM prompt caching (Anthropic-style ephemeral caching) works by matching prefix blocks byte-for-byte. The system prompt is the first block sent to the model. When it changes between requests, the entire prefix cache is invalidated:

Request 1: system = [base + instructions + context]                  → cached
Request 2: system = [base + instructions + context + enrich(file1)]  → DIFFERENT → cache miss
Request 3: system = [base + instructions + context + enrich(file2)]  → DIFFERENT → cache miss
Request 4: system = [base + instructions + context]                  → matches Request 1 → cache hit
Request 5: system = [base + instructions + context + enrich(file3)]  → DIFFERENT → cache miss

The /agentmemory/enrich endpoint (src/functions/enrich.ts) returns variable content based on the current file stash — it runs mem::search (semantic search with file names as queries), mem::file-context (cross-session file history), and bug memory matching. Since the agent touches different files each turn, the enrich output differs on every model request where tool calls occur. In practice, nearly every turn produces a tool call, so the cache miss rate is very high.

Aggravating factors

  1. Default tool visibility: AGENTMEMORY_TOOLS defaults to "all" (53 tools) rather than "core" (8 tools), making the system prompt prefix larger, which amplifies the token cost per cache miss.

  2. Growing memory data: As sessions accumulate, the /agentmemory/context and /agentmemory/enrich responses grow, making the variable portion larger relative to the fixed portion.

  3. Contrast with Claude Code hooks: On Claude Code, agentmemory injects via additionalContext (returned from hook stdout), which appears in the message stream as a system reminder — the system prompt remains stable and caching is unaffected. This problem is specific to the opencode plugin's use of chat.system.transform.

Proposed Solution

Migrate the per-turn enrich injection from experimental.chat.system.transform to chat.message.

OpenCode's chat.message hook allows pushing text parts into the user message before it reaches the LLM, without touching the system prompt:

// Proposed change
"chat.message": async (input, output) => {
  const stash = stashFor(sid);
  if (stash.size === 0) return;
  const files = [...stash].slice(0, 10);
  const enrichResult = await postJson("/enrich", { sessionId: sid, files });
  if (enrichCtx) {
    output.parts.push({
      type: "text",
      text: enrichCtx,  // ✅ Injected into message stream, not system prompt
    });
    for (const f of files) stash.delete(f);
  }
}

Why this works

Mechanism System prompt Cache behavior
chat.system.transform (current) Changes every turn ❌ Cache miss on every tool turn
chat.message (proposed) Never changes within a session ✅ Cache hits preserved

The chat.message hook fires once per user message (not per model request in the tool-call loop). Content injected via output.parts.push() becomes part of the user's message text. The system prompt — the cached prefix — remains byte-identical throughout the session.

Implementation plan

  1. Move enrich logic from experimental.chat.system.transform (lines 639–656) into chat.message (lines 545–574) in plugin/opencode/agentmemory-capture.ts.

  2. Keep static injections in chat.system.transform: the AGENTMEMORY_INSTRUCTIONS block and the /agentmemory/context result (first-turn-only, guarded by contextInjectedSessions) — these are stable within a session and do not harm caching.

  3. Remove the per-turn enrich block from chat.system.transform entirely (lines 639–656).

  4. Update version: bump plugin version (plugin.json, package.json, src/version.ts, etc.) following the project's versioning conventions.

Alternative considered

Use experimental.chat.messages.transform instead of chat.message. This hook operates on the full message array, allowing insertion as a standalone system-reminder message between conversation turns, which is closer to Claude Code's additionalContext semantics. However, chat.message is simpler, already implemented in the plugin, and avoids the need to introduce a new hook handler.

Side benefits

  • No functional regression: enrich still runs and injects the same information — only the injection target changes.
  • Reduced token costs: cache hits mean fewer input tokens billed.
  • Lower latency: cached requests process faster on the LLM provider side.
  • Feature toggle: the existing AGENTMEMORY_INJECT_CONTEXT env var can be extended to also gate the enrich injection if needed.

References

  • plugin/opencode/agentmemory-capture.ts:613-656 — chat.system.transform hook (current enrich injection)
  • plugin/opencode/agentmemory-capture.ts:545-574 — chat.message hook (target for migration)
  • src/functions/enrich.ts — mem::enrich function definition
  • src/mcp/tools-registry.ts:952-960 — AGENTMEMORY_TOOLS default setting
  • OpenCode plugin API: chat.message injects via output.parts.push() into message stream; chat.system.transform injects via output.system.push() into system prompt

HWliao avatar May 29 '26 11:05 HWliao

Really clean root-cause writeup — the prefix-invalidation reasoning is exactly right, and moving the variable enrich payload out of the system prefix and into the message stream (chat.message / output.parts.push()) is the correct fix. The "stable prefix, volatile suffix" rule is the whole game with Anthropic ephemeral caching, and a per-turn system-prompt mutation defeats it completely.

One thing worth adding to the issue so the fix is verifiable rather than just plausible — the headline "cache rate dropped ~10pp" can understate the real billing impact, because a cache miss isn't just "not a hit." With Anthropic pricing the same prefix tokens get billed at three very different rates depending on what happened to them:

  • cache read (prefix matched): ~0.1× input price
  • plain input (never cached): 1× input price
  • cache write (new prefix written to cache): 1.25× input for 5-min TTL, 2× for 1-hour TTL

So when the volatile enrich block invalidates the prefix, the large stable AGENTMEMORY_INSTRUCTIONS + 53-tool block (your aggravating factor #1) flips from being billed at 0.1× to being re-written at 1.25–2× every turn. That's a 12.5–20× cost swing on those prefix tokens, not a 10% one — which is why trimming AGENTMEMORY_TOOLS from all→core and fixing the injection point compound so strongly.

For confirming the fix landed, the cleanest signal is the per-turn split of cache_read_input_tokens vs cache_creation_input_tokens (rather than the aggregate hit-rate %): after the migration you'd expect cache-creation to drop toward "once per session" and cache-read to dominate every subsequent turn. If you want a quick offline way to eyeball that from a real session's logs without standing up a dashboard, I wrote a tiny local read-only CLI for exactly this attribution (output vs cache-read vs cache-write vs fresh input, per turn) for Claude Code's .jsonl logs — https://github.com/wartzar-bee/tokenscope . OpenCode stores usage in its SQLite session/message tables instead, but the same five columns you already reference (tokens_cache_read / tokens_cache_write) are all you need: graph cache-write-per-turn before vs after and the regression either flattens or it didn't.

wartzar-bee avatar May 29 '26 16:05 wartzar-bee

You’re right. I’ll try to fix this locally later, and when I do, I’ll pay attention to OpenCode’s JSONL logs and compare the per-turn cache read numbers.

HWliao avatar May 30 '26 05:05 HWliao

Great — one concrete thing to look for when you pull the JSONL: compare cache_creation_tokens on a turn before the fix vs. the same turn after. If the volatile enrich block was the invalidation source, post-fix you should see cache_creation drop close to zero on follow-up turns (the prefix is now stable, so nothing needs re-writing), while cache_read holds steady or grows. If cache_creation stays elevated even after the fix, that usually means there's a second mutation somewhere else in the prefix chain — the per-turn log makes it visible immediately.

The exact field names in Anthropic's raw JSONL: usage.cache_creation_input_tokens (what got re-billed at write price) and usage.cache_read_input_tokens (what the cache actually served). Good luck with the fix.

wartzar-bee avatar May 31 '26 16:05 wartzar-bee

Confirming this is a wider issue across multiple agent integrations, not just OpenCode. I went through integrations/ and plugin/ on main and the same prefix-invalidation pattern shows up in several places:

  • Pi (integrations/pi/index.ts:240-252): pi.on("before_agent_start", ...) returns {systemPrompt: ...} — mutates system prompt on every user prompt, same prefix-invalidation problem. The fix shape is straightforward: Pi has an input event with action: "transform" that can append the recall block to the user message text instead of the system prompt prefix (verified in the Pi extension docs).

  • Hermes (integrations/hermes/__init__.py:222-243): system_prompt_block() calls /context and returns the payload; Hermes' memory_manager.build_system_prompt() concatenates provider blocks into the system prompt per turn. Then prefetch() adds a second /smart-search call on top — double cache miss per turn. Hermes users are paying the highest hidden premium here.

  • OpenClaw (integrations/openclaw/plugin.mjs:181-192): api.on("before_agent_start", ...) returns {prependContext: ...}. OpenClaw's runtime handling is closed-source so I can't 100% verify the injection target, but the file's own comment says "agentmemory recalls relevant prior observations before each turn" which strongly suggests it lands in the system prompt. Worth a maintainer confirmation.

  • Claude Code is fine — additionalContext (the hook stdout path) flows into the message stream as a system reminder, the system prompt stays stable. Wartzar-bee's contrast with Claude Code in the issue body already calls this out.

  • MCP clients (Cursor, Gemini CLI, Codex CLI, GitHub Copilot CLI) are fine — the MCP server exposes tools for the LLM to call; it doesn't mutate prompts itself. Whether the MCP clients keep the system prompt stable is their problem, not agentmemory's.

Wartzar-bee's cost framing on the 12.5–20× swing on prefix tokens is the right one — fixing this on OpenCode alone leaves Pi, Hermes, and OpenClaw users paying the same hidden premium. Same root cause across all of them: volatile enrichment payloads in the prefix block.

The good news is the fix shape is consistent everywhere: move per-turn volatile content out of the prefix and into the message stream (or equivalent per-agent mechanism):

  • Pi → input event transform (action: "transform")
  • OpenCode → chat.message (output.parts.push()), as already proposed
  • Hermes → keep prefetch() (already message-shaped), but skip system_prompt_block() for per-turn use, or make it opt-in
  • OpenClaw → TBD once injection target is confirmed

happyTonakai avatar Jul 02 '26 00:07 happyTonakai