Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
codex: Disconnect and Connect restart the Codex app's own app-server, so the app stops sending to magpie without a restart
yetonedf8374921895
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex 6e5fe8bb7..b18145b67 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -76,7 +76,7 @@ something else shows up as drift.- Grok App (RongleCat/grok-app, a desktop front end that starts Grok Build over ACP) keeps its provider channels in `agent-home/config.toml` under its data folder: `$GROK_APP_HOME`, else where its `directories` crate puts it, or its `~/.grok-app` fallback when that is the one there (`grokApp` in [`grokapp.go`](../../internal/agent/grokapp.go)). Its composer lists only Grok Build's official catalog, never the `[model."magpie/…"]` tables of Grok Build's row, so magpie adds itself as a channel, `[model.magpie]`, with the keys the App's Providers page writes: the gateway's `/v1`, a key naming Grok App, `api_backend = "chat_completions"`, `app_provider_mode = "generic"`, and `app_models`, a JSON list of magpie's models with `contextWindow`, `supportsVision` and their effort levels (no `none`; a default the user marks in the App stays, else medium). The picked model's `context_window` (a bare integer) and `supports_reasoning_effort` (a bare bool, Grok Build's gate for `--reasoning-effort`) are on the channel, as the App puts them there when a model is picked in its composer. `[models] default` is the route, and magpie does not set it: setting it to `"magpie"` makes the App drop its own sign-in (`ensure_independent_for_custom_route`). The route stays whatever the App had. Pressing Use on magpie under Accounts is what switches it. A magpie that already set the route puts the old one back once, on the next sync or connect (`grokAppReleased`); a Use after that stays. Disconnect drops only the channel, and puts the route back only when it is still `"magpie"`: the one stashed at connect, else the one `connect.was` holds. One of the App's own routes picked in magpie's model field is written as the route and takes magpie's channel out, as picking another provider does elsewhere. A sync with no channel and a route other than `"magpie"` writes nothing, magpie's stash included, and Check says so when the route is `"magpie"` with the channel gone. A model picked in the App's composer since is the user's and stays through a sync, and a sync with nothing to change doesn't write. Shared mode keeps `GROK_HOME` at `~/.grok` (Grok Build's library row). Independent mode, which Use turns on, reads agent-home: the Library writes `AGENTS.md`, `[mcp_servers]` in the same `config.toml`, and `skills/` there, and Grok App also reads `~/.agents/skills`. RTK has no Grok hook, so the Library lists Grok App with the switch off. The notice, while the App runs, says magpie is a custom provider in Settings › Account, a chat can pick its models in the model picker, and the App stays on its current route until Use.- JSON/JSONC config edits and their previews reject malformed input rather than editing a partially parsed document. Object edits and VS Code's model-group array edits leave the original file untouched on a parse error; valid comments and trailing commas remain supported (`internal/edit`).- A config that starts with a UTF-8 byte order mark (a Windows `settings.json` or `config.toml` saved by PowerShell, Notepad or a channel switcher, #1534) is read without it (`edit.Read`), and a write keeps it (`keepBOM` in `WriteAtomic`): the user's file keeps the encoding it was saved in. That covers every format `internal/edit` writes (JSON/JSONC and its arrays, TOML, YAML, env); Codex reads a TOML file through a BOM too, so magpie no longer refuses one. A file read some other way trims it with `edit.TrimBOM` (the Claude Code and CC Switch imports). A line an edit takes out of a CRLF file goes with its `\r\n`.-- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/<model>`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`, through the `provider.CodexAppOnMagpie` hook) and again when Codex is put back on the account after its reset, on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`.+- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/<model>`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes (`model_provider`, `openai_base_url`, `model_catalog_json`, the magpie table's `base_url`; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out. Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`.- Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is.- Claude Desktop applying a configLibrary profile other than magpie's is not drift when that profile is a gateway profile for this magpie's gateway (`desktopAppliedGateway` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)): Desktop's "Import configuration" adds a file exported on another computer, magpie's profile there with the user's connectors (`managedMcpServers`), as a new entry under a random id (aa86222 on Discord). magpie keeps it applied on Reconnect and through Sync, and writes in it only `inferenceGatewayApiKey` (with a missing auth scheme) when the gateway would refuse its key (`desktopKeyApplied`; magpie's own keys count as taken, `desktopKeyTaken`). A profile for another gateway, CC Switch's among them, is still drift, and Reconnect applies magpie's. The first switch-on still starts magpie's profile from an applied one (#2035). `TestClaudeDesktopImportedProfileIsOnMagpie`.- A field that follows another while empty (`Follows`: Claude Code's tiers and subagents on its main model) is read by `Drift` as on that field's model. The main model moved, in Claude Code's own `/model`, onto the model magpie had set a tier to is not drift (#1050). The tier keeps that model as its own through the move and the next one (`tier_own` in the stash), whatever it would follow on the new main model: fable, which follows no model that is no Fable, and haiku, which follows a Claude model on its Haiku, read as following and lost their model on the next move (#2257).diff --git a/internal/agent/agents.go b/internal/agent/agents.goindex 0d0064e9a..4684214ee 100644--- a/internal/agent/agents.go+++ b/internal/agent/agents.go@@ -47,19 +47,35 @@ func init() {// a Copilot CLI signed in inside a running distro (#723)provider.CopilotWSLHomes = copilotWSLHomes// the Codex app's app-server is restarted when magpie becomes Codex's- // provider for its used-up ChatGPT account, and when it stops being it- provider.CodexAppOnMagpie = codexAppOnMagpie+ // provider for its used-up ChatGPT account, and when it stops being it;+ // and when Codex is connected or disconnected, or its route otherwise+ // changes, so a running app sends where its config now says+ provider.CodexAppRoute = codexAppRoute}-// codexAppOnMagpie is whether magpie is Codex's provider for its used-up-// ChatGPT account (AppOut); not known when Codex's config can't be read.-func codexAppOnMagpie() (on, known bool) {+// codexAppRoute is where Codex's config sends it, as the app-server reads+// it at its start: the keys magpie writes for that, never one the Codex+// app writes itself (model); and whether magpie is Codex's provider for+// its used-up ChatGPT account (AppOut). Not known when Codex's config+// can't be read.+func codexAppRoute() (route string, out, known bool) {home, _ := homes()a := codex(home)if _, err := os.ReadFile(a.Path); err != nil && !errors.Is(err, fs.ErrNotExist) {- return false, false+ return "", false, false}- return a.AppOut != nil && a.AppOut(), true+ out = a.AppOut != nil && a.AppOut()+ var b strings.Builder+ for _, k := range []string{"model_provider", "openai_base_url", "model_catalog_json"} {+ v, _ := edit.GetTOMLTop(a.Path, k)+ b.WriteString(k + "=" + v + "\n")+ }+ t, _ := edit.GetTOMLTable(a.Path, "model_providers."+magpieID)+ b.WriteString("magpie.base_url=" + t["base_url"] + "\n")+ if out {+ b.WriteString("out\n")+ }+ return b.String(), out, true}// others are clients that reach the gateway without being agents magpiediff --git a/internal/agent/codex_app_route_test.go b/internal/agent/codex_app_route_test.gonew file mode 100644index 000000000..2b219ff20--- /dev/null+++ b/internal/agent/codex_app_route_test.go@@ -0,0 +1,49 @@+package agent++import (+ "path/filepath"+ "testing"++ "github.com/yetone/magpie/internal/edit"+)++// The route the Codex app's app-server is restarted on (codex_app_server.go)+// changes when Codex is connected beside its ChatGPT sign-in and when it is+// disconnected (JiangLiuer222 on X: the app kept sending to 127.0.0.1:3425+// after Disconnect), and not when the Codex app writes a model pick of its+// own, which would restart it on every pick.+func TestCodexAppRouteFollowsConnectAndDisconnect(t *testing.T) {+ home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"gpt-5.5\"\n")+ cx := codex(home)+ route := func() string {+ t.Helper()+ r, _, known := codexAppRoute()+ if !known {+ t.Fatal("route not known")+ }+ return r+ }+ before := route()+ if _, err := cx.ConnectHow(); err != nil {+ t.Fatal(err)+ }+ connected := route()+ if connected == before {+ t.Fatalf("connect left the route as it was:\n%s", read())+ }+ // the Codex app writes its own pick: no restart for that+ if err := edit.SetTOMLTop(filepath.Join(home, ".codex", "config.toml"), edit.KV{Path: "model", Value: "gpt-6.1-sol"}); err != nil {+ t.Fatal(err)+ }+ if route() != connected {+ t.Fatalf("a model pick changed the route:\n%s", read())+ }+ if err := cx.Disconnect(); err != nil {+ t.Fatal(err)+ }+ // the [model_providers.magpie] table stays, for the threads started+ // on it; openai_base_url goes+ if r := route(); r == connected {+ t.Fatalf("disconnect left the route as it was: %q\n%s", r, read())+ }+}diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.goindex 59cdb07e3..631cf87a9 100644--- a/internal/provider/codex_app_server.go+++ b/internal/provider/codex_app_server.go@@ -31,13 +31,23 @@ import (// system the app runs on, with nothing for the user to do, once no Codex// turn is running: none through magpie, none open in Codex's sessions.//+// The same holds for every change magpie makes to where Codex sends its+// requests: a Disconnect that takes openai_base_url out, a Connect that+// puts it in, failover, the gateway moved to another port. The app-server+// read config.toml as it started, and a Codex app left running kept+// sending to 127.0.0.1:3425 after Codex was disconnected (JiangLiuer222 on+// X), so each such change restarts it the same way.+//// The app-server is ended as a clean exit (proc.End): the app reads any// other exit as a crash and shows it.-// CodexAppOnMagpie is set by the agent package: whether magpie is Codex's-// provider for its used-up ChatGPT account (AppOut), known false when-// Codex's config can't be read.-var CodexAppOnMagpie func() (on, known bool)+// CodexAppRoute is set by the agent package: what in Codex's config the+// app-server reads as it starts and magpie writes (its provider, base URL+// and model list: route, compared, never parsed), and whether magpie is+// Codex's provider for its used-up ChatGPT account (out, AppOut); known+// false when Codex's config can't be read. Nothing the Codex app writes+// itself (its model pick) is in route, or a pick would restart it.+var CodexAppRoute func() (route string, out, known bool)// codexAppEvery is how often KeepCodexAppOnItsProvider looks; codexAppIdle// how long after Codex's last request through magpie a turn counts ended@@ -128,7 +138,8 @@ func sameDir(a, b string) bool {// codexApp is what KeepCodexAppOnItsProvider knows.var codexApp struct {sync.Mutex- seen, on bool+ seen bool+ route string// stale: the app-servers started before Codex's provider last changed,// each with how often it was endedstale map[int]int@@ -161,25 +172,28 @@ func KeepCodexAppOnItsProvider(ctx context.Context, busy func() (int, time.Time)}}-// codexAppStep notes the app-servers running as magpie becomes Codex's-// provider for the used-up account, or stops being it, and ends each of-// them once no Codex turn is running. Started with magpie on, the app may+// codexAppStep notes the app-servers running as Codex's route changes+// (magpie becomes Codex's provider for the used-up account, or stops being+// it; Codex is connected or disconnected), and ends each of them once no+// Codex turn is running. Started with magpie on, the app may// have opened before: its app-servers are ended too. It says which pids it// ended.func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Time)) []int {- if CodexAppOnMagpie == nil {+ if CodexAppRoute == nil {return nil}- on, known := CodexAppOnMagpie()+ route, out, known := CodexAppRoute()if !known {return nil}home := codexHome()c := &codexAppc.Lock()- changed := !c.seen && on || c.seen && c.on != on+ // at the first look only a used-up account's app-servers are ended:+ // what the others read before magpie started isn't known+ changed := !c.seen && out || c.seen && c.route != routeif !changed {- c.seen, c.on = true, on+ c.seen, c.route = true, route}c.Unlock()if changed {@@ -192,7 +206,7 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Timreturn nil}c.Lock()- c.seen, c.on = true, on+ c.seen, c.route = true, routec.stale, c.stuck = map[int]int{}, falsefor _, p := range pids {c.stale[p] = 0diff --git a/internal/provider/codex_app_server_test.go b/internal/provider/codex_app_server_test.goindex 249ad8781..d6c89ae38 100644--- a/internal/provider/codex_app_server_test.go+++ b/internal/provider/codex_app_server_test.go@@ -17,11 +17,13 @@ import (// and their ends, for codexAppStep.type codexAppStub struct {on, known bool- running []int- listErr error- endErr error- turnOpen bool- ended []int+ // route: where Codex's config sends it, beside on+ route string+ running []int+ listErr error+ endErr error+ turnOpen bool+ ended []int// next: the app-server the app starts after one is endednext int}@@ -29,17 +31,23 @@ type codexAppStub struct {func stubCodexApp(t *testing.T) *codexAppStub {t.Helper()s := &codexAppStub{known: true, next: 100}- oldOn, oldList, oldEnd, oldTurn := CodexAppOnMagpie, codexAppServersOn, endCodexAppServer, codexTurnRunning+ oldOn, oldList, oldEnd, oldTurn := CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunningt.Cleanup(func() {- CodexAppOnMagpie, codexAppServersOn, endCodexAppServer, codexTurnRunning = oldOn, oldList, oldEnd, oldTurn+ CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunning = oldOn, oldList, oldEnd, oldTurncodexApp.Lock()- codexApp.seen, codexApp.on, codexApp.stale, codexApp.stuck = false, false, nil, false+ codexApp.seen, codexApp.route, codexApp.stale, codexApp.stuck = false, "", nil, falsecodexApp.Unlock()})codexApp.Lock()- codexApp.seen, codexApp.on, codexApp.stale, codexApp.stuck = false, false, nil, false+ codexApp.seen, codexApp.route, codexApp.stale, codexApp.stuck = false, "", nil, falsecodexApp.Unlock()- CodexAppOnMagpie = func() (bool, bool) { return s.on, s.known }+ CodexAppRoute = func() (string, bool, bool) {+ r := s.route+ if s.on {+ r += "|out"+ }+ return r, s.on, s.known+ }codexAppServersOn = func(context.Context, string) ([]int, error) {if s.listErr != nil {return nil, s.listErr@@ -107,6 +115,45 @@ func TestCodexAppServerRestartedEachWay(t *testing.T) {}}+// Disconnecting Codex takes openai_base_url out of its config, and a+// Codex app left running kept sending to 127.0.0.1:3425 (JiangLiuer222 on+// X): its app-server read the config as it started. Each change to where+// Codex's config sends it (a disconnect, a connect) restarts the app's+// app-server once no Codex turn runs, as the used-up takeover does; a+// look with nothing changed ends nothing.+func TestCodexAppServerRestartedOnDisconnect(t *testing.T) {+ signIn(t)+ s := stubCodexApp(t)+ now := time.Now()+ idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }+ step := func() []int { return codexAppStep(context.Background(), now, idle) }++ s.running = []int{60}+ s.route = "openai_base_url=http://127.0.0.1:3425/backend-api/codex"+ if got := step(); got != nil {+ t.Fatalf("first look, connected: ended %v", got)+ }+ if got := step(); got != nil {+ t.Fatalf("nothing changed: ended %v", got)+ }+ s.route = "openai_base_url=" // disconnected+ s.turnOpen = true+ if got := step(); got != nil {+ t.Fatalf("a turn open in Codex's sessions: ended %v", got)+ }+ s.turnOpen = false+ if got := step(); !slices.Equal(got, []int{60}) {+ t.Fatalf("disconnected, idle: ended %v, want [60]", got)+ }+ if got := step(); got != nil {+ t.Fatalf("the new app-server read the config as it started: ended %v", got)+ }+ s.route = "openai_base_url=http://127.0.0.1:3425/backend-api/codex" // connected again+ if got := step(); !slices.Equal(got, []int{100}) {+ t.Fatalf("connected again: ended %v, want [100]", got)+ }+}+// A magpie started while it is Codex's provider for a used-up account// restarts the app-servers it finds: they may have started before.// Started with Codex on its account, it leaves them be.