diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f83e0cf5f..c6d01e795 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -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 diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index a5f1ba249..a90dbd31d 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -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 diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 34e9d34d9..45d06e53c 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -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}) diff --git a/internal/gateway/codeassist.go b/internal/gateway/codeassist.go index da23394d3..eef937519 100644 --- a/internal/gateway/codeassist.go +++ b/internal/gateway/codeassist.go @@ -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 diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 805f744b0..99bce8c24 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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: diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index 77c900bb8..906bf03e6 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -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 } diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index 90db1e2f5..fdde827ce 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -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: "\n" + t + "\n"}}}) + } 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 { diff --git a/internal/gateway/responses_instruction_roles_test.go b/internal/gateway/responses_instruction_roles_test.go new file mode 100644 index 000000000..36e885a9a --- /dev/null +++ b/internal/gateway/responses_instruction_roles_test.go @@ -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, "Plan: do not edit files."}, + {role, "Keep the task local."}, + {"user", "Plan a change."}, + {"assistant", "The plan is ready."}, + {role, "Default: previous Plan instructions no longer apply."}, + {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) + } + }) + } +} diff --git a/internal/gateway/search_own_api_test.go b/internal/gateway/search_own_api_test.go index 3d40bb2f3..6bc436e05 100644 --- a/internal/gateway/search_own_api_test.go +++ b/internal/gateway/search_own_api_test.go @@ -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) + } + } }