Files
magpie/internal/gateway/codex_spawn_models.go
T
yetone 403f3845e2 gateway: Codex's spawn_agent names every model also when Codex hands it to the lead through a tool search, as it does on 0.162 (Gearclickist on Discord)
Gearclickist, after v0.1.1214: the lead still saw only five models for
its subagents. v0.1.1214 (5d33f060b) widened spawn_agent in the request's
tools only. Codex 0.162 doesn't put it there for a model that can search
tools: with supports_search_tool the multi-agent V1 tools are Deferred
(codex-rs rust-v0.162.1 core/src/tools/spec_plan.rs:1475-1479), the lead
calls tool_search, and spawn_agent, with Codex's five
(core/src/agent/child_config.rs:20 MAX_SPAWN_AGENT_MODEL_OVERRIDES = 5,
used in core/src/tools/handlers/multi_agents_spec.rs:830), arrives in a
tool_search_output item in the conversation. Codex resends that item on
every later turn. magpie's /models entries and Codex's own say
supports_search_tool, so this is the usual case, and the fix never fired.

The limit is only in what Codex writes. find_spawn_agent_model_name
(child_config.rs:318) takes any model of the catalog Codex loaded; the
five also appear in its error text (child_config.rs:335).

spawnAgentModels now widens the spawn_agent in each tool_search_output
in input as well as in tools (moreSpawnTools, shared by both). The added
text is unchanged and stays neutral; base_instructions are untouched.
The same output is widened the same way on each turn, so the history
Codex resends stays byte-stable.

Run:
- Real Codex 0.162.1 in a sandbox HOME/CODEX_HOME, wired by a sandbox
  magpie (`magpie codex fake/m1`, gateway on 127.0.0.1:3593) to a fake
  Responses upstream with 40 models that calls tool_search, then
  spawn_agent with model fake/m12.
  - Before: the lead's searched spawn_agent named fake/m1..m5 only.
  - After: it names all 40, Codex's five then the other 35 under the
    added header.
  - Both times Codex accepted fake/m12 and the child's request reached
    the upstream on m12.
  - The same Codex pointed straight at the fake (no magpie) gave the raw
    request saved as testdata/workdir/codex-0.162.1-tool-search.json
    (sandbox paths replaced).
- TestSpawnAgentNamesEveryModelAfterToolSearch (/v1, CodexPath with a
  magpie lead, CodexPath with a ChatGPT lead and V1) fails on the old
  codex_spawn_models.go in all 3 subtests ("doesn't name fake/m6") and
  passes now.
- go test ./internal/gateway -count=1 under a sandbox HOME: ok.
- gofmt -l clean; go vet ./internal/gateway on darwin, GOOS=linux -tags
  nogui, GOOS=windows.

Not run: a real ChatGPT-account lead at CodexPath (covered by the stub
backend test only), the Codex App, and a V2 lead (V2 keeps spawn_agent in
tools, which v0.1.1214 already covers).
2026-10-13 02:32:23 +08:00

238 lines
7.5 KiB
Go

package gateway
import (
"bytes"
"cmp"
"encoding/json"
"net/http"
"slices"
"strings"
"github.com/yetone/magpie/internal/codexcat"
"github.com/yetone/magpie/internal/provider"
)
// Codex's spawn_agent tool names only the first five models of its
// catalog to its lead (codex-rs core/src/agent/child_config.rs
// MAX_SPAWN_AGENT_MODEL_OVERRIDES, in multi_agents_spec.rs
// spawn_agent_models_description and, with model_catalog_in_context,
// context/world_state/model_catalog.rs), Codex's own ahead of magpie's,
// though it takes any model of the catalog named in spawn_agent's model
// argument (find_spawn_agent_model_name). So a lead could put its
// subagents on five models at most, with "Codex subagents on any model"
// on or not (Gearclickist on Discord). spawnAgentModels has the tool name
// the rest of the catalog too, the models a subagent spawned from that
// lead can work on: every one, but only a ChatGPT account's when the lead
// is answered by the ChatGPT backend in multi-agent V2, which seals its
// subagents' tasks for a ChatGPT account alone (#619).
// spawnMore heads the models spawnAgentModels adds to spawn_agent's
// description; one that has it already is left as it is. It goes upstream
// with the rest of the prompt, to OpenAI too when the lead is a ChatGPT
// account, so it stays neutral: it names neither magpie nor Codex's limit,
// and says nothing of who the agent is.
const spawnMore = "More models that may be set as `model`:"
// spawnMost is the most models spawnAgentModels adds, to keep the tool's
// description in bounds.
const spawnMost = 200
type spawnChoice struct{ slug, name string }
// spawnAgentModels is body, a Codex request at CodexPath (codexPath) or at
// /v1/responses (Codex with magpie as its model provider), with its
// spawn_agent tool naming every model of the catalog that Codex was handed
// there, not only the first five. lead is the request's model.
func spawnAgentModels(r *http.Request, body []byte, lead string, codexPath bool) []byte {
if !bytes.Contains(body, []byte(`"spawn_agent"`)) || !bytes.Contains(body, []byte("Available model overrides")) {
return body
}
choices := spawnChoices(r, lead, codexPath)
if len(choices) == 0 {
return body
}
var q map[string]json.RawMessage
if json.Unmarshal(body, &q) != nil {
return body
}
changed := false
if tools, ok := moreSpawnTools(q["tools"], choices); ok {
q["tools"], changed = tools, true
}
// A model that can search tools is handed spawn_agent only when it
// searches for it: Codex defers its multi-agent V1 tools behind
// tool_search (codex-rs core/src/tools/spec_plan.rs, Deferred when
// supports_search_tool), and the tool comes back in the conversation,
// in a tool_search_output, not in tools (Gearclickist on Discord, after
// v0.1.1214). Codex sends that output as it got it on every turn, so
// it is widened the same way on each.
var input []map[string]json.RawMessage
if json.Unmarshal(q["input"], &input) == nil {
in := false
for _, it := range input {
var kind string
json.Unmarshal(it["type"], &kind)
if kind != "tool_search_output" {
continue
}
if tools, ok := moreSpawnTools(it["tools"], choices); ok {
it["tools"], in = tools, true
}
}
if in {
q["input"], changed = rawJSON(input), true
}
}
if !changed {
return body
}
return rawJSON(q)
}
// moreSpawnTools is raw, a list of tools (a request's, or the ones a
// tool_search_output hands the model), with the spawn_agent among them,
// on its own or in Codex's collaboration namespace, naming choices too;
// false when there is none to widen.
func moreSpawnTools(raw json.RawMessage, choices []spawnChoice) (json.RawMessage, bool) {
var tools []map[string]json.RawMessage
if json.Unmarshal(raw, &tools) != nil {
return raw, false
}
changed := false
for _, t := range tools {
if moreSpawnModels(t, choices) {
changed = true
continue
}
// Codex's collaboration namespace holds it
var kind string
json.Unmarshal(t["type"], &kind)
var inner []map[string]json.RawMessage
if kind != "namespace" || json.Unmarshal(t["tools"], &inner) != nil {
continue
}
in := false
for _, it := range inner {
in = moreSpawnModels(it, choices) || in
}
if in {
t["tools"] = rawJSON(inner)
changed = true
}
}
if !changed {
return raw, false
}
return rawJSON(tools), true
}
// rawJSON is v encoded as it is, its < > & left as they are.
func rawJSON(v any) []byte {
var b bytes.Buffer
enc := json.NewEncoder(&b)
enc.SetEscapeHTML(false)
if enc.Encode(v) != nil {
return nil
}
return bytes.TrimRight(b.Bytes(), "\n")
}
// moreSpawnModels adds to t, when it is spawn_agent with a model
// argument and Codex's list of models in its description, the choices
// that list doesn't name.
func moreSpawnModels(t map[string]json.RawMessage, choices []spawnChoice) bool {
var name, kind, desc string
json.Unmarshal(t["name"], &name)
json.Unmarshal(t["type"], &kind)
json.Unmarshal(t["description"], &desc)
if name != "spawn_agent" || kind != "function" || !strings.Contains(desc, "Available model overrides") || strings.Contains(desc, spawnMore) {
return false
}
var params struct {
Properties map[string]json.RawMessage `json:"properties"`
}
if json.Unmarshal(t["parameters"], &params) != nil || params.Properties["model"] == nil {
return false
}
var lines []string
for _, c := range choices {
if strings.Contains(desc, "`"+c.slug+"`") {
continue
}
line := "- `" + c.slug + "`"
if c.name != "" && c.name != c.slug {
line += ": " + c.name
}
lines = append(lines, line)
if len(lines) == spawnMost {
break
}
}
if len(lines) == 0 {
return false
}
// after Codex's own list, its header's line and a "- `slug`: …" line
// each, ahead of the text that follows it
end := strings.Index(desc, "Available model overrides")
for {
nl := strings.IndexByte(desc[end:], '\n')
if nl < 0 {
end = len(desc)
break
}
end += nl
if !strings.HasPrefix(desc[end+1:], "- `") {
break
}
end++
}
add := "\n" + spawnMore + "\n" + strings.Join(lines, "\n")
t["description"] = rawJSON(desc[:end] + add + desc[end:])
return true
}
// spawnChoices is the models of the catalog Codex was handed, at CodexPath
// or at /v1, that a subagent of a lead on lead can work on, in the
// catalog's order.
func spawnChoices(r *http.Request, lead string, codexPath bool) []spawnChoice {
sealed := !codexcat.V1() && (codexPath && !strings.Contains(lead, "/") || provider.CodexAccountModel(lead))
var out []spawnChoice
if codexPath {
// Codex's own, as its backend lists them to it, less the ones
// taken out of its list on the Agents page
hidden := provider.CodexNativeHidden()
type own struct {
spawnChoice
at int
}
var owns []own
for slug, e := range codexcat.CacheEntries() {
if v, _ := e["visibility"].(string); v != "list" || hidden[slug] {
continue
}
name, _ := e["display_name"].(string)
at, _ := e["priority"].(float64)
owns = append(owns, own{spawnChoice{slug, name}, int(at)})
}
slices.SortFunc(owns, func(a, b own) int { return cmp.Or(a.at-b.at, strings.Compare(a.slug, b.slug)) })
for _, o := range owns {
out = append(out, o.spawnChoice)
}
if sealed || codexOwnOnly() {
return out
}
for _, m := range provider.CodexListed() {
out = append(out, spawnChoice{m.ID, m.Name})
}
return out
}
shown, _ := provider.CatalogFor("codex")
for _, m := range provider.CodexCatalog(keyAllowed(r, shown)) {
if sealed && !provider.CodexAccountModel(m.ID) {
continue
}
out = append(out, spawnChoice{m.ID, m.Name})
}
return out
}