gateway: a relayed Responses reply says a namespaced call's arguments are not sealed, so Codex V2 hands the subagent its task (#3183)

Codex offers its collaboration tools in a namespace, and marks
spawn_agent's message "encrypted". On a vendor serving the Responses
API natively the request is relayed as it came, and the vendor's reply
went back as it came too: the function_call for collaboration.spawn_agent
reached Codex with its plain-text arguments and no encrypted_function_args
field at all. Codex reads a namespaced call as DirectPlaintextMessage
only when that field is there and empty (tools/router.rs, rust-v0.163.0),
so it took the task for sealed, wrapped the plain text in an
encrypted_content of its own, and the subagent — asked over that —
replied "tell me the task" and did nothing. The translated path has said
"not sealed" since #613 (callTo's encrypted_function_args []), and the
Grok and Zed relays have had it through nsTidy since #404; the relay to
any other vendor is the branch left out.

What changed: the namespaced tools a Responses request offers are now
read on every relay, not only Grok's and Zed's, and a call that comes
back with its namespace named is answered with the empty
encrypted_function_args list when it carries none. A call carrying a
seal — OpenAI's own, or any upstream that answers the mark — goes back
with that seal untouched, and calls to tools outside every namespace
say nothing about seals either way. The field Codex replays of it in a
later turn's history is still what forVendor leaves out of what a
non-OpenAI vendor is asked (openaiOnly), so the loop closes without the
vendor ever seeing it.

TestNativeRelayNamespacedCallSaysUnsealed relays a request with the
collaboration namespace to a stub vendor whose reply carries the call
streamed and whole, and reads every function_call Codex would see: both
shapes say the arguments are plain text, and the namespace went up as
Codex sent it (the request was relayed, not translated). Without the
fix the call arrives with no encrypted_function_args. TestNativeRelayLeavesOtherCallsBe
holds a sealed call's seal and leaves a plain call alone.

Run: go test ./internal/gateway -count=1 ok (322s); the new tests and
the #404/#613 namespace tests green with and without -race; gofmt -l
clean; go vet of the package clean; CGO_ENABLED=0 go build -tags nogui
for darwin/arm64, linux/amd64 and windows/amd64. Not tried against the
reporter's vendor; the stub's reply is the shape their probe recorded
(namespace and plain arguments kept, no encrypted list).

Generated-by: GLM-5.3-Flash (ZCode)

Landed from ggbdpq's branch (patch posted on the issue; sha256/patch-id
checked against the issue) by yetone, rebased on origin/main 2026-11-03.
Run at the pushed tree, on mote (macOS): go test -tags nogui -count=1 of
internal/gateway with -run over this batch's tests and their families
(PlainSchema, Antigravity, AutoMode, WebP, ClaudeTUI, NativeRelay,
Namespace, Grok, Zed, Codex, ClinePass, rewrite) ok; -race -count=3 of
the new tests ok; GOOS=linux and GOOS=windows go vet of internal/gateway
and gofmt -l clean. The full gateway-and-importers run, started at an
earlier base, was still running at the push; its reds get issues.
Changed in review: the widening is to every Responses relay except
OpenAI's own (openai.com, Azure) and a ChatGPT account (accountAgent
codex), whose replies go back as they came; OpenAI answers the seal
itself, and this does not add the empty list to its replies.
TestSealsItsOwnIsOpenAIOnly holds the exclusion (sealsItsOwn); with
the openai.com and Azure checks taken out its OpenAI and Azure rows go
red.
Broken by hand: the product change reverted,
TestNativeRelayNamespacedCallSaysUnsealed red; restored, green.
Not tried against the reporter's vendor or a real Codex V2 subagent.
This commit is contained in:
ggbdpq
2026-11-03 02:27:57 +08:00
committed by yetone
parent 9fdcb7c31e
commit 3b961f2949
3 changed files with 230 additions and 7 deletions
+13 -5
View File
@@ -5696,9 +5696,13 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
body = xaiBody(p, proto, body)
// a Grok subscription is given Codex's namespaced functions flat
// (grokBody), and Zed's plugin likewise (ZedBody); a call to one goes
// back under its namespace (#404)
// back under its namespace (#404). Any vendor asked as Codex sends it
// has its namespaced calls read by Codex: one without the empty
// encrypted_function_args list reads as sealed (#3183). OpenAI's own
// API and a ChatGPT account answer the mark themselves, and their
// replies go back as they came.
var named map[string]nsTool
if proto == provider.Responses && p.Account != nil && (p.Account.Agent == "grok" || p.PluginProvider() == "grok" || p.PluginProvider() == "zed") {
if proto == provider.Responses && !sealsItsOwn(p) {
named = namespacedIn(body)
}
// a ChatGPT account is given a declared tool whose name its backend
@@ -6257,6 +6261,13 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if tidy != nil {
out = tidy.write(out)
}
// spaces before written: a whole reply (no sse) is held by the
// first filter that takes it, and the call's namespace must be
// worded for Codex before the text calls are read out of the
// message items (#3183)
if spaces != nil {
out = spaces.write(out)
}
if written != nil {
out = written.write(out)
}
@@ -6266,9 +6277,6 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if search != nil {
out = search.write(out)
}
if spaces != nil {
out = spaces.write(out)
}
// crArgs before ints: ints runs on every reply now and holds
// one that came whole to its own flush, which crArgs, after it,
// would never see (#3152 beside #4256's glm-5.3-flash routes)
+29 -2
View File
@@ -13,6 +13,9 @@ package gateway
import (
"bytes"
"encoding/json"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// Codex groups some tools in a namespace (collaboration's spawn_agent,
@@ -175,12 +178,28 @@ func (t *nsTidy) carries(b []byte) bool {
// call names a function_call to a namespaced function by its name and
// namespace, or a call to a tool renamed for a ChatGPT account by the
// agent's name, and reports whether it was one.
// agent's name, and reports whether it was one. A call whose namespace
// the upstream said itself (a vendor asked as Codex sends it, #3183)
// needs no naming, only the word that its arguments are not sealed: Codex
// reads a namespaced call without the empty list as sealed, and the
// plain-text task would reach its subagent as ciphertext.
func (t *nsTidy) call(it map[string]any) bool {
if it == nil || it["namespace"] != nil || it["type"] != "function_call" && it["type"] != "custom_tool_call" {
if it == nil || it["type"] != "function_call" && it["type"] != "custom_tool_call" {
return false
}
name, _ := it["name"].(string)
if ns, _ := it["namespace"].(string); ns != "" {
for _, q := range t.named {
if q.Namespace == ns && q.Name == name {
if _, ok := it["encrypted_function_args"]; !ok {
it["encrypted_function_args"] = []any{}
return true
}
break
}
}
return false
}
if n, ok := t.back[name]; ok {
it["name"] = n
return true
@@ -194,3 +213,11 @@ func (t *nsTidy) call(it map[string]any) bool {
callTo(it, name, t.named)
return true
}
// sealsItsOwn says p is OpenAI's own Responses API (openai.com, Azure) or a
// ChatGPT account: it answers a namespaced call's seal itself, and its
// replies go back as they came, never given the empty
// encrypted_function_args a relay's are (#3183).
func sealsItsOwn(p provider.Provider) bool {
return accountAgent(p) == "codex" || strings.HasSuffix(p.Host(), "openai.com") || p.IsAzure()
}
@@ -0,0 +1,188 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// codexCollabTools is Codex's collaboration namespace, spawn_agent in it.
const codexCollabTools = `"tools":[
{"type":"function","name":"exec_command","parameters":{"type":"object"}},
{"type":"namespace","name":"collaboration","description":"Tools in the collaboration namespace.","tools":[
{"type":"function","name":"spawn_agent","description":"Spawns an agent.","parameters":{"type":"object","properties":{"message":{"type":"string","encrypted":true}}}}
]}
]`
// #3183 (john-zeng-233): a vendor serving the Responses API natively is
// relayed Codex's request as it came, and its reply goes back as it came:
// the call to collaboration.spawn_agent reached Codex without the empty
// encrypted_function_args list, and Codex read the plain-text message as
// sealed — the subagent was handed its task in an encrypted_content and
// asked what the task was. Codex picks DirectPlaintextMessage only when
// the list is there and empty, as the translated path's callTo gives it.
func TestNativeRelayNamespacedCallSaysUnsealed(t *testing.T) {
fresh(t)
var mu sync.Mutex
var sent []map[string]any
call := `{"type":"function_call","id":"fc_1","call_id":"c9","name":"spawn_agent","namespace":"collaboration","arguments":"{\"message\":\"go\"}","status":"completed"}`
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var q map[string]any
json.Unmarshal(b, &q)
mu.Lock()
sent = append(sent, q)
mu.Unlock()
done := `{"id":"r1","object":"response","status":"completed","output":[` + call + `],"usage":{"input_tokens":5,"output_tokens":3}}`
if q["stream"] != true {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, done)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`,
`event: response.output_item.added`+"\n"+`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"c9","name":"spawn_agent","namespace":"collaboration","arguments":""}}`,
`event: response.output_item.done`+"\n"+`data: {"type":"response.output_item.done","output_index":0,"item":`+call+`}`,
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":`+done+`}`))
}))
defer up.Close()
if err := provider.Save(provider.Provider{ID: "ucloud", Name: "UCloud", Key: "k", Models: []string{"m"}, Responses: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
s := New()
for _, stream := range []bool{true, false} {
mu.Lock()
sent = nil
mu.Unlock()
body := `{"model":"ucloud/m","stream":` + map[bool]string{true: "true", false: "false"}[stream] + `,` + codexCollabTools + `,"input":[{"type":"message","role":"user","content":"go"}]}`
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("stream %v: %d %s", stream, rec.Code, rec.Body)
}
// relayed, not translated: the namespace went up as Codex sent it
mu.Lock()
if len(sent) != 1 {
t.Fatalf("stream %v: the vendor was asked %d times", stream, len(sent))
}
q := sent[0]
mu.Unlock()
tools, _ := q["tools"].([]any)
if len(tools) != 2 {
t.Fatalf("stream %v: the vendor was offered %v", stream, q["tools"])
}
if tm, _ := tools[1].(map[string]any); tm["type"] != "namespace" || tm["name"] != "collaboration" {
t.Fatalf("stream %v: the request was translated, its tools went as %v", stream, q["tools"])
}
// every function_call Codex reads says its arguments are plain text
var items []map[string]any
if stream {
for _, line := range strings.Split(rec.Body.String(), "\n") {
data, ok := strings.CutPrefix(line, "data: ")
if !ok {
continue
}
var ev struct {
Item map[string]any `json:"item"`
Response struct {
Output []map[string]any `json:"output"`
} `json:"response"`
}
if err := json.Unmarshal([]byte(data), &ev); err != nil {
t.Fatalf("%v: %s", err, data)
}
if ev.Item != nil {
items = append(items, ev.Item)
}
items = append(items, ev.Response.Output...)
}
} else {
var res struct {
Output []map[string]any `json:"output"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("%v: %s", err, rec.Body)
}
items = res.Output
}
if len(items) == 0 || stream && len(items) != 3 {
t.Fatalf("stream %v: %s", stream, rec.Body)
}
for _, it := range items {
sealed, ok := it["encrypted_function_args"].([]any)
if it["name"] != "spawn_agent" || it["namespace"] != "collaboration" || !ok || len(sealed) != 0 {
t.Fatalf("stream %v: Codex was given %v", stream, it)
}
}
}
}
// The seal a reply carries is the seal the client reads: an upstream that
// answered a namespaced call with its arguments sealed hands that seal on
// untouched, and a call to a tool outside every namespace says nothing
// about seals either way (#3183).
func TestNativeRelayLeavesOtherCallsBe(t *testing.T) {
fresh(t)
sealed := `{"type":"function_call","id":"fc_1","call_id":"c9","name":"spawn_agent","namespace":"collaboration","arguments":"","encrypted_function_args":[{"content":"gAAAAAsealed"}],"status":"completed"}`
plain := `{"type":"function_call","id":"fc_2","call_id":"c8","name":"exec_command","arguments":"{}","status":"completed"}`
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"r1","object":"response","status":"completed","output":[`+sealed+`,`+plain+`],"usage":{"input_tokens":5,"output_tokens":3}}`)
}))
defer up.Close()
if err := provider.Save(provider.Provider{ID: "ucloud", Name: "UCloud", Key: "k", Models: []string{"m"}, Responses: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
s := New()
body := `{"model":"ucloud/m","stream":false,` + codexCollabTools + `,"input":[{"type":"message","role":"user","content":"go"}]}`
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
var res struct {
Output []map[string]any `json:"output"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatal(err)
}
if len(res.Output) != 2 {
t.Fatalf("%s", rec.Body.String())
}
if got, ok := res.Output[0]["encrypted_function_args"].([]any); !ok || len(got) != 1 {
t.Fatalf("the seal was lost: %v", res.Output[0])
}
if _, ok := res.Output[1]["encrypted_function_args"]; ok {
t.Fatalf("a plain call was given a seal: %v", res.Output[1])
}
}
// OpenAI's own API, Azure's and a ChatGPT account answer the seal
// themselves: their replies are not given the empty list a relay's are,
// and a third-party relay's are (#3183).
func TestSealsItsOwnIsOpenAIOnly(t *testing.T) {
for _, tc := range []struct {
name string
p provider.Provider
own bool
}{
{"OpenAI's API", provider.Provider{ID: "openai", Responses: "https://api.openai.com/v1"}, true},
{"Azure", provider.Provider{ID: "az", Responses: "https://x.openai.azure.com/openai/v1"}, true},
{"a ChatGPT account", provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex"}}, true},
{"a relay", provider.Provider{ID: "ucloud", Responses: "https://api.modelverse.cn/v1"}, false},
{"a Grok account", provider.Provider{ID: "grok", Account: &provider.Account{Agent: "grok"}, Responses: "https://api.x.ai/v1"}, false},
} {
if got := sealsItsOwn(tc.p); got != tc.own {
t.Errorf("%s: sealsItsOwn %v, want %v", tc.name, got, tc.own)
}
}
}