gateway: an agent's compaction is recorded as Compaction, not a plain turn

shangyuan0818 (Discord, v0.1.3354): Claude Code's compactions don't show
in Usage → Requests. Through the gateway they were recorded and counted,
but as ordinary turns (Kind ""), so nothing read as a compaction: the
Compaction purpose listed none, the OTel export skipped them as turns
the transcript has (Claude Code's compaction is skipTranscript, so it
has none), and the reply ended the agent's turn.

The main handler now marks a call compacting() recognises (Claude
Code's summary ask, OpenCode's and the other agents' prompts) as
KindCompact, on every route it serves (messages, chat, responses,
gemini), unless a header already set its kind. The check reads the
facts parse the request already makes (bodyFacts.compact). Codex's
backend route already took the kind from its header; it now uses the
same constant.

Not fixable here: Claude Code used directly (not through magpie) never
writes a compaction's usage to its transcript (only compact_boundary
with token counts before and after), so magpie can't count those.

Run (mote, at this change on 3cabaab54):
- go test -timeout 45m -count=1 ./internal/gateway ./internal/usage ./internal/otlp: ok
- go vet ./internal/gateway, GOOS=linux and GOOS=windows: ok
- gofmt -l internal/: clean
Rebased onto 25eec8f6c (4 commits, 65 lines in internal/gateway, an
images-API change); at the pushed head: go vet ./internal/gateway and
go test ./internal/gateway -run 'Compact' (every compaction test): ok.
Broken by hand: TestCompactionRecordedAsCompaction on the old code is
red in 4 of 5 cases (claude code fork, claude code plain, chat,
responses: recorded as kind "", want "compact"); the plain turn stays "".
Not tried: a real Claude Code /compact through a sandbox gateway, and
Claude Desktop (assumed to be the same, since it runs Claude Code).
This commit is contained in:
yetone
2026-11-09 11:37:06 +08:00
parent 25eec8f6cb
commit c9d253e4a2
5 changed files with 100 additions and 2 deletions
+1 -1
View File
@@ -2055,7 +2055,7 @@ func callKind(h http.Header) string {
v = threadSource(h.Get("x-codex-turn-metadata"))
}
if v == "" && dshCompacts(h) {
v = "compact" // DSH's compaction of its context
v = KindCompact // DSH's compaction of its context
}
if v == "" && h.Get("User-Agent") == SearchAgent {
v = "web_search"
+82
View File
@@ -0,0 +1,82 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// ccCompactAsk is the last user text of Claude Code's compaction as
// 2.1.316 writes it (PZ: its CRITICAL preamble, then ITe's ask), cut
// short after the ask's first lines.
const ccCompactAsk = "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.\n\n" +
"- Do NOT use Read, Bash, Grep, Glob, Edit, Write, or ANY other tool.\n" +
"- You already have all the context you need in the conversation above.\n" +
"- Tool calls will be REJECTED and will waste your only turn — you will fail the task.\n" +
"- Your entire response must be plain text: an <analysis> block followed by a <summary> block.\n\n" +
"Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.\n" +
"This summary should be thorough in capturing technical details, code patterns, and architectural decisions"
// An agent compacting its conversation through the gateway is recorded
// as a compaction (Kind "compact", the Usage page's Compaction purpose),
// on every route a client can send it by, as Codex's are. Claude Code's
// compaction is a call its transcript never records (skipTranscript), so
// the gateway's row is the only place it is counted; recorded as a plain
// turn, it read as no compaction at all (shangyuan0818 on Discord), and
// the OTel export left it to a transcript that doesn't have it.
func TestCompactionRecordedAsCompaction(t *testing.T) {
ccSystem := `[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.316; cc_entrypoint=cli;"},{"type":"text","text":"You are Claude Code, Anthropic's official CLI for Claude."}]`
tools := `[{"name":"Bash","description":"Run a command","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}}]`
ask, _ := json.Marshal(ccCompactAsk)
for _, tc := range []struct {
name, path, body string
compact bool
}{
// the cache-sharing fork (tengu_compact_cache_prefix, on by
// default): the turn's own system prompt and tools, the ask put
// after the last tool result
{"claude code fork", "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":20000,"system":` + ccSystem + `,"tools":` + tools + `,"messages":[` +
`{"role":"user","content":"fix the failing test"},` +
`{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"go test ./..."}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":` + string(ask) + `}]}]}`, true},
// its fallback: a system prompt of its own, no tools
{"claude code plain", "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":20000,"system":[{"type":"text","text":"You are a helpful AI assistant tasked with summarizing conversations."}],"messages":[` +
`{"role":"user","content":"fix the failing test"},{"role":"assistant","content":"fixed"},{"role":"user","content":[{"type":"text","text":` + string(ask) + `}]}]}`, true},
{"chat", "/v1/chat/completions", `{"model":"fake/m1","stream":true,"messages":[{"role":"system","content":"You are a context summarization agent. You are given a conversation between a user and an agent."},{"role":"user","content":"fix it"}]}`, true},
{"responses", "/v1/responses", `{"model":"fake/m1","stream":true,"input":[{"role":"user","content":"fix it"},{"role":"assistant","content":"done"},{"role":"user","content":` + quote(codexCompactPrompt) + `}]}`, true},
{"turn", "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":300,"system":` + ccSystem + `,"tools":` + tools + `,"messages":[{"role":"user","content":"fix the failing test"}]}`, false},
} {
t.Run(tc.name, func(t *testing.T) {
fresh(t)
up := httptest.NewServer(&paced{events: copilotThinkingReply})
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Anthropic: up.URL, Key: "k", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body))
req.Header.Set("User-Agent", "claude-cli/2.1.316 (external, cli)")
req.Header.Set("X-Claude-Code-Session-Id", "cc-session")
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
u := lastUsage(t)
want := ""
if tc.compact {
want = "compact"
}
if u.Kind != want || u.Output != 1277 {
t.Fatalf("recorded as kind %q with %d output tokens, want kind %q", u.Kind, u.Output, want)
}
rows, _, _ := usage.Ledger(usage.All, usage.Filter{Purpose: usage.PurposeOf("compact")})
if tc.compact != (len(rows) == 1) {
t.Fatalf("the Compaction purpose lists %d rows", len(rows))
}
})
}
}
+4
View File
@@ -7,6 +7,10 @@ import "strings"
// rule may send that request to a cheaper, faster model (provider.Rule's
// Compact). The prompts are the agents' own, read from each one's release.
// KindCompact is the Kind of a call an agent made to compact its
// conversation (usage's "Compaction" purpose).
const KindCompact = "compact"
// compactLead is how far into the system prompt, or into a text part of the
// last user message, an agent's compaction prompt may begin. Each agent puts
// its prompt first or behind a short lead of its own (Claude Code's billing
+9
View File
@@ -2280,6 +2280,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
var clientResponseID string // only a reply released to the client owns this ID
call := Call{Time: start, From: from, Model: unprefixed(modelOf(body)), Agent: who.agent, Via: who.via, Kind: requestCallKind(r.Header, metadata),
wire: archiving(r, capture, start, nil), headers: headerLogOf(r.Context())}
// an agent compacting its conversation is recorded as the compaction
// it is, as Codex's are by their header: Claude Code's compaction is a
// call its transcript never records (skipTranscript), so this row is
// the only place it is counted, and as a plain turn it read as no
// compaction at all (shangyuan0818 on Discord), the OTel export left
// it to that transcript, and its reply ended the agent's turn
if call.Kind == "" && factsOf(from, plain).compact {
call.Kind = KindCompact
}
// the reply counted as it reaches the agent, for the Routing page
// while it is out (#4951); learned from once it ends
capture.live = liveBegin(inflightOf(r.Context()), call.Model, from)
+4 -1
View File
@@ -10,11 +10,13 @@ import (
// bodyFacts is what the readers of a request's conversation that only
// read it take from it: the turn count (turnOf), the folder its agent
// works in and whether that is a git repository, as the text says
// (dirOf, tellWorkPlace). A body that doesn't parse says none of them.
// (dirOf, tellWorkPlace), and whether it is the agent compacting its
// conversation (compacting). A body that doesn't parse says none of them.
type bodyFacts struct {
turn int
within bool
dir, git string
compact bool
}
// factsOf is bodyFacts of body, read in protocol proto. Each of its
@@ -70,6 +72,7 @@ func readFacts(proto provider.Protocol, body []byte) bodyFacts {
var f bodyFacts
f.turn, f.within = turnIn(req)
f.dir, f.git = workPlace(req)
f.compact = compacting(req)
return f
}