diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 55141ab56..f1ca61f50 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -251,6 +251,7 @@ recorded as a prediction failure (`noPrediction`). - Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models stay in it when they are kept out of other agents' lists for routing groups, by the codex provider "Only through routing groups" (`Provider.Unlisted`) or a group that unlists its members (`Group.Unlists`): Codex's own catalog (`catalogOf("codex")`, behind `ListedFor`/`CatalogFor`) keeps `CodexOwn` entries, so the Agents page shows its Codex section, its picker offers them as magpie's, and the desk file and `spawnChoices` list them. #1602 dropped them here, and the picker then still offered them through the own-models switch while the Codex app had none (士奇 on Discord, 10-28). They are hidden from Codex through Codex's list (`provider.CodexNativeHidden`, `TestCodexModelListKeepsOwnForGroups`, `TestCodexOwnModelsListedOnlyThroughGroups`). Every agent keeps a signed-in subscription's own models (`provider.SubscriptionKept`: an account's, its provider not `Unlisted`) that a group listing alone would keep out: `catalogOf(agent)` keeps them for any agent, so the Agents page, the pickers, the files magpie writes and the agent's `/v1/models` (and `/v1/models/{id}`, Desktop's aliases through `provider.CatalogOf`) still have them with the group on. Only a client that is no agent (`CatalogFor("")`, `Catalog()`) is given the group alone (#1783). a3ee00c05 had kept them for Codex alone, and Hermes Agent and WorkBuddy lost the Codex section with the group on (士奇 on Discord, 10-30; `TestSubscriptionModelsStayInEveryAgentsListWithGroupOn`). A backend answer that says the sign-in itself is revoked (`provider.SignInRevoked`, a 401 `token_revoked`; jjt on Discord, #4308) isn't passed through: the list is Codex's cached one (`codexcat.CacheEntries`) and magpie's, so the picker keeps magpie's models; any other refusal, a 401 `token_expired` among them, still is. The desk file does the same while the live list says revoked (`provider.CodexListRevoked`, `codexDesk.revoked`) (`TestCodexModelListRevokedSignIn`, `TestCodexDesktopCatalogRevokedSignIn`). - The Codex app and its VS Code extension read only the first 100 of that list by priority, hidden entries counted: each asks its app-server for `model/list` with `limit: 100` and never for the next page (ChatGPT.app 26.1013, openai.chatgpt 26.51021; the CLI's `/model` lists every one). So `codexcat.FitOwn` ranks the list last of all: hidden entries after every listed one, and, with more than 100 listed (`codexcat.AppList`), Codex's own listed models (the backend's entries in `codexMerged`; a ChatGPT account's `codex/…` ones, `codexcat.ChatGPTOwn`, on the other two routes) and then the models Codex used in the last 30 days (`usage.CodexUsed`, most recent first, at most 100) brought into the first 100 in the order they stood, the rest kept in theirs. The user's own order (`codexcat.Order`, #855) goes first, so an order that names only magpie's models (set while Codex's list had no Codex section, or before OpenAI added a model) no longer puts every GPT model past the 100th (maiya on Discord); the user takes one out of the app by hiding it in Codex's list. The same holds for `/v1/codex/models` (with the models that key's Codex used alone, `usage.CodexUsedBy`, before the 1 MiB cut) and the `model_catalog_json` magpie writes (`codexcat.CatalogUsed`). `codexListTag` carries a tag of the used set (`codexcat.UsedTag`), so the ETag and `X-Models-Etag` change when Codex uses a model it hadn't; `usage.CodexUsed` is read again a minute on, or at once when `Append` writes a Codex call to a model it doesn't hold (`codexUsedNew`). `TestCodexModelListKeepsUsedModelsInTheAppsHundred`, `TestCodexCatalogKeepsTheKeysUsedModelsFirst`, `TestFitKeepsUsedModelsWhereTheCodexAppReads`, `TestCodexUsed`, `TestCodexModelListKeepsOwnModelsInTheAppsHundred`, `TestFitOwnKeepsCodexsOwnInTheAppsHundred` and `TestCatalogUsedKeepsChatGPTOwn` cover it (@ZhenLuoTTAWDTT on X). - Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming Messages request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. The signature itself is kept in magpie's folder, `gemini-signatures/`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__`), so an id stays under 64 characters however long the step's signature (#2411: LobeHub's PostgreSQL index turned away a 3KB id). A key magpie no longer has, or whose file doesn't hash to it, reads as no signature; one not read for 90 days is removed. Where the folder can't be written, the id carries the signature as before. Across APIs, only Claude's reasoning is carried to a Responses client, below. +- A Responses upstream reads only the reasoning it sealed itself (`encrypted_content`). When one answers that it can't read the sealed reasoning or compaction it was sent (`foreignReasoning` in [`affinity.go`](../../internal/gateway/affinity.go): OpenAI's and Codex's "could not be verified", xAI's "Could not decrypt", Azure's "invalid encrypted summary", a relay's compaction-blob refusal), `serve` asks once more without it and remembers its hashes for that conversation (`stickKey`) and key or account (`candidate.vendor`, `refusedSeals`), so the conversation's later turns there go without it the first time; the try is `fail: foreign`. A Responses client's own items go first (`withoutReasoning`, `withoutRefused`), then OpenAI's compaction (`withoutCompaction`). A Chat, Messages or Gemini client holds a Responses upstream's sealed reasoning in its calls' ids instead (`__rk__`, `carryReasoning` and `unreasonCalls` in [`reasoning_carry.go`](../../internal/gateway/reasoning_carry.go), 9da9bfabd), and every later turn of its history sends it again, so a conversation that moved to another Responses upstream or account (Grok to Codex after a 402, and back) was refused on that turn and every one after it (#4798, zane668, ZanderH-code). Such a refusal is asked again once too: `refuseCarried` remembers what the request's calls carried as refused by that key or account, and `translate` leaves those items out of this and every later request to it (`withoutRefusedCarry`, scoped to the try's provider through `withSealScope`). The calls, their arguments and results and the text go as the client wrote them, under the calls' own ids; the one that sealed an item, and every other key or account, is still given it. As for a Responses client, all the reasoning the request carried goes, the upstream's own earlier items among them; what it seals next goes along. `TestForeignSealAcrossGroupMembers`, `TestForeignCarriedReasoningAskedAgainWithout`. - Claude signs a thinking block for the conversation and the account it was made in. When an Anthropic upstream answers 400 that a block's signature is invalid, "bound to a different conversation" or "not created in this conversation" (`boundRefusal`: a conversation moved between accounts or providers, or a relay that serves Claude from several accounts of its own; ferock on Discord, through Command Code's plugin), `forward` asks once more without the block it names (`messages..content.`) and every thinking block after it, whose signatures cover it, and remembers those signatures for that provider and account (`refuseBoundThinking`, `withoutRefusedThinking` in [`thinking_bound.go`](../../internal/gateway/thinking_bound.go)), so the conversation's later turns go without them the first time. Every route to an Anthropic upstream (relayed, translated, a plugin's fetch, count_tokens) passes there. Blocks before it, other providers and accounts, and every other refusal (DeepSeek's wanting its thinking back among them) are left as they are. magpie doesn't send the `thinking-binding-controls` beta's `drop_block` for an agent. `TestBoundThinkingLeftOut`, `TestPluginBoundThinkingLeftOut`, `TestOtherRefusalKeepsThinking`. - Claude's reasoning goes to a Responses client (Codex) in an envelope and comes back as Claude wrote it (mysterious_dove_96933 on Discord). Anthropic wants a tool loop's next request to have the turn's thinking blocks, signed, and its `redacted_thinking` whole, or answers 400; Codex with `store: false` keeps only a reply's items, and of a reasoning item only `encrypted_content` is opaque. So the Anthropic decoders name a signature as Claude's (`KSig` with `sealAnthropic`, `Part.SignedBy`), and the Responses encoder and `renderResponses` give each thinking block a reasoning item whose `encrypted_content` is `magpie-claude1:` and the block's JSON in base64 (`claudeThinking`, [`internal/claudeseal`](../../internal/claudeseal/claudeseal.go)): its summary with it, an empty summary for a block signed with no text, and a `redacted_thinking` block as an item of its own. `parseResponses` reads such an item back into the block (`claudePart`), in order, so `anthropicBody` sends it as it was; an envelope that can't be read is its summary, as before. A Gemini thought's signature isn't named, and isn't sealed. The envelope goes to no Responses API: `passthrough` and `forwardOnce` take it out (`withoutClaudeSeals`: the item keeps its summary, one with none goes), `codexInputAs` leaves such an item out for Codex's own models as it does one with nothing sealed, and `codexUpstreamOn` takes it out before the ChatGPT backend; OpenAI's own `encrypted_content` is untouched. `redact.MaskJSON` keeps it whole (a reasoning item's seal), so the placeholders Claude was sent stay in what its signature covers. Claude's subscription names its signatures too, so Codex gets the same items, though its tool loop goes on inside Claude Code's own run, which keeps the thinking itself. `TestCodexToolLoopGivesClaudeItsThinkingBack`, `TestClaudeBlocksNeverGoToAResponsesAPI`, `TestGeminiSignatureIsNotSealedAsClaudes`, `TestMaskJSONKeepsClaudeBlocks`. - 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`. diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index c2ae0d4e1..53489c45f 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -1088,7 +1088,12 @@ func seals(body []byte, kinds ...string) [][sha256.Size]byte { // 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) { - ss := seals(body, kinds...) + noteRefused(key, who, seals(body, kinds...)) +} + +// noteRefused notes that who turned away the sealed items of these hashes +// in the conversation key. +func noteRefused(key, who string, ss [][sha256.Size]byte) { if len(ss) == 0 { return } diff --git a/internal/gateway/foreign_carry_test.go b/internal/gateway/foreign_carry_test.go new file mode 100644 index 000000000..57e875da2 --- /dev/null +++ b/internal/gateway/foreign_carry_test.go @@ -0,0 +1,270 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// codexUnverifiable is Codex's refusal of reasoning another vendor or +// account sealed, as #4798's reporters quote it (zane668, ZanderH-code). +const codexUnverifiable = "The encrypted content KqMXgAAAAABpGZWl could not be verified. Reason: Encrypted content could not be decrypted or parsed." + +// carrySealer is a Responses upstream that seals its reasoning as +// "sealed-by-#", each item its own, reads only its own, and answers each request it +// takes with that reasoning and a call, as Grok and Codex answer a tool +// loop. It keeps every request's input. +type carrySealer struct { + name string + refusal string // its words for reasoning it can't read, as a 400 + mu sync.Mutex + down int // answering this status, for the conversation to move on + n int + inputs [][]map[string]any +} + +func (s *carrySealer) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q struct { + Input []map[string]any `json:"input"` + } + json.Unmarshal(b, &q) + foreign := false + for _, it := range q.Input { + if enc, _ := it["encrypted_content"].(string); it["type"] == "reasoning" && !strings.HasPrefix(enc, "sealed-by-"+s.name+"#") { + foreign = true + } + } + s.mu.Lock() + s.inputs = append(s.inputs, q.Input) + down := s.down + s.n++ + n := s.n + s.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch { + case down != 0: + w.WriteHeader(down) + io.WriteString(w, `{"error":{"message":"Grok Build usage balance exhausted","type":"insufficient_quota"}}`) + return + case foreign: + w.WriteHeader(400) + msg, _ := json.Marshal(s.refusal) + io.WriteString(w, `{"error":{"message":`+string(msg)+`,"type":"invalid_request_error","param":null}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + call := fmt.Sprintf("call_%s_%d", s.name, n) + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r`+call+`","model":"m"}}`, + `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_`+call+`","summary":[],"encrypted_content":"sealed-by-`+s.name+`#`+call+`"}}`, + `data: {"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_`+call+`","call_id":"`+call+`","name":"shell","arguments":"","status":"in_progress"}}`, + `data: {"type":"response.function_call_arguments.delta","item_id":"fc_`+call+`","output_index":1,"delta":"{\"cmd\":\"cat a.txt\"}"}`, + `data: {"type":"response.output_item.done","output_index":1,"item":{"type":"function_call","id":"fc_`+call+`","call_id":"`+call+`","name":"shell","arguments":"{\"cmd\":\"cat a.txt\"}","status":"completed"}}`, + `data: {"type":"response.completed","response":{"id":"r`+call+`","usage":{"input_tokens":7,"output_tokens":1}}}`)) +} + +// taken is what each request since the last call carried: its reasoning's +// sealer, in order, and the call ids and arguments of its calls and results. +func (s *carrySealer) taken() (seals [][]string, calls []string) { + s.mu.Lock() + defer s.mu.Unlock() + for _, in := range s.inputs { + var got []string + for _, it := range in { + switch it["type"] { + case "reasoning": + by, _, _ := strings.Cut(strings.TrimPrefix(it["encrypted_content"].(string), "sealed-by-"), "#") + got = append(got, by) + case "function_call": + calls = append(calls, it["call_id"].(string)+" "+it["arguments"].(string)) + case "function_call_output": + calls = append(calls, it["call_id"].(string)+" -> "+fmt.Sprint(it["output"])) + } + } + seals = append(seals, got) + } + s.inputs = nil + return seals, calls +} + +// carryClient is a client of one API in a tool loop: it keeps the calls it +// was given, ids as given, and sends them back with their results. +type carryClient struct { + from provider.Protocol + stream bool + calls []string // the ids it was given, in order +} + +func (c *carryClient) ask(t *testing.T, s *Server) (int, string) { + t.Helper() + const user = "Sum the numbers in a.txt" + var path, body string + st := fmt.Sprint(c.stream) + switch c.from { + case provider.Chat: + msgs := `{"role":"user","content":"` + user + `"}` + for _, id := range c.calls { + msgs += `,{"role":"assistant","content":"Reading it.","tool_calls":[{"id":"` + id + `","type":"function","function":{"name":"shell","arguments":"{\"cmd\":\"cat a.txt\"}"}}]},{"role":"tool","tool_call_id":"` + id + `","content":"1 2 3"}` + } + path, body = "/v1/chat/completions", `{"model":"group/grok-codex","stream":`+st+`,"reasoning_effort":"high","tools":[{"type":"function","function":{"name":"shell","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}}],"messages":[`+msgs+`]}` + case provider.Anthropic: + msgs := `{"role":"user","content":"` + user + `"}` + for _, id := range c.calls { + msgs += `,{"role":"assistant","content":[{"type":"text","text":"Reading it."},{"type":"tool_use","id":"` + id + `","name":"shell","input":{"cmd":"cat a.txt"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"` + id + `","content":"1 2 3"}]}` + } + path, body = "/v1/messages", `{"model":"group/grok-codex","stream":`+st+`,"max_tokens":32000,"thinking":{"type":"adaptive"},"tools":[{"name":"shell","input_schema":{"type":"object","properties":{"cmd":{"type":"string"}}}}],"messages":[`+msgs+`]}` + case provider.Gemini: + msgs := `{"role":"user","parts":[{"text":"` + user + `"}]}` + for _, id := range c.calls { + msgs += `,{"role":"model","parts":[{"text":"Reading it."},{"functionCall":{"id":"` + id + `","name":"shell","args":{"cmd":"cat a.txt"}}}]},{"role":"user","parts":[{"functionResponse":{"id":"` + id + `","name":"shell","response":{"output":"1 2 3"}}}]}` + } + path, body = "/v1beta/models/group/grok-codex:generateContent", `{"tools":[{"functionDeclarations":[{"name":"shell","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}]}],"contents":[`+msgs+`]}` + } + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body))) + if rec.Code == 200 { + c.calls = append(c.calls, c.givenID(t, rec.Body.Bytes())) + } + return rec.Code, rec.Body.String() +} + +// givenID is the id of the one call the reply gave the client. +func (c *carryClient) givenID(t *testing.T, body []byte) string { + t.Helper() + if c.from != provider.Gemini { + return askedCallID(t, c.from, body, c.stream) + } + var m struct { + Candidates []struct { + Content struct { + Parts []struct { + FunctionCall *struct{ ID string } `json:"functionCall"` + } + } + } + } + json.Unmarshal(body, &m) + var ids []string + for _, cand := range m.Candidates { + for _, p := range cand.Content.Parts { + if p.FunctionCall != nil { + ids = append(ids, p.FunctionCall.ID) + } + } + } + if len(ids) != 1 { + t.Fatalf("gemini client was given calls %v: %s", ids, body) + } + return ids[0] +} + +// #4798 (zane668, ZanderH-code): a Chat, Messages or Gemini client's +// conversation moved from Grok to Codex, and back. The reasoning one of +// them sealed rides in its calls' ids (reasoning_carry.go) and reached +// the other, which refused it with a 400; nothing asked again, and every +// later turn carried the same item, so the session ended there. Now the +// refusal is asked again without what the calls carry, the turn is +// answered, the next turn there leaves the refused item out up front +// while the upstream's own goes along, and the calls, their arguments +// and their results go as the client wrote them, under their own ids. +func TestForeignCarriedReasoningAskedAgainWithout(t *testing.T) { + for _, cl := range []carryClient{{from: provider.Chat}, {from: provider.Chat, stream: true}, {from: provider.Anthropic}, {from: provider.Anthropic, stream: true}, {from: provider.Gemini}} { + t.Run(fmt.Sprintf("%s stream=%v", cl.from, cl.stream), func(t *testing.T) { + fresh(t) + grok := &carrySealer{name: "grok", refusal: xaiUndecryptable} + codex := &carrySealer{name: "codex", refusal: codexUnverifiable} + for _, u := range []struct { + id string + name string + h http.Handler + }{{"grok1", "Grok (SuperGrok)", grok}, {"codex1", "Codex", codex}} { + up := httptest.NewServer(u.h) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: u.id, Name: u.name, Key: "k-" + u.id, Models: []string{"m"}, Responses: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{Name: "grok-codex", Members: []string{"grok1/m", "codex1/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + c := &cl + + // Grok answers, and the call it gave carries its reasoning + if code, body := c.ask(t, s); code != 200 { + t.Fatalf("first turn: %d %s", code, body) + } + if _, items := unreasonedID(c.calls[0]); len(items) != 1 { + t.Fatalf("the call's id %q carries %d items", c.calls[0], len(items)) + } + grok.taken() + + // Grok's balance runs out: Codex takes the turn, refuses + // Grok's reasoning once, and answers without it + grok.mu.Lock() + grok.down = http.StatusPaymentRequired + grok.mu.Unlock() + if code, body := c.ask(t, s); code != 200 { + t.Fatalf("after the switch: %d %s", code, body) + } + seals, calls := codex.taken() + if fmt.Sprint(seals) != "[[grok] []]" { + t.Fatalf("Codex was sent reasoning %v, want Grok's, then none", seals) + } + for _, cl := range calls { + if want := []string{"call_grok_1 {\"cmd\":\"cat a.txt\"}", "call_grok_1 -> 1 2 3"}; !strings.HasPrefix(cl, "call_grok_1") || cl != want[0] && cl != want[1] { + t.Fatalf("Codex was sent the call as %q", cl) + } + } + if len(calls) != 4 { + t.Fatalf("Codex was sent calls %q", calls) + } + + // the next turn there goes once, with Codex's own reasoning + // and none of Grok's + if code, body := c.ask(t, s); code != 200 { + t.Fatalf("the turn after: %d %s", code, body) + } + if seals, _ := codex.taken(); fmt.Sprint(seals) != "[[codex]]" { + t.Fatalf("Codex was then sent reasoning %v, want its own alone", seals) + } + + // and the other way: Grok, back, is refused Codex's once and + // asked again without what the calls carry — its own earlier + // reasoning too, as a Responses client's request goes without + // all of it (withoutReasoning) — and its next turn has its + // newest reasoning, none of what it refused + grok.mu.Lock() + grok.down = 0 + grok.mu.Unlock() + grok.taken() + sticks.Lock() + sticks.m = map[string]stick{} + sticks.Unlock() + restingUntil.Lock() + restingUntil.m = map[string]time.Time{} + restingUntil.Unlock() + if code, body := c.ask(t, s); code != 200 || !strings.Contains(c.calls[len(c.calls)-1], "call_grok_") { + t.Fatalf("back on Grok: %d %s (calls %q)", code, body, c.calls) + } + if seals, _ := grok.taken(); fmt.Sprint(seals) != "[[grok codex codex] []]" { + t.Fatalf("Grok was sent reasoning %v, want its own and Codex's, then none", seals) + } + if code, body := c.ask(t, s); code != 200 { + t.Fatalf("Grok's next turn: %d %s", code, body) + } + if seals, _ := grok.taken(); fmt.Sprint(seals) != "[[grok]]" { + t.Fatalf("Grok was then sent reasoning %v, want its newest alone", seals) + } + }) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2c077ad47..c9acc275a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3292,6 +3292,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // with the try's own, to the agent if it is the one it gets // (#4145) ctx = withReplySink(ctx, c.p.ID, hw.heardUpstream) + if from != provider.Responses { + // the reasoning its calls carry that this one refused + // earlier in the conversation isn't sent to be refused + // again (reasoning_carry.go, #4798) + ctx = withSealScope(ctx, c.p.ID, stuck, c.vendor()) + } // a key or account with a MaxConcurrency is asked once one of // its slots is free, in turn; the agent gone while it waits, // nothing is sent (the 499 below) @@ -3589,6 +3595,21 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro i-- continue } + if resealed == 0 && from != provider.Responses && !hw.passing && hw.code() >= 400 && foreignReasoning.Match(hw.errBody()) { + // the same refusal of a client of another API: the sealed + // reasoning its calls' ids carry (reasoning_carry.go), which + // a Responses upstream other than the one that sealed it + // can't read, and which every later turn of the client's + // history carries again. Asked again without it, and never + // sent here again in the conversation (#4798) + resealed = 2 + if refuseCarried(stuck, c.vendor(), from, attemptBody) { + try.Fail = failForeign + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) + i-- + continue + } + } 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 @@ -7478,6 +7499,9 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr } } } + // the carried reasoning this key or account refused in the + // conversation (reasoning_carry.go, #4798) + withoutRefusedCarry(r.Context(), p, request) // a glm-5.3-flash* replica's CR stitched into a call's arguments // (tool_args_cr.go, #4256) request.CR = glmServed(wiresOf(r.Context()), p, model) diff --git a/internal/gateway/reasoning_carry.go b/internal/gateway/reasoning_carry.go index e7543f8ba..62acad8b5 100644 --- a/internal/gateway/reasoning_carry.go +++ b/internal/gateway/reasoning_carry.go @@ -1,9 +1,13 @@ package gateway import ( + "bytes" + "context" + "crypto/sha256" "encoding/json" "slices" "strconv" + "time" "github.com/yetone/magpie/internal/provider" ) @@ -153,3 +157,112 @@ func unreasonCalls(r *Request) { } } } + +// A carried item reaches whichever Responses upstream a conversation goes +// to next, not only the one that sealed it: after a fallback, a switch of +// account or a group's next turn, Codex refuses Grok's ("The encrypted +// content … could not be verified") and Grok Codex's ("Could not decrypt +// the provided encrypted_content"), and the call's id stays in the +// 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 +// 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 +// (refuseCarried), the request is asked again, and the translation leaves +// them out of this and every later request to it (withoutRefusedCarry). +// The calls, their results and the text stay as they were; the call's id +// is its own either way. Another key or account, the one that sealed it +// among them, is still given them. + +// sealScopeKey holds a try's sealScope in its context. +type sealScopeKey struct{} + +// sealScope is whose refusals of carried reasoning a try's translation +// reads: the conversation (stickKey), and the key or account +// (candidate.vendor) of the provider it goes to. +type sealScope struct { + id, key, who string +} + +// withSealScope is ctx for a try to provider id, as who, in the +// conversation key. +func withSealScope(ctx context.Context, id, key, who string) context.Context { + return context.WithValue(ctx, sealScopeKey{}, sealScope{id: id, key: key, who: who}) +} + +// carriedSeal is the hash refusedSeals knows a carried reasoning part by: +// its item's encrypted_content, as seals hashes a Responses client's. +func carriedSeal(p Part) ([sha256.Size]byte, bool) { + if !p.sealedBy(sealResponses) { + return [sha256.Size]byte{}, false + } + var it sealedItem + if decodeJSON(p.Sealed, &it) != nil || !sealedKinds[it.Type] || it.Enc == "" { + return [sha256.Size]byte{}, false + } + return sha256.Sum256([]byte(it.Enc)), true +} + +// withoutRefusedCarry leaves out of req the carried reasoning the key or +// account of ctx's try to p refused earlier in the conversation. Nothing +// else changes; a request with none goes as it is. +func withoutRefusedCarry(ctx context.Context, p provider.Provider, req *Request) { + sc, ok := ctx.Value(sealScopeKey{}).(sealScope) + if !ok || sc.id != p.ID { + return + } + refusedSeals.Lock() + r, ok := refusedSeals.m[sc.key+"|"+sc.who] + refusedSeals.Unlock() + if !ok || time.Since(r.at) > stickKeep { + return + } + for i, m := range req.Messages { + gone := func(p Part) bool { + h, ok := carriedSeal(p) + return ok && r.seals[h] + } + if slices.ContainsFunc(m.Parts, gone) { + req.Messages[i].Parts = slices.DeleteFunc(slices.Clone(m.Parts), gone) + } + } +} + +// refuseCarried remembers the reasoning body's calls carry, in a request +// from a client of from, as refused by who in the conversation key; true +// when any of it wasn't already, so that asking again leaves something +// out. +func refuseCarried(key, who string, from provider.Protocol, body []byte) bool { + if from == provider.Responses || !bytes.Contains(body, []byte(reasonTail)) { + return false + } + req, err := parseRequest(from, body, false, true) + if err != nil { + return false + } + var ss [][sha256.Size]byte + for _, m := range req.Messages { + for _, p := range m.Parts { + if h, ok := carriedSeal(p); ok { + ss = append(ss, h) + } + } + } + k := key + "|" + who + refusedSeals.Lock() + r := refusedSeals.m[k] + fresh := false + for _, h := range ss { + if !r.seals[h] || time.Since(r.at) > stickKeep { + fresh = true + } + } + refusedSeals.Unlock() + if !fresh { + return false + } + noteRefused(key, who, ss) + return true +}