From 5b917c1d8fd886d4e9a66af5cf34fe2bee8219a6 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 1 Oct 2026 16:07:24 +0800 Subject: [PATCH] =?UTF-8?q?grok:=20Codex's=20sub-agent=20tools=20reach=20a?= =?UTF-8?q?=20Grok=20subscription=20(#404)=20=E2=80=94=20Codex=20groups=20?= =?UTF-8?q?spawn=5Fagent,=20wait=5Fagent,=20send=5Fmessage=20and=20followu?= =?UTF-8?q?p=5Ftask=20in=20its=20collaboration=20namespace=20and=20set=5Ft?= =?UTF-8?q?hread=5Ftitle=20in=20codex=5Fapp,=20and=20since=20aa08863d12=20?= =?UTF-8?q?a=20namespace=20was=20left=20out=20whole,=20as=20Grok's=20backe?= =?UTF-8?q?nd=20turns=20a=20request=20away=20over=20the=20type:=20multi=5F?= =?UTF-8?q?agent=5Fv2=20on=20Grok=20had=20no=20tools=20to=20spawn=20with.?= =?UTF-8?q?=20A=20namespace's=20functions=20now=20go=20to=20Grok=20as=20fu?= =?UTF-8?q?nctions=20of=20their=20own=20under=20the=20flat=20name=20the=20?= =?UTF-8?q?translation=20path=20gives=20them=20(collaboration=5F=5Fspawn?= =?UTF-8?q?=5Fagent,=20flatName,=20now=20provider.FlatName),=20and=20so=20?= =?UTF-8?q?do=20a=20call=20to=20one=20handed=20back=20and=20a=20tool=5Fcho?= =?UTF-8?q?ice=20naming=20one;=20the=20namespace=20type=20itself=20still?= =?UTF-8?q?=20never=20reaches=20Grok,=20nor=20does=20a=20freeform=20tool?= =?UTF-8?q?=20(apply=5Fpatch,=20or=20one=20inside=20a=20namespace),=20and?= =?UTF-8?q?=20a=20namespace=20with=20no=20function=20goes=20whole.=20Respo?= =?UTF-8?q?nses=20Lite's=20"functions"=20namespace=20stays=20plain=20names?= =?UTF-8?q?.=20On=20the=20way=20back=20a=20call=20Grok=20makes=20to=20a=20?= =?UTF-8?q?flat=20name=20reaches=20Codex=20under=20its=20own=20name=20and?= =?UTF-8?q?=20namespace=20with=20an=20empty=20encrypted=5Ffunction=5Fargs,?= =?UTF-8?q?=20as=20callTo=20gives=20one,=20streamed=20(output=5Fitem.added?= =?UTF-8?q?/done,=20response.completed)=20or=20not.=20A=20ChatGPT=20accoun?= =?UTF-8?q?t=20still=20gets=20the=20namespace=20as=20Codex=20sent=20it.=20?= =?UTF-8?q?TestGrokGetsNamespacedTools=20(a=20fake=20Grok=20upstream=20ret?= =?UTF-8?q?urning=20a=20call=20to=20collaboration=5F=5Fspawn=5Fagent),=20T?= =?UTF-8?q?estGrokBodyFlattensNamespacedCalls=20and=20the=20updated=20Test?= =?UTF-8?q?GrokBodyLeavesOutCustomTools=20fail=20without=20the=20change.?= =?UTF-8?q?=20go=20vet,=20go=20build=20-tags=20nogui=20(darwin,=20GOOS=3Dl?= =?UTF-8?q?inux),=20GOOS=3Dwindows=20go=20build,=20go=20test=20-tags=20nog?= =?UTF-8?q?ui=20./...=20pass=20(TestUserPath,=20a=20load=20flake,=20passes?= =?UTF-8?q?=20alone).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/gateway.go | 22 ++- internal/gateway/grok_namespace.go | 169 ++++++++++++++++++++++++ internal/gateway/grok_namespace_test.go | 131 ++++++++++++++++++ internal/gateway/responses.go | 17 +-- internal/provider/grok.go | 74 ++++++++++- internal/provider/grok_test.go | 46 ++++++- 6 files changed, 440 insertions(+), 19 deletions(-) create mode 100644 internal/gateway/grok_namespace.go create mode 100644 internal/gateway/grok_namespace_test.go diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 59eb53f28..51edd331e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1684,6 +1684,12 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if proto != provider.Anthropic { body = s.withoutRefused(p.ID, proto, body) } + // a Grok subscription is given Codex's namespaced functions flat + // (grokBody); a call to one goes back under its namespace (#404) + var named map[string]nsTool + if proto == provider.Responses && p.Account != nil && p.Account.Agent == "grok" { + named = namespacedIn(body) + } res, err := s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header) if err != nil { return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true @@ -1792,6 +1798,10 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if searchFn && sse { search = &searchTidy{} } + var spaces *nsTidy + if named != nil { + spaces = &nsTidy{named: named, sse: sse} + } buf := make([]byte, 32<<10) var rerr error for { @@ -1805,6 +1815,9 @@ 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) + } if _, werr := w.Write(out); werr != nil { return res.StatusCode, "", true } @@ -1821,7 +1834,14 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. w.Write(tidy.flush()) } if search != nil { - w.Write(search.flush()) + out := search.flush() + if spaces != nil { + out = spaces.write(out) + } + w.Write(out) + } + if spaces != nil { + w.Write(spaces.flush()) } if sse && r.Context().Err() == nil && !sniff.whole() { // the upstream died mid-reply, or ended it short of its last diff --git a/internal/gateway/grok_namespace.go b/internal/gateway/grok_namespace.go new file mode 100644 index 000000000..fa75be50c --- /dev/null +++ b/internal/gateway/grok_namespace.go @@ -0,0 +1,169 @@ +package gateway + +import ( + "bytes" + "encoding/json" +) + +// Codex groups some tools in a namespace (collaboration's spawn_agent, +// codex_app's set_thread_title), which a Grok subscription's backend turns +// a request away over. Its functions go to Grok flat (provider's grokBody, +// collaboration__spawn_agent) as they go to a backend magpie translates +// for, and a call the model makes to one comes back to Codex under its own +// name and namespace (#404). + +// namespacedIn is the namespaced functions a Responses request offers or +// has called, by the flat name Grok is given them under. +func namespacedIn(body []byte) map[string]nsTool { + if !bytes.Contains(body, []byte(`"namespace"`)) { + return nil + } + var q struct { + Tools []rTool `json:"tools"` + Input json.RawMessage `json:"input"` // a list, or the text alone + } + if json.Unmarshal(body, &q) != nil { + return nil + } + var items []struct { + Name string `json:"name"` + Namespace string `json:"namespace"` + } + json.Unmarshal(q.Input, &items) + named := map[string]nsTool{} + add := func(space, name string) { + if space != "" && space != liteNamespace && name != "" { + named[flatName(space, name)] = nsTool{Namespace: space, Name: name} + } + } + for _, t := range q.Tools { + if t.Type != "namespace" { + continue + } + for _, nt := range t.Tools { + if nt.Type == "function" { + add(t.Name, nt.Name) + } + } + } + for _, it := range items { + add(it.Namespace, it.Name) + } + if len(named) == 0 { + return nil + } + return named +} + +// nsTidy gives, in a relayed Responses reply, the model's calls to a +// namespaced function their name and namespace back. A stream's lines pass +// as they came unless one carries such a call; a reply that isn't one is +// held whole and gone through at the end. +type nsTidy struct { + named map[string]nsTool + sse bool + buf []byte +} + +func (t *nsTidy) write(b []byte) []byte { + t.buf = append(t.buf, b...) + if !t.sse { + return nil + } + i := bytes.LastIndexByte(t.buf, '\n') + if i < 0 { + return nil + } + out := t.lines(t.buf[:i+1]) + t.buf = append(t.buf[:0], t.buf[i+1:]...) + return out +} + +func (t *nsTidy) flush() []byte { + b := t.buf + t.buf = nil + if !t.sse { + if out, ok := t.restore(b); ok { + return out + } + return b + } + return t.lines(b) +} + +func (t *nsTidy) lines(b []byte) []byte { + if !bytes.Contains(b, []byte(`"function_call"`)) { + return append([]byte(nil), b...) + } + var out []byte + for len(b) > 0 { + line := b + if i := bytes.IndexByte(b, '\n'); i >= 0 { + line, b = b[:i+1], b[i+1:] + } else { + b = nil + } + body := bytes.TrimRight(line, "\r\n") + data, ok := bytes.CutPrefix(body, []byte("data:")) + if !ok || !bytes.Contains(data, []byte(`"function_call"`)) { + out = append(out, line...) + continue + } + nb, ok := t.restore(data) + if !ok { + out = append(out, line...) + continue + } + out = append(append(append(out, "data: "...), nb...), line[len(body):]...) + } + return out +} + +// restore is an event, or a whole reply, with its namespaced calls named +// as Codex knows them, and whether there was one. +func (t *nsTidy) restore(data []byte) ([]byte, bool) { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + var ev map[string]any + if dec.Decode(&ev) != nil || ev == nil { + return nil, false + } + changed := false + if it, _ := ev["item"].(map[string]any); t.call(it) { + changed = true + } + res, _ := ev["response"].(map[string]any) + if res == nil && ev["object"] == "response" { + res = ev + } + if res != nil { + out, _ := res["output"].([]any) + for _, it := range out { + if im, _ := it.(map[string]any); t.call(im) { + changed = true + } + } + } + if !changed { + return nil, false + } + nb, err := marshalPlain(ev) + if err != nil { + return nil, false + } + return nb, true +} + +// call names a function_call to a namespaced function by its name and +// namespace, and reports whether it was one. +func (t *nsTidy) call(it map[string]any) bool { + if it == nil || it["type"] != "function_call" || it["namespace"] != nil { + return false + } + name, _ := it["name"].(string) + if _, ok := t.named[name]; !ok { + return false + } + callTo(it, name, t.named) + return true +} diff --git a/internal/gateway/grok_namespace_test.go b/internal/gateway/grok_namespace_test.go new file mode 100644 index 000000000..f781e76ae --- /dev/null +++ b/internal/gateway/grok_namespace_test.go @@ -0,0 +1,131 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// Codex's sub-agent tools, in its collaboration namespace, reach a Grok +// subscription as functions under their flat names, a call made earlier +// with them; the call Grok makes back reaches Codex under spawn_agent and +// its namespace again, streamed or not (#404). +func TestGrokGetsNamespacedTools(t *testing.T) { + grokSignedIn(t) + var mu sync.Mutex + var sent []map[string]any + call := `{"type":"function_call","id":"fc_1","call_id":"c9","name":"collaboration__spawn_agent","arguments":"{\"message\":\"go\"}","status":"completed"}` + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/responses" { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"data":[{"id":"grok-4.7","api_backend":"responses"}]}`) + return + } + 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":"collaboration__spawn_agent","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() + was := provider.GrokBase + provider.GrokBase = up.URL + "/v1" + defer func() { provider.GrokBase = was }() + + s := New() + for _, stream := range []bool{true, false} { + mu.Lock() + sent = nil + mu.Unlock() + body := `{"model":"grok/grok-4.7","stream":` + map[bool]string{true: "true", false: "false"}[stream] + `,` + namespacedTools + `,"input":[ + {"type":"message","role":"user","content":"go"}, + {"type":"function_call","call_id":"c1","name":"spawn_agent","namespace":"collaboration","arguments":"{}"}, + {"type":"function_call_output","call_id":"c1","output":"ok"}]}` + 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) + } + mu.Lock() + if len(sent) != 1 { + t.Fatalf("stream %v: Grok was asked %d times", stream, len(sent)) + } + q := sent[0] + mu.Unlock() + var names []string + for _, tl := range q["tools"].([]any) { + tm := tl.(map[string]any) + names = append(names, tm["type"].(string)+":"+tm["name"].(string)) + } + if got := strings.Join(names, ","); got != "function:exec_command,function:collaboration__spawn_agent" { + t.Fatalf("stream %v: Grok was offered %s", stream, got) + } + in := q["input"].([]any) + if c := in[1].(map[string]any); c["name"] != "collaboration__spawn_agent" || c["namespace"] != nil || c["call_id"] != "c1" { + t.Fatalf("stream %v: the call handed back went as %v", stream, c) + } + if o := in[2].(map[string]any); o["call_id"] != "c1" { + t.Fatalf("stream %v: its output went as %v", stream, o) + } + + // every function_call Codex reads is spawn_agent in collaboration + 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 { + // arguments not sealed, as callTo says: an empty list + if sealed, ok := it["encrypted_function_args"].([]any); it["name"] != "spawn_agent" || it["namespace"] != "collaboration" || it["call_id"] != "c9" || !ok || len(sealed) != 0 { + t.Fatalf("stream %v: Codex was given %v", stream, it) + } + } + } +} diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index 2aee69aa7..c34369def 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -1,13 +1,13 @@ package gateway import ( - "crypto/sha256" - "encoding/hex" "encoding/json" "fmt" "slices" "strings" "time" + + "github.com/yetone/magpie/internal/provider" ) // ---- OpenAI Responses ------------------------------------------------------- @@ -99,17 +99,10 @@ func searchFound(tools []rTool) string { return "These tools are now available to call: " + strings.Join(names, ", ") } -// flatName is the name a namespaced tool is offered to a model under, which -// takes one flat name: namespace__name, as Codex names an MCP server's tools. -// A name longer than the 64 characters APIs allow is cut and made unique by -// a hash of the whole. +// flatName is the name a namespaced tool is offered to a model under, +// namespace__name, the same a Grok subscription is offered it under. func flatName(namespace, name string) string { - flat := namespace + "__" + name - if len(flat) <= 64 { - return flat - } - sum := sha256.Sum256([]byte(namespace + "\x00" + name)) - return flat[:55] + "_" + hex.EncodeToString(sum[:4]) + return provider.FlatName(namespace, name) } type rRequest struct { diff --git a/internal/provider/grok.go b/internal/provider/grok.go index 4f7140ec0..2a86e827e 100644 --- a/internal/provider/grok.go +++ b/internal/provider/grok.go @@ -10,6 +10,8 @@ import ( "bufio" "bytes" "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" "io" @@ -193,7 +195,8 @@ func grokSigned(acct *Account, home string) { // grokTools are the tool types Grok's backend takes; it turns the whole // request away over another, as over Codex's freeform apply_patch (custom) -// or its sub-agent tools, grouped in a namespace. +// or a namespace, which groups its sub-agent tools. A namespace's functions +// go as functions of their own (grokFlat). var grokTools = map[string]bool{"function": true, "web_search": true, "x_search": true, "image_generation": true, "collections_search": true, "file_search": true, "code_execution": true, "code_interpreter": true, "mcp": true, "shell": true, "tool_search": true} @@ -204,12 +207,15 @@ var grokTools = map[string]bool{"function": true, "web_search": true, "x_search" // reach the live web, which Grok's doesn't take either; it searches live. // And Codex hands reasoning back with "content": null, which the backend // can't read the encrypted reasoning beside ("Could not decode the -// compaction blob"), so a null content goes. A tool_choice with no tools +// compaction blob"), so a null content goes. A namespace's functions, as +// collaboration's spawn_agent, go flat (collaboration__spawn_agent), and so +// do the calls to them handed back and a tool_choice naming one (#404). +// A tool_choice with no tools // left goes too: the backend turns the request away over it ("A // tool_choice was set on the request but no tools were specified"), as it // would Codex's compaction summary, sent without tools (#378). func grokBody(body []byte) []byte { - if !bytes.Contains(body, []byte(`"tools"`)) && !bytes.Contains(body, []byte(`"reasoning"`)) && !bytes.Contains(body, []byte(`"tool_choice"`)) { + if !bytes.Contains(body, []byte(`"tools"`)) && !bytes.Contains(body, []byte(`"reasoning"`)) && !bytes.Contains(body, []byte(`"tool_choice"`)) && !bytes.Contains(body, []byte(`"namespace"`)) { return body } dec := json.NewDecoder(bytes.NewReader(body)) @@ -224,6 +230,11 @@ func grokBody(body []byte) []byte { for _, t := range tools { if tm, ok := t.(map[string]any); ok { ty, _ := tm["type"].(string) + if ty == "namespace" { + dirty = true + kept = append(kept, grokFlat(tm)...) + continue + } if !grokTools[ty] { dirty = true continue @@ -237,6 +248,9 @@ func grokBody(body []byte) []byte { } m["tools"] = kept if tc, ok := m["tool_choice"].(map[string]any); ok { + if flatCall(tc) { + dirty = true + } if ty, _ := tc["type"].(string); !grokTools[ty] { delete(m, "tool_choice") dirty = true @@ -251,6 +265,9 @@ func grokBody(body []byte) []byte { } input, _ := m["input"].([]any) for _, it := range input { + if im, ok := it.(map[string]any); ok && flatCall(im) { + dirty = true + } if im, ok := it.(map[string]any); ok && im["type"] == "reasoning" { if c, ok := im["content"]; ok && c == nil { delete(im, "content") @@ -268,6 +285,57 @@ func grokBody(body []byte) []byte { return b } +// liteNamespace is the namespace Codex's Responses Lite groups its own +// functions in, which Codex reads as none at all. +const liteNamespace = "functions" + +// FlatName is the name a namespaced tool is offered to a model under, which +// takes one flat name: namespace__name, as Codex names an MCP server's tools. +// A name longer than the 64 characters APIs allow is cut and made unique by +// a hash of the whole. +func FlatName(namespace, name string) string { + flat := namespace + "__" + name + if len(flat) <= 64 { + return flat + } + sum := sha256.Sum256([]byte(namespace + "\x00" + name)) + return flat[:55] + "_" + hex.EncodeToString(sum[:4]) +} + +// grokFlat is a namespace's functions, each under its flat name; what else +// it holds, a freeform tool, Grok's backend wouldn't take either. +func grokFlat(ns map[string]any) []any { + space, _ := ns["name"].(string) + nested, _ := ns["tools"].([]any) + var out []any + for _, n := range nested { + nm, _ := n.(map[string]any) + name, _ := nm["name"].(string) + if nm == nil || nm["type"] != "function" || name == "" { + continue + } + if space != "" && space != liteNamespace { + nm["name"] = FlatName(space, name) + } + out = append(out, nm) + } + return out +} + +// flatCall names a call to a namespaced tool, or a tool_choice of one, by +// the flat name it was offered under, and reports whether it was one. +func flatCall(it map[string]any) bool { + space, ok := it["namespace"].(string) + if !ok { + return false + } + delete(it, "namespace") + if name, _ := it["name"].(string); name != "" && space != "" && space != liteNamespace { + it["name"] = FlatName(space, name) + } + return true +} + // grokHeaders say a request comes from the Grok CLI, which the backend // wants to know the version of: without it the CLI is "outdated". func grokHeaders(req *http.Request, token string) { diff --git a/internal/provider/grok_test.go b/internal/provider/grok_test.go index 99b6b57e3..84644936c 100644 --- a/internal/provider/grok_test.go +++ b/internal/provider/grok_test.go @@ -3,6 +3,7 @@ package provider import ( "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "os" @@ -79,9 +80,11 @@ func TestGrokTokenReadsTheCLIsSignIn(t *testing.T) { } // Codex's freeform apply_patch is left out: Grok's backend turns away a -// request with a tool type it doesn't know. +// request with a tool type it doesn't know, a namespace among them. A +// namespace's functions go as functions of their own, under their flat +// names (#404); one with none to give goes whole. func TestGrokBodyLeavesOutCustomTools(t *testing.T) { - in := []byte(`{"model":"grok-4.7","tools":[{"type":"function","name":"shell"},{"type":"custom","name":"apply_patch","format":{"type":"grammar"}},{"type":"namespace","name":"multi_agent_v1","tools":[]},{"type":"web_search","external_web_access":false}],"tool_choice":{"type":"custom","name":"apply_patch"},"max_output_tokens":100}`) + in := []byte(`{"model":"grok-4.7","tools":[{"type":"function","name":"shell"},{"type":"custom","name":"apply_patch","format":{"type":"grammar"}},{"type":"namespace","name":"multi_agent_v1","tools":[]},{"type":"namespace","name":"collaboration","description":"agents","tools":[{"type":"function","name":"spawn_agent","parameters":{"type":"object"}},{"type":"custom","name":"freeform"}]},{"type":"namespace","name":"odd","tools":[{"type":"custom","name":"x"}]},{"type":"web_search","external_web_access":false}],"tool_choice":{"type":"custom","name":"apply_patch"},"max_output_tokens":100}`) var got struct { Tools []map[string]any `json:"tools"` Choice any `json:"tool_choice"` @@ -90,7 +93,9 @@ func TestGrokBodyLeavesOutCustomTools(t *testing.T) { if err := json.Unmarshal(grokBody(in), &got); err != nil { t.Fatal(err) } - if len(got.Tools) != 2 || got.Tools[0]["type"] != "function" || len(got.Tools[1]) != 1 || got.Tools[1]["type"] != "web_search" || got.Choice != nil || got.Max != 100 { + if len(got.Tools) != 3 || got.Tools[0]["type"] != "function" || got.Tools[0]["name"] != "shell" || + got.Tools[1]["type"] != "function" || got.Tools[1]["name"] != "collaboration__spawn_agent" || got.Tools[1]["parameters"] == nil || + len(got.Tools[2]) != 1 || got.Tools[2]["type"] != "web_search" || got.Choice != nil || got.Max != 100 { t.Fatalf("%+v", got) } same := []byte(`{"tools":[{"type":"function","name":"x"}],"tool_choice":"auto"}`) @@ -99,6 +104,41 @@ func TestGrokBodyLeavesOutCustomTools(t *testing.T) { } } +// A call to a namespaced function handed back, and a tool_choice naming +// one, go under the flat name Grok was offered it by; its output keeps its +// call_id. Responses Lite's "functions" namespace is no namespace at all. +func TestGrokBodyFlattensNamespacedCalls(t *testing.T) { + in := []byte(`{"tools":[{"type":"function","name":"exec_command"},{"type":"namespace","name":"codex_app","tools":[{"type":"function","name":"set_thread_title"}]},{"type":"namespace","name":"functions","tools":[{"type":"function","name":"view_image"}]}],"tool_choice":{"type":"function","name":"set_thread_title","namespace":"codex_app"},"input":[ + {"type":"function_call","call_id":"c1","name":"spawn_agent","namespace":"collaboration","arguments":"{}"}, + {"type":"function_call_output","call_id":"c1","output":"ok"}, + {"type":"function_call","call_id":"c2","name":"exec_command","arguments":"{}"}, + {"type":"function_call","call_id":"c3","name":"view_image","namespace":"functions","arguments":"{}"}]}`) + var got struct { + Tools []map[string]any `json:"tools"` + Choice map[string]any `json:"tool_choice"` + Input []map[string]any `json:"input"` + } + if err := json.Unmarshal(grokBody(in), &got); err != nil { + t.Fatal(err) + } + var names []string + for _, tl := range got.Tools { + names = append(names, fmt.Sprint(tl["name"])) + } + if strings.Join(names, ",") != "exec_command,codex_app__set_thread_title,view_image" { + t.Fatalf("tools %v", names) + } + if got.Choice["name"] != "codex_app__set_thread_title" || got.Choice["namespace"] != nil { + t.Fatalf("tool_choice %v", got.Choice) + } + if c := got.Input[0]; c["name"] != "collaboration__spawn_agent" || c["namespace"] != nil || c["call_id"] != "c1" { + t.Fatalf("call %v", c) + } + if got.Input[1]["call_id"] != "c1" || got.Input[2]["name"] != "exec_command" || got.Input[3]["name"] != "view_image" || got.Input[3]["namespace"] != nil { + t.Fatalf("input %v", got.Input) + } +} + // A tool_choice with no tools beside it goes: the backend turns the // request away over it, as it did Codex's compaction summary (#378). func TestGrokBodyDropsLoneToolChoice(t *testing.T) {