ac4af582301a4e8a29245dbba767eba31334ddf9
78
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
01de489de1 |
search: a ChatGPT account searches for another model by the backend's own search (lucy_85908)
A third-party model in Codex (DeepSeek, MiniMax, ...) had its web searches made by asking gpt-6-luna on the Codex account to search through /responses. A ChatGPT account now searches by the ChatGPT backend's /alpha/search, the request Codex's web.run sends by itself with no model turn (codex-rs ext/web-search): one search_query, the account's small model in "model", allowed_callers ["direct"], and external_web_access from the client's web_search tool (#5018: Codex's "cached" sends false; live by default). The output's pages are read by their 80-dash rule and ref_id; the private-use citation marks are dropped. Measured on a real Plus account (2026-11-03, token not refreshed): 151 alpha/search calls left the 5h window at the same percent, ~1.5-2.2s each; 51 searches by gpt-6-luna took 0% -> 1% of it, 7-15s each, ~9-17k tokens in (40 of them: 414,585 in, 10,313 out). The backend answered the same for any "model" (deepseek-v4 too) and any max_output_tokens. - Automatic (and searchInTurn) picks the backend's search for a ChatGPT account; Settings > Web search offers "<id>/@search" as "its web search". "<id>" and "<id>/<model>" saved before still search by that model, so a user's pick is unchanged. - When the backend's search fails, the account's small model searches (codexSearchBy). - Codex web.run's own search for a non-ChatGPT model (alphaSearchHere) and a Responses request's web_search tool pass their mode on. Run at this head (rebased on origin/main), on mote: - go test ./internal/gateway/... ./internal/gui/ ./internal/agent/ -timeout 45m: gateway and agent ok; gui red only on TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 on mote). After the rebase: the gateway's search tests again ok. - searcher-pick.test.cjs: 22/22, chromium + webkit, en/zh (+ the label is in zh, zh-TW, ja, de). - gofmt -l clean; GOOS=linux go vet gateway, provider; GOOS=windows go vet gateway, gui. - Whole GUI suite on the Linux box (wsl-run): not finished when pushed; its reds so far are WebKit pages this doesn't touch (add-provider, API key palette, Routing headers, click-scroll, Codex resets). Broken by hand, each red: the Automatic switch (TestCodexSearchesWith ItsCheapModel, TestChatGPTAccountSearchesByItsWebSearch), the responses.go mode (TestResponsesWebSearchModeKept), the body's mode, the fallback, and the picker option (searcher-pick). Not tried: a real search through magpie in a sandbox (the request shape was tried by hand against the backend); an account out of its allowance (does alpha/search still answer?); the model fallback still searches live when Codex asked cached. Suggested by lucy_85908 on Discord. |
||
|
|
8d7439a1a0 |
gateway: a translated system turn is folded for a Responses upstream, and a relay's "Upstream request failed" 400 fails a group over (#4632)
Two faults, one turn. Claude Code 2.1.296 and later send their
environment as a message with role "system" inside messages
(Request.envInTurns). The Chat and Anthropic builds fold such a message
into the system prompt (responseInstructions); buildResponses wrote the
role as it came, and a relay whose Responses endpoint fronts the ChatGPT
backend — which takes user, assistant and developer alone — answered
every translated turn 400 "Upstream request failed". That 400 matched
none of the wordings that make a 4xx retryable, so the holdWriter held
it as final and the group's second member never ran: the relay's answer
went to the agent, every turn.
What changed: buildResponses folds a translated request's system and
developer messages the way the Chat and Anthropic builds do, keyed on
the read. A Responses client's own instruction items are kept by the
read (#2532) and go where they stood; so do a codex account's, which
its send says as developer ones in place (codexBody — the fold would
move them out of conversation order, so buildFor marks the account's
requests kept). A translated request's system message is the harness's,
so it is said in the instructions, and one after a reply is told as a
user <system-reminder>, as on every other target. A relay's own word
that the provider behind it turned the request away ("sub2api: Upstream
request failed", type upstream_error — the words the Codex compaction
already reads, #866, #1511) joins the wordings that make a 400 or 422
retryable (retryable) and fail a group over (shapeRefused): the next
member is asked, and nobody rests. A 400 that says nothing of the kind
still ends the route, as a bad request would fail on every member
alike.
Run: TestClaudeSystemTurnSaidInTheInstructionsOnResponses and
TestGroupFailsOverARelaysUpstreamFailed, red at upstream/main
|
||
|
|
b683f1c0e1 |
gateway: a search on Volcengine Ark asks for no include value Ark refuses
axelburks on Discord #feedback (1566310723922042991): every web search on an Ark model (ark.cn-beijing.volces.com) failed with 400 "The parameter `include` specified in the request are not valid: unknown type: web_search_call.action.sources". buildResponses adds that value to every Responses request offering web_search on any host but api.x.ai (#315, |
||
|
|
5032d3ade7 |
gateway: a reasoning item magpie hands Codex with its text in it becomes one of its own, a summary and nothing sealed (#2855)
What changed A Responses reasoning item that carries the model's reasoning as content parts (reasoning_text) — another vendor's shape; OpenAI's own items carry summaries — no longer reaches a client of magpie's as the upstream wrote it. It is made over into the item magpie makes of any other upstream's reasoning: its text (and its summaries) as one summary, an rs_ id, no content and no seal — in a reply translated for the client (magpieMadeReasoningRaw at the encoder's sealed item and the whole reply's renderer) and in one relayed as it came (reasoningTidy, a passthrough filter on Responses streams and whole replies, the item in output_item.added/done and in response.completed's output). The subsystems doc's rule is amended to say so. Why A Codex conversation that used OpenAI, went through magpie to DeepSeek, then had magpie disconnected again, was stuck: every later turn, the remote compact too, answered 400 "Invalid 'input[43].content': array too long. Expected an array with maximum length 0, but got an array with length 1 instead." The reporter's rollout forensics narrow it: the DeepSeek phase had left 25 reasoning items, each with its text in content parts and a 38-character encrypted_content of the vendor's own (not the gAAAA the thread's own GPT-phase items carry, which have no content), which Codex stores and replays to OpenAI. OpenAI takes a reasoning item sent back only with its content empty (#1411) and cannot open another vendor's seal, so such an item poisons the thread for OpenAI wherever it was planted — and once Codex holds it, no retry of magpie's can strip it: client keeps, and #2855 came with magpie out of the path entirely. A Chat-API upstream's turn has always translated to an item of magpie's own (an rs_ id and a summary, TestTranslatedChatReasoningCarriesNoContent pins it); the items the reporter held are a Responses wire's own, which both the translated and the relayed reply handed over as they came. What magpie hands a client must be re-sendable to a strict Responses upstream: the text is kept in the summary, so an upstream that wants its reasoning back still gets it (withReasoningText), and magpie's own OpenAI destinations keep the item out as they did (#1008, #1044, #1411). Run - TestForeignSealedReasoningGivenCodexCarriesNoContent (translated) and TestForeignSealedReasoningRelayedCarriesNoContent (relayed) fail on upstream/main with the issue's item handed over whole — content, empty summary and the vendor's seal in both output_item.done and response.completed — and pass with the change; TestTranslatedChatReasoningCarriesNoContent (a Chat upstream's reasoning, translated) is green without and with the change. - Restoring the three product files alone to upstream/main (tests kept) fails the two again; restoring them back passes. - Attaching content to the made item fails both again ("carries its text"), and dropping the made summary fails both ("carries no summary"). - go test -tags nogui -count=1 ./internal/gateway: ok 312.4s; -run 'TestTranslated|TestReasoning|TestSealed': ok 7.9s; go test -race -tags nogui -count=1 -run 'TestTranslated|TestReasoning': ok 9.4s. gofmt -l internal/gateway empty. go vet -tags nogui and go build -tags nogui -o /dev/null . on darwin, GOOS=linux and GOOS=windows: pass (a pre-existing cgo -Wenum-conversion warning in internal/gui/trayimage_darwin.go on darwin, untouched). Not tried against real OpenAI or DeepSeek accounts; the reporter's rollout reading is taken from the issue, not re-derived from a live thread. Reviewed and landed as one batch of 12 commits (gua's #4593, #3269, sibling, and four review follow-ups). Run for the batch, whose last commit's tree is 5d58a75f3: - Full suite before the rebase (base |
||
|
|
0b9727ec93 |
gateway: a streamed reasoning summary the upstream seals by its own id is not given to the client twice (#2974)
What changed: - responsesDecoder remembers, by its output_index, the id a reasoning item went out added by, and tells the item's sealed done event by that id, so an upstream whose ids change per event (Copilot's) has its done recognized as the item that streamed. - responsesEncoder remembers the id KThinkStart came with whatever its shape (thinkUp; thinkID kept taking rs_ ids only) and closes the streamed item with the sealed one when the seal is that item's, instead of closing it unsealed and adding the sealed item again. Why: on the translated Responses -> Responses path, a reasoning item whose upstream id does not start with rs_ and that streams a summary reached the client twice — once under an rs_ id the encoder made up, then again whole at output_item.done, because the seal's id never matched the made-up one (#2974, reported and probed by yetone). Run (darwin/arm64, go test -tags nogui): - new TestResponsesStreamForeignReasoningIDNotDoubled (stable ids and ids that change per event) is red on |
||
|
|
ef0a5c673a |
gateway: a web search is left out of a request relayed to a provider that runs none (mxmllln)
mxmllln (Discord #feedback, magpie 0.1.2219, Codex Desktop 0.166.0-alpha.5.1 with remote_compaction_v2): a thread on commandcode/deepseek/deepseek-v4- flash-vision-exp with 52 function calls and 8 web searches (magpie ran them for the model through gpt-6.1-sol) failed compaction with Command Code's 400 "An assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'", and every later message too. Cause: a Responses turn that offers web_search to a provider that runs no search is translated for magpie's search, and the translation leaves the web_search_call items out (searchedForIt, searchRoundsBack). A request that offers no web_search is relayed as Codex sent it, items and all: magpie's summary request for a compaction_trigger (tools: []), the summary request Codex makes itself (#1270), a turn with search off. Command Code's Provider API turns the Responses request into chat for DeepSeek, a web_search_call becomes an assistant tool call nothing answers, and DeepSeek refuses it. pairToolItems pairs function and custom calls only. Fix: the relay of a Responses request leaves the web_search_call items out when the provider doesn't search for that model (searchesModel), as the translation does. Kept as they were: a provider that searches itself (Codex and Copilot accounts, OpenAI, Command Code's gpt-6-luna etc. on Responses), a relay Codex's turns go to as sent (codexAsSent), and a native compaction (keepsCompaction). The item holds only the query and the page URLs, never what the pages said, so there is no result text to pair it with; the reply after it says what was found. Other routes checked: the Responses -> Chat and -> Messages translations already drop the item (or, for Claude's signed thinking, pair it with a result through searchRoundsBack); Chat and Anthropic clients send no web_search_call; magpie's plain-text summary retry (plainCompact) reads no web_search_call. count_tokens is Anthropic-only. Tests: search_relay_history_test.go. A fake Command Code that refuses a deepseek request holding a web_search_call with DeepSeek's message, the history built from searchedHistory (a real ChatGPT backend web_search_call, 2026-10-09) plus a function call and its output: compaction_trigger, Codex's own summary request and a turn with search off each answer 200, nothing sent holds a web_search_call, the call and output stay. gpt-6-luna on the same provider still gets its search. Unit test for withoutSearchCalls. Run (mote-run, at this tree): - go test ./internal/gateway -run 'TestSearchedThread|TestWithoutSearchCalls' -v: ok - go test ./internal/gateway -run 'Search|Compact|Compaction|Pair|ToolRun|WithoutSearch': ok - gofmt -l internal/gateway: clean Broken by hand: with the withoutSearchCalls call taken out of attempt, all three TestSearchedThreadCompactsOnARelayThatDoesntSearch subtests fail. Not tried: a real Command Code account (none here), Codex Desktop on Windows, the reporter's thread. Full suite and Linux/Windows vet run after the push. |
||
|
|
2df46e3c87 |
gateway: Claude's thinking around magpie's search goes back where Claude wrote it (oreoft)
oreoft on Discord: Codex Desktop on a Claude model (Responses translated
to Messages) on a Bedrock-backed line. After a turn with reasoning and a
web_search_call, the next turn got 400 "messages.N.content.1: thinking or
redacted_thinking blocks in the latest assistant message cannot be
modified", Codex retried it ~6 times, then "stream disconnected".
Cause: on a line that doesn't search by itself, magpie runs the search
(searchRounds). Claude writes the reply as two messages: [thinking A,
text, web_search tool_use], then after magpie's tool_result [thinking B,
answer]. Codex keeps only the items: reasoning A, message,
web_search_call, reasoning B, message. parseResponses dropped the
web_search_call, so the next turn sent one message [thinking A, text,
thinking B, answer]. Each block kept its exact text and signature
(claudeseal), but B had moved, which Bedrock checks and direct Anthropic
lets pass.
Fix: parseResponses keeps a web_search_call as a Search part.
searchRoundsBack splits an assistant run that holds Claude's signed (or
redacted) thinking at each search into magpie's web_search call (named as
searchTool names it) and a result with the query and the pages found,
since what the search said was never kept. The latest assistant message
is then [thinking B, answer], as Claude wrote it. A search with no
Claude thinking beside it is left out, as before, and a history with no
web_search_call is untouched (direct Anthropic with valid signatures and
no search: same body as before).
Run:
- TestClaudeThinkingAroundMagpieSearchGoesBackAsWritten (new): a strict
fake Messages upstream refuses, with Bedrock's words, a latest
assistant message whose thinking blocks aren't one it wrote at the
same places. The test runs Codex's two turns through /v1/responses with
a fake Tavily, streamed and not. TestSearchWithoutClaudeThinkingStaysOut
(new). Both pass, with the focused Search/Codex tool-loop tests, on mote.
- Broken by hand (claudeSigned always false, i.e. the old drop): red with
"400 (refused 2) messages.1.content.1: thinking ... cannot be
modified", the reporter's error, after Codex-style retries.
- Full suite go test -tags nogui -count=1 -timeout 45m ./... on the Linux
box (mote had three other full suites running): every package ok except
internal/agent's TestInstalledVersion, TestGrokInstalled,
TestCursorFolderFromTheEditorIsNotTheCLI,
TestCopilotFolderFromAnIDEPluginIsNotTheCLI and TestOmpDetectedWithPiDir.
These are #4033 and #3548, red at main on that box, in a package this
change doesn't touch. After the rebase onto
|
||
|
|
024393fbb9 |
gateway: a Codex mode switch keeps its developer role on a translated Responses turn (#2532)
Refs yetone/magpie#2532 (the Responses-to-Responses translation case). An offered web_search can select translation even for a Responses upstream. Keep system/developer items in place instead of lifting initial Plan instructions and demoting a later Default update to a user reminder. Other APIs and the Claude bridge retain their existing cache mapping. Update the gateway routing reference and cover search continuation rounds. Verification on macOS arm64 with Go 1.26.10, isolated HOME and pinned caches: - New tests on unmodified |
||
|
|
fa427216a4 |
gateway: a Responses stream's argument deltas go to the call they name, one call each
JoeyWu-tech (#3985): a Responses upstream that adds two function_call items before either is argued (output_index 0 and 1, every delta and done naming its item_id) reached a Chat client as call_1 with no arguments and call_2 with both calls' run together. responsesDecoder opened a call at every response.output_item.added and gave every response.function_call_arguments.delta to the call opened last, never matching it by the delta's item_id or output_index — the same shape #3945 fixed on Messages and |
||
|
|
fc43c69e53 |
gateway: a Codex thread switched to another effort is shown and sent at it
zzzkl3994 (Discord #feedback): Codex switched from medium to xhigh
mid-session, and Routing still showed medium. Their rollout had
{"type":"configuration_update","reasoning":{"effort":"xhigh"}}.
What Codex sends, captured from the real codex 0.162.1 TUI in a sandbox
CODEX_HOME against a local Responses server (built-in openai provider
via openai_base_url, /model -> Extra high -> "s"):
- reasoning_effort_override off (the default): reasoning.effort at the
top goes xhigh; no item.
- reasoning_effort_override on: the top stays at the thread's first
(medium), and every turn carries a configuration_update after its user
message, the last one {"effort":"xhigh"}. This is the reporter's case.
magpie read only the top, so for such a thread:
- Routing's route and try showed medium (requestEffort/bodyEffort);
- a Responses vendor not OpenAI's got the items taken out (forVendor)
and was asked at medium;
- a translated request (parseResponses) was asked at medium;
- magpie's own pick (withEffort, a fixed member) set the top, which an
upstream reading the items overrode.
Now the effort of a Responses request is its last configuration_update's
when it has one (effortUpdated):
- bodyEffort/requestEffort read it, so Routing, tries and usage say xhigh;
- parseResponses takes it as the request's effort;
- forVendor puts it at the top where it takes the items out;
- withBodyEffort and withFixedEffort rewrite the last update (the top
stays, so the thread's prefix does too);
- withoutAnyReasoning drops the items with the reasoning ask.
OpenAI's API and the ChatGPT backend still get the body as Codex sent it.
No Codex prompt or base_instructions is touched.
Tests (codex_effort_change_test.go), built from the captured request:
- TestCodexEffortChangeShownAndSent: route and try at xhigh, a Responses
relay asked xhigh with no item;
- TestCodexEffortChangeReachesChatVendor: Chat vendor asked xhigh;
- TestCodexEffortChangeReaders: readers, magpie's pick, a fixed effort,
reasonless, and OpenAI/ChatGPT bodies byte for byte.
Red on the old code (fix files stashed, two stub funcs): all three fail,
route at "medium", sent medium.
Run at this head (rebased on
|
||
|
|
8eb7f5565b |
gateway: a translated body lets its built conversation go as it fills (#4004)
marshalBody wrote a translated request's list (Chat's and Anthropic's messages, Responses' input) an item at a time, but the list itself, the conversation the builder made, strings joined from the request's parts among it, stayed held in the body's map until the whole body was written: at the body's peak it sat beside the written items and the body. The builder names that list as spent, and each item is set to its zero value once written. Every caller's map is its own and dropped after the call (buildChat, buildAnthropic, buildResponses); buildGemini spends nothing. Keys are checked before anything is spent, so the json.Marshal fallback for an odd key still sees the whole map. Measured on mote, TestZZPeak4004-style scratch harness (not committed): a 45 MiB Codex conversation sent Responses -> Chat through the gateway, GOGC=10, HeapInuse sampled every 2 ms, 3 runs each: base |
||
|
|
0b99b8fbe5 |
gateway: a translated body is written a message at a time (#4004)
jihuayu's heap profile (#4004, v0.1.1707 on a 2 GiB server) had json.Marshal and its bytes.growSlice under buildChat as the largest holders, about 128 MiB together, on 45 MiB Codex requests. json.Marshal writes the whole body into one buffer that doubles as it fills and then copies it out, so each grown-out buffer is garbage until the next GC. marshalBody writes the same bytes: the keys sorted, every value through json.Marshal, but a list (messages, input items, contents) one item at a time, into one buffer sized to what they come to. buildChat, buildResponses, anthropicBody and buildGemini use it. Anything json.Marshal refuses gets json.Marshal's own answer. A slice's items are marshalled by address, as json.Marshal reaches them, so a MarshalJSON on the pointer is still called. Run on mote at this head: - TestMarshalBodyIsJSONMarshal: byte-equal to json.Marshal for lists of maps and of typed maps, one-item, empty and nil lists, nil, []byte, json.RawMessage and lists of it, pointer and value Marshalers, HTML characters, U+2028/2029, control characters, escaped keys; NaN, Inf and a chan are refused as json.Marshal refuses them. - TestMarshalBodyAllocatesTwoBodies: a 47 MiB, 170-message body. json.Marshal allocated 205 MiB, marshalBody 98 MiB. The bar is 2.5x the body (117 MiB), which json.Marshal's 205 fails. - go vet ./internal/gateway for darwin, linux and windows: ok. - go test ./internal/gateway -timeout 45m: ok (543s), and again after the rebase onto origin/main, at this head: ok (529s). Real account, on this Mac in a sandbox HOME with only the DeepSeek provider copied: a streamed Codex-style /v1/responses request with a function call and a ~100 KB tool output (translated, 36,343 tokens in) answered about the tool's output and completed. /v1/messages and /v1/chat/completions also answered 200. Not tried: a 45 MiB request against a real vendor; the plugin RPC copy and toolOutput's unquote, which the same profile lists, are separate changes. |
||
|
|
8c5c83c9fc |
gateway: a Responses client's cache marks to Claude last an hour (#3972)
7eleven (Discord #feedback, #3972): Codex routed to a Claude model on an Anthropic Messages upstream (an API key or a relay) had the cache marks magpie adds at Anthropic's default five minutes. Codex's turns are often further apart, so the thread's prompt was written again after each pause. Decided, zero config: the marks anthropicBody adds for a Responses client to a Claude model carry ttl 1h (addedMark, Request.hourMarks). - Price (claude-api skill, prompt caching): a 5m write is 1.25x input, a 1h write 2x, a read 0.1x (less on Opus 5.5 / Fable). In a busy loop the 1h marks cost 0.75x more on each turn's new tokens only; one turn after a 5 to 60 minute pause reads the prefix instead of writing it again (1.25x of the whole prefix), which pays for dozens of turns. - Codex's own vendor keeps a thread cached an hour (chatGPTCold); Claude subscriptions already go 1h through Claude Code (cacheMark1h). - No magpie setting exists for these marks: tune's cache_ttl and subagent_cache_ttl write Claude Code's own settings and don't apply. - The client's own say wins: prompt_cache_retention "in_memory" keeps 5m; marks a client placed itself are never touched (only magpie's added marks change). Every added mark has the same ttl, so none follows a shorter one. - A relay that answers 400 naming cache_control and ttl is asked again at 5m and remembered in unfit (hourMarksRefused). - Not changed: Chat clients' marks (OpenCode and one-off callers alike) stay 5m; left open on #3972. Non-Claude models on Messages unchanged. Tests: TestResponsesToClaudeMarksLastAnHour, TestHourMarksRefused. Broken by hand, each on mote: - addedMark always 5m: the four 1h subtests and both refusal cases red. - the refusal retry removed: "ttl refused" red (400 after 1 call). - in_memory ignored (hourMarks = true): "in_memory asked" red. Docs: gateway-routing.md, a bullet beside the Kiro cache marks. Run (mote, at this commit): go build -tags nogui ./... ok; go test -tags nogui ./internal/gateway ok (522.7s). Not run: full suite (pushed at once per the owner's rule). GOOS=linux and GOOS=windows go vet ./internal/gateway ok; gofmt -l clean. Not tried: a real Anthropic key or relay (no request was sent upstream), Bedrock or Vertex with ttl 1h (the refusal fallback covers a 400). |
||
|
|
2a19245cec |
gateway: Codex's output token replay goes to OpenAI only (Copilot refused it)
echo_ts on Discord (#feedback): a Codex conversation begun on gpt-6-astra
and carried on on a Copilot model failed with "Copilot: Invalid value:
'output.encrypted_content'. Supported values are: ...".
Cause: Codex with output token replay on (codex-rs core/src/client.rs)
adds "output.encrypted_content" to include, and keeps each message's and
call's sealed copy (encrypted_content) in its history, only for a
provider named "OpenAI". Signed in, Codex reaches magpie as that
provider, so a magpie model got both as they came: the passthrough to
Copilot's /responses (forVendor) and the rebuilt request (buildResponses)
both kept the include, and Copilot refuses it.
Now magpie does what Codex does under any other provider name
(!is_openai): forVendor drops output.encrypted_content from include and
encrypted_content from every input item but reasoning and compactions
(ResponseItem::clear_encrypted_content keeps those). buildResponses asks
for it only of api.openai.com and chatgpt.com. OpenAI's API and the
ChatGPT backend get the request as before. Astra's sealed reasoning
still goes along; one Copilot can't read is taken out once refused, as
before (foreignReasoning).
Tests: TestCodexOutputReplayStaysWithOpenAI (the fake refuses with the
reporter's literal error; signed-in and /v1/responses routes) and
TestResponsesOutputReplayOnlyToOpenAI. The rewrite equivalence test's
reference copy (wasForVendor) gets the same rule, with new marks.
Run: go test ./internal/gateway -count=1 -timeout 45m: every test ok but TestHandedOverGatewayFinishesItsStream
("request 0 during the handover: ... EOF"), which this change doesn't
reach; it passes 5 of 5 alone (-count=5) and is open as #3568.
gofmt -l clean; go vet, GOOS=windows and GOOS=linux go vet of
internal/gateway clean.
Broken by hand: with codex_backend.go and responses.go as on main, both
new tests are red (400 with the reporter's error; include kept for
api.githubcopilot.com, relay.example and api.x.ai).
Not tried: a real Codex with output token replay against a real Copilot
account, nor Copilot's answer to a message's encrypted_content alone
(left out because Codex leaves it out for any provider not OpenAI's).
|
||
|
|
79c8667c92 |
gateway: Codex gives Claude its signed thinking back through encrypted_content
Codex calling a Claude model through magpie (mysterious_dove_96933 on
Discord): a reply's reasoning items carried only the summary, so Claude's
thinking signature and a redacted_thinking block's data were gone. On
the next request of a tool loop magpie sent Anthropic the turn as
[tool_use] alone, with thinking on, which Anthropic documents as a 400
("final assistant message must start with a thinking block"), and the
model lost its reasoning across calls either way.
Now the Anthropic decoders name a signature as Claude's (KSig with
sealAnthropic, Part.SignedBy). 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 (internal/claudeseal):
its summary beside it, an empty summary for a block signed with no
text, and redacted_thinking as an item of its own. parseResponses reads
it back into the block as Claude wrote it, in order, so anthropicBody
sends it as before for an Anthropic client. A Gemini thought's
signature isn't named and isn't sealed.
The envelope never reaches a Responses API: withoutClaudeSeals in
passthrough and forwardOnce (the item keeps its summary, one with none
goes), codexInputAs leaves such an item out for Codex's own models, and
codexUpstreamOn takes it out before the ChatGPT backend. OpenAI's own
encrypted_content is untouched. sessions.PortCodexRollouts writes such
an item as its summary, so a thread resumed against OpenAI itself isn't
refused. redact.MaskJSON already keeps a reasoning item's seal whole
(no change); TestMaskJSONKeepsClaudeBlocks holds that.
Run, at
|
||
|
|
44a626bed3 |
gateway: an image's detail reaches a Chat or Responses upstream; Responses' original goes to Chat as high (mysterious_dove)
mysterious_dove on Discord (Codex): a Responses request translated to Chat Completions lost every image's detail, so detail=high and detail=original were dropped. The IR had no field for it: Part now carries Detail, read from a Responses input_image and a Chat image_url object, in message content and in a tool's output (toolOutput). - Chat (buildChat, chatImage/chatDetail): low, high and auto go as they came; Responses' original, which Chat lacks, goes as high; an image with no detail goes without one, as before. Both the message image and a tool's image (the follow-up user message) use it. - Responses (buildResponses and the orphaned tool output rewrite, responsesDetail): the sibling. A Chat client's low/high, and a Responses client's original, reached a Responses upstream as auto. They now go as sent; anything else, none included, is still auto (#1474's strict vLLM needs one). - Anthropic and Gemini have no such field; nothing is sent there. Ollama's native route has none either. buildChat/buildResponses are the one choke point for translations, plugins included. The GUI "downgrade list" with "图片 detail=high 降级:丢弃" named in the report isn't in magpie, the plugins repo or the site (grepped for the labels, 降级, detail=, downgrade): it is not changed here. Doc: docs/subsystems/gateway-routing.md gets a bullet beside the tool images one. Tests (internal/gateway/image_detail_chat_test.go): - TestResponsesImageDetailReachesChat: high, original, low, auto, none, and a function_call_output image with original -> high, high, low, auto, "", high. - TestChatImageDetailReachesResponses: low, high, none -> low, high, auto. Red on the old code (chat.go, ir.go, responses.go stashed): Chat images had detail "" for all four, Responses had "auto" for low and high. Broken by hand (chatDetail returning "original" for original): red with detail "original", want "high" on images 1 and 5. Run: - gofmt -l internal/gateway: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok. - go test -tags nogui ./internal/gateway (sandbox HOME): ok 492s. - Full go test -tags nogui -count=1 -timeout 45m ./... in a sandbox HOME at 22a563c4f (this change on |
||
|
|
d088030315 |
gateway: a long Codex request's facts, tier and metadata skip the walks over its conversation (#3394)
A Codex Responses request carries the whole conversation, and the gateway
walked it several times per request for what it reads at the top level:
- requestSessionMetadata searched the body for "client_metadata", which
Codex sends last, before asking topMember. A long body now asks the
memoized split straight away.
- bodyTier asked gjson for speed and service_tier, walking the body each
time; a long body now asks topMember too (topValue).
- userWords ran its reminder and "## My request" regexes on every text;
each now runs only when its marker is present.
- readFacts (turn count, work folder) ran the full parse. It now parses
in facts mode (readResponses): views over the raw bytes, no parts for
assistant replies, and tool outputs as bare ToolResult parts, which is
all turnIn and workPlace read.
Bench (a fake ChatGPT backend, ~2MB Codex body, client_metadata last),
per request: 31.7ms, 24.2MB, 71.2k allocs on origin/main; 19.2-21.4ms,
17.2MB, 59.6k allocs with these and the provider commit after it.
Real account: a sandbox HOME with only the deepseek provider, 310KB
Responses bodies to deepseek/deepseek-flash through `magpie serve`:
base 15ms process CPU per request (19/20 ok), new 13ms (20/20, then
8/8 again).
TestResponsesFactsAsTheWholeParse compares readFacts with the full
parse's turnIn and workPlace over constructed bodies and five real Codex
fixtures. Broken by hand twice (user parts skipped; ToolResult turned
into Text): red both times. tier_record_test adds four long-body cases
(tier after the conversation, a nested one ignored, Anthropic speed
fast, a Chat numeric tier).
Run at this head (
|
||
|
|
e57e785633 |
gateway: a rewritten body is written back by marshalJSON, not json.Marshal (#3394)
withReasoningText runs on every replayed request to DeepSeek and the
like (#1104), and wrote the whole body back with json.Marshal twice:
once for the input list, once for the body around it. encoding/json
writes a json.RawMessage through its scanner, a call a byte, so a long
conversation was compacted twice a request. marshalJSON (marshalRaw,
#1532) writes the same bytes, checked by jsonCheck and copied, and
falls back to json.Marshal for any other value; TestMarshalRawIsEncodingJSON
holds the two equal. The same body rewrites in affinity.go,
anthropic.go, codex_backend.go and limit.go took json.Marshal of a
map[string]json.RawMessage too, and use marshalJSON now. Nothing a
body goes out as changes.
Run:
- Real DeepSeek account in a sandbox HOME, magpie serve on 3482, 12
streamed /v1/responses requests of a synthetic 1.5MB conversation with
Codex 0.162.0's real tools and a codex_cli_rs/0.162.1 User-Agent, CPU
time from ps, two rounds each:
|
||
|
|
1859da57bd |
gateway: readers of a rewritten request see its input in place (#3383)
Only the body a request arrived with is held (holdBody), so decodeJSON
shares a raw value with it and copies one from any other body. Once a
route rewrites a Codex request (its model, its fields), the new body is
held by nobody, and each reader that only looks at it copied the whole
input to do so: conversationID, hasSealedAgentMessage,
orphanedToolOutputs, joinToolRuns, pairToolItems, withReasoningText,
and affinity's seal and kind strippers. Each such copy was ~0.4 to
0.5 MB on a 680 KB request.
decodeJSONView is decodeJSON whose raw values always share the bytes
they came from, capped, for a reader that keeps nothing it decodes and
writes none of it. Those readers use it. Each one only reads, or builds
a new body with json.Marshal or marshalPlain (which copy), or returns
the body it was given. promptBuilder keeps raw parts past its return,
and parseResponses keeps its result, so both stay on decodeJSON.
Measured on the 680 KB Codex request benchmark (30x, 3 runs):
16.37 MB/op, 54,703 allocs/op -> 14.96 MB/op, 54,222 allocs/op (-8.6%).
What was run:
- TestDecodeJSONViewShares: q["input"], q["tools"] and an item's
content from decodeJSONView point into the body and are capped, and
decodeJSON still copies from a body that isn't held. With `share ||`
taken out of fillJSONIn it is red ("tools []: not body's own bytes,
capped"); restored, green.
- fjCompare checks decodeJSONView against json.Unmarshal on every seed
as it does decodeJSON.
- Real DeepSeek A/B through a recording proxy in a sandbox HOME, Codex
UA, 5 requests with a tool-call history:
|
||
|
|
d7ad3f2a3e |
gateway: input scanners read a request's items in place, not copied (#3383)
Seven readers of a Responses request's input (the seal stripper and withoutKinds in affinity, hasSealedAgentMessage, joinToolRuns, orphanedToolOutputs, pairToolItems, withReasoningText) and the prompt builder decoded `input` into a []json.RawMessage. fillJSONIn clones each RawMessage under a sixteenth of the held body, so every item of a long Codex history was copied once per reader, per request. None of them keeps an item past its return (they marshal new output or assign into the slice), so inputList hands them elementsOf's capped subslices of the raw input instead. hasSealedAgentMessage reads an item's content the same way. Run at |
||
|
|
efb7cb11d4 |
gateway: a safety refusal said in a stream is a refusal for a client answered whole too, and rests nobody (#3274, CartethyiaQwQ)
CartethyiaQwQ (#3274): Codex's "safety filter: cyber_policy" refusal (the Daybreak note) set healthy accounts aside; two such turns benched a five-account pool for about 17 minutes. Cause: the HTTP 400 cyber_policy is already a refusal (policyRefusal reads its code: next account asked, nobody rests), and so is one said in a stream relayed as a stream. A Codex account is always streamed upstream, so a stream:false Responses, Chat or Messages request is answered from that stream whole. There, a response.failed or error event whose error has a code (cyber_policy) but no invalid_request_error type got no status from the decoder, and the whole path answered it 502 api_error: retried on the same account, then every account asked, each one but the last resting by backoff. A refusal after a few words went to the client as a finished 200 turn, and the failure after it rested the account. Fix, at the decoders and the whole path: - filterRefused (fallback.go): a stream error event refusedCode reads as the safety filter's gets status 400 and Said {"error":{type invalid_request_error, code}}. Used by every decoder that set Code: refusedCode -- Responses (both error sites, after requestRefused), Chat, Anthropic and carriedError. - The whole path (gateway.go) answers a reply the filter cut part way as the refusal, not its words so far, and notes it in refusedHeader, since Anthropic's error shape drops the code that settle reads. - restAfterMarked: a 400 whose error object policyRefusal reads as a refusal rests nobody and counts no failure (By "off", Why refused), as the ZDR refusal does, for any route that reaches it. - docs/subsystems/gateway-routing.md says so. Review of the submitted patch (dc6c695db, not taken as is): it matched `safety filter|cyber_policy|Daybreak access` anywhere in a 400's words, so a 400 that echoes the user's prompt in its message skipped the rest too; its fixture was magpie's own refusedError text, which restAfter is never handed for a 400; and it gated on status 400, while the path that rested (above) answered 502, so it would not have stopped the rests. Its restAfter unit tests' shape is kept in TestRestAfterPolicyRefusal. Run at |
||
|
|
f5b0157420 |
gateway: a tool Claude Code's tool search loads goes to OpenAI's Responses API where it was loaded (#2660)
Through /v1/messages translated to a Responses provider, every deferred
tool ToolSearch loaded joined the top-level tools on the next request, so
the prompt changed from its first bytes and the cache missed on each load
(maximia's probe: cached tokens dropped on every request after a load).
Now, where Request.LoadedInPlace is set, a deferred tool (defer_loading,
Tool.Deferred) that a tool_result's tool_reference names (toolRefs,
Part.Loads) goes in an {"type":"additional_tools","role":"developer",
"tools":[...]} item right after the run of tool outputs that loaded it,
once, and not in tools (buildResponses). Parallel results and one result
naming several share one item; a tool named again isn't repeated; the
output's text is as before. A history whose loading result is gone
(compaction, edits) puts the tool back in tools: a new prefix, expected.
Scope (loadsInPlace): OpenAI's own API with a key (api.openai.com,
*.api.openai.com), whose tool search guide documents the item and says
its tools load at the end of the context so the cache is kept; and a
provider the user sets with `magpie provider set <id> additional-tools=on`
(Provider.AdditionalTools, kept by the GUI's save like codexAsSent).
Nothing else: xAI answers the item 422 (#350), the ChatGPT backend has
been seen taking it only for Codex's Responses Lite, Azure, plugins and
relays are untried. An upstream that refuses a request holding the item
with a 400/422 naming additional_tools is asked again with every tool in
tools, logged ("turned away additional_tools ... loaded tools go in tools
from now on") and not sent the item again while magpie runs.
Not handled: a tool a tool_addition block in a system message loads (MCP
late tools, the advisor) stays in tools. Not tried against a real
upstream: no OpenAI key or custom Responses relay was used; the item's
shape and position follow OpenAI's docs, and the fixtures follow
maximia's three-request probe (Claude Code 2.1.302) and the
tool_reference shape Claude Code 2.1.306's binary writes.
Tests: TestLoadedToolsKeepThePrefix (top-level tools and instructions
identical across the three requests, each input a prefix of the next),
TestLoadedToolsInOneItem (parallel, batch, repeat), TestLoadedToolsWhereNotTaken
(unsupported upstream unchanged; compacted; non-deferred),
TestLoadsInPlaceScope, TestLoadedToolsThroughTheGateway (off by default on
a relay, on with the flag, refusal retried without the item and not sent
again), TestAdditionalToolsPair (CLI). Broken by hand: with the
buildResponses placement disabled, the first two and the gateway test go
red; with the refusal retry disabled, TestLoadedToolsThroughTheGateway
goes red.
Run at cff7dc67d (this change on
|
||
|
|
19527ca8dd |
gateway: tools turned off with none declared reach a plugin as tool_choice none (#3110)
Cause: buildResponses wrote tool_choice only inside its tools block, so a
Chat "none", Anthropic {"type":"none"} or Gemini NONE with no tools was
dropped on the way to Responses. A provider plugin that adds a
server-side tool (Grok's x_search, plugins PR #263) couldn't tell
"tools off" from "no choice". The other builders (Chat, Anthropic,
Gemini, Code Assist) send no tool choice without tools, which is what
their vendors accept (OpenAI Chat refuses a lone tool_choice), so they
are unchanged.
Fix:
- buildResponses keeps a lone "none" (only "none"; "" and "auto"
still go unsaid).
- forwardTranslated strips it again for every non-plugin upstream, and
for a plugin on api.x.ai or Copilot (refusesLoneToolChoice, the #378
rule now shared with passthrough). A vendor never sees it.
- The grok plugin's body shaping (grokPluginBody) keeps a lone "none";
the built-in's grokBody still drops it. grok plugin 0.1.18
(magpie-community/plugins aee6b9d, on npm) drops any lone tool_choice
itself before Grok, so the mover's min goes 0.1.17 -> 0.1.18.
Run at this commit (worktree on
|
||
|
|
ec7f474323 |
gateway: Codex on Copilot is relayed with its web_search, and a translated call's arguments stream (echo_ts)
echo_ts (magpie 0.1.1279, macOS): Codex on a GitHub Copilot subscription
through magpie was about 10x slower than Copilot directly. Two causes,
both in the gateway:
- Codex offers web_search on every turn, and magpie counted Copilot as a
provider that can't search, so every Codex turn on Copilot was
translated for magpie's search instead of relayed.
- On that translated path responsesDecoder held a call's argument deltas
until the call was done, so Codex saw nothing while the model wrote a
command or a patch, then all of it at once. A custom tool (apply_patch)
got no custom_tool_call_input deltas at all.
Fixes:
- search.go: searchesItself counts a Copilot account on Responses. Real
check on 2026-10-17 with the owner's account: gpt-5.3-codex,
gpt-5.4-mini, gpt-6-luna, grok-4.7 and mai-code-1.1-flash each answered
a request offering web_search with web_search_call items and cited
pages. searchRank never picks Copilot to search for another provider's
models (its premium requests).
- gateway.go: a Copilot Responses request whose tools mark an argument
"encrypted" (MultiAgentV2's spawn_agent message) is still translated,
marks left out (asksSealing in responses.go). Checked on the real
account: relayed, Copilot seals the message ("UlQC...", no
encrypted_function_args), and the subagent's turn carrying it came back
"Encrypted function output content could not be decrypted or
decoded". This was already broken for a Copilot turn without
web_search; it is fixed for that too. An unsealed agent_message relayed
with web_search answers normally (checked).
- responses.go: responsesDecoder gives argument deltas as they come. It
holds only the deltas that make the arguments whole JSON, until the
done events, so #613's case (deltas that disagree with done) still
ends with the fuller arguments. The encoder sends a custom tool's input
as custom_tool_call_input.delta, read out of the {"input": ...}
arguments as they stream (customStream in custom_tool.go, which waits
for cut escapes, surrogate pairs and UTF-8), and closes it with
custom_tool_call_input.done.
- docs/subsystems/gateway-routing.md says the above.
Not changed: the HTTP/2 connection. Head-of-line blocking from large
uploads on the one connection to Copilot was measured on the real
account with a Go client: a 4MB request and a small one 300ms later,
5 rounds x 2, same connection vs a new one. The small request's first
byte took 0.93-1.68s on the shared connection, 1.26-4.77s on its own
(handshake included), 0.66-1.08s alone. No sign of blocking.
Small requests slower while a long session runs (echo_ts, 42.8s vs
17-29s first text, xhigh): nothing in magpie serializes Copilot requests
by default (lanes need MaxConcurrency, the RPM gate MaxRPM; Go's h2
windows are 1GB per connection, 4MB per stream). Measured: small
requests beside a 412s xhigh stream (16,617 output tokens) were as fast
as idle, via magpie 0.8-1.1s first text, direct 1.3-2.0s, sent_ms
1-10ms. One global lock found: copilotMu is held across the token
refresh's HTTP call, which stalls every Copilot request only around a
refresh, filed as #2762, not changed here. usage.jsonl's own_ms,
queued_ms and sent_ms against ttft_ms tell magpie's time from Copilot's.
Tests:
- TestCallArgsStreamWhenTranslated (function and custom), through the
real handler with an upstream that holds the rest of the call until
the client has the first delta.
- TestResponsesCallArgsStream, TestCustomInputStreams (pieces of 1, 2, 3,
5, 7 bytes and whole).
- TestCopilotRelayedUnlessAskedToSeal; TestCopilotUltraSubagentWithWebSearch
now expects the subagent relayed with the search.
Broken by hand at this tree, each went red:
- decoder holding every delta: TestCallArgsStreamWhenTranslated,
TestResponsesCallArgsStream;
- no custom input delta: TestCallArgsStreamWhenTranslated/custom;
- Copilot out of searchesItself: TestCopilotRelayedUnlessAskedToSeal,
TestCopilotUltraSubagentWithWebSearch;
- the asksSealing check off: the same two.
Real use: a built magpie serve in a sandbox HOME (port 3461) with the
owner's Copilot account, Codex-shaped requests offering exec_command,
apply_patch and web_search to copilot/gpt-5.3-codex:
- unmarked: relayed (Copilot's own response ids), apply_patch gave 93
custom_tool_call_input deltas from 3.55s to 11.69s;
- with a sealed spawn_agent: translated, apply_patch 117 deltas from
1.45s to 11.73s, exec_command 92 function_call_arguments deltas from
1.55s to 8.16s.
Not tried with the Codex binary itself.
Run at
|
||
|
|
55d6ea4ffc |
gateway: a translated model's messages say their phase, so Codex folds them (#2437)
Codex Desktop folds a finished turn's commentary and calls under "Worked
for …" by each assistant message's `phase`, which OpenAI's own models
write ("commentary" / "final_answer"). A message with none is read as an
answer, so every progress line of a model magpie translates (the
reporter's Qoder plugin, a chat upstream) stayed unfolded.
The Responses encoder now holds a message's output_item.done until the
next item that isn't reasoning opens (commentary) or the reply completes
(final_answer); the completed output carries the same phases.
renderResponses does the same for a whole reply. A Responses upstream
relayed as it is (passthrough) gets the same rule through a new phase
tidy, streamed or whole. A phase the upstream wrote is kept; a reply cut
short (incomplete, failed, error, a stream with no end) guesses no final
answer, since Codex reads a missing phase as the answer. Keepalives go
out at once; sequence numbers are given in write order. At most 512
events wait behind a message, then it goes without a phase. Codex's
base_instructions are not touched.
Run (worktree at origin/main
|
||
|
|
dd25997a45 |
codex: a client's access_programs and the account's extraBody reach the ChatGPT backend, and its refusal comes back as it said it (magpie-releases#18)
NonMirror (0.1.1239, OpenCode, codex/gpt-daybreak-blue-latest on a ChatGPT
sign-in): a top-level Responses access_programs never reached upstream,
and the codex provider's extraBody wasn't applied.
Cause:
- A Codex account is streamed upstream, so a whole (stream:false)
Responses request and every Chat or Messages request is translated
(parseResponses/parseChat -> Request -> buildResponses). Request had no
field for access_programs, so the rebuilt body dropped it. Only a
streamed Responses request, relayed through codexBody, kept it.
- WithExtraBody skipped every signed-in account, and withPicks didn't
copy the providers.json ExtraBody onto the account.
- writeError rewrapped every vendor error with code and param null, so
even a forwarded refusal lost what it was about.
- The backend refuses a program the workspace hasn't got inside a 200
stream (error event, invalid_request_error, access_program_not_enabled).
The whole-translated path answered that 502 api_error, and translated
streams wrote it as api_error, which holdWriter reads as 502: the same
request went three times, then to the other accounts, and every one
rested.
Fix:
- Request.AccessPrograms (Responses and Chat), built into the Responses
body as it came; a null is kept.
- A ChatGPT (Codex) account takes extraBody; store, tool_choice and
include stay magpie's (codexOwned). withPicks keeps ExtraBody.
- writeVendorError keeps the vendor's error.code and error.param on the
relayed, whole-translated and streamed-translated status-error paths.
- requestRefused: a Responses stream error/failed whose error type is
invalid_request_error carries status 400 and the vendor's error
(Event.Said). The whole path answers that 400 with code and param; the
Chat, Anthropic and Responses encoders write its type/code/param
(saidError). Read by the type, never by words.
- Codex CLI sends access_programs as a top-level object on its Responses
request (codex-rs ResponsesApiRequest.access_programs); OpenAI's Daybreak
guide documents the same field.
Run:
- New: internal/gateway/codex_access_programs_test.go
(TestCodexAccessProgramsReachBackend, TestCodexAccountTakesExtraBody,
TestAccessProgramsNullKept), passes -count=3.
- Broken by hand, each went red: buildResponses not emitting the field
(probe answered 200, the reporter's symptom); extraBodyTakes' Codex case;
withPicks' line; codexOwned emptied; writeVendorError ignoring the body;
the continuation site alone; retryable(400) true (asked twice, rested);
requestRefused returning nothing (502, asked 4 times, both accounts
rested); saidError a no-op (streamed: asked 4 times, rested); the whole
site back to 502 (same).
- go test -timeout 30m ./...: all 62 packages ok (gateway 1559s at load
~26; an earlier run at the default 10m timed out in gateway under that
load, not a failure). gofmt -l clean. GOOS=linux and GOOS=windows
go vet -tags nogui ./... clean.
Real account (sandbox HOME, own port 3486, copied auth.json with a dead
refresh token; owner's ChatGPT Pro account, model codex/gpt-5.6-luna):
- "__daybreak_forwarding_probe__": 400 invalid_value, param
access_programs.cyber ("Supported values are: 'standard',
'daybreak_blue', and 'daybreak_red'") on Responses whole and streamed,
Chat whole and streamed. The backend says invalid_value, not the
guide's invalid_access_program.
- standard: 200. null: 400 invalid_type.
- daybreak_blue (not enabled for this workspace): 400
access_program_not_enabled with param on Responses and Chat whole, the
error event with that code on Responses and Chat streamed; ~1s each,
one try (was 3 tries and a 502 before this change).
- The next plain request was served 200 by the same account: nothing
rested.
Not verified: the Daybreak model itself (not listed for this account),
so no 200 with daybreak_blue; OpenCode's own wire; the Messages route
against the real backend (fake backend only).
|
||
|
|
919c8b934a |
gateway: a second answer to one call is dropped on the way to Gemini and Responses (#2262, ggbdpq)
A client that answers one tool call twice sent Google a call turn with more functionResponses than functionCalls, which Google refuses with 400, along with every later turn of the conversation. The Chat and Messages builds already keep the first answer (pairToolMessages, pairToolBlocks). The Gemini build (buildCodeAssistSent: Google sign-in, Vertex, a custom Gemini provider) and the Responses build (buildResponses) now leave the second one out before they build, with the images it carried (dropSecondAnswers). A call made again under the same id takes an answer of its own, and the request itself is left as it was, since a fallback builds from it again. This differs from the issue's patch. It dedups across the whole history in pairFunctionTurns, keyed by id, or by name when there is no id. Keying by name drops a real answer to a second call of the same function. Keying by id ignores a call made again under that id. The patch also left the duplicate's images in the turn and didn't cover Responses. Also fixed: parseGemini matched a functionResponse with no id to the latest call of that name, so two calls of one function were both answered as the second. Each now goes to the first call of that name still unanswered. pairToolItems (relayed Codex bodies) already keeps one answer per call and is unchanged. Run: - gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui, GOOS=windows): clean. - go test -tags nogui -p 4 -timeout 40m ./... with the other three commits of this push: see the last one's body. Broken by hand: TestGeminiDropsASecondAnswer, TestSecondAnswerDroppedWithItsImages and TestGeminiClientUnnamedCallsAnsweredInOrder fail on the code before this. Not tried: against Google's or a Responses upstream's real API. Co-authored-by: ggbdpq <ggbdpq@gmail.com> |
||
|
|
f348025c09 |
gateway: a Chat or Messages client's interrupted tool call gets its synthetic result on the way into Responses, not the upstream's 400 "No tool output found" every turn (#2222, ggbdpq)
A Chat or Anthropic client whose turn was cut off (Esc, a dropped connection, a crash) sends its history with a tool call no result answers. buildChat and buildAnthropic each give such a call a synthetic result (pairToolMessages, pairToolBlocks), but buildResponses didn't, so a Responses upstream answered 400 "No tool output found for function call <id>" on that turn and every turn after it. ggbdpq's patch called pairToolItems on the body in forwardTranslated. It is called at the end of buildResponses instead: that is where every Responses body is built from a client's request, including Zed's (zed.go builds through it and doesn't pass forwardTranslated). The patch's tests are kept as written. Run, on origin/main |
||
|
|
9f8ad6edb8 |
gateway: the model's text between a batch's tool calls goes ahead of the batch's first call, so OpenCode Go stops answering "No tool output found" (#2100, eugene1003)
What: joinToolRuns (responses.go), which mends a relayed Responses
request's tool runs in attempt before every destination, now moves an
assistant message the model wrote between its own calls, before the run's
first result, to just ahead of the run's first call, together with the
reasoning items right before it (so a reasoning item keeps the item that
followed it). The reporter's Codex rollout was
[text, call_A, text, call_B, out_A, out_B]; it reaches the upstream as
[text, text, call_A, call_B, out_A, out_B]. Reasoning alone between calls,
hosted calls and anything carrying a call_id stay where they were (#1752's
review note), and V2 (text after out_A, between whole exchanges) and V3
(calls together) go byte for byte.
Why: magpie relays deepseek-v4.1-flash at OpenCode Go to its /responses
(models.dev names no SDK for it, so every API may be tried, and #1822's
turn shows Go's DeepSeek answering there). Go builds a chat form in which
an assistant message after a call opens a new assistant message, so the
first one's tool_calls were followed by no tool message: 400 "No tool
output found for tool call call_aaaa1111" - the same text joinToolRuns'
comment already lists for Go. The translation to a Chat upstream was
already right on main (joinSplitCalls + mergeTurns join the step into one
assistant message); TestTextBetweenABatchsCallsStaysInItsStep now guards
it with the reporter's shape. Native ChatGPT sign-ins don't go through
joinToolRuns. Moved plugins get the relayed body after attempt, so they
get the change too; no plugin translator was touched.
Run:
- TestRelayedTextBetweenABatchsCallsIsAnswered (V1-V4, fake upstream that
checks the exchange as Go does) and the new TestJoinToolRunsOnlyMoves...
cases fail on origin/main
|
||
|
|
3aa22f9d9c |
gateway: a translated Responses reply keeps the web search that ran, with its query and sources (#2044, BussanQ)
What changed: responsesEncoder.event gets a KSearch case and
renderResponses a Search case. Both emit a completed web_search_call
item (ws_ id, action.type "search", query plus queries, and the
nonempty source URLs in action.sources) through the shared
responsesSearchItem. The stream adds the item, sends
response.web_search_call.completed {item_id, output_index} and
output_item.done, and the same item stays in the terminal response's
output, in order with text, reasoning and client tool calls.
Why: a search magpie ran for a model that can't search (searchRounds),
or one decoded from an upstream Responses or Anthropic reply, reached
the client only as answer text. Anthropic clients already got
server_tool_use / web_search_tool_result; Responses clients (bqAgent)
had no record that a search ran or what it found. No earlier progress
events or url_citation offsets are invented.
From BussanQ's reference commit b1a4e7b, reviewed line by line and
applied onto origin/main. Added on review:
TestResponsesSearchItemReplayed (the item sent back as the next input,
as Codex does, parses and leaves the turn's messages unchanged) and a
docs line saying so.
What was run (sandbox HOME, pinned caches, go1.26.8):
- go test -tags nogui -count=1 ./internal/gateway -run
'TestResponsesSearch.*|TestWebSearchForAModelThatCannot|
TestSearchToldAsAnthropics|TestWebSearchAskedOfEachAPI|
TestAnthropicServerToolLeftOut|TestParallelToolCallIDs|
TestResponsesStreamToolThenHiddenThinking': ok
- Break check: origin/main's responses.go put back with the new tests:
TestResponsesSearchResults "search output lost or reordered: got
[message message function_call]", TestResponsesSearchDecodedResults
"decoded provider search missing", TestResponsesSearchFollowedByFailure
"completed search or subsequent error lost", and
TestWebSearchForAModelThatCannot "delegated search missing from
Responses output" all FAIL; pass with the change restored.
- go test -tags nogui ./internal/gateway (whole package)
- gofmt -l; go vet -tags nogui for darwin, GOOS=linux, GOOS=windows
Not run: a live provider; the full repository suite.
Co-authored-by: BussanQ <bussanq@gmail.com>
|
||
|
|
320af98581 |
gateway: an upstream's error in a shape its decoder can't read fails the reply, so Codex tries again (#1933, tensornull)
A translated stream whose upstream said it failed, but not in the shape
its protocol's decoder reads, ended as a completed reply with no output
and zero usage. Codex took that as its turn's end (exit 0, no message)
and never used its stream retry. tensornull's three fixtures, on an
Anthropic provider asked from Codex's Responses:
- {"type":"error","error":"fixture upstream failure"}: decodeAnthropic's
struct wants an object for error, so the event decoded to nothing,
while upstreamEnds counted the type "error" as the reply's end.
- Messages events with their type left out (named only by "event:"):
the decoder read nothing, and upstreamStop's delta.stop_reason still
marked the reply ended.
- A Responses response.failed from the Anthropic endpoint: upstreamEnds
took any protocol's last event, and the Anthropic decoder ignores it.
Now:
- replyEnds (upstream.go) reads a reply's end in the protocol it was
asked in: Anthropic's message_stop, error or a message_delta's
stop_reason; Responses' response.completed/incomplete/failed or error;
Gemini's finishReason; Chat's finish_reason. The other two fixtures no
longer read as whole and end as errEndedShort, a failure the gateway
and the client retry, like the "ping then EOF" control. It replaces
upstreamEnds in both the streaming loop (continuation.go) and the
unstreamed one (gateway.go).
- carriedError: every decoder (Anthropic, Responses, Chat, Code
Assist/Gemini) that can't decode an event still tells an error it
carries ({"error":"…"}, type error, response.failed) as KError with
its words. Siblings found the same way: a Chat upstream's
{"error":"…"} chunk ended a translated reply as completed; a Responses
upstream's string error or a response.failed with no error object
(status failed) did too, read as stop.
- An error event with no message says its type or the event itself,
never "".
One test's fixture changed with it: TestTranslatedEffortLoggedAsSent
served Chat chunks from its Responses upstream, which the Responses
decoder reads as nothing. It "completed" only because a finish_reason
counted as the end, the same empty success this fixes, so it now fails
with errEndedShort. The case gets a Responses reply (responsesHi).
What a whole reply does is unchanged: a valid Messages text reply, and
Claude's empty end_turn (asked of in the report), still complete on the
first ask (TestWellFormedStreamsStillComplete).
Run: the new tests in stream_error_shape_test.go use the report's bytes
(event: lines included). Against origin/main's code (fix reverted, tests
kept) 8 subtests fail: anthropic error string, error object with no
message, events with no type, responses failure on the messages route,
chat error string, both Responses-upstream cases, and the unstreamed
client; the error-object control and the well-formed ones pass on both.
With the fix all pass. go test -tags nogui -timeout 40m ./internal/gateway (sandbox
HOME, caches pinned); gofmt -l; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows. tensornull's reproduce.py against a nogui build of this
tree: error-string now ends response.failed "fixture upstream failure"
after 3 gateway attempts, the same as the error-object control (was
response.completed after 1). Not run: the Codex CLI replay; a Responses
client asking a Responses upstream is passed its bytes as they are, so
that pairing is unchanged.
|
||
|
|
bbc7ee0a96 | gateway: an image Claude Code sends to a Responses provider carries detail auto, so a strict upstream (vLLM) no longer refuses it with 400 (#1474, zacharyxz) | ||
|
|
da085e3f78 |
gateway: joinToolRuns leaves the model's own step and every call-carrying item in place, and a result written before its call opens no run (#1752, #1822)
What: follow-up to Edward4226's joinToolRuns (previous commit), after review
against Codex rust-v0.162.1 and the code around it.
- An item carrying a call_id is never moved, whatever its type. Before, only
function_call/custom_tool_call/tool_search_call counted as calls, so a
local_shell_call (or any call type Codex adds) inside a run was moved after
results, its own output's among them.
- Before the run's first result, what the model wrote between its own calls
(reasoning, assistant text, a hosted tool's call) stays where it is. Before,
[call_a, reasoning, call_b, out_a, out_b] sent the reasoning after the
results, where it reads as the next step's: DeepSeek, whose step must lead
with its reasoning (reasonFirst,
|
||
|
|
5b7112fe2f |
gateway: an item a batch's tool results were interrupted by goes after them, so strict Responses upstreams stop refusing the relayed request
What: the normalization a relayed Responses request goes through before it
leaves (gateway.go, attempt) gains joinToolRuns beside orphanedToolOutputs
and pairToolItems: an item that sits inside a run of tool calls and results
- between a call and the result that answers it - is moved to the end of
that run. A run is open while one of its calls has been seen and the result
answering it is still ahead, so an item between two whole exchanges stays
where it is. Codex writes such an item itself: when a tool returned an
image it resized, its <image_resize_notice> goes between one batch's two
results (the report from the Codex app on Windows, one assistant step with
view_image and exec_command).
Before, the run reached the upstream with the item inside it and a strict
one refused the whole request with 400: Volcengine's Agent Plan "An
assistant message with 'tool_calls' must be followed by tool messages
responding to each 'tool_call_id'", OpenCode Zen/Go "No tool output found
for tool call <id>" - both naming a result that is in the request. After,
the results follow the calls, the item goes after them, and both answer
200. This is the rule the chat path has had since #1275 (pairToolMessages
closes a run with its results, interrupted ones included, before another
message) and the same family as #1341 (pairToolItems, a call nothing
answers), and it is applied before the request is relayed or translated,
so every destination whose own form is strict gets it in the same change.
The item's own bytes, its role and its order among the other non-tool items
are as they were. A request with no tool items, one whose exchanges are each
whole, and a body that is not a Responses request come back byte for byte
(TestJoinToolRunsLeavesWholeExchangesAlone). One expectation changed on
purpose: TestGrokGetsAgentMessageAsUser's turn holds a subagent's reply
between the send_message call and its output, and Grok is now given that
reply after the run. Its conversion is unchanged (same user message, same
"From <author> to <recipient>" header, same text and images) and only its
place moved, the way every other item Grok is handed keeps the place magpie
gave it; a review that knows Grok's backend needs the reply in place can
narrow the rule to messages other than agent_message.
Run:
- go test -tags nogui ./internal/gateway/: 2 failures, both red on
origin/main
|
||
|
|
f4cc7459ea |
gateway: a DeepSeek step that said something before its call leads with its reasoning, so DeepSeek no longer refuses it with 400 (#1822, #1592, #1687)
Codex through magpie to OpenCode Go's DeepSeek (#1822), and to DeepSeek's own API (#1592, #1687), was refused now and then with "The `reasoning_text` in the thinking mode must be passed back to the API". The cause, checked against api.deepseek.com/v1/responses on 2026-10-12: DeepSeek reads each step (a run of reasoning, assistant messages and calls after a user message or tool output) as one assistant message whose thinking is the item the step starts with. In the current turn (since the last user message), a step that has a call or follows a tool output must lead with a reasoning item. [message, reasoning, call] and [output, message] are refused; [reasoning, message, call] and [output, reasoning, message] are taken. When a step had no reasoning (another model's turn, a translated one), magpie inserted its " " reasoning right before the call, which gave [message, reasoning " ", call]. A step with only a call worked, and only the current turn is checked, which is why the reporter saw it come and go. What changed: - responses.go: withReasoningText and buildResponses now share reasonFirst. Each such step leads with reasoning: the step's own first reasoning item is moved ahead, otherwise one holding a space is put first. A sealed item keeps its id and encrypted_content. A body already in that shape goes byte for byte. - Sibling, the same API family: an assistant reply right after a tool result, with no reasoning, is refused too (checked on DeepSeek's Chat and Anthropic endpoints). Chat (withReasoningOnToolTurns relayed, buildChat translated) now gives such a reply reasoning_content " ". Anthropic (withThinkingOnToolTurns) gives it a thinking block. Anthropic takes thinking anywhere in the message, so ordering is not an issue there. - The DeepSeek fakes in the tests now model the real rules. The stricter Responses fake also turns TestDeepSeekGroupMemberAfterChatGPT red on the old code: its "an assistant note" case is this bug, which the old lenient fake hid. - docs/subsystems/gateway-routing.md: the Responses, Chat and Messages replay paragraphs. What was run: - New tests: TestDeepSeekStepSaysBeforeItsCall covers the reporter's shape across OpenCode Go, DeepSeek and a group, streamed and not. Also TestWithReasoningTextLedStepsUnchanged, TestTranslatedDeepSeekStepLeadsWithReasoning, TestChatReplyAfterToolGetsReasoning and TestAnthropicReplyAfterToolGetsThinking. All but the unchanged-body test fail on the old code. - gofmt -l; go vet ./... on darwin, and with -tags nogui on linux and windows; go test ./internal/gateway. - Real API: direct requests to api.deepseek.com (Responses, Chat, Anthropic) with the old and new shapes, as listed above. What wasn't: - OpenCode Go's own endpoint: the test account is refused with "This Go model requires Global regions", an account setting, so its fix rests on it relaying DeepSeek's rule unchanged (the reporter's error text is DeepSeek's). - A built magpie end to end against the real API. - Other thinking vendors (Kimi, GLM) were not checked for the same step rule. Their paths are unchanged. |
||
|
|
2a63414adb |
gateway: a Claude turn that calls a tool and then thinks without showing it reaches Codex whole, ending in response.completed, not cut short by a panic (#1786)
The Responses encoder read the open function_call's id and name from the
collector's last part. When a hidden thinking block came after a
tool_use (a redacted_thinking block, or a thinking block signed with no
text, from content_block_start or a signature_delta), the collector had
already appended that thinking, last(ToolCall) was nil, and closing the
call dereferenced it. The server recovered the panic mid-stream, so the
client saw a 200 chunked body cut short ("unexpected EOF", "stream
disconnected before completion") and no response.completed.
The encoder now keeps the open call's id and name itself (e.call), set
when the item opens, for closing it and for the custom-tool check on its
argument deltas. The other stream encoders (Chat, Anthropic, Gemini)
track their open tool call in their own state and never read the
collector's last part, so only this one had the bug.
Verified:
- TestResponsesStreamToolThenHiddenThinking runs the reporter's sequence
through a real gateway server (httptest) to a fake Anthropic upstream
and a real HTTP client: redacted_thinking, empty thinking signed at its
start, empty thinking signed in a delta, and visible thinking as the
control. With the old responses.go the three hidden cases FAIL with
"status 200, the stream was cut short: unexpected EOF" and the log shows
the nil pointer panic; the visible case passes on both.
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./..., go test -tags nogui ./... (see the push).
Not done here: the max_tokens setting the issue also asks for is a
separate feature request.
|
||
|
|
5feadabef6 |
gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.
decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.
Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:
CPU in the request's handler time per request
(pprof, per request) (ns/op)
anthropic 154ms -> 45ms 208-212ms -> 52ms
anthropic, group 178ms -> 51ms 249-262ms -> 65-67ms
chat 122ms -> 35ms 167-254ms -> 50-54ms
responses 215ms -> 56ms 294-452ms -> 70ms
TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).
Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
Responses; direct, through a group, translated to each other protocol,
with images, thinking, escapes, odd spacing, a repeated key, and four
2 MB conversations) and compares what the vendor gets with
testdata/upstream_bodies, recorded on the code before this change
(all 18 identical; three runs agreed). Breaking decodeJSON's \n
unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
the gateway's, and jsonValid with json.Valid, over seeds, every cut
and a changed byte at every place of each seed, and 2.5 minutes of
fuzzing (~1.75M inputs). Breaking the validator's control-byte check
by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
origin/main
|
||
|
|
691858e064 |
gateway: a Codex routing group that falls to DeepSeek sends every tool call with reasoning_text, so DeepSeek no longer refuses it with 400 (#1592, waangzh)
What the reporter saw: a Codex mixed group (ChatGPT first, DeepSeek after)
answered 400 "The `reasoning_text` in the thinking mode must be passed back
to the API." once the turn fell to DeepSeek.
Cause, checked against the real api.deepseek.com/v1/responses on 2026-10-11
with the owner's key: DeepSeek refuses a history where
- a reasoning item is sealed only (ChatGPT's encrypted_content, no summary),
- a function_call/custom_tool_call has no reasoning item in its step (an
assistant turn ChatGPT answered without one, or a second step), or
- a reasoning item's reasoning_text is empty.
It accepts reasoning_text " " (with or without encrypted_content and id).
withReasoningText only filled the third case.
Change:
- withReasoningText (passthrough) walks the input by step: a reasoning item
with no text gets its summary, else noReasoning (" "), keeping its other
fields (encrypted_content, id); a tool call with no reasoning item since
the last output or user message gets one with noReasoning before it.
- buildResponses (translated, e.g. an Anthropic agent onto DeepSeek's
Responses) does the same for a tool call with no thinking before it.
- Only where replaysReasoning says so (DeepSeek); gpt-5.4 on a relay gets
no reasoning_text.
- gateway-routing.md describes the Responses replay.
Run:
- The reporter's 400 reproduced on the real API, directly and through the
old binary (direct model and group/codex-different); the new binary
answers 200 completed for each case, whole and streamed.
- New TestDeepSeekGroupMemberAfterChatGPT (8 subcases) and
TestTranslatedDeepSeekCallWithoutReasoning fail on the old code, and
TestDeepSeekReasoningPassedThrough's empty item; all pass now. The fake
now refuses what the real API refuses.
- go test ./internal/gateway, gofmt, GOOS=linux/windows go vet -tags nogui.
Not done: DeepSeek's Anthropic endpoint has the same rule (a tool_use with
no thinking is refused, checked live); not changed here. Kimi and GLM
thinking were not checked: no key, and magpie has no replay rule for them.
|
||
|
|
13356b9da7 |
gateway: a Responses reasoning item goes through translation to Responses with its id, summary and encrypted_content, both ways (#1445, XYenon)
What changed: parseResponses keeps a reasoning item that has encrypted_content raw (Part.Sealed), and buildResponses sends it back as it came when it has no reasoning text and DeepSeek replay is off (sealedReasoning). The decoder says where an item begins (KThinkStart with its id) and hands over the done item (KSealed). The encoder streams the summary under the upstream's own id and gives the done item and the completed response's output as the upstream wrote them; renderResponses does the same for a reply that wasn't streamed. Why: the old code made its own rs_ id, dropped encrypted_content and left reasoning out of the next request, so a store:false conversation through a stream-only account or web search lost its reasoning each turn. Reasoning with text in it (another vendor's) is still left out for OpenAI (#1411); withoutBareReasoning and the foreign-reasoning retry still act on the built body. Run: the new tests in reasoning_state_responses_test.go (OpenAI's documented item and stream shapes) fail on the old code and pass now; the seal isn't handed to Messages, Chat or Gemini clients. gofmt -l; go vet -tags nogui on darwin, linux and windows; the full internal/gateway tests in a scratch HOME: ok. Not tried with a real account. |
||
|
|
68aab298d3 |
gateway, codex: a provider the user added by its address is sent the service_tier Codex asks for, and offered Fast and Ultrafast (hsiangron on X)
Codex's Fast (service_tier=priority) and Ultrafast (ultrafast) were dropped on the way to a custom provider: the gateway only passed a tier on to chatgpt.com and Cursor, and magpie's models.json entries for such a provider's models offered no tiers, so the user's own picks were written over. - Request.Tier keeps the client's service_tier as sent; for a provider with no preset and no account (OwnTier) both buildResponses and buildChat send it as it is. One that refuses the field by name is asked again without it and remembered as unfit for it, as the other optional fields are. - codexcat offers such a provider's model the tiers Codex's own entry gives the same slug (dated snapshot and provider prefix stripped), Fast on another GPT model, none otherwise. Presets and groups are unchanged. Run: TestOwnProviderGetsTier (Responses/Chat x priority/ultrafast/flex), TestPresetProviderGetsNoTier, TestOwnProviderRefusingTier, TestOwnProviderTiers; the gateway ones fail without the gateway change and TestOwnProviderTiers fails without the codexcat change. go test gateway, codexcat, catalog, provider; go vet darwin/linux/windows; gofmt -l clean. Not tried against the reporter's relay. |
||
|
|
b3330ea82d |
gateway: a Responses request relayed with a tool call no result answers sends the call a synthetic result, instead of Volcengine coding plan's 400 "An assistant message with 'tool_calls' must be followed by tool messages" (#1341, XcodeFish)
The reporter's own experiment through magpie to the same upstream: a function_call with no function_call_output was turned away with exactly the reported 400, and the same request with the output went through. Volcengine checks the exchange on the chat form it turns /responses into. The Chat path has mended this shape since #1275 (pairToolMessages); the Responses relay had only orphanedToolOutputs, which handles the opposite case (a result with no call). pairToolItems runs beside orphanedToolOutputs for every Responses request not going to a ChatGPT account. A function_call or custom_tool_call that no result in the input answers gets "[The result of this tool call is unavailable: the turn was interrupted.]". As in the Chat path, that result goes at the end of the run of calls and results the call is in, so no result lands between two parallel calls. A result with no call is still left to orphanedToolOutputs. A result naming a call from an earlier request (previous_response_id) stays as it is. Based on ggbdpq's patch on the issue, which put the result right after the call. TestResponsesRelayAnswersALoneCall (through the whole gateway) fails without the change ("the lone call went unanswered") and passes with it. TestPairToolItemsAnswersALoneCall covers parallel calls, custom calls, byte-for-byte pass-through of paired, out-of-order and previous_response_id requests, and that the caller's buffer is left alone. go test -tags nogui ./internal/gateway under a temp HOME passes, as do go vet (darwin, linux, windows) and gofmt. Not tried against the real Volcengine coding plan: the only Volcengine key here is a pay-as-you-go Ark key with no DeepSeek model enabled. The reporter's Codex rollout shows every call paired, so which call went unanswered in their request is not known. They are asked whether it still happens. |
||
|
|
4a8338cced |
codex: Codex's Ultrafast (service_tier "ultrafast") reaches the ChatGPT backend when magpie's pool of Codex accounts serves the turn, as it does on Codex's own sign-in; it was dropped for anything but Fast's "priority", and OpenAI's API still gets it as Fast (yxinyu715 on X: two Pro accounts, Ultrafast does nothing through magpie)
Run: TestCodexPoolKeepsUltrafast fails on the old code (backend asked for <nil>) and passes now; go test ./internal/gateway ./internal/provider ./internal/codexcat pass; go vet clean. Not tried with a real account offering Ultrafast: the owner's accounts don't list it. |
||
|
|
40c5b92a93 |
gateway: structured output crosses every translation: a Responses text.format or a Chat response_format reaches a Chat, Responses, Messages or Gemini upstream in its own words (frostming on Discord: responses.parse through magpie to OpenRouter came back as plain text)
The IR held a schema only from Anthropic's output_config.format, and only Messages (and Claude Code's --json-schema) were asked for one. A Responses request to a provider magpie speaks Chat or Messages to (OpenRouter has no Responses URL) lost text.format; a Chat request translated to Responses or Messages lost response_format; an Anthropic schema translated to Chat or Responses was lost too. Format (format.go) now carries json_schema (name, description, schema, strict) or json_object from Responses, Chat, Anthropic and Gemini, and each builder asks for it in its upstream's field. Where a target can't say it (json_object on Messages or Claude Code; the vendor bridges Cursor, Devin, Kiro, Qoder, Command Code, Zed) it is told in the system prompt. An upstream answering 400/422 naming the field (DeepSeek's "This response_format type is unavailable now") is asked again with it told in words, and so from then on. Relayed requests are unchanged. |
||
|
|
d637a3cf5e |
gateway: a DeepSeek model whose Codex request is passed through as it is (OpenCode Go's deepseek-v4.1-flash) gets its reasoning back as reasoning_text, and is never asked without it (#1104)
Codex hands a reasoning item back as it got it; one from a turn magpie translated, or another provider in a mixed group served, has only its summary. Passed through to OpenCode Go's /responses, DeepSeek refused the request with "The `reasoning_text` in the thinking mode must be passed back to the API". That refusal names the input, so passthrough asked once more without every unsealed reasoning item (withoutBareReasoning) and marked the model as refusing them, which left the reasoning out of every later request. For a model that wants its reasoning back (replaysReasoning, the predicate #388's buildResponses uses), a reasoning item without reasoning_text now gets its summary as one, and withoutBareReasoning is never applied to it. TestDeepSeekReasoningPassedThrough plays OpenCode Go with the reporter's error word for word. Without the change it fails ("reasoning_text sent = \"\", want the summary"); with only the strip guards taken out it fails ("a reasoning item with nothing in it was answered"). go test -race ./internal/gateway, -race -count=10 on the new test, and go vet ./... pass. |
||
|
|
23166a7d42 |
gateway: a custom tool's call magpie hands Codex has a ctc_ id, and a magpie model or group on OpenAI's API gets call ids OpenAI takes (Lullaby on Discord: Invalid 'input[155].id': 'fc_18da5b9a10256a3e00000011'. Expected an ID that begins with 'tsc'. 这个问题貌似还是没有修复, then "Expected an ID that begins with 'ctc'", auto-compaction failing with it) — two causes. A vendor's apply_patch, translated to Codex's custom_tool_call, was given an fc_ id as a function call is (itemPrefix), and OpenAI turns away a custom_tool_call whose id isn't a ctc_ one. And the tsc_ rename (1a9c4ca6) ran only for Codex's own models: a magpie model or routing group relayed to OpenAI's API on a key (passthrough) sent the session's fc_ ids as they were. The id kinds are now one table, openaiItemPrefix (tool_search_call tsc_, custom_tool_call ctc_, the two OpenAI's errors name): calls are minted with them in the stream and the rendered reply, and callItemIDs (was searchCallIDs) renames fc_X to tsc_X / ctc_X before Codex's own /responses and /responses/compact and before a passthrough to an openai.com host, call_ids and the rest of the body byte for byte. A ChatGPT account's request keeps no ids (provider.codexInput), so it is left alone. TestCustomToolCallHasCtcID, TestMagpieModelOpenAICallIDs (a fake OpenAI behind the provider's proxy answering the same 400s, direct and through a group) and TestCodexOwnModelCustomCallIDs (turn and compaction) fail without the change; TestCustomCallIDsUntouched keeps a clean request byte for byte. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass.
|
||
|
|
0ebce8b4ed | gateway: a translated Responses request doesn't ask the upstream to seal a tool's arguments (#613) — Codex marks spawn_agent's message "encrypted"; its calls go back to Codex as unsealed (encrypted_function_args []), so an upstream honouring the mark would hand the subagent ciphertext as its message. The marks are left out of the tools sent (unsealed). TestNamespacedCallKeepsArgsWhenSearchTakesOver checks the upstream isn't asked to seal. | ||
|
|
71f9884ee7 | gateway: a call from a Responses upstream keeps the arguments its finished call holds (#613) — Codex offers web_search beside its namespaced tools; on a provider not set to search by itself the request is translated rather than relayed, and spawn_agent (every namespaced tool) came back with arguments {}: the decoder took the argument deltas once any came, and dropped what output_item.done / function_call_arguments.done held. A call's arguments are now given once it is done, the fuller of the deltas and its done events (JSON first); a stream that ends with a call open gives what it has. TestNamespacedCallKeepsArgsWhenSearchTakesOver (the issue's request, stream and not: arguments {} without the fix), TestResponsesCallArgsFromDone. | ||
|
|
f1ca6139b5 | usage: a Codex call through the gateway that wrote to its upstream's cache is no longer listed a second time as a local session call (laowangba233 on #589: 用量中的统计是不是重复了 … 为啥会一个是提供商的一个是本地会话的) — the Usage page drops a Codex rollout's call when it matches a gateway record by session, end time within 2s and equal tokens. Codex reads input_tokens_details.cache_write_tokens from a Responses reply and keeps it as cache_write_input_tokens; the gateway's rUsage read only cached_tokens, so for a call whose upstream told a write the record had CacheWrite 0 and the rollout didn't, the tokens never matched, and the call stayed listed under Local session beside its provider's row. Calls without a write matched, so only some calls were counted twice (Maru Code 92 calls plus 22 "本地会话" in the report). Also, sessions' spent took only the cache read out of Codex's input_tokens, which holds the write too, so such a call's write was counted twice in its own input. Now: the gateway reads cache_write_tokens (input = input_tokens - cached - written) and tells it to Codex when it translates a reply; spent takes the write out of the input as well; and the matcher compares a call's input plus cache writes, its output and its cache reads, so a record and a rollout that split the write differently — an older Codex without the field, or records already in usage.jsonl from before this change — still match, and the duplicates already on a user's page go too. The session caches' versions go up (sessions.json 11, calls-v4) so kept parses are read again, and older calls-v* folders are removed. Under a provider filter the provider ranking still lists the other providers, as it is a picker; the duplicates were what made it read as double counting. TestCodexCacheWriteMatchesGatewayCall (a Codex rollout and gateway records for two calls, one with a 9000-token cache write; with the rollout naming the write and the record not, both naming it, and an older Codex without it: two rows, no Local session row, the provider ranking maru-code alone, unfiltered and filtered to the provider, by QueryPage and LedgerOf; fails without the change with a third row from the log), TestCodexCacheWriteNotInInput and TestResponsesUsageCacheWrite (parse and round trip through what Codex is told) are new and fail without the change; TestCallsCodex's call with a write now expects input 200 (2500 - 2000 read - 300 written). go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./internal/... under a temp HOME pass (TestFXInState's known TempDir-cleanup flake aside, which passes alone). | ||
|
|
1a283b95fc |
fix(gateway): normalize standalone Responses tool outputs (#544)
* fix(gateway): normalize standalone Responses tool outputs * fix(gateway): preserve native notifications and tool result ordering |
||
|
|
55e7df478f |
codex: a group's effort for the turn keeps Codex's reasoning.context, and Codex's custom tools (code mode's exec, apply_patch) reach a model magpie translates for (#534, #520 follow-up, azir12345: since v0.1.637 a Plus account's gpt-6.1-sol fails with 400 "X-OpenAI-Internal-Codex-Responses-Lite requires reasoning.context to be all_turns", and Codex said it had only the collaboration and wait tools, no terminal) — ChatGPT's catalog marks gpt-6.1-sol (as gpt-6-sol, gpt-6-luna, gpt-5.6-*) use_responses_lite with tool_mode code_mode_only, and Codex asks for the bare slug with its native metadata: the X-OpenAI-Internal-Codex-Responses-Lite header (add_responses_lite_header, which magpie forwards with the other x-openai-* headers), reasoning {"effort","summary","context":"all_turns"} (build_reasoning), and its tools moved into an additional_tools item, every other tool reached through exec, a custom (freeform, lark grammar) tool in the "functions" namespace, beside wait and the collaboration namespace. magpie routes the bare id to the group auto-gpt-6-1-sol, and the effort the group picks for the turn went through withEffort, whose Responses branch rebuilt reasoning as {effort, summary} and dropped context, so ChatGPT refused the Lite request; it now sets only the effort (withBodyEffort), keeping every other field of reasoning as Codex sent it. A member served by translation (Chat, Anthropic, a Responses plugin) had parseResponses drop custom tools and ignore custom_tool_call / custom_tool_call_output items, so exec vanished and the model saw only wait and the collaboration tools; a custom tool (top-level or in a namespace) is now offered as a function taking one string "input", its description its own plus a note on input and its grammar, an earlier custom_tool_call goes to the model as a call with {"input":…} and its output as the call's result, and the model's call goes back to Codex as the custom_tool_call it runs (name and namespace as Codex knows them, input from the "input" argument, else the arguments as given), streamed without function_call_arguments events and in the non-streamed reply alike. This also gives translated models Codex's freeform apply_patch, which was dropped silently before. The Lite header is still forwarded as it was; nothing showed it needs dropping. Codex's base_instructions and identity line are untouched. No request was made to ChatGPT. TestWithEffort's Lite case fails without the decide.go change ("want \"context\":\"all_turns\""); TestCodexCustomToolsTranslated (a code-mode Lite turn through a fake Chat provider: exec offered with input and its grammar, the earlier call and output shown, the model's exec call back as a custom_tool_call with its input and no arguments) and TestCodexCustomToolNamespaced (namespaced and non-JSON calls, renderResponses) cover the tools; TestAdditionalToolsTranslated, TestNamespacedToolsOffered and TestGrokPluginGetsNamespacedTools now expect the custom tools offered. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass (TestDevinSignedInOnlyInMagpie failed once on its wait, passes alone; untouched).
|