diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 147eec5a8..e4a0476e6 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -224,7 +224,7 @@ something else shows up as drift. - A Codex that isn't connected is never pointed at the gateway, however many of its ChatGPT accounts are on in magpie. magpie once wrote `openai_base_url` for it by itself while another account was on, for account failover (#1385; stash `codex.failover`, and with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so an unconnected Codex's every request went through magpie, its row saying not connected, until a Disconnect (TylerBai_loveai on X). Failover between Codex's accounts now comes with connecting it. Sync takes out what failover wrote before, the marked base URL or mirror `base_url` (`failover` in codex.go), and the route change restarts the app-server; a base URL the user wrote by hand (#856) has no mark and stays. `TestCodexNotConnectedStaysOffMagpie`, `TestCodexFailoverFromBeforeTakenOut`, `TestCodexSwitchOnlyKeepsCodexOffTheGateway`, `TestCodexHandWrittenBaseURLStays`. Until that Sync, such a Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`). 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). 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, from any caller, says magpie isn't running and to open it (503), never as magpie (`ServedBy`). A page, a browser extension or a rebound name on Codex's path is refused (403) with the same advice; before, every call with an Origin, a translation extension's `/v1/chat/completions` included, was told only that the relay "serves Codex on this computer only" (jipairamen on X; `TestCodexRelayTellsExtensionToOpenMagpie`). 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. - Codex's "applies to" field (`scope`, stash `codex.scope`; hpnjstar on X) chooses `codex -p magpie` alone: Codex reads `--profile ` from `.config.toml` beside `config.toml` (tried with codex-cli 0.165.0; it refuses `-p` while `config.toml` holds the legacy `[profiles.magpie]` or `profile = "magpie"`), so magpie writes `magpie.config.toml` with `model_provider`, `model`, `model_catalog_json`, the effort and its own `[model_providers.magpie]`, and never touches `config.toml` or the top-level `model_provider`, `model` and `openai_base_url` ([`codex_profile.go`](../../internal/agent/codex_profile.go)). Only magpie's models are offered; none of Codex's own, no joining, failover, CC Switch tables or subagent fields. Disconnect deletes that file and magpie's catalog. The choice changes only while Codex is disconnected, so the two wirings never share a config. An older Codex without profile files isn't served (`TestCodexProfileOnlyLeavesConfigTomlAlone`). - Codex on a magpie model the user has since unchecked in its provider's model list (`provider.Unpicked`: the provider has picks, its served models lack it, and it is not a decision model) moves to that provider's first model magpie lists for Codex (`pickedInstead`, [`model_unpicked.go`](../../internal/agent/model_unpicked.go)), in each wiring: Codex's Sync puts it through `set`, as picking it does, and the profile's Sync through `put` (JNDliuliuM on X: Codex CLI, restarted, still started on the old model; `Resolve` still serves it). A provider with no picks, whose list is the vendor's, keeps a model it lacks (#2642), and one with none of its models listed leaves Codex where it is. Other agents' model fields, and Codex's subagent and compaction models, are not moved yet (#6504). -- 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). Codex 0.166 refuses to resume a thread whose provider isn't the one configured ("This chat uses openai, but your current provider is magpie", openai/codex#58865; 毅 on Discord), and for a legacy thread the rollout's `session_meta` wins over the state DB row. So when magpie becomes the provider, bringOver relabels plain rollouts in place and also moves legacy threads Codex packed to `.jsonl.zst` that were updated in the last 30 days, up to 128 MB a sync, newest first, each with a copy kept in the trash (`sessions.MovePackedCodexThreads`, `TestCodexThreadsFollowMagpieIn`, `TestMovePackedCodexThreads`); bringBack moves them back. A paginated thread (`history_mode = 'paginated'` in the row, every thread Codex 0.166 starts) is listed and resumed on the provider its row names, never its files' (codex-rs thread-store `read_thread`: "Paginated history may contain only a suffix, so its display metadata lives in SQLite"), so the 30 days and the budget left an API-key user's older OpenAI threads refused in the Codex app (Parry_Moody and Cyrus on Discord). Every one now moves by its row alone, of any age, packed or not, an id of any length, its files neither written nor copied (`sessions.RetagPagedCodexThreads`, after the in-place relabel), in bringOver, bringBack, bringOfficial, bringBeside and giveBeside (`RetagPagedCodexThreadIDs`); one a Codex has open (its writer lock, which would write its provider back) or wrote to in the last minute waits for the next sync. The Sessions page lists a paginated thread on its row's provider (`codexPagedProviders`, read again when the database or its WAL changes). Tried with the real codex 0.166.0 (`codex exec resume`): refused on magpie with the row on openai, resumed after the retag, and back on OpenAI after the reverse (`TestCodexPagedThreadsFollowByRow`, `TestRetagPagedCodexThreads`). Codex rebuilds a row from the rollout when a search listing or a missing row reconciles it, which would put a retagged thread back on its file's provider until the next sync. A thread a move leaves where it was because it was written to in the last minute or a Codex holds it open gets one more Sync once it is quiet and let go (`sessions.CodexThreadsBusyOn`: a recent rollout, or its writer lock held, tried under Codex's coordination lock; `codexThreadsLater` looks every 15s for up to 12h, one wait per home and provider): no other Sync may come for hours. bringBack's (the thread a turn ran in during the takeover, as the account came back) otherwise stayed on magpie, and the Codex app couldn't resume it on OpenAI, so Retry failed each time and its model read unavailable (nb5p on Discord, `TestCodexTakeoverThreadComesBackOnceQuiet`). bringOver's and lendOwn's are the chats the Codex app had loaded as magpie became Codex's provider: the app holds every loaded thread's lock however long ago it was written (tried with codex 0.165's app-server), checks a loaded thread's provider against config.toml at each turn, and refuses it ("This chat uses OpenAI, but your current provider is magpie", crypto0xfish on Discord) until it lets the thread go; resumed after that, it was refused again on its row's `openai` until something else synced (`TestCodexOpenThreadFollowsMagpieOnceLetGo`). The chat open at the switch is moved by its row (a legacy one in place, at equal id length) just before the Codex app's app-server is ended for the route change (`provider.CodexBeforeAppEnd`, `codexRetagOpenThreads`, `sessions.RetagLoadedCodexThreads`): the app holds its lock, but the end is a clean SIGTERM that writes nothing back, and the next app-server resumes it on the new provider, in both directions (tried with the real codex 0.167.1 app-server: refused with `modelProviderMismatch` openai to magpie and `modelProviderNotConfigured` magpie to openai without the retag, resumed with it; hubo31377762 on X; `TestCodexOpenThreadsMoveBeforeAppServerEnds`, `TestCodexRouteChangeMovesOpenChatsFirst`). The resumed thread's sandbox falls back to config.toml's default whatever the provider (#6028, a separate bug). That is done for the provider Codex was on before magpie (stash `codex.provider`, `openai` when none), a provider of the user's own too: a relay's table or CC Switch's `custom`, whose threads the Codex app listed and refused to open on magpie ("This chat uses custom, but your current provider is magpie", hxy920830 on X). An id of magpie's length (`custom`) is relabelled in place; any other (`myrelay`) is rewritten with a copy kept, the threads of the last 30 days, 128 MB a sync, newest first (`sessions.MoveRecentCodexThreads`), and none moves of a provider a profile names. OpenAI's threads come to magpie too, since the Codex app lists them and refuses each one there as it did on that provider ("此聊天使用的是 OpenAI,但你当前的提供商是 magpie", Lice9735 on X, Codex on its own `openai-http` table before). They are recorded in stash `codex.lent` with the user's provider as `to`, as `lendOwn` records its own below: the Disconnect gives every thread on magpie to that provider, where Codex resumes them, and `giveLent` gives these back to OpenAI once Codex is on it again. None moves while a profile names `openai` (`TestCodexOpenAIThreadsFollowMagpieFromOwnProvider`). Before, they stayed on OpenAI there. The Disconnect puts the user's `model_provider` back and bringBack returns the threads to it; so does CC Switch switching back to that provider (`TestCodexThreadsFollowMagpieIn`, `TestMoveRecentCodexThreads`). A thread started on `cc-switch-official`, the id CC Switch 3.17 to 3.20 gave the official account, is moved to `openai` (or `magpie`, whichever Codex is on) while magpie wires Codex, as CC Switch 4 does itself (#7948 there), unless the user's own top-level `model_provider` or a profile names that id (`bringOfficial`, AcMilan on Discord, `TestCodexMovesCCSwitchOfficialThreads`). CC Switch's OpenAI mirror is the ChatGPT account's as much, and the Codex app names a provider by its table's `name`, so a thread on the mirror with Codex on `openai`, or the other way round, was refused as "This chat uses OpenAI, but your current provider is OpenAI" (Chris on Discord; codex 0.167 `exec resume` refuses both by id, 0.168 drops the check). Its threads move the same way: `bringOfficial` takes every mirror table's that isn't at the top, named by a profile, or the provider magpie took down (stash `codex.provider`, whose threads `bringBeside` and `bringOver` move with a record and give back at the Disconnect), and a mirror at the top takes OpenAI's through `lendOwn` (`TestCodexMirrorThreadsFollowOpenAI`, `TestCodexMirrorAtTopJoinsWithItsThreads`, `TestCodexMirrorAtTopTakesOpenAIThreads`). Before #4347 (v0.1.2652) the beside wiring took a provider of the user's (CC Switch's `custom`) down and kept it in stash `codex.provider`, leaving Codex on OpenAI by the base URL with every thread of that provider refused ("This chat uses custom, but your current provider is openai", yikelizi9438 on Discord). While Codex stays so (routed by `openai_base_url`, no top-level `model_provider`), `bringBeside` moves that provider's threads to `openai` the same way (in place at OpenAI's length, the last 30 days rewritten otherwise) and records them in stash `codex.brought`; the Disconnect puts the provider back and `giveBeside` returns exactly those threads to it (`sessions.MoveCodexThreadIDs`), and if magpie becomes Codex's provider instead they go on to `magpie` (`followBeside`), where bringBack returns them at the Disconnect (`TestCodexBesideBringsTakenProvidersThreads`). The other way round, Codex on a provider of the user's at the top (CC Switch's `custom`, kept since #4347, CC Switch's OpenAI mirror too; not magpie, `openai` or `cc-switch-official`) could not continue a thread started on OpenAI before ("This chat uses openai, but your current provider is custom. Switch to openai to continue", harris on Discord, after CC Switch). Each Sync moves OpenAI's threads to that provider the same way (`lendOwn`: in place at OpenAI's length, by the row for a paginated one, the last 30 days rewritten otherwise) and records them in stash `codex.lent`; once Codex is on OpenAI again `giveLent` returns exactly those (`sessions.MoveCodexThreadIDs`, `RetagPagedCodexThreadIDs`), the record kept while Codex is on that provider or on magpie and dropped on any other. None moves while a profile names `openai`, after the user disconnected Codex, or from a distro's Codex (`TestCodexOwnProviderTakesOpenAIThreads`, `TestCodexOwnProviderLeavesOpenAIThreads`). Each rewrite (`codexOnto`, shared by bringOver, bringBeside and lendOwn) goes `packedBudget` bytes a sync, newest first; when the budget stops it with threads left (`MovePackedCodexThreads` and `MoveRecentCodexThreads` say `more`), it asks for the next sync at once (`codexThreadsAgain`) instead of leaving them refused until something else syncs, which may be hours away (`TestCodexThreadsLeftByTheBudgetAskAgain`). Threads on any other provider, and ones older than 30 days that can't be relabelled in place, stay put: the Sessions page's Move or Resume takes them over. +- 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). Codex 0.166 refuses to resume a thread whose provider isn't the one configured ("This chat uses openai, but your current provider is magpie", openai/codex#58865; 毅 on Discord), and for a legacy thread the rollout's `session_meta` wins over the state DB row. So when magpie becomes the provider, bringOver relabels plain rollouts in place and also moves legacy threads Codex packed to `.jsonl.zst` that were updated in the last 30 days, up to 128 MB a sync, newest first, each with a copy kept in the trash (`sessions.MovePackedCodexThreads`, `TestCodexThreadsFollowMagpieIn`, `TestMovePackedCodexThreads`); bringBack moves them back. A paginated thread (`history_mode = 'paginated'` in the row, every thread Codex 0.166 starts) is listed and resumed on the provider its row names, never its files' (codex-rs thread-store `read_thread`: "Paginated history may contain only a suffix, so its display metadata lives in SQLite"), so the 30 days and the budget left an API-key user's older OpenAI threads refused in the Codex app (Parry_Moody and Cyrus on Discord). Every one now moves by its row alone, of any age, packed or not, an id of any length, its files neither written nor copied (`sessions.RetagPagedCodexThreads`, after the in-place relabel), in bringOver, bringBack, bringOfficial, bringBeside and giveBeside (`RetagPagedCodexThreadIDs`); one a Codex has open (its writer lock, which would write its provider back) or wrote to in the last minute waits for the next sync. The Sessions page lists a paginated thread on its row's provider (`codexPagedProviders`, read again when the database or its WAL changes). Tried with the real codex 0.166.0 (`codex exec resume`): refused on magpie with the row on openai, resumed after the retag, and back on OpenAI after the reverse (`TestCodexPagedThreadsFollowByRow`, `TestRetagPagedCodexThreads`). Codex rebuilds a row from the rollout when a search listing or a missing row reconciles it, which would put a retagged thread back on its file's provider until the next sync. A thread a move leaves where it was because it was written to in the last minute or a Codex holds it open gets one more Sync once it is quiet and let go (`sessions.CodexThreadsBusyOn`: a recent rollout, or its writer lock held, tried under Codex's coordination lock; `codexThreadsLater` looks every 15s for up to 12h, one wait per home and provider): no other Sync may come for hours. bringBack's (the thread a turn ran in during the takeover, as the account came back) otherwise stayed on magpie, and the Codex app couldn't resume it on OpenAI, so Retry failed each time and its model read unavailable (nb5p on Discord, `TestCodexTakeoverThreadComesBackOnceQuiet`). So the takeover's end waits too (`outStays` in Sync): while a Codex holds a chat on magpie open or wrote to one this minute (`codexHeldOnMagpie`, T3 Code's own left out), Codex stays on magpie and `codexThreadsLater` asks for the Sync that ends it once they are let go. The Codex app keeps the takeover's app-server at the reset (Restart the Codex app to follow is off by default), with its chats loaded and locked, so ending it at once put config.toml on OpenAI under them and every send was refused with "This chat uses magpie, but your current provider is OpenAI" (milianxinqi on X, `TestCodexTakeoverWaitsForTheOpenChat`). Nothing waits when the app-server is restarted for the change (Restart the Codex app to follow on, `TestCodexTakeoverEndsAtOnceWhenTheAppFollows`, or Always ChatGPT by hand), which moves its open chats first (`codexRetagOpenThreads`). bringOver's and lendOwn's are the chats the Codex app had loaded as magpie became Codex's provider: the app holds every loaded thread's lock however long ago it was written (tried with codex 0.165's app-server), checks a loaded thread's provider against config.toml at each turn, and refuses it ("This chat uses OpenAI, but your current provider is magpie", crypto0xfish on Discord) until it lets the thread go; resumed after that, it was refused again on its row's `openai` until something else synced (`TestCodexOpenThreadFollowsMagpieOnceLetGo`). The chat open at the switch is moved by its row (a legacy one in place, at equal id length) just before the Codex app's app-server is ended for the route change (`provider.CodexBeforeAppEnd`, `codexRetagOpenThreads`, `sessions.RetagLoadedCodexThreads`): the app holds its lock, but the end is a clean SIGTERM that writes nothing back, and the next app-server resumes it on the new provider, in both directions (tried with the real codex 0.167.1 app-server: refused with `modelProviderMismatch` openai to magpie and `modelProviderNotConfigured` magpie to openai without the retag, resumed with it; hubo31377762 on X; `TestCodexOpenThreadsMoveBeforeAppServerEnds`, `TestCodexRouteChangeMovesOpenChatsFirst`). The resumed thread's sandbox falls back to config.toml's default whatever the provider (#6028, a separate bug). That is done for the provider Codex was on before magpie (stash `codex.provider`, `openai` when none), a provider of the user's own too: a relay's table or CC Switch's `custom`, whose threads the Codex app listed and refused to open on magpie ("This chat uses custom, but your current provider is magpie", hxy920830 on X). An id of magpie's length (`custom`) is relabelled in place; any other (`myrelay`) is rewritten with a copy kept, the threads of the last 30 days, 128 MB a sync, newest first (`sessions.MoveRecentCodexThreads`), and none moves of a provider a profile names. OpenAI's threads come to magpie too, since the Codex app lists them and refuses each one there as it did on that provider ("此聊天使用的是 OpenAI,但你当前的提供商是 magpie", Lice9735 on X, Codex on its own `openai-http` table before). They are recorded in stash `codex.lent` with the user's provider as `to`, as `lendOwn` records its own below: the Disconnect gives every thread on magpie to that provider, where Codex resumes them, and `giveLent` gives these back to OpenAI once Codex is on it again. None moves while a profile names `openai` (`TestCodexOpenAIThreadsFollowMagpieFromOwnProvider`). Before, they stayed on OpenAI there. The Disconnect puts the user's `model_provider` back and bringBack returns the threads to it; so does CC Switch switching back to that provider (`TestCodexThreadsFollowMagpieIn`, `TestMoveRecentCodexThreads`). A thread started on `cc-switch-official`, the id CC Switch 3.17 to 3.20 gave the official account, is moved to `openai` (or `magpie`, whichever Codex is on) while magpie wires Codex, as CC Switch 4 does itself (#7948 there), unless the user's own top-level `model_provider` or a profile names that id (`bringOfficial`, AcMilan on Discord, `TestCodexMovesCCSwitchOfficialThreads`). CC Switch's OpenAI mirror is the ChatGPT account's as much, and the Codex app names a provider by its table's `name`, so a thread on the mirror with Codex on `openai`, or the other way round, was refused as "This chat uses OpenAI, but your current provider is OpenAI" (Chris on Discord; codex 0.167 `exec resume` refuses both by id, 0.168 drops the check). Its threads move the same way: `bringOfficial` takes every mirror table's that isn't at the top, named by a profile, or the provider magpie took down (stash `codex.provider`, whose threads `bringBeside` and `bringOver` move with a record and give back at the Disconnect), and a mirror at the top takes OpenAI's through `lendOwn` (`TestCodexMirrorThreadsFollowOpenAI`, `TestCodexMirrorAtTopJoinsWithItsThreads`, `TestCodexMirrorAtTopTakesOpenAIThreads`). Before #4347 (v0.1.2652) the beside wiring took a provider of the user's (CC Switch's `custom`) down and kept it in stash `codex.provider`, leaving Codex on OpenAI by the base URL with every thread of that provider refused ("This chat uses custom, but your current provider is openai", yikelizi9438 on Discord). While Codex stays so (routed by `openai_base_url`, no top-level `model_provider`), `bringBeside` moves that provider's threads to `openai` the same way (in place at OpenAI's length, the last 30 days rewritten otherwise) and records them in stash `codex.brought`; the Disconnect puts the provider back and `giveBeside` returns exactly those threads to it (`sessions.MoveCodexThreadIDs`), and if magpie becomes Codex's provider instead they go on to `magpie` (`followBeside`), where bringBack returns them at the Disconnect (`TestCodexBesideBringsTakenProvidersThreads`). The other way round, Codex on a provider of the user's at the top (CC Switch's `custom`, kept since #4347, CC Switch's OpenAI mirror too; not magpie, `openai` or `cc-switch-official`) could not continue a thread started on OpenAI before ("This chat uses openai, but your current provider is custom. Switch to openai to continue", harris on Discord, after CC Switch). Each Sync moves OpenAI's threads to that provider the same way (`lendOwn`: in place at OpenAI's length, by the row for a paginated one, the last 30 days rewritten otherwise) and records them in stash `codex.lent`; once Codex is on OpenAI again `giveLent` returns exactly those (`sessions.MoveCodexThreadIDs`, `RetagPagedCodexThreadIDs`), the record kept while Codex is on that provider or on magpie and dropped on any other. None moves while a profile names `openai`, after the user disconnected Codex, or from a distro's Codex (`TestCodexOwnProviderTakesOpenAIThreads`, `TestCodexOwnProviderLeavesOpenAIThreads`). Each rewrite (`codexOnto`, shared by bringOver, bringBeside and lendOwn) goes `packedBudget` bytes a sync, newest first; when the budget stops it with threads left (`MovePackedCodexThreads` and `MoveRecentCodexThreads` say `more`), it asks for the next sync at once (`codexThreadsAgain`) instead of leaving them refused until something else syncs, which may be hours away (`TestCodexThreadsLeftByTheBudgetAskAgain`). Threads on any other provider, and ones older than 30 days that can't be relabelled in place, stay put: the Sessions page's Move or Resume takes them over. - 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 locked card offers one action, Let magpie set it (`take`, `POST /api/tune/takeover`, `TuneTakeOver`; sufeng1894 on X: the card had no way to adjust it), and nothing moves without that click: the limit goes into Long conversations by `tuneMigrateCodex`'s rule (at magpie's default or Full window it is taken; a Compact at the user typed takes it only when lower), is taken out of config.toml, and its text is stashed (`tune.codex.compact_file`), so Undo puts Long conversations back and writes the limit in again unless the user changed either since. Background compaction's `model_async_compact_threshold_percent` of the user's (with `enabled = true` or none) is taken the same way: Settings' Background compaction takes it on, at that share, and the `codex.async` stash names the file's value magpie's, so the file is unchanged and the card adjusts it; Undo turns Background compaction back and gives the value back as the user's, written again if a later share replaced it. `tuneMigrateCodex` forgets an older tune's stash only once the limit is out of the file, and `codexAsyncSync` stashes what it wrote even when a later write fails, so a value magpie wrote never reads as the user's and locks the card (`TestTuneCodexTakeOver`, `TestTuneCodexTakeOverAsync`, `TestTuneCodexMigrateKeepsStash`, context-tune.test.cjs). 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..[.]` 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 the window Codex's catalog gives them (`codexcat.OwnWindow`, else 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. - A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. An object or array `connect` returns is taken as its JSON text (`agentplug.keys`), so it is written in the order the plugin gave it, not sorted as a Go map would be: Kilo lists its effort variants in key order (#1890, `TestPluggedKeepsPluginOrder`). What each key held before the first write is stashed under `plugin::`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`). Its `agent.library` (instructions, `mcp` with `mcpFormat`, skills) gives it the Library's three as well, written by `internal/library` as any agent's are ([library](library.md)); a `mcpFormat` outside `agentplug.MCPFormats`, or an `mcp` without one, keeps the plugin from loading. Turning the plugin off or removing it (`provider.SetPluginOff`, `provider.RemovePlugin`, from the CLI or the Plugins page) first disconnects its agent as `magpie default` does (`provider.PluginAgentGoing`, set to `agent.UnwirePlugin` in [`plugged_gone.go`](../../internal/agent/plugged_gone.go)), since without the plugin magpie no longer knows the agent (#3810); a plugin already off is read from its module as it is, and one whose module is gone puts back each file whose stash names its spec. A failure keeps the plugin as it was. On again, the agent stays as the user had it, and connecting it puts back the model it was on (Disconnect's `.reconnect`). The stash records the plugin's spec and the file's format, so `magpie default` for the agent of a plugin deleted on disk puts the file back from the stash alone (`agent.RestoreGone`; an older stash's format is its file's name, `agentplug.FormatOf`); a file that no longer holds the gateway's key is the user's and left alone, and one that can't be read is put back over by nothing; with the plugin only switched off, it says the agent is off magpie already, not "unknown agent" (`TestPluginOffPutsItsAgentBack`, `TestRestoreGoneAgent`, `TestGoneAgentDefault`). diff --git a/internal/agent/codex.go b/internal/agent/codex.go index b88f4531e..40ca98309 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -1409,6 +1409,32 @@ func codexIn(at place) *Agent { out := func() bool { return stashShared()[at.key("codex.login")] != "chatgpt" && codexUsedUp() && !codexSignInKept() } + // outStays: the takeover's end (the account has room again, at its + // reset, or is one the user keeps Codex on) waits while a Codex has a + // chat on magpie open, unless the Codex app's app-server is restarted + // for it. The app keeps the app-server the takeover started (#4550, + // Restart the Codex app to follow off by default) and its chats with + // it, each holding its lock, so bringBack can't move them, and with + // config.toml back on OpenAI every send in one was refused: "This chat + // uses magpie, but your current provider is OpenAI. Switch to magpie + // to continue" (milianxinqi on X: "用的好好的,codex 突然就弹这个了"). + // magpie serves those chats on the account with room meanwhile, and + // the app shows no account on that app-server either way. Once the + // chats are let go (the app restarted or quit, the chat closed) + // codexThreadsLater asks for the Sync that ends it, and bringBack + // moves them where Codex is then. The takeover turned off by hand + // (Always ChatGPT) restarts the app-server, moving its chats, and + // ends at once. + outStays := func() bool { + if at.spell != nil || stashShared()[at.key("codex.login")] == "chatgpt" || codexAppFollows() { + return false + } + if !codexHeldOnMagpie(dir) { + return false + } + codexThreadsLater(dir, magpieID) + return true + } dropBase := func() error { forget(at.key("codex.failover")) if !viaBase() { @@ -2198,6 +2224,12 @@ func codexIn(at place) *Agent { } // put back before #540's way back, which would take // codex/ for a magpie model picked beside the sign-in + // the takeover ends below once the account has room, unless a + // Codex still has a chat on magpie open (outStays) + ending := asProvider() && stashShared()[at.key("codex.out")] == "1" && !out() + if ending && outStays() { + ending = false + } if own := stashShared()[at.key("codex.out_own")]; own != "" { m := get("model") switch { @@ -2206,7 +2238,7 @@ func codexIn(at place) *Agent { // moved since (another model picked, magpie API, a // disconnect): that stands forget(at.key("codex.out_own"), at.key("codex.out_stand")) - case !out(): + case ending: // back beside the sign-in on the one picked, as Join // leaves it: Codex's own sign-in, magpie's models joined forget(at.key("codex.out_own"), at.key("codex.out"), at.key("codex.out_stand")) @@ -2234,7 +2266,7 @@ func codexIn(at place) *Agent { switch { case viaBase() && !asProvider() && out(): return set(m) - case asProvider() && stashShared()[at.key("codex.out")] == "1" && !out(): + case ending: return set(m) } } @@ -3109,6 +3141,28 @@ var codexUsedUp = func() bool { // user keeps it on (provider.CodexSignInKept). A var so tests can say. var codexSignInKept = provider.CodexSignInKept +// codexAppFollows reports whether magpie restarts the Codex app's +// app-server for a change of Codex's route it makes by itself +// (provider.CodexRestartsApp), moving the chats the app has open onto the +// new provider first. A var so tests can say. +var codexAppFollows = provider.CodexRestartsApp + +// codexHeldOnMagpie says whether a Codex holds open, or wrote to this +// minute, a thread of the Codex home dir on magpie that Codex resumes on +// the provider config.toml names: T3 Code's own (t3CodexRunsIn) stay on +// magpie whatever it names, and are left out. +func codexHeldOnMagpie(dir string) bool { + var skip func(string) bool + if user, _ := homes(); t3CodexRunsIn(user, dir) { + by, ok := sessions.CodexThreadsBy(dir, magpieID) + skip = func(id string) bool { + t, found := by[id] + return ok && found && t3Started(t.Originator) + } + } + return sessions.CodexThreadsBusyOnBut(dir, magpieID, skip) +} + // codexFailover reports whether Codex is signed in to a ChatGPT account // with more of its accounts on in magpie, behind it, and the user hasn't // asked magpie to only switch its sign-in (provider.SwitchOnly). diff --git a/internal/agent/codex_takeover_open_chat_test.go b/internal/agent/codex_takeover_open_chat_test.go new file mode 100644 index 000000000..09ddd70e2 --- /dev/null +++ b/internal/agent/codex_takeover_open_chat_test.go @@ -0,0 +1,140 @@ +package agent + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/filelock" +) + +// milianxinqi on X, the Codex app: "Model provider mismatch. This chat +// uses magpie, but your current provider is OpenAI. Switch to magpie to +// continue." ("用的好好的,codex 突然就弹这个了"). The ChatGPT account ran +// out, magpie became Codex's provider (the takeover) and the chat was +// started on magpie. At the account's reset Sync put Codex back beside +// its sign-in, on OpenAI, while the Codex app kept the app-server the +// takeover started (Restart the Codex app to follow is off by default) +// with the chat loaded and its lock held, so bringBack couldn't move it +// and every send in it was refused. The takeover now waits while a Codex +// holds a chat on magpie, and ends once the app lets it go. +func TestCodexTakeoverWaitsForTheOpenChat(t *testing.T) { + const id = "019a0000-0000-7000-8000-0000000000c1" + home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "") + dir := filepath.Join(home, ".codex") + cx := codex(home) + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + asked := watchCodexThreads(t) + t.Cleanup(func() { codexUsedUp = func() bool { return false } }) + + codexUsedUp = func() bool { return true } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if cfg := read(); !strings.Contains(cfg, `model_provider = "magpie"`) { + t.Fatalf("used up, magpie not Codex's provider:\n%s", cfg) + } + // the chat started during the takeover, quiet, that the Codex app has + // loaded (codex-rs rollout writer_lock.rs) + path := codexThreadOn(t, dir, id, "magpie") + old := time.Now().Add(-10 * time.Minute) + os.Chtimes(path, old, old) + letGo := holdCodexThreadLock(t, dir, id) + + // the reset: the account has room again + codexUsedUp = func() bool { return false } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if cfg := read(); !strings.Contains(cfg, `model_provider = "magpie"`) { + t.Fatalf("the account back with a chat on magpie open in the Codex app, Codex was put on OpenAI under it (\"This chat uses magpie, but your current provider is OpenAI\"):\n%s", cfg) + } + if p := codexRowOn(t, dir, id); p != "magpie" { + t.Fatalf("the open chat is on %q, want magpie, the provider Codex is on", p) + } + select { + case <-asked: + t.Fatal("a Sync asked for while the app still holds the chat") + case <-time.After(100 * time.Millisecond): + } + + // the app lets it go: restarted, quit, or the chat closed + letGo() + select { + case <-asked: + case <-time.After(5 * time.Second): + t.Fatal("the chat let go, no Sync asked for to end the takeover") + } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if cfg := read(); strings.Contains(cfg, "model_provider =") { + t.Fatalf("the chat let go, magpie still Codex's provider:\n%s", cfg) + } + if p := codexRowOn(t, dir, id); p != "openai" { + t.Fatalf("the chat is on %q after the takeover ended, want openai, where Codex resumes it", p) + } +} + +// With Restart the Codex app to follow on, magpie restarts the app-server +// for the takeover's end and moves the chats it has open first +// (codexRetagOpenThreads): nothing waits. +func TestCodexTakeoverEndsAtOnceWhenTheAppFollows(t *testing.T) { + const id = "019a0000-0000-7000-8000-0000000000c2" + home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "") + dir := filepath.Join(home, ".codex") + cx := codex(home) + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + watchCodexThreads(t) + oldFollows := codexAppFollows + codexAppFollows = func() bool { return true } + t.Cleanup(func() { codexUsedUp = func() bool { return false }; codexAppFollows = oldFollows }) + + codexUsedUp = func() bool { return true } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + path := codexThreadOn(t, dir, id, "magpie") + old := time.Now().Add(-10 * time.Minute) + os.Chtimes(path, old, old) + holdCodexThreadLock(t, dir, id) + + codexUsedUp = func() bool { return false } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if cfg := read(); strings.Contains(cfg, "model_provider =") { + t.Fatalf("the app restarted for the change, the takeover still waited:\n%s", cfg) + } +} + +// holdCodexThreadLock holds a thread's writer lock as a Codex that has it +// loaded does, till the returned func or the test's end. +func holdCodexThreadLock(t *testing.T, dir, id string) (letGo func()) { + t.Helper() + locks := filepath.Join(dir, "thread-writer-locks") + os.MkdirAll(locks, 0o755) + lf, err := os.OpenFile(filepath.Join(locks, id+".lock"), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + t.Fatal(err) + } + if got, err := filelock.TryLock(lf); !got { + t.Fatal("lock:", err) + } + done := false + letGo = func() { + if !done { + done = true + filelock.Unlock(lf) + lf.Close() + } + } + t.Cleanup(letGo) + return letGo +} diff --git a/internal/agent/codex_takeover_thread_test.go b/internal/agent/codex_takeover_thread_test.go index 172e7b6da..b72f6544a 100644 --- a/internal/agent/codex_takeover_thread_test.go +++ b/internal/agent/codex_takeover_thread_test.go @@ -46,8 +46,9 @@ func watchCodexThreads(t *testing.T) <-chan struct{} { // Codex went back to OpenAI, but the thread, written to that minute, was // left on magpie for a later Sync, and none came: the Codex app couldn't // go on with it on OpenAI, Retry failed the same way every time and its -// model read "model unavailable". bringBack asks for that Sync once the -// thread is quiet, and it moves the thread where Codex is. +// model read "model unavailable". The takeover now stays while the thread +// is written to (outStays), a Sync is asked for once it is quiet, and that +// one ends the takeover and moves the thread where Codex is. func TestCodexTakeoverThreadComesBackOnceQuiet(t *testing.T) { const id = "019a0000-0000-7000-8000-0000000000b1" home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "") @@ -75,8 +76,8 @@ func TestCodexTakeoverThreadComesBackOnceQuiet(t *testing.T) { if err := cx.Sync(); err != nil { t.Fatal(err) } - if cfg := read(); strings.Contains(cfg, "model_provider =") { - t.Fatalf("allowance back, magpie still Codex's provider:\n%s", cfg) + if cfg := read(); !strings.Contains(cfg, `model_provider = "magpie"`) { + t.Fatalf("allowance back with a thread on magpie written to this minute, the takeover ended under it:\n%s", cfg) } if p := codexRowOn(t, dir, id); p != "magpie" { t.Fatalf("a thread being written to was moved: %q", p) @@ -97,6 +98,9 @@ func TestCodexTakeoverThreadComesBackOnceQuiet(t *testing.T) { if err := cx.Sync(); err != nil { t.Fatal(err) } + if cfg := read(); strings.Contains(cfg, "model_provider =") { + t.Fatalf("the thread quiet, magpie still Codex's provider:\n%s", cfg) + } if p := codexRowOn(t, dir, id); p != "openai" { t.Fatalf("thread on %q after the later Sync, want openai, where Codex lists it", p) } diff --git a/internal/provider/routing.go b/internal/provider/routing.go index 8cc89d86b..2026d3d73 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -221,6 +221,12 @@ func SetRestartApp(id string, on bool) error { return Save(*p) } +// CodexRestartsApp is codexRestartsApp, for the agent package: a change +// of Codex's route magpie makes by itself restarts the Codex app's +// app-server (moving the chats it has open first, CodexBeforeAppEnd) only +// when it says so. +func CodexRestartsApp() bool { return codexRestartsApp() } + // codexRestartsApp is whether the user had magpie restart the Codex app's // app-server for a change it makes by itself (Provider.RestartApp). While // providers.json can't be read it is unknown, and the app is left be: a diff --git a/internal/sessions/codex_provider.go b/internal/sessions/codex_provider.go index 7df96c121..867b79d25 100644 --- a/internal/sessions/codex_provider.go +++ b/internal/sessions/codex_provider.go @@ -623,6 +623,13 @@ type CodexThreadBy struct { // it was written to. A database that can't be read, and a rollout that // can't be found, say nothing. func CodexThreadsBusyOn(home, p string) bool { + return CodexThreadsBusyOnBut(home, p, nil) +} + +// CodexThreadsBusyOnBut is CodexThreadsBusyOn leaving out the threads +// skip names: another client's on p, which stay there whatever Codex's +// config says (T3 Code's on magpie). +func CodexThreadsBusyOnBut(home, p string, skip func(id string) bool) bool { now := time.Now() locked := codexLockedIDs(home) for _, path := range codexStateDBs(home) { @@ -640,7 +647,7 @@ func CodexThreadsBusyOn(home, p string) bool { if err == nil { for rows.Next() { var id, r string - if rows.Scan(&id, &r) != nil { + if rows.Scan(&id, &r) != nil || skip != nil && skip(id) { continue } if locked[strings.ToLower(id)] {