From 0cb6e13d913eaee11881c91eecbaa328d41b08eb Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 12:58:21 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20a=20developer=20message=20Codex=20ad?= =?UTF-8?q?ds=20mid-thread=20stays=20where=20it=20is,=20so=20the=20thread'?= =?UTF-8?q?s=20cached=20prefix=20does=20too=20(#502,=20Koohoko:=20after=20?= =?UTF-8?q?a=20memory=20request=20the=20next=20turn=20of=20the=20same=20se?= =?UTF-8?q?ssion=20wrote=20the=20whole=20conversation=20to=20the=20cache?= =?UTF-8?q?=20again)=20=E2=80=94=20Codex=20adds=20a=20developer=20message?= =?UTF-8?q?=20to=20a=20thread=20where=20its=20context=20changed=20(a=20wor?= =?UTF-8?q?ld-state=20or=20skills=20diff,=20a=20settings=20or=20model=20ch?= =?UTF-8?q?ange,=20and=20so=20after=20its=20memory=20pipeline=20has=20run)?= =?UTF-8?q?=20and=20keeps=20it=20there=20in=20every=20later=20request,=20w?= =?UTF-8?q?hich=20leaves=20OpenAI's=20prefix=20as=20it=20was.=20parseRespo?= =?UTF-8?q?nses=20lifted=20every=20developer=20and=20system=20message,=20w?= =?UTF-8?q?herever=20it=20stood,=20into=20the=20system=20prompt,=20so=20on?= =?UTF-8?q?=20a=20translated=20route=20that=20turn's=20system=20changed:?= =?UTF-8?q?=20Anthropic's=20system=20comes=20before=20the=20messages,=20so?= =?UTF-8?q?=20the=20whole=20conversation=20was=20written=20to=20the=20cach?= =?UTF-8?q?e=20again,=20and=20a=20Claude=20subscription's=20waiting=20Clau?= =?UTF-8?q?de=20Code=20is=20found=20by=20its=20system=20(turnKey),=20so=20?= =?UTF-8?q?a=20new=20one=20was=20started=20and=20told=20the=20whole=20conv?= =?UTF-8?q?ersation=20in=20one=20message.=20Developer=20messages=20before?= =?UTF-8?q?=20the=20thread's=20first=20reply=20(Codex's=20initial=20contex?= =?UTF-8?q?t)=20are=20lifted=20as=20before;=20one=20after=20it=20now=20sta?= =?UTF-8?q?ys=20in=20place=20as=20a=20user=20message=20inside=20,=20which=20the=20router's=20classifier=20already=20leav?= =?UTF-8?q?es=20out=20of=20the=20user's=20words.=20The=20memory=20request?= =?UTF-8?q?=20itself=20(another=20model,=20its=20own=20prompt,=20the=20sam?= =?UTF-8?q?e=20session)=20moves=20nothing=20in=20magpie:=20affinity=20is?= =?UTF-8?q?=20scoped=20by=20model=20or=20by=20a=20group's=20first=20words,?= =?UTF-8?q?=20the=20Claude=20bridge's=20runs=20by=20the=20conversation.=20?= =?UTF-8?q?TestCodexLaterDeveloperMessageKeepsTheSystem=20and=20TestCodexT?= =?UTF-8?q?hreadKeepsItsClaudeRunAcrossAMemoryCall=20(a=20Codex=20thread?= =?UTF-8?q?=20on=20a=20Claude=20subscription,=20a=20memory=20call=20in=20t?= =?UTF-8?q?he=20same=20session=20between,=20then=20a=20developer=20message?= =?UTF-8?q?:=20the=20same=20Claude=20Code=20goes=20on)=20fail=20without=20?= =?UTF-8?q?the=20change.=20No=20real=20vendor=20request=20was=20made.=20go?= =?UTF-8?q?=20vet=20./internal/...,=20go=20build=20-tags=20nogui=20(darwin?= =?UTF-8?q?,=20GOOS=3Dlinux),=20GOOS=3Dwindows=20go=20build,=20go=20test?= =?UTF-8?q?=20-tags=20nogui=20./internal/gateway/=20./internal/provider/?= =?UTF-8?q?=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gateway/codex_developer_cache_test.go | 108 ++++++++++++++++++ internal/gateway/responses.go | 17 +++ 2 files changed, 125 insertions(+) create mode 100644 internal/gateway/codex_developer_cache_test.go diff --git a/internal/gateway/codex_developer_cache_test.go b/internal/gateway/codex_developer_cache_test.go new file mode 100644 index 000000000..58cbde4be --- /dev/null +++ b/internal/gateway/codex_developer_cache_test.go @@ -0,0 +1,108 @@ +package gateway + +import ( + "encoding/json" + "net/http/httptest" + "regexp" + "strconv" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// codexItem is a Responses input message, as Codex sends one. +func codexItem(role, text string) string { + kind := "input_text" + if role == "assistant" { + kind = "output_text" + } + return `{"type":"message","role":"` + role + `","content":[{"type":"` + kind + `","text":` + strconv.Quote(text) + `}]}` +} + +// A developer message Codex adds once its conversation has gone on (its +// context changed: world state, settings) stays where it is: the system +// prompt, and so Anthropic's cached prefix, is the one the turns before +// had (#502: the turn after it wrote the whole conversation to the cache). +func TestCodexLaterDeveloperMessageKeepsTheSystem(t *testing.T) { + head := codexItem("developer", "sandboxed") + `,` + + codexItem("user", "cwd") + `,` + codexItem("user", "fix the bug") + turn1 := `{"model":"claude-opus-5-5","instructions":"You are Codex.","input":[` + head + `]}` + turn2 := `{"model":"claude-opus-5-5","instructions":"You are Codex.","input":[` + head + `,` + + codexItem("assistant", "done") + `,` + codexItem("developer", "a new skill") + `,` + + codexItem("user", "thanks, and the test?") + `]}` + r1, err := parseResponses([]byte(turn1)) + if err != nil { + t.Fatal(err) + } + r2, err := parseResponses([]byte(turn2)) + if err != nil { + t.Fatal(err) + } + if r1.System != r2.System || !strings.Contains(r1.System, "permissions instructions") { + t.Fatalf("system changed:\n%q\n%q", r1.System, r2.System) + } + var q1, q2 struct { + System json.RawMessage + Messages []json.RawMessage + } + json.Unmarshal(buildAnthropic(r1, "claude-opus-5-5"), &q1) + json.Unmarshal(buildAnthropic(r2, "claude-opus-5-5"), &q2) + if string(q1.System) != string(q2.System) { + t.Fatalf("Anthropic's system changed:\n%s\n%s", q1.System, q2.System) + } + last := r2.Messages[len(r2.Messages)-1] + if len(r2.Messages) != 3 || last.Role != "user" || !strings.Contains(text(last.Parts), "\n") || + !strings.HasSuffix(text(last.Parts), "thanks, and the test?") { + t.Fatalf("messages: %+v", r2.Messages) + } + // the user's words are what the router's classifier is asked about + if got := userText(r2); got != "thanks, and the test?" { + t.Fatalf("user text %q", got) + } + if turn, within := turnIn(r2); turn != 2 || within { + t.Fatalf("turn %d within %v", turn, within) + } +} + +// A Codex thread on a Claude subscription goes on in the Claude Code that +// had its turn before, when a memory request of Codex's (another model, +// its own instructions, the same session) came in between and Codex then +// added a developer message to the thread. +func TestCodexThreadKeepsItsClaudeRunAcrossAMemoryCall(t *testing.T) { + fakeClaude(t) + s := New() + p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}} + said := regexp.MustCompile(`pid \d+ turn \d+`) + ask := func(body string) string { + t.Helper() + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)) + req.Header.Set("session_id", "019a-codex-thread") + rec := httptest.NewRecorder() + var u Usage + if code, msg := s.serveClaudeSubscription(rec, req, provider.Responses, p, "claude-sonnet-5", []byte(body), &u); code != 200 { + t.Fatalf("%d %s", code, msg) + } + got := said.FindString(rec.Body.String()) + if got == "" { + t.Fatalf("no answer: %s", rec.Body) + } + return got + } + tools := `"tools":[{"type":"function","name":"shell","parameters":{"type":"object"}}]` + head := codexItem("developer", "sandboxed") + `,` + codexItem("user", "fix the bug") + first := ask(`{"model":"claude-sonnet-5","instructions":"You are Codex.",` + tools + `,"input":[` + head + `]}`) + pid, _, _ := strings.Cut(strings.TrimPrefix(first, "pid "), " ") + + // Codex's memory extraction: the same session, a prompt of its own + if mem := ask(`{"model":"claude-sonnet-5","instructions":"Extract memories.","input":[` + codexItem("user", "rollout: …") + `]}`); strings.Contains(mem, "pid "+pid+" ") { + t.Fatalf("the memory call took the thread's run: %q", mem) + } + + second := ask(`{"model":"claude-sonnet-5","instructions":"You are Codex.",` + tools + `,"input":[` + head + `,` + + codexItem("assistant", first) + `,` + codexItem("developer", "memories updated") + `,` + + codexItem("user", "and the test?") + `]}`) + if second != "pid "+pid+" turn 2" { + t.Fatalf("the thread's next turn: %q, first %q", second, first) + } +} diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index ee3a20a6c..03461e582 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -159,7 +159,17 @@ func parseResponses(body []byte) (*Request, error) { if err := json.Unmarshal(q.Input, &items); err != nil { return nil, fmt.Errorf("invalid input: %v", err) } + // replied: the conversation has had a turn answered. Codex adds a + // developer message where its context changed (world state, settings, + // a model switch) and keeps it there; lifted into the system prompt it + // changed the prompt's very start, so the whole conversation was + // written to the vendor's cache again (Anthropic's system comes + // first; a Claude subscription's waiting run is found by it) (#502) + replied := false for _, it := range items { + if it.Role == "assistant" || strings.HasPrefix(it.Type, "function_call") || strings.HasPrefix(it.Type, "tool_search") || it.Type == "reasoning" { + replied = true + } switch { case it.Type == "message" || (it.Type == "" && it.Role != ""): role := "user" @@ -167,6 +177,13 @@ func parseResponses(body []byte) (*Request, error) { role = "assistant" } parts := responsesParts(it.Content) + if (it.Role == "system" || it.Role == "developer") && replied { + // in place, told as the system's, not the user's words + if t := text(parts); t != "" { + r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: Text, Text: "\n" + t + "\n"}}}) + } + continue + } if it.Role == "system" || it.Role == "developer" { if t := text(parts); t != "" { if r.System != "" {