gateway: Codex's spawn_agent names every model a subagent may be put on, not only the first five (Gearclickist on Discord)

Gearclickist turned on "Codex subagents on any model", but when Codex
dispatched subagents only a few models could be picked. Codex itself caps
the list: spawn_agent's description names only the first five
show_in_picker models of its catalog (codex-rs child_config.rs
MAX_SPAWN_AGENT_MODEL_OVERRIDES, multi_agents_spec.rs
spawn_agent_models_description), Codex's own ahead of magpie's. Yet it
takes any catalog model by name (find_spawn_agent_model_name). So the lead
saw none of magpie's models.

spawnAgentModels (codex_spawn_models.go) adds the rest of the catalog
Codex was handed after Codex's own list, under a line of its own, at most
200. It covers spawn_agent at the top level and in Codex's multi_agent_v1
namespace, at CodexPath (codexBackend) and at /v1/responses for Codex
(handle).
- At CodexPath the list is Codex's own listed models less those hidden on
  the Agents page, then CodexListed unless Codex is held to its own.
- At /v1 it is CodexCatalog under the key's allowance.
- A lead the ChatGPT backend answers in multi-agent V2 seals its
  subagents' tasks for a ChatGPT account (#619), so it is offered Codex's
  own only.
Only the tool's description changes, never base_instructions. With V1 on,
it does change in requests to the ChatGPT backend too.

Not covered: the model_catalog_in_context feature (under development, off
by default) puts a five-model catalog in context, and it is not widened.

Run:
- go test ./internal/gateway ./internal/agent -count=1 under a sandbox
  HOME: ok.
- TestSpawnAgentNamesEveryModel uses 40 models on a real Codex 0.162.0
  request (testdata/workdir/codex-0.162.0.json). Its 4 subtests are
  CodexPath, /v1, a sealed V2 lead and a V1 lead, and all pass.
  - With spawnAgentModels returning body by hand: CodexPath, /v1 and V1
    go red.
  - With the sealed rule taken out: V2 goes red.
- go vet on darwin, GOOS=linux -tags nogui, and GOOS=windows; gofmt -l
  is clean.

Not verified: a real Codex lead picking one of magpie's models past the
fifth from the longer list.
This commit is contained in:
yetone
2026-10-12 23:30:08 +08:00
parent 7639c1d8db
commit 5d33f060b7
6 changed files with 357 additions and 5 deletions
+1
View File
@@ -58,6 +58,7 @@ something else shows up as drift.
- Claude Code 2.1.296 reads a Claude model whose version has a dot (`relay/claude-opus-4.6-us`) as Claude Opus 4: a retired warning, budget thinking, 32000 output tokens, no effort. With dashes (`relay/claude-opus-4-6-us`) it knows the model (misteer_ti. on Discord). So every model magpie writes into its settings (`model`, the tier envs, `ANTHROPIC_SMALL_FAST_MODEL`, `CLAUDE_CODE_SUBAGENT_MODEL`, `modelPicker`), T3 Code's Claude slugs and Claude Desktop's Code-tab ids (`claudeLooking`) spell a dotted Claude version with dashes (`provider.ClaudeSpelled`), only when that spelling stands for one served id. A Claude model listed to Desktop with reasoning levels is given as `magpie-<n>.anthropic.<model>`, its dotted version dashed as well (`claudeModel`: Copilot's `claude-opus-5.5` is `…anthropic.claude-opus-5-5`, which Claude Code knows; it was `mythos-magpie-<n>`, an unknown model, and Haiku 4.5 got an effort Copilot refuses, #1819); a request for it is served by `<n>` alone (`aliased`), so that spelling needn't be unique. Mythos counts as Claude here too: Claude Code matches `claude-mythos-5-1` by substring, so `claude-mythos-5.1` would read as Mythos 5. Every read of those keys takes it back (`provider.ClaudeRead`: `claudeIn`'s `env`, `claudeMain`, `claudeStandInAt`), so magpie's fields, applied state and Drift keep the dotted id. The user's own values are stashed and given back as written. Values an older magpie wrote dotted are rewritten on the next Sync. Other vendors' ids are never respelled ([`claudedash.go`](../../internal/provider/claudedash.go)).
- Codex's "subagents" field is `[agents] default_subagent_model`: only the model a subagent starts on when its lead names none in `spawn_agent` (codex-rs `core/src/agent/child_config.rs`). Unset, it isn't "same as model": the lead may still name another, so the GUI calls it the lead's pick, else the model (`leadPicks` in app.js), and its title points at the "subagent model" field.
- Codex's "subagent model" field writes nothing to Codex's config: its lead names each subagent's model in `spawn_agent`, which `[agents]` can't overrule. It is magpie's setting (`settings.CodexSubagentModel`, [`codex_subagent.go`](../../internal/provider/codex_subagent.go)), and the gateway moves the subagent's request onto it (see [gateway routing](gateway-routing.md)). Its options are every model and routing group Codex's own lists show (`CatalogFor("codex")`, so a model taken out of them or not picked is left out here too), ChatGPT accounts' first (#1633: a lead on a chat provider wants its subagents there too). A task a ChatGPT-backed lead sealed opens only on a ChatGPT account, so the gateway keeps such a subagent on its own model when the one set is another provider's. Its setter takes any `provider/model` or `group/<id>`, also one magpie doesn't serve now, so a profile or backup put back on another computer still applies (`ApplyFields` stops at the first failed Set), and refuses one of Codex's own bare names.
- Codex's `spawn_agent` tool names only the first five models of its catalog to the lead (codex-rs `MAX_SPAWN_AGENT_MODEL_OVERRIDES` in `child_config.rs`, `spawn_agent_models_description`), Codex's own ahead of magpie's, though it takes any catalog model by name (`find_spawn_agent_model_name`). So a lead could put its subagents on none of magpie's models (Gearclickist on Discord). The gateway adds the rest of the catalog Codex was handed to that tool's description, after Codex's own list, at most 200 (`spawnAgentModels` in [`codex_spawn_models.go`](../../internal/gateway/codex_spawn_models.go)). At `CodexPath` that is Codex's own listed models less the hidden ones, then `CodexListed` unless Codex is held to its own. At `/v1` it is `CodexCatalog` under the key's allowance. A lead the ChatGPT backend answers in multi-agent V2 seals its subagents' tasks for a ChatGPT account (#619), so it gets Codex's own only. The model catalog Codex puts in context under `model_catalog_in_context` (under development, off by default) is capped at five too, and isn't widened.
- Snow CLI runs on one profile at a time (`profiles/<name>.json` in `~/.snow` or `$SNOW_CONFIG_DIR`, named in `active-profile.json`) and copies the active one over `config.json` at every start, `snow --ask` too ([`snow.go`](../../internal/agent/snow.go)). magpie writes a `magpie` profile, makes it the active one, and copies it to `config.json` itself, so a Snow already running and Snow App's "Sync Snow CLI API config" see the same. It is made from the profile the user was on, their settings kept and its OAuth sign-in left out. A vision model of that profile comes along only with an endpoint and key of its own (`snowOwnVision`), since one on the profile's would now go to the gateway. `maxContextTokens`, `maxTokens` and `supportsVision` follow the model from the catalog (`snowSynced`; `supportsVision` as every agent is told, true while magpie's Vision describes images); what magpie last wrote of them is stashed, and one the user changed since in Snow's own settings is kept through later picks and syncs. The small field is magpie's profile's `basicModel`, Snow's light model for summaries, compaction and file search: empty while it follows the main model, a model through magpie of its own kept through new main models and syncs; on a profile of the user's it offers nothing and is hidden. The thinking field is magpie's profile's `chatThinking` (`{enabled: true, reasoning_effort}`), the only thinking setting Snow reads on the chat protocol; empty deletes it, Snow's default, which sends thinking disabled. A chatThinking the user brought from their profile is shown, not written over. The profile they were on (or that there was no `active-profile.json`) and a `magpie.json` of their own are stashed and put back by Disconnect. A Snow from before profiles (`config.json` alone) gets the `default.json` Snow itself would have made of it, so its next start doesn't take magpie's for the user's. Picking a model of another of the user's profiles switches Snow to that profile. On magpie's profile, a value that is neither a model through magpie nor the model of one of the user's profiles is refused and changes nothing (#1457: `magpie snow --help` used to take magpie out and write `--help` as the model of the profile it went back to). Gemini CLI's auth field refuses an auth it doesn't know before it unroutes, for the same reason. On the CLI, `-h`/`--help` after any command or agent only prints its usage, before `run` reads or moves anything, and any other flag given to `magpie <agent> …` is refused (`help_cli.go`; `TestHelpOnEveryCommandDoesNothing` walks `run`'s switch and every agent).
- omp's `enabledModels` in `config.yml` is the list it holds its default role to: a model left out of it isn't used, whatever `modelRoles.default` says (#1769). So a model picked for the default role is added to a list that is there and doesn't take it in already, by name or by one of omp's globs (`*` not crossing `/`, as `Bun.Glob`), and once nothing in `config.yml` is on magpie its plain `magpie/…` entries are taken out (a list left empty goes, never `[]`); a renamed provider's entries are renamed once, and folder-scoped entries are left alone (`ompScope*` in [`omp_scope.go`](../../internal/agent/omp_scope.go)). No list, no change: omp then takes every model. A list that leaves the default role's model out is drift, which Reapply mends.
- A value an agent spells as its own provider's model is never taken for one of magpie's, even when magpie has a provider of the same name (`Spelled`, #835).
+5 -4
View File
@@ -1179,10 +1179,11 @@ func codexIn(at place) *Agent {
Options: func(cur map[string]string) []Option { return codexEfforts(models(), cur["model"]) },
},
{
// Codex lists only the first few models in the spawn_agent
// tool it gives the model, its own ahead of magpie's, so a
// subagent is put on one of magpie's here, where it can't be
// by the model unless asked by name. It is only the model a
// Codex lists only the first five models in the spawn_agent
// tool it gives the model, its own ahead of magpie's (the
// gateway names the rest there, spawnAgentModels), and a
// subagent is put on one of magpie's here without the lead
// naming it. It is only the model a
// spawn that names none starts on: unset, the lead's own,
// but a lead naming another in spawn_agent gets that one
// (core/src/agent/child_config.rs), so the GUI says the
+3
View File
@@ -103,6 +103,9 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
body, model = withModel(body, pick.To), pick.To
}
}
// spawn_agent names every model a subagent may be put on,
// not only Codex's first five (Gearclickist on Discord)
body = spawnAgentModels(r, body, model, true)
}
// The namespace owns the route even if a model is not in the catalog.
// Unknown providers/groups must fail locally, never fall through to OpenAI.
+196
View File
@@ -0,0 +1,196 @@
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.
const spawnMore = "More models that may be set as `model` (Codex names only five above; magpie serves these too):"
// 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
}
var tools []map[string]json.RawMessage
if json.Unmarshal(q["tools"], &tools) != nil {
return body
}
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 body
}
q["tools"] = rawJSON(tools)
return rawJSON(q)
}
// 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
}
+144
View File
@@ -0,0 +1,144 @@
package gateway
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// spawnDescription is the description of the spawn_agent tool in a
// Responses request body, "" when it has none.
func spawnDescription(t *testing.T, body []byte) string {
t.Helper()
var q struct {
Tools []struct {
Type string `json:"type"`
Name string `json:"name"`
Description string `json:"description"`
Tools []struct {
Name string `json:"name"`
Description string `json:"description"`
} `json:"tools"`
} `json:"tools"`
}
if err := json.Unmarshal(body, &q); err != nil {
t.Fatalf("%v: %.300s", err, body)
}
for _, tl := range q.Tools {
// a translated request has it flat, multi_agent_v1__spawn_agent
if tl.Name == "spawn_agent" || strings.HasSuffix(tl.Name, "__spawn_agent") {
return tl.Description
}
for _, in := range tl.Tools {
if in.Name == "spawn_agent" {
return in.Description
}
}
}
return ""
}
// codexSpawnRequest is a real Codex 0.162.0 request, its spawn_agent
// naming the five models Codex names at most, on model.
func codexSpawnRequest(t *testing.T, model string) string {
t.Helper()
b, err := os.ReadFile("testdata/workdir/codex-0.162.0.json")
if err != nil {
t.Fatal(err)
}
return string(withModel(b, model))
}
// Codex's spawn_agent names only the first five models of its catalog
// to the lead (codex-rs MAX_SPAWN_AGENT_MODEL_OVERRIDES), though it takes
// any model of it: with 40 of magpie's in the catalog, the lead saw none
// of them (Gearclickist on Discord: "Codex subagents on any model" on,
// and only a few models could be picked). The tool now names every model
// a subagent of that lead can work on, at CodexPath and at /v1; for a
// lead the ChatGPT backend answers in multi-agent V2, whose subagents'
// tasks only a ChatGPT account opens, only Codex's own.
func TestSpawnAgentNamesEveryModel(t *testing.T) {
var models []string
for i := 1; i <= 40; i++ {
models = append(models, fmt.Sprintf("m%d", i))
}
f := &fake{t: t, reply: sse(`data: {"type":"response.created","response":{"id":"r1"}}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9,"output_tokens":2}}}`)}
up := setup(t, provider.Responses, f)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Responses: up.URL + "/v1", Models: models}); err != nil {
t.Fatal(err)
}
var upstream []byte
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
upstream, _ = io.ReadAll(r.Body)
w.Header()["Content-Type"] = nil
io.WriteString(w, sse(`data: {"type":"response.created","response":{"id":"r1"}}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9,"output_tokens":2}}}`))
})
namesAll := func(t *testing.T, desc string) {
t.Helper()
for _, m := range models {
if !strings.Contains(desc, "- `fake/"+m+"`") {
t.Fatalf("spawn_agent doesn't name fake/%s:\n%s", m, desc)
}
}
// Codex's own five kept, and its text after the list
head, tail, _ := strings.Cut(desc, spawnMore)
list, rest, ok := strings.Cut(tail, "\n Spawn a sub-agent")
if !ok || !strings.Contains(head, "- `gpt-6.1-sol`") || !strings.Contains(head, "- `gpt-5.6-sol`") ||
!strings.HasPrefix(rest, " for a well-scoped task.") {
t.Fatalf("description:\n%s", desc)
}
for _, l := range strings.Split(strings.TrimPrefix(list, "\n"), "\n") {
if !strings.HasPrefix(l, "- `") {
t.Fatalf("line %q in the list:\n%s", l, desc)
}
}
}
t.Run("CodexPath, a lead on magpie's model", func(t *testing.T) {
code, body := codexPost(t, codexSpawnRequest(t, "fake/m1"))
if code != 200 {
t.Fatalf("%d %s", code, body)
}
namesAll(t, spawnDescription(t, f.got))
})
t.Run("/v1, Codex with magpie as its provider", func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(codexSpawnRequest(t, "fake/m2")))
req.Header.Set("User-Agent", "codex_cli_rs/0.162.0")
New().Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
namesAll(t, spawnDescription(t, f.got))
})
t.Run("a lead on Codex's own model, V2", func(t *testing.T) {
code, body := codexPost(t, codexSpawnRequest(t, "gpt-6.1-sol"))
if code != 200 {
t.Fatalf("%d %s", code, body)
}
if d := spawnDescription(t, upstream); d == "" || strings.Contains(d, "fake/") || strings.Contains(d, spawnMore) {
t.Fatalf("a sealed lead's subagents offered magpie's models:\n%s", d)
}
})
t.Run("a lead on Codex's own model, V1", func(t *testing.T) {
if err := provider.SetCodexAgentsV1(true); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { provider.SetCodexAgentsV1(false) })
code, body := codexPost(t, codexSpawnRequest(t, "gpt-6.1-sol"))
if code != 200 {
t.Fatalf("%d %s", code, body)
}
namesAll(t, spawnDescription(t, upstream))
})
}
+8 -1
View File
@@ -1156,11 +1156,18 @@ func (s *Server) handle(from provider.Protocol) http.HandlerFunc {
return
}
var err error
body, _, err = requestModel(body)
var model string
body, model, err = requestModel(body)
if err != nil {
writeError(w, from, 400, err.Error())
return
}
// Codex with magpie as its provider: spawn_agent names every
// model a subagent may be put on, not only Codex's first five
// (Gearclickist on Discord)
if from == provider.Responses && (fromCodex(r.Header) || agentOf(r) == "codex") {
body = spawnAgentModels(r, body, model, false)
}
if from == provider.Chat {
body = thinkingEffort(body)
}