From b59e4b747f70ea5ff77db84f08aa377152e532ac Mon Sep 17 00:00:00 2001 From: JoeyWu-tech Date: Tue, 27 Oct 2026 09:48:13 -0700 Subject: [PATCH] gateway: a conversation on a new account leaves out the old one's seals (#3887) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hheei (#3887): a Codex conversation with a web search in it (OpenAI's own web_search, a web_search_call in its history) failed on every turn with "HTTP 400: Codex: Encrypted content could not be decrypted or parsed. (code: invalid_encrypted_content)" once magpie had moved it to another ChatGPT account of the same routing group: after its affinity went cold ("why": "cold", over two hours on), or after the account it was on was used up or rate limited. What an account's turn wrote comes back sealed for that account (encrypted_content): its reasoning, a web search, and with Codex's output token replay on (codex-rs core/src/client.rs: only for a provider named "OpenAI", which Codex signed in reaches magpie as) each message and call. Codex hands it all back on every turn, and between ChatGPT accounts, or a ChatGPT account and an OpenAI API key, magpie sends it as it came (forVendor, 2a19245c). The account asked next can't read the first's seals and says so. serve asked again without the reasoning only (withoutReasoning), was refused again over the web search, had no compaction to leave out, and passed the 400 on. What it remembered as refused for the conversation's later turns (refusedSeals) was reasoning and compactions only, so each later turn went the same way. The relay of Codex's own sign-in (withoutUnreadable) left only the reasoning out as well. Now such a refusal is asked again without every seal but a compaction's (withoutSeals): reasoning goes whole, as before, and any other item keeps all but its encrypted_content (withoutItemSeal, the rest of it byte for byte). refused records what was taken out for the key or account that refused, and withoutRefused leaves it out of the conversation's later requests there up front, reasoning whole and the rest by its seal alone. What that one sealed itself still goes along, and a request on the account that sealed what it carries goes as it came, so a turn that doesn't move keeps OpenAI's cache and replay as before. A compaction keeps its own step (withoutCompaction after a second refusal, unless native compaction is on). The relay asks again the same way after its 400. The retry is serve's, so it holds whatever moved the conversation: an account used up, rate limited or resting, the next member of a group, routing's own pick once the affinity went cold; on the backend path (one of Codex's own models, signed in) and on /v1/responses (the codex provider's model, a group of it) alike. gateway-routing.md says so. A refusal doesn't say whose seal it couldn't read, so the account asked loses its own seals from an earlier stay in the conversation too, and they are remembered as refused, as its reasoning already was. Not changed, each as on main (#3934): a context_compaction another account sealed stays in through both steps (keepsSeal has it, compactionKinds doesn't); the relay keeps no record of what was refused, so each later turn there is refused once and asked again, and a refusal in its stream reaches Codex as it came; the relay's /responses/compact isn't asked again; the Routing view still calls such a try "another account's reasoning" (client.js and its translations). What was run (tree 326b178e, on origin/main f8cd964a, go1.26.8, linux/amd64, Linux 5.15), outside graftcp, umask 077: - TestForeignSealedItemsMoveToAnotherAccount, new: a conversation holding acct-1's sealed reasoning, web search, call and answer moves to acct-2 as acct-1 answers 429 or response.failed rate_limit_exceeded, signed in, as codex/gpt-5.5 and as group/g, acct-2 refusing with a 400 or in its stream (12 cases). acct-2 is asked with every seal, refuses, is asked again bare and answers, and the next turn asks it bare with its own seals on: ok - TestForeignSealedItemsAfterAColdSwitch, new: the same conversation moved back to acct-1 by its affinity gone cold (Why "cold"), 6 cases: ok - TestForeignSealedItemsRelayedToAnotherSignIn, new: Codex's own sign-in relayed as acct-2, the history sealed by acct-1: ok - TestSealsTakenOutLeaveTheRest, new: the exact bytes withoutSeals and withoutRefused leave (a seal first, in the middle and last in its item; compactions keeping theirs; reasoning alone taken as withoutKinds took it), and nothing taken out for another account or conversation: ok - the three new end-to-end tests with affinity.go, gateway.go, codex_backend.go and routing.go as on main (swapped in through go test -overlay, the checkout left as committed; the unit test left out, as it calls withoutSeals): 21 of 21 red. The 400 cases: "moved on: 400 {"error":{"code":"invalid_encrypted_content","message":"Codex: Encrypted content could not be decrypted or parsed.","param":null,"type":"invalid_request_error"}}", and "gone cold: 400" with the same; in the stream: "moved on: 200" and "gone cold: 200", the response.failed invalid_encrypted_content passed on to Codex; the relay: "400 {"error":{"message":"Encrypted content could not be decrypted or parsed.", ... "code":"invalid_encrypted_content"}}" - broken by hand, one at a time, each swapped in the same way, beside the tests already there for foreign seals, compactions, reasoning and output replay (TestForeignSeal*, TestForeignCompaction*, TestForeignReasoning*, TestCodexOwnModelAfterAnotherVendor, TestCodexSpentMovesToGrokWithSealedReasoning, TestCodexOutputReplay*), all green under each but where named: - serve's retry taking the reasoning only (withoutKinds(body, "reasoning")): TestForeignSealedItemsMoveToAnotherAccount (12 of 12) and TestForeignSealedItemsAfterAColdSwitch (6 of 6) red, "moved on: 400" and "gone cold: 400" with the error as on main - the relay's taking the reasoning only: TestForeignSealedItemsRelayedToAnotherSignIn red, "400 {"error":{"message":"Encrypted content could not be decrypted or parsed.",...}}" - refused recording reasoning and compactions only (seals as on main): the same 18 cases and TestSealsTakenOutLeaveTheRest red, the next turn refused once more, "then asked [{"acct-2" "message user, web_search_call 上海天气 gAAAA-acct-1-w1, function_call c1 gAAAA-acct-1-f1, ..."} {"acct-2" ...}]", and "next turn:" with the seals left on - withoutRefused taking out reasoning and compactions only: the same 19 red, with the same lines - withoutRefused dropping each refused item whole: the same 19 red, "then asked [{"acct-2" "message user, message assistant, message user, message assistant, message user, reasoning gAAAA-acct-2-r3, ..."}]", the searches and calls gone - withoutItemSeal writing the item out again (marshalPlain): TestSealsTakenOutLeaveTheRest red, "got {...}" with the web search's keys sorted, {"action":{...},"id":"ws_1",...,"type":"web_search_call"} - withoutItemSeal without its keepsSeal check: TestSealsTakenOutLeaveTheRest and TestForeignCompactionToGrok red, "grok was sent [["compaction:sealed-by-openai-compaction" "reasoning:sealed-by-openai"] []]": the compaction lost its seal in the first step instead of going in its own - the related tests (TestForeign*, TestCodexOwnModel*, TestCodexSpent*, output replay, the rewrite equivalence tests, TestAffinity*, TestNativeCompaction*, TestRemoteMagpie*, TestGatewayKey*, groups and Codex accounts): 257 passed with their subtests, none skipped (Bun 1.4.2) - go test -tags nogui -count=1 -timeout 45m ./internal/gateway (log kept), Bun 1.4.2: 5418 passed with their subtests, 3 skipped, and one red, TestPluginToldWhereTheAgentWorks (#3675): "not in one: the plugin was told "/tmp/TestPluginToldWhereTheAgentWorks191044475/005", git "yes"; want "/tmp/TestPluginToldWhereTheAgentWorks191044475/005", "no"". It is red the same alone, and with the four code files as on f8cd964a: this box has an empty /tmp/.git, and GitOnDisk counts a .git in any folder above. - read against main's 7f0f71a0 (#2481) and fff05e55 (#2725), which change code beside this: 7f0f71a0 puts the route on two of the relay's record exits, which come after withoutUnreadable has chosen the body asked again; fff05e55 changes only whether Codex's compaction trigger is kept native (plannedCarrier), not serve's retry or the step it skips for a provider compacting natively (compactsNatively), so a trigger it now has magpie summarise goes through serve and the same retry. Neither changes what withoutSeals or withoutUnreadable do. - go test -tags nogui -count=1 -timeout 45m ./... (log kept), Bun 1.4.2: 69 packages ok and 7 red, none in what this changes; gateway's only red is TestPluginToldWhereTheAgentWorks (#3675), the new tests pass in it. The reds: agent TestInstalledVersion, TestCopilotFolderFromAnIDEPluginIsNotTheCLI, TestQoderSettingsFromAnIDEPluginIsNotTheCLI and TestOmpDetectedWithPiDir (#3141), the two Reasonix tests (#3641) and TestWSLColdPlaceOpensNothing (#3924); edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask 077, #3640); gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie (#3649); provider TestCodexAppServersOnHome (#3906), then "close of synctest channel from outside bubble" (#3632); tui TestTUIFetchesSubscriptionModels/agent (#3919). - gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go build -tags nogui for linux and darwin, and go vet and go build for windows without the tag: exit 0 each. go vet and go build without the tag on linux: exit 1 (this box has no GTK or WebKitGTK dev packages). Not tried: real ChatGPT or OpenAI accounts. Whether the ChatGPT backend takes a web_search_call with neither its id (magpie's Codex account route sends none, as on main) nor its seal; hheei's 200 was OpenAI's Responses API with the id kept. Whether one account refuses another's replayed message and call seals at all (the fake does; if it reads them, they are still taken out on a hop, where the conversation's cache is gone anyway). OpenAI refusing in the stream: the fake does, as xAI may; hheei's refusal came as a 400. An OpenAI API key as the next member of a group: forVendor keeps the seals for *openai.com only, so a fake on 127.0.0.1 can't stand in for it; it reaches the same retry in serve. Nor magpie's summary of a Codex compaction after a move: codexCompact asks through serve, so the same retry should apply, but no test drives it. Ported onto origin/main 5ee5274bd from yinwu01/magpie 2d764b1c (posted on #3887, sha256 d9185e84...). Conflicts resolved by hand: main had since grown noteRefused (also used by reasoning_carry.go's refuseCarried), so refused(key, who, sent, left) now hands it the seals sent minus those left; foreignReasoning keeps main's broader pattern; foreign_seal_test.go keeps main's TestForeignSealAzureSummary and TestForeignSealGrokRelayCompactionBlob beside the four new tests; the Affinity row and the new bullet in gateway-routing.md were merged into main's text. What was run for the port (mote, macOS, go1.26.8): - go vet -tags nogui ./internal/gateway, and go test -tags nogui -count=1 -run 'TestForeign|TestSeals|TestCodexOutputReplay| TestCodexOwnModel|TestCodexSpent|TestRefused|TestReasoningCarr| TestWithout|TestNativeCompaction' ./internal/gateway: ok - the three new end-to-end tests on 5ee5274bd (old code, the unit test left out as it calls withoutSeals): all red, TestForeignSealedItemsMoveToAnotherAccount and ...AfterAColdSwitch "moved on: 400 {...invalid_encrypted_content... Codex: Encrypted content could not be decrypted or parsed.}" and "gone cold: 400", ...RelayedToAnotherSignIn "400 {...Encrypted content could not be decrypted or parsed...}" Batch run, at tree 104d75f0a (the twelve coffemon ports together, on origin/main 7d022bdb6), mote, macOS, go1.26.8: - go test -tags nogui -count=1 -timeout 45m on the packages the batch changes (agent, autostart, daemon, gateway, library, proc, provider, sessions, testenv, tui, gui): ok each. - GUI, node --test with Playwright 1.62.0, Chromium and WebKit: library-*.test.cjs and i18n-keys.test.cjs, 1044 of 1044 pass. - gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... and go build ./...: ok at cdd7c8e46, the same batch on origin/main 00098f12b one rebase before. - The whole go test ./... at cdd7c8e46: 86 packages ok, one red, internal/cli TestEveryRouteHasACommandOrIsNamed (GET /api/context/reply has no command), red on main too (#5026). - Linux (wsl-run, Ubuntu 24.04, at 339055896, the batch on f4c664a09): proc, autostart, testenv, tui ok; agent: only TestGrokInstalled red (#3548); #4033's proc.Look reds (Zed, Copilot, Qoder, Cursor, Omp) pass. - Windows (win-run, Windows 11, at 339055896): proc, autostart, testenv, tui ok; library and agent red in the same tests as on origin/main f4c664a09 (#4115, #1827, #4786; #5068, #5069, #5070 filed now). - Rebased onto origin/main fb1f4856a (three commits, no file in common with the batch) and run again at the pushed tree: gofmt -l nothing, go build ./... and go vet ./... ok; go test -tags nogui sessions, agent, autostart, tui, proc, testenv ok; i18n-keys and library-* 1044 of 1044 pass. - Not run before the push: the whole GUI suite (a run at cdd7c8e46 was cut off at 1170 of ~1174 tests when mote rebooted; it runs again after the tag and any red is filed). --- docs/subsystems/gateway-routing.md | 3 +- internal/gateway/affinity.go | 118 ++++++-- internal/gateway/codex_backend.go | 7 +- internal/gateway/foreign_seal_test.go | 381 ++++++++++++++++++++++++++ internal/gateway/gateway.go | 24 +- internal/gateway/reasoning_carry.go | 2 +- internal/gateway/routing.go | 4 +- 7 files changed, 492 insertions(+), 47 deletions(-) diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 8f6355ef7..cacc13917 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -39,7 +39,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). DashScope (`dashScope`: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (`dashScopeDraws`) on its own API, `/api/v1/services/aigc/multimodal-generation/generation` (`drawDashScope`), as docs.qwencloud.com gives it: the prompt as the user message's `text` part after an edit's images as `image` parts (a URL or data URL), `n`, `size` as `W*H` (a ratio is a 400 that says to give WxH), `watermark: false`, no mask; the images are read from every `output.choices[].message.content[].image` (`readDashScopeAnswer`), and a refusal says its `message` and `code`. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, `TestDashScopeDrawsOnItsOwnAPI`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. A group's Add a model picker offers each provider's image models, `/api/groups`' `drawers` (`gateway.Drawers` less hidden ones, apart from the chat `models`), said as such and with no reasoning level (jzw690 on X); such a member draws whether or not its provider's picks name it, as picks are of chat models (`provider.FindDrawingGroup`, used by `GroupDraws`, `resolveDrawing` and the image group's turns; video keeps `FindGroup`), and the group is no model agents are offered. `TestImageGroupOfUnpickedImageModelsDraws`, `TestGroupEditorOffersImageModels`, `group-pick-drawers.test.cjs`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`draw_dashscope.go`](../../internal/gateway/draw_dashscope.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | -| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`conversationID`), and a Claude Code subagent's apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its sealed reasoning was refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | +| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`conversationID`), and a Claude Code subagent's apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its seals were refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | | One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A large body (64KB or more, or of no stated length) is pinged too, as a silent connection takes a body that fits its send buffer, but its ping's answer is queued behind the body's own DATA, so on a slow uplink a working connection loses it (#3909: a ~680KB turn on a 2-10KB/s uplink failed every try). Such a body whose connection was dropped for a lost ping is sent once more, through `GetBody`, on a new connection that is not pinged and is given up on when a write moves no bytes for a minute (`uploadTransport`); for 30 minutes after, large bodies go there at once (`drawsApart.slow`; `TestUploadStillUnderwayIsNotCutByHealthPing`, `TestSlowUplinkSkipsTheLostTry`, `TestLargeBodyOnSilentConnectionIsSentAgain`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`, `catalog.WrongEndpoint`: the English wordings and AgentRouter's Chinese one, #3766, read escaped too; a model's test reads them as well, see [Providers and accounts](providers-accounts.md)) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. It goes to the first API `usable` gives, Chat where the provider has a Chat URL too, except one that asks an image's size or shape (`generationConfig.imageConfig`), which only a Gemini API takes: that one is translated on the Gemini URL (#3820, `TestGeminiImageConfigGoesToTheGeminiAPIBesideChat`). | [`gateway.go`](../../internal/gateway/gateway.go) | | Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) A request outside the chat path gets a route of its own too ([`media_route.go`](../../internal/gateway/media_route.go), `sideRoute`): an image (`images`, each account `drawOnAccounts` asks a try), a video's start (`videosCreate`; its polls and download are the same video and add none) and an embedding, rerank, transcription or speech (`retrieve`). Each try's key or account is put in `Order` so the page finds its seat, the route's `Kind` stays empty, and the one usage row names it in `RouteID` (zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's requests and not on Routing; `TestVideoIsOnRoutingOnce`, `TestImageIsOnRouting`, `TestEmbeddingAndRerankAreOnRouting`). | | Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the body is kept as it went and masked when `PromptText` first reads it, so the request itself never waits on masking (#3973). `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`. Once a body is dropped, or magpie quits, the GUI reads the request archive's copy when the route names one (`Route.Archive`; wangbinyq on Discord): `ArchivedPromptText` parses it the same way and masks it as the body in memory is (`maskedCopy`), and the reply beside it comes from `ReplyBody` (the Recent calls' reply) or the archive's, read into pieces by `ReplyPieces` and masked alike (`prompt_reply.go`, served as `/api/context/reply`). A body or reply that can't be masked shows nothing, and one the archive cut short isn't parsed (`TestArchivedPromptTextIsMasked`, `TestReplyPiecesAreMasked`, `TestContextTextFromTheArchive`). It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) | @@ -264,6 +264,7 @@ recorded as a prediction failure (`noPrediction`). - A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them — one that carries its text in it (content parts, another vendor's shape) made over into one magpie could have, its text a summary and nothing sealed, in a reply translated or relayed as it came, for the client to store and replay where OpenAI's rules hold even with magpie disconnected (#2855, the reporter's rollout: 25 reasoning items a DeepSeek phase had left, each with its text in it and a seal of the vendor's own, stuck every later turn on OpenAI with a 400 `array too long` nothing of magpie's could strip then); any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. The summary request magpie makes offers none either: `codexInputAs` sends `tools: []` and leaves out the `additional_tools` input item, where Codex's Responses Lite (the entry of a ChatGPT account's gpt-6 model, copied from Codex's own) puts every tool; left in, the model may call one in place of the summary (the likely cause of WuSix's codex/gpt-6-astra "the model wrote no summary" on Discord, not confirmed on a real reply), and a reply with no summary says what it held instead (`answeredWith`). A reply that called a tool instead (`calledTool`) is asked once more with the conversation as text (`plainCompact`), and compacted locally when that writes no summary either: a model deep in an exchange of calls goes on with it whatever it is offered (Lucy on Discord: DeepSeek through group/auto-deepseek-v4-1-flash answered reasoning and an `exec_command` call 3 times in a row; `TestCodexCompactToolCallAsksAgainAsText`, `TestCodexCompactToolCallEveryTimeCompactsLocally`, over Chat, Responses and Messages, a group and a single model). When a provider answers its summary request 404, 405 or 501 (`lacksEndpoint`), or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). So does a summary request refused for its size (`summaryTooLarge`): a 413 byte cap, or an overflow of the model's window. Codex's remote compaction trims only by its own token estimate against the catalog's window and asks nothing smaller after either, so the turn's `context_length_exceeded` led to a compaction refused the same way, every time, and the session could neither compact nor go on (celestial_eagle_99230 on Discord: DeepSeek's own API, 1M window, answered 413 "Failed to buffer the request body: length limit exceeded"). The text ask leaves images out, keeps the ends of a long output and the latest 400K characters. `TestCodexCompactTooLargeAsksSmaller`, `TestCodexCompactTooLargeCompactsLocally`, `TestCodexCompactOtherRefusalStays`. Any other failure goes back with its status, said as the compaction's with who answered it (`compactFailed`: "compaction: (, ) answered the summary request 502 Bad Gateway: …"), the vendor's code, param and Retry-After kept. Not so the compaction Codex runs before a turn on another model, on the model the thread was on: a switch to a smaller window (`compaction.reason` `model_downshift` in the turn metadata) or to another compaction hash (`comp_hash_changed`), the only places Codex names either (`maybe_run_previous_model_inline_compact` in codex-rs `core/src/session/turn.rs`). When it fails, Codex asks the turn's own model instead only under its provider named "OpenAI" (`compact_model_fallback.rs`). Under magpie's provider, the one Codex has while its sign-in is used up (codex.out), the refusal was the turn's, and every turn of that thread asked the used-up account again, restarts or not, while a new thread worked (hiwise_aigc on X). Off `CodexPath`, `codexCompact` compacts such a failure locally (`previousModelCompaction`), whatever the failure, the compaction-failure hold included, and the thread goes on on the model it was switched to. On `CodexPath` the provider is Codex's own "OpenAI", which asks the turn's model itself, so the failure goes back as before. `TestCodexLeavingModelCompactsLocally`; Codex 0.162.1 in a sandbox sent the old model's `compaction_trigger` to `/v1` and failed the turn on a 429, and went on to the new model once the trigger was answered. A compaction relayed to OpenAI (`/responses/compact` on Codex's own model, as a `/responses` turn) that OpenAI answers with an error status and an empty body, which Codex shows as "unexpected status 502 Bad Gateway: Unknown error", or with a web page, is said in words naming the model, the status, and the account it went to (`codexSaidNothing`, outrageous_piglet on Discord); an error OpenAI says in JSON goes as it came. `TestCodexOwnCompactFailureIsSaid`, `TestCodexCompactFailureSaysCompaction`, `TestCodexCompactNoEndpointCompactsLocally`. So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301). A summary is wanted only whole (`askWhole`, `holdWriter.wantWhole`): its stream is held to its end, not let through at its first words, so a reply cut short (`errEndedShort`), failed halfway (a 429 "Individual quota reached" after some of it) or ended `incomplete` (`endedIncomplete`, `incompleteReply`) fails over to the next candidate like a failure before any of it, and rests the account as that failure would; one that reached its output limit rests nobody. With nobody left, `codexCompact` answers 502 and never hands Codex the words before the cut as the summary (#2274, huangzuomin: Antigravity cutting each summary short) — but one whose stream merely broke off, with nothing failed or incomplete in it, is followed by magpie's own summary (#3526, Edward4226: Codex told a 502 asked the same huge summary over three times and the guard then held the conversation), as when no model can be asked at all. So is a translated summary serve found cut and answered 502 "the reply ended before it was complete" (`summaryEndedShort`).. Codex with context_management's experimental mode compacts in the background at every step while the conversation is over its threshold and drops a failed compaction without a word, so a conversation whose summaries keep failing is asked again every few seconds, each paying for the whole history (1169 compactions in 6 hours there). After `compactFailsMost` (3) failed summaries in a row of one conversation (`prompt_cache_key`) on one model, each within `compactHeldFor` (5 minutes) of the last, the next is answered at once with a 400 naming the last failure, which Codex doesn't ask again, and no model is asked until 5 minutes have passed (`compactFails` in [`codex_compact_guard.go`](../../internal/gateway/codex_compact_guard.go)); a summary that comes clears the count, and a sign-in's 401 or 403 isn't counted. `TestCodexCompactCutSummaryFailsOver`, `TestCodexCompactCutSummaryIsNoSummary`, `TestCodexCompactKeepsFailingIsHeld`. - An `output_text` annotation without the offsets OpenAI's schema wants of its kind (a `url_citation` or `container_file_citation` with no `start_index`/`end_index`, as Volcengine Ark's Responses endpoint writes its url citations) cannot be replayed where that schema holds: the ChatGPT backend refuses the whole request, every turn of the thread, with "Missing required parameter: 'input[n].content[m].annotations[k].start_index'" (#4921; `withoutOffsetlessCitations` in [`codex_backend.go`](../../internal/gateway/codex_backend.go), the same leaving-out as a reasoning item's text, #1411). A whole reply streamed as the vendor's own events drops such an annotation in every place a client reads one (`dropOffsetlessCitations` beside `responsesWholeEvents` in [`whole_stream.go`](../../internal/gateway/whole_stream.go), the #2855 rule: what magpie hands a client must be something it could send again); a history that carries one goes to the ChatGPT backend, OpenAI's API and a relay that has turned one away without it, and a refusal naming the parameter is asked again without it (`refusesCitationOffsets`). The text, a citation with its offsets, and a `file_citation` or `file_path`, which OpenAI places by a single `index`, go as they came (`TestCitationsWithoutOffsetsAskedAgainWithout`, `TestWholeAsStreamDropsCitationsWithoutOffsets`, `TestCitationsWithOneIndexKept`). - A reasoning item with its text in it (`content` parts: DeepSeek's Responses API writes `reasoning_text`, relayed to Codex as it came) is another vendor's. OpenAI's API and the ChatGPT backend take a reasoning item's `content` only empty, and refuse the whole request over one with 400 "Invalid 'input[n].content': array too long. Expected an array with maximum length 0" (`array_above_max_length`). Codex hands the item back on every later turn, so it never goes to them: for one of Codex's own models, `codexInput(body, false)` leaves it out (and a reasoning item with nothing sealed in it) on `/backend-api/codex`'s `/responses` and on `/responses/compact`, before Codex's own sign-in, its API key or a magpie Codex account (`compactOn`) is asked. Codex compacts a thread before its first turn back on its own model, and a refused compaction shows as that turn's error (jue on Discord). `passthrough` leaves it out for OpenAI, Azure OpenAI and a Codex account (`withoutReasoningText`), and for any other upstream once it has refused one (`refusesReasoningText`, `reasoningTextRefused`, #1411). OpenAI's own sealed reasoning (`encrypted_content`, no text) stays, and a DeepSeek model (`replaysReasoning`) still gets the text. `TestForeignReasoningNeverReachesOpenAI`, `TestReasoningTextLeftOutWhereRefused`, `TestReasoningTextNotSentToCodexAccount`. +- A conversation that moves to another key, account or vendor carries what the one before sealed (`encrypted_content`): its reasoning, and the sealed copy an answer's other items may carry: a web search's (`web_search_call`), and with Codex's output token replay on, each message's and call's (Codex keeps those for a provider named "OpenAI" only, and signed in it reaches magpie as that provider). `forVendor` takes the copies out for a vendor not OpenAI's, reasoning and compactions aside; between ChatGPT accounts, or a ChatGPT account and an OpenAI API key, all of it goes as it came. One that can't read it says so (`foreignReasoning`: OpenAI's `invalid_encrypted_content`, "could not be verified" of reasoning and "Encrypted content could not be decrypted or parsed." of a web search; xAI's "Could not decrypt"), as a 400 or as the stream's error, and `serve` asks it again without them (`withoutSeals`): a reasoning item goes whole, any other item keeps all but its `encrypted_content` (`withoutItemSeal`), and a compaction keeps its seal. Refused again, or with nothing else sealed, the compaction OpenAI sealed goes (`withoutCompaction`), unless native compaction is on (below). What was taken out is remembered by its hash for the conversation and the key or account that refused it, for `stickKeep` (`refused`, `refusedSeals`), and its later requests there leave it out up front (`withoutRefused`); what that one sealed itself still goes along, and a request that stays where its seals were made goes as it came. A refusal doesn't say whose seal it couldn't read, so every one goes, the asked one's own from an earlier stay in the conversation too, and all are remembered. It is the same whatever moved the conversation: a key or account resting, used up or rate limited, the next member of a group, or routing's own pick once its affinity went cold, on the backend path and on `/v1/responses` alike (#3887, hheei: after such a move a `web_search_call` another ChatGPT account of the group had sealed was refused, only the reasoning was left out, and every turn failed). Codex's own sign-in, relayed as it came (`codexUpstreamOn`), is asked again the same way when the backend answers its `/responses` with a 400 (`withoutUnreadable`, after the item the refusal names, if any); it keeps no record of what was refused, and a refusal in the stream reaches Codex as it came. `TestForeignSealAcrossGroupMembers`, `TestForeignSealGrokToCodexAccount`, `TestForeignSealedItemsMoveToAnotherAccount`, `TestForeignSealedItemsAfterAColdSwitch`, `TestForeignSealedItemsRelayedToAnotherSignIn`, `TestSealsTakenOutLeaveTheRest`. - Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The trigger is kept only when a key or account the request would go over (the provider's and its fallbacks', or a group's members', held and capped ones too, not one whose own list lacks the model) can be asked it on Responses (`plannedCarrier`, read from `perKeyBarred` without weighing, so a provider routed in turn isn't moved along by the decision). When the vendor lists the model only to keys that speak no Responses there, a key set to Chat say, `codexCompact` gives magpie's summary through the listed key, as with native compaction off; before, the trigger was kept and refused 400 `carrierError` with no upstream asked (#2725, ggbdpq; `TestNativeCompactionTriggerSummarisedWhenNoListedKeyCarriesIt`, `TestNativeCompactionTriggerThroughTheListedKeyThatCarriesIt`, `TestNativeCompactionDecisionLeavesTheTurnsAlone`). The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); a writer whose own list has since dropped the model is tried still, as the last resort an account whose list lacks the model is — it sealed the model's compaction, and no other can read it (`planned.unlisted`, `TestNativeCompactionWriterWhoseListLacksTheModel`, #2642: it was refused as "switched off, removed, or no longer serves" though it was on, and switching it on changed nothing). With the writer gone from the candidates, magpie answers 400 `checkpointError` with the reason its settings give (`checkpointGone`: the provider removed, the account signed out, its sign-in lapsed, paused while others are on, switched off, kept from the model in Names, prices & levels, the key off or gone, the model disabled, or the model or group asked for not going to it), what lets the conversation go on, and whether native compaction is on for the writer's provider now, and never sends it to another key, drops it, or summarises it in its place (`TestNativeCompactionWriterGoneSaysWhy`). One of Codex's own models asked on the backend path is decided as a magpie model is when magpie's Codex accounts serve it (`codexAccounts`): the trigger is kept only with the codex provider's native compaction on, else `codexCompact` gives magpie's summary, which any account reads, and no writer is recorded (#2582, ump45nose; before, every such compaction was sealed natively whatever the setting, and the conversation was held to its account; `TestCodexOwnModelCompactionHonoursTheToggle`). Codex's own sign-in alone, relayed as it came, still compacts natively, unrecorded, as does `/responses/compact`; but a request carrying a compaction magpie recorded the writer of goes through routing even then (`codexSealedFor`), so with the writer switched off the one account left isn't sent it. A legacy `/responses/compact` carrying one is judged at its passthrough (`sealedCompact`): the writer on in magpie answers it signed as the writer — its own seal while the sign-in can be asked, a key's seal, a request signing with its own `chatgpt-account-id`, or an unreadable sign-in state relays as it came — and a writer gone is refused with `checkpointError`'s reason, the same words as on `/responses` (`TestNativeCompactionCompactJudgesItsWriter`, #2727). The writer matched is the account user the record holds, so two Team seats of one email read as one and such a compact relays as it came. A gateway key held to some accounts (#905) is asked of the account the compact goes to (`compactSigninHeld`): the writer when it answers it, so a writer the key may not use is refused 403 (`sealedCompactHeldError`) with nothing asked, and one it may use answers though the sign-in isn't the key's (`TestNativeCompactionCompactKeepsTheKeysAccounts`). With the writer held at its usage cap or for credits it may not spend, the answer is 429 `checkpointCappedError` (record `checkpointCappedRecord`, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; `TestNativeCompactionWriterAtItsCap`). `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A route carrying a compaction names its sealer (`Route.Compaction`), and Routing says that is why no other account was asked, not that it is "the only account on" for the model (#2639; `TestNativeCompactionRouteNamesItsWriter`, `routing-compaction.test.cjs`). A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`. - A compaction magpie answers itself (`codexCompact`: a magpie model, Codex's own models through magpie's Codex accounts, a CC Switch table) goes to Codex as a `compaction` item whose `encrypted_content` is `magpie1:` and the summary in base64 (`codexsummary.Encrypted`), and `codexInputAs` sends Codex's own summary message in its place (`codexsummary.Message`: Codex's summary prefix, a newline and the summary, as a user message). Codex keeps the item in its rollout and replays it, and OpenAI refuses it once Codex talks to OpenAI itself (`invalid_encrypted_content`, LukeMa on X). So `sessions.PortCodexRollouts` writes that same message into the rollouts in its place ([`codex_portable.go`](../../internal/sessions/codex_portable.go)). A reasoning item carrying Claude's block (`magpie-claude1:`, above) is written as its summary, as the gateway sends it to OpenAI (`TestPortLineDropsClaudeBlocks`). It changes only magpie's items, keeps every other line's bytes and the file's line count, mode and time, and drops an unreadable item together with its `replacement_history_metadata` entry. Every rewritten line keeps its length (`fitLine`: a shorter one padded with spaces after its JSON, a longer one in a paginated rollout not written), as Codex keeps places in a rollout by byte: a fork's `history_base.end_byte_offset` and the state database's turn and projection offsets. A shorter parent left a fork's place past its end, and Codex refused to open the fork ("cutoff byte offset is past the source rollout", xybio on Discord); once per Codex home a pass sets each such fork's place again from the ordinal it names (`repairLineages`). `MoveCodexProvider` keeps the session_meta line's length the same way and refuses a longer provider id for a paginated rollout. It and `MoveCodexThreads` (Codex stepping off magpie) hold the thread's writer lock as Codex's own archive does, from before a file is copied until the thread's row has moved: a Codex that has the thread open writes on to the file it opened, and what it wrote after a move was lost (#3751). Such a thread is refused as one written to in the last minute is (`ErrActive`), and a Codex home without writer locks moves as before. A pass publishes as Codex publishes a compressed rollout: under `thread-writer-locks/.coordination.lock`, only with the thread's lock free, through a temp file and a rename. A thread a Codex has open is left for a later pass, and a Codex home without writer locks is left alone. It runs 2 minutes after the GUI or `magpie serve` starts and every 10 minutes after, on Codex Disconnect (3s), and as the GUI quits (3s). Each pass reads what changed since the last whole pass, plus what was held (`codex-portable.json`). A ported thread was resumed by Codex 0.162.1 against an upstream that refuses `magpie1:` as OpenAI does. Not tried: a Codex in a WSL distro, whose locks this machine can't take, so it is skipped. `TestPortCodexRollouts*`, `TestPortedCompactionReadsTheSame`. - A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's shape taken off (`fromLite`): its `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), its `reasoning.context` left out, its Lite marker removed from `client_metadata` (`withoutLiteMetadata`), and its `X-OpenAI-Internal-Codex-Responses-Lite` header not sent on (`liteKept`). A Codex websocket turn repeats the marker in `client_metadata`; leaving it beside a removed `reasoning.context` made a downstream Responses relay forward an inconsistent Lite request, which its ChatGPT backend refused with "requires `reasoning.context` to be `all_turns`". A subagent a Lite lead (gpt-6.1-sol) spawns on another model comes in that shape, its model name alone changed, and OpenCode Go's DeepSeek answered it 503 "Endpoint is unavailable" (TangForX on X, `TestLiteSubagentLeavesLite`). Also the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). That holds when Codex offers `web_search` too: the request is relayed with it, not translated for magpie's search (`searchedForIt`), which merged the developer messages into `instructions`, sent `apply_patch` as a function, left `web_search` out and added `max_output_tokens` (`codexAsSent` in `route`; maralica on Discord). `spawn_agent`'s description is still widened with the catalog's models (`spawnAgentModels`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`, `TestCodexAsSentWebSearch`, `TestFromLiteRemovesOnlyTheWebsocketLiteMarker`, `TestCodexTitleRelayKeepsLiteShapeConsistent`. diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index b361bb35e..283966574 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -1022,7 +1022,9 @@ func unanswered(key string, c candidate) { // foreignReasoning is how a vendor refuses reasoning another account (or // organization, or vendor) sealed: OpenAI's "The encrypted content for -// item rs_… could not be verified", invalid_encrypted_content; xAI's +// item rs_… could not be verified", invalid_encrypted_content, and for a +// web search another ChatGPT account ran "Encrypted content could not be +// decrypted or parsed." (#3887); xAI's // (Grok's API and a SuperGrok account alike) "Could not decrypt the // provided encrypted_content. Ensure the value is the unmodified // encrypted_content from a previous response."; Azure's (through a relay @@ -1037,12 +1039,13 @@ func unanswered(key string, c candidate) { var foreignReasoning = regexp.MustCompile(`(?i)invalid_encrypted_content|invalid[ _]encrypted[ _](summary|content)|encrypted[ _]content.{0,80}could not be (verified|decrypted)|could not (decrypt|verify).{0,40}encrypted[ _]content|could not (decode|decrypt).{0,20}compaction[ _]blob`) // refusedSeals remembers, per conversation and the key or account that -// refused it, the sealed reasoning another one wrote. Codex hands every -// earlier turn's reasoning back on each request, so once a conversation -// has moved, what was sealed before it moved is left out of its later -// requests there up front, rather than refused and asked again each turn. -// Reasoning the one it moved to sealed itself still goes along, for its -// cache and its train of thought. +// refused it, what another one sealed: its reasoning, and the sealed copy +// output token replay keeps of each message, call and web search (#3887). +// Codex hands every earlier turn's items back on each request, so once a +// conversation has moved, what was sealed before it moved is left out of +// its later requests there up front, rather than refused and asked again +// each turn. What the one it moved to sealed itself still goes along, for +// its cache and its train of thought. var refusedSeals = struct { sync.Mutex m map[string]sealsRefused // scope|conversation|who → what it refused @@ -1053,7 +1056,7 @@ type sealsRefused struct { seals map[[sha256.Size]byte]bool } -// sealedItem is what's read of an input item to tell sealed reasoning. +// sealedItem is what's read of an input item to tell what it has sealed. type sealedItem struct { Type string `json:"type"` Enc string `json:"encrypted_content"` @@ -1062,14 +1065,15 @@ type sealedItem struct { // sealedKinds are the input items a vendor seals for itself: its // reasoning, and the compaction a conversation's earlier turns were // folded into (OpenAI's, when Codex compacts on its own models; magpie's -// own is text by the time a request is sent). +// own is text by the time a request is sent). Refused, they go whole; +// any other item loses its sealed copy alone (withoutItemSeal). var sealedKinds = map[string]bool{"reasoning": true, "compaction": true, "compaction_summary": true} var compactionKinds = []string{"compaction", "compaction_summary"} -// seals are the sealed reasoning and compactions (encrypted_content) in a -// Responses request's input, of these types. -func seals(body []byte, kinds ...string) [][sha256.Size]byte { +// seals are what is sealed (encrypted_content) in a Responses request's +// input, item by item. +func seals(body []byte) [][sha256.Size]byte { var q struct { Input []sealedItem `json:"input"` } @@ -1078,17 +1082,22 @@ func seals(body []byte, kinds ...string) [][sha256.Size]byte { } var out [][sha256.Size]byte for _, it := range q.Input { - if slices.Contains(kinds, it.Type) && it.Enc != "" { + if it.Enc != "" { out = append(out, sha256.Sum256([]byte(it.Enc))) } } return out } -// refused notes that who turned away the sealed items of these types in -// body, in the conversation key names. -func refused(key, who string, body []byte, kinds ...string) { - noteRefused(key, who, seals(body, kinds...)) +// refused notes, in the conversation key names, that who turned away the +// seals taken out of sent, the request it refused, to make left, the one +// asked in its place. +func refused(key, who string, sent, left []byte) { + kept := map[[sha256.Size]byte]bool{} + for _, s := range seals(left) { + kept[s] = true + } + noteRefused(key, who, slices.DeleteFunc(seals(sent), func(s [sha256.Size]byte) bool { return kept[s] })) } // noteRefused notes that who turned away the sealed items of these hashes @@ -1119,9 +1128,9 @@ func noteRefused(key, who string, ss [][sha256.Size]byte) { } } -// withoutRefused takes out of a Responses request the sealed reasoning -// and compactions who already refused in this conversation; the rest -// stays as it is. +// withoutRefused takes out of a Responses request what who already +// refused in this conversation: sealed reasoning and compactions whole, +// any other item's sealed copy alone; the rest stays as it is. func withoutRefused(key, who string, body []byte) ([]byte, bool) { k := key + "|" + who refusedSeals.Lock() @@ -1142,15 +1151,21 @@ func withoutRefused(key, who string, body []byte) ([]byte, bool) { if !isList { return nil, false } - kept := items[:0:0] + kept, changed := items[:0:0], false for _, it := range items { var t sealedItem - if decodeJSONView(it, &t) == nil && sealedKinds[t.Type] && t.Enc != "" && r.seals[sha256.Sum256([]byte(t.Enc))] { - continue + if decodeJSONView(it, &t) == nil && t.Enc != "" && r.seals[sha256.Sum256([]byte(t.Enc))] { + if sealedKinds[t.Type] { + changed = true + continue + } + if b, ok := withoutItemSeal(it); ok { + it, changed = b, true + } } kept = append(kept, it) } - if len(kept) == len(items) { + if !changed { return nil, false } q["input"], _ = json.Marshal(kept) @@ -1158,11 +1173,56 @@ func withoutRefused(key, who string, body []byte) ([]byte, bool) { return b, err == nil } -// withoutReasoning takes the sealed reasoning out of a Responses request's -// input — what another account wrote and this one can't read. What was -// said and done stays; only the model's private notes to itself go. -func withoutReasoning(body []byte) ([]byte, bool) { - return withoutKinds(body, "reasoning") +// withoutSeals takes out of a Responses request's input what is sealed, +// but a compaction, for one that can't read what another account sealed: +// the sealed reasoning, the model's private notes to itself, and the +// sealed copy output token replay keeps of each item answered, a message, +// a call or a web search (#3887, hheei: the reasoning alone went, and the +// web search another ChatGPT account ran was refused again). What was +// said and done stays. +func withoutSeals(body []byte) ([]byte, bool) { + var q map[string]json.RawMessage + if decodeJSONView(body, &q) != nil { + return nil, false + } + items, isList := inputList(q["input"]) + if !isList { + return nil, false + } + kept, changed := items[:0:0], false + for _, it := range items { + var t struct { + Type string `json:"type"` + } + if decodeJSONView(it, &t) == nil && t.Type == "reasoning" { + changed = true + continue + } + if b, ok := withoutItemSeal(it); ok { + it, changed = b, true + } + kept = append(kept, it) + } + if !changed { + return nil, false + } + q["input"], _ = json.Marshal(kept) + b, err := marshalJSON(q) + return b, err == nil +} + +// withoutItemSeal is an input item without its sealed copy +// (encrypted_content), every other byte as it came; false for one with +// nothing sealed, and for reasoning and a compaction (keepsSeal), whose +// seal is all there is of them. +func withoutItemSeal(it []byte) ([]byte, bool) { + if keepsSeal[string(memberOrNil(it, "type"))] { + return nil, false + } + if s, ok := stringBytes(memberOrNil(it, "encrypted_content")); !ok || len(s) == 0 { + return nil, false + } + return withoutTopMember(it, "encrypted_content"), true } // withoutCompaction takes out of a Responses request's input the sealed diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 0dcaac480..51a92f073 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1754,8 +1754,9 @@ func codexRelayedAccount(base string, h http.Header, on *provider.Provider) (pro var unreadableItem = regexp.MustCompile(`(?i)(?:encrypted content for item|item with id|referenced reasoning item) '?([A-Za-z]+_[A-Za-z0-9_-]+)'?`) // withoutUnreadable is body without what OpenAI's refusal msg says it -// can't read: the item it names, the reasoning another account sealed, or -// a member of Codex's passthrough it doesn't know. +// can't read: the item it names, what another account sealed +// (withoutSeals: a web search's too, #3887), or a member of Codex's +// passthrough it doesn't know. func withoutUnreadable(body, msg []byte) ([]byte, bool) { if f, ok := refusedPassthrough(msg); ok { // a member of Codex's passthrough the backend doesn't know yet @@ -1771,7 +1772,7 @@ func withoutUnreadable(body, msg []byte) ([]byte, bool) { } } if foreignReasoning.Match(msg) { - return withoutReasoning(body) + return withoutSeals(body) } return nil, false } diff --git a/internal/gateway/foreign_seal_test.go b/internal/gateway/foreign_seal_test.go index 3aca858d9..235ab42bc 100644 --- a/internal/gateway/foreign_seal_test.go +++ b/internal/gateway/foreign_seal_test.go @@ -503,3 +503,384 @@ func TestForeignSealGrokRelayCompactionBlob(t *testing.T) { t.Fatalf("next turn sent %q, want one request without the seal", got) } } + +// openaiUndecryptable is what OpenAI told hheei (#3887) of a web search +// another ChatGPT account ran, with code invalid_encrypted_content, and +// magpie passed on as "Codex: Encrypted content could not be decrypted or +// parsed.". It names no item. +const openaiUndecryptable = "Encrypted content could not be decrypted or parsed." + +// accountSealer is the ChatGPT backend behind several of Codex's +// accounts, told apart by chatgpt-account-id. Each seals what it writes +// as "gAAAA--…" and reads no other account's seal: neither its +// sealed reasoning nor, with output token replay, the sealed copy of a +// message, a call or a web search. It refuses one sealed elsewhere as a +// 400, or in the stream after the backend's first events: reasoning as +// openaiUnverifiable, anything else as hheei was told. An account in out +// answers as that says instead. +type accountSealer struct { + stream bool + mu sync.Mutex + out map[string]func(w http.ResponseWriter) + asked []sealedAsk +} + +// sealedAsk is a request accountSealer was sent: the account, and its +// input as heldItems reads it. +type sealedAsk struct{ acct, input string } + +func (c *accountSealer) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + acct := r.Header.Get("chatgpt-account-id") + var q struct { + Input []sealedItem `json:"input"` + } + json.Unmarshal(b, &q) + why := "" + for _, it := range q.Input { + if it.Enc != "" && !strings.HasPrefix(it.Enc, "gAAAA-"+acct+"-") && why != openaiUnverifiable { + why = openaiUndecryptable + if it.Type == "reasoning" { + why = openaiUnverifiable + } + } + } + c.mu.Lock() + c.asked = append(c.asked, sealedAsk{acct, heldItems(b)}) + out := c.out[acct] + c.mu.Unlock() + if out != nil { + out(w) + return + } + if why != "" && !c.stream { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + io.WriteString(w, `{"error":{"message":"`+why+`","type":"invalid_request_error","param":null,"code":"invalid_encrypted_content"}}`) + return + } + lead := []string{ + `event: codex.rate_limits` + "\n" + `data: {"type":"codex.rate_limits","plan_type":"plus","rate_limits":{"allowed":true,"limit_reached":false,"primary":{"used_percent":3,"window_minutes":300,"reset_after_seconds":100}}}`, + `event: response.created` + "\n" + `data: {"type":"response.created","response":{"id":"r0","model":"gpt-5.5"}}`, + `event: response.in_progress` + "\n" + `data: {"type":"response.in_progress","response":{"id":"r0","model":"gpt-5.5"}}`, + } + if why != "" { + io.WriteString(w, sse(append(lead, + `event: response.failed`+"\n"+`data: {"type":"response.failed","response":{"id":"r0","status":"failed","error":{"code":"invalid_encrypted_content","message":"`+why+`"}}}`)...)) + return + } + // most of it read from the account's cache, which keeps the + // conversation there while it is warm + io.WriteString(w, sse(append(lead, + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"from `+acct+`"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":24000,"input_tokens_details":{"cached_tokens":20000},"output_tokens":5}}}`)...)) +} + +func (c *accountSealer) setOut(acct string, answer func(w http.ResponseWriter)) { + c.mu.Lock() + defer c.mu.Unlock() + if c.out == nil { + c.out = map[string]func(w http.ResponseWriter){} + } + c.out[acct] = answer +} + +// took is what was asked since the last call. +func (c *accountSealer) took() []sealedAsk { + c.mu.Lock() + defer c.mu.Unlock() + out := c.asked + c.asked = nil + return out +} + +// on puts c behind Codex's sign-in, for the test. +func (c *accountSealer) on(t *testing.T) { + t.Helper() + up := httptest.NewServer(c) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) +} + +// heldItems is a Responses request's input as these tests check it: each +// item's type, a message's role, a call's call_id, a web search's query, +// and its seal. +func heldItems(body []byte) string { + var q struct { + Input []struct { + Type string `json:"type"` + Role string `json:"role"` + CallID string `json:"call_id"` + Action struct { + Query string `json:"query"` + } `json:"action"` + Enc string `json:"encrypted_content"` + } `json:"input"` + } + if json.Unmarshal(body, &q) != nil { + return "unreadable" + } + var out []string + for _, it := range q.Input { + out = append(out, strings.Join(strings.Fields(strings.Join([]string{it.Type, it.Role, it.CallID, it.Action.Query, it.Enc}, " ")), " ")) + } + return strings.Join(out, ", ") +} + +// codexUser is the user's message in a Codex conversation. +func codexUser(text string) string { + return `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + text + `"}]}` +} + +// replayedTurn is what turn n on acct leaves in a Codex conversation with +// output token replay on: its sealed reasoning, a web search it ran +// (hheei's), a call with its output, and its answer, the search, the call +// and the answer each with its sealed copy. +func replayedTurn(acct, n string) string { + seal := func(what string) string { return `"encrypted_content":"gAAAA-` + acct + `-` + what + n + `"` } + return `{"type":"reasoning","id":"rs_` + n + `","summary":[],"content":null,` + seal("r") + `},` + + `{"type":"web_search_call","id":"ws_` + n + `","status":"completed","action":{"type":"search","query":"上海天气","sources":[{"type":"url","url":"https://www.weather.com.cn/weather/101020100.shtml"}]},` + seal("w") + `},` + + `{"type":"function_call","name":"shell","arguments":"{\"cmd\":\"ls\"}","call_id":"c` + n + `",` + seal("f") + `},` + + `{"type":"function_call_output","call_id":"c` + n + `","output":"a.go"},` + + `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"晴,22 度"}],` + seal("m") + `}` +} + +// replayedHeld is replayedTurn as heldItems reads it: as acct sealed it, +// or with its reasoning gone and no seal left on the rest. +func replayedHeld(acct, n string, sealed bool) string { + if !sealed { + return "web_search_call 上海天气, function_call c" + n + ", function_call_output c" + n + ", message assistant" + } + s := " gAAAA-" + acct + "-" + return "reasoning" + s + "r" + n + ", web_search_call 上海天气" + s + "w" + n + ", function_call c" + n + s + "f" + n + + ", function_call_output c" + n + ", message assistant" + s + "m" + n +} + +// askThread is Codex signed in to ChatGPT as signedIn asking s at path for +// model, in its thread 3887, with the conversation's items. +func askThread(s *Server, path, model, signedIn string, items ...string) (int, string) { + body := `{"model":"` + model + `","stream":true,"store":false,` + + `"include":["reasoning.encrypted_content","output.encrypted_content"],"prompt_cache_key":"thread-3887",` + + `"tools":[{"type":"web_search"},{"type":"function","name":"shell","parameters":{"type":"object"}}],` + + `"input":[` + strings.Join(items, ",") + `]}` + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", path, strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", signedIn) + req.Header.Set("session_id", "thread-3887") + s.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.String() +} + +// Where a Codex conversation is asked through magpie's Codex accounts: one +// of Codex's own models signed in, the codex provider's model, and a +// routing group of it. +var codexAccountRoutes = []struct{ name, path, model string }{ + {"signed in", CodexPath + "/responses", "gpt-5.5"}, + {"magpie model", "/v1/responses", "codex/gpt-5.5"}, + {"group", "/v1/responses", "group/g"}, +} + +var sealRefusals = []struct { + name string + stream bool +}{{"400", false}, {"in the stream", true}} + +// A Codex conversation with a web search in it (hheei, #3887), and with +// output token replay on a sealed copy on each message and call, moves +// from one ChatGPT account to another as the first is used up or rate +// limited. The second can't read what the first sealed and says so; it is +// asked again with the reasoning left out and the seal taken off the +// rest, and the next turn goes to it so up front, its own seals on. +// Before, only the reasoning went, the search was refused again, and +// Codex got "Encrypted content could not be decrypted or parsed.". +func TestForeignSealedItemsMoveToAnotherAccount(t *testing.T) { + for _, x := range codexSpent { + if x.name != "429 json" && x.name != "response.failed rate_limit_exceeded" { + continue + } + for _, on := range codexAccountRoutes { + for _, refusal := range sealRefusals { + t.Run(x.name+", "+on.name+", refused "+refusal.name, func(t *testing.T) { + codexSignedIn(t, "spare@example.com") + if err := provider.SetRouting("codex", provider.Ordered); err != nil { + t.Fatal(err) + } + up := &accountSealer{stream: refusal.stream} + up.on(t) + if on.model == "group/g" { + refusalGroup(t, "codex/gpt-5.5") + } + s := New() + + // the account that sealed it all reads it back as it came + turn := []string{codexUser("上海天气怎么样"), replayedTurn("acct-1", "1"), codexUser("明天呢")} + if code, body := askThread(s, on.path, on.model, "acct-1", turn...); code != 200 || !strings.Contains(body, "from acct-1") { + t.Fatalf("first: %d %s", code, body) + } + if got := up.took(); len(got) != 1 || got[0] != (sealedAsk{"acct-1", "message user, " + replayedHeld("acct-1", "1", true) + ", message user"}) { + t.Fatalf("acct-1 was sent %q", got) + } + + up.setOut("acct-1", x.refuse) + turn = append(turn, replayedTurn("acct-1", "2"), codexUser("后天呢")) + code, body := askThread(s, on.path, on.model, "acct-1", turn...) + if code != 200 || !strings.Contains(body, "from acct-2") { + t.Fatalf("moved on: %d %s", code, body) + } + sealed := "message user, " + replayedHeld("acct-1", "1", true) + ", message user, " + replayedHeld("acct-1", "2", true) + ", message user" + bare := "message user, " + replayedHeld("acct-1", "1", false) + ", message user, " + replayedHeld("acct-1", "2", false) + ", message user" + if got := up.took(); len(got) != 3 || got[0].acct != "acct-1" || got[1] != (sealedAsk{"acct-2", sealed}) || got[2] != (sealedAsk{"acct-2", bare}) { + t.Fatalf("asked %q", got) + } + if r := lastRoute(s); len(r.Tries) != 3 || r.Tries[1].Fail != failForeign || r.Tries[2].Status != 200 { + t.Fatalf("tries: %+v", r.Tries) + } + + // what acct-2 refused stays out of the next turn up front, + // and what it sealed itself goes along + turn = append(turn, replayedTurn("acct-2", "3"), codexUser("谢谢")) + if code, body := askThread(s, on.path, on.model, "acct-1", turn...); code != 200 || !strings.Contains(body, "from acct-2") { + t.Fatalf("next turn: %d %s", code, body) + } + if got := up.took(); len(got) != 1 || got[0] != (sealedAsk{"acct-2", bare + ", " + replayedHeld("acct-2", "3", true) + ", message user"}) { + t.Fatalf("then asked %q", got) + } + }) + } + } + } +} + +// The same conversation moved by its affinity going cold, as hheei's did +// ("why": "cold", two hours on): the account that answered it last did so +// over an hour ago, so routing's first is asked, and it reads none of the +// other's seals. +func TestForeignSealedItemsAfterAColdSwitch(t *testing.T) { + for _, on := range codexAccountRoutes { + for _, refusal := range sealRefusals { + t.Run(on.name+", refused "+refusal.name, func(t *testing.T) { + codexSignedIn(t, "spare@example.com") + if err := provider.SetRouting("codex", provider.Ordered); err != nil { + t.Fatal(err) + } + up := &accountSealer{stream: refusal.stream} + up.on(t) + if on.model == "group/g" { + refusalGroup(t, "codex/gpt-5.5") + } + s := New() + + // acct-1's safety filter refuses the first turn, so acct-2 + // answers it, and the conversation stays there (#248) + up.setOut("acct-1", refusing400) + turn := []string{codexUser("上海天气怎么样")} + if code, body := askThread(s, on.path, on.model, "acct-1", turn...); code != 200 || !strings.Contains(body, "from acct-2") { + t.Fatalf("first: %d %s", code, body) + } + up.setOut("acct-1", nil) + up.took() + sticks.Lock() + for k, st := range sticks.m { + st.at = st.at.Add(-2 * time.Hour) + sticks.m[k] = st + } + sticks.Unlock() + + turn = append(turn, replayedTurn("acct-2", "1"), codexUser("明天呢")) + code, body := askThread(s, on.path, on.model, "acct-1", turn...) + if code != 200 || !strings.Contains(body, "from acct-1") { + t.Fatalf("gone cold: %d %s", code, body) + } + if r := lastRoute(s); r.Affinity == nil || r.Affinity.Why != "cold" { + t.Fatalf("affinity %+v", r.Affinity) + } + bare := "message user, " + replayedHeld("acct-2", "1", false) + ", message user" + if got := up.took(); len(got) != 2 || got[0] != (sealedAsk{"acct-1", "message user, " + replayedHeld("acct-2", "1", true) + ", message user"}) || got[1] != (sealedAsk{"acct-1", bare}) { + t.Fatalf("asked %q", got) + } + + turn = append(turn, replayedTurn("acct-1", "2"), codexUser("后天呢")) + if code, body := askThread(s, on.path, on.model, "acct-1", turn...); code != 200 || !strings.Contains(body, "from acct-1") { + t.Fatalf("next turn: %d %s", code, body) + } + if got := up.took(); len(got) != 1 || got[0] != (sealedAsk{"acct-1", bare + ", " + replayedHeld("acct-1", "2", true) + ", message user"}) { + t.Fatalf("then asked %q", got) + } + }) + } + } +} + +// Codex's own sign-in alone, relayed as it came, now on another account +// (signed in again, or moved on once the first was spent, +// provider.SwitchWhenSpent): the backend's 400 for the first account's +// seals is answered by asking again without them, the web search's and +// the replayed copies too. +func TestForeignSealedItemsRelayedToAnotherSignIn(t *testing.T) { + codexSignedIn(t) + up := &accountSealer{} + up.on(t) + turn := []string{codexUser("上海天气怎么样"), replayedTurn("acct-1", "1"), codexUser("明天呢")} + code, body := askThread(New(), CodexPath+"/responses", "gpt-5.5", "acct-2", turn...) + if code != 200 || !strings.Contains(body, "from acct-2") { + t.Fatalf("%d %s", code, body) + } + if got := up.took(); len(got) != 2 || got[0] != (sealedAsk{"acct-2", "message user, " + replayedHeld("acct-1", "1", true) + ", message user"}) || + got[1] != (sealedAsk{"acct-2", "message user, " + replayedHeld("acct-1", "1", false) + ", message user"}) { + t.Fatalf("asked %q", got) + } +} + +// What another account sealed is taken out with every other byte as it +// came: reasoning whole, and of a web search, a message and a call only +// their sealed copy, wherever it sits in the item. A compaction's seal +// stays for withoutCompaction. What was refused is left out of the +// conversation's later requests to who refused it, and only that. +func TestSealsTakenOutLeaveTheRest(t *testing.T) { + fresh(t) + in := `{"input":[` + codexUser("上海天气怎么样") + `,` + + `{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"gAAAA-r1"},` + + `{"encrypted_content":"gAAAA-w1","type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"上海天气"}},` + + `{"type":"function_call","name":"shell","encrypted_content":"gAAAA-f1","arguments":"{\"cmd\":\"ls\"}","call_id":"c1"},` + + `{"type":"function_call_output","call_id":"c1","output":"a.go"},` + + `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"晴"}],"encrypted_content":"gAAAA-m1"},` + + `{"type":"compaction","encrypted_content":"gAAAA-c1"},{"type":"context_compaction","encrypted_content":"gAAAA-x1"}],"model":"gpt-5.5","stream":true}` + want := `{"input":[` + codexUser("上海天气怎么样") + `,` + + `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"上海天气"}},` + + `{"type":"function_call","name":"shell","arguments":"{\"cmd\":\"ls\"}","call_id":"c1"},` + + `{"type":"function_call_output","call_id":"c1","output":"a.go"},` + + `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"晴"}]},` + + `{"type":"compaction","encrypted_content":"gAAAA-c1"},{"type":"context_compaction","encrypted_content":"gAAAA-x1"}],"model":"gpt-5.5","stream":true}` + left, ok := withoutSeals([]byte(in)) + if !ok || string(left) != want { + t.Fatalf("got %s", left) + } + + // reasoning alone is taken out as it was before + alone := `{"input":[` + codexUser("hi") + `,{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"gAAAA-r1"},` + + `{"type":"function_call","name":"shell","arguments":"{}","call_id":"c1"}],"model":"gpt-5.5"}` + was, _ := withoutKinds([]byte(alone), "reasoning") + if got, ok := withoutSeals([]byte(alone)); !ok || string(got) != string(was) { + t.Fatalf("reasoning alone: %s, was %s", got, was) + } + // nothing but a compaction sealed: nothing to take out here + if got, ok := withoutSeals([]byte(`{"input":[{"type":"compaction","encrypted_content":"gAAAA-c1"},{"type":"message","role":"user","content":"hi"}]}`)); ok { + t.Fatalf("compaction: %s", got) + } + + // the next turn, with what the one that refused sealed itself + refused("thread", "codex@b", []byte(in), left) + own := `,{"type":"message","role":"assistant","content":[{"type":"output_text","text":"多云"}],"encrypted_content":"gAAAA-b2"}` + next := strings.Replace(in, `],"model"`, own+`],"model"`, 1) + if got, ok := withoutRefused("thread", "codex@b", []byte(next)); !ok || string(got) != strings.Replace(want, `],"model"`, own+`],"model"`, 1) { + t.Fatalf("next turn: %s", got) + } + for _, other := range [][2]string{{"thread", "codex@a"}, {"another", "codex@b"}} { + if got, ok := withoutRefused(other[0], other[1], []byte(next)); ok { + t.Fatalf("%v: %s", other, got) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index ec83b377d..baa16157d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3235,8 +3235,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro var nt netTrace // where the try's time went (TryNet) attemptBody := body if from == provider.Responses { - // reasoning another sealed, which this one refused earlier in - // the conversation, isn't sent to be refused again; its own is + // what another sealed, which this one refused earlier in the + // conversation, isn't sent to be refused again; its own is if b, ok := withoutRefused(stuck, c.vendor(), attemptBody); ok { attemptBody = b } @@ -3832,17 +3832,19 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } if resealed < 2 && from == provider.Responses && !hw.passing && hw.code() >= 400 && foreignReasoning.Match(hw.errBody()) { // the conversation moved here from another account or vendor, - // whose sealed reasoning this one can't read: asked again - // without it, and what it refused isn't sent here again. xAI - // says so as a 400, or as the stream's error, which may be - // read as another status. Refused again, or with no reasoning - // to leave out, it's the compaction OpenAI sealed that goes - // (waroy: Codex compacted on GPT, then switched to Grok) + // whose seals this one can't read: asked again without them + // (its reasoning, and each message's, call's and web search's + // sealed copy, #3887), and what it refused isn't sent here + // again. xAI says so as a 400, or as the stream's error, which + // may be read as another status. Refused again, or with + // nothing else sealed to leave out, it's the compaction OpenAI + // sealed that goes (waroy: Codex compacted on GPT, then + // switched to Grok) b, ok := []byte(nil), false if resealed == 0 { resealed = 1 - if b, ok = withoutReasoning(body); ok { - refused(stuck, c.vendor(), attemptBody, "reasoning") + if b, ok = withoutSeals(body); ok { + refused(stuck, c.vendor(), attemptBody, b) } } // a compaction sealed where native compaction is on is never @@ -3850,7 +3852,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if !ok && checkpoint == nil && !s.compactsNatively(c.p, c.model) { resealed = 2 if b, ok = withoutCompaction(body); ok { - refused(stuck, c.vendor(), attemptBody, compactionKinds...) + refused(stuck, c.vendor(), attemptBody, b) } } if ok { diff --git a/internal/gateway/reasoning_carry.go b/internal/gateway/reasoning_carry.go index 62acad8b5..795ded623 100644 --- a/internal/gateway/reasoning_carry.go +++ b/internal/gateway/reasoning_carry.go @@ -166,7 +166,7 @@ func unreasonCalls(r *Request) { // client's history, so every later turn carried the same item and was // refused the same way (#4798, zane668: Pi's Chat to Grok, then Codex; // ZanderH-code: Claude Desktop's Messages to Codex). A Responses client's -// own items are asked again without them (withoutReasoning) and left out +// own items are asked again without them (withoutSeals) and left out // of the conversation's later requests there (withoutRefused); a carried // item goes the same way: refused, the items the request carried are // remembered as refused by that key or account in the conversation diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 7da1ac761..694a71394 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -380,8 +380,8 @@ const ( failAuth = "auth" // failCanceled: the agent went away before the answer came failCanceled = "canceled" - // failForeign: the conversation's reasoning was sealed by another - // account, and is sent again without it + // failForeign: the conversation's reasoning, or another item's sealed + // copy, was sealed by another account, and is sent again without it failForeign = "foreign" // failFloor: the request asked for a shorter reply than the provider // gives, and is sent again asking for the least it takes