gateway: a Codex mode switch keeps its developer role on a translated Responses turn (#2532)

Refs yetone/magpie#2532 (the Responses-to-Responses translation case).
An offered web_search can select translation even for a Responses upstream.
Keep system/developer items in place instead of lifting initial Plan
instructions and demoting a later Default update to a user reminder.
Other APIs and the Claude bridge retain their existing cache mapping.
Update the gateway routing reference and cover search continuation rounds.

Verification on macOS arm64 with Go 1.26.10, isolated HOME and pinned caches:
- New tests on unmodified cc04ce68c1 plus
  test changes fail with real assertions in
  TestResponsesInstructionRolesThroughSearch (developer/system),
  TestResponsesInstructionsOtherAPIsUnchanged and
  TestCodexSearchAnsweredOnResponses.
- Those patched tests, TestCodexLaterDeveloperMessageKeepsTheSystem and
  TestSearchOfferedStaysOnTheClientsAPI pass, also with -race.
- gofmt and diff checks pass.
- Native, Linux/nogui and Windows vet and builds pass.
- go test -tags nogui ./... fails in the unchanged internal/agent package:
  TestRunningNeedsNoPs cannot find its sleep 314.159 process. The complete
  internal/gateway suite passes (427.556s), as do the other packages.
- The patched executable against an isolated local capture upstream keeps
  Plan and Default as developer messages in minimal and full histories
  with web_search offered; real configuration hashes remain unchanged.
Not run: paid real-upstream acceptance, native Linux/Windows runtime tests,
or browser GUI tests (no GUI assets changed).

The unrelated agent failure was traced to macOS pgrep returning exit 3,
"Regular expression evaluation error (illegal byte sequence)", under the
inherited locale. The same local sleep process is found with LC_ALL=C.
TestRunningNeedsNoPs fails 20/20 under -race with the inherited locale and
passes 20/20 with LC_ALL=C (3.848s). No agent code or timeout was changed.
A full-suite recheck with LC_ALL=C is running at commit time; retain the
initial failure and publish as a draft until that recheck completes.

Adapted when landing: a blank line before the next heading in
docs/subsystems/gateway-routing.md. Cherry-picked by ggbdpq (gua2100).

Review and run record (landed by the maintainer's agent; gua2100 brought
both fixes from Discord, rebased onto main):
- External code, read line by line: no network, dependency, workflow or
  credential change; Codex base_instructions/identity untouched.
- Base origin/main d99e213f5. Full checks on mote (macOS, Go 1.26.8,
  sandbox HOME) at 31f025634, whose tree is the one pushed (only messages reworded since): gofmt, go vet darwin, linux,
  windows, builds for all three: rc=0. go test -tags nogui -count=1
  -timeout 45m ./...: 79 packages ok, internal/gateway ok (855s); two reds
  in untouched packages, both filed before: internal/plugin
  TestGatewayHookMixedPiPackage (#2865, "starting plugins: context deadline
  exceeded") and internal/update TestRelaunchOpenTriedAgain (#3881). Run
  alone at the same tree both pass (plugin 97s; update -count=3).
- Broken by hand: the #3739 regex reverted, so both Kimi tests fail (400
  handed back). The #2532 product files reverted (six files), so all three
  tests fail. The mergeTurns role guard removed fails (5 input messages,
  want 7).
- Real binary on mote, sandbox HOME, a fake upstream that records requests:
  at d99e213f5, wrke1990's literal #2532 body sends Plan in instructions
  and Default as a user <system-reminder>; at HEAD both developer items
  keep their role and place. #3739's curl body (and zfsdream96's ZCode
  shape, output_config effort max, no thinking) is a 400 at d99e213f5; at
  HEAD it is a 200 after one retry without thinking, and the next
  request goes without disabled.
- Rebased onto fa427216a (responses.go stream deltas, landed meanwhile;
  no conflict). At the rebased pushed tree: gofmt, go vet and
  go test -count=1 ./internal/gateway ok (580s) on mote. The full suite
  was not rerun after that rebase.
- Not covered: the search reroute's re-parse when a fallback changes
  whether the target is Responses (breaking it leaves the tests green;
  no route found that reaches it). Not tried: the real Kimi Code
  endpoint and its kimi-code-cn preset (a custom Anthropic provider with
  Kimi's literal 400 was used), a real Codex session against a paid
  upstream, Windows/Linux runtime. #3739's second symptom (k3 losing
  thinking when output_config.effort is asked) is not addressed.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
wrke1990
2026-10-30 21:38:00 +08:00
committed by yetone
co-authored by ggbdpq
parent 72e8d9fa6c
commit 024393fbb9
9 changed files with 233 additions and 16 deletions
+22
View File
@@ -1233,6 +1233,28 @@ the row of the entry that id reaches, with its label, under the bare id.
`internal/gui/tests/bare-ids.test.cjs`.
- A URL magpie downloads but didn't choose itself is downloaded from public addresses only, wherever the request came from ([`image_fetch_guard.go`](../../internal/gateway/image_fetch_guard.go)). That is an image a caller names (an `/v1/images/edits` or `/v1/images/generations` reference image, for an images API that takes files, Gemini's own API or Code Assist: `fetchPicture` in [`draw.go`](../../internal/gateway/draw.go), `publicClient`), a page `web_fetch` reads (`webFetchClient`), and an image or video a vendor answers by URL, which what the model was asked to draw or do can steer (the inline download for a `b64_json` caller in `draw.go` and `/v1/videos/{id}/content` in [`video.go`](../../internal/gateway/video.go), `vendorClient`; generate_image's own download in [`internal/imagemcp`](../../internal/imagemcp/imagemcp.go), `PublicClient`). Every address the host resolves to must be public (`publicAddr`, which is [`internal/netguard`](../../internal/netguard/netguard.go)'s `Public`, the rule a provider's icon uses too: not loopback, RFC 1918, fc00::/7, link-local with 169.254.169.254, CGNAT 100.64/10, unspecified, multicast, documentation, reserved, benchmarking, Teredo, nor an IPv4-mapped, NAT64 or 6to4 form of one; an AAAA record Loon synthesizes for an A answer in the same reply, `fd27:712::/96` with that IPv4 address inside, is left out and the A answer judged in its place, `dropLoon`), and the request goes to the address checked, so a name that resolves elsewhere the second time changes nothing; a direct connection is checked again on the address dialled (`guardDialer`). Through a proxy the proxy is sent that address, never the name (an `https://` CONNECT or SOCKS keeps the name for TLS and Host; a plain `http://` URL through an HTTP proxy is asked for by the address in Host too). A fake-IP resolver's answer is the one shape let past that (#2593; ggbdpq, with h4rk8s's and TomXPRIME's reports): Clash's TUN with fake-ip, Clash Verge, Surge's enhanced mode and Loon answer every name in 198.18.0.0/15 (`netguard.FakeIP`), so with one on every download was refused as a private address. A name (never an address literal) whose every answer is in that range is fetched: with no proxy (pure TUN) its fake address is pinned and dialled, the dial guard letting that one address in, and the TUN carries it; through a proxy on this computer (a loopback address or `localhost`, `onThisComputer`) the proxy is given the name, never the fake address, which a real proxy can't route (h4rk8s: a CONNECT by the name went through where one by its 198.18 address failed), and a plain `http://` request's Host is the checked name, never the caller's own; through a proxy elsewhere it is refused. An answer with any other address beside the fake ones (private or public) is judged as any, so a fake one beside 192.168.x is refused. The trust this asks for is the fake-IP resolver's: which host the name stands for, and so where the TUN or the proxy connects, is decided where magpie can't see, and a name that really points at the user's network is reached if that resolver's rules send it there. A provider's icon was already fetched this way (`publicIP` in [`internal/provider/icon.go`](../../internal/provider/icon.go), #252), and shares the rule. `TestFakeIPNameGoesToALocalProxyByName`, `TestFakeIPNameDialledThroughTheTUN`, `TestFakeIPRefusesTheRest` in [`fakeip_test.go`](../../internal/gateway/fakeip_test.go). Each redirect, up to 5, is checked the same, and a caller's image must sniff as an image. A request from this computer gets nothing more: a reverse proxy or relay in front of magpie on the same host makes every request it carries arrive from loopback, so where a request came from is never a reason to reach a private address. Two things are: settings.json's `fetchPrivate` (`settings.FetchPrivate`, none by default, no Settings page, this computer's own and never brought by a sync or restore), a list of names, `name:port`s, IPs and CIDR ranges the user lets magpie download from (`allowFor`; a settings.json that can't be read lets nothing extra in), and for a vendor's URL the `host:port` of that provider's own endpoints, which the user named themselves (a provider on the LAN that serves its images from itself). A vendor's image that can't be downloaded is answered by its URL, never dropped; its video is a 502 naming why. A URL left for the vendor to fetch (a chat model's message) is the vendor's to fetch.
### Instruction roles on translated Responses turns
A Responses request translated back to Responses keeps its `system` and
`developer` input messages in place, including messages added after an
assistant reply (`parseRequest` in
[`gateway.go`](../../internal/gateway/gateway.go), `readResponsesFor` in
[`responses.go`](../../internal/gateway/responses.go)). Its top-level
`instructions` stays separate. Offering `web_search` to a custom provider
that is not known to search natively can select this path even when no
search is called. Previously it lifted initial instruction items into
`instructions` and changed later ones into user reminders, so a Codex
Plan-to-Default transition lost its developer authority.
This does not change the Claude subscription or other APIs' existing
cache-preserving mapping. If the upstream falls back from Responses to
another API, that API's builder applies the existing mapping through
`responseInstructions`; building it leaves the native request intact.
`TestResponsesInstructionRolesThroughSearch` checks the upstream-bound
roles and positions, `TestCodexSearchAnsweredOnResponses` checks both sides
of a search round, and `TestResponsesInstructionsOtherAPIsUnchanged`
compares the other builders with their previous output.
## A Responses WebSocket
Codex speaks Responses over a WebSocket to its own provider, which magpie's
+1
View File
@@ -898,6 +898,7 @@ func buildAnthropic(r *Request, model string) []byte {
// signature goes as its text instead of being left out. host is the
// upstream's (outputEffortAt).
func anthropicBody(r *Request, model, host string, replay bool) []byte {
r = responseInstructions(r)
if r.Format != nil && r.Format.schema() == nil {
// output_config.format takes a schema only: any JSON object is
// asked for in words
+1
View File
@@ -321,6 +321,7 @@ func chatReplaysReasoning(host, model string) bool {
}
func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
r = responseInstructions(r)
var msgs []map[string]any
if r.System != "" {
msgs = append(msgs, map[string]any{"role": "system", "content": r.System})
+1
View File
@@ -315,6 +315,7 @@ func buildCodeAssist(r *Request, model, agent string) []byte {
// the request goes out under is the one everything below is shaped from.
// agent "vertex" is Vertex AI's request (buildVertex).
func buildCodeAssistSent(r *Request, sent, agent string) []byte {
r = responseInstructions(r)
ag := agent == "antigravity"
vx := agent == "vertex"
at := "" // the level the id says it thinks at
+27 -13
View File
@@ -6707,10 +6707,29 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
msg := "input_image without image_url cannot be translated; send an image_url or use a native Responses route"
return writeError(w, from, 400, msg), msg
}
request, err := parse(from, body)
request, err := parseRequest(from, body, false, to == provider.Responses)
if err != nil {
return writeError(w, from, 400, err.Error()), err.Error()
}
if request.WebSearch {
// an API on which the provider searches by itself comes first;
// without one, its model is given magpie's search. A searcher
// asked for another model goes there too: on its first API
// (DeepSeek's Chat) it had no search tool and answered from
// nothing (#669)
for _, t := range s.usable(p, model) {
if searchesFor(p, t, model, request) {
if from == provider.Responses && (to == provider.Responses) != (t == provider.Responses) {
request, err = parseRequest(from, body, false, t == provider.Responses)
if err != nil {
return writeError(w, from, 400, err.Error()), err.Error()
}
}
to = t
break
}
}
}
// a Grok model's 2500.0 in a call's arguments, which Codex turns away
// (grok_integral.go, #1431)
request.Grok = grokServed(wiresOf(r.Context()), p, model)
@@ -6724,17 +6743,6 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
zen = &zenReply{z: zenFreeTools(request)}
}
if request.WebSearch {
// an API on which the provider searches by itself comes first;
// without one, its model is given magpie's search. A searcher
// asked for another model goes there too: on its first API
// (DeepSeek's Chat) it had no search tool and answered from
// nothing (#669)
for _, t := range s.usable(p, model) {
if searchesFor(p, t, model, request) {
to = t
break
}
}
if !searching(r.Context()) && canSearchFor(p) && !searchesFor(p, to, model, request) {
ask := antigravityRound(w, p, s.askTranslated(p, to, model, r.Header, w.Header()))
if zen != nil {
@@ -6973,13 +6981,19 @@ func parse(proto provider.Protocol, body []byte) (*Request, error) {
// parseIn is parse, for facts only as readResponses, readChat and
// readAnthropic say.
func parseIn(proto provider.Protocol, body []byte, facts bool) (*Request, error) {
return parseRequest(proto, body, facts, false)
}
// parseRequest keeps native instruction messages for Responses-to-Responses
// turns. Routing facts and subscription backends keep their existing mapping.
func parseRequest(proto provider.Protocol, body []byte, facts, keepInstructions bool) (*Request, error) {
var req *Request
var err error
switch proto {
case provider.Chat:
req, err = readChat(body, facts)
case provider.Responses:
req, err = readResponses(body, facts)
req, err = readResponsesFor(body, facts, keepInstructions)
case provider.Gemini:
req, err = parseGemini(body)
default:
+1 -1
View File
@@ -118,7 +118,7 @@ func attachmentText(p Part) string {
// Message is one turn.
type Message struct {
Role string // user | assistant
Role string // user | assistant; system | developer on Responses-to-Responses
Parts []Part
}
+45 -1
View File
@@ -323,6 +323,12 @@ func parseResponses(body []byte) (*Request, error) { return readResponses(body,
// of raw values a parse kept would need. Run on every request, a long
// Codex conversation's tool outputs were most of the parse (#3394).
func readResponses(body []byte, facts bool) (*Request, error) {
return readResponsesFor(body, facts, false)
}
// readResponsesFor keeps instruction roles and positions on Responses-to-
// Responses turns. Other APIs keep their existing system/cache mapping.
func readResponsesFor(body []byte, facts, keepInstructions bool) (*Request, error) {
decode := decodeJSON
if facts {
decode = decodeJSONView
@@ -376,6 +382,10 @@ func readResponses(body []byte, facts bool) (*Request, error) {
if !facts || role != "assistant" {
parts = responsesParts(it.Content)
}
if keepInstructions && (it.Role == "system" || it.Role == "developer") {
r.Messages = append(r.Messages, Message{Role: it.Role, Parts: parts})
continue
}
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 != "" {
@@ -890,7 +900,7 @@ func pairToolItems(body []byte) []byte {
func mergeTurns(msgs []Message) []Message {
var out []Message
for _, m := range msgs {
if n := len(out); n > 0 && out[n-1].Role == m.Role {
if n := len(out); n > 0 && out[n-1].Role == m.Role && (m.Role == "user" || m.Role == "assistant") {
out[n-1].Parts = append(out[n-1].Parts, m.Parts...)
continue
}
@@ -899,6 +909,40 @@ func mergeTurns(msgs []Message) []Message {
return out
}
// responseInstructions applies the existing cache-preserving mapping only
// at an API that cannot keep native Responses instruction items.
func responseInstructions(r *Request) *Request {
if !slices.ContainsFunc(r.Messages, func(m Message) bool { return m.Role == "system" || m.Role == "developer" }) {
return r
}
out := *r
out.Messages = nil
replied := false
for _, m := range r.Messages {
if m.Role == "assistant" || slices.ContainsFunc(m.Parts, func(p Part) bool {
return p.Kind == ToolCall || p.Kind == ToolResult || p.Kind == Thinking
}) {
replied = true
}
if m.Role == "system" || m.Role == "developer" {
if t := text(m.Parts); t != "" {
if replied {
out.Messages = append(out.Messages, Message{Role: "user", Parts: []Part{{Kind: Text, Text: "<system-reminder>\n" + t + "\n</system-reminder>"}}})
} else {
if out.System != "" {
out.System += "\n\n"
}
out.System += t
}
}
continue
}
out.Messages = append(out.Messages, m)
}
out.Messages = mergeTurns(out.Messages)
return &out
}
func responsesParts(raw json.RawMessage) []Part {
var s string
if decodeJSON(raw, &s) == nil {
@@ -0,0 +1,112 @@
package gateway
import (
"encoding/json"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Offering search can translate a Responses request back to Responses. Mode
// changes must keep their authority even though the request is not relayed.
func TestResponsesInstructionRolesThroughSearch(t *testing.T) {
srv, seen := relayOfEvery(t)
fresh(t)
if err := provider.Save(provider.Provider{
ID: "instruction-relay", Name: "Instruction relay", Key: "k",
Responses: srv.URL + "/v1", Models: []string{"example-model"},
}); err != nil {
t.Fatal(err)
}
for _, role := range []string{"developer", "system"} {
t.Run(role, func(t *testing.T) {
seen()
messages := []struct{ role, text string }{
{role, "<collaboration_mode>Plan: do not edit files.</collaboration_mode>"},
{role, "Keep the task local."},
{"user", "Plan a change."},
{"assistant", "The plan is ready."},
{role, "<collaboration_mode>Default: previous Plan instructions no longer apply.</collaboration_mode>"},
{role, "Implement the accepted plan."},
{"user", "Implement the plan."},
}
var input []string
for _, m := range messages {
input = append(input, codexItem(m.role, m.text))
}
body := `{"model":"instruction-relay/example-model","stream":true,"instructions":"You are a coding assistant.",` +
`"input":[` + strings.Join(input, ",") + `],"tools":[{"type":"web_search"}]}`
if code, out := post(t, "/v1/responses", body); code != 200 {
t.Fatalf("%d %s", code, out)
}
paths, bodies := seen()
if len(paths) != 1 || paths[0] != "/v1/responses" {
t.Fatalf("upstream paths %v, want one Responses request", paths)
}
var got struct {
Instructions string `json:"instructions"`
Input []struct {
Type, Role string
Content json.RawMessage
} `json:"input"`
}
if err := json.Unmarshal([]byte(bodies[0]), &got); err != nil {
t.Fatal(err)
}
if got.Instructions != "You are a coding assistant." {
t.Fatalf("instruction item moved into the prefix: %q", got.Instructions)
}
if len(got.Input) != len(messages) {
t.Fatalf("input messages %d, want %d: %s", len(got.Input), len(messages), bodies[0])
}
for i, want := range messages {
m := got.Input[i]
if m.Type != "message" || m.Role != want.role || text(responsesParts(m.Content)) != want.text {
t.Errorf("input[%d]: %s %s %s, want %s %q", i, m.Type, m.Role, m.Content, want.role, want.text)
}
}
})
}
}
// A provider can fall back from Responses to another API. Its existing
// mapping still applies there, and building it must not mutate the native turn.
func TestResponsesInstructionsOtherAPIsUnchanged(t *testing.T) {
body := []byte(`{"model":"example-model","instructions":"You are Codex.","input":[` +
codexItem("developer", "Plan: do not edit files.") + `,` +
codexItem("user", "Plan a change.") + `,` +
codexItem("assistant", "The plan is ready.") + `,` +
codexItem("developer", "Default: implement the plan.") + `,` +
codexItem("user", "Implement it.") + `]}`)
native := &Request{Model: "example-model", System: "You are Codex.", Messages: []Message{
{Role: "developer", Parts: []Part{{Kind: Text, Text: "Plan: do not edit files."}}},
{Role: "user", Parts: []Part{{Kind: Text, Text: "Plan a change."}}},
{Role: "assistant", Parts: []Part{{Kind: Text, Text: "The plan is ready."}}},
{Role: "developer", Parts: []Part{{Kind: Text, Text: "Default: implement the plan."}}},
{Role: "user", Parts: []Part{{Kind: Text, Text: "Implement it."}}},
}}
legacy, err := parse(provider.Responses, body)
if err != nil {
t.Fatal(err)
}
before := string(buildResponses(native, "example-model", "", false))
for _, proto := range []provider.Protocol{provider.Chat, provider.Anthropic, provider.Gemini} {
t.Run(string(proto), func(t *testing.T) {
got, err := build(proto, native, "example-model", "", false)
if err != nil {
t.Fatal(err)
}
want, err := build(proto, legacy, "example-model", "", false)
if err != nil {
t.Fatal(err)
}
if string(got) != string(want) {
t.Fatalf("non-Responses mapping changed:\ngot %s\nwant %s", got, want)
}
if after := string(buildResponses(native, "example-model", "", false)); after != before {
t.Fatalf("building %s mutated the native request:\n%s\n%s", proto, before, after)
}
})
}
}
+23 -1
View File
@@ -2,6 +2,7 @@ package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
@@ -116,7 +117,11 @@ func TestCodexSearchAnsweredOnResponses(t *testing.T) {
if _, err := p.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
code, out := post(t, "/v1/responses", `{"model":"xiaomi/mimo-v2.6-flash","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"What is the latest Go?"}]}],
code, out := post(t, "/v1/responses", `{"model":"xiaomi/mimo-v2.6-flash","stream":true,"instructions":"You are a coding assistant.","input":[`+
codexItem("developer", "Plan: do not make changes.")+`,`+
codexItem("user", "Plan a version check.")+`,`+
codexItem("assistant", "Check the latest Go release.")+`,`+
codexItem("developer", "Default: previous Plan instructions no longer apply.")+`,{"type":"message","role":"user","content":[{"type":"input_text","text":"What is the latest Go?"}]}],
"tools":[{"type":"function","name":"shell","description":"run","parameters":{"type":"object","properties":{}}},{"type":"web_search","external_web_access":false}]}`)
if code != 200 {
t.Fatalf("%d %s", code, out)
@@ -133,4 +138,21 @@ func TestCodexSearchAnsweredOnResponses(t *testing.T) {
if !strings.Contains(asked[0], `"web_search"`) || !strings.Contains(asked[1], "1.27.1") {
t.Fatalf("search tool or result not given to the model:\n%s\n%s", asked[0], asked[1])
}
for i, body := range asked {
var sent struct {
Instructions string `json:"instructions"`
Input []struct {
Role string
Content json.RawMessage
} `json:"input"`
}
if err := json.Unmarshal([]byte(body), &sent); err != nil {
t.Fatal(err)
}
if sent.Instructions != "You are a coding assistant." || len(sent.Input) < 5 ||
sent.Input[0].Role != "developer" || sent.Input[3].Role != "developer" ||
text(responsesParts(sent.Input[3].Content)) != "Default: previous Plan instructions no longer apply." {
t.Fatalf("search round %d changed instruction authority: %s", i+1, body)
}
}
}