Commit Graph
78 Commits
Author SHA1 Message Date
yetone 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.
2026-11-03 15:59:14 +08:00
ggbdpq 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 77e853588
and green here; TestUpstreamFailedWordsFailARelayOver's guards (a 401,
403 or 429 with the words, a plain bad request, and an
insufficient_quota beside them keep their reading); the codex account's
own shape (TestCodexAccountUpstream, both clients), the instruction
roles contract (TestResponsesInstructionRolesThroughSearch,
TestResponsesInstructionsOtherAPIsUnchanged), the compaction, group and
retry families, the full gateway package, gofmt, vet on darwin, linux
and windows, and builds of all three (-tags nogui).

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 22:23:51 +08:00
yetone 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, c4ae3ca77); Ark became a host that searches by itself
later (a0cb8b646), and forArkSearch fitted the tool but not include.

Ark's 创建 Response page (docs.volcengine.com/docs/82379/1569618) names
`include` but lists no values, so they were asked of the real API with
the owner's key (deepseek-v4-1-flash-260910): reasoning.encrypted_content
is taken; web_search_call.action.sources, web_search_call.results,
file_search_call.results, message.input_image.image_url,
computer_call_output.output.image_url, code_interpreter_call.outputs and
message.output_text.logprobs are each refused with the reporter's 400.

- search_ark.go: arkIncludes (reasoning.encrypted_content alone) and
  includeTaken(host, v), Ark's host only.
- buildResponses (every translated request, Claude Code's
  web_search_20250305 and Settings' searcher on an Ark model included):
  a value Ark refuses is left out of the client's include, and the
  sources value isn't added for Ark. Every other host is as it was.
- forArkSearch (a Responses client relayed to Ark): include keeps what
  Ark takes, and goes when nothing is left. The AI SDK's OpenAI
  provider (OpenCode) adds web_search_call.action.sources itself
  whenever it offers web_search (@ai-sdk/openai 3.0.27, index.mjs
  addInclude), so that route failed the same way.

Siblings in searchHosts[Responses]: api.openai.com takes the value
(OpenAI's own), api.x.ai already gets none, and api.deepseek.com took
it with web_search on the real API (200, completed). open.bigmodel.cn
and api.z.ai: no key here, not tried; no report of a refusal.

Tests: TestArkSearchSendsNoIncludeItRefuses (a fake Ark on the real
host through a redirected dialer that answers the reporter's 400 for
any include value Ark refuses: Claude Code's search translated,
OpenCode's relayed with sealed reasoning kept, and Settings' searcher
on the Ark model), TestArkIncludeScope (OpenAI's and a relay's include
unchanged, sources still added; Ark's keeps only what it takes).

Broken by hand: includeTaken returning true and forArkSearch's include
filter off: all three subtests red with the reporter's exact 400
(searcher: "...unknown type: web_search_call.action.sources ... (the
searcher picked in Settings › Web search ...)"), and TestArkIncludeScope
red.

Real use: the bodies the fixed gateway sends Ark on all three routes
(captured from the test) sent to the real Ark API: each is accepted and
streams; the old shape (with the sources value) is refused with the
reporter's 400. This account hasn't activated Ark's web search, so the
search itself ends ToolNotOpen; a search returning pages wasn't seen.

Run (mote, mote-run, at e84870f17 + this change):
- gofmt -l internal/gateway: nothing.
- go vet ./internal/gateway, GOOS=linux go vet -tags nogui
  ./internal/gateway, GOOS=windows go vet ./internal/gateway: ok.
- go test -count=1 -timeout 45m ./internal/gateway: ok (572.5s).

Not run: the other packages' suites (only internal/gateway changed).

Rebased onto 6874b892b, which changes no internal/gateway file; gofmt, vet x3 and the Ark/include/search tests ran again there: ok.
2026-11-01 13:43:35 +08:00
ggbdpq 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 d307aa648, wsl-run magpie-desktop,
  go test -tags nogui -count=1 -timeout 45m ./...): 81 packages ok. Reds,
  all with issues and none in code this batch touches: internal/agent
  TestInstalledVersion, TestGrokInstalled, TestOmpDetectedWithPiDir
  (#4033, #3548, #3141); gateway TestUnroutedHeldReportSaved (#4300);
  gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestColdTurnsTaken (#4510); provider
  TestClaudeAccountServesModelsListedSinceItsFetch (#3174). Run alone at
  origin/main 573b21f4b, TestGrokInstalled, TestOmpDetectedWithPiDir
  and TestSettingsSaveKeepsWhatItDoesNotSend are red there too. The
  other four pass there alone.
- After the rebase onto origin/main 573b21f4b, at this tree:
  internal/usage, update, gateway and provider ok. In internal/agent,
  the #4033/#3141 install-detection reds plus TestCopilotFolderFrom-
  AnIDEPluginIsNotTheCLI and TestZedAppPath. Those two are flaky the
  same way at origin/main (-count=10 alone: 4 and 5 of 10 red) and are
  already listed in #4033. The #3269 tests (TestCopilotLauncher*) pass
  5 of 5.
- Rebased onto origin/main ef63ef4a2. The #2855 commit met 0b9727ec9
  (#2974) in responses.go: the streamed item's done now takes both, the
  upstream's own id (thinkUp) and the made-over item; and in
  gateway-routing.md main's paragraph is kept with #2855's clause. That
  matches gua's latest head (range-diff: context only). At tree d7c76c6fa:
  internal/gateway, provider, usage, redact and update ok; vet
  GOOS=linux -tags nogui ./internal/..., darwin and GOOS=windows for
  gateway and provider.
- Rebased last onto origin/main d8f7d089f (5 commits: internal/agent
  and GUI files only). At tree 0d4bfd8c8, the pushed one: internal/agent's
  TestCopilotLauncher*, TestClaude*, TestOwn* and TestVSCode* ok, -count=3;
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI red once there, as it is at
  main (#4033). Vet of internal/agent: darwin, linux and windows.
- gofmt -l clean. On mote: go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- Broken by hand, each turning its guard red: the lift gate
  (TestReadingKeepsARefusalsRest, TestAutoVisionKeepsOffARefusedAccount);
  the named-time condition (TestNamedQuotaTimeReplacesAGuess); the
  filter-chain hop (WholeReply/glm-5.3-flash); Edward's aAt
  (TestKeyAllowanceElapsedResetStartsAgain); and the old
  magpieMadeReasoning, which panics in TestMadeReasoningSaysItsTextOnce/
  no_summary. Every new test of gua's is red at base d307aa648.
Not tried: real OpenAI, DeepSeek, GLM or ChatGPT accounts; a real VS Code
1.144 install on Windows; a GUI run (no GUI files are touched).

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 07:06:19 +08:00
ggbdpq 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 ef655acb with the duplicate
  shown (added reasoning ids [rs_18dff…0001 Cp6820f38x Cp6820f3bx])
  and green with the fix
- ablation: upstream responses.go restored under the new test → red
  again; fix back → green
- mutations: dropping the remembered id → both subtests red; dropping
  the output_index rewrite → only the rotating-ids subtest red
- full ./internal/gateway/: ok 356.0s; -race targeted families:
  ok 11.1s; gofmt clean; go vet darwin/linux/windows clean; builds
  darwin ./..., linux ./... and GOOS=windows . all ok

Landing record (yetone):
Run at the pushed batch head (tree a6b084d0b, on origin/main 616405061),
go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider and internal/plugin (this batch's
packages and those main changed since the full run): all ok. gofmt -l
clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags
nogui ./... clean. internal/gui on macOS (mote-run):
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
(#3949), both red at main too.
- The full go test ./... -timeout 45m -count=1 ran one rebase earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's
group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux
(wsl-run): 82 packages ok. internal/agent has 4 reds, all red at
origin/main on that box as well: TestInstalledVersion,
TestGrokInstalled, TestOmpDetectedWithPiDir and
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root
package and internal/cli need gtk4 to build, so they ran on macOS
(mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An
earlier full run at base d307aa648 was red once in
TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both
the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
Broken by hand: internal/gateway/responses.go put back to the base with
the test kept: TestResponsesStreamForeignReasoningIDNotDoubled goes red
with the doubled ids (rs_… Cp6820f38x Cp6820f3bx); restored, green.
Not tried: a real upstream that sends non-rs_ reasoning ids; the ids are
the reporter's shape in a fake stream.

Landing record (yetone):
Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider, internal/agent and internal/usage
(this batch's packages, plus those main changed since the full run): all
ok except internal/agent's TestInstalledVersion, TestGrokInstalled and
TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033,
#3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the
root package and internal/cli ok; internal/gui red in
TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
(#3949) and TestColdTurnsTaken (#4510), the first two red at main too.
- The full go test ./... -timeout 45m -count=1 ran two rebases earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82
packages ok, internal/agent's 4 reds as above, plus
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The
root package, internal/cli and internal/gui need gtk4 to build, so they
ran on macOS as above. An earlier full run at base d307aa648 was red
once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone
at both the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
- Rebased after these runs onto origin/main c1457f2ee. Its two commits
since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither
internal/gateway nor internal/redact, nor any file this batch changes,
and were not run again here.
Broken by hand: internal/gateway/responses.go put back to the base with
the test kept: TestResponsesStreamForeignReasoningIDNotDoubled goes red
with the doubled ids (rs_… Cp6820f38x Cp6820f3bx); restored, green.
Not tried: a real upstream that sends non-rs_ reasoning ids; the ids are
the reporter's shape in a fake stream.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 06:38:01 +08:00
yetone 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.
2026-10-31 02:04:22 +08:00
yetone 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 acdc85ac8: internal/gateway
  vet and tests again on the Linux box, ok (1293s). go vet of
  internal/gateway for darwin, linux and windows on mote; gofmt clean.

Not tried: a real Bedrock-backed Claude line or a real Codex Desktop.
Anthropic's search run by the upstream itself (server_tool_use, a relay
told to search) isn't told to Codex as web_search_call, so it isn't
covered here. The rebuilt tool_result holds the query and URLs, not
the page text the model saw.
2026-10-30 22:55:21 +08:00
wrke1990andggbdpq 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 cc04ce68c1 plus
  test changes fail with real assertions in
  TestResponsesInstructionRolesThroughSearch (developer/system),
  TestResponsesInstructionsOtherAPIsUnchanged and
  TestCodexSearchAnsweredOnResponses.
- Those patched tests, TestCodexLaterDeveloperMessageKeepsTheSystem and
  TestSearchOfferedStaysOnTheClientsAPI pass, also with -race.
- gofmt and diff checks pass.
- Native, Linux/nogui and Windows vet and builds pass.
- go test -tags nogui ./... fails in the unchanged internal/agent package:
  TestRunningNeedsNoPs cannot find its sleep 314.159 process. The complete
  internal/gateway suite passes (427.556s), as do the other packages.
- The patched executable against an isolated local capture upstream keeps
  Plan and Default as developer messages in minimal and full histories
  with web_search offered; real configuration hashes remain unchanged.
Not run: paid real-upstream acceptance, native Linux/Windows runtime tests,
or browser GUI tests (no GUI assets changed).

The unrelated agent failure was traced to macOS pgrep returning exit 3,
"Regular expression evaluation error (illegal byte sequence)", under the
inherited locale. The same local sleep process is found with LC_ALL=C.
TestRunningNeedsNoPs fails 20/20 under -race with the inherited locale and
passes 20/20 with LC_ALL=C (3.848s). No agent code or timeout was changed.
A full-suite recheck with LC_ALL=C is running at commit time; retain the
initial failure and publish as a draft until that recheck completes.

Adapted when landing: a blank line before the next heading in
docs/subsystems/gateway-routing.md. Cherry-picked by ggbdpq (gua2100).

Review and run record (landed by the maintainer's agent; gua2100 brought
both fixes from Discord, rebased onto main):
- External code, read line by line: no network, dependency, workflow or
  credential change; Codex base_instructions/identity untouched.
- Base origin/main d99e213f5. Full checks on mote (macOS, Go 1.26.8,
  sandbox HOME) at 31f025634, whose tree is the one pushed (only messages reworded since): gofmt, go vet darwin, linux,
  windows, builds for all three: rc=0. go test -tags nogui -count=1
  -timeout 45m ./...: 79 packages ok, internal/gateway ok (855s); two reds
  in untouched packages, both filed before: internal/plugin
  TestGatewayHookMixedPiPackage (#2865, "starting plugins: context deadline
  exceeded") and internal/update TestRelaunchOpenTriedAgain (#3881). Run
  alone at the same tree both pass (plugin 97s; update -count=3).
- Broken by hand: the #3739 regex reverted, so both Kimi tests fail (400
  handed back). The #2532 product files reverted (six files), so all three
  tests fail. The mergeTurns role guard removed fails (5 input messages,
  want 7).
- Real binary on mote, sandbox HOME, a fake upstream that records requests:
  at d99e213f5, wrke1990's literal #2532 body sends Plan in instructions
  and Default as a user <system-reminder>; at HEAD both developer items
  keep their role and place. #3739's curl body (and zfsdream96's ZCode
  shape, output_config effort max, no thinking) is a 400 at d99e213f5; at
  HEAD it is a 200 after one retry without thinking, and the next
  request goes without disabled.
- Rebased onto fa427216a (responses.go stream deltas, landed meanwhile;
  no conflict). At the rebased pushed tree: gofmt, go vet and
  go test -count=1 ./internal/gateway ok (580s) on mote. The full suite
  was not rerun after that rebase.
- Not covered: the search reroute's re-parse when a fallback changes
  whether the target is Responses (breaking it leaves the tests green;
  no route found that reaches it). Not tried: the real Kimi Code
  endpoint and its kimi-code-cn preset (a custom Anthropic provider with
  Kimi's literal 400 was used), a real Codex session against a paid
  upstream, Windows/Linux runtime. #3739's second symptom (k3 losing
  thinking when output_config.effort is asked) is not addressed.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-30 21:38:00 +08:00
ggbdpq 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 865df247 fixed on Chat.

The decoder now reads a call by its item: a function_call item added
waits, its lines kept as they came, and goes — start, arguments, done —
at its own first delta or its output_item.done, whichever comes first,
while no other call is open; a call whose item ends while another is open
goes when that one does, and every call still waiting goes before the
reply ends, in output_index order. A delta or done names its call by
item_id, then output_index; one that names nothing at all goes, while no
call is open, to the first waiting one, since a stream whose events name
nothing streams its calls in order — that keeps the call args of such a
stream held and given as before (TestResponsesCallArgsStream and
TestResponsesCallArgsFromDone read them). A stream in Responses' own
order — an item added, argued and done before the next — reads as
before, its start one line later, at its first arguments.

Tests (responses_batched_calls_test.go): the report's stream to a Chat
client, the same with the two calls' arguments by turns, and a stream in
Responses' own order held to the same two calls. The streams are built by
hand from the report, not captured bytes; no real upstream was read.

Run (go1.25.5, darwin/arm64): go test -tags nogui ./internal/gateway -run
'TestResponsesBatchedCalls|TestResponsesOwnOrderUnchanged' — red on
upstream/main (call_1 read_file empty, call_2 read_file {"path":
"a.py"}{"path": "b.py"}, the report's own reading), green here. The full
gateway suite (-tags nogui) was red first at
TestResponsesCallArgsStream, TestResponsesCallArgsFromDone and
TestResponsesToolWithoutReasoningStillTimed, whose streams name no item —
the deltas went out raw with no call open — and green after the
nothing-named fallback; gofmt -l clean; go vet -tags nogui for linux,
windows and darwin; go build -tags nogui for the three; the new tests
with TestRelay*, TestInterleaved* and TestResponsesCallArgs*, -race
-count=5, no race reported.

Generated-by: GLM-5.3-Flash (ZCode)

Review (applied with git am-equivalent cherry-pick of ggbdpq's
edfdf7b97, branch hunt101-ha-3985-responses-delta; the issue's patch
SHA-256 prefix 03728df281142c12 matches the branch's diff), run on mote
at d99e213f5 + this commit:
- The three new tests on origin/main d99e213f5 with responses.go as it
  was: TestResponsesBatchedCallsToChat and
  TestResponsesBatchedCallsByTurnsToChat FAIL ("tool calls: call_1
  read_file" with no args, call_2 with both); TestResponsesOwnOrderUnchanged
  passes there and here. All three pass with the fix.
- Real bytes: Copilot's captured stream (testdata/copilot_rotating_ids.sse,
  item ids rotating every event, output_index steady) translated for a
  Chat client still gives exec_command {"cmd":"go version"} (a review
  probe, not committed); TestCopilotItemKeepsItsID and
  TestResponsesCallArgs* pass.
- Probe: one call whose added names no output_index and whose delta and
  done name another item_id/index still reaches a Messages and a Chat
  client with its args (they come from the item's done).
- Hot path: per event, two more fields decoded and a scan of the waiting
  calls (empty in Responses' own order); a call's added line and first
  delta are decoded twice. Linear, no per-chunk buffering.
- gofmt -l clean; go vet -tags nogui ./..., GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./...; go build, GOOS=linux -tags
  nogui, GOOS=windows: ok. go test -tags nogui -count=1 -timeout 45m
  ./...: 81 packages ok, none failed (internal/gateway 779s).

Not tried: a real upstream that adds two calls before arguing either
(none is known; the report's stream is built by hand). Not handled: a
delta whose item_id and output_index both match no waiting call while
no call is open goes out with no call, as an unnamed one did before;
the call's args still come from its done item.

Refs #3985
2026-10-30 21:25:32 +08:00
yetone 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 96a703a59), on mote:
- go vet ./internal/gateway, and GOOS=linux / GOOS=windows -tags nogui
- go test -timeout 45m ./internal/gateway: ok (844s), at
  cb8f6ecca. Then rebased onto adc618bbf, whose only gateway change is a
  new test file (plugin_kinds_test.go). At this head: go vet
  ./internal/gateway and -run "CodexEffortChange|PluginKind" ok

Not tried:
- a real Codex thread through magpie to a real non-OpenAI vendor (the
  bodies are from the captured TUI request);
- GUI files: none touched.

Not covered here: ysm119's max on Cursor and DeepSeek. The agent isn't
known and the cause isn't confirmed, so it's filed as #4253 with what
was checked.
2026-10-29 18:29:55 +08:00
yetone 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 425a61322: peak 302, 301, 301 MiB (base heap 54 MiB)
  this change:    peak 278, 271, 273 MiB
Live at send is the same, 149 MiB above base (the request, its parse,
the body), as the conversation was garbage by then either way.

Tests: TestMarshalBodyLetsSpentGo (new) writes a list of probes, each
looking whether the item before it was let go, and that a list not
named spent is unchanged. Broken by hand (spend never zeroing): red,
"items [0 1 2 3] were still held when the next was written".
TestMarshalBodyIsJSONMarshal passes with the messages spent.

Run on mote at 425a61322 + this change: GOOS=linux/windows/darwin go
vet -tags nogui ./internal/gateway/: ok; go test -count=1 -timeout 45m
./internal/gateway/: ok (537.8s). Rebased onto f6e7214af, whose only
gateway change is a host in buildChat's inlineThink; at the pushed head:
the three vets again ok, and go test -run 'TestMarshalBody|MiniMax|
Minimax|TestChat|TestResponses|TestAnthropic|Translat' ./internal/gateway/:
ok (31.8s).

Not tried: a real upstream; the bytes sent are the same, which
TestMarshalBodyIsJSONMarshal holds to json.Marshal's.
2026-10-29 02:17:47 +08:00
yetone 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.
2026-10-28 17:50:17 +08:00
yetone 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).
2026-10-28 13:12:00 +08:00
yetone 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).
2026-10-27 23:38:47 +08:00
yetone 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 5e3dd1d52 plus this change:
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/sessions/
  ./internal/redact/ ./internal/claudeseal/: sessions, redact,
  claudeseal ok; gateway ok but for TestResponsesStreamToolThenHiddenThinking
  (#1786), whose hidden cases wanted no reasoning item, the loss this
  fixes. They now want one item carrying the sealed block with an empty
  summary, and its guarantee (a whole stream, no panic) is unchanged;
  re-run green.
- gofmt -l clean; go vet (darwin) on the touched packages, GOOS=linux
  go vet -tags nogui ./internal/..., GOOS=windows go vet on the touched
  packages: clean.
- TestCodexToolLoopGivesClaudeItsThinkingBack (a fake Anthropic: signed
  thinking, redacted_thinking, a text-less signed block, tool_use; a
  Codex-shaped request with store false and the encrypted_content
  include; then the follow-up) fails on 5e3dd1d52: "stream=true:
  Anthropic was sent 1 assistant blocks, want 4". Passes now, streamed
  and not.
- Real: a sandbox HOME with only OpenRouter's key (Anthropic endpoint,
  anthropic/claude-opus-5.5, served by Claude Platform on AWS), magpie
  serve on its own port, a Codex-shaped two-turn tool loop at effort
  high, streamed and not: turn 1 gave a reasoning item with
  magpie-claude1: (3.1KB), turn 2 was 200 through /v1/responses →
  /v1/messages and answered from the tool output.

Broken by hand:
- withoutClaudeSeals a no-op: TestClaudeBlocksNeverGoToAResponsesAPI
  red, the relay sent magpie-claude1: items.
- codexInputAs not leaving them out: red, "ChatGPT backend would be
  sent …".
- sealing any signature (no sealAnthropic check):
  TestGeminiSignatureIsNotSealedAsClaudes red.
- portValue's reasoning branch off: TestPortLineDropsClaudeBlocks red.

Not tried: the 400 itself. Through OpenRouter, Opus 5.5 answered turn 2
with the envelope stripped too (the old shape), so this route shows
only the lost reasoning, not the refusal. Not tried on api.anthropic.com
directly, Bedrock or Vertex keys, or Claude's subscription (whose tool
loop stays inside Claude Code's run). Codex resuming a ported thread
against OpenAI with such items wasn't run.
2026-10-27 11:26:54 +08:00
yetone 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 689cf4142), after another
  session's suite ended: 71 packages ok, internal/provider FAIL with
  "close of synctest channel from outside bubble" in filememo.Forget
  from TestUnreadLoginsWriteErrorsKeepCredentials: that is #3632, open,
  not touched here.
- Rebased on a6c808b68 (hermes.go, app.css, a GUI test, a doc: no file
  in common). The rerun at the pushed head could not build: the disk is
  full machine-wide ("no space left on device", 150MB free), so the
  tests were not run at the pushed head.

Not tried: a real Chat upstream reading detail (no reply differs in a
way a test can see without a vision model and a large image). No GUI
or i18n change, so no GUI run.
2026-10-26 17:58:26 +08:00
yetone 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 (720e491d2 + these two commits): gofmt clean, go build,
GOOS=linux and GOOS=windows go vet -tags nogui on gateway and provider;
go test -run 'Facts|Tier|Session|Responses|Metadata|UserWords|Prompt|Memo'
./internal/gateway ok. The full gateway and provider packages are
running and are reported on #3394.
2026-10-26 16:13:27 +08:00
yetone 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: b97e0aa2a 0.74s and 0.75s, this 0.67s and
  0.66s, about 62ms -> 55ms a request. All 48 answered 200.
- go test ./internal/gateway -count 1 -timeout 45m at this tree: ok
  (370s).
- No new test: the change is the encoder, and TestMarshalRawIsEncodingJSON
  already fails if marshalJSON's bytes differ from json.Marshal's.
- gofmt -l clean; GOOS=linux and windows go vet -tags nogui ./internal/gateway ok.
2026-10-25 00:59:10 +08:00
yetone 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: 2d21034d8 and this commit
  each answered "ok" 5 of 5, and the 5 upstream bodies are byte for
  byte the same.
- go vet (darwin; linux and windows with -tags nogui), gofmt -l clean.
- go test -timeout 45m ./internal/gateway/: ok (492s) at beef295be

Not tried: the full ./... suite at this head (queued behind others).
2026-10-24 21:59:05 +08:00
yetone 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 83234fe92 + this change:
- BenchmarkZZCodexStream (a 680 KB Codex request through the gateway,
  a probe not committed), -benchtime 30x -count 3:
  before 20,077,746 B/op 76,687 allocs/op;
  after  16,417,942 / 16,430,955 / 16,469,180 B/op, ~72,780 allocs/op
  (-18% bytes).
- Real account, sandbox HOME with only the DeepSeek provider, through a
  recording proxy to api.deepseek.com: 5 Codex-UA /v1/responses requests
  each with a user message, reasoning, function_call,
  function_call_output and assistant message in the history, on the old
  and new binary. All 10 answered "ok"; the 5 bodies sent upstream are
  byte-identical between old and new.
- gofmt -l clean; GOOS=linux and windows go vet -tags nogui
  ./internal/gateway ok.
- go test -timeout 45m ./internal/gateway/: ok (667s).

Rebased onto 1537817e0: build, both vets and go test -run
'Responses|Affin|Seal|Prompt|Tool|Codex|Reasoning|Orphan|DecodeJSON'
./internal/gateway/ ok (64s).

Not tried: the full ./... suite at this head (it runs after the push).
2026-10-24 21:38:12 +08:00
yetoneand卡提希娅可爱捏 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 21f7f9df2 (origin/main then) plus this change, unless said:
- New TestStreamRefusalAnsweredWholeRestsNobody: {response.failed, error
  event, refusal after text} x {Responses, Chat, Messages answered whole}
  x {next answers, nobody left}; fixture is the reporter's quoted message
  without magpie's 300-char cut. Asserts the client gets 200 from the
  next account or a 400 naming cyber_policy, every try failRefused with
  no Rest, nothing resting.
- New TestRestAfterPolicyRefusal: cyber_policy 400 rests nobody and
  counts 0 failures; a plain 400, and two 400s echoing the reporter's
  words in the message (code string_above_max_length / code null) still
  rest by backoff.
- Red on the old code: all 18 TestStreamRefusalAnsweredWholeRestsNobody
  subtests and TestRestAfterPolicyRefusal/cyber_policy. Broken by hand,
  each went red: filterRefused returning no status (all 18); the
  part-way clause dropped (6 "after some text"); refusedHeader not set
  (6 Messages subtests).
- A scratch matrix before the fix (also streamed Responses/Chat/Messages
  and Codex's own path, HTTP 400 and response.failed): only the whole
  routes rested; the streamed ones and the HTTP 400 already passed.
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
  go vet -tags nogui ./... clean.
- go test -race -timeout 45m ./internal/gateway/: FAIL on two tests
  this change doesn't reach, each ok alone with -race -count=3 and
  filed: TestPluginStreamLongActiveReader (client deadline after 36MB,
  #3286) and TestQuietKeptAliveOnlySoLong (0 keepalives in a 3s pause,
  #3287). Load was 180-280 from other sessions' GUI runs.
- Rebased on ba1dc7f97: gofmt, go vet ./internal/gateway/ and the two
  new tests again: ok.
- go test -timeout 45m ./... at ba1dc7f97 plus this change: ok, 69
  packages, no FAIL (internal/gateway 783s).

Not tried: a real Codex account. Whether the ChatGPT backend sends
cyber_policy as an HTTP 400 or inside a 200 stream, and with or without
an error type, isn't known from the issue; every shape is covered by
tests, not by a live refusal.

Co-authored-by: 卡提希娅可爱捏 <134358478+CartethyiaQwQ@users.noreply.github.com>
2026-10-22 22:53:47 +08:00
yetone 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 82fb0702f), sandbox HOME, one suite on
the machine: gofmt -l internal/ clean; go vet ./... (darwin),
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... all clean;
go test -timeout 45m ./... every package ok (gateway 890s, agent 871s,
provider 447s), no FAIL. Rebased onto 52209522a (gui assets, redact and a
gateway-routing.md line of others; no overlap in code): go build ./...,
go vet of gateway, cli and redact, the tests above with TestToolSearch*
and TestCodexAsSent, and go test ./internal/redact, all ok. GUI (playwright) suite not
run: no GUI asset changed (internal/gui/providers.go is Go, in the suite).
2026-10-21 19:58:52 +08:00
yetone 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 efd1b697e):
- gofmt -l: clean
- go vet ./...: darwin, GOOS=linux -tags nogui, GOOS=windows: clean
- set -o pipefail; go test -timeout 45m ./...: exit 0, 68 packages ok
  (gateway 660.6s, provider 270.9s), no FAIL
- broken by hand, each went red then green on restore: removing the
  "none" emit (ReachesPlugin, PerBuilder/responses); grokPluginBody with
  keepNone=false (TestGrokPluginBodyKeepsLoneNone, ReachesPlugin);
  dropping the !p.IsPlugin() check (NotSentToVendor)
- plugins: bun test 2018 pass, 0 fail; the new tool-choice test is red
  against the old index.mjs

Not tried: live Grok, xAI or OpenAI with a lone "none". Other Responses
plugins (commandcode, factory, opendesign, zed) now get a lone "none" in
this case; their vendors take Codex's lone "auto", but this is untested.
2026-10-21 10:14:07 +08:00
yetone 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 d783df46c plus this change (load 160-330 from other sessions): gofmt -l clean; go vet ./... for darwin,
linux (-tags nogui) and windows ok; go test -timeout 45m ./...:
60 packages ok; internal/agent, internal/gateway and internal/library
timed out at 45m (#2544/#2723, #2108, filed #2853), internal/gui's
TestSetAnswersWhileDevinAndProvidersHang (#1375) and TestMainWindowCorners
(#2645) red. Rerun alone: internal/library ok 1184s; the two gui tests
ok; internal/gateway timed out at 45m again (load ~300), then at
-timeout 3h ran 2887s with one red, TestClaudeAccountsSpentFallBackToCodex
"stream=true: no answer" at its 30s wall wait (filed #2858; -count=3
alone ok). The tests above, after the rebase: ok.
2026-10-19 00:33:29 +08:00
yetone 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 cf21b71ff):
- new tests in internal/gateway/phase_test.go: encoder (call, reasoning
  then call, last, reasoning after, length cut, two messages around a
  call, keepalive while held), renderResponses, phase tidy (SSE fed a
  byte at a time, CRLF, upstream phase kept, incomplete, no end, whole
  reply with a 20-digit number kept) and a passthrough through the gateway
- broken by hand, each went red: encoder release ignoring the phase (3
  tests), renderResponses without phaseOutput (1), passthrough without
  the tidy (1), unphased ignoring an upstream phase (1 subtest)
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows ok
- full suite: set -o pipefail; HOME=<scratch>/home-2437 GOMODCACHE=~/go/pkg/mod go test -tags nogui -count=1 -timeout 45m ./... at cf21b71ff plus this change: exit 0, 66 packages ok, none FAIL (gateway 844s, provider 355s)

- rebased onto origin/main a61a6f954 and run again: gofmt -l clean; go vet -tags nogui darwin, linux, windows ok; set -o pipefail; go test -timeout 45m ./... in a scratch HOME: exit 0, 66 packages ok

Full suite: green at a61a6f954 plus this change, 66 packages ok, exit 0.
2026-10-16 02:43:02 +08:00
yetone 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).
2026-10-15 16:51:31 +08:00
yetoneandggbdpq 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>
2026-10-15 09:36:25 +08:00
yetoneandggbdpq 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 2a99e7a42, and
again on 91b9065a5 for vet, gui, provider, tui, gateway, agent and
the tests named here:
- TestTranslatedToResponsesAnswersALoneCall is red without the
  responses.go change (the lone call_a goes into input unanswered) and
  green with it; TestPairToolItems*, TestResponsesRelay* and the Zed
  tests pass.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ./...;
  go build for the three; go test -tags nogui -count=1 -p 4 ./... at a machine load of 100-150:
  50 packages ok; internal/agent and internal/gateway ran past the 10m
  default under that load and pass with -timeout 40m (674s, 798s);
  internal/gui's TestSetAnswersWhileDevinAndProvidersHang failed once
  (a state took 10.4s; open as #1375) and the package passes rerun.
- The shape against ChatGPT's real Codex backend (gpt-5.6-luna, the
  owner's account, store false): a lone call is answered "No tool output
  found for function call call_a." and the same history with the call
  paired completes.
Not tried: a real interrupted Chat client end to end through magpie.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 01:56:35 +08:00
yetone 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 2fbbd1694 with the fix stashed: V1 and V4
  "status 400: Fake: No tool output found for tool call call_aaaa1111",
  and got [function_call:a function_call:b message: ...] want
  [message: function_call:a ...]; pass with it.
- gofmt -l clean; go vet ./internal/gateway (darwin), GOOS=linux -tags
  nogui, GOOS=windows: clean.
- go test -tags nogui ./internal/gateway/... under a scratch HOME with
  pinned caches: ok (2011s at load ~230; a first run with the default
  10m -timeout was killed by the timeout under that load, not a failure).
Not tried: the real OpenCode Go. The key on this machine answers "This Go
model requires Global regions" / "An active OpenCode Go subscription is
required" for every Go model, and Zen's free tier refuses non-OpenCode
clients, so the fix rests on the reporter's V1-V4 table and the fake.
2026-10-14 15:20:24 +08:00
yetoneandBussanQ 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>
2026-10-14 05:23:58 +08:00
yetone 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.
2026-10-13 14:48:49 +08:00
ump45nose 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) 2026-10-13 05:09:18 +08:00
yetoneandEdward4226 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, f4cc7459), would get a step that isn't.
  Anything else there (a subagent's agent_message, a note) still moves after
  the run, so TestGrokGetsAgentMessageAsUser's expectation from the previous
  commit stands.
- A call opens a run only when a result after it answers it. Before, a result
  written before its call (an odd replay) left the run open for the rest of
  the request, and every later message was moved to its end.

Where it happens, checked in Codex's source: prepare_response_items
(core/src/image_preparation.rs) pushes the developer <image_resize_notice>
right after each function_call_output / custom_tool_call_output whose image
it resized, so a batch of two image results has it between them, as #1822's
rollout shows (lines 347-349).

Routes: joinToolRuns sits in attempt before every destination, so the
Responses relay, plugins (relayed through passthrough) and translations all
get it. Translations rebuilt the order themselves for a developer or user
item (the developer one is lifted into the system prompt, user turns merge
and results go first), but an assistant message between two results closed
the chat exchange: pairToolMessages answered the second call with the
synthetic "unavailable" result and sent the real one as user text
(TestTranslatedToolRunKeepsItsRealResults, red without the call site).

Docs: gateway-routing.md says what attempt mends in a Responses request's
tool exchanges (joinToolRuns, orphanedToolOutputs, pairToolItems).

Run:
- TestRelayedCodexImageBatchKeepsItsResultsTogether (#1822's call ids, two
  view_image results, the notice between; the fake answers DeepSeek's "No
  tool output found for tool call …") and TestTranslatedToolRunKeepsItsRealResults
  fail with the call site removed (400 / synthetic result) and pass with it.
  TestJoinToolRunsOnlyMovesWhatBreaksARun fails on the previous commit's
  joinToolRuns (reasoning moved, local_shell_call moved, a request rewritten
  for a result before its call) and passes now.
- go test -tags nogui -count=1 ./internal/gateway/ under a sandbox HOME with
  a private GOCACHE: ok (376s). gofmt -l: nothing. go vet (darwin),
  GOOS=linux go vet -tags nogui, GOOS=windows go vet on ./internal/gateway/:
  clean.
- Real DeepSeek (api.deepseek.com/v1/responses, deepseek-v4-flash), direct:
  a developer note between the two results 400 "No tool output found for
  tool call call_01_x2"; the same note after the results 200. Through a
  sandbox magpie (own HOME, :3591, only the deepseek provider), streamed and
  whole: origin/main's build 400 with that refusal, this build 200. The
  <image_resize_notice> text itself between the results is answered 200 by
  DeepSeek directly, before and after, with text results.

Not tried: OpenCode Go (this account's workspace isn't set to Global
regions, so every request there is refused before the model); the
reporter's image results and full-length history; Volcengine; a real Grok
subscription for the agent_message's new place.

Co-authored-by: Edward4226 <234070868+Edward4226@users.noreply.github.com>
2026-10-13 03:49:32 +08:00
Edward4226 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 6c1c0a7 as well and neither from this change -
  TestClaudeAsRootEnv (a Linux-only expectation with no Windows guard) and
  TestSweepBridgeProjectsTakesOnlyTheBridgesFolders (needs a symlink
  privilege this Windows box doesn't hold). Everything else passes,
  TestQueuedStreamKeptAliveOnceSentToItsVendor among them (that one failed
  once on main under load; it is the queued-stream timing in the standards).
- the same run under a temporary HOME with GOPATH/GOMODCACHE/GOCACHE pinned
  from go env: the same two failures.
- gofmt -l on the four changed files: nothing. go vet ./..., GOOS=linux go
  vet -tags nogui ./..., GOOS=windows go vet ./...: clean. go build,
  GOOS=windows go build, GOOS=linux go build -tags nogui: ok.
- without the change: with the one call-site line taken out,
  TestResponsesRelayKeepsAToolRunTogether prints
  `status 400: ... "Fake: An assistant message with 'tool_calls' must be
  followed by tool messages responding to each 'tool_call_id'."`; the line
  back, it passes.
- real upstreams, the reporter's shape (two parallel calls, an image
  result, Codex's <image_resize_notice>, the second result), the same build
  with the line and without it, streamed the way Codex sends it:
  Volcengine Agent Plan / deepseek-v4.1-flash - run whole 200/200; the
  notice between the results 400 "insufficient tool messages following
  tool_calls message" then 200; any other note there 400 then 200.
  OpenCode Zen/Go / deepseek-v4.1-flash - run whole 200/200; a note between
  the results 400 "No tool output found for tool call call_b" then 200; the
  notice between them 200/200, their gateway recognizing that one item.
- the reporter's own rebuilt turn (1399 items, from their rollout) to
  Volcengine: refused "insufficient tool messages following tool_calls
  message" without the change, past that check with it (what is left is the
  input's length, 1.7M tokens, over the model's limit).

Not tried: a real Grok subscription - the reply's new place is unverified
against xAI's backend, though its conversion is unchanged and its plugin
(community plugins packages/grok) converts in place the same way; a real
ChatGPT (native Codex account) destination, which takes standalone tool
outputs itself and is left as it came; the Windows GUI. The OpenCode Zen/Go
400 of the original report is not reproduced by the reporter's own bytes:
with both results and the notice between them that gateway answers 200
before and after this change, so the report's refusal may be the follow-up
body assembled before the batch's last output was in it
(openai/codex#44604).

Refs: #1341, #1275. Reported as anomalyco/opencode#54698 and
openai/codex#44604.
2026-10-13 03:49:32 +08:00
yetone 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.
2026-10-13 00:08:23 +08:00
yetone 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.
2026-10-12 22:21:49 +08:00
yetone 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 498b77fbc, with #1667's fix below it: all 48 packages ok
  (gateway 394s).
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway clean.

Not tried: real vendor traffic; Windows and Linux runs (vet only).
2026-10-12 03:28:16 +08:00
yetone 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.
2026-10-11 19:59:15 +08:00
yetone 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.
2026-10-10 13:29:45 +08:00
yetone 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.
2026-10-09 14:16:53 +08:00
yetone 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.
2026-10-09 01:19:25 +08:00
yetone 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.
2026-10-08 16:53:56 +08:00
yetone 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.
2026-10-08 10:37:02 +08:00
yetone 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.
2026-10-08 02:15:01 +08:00
yetone 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. 2026-10-03 10:28:46 +08:00
yetone 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. 2026-10-03 06:10:29 +08:00
yetone 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. 2026-10-03 06:09:11 +08:00
yetone 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). 2026-10-03 00:47:33 +08:00
Zhaofeng 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
2026-10-02 18:26:23 +08:00
yetone 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). 2026-10-02 15:59:14 +08:00