grok: Codex's sub-agent tools reach a Grok subscription (#404) — Codex groups spawn_agent, wait_agent, send_message and followup_task in its collaboration namespace and set_thread_title in codex_app, and since aa08863d12 a namespace was left out whole, as Grok's backend turns a request away over the type: multi_agent_v2 on Grok had no tools to spawn with. A namespace's functions now go to Grok as functions of their own under the flat name the translation path gives them (collaboration__spawn_agent, flatName, now provider.FlatName), and so do a call to one handed back and a tool_choice naming one; the namespace type itself still never reaches Grok, nor does a freeform tool (apply_patch, or one inside a namespace), and a namespace with no function goes whole. Responses Lite's "functions" namespace stays plain names. On the way back a call Grok makes to a flat name reaches Codex under its own name and namespace with an empty encrypted_function_args, as callTo gives one, streamed (output_item.added/done, response.completed) or not. A ChatGPT account still gets the namespace as Codex sent it. TestGrokGetsNamespacedTools (a fake Grok upstream returning a call to collaboration__spawn_agent), TestGrokBodyFlattensNamespacedCalls and the updated TestGrokBodyLeavesOutCustomTools fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestUserPath, a load flake, passes alone).

This commit is contained in:
yetone
2026-10-01 16:20:10 +08:00
parent 2fc277de9f
commit 5b917c1d8f
6 changed files with 440 additions and 19 deletions
+21 -1
View File
@@ -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
+169
View File
@@ -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
}
+131
View File
@@ -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)
}
}
}
}
+5 -12
View File
@@ -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 {
+71 -3
View File
@@ -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) {
+43 -3
View File
@@ -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) {