Files
magpie/internal/gateway/codex_resume.go
T
yetone 12a9970d6e gateway: a resumed Codex subagent leaves a spawn model magpie no longer serves
jockyer on X: after removing a provider and switching Codex to another
model, requests kept naming the removed provider's model. Codex's
resume_agent asks for the lead's current model, and codexResumeTo put
the subagent back on the model its thread was spawned on
(codex-subagents.json, kept 30 days and across restarts) without asking
whether that model was still served. Every resume answered 404 "magpie
knows no model a/x". A spawn model of magpie's that is now unserved
(provider removed or switched off, as standIn judges it) is no longer
gone back to. The request goes on as asked, and that model is noted as
the thread's model from then on.

Other state checked after an in-process provider.Delete (the GUI's and
CLI's path inside agent.Reseat), each with a probe test. None of these
sent a request to the removed provider:
- chat completions on its own ids and on bare shared ids, with and
  without session affinity;
- /v1/responses with Codex headers, and /v1/messages with Claude Code
  headers, on the new model and on the old one;
- the old one with StandIn wired, including claude-haiku-*;
- a routing group with a member on it, with the catalog held or not;
- a delete written by another process with no request in flight.
Server-instance state was read: codexLeads, codexTurns and
codexSubagentPick validate with Resolve or CodexSubagentUnserved.
While one request holds the catalog without a break, another process's
removal is routed past for up to about 1s (heldFor). That is filed as
#5541 and not changed here.

Run on mote (mote-run), at 6f5d48ea0 and again after the rebase on
25b201eb6:
- go test ./internal/gateway -count=1 -timeout 45m: ok (776s, at
  6f5d48ea0);
- after the rebase: go test ./internal/gateway -run TestCodex: ok
  (49s);
- go vet ./internal/gateway for darwin, linux and windows: ok;
- gofmt -l: clean.
Broken by hand: with codex_resume.go at the old code,
TestCodexResumedSubagentLeavesARemovedProvider is red (404 on the
first resume).

Not tried: a real Codex app resuming a subagent after a real provider
removal. The reporter's "until the gateway restarted" was not
reproduced. A restart doesn't clear codex-subagents.json, so this
fix may not be their whole case. Settings' own model picks
(CodexTitles, CodexDescriptions and the like) that name a removed
provider were not checked.
2026-11-06 22:36:23 +08:00

207 lines
6.6 KiB
Go

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 ""
}
// threadOf is the thread a request names apart from its session, for
// ${threadId} (provider/conversation.go): Codex's thread_id, in its turn
// metadata or its thread-id header. "" when it names none — no other
// agent does — and ${threadId} is then the session's.
func threadOf(h http.Header, body []byte) string {
for _, t := range []string{requestSessionMetadata(h, body).Thread, h.Get("thread-id")} {
if t = strings.TrimSpace(t); t != "" && len(t) <= 128 {
return t
}
}
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 ""
}
to := s.codexSpawns.keep(thread, asked)
// a spawn model of magpie's it no longer serves (its provider removed
// or switched off) is not gone back to: the subagent was sent there,
// to a 404, after the user had removed the provider and moved Codex
// to another model (jockyer on X). It goes on as asked, and that is
// its model from now on.
if strings.Contains(to, "/") && unserved(to) {
s.codexSpawns.moved(thread, to, asked)
return ""
}
return to
}
// moved notes asked as thread's model in place of from, the model it was
// spawned on, which magpie no longer serves.
func (c *codexSpawns) moved(thread, from, asked string) {
c.mu.Lock()
defer c.mu.Unlock()
if v, ok := c.m[thread]; !ok || v.Model != from {
return
}
now := time.Now()
c.m[thread] = codexSpawn{Model: asked, At: now}
c.save(c.from, now)
}
// 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)
}
}