Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: pin Claude Code's per-request billing stamp, so the conversation cache reuses agent prompts

Gabe Ortizbae372b9aac6
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index 6d9265b3b..eaeadf08d 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -714,7 +714,9 @@ and pictures. The oldest checkpoint - in practice the end of the system prompt,
shares - is kept for good while the rest rotates by least recent use, so a NEW chat that shares that prefix starts
reading after it instead of from token 0. A prompt read from the start is also checkpointed at the end of its system
prompt when that is 2,048 tokens or more (engine 0.1.20; PR #62 + #65), so that root exists for agent clients with long
-system prompts and tool lists. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`,
+system prompts and tool lists. Claude Code stamps its system prompt with a billing header that changes on every
+request (`cch=...`) and every session (the 4th part of `cc_version=`); the server pins both stamps (to `f`s, as
+llama.cpp does), so the system prompt and the tool list in front of it are the same prompt on every turn. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`,
`--prompt-cache-root N` (0 = no system-prompt checkpoint), `--turn-token ID`.
A one-shot request that no later request continues (a classification call, a probe) can send
`"strata_checkpoint": false` in its body: it saves no checkpoint at its last turn nor every 16K tokens, so what
diff --git a/serve/frontend.py b/serve/frontend.py
index 49a8f74b6..176f418c4 100644
--- a/serve/frontend.py
+++ b/serve/frontend.py
@@ -336,6 +336,35 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:
return _late_system_to_user(messages), tools, kwargs
+BILLING_HEADER = "x-anthropic-billing-header:"
+
+
+def pin_billing_stamp(system: str) -> str:
+ """Claude Code starts its system prompt with `x-anthropic-billing-header: cc_version=2.1.170.bf4;
+ cc_entrypoint=sdk-cli; cch=b145e;`. cch changes on EVERY request and the version's 4th part on every session, so
+ the prompt changed ~22K tokens in (after the tool list) on every turn and the conversation cache could only reuse
+ up to its last 16K checkpoint: half of every agent prompt was read again. Both stamps are pinned to f's, as
+ llama.cpp does (ggml-org/llama.cpp#21793); only a header at the very start of the system text is touched, and
+ only inside its first 160 characters."""
+ if not system.startswith(BILLING_HEADER):
+ return system
+ s = list(system)
+ cch = system.find("cch=", len(BILLING_HEADER))
+ if 0 <= cch <= 160:
+ v, end = cch + 4, system.find(";", cch + 4)
+ if end > v and end - v <= 16:
+ s[v:end] = "f" * (end - v)
+ cv = system.find("cc_version=")
+ if 0 <= cv <= 160:
+ v, end = cv + len("cc_version="), system.find(";", cv)
+ if v < end and end - v <= 64:
+ parts = system[v:end].split(".")
+ if len(parts) > 3:
+ tail = v + len(".".join(parts[:3])) + 1
+ s[tail:end] = "f" * (end - tail)
+ return "".join(s)
+
+
def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[dict], list[dict] | None, dict]:
"""Anthropic Messages -> (template messages, template tools, template kwargs). `think_unasked`: a request
without "thinking", an effort or a budget gets the template's default (it thinks), as through 0.1.31; False
@@ -343,7 +372,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d
messages = []
system = req.get("system")
if system:
- messages.append({"role": "system", "content": _text_of(system)})
+ messages.append({"role": "system", "content": pin_billing_stamp(_text_of(system))})
for m in _object_list(req.get("messages"), "messages"):
content = m.get("content")
if isinstance(content, str):
diff --git a/serve/test_server.py b/serve/test_server.py
index 3630d168e..23a37f7e6 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -3892,5 +3892,80 @@ class VisionShutdown(unittest.TestCase):
self.assertFalse(d.exists())
+class ClaudeCodeBillingStamp(unittest.TestCase):
+ """Claude Code starts its system prompt with `x-anthropic-billing-header: cc_version=2.1.170.bf4;
+ cc_entrypoint=sdk-cli; cch=b145e;` - cch changes on every request and the cc_version tail on every session. Both
+ are pinned, so the system prompt (and the tool list rendered before it) is the same prompt on every turn and the
+ conversation cache can reuse it (llama.cpp does the same: ggml-org/llama.cpp#21793)."""
+
+ HEADER = "x-anthropic-billing-header: cc_version=2.1.170.{v}; cc_entrypoint=sdk-cli; cch={c};"
+
+ def system_of(self, system):
+ from serve.frontend import anthropic_to_messages
+ return anthropic_to_messages({"system": system, "messages": [{"role": "user", "content": "u"}]})[0][0]["content"]
+
+ def blocks(self, v="bf4", c="b145e"): # Claude Code's own shape: the header is the first text block
+ return [{"type": "text", "text": self.HEADER.format(v=v, c=c)},
+ {"type": "text", "text": "You are a Claude agent, built on Anthropic's Claude Agent SDK."}]
+
+ def test_cch_is_pinned(self):
+ self.assertEqual(self.system_of(self.blocks(c="b145e")), self.system_of(self.blocks(c="db3bf")))
+ self.assertIn("cch=fffff;", self.system_of(self.blocks()))
+
+ def test_cc_version_tail_is_pinned(self):
+ self.assertEqual(self.system_of(self.blocks(v="bf4")), self.system_of(self.blocks(v="473")))
+ self.assertIn("cc_version=2.1.170.fff;", self.system_of(self.blocks()))
+ # newer Claude Code: no cch, the stamp only in the version tail
+ newer = "x-anthropic-billing-header: cc_version=2.1.220.{}; cc_entrypoint=cli;You are"
+ self.assertEqual(self.system_of(newer.format("473")), self.system_of(newer.format("9c1")))
+ self.assertIn("cc_version=2.1.220.fff;", self.system_of(newer.format("473")))
+
+ def test_a_plain_version_is_kept(self):
+ text = "x-anthropic-billing-header: cc_version=2.1.220; cc_entrypoint=cli;You are"
+ self.assertEqual(self.system_of(text), text)
+
+ def test_string_system_is_pinned(self):
+ text = self.HEADER.format(v="bf4", c="e4157") + "You are a Claude agent."
+ self.assertEqual(self.system_of(text),
+ "x-anthropic-billing-header: cc_version=2.1.170.fff; cc_entrypoint=sdk-cli; cch=fffff;"
+ "You are a Claude agent.")
+
+ def test_only_at_the_start_of_the_system_prompt(self):
+ from serve.frontend import anthropic_to_messages
+ later = "Hello.\n" + self.HEADER.format(v="bf4", c="e4157")
+ self.assertEqual(self.system_of(later), later)
+ user = self.HEADER.format(v="bf4", c="e4157")
+ msgs = anthropic_to_messages({"messages": [{"role": "user", "content": user}]})[0]
+ self.assertEqual(msgs[0]["content"], user)
+ plain = "You are a helpful assistant. cch=abc; cc_version=1.2.3.4;"
+ self.assertEqual(self.system_of(plain), plain)
+
+ def test_bounds(self):
+ long_stamp = "x-anthropic-billing-header: cch=" + "a" * 17 + ";You are"
+ self.assertEqual(self.system_of(long_stamp), long_stamp)
+ far = "x-anthropic-billing-header: " + "x" * 160 + " cch=abcde;You are"
+ self.assertEqual(self.system_of(far), far)
+ unterminated = "x-anthropic-billing-header: cc_version=2.1.170.bf4 cch=abcde"
+ self.assertEqual(self.system_of(unterminated), unterminated)
+
+ def test_two_turns_share_the_whole_system_prompt(self):
+ from serve.frontend import anthropic_to_messages
+ tok = ByteTokenizer()
+ svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
+ tools = [{"name": "Bash", "description": "Run a command.", "input_schema": {
+ "type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}]
+ turn1 = [{"role": "user", "content": "fix the bug"}]
+ turn2 = turn1 + [{"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "Bash",
+ "input": {"command": "ls"}}]},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "a.py"}]}]
+ ids = []
+ for c, msgs in (("b145e", turn1), ("db3bf", turn2)):
+ m, t, kw = anthropic_to_messages({"system": self.blocks(c=c), "messages": msgs, "tools": tools})
+ ids.append(svc.encode_prompt(m, t, kw))
+ first = svc.encode_prompt(*anthropic_to_messages({"system": self.blocks(c="b145e"), "messages": turn1,
+ "tools": tools}))
+ self.assertEqual(ids[1][:len(first) - 8], first[:len(first) - 8]) # all but the generation header
+
+
if __name__ == "__main__":
unittest.main()