Skip to content

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

gateway: Codex's memories after a model switch wait for the new turn, as titles do

yetoneb7d5a97feceb
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index ce3cdd33a..3be021438 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -30,7 +30,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).
| WSL under NAT | On Windows, while the gateway listens on loopback alone, `serveWSL` also serves it, in plain HTTP, at each address Windows has on a WSL network (`WSLNets`: the `vEthernet (WSL…)` adapters, looked for every 10s, since WSL's VM brings its adapter up and down). That is where a distro in NAT networking reaches Windows, and what `place` writes into its agents (zaidu259434 on X: Codex in WSL failed with sharing off). `lanGuard` takes a request there as this computer's (`fromWSL`) only when it arrives at that address, from inside that network, with the WSL key: `WSLKey`, a `wsl-` secret in magpie's folder (`wsl-key`, 0600), optionally followed by `-<agent>`. It becomes a loopback request carrying `magpie` or `magpie-<agent>` (`asFromLoopback`). Anything else there, a Docker Desktop container on the same network included, is judged as another machine's. Windows' firewall still decides whether WSL gets in: WSL's network is a Public one. | [`wsl.go`](../../internal/gateway/wsl.go) |
| TLS | `--tls-cert`/`--tls-key` (`MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY`) make `ListenAndServe`, `Relisten` (both through `Server.listen`) and `magpie web`'s page (`ServeTLS`) wrap the listener in `tlsListener`. A connection from another computer is `tls.Server` at once, so its plain HTTP gets net/http's 400. One from this computer (`fromThisComputer`: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (`sniffWait`), and 0x16 makes it TLS, so `URL()`, the agents, MCP servers, `ServedBy` and the healthcheck keep `http://127.0.0.1`. `certFiles.get` reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). `tlsConfig` refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). `Scheme()` gives the scheme of `LANURLs`, a scheme-less `MAGPIE_PUBLIC_URL` and the page's network links. Host and Origin checks (`foreignPage`, `rebound`) don't depend on the scheme. | [`tls.go`](../../internal/gateway/tls.go), [`lan.go`](../../internal/gateway/lan.go) |
| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; a name ending `:latest`, as the ollama CLI asks, is the bare id unless a model is really called that (`ollamaName`); the client then chats on `/v1/chat/completions`, or on Ollama's own `POST /api/chat` and `POST /api/generate` (`ollama_chat.go`, Zed's Ollama provider, super_lalalalala on Discord), which `ollamaChatBody` turns into a `/v1/chat/completions` body handed to the same `handle(provider.Chat)` on a clone of the request, so they are routed, held to a key's models and counted as it is: `messages` with `images` (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's `thinking` as `reasoning_content` and its `tool_calls` given ids where Ollama sent none, a tool result matched to its call by `tool_call_id`, else `tool_name`, else in order (one with no call is a 400), `tools`, `format` (`json` or a schema), `think` (a level is `reasoning_effort`), and `options`' `temperature`, `top_p`, `seed`, `stop`, the two penalties and a positive `num_predict` as `max_tokens` (`num_ctx`, `top_k` and the rest of Ollama's own are dropped); `ollamaWriter` turns the reply into Ollama's NDJSON lines (streamed unless `stream:false`, then one object), tool calls with their `arguments` as an object and an `id`, and a last `done` line with `done_reason` and the token counts, and an error into `{"error":"…"}` with the status `/v1` would give; a request with no messages or prompt is answered `done_reason:"load"`, as Ollama does to warm a model), `/mcp/{name}`, `/mcp/magpie/web-search`, `/mcp/magpie/vision` and `/mcp/magpie/image` with its `/mcp/magpie/image/files/{name}` (magpie's own web search, image recognition and image generation as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/magpie/goroutines` (`goroutineDump`, [`goroutines.go`](../../internal/gateway/goroutines.go), for `magpie goroutines`, #3362) answers every goroutine's stack and wait as text (`runtime/pprof`'s `goroutine` profile at debug 2) to the same callers, through `goroutinesRefused`, and is answered ahead of everything below (`dumpFirst`, around `Handler`'s wrappers and around `lanGuard` in `Front`), since it is asked for while magpie hangs: the allow list reads settings.json under its lock, and `holdCatalog` takes `provider.Hold`'s and `filememo`'s, so a stuck holder of any of them would hold the dump too; a caller `goroutinesRefused` lets in is one those let in anyway, and any other goes through them as before (`TestGoroutineDumpAnswersWhileRequestsWait`). `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://<id>` (Chromium, the id 32 letters a–p), `moz-extension://<uuid>` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://<uuid>` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/<token>` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`), and its port hands the gateway's client routes (`ClientPath`) to `Server.Front`, the same lanGuard-over-Handler the gateway's listener serves, so every route there is judged as on the gateway's port (`TestClientPathCoversHandler` fails when a route Handler adds is in neither `ClientPath` nor its list of routes that stay on the gateway's port). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`ollama.go`](../../internal/gateway/ollama.go), [`ollama_chat.go`](../../internal/gateway/ollama_chat.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) |
-| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-<slug>`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) |
+| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key; a memory call first waits beside the turn it was started with, through `codexLeads`, see the side turns below), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-<slug>`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) |
| A found group's two ids | A group magpie found is listed (`/v1/models`, the catalog, the lists written into agents, the pickers, the CLI and TUI) as `auto/<model>`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`, preferring a spelling models.dev lists), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). Its old id `group/auto-<slug>` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/<model>` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/<model>` by the old id. An agent field magpie set to `group/auto-<slug>` moves to `auto/<model>` on the next `SyncCatalog` (`agent.renameFoundGroups`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/<model>`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/<x>` is its model and found groups list as `group/auto-<slug>` (`autoRefsOn`). Hand-made groups stay `group/<id>`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) |
| Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) |
| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first) or `fast` (speed first). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/<id>`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) |
@@ -75,6 +75,20 @@ key's last turn is older than 3s (`codexSideFresh`) waits, up to 5s
(`codexSideWait`) or its cancellation, for the next turn and takes its
model (`codexLeads.sideOf`, `TestCodexTitleBeforeTheFirstTurnFollowsTheSwitch`);
a later rename suggestion with no turn beside it waits the 5s. Codex
+starts its memories with each turn of a conversation that has the user's
+input (codex-rs `start_memories_startup_task`; extraction under that
+conversation's thread, consolidation on a thread of its own), so a memory
+call waits the same way even when tied to a seen thread (`sideOf`'s
+`beside`): one that beats the first turn after a switch, in a new
+conversation or one under way, goes on the model switched to, through the
+ChatGPT backend (`codexMemorySession`) and with magpie as Codex's provider
+(`codexMemoryStandIn`, which reads `codexLeads` before its last-turn
+record), cybercaius on Discord
+(`TestCodexSideCallsBeforeTheFirstTurnFollowTheSwitch`,
+`TestCodexMemoryOfASwitchedConversationFollowsTheSwitch`,
+`TestCodexMemoryStandInFollowsTheSwitch`). A call tied to a seen thread
+and not started with a turn (a prediction, a known thread's title) takes
+that thread's last model at once. Codex
asks a title with no reasoning effort on any model but its own title
model, and its auto-review at a model's default, which it has none of for
magpie's models; a model that needs an effort answered those with 400
@@ -129,7 +143,7 @@ recorded as a prediction failure (`noPrediction`).
- A model the user disabled (#1867) gets a 403 for every caller (`idOff`), before anything is sent; see [Disabled models](#disabled-models).
- Sealed tasks (#619) are checked here. A Codex subagent's task its lead's `spawn_agent` sealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (`leadProvider`, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (`send_message`) goes back to the Responses provider that answered the lead's own conversation (`leadProvider` of the request's `conversationID`, #1237); otherwise it is refused before anyone is asked (`sealedReader`, `sealedTaskError`). A sealed message (`Message Type: MESSAGE`, not a task) that nobody asked can open is left out instead, an `input_text` note naming its sender in its place (`withoutSealedMessages`, #1613): a lead on a chat provider whose subagent is on one of Codex's own models goes on, as the subagent's final result still reaches it as text. Only a sealed task (`NEW_TASK`, or an item with neither header) is refused. Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversations `affinity.json` keeps, or the lead's last reply broken off, `unanswered`), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (`loggedAnswers`, #1367), and `leadFirst` reads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it. It also says what is sealed (`sealedTaskItself`, #1855): the task itself, `spawn_agent`'s `message`, which the backend returns sealed (`encrypted_function_args`) and Codex hands the subagent as it came, so `fork_turns="none"`, which only leaves the lead's turns out, doesn't help; nothing in it can be left out for the subagent to go on.
- A model set for Codex's subagents (`settings.CodexSubagentModel`, the Agents page's Codex "subagent model", willz on Discord) is put on a Codex subagent's request (`x-openai-subagent` read as `kind:collab_spawn`) before this check, whatever model its lead's `spawn_agent` asked for (`codexSubagentPick` in [`codex_subagent.go`](../../internal/gateway/codex_subagent.go)): in `codexBackend` for one of Codex's own bare models, which then goes through `serveAgent`, and in `serve` for any other. Any model magpie serves can be set (`provider.SetCodexSubagentModel`, #1633): a task handed as text (a lead magpie served on a chat provider, or multi-agent V1) is read by any model. A request carrying a task the ChatGPT backend sealed (`sealedTaskIn`: a sealed agent message that isn't a `MESSAGE`, which `withoutSealedMessages` leaves out) is put only on a ChatGPT account's model; set to another, the subagent stays on the model asked for, which the sealed gate below handles as with nothing set. When magpie doesn't serve the model set now, or a gateway key held to some models may not use it, the subagent goes on the model asked for too. The route trace keeps both models and the reason it stayed (`Route.Subagent`), and the Routing page's `kindWhy` says it. The lead's turns, titles and every other kind are never moved.
- - With no model set for them, in magpie or in Codex's config (`[agents] default_subagent_model`, `[memories] extract_model`/`consolidation_model`, read by `agent.CodexSideSet`; a config it can't read counts as set), a Codex subagent or memory call on one of Codex's own bare models, made in a conversation whose own turns go on one of magpie's models, follows that model instead of going to the ChatGPT sign-in (`codexFollowTo` in [`codex_follow.go`](../../internal/gateway/codex_follow.go), cybercaius on Discord). The model is the parent thread's last own turn (`x-codex-parent-thread-id` or the turn metadata's parent), else its own thread's, else the last one by the gateway key (`codexLeads`, at most 512 threads), else, before any turn has come through magpie (Codex consolidates its memories as it starts), Codex's config `model` when it is one of magpie's (`codexSessionOf`, `TestCodexMemoriesBeforeAnyTurnFollowTheConfig`). A sealed task, a model magpie can't resolve now or one a gateway key may not use leaves the call as it came; a subagent's trace keeps both models in `Route.Subagent`. Codex's auto-review follows the session only when `settings.CodexAutoReview` is `session` (`settings.CodexAutoReviewSession`): `codexcat` then has each of magpie's entries name itself as `auto_review_model_override`, and Codex's own entries keep OpenAI's, since codex-auto-review is free on a paid ChatGPT sign-in (#1593). On a Free plan it isn't (cybercaius measured it on Discord), so with the setting unset and Codex's live sign-in on the `free` plan (`codexcat.AutoReviewModel`, the plan from `provider.CodexSignInPlan`), it counts as `session` (`TestCodexAutoReviewOnAFreePlan`).
+ - With no model set for them, in magpie or in Codex's config (`[agents] default_subagent_model`, `[memories] extract_model`/`consolidation_model`, read by `agent.CodexSideSet`; a config it can't read counts as set), a Codex subagent or memory call on one of Codex's own bare models, made in a conversation whose own turns go on one of magpie's models, follows that model instead of going to the ChatGPT sign-in (`codexFollowTo` in [`codex_follow.go`](../../internal/gateway/codex_follow.go), cybercaius on Discord). The model is the parent thread's last own turn (`x-codex-parent-thread-id` or the turn metadata's parent), else its own thread's, else the last one by the gateway key (`codexLeads`, at most 512 threads), else, before any turn has come through magpie (Codex consolidates its memories as it starts), Codex's config `model` when it is one of magpie's (`codexSessionOf`, `TestCodexMemoriesBeforeAnyTurnFollowTheConfig`). A memory call is read after the turn it was started with (`codexMemorySession`, above). A sealed task, a model magpie can't resolve now or one a gateway key may not use leaves the call as it came; a subagent's trace keeps both models in `Route.Subagent`. Codex's auto-review follows the session only when `settings.CodexAutoReview` is `session` (`settings.CodexAutoReviewSession`): `codexcat` then has each of magpie's entries name itself as `auto_review_model_override`, and Codex's own entries keep OpenAI's, since codex-auto-review is free on a paid ChatGPT sign-in (#1593). On a Free plan it isn't (cybercaius measured it on Discord), so with the setting unset and Codex's live sign-in on the `free` plan (`codexcat.AutoReviewModel`, the plan from `provider.CodexSignInPlan`), it counts as `session` (`TestCodexAutoReviewOnAFreePlan`).
- A model set for Claude Desktop's subagents (`settings.DesktopSubagentModel`, the Agents page's Claude Desktop "subagent model") is put on a subagent's turn in Desktop's Code tab or Cowork after `desktopTurn`, the tiers and the groups, whatever model its lead or its tier asked for (`desktopSubagentPick` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)). Desktop runs its Claude Code with `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1`, under which Claude Code ignores the `CLAUDE_CODE_SUBAGENT_MODEL` magpie writes into its settings (see [agent wiring](agent-wiring.md)). A subagent's request is one with `x-claude-code-agent-id` (`subagentOf`) from `claude-desktop`, and only one that offers tools is its turn: Claude Code's tool-less helper calls inside a subagent, on the haiku tier's model, stay where they are, and so do the lead's turns, terminal Claude Code's and every other agent's. The model set must be served by its exact id (`provider.DesktopSubagentUnserved`: `Resolve` takes any model name under a provider that is on), enabled, and allowed to a gateway key held to some models (`groupAllowed` for a group); otherwise the subagent goes on the model asked for and the route trace says why (`Route.Subagent`, said on the Routing page by `subagentWhy`, its `Kind` staying empty). `Route.Model` and the ledger's `Requested` keep the model the subagent asked for. `count_tokens` counts on the model set the same way (`countTokens`). The setting is read on each request, so a change needs no restart of Desktop, and a provider renamed since it was set is read by its new id (`RenamedRef`). A Desktop on another computer that reaches magpie with a named gateway key is read as Claude Code (`agentOf`), so none of Desktop's routing, this included, applies to it. A subagent's turn, moved or not, is never kept as the session's model in `claude-desktop.model` (`desktopTurn`'s `bySubagent`): a subagent on the opus tier's model took the session's place until the lead's next turn, and Desktop's titles asked for meanwhile went to it.
- Desktop's subagent effort (`settings.DesktopSubagentEffort`, `desktopSubagentEffort` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)) applies to the same subagent tool turns, independently of model replacement. Empty leaves requests unchanged. Set, it takes the place of a request model's effort suffix before the existing attempt-level effort fitting: a member fixed at an effort wins, then this pick fitted within group/model levels, then the turn's or request's effort. `withFixedEffort` can enable reasoning when it was disabled, or disable it with `none` on a model that supports that level; a reasonless model is still sent no reasoning fields. `countTokens` applies the pick after restoring any unmasked body. `Route.Effort` keeps the incoming effort, `Route.SubagentEffort` the configured pick, and each try and usage record the level actually sent; the Routing story explains the configured pick even when no model was replaced. A nonempty model pick already classifies the turn, so the effort check reuses it; empty effort costs only a held-settings read. The next request takes a changed or cleared effort without a Desktop restart.
- Every Claude Code subagent's turn, Desktop's or a terminal's, moved or not, keeps its `x-claude-code-agent-id` in `Route.SubagentID` (`subagentTurnOf` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)): a request with the id that offers tools and names no kind, the turn the two settings above take. Claude Code 2.1.295 sends the id from any agent context but the main one; its `x-claude-code-request-class` and `x-claude-code-agent-type` hints go only to a first-party base URL or with `CLAUDE_CODE_GATEWAY_HINT_HEADERS`, so magpie doesn't get them. A Desktop pick or effort that found the turn is trusted, so the body isn't decoded again, and a request without the id isn't decoded at all. The Routing page tags it as Codex's subagents are (`tagKind` in [`routing.js`](../../internal/gui/assets/routing.js)): in the request list, the story, the replay and the tray panel, with the reason `kindWhy` gives Codex's. `Kind` stays empty, so its purpose stays unmarked in the Purpose filter, as in the ledger and on the Usage page. The ledger's `Subagent` keeps the same id, and also marks a subagent's tool-less helper calls, which aren't tagged. A route recorded before this has no id and no tag.
diff --git a/internal/gateway/codex_follow.go b/internal/gateway/codex_follow.go
index 33f199553..605617291 100644
--- a/internal/gateway/codex_follow.go
+++ b/internal/gateway/codex_follow.go
@@ -20,7 +20,8 @@ import (
// account rather than where the user had routed Codex (cybercaius on
// Discord). With nothing set for them, a subagent and the memories follow
// the session: they go on the model the conversation's own turns go on,
-// when that is one of magpie's (codexSessionOf), as the app's titles,
+// when that is one of magpie's (codexSessionOf; a memory call, started
+// with a turn, after that turn: codexMemorySession), as the app's titles,
// descriptions, summaries and composer predictions do (codexSideTo). The auto-review follows it when set to
// (settings.CodexAutoReviewSession, which codexcat writes into each of
// magpie's entries); left to Codex it stays on codex-auto-review, which a
@@ -121,19 +122,28 @@ var (
codexSideWait = 5 * time.Second
)
-// sideOf is of for the Codex app's own side turns: a title, description,
-// summary or prediction. Codex writes a new conversation's title on a
-// temporary thread of its own, with no link to the conversation, started
-// as the user's first message is sent, so it often reaches magpie before
-// that conversation's first turn. Read then, the key's last turn is the
-// previous conversation's, on the model the user switched away from
-// (cybercaius on Discord: the first title after a switch came from the
-// old model). When this key's last turn is older than codexSideFresh,
-// such a call waits, up to codexSideWait or until it is cancelled, for
-// the next turn of any conversation, and takes that one's model.
-func (l *codexLeads) sideOf(r *http.Request, body []byte) string {
+// sideOf is of for a side call started beside a turn: the Codex app's
+// title, description, summary or prediction, and Codex's memories. Codex
+// writes a new conversation's title on a temporary thread of its own, with
+// no link to the conversation, started as the user's first message is
+// sent, so it often reaches magpie before that conversation's first turn.
+// Read then, the key's last turn is the previous conversation's, on the
+// model the user switched away from (cybercaius on Discord: the first
+// title after a switch came from the old model). When this key's last
+// turn is older than codexSideFresh, such a call waits, up to
+// codexSideWait or until it is cancelled, for the next turn of any
+// conversation, and takes that one's model.
+//
+// beside is a call Codex starts with every turn of its conversation, tied
+// to it: its memories, which Codex extracts and consolidates as each turn
+// with the user's input starts (codex-rs app-server turn_processor,
+// start_memories_startup_task), under that conversation's thread. Racing
+// the turn, the conversation's last model is the one before a switch, so
+// it waits too. A call tied to a conversation that isn't (a composer
+// prediction, a known thread's title) takes its last model at once.
+func (l *codexLeads) sideOf(r *http.Request, body []byte, beside bool) string {
model, tied, at := l.lookup(r, body)
- if tied || model == "" || time.Since(at) < codexSideFresh {
+ if tied && !beside || model == "" || time.Since(at) < codexSideFresh {
return model
}
l.mu.Lock()
@@ -177,13 +187,19 @@ func (s *Server) codexFollowTo(r *http.Request, agent, kind, asked string, body
default:
return ""
}
- to := s.codexSessionOf(r, body)
- if to == "" || to == asked {
+ // the user's own pick in Codex's config is kept; read before the
+ // session, which a memory call may wait on
+ if CodexSideSet == nil || CodexSideSet(which) {
return ""
}
- // the user's own pick in Codex's config is kept; read last, as it
- // reads the config
- if CodexSideSet == nil || CodexSideSet(which) {
+ var to string
+ if which == "memories" {
+ // started with a turn, maybe the first after a switch
+ to = s.codexMemorySession(r, body)
+ } else {
+ to = s.codexSessionOf(r, body)
+ }
+ if to == "" || to == asked {
return ""
}
return to
@@ -206,7 +222,13 @@ func (s *Server) codexSessionOf(r *http.Request, body []byte) string {
// codexSideSession is codexSessionOf for the Codex app's own side turns,
// read after the turn they were started beside (codexLeads.sideOf).
func (s *Server) codexSideSession(r *http.Request, body []byte) string {
- return s.servedSession(r, s.codexLeads.sideOf(r, body))
+ return s.servedSession(r, s.codexLeads.sideOf(r, body, false))
+}
+
+// codexMemorySession is codexSessionOf for Codex's memory calls, read
+// after the turn they were started with (codexLeads.sideOf, beside).
+func (s *Server) codexMemorySession(r *http.Request, body []byte) string {
+ return s.servedSession(r, s.codexLeads.sideOf(r, body, true))
}
// servedSession is to, else the model in Codex's config, when magpie can
diff --git a/internal/gateway/codex_follow_test.go b/internal/gateway/codex_follow_test.go
index 04fc02dd7..b5d7a3ed5 100644
--- a/internal/gateway/codex_follow_test.go
+++ b/internal/gateway/codex_follow_test.go
@@ -277,3 +277,150 @@ func TestCodexMemoriesBeforeAnyTurnFollowTheConfig(t *testing.T) {
t.Fatalf("the relay got %v", reqs)
}
}
+
+// codexSideAsk is one of Codex's side calls on one of its own models, with
+// the headers Codex sends for it.
+func codexSideAsk(s *Server, model string, h map[string]string) {
+ body := `{"model":"` + model + `","stream":true,"input":[` + leadAsk + `]}`
+ req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body))
+ req.Header.Set("Authorization", "Bearer chatgpt-token")
+ req.Header.Set("chatgpt-account-id", "acct-1")
+ req.Header.Set("User-Agent", "codex_cli_rs/0.159.0 (Mac OS 26.2.0; arm64)")
+ for k, v := range h {
+ req.Header.Set(k, v)
+ }
+ s.Handler().ServeHTTP(httptest.NewRecorder(), req)
+}
+
+// beforeTheTurn runs side, then turn once side is waiting for a turn or has
+// been answered (on the old code a memory call never waits, and is
+// answered first), and waits for side to finish.
+func beforeTheTurn(t *testing.T, s *Server, side, turn func()) {
+ t.Helper()
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ side()
+ }()
+ for waiting := false; !waiting; {
+ select {
+ case <-done:
+ waiting = true
+ default:
+ s.codexLeads.mu.Lock()
+ waiting = s.codexLeads.next != nil
+ s.codexLeads.mu.Unlock()
+ if !waiting {
+ time.Sleep(time.Millisecond)
+ }
+ }
+ }
+ turn()
+ <-done
+}
+
+// cybercaius on Discord: after switching Codex's model, does the first of
+// each side call go on the new model, as the title does? Each kind, sent
+// before the first turn on the new model reaches magpie: a new
+// conversation's title and description (a temporary thread of the app's),
+// its composer prediction (a fork of it), and its memories, which Codex
+// starts with every turn of a conversation (phase 1 under the
+// conversation's thread, phase 2 on a consolidation thread of its own).
+// Each goes on the model switched to, none on the one before, none to
+// ChatGPT.
+func TestCodexSideCallsBeforeTheFirstTurnFollowTheSwitch(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ h map[string]string
+ }{
+ {"title", map[string]string{"session_id": "title-thread", "x-codex-turn-metadata": `{"thread_source":"thread_title"}`}},
+ {"description", map[string]string{"session_id": "desc-thread", "x-codex-turn-metadata": `{"thread_source":"thread_description"}`}},
+ {"prediction", map[string]string{"session_id": "fork-of-lead-2", "x-codex-turn-metadata": `{"thread_source":"composer_predictions","forked_from_thread_id":"lead-2"}`}},
+ {"memory extraction", map[string]string{"session_id": "lead-2", "x-codex-turn-metadata": `{"thread_source":"memory_consolidation","request_kind":"memory"}`}},
+ {"memory consolidation", map[string]string{"session_id": "consolidation-thread", "x-openai-memgen-request": "true", "x-codex-turn-metadata": `{"thread_source":"memory_consolidation"}`}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ up, old, s := codexFollowSetup(t, false)
+ switched := relayOn(t, "fourth")
+ wasModel, wasFresh, wasWait := CodexSideModel, codexSideFresh, codexSideWait
+ CodexSideModel = func() string { return "" }
+ codexSideFresh, codexSideWait = 0, time.Minute
+ t.Cleanup(func() { CodexSideModel, codexSideFresh, codexSideWait = wasModel, wasFresh, wasWait })
+ beforeTheTurn(t, s, func() { codexSideAsk(s, "gpt-5.6-luna", c.h) }, func() {
+ if rec := codexSubTurn(s, "fourth/gpt-6-astra", "lead-2", "", leadAsk); rec.Code != 200 {
+ t.Errorf("new conversation: %d %s", rec.Code, rec.Body.String())
+ }
+ })
+ if got := up.asked(); len(got) != 0 {
+ t.Fatalf("ChatGPT was asked for %v", got)
+ }
+ if reqs := old.requests(); len(reqs) != 1 {
+ t.Fatalf("the model switched from got %d requests, the %s among them", len(reqs), c.name)
+ }
+ if reqs := switched.requests(); len(reqs) != 2 {
+ t.Fatalf("the model switched to got %d requests, want the turn and the %s", len(reqs), c.name)
+ }
+ })
+ }
+}
+
+// The model switched in a conversation already under way: Codex starts its
+// memories with the conversation's next turn, under that thread, and the
+// memory call that beats the turn to magpie goes on the new model, not on
+// the thread's last. A composer prediction of that thread asked after the
+// turn is on the new model too.
+func TestCodexMemoryOfASwitchedConversationFollowsTheSwitch(t *testing.T) {
+ up, old, s := codexFollowSetup(t, false)
+ switched := relayOn(t, "fourth")
+ wasModel, wasFresh, wasWait := CodexSideModel, codexSideFresh, codexSideWait
+ CodexSideModel = func() string { return "" }
+ codexSideFresh, codexSideWait = 0, time.Minute
+ t.Cleanup(func() { CodexSideModel, codexSideFresh, codexSideWait = wasModel, wasFresh, wasWait })
+ memory := map[string]string{"session_id": "lead-1", "x-codex-turn-metadata": `{"thread_source":"memory_consolidation","request_kind":"memory"}`}
+ beforeTheTurn(t, s, func() { codexSideAsk(s, "gpt-5.6-luna", memory) }, func() {
+ if rec := codexSubTurn(s, "fourth/gpt-6-astra", "lead-1", "", leadAsk); rec.Code != 200 {
+ t.Errorf("the switched turn: %d %s", rec.Code, rec.Body.String())
+ }
+ })
+ codexSideAsk(s, "gpt-6-luna", map[string]string{"session_id": "fork-of-lead-1", "x-codex-turn-metadata": `{"thread_source":"composer_predictions","forked_from_thread_id":"lead-1"}`})
+ if got := up.asked(); len(got) != 0 {
+ t.Fatalf("ChatGPT was asked for %v", got)
+ }
+ if reqs := old.requests(); len(reqs) != 1 {
+ t.Fatalf("the model switched from got %d requests", len(reqs))
+ }
+ if reqs := switched.requests(); len(reqs) != 3 {
+ t.Fatalf("the model switched to got %d requests, want the turn, the memory and the prediction", len(reqs))
+ }
+}
+
+// Codex with magpie as its provider asks for its memories on a model of
+// its own by its bare name (codexMemoryStandIn): the one that beats the
+// first turn after a switch goes on the model switched to, not on the
+// last turn's.
+func TestCodexMemoryStandInFollowsTheSwitch(t *testing.T) {
+ fresh(t)
+ old, switched := relayOn(t, "third"), relayOn(t, "fourth")
+ wasFresh, wasWait := codexSideFresh, codexSideWait
+ codexSideFresh, codexSideWait = 0, time.Minute
+ t.Cleanup(func() { codexSideFresh, codexSideWait = wasFresh, wasWait })
+ s := New()
+ if rec := codexCall(t, s, "third/gpt-6-astra", ""); rec.Code != 200 {
+ t.Fatalf("the old turn: %d %s", rec.Code, rec.Body.String())
+ }
+ beforeTheTurn(t, s, func() {
+ if rec := codexCall(t, s, "gpt-5.6-luna", "memory_consolidation"); rec.Code != 200 {
+ t.Errorf("memory: %d %s", rec.Code, rec.Body.String())
+ }
+ }, func() {
+ if rec := codexCall(t, s, "fourth/gpt-6-astra", ""); rec.Code != 200 {
+ t.Errorf("the switched turn: %d %s", rec.Code, rec.Body.String())
+ }
+ })
+ if reqs := old.requests(); len(reqs) != 1 {
+ t.Fatalf("the model switched from got %d requests", len(reqs))
+ }
+ if reqs := switched.requests(); len(reqs) != 2 {
+ t.Fatalf("the model switched to got %d requests, want the turn and the memory", len(reqs))
+ }
+}
diff --git a/internal/gateway/codex_memory.go b/internal/gateway/codex_memory.go
index 6c788dfa1..b346a2832 100644
--- a/internal/gateway/codex_memory.go
+++ b/internal/gateway/codex_memory.go
@@ -30,6 +30,9 @@ func (s *Server) rememberCodexTurn(r *http.Request, who, agent, kind, asked stri
return
}
s.codexTurns.Store(codexTurnKey(r, who), asked)
+ // and by its conversation, for a memory call that raced it
+ // (codexMemoryStandIn)
+ s.codexLeads.saw(r, kind, asked)
}
// isReviewCall: Codex's auto-review of an approval (the guardian), which
@@ -66,13 +69,26 @@ func freeOnChatGPT(model, plan string) bool {
// another computer — was answered 404 "magpie knows no model
// \"codex-auto-review\"" (Adam on Discord). "" for any other call, a model
// magpie serves, or a Codex that has had no turn answered here.
-func (s *Server) codexMemoryStandIn(r *http.Request, who, agent, kind, asked string) string {
+//
+// Codex starts its memories with each turn of a conversation, so a memory
+// call can come before the turn it was started with, the first after the
+// model was switched: it is read after that turn, as the app's titles are
+// (codexLeads.sideOf, beside), not on the model switched away from
+// (cybercaius on Discord).
+func (s *Server) codexMemoryStandIn(r *http.Request, who, agent, kind, asked string, body []byte) string {
if agent != "codex" || !isMemoryKind(kind) && !isReviewCall(kind, asked) {
return ""
}
if _, _, ok := provider.Resolve(asked); ok {
return ""
}
+ if isMemoryKind(kind) {
+ if m := s.codexLeads.sideOf(r, body, true); m != "" && m != asked {
+ if _, _, ok := provider.Resolve(m); ok {
+ return m
+ }
+ }
+ }
key := codexTurnKey(r, who)
if m, ok := s.codexTurns.Load(key); ok {
if m, _ := m.(string); m != "" && m != asked {
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index f509a2e15..947de8517 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -1816,7 +1816,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// that same name, went on unresolved, a 404 (Adam on Discord)
asked = grouped(at(m))
}
- if m := s.codexMemoryStandIn(r, call.Agent, agent, call.Kind, asked); m != "" {
+ if m := s.codexMemoryStandIn(r, call.Agent, agent, call.Kind, asked, body); m != "" {
asked = m
}
// a Codex subagent on the model set for Codex's subagents, whatever