diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 32848706b..5feb16bbe 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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) diff --git a/internal/gateway/grok_namespace.go b/internal/gateway/grok_namespace.go index e65866234..110248753 100644 --- a/internal/gateway/grok_namespace.go +++ b/internal/gateway/grok_namespace.go @@ -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() +} diff --git a/internal/gateway/native_relay_collab_test.go b/internal/gateway/native_relay_collab_test.go new file mode 100644 index 000000000..765492ac0 --- /dev/null +++ b/internal/gateway/native_relay_collab_test.go @@ -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) + } + } +}