codex: a tool name the ChatGPT backend refuses goes as one it takes, and comes back as the agent's

wing3556 on Discord (11-02): a compaction through a Codex account failed
400 "Codex: Invalid response.create payload: Invalid 'input[83].name':
string does not match pattern. Expected a string that matches the
pattern '^[a-zA-Z0-9_.-]+\z'." The ChatGPT backend checks every tool
name in a request, a call's in input as well as a tool's in tools, and
refuses the whole request when one fails. A conversation can hold a call
by such a name: a model another provider served wrote one with a space,
a colon or non-ASCII in it, and the agent kept it beside its "no such
tool" answer. Every request that replayed it, the compaction above all,
then failed on Codex. Nothing on the way checked: buildResponses copies a
call's name as it is, and redaction keeps names as written.

What changed:
- provider.CodexToolName: a valid name stays as it is. Otherwise each
  refused byte becomes "_", the result is cut to 55 and gets "_" plus 8
  hex of its sha256, so it is the same on every request and two names
  never meet. CodexToolNames applies it to tools (namespace children
  too), function_call/custom_tool_call items, additional_tools and
  tool_search_output items, and tool_choice. A body with no bad name goes
  byte for byte.
- It runs where every request to the ChatGPT backend passes: codexBody
  (an account's, translated or relayed) and codexUpstreamOn (Codex's
  own sign-in, /responses and /responses/compact), beside DeclareSearch.
- A tool the agent declared under such a name is called back by its own
  name: translated replies through decoderFor (now given the request's
  tools; codexNamesBack), relayed Responses replies through nsTidy's new
  back map (codexRenamedIn).
- docs/subsystems/gateway-routing.md says so beside #1270's paragraph.

Not covered: namespaces, the OpenAI API (whose pattern has no "." and a
64 limit), Azure and Copilot Responses, filed as #4875.

Run on mote at this head:
- TestCodexToolNamesTheBackendTakes and TestCodexToolNamesKeepValid
  pass. The fake backend refuses a bad name with the reporter's 400 word
  for word; the test covers Claude Code's compaction on /v1/messages with
  four bad history names (sent twice, byte-equal), Chat with a declared
  "search:web" called back by that name, Responses relayed the same, and
  Codex's own /backend-api/codex/responses.
- go test ./internal/provider ./internal/gateway (-timeout 45m): provider ok;
  gateway ok but TestCodexPoolSaysTheClientsVersion, the red already
  filed as #4807 (full package run only, another test's Codex identity
  reaches it); it passes alone at this head.
- go vet ./... (darwin) and GOOS=linux/windows CGO_ENABLED=0 go vet
  -tags nogui ./...: ok. gofmt -l: clean.

Broken by hand:
- codexBody hook off: compaction red with the reporter's 400.
- codexUpstreamOn hook off, decoder restore off, passthrough restore off
  (together): the codex, chat and responses cases each red.

Not tried: wing3556's real conversation (we don't have its bytes, and
the agent is unknown; Claude Code is likely). No real ChatGPT account
was asked with a bad name, so whether the real backend also limits
length is unknown.
This commit is contained in:
yetone
2026-11-02 15:15:21 +08:00
parent e7185daebe
commit b4a9cd8db5
10 changed files with 501 additions and 14 deletions
File diff suppressed because one or more lines are too long
+6
View File
@@ -972,6 +972,12 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
// is refused by the ChatGPT backend (#1270), as on an account's
body = provider.DeclareSearch(body, strings.EqualFold(r.Header.Get("X-OpenAI-Internal-Codex-Responses-Lite"), "true"))
}
if r.Method == http.MethodPost && base == provider.CodexBase {
// a call in the history by a name the backend refuses (another
// provider's model wrote it) turned every turn and compaction
// away, as on an account's (provider.CodexToolNames, wing3556)
body = provider.CodexToolNames(body)
}
u := base + rest
if r.URL.RawQuery != "" {
u += "?" + r.URL.RawQuery
+54
View File
@@ -0,0 +1,54 @@
package gateway
import (
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// A ChatGPT account's backend refuses a tool name outside
// ^[a-zA-Z0-9_.-]+\z, a call's in the history as much as a declared
// tool's, and the account's send gives it another (provider's
// CodexToolNames, wing3556 on Discord). A call the model makes to a
// declared tool so renamed comes back to the agent by the name it
// declared: from a translated reply's events (decoderFor), and from a
// Responses reply relayed as it came (nsTidy's back).
// codexNamesBack maps each declared tool's name the ChatGPT backend is
// given in its place back to the agent's; nil when none is renamed.
func codexNamesBack(tools []Tool) map[string]string {
if len(tools) == 0 {
return nil
}
names := make([]string, 0, len(tools))
for _, t := range tools {
names = append(names, t.Name)
}
return provider.CodexToolNamesBack(names)
}
// codexRenamedIn is codexNamesBack for body, a Responses request: the
// functions and custom tools it declares in tools or in an
// additional_tools item.
func codexRenamedIn(body []byte) map[string]string {
var names []string
add := func(ts gjson.Result) {
ts.ForEach(func(_, t gjson.Result) bool {
if k := t.Get("type").String(); k == "function" || k == "custom" {
if n := t.Get("name"); n.Type == gjson.String {
names = append(names, n.String())
}
}
return true
})
}
top := gjson.GetManyBytes(body, "tools", "input")
add(top[0])
top[1].ForEach(func(_, it gjson.Result) bool {
if it.Get("type").String() == additionalToolsItem {
add(it.Get("tools"))
}
return true
})
return provider.CodexToolNamesBack(names)
}
+198
View File
@@ -0,0 +1,198 @@
package gateway
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"sync"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// namesBackend stands in for the ChatGPT backend's check of tool names:
// a name outside ^[a-zA-Z0-9_.-]+\z, a call's in input or a tool's in
// tools, is the 400 wing3556 got on a compaction (Discord, 11-02), word
// for word. A request that passes is answered with a call to the first
// tool it declares, by the name it was given, or with text when it
// declares none. It keeps every body it was sent.
type namesBackend struct {
mu sync.Mutex
bodies [][]byte
}
func (n *namesBackend) last(t *testing.T) []byte {
t.Helper()
n.mu.Lock()
defer n.mu.Unlock()
if len(n.bodies) == 0 {
t.Fatal("the ChatGPT backend was asked nothing")
}
return n.bodies[len(n.bodies)-1]
}
var backendNameOK = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
// namesRefused is the backend's 400 for the first name in b it refuses,
// or "" when it takes them all.
func namesRefused(b []byte) string {
bad := func(field string) string {
return `{"error":{"message":"Invalid '` + field + `': string does not match pattern. Expected a string that matches the pattern '^[a-zA-Z0-9_.-]+\\z'.","type":"invalid_request_error","param":"` + field + `","code":"invalid_value"}}`
}
for i, it := range gjson.GetBytes(b, "input").Array() {
switch it.Get("type").String() {
case "function_call", "custom_tool_call":
if !backendNameOK.MatchString(it.Get("name").String()) {
return bad(fmt.Sprintf("input[%d].name", i))
}
}
}
for i, tl := range gjson.GetBytes(b, "tools").Array() {
if k := tl.Get("type").String(); (k == "function" || k == "custom") && !backendNameOK.MatchString(tl.Get("name").String()) {
return bad(fmt.Sprintf("tools[%d].name", i))
}
}
return ""
}
func namesUpstream(t *testing.T) *namesBackend {
t.Helper()
n := &namesBackend{}
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/models") {
io.WriteString(w, `{"models":[{"slug":"gpt-5.5","display_name":"GPT-5.5","visibility":"list","supported_reasoning_levels":[{"effort":"medium"}],"context_window":272000}]}`)
return
}
b, _ := io.ReadAll(r.Body)
n.mu.Lock()
n.bodies = append(n.bodies, b)
n.mu.Unlock()
if msg := namesRefused(b); msg != "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
io.WriteString(w, msg)
return
}
w.Header().Set("Content-Type", "text/event-stream")
name := gjson.GetBytes(b, `tools.#(type=="function").name`).String()
if name == "" {
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
`data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"item_id":"msg_1","delta":"Summary: did X."}`,
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"Summary: did X."}]}}`,
`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":1}}}`))
return
}
item := `{"type":"function_call","id":"fc_1","call_id":"call_9","name":"` + name + `","arguments":"{\"q\":\"x\"}","status":"completed"}`
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_9","name":"`+name+`","arguments":""}}`,
`data: {"type":"response.function_call_arguments.delta","output_index":0,"item_id":"fc_1","delta":"{\"q\":\"x\"}"}`,
`data: {"type":"response.output_item.done","output_index":0,"item":`+item+`}`,
`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[`+item+`],"usage":{"input_tokens":5,"output_tokens":1}}}`))
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
return n
}
// wing3556 (Discord, 11-02): an agent's compaction through a Codex
// account failed 400 "Invalid 'input[83].name': string does not match
// pattern", the history holding a call by a name the ChatGPT backend
// refuses, which a model another provider served had written. Every path
// to the backend sends each such name as one it takes, the same on every
// request: Claude Code's Messages and a Chat client translated, a
// Responses client relayed, and Codex's own turn on its sign-in. A tool
// the agent declared under such a name is called back by that name.
func TestCodexToolNamesTheBackendTakes(t *testing.T) {
codexSignedIn(t)
n := namesUpstream(t)
bad := []string{"web search", "mcp:files:read", "读取文件", "Read\n"}
esc := func(s string) string { return strings.TrimSuffix(strings.TrimPrefix(string(mustJSON(s)), `"`), `"`) }
// Claude Code's compaction: the summary asked for over a history of
// calls to tools no longer declared, with none offered
var blocks, results []string
for i, b := range bad {
blocks = append(blocks, fmt.Sprintf(`{"type":"tool_use","id":"toolu_%d","name":"%s","input":{}}`, i, esc(b)))
results = append(results, fmt.Sprintf(`{"type":"tool_result","tool_use_id":"toolu_%d","content":"<tool_use_error>Error: No such tool available: %s</tool_use_error>","is_error":true}`, i, esc(b)))
}
compaction := `{"model":"codex/gpt-5.5","max_tokens":2000,"stream":true,"messages":[
{"role":"user","content":"look it up"},
{"role":"assistant","content":[` + strings.Join(blocks, ",") + `]},
{"role":"user","content":[` + strings.Join(results, ",") + `]},
{"role":"user","content":"Your task is to create a detailed summary of the conversation so far."}]}`
code, out := post(t, "/v1/messages", compaction)
if code != 200 || !strings.Contains(out, "Summary: did X.") {
t.Fatalf("compaction: %d %s\nthe backend got %s", code, out, n.last(t))
}
first := n.last(t)
if msg := namesRefused(first); msg != "" {
t.Fatalf("compaction: %s in %s", msg, first)
}
if code, _ := post(t, "/v1/messages", compaction); code != 200 || string(n.last(t)) != string(first) {
t.Errorf("the same compaction went differently the second time:\n%s\n%s", first, n.last(t))
}
var sent []string
for _, it := range gjson.GetBytes(first, `input.#(type=="function_call")#.name`).Array() {
sent = append(sent, it.String())
}
if len(sent) != len(bad) || sent[0] == sent[1] {
t.Errorf("calls named %q", sent)
}
// a Chat client that declares a tool under such a name: the backend
// is given one it takes, and the client is called back by its own
code, out = post(t, "/v1/chat/completions", `{"model":"codex/gpt-5.5","stream":true,"messages":[{"role":"user","content":"find x"}],
"tools":[{"type":"function","function":{"name":"search:web","parameters":{"type":"object"}}}]}`)
if code != 200 || !strings.Contains(out, `"name":"search:web"`) {
t.Errorf("chat: %d %s\nthe backend got %s", code, out, n.last(t))
}
// a Responses client, relayed: the history's call and the declared
// tool go as names the backend takes, the call back by the agent's
code, out = post(t, "/v1/responses", `{"model":"codex/gpt-5.5","stream":true,"input":[
{"type":"message","role":"user","content":[{"type":"input_text","text":"find x"}]},
{"type":"function_call","call_id":"call_1","name":"web search","arguments":"{}"},
{"type":"function_call_output","call_id":"call_1","output":"no such tool"}],
"tools":[{"type":"function","name":"search:web","parameters":{"type":"object"}}]}`)
if code != 200 || !strings.Contains(out, `"name":"search:web"`) || namesRefused(n.last(t)) != "" {
t.Errorf("responses: %d %s\nthe backend got %s", code, out, n.last(t))
}
// Codex's own turn on its sign-in, a call another provider's model
// wrote in its history
code, out = codexPost(t, `{"model":"gpt-5.5","stream":true,"input":[
{"type":"message","role":"user","content":[{"type":"input_text","text":"go on"}]},
{"type":"function_call","call_id":"call_1","name":"mcp:files:read","arguments":"{}"},
{"type":"function_call_output","call_id":"call_1","output":"unsupported call"}],
"tools":[{"type":"function","name":"shell","parameters":{"type":"object"}}]}`)
if code != 200 || namesRefused(n.last(t)) != "" {
t.Errorf("codex: %d %s\nthe backend got %s", code, out, n.last(t))
}
}
// A name the backend takes goes as it is, and a conversation of them
// goes byte for byte.
func TestCodexToolNamesKeepValid(t *testing.T) {
for _, name := range []string{"Read", "mcp__claude_ai_Gmail__search", "functions.exec_command", "a-b_c.d"} {
if got := provider.CodexToolName(name); got != name {
t.Errorf("%q became %q", name, got)
}
}
body := []byte(`{"model":"gpt-5.5","input":[{"type":"function_call","call_id":"c","name":"Read","arguments":"{}"}],"tools":[{"type":"function","name":"Read"}]}`)
if got := provider.CodexToolNames(body); string(got) != string(body) {
t.Errorf("changed: %s", got)
}
long := strings.Repeat("工具", 40)
if got := provider.CodexToolName(long); !backendNameOK.MatchString(got) || len(got) > 64 || got != provider.CodexToolName(long) {
t.Errorf("long name became %q", got)
}
}
+1 -1
View File
@@ -559,7 +559,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
return writeError(w, from, 502, failed), failed
}
} else {
dec := carryReasoning(decoderFor(p, actual), from, actual)
dec := carryReasoning(decoderFor(p, actual, request.Tools), from, actual)
attemptSee := see
if names := textCallNames(request.Tools); names != nil {
t := &textCallSee{names: names, see: see}
+29 -5
View File
@@ -5582,6 +5582,13 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if proto == provider.Responses && p.Account != nil && (p.Account.Agent == "grok" || p.PluginProvider() == "grok" || p.PluginProvider() == "zed") {
named = namespacedIn(body)
}
// a ChatGPT account is given a declared tool whose name its backend
// refuses under another; a call to it goes back by the agent's
// (codex_names.go)
var renamed map[string]string
if proto == provider.Responses && accountAgent(p) == "codex" {
renamed = codexRenamedIn(body)
}
// the new input alone, after the id the provider keeps the previous
// response under, when it answered that one (prev_response.go)
sentWhole, delta := body, false
@@ -5999,8 +6006,8 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
search = &searchTidy{}
}
var spaces *nsTidy
if named != nil {
spaces = &nsTidy{named: named, sse: sse}
if named != nil || renamed != nil {
spaces = &nsTidy{named: named, back: renamed, sse: sse}
}
// a reasoning item another vendor wrote with its text in it, in a reply
// relayed as it came, made into one magpie could have (#2855): the
@@ -7579,7 +7586,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
}
return writeVendorError(w, from, res.StatusCode, msg, b), msg
}
dec := carryReasoning(decoderFor(p, actual), from, actual)
dec := carryReasoning(decoderFor(p, actual, request.Tools), from, actual)
rd, sse := eventStream(res)
if !sse {
// the provider ignored stream:true; read the whole reply as one
@@ -7883,12 +7890,29 @@ func build(proto provider.Protocol, r *Request, model, host string, rejectTemp b
// OpenCode reads it, as it came: the plugin knows its vendor and gives its
// reasoning apart, so a <think> at the head of its text is the model's
// words, not a block of thinking to take out (Qoder's, #2634).
func decoderFor(p provider.Provider, proto provider.Protocol) func(data string, emit func(Event)) error {
//
// A ChatGPT account is given a declared tool whose name its backend
// refuses under another (provider.CodexToolName); the model's call to it
// comes back by the name the agent declared, from tools, the request's.
func decoderFor(p provider.Provider, proto provider.Protocol, tools []Tool) func(data string, emit func(Event)) error {
if proto == provider.Chat && p.IsPlugin() {
d := &chatDecoder{past: true}
return d.decode
}
return decoder(proto)
dec := decoder(proto)
if proto == provider.Responses && accountAgent(p) == "codex" {
if back := codexNamesBack(tools); back != nil {
return func(data string, emit func(Event)) error {
return dec(data, func(ev Event) {
if n, ok := back[ev.Name]; ok {
ev.Name = n
}
emit(ev)
})
}
}
}
return dec
}
func decoder(proto provider.Protocol) func(data string, emit func(Event)) error {
+23 -6
View File
@@ -71,8 +71,11 @@ func namespacedIn(body []byte) map[string]nsTool {
// held whole and gone through at the end.
type nsTidy struct {
named map[string]nsTool
sse bool
buf []byte
// back maps a declared tool's name a ChatGPT account was given in its
// place to the agent's own (codexRenamedIn)
back map[string]string
sse bool
buf []byte
}
func (t *nsTidy) write(b []byte) []byte {
@@ -102,7 +105,7 @@ func (t *nsTidy) flush() []byte {
}
func (t *nsTidy) lines(b []byte) []byte {
if !bytes.Contains(b, []byte(`"function_call"`)) {
if !t.carries(b) {
return append([]byte(nil), b...)
}
var out []byte
@@ -115,7 +118,7 @@ func (t *nsTidy) lines(b []byte) []byte {
}
body := bytes.TrimRight(line, "\r\n")
data, ok := bytes.CutPrefix(body, []byte("data:"))
if !ok || !bytes.Contains(data, []byte(`"function_call"`)) {
if !ok || !t.carries(data) {
out = append(out, line...)
continue
}
@@ -164,13 +167,27 @@ func (t *nsTidy) restore(data []byte) ([]byte, bool) {
return nb, true
}
// carries reports whether b may hold a call restore names again: a
// function call, or a custom tool's to one renamed.
func (t *nsTidy) carries(b []byte) bool {
return bytes.Contains(b, []byte(`"function_call"`)) || t.back != nil && bytes.Contains(b, []byte(`"custom_tool_call"`))
}
// call names a function_call to a namespaced function by its name and
// namespace, and reports whether it was one.
// namespace, or a call to a tool renamed for a ChatGPT account by the
// agent's name, 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 {
if it == nil || it["namespace"] != nil || it["type"] != "function_call" && it["type"] != "custom_tool_call" {
return false
}
name, _ := it["name"].(string)
if n, ok := t.back[name]; ok {
it["name"] = n
return true
}
if it["type"] != "function_call" {
return false
}
if _, ok := t.named[name]; !ok {
return false
}
+1 -1
View File
@@ -1363,7 +1363,7 @@ func (s *Server) askTranslated(p provider.Provider, to provider.Protocol, model
go func() {
defer close(events)
defer res.Body.Close()
dec := decoderFor(p, actual)
dec := decoderFor(p, actual, q.Tools)
send := func(ev Event) error {
select {
case events <- ev:
+185
View File
@@ -0,0 +1,185 @@
package provider
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"regexp"
"github.com/tidwall/gjson"
)
// The ChatGPT backend checks every tool name a request carries, a call's
// in the input as much as a tool's in tools, against ^[a-zA-Z0-9_.-]+\z,
// and turns the whole request away when one fails: 400 "Invalid
// 'input[83].name': string does not match pattern" (wing3556 on Discord,
// on a compaction). A conversation can hold a call by a name no tool has:
// a model another provider served wrote one with a space, a colon or a
// word of its own script in it, and the agent kept the call in its
// history beside the "no such tool" it answered. Each request that
// replays it, a compaction's above all, failed on Codex every time. Such a
// name goes as CodexToolName makes it; a valid one goes as it is, so a
// conversation that worked is sent byte for byte as before.
// codexNameOK is a name the ChatGPT backend takes.
var codexNameOK = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
// CodexToolName is name as the ChatGPT backend takes it: as it is when
// it is valid, else each character the backend refuses as "_", cut to
// 55, and a hash of the whole after it (as FlatName cuts a long name), so
// a name is made the same on every request and two names that differ
// never come out alike. An agent's declared tool so renamed is called
// back by its own name (CodexToolNamesBack).
func CodexToolName(name string) string {
if codexNameOK.MatchString(name) {
return name
}
b := []byte(name)
out := make([]byte, 0, len(b)+9)
for _, c := range b {
if c == '_' || c == '.' || c == '-' || c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' {
out = append(out, c)
} else {
out = append(out, '_')
}
}
if len(out) > 55 {
out = out[:55]
}
sum := sha256.Sum256(b)
return string(out) + "_" + hex.EncodeToString(sum[:4])
}
// CodexToolNamesBack maps each name of declared that CodexToolName
// changes back to the name the agent declared; nil when none changes.
func CodexToolNamesBack(declared []string) map[string]string {
var back map[string]string
for _, n := range declared {
if c := CodexToolName(n); c != n {
if back == nil {
back = map[string]string{}
}
back[c] = n
}
}
return back
}
// CodexToolNames is body, a Responses request for the ChatGPT backend,
// with every tool name in it as CodexToolName makes it, or body byte for
// byte when each one is valid already.
func CodexToolNames(body []byte) []byte {
if !codexNamesBad(body) {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))
dec.UseNumber()
var m map[string]any
if dec.Decode(&m) != nil || m == nil || !codexToolNames(m) {
return body
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if enc.Encode(m) != nil {
return body
}
return bytes.TrimSuffix(buf.Bytes(), []byte("\n"))
}
// codexNamesBad reports whether body names a tool the backend refuses,
// read where codexToolNames reads it, without decoding the conversation.
func codexNamesBad(body []byte) bool {
bad := false
name := func(v gjson.Result) {
if n := v.Get("name"); n.Type == gjson.String && !codexNameOK.MatchString(n.String()) {
bad = true
}
}
var tools func(ts gjson.Result)
tools = func(ts gjson.Result) {
ts.ForEach(func(_, t gjson.Result) bool {
switch t.Get("type").String() {
case "function", "custom":
name(t)
case "namespace":
tools(t.Get("tools"))
}
return !bad
})
}
top := gjson.GetManyBytes(body, "tools", "input", "tool_choice")
tools(top[0])
top[1].ForEach(func(_, it gjson.Result) bool {
switch it.Get("type").String() {
case "function_call", "custom_tool_call":
name(it)
case "additional_tools", "tool_search_output":
tools(it.Get("tools"))
}
return !bad
})
if tc := top[2]; tc.IsObject() {
switch tc.Get("type").String() {
case "function", "custom":
name(tc)
case "allowed_tools":
tools(tc.Get("tools"))
}
}
return bad
}
// codexToolNames makes every tool name in m, a Responses request, one the
// backend takes: a function's or a custom tool's in tools (a namespace's
// own among them), in an additional_tools item or a tool search's output,
// a call's in the input, and the one tool_choice names. It says whether
// it changed one.
func codexToolNames(m map[string]any) bool {
changed := false
fix := func(o map[string]any) {
if n, ok := o["name"].(string); ok {
if c := CodexToolName(n); c != n {
o["name"] = c
changed = true
}
}
}
var tools func(ts []any)
tools = func(ts []any) {
for _, t := range ts {
tm, _ := t.(map[string]any)
switch tm["type"] {
case "function", "custom":
fix(tm)
case "namespace":
nested, _ := tm["tools"].([]any)
tools(nested)
}
}
}
ts, _ := m["tools"].([]any)
tools(ts)
input, _ := m["input"].([]any)
for _, raw := range input {
it, _ := raw.(map[string]any)
switch it["type"] {
case "function_call", "custom_tool_call":
fix(it)
case "additional_tools", "tool_search_output":
nested, _ := it["tools"].([]any)
tools(nested)
}
}
if tc, _ := m["tool_choice"].(map[string]any); tc != nil {
switch tc["type"] {
case "function", "custom":
fix(tc)
case "allowed_tools":
nested, _ := tc["tools"].([]any)
tools(nested)
}
}
return changed
}
+3
View File
@@ -330,6 +330,9 @@ func codexBody(body []byte) []byte {
m["stream"] = true
m["tool_choice"] = "auto"
declareSearch(m, false)
// a call's name the backend refuses, in a history another provider's
// model wrote, turned the whole request away (codex_names.go)
codexToolNames(m)
if _, ok := m["parallel_tool_calls"]; !ok {
m["parallel_tool_calls"] = true
}