From 25bf394a72a6eeb8bba9876b58e8a8a79d896d42 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 29 Oct 2026 02:41:29 +0800 Subject: [PATCH] gateway: a resumed Codex subagent goes back on the model it was spawned on HoGee_xxl on X: a Codex subagent brought back with resume_agent ran on the lead's model, not the one the lead spawned it on. Codex's multi-agent V1 (the one magpie's own models ask for) builds the resumed subagent's config from the lead's current turn: codex-rs core/src/agent/child_config.rs build_agent_resume_config -> build_agent_shared_config sets config.model to turn.model_info().slug, and core/src/agent/control/spawn.rs resume_single_agent_from_rollout starts the thread on that config without reading back the thread's stored model. Neither the spawn_agent model nor [agents] default_subagent_model is asked again. V2's ensure_v2_agent_loaded does put a thread back on its stored model, so this follows Codex's own rule. The gateway now notes the model each Codex subagent thread (thread_id in x-codex-turn-metadata / client_metadata; session_id only on a Codex old enough not to share it) first asked for, and puts a later request of that thread asking for another back on it. Kept in codex-subagents.json beside providers.json (0600, temp file and rename, the 512 latest, 30 days), so a resume after a restart is known. A model set for every subagent (codexSubagentPick) still wins. No prompt or base_instructions is touched. Run (mote-run): go test ./internal/gateway -run 'TestCodexResumed| TestCodexSubagentThreadOf|TestCodexSubagent|TestCodexFollow| SessionMetadata|TestCodexSide' -count=1: ok. Broken by hand: skipping the restore in codex_backend.go turns TestCodexResumedSubagentKeepsItsSpawnModel red ("worker-1 asking gpt-5.5 went on gpt-5.5, want gpt-6-astra"); skipping the save turns its after-restart step red. Not tried: a real Codex resume_agent run against a real ChatGPT account. --- internal/gateway/codex_backend.go | 8 +- internal/gateway/codex_resume.go | 170 ++++++++++++++++++++++++++ internal/gateway/codex_resume_test.go | 100 +++++++++++++++ internal/gateway/gateway.go | 3 + internal/gateway/session_parent.go | 2 + 5 files changed, 282 insertions(+), 1 deletion(-) create mode 100644 internal/gateway/codex_resume.go create mode 100644 internal/gateway/codex_resume_test.go diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 4f80cb16e..b120e5a93 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -108,7 +108,13 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) { noteAsked(r.Context(), model) // a turn of the conversation's own: the model its side calls may // follow (codexFollowTo) - kind := requestCallKind(r.Header, requestSessionMetadata(r.Header, body)) + meta := requestSessionMetadata(r.Header, body) + kind := requestCallKind(r.Header, meta) + // a subagent resume_agent brought back on its lead's model goes + // back on the one it was spawned with (codexResumeTo) + if to := s.codexResumeTo(r, agentOf(r), kind, model, meta); to != "" { + body, model = withModel(body, to), to + } s.codexLeads.saw(r, kind, model) // a thread's title, where Settings sends it (#705) — the request // still on Codex's own model, through its sign-in, when it says diff --git a/internal/gateway/codex_resume.go b/internal/gateway/codex_resume.go new file mode 100644 index 000000000..52fd6ea5f --- /dev/null +++ b/internal/gateway/codex_resume.go @@ -0,0 +1,170 @@ +package gateway + +import ( + "encoding/json" + "net/http" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/steady" + "github.com/yetone/magpie/internal/usage" +) + +// A Codex subagent resumed with resume_agent went on its lead's model, not +// the one it was spawned on (HoGee_xxl on X). Codex's multi-agent V1, which +// magpie's own models ask for, builds the resumed subagent's config from +// the lead's current turn (codex-rs core/src/agent/child_config.rs, +// build_agent_resume_config → build_agent_shared_config sets config.model +// to turn.model_info().slug), and resume_single_agent_from_rollout +// (core/src/agent/control/spawn.rs) starts the thread on that config +// without reading back the model the thread has stored; neither the +// spawn_agent model nor [agents] default_subagent_model is asked again. +// Multi-agent V2's own reload does put a thread back on its stored model +// (spawn.rs, ensure_v2_agent_loaded: config.model = stored_model), so +// keeping a subagent on the model it was spawned with is Codex's own rule, +// which the V1 path misses. +// +// So the gateway notes the model each Codex subagent thread first asked +// for, and puts a later request of that thread asking for another back on +// it. Within a V1 thread the model never changes otherwise: a subagent has +// no /model. Kept on disk (codex-subagents.json, next to the providers) so +// a subagent resumed after magpie restarted, an update's included, is +// still known. A model set for every subagent (codexSubagentPick) still +// moves the request after this. + +// codexSpawnsKept is how many subagent threads are remembered, the latest. +const codexSpawnsKept = 512 + +// codexSpawnKeep is how long a subagent thread's model is remembered after +// its last request. +const codexSpawnKeep = 30 * 24 * time.Hour + +type codexSpawn struct { + Model string `json:"model"` + At time.Time `json:"at"` +} + +// codexSpawns is the model each Codex subagent thread was spawned on, by +// its thread id. +type codexSpawns struct { + mu sync.Mutex + m map[string]codexSpawn + from string // the file m was read from +} + +func codexSpawnsPath() string { + return filepath.Join(filepath.Dir(provider.Path()), "codex-subagents.json") +} + +// codexSubagentThread is the thread a Codex subagent's request is of: +// thread_id in its turn metadata. Codex's session_id is shared by a root +// thread and every subagent under it, so it names a subagent only in a +// Codex from before that, where it differs from the parent thread. +func codexSubagentThread(h http.Header, meta sessionMetadata) string { + if t := strings.TrimSpace(meta.Thread); t != "" && len(t) <= 128 { + return t + } + parent := strings.TrimSpace(meta.Parent) + if parent == "" { + parent = strings.TrimSpace(h.Get("x-codex-parent-thread-id")) + } + if s := sessionOf(h); s != "" && parent != "" && s != parent { + return s + } + return "" +} + +// codexResumeTo is the model a Codex subagent's request goes on instead +// of asked: the one its thread was spawned on, when it asks for another. +// "" leaves the request as it came: not a Codex subagent's, a thread not +// seen before (noted now), or its own model asked for. +func (s *Server) codexResumeTo(r *http.Request, agent, kind, asked string, meta sessionMetadata) string { + if agent != "codex" && !fromCodex(r.Header) || asked == "" || usage.PurposeOf(kind) != "kind:collab_spawn" { + return "" + } + thread := codexSubagentThread(r.Header, meta) + if thread == "" { + return "" + } + return s.codexSpawns.keep(thread, asked) +} + +// keep notes asked as thread's model when thread is new, and says the +// model it was spawned on when that isn't asked. +func (c *codexSpawns) keep(thread, asked string) string { + c.mu.Lock() + defer c.mu.Unlock() + path := codexSpawnsPath() + if c.m == nil || c.from != path { + c.m, c.from = readCodexSpawns(path), path + } + now := time.Now() + if v, ok := c.m[thread]; ok && now.Sub(v.At) < codexSpawnKeep { + v.At = now + c.m[thread] = v + if v.Model != asked { + return v.Model + } + return "" + } + c.m[thread] = codexSpawn{Model: asked, At: now} + // written as a thread is first seen, once a spawn, not once a request + c.save(path, now) + return "" +} + +func readCodexSpawns(path string) map[string]codexSpawn { + m := map[string]codexSpawn{} + b, err := os.ReadFile(path) + if err != nil { + return m + } + // a file that can't be read is no memory: each thread is noted afresh + if decodeJSON(b, &m) != nil { + return map[string]codexSpawn{} + } + return m +} + +// save writes the latest threads, only for this user to read. Called +// with c.mu held. +func (c *codexSpawns) save(path string, now time.Time) { + ids := make([]string, 0, len(c.m)) + for id, v := range c.m { + if now.Sub(v.At) >= codexSpawnKeep || v.Model == "" { + delete(c.m, id) + continue + } + ids = append(ids, id) + } + if len(ids) > codexSpawnsKept { + sort.Slice(ids, func(i, j int) bool { return c.m[ids[i]].At.After(c.m[ids[j]].At) }) + for _, id := range ids[codexSpawnsKept:] { + delete(c.m, id) + } + } + b, err := json.Marshal(c.m) + if err != nil { + return + } + if os.MkdirAll(filepath.Dir(path), 0o700) != nil { + return + } + path, err = edit.Target(path) // a symlink stays, its target written + if err != nil { + return + } + tmp := path + ".magpie-tmp" + if os.WriteFile(tmp, b, 0o600) != nil { + return + } + if steady.Rename(tmp, path) != nil { + os.Remove(tmp) + } +} diff --git a/internal/gateway/codex_resume_test.go b/internal/gateway/codex_resume_test.go new file mode 100644 index 000000000..76b2d232a --- /dev/null +++ b/internal/gateway/codex_resume_test.go @@ -0,0 +1,100 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +const workerAsk = `{"type":"message","role":"user","content":[{"type":"input_text","text":"go on"}]}` + +// codexThreadAsks is a request of Codex's as a recent Codex sends it: the +// session_id shared by the root thread and every subagent under it, the +// thread's own id in its turn metadata; a subagent's when parent is set. +func codexThreadAsks(s *Server, model, thread, parent string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + body := `{"model":"` + model + `","stream":true,"input":[` + workerAsk + `]}` + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + req.Header.Set("User-Agent", "codex_cli_rs/0.162.1 (Mac OS 26.2.0; arm64)") + req.Header.Set("session_id", "root-1") + meta := `{"session_id":"root-1","thread_id":"` + thread + `"` + if parent != "" { + req.Header.Set("x-openai-subagent", "collab_spawn") + req.Header.Set("x-codex-parent-thread-id", parent) + meta += `,"parent_thread_id":"` + parent + `"` + } + req.Header.Set("x-codex-turn-metadata", meta+"}") + s.Handler().ServeHTTP(rec, req) + return rec +} + +// HoGee_xxl on X: Codex's resume_agent builds the resumed subagent's +// config from its lead's turn (codex-rs core/src/agent/child_config.rs, +// build_agent_resume_config), so a subagent spawned on gpt-6-astra came +// back on the lead's gpt-5.5. It goes back on gpt-6-astra; another +// subagent, and the lead, go on as asked. Remembered across a restart. +func TestCodexResumedSubagentKeepsItsSpawnModel(t *testing.T) { + up := codexSubagentSetup(t) + s := New() + steps := []struct{ model, thread, parent, want string }{ + {"gpt-5.5", "root-1", "", "gpt-5.5"}, // the lead + {"gpt-6-astra", "worker-1", "root-1", "gpt-6-astra"}, // spawned on astra + {"gpt-5.5", "worker-2", "root-1", "gpt-5.5"}, // spawned on the lead's + {"gpt-5.5", "worker-1", "root-1", "gpt-6-astra"}, // resumed on the lead's + {"gpt-5.5", "root-1", "", "gpt-5.5"}, // the lead's own, untouched + } + for i, st := range steps { + if rec := codexThreadAsks(s, st.model, st.thread, st.parent); rec.Code != 200 { + t.Fatalf("step %d: %d %s", i, rec.Code, rec.Body.String()) + } + if got := up.asked(); got[len(got)-1] != st.want { + t.Fatalf("step %d (%s asking %s) went on %s, want %s", i, st.thread, st.model, got[len(got)-1], st.want) + } + } + // a magpie started afresh still knows worker-1 + if rec := codexThreadAsks(New(), "gpt-5.5", "worker-1", "root-1"); rec.Code != 200 { + t.Fatalf("after a restart: %d %s", rec.Code, rec.Body.String()) + } + if got := up.asked(); got[len(got)-1] != "gpt-6-astra" { + t.Fatalf("after a restart worker-1 went on %s", got[len(got)-1]) + } +} + +// A model set for every subagent still holds a resumed one to it. +func TestCodexResumedSubagentHeldToTheModelSet(t *testing.T) { + up := codexSubagentSetup(t) + s := New() + codexThreadAsks(s, "gpt-5.5", "worker-1", "root-1") + if err := provider.SetCodexSubagentModel("codex/gpt-6-astra"); err != nil { + t.Fatal(err) + } + if rec := codexThreadAsks(s, "gpt-5.5", "worker-1", "root-1"); rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + if got := up.asked(); got[len(got)-1] != "gpt-6-astra" { + t.Fatalf("held subagent went on %s", got[len(got)-1]) + } +} + +// A Codex from before session_id was shared names a subagent's thread by +// its session_id; a recent one whose metadata lacks thread_id shares the +// lead's session_id, and is left as asked rather than tied to the lead. +func TestCodexSubagentThreadOf(t *testing.T) { + h := httptest.NewRequest("POST", "/", nil).Header + h.Set("session_id", "worker-9") + h.Set("x-codex-parent-thread-id", "lead-9") + if got := codexSubagentThread(h, sessionMetadata{}); got != "worker-9" { + t.Fatalf("older Codex: %q", got) + } + h.Set("session_id", "lead-9") + if got := codexSubagentThread(h, sessionMetadata{}); got != "" { + t.Fatalf("shared session id taken as the thread: %q", got) + } + if got := codexSubagentThread(h, sessionMetadata{Thread: "worker-10"}); got != "worker-10" { + t.Fatalf("thread_id: %q", got) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2a35e7a23..b2487221d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -435,6 +435,9 @@ type Server struct { // codexLeads is the model each Codex conversation's own turns last // went on, for its side calls to follow (codexFollowTo) codexLeads codexLeads + // codexSpawns is the model each Codex subagent thread was spawned on, + // which a resumed one goes back on (codexResumeTo) + codexSpawns codexSpawns // the listener, swapped when the gateway is shared on the network or // taken off it (see Relisten) lnMu sync.Mutex diff --git a/internal/gateway/session_parent.go b/internal/gateway/session_parent.go index 98ccd2998..eab7ced8c 100644 --- a/internal/gateway/session_parent.go +++ b/internal/gateway/session_parent.go @@ -32,6 +32,7 @@ func isPredictionKind(kind string) bool { // prompts or the rest of the metadata in the trace. type sessionMetadata struct { Turn string `json:"turn_id"` + Thread string `json:"thread_id"` Source string `json:"thread_source"` Parent string `json:"parent_thread_id"` Forked string `json:"forked_from_thread_id"` @@ -57,6 +58,7 @@ func requestSessionMetadata(h http.Header, body []byte) sessionMetadata { } } else if len(metadata) > 0 { _ = json.Unmarshal(metadata["turn_id"], &m.Turn) + _ = json.Unmarshal(metadata["thread_id"], &m.Thread) // Compatibility projections used by clients without the full blob. _ = json.Unmarshal(metadata["thread_source"], &m.Source) _ = json.Unmarshal(metadata["parent_thread_id"], &m.Parent)