From 8a1ca956fd52e086e132345242957b9df3ef6fc8 Mon Sep 17 00:00:00 2001 From: SipengXie2024 <184713193+SipengXie2024@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:29:41 +0000 Subject: [PATCH] fix(antigravity): keep mid-conversation system messages in place so the prompt prefix stays cacheable Claude Code sends {role: "system"} messages inside messages: one with the environment after the first user message, and a notice after every tool result, which stays in the history. buildContents moved all of them to the end of systemInstruction. systemInstruction precedes the contents, so every tool round changed the start of the prompt and Gemini's implicit prefix cache matched only the tools and the fixed system prompt: in a Claude Code tool loop on gemini-4-neon cache_read stayed at about 34k tokens of a 100k-200k token conversation (9.4% of input tokens over 3947 requests). System messages before the first model turn still go to systemInstruction. Later ones stay at their position as text at the end of the user turn they follow; one that follows a model turn joins the next user turn after its tool results, so a functionCall is still followed directly by its functionResponse. System message text is trimmed in both wire forms, since Claude Code sends the newest one as cache_control blocks and the same message as a string once it is history. --- .../pkg/antigravity/request_transformer.go | 73 +++++- .../pkg/antigravity/system_notice_test.go | 210 ++++++++++++++++++ 2 files changed, 282 insertions(+), 1 deletion(-) create mode 100644 backend/internal/pkg/antigravity/system_notice_test.go diff --git a/backend/internal/pkg/antigravity/request_transformer.go b/backend/internal/pkg/antigravity/request_transformer.go index b026fa7e29..2635de3863 100644 --- a/backend/internal/pkg/antigravity/request_transformer.go +++ b/backend/internal/pkg/antigravity/request_transformer.go @@ -421,9 +421,21 @@ func buildSystemInstruction(system json.RawMessage, modelName string, opts Trans } // buildContents 构建 contents +// +// {role: "system"} messages before the first model turn are the conversation's +// standing context and go to systemInstruction. Later ones are notices an agent +// client adds as the conversation goes on (Claude Code adds one after each tool +// result); they stay at their place as user text. systemInstruction precedes +// the contents in the prompt, and Gemini's implicit cache only matches a prompt +// prefix, so a notice appended there would change every request's prefix and +// leave the whole conversation uncached. func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isThinkingEnabled, allowDummyThought, multimodalToolResults bool) ([]GeminiContent, []GeminiPart, bool, error) { var contents []GeminiContent var systemParts []GeminiPart + // Notices that follow a model turn wait for the next user turn: a + // functionCall must be followed directly by its functionResponse. + var pendingNotices []GeminiPart + seenModel := false strippedThinking := false for i, msg := range messages { @@ -441,10 +453,31 @@ func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isT } if role == "system" { - systemParts = append(systemParts, parts...) + parts = trimSystemTextParts(parts) + if !seenModel { + systemParts = append(systemParts, parts...) + continue + } + notice := systemReminderParts(parts) + if n := len(contents); n > 0 && contents[n-1].Role == "user" && len(pendingNotices) == 0 { + contents[n-1].Parts = append(contents[n-1].Parts, notice...) + } else { + pendingNotices = append(pendingNotices, notice...) + } continue } + if role == "model" { + seenModel = true + if len(pendingNotices) > 0 { + contents = append(contents, GeminiContent{Role: "user", Parts: pendingNotices}) + pendingNotices = nil + } + } else if len(pendingNotices) > 0 { + parts = append(parts, pendingNotices...) + pendingNotices = nil + } + // 只有 Gemini 模型支持 dummy thinking block workaround // 只对最后一条 assistant 消息添加(Pre-fill 场景) // 历史 assistant 消息不能添加没有 signature 的 dummy thinking block @@ -475,10 +508,48 @@ func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isT Parts: parts, }) } + if len(pendingNotices) > 0 { + contents = append(contents, GeminiContent{Role: "user", Parts: pendingNotices}) + } return contents, systemParts, strippedThinking, nil } +// trimSystemTextParts renders a system message's text the same way whether +// the client sent it as a string (which buildParts trims) or as text blocks: +// Claude Code sends its newest system message as blocks with cache_control and +// the same message as a string once it is history. +func trimSystemTextParts(parts []GeminiPart) []GeminiPart { + out := parts[:0] + for _, p := range parts { + if isPlainTextPart(p) { + p.Text = strings.TrimSpace(p.Text) + if p.Text == "" { + continue + } + } + out = append(out, p) + } + return out +} + +// systemReminderParts marks a system notice placed in a user turn the way +// agent clients mark harness text in user turns. +func systemReminderParts(parts []GeminiPart) []GeminiPart { + out := make([]GeminiPart, 0, len(parts)) + for _, p := range parts { + if isPlainTextPart(p) { + p.Text = "\n" + p.Text + "\n" + } + out = append(out, p) + } + return out +} + +func isPlainTextPart(p GeminiPart) bool { + return !p.Thought && p.InlineData == nil && p.FunctionCall == nil && p.FunctionResponse == nil +} + // DummyThoughtSignature 用于跳过 Gemini 3 thought_signature 验证 // 参考: https://ai.google.dev/gemini-api/docs/thought-signatures // 导出供跨包使用(如 gemini_native_signature_cleaner 跨账号修复) diff --git a/backend/internal/pkg/antigravity/system_notice_test.go b/backend/internal/pkg/antigravity/system_notice_test.go new file mode 100644 index 0000000000..8f502c83e3 --- /dev/null +++ b/backend/internal/pkg/antigravity/system_notice_test.go @@ -0,0 +1,210 @@ +package antigravity + +import ( + "encoding/json" + "fmt" + "math/rand" + "strings" + "testing" + "testing/quick" + + "github.com/stretchr/testify/require" +) + +// Messages shaped like Claude Code's: a {role: "system"} message with the +// environment after the first user message, and another {role: "system"} +// notice after every tool result. The newest system message carries +// cache_control as a block list; once it is history the client sends it as a +// plain string. +const ( + ccAsk = `{"role":"user","content":[{"type":"text","text":"read f.txt"}]}` + ccEnvLatest = `{"role":"system","content":[{"type":"text","text":"# Environment\nPrimary working directory: /repo","cache_control":{"type":"ephemeral"}}]}` + ccEnv = `{"role":"system","content":"# Environment\nPrimary working directory: /repo"}` + ccCall1 = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{"file_path":"/repo/f.txt"}}]}` + ccResult1 = `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"hello"}]}` + ccCall2 = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_2","name":"Read","input":{"file_path":"/repo/g.txt"}}]}` + ccResult2 = `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_2","content":"world"}]}` + ccNotice = `{"role":"system","content":"Plain output style is active."}` + ccNoticeLast = `{"role":"system","content":[{"type":"text","text":"Plain output style is active.","cache_control":{"type":"ephemeral"}}]}` +) + +func transformClaudeCodeMessages(t *testing.T, msgs ...string) V1InternalRequest { + t.Helper() + var messages []ClaudeMessage + require.NoError(t, json.Unmarshal([]byte("["+strings.Join(msgs, ",")+"]"), &messages)) + body, err := TransformClaudeToGeminiWithOptions(&ClaudeRequest{ + Model: "gemini-4-neon", + System: json.RawMessage(`"You are Claude Code."`), + Messages: messages, + Tools: []ClaudeTool{{Name: "Read", Description: "Read a file", InputSchema: map[string]any{"type": "object"}}}, + }, "project-1", "gemini-4-neon-high", DefaultTransformOptions()) + require.NoError(t, err) + var req V1InternalRequest + require.NoError(t, json.Unmarshal(body, &req)) + return req +} + +func mustJSON(t *testing.T, v any) string { + t.Helper() + b, err := json.Marshal(v) + require.NoError(t, err) + return string(b) +} + +// Gemini's implicit cache matches the prompt from its first byte, and the +// systemInstruction comes before the conversation. Each request of a tool loop +// must therefore keep the previous request's systemInstruction, tools and +// contents byte for byte and only add to the end. +func TestClaudeCodeToolLoopKeepsThePromptPrefix(t *testing.T) { + requests := []V1InternalRequest{ + transformClaudeCodeMessages(t, ccAsk, ccEnvLatest), + transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNoticeLast), + transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNotice, ccCall2, ccResult2, ccNoticeLast), + } + for n := 1; n < len(requests); n++ { + before, now := requests[n-1].Request, requests[n].Request + require.Equal(t, mustJSON(t, before.SystemInstruction), mustJSON(t, now.SystemInstruction), "request %d changed the systemInstruction", n+1) + require.Equal(t, mustJSON(t, before.Tools), mustJSON(t, now.Tools), "request %d changed the tools", n+1) + require.Greater(t, len(now.Contents), len(before.Contents)) + for i := range before.Contents { + require.Equal(t, mustJSON(t, before.Contents[i]), mustJSON(t, now.Contents[i]), "request %d changed content %d of the request before", n+1, i) + } + } +} + +// The same holds for any conversation that grows the way Claude Code grows +// it: tool calls, tool results with notices after some of them or between a +// call and its result, finished replies and new questions. +func TestGrowingConversationOnlyAddsToThePrompt(t *testing.T) { + notices := []string{"Plain output style is active.", " The user hasn't heard from you in a while.\n", "Today's date is 2026-12-01."} + // system renders a system message; the newest one comes as blocks with + // cache_control, older ones as strings. + system := func(text string, newest bool) string { + if newest { + return mustJSON(t, map[string]any{"role": "system", "content": []map[string]any{{"type": "text", "text": text, "cache_control": map[string]string{"type": "ephemeral"}}}}) + } + return mustJSON(t, map[string]any{"role": "system", "content": text}) + } + type message struct { + json string + notice string // the text of a system message, rendered by position + } + render := func(msgs []message) []string { + out := make([]string, len(msgs)) + for i, m := range msgs { + if m.notice != "" { + out[i] = system(m.notice, i == len(msgs)-1) + } else { + out[i] = m.json + } + } + return out + } + + property := func(seed int64) bool { + rng := rand.New(rand.NewSource(seed)) + msgs := []message{{json: ccAsk}, {notice: "# Environment\nPrimary working directory: /repo"}} + var requests [][]string + requests = append(requests, render(msgs)) + for step := 0; step < 2+rng.Intn(8); step++ { + id := fmt.Sprintf("toolu_%d", step) + if rng.Intn(4) == 0 { + msgs = append(msgs, + message{json: mustJSON(t, map[string]any{"role": "assistant", "content": fmt.Sprintf("answer %d", step)})}, + message{json: mustJSON(t, map[string]any{"role": "user", "content": fmt.Sprintf("question %d", step)})}) + } else { + msgs = append(msgs, message{json: mustJSON(t, map[string]any{"role": "assistant", "content": []map[string]any{ + {"type": "tool_use", "id": id, "name": "Read", "input": map[string]string{"file_path": id}}}})}) + if rng.Intn(5) == 0 { + msgs = append(msgs, message{notice: notices[rng.Intn(len(notices))]}) + } + msgs = append(msgs, message{json: mustJSON(t, map[string]any{"role": "user", "content": []map[string]any{ + {"type": "tool_result", "tool_use_id": id, "content": fmt.Sprintf("result %d", step)}}})}) + } + for n := rng.Intn(3); n > 0; n-- { + msgs = append(msgs, message{notice: notices[rng.Intn(len(notices))]}) + } + requests = append(requests, render(msgs)) + } + var before V1InternalRequest + for n, r := range requests { + now := transformClaudeCodeMessages(t, r...) + for i, c := range now.Request.Contents { + if c.Role == "system" || (i > 0 && now.Request.Contents[i-1].Role == c.Role) { + t.Logf("seed %d request %d: content %d has role %q after %q", seed, n, i, c.Role, now.Request.Contents[max(i-1, 0)].Role) + return false + } + } + if n > 0 { + if mustJSON(t, before.Request.SystemInstruction) != mustJSON(t, now.Request.SystemInstruction) { + t.Logf("seed %d request %d changed the systemInstruction", seed, n) + return false + } + for i := range before.Request.Contents { + if mustJSON(t, before.Request.Contents[i]) != mustJSON(t, now.Request.Contents[i]) { + t.Logf("seed %d request %d changed content %d", seed, n, i) + return false + } + } + } + before = now + } + return true + } + require.NoError(t, quick.Check(property, &quick.Config{MaxCount: 300})) +} + +func TestSystemMessagesBeforeTheFirstModelTurnStayInSystemInstruction(t *testing.T) { + req := transformClaudeCodeMessages(t, ccAsk, ccEnvLatest, ccCall1, ccResult1, ccNoticeLast).Request + + var system []string + for _, p := range req.SystemInstruction.Parts { + system = append(system, p.Text) + } + joined := strings.Join(system, "\n") + require.Contains(t, joined, "# Environment") + require.NotContains(t, joined, "Plain output style is active.") +} + +func TestSystemNoticeFollowsTheToolResultsOfItsUserTurn(t *testing.T) { + req := transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNotice, ccCall2, ccResult2, ccNoticeLast).Request + + require.Len(t, req.Contents, 5) + for i, c := range req.Contents { + require.NotEqual(t, "system", c.Role) + if i > 0 { + require.NotEqual(t, req.Contents[i-1].Role, c.Role, "contents %d and %d share a role", i-1, i) + } + } + for _, i := range []int{2, 4} { + parts := req.Contents[i].Parts + require.Equal(t, "user", req.Contents[i].Role) + require.Len(t, parts, 2) + require.NotNil(t, parts[0].FunctionResponse, "the tool result must come first") + require.Equal(t, "\nPlain output style is active.\n", parts[1].Text) + } +} + +// A notice between a model turn and the user turn holding its tool results +// joins that user turn after the results: a functionCall must be followed +// directly by its functionResponse. +func TestSystemNoticeAfterAModelTurnWaitsForTheNextUserTurn(t *testing.T) { + req := transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccNotice, ccResult1).Request + + require.Len(t, req.Contents, 3) + require.Equal(t, "model", req.Contents[1].Role) + last := req.Contents[2] + require.Equal(t, "user", last.Role) + require.Len(t, last.Parts, 2) + require.NotNil(t, last.Parts[0].FunctionResponse) + require.Contains(t, last.Parts[1].Text, "Plain output style is active.") +} + +func TestSystemNoticeEndingTheRequestAfterAModelTurnBecomesAUserTurn(t *testing.T) { + req := transformClaudeCodeMessages(t, ccAsk, ccEnv, `{"role":"assistant","content":"partial answer"}`, ccNotice).Request + + require.Len(t, req.Contents, 3) + require.Equal(t, "model", req.Contents[1].Role) + require.Equal(t, "user", req.Contents[2].Role) + require.Contains(t, req.Contents[2].Parts[0].Text, "Plain output style is active.") +}