Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

codex: a thread open when magpie quits goes on through a relay, not a 503

yetone4534561f6bb8
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md
index 650112675..3da5d1e7b 100644
--- a/docs/subsystems/agent-wiring.md
+++ b/docs/subsystems/agent-wiring.md
@@ -121,7 +121,7 @@ something else shows up as drift.
- Listing never starts a stopped WSL distro. A stopped distro's agent shows what was last seen there (`asleep`, `wsl.json`); setting one of its fields writes its files, which starts the distro.
- Codex's sign-in (`login`) is ChatGPT (`""`, the default), Always ChatGPT (`chatgpt`) or magpie API (`api`). With ChatGPT, magpie's models join Codex's own beside the sign-in (`openai_base_url`), and while the Codex app holds the ChatGPT account Codex is signed in to (`codexUsedUp`, `provider.CodexUsedUp`: OpenAI no longer allows the account and it has no credits left, a workspace still within its overage excepted), magpie is made Codex's provider (`codex.out`): the Codex app sends nothing at all on an account it holds, a magpie model's turn included (#540), and as a provider of its own magpie is past that. A window at 100% with credits left doesn't count, and Codex stays signed in. Sync puts it back beside the sign-in once the account has room. Always ChatGPT never does that: Codex stays in its ChatGPT state, and the Codex app may send nothing till the account has room, while Codex CLI's turns still reach magpie by the base URL, and its routing and other accounts serve them. Codex's app-server answers `account/read` and `getAuthStatus` with no account and no token for a provider without `requires_openai_auth`, and the Codex app then switches to an identity of no account: its ChatGPT mode's chats and projects ("Work") are gone, with its Chrome control (#1824) and cloud tasks, while magpie's models still answer (Qyburn3 on X). So `[model_providers.magpie]` says `requires_openai_auth = true` while Codex has a ChatGPT sign-in with room (`openaiAuth`: `codexChatGPTKnown` and not `codexUsedUp`), magpie API included; Codex still sends magpie's key (`experimental_bearer_token`) and no ChatGPT-Account-ID, with the same tools (tried with ChatGPT.app 26.1021 and its codex 0.164.0-alpha.11 against a capturing server). Not for an API key alone (Codex drops its image tool for a provider requiring OpenAI auth, `uses_openai_actor_authorization`), no sign-in (the app would ask for one), or a sign-in the Codex app holds: the app would read its rate limit again and grey Send for magpie's models too, which `codex.out` exists to get past. Sync writes the key in or takes it out as the sign-in or the allowance changes, an older magpie's table included (`authStale`), and the key is part of the app-server's route (`codexAppRoute`), so the Codex app is restarted onto its account (`TestCodexMagpieProviderKeepsChatGPTAccount`, `TestCodexAppRouteFollowsOpenAIAuth`). While magpie is Codex's provider for `codex.out` the app has no account till the reset, so the Agents row opened over that takeover names browser use among what is off and offers Keep on ChatGPT right there (`keepChatGPT`, posting `login` = `chatgpt`); picked on one of Codex's own models taken over (`codex/<model>`), `set` puts Codex back on its sign-in at once, `model_provider` and `model_catalog_json` gone, where it had left magpie the provider (eddie.zhan on Discord, `TestCodexOwnModelOutThenKeptOnChatGPT`). While magpie is Codex's provider (magpie API, or `codex.out`), `Joined` reports false although the `codex.joined` mark stays for Sync's way back: the Agents row said Codex's own models stay in `/model` beside magpie's, the ChatGPT state the Codex app blocks sending in, and the app only leaves that state once it is restarted (#2267, `TestCodexProviderIsNotJoined`). A Codex that reaches the gateway from another machine (a WSL distro under NAT, or `MAGPIE_ADDR` pinned beyond loopback, `onAnotherMachine(at.gw())`) is wired as one with no ChatGPT sign-in (`chatGPT()` is false there): never joined or beside, since beside its sign-in it would send its ChatGPT token to `/backend-api/codex`, and from there the gateway takes a named key alone, so every request was a 401 (#2145, `TestCodexBeyondLoopbackNotJoined`). magpie is its provider and it sends `gwKey()`, the LAN sharing key; one of its own models picked goes straight to OpenAI on its sign-in.
- Whether Codex is signed in to ChatGPT is read from its auth.json or keychain item (`codexChatGPTKnown`, `provider.CodexSignInKnown`). Codex rewrites auth.json in place when it refreshes its tokens (codex-rs `FileAuthStorage::save` opens it with truncate), so a read in that moment finds it empty or cut off, and a keychain read can fail for a moment. Such a read is unknown, and Codex is taken to be as magpie last wired it (joined, beside, or `codex.out`); only a sign-in that isn't there (no auth.json, no item) or holds no ChatGPT token is "not signed in". Taking an unknown read for "not signed in" made Sync or a pick move Codex from beside its sign-in to magpie as its provider, with no `codex.out` to bring it back, and the Codex app showed "magpie" for its account and magpie's catalog for its models, on and off (lucy on Discord, v0.1.1394; `TestCodexHalfWrittenAuthKeepsSignIn`, `TestCodexHalfWrittenAuthKeepsOut`, `TestCodexSignInKnown`).
-- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next — never for a Codex that reaches the gateway from another machine, where that path takes a named key alone and the failed-over turn came back a 401 (#2145, `TestCodexFailoverBeyondLoopbackNotWritten`); Sync takes one it wrote before off again. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). Every restart magpie makes runs `codex app-server daemon restart` as its own responsible process on macOS (`proc.CombinedOutputOwn`, a disclaimed `posix_spawn`): the daemon works in the folder of each codex attached to it, and as magpie's child the first codex in ~/Desktop had macOS ask for the Desktop folder in magpie's name (reformed9448 on Discord; `TestRestartedCodexDaemonIsNotMagpies`). A magpie built without cgo (the CLI) still restarts it as its own child. A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place.
+- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next — never for a Codex that reaches the gateway from another machine, where that path takes a named key alone and the failed-over turn came back a 401 (#2145, `TestCodexFailoverBeyondLoopbackNotWritten`); Sync takes one it wrote before off again. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). So does every thread already open, in the Codex app above all: each turn went to the closed port, and a system proxy in between answered `503 Service Unavailable: Unknown error, url: http://127.0.0.1:3425/backend-api/codex/responses` until magpie was opened again (idkatbro on X; without a proxy Codex says "Connection refused" and reconnects). Masking plays no part: it runs only in the gateway, and its own 503 says why. When `EndCodexFailover` took failover out, the gateway's address is this computer's and Codex runs (`provider.CodexPIDs`: the app's app-server, the daemon, the CLI's sessions, an editor's codex), `OnShutdown` starts `magpie codex-relay` apart from itself (`agent.RelayOpenCodex`, `codexrelay.Start`; Setsid, or a detached process on Windows). It waits up to 60 s for the gateway to let go of the port, then serves only `/backend-api/codex/*` from Codex on this computer (a loopback Host, no Origin) and passes each request to the ChatGPT backend as the gateway passes a turn of Codex's own: the same item-id, compaction and Claude-seal rewrites, zstd and proxy, signed by the caller's own Authorization (`gateway.CodexRelay`). A magpie model, a turn on one of magpie's accounts, and a turn masking would have masked are refused with a readable 400 instead (Codex retries a 5xx five times over and shows a 4xx at once); anything else says magpie isn't running, never as magpie (`ServedBy`). It ends once every Codex process it was left for has and nothing is in flight, and the next magpie to serve the gateway asks it to leave (`codexrelay.Leave` in `ListenAndServe` and `serveGatewayLocked`; a POST with the token from `codex-relay.json`, 0600 in magpie's folder): it closes its listener at once and finishes the turns it streams, up to 30 minutes. `TestCodexRelay*`, `TestLeaveFreesPortAndFinishesStream`, `TestEndsWhenCodexGone`, `TestLeaveNeedsToken`. Not covered: a connected Codex (magpie's models, left pointed at magpie by design), a Codex in a WSL distro, and a magpie that ends without quitting. Every restart magpie makes runs `codex app-server daemon restart` as its own responsible process on macOS (`proc.CombinedOutputOwn`, a disclaimed `posix_spawn`): the daemon works in the folder of each codex attached to it, and as magpie's child the first codex in ~/Desktop had macOS ask for the Desktop folder in magpie's name (reformed9448 on Discord; `TestRestartedCodexDaemonIsNotMagpies`). A magpie built without cgo (the CLI) still restarts it as its own child. A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place.
- A Codex thread keeps the provider it was started on. While a magpie model is on, CC Switch's provider tables go through magpie too (`takeTables`), and get their own base URL back when Codex steps off magpie (`giveTables`, stash `codex.tables`). CC Switch's OpenAI mirror (a table of another id, `name = "OpenAI"`, `requires_openai_auth`, no `base_url`) isn't reached by `openai_base_url`, which takes only the built-in provider to magpie: a thread started on it and reopened went straight to ChatGPT, which refused the magpie model picked in it, and magpie never saw the request (#1796). While Codex goes to magpie by the base URL, `takeMirrors` gives each such mirror magpie's ChatGPT backend as its `base_url` (stash `codex.mirrors`), and `giveMirrors` takes it off again; a mirror a profile names, or one whose `base_url` was changed since, stays as it is. Moving the threads onto another provider is the Sessions page's Move (#887).
- An agent's config is written in the form the installed version reads, taken from what that version declares, not the latest one. VSCodium has no Copilot Chat of its own, and the Marketplace's last one (0.48.1) has no Custom Endpoint provider, only OpenAI Compatible (`customoai`, #1014). magpie reads the provider list in the package.json of the `github.copilot-chat` installed under `~/.vscode-oss/extensions` (`vscodeChatOf`). It writes its group for `customendpoint` when that is declared, for `customoai` when only that is, with each model's window as `maxInputTokens` + `maxOutputTokens` and the token as `x-api-key` (that version drops an Authorization in `requestHeaders`). A missing or unreadable extension keeps `customendpoint`. Sync rewrites a group written for the other provider, and Check reports it, as it does a Copilot Chat declaring neither. That Copilot Chat registers its providers only while signed in to GitHub with a personal Copilot plan, which the Notice says.
- Tuned settings are written only on the user's click, never by Sync or Connect. A window that is Long conversations (`TuneLong`) is stashed once as Long conversations was (`tune.long.compact`, one stash for both agents, as the value is one), and Undo puts it back, Full window included, unless the user changed it since. Codex's card is always Long conversations, unless config.toml has a `model_auto_compact_token_limit` of the user's, which Codex stops at first: that one is `locked`. A limit an older magpie's tune wrote there (`tune.codex.compact`) is moved by `tuneMigrateCodex`, from Codex's Sync and from the card: Long conversations at magpie's default, or under Full window, takes it as the user's own choice; one the user typed takes it only when it is lower, where Codex compacted; the file gets back what it had; and a limit the user changed after the click is theirs and stays. Claude Code's `CLAUDE_CODE_AUTO_COMPACT_WINDOW` is Long conversations when magpie wrote it from that value (`claude.compact_long` beside `claude.compact_window`, set by `writeCompact`), and its top-level `autoCompactWindow` when magpie wrote it (`claude.compact_default`) and it equals Long conversations; a window from a provider's Compact at, or the user's own, stays `locked`. A Claude model's own `modelSettings` window, under no such variable, is still per model, since Long conversations doesn't reach Claude models. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Codex's window is the one magpie's catalog lists for each model it ran (typed, or the vendor's), and with none in config.toml it runs now at what magpie tells Codex (`provider.CompactFor`, else Long conversations in the agent's opened row, as `codexcat` writes it); a model of magpie's whose window isn't known caps nothing short of 1M (or the user's own larger value), never the largest prompt seen (zhemu on Discord: a 1M model at 750K was offered up to 410K), and only Codex's own models, outside the catalog, keep 272K or the largest prompt (`codexWindow`, `TestTuneWindowsAreTheUsers`). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest; with the compactions timed, it never advises a window that compacts more often than the one now, so never a longer wait: of the windows that compact no more often it takes the cheapest, and of those within 3% of that (`sameCost`, the same bar as changing at all) the one that compacts least, the larger of two that compact as often. Tokens and seconds share no unit the files measure, so the advice doesn't trade one for the other at a guessed rate; a cheaper window that waits longer is said with its wait in the row and the picker, for the user to choose. The wait per compaction is taken as the same at every window: the files time compactions only near the window the user ran with, too narrow to fit how it grows with the prompt. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.
diff --git a/internal/agent/codex.go b/internal/agent/codex.go
index f2f0ea5f8..58e4965f8 100644
--- a/internal/agent/codex.go
+++ b/internal/agent/codex.go
@@ -2,11 +2,13 @@ package agent
import (
"cmp"
+ "context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
+ "net"
"net/url"
"os"
"path/filepath"
@@ -24,6 +26,7 @@ import (
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/codexcat"
+ "github.com/yetone/magpie/internal/codexrelay"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/lastgood"
@@ -2304,23 +2307,52 @@ func codexFailover() bool {
// The app-server codex sessions share read the old base URL as it started
// and keeps it, and KeepCodexDaemonCurrent ends with magpie, so it is
// restarted here, when no session is on it (thisisvainxx on X: back on
-// its own config, Codex took "several restarts").
-func EndCodexFailover() error {
+// its own config, Codex took "several restarts"). ended says it took
+// failover out: a thread open in the Codex app still sends to the
+// gateway's address, which the caller leaves a relay at (codexrelay).
+func EndCodexFailover() (ended bool, err error) {
home, err := os.UserHomeDir()
if err != nil {
- return err
+ return false, err
}
a := codex(home)
if !a.FailingOver() {
- return nil
+ return false, nil
}
if err := a.EndFailover(); err != nil {
- return err
+ return false, err
}
codexDaemonCheck(a.Path)
- return nil
+ return true, nil
}
+// RelayOpenCodex leaves a relay at the gateway's address for the Codex
+// processes running as magpie quits (codexrelay.Start), when the address
+// is this computer's own and Codex is running at all.
+func RelayOpenCodex() error {
+ u, err := url.Parse(gateway.URL())
+ if err != nil {
+ return err
+ }
+ if ip := net.ParseIP(u.Hostname()); !strings.EqualFold(u.Hostname(), "localhost") && (ip == nil || !ip.IsLoopback()) {
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ pids := codexPIDs(ctx)
+ if len(pids) == 0 {
+ return nil
+ }
+ return startRelay(u.Host, pids)
+}
+
+// startRelay and codexPIDs are vars so tests start no relay and list
+// Codex processes of their own.
+var (
+ startRelay = codexrelay.Start
+ codexPIDs = provider.CodexPIDs
+)
+
// CodexDesktopList is the list a Codex beside its ChatGPT sign-in is
// handed, as the file the Codex app reads it from (deskList); ok false
// while it isn't known. Set to gateway.CodexDesktopCatalog; nil writes
diff --git a/internal/agent/codex_proxy_test.go b/internal/agent/codex_proxy_test.go
index f55ffb6ad..9cc02dc3a 100644
--- a/internal/agent/codex_proxy_test.go
+++ b/internal/agent/codex_proxy_test.go
@@ -409,8 +409,8 @@ func TestCodexFailoverEndsWithMagpie(t *testing.T) {
asked = append(asked, h)
return provider.CodexDaemonCheck{}
}
- if err := EndCodexFailover(); err != nil {
- t.Fatal(err)
+ if ended, err := EndCodexFailover(); err != nil || !ended {
+ t.Fatalf("failover not said ended (%v): the open threads get no relay", err)
}
if cfg := read(); strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) {
t.Fatalf("magpie quit, Codex still pointed at it:\n%s", cfg)
@@ -436,8 +436,8 @@ func TestCodexFailoverEndsWithMagpie(t *testing.T) {
if err := edit.SetTOMLTop(cx.Path, edit.KV{Path: "openai_base_url", Value: base}); err != nil {
t.Fatal(err)
}
- if err := EndCodexFailover(); err != nil {
- t.Fatal(err)
+ if ended, err := EndCodexFailover(); err != nil || ended {
+ t.Fatalf("the user's own base URL said ended (%v): a relay would take the port for nothing", err)
}
if cfg := read(); !strings.Contains(cfg, `openai_base_url = "`+base+`"`) {
t.Fatalf("the user's base URL was taken:\n%s", cfg)
@@ -495,10 +495,52 @@ func TestCodexMirrorFailoverHeldAndEndsWithMagpie(t *testing.T) {
if cfg := sync(); !strings.Contains(cfg, `base_url = "`+gateway.URL()) {
t.Fatalf("not written once the proxy passes it on:\n%s", cfg)
}
- if err := EndCodexFailover(); err != nil {
+ if _, err := EndCodexFailover(); err != nil {
t.Fatal(err)
}
if cfg := read(); strings.Contains(cfg, "base_url") || !strings.Contains(cfg, `model_provider = "custom"`) || !strings.Contains(cfg, "supports_websockets = true") {
t.Fatalf("magpie quit, CC Switch's mirror still pointed at it:\n%s", cfg)
}
}
+
+// At quit, a relay is left at the gateway's own address for the Codex
+// processes running then (idkatbro on X: an open thread got 503 until
+// magpie was opened again); none when no Codex runs, and none for a
+// gateway on another computer's address, which a relay here can't take.
+func TestRelayOpenCodexLeftForRunningCodex(t *testing.T) {
+ wasStart, wasPIDs := startRelay, codexPIDs
+ t.Cleanup(func() { startRelay, codexPIDs = wasStart, wasPIDs })
+ type call struct {
+ addr string
+ pids []int
+ }
+ var started []call
+ startRelay = func(addr string, pids []int) error {
+ started = append(started, call{addr, pids})
+ return nil
+ }
+ running := []int{41, 42}
+ codexPIDs = func(context.Context) []int { return running }
+
+ t.Setenv("MAGPIE_ADDR", "127.0.0.1:3499")
+ if err := RelayOpenCodex(); err != nil {
+ t.Fatal(err)
+ }
+ if len(started) != 1 || started[0].addr != "127.0.0.1:3499" || len(started[0].pids) != 2 {
+ t.Fatalf("no relay for the open Codex: %+v", started)
+ }
+ // a gateway on every interface is reached on loopback, and relayed
+ t.Setenv("MAGPIE_ADDR", "0.0.0.0:3498")
+ if err := RelayOpenCodex(); err != nil || len(started) != 2 || started[1].addr != "127.0.0.1:3498" {
+ t.Fatalf("%v %+v", err, started)
+ }
+ running = nil
+ if err := RelayOpenCodex(); err != nil || len(started) != 2 {
+ t.Fatalf("a relay with no Codex running: %v %+v", err, started)
+ }
+ running = []int{41}
+ t.Setenv("MAGPIE_ADDR", "192.0.2.7:3425")
+ if err := RelayOpenCodex(); err != nil || len(started) != 2 {
+ t.Fatalf("a relay for another computer's address: %v %+v", err, started)
+ }
+}
diff --git a/internal/cli/main.go b/internal/cli/main.go
index a8ed5294a..07943348d 100644
--- a/internal/cli/main.go
+++ b/internal/cli/main.go
@@ -17,6 +17,7 @@ import (
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/claudebridge"
+ "github.com/yetone/magpie/internal/codexrelay"
"github.com/yetone/magpie/internal/davsync"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/imagemcp"
@@ -323,6 +324,8 @@ func run(args []string) error {
return toolsCmd(args[1:])
case "tool":
return toolCmd(args[1:])
+ case codexrelay.Command: // internal: what a quitting magpie leaves for Codex's open threads
+ return codexrelay.Main(args[1:], gateway.CodexRelay())
}
}
startUp()
diff --git a/internal/codexrelay/proc_unix.go b/internal/codexrelay/proc_unix.go
new file mode 100644
index 000000000..a456f97a9
--- /dev/null
+++ b/internal/codexrelay/proc_unix.go
@@ -0,0 +1,23 @@
+//go:build !windows
+
+package codexrelay
+
+import (
+ "os/exec"
+ "syscall"
+)
+
+// alive reports whether pid is still running.
+func alive(pid int) bool {
+ err := syscall.Kill(pid, 0)
+ return err == nil || err == syscall.EPERM
+}
+
+// detach keeps the relay out of magpie's process group, so it outlives
+// magpie.
+func detach(cmd *exec.Cmd) {
+ if cmd.SysProcAttr == nil {
+ cmd.SysProcAttr = &syscall.SysProcAttr{}
+ }
+ cmd.SysProcAttr.Setsid = true
+}
diff --git a/internal/codexrelay/proc_windows.go b/internal/codexrelay/proc_windows.go
new file mode 100644
index 000000000..d7b921a8f
--- /dev/null
+++ b/internal/codexrelay/proc_windows.go
@@ -0,0 +1,32 @@
+package codexrelay
+
+import (
+ "os/exec"
+ "syscall"
+)
+
+const (
+ synchronize = 0x00100000
+ waitTimeout = 0x00000102
+ detachedProc = 0x00000008
+ newProcGroup = 0x00000200
+)
+
+// alive reports whether pid is still running.
+func alive(pid int) bool {
+ h, err := syscall.OpenProcess(synchronize, false, uint32(pid))
+ if err != nil {
+ return false
+ }
+ defer syscall.CloseHandle(h)
+ ev, _ := syscall.WaitForSingleObject(h, 0)
+ return ev == waitTimeout
+}
+
+// detach starts the relay outside magpie's console, so it outlives it.
+func detach(cmd *exec.Cmd) {
+ if cmd.SysProcAttr == nil {
+ cmd.SysProcAttr = &syscall.SysProcAttr{}
+ }
+ cmd.SysProcAttr.CreationFlags |= detachedProc | newProcGroup
+}
diff --git a/internal/codexrelay/relay.go b/internal/codexrelay/relay.go
new file mode 100644
index 000000000..f64888198
--- /dev/null
+++ b/internal/codexrelay/relay.go
@@ -0,0 +1,303 @@
+// Package codexrelay keeps the Codex threads open when magpie quits
+// working until magpie is opened again or they end.
+//
+// Codex signed in to ChatGPT sends its turns to magpie's gateway while
+// magpie fails it over (agent.EndCodexFailover). At quit magpie takes that
+// base URL out of Codex's config, but a thread already open, in the Codex
+// app above all, keeps the URL it started with, and every turn after went
+// to a closed port: "503 Service Unavailable: Unknown error" through a
+// system proxy, "Connection refused" without one, until magpie was opened
+// again (idkatbro on X). So at quit, with Codex running, magpie starts a
+// small process of its own (`magpie codex-relay`) that takes the port up
+// once the gateway lets go of it and passes those turns on to the ChatGPT
+// backend on Codex's own sign-in (gateway.CodexRelay). It ends once every
+// Codex process it was started for has, and leaves when the next magpie
+// starts (Leave), finishing the turns it is streaming first: no running
+// turn is cut.
+package codexrelay
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/subtle"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "os"
+ "os/signal"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "syscall"
+ "time"
+
+ "github.com/yetone/magpie/internal/proc"
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// Command is the magpie command a relay runs as.
+const Command = "codex-relay"
+
+// LeavePath is where the next magpie tells the relay to leave; with
+// TokenHeader holding the token the relay wrote in its state file.
+const (
+ LeavePath = "/.magpie-codex-relay/leave"
+ TokenHeader = "X-Magpie-Relay-Token"
+)
+
+// Timings, vars for tests.
+var (
+ // bindFor is how long the relay waits for the gateway's port: the
+ // quitting magpie holds it until its own requests have finished.
+ bindFor = 60 * time.Second
+ // watchEvery is how often the relay looks for its Codex processes.
+ watchEvery = 15 * time.Second
+ // drainFor caps how long a leaving relay finishes its streams.
+ drainFor = 30 * time.Minute
+ // leaveWait is how long Leave waits for the relay to answer.
+ leaveWait = 2 * time.Second
+)
+
+// state is what a running relay says of itself, for Leave.
+type state struct {
+ Pid int `json:"pid"`
+ Addr string `json:"addr"`
+ Token string `json:"token"`
+}
+
+func statePath() string { return filepath.Join(settings.Dir(), "codex-relay.json") }
+
+// Start runs a relay at addr for the Codex processes pids, apart from
+// this process so it outlives it.
+func Start(addr string, pids []int) error {
+ exe, err := os.Executable()
+ if err != nil {
+ return err
+ }
+ ids := make([]string, len(pids))
+ for i, p := range pids {
+ ids[i] = strconv.Itoa(p)
+ }
+ cmd := proc.Command(exe, Command, "--addr", addr, "--pids", strings.Join(ids, ","))
+ detach(cmd)
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ return cmd.Process.Release()
+}
+
+// Main is `magpie codex-relay --addr host:port --pids 1,2`, serving h.
+func Main(args []string, h http.Handler) error {
+ var addr string
+ var pids []int
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "--addr":
+ if i+1 < len(args) {
+ addr = args[i+1]
+ i++
+ }
+ case "--pids":
+ if i+1 < len(args) {
+ for _, s := range strings.Split(args[i+1], ",") {
+ if s == "" {
+ continue
+ }
+ n, err := strconv.Atoi(s)
+ if err != nil || n <= 0 {
+ return fmt.Errorf("codex-relay: bad pid %q", s)
+ }
+ pids = append(pids, n)
+ }
+ i++
+ }
+ default:
+ return fmt.Errorf("codex-relay: unknown argument %q (magpie starts this itself when it quits)", args[i])
+ }
+ }
+ if addr == "" || len(pids) == 0 {
+ return errors.New("usage: magpie codex-relay --addr host:port --pids pid,… (magpie starts this itself when it quits)")
+ }
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
+ ctx, stop := context.WithCancel(context.Background())
+ go func() { <-sig; stop() }()
+ return Run(ctx, addr, pids, h)
+}
+
+// Run serves h at addr until ctx ends, the next magpie tells it to leave,
+// or none of pids runs and nothing is in flight; then it finishes the
+// requests it has, for up to drainFor.
+func Run(ctx context.Context, addr string, pids []int, h http.Handler) error {
+ ln, err := bind(ctx, addr)
+ if err != nil {
+ return err
+ }
+ b := make([]byte, 16)
+ if _, err := rand.Read(b); err != nil {
+ ln.Close()
+ return err
+ }
+ me := state{Pid: os.Getpid(), Addr: ln.Addr().String(), Token: hex.EncodeToString(b)}
+ if err := writeState(me); err != nil {
+ ln.Close()
+ return err
+ }
+ defer dropState(me.Token)
+
+ var inFlight atomic.Int64
+ left := make(chan struct{})
+ var leaving atomic.Bool
+ srv := &http.Server{ReadHeaderTimeout: 30 * time.Second}
+ srv.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == LeavePath {
+ tok := r.Header.Get(TokenHeader)
+ if r.Method != http.MethodPost || r.Header.Get("Origin") != "" || subtle.ConstantTimeCompare([]byte(tok), []byte(me.Token)) != 1 {
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return
+ }
+ // the port is free once this is answered: the next magpie
+ // binds it at once, while the streams here finish
+ srv.SetKeepAlivesEnabled(false)
+ ln.Close()
+ if leaving.CompareAndSwap(false, true) {
+ close(left)
+ }
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ inFlight.Add(1)
+ defer inFlight.Add(-1)
+ h.ServeHTTP(w, r)
+ })
+ go srv.Serve(ln)
+
+ t := time.NewTicker(watchEvery)
+ defer t.Stop()
+wait:
+ for {
+ select {
+ case <-ctx.Done():
+ break wait
+ case <-left:
+ break wait
+ case <-t.C:
+ if inFlight.Load() == 0 && !anyAlive(pids) {
+ break wait
+ }
+ }
+ }
+ drain, cancel := context.WithTimeout(context.Background(), drainFor)
+ defer cancel()
+ srv.Shutdown(drain)
+ return nil
+}
+
+// bind listens at addr, waiting up to bindFor for it to be let go of.
+func bind(ctx context.Context, addr string) (net.Listener, error) {
+ end := time.Now().Add(bindFor)
+ for {
+ ln, err := net.Listen("tcp", addr)
+ if err == nil {
+ return ln, nil
+ }
+ if time.Now().After(end) {
+ return nil, err
+ }
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(200 * time.Millisecond):
+ }
+ }
+}
+
+func anyAlive(pids []int) bool {
+ for _, p := range pids {
+ if alive(p) {
+ return true
+ }
+ }
+ return false
+}
+
+// writeState writes the relay's state where only this user reads it,
+// whole or not at all.
+func writeState(st state) error {
+ b, err := json.Marshal(st)
+ if err != nil {
+ return err
+ }
+ p := statePath()
+ if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
+ return err
+ }
+ tmp, err := os.CreateTemp(filepath.Dir(p), ".codex-relay-*")
+ if err != nil {
+ return err
+ }
+ defer os.Remove(tmp.Name())
+ if err := tmp.Chmod(0o600); err != nil && !errors.Is(err, errors.ErrUnsupported) {
+ tmp.Close()
+ return err
+ }
+ if _, err := tmp.Write(b); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Sync(); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ return err
+ }
+ return os.Rename(tmp.Name(), p)
+}
+
+func readState() (state, bool) {
+ b, err := os.ReadFile(statePath())
+ if err != nil {
+ return state{}, false
+ }
+ var st state
+ if json.Unmarshal(b, &st) != nil || st.Pid <= 0 || st.Addr == "" || st.Token == "" {
+ return state{}, false
+ }
+ return st, true
+}
+
+// dropState removes the state file when it is still this relay's.
+func dropState(token string) {
+ if st, ok := readState(); ok && st.Token == token {
+ os.Remove(statePath())
+ }
+}
+
+// Leave tells a relay serving at the gateway's port to let go of it,
+// for the magpie starting to serve there. It returns once the relay has
+// closed its listener (its streams go on finishing), or at once when
+// there is none.
+func Leave() {
+ st, ok := readState()
+ if !ok {
+ return
+ }
+ if !alive(st.Pid) {
+ os.Remove(statePath())
+ return
+ }
+ req, err := http.NewRequest(http.MethodPost, "http://"+st.Addr+LeavePath, nil)
+ if err != nil {
+ return
+ }
+ req.Header.Set(TokenHeader, st.Token)
+ c := &http.Client{Timeout: leaveWait, Transport: &http.Transport{Proxy: nil, DisableKeepAlives: true}}
+ if res, err := c.Do(req); err == nil {
+ res.Body.Close()
+ }
+}
diff --git a/internal/codexrelay/relay_test.go b/internal/codexrelay/relay_test.go
new file mode 100644
index 000000000..920dd96b2
--- /dev/null
+++ b/internal/codexrelay/relay_test.go
@@ -0,0 +1,208 @@
+package codexrelay
+
+import (
+ "context"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/proc"
+ "github.com/yetone/magpie/internal/settings"
+ "github.com/yetone/magpie/internal/testenv"
+)
+
+// The tests run in a home of their own, never the user's real files.
+func TestMain(m *testing.M) { testenv.Main(m) }
+
+// freeAddr is a loopback address nothing listens on, held until the
+// relay binds it: a port freed here could be handed to anything next.
+func freeAddr(t *testing.T) (string, net.Listener) {
+ t.Helper()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return ln.Addr().String(), ln
+}
+
+// sleeper is a process of the test's own for the relay to watch, ended
+// with the test.
+func sleeper(t *testing.T) int {
+ t.Helper()
+ cmd := proc.Command("sleep", "600")
+ if runtime.GOOS == "windows" {
+ cmd = proc.Command("powershell", "-NoProfile", "-Command", "Start-Sleep 600")
+ }
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() })
+ return cmd.Process.Pid
+}
+
+func fast(t *testing.T) {
+ t.Helper()
+ wb, ww, wl := bindFor, watchEvery, leaveWait
+ bindFor, watchEvery, leaveWait = 10*time.Second, 50*time.Millisecond, 5*time.Second
+ t.Cleanup(func() { bindFor, watchEvery, leaveWait = wb, ww, wl })
+}
+
+func waitFor(t *testing.T, what string, ok func() bool) {
+ t.Helper()
+ end := time.Now().Add(20 * time.Second)
+ for !ok() {
+ if time.Now().After(end) {
+ t.Fatalf("never: %s", what)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+// The next magpie starting tells the relay to leave, and binds the port
+// at once; the turn the relay is streaming then goes on to its end
+// rather than being cut, and the relay ends after it.
+func TestLeaveFreesPortAndFinishesStream(t *testing.T) {
+ fast(t)
+ addr, hold := freeAddr(t)
+ pid := sleeper(t)
+ release := make(chan struct{})
+ streaming := make(chan struct{})
+ h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "first ")
+ w.(http.Flusher).Flush()
+ close(streaming)
+ <-release
+ io.WriteString(w, "last")
+ })
+ done := make(chan error, 1)
+ go func() { done <- Run(context.Background(), addr, []int{pid}, h) }()
+ // the relay waits for the port the quitting magpie still holds
+ time.Sleep(300 * time.Millisecond)
+ hold.Close()
+ waitFor(t, "state written", func() bool { _, ok := readState(); return ok })
+
+ type reply struct {
+ body string
+ err error
+ }
+ got := make(chan reply, 1)
+ go func() {
+ res, err := http.Get("http://" + addr + "/backend-api/codex/responses")
+ if err != nil {
+ got <- reply{err: err}
+ return
+ }
+ b, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ got <- reply{string(b), err}
+ }()
+ <-streaming
+
+ Leave()
+ ln, err := net.Listen("tcp", addr)
+ if err != nil {
+ t.Fatalf("the port isn't free after Leave: %v", err)
+ }
+ ln.Close()
+ select {
+ case err := <-done:
+ t.Fatalf("relay ended with a turn still streaming: %v", err)
+ case <-time.After(200 * time.Millisecond):
+ }
+ close(release)
+ r := <-got
+ if r.err != nil || r.body != "first last" {
+ t.Fatalf("the streaming turn was cut: %q %v", r.body, r.err)
+ }
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("relay didn't end after its last turn")
+ }
+ if _, ok := readState(); ok {
+ t.Fatal("state left behind")
+ }
+}
+
+// With every Codex process it was left for gone, the relay ends of
+// itself and gives the port back.
+func TestEndsWhenCodexGone(t *testing.T) {
+ fast(t)
+ addr, hold := freeAddr(t)
+ hold.Close()
+ pid := sleeper(t)
+ done := make(chan error, 1)
+ go func() {
+ done <- Run(context.Background(), addr, []int{pid}, http.NotFoundHandler())
+ }()
+ waitFor(t, "state written", func() bool { _, ok := readState(); return ok })
+ select {
+ case <-done:
+ t.Fatal("ended while Codex runs")
+ case <-time.After(300 * time.Millisecond):
+ }
+ p, _ := os.FindProcess(pid)
+ p.Kill()
+ p.Wait()
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("relay outlived the Codex it was left for")
+ }
+ if _, ok := readState(); ok {
+ t.Fatal("state left behind")
+ }
+}
+
+// Leave asks only with the relay's token: a request without it, or from
+// a page, doesn't move the relay off the port. A relay that is gone
+// leaves no state for the next start to ask.
+func TestLeaveNeedsToken(t *testing.T) {
+ fast(t)
+ addr, hold := freeAddr(t)
+ hold.Close()
+ pid := sleeper(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- Run(ctx, addr, []int{pid}, http.NotFoundHandler()) }()
+ waitFor(t, "state written", func() bool { _, ok := readState(); return ok })
+ st, _ := readState()
+ for _, c := range []struct{ token, origin string }{{"", ""}, {"wrong", ""}, {st.Token, "null"}} {
+ req, _ := http.NewRequest("POST", "http://"+addr+LeavePath, nil)
+ if c.token != "" {
+ req.Header.Set(TokenHeader, c.token)
+ }
+ if c.origin != "" {
+ req.Header.Set("Origin", c.origin)
+ }
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode != 403 {
+ t.Fatalf("%+v: %d", c, res.StatusCode)
+ }
+ }
+ if _, err := net.Listen("tcp", addr); err == nil {
+ t.Fatal("the relay let go of the port without its token")
+ }
+ cancel()
+ <-done
+ // a state file whose relay is gone is removed, nothing asked
+ if err := writeState(state{Pid: 999999, Addr: addr, Token: "x"}); err != nil {
+ t.Fatal(err)
+ }
+ Leave()
+ if _, err := os.Stat(statePath()); !os.IsNotExist(err) {
+ t.Fatalf("dead relay's state kept: %v", err)
+ }
+ if !strings.HasPrefix(statePath(), settings.Dir()) {
+ t.Fatal("state outside magpie's folder")
+ }
+}
diff --git a/internal/gateway/codex_relay.go b/internal/gateway/codex_relay.go
new file mode 100644
index 000000000..5be46b259
--- /dev/null
+++ b/internal/gateway/codex_relay.go
@@ -0,0 +1,135 @@
+package gateway
+
+import (
+ "bytes"
+ "net/http"
+ "strings"
+
+ "github.com/yetone/magpie/internal/masking"
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// CodexRelay is what serves Codex's own ChatGPT sign-in at the gateway's
+// address once magpie has quit, for the Codex threads still open then
+// (codexrelay). magpie takes the failover base URL out of Codex's config
+// at quit (agent.EndCodexFailover), but a thread open in the Codex app,
+// and the app-server holding it, keep the URL they started with: every
+// turn after went to a port nobody listened on, and a system proxy in
+// between answered 503 "Unknown error" until magpie was opened again
+// (idkatbro on X). The relay passes those turns on to the ChatGPT backend
+// as the gateway does a turn on one of Codex's own models, signed by the
+// caller's own Authorization; it adds no credential of its own. What only
+// the running magpie could do is refused with a reason Codex shows: a
+// magpie model, a turn on one of magpie's accounts, masking (Settings ›
+// Privacy) that would have masked it. Its answer at "/" never says it is
+// magpie (ServedBy), so the next magpie starting asks it to leave.
+func CodexRelay() http.Handler {
+ client := &http.Client{Transport: upstreamTransport()}
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !loopbackHost(r.Host) || r.Header.Get("Origin") != "" {
+ // as the gateway's corsGuard: a rebound or foreign page, or
+ // a frame's null, never reaches the sign-in Codex sends
+ relayError(w, http.StatusForbidden, "magpie's Codex relay serves Codex on this computer only")
+ return
+ }
+ if !strings.HasPrefix(r.URL.Path, CodexPath+"/") {
+ relayError(w, http.StatusServiceUnavailable, relayGone)
+ return
+ }
+ if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
+ http.Error(w, "magpie speaks HTTP", http.StatusUpgradeRequired)
+ return
+ }
+ rest := strings.TrimPrefix(r.URL.Path, CodexPath)
+ body, status, err := readBoundedRequestBody(w, r, requestLimits{})
+ if err != nil {
+ relayError(w, status, err.Error())
+ return
+ }
+ if r.Method == http.MethodPost && (rest == "/responses" || rest == "/responses/compact") {
+ if msg := relayRefuses(r, body); msg != "" {
+ // 400, not 503: Codex retries a 5xx five times over for
+ // a refusal that a retry doesn't change (seen with codex
+ // 0.162.1), and shows a 4xx's message at once
+ relayError(w, http.StatusBadRequest, msg)
+ return
+ }
+ // as codexBackend sends a turn of Codex's own to its sign-in
+ body = plainItemIDs(boundCallIDs(callItemIDs(body)))
+ body, _ = codexInput(body, false)
+ }
+ body = withoutClaudeSeals(body)
+ base := provider.CodexBase
+ if apiKey(r.Header) && rest != "/models" {
+ base = codexAPIBase
+ }
+ if r.Method == http.MethodPost && rest == "/responses" && base == provider.CodexBase {
+ body = provider.DeclareSearch(body, strings.EqualFold(r.Header.Get("X-OpenAI-Internal-Codex-Responses-Lite"), "true"))
+ }
+ u := base + rest
+ if r.URL.RawQuery != "" {
+ u += "?" + r.URL.RawQuery
+ }
+ req, err := http.NewRequestWithContext(provider.ViaSignedIn(r.Context(), "codex"), r.Method, u, bytes.NewReader(body))
+ if err != nil {
+ relayError(w, http.StatusBadGateway, err.Error())
+ return
+ }
+ copyHeaders(req.Header, r.Header)
+ req.Header.Del("Accept-Encoding")
+ provider.CodexCompressed(req, body)
+ res, err := client.Do(req)
+ if err != nil {
+ relayError(w, http.StatusBadGateway, "OpenAI can't be reached ("+err.Error()+"). magpie isn't running, so this thread goes to OpenAI on Codex's own sign-in.")
+ return
+ }
+ defer res.Body.Close()
+ for k, vs := range res.Header {
+ if !hopHeader(k) {
+ w.Header()[k] = vs
+ }
+ }
+ w.WriteHeader(res.StatusCode)
+ flush := http.NewResponseController(w)
+ buf := make([]byte, 32<<10)
+ for {
+ n, err := res.Body.Read(buf)
+ if n > 0 {
+ if _, werr := w.Write(buf[:n]); werr != nil {
+ return
+ }
+ flush.Flush()
+ }
+ if err != nil {
+ return
+ }
+ }
+ })
+}
+
+// relayGone is the relay's answer to anything but Codex's own turns.
+const relayGone = "magpie isn't running: only Codex threads open when it quit are passed on, on Codex's own ChatGPT sign-in. Open magpie for everything else."
+
+// relayRefuses says why a turn can't be passed on with magpie gone, ""
+// when it can: what only the running gateway serves, and a turn masking
+// would have masked, which never goes unmasked.
+func relayRefuses(r *http.Request, body []byte) string {
+ model := modelOf(body)
+ if strings.Contains(model, "/") {
+ return model + " is one of magpie's models, and magpie isn't running. Open magpie to go on with this thread, or pick one of Codex's own models."
+ }
+ if r.Header.Get(AccountHeader) != "" {
+ return AccountHeader + " names one of magpie's Codex accounts, and magpie isn't running. Open magpie to go on with this thread."
+ }
+ if masking.Wanted(settings.Load()) {
+ return "magpie isn't running, and Settings › Privacy masks what is sent: this turn is not sent unmasked. Open magpie to go on with this thread."
+ }
+ return ""
+}
+
+// relayError answers as the ChatGPT backend words an error, so Codex
+// shows the message (an empty body reads "Unknown error").
+func relayError(w http.ResponseWriter, status int, msg string) {
+ writeError(w, provider.Responses, status, msg)
+}
diff --git a/internal/gateway/codex_relay_test.go b/internal/gateway/codex_relay_test.go
new file mode 100644
index 000000000..88a9bccea
--- /dev/null
+++ b/internal/gateway/codex_relay_test.go
@@ -0,0 +1,185 @@
+package gateway
+
+import (
+ "bytes"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// relayUp is a fake ChatGPT backend for the relay: what it was sent.
+type relayUp struct {
+ mu sync.Mutex
+ got []relayGot
+ srv *httptest.Server
+ code int
+}
+
+type relayGot struct {
+ path, auth, body, encoding string
+}
+
+func newRelayUp(t *testing.T) *relayUp {
+ t.Helper()
+ up := &relayUp{code: 200}
+ up.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ up.mu.Lock()
+ up.got = append(up.got, relayGot{r.URL.Path, r.Header.Get("Authorization"), string(b), r.Header.Get("Content-Encoding")})
+ up.mu.Unlock()
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.WriteHeader(up.code)
+ io.WriteString(w, "event: response.completed\ndata: {\"type\":\"response.completed\"}\n\n")
+ }))
+ t.Cleanup(up.srv.Close)
+ was := provider.CodexBase
+ provider.CodexBase = up.srv.URL + "/backend-api/codex"
+ t.Cleanup(func() { provider.CodexBase = was })
+ return up
+}
+
+func (up *relayUp) sent() []relayGot {
+ up.mu.Lock()
+ defer up.mu.Unlock()
+ return append([]relayGot(nil), up.got...)
+}
+
+func relayDo(h http.Handler, method, host, path, body string, hdr map[string]string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(method, path, strings.NewReader(body))
+ req.Host = host
+ for k, v := range hdr {
+ req.Header.Set(k, v)
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ return rec
+}
+
+// A Codex thread open when magpie quit keeps sending its turns to the
+// gateway's address (idkatbro on X: 503 "Unknown error" until magpie was
+// opened again). The relay passes one on Codex's own model to the ChatGPT
+// backend with the caller's own sign-in, and its reply comes back whole.
+func TestCodexRelayPassesOwnTurnOn(t *testing.T) {
+ fresh(t)
+ up := newRelayUp(t)
+ h := CodexRelay()
+ rec := relayDo(h, "POST", "127.0.0.1:3425", CodexPath+"/responses", `{"model":"gpt-5.5","input":"hi","stream":true}`,
+ map[string]string{"Authorization": "Bearer chatgpt-token", "Content-Type": "application/json"})
+ if rec.Code != 200 || !strings.Contains(rec.Body.String(), "response.completed") {
+ t.Fatalf("%d %s", rec.Code, rec.Body.String())
+ }
+ got := up.sent()
+ if len(got) != 1 || got[0].path != "/backend-api/codex/responses" || got[0].auth != "Bearer chatgpt-token" {
+ t.Fatalf("upstream was sent %+v", got)
+ }
+ // the model list Codex asks for, and localhost by name, go on too
+ rec = relayDo(h, "GET", "localhost:3425", CodexPath+"/models?client_version=0.162.1", "", map[string]string{"Authorization": "Bearer chatgpt-token"})
+ if rec.Code != 200 || len(up.sent()) != 2 || up.sent()[1].path != "/backend-api/codex/models" {
+ t.Fatalf("%d %+v", rec.Code, up.sent())
+ }
+}
+
+// What only the running magpie serves is refused with a reason Codex
+// shows at once (a 4xx; a 5xx it retries five times over), and nothing
+// goes to OpenAI: a magpie model, a turn on one of
+// magpie's accounts, and one masking would have masked, never sent
+// unmasked.
+func TestCodexRelayRefusesWhatNeedsMagpie(t *testing.T) {
+ fresh(t)
+ up := newRelayUp(t)
+ h := CodexRelay()
+ auth := map[string]string{"Authorization": "Bearer chatgpt-token"}
+ for _, c := range []struct {
+ name, body string
+ hdr map[string]string
+ mask bool
+ want string
+ }{
+ {"magpie model", `{"model":"openrouter/kimi-k2","input":"hi"}`, auth, false, "one of magpie's models"},
+ {"magpie account", `{"model":"gpt-5.5","input":"hi"}`, map[string]string{"Authorization": "Bearer t", AccountHeader: "[email protected]"}, false, "magpie's Codex accounts"},
+ {"masking", `{"model":"gpt-5.5","input":"DB_PASSWORD=hunter2"}`, auth, true, "not sent unmasked"},
+ } {
+ if err := settings.Save(settings.Settings{Redact: c.mask}); err != nil {
+ t.Fatal(err)
+ }
+ rec := relayDo(h, "POST", "127.0.0.1:3425", CodexPath+"/responses", c.body, c.hdr)
+ var e struct {
+ Error struct{ Message string } `json:"error"`
+ }
+ json.Unmarshal(rec.Body.Bytes(), &e)
+ if rec.Code != http.StatusBadRequest || !strings.Contains(e.Error.Message, c.want) || !strings.Contains(e.Error.Message, "magpie isn't running") {
+ t.Errorf("%s: %d %s", c.name, rec.Code, rec.Body.String())
+ }
+ }
+ if got := up.sent(); len(got) != 0 {
+ t.Fatalf("OpenAI was sent %+v", got)
+ }
+}
+
+// Only Codex on this computer is served: a page (any Origin, null too)
+// and a name rebound to 127.0.0.1 are turned away before anything goes
+// on, as corsGuard turns them from the gateway.
+func TestCodexRelayOnlyThisComputer(t *testing.T) {
+ fresh(t)
+ up := newRelayUp(t)
+ h := CodexRelay()
+ body := `{"model":"gpt-5.5","input":"hi"}`
+ for _, c := range []struct{ host, origin string }{
+ {"127.0.0.1:3425", "null"},
+ {"127.0.0.1:3425", "https://evil.example"},
+ {"evil.example:3425", ""},
+ {"magpie.localhost:3425", ""},
+ } {
+ hdr := map[string]string{"Authorization": "Bearer chatgpt-token"}
+ if c.origin != "" {
+ hdr["Origin"] = c.origin
+ }
+ if rec := relayDo(h, "POST", c.host, CodexPath+"/responses", body, hdr); rec.Code != 403 {
+ t.Errorf("%+v: %d %s", c, rec.Code, rec.Body.String())
+ }
+ }
+ if got := up.sent(); len(got) != 0 {
+ t.Fatalf("OpenAI was sent %+v", got)
+ }
+ if rec := relayDo(h, "POST", "[::1]:3425", CodexPath+"/responses", body, map[string]string{"Authorization": "Bearer t"}); rec.Code != 200 {
+ t.Fatalf("::1: %d %s", rec.Code, rec.Body.String())
+ }
+}
+
+// Anything but Codex's turns says magpie isn't running, readably; and
+// the relay's answer at "/" is never taken for magpie's (ServedBy), so
+// the next magpie starting still serves the gateway. An OpenAI that
+// can't be reached is said too, never an empty body Codex shows as
+// "Unknown error".
+func TestCodexRelayIsNotMagpie(t *testing.T) {
+ fresh(t)
+ newRelayUp(t)
+ h := CodexRelay()
+ for _, p := range []string{"/", "/v1/models", "/v1/chat/completions"} {
+ rec := relayDo(h, "GET", "127.0.0.1:3425", p, "", nil)
+ b := rec.Body.Bytes()
+ var info struct {
+ Name string `json:"name"`
+ }
+ json.Unmarshal(b, &info)
+ if rec.Code != 503 || info.Name == "magpie" || bytes.Contains(b, []byte(`"magpie"`)) || !strings.Contains(string(b), "magpie isn't running") {
+ t.Errorf("%s: %d %s", p, rec.Code, b)
+ }
+ }
+ provider.CodexBase = "http://127.0.0.1:1/backend-api/codex"
+ rec := relayDo(h, "POST", "127.0.0.1:3425", CodexPath+"/responses", `{"model":"gpt-5.5","input":"hi"}`, map[string]string{"Authorization": "Bearer t"})
+ if rec.Code != 502 || !strings.Contains(rec.Body.String(), "OpenAI can't be reached") {
+ t.Fatalf("%d %s", rec.Code, rec.Body.String())
+ }
+ // a WebSocket is sent to plain HTTP, as the gateway does
+ if rec := relayDo(h, "GET", "127.0.0.1:3425", CodexPath+"/responses", "", map[string]string{"Upgrade": "websocket"}); rec.Code != http.StatusUpgradeRequired {
+ t.Fatalf("websocket: %d", rec.Code)
+ }
+}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 31702d662..6797ce8ff 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -32,6 +32,7 @@ import (
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/awake"
"github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/codexrelay"
"github.com/yetone/magpie/internal/filememo"
"github.com/yetone/magpie/internal/gwbudget"
"github.com/yetone/magpie/internal/gwmw"
@@ -585,6 +586,11 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
s.lnMu.Lock()
s.tls = cfg
s.lnMu.Unlock()
+ // the Codex relay a magpie quitting left at the port (codexrelay)
+ // lets go of it, finishing the turns it streams
+ if !Handover && !Inherited() {
+ codexrelay.Leave()
+ }
ln, err := s.listen(listenAddr())
if err != nil {
return err
diff --git a/internal/gui/app.go b/internal/gui/app.go
index 6eff87c1e..6d939dab9 100644
--- a/internal/gui/app.go
+++ b/internal/gui/app.go
@@ -395,9 +395,19 @@ func Run(version string, showMain bool, link string) error {
return
}
if served.Load() != nil {
- if err := agent.EndCodexFailover(); err != nil {
+ ended, err := agent.EndCodexFailover()
+ if err != nil {
log.Println("codex failover:", err)
}
+ // the threads Codex has open keep the gateway's address
+ // they began with: a relay serves them there on Codex's
+ // own sign-in once the gateway has let go (codexrelay;
+ // idkatbro on X: 503 "Unknown error" till magpie reopened)
+ if ended {
+ if err := agent.RelayOpenCodex(); err != nil {
+ log.Println("codex relay:", err)
+ }
+ }
}
// the compactions magpie made in Codex's threads written as
// Codex's own, for the threads no Codex has open: with magpie
diff --git a/internal/gui/backend.go b/internal/gui/backend.go
index 1107f6f6e..d7aa63466 100644
--- a/internal/gui/backend.go
+++ b/internal/gui/backend.go
@@ -9,6 +9,7 @@ import (
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/codexrelay"
"github.com/yetone/magpie/internal/filememo"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
@@ -130,6 +131,9 @@ func serveGatewayLocked() *gateway.Server {
// so is the one that handed this one its socket, still finishing its
// requests on it (gui/handover.go)
if !gateway.Handover && !gateway.Inherited() {
+ // the Codex relay a magpie quitting left at the port (codexrelay)
+ // lets go of it, finishing the turns it streams
+ codexrelay.Leave()
if o := gateway.ServedBy(); o.Running {
if update.Newer(gateway.Version, o.Version) {
log.Printf("gateway: magpie %s serves %s, older than this one (%s); agents' requests go through it until it quits", o.Version, gateway.URL(), gateway.Version)
diff --git a/internal/provider/codex_daemon.go b/internal/provider/codex_daemon.go
index 0ea66fe6c..d636a6dba 100644
--- a/internal/provider/codex_daemon.go
+++ b/internal/provider/codex_daemon.go
@@ -554,3 +554,23 @@ func splitExe(args string) (exe, rest string) {
// CodexHome is the Codex home magpie wires and signs Codex in through.
func CodexHome() string { return codexHome() }
+
+// CodexPIDs lists the Codex processes running now that may hold a thread
+// sending to magpie's gateway: the Codex app's app-server, the managed
+// daemon, the CLI's sessions, an editor's codex. A relay magpie leaves at
+// quit for them ends once they all have (codexrelay).
+func CodexPIDs(ctx context.Context) []int {
+ ps, err := listProcesses(ctx)
+ if err != nil {
+ return nil
+ }
+ var pids []int
+ for _, p := range ps {
+ exe, _ := splitExe(p.Args)
+ base := strings.ToLower(exe[strings.LastIndexAny(exe, `/\`)+1:])
+ if p.PID != os.Getpid() && (base == "codex" || base == "codex.exe" || isCodexAppServer(p.Args) || isManagedDaemon(p.Args)) {
+ pids = append(pids, p.PID)
+ }
+ }
+ return pids
+}
diff --git a/internal/provider/codex_daemon_test.go b/internal/provider/codex_daemon_test.go
index e2fd2a1c5..1f6bb326a 100644
--- a/internal/provider/codex_daemon_test.go
+++ b/internal/provider/codex_daemon_test.go
@@ -599,3 +599,29 @@ func TestCodexDaemonEnvIsTheTerminals(t *testing.T) {
t.Errorf("env %q, want %q", got, in)
}
}
+
+// CodexPIDs finds what can hold a thread open on the gateway's address
+// as magpie quits: the Codex app, a CLI session, the app's app-server and
+// a managed daemon; never another program, nor magpie itself.
+func TestCodexPIDsFindsOpenCodex(t *testing.T) {
+ old := listProcesses
+ t.Cleanup(func() { listProcesses = old })
+ listProcesses = func(context.Context) ([]proc.Process, error) {
+ return []proc.Process{
+ {PID: 11, Args: "/Applications/Codex.app/Contents/MacOS/Codex"},
+ {PID: 12, Args: "/opt/homebrew/bin/codex resume"},
+ {PID: 13, Args: codexWindowsAppServer},
+ {PID: 14, Args: "/Users/u/.codex/bin/codex app-server --managed-daemon"},
+ {PID: 15, Args: "/usr/bin/vim codex.md"},
+ {PID: 16, Args: "/Applications/Codexify.app/Contents/MacOS/Codexify"},
+ {PID: os.Getpid(), Args: "/usr/local/bin/codex"},
+ }, nil
+ }
+ if got := CodexPIDs(context.Background()); !slices.Equal(got, []int{11, 12, 13, 14}) {
+ t.Fatalf("got %v", got)
+ }
+ listProcesses = func(context.Context) ([]proc.Process, error) { return nil, errors.New("ps failed") }
+ if got := CodexPIDs(context.Background()); got != nil {
+ t.Fatalf("a failed list gave %v", got)
+ }
+}