diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 47ec514e7..5fed821ba 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -346,7 +346,7 @@ recorded as a prediction failure (`noPrediction`). - 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`. - A thinking block DeepSeek's Anthropic endpoint made is signed with its reply's id, a UUID, which Claude refuses ("Invalid `signature` in `thinking` block"). A routing group whose conversation ran on DeepSeek and goes on to Claude (DeepSeek unticked; GgbondHi6930 on X) holds such blocks, so before any refusal, `forwardOnce` leaves them out of every request to an upstream serving Claude (api.anthropic.com, or a `claude-` model name; `withoutForeignThinking` in [`thinking_bound.go`](../../internal/gateway/thinking_bound.go)), and `refuseBoundThinking` reads a refusal's indices against that same body. A thinking block signed empty (or with no signature) is left out there too: magpie gives every block a Messages client gets a signature, "" for reasoning it has none for (a Chat or Responses vendor's, Grok on Cursor's plugin), Claude Code keeps such blocks through a compaction, and a group that moves on to Claude mid tool loop was turned away on every turn (citricdu on Discord: Kiro's Claude Opus 5.5 answered a bare invalid_request_error, which `refuseBoundThinking` can't read). An assistant message left with nothing goes; its text, tool calls and the results stay. The rule reaches every route to an upstream serving Claude (relayed, translated, a plugin's fetch such as Kiro's, Bedrock's `us.anthropic.claude-…` and Vertex AI's `claude-…@` ids, count_tokens). A model that asked for its tool turns' thinking back (`thinkingBackNeeded`, DeepSeek under another name) keeps the blocks filled in for it. Claude's own signatures (base64), redacted_thinking and other vendors' signatures go as they were; DeepSeek's endpoint and every other upstream get the body byte for byte. `TestDeepSeekThinkingThenClaude`, `TestDeepSeekThinkingThenClaudeResponses`, `TestWithoutForeignThinking`, `TestUnsignedThinkingNotSentToClaude`, `TestGrokThinkingThenClaude`. - 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), or a kind of input item it doesn't take (`inputKindRefused`: Command Code's 400 `unsupported_input_item`, which takes messages, function calls, their outputs and reasoning only, and Grok's 422 "unknown item type"; as that status, as another magpie's 400 or 502 in front of it, or as an error in the summary's stream; never a 401, 403 or 429), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008, #5181, #5259), so the refusal never counts toward the guard's three. The text, and magpie's own summary, carry a Codex subagent's `agent_message` items (its task, the lead's follow-ups) as the user's (`itemText`). `TestCodexCompactUnsupportedInputItemAsksAgainAsText`, `TestCodexCompactUnsupportedInputItemCompactsLocally`, `TestCodexCompactUnsupportedInputWordsOnAnAccountFailureStay`. 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`. A summary is waited for `compactWithin` (4 minutes) at most: Codex hears nothing while it is made and gives up on a stream silent for 300s, so a later summary, and a local one made after Codex left, reached nobody, and Codex sent the same history again, 300s each time (#5275, hayden4608: a ~3.1MB summary request still going up a ~10KB/s uplink at 299s). Past it the ask ends (`sideTimedOut`, logged as magpie's own limit, not the agent leaving) and magpie's own summary goes to Codex while it still waits. A compaction Codex left before it was answered writes nothing and counts as a failure (499), never clearing the count. `TestCodexCompactLateSummaryCompactsLocallyInTime`, `TestCodexCompactLeftBeforeAnsweredStillCounts`. +- 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), or a kind of input item it doesn't take (`inputKindRefused`: Command Code's 400 `unsupported_input_item`, which takes messages, function calls, their outputs and reasoning only, Grok's 422 "unknown item type", and a local Qwen server's 400 "Unsupported input item: agent_message" (cyberestro on X; `inputKindWords` reads the words with a space or an underscore); as that status, as another magpie's 400 or 502 in front of it, or as an error in the summary's stream; never a 401, 403 or 429), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008, #5181, #5259), so the refusal never counts toward the guard's three. The text, and magpie's own summary, carry a Codex subagent's `agent_message` items (its task, the lead's follow-ups) as the user's (`itemText`). `TestCodexCompactUnsupportedInputItemAsksAgainAsText`, `TestCodexCompactUnsupportedInputItemCompactsLocally`, `TestCodexCompactUnsupportedInputWordsOnAnAccountFailureStay`. 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`. A summary is waited for `compactWithin` (4 minutes) at most: Codex hears nothing while it is made and gives up on a stream silent for 300s, so a later summary, and a local one made after Codex left, reached nobody, and Codex sent the same history again, 300s each time (#5275, hayden4608: a ~3.1MB summary request still going up a ~10KB/s uplink at 299s). Past it the ask ends (`sideTimedOut`, logged as magpie's own limit, not the agent leaving) and magpie's own summary goes to Codex while it still waits. A compaction Codex left before it was answered writes nothing and counts as a failure (499), never clearing the count. `TestCodexCompactLateSummaryCompactsLocallyInTime`, `TestCodexCompactLeftBeforeAnsweredStillCounts`. - 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`. @@ -414,6 +414,7 @@ recorded as a prediction failure (`noPrediction`). - A tool's `strict` that an upstream turns away (`toolStrictRefusal` in [`strict_refused.go`](../../internal/gateway/strict_refused.go): "Unsupported Chat Completions API field: tools[0].function.strict", OpenAI-style unknown_parameter, "Extra inputs are not permitted" and pydantic's extra_forbidden on it) is asked once more without it, in Chat's `tools[].function` and Responses' `tools[]` alike, and marked for that provider and API (`toolStrictRefused`): its next requests go without it at once. OpenCode 2 sends `"strict": false` on every tool through `@ai-sdk/openai-compatible`, and a custom provider that refused it ended the session (#1980). An upstream that hasn't refused it still gets it, as the ChatGPT backend needs it (#383). `TestToolStrictLeftOutWhereRefused` (real OpenCode 2.0.25 requests), `TestToolStrictRefusalWordings`. - A history call to a tool the request doesn't declare, which an agent that loads its tools on demand sends (pi's and T3 Code's `tool_search`: the tools a search found are called in the history but not declared in the next request's `tools`, and pi sends `"tools": []` with no tools left; Gearclickist on Discord), goes as sent where it is taken: OpenAI's Chat and Responses, the ChatGPT backend and Gemini take it, and Anthropic takes a call to a tool it isn't given ([`undeclared_tools.go`](../../internal/gateway/undeclared_tools.go)). Anthropic refuses calls with no tools at all ("Requests which include `tool_use` or `tool_result` blocks must define tools"), so `anthropicBody` declares a stub for each tool the history called when the request has none (description "Called earlier in this conversation; not available now.", any object as its input) with `tool_choice` `none`, as the Kiro plugin declares its history's tools for Kiro. An upstream that turns the request away naming such a tool as not found, unknown or not defined, or that says tools must be defined beside the calls (`refusesHistoryTools`: a relay in front of Kiro or Bedrock, a vendor checking each name), is asked once more with a stub declared for each tool the history called and `tools` lacks (`withHistoryTools`, Chat, Responses and Messages bodies, relayed or translated), `tool_choice` `none` only where the client offered no tools, and marked for that provider and API (`historyToolsRefused`): its next requests carry the stubs at once. A Responses call under a namespace is the namespace's, and a request whose calls are all declared goes as it was. `TestUndeclaredHistoryToolRefusedThenStubbed`, `TestToollessHistoryToAnthropicDeclaresStubs`, `TestToollessHistoryRefusedOnChat`, `TestUndeclaredHistoryToolTakenAsSent`, `TestRefusesHistoryToolsMatch`. - A Codex custom tool (exec, apply_patch) that a Responses upstream turns away (`customToolRefusal` in [`custom_tool.go`](../../internal/gateway/custom_tool.go): DeepSeek's 400 "Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.", #2656; xAI's 422 "tools[N].type: unknown variant `custom`, expected one of …", Rust's own wording of the type, #3392) ends the relay: `passthrough` marks the model (`customToolRefused`) and returns not done, and `attempt` translates the request on the same API (`ownAPI`), where each custom tool is offered as a function taking its `input` and a call comes back as the `custom_tool_call` Codex runs, its name kept. A marked model's next requests with a custom tool are translated at once; one without stays relayed, and an upstream that never refused them still gets them as sent. A compaction (`keepsCompaction`) isn't translated, and gets the refusal. Where the refusal reaches a group untranslated it is a shape refusal (`shapeRefused`): the next member is asked. `TestCustomToolTranslatedWhereRefused`, `TestCustomToolRefusalInGroup`, `TestCustomToolRefusalWordings`. +- An input item a Responses upstream has no type for (`inputKindWords`: a local Qwen server's 400 "Unsupported input item: agent_message" for the item a Codex subagent's task comes in, cyberestro on X; Command Code's `unsupported_input_item`; xAI's "unknown item type") ends the relay the same way, when the request carries an item other than a message, a function call, its output or reasoning (`hasOtherItem` in [`input_kinds.go`](../../internal/gateway/input_kinds.go)): `passthrough` marks the model (`inputKindsRefused`), and `attempt` translates the request on the same API, where an `agent_message` is the user's turn and a custom tool call a function call. A marked model's next such requests are translated at once. A native compaction or a sealed task isn't translated and gets the refusal, and magpie's own summary ask (`inCompaction`) keeps its own way on, the conversation as text (`inputKindRefused` above). `TestUnsupportedInputItemTranslated`, `TestInputItemRefusalWordings`, `TestCodexCompactQwenInputItemAsksAgainAsText`. - xAI's own API (api.x.ai, wherever a Grok model is served — the Grok subscription's plugin shapes its own bodies, provider's `grokShaped`) takes none of three things a client's wire puts in wrong (`xaiBody` in [`xai_body.go`](../../internal/gateway/xai_body.go), shaped in `passthrough` and on the built body in `forwardTranslated` alike, for a custom-tool refusal puts a Codex request on the translated path from the next turn on; there is nothing to learn, xAI takes none of them at all, #3392's follow-up): Codex hands a sealed reasoning item back with `"content": null` beside its `encrypted_content`, which the backend answers "Could not decode the compaction blob. Ensure it is unmodified from the compact response." (the first turn goes through, every one after it 400s) — the null goes, the item otherwise as it came; and Claude Code, its messages carrying a system turn mid-conversation since Anthropic made them GA, sends one that xAI's Messages answers "Invalid request content: Invalid message role." — each folds into the top-level `system`, its text and blocks (a `cache_control` kept) as they came, the only place that API takes the role; and a tool's schema can say `"required": null` where none are (Claude Code's own tools, an MCP server's among them — Anthropic's API takes the null), which xAI's validation of each schema answers "Invalid request content: Schema validation failed: [standard_violation] /required: null is not of type \"array\"" (the claude calls 400ed once the system turns folded) — the key goes from every shape a body leaves magpie in, `input_schema`, `parameters` and `function`'s, at the schema's root or nested, a real array of names kept as it came. `TestXAITakesCodexsSealedReasoningBack`, `TestXAILearnsCustomToolsThenTakesTheReplay`, `TestXAIFoldsClaudesSystemTurn`, `TestXAITakesANullRequiredToolSchema`, `TestXaiBodyDropsNullRequiredInEveryShape`. - A tool call's arguments reach the client as the vendor writes them, translated too (echo_ts on Discord: Codex on Copilot about 10x slower, an apply_patch shown only once whole). The Responses decoder hands each `function_call_arguments.delta` and `custom_tool_call_input.delta` on as a `KToolArgs` delta (`argsDelta`), holding back only the one that would make the JSON whole until `.done`, which `endCall` checks against the final arguments; the Responses encoder streams a custom tool's input as `custom_tool_call_input.delta` (`customStream` in [`custom_tool.go`](../../internal/gateway/custom_tool.go)) before its `.done`. A Copilot account's Responses request is relayed with a `web_search` tool in it (`searchesItself`; checked on a real account 2026-10-17), and Copilot is never picked to search for another provider's model (`searchRank`). It is translated instead when a tool marks a parameter `"encrypted": true` (`asksSealing`, MultiAgentV2's `spawn_agent`): Copilot seals such an argument and can't read its own seal on the subagent's turn. `TestCallArgsStreamWhenTranslated`, `TestCustomInputStreams`, `TestResponsesCallArgsStream`, `TestCopilotRelayedUnlessAskedToSeal`, `TestCopilotUltraSubagentWithWebSearch`. - A relayed Responses stream gives each output item the one id its `response.output_item.added` gave it, in every event after that carries an `item_id` or an `item`, and in the `output` of `response.completed`, `response.incomplete` or `response.failed` (`idTidy` in [`itemids.go`](../../internal/gateway/itemids.go), applied in `passthrough` before `phaseTidy`). GitHub Copilot's `/responses` gives an item another id in every event (checked 2026-10-19 on a real account, gpt-5.5 with web_search), and Codex starts an item by the added's id and ends one by the done's, so a commentary message was shown twice and a web search never ended (echo_ts on Discord, `TestCopilotItemKeepsItsID`). An upstream whose ids agree goes through byte for byte (`TestItemIDsThatAgreeGoAsTheyCame`); a translated reply's ids are magpie's own. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 81dde61ed..997bc796e 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -4166,7 +4166,9 @@ func itemNotFound(rec *recorder) bool { // outputs and reasoning, and answers anything else 400 // "unsupported_input_item" with param "input" (#5181, Edward4226; #5259, // Mmx233, a Codex subagent's history), and Grok's backend an -// agent_message 422 "unknown item type". It comes as that status, as +// agent_message 422 "unknown item type", and a local Qwen server's +// Responses API 400 "Unsupported input item: agent_message" (cyberestro +// on X). It comes as that status, as // another magpie's message in front of it ("Remote magpie: Command Code: // {…}", a 400 or its 502), or as an error event in the summary's stream. // The conversation as text is messages alone, which it takes. A refusal @@ -4182,7 +4184,7 @@ func inputKindRefused(rec *recorder, err error) bool { return inputKindWords.Match(rec.body.Bytes()) } -var inputKindWords = lazyre.New(`(?i)unsupported_input_item|unknown item type`) +var inputKindWords = lazyre.New(`(?i)unsupported[ _]input[ _]item|unknown item type`) // compactFailure names who answered a summary request with a failure — the // provider, the model and the provider's base URL — and what it said. diff --git a/internal/gateway/codex_compact_guard.go b/internal/gateway/codex_compact_guard.go index f864e52b4..ed3b0f57f 100644 --- a/internal/gateway/codex_compact_guard.go +++ b/internal/gateway/codex_compact_guard.go @@ -136,6 +136,13 @@ func asksCompaction(ctx context.Context) bool { return v } +// inCompaction is whether ctx is a summary ask for a compaction, its +// roles swapped or as sent (askAsSent). +func inCompaction(ctx context.Context) bool { + _, ok := ctx.Value(compactionAskKey{}).(bool) + return ok +} + func askCompaction(r *http.Request) *http.Request { return r.WithContext(context.WithValue(r.Context(), compactionAskKey{}, true)) } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 73753a246..11598e87a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5903,6 +5903,15 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P if relay && !keep && customOff() { relay, ownAPI = false, true } + // and input items a model turned away before (input_kinds.go: a + // subagent's agent_message to a server that knows OpenAI's first + // items alone) + itemsOff := func() bool { + return from == provider.Responses && !inCompaction(r.Context()) && !s.fits(p.ID, inputKindsRefused(model), from) && hasOtherItem(body) + } + if relay && !keep && itemsOff() { + relay, ownAPI = false, true + } // and a backend that turned a request for one body away because it // only streams (stream_only.go) is asked streamed, translated streamOnly := (from == provider.Chat || from == provider.Responses) && !streamOf(body) && !s.fits(p.ID, streamOnlyRefused(model), from) @@ -5930,7 +5939,7 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P // or it turned the custom tools away just now: speak it translated, // except a compaction or a sealed subagent task, which a // translation would leave out - if customOff() || !s.fits(p.ID, streamOnlyRefused(model), from) && !streamOf(body) { + if customOff() || itemsOff() || !s.fits(p.ID, streamOnlyRefused(model), from) && !streamOf(body) { if keep || sealed { return writeError(w, from, status, msg), msg } @@ -7109,6 +7118,16 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. s.markUnfit(p.ID, customToolRefused(model), proto) return res.StatusCode, p.Name + ": " + provider.APIError(b, res.Status), false } + if proto == provider.Responses && !inCompaction(r.Context()) && inputKindWords.Match(b) && hasOtherItem(body) { + // an input item it has no type for turned away (a local + // Qwen server's "Unsupported input item: agent_message", + // input_kinds.go): translated on the same API, and so from + // then on. A compaction's summary ask has its own way on, the + // conversation as text (inputKindRefused) + res.Body.Close() + s.markUnfit(p.ID, inputKindsRefused(model), proto) + return res.StatusCode, p.Name + ": " + provider.APIError(b, res.Status), false + } if gather == nil && refusesWhole(proto, body, b) { // a backend that only streams (stream_only.go): the request // is translated on the same API, which asks it streamed and diff --git a/internal/gateway/input_item_refused_test.go b/internal/gateway/input_item_refused_test.go new file mode 100644 index 000000000..785d2b95e --- /dev/null +++ b/internal/gateway/input_item_refused_test.go @@ -0,0 +1,219 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// qwenInputRefusal is a local Qwen server's Responses API turning away an +// input item it has no type for, as cyberestro on X got it from +// http://127.0.0.1:30010/v1 for a Codex subagent's agent_message: +// "qwen: Unsupported input item: agent_message". +func qwenInputRefusal(kind string) string { + return `{"error":{"message":"Unsupported input item: ` + kind + `","type":"invalid_request_error","code":400}}` +} + +// basicItem is whether a Responses server that knows OpenAI's first +// input items alone takes it: messages, function calls, their outputs and +// reasoning. +func basicItem(kind string) bool { + switch kind { + case "", "message", "function_call", "function_call_output", "reasoning": + return true + } + return false +} + +// strictInputUpstream is such a server: an item of another kind is +// refused, in qwen's words; anything else is answered "ok". +type strictInputUpstream struct { + mu sync.Mutex + asked []map[string]any +} + +func (u *strictInputUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q map[string]any + json.Unmarshal(b, &q) + u.mu.Lock() + u.asked = append(u.asked, q) + u.mu.Unlock() + items, _ := q["input"].([]any) + for _, it := range items { + if m, _ := it.(map[string]any); m != nil { + if k, _ := m["type"].(string); !basicItem(k) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + io.WriteString(w, qwenInputRefusal(k)) + return + } + } + } + answerOK(w, r, q["stream"] == true) +} + +// answerOK answers "ok", streamed or whole. +func answerOK(w http.ResponseWriter, r *http.Request, stream bool) { + if stream { + w.Header().Set("Content-Type", "text/event-stream") + msg := `{"type":"message","id":"m1","role":"assistant","content":[{"type":"output_text","text":"ok"}]}` + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","status":"in_progress","output":[]}}`, + `data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","content":[]}}`, + `data: {"type":"response.output_text.delta","output_index":0,"item_id":"m1","content_index":0,"delta":"ok"}`, + `data: {"type":"response.output_item.done","output_index":0,"item":`+msg+`}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[`+msg+`],"usage":{"input_tokens":9,"output_tokens":1}}}`)) + return + } + answer(w, r) +} + +// subagentTurn is a Codex subagent's turn under MultiAgentV2: its task +// came as an agent_message (the item codex-rs hands a subagent its +// NEW_TASK in, as #5259's and plugins#61's requests carry it), and it has +// called a tool since. +const subagentTurn = `{"model":%q,"stream":%t,"store":false,"input":[ + {"type":"message","role":"developer","content":[{"type":"input_text","text":"be brief"}]}, + {"type":"agent_message","author":"/root","recipient":"/root/research","content":[{"type":"input_text","text":"Message Type: NEW_TASK\nPayload:\nCompare Vault secret rotation with rollout restart timing."}]}, + {"type":"function_call","call_id":"call_1","name":"exec_command","arguments":"{\"cmd\":\"ls\"}"}, + {"type":"function_call_output","call_id":"call_1","output":"notes.md"}, + {"type":"agent_message","author":"/root","recipient":"/root/research","content":[{"type":"input_text","text":"Message Type: MESSAGE\nPayload:\nKeep the observed event order."}]}], + "tools":[{"type":"function","name":"exec_command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}]}` + +// cyberestro on X: a Codex subagent on a local Qwen server's Responses +// API was refused 400 "Unsupported input item: agent_message", the item +// its task comes in, and magpie gave the 400 back, every turn. The turn +// is now asked again translated on the same API, the agent_message as the +// user's turn it is, and the next turn goes translated at once; a server +// that takes the item still gets it as sent. +func TestUnsupportedInputItemTranslated(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream %t", stream), func(t *testing.T) { + fresh(t) + strict := &strictInputUpstream{} + qs := httptest.NewServer(strict) + t.Cleanup(qs.Close) + var taking []map[string]any + var mu sync.Mutex + lax := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q map[string]any + json.Unmarshal(b, &q) + mu.Lock() + taking = append(taking, q) + mu.Unlock() + answerOK(w, r, q["stream"] == true) + })) + t.Cleanup(lax.Close) + for _, p := range []provider.Provider{ + {ID: "qwen", Name: "qwen", Key: "k", Models: []string{"qwen"}, Responses: qs.URL + "/v1"}, + {ID: "lax", Name: "Lax", Key: "k", Models: []string{"m1"}, Responses: lax.URL + "/v1"}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + s := New() + ask := func(model string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(fmt.Sprintf(subagentTurn, model, stream)))) + return rec + } + rec := ask("qwen/qwen") + if rec.Code != 200 { + t.Fatalf("qwen: %d %s", rec.Code, rec.Body) + } + if len(strict.asked) != 2 { + t.Fatalf("qwen asked %d times", len(strict.asked)) + } + again, _ := json.Marshal(strict.asked[1]["input"]) + for _, want := range []string{"Compare Vault secret rotation", "Keep the observed event order", "exec_command", "notes.md"} { + if !strings.Contains(string(again), want) { + t.Errorf("asked again without %q: %s", want, again) + } + } + if !strings.Contains(rec.Body.String(), "ok") { + t.Errorf("Codex got %s", rec.Body) + } + + // the next turn goes translated at once + if rec = ask("qwen/qwen"); rec.Code != 200 || len(strict.asked) != 3 { + t.Fatalf("next turn: %d, asked %d times: %s", rec.Code, len(strict.asked), rec.Body) + } + + // a server that takes the item gets it as sent + if rec = ask("lax/m1"); rec.Code != 200 || len(taking) != 1 { + t.Fatalf("lax: %d, asked %d times: %s", rec.Code, len(taking), rec.Body) + } + if b, _ := json.Marshal(taking[0]["input"]); !strings.Contains(string(b), `"agent_message"`) { + t.Errorf("lax got %s", b) + } + }) + } +} + +// The refusal's wordings that name an input item the server has no type +// for are read as one; a refusal of anything else is not. +func TestInputItemRefusalWordings(t *testing.T) { + for _, b := range []string{ + qwenInputRefusal("agent_message"), + "Unsupported input item: custom_tool_call", + commandCodeInputRefusal, + `{"error":{"message":"unknown item type"}}`, + } { + if !inputKindWords.MatchString(b) { + t.Errorf("not read as an input item refusal: %s", b) + } + } + for _, b := range []string{ + `{"error":{"message":"Unsupported parameter: temperature"}}`, + `{"error":{"message":"Invalid API key"}}`, + deepSeekCustomRefusal, + } { + if inputKindWords.MatchString(b) { + t.Errorf("read as an input item refusal: %s", b) + } + } +} + +// cyberestro's compaction: the summary request of a subagent's +// conversation, refused for its agent_message in qwen's words, is asked +// again with the conversation as text, which the server takes, and the +// subagent's task is in it. +func TestCodexCompactQwenInputItemAsksAgainAsText(t *testing.T) { + f := &fake{t: t} + f.refuse = func(b []byte) (int, string) { + f.reply = wholeSummary(provider.Responses) + var q struct { + Input []struct { + Type string `json:"type"` + } `json:"input"` + } + json.Unmarshal(b, &q) + for _, it := range q.Input { + if !basicItem(it.Type) { + return 400, qwenInputRefusal(it.Type) + } + } + return 0, "" + } + setup(t, provider.Responses, f) + code, body := codexPost(t, compactSubagentRequest) + if code != 200 { + t.Fatalf("%d %s", code, body) + } + if got := compactedText(t, body); got != "SUMMARY" { + t.Fatalf("summary %q, want the model's", got) + } + if !strings.Contains(string(f.got), "Compare Vault secret rotation") { + t.Errorf("the summary was asked without the task: %s", f.got) + } +} diff --git a/internal/gateway/input_kinds.go b/internal/gateway/input_kinds.go new file mode 100644 index 000000000..c6363c47d --- /dev/null +++ b/internal/gateway/input_kinds.go @@ -0,0 +1,51 @@ +package gateway + +import ( + "encoding/json" +) + +// A Responses API that knows OpenAI's first input items alone — messages, +// function calls, their outputs and reasoning — turns away a request +// carrying any other: a local Qwen server answers a Codex subagent's turn +// 400 "Unsupported input item: agent_message" (cyberestro on X), the item +// MultiAgentV2 hands a subagent its task in, and Command Code's answers +// "unsupported_input_item" (#5181, #5259). A relay sends Codex's items as +// they came, so every such turn failed. The request is then translated +// on the same API, which reads an agent_message as the user's turn, a +// custom tool call as a function call, and leaves out what has no +// counterpart; and so from then on for that model, as a custom tool +// turned away is (custom_tool.go). The words are inputKindWords, which +// the compaction's summary ask reads too (inputKindRefused): that ask is +// left to its own way on, the conversation as text (inCompaction). + +// inputKindsRefused is how unfit remembers model turning away input +// items other than the first ones. +func inputKindsRefused(model string) string { return "input kinds\x00" + model } + +// hasOtherItem reports whether a Responses body's input carries an item +// other than a message, a function call, its output or reasoning. +func hasOtherItem(body []byte) bool { + if !bodyHas(body, `"input"`) { + return false + } + var q struct { + Input json.RawMessage `json:"input"` + } + if json.Unmarshal(body, &q) != nil { + return false + } + var items []struct { + Type string `json:"type"` + } + if json.Unmarshal(q.Input, &items) != nil { + return false + } + for _, it := range items { + switch it.Type { + case "", "message", "function_call", "function_call_output", "reasoning": + default: + return true + } + } + return false +}