Commit Graph
71 Commits
Author SHA1 Message Date
yetone 2979fbdc99 gateway: OpenCode 1's promptCacheKey reaches the upstream as prompt_cache_key (#5468)
OpenCode 1 (opencode-ai 1.19.5) with its provider's setCacheKey writes the
session's key into a Chat body as camelCase promptCacheKey (a real run on
mote against a recording server: "promptCacheKey":"ses_…"), a field no Chat
API reads; a passthrough upstream got it as written and no cache key, a
translated route never read it. The next commit has magpie set setCacheKey
for OpenCode, so this comes first.

Now a Chat request's promptCacheKey is taken out and sent as
prompt_cache_key, for every route (handle, beside thinkingEffort), so
req.CacheKey and the relay both see it. A prompt_cache_key the body has
already is the one kept. The body is re-encoded without HTML escaping.

Run on mote: go test -run 'OpenCode|CacheKey' ./internal/gateway ok; go vet
./internal/gateway on darwin, GOOS=linux and GOOS=windows; go build ./...
(darwin, windows).
Broken by hand: without the cacheKeyCamel call, TestOpenCodeCamelCacheKey
fails (upstream body still "promptCacheKey":"ses_1a2b", no
prompt_cache_key).
Not tried: OpenCode 1 through a running magpie gateway end to end (the
recording server saw OpenCode's body; the test covers magpie's half).

Reported-by: mariamatrix
Reported-by: mahiro233
2026-11-06 15:02:53 +08:00
e1d4dca967 gateway: a Chat reply's leading <thinking> block is read as thinking
A Chat reply may open its reasoning with <thinking>…</thinking> in the
text. thoughtTags held only <thought> and <think>, so neither tag matched:
chatDecoder.text took the block for the answer's own text and no thinking
block went out (#5106). In a recorded day on one OpenAI-compatible host,
47 of 2832 turns carried a literal <thinking in the answer's text, 44 of
them at offset 0 (neighbads).

<thinking> is added beside the two, closed by </thinking>. It shares no
whole prefix with <think> (they part at the seventh byte, 'i' against
'>'), so the wait in text covers the shared lead and no lead can name two
opening tags. markedThought reads the same map, so a Gemini-marked chunk
opening with <thinking> is thought's text too.

afterThought, which strips a leading block from the titles,
descriptions and predictions Codex asks for (codex_titles.go), now reads
the same map instead of its own <think>, so a <thinking>- or
<thought>-led reply no longer leaves the block in a title (added in the
port; the patch left it as a sibling).

Run (mote): go test -tags nogui -count=5 -run 'TestChatThoughtTags|
TestMarkedThought|ThoughtTag|TestAfterThought|Title|Description'
./internal/gateway/ ok; gofmt -l clean; go vet -tags nogui
./internal/gateway/ clean.
Broken by hand: chat.go put back to origin/main, the four <thinking>
cases of TestChatThoughtTags FAIL and TestAfterThoughtCloseInCode FAILs
on the <thinking> and <thought> leads.
Not tried: a live model that sends the tag (the reporter's model sends
it in about 1.7% of turns, not on demand). The plugins repo's think-tags
middleware keeps its own list and is not changed here.

The tag and the whole/split cases are neighbads' patch on their fork;
ggbdpq added the open-tag-alone and never-closed cases.

Fixes #5106

Generated-by: GLM-5.3-Flash (ZCode)
Co-authored-by: neighbads <16126598+neighbads@users.noreply.github.com>
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 10:04:22 +08:00
yetone 9feb1024c7 zen: free models are asked as OpenCode 2.2.5 asks them (#3491)
laomao04_65777 on Discord: Zen's free models answered 429 "Free usage limit
reached. Free models work in OpenCode" to the built-in OpenCode Zen provider,
while real OpenCode 2 on the same machine was served. magpie sent OpenCode
1.x's shape. It now sends what OpenCode 2.2.5 sent in a captured request
(internal/provider/testdata/opencode-2.2.5-chat.json, from a recording proxy),
as the zen-free plugin does since plugins d62193c and 8501988:

- User-Agent opencode/latest/<v>/cli. <v> is the version OpenCode's updater
  (opencode.ai/update/api/latest/cli/npm) names, never below 2.2.5 and never
  anything but a plain x.y.z. It is read in the background at most every 6h,
  with a 3s timeout and no redirects.
- x-opencode-project is OpenCode's project id for the folder the agent says it
  works in: sha1 of git-remote:host/path (origin, else the first remote;
  worktree .git files followed), else of directory:<root or folder>. It is no
  longer "global".
- b3 and traceparent: one trace a conversation, a new span a request.
- The session id goes in x-opencode-session, x-opencode-session-id,
  x-session-affinity and x-session-id. Accept is */*, and x-opencode-request
  is gone.
- On a free request the agent's own headers (Claude Code's x-stainless-*,
  Codex's originator) are dropped. Only Content-Type and Anthropic-Version
  and Anthropic-Beta are kept.
- The core tools are edit, glob, grep, read and shell with 2.2.5's schemas,
  strict false on Chat. Claude Code's Read, Edit, Glob and Grep are offered
  under those names. Its Bash is no longer bash: shell is a stub.
- OpenCode's <env> block, word for word, for the agent's folder, is added to
  the system prompt unless it has one already (OpenCode's own).
- Paths are the v2 catalog's: /inference/openai/v1 for Chat and Responses,
  and /inference/anthropic/v1 for Messages. The models list is unchanged.

Every route takes this: chat, responses and messages through forwardOnce, the
Test button's probe (tiny/zenFreeProbe), and the models list
(listHeadersAt: UA and x-opencode-client).

Sibling: paid Zen and OpenCode Go share OpenCodeClient, so they get 2.2.5's
headers. Their /zen/v1 and /zen/go/v1 paths are left as they are: #4740.

Run on mote (mote-run) at this tree:
- gofmt -l . is clean.
- GOOS=darwin and windows go vet ./... pass. GOOS=linux go vet passes for
  internal/provider and internal/gateway. The whole-tree Linux vet stops in
  Wails' cgo when run from macOS, and in WSL for want of gtk4, before it
  reaches this change.
- go test ./internal/provider ./internal/gateway -count=1 -timeout 45m:
  ok provider (154s) and ok gateway (715s) on base 788057340. After the
  rebase onto a5a9cdf7b, which touched gateway.go and ir.go, the same
  tree passed again: ok provider (138s) and ok gateway (816s), with GOOS
  darwin, linux and windows go vet of both packages.
- Rebased again onto 4c815ac2a, which touched search.go and provider.go.
  At that head gofmt and the three-OS vet of both packages are clean, and
  -run 'OpenCode|Zen|Search|Searcher' passes in both packages. The full
  suites were not rerun after this last rebase.

Broken by hand, each turning a test red (provider and gateway, -run
'OpenCode|Zen', on mote):
- version 1.19.0: TestOpenCodeClientIs225 and TestOpenCodeVersionFromUpdater.
- the old /inference/v1 path: TestOpenCodeFreeURL, TestZenFreeAsOpenCode225,
  TestZenFreeAtInferenceURL and TestZenPublicTestAsksFreeModels.
- caller headers kept: TestZenFreeAsOpenCode225.
- no env block: TestZenFreeAsOpenCode225.
- no strict: TestZenFreeAtInferenceURL.
- project "global": TestOpenCodeClientIs225, TestOpenCodeClientHeaders and
  TestZenFreeAsOpenCode225.
- the same span on every request: TestOpenCodeClientIs225 and
  TestOpenCodeClientHeaders.
- no 2.2.5 floor: TestOpenCodeVersionFromUpdater.
- a changed read schema: TestOpenCodeToolsAre225s.

Not tried:
- A real 200 from a free model: this egress IP's free allowance is spent.
  The captured 2.2.5 request itself got 429.
- Header order and case: Go's HTTP/1 writes headers sorted, and HTTP/2
  lowercases them, so OpenCode's order cannot be copied.
- Windows' project id against real OpenCode on Windows.
2026-11-01 14:48:19 +08:00
yetone 645eb92f3f gateway: a refusal after shown thinking goes to the next fallback
yhwangl on X: a request whose content trips a vendor's safety filter
after the model streamed its thinking, before any answer, stopped there;
the group's next member was never asked, as it is when credit runs out.

When a model's reasoning is shown, a try passes on its first thinking
event, so a refusal after it was the agent's. Now, for a streamed
Anthropic, Chat or Responses request with another member still to ask
(handsOver), the try's events go out one by one (passOver) and a refusal
or refusal error before any text or tool call hands the request on
(handOver): Anthropic's open blocks are closed and the next member's
stream is spliced into the same reply (spliceAfter): its message_start
or response.created/in_progress/queued are dropped, block indexes or
output_index go after those sent, sequence_number goes on. Chat chunks
go as they come. Once text or a call has gone, a refusal stays the
agent's as before. With no other member nothing changes. A refusal is
about the request, so nobody is rested for it.

Zhipu's finish_reason "sensitive" and error 1301 (敏感), DashScope's
data_inspection_failed and Volcengine Ark's *SensitiveContentDetected
are now read as refusals too.

Not covered (#4604): Gemini clients; a Responses reasoning item handed
over gets no output_item.done and the next completed lists only its own
output; A's thinking signature stays in the reply; non-streamed requests.

Run (mote, worktree at base 3baf3b6df):
- go test -count=1 -timeout 45m ./internal/gateway/...: ok (597s)
- targeted -run 'TestRefusal|TestSensitive|TestThinking|TestDeepSeek|
  TestStreamEvent|TestHighRisk|Refus': ok
- gofmt -l internal/: clean; go vet ./internal/gateway; GOOS=linux go vet
  -tags nogui ./...; GOOS=windows go vet ./...: ok
Rebased on 8a410f35a (5 commits, Claude TUI files in internal/gateway):
go vet ./internal/gateway and the targeted run plus ClaudeTUI|
ClaudeSubscription tests ok at the pushed head.
Broken by hand: handsOver forced to false (the old behaviour):
TestRefusalAfterShownThinkingGoesToTheNext (every upstream x client
subtest: b never asked), TestRefusalHandedOverTwice and
TestDeepSeekRefusalHoldsATrustedMemberAgain red; reverted.
Not tried: a real GLM, DashScope or Ark account tripping its filter, and
a real Claude Code or Codex client reading the spliced stream; the tests
use fake upstreams with GLM's, DeepSeek's and Anthropic's event shapes.
2026-11-01 00:40:07 +08:00
yetone ccc791231f gateway: a long turn sent to a Chat upstream is copied once, not five times
A 3.2 MB Codex /v1/responses request served by a Chat provider allocated
about 70 MB in the gateway, and that garbage, at GOGC 100 over the app's
live heap, set the peak footprint. Four copies went:

- unquoteJSON built an escaped string (any text with a newline) in a
  buffer and then copied it into a string; the buffer is the string now
  (unsafe.String, nothing writes to it again), with a copy only when
  \u escapes left more than a quarter of it unused.
- turnIn joined every user text of the conversation (userSaid) only to
  see whether any was there; saysAnything stops at the first.
- buildChat's user message grew a strings.Builder part by part across
  a merged turn; joinTexts sizes it once and takes a lone part as it is.
- marshalItems ran json.Marshal, whose buffer doubles and is then
  copied out, over one message that holds the whole turn. marshalSized
  sizes the maps, lists, strings, bools and ints a body is made of
  first and writes them into one slice of that size, as encoding/json
  writes them (HTML escaped, � for bad UTF-8, U+2028/2029); any
  other value is json.Marshal's own. A []any item, reached by its
  address, is a *any, which went to json.Marshal twice (to size, then
  to write) until it was dereferenced; TestMarshalBodyAllocatesTwoBodies
  caught that at 154 MiB for a 47 MiB body, now 52.

Run on mote (M5 Pro), at this tree:
- TestLongTurnCopiedFewTimes, a 2.0 MB 300-turn Responses body with
  CJK and newlines: read 6.72 MB -> 4.76 MB (3.4x -> 2.4x), turnIn
  1.93 MB -> 10 KB, buildChat 27.3 MB -> 6.06 MB (13.7x -> 3.0x).
  Broken by hand one at a time in the mote copy, each red on its own
  bound: unquote back to string(b) 3.4x; userSaid back in turnIn
  1.9 MB; the Builder back 7.4x; json.Marshal back 6.2x.
- TestMarshalSizedIsJSONMarshal: byte for byte against json.Marshal
  over all 256 bytes, bad UTF-8, a lone surrogate, U+2028/2029, HTML
  characters, keys needing escapes, nil maps and lists, floats,
  RawMessage, pointers, and a func json.Marshal refuses.
- go test -count=1 -timeout 45m ./internal/gateway/: ok (582.9s).
- go vet ./internal/gateway/ for darwin, linux and windows; gofmt clean.
- Gateway bench (120 requests of a 3.2 MB Responses body, 4 at a time,
  through a fake Chat provider, 200 MB ballast held live), 3 runs each,
  old/new: TotalAlloc 8368-8403 MB -> 5889-5891 MB (-30%), GCs 26-27
  -> 18-19, phys_footprint_peak 795/806/807 MB -> 763/762/749 MB,
  CPU 7.89-7.92 s -> 8.01-8.17 s (the size pass costs about what the
  copies saved).

Real use: this build (go build -tags nogui) in a sandbox HOME with the
owner's DeepSeek key only, magpie serve on 127.0.0.1:3581. A 180 KB
/v1/responses request (a long CJK turn with <tag> & "quotes" \ tabs,
a function_call and its output holding U+2028, then a question) to
deepseek/deepseek-flash, served through buildChat: answered with both
code words as sent (<ZEBRA&42>, MANGO), non-streamed and streamed.

Not tried: an Anthropic-in, Chat-out request, and the live app's own
peak (the bench stands in for it).
2026-10-31 21:39:37 +08:00
yetone 2987f5e2b7 gateway: a Chat usage's magpie_cache_unknown is read, as an Anthropic one's (#3991, #3979)
Trae CN users see cache read 0 / write 0 on every call. Trae's chat
token_usage stopped naming any cache count around 10-28 (modeyang's 786
trae-cn calls on 10-29 all at 0; plugins#434). opencode-trae-auth 0.2.26
now says magpie_cache_unknown on such a usage, as the Kiro plugin does,
but only aUsage read that flag: cUsage, which a Chat plugin's usage goes
through, dropped it, so the zero still counted as a 0% miss.

cUsage now reads magpie_cache_unknown into Usage.cacheUnknown, so the
route and the usage ledger mark the call's cache as unknown instead of a
miss. A counted 0 (prompt_tokens_details.cached_tokens: 0) stays a miss.
The flag is read, never told by chat(); a same-protocol reply is passed
through as it came, as Kiro's is on /v1/messages.

Test: TestChatCacheUnknownReachesTheRoute, with the plugin's Chat output
for chansee97's real token_usage (plugins#455): pi whole, pi streamed,
translated for Claude Code, and a counted miss.

Run (mote):
- go test -run 'CacheUnknown|CacheCounted' ./internal/gateway: ok
- broken by hand: the old chat.go fails 3 of 4 subtests (the counted
  miss stays green)
- go vet ./internal/gateway on darwin, GOOS=linux, GOOS=windows: ok
- gofmt -l internal/gateway: clean
- go test -timeout 45m ./internal/gateway: ok (641s), at base d6e111638 plus this change;
  rebased on d9845432f (4 commits, none in internal/gateway), where
  -run 'CacheUnknown|CacheCounted|Usage' ./internal/gateway: ok

Not tried: a real Trae CN account (none available), so whether Trae now
omits the cache fields or sends 0 is not confirmed; if it sends 0, the
call stays a 0% miss. Not run: the full ./... suite (the change is one
struct field in internal/gateway).
2026-10-31 20:35:12 +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
yetone cae785a37a chat: max_completion_tokens to OpenAI's own API, and the other name once a 400 asks for it
GoxxKintBlade on X (tweet 2116038360645206158, v0.1.2145) and Jothulmo
(tweet 2116045916549652992): an OpenAI API key provider's test was red
for every model, "gpt-6.1-sol: 400 Unsupported parameter: 'max_tokens'
is not supported with this model. Use 'max_completion_tokens' instead."

Cause: the model test's Chat body (provider.tinyBody) sent max_tokens
to every host but Bedrock and Azure. The gateway had the same gap on a
pass-through: a chat client's max_tokens (and magpie's own image
describer and classifier, which ask the gateway in Chat with max_tokens)
went to api.openai.com as sent. Only the Anthropic/Responses-to-Chat
translator (buildChat) already used max_completion_tokens there.

Fix, scoped by vendor:
- provider.OpenAIHost: openai.com and *.openai.com only (not Azure,
  not "notopenai.com", not a relay).
- The test's Chat body asks OpenAI's own API with max_completion_tokens.
- The gateway's forwardOnce, the one place every upstream request
  passes, renames max_tokens to max_completion_tokens for OpenAI's own
  API (chatTokenField). DeepSeek (deepseekTokenField), Zhipu and relays
  get the body as the client sent it.
- A Chat 400 whose words name the other field as the one to use
  (provider.TokenFieldWanted: "use 'max_completion_tokens'" or "use
  max_tokens"; a limit on the value is not one) is asked once more with
  that name, in the model test (probe) and in the gateway (forward,
  retryTokenField), and the gateway remembers it per provider in unfit.
  That covers a relay in front of OpenAI's reasoning models. The key is
  renamed in place (provider.WithTokenField), so the rest of the body
  keeps its bytes.

Tests (new): TestOpenAIProbeAsksMaxCompletionTokens,
TestProbeRetriesTokenFieldNamed, TestTokenFieldWanted, TestWithTokenField
(internal/provider); TestOpenAIChatGetsMaxCompletionTokens,
TestChatTokenFieldRetriedWhenNamed (internal/gateway). The last one also
checks that a vendor reading max_tokens gets the body as sent, in one
request; TestDeepSeekChatGetsMaxTokens still passes unchanged.

Broken by hand: OpenAIHost taken out of tinyBody, probe's retry turned
off, chatTokenField and retryTokenField returning early. All four new
behavior tests went red with real FAILs (the probe test: "Status:400 ...
Use 'max_completion_tokens' instead."; the gateway retry test: HTTP 400
from the relay), and green again with the change put back.

Run on mote (mote-run): gofmt -l internal/ (nothing),
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... (VET-OK),
go test -timeout 45m -count=1 ./internal/provider ./internal/gateway
at base dca3e2d71: internal/provider ok (340s); internal/gateway was
still running at push time. Rebased onto e8d42c02d (6 commits, which
change both packages), then at this head on mote: gofmt -l (nothing),
linux and windows go vet ./internal/... (VET-OK), and go test -count=1
-run "TokenField|OpenAIProbe|OpenAIChat|DeepSeekChatGetsMaxTokens|
Bedrock|Azure|Mantle|TestModels|TestTest" on both packages: ok.

Not tried: a real OpenAI key (no real network in tests; the fixture is
OpenAI's own 400 text from the report). The full ./... suite runs on
mote after the push.
2026-10-30 14:17:26 +08:00
yetone fc16214dac gateway: a <think> block after a line end at a Chat reply's head is thinking (jenryai on X)
jenryai on X (tweet 2115754572383932513) said a Grok reverse proxy added
as a custom provider gives its thinking as the answer's text. The Chat
decoder takes a leading <think>…</think> as thinking, but only after
spaces and "\n". grok2api_python (xLmiler, a Grok relay) writes its
grok-3-search results as "\r\n<think>{results}</think>\r\n" at the head
of the reply, so the "\r" made the whole block text, on every
translated route (Claude Code's Messages, Codex's Responses, streamed
or not). The lead now skips " \t\r\n" (leadSpace), the line breaks after
the close are trimmed with their "\r", and afterThought (Codex titles)
skips the same lead. Scoped by what is in the stream: a <think> later in
the text is still the model's words, and a plugin's Chat text is still
read as it came.

Checked against the relays' own source, the others already worked here
and are not changed: chenyme/grok2api (Go, and its Python 1.x
reasoning_content), jiujiu532/grok2api (reasoning_content),
TQZHR/grok2api's "<think>\n…\n</think>\n" and grok2api_python's
"<think>" + token for its reasoning models were all run through
/v1/messages and /v1/responses and came out as thinking. The plugins
repo's think-tags middleware already skips /^\s*/ before the tag.

Tests: TestGrokRelayThinkAfterLineEnd sends grok2api_python's literal
chunk shape (json.dumps spacing, \u-escaped Chinese, no finish_reason
before [DONE]) to /v1/messages streamed and not, and to /v1/responses;
TestChatThinkTags gains a "\r" + "\n<think>" split and a tab lead;
TestAfterThoughtCloseInCode a "\r\n" lead. Broken by hand: with
chat.go's change stashed, all three routes of the new test, both new
TestChatThinkTags cases and the afterThought case are red (the answer
was "\r\n<think>\r\n<details>…</think>\r\nMagpie is a gateway.").

Run (mote, at this commit on f6263439a): gofmt -l clean; go vet
./internal/gateway for darwin, GOOS=linux and GOOS=windows ok;
go test ./internal/gateway -timeout 45m -count=1: ok (472s).

Not tried: the reporter's own relay and client (not named yet), a real
grok2api_python deployment, and other packages' suites (only
internal/gateway changed). The reporter's "流口水" (slow/stuttering, or
rambling) has no cause found in magpie; the relays' tool-call sieves
hold text back on their side.
2026-10-29 19:34:39 +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 f6e7214af7 minimax: api.minimax.cn is MiniMax China, for the usage card and the thinking sent back
MiniMax moved its China API host to api.minimax.cn (MiniMax-AI/cli
8746d48f, 2026-09-28: mmx agent setup now writes it into Claude Code,
Codex, OpenCode and pi). api.minimaxi.com still answers, but a provider
pointed at the new host got no usage card, because the plan-quota source
knew only api.minimaxi.com and api.minimax.io. Chat requests to it also
lost the <think> block MiniMax wants back on the turns after.

Every place in magpie that matches MiniMax by host is covered:
- planquota.go: api.minimax.cn reads /v1/token_plan/remains on its own
  host. Probed without a key, api.minimax.cn answers this path with the
  same base_resp 1004 as api.minimaxi.com.
- gateway/chat.go: inlineThink also matches minimax.cn.
Pricing and the catalog go by the provider's Catalog id ("minimax"),
not by host, so nothing changes there. The presets keep api.minimaxi.com.

Tests: a TestPlanQuotaSource case and a TestMiniMaxThinkingGoesBackInTags
case for api.minimax.cn. Both are red on the old code (code reverted by
hand, test kept; mote-run) and green with the fix.

Run on mote (mote-run):
- At 96bfdd57c (base 11c427eaa): gofmt -l on the changed files prints
  nothing; GOOS=linux go vet -tags nogui ./... ok; GOOS=windows go vet
  ./... ok; go test -count=1 -timeout 45m ./...: 76 packages ok
  (internal/gateway 1073s, internal/provider 490s). internal/gui timed
  out at 45m, with TestRestartHandsTheGatewayOver stuck 43m in
  gateway stopAccepting during the handover at load ~110. That is not
  this change: filed as #4107 with the stacks.
- Rebased onto 425a61322 and run again at this head: TestPlanQuotaSource
  and TestMiniMaxThinkingGoesBackInTags pass; ./internal/provider ok;
  go vet (darwin), linux -tags nogui and windows vet ok;
  TestRestartHandsTheGatewayOver -count=5 ok.
Not tried: a real Coding Plan key against api.minimax.cn (I have none),
so the card on that host is checked only by the shape of the no-key reply.
2026-10-29 01:52:34 +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 c752082e47 gateway: a turn's thinking goes back to Qoder's plugin; qoder min 0.2.42
uk.jent on Discord: Qoder dropped the model's earlier thinking. Qoder.app's
own client sends reasoning_content on every earlier assistant turn, and the
Qoder plugin left it out from its first version on; 0.2.42 sends it.
An Anthropic- or Responses-speaking agent's thinking reached the plugin
only when chatReplaysReasoning held, so qoder and qoder-cn are added
beside Command Code's plugin; a tool turn with no thinking gets the same
" " DeepSeek gets, which 0.2.42 reads as none. The qoder mover min is
0.2.42 (npm view --prefer-online: 0.2.42).

Run (mote): go build ./..., go vet -tags nogui on gateway and provider,
go test -tags nogui -timeout 45m ./internal/gateway/ (ok, 535s) and
./internal/provider/, which crashes in TestUnreadLoginsWriteErrorsKeepCredentials
on "close of synctest channel from outside bubble", #3632, open and not
this change. TestPluginStreamsPastTheBudgetWait, run alone, was red 2 of
3 with this change and 3 of 4 on clean dc1af8231 (connection reset by
peer, #3946). Real account, plugin side: DeepSeek-V4-Pro on Qoder recalls
a codeword its thinking before a tool call named with 0.2.42, not 0.2.41.

Broken by hand: TestCommandCodePluginReasoning with qoder and qoder-cn
added is red on the old chatReplaysReasoning (no reasoning_content).

Not tried: a Claude Code session through magpie onto Qoder end to end;
Qoder CN.
2026-10-28 04:32:30 +08:00
yetone 865df24727 gateway: a Chat stream's tool calls sent by turns are read by index, one call each
mysterious_dove (Discord, on 098ac9696): a Chat upstream that streams two
tool calls' fragments by turns (index 0, 1, 0, 1, 0, 1, the first of each
with id and name, the rest only arguments) reached Codex as six
function_call items: the first two with their names and `{}`-ish partial
arguments, four with no name, half the arguments and fresh ids.
chatDecoder started a new call at every change of index.

chatDecoder now reads fragments by tool_calls[].index (toolCall). The open
call streams as it comes; a call that starts while the open one's
arguments aren't yet whole JSON is held by its index and given whole, in
index order, at finish_reason or [DONE]. A sequential stream streams as
before; a repeated id still continues its call, a new id at the same
index still starts the next one.

Siblings: every Chat-to-X translation (Responses, Anthropic Messages,
Gemini, a whole reply via collector) reads through chatDecoder, so all
are fixed here. Checked and unchanged: chattidy's streamCallIndexes,
chat_call_ids, grok_integral, whole_stream and textcalls already key by
index or build no calls from fragments.

Tests (translate_stream_test.go): TestInterleavedToolCallsToResponses
(the exact interleaved stream: 2 function_call items, whole JSON args,
index order, one output_index and item id per item across added/delta/
done), TestInterleavedToolCallsToAnthropic (2 tool_use blocks),
TestInterleavedToolCallsWhole (2 calls), TestToolCallsNamedFirstThenArgued
(names first, then args, [DONE] with no finish_reason).

Broken by hand: with origin/main's chat.go put back, all four fail
("6 function_call items, want 2"; 6 tool_use blocks; 6 calls of fragments).

Run at this head (rebased on d157700a0): go test ./internal/gateway/ -run
'TestInterleaved|NamedFirst|ToolCall|Parallel|ChatTranslation|RepeatedToolCall'
ok; gofmt -l internal/gateway/ empty; go vet, GOOS=linux go vet -tags
nogui, GOOS=windows go vet ./internal/gateway/ ok.

Not tried: the full `go test ./internal/gateway/... -timeout 45m` before
the push: other sessions' gateway suites held the machine for 2h (load
150-200) and a second suite at once would only time out; it runs after
the push. Not tried against the reporter's real upstream; the fixture is
built from the report's description, not captured bytes.
2026-10-27 00:28:06 +08:00
yetone 43001be863 gateway: a relayed Chat body's unpaired tool calls are paired before Kimi sees them
Paidaixinbao on X: Qoder through magpie on Kimi Code, a conversation
forked at an earlier turn fails on every prompt while a new one works.
A Chat client's body to a Chat upstream was relayed as-is, and only
translated requests had their tool exchanges mended (pairToolMessages).
A forked or stopped history can hold a call with no tool answer, calls
split over two assistant messages, a user turn between a call and its
answer, or an answer to no call. Kimi turns the whole request away with
400 "an assistant message with 'tool_calls' must be followed by tool
messages responding to each 'tool_call_id'..." or "tool_call_id  is not
found". toolPairsOut now pairs such a body on the Chat relay (joining
split calls, answering the unanswered, turning an orphan answer into
user text); a paired body goes out byte for byte.

Run:
- Real Kimi Code API (kimi.com/coding/v1, 2026-10-26; the account's
  plan has lapsed, so a body past validation answers 403 and a refused
  one 400): unanswered call, split calls, user between call and answer,
  one of two answered and an orphan answer are each 400; every one of
  them after toolPairsOut is 403, past validation. A tool turn without
  reasoning_content, null content, repeated ids, out-of-order and
  double answers, prefill and a reasoning field all pass as-is, so
  they are not the cause and are left alone.
- gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -timeout 45m ./internal/gateway: ok, at this commit.
- Two fixtures held an unpaired body only by accident and are paired
  now: image_input's chat-tool case (a lone tool message) and the
  large-chat upstream golden (its last call left unanswered); the new
  large-chat hash is the same on the old code.

Broken by hand: without the toolPairsOut call all six subtests of
TestChatRelayPairsToolsForKimi go red against a fake Kimi with Kimi's
own wording; without joinSplitChatCalls the split case goes red;
reading only string content in toolAsUser turns the parts case red.

Not tried: the real Qoder app and the reporter's own forked history,
so which shape their fork holds is not proven; Qoder's "unsupported
request" text is not magpie's wording. A real Kimi model answer (the
plan has lapsed, only validation was seen). A non-Kimi Chat upstream,
though the rule is OpenAI's too and runs for every Chat relay.
2026-10-26 22:40:48 +08:00
yetone 9a888323a2 gateway: a Chat or Messages request is read for its folder and turn without its history (#3472)
A plugin's request is read for its work folder on every try
(tellWorkPlace -> readFacts -> parseIn(proto, body, true)). Only the
Responses reader had a facts mode (#3394); Chat and Messages parsed the
whole conversation, copying every assistant turn, tool call and tool
output, to learn a folder and whether the last turn was a tool's answer.
On a long conversation that history was most of what each try allocated.

readChat and readAnthropic now take facts, as readResponses does: they
decode with decodeJSONView, keep an assistant message as its role alone
and a tool result as its kind and call id, and keep the system and user
text that workPlace reads. parseChat and parseAnthropicRequest are
readChat/readAnthropic with facts off, unchanged.

Numbers (1.3 MB body, least of 3 runs, TotalAlloc):
  Chat facts 980 KB, whole parse 4.5 MB
  Messages facts 1.08 MB, whole parse 5.3 MB
Through the gateway on the plugin path (probe, 60 requests of ~938 KB,
counting the test client and fake vendor), per request:
  /v1/chat/completions 24.4 MB -> 21.2 MB
  /v1/messages         39.8 MB -> 33.7 MB
Retained heap is unchanged (~15-19 MB); this is churn, which is what the
reporter's heapSys grows from.

Tests:
- TestChatAndMessagesFactsAsTheWholeParse: facts give the same folder,
  turn and tool-answer facts as the whole parse, over the real fixtures
  (workdir/pi-1.1.0, claude-code-2.1.296, context/claude-code, the
  upstream_bodies chat/anthropic families), a large conversation and
  hand cases (model and tool both spoke; answered then a tool; answered
  then nothing; a tool's result alone).
- TestChatAndMessagesFactsLeaveTheHistory: facts allocate under a third
  of the whole parse.
- TestReadersOfAHeldBodyParseItOnce's last check now counts readFacts
  calls through the factsParsed hook instead of allocation, which the
  cheaper facts no longer show.
Broken by hand, each red then green: dropping the assistant message in
Chat facts; keeping only role-less messages in Messages facts; facts off
in parseIn (the allocation test); a held-facts lookup matching any entry.

Run at this head (base origin/main 1bb8143b3):
- go test ./internal/gateway -skip '^TestZZ' -count=1 -timeout 45m: ok
  (401s)
- go test ./internal/plugin ./internal/provider (provider with
  -skip TestUnreadLoginsWriteErrorsKeepCredentials, #3632): ok, run
  with the next commit in the tree
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui for
  internal/gateway, internal/plugin, internal/provider: clean
- Real accounts in a sandbox HOME (only the deepseek provider and the
  Command Code plugin copied): /v1/messages and /v1/chat/completions
  multi-turn requests with a working-directory line, a tool call and a
  tool result, to deepseek/deepseek-flash and
  commandcode-plan/claude-haiku-5-5: all 200, answers right (the plugin
  quoted the tool's "file a: 你好" back exactly).
Not tried: a real Claude Code or Codex session against this build.

Rebased onto origin/main 6e6aba51c (a providers key change) and run again at the pushed head: go build -tags nogui ./... ok; go test ./internal/provider (same skip) ok 115s, ./internal/plugin ok 110s, ./internal/gateway -run 'Facts|Parse|Plugin|WorkPlace|Fetch' ok 50s. The full gateway run above was at 1bb8143b3.
2026-10-26 21:04:48 +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
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
yetoneandggbdpq 08400f4ebd gateway: a byte cap after the stream has begun says request_too_large, so Pi compacts (#2533)
A vendor's 413 that came after the stream's headers had gone out (a
keepalive sent while the vendor was quiet) reached Pi as a stream error
of type api_error saying "413 Request Entity Too Large". Pi compacts only
when the error's text says request_too_large (overflow.ts), so the turn
stopped. A 413 before the headers was already typed request_too_large
(writeErrorSaid, 97f264c7).

streamError, which every failure in a stream already begun goes through
(failTo and holdWriter's), appends "(request_too_large)" to the text of a
413 that isn't a context overflow and doesn't say it already; the Chat
and Anthropic encoders type that event request_too_large. Gemini keeps
its own status shape; an overflow stays context_length_exceeded.

Review change (on top of ggbdpq's 8a278645): the test matched
request_too_large anywhere in the body, so Chat's new type alone passed
it: with the text append taken out by hand it stayed green. It now reads
the error event's message (what Pi reads) and type. The new
TestStreamErrorByteCapInEveryShape runs streamError for Chat, Anthropic,
Responses and Gemini, and for a 413 that says the prompt is too long.

Run:
- With gateway.go, chat.go and anthropic.go put back: both tests FAIL.
  With only the text append taken out: both FAIL. With only Anthropic's
  type taken out: TestStreamErrorByteCapInEveryShape FAILs ("anthropic …
  want "type":"request_too_large""). Restored: ok.
- TestBodyRejectionErrorShapes, TestStreamErrorSaysItPasses,
  TestGroupLastFailureInStreamSaysItPasses: ok.
- Full suite, go test -tags nogui -timeout 45m ./... (set -o pipefail,
  sandbox HOME, load ~350) at 0224e826f (these four commits on
  ebf3f48f7) plus #2545's patch: every package ok except internal/agent,
  whose one red (TestRekeyGivesWSLAgentTheSharingKey) is #2545's, which
  was dropped (problems posted on #2545). internal/agent alone at
  0224e826f: ok. Rebased on dccfefdf7 (#2635, internal/library only):
  build, vet, internal/library ok. gofmt -l clean; go vet darwin (gui),
  GOOS=linux and GOOS=windows -tags nogui: clean. GUI (i18n-keys,
  gui-de/ja/zh-TW, import-*, key-import, login-import): all pass except
  login-import's Chromium case, which fails the same alone on origin/main
  ebf3f48f7 (#1307, output posted there).
Not tried: a real nginx 413 or a real Pi compacting after it.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-17 11:54:55 +08:00
yetone d4a1b9baa7 gateway: a </think> inside code no longer ends a reply's thinking; a plugin's text keeps its <think> (#2634)
Kane-Kuroneko's Qoder replies through Codex began mid-sentence at a
backtick: the Chat decoder took any reply whose text began with <think>
as inline thinking up to the first literal </think>, even one inside an
inline-code example ("使用 `<think>...</think>` 标签"), for every Chat
upstream.

- The close is looked for only outside Markdown code (mdCode in
  chat.go): an inline span (taken to end with its line, so a stray
  backtick can't swallow the answer) or a fenced block. Backtick runs and
  a close split across chunks are held, as the tag tail was.
- A plugin's Chat reply is read as OpenCode reads it, its text as it came
  (decoderFor, used by streamTranslated, the continuation path and the
  search path): the plugin knows its vendor and gives reasoning apart.
  Qoder's plugin sends reasoning_content and has no splitter of its own.
- A reply that already gave thinking in reasoning_content/reasoning has
  no leading-tag lookup in its text.
- The line breaks after a close are left out however they're chunked:
  one character a delta used to leave "\n" at the head of the answer.
- Codex titles/descriptions/predictions (codex_titles.go) strip a leading
  block with the same close rule (afterThought), the sibling cut.
MiniMax (2ab69d0f) and Gemini's <thought> keep working: their existing
tests pass unchanged.

Tests use the reporter's literal bytes, whole, a character a delta and a
byte a delta: TestChatThinkCloseInCode, TestThinkExampleReachesClientsWhole
(Codex /v1/responses and Claude Code /v1/messages against a fake Chat
upstream), TestChatThinkTagAfterReasoningField, TestPluginThinkTagIsText
(the fake plugin as qoder, through Bun, with #2634's historical
boundary), TestAfterThoughtCloseInCode.

Broken by hand, each watched go red: close matched inside code ->
TestChatThinkCloseInCode, TestThinkExampleReachesClientsWhole,
TestAfterThoughtCloseInCode; reasoning-field rule off ->
TestChatThinkTagAfterReasoningField; plugin scope off ->
TestPluginThinkTagIsText; newline trim off -> TestChatThinkCloseInCode,
TestThinkExampleReachesClientsWhole, plus the existing MiniMax tests.

Run: gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
go vet -tags nogui ./... clean; go test -timeout 45m ./... on this change plus the next
commit's library edit (the worktree held both while it ran): 64
packages ok, internal/gateway ok (524s), internal/library ok; internal/gui's
real-window darwin tests were killed at their 30s bar under a load
average of ~295, and internal/provider failed to link on a GOCACHE file
another run trimmed. Rerun alone: internal/provider ok (206s),
internal/gui ok (165s). No GUI files touched. Not tried
against real Qoder or MiniMax accounts.

Not changed: the plugins repo's think-tags middleware
(packages/think-tags) also ends a block at the first indexOf("</think>")
when a user turns it on.
2026-10-17 08:49:42 +08:00
yetoneandggbdpq ed0335f75c gateway: an assistant turn cut off before it said anything is left out of what a Chat upstream is sent (#2599)
timonwong (#2599): after the user stops a reply while the model is still
thinking, the agent keeps a turn with no text and no calls and sends it
again on every later turn. Translated (buildChat) or relayed, it reached
the Chat upstream as {"role":"assistant","content":""} (reasoning_content
alone, on DeepSeek), and DeepSeek and Kimi turned every request of the
conversation away: "Invalid assistant message: content or tool_calls must
be set".

One rule, withoutSilentAssistants (chat.go), runs on both Chat routes:
buildChat before pairToolMessages (Claude Code, Codex and Gemini clients,
and the plugins fed by buildChat), and silentAssistantsOut in passthrough
next to developerAsSystem (a Chat client's own body). An assistant
message with no content or only blank text parts, and no tool_calls or
function_call, is left out; the user messages it stood between join into
one (texts with a blank line, else their parts in order), so no two user
messages stand in a row. A prefill (prefix, partial, a Resume), a legacy
function_call, a refusal and an audio reply stay. A relayed body without
such a turn goes byte for byte. TestChatThinkingOnlyAssistantKeptOutside-
Exchange pinned the old pass-through; it now expects the joined message.

Built on ggbdpq's patch (cb438ebb on their fork) and its fake upstream,
written again because the review found it missed shapes the issue names:
- after a tool result it kept the empty turn ("a strict template wants the
  reply behind its tool message"), so the interruption mid tool loop still
  sent content "" and still got the 400. tool then user is what any agent
  sends when the user writes after a tool result; it is now left out.
- the relay dropped an assistant with a legacy function_call or a refusal
  and empty content, and a client's own prefix/partial prefill;
  kept blank text-part arrays (still refused); joined only string users;
  re-marshalled with HTML escaping.
- its Resume check compared a joinSplitCalls turn index with
  len(r.Messages)-1.

Verified (sandbox HOME, pinned caches, go1.26.8 darwin/arm64, base
origin/main 72d6103e2):
- The fake upstream refuses with the issue's literal 400 body any
  assistant without content or tool_calls, plus DeepSeek's #1462/#1822
  reasoning rule. On main's product code 18 subtests of the new tests go
  red with that 400 (Claude Code: thinking, redacted, empty text,
  thinking+empty text, [], "", after a tool result; Codex: lone reasoning,
  empty output_text, no content; Gemini thought-only; relay: "", null, no
  content, blank parts, after a tool result; relay keeps-what-speaks), and
  TestChatThinkingOnlyAssistantLeftOutOutsideExchange. With ggbdpq's
  product files instead, after-a-tool-result (both routes), blank parts
  and TestChatRelaySilentAssistantsOnly are red. With this change all
  pass; TestChatResumeEmptyPrefillKept is a guard, green before and after.
- gofmt -l: clean. go vet -tags nogui ./... for darwin, linux, windows:
  ok. Full suite with both this and the #2575 test change in the tree,
  set -o pipefail; go test -tags nogui -timeout 45m ./... : 66 packages
  ok, none failed (internal/gateway 825s, internal/provider 266s).
- Rebased onto origin/main ec6454395 (claude_subscription, ir.go):
  gofmt clean, vet darwin/linux/windows on internal/gateway and
  internal/settings ok; go test -tags nogui -timeout 45m
  ./internal/gateway ./internal/settings: ok (gateway 668s).
- Not tried against real DeepSeek or Kimi (the fake answers with the
  issue's bytes). Gemini and Responses upstreams are not changed; the
  Messages build already drops an empty turn and merges same-role
  neighbours (anthropicBody's push).

Co-authored-by: ggbdpq <67929842+ggbdpq@users.noreply.github.com>
2026-10-17 05:15:16 +08:00
yetone 72d6103e28 gateway: a Chat tool in MCP's or another API's shape goes upstream as a Chat function tool (#2622)
jinyue806 (#2622): ZCode sends its tools on /v1/chat/completions in MCP's
shape, {"name","description","inputSchema"}, with no type and no function
object. magpie relayed them as they came, and SenseNova turned every request
with tools away ("field Tools[0].Type invalid, should be set"; a flat
{"type":"function","name":…} got "function cannot be empty"). A missing
type is invalid Chat Completions for every upstream, not SenseNova only, and
the translated routes were broken too: parseChat read no name from such a
tool, so Messages and Responses upstreams were offered a tool named "".

shapeChatTools puts a tool with its name at the top (no type, or type
"function" without a function object) into {"type":"function","function":
{name, description, parameters, strict}}, parameters taken from
parameters, inputSchema or input_schema; other fields stay beside it. It
runs right after liftMessageTools at the same two choke points: handle, for
every Chat body before routing (relay, schema fixers, redaction, plugins),
and parseChat, for a body that never came through handle. A tool that has
its function, a hosted tool (any other type) and one with no name are left
alone, and a request with nothing to shape is relayed byte for byte.

Verified:
- TestChatToolInAnotherShapeIsShaped sends the reporter's curl body with
  each of the four tool shapes from the report through the Chat relay,
  Messages and Responses. With shapeChatTools made a no-op by hand all 12
  subtests FAIL: relayed as {"name":"f","inputSchema":{…}} as it came, and
  translated as {"name":"",…}. TestShapeChatToolsLeavesChatShape (byte for
  byte on Chat-shaped/hosted/nameless tools; strict and cache_control kept)
  FAILs on the same break. Both pass restored.
- gofmt -l: clean. go vet -tags nogui ./... for darwin, linux, windows: ok.
- Full suite at 81313b912 + this change, sandbox HOME, pinned caches:
  set -o pipefail; go test -tags nogui -timeout 45m ./... : 59 packages ok
  (internal/gateway 1134s, internal/provider 548s). 7 packages failed only
  on "no space left on device" while the disk filled mid-run (cli
  TestModelDisableCmd, library TestAgentMCPFiles, sessions
  TestCodexTitleEvidenceBound, settings TestSaveConcurrent, and gui, tui,
  usage which printed PASS but couldn't write testlog.txt). Rerun once
  space was back (30G free): cli, gui, library, sessions, settings, tui,
  usage all ok.
- Rebased onto origin/main a69cd0707 (#2611's chat call ids, chattidy):
  gofmt clean, vet darwin/linux/windows on internal/gateway ok,
  go test -tags nogui -timeout 45m ./internal/gateway ./internal/source:
  ok (gateway 510s). No other package changed between the two bases.
- Not tried against the real SenseNova (no key here); the reporter's own
  table shows {"type":"function","function":{…}} answered 200.

The "inference request is invalid ... reason=unknown retryable=false" text
in the report is not magpie's (no such string in the repo); it is the
client's wrapper of the upstream error, so nothing changed there.
2026-10-17 04:07:25 +08:00
yetone 7170b5d8bd usage: the plan credits a reply says it cost are summed by model, agent and session (#2512)
wwcraft_ on Discord asked for the WorkBuddy credits spent on the Usage
page, by model, agent and session. WorkBuddy's chat stream ends with
usage.credit, the per-request figure its own app shows as "Credits
Consumed". The built-in and the moved plugin both hand that chunk to the
gateway's chat decoder (the plugin's renamed()/kept() pass usage on as it
came), so cUsage reads `credit` into Usage.Credits and the three record
sites keep it on the row. A reply that says nothing has no credits, not 0.

- usage: Record.Credits; Totals/Via sum Credits and count Credited; the
  packed row keeps it under its own flag bit (4096, in TestRowFlagsApart);
  the ledger CSV gains a trailing "credits" column.
- GUI: the Usage ranking's line says "0.7 credits" (积分, 積分,
  クレジット, Credits) beside the cost, its title how many requests said
  it; the Sessions page's Routed line says it per route. TUI usage page
  and `magpie usage` tables say it muted on the same line. No new layout.

Real replies on workbuddy-ai, 10-16: gemini-3.5-flash "credit":0.01;
deepseek-v4.1-flash, minimax-m3, kimi-k2.6 "credit":0; glm-5.3-flash
refused (14003). The tests use those bytes.

Run (at b07b518e7 on origin/main 63be47717, with #2511's commit):
- gofmt -l clean; go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean; go build: ok.
- go test -timeout 45m ./... with pipefail, sandbox HOME: 63 packages ok,
  usage (200s), cli, tui, gui among them; agent, gateway and library timed
  out at load ~270 (see the #2511 commit); library ok alone, agent and
  gateway ok with -timeout 150m: agent ok (5529s); gateway red only in TestIntentClassifierGroup (#1813), TestMaxRPMWaitsForRoomInTheMinute (#1791) and TestMaxRPMGroupPrefersMemberWithRoom (#2520), known timing reds under load, each passing alone here -count=3 (19s).
- New: TestPlanCreditsReachTheLedger (chat stream, whole reply,
  translated /v1/messages, free 0, none), TestPlanCreditsSummed,
  TestPlanCreditsPacked, TestFormatCredits, TestUsageSaysCredits, and
  plan-credits.test.cjs (en, zh, zh-TW, ja, de; Chromium and WebKit;
  420px fit) 12/12.
- Broken by hand: dropping Credits at the record site turns the gateway
  test red; skipping it in unpack turns the usage tests red; dropping the
  ranking's ledCredits turns plan-credits red in every language.
- GUI reds elsewhere: see the #2511 commit (#2536, #2552, a
  provider-detect-draft load timeout that passes 3/3 alone).
- Rebased onto origin/main ba132d68b (13 commits; chat.go, gateway.go, app.js, i18n.js among theirs): gofmt and go vet ./internal/... clean; Credits/DeepSeek/Balance/Ledger/RowFlags tests in usage, gateway, provider, cli, tui ok; plan-credits 12/12, balance-parts 4/4, i18n-keys 3/3 in both engines.
2026-10-16 20:11:34 +08:00
yetone 686e8a93ac gateway: a moved subscription's failed tool result reaches its plugin marked
A moved Devin or Qoder got a failed tool result as plain text: the
built-in wrote "Error: " before it (devin.go, qoder.go), and buildChat sent
no mark at all. The chat request to those plugins now says it in the text
(failedAsText), and Cursor's carries is_error, which cursor 0.2.18 reads as
the built-in told Cursor isError. buildHost names a moved subscription by
its plugin, so the request is built for the plugin's protocol, not the
built-in's.

TestPluginToolFailureSaid and TestMovedBuildHostIsPlugin go red without
the change.

Run at 63be47717 with this batch: go test -tags nogui ./... -count=1 -timeout 90m, 66 packages ok, no FAIL (load ~250). gofmt -l clean; GOOS=linux and GOOS=windows go vet of provider, gateway and plugin pass.
2026-10-16 19:37:59 +08:00
yetone e243937ca3 gateway: a fast pick can be sent as Ultrafast where the account offers it (#1954)
zhenghaowen0967 asked for an agent's fast pick of a ChatGPT model to go as
Codex's Ultrafast without the client asking for it. settings.UltraPicks
holds the agent's fast picks that are set to Ultrafast; each one is in
FastPicks too.

- The gateway marks those candidates `ultra` in fastPick.
  - On Chat and Responses, a try sends service_tier "ultrafast".
  - From Messages, a try carries withUltra to forwardTranslated, which
    sets Request.Ultrafast for the ChatGPT backend.
  - In every case, the #1784 check decides the account. One whose list
    doesn't offer Ultrafast goes after a mate that does (tierMate). With
    no mate left, it is sent priority.
  - That check now covers Chat as well as Responses.
- Sibling fix: chat.go dropped a Chat client's own service_tier
  "ultrafast" (Fast was false, Ultrafast unset). It now parses as
  Responses does.
- provider: SetFastTier (""/priority/ultrafast) behind SetFastPick.
  CanUltra and UltraModels say whether one of Codex's accounts lists
  Ultrafast on the model. UltraPicks follow a provider rename
  (renameModelPrefs) and survive a GUI settings save.
- GUI: an option gets ultraOk/ultra. Where ultraOk is set, the bolt in
  the picker steps usual -> Fast -> Ultrafast -> usual, as a camera's
  flash button steps its modes. Ultrafast shows two overlapped bolts, in
  the row and after the field's model. Tooltips and the status line are
  in en, zh, zh-TW, ja and de. POST /api/agent-fast takes `ultra`.
- No `:ultrafast` suffix for routing groups yet.

Tests, each broken by hand and seen red:
- TestUltraPickSentUltrafast covers omp/Responses with no tier asked
  (acct-pro:ultrafast), the Pro account out (then acct-plus:priority),
  another agent unchanged, opencode/Chat and claude/Messages picks, a
  Chat client's own ultrafast, and switching back to Fast or off.
  - Red with ultra forced false (4 cases).
  - Red without withUltra (claude went priority).
  - Red without the chat.go parse (2 cases).
- TestSetFastPick: red without UltraPicks in renameModelPrefs.
- TestSettingsSaveKeepsWhatItDoesNotSend: red without the api.go carry.
- fast-ultra.test.cjs (en zh ja de, window and 440px panel): red (9/9)
  without the Ultrafast step.

Run (vet, gofmt, GUI and full suite at base 8b84dc902; the reruns
below at a rebase onto 6b3ee5a03 and then onto 63be47717 origin/main):
- gofmt -l: clean.
- go vet -tags nogui ./... for darwin, linux and windows: clean.
- GUI, chromium + webkit: fast-ultra, fast-pick, group-member-fast,
  i18n-keys, model-pick and 14 other agent-model/picker files. 197/197
  pass.
- Full suite: set -o pipefail; go test -timeout 45m ./... (sandbox
  HOME, macOS, 3 other sessions' suites running at the same time):
  every package ok except two.
  - internal/gateway: TestMaxRPMGroupPrefersMemberWithRoom hit its fixed
    1s bar (1.126s) under load. It passes 5/5 alone (-count=5). Filed
    as #2520.
  - internal/gui: TestPanelJoinsFullScreenSpaces, red on macOS 26.2 on
    main already, filed as #2450.
- Rerun of internal/gateway and internal/library after the rebase onto
  6b3ee5a03 (both packages changed upstream), -timeout 60m, load
  average ~290: library ok. gateway hit the 60m timeout (the test
  running, TestPauseByFolder, was 13s in) and
  TestQueueRefusalIsInTheUsageLedger saw b's 1s queue timeout as a
  second 429. Filed as #2541. TestQueueRefusalIsInTheUsageLedger,
  TestPauseByFolder and TestUltraPickSentUltrafast, -count=5 at this
  head: ok.
- At the 63be47717 rebase: gofmt clean; vet darwin/linux/windows clean.
  internal/provider ok, internal/settings ok. internal/agent hit the
  45m timeout under load ~295 (in TestCursorLocalEffort, at 0s), so
  this is not a green for that package. Its -run
  "Fast|Option|Models|Picker|Cursor|Codex" subset, run through the
  shared 3-slot queue, was ok in 794s. The whole package is left to
  CI's Test run.

Not tried: a real Pro account's Ultrafast. The fake ChatGPT backend's
model lists offer it on one account only.
2026-10-16 19:14:52 +08:00
yetone afb0ff7720 gateway: a tool Pi adds in a message of its own joins the request's tools on every route, once by name (#2322, deephbz)
Pi 1.2.0 with supportsMidConvoToolAdditions sends a tool it adds
mid-conversation as {"role":"system","tools":[...]} with no content and
keeps top-level tools as they were. parseChat read only top-level tools
and the Chat relay sent the message on as it came, so the tool could be
called on no route, and the tools-only message became an empty part of
the system text ("</cwd>\n\n\n\nUpdated ...").

liftMessageTools (message_tools.go) moves message tools into the
request's tools. handle does it for every Chat body, before serveAgent,
so the Chat relay, schema fixers, redaction, the prompt shown and
routing all see them; parseChat does it too for a body that never came
through handle. Each tool joins once by name and the first definition
wins (top-level, then the earliest message's), as liftAdditionalTools
and a tool_addition in withoutDeferredTools do. A system or developer
message that carried only tools is left out; one with content keeps
its place without tools. Message order is unchanged: the in-place
system message / inline-tools beta part of #2322 is not in this commit.
6312af989 (#2338, inline-only tool_addition joins tools) is not on
origin/main a1f7b8c13, so this builds on neither; the rule matches it.

Tests, from deephbz's literal Pi 1.2.0 request (last comment on #2322):
TestPiAddedToolReachesEveryRoute (Chat relayed to an OpenAI-compatible
upstream, Messages, Responses, Gemini, Codex), TestPiAddedToolOffered-
ToClaudeCode (the Claude subscription bridge's MCP tools.json, a fake
claude; skipped on Windows), TestMessageToolsFirstDefinitionWins.

Run (sandbox HOME, -tags nogui -p 1):
- go test ./internal/gateway -run 'TestPiAddedTool|TestMessageTools|
  Chat|Messages|AdditionalTools|Lite|Deferred|ExtraBody|Gemini|
  CodexAccessPrograms|Developer|ThinkingEffort|Kimi|DeepSeek|ClaudeRun|
  ClaudeSubscription|Strict|Prompt' -count=1: ok (75.8s)
- broken by hand: liftMessageTools a no-op -> every route subtest, the
  bridge test and FirstDefinitionWins red (tools [lookup_pantry], empty
  system relayed, "\n\n\n\n" in the system text); only handle's lift
  removed -> chat relayed red; only parseChat's lift removed -> the
  bridge test and FirstDefinitionWins red.
- gofmt -l internal/gateway: clean; go vet -tags nogui ./internal/gateway
  for GOOS=darwin, linux, windows: clean.
Not run: other packages, the full suite. Not tried with a real Pi or a
real upstream.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +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
yetone cb2335dc41 gateway: Gemini's <thought> tags stay out of the answer when only the opening chunk is marked (#2098)
Gemini 4 Argon over AI Studio's Chat API marks the chunk that opens
<thought> as a thought (extra_content.google.thought) but not the one
that closes it and goes on into the answer. The decoder took a marked
chunk whole as reasoning, past the tag parser, so the reasoning began
"<thought>" and the next, unmarked chunk reached Codex's answer as
"</thought>接下来我将调用 probe…", streamed and in response.completed.

A marked chunk now goes through the same in-band tag parser as text
when it carries a tag, or could be the start of one, with its text kept
as thought: the open tag is dropped, the close in the unmarked chunk
after it ends the thought, and the answer starts clean. A marked chunk
with no tag in sight is thought as before; an answer that only quotes a
tag later keeps it.

Run:
- TestGeminiMarkedThoughtTagLeftOut: the reporter's /v1/responses body
  and the stream deltas as #2098 captured them; output_text is the
  answer with no tag, reasoning is "[REASONING CONTENT REDACTED]", the
  completed output has the probe call with {"number":42}. FAILs on the
  old chat.go ("</thought>接下来…" in the stream, "<thought>[REASONING…"
  as reasoning).
- TestChatMarkedThoughtTags: tags split across chunks, marked and not,
  no tags, quoted tags. Also TestChatThoughtTags and TestGeminiThoughts*.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
  internal/gateway; go test -tags nogui ./internal/gateway/.

Not tried: a real Gemini 4 Argon stream (no AI Studio key here).
2026-10-14 15:34:16 +08:00
geoqiao 3a9d73c5c6 gateway: a plugin's deferred usage is billed with its step, never told as the prompt
The Cursor plugin collects a tool step's late usage event with the
conversation's next step. It used to add it to that step's prompt_tokens,
which agents read as how full their context is: pi saw 366940 tokens
(181270 + 185670) on a 300k window where 185670 were in use, and compacted.
The plugin now reports it apart, as usage.magpie_deferred (yetone/magpie#1053).

The gateway parses the field into Usage.Deferred and adds it only where it
bills: the usage records (6 sites in serve), the OTel attempt span and route
pricing, as a tier before the request's own, so promptCounted still reads the
request's own prompt. What a client is told (Usage.chat, the Anthropic
encoding) stays the request's own. A reply without the field is handled as
before. docs/subsystems/provider-plugins.md describes the field.

Verified: go test -tags nogui ./... (50 packages ok, sandbox HOME, caches
pinned); gofmt; go vet on darwin, linux (nogui) and windows; go build on the
same three. The new tests were broken by hand and each went red: billed()
ignoring Deferred, cUsage dropping the field, routeUsage without the tier,
Usage.add forgetting it, the decoder ignoring a usage with only a deferred
part, the usage records and the OTel span not using billed(). Not tried: a
real Cursor account on this checkout; the plugin side was run against real
Cursor (composer-2.5, forced late events), where the deferred totals matched
the dashboard's events token for token.

Picked from geoqiao/magpie cursor-deferred-usage (595d6384c), as PRs here
are collaborators-only. Rebased over the service-tier logging (#1784),
keeping its TierAsked/TierSent/TierServed beside billed() at the three
usage.Record sites, and Usage's Tier beside Deferred. Run on this tree:
go test -tags nogui -timeout 40m ./internal/gateway and ./internal/provider
(sandbox HOME); gofmt -l; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows. billed() forced to ignore Deferred: 3 tests and 5 subtests
of deferred_usage_test.go go red.
2026-10-13 14:50:48 +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
yetone a64b3a8d46 plugin: a pi provider's message_start tells the prompt's usage pi's start named, so Claude Code's context meter isn't 0 until the turn ends (#1887)
What: pi.js wrote message_start with usageOf() and no argument, so every
field was 0 until message_delta. Claude Code's context meter reads the
usage the assistant message has so far, and a turn interrupted before
message_delta was stored with 0. message_start now carries the vendor's
prompt (input, cache read, cache write) and the output pi's start named
(startUsage): from pi's start event's partial.usage, as the issue
describes, or, as pi-ai's anthropic-messages pushes start before it reads
the vendor's message_start (start's usage is still 0 then), from the
partial message the events after it share. That message is pi's own,
still being written (by the time magpie reads it pi may have pushed the
whole turn), so only its prompt is taken from it, never its output.
message_delta is unchanged: the whole turn's cumulative usage from done.

Siblings, the gateway's translators to Anthropic's stream:
- Gemini / Code Assist (codeassist.go): usageMetadata rides on the first
  chunk, but KStart was emitted before reading it. KStart now carries the
  prompt (input, cached); output stays 0 there.
- Chat Completions (chat.go): most streams count only at their end, so
  nothing to tell; a stream that counts on its first chunk now has its
  prompt on KStart.
- Responses: response.created has no usage. Anthropic-to-Anthropic and the
  Claude subscription already carry it. Cursor, Kiro, Devin, Qoder,
  Command Code send KStart before any usage is known.

Ledger: no double count. The usage sniffer and the collector both take
each field's latest non-zero value (Usage.add replaces, it doesn't sum),
and continuation/search take a try's KStart usage as its own (this =
ev.Usage) and KUsage replaces it. message_delta's input equals
message_start's, which Anthropic's clients also take as the same count.

Run (Go 1.26.8, darwin):
- TestPiPackage with a fake pi stream as the issue's (start with
  partial.usage input 11, cache 3/2, output 0, text, done with output 7):
  message_start 11/3/2/0, message_delta 11/3/2/7; and pi-ai's order
  ("late": start with zero usage, then the shared message counted):
  message_start 11/3/2/0. Red with message_start back on usageOf(), and
  the late case red when only start's usage is read.
- TestPromptUsageOnMessageStart (Gemini, chat counting per chunk, chat
  counting at the end): red with codeassist.go and chat.go stashed.
- go test ./internal/plugin and ./internal/gateway in full (-timeout 28m;
  the default 10m timed out under load average ~20). The disk filled
  during the run (3.7G free, not this change's): every failure was
  ENOSPC, and each of them (37 gateway, TestFakePlugin) passed on rerun.
- gofmt -l; go vet for darwin, linux and windows on both packages.
Not tried against a real pi vendor or Claude Code's meter.

Reported-by: guoqchen1001
2026-10-13 10:29:31 +08:00
TryWorldandTryWorld 184f9184d3 gateway: a Chat turn's thinking is read in every spelling the client … (#1075)
* gateway: a Chat turn's thinking is read in every spelling the client sends it back in

A client sends the previous assistant turn's thinking back in reasoning_content (DeepSeek's, which OpenCode and most clients send), reasoning (OpenRouter's) or reasoning_details (OpenRouter's structured one). parseChat read only reasoning_content, so a request translated to a non-Chat upstream lost the thinking of every turn sent another way and the model went on without its own reasoning, which a tool-calling session shows from its second turn on. chattidy's passthrough has read all three since mistralThinking (#494); the parse layer never got the same reader.

The assistant branch now reads the thinking through reasoningText, messageReasoning's own reader, in the order the passthrough keeps it: reasoning_content, else reasoning, else reasoning_details' text.

TestParseChatReadsEveryReasoningSpelling (a tool-calling turn per spelling) and TestParseChatTakesTheFirstReasoningSpellingSent fail without the change ("the assistant turn's parts: [{Kind:tool_call ...}]"). go vet -tags nogui ./internal/gateway/..., builds for windows, darwin and linux, and the package's chat/reasoning/thinking tests pass.

* docs: the Chat parse layer reads the thinking's spellings too

The change reads a Chat turn's thinking through messageReasoning and
reasoningText, so parseChat takes the same three spellings the
passthrough has taken since mistralThinking (#494). AGENTS.md asks for the
owning reference to be updated in the same PR, and gateway-routing.md said
nothing of it: its reasoning bullets are about holding a reply's own
reasoning for a failover and about what a translated Responses reply gives
Codex, not about what a client sends back.

A bullet beside the held-reasoning one now records the spellings, the
order they are read in, and the gap that was there: the parse layer read
reasoning_content alone, so a tool-calling session whose client spelled it
another way went on without the model's own reasoning.

---------

Co-authored-by: TryWorld <TryWorld2026@users.noreply.github.com>
2026-10-13 09:41:46 +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 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
wei 67c6df418f gateway: Gemini turning away any thinking level, at once or passed through, is remembered for that model and level, and no longer stops a provider's thoughts
The commit before last tells Google's 400 for minimal apart from
thinking_config turned away. It left three ways for a level refusal to
still mark the provider unfit for thinking_config, or to reach the client:

  * Only minimal was told apart. Gemini 3 turns away any level a model
    hasn't, in the same words (AI Studio's "Thinking level MINIMAL is not
    supported for this model. Please retry with other thinking level."
    for gemini-3.8-flash). Any other level's 400 names thinking, matched
    refusesThinkingConfig, and the provider was marked unfit for
    thinking_config: no model on it was asked for its thoughts again
    until magpie restarted.
  * The check ran only while the model wasn't yet marked as refusing
    reasoning off. Claude Code sends its turn, a title and the auto mode
    classifier at once. A second 400 for minimal that arrived after the
    first had marked the model matched refusesThinkingConfig, and the
    provider lost its thoughts the same way.
  * Passed through, a Chat client's own reasoning_effort minimal went to
    gemini-3.8-flash as sent, and AI Studio's 400 went back to the client
    every time. The passthrough asked again only when the error listed the
    levels (effortLevelsNamed, Command Code's), and didn't remember that
    either.

Now:

  * geminiRefusedLevel reads the level from Google's 400, in AI Studio's
    words, Vertex AI's ("Thinking level is unsupported:
    THINKING_LEVEL_MINIMAL") and generateContent's ("thinking_level
    MINIMAL is not supported by this model"). forwardTranslated marks that
    level refused for the model (levelRefused) and asks again at the
    nearest level the model has left, still for its thoughts, and at that
    level from then on. geminiLevels gives the levels left: the model's
    own, or Gemini 3's where they aren't known or none of its own is left.
    A level turned away a second time in one request, with none left,
    goes back to the client as it came. Such a 400 never reaches
    refusesThinkingConfig.
  * The passthrough asks a none or minimal that Gemini turns away again at
    the model's lowest level (onEffort), and from then on sends that level
    at the lowest up front (turnedAway). The mark is per level. AI Studio
    takes none from gemini-3.8-flash, so none still goes as sent after
    minimal was refused. A refusal that lists the levels marks reasoning
    off as a whole (offRefused), as the translated route already did,
    unless it lists the other off level among those taken
    (otherOffNamed: OpenAI's "'minimal' is not supported with the
    'gpt-5.1' model. Supported values are: 'none', 'low', 'medium', and
    'high'."), which marks only the level refused. It is asked again at
    onEffort rather than a fixed low.
  * Both routes read and write the same marks. A refusal on one holds for
    the other.

Tests, with what the commit before this one (b9fe82b9) gives:

  * TestGeminiRefusedLevel: each of the three wordings gives its level.
    Gemini's fields turned away, a level named but not turned away
    (made up), Command Code's list of levels and an OpenAI unsupported
    value give none. (The function is new.)
  * TestGeminiThinkingLevelRefused/medium: gemini-3-pro-image-preview
    turning away medium is asked again at high with its thoughts, and at
    high at once the next turn. gemini-3.8-flash on the same provider still
    goes at medium. There: "gemini-3-pro-image-preview: the thoughts
    weren't asked for".
  * TestGeminiThinkingLevelRefused/no_level_left: a model turning away
    every level is asked at each once (minimal twice), and the client gets
    Google's 400. The provider's other model still gets its thoughts.
    There: "200 at [low ]", the turn asked again without the field.
  * TestGeminiMinimalRefusedTwiceAtOnce: two reasoning-off turns at once
    are both turned away at minimal. Each is asked again at low, and the
    next thinking turn still asks for the thoughts. There: "reasoning off
    went at [ low minimal minimal]".
  * TestPassthroughGeminiMinimalRefused: a Chat client's minimal to
    gemini-3.8-flash goes [minimal low], then [low], and none [none]. Claude
    Code's reasoning off then goes at [low]. gemini-3.7-flash, turned away
    at minimal by Claude Code's reasoning off, has a Chat client's minimal
    go at [low]. gemini-3.5-flash, which takes minimal, has it go as sent.
    There: "gemini-3.8-flash at "minimal": 400 at [minimal]".
  * TestPassthroughEffortNoneRefused: when Command Code refuses none, the
    second turn goes at low in one request. There: "turn 2: ... after 2
    calls".
  * TestPassthroughMinimalRefusedNoneTaken: on Chat and Responses,
    OpenAI's refusal of minimal has minimal go at low, in one request from
    the second turn, and none still go as sent. There: "chat turn 2 at
    minimal: ... after 2 calls". Marking reasoning off as a whole for it
    fails with "chat turn 3 at none: ... last sent ... low".
  * TestGeminiThinkingOffAtItsLowest also runs AI Studio's wording. It
    shares geminiUpstream with the tests above.

Mutations of the change were each caught by these tests:

  * dropping the second-refusal guard, or the fallback to Gemini 3's
    levels;
  * dropping the refit of an effort;
  * dropping the passthrough's up-front step, its mark, or its Gemini
    match;
  * marking reasoning off as a whole for a Gemini refusal, on either
    route;
  * narrowing the pattern to one vendor's wording, or loosening it to
    any level after "thinking level", lazily or not;
  * checking refusesThinkingConfig first;
  * turnedAway ignoring offRefused.

Verified on b9fe82b9 with a temporary HOME. gofmt -l, go vet ./...,
go build, GOOS=linux go build -tags nogui and GOOS=windows go build pass.
go test -tags nogui ./... passes, and so does -race -count=20 on the tests
above.

Not tried live. The AI Studio project's prepayment credits were depleted
(402), so the calls never reached the model. The wording for minimal is
AI Studio's, as observed on gemini-3.8-flash. Other levels are taken to be
refused in the same words.
2026-10-10 17:54:54 +08:00
yetone ea84c99c78 gateway: a DeepSeek model's tool call the client kept no thinking for goes with reasoning_content, so DeepSeek no longer turns the request away (#1462, Clear8Heart)
DeepSeek's Chat API in thinking mode refuses a whole request with 400
"The `reasoning_content` in the thinking mode must be passed back to the
API" when an assistant tool-call message since the user's last message
comes back without reasoning_content. OpenCode (and any client that
continues a turn another model made, or that dropped the thinking) sends
such turns, and magpie relayed them as they came.

What changed:
- chatReplaysReasoning(host, model) names the Chat upstreams that want
  reasoning back: a DeepSeek host, a model named deepseek wherever it is
  served (OpenCode Go's deepseek-v4.1-flash, OpenRouter), and Command
  Code's plugin. buildChat uses it as before.
- Passthrough (gateway.go, provider.Chat): for such an upstream, not
  Mistral (#494), withReasoningOnToolTurns gives every assistant
  tool-call message without reasoning_content one: its thinking from
  another field (reasoning, OpenRouter's) when it has some, else " ".
  The gate takes the member's model, so a group reaching a DeepSeek
  member is covered.
- Translated (buildChat, Responses/Anthropic -> Chat): a tool-call turn
  with no thinking gets " " too.
- Every tool turn, not only the last: DeepSeek also refuses an earlier
  tool turn of the current user turn missing it.
- " ", not "": DeepSeek's Chat takes "", but relays that omit empty
  fields drop it, and DeepSeek's Responses API refuses an empty
  reasoning_text. A vendor that refuses the field still gets the #494
  retry without it.

Checked against api.deepseek.com (owner's key, deepseek-flash, Chat):
last tool turn missing -> 400; "" -> 200; " " -> 200; real -> 200; an
earlier tool turn of the current user turn missing -> 400; a tool turn
before the latest user message missing -> 200; answers missing -> 200.

Not changed, found on the way: DeepSeek's Responses API refuses a
function_call with no reasoning item (and empty reasoning_text), and its
Anthropic API a tool_use with no thinking block; magpie relays those
natively as they come. OpenCode Go's deepseek-v4.1-flash could not be
tried for real: the owner's workspace answers "requires Global regions".

Run:
- New tests fail on the old code (TestChatToolTurnWithoutReasoningRelayed:
  400 "reasoning_content ... must be passed back"; TestTranslatedToolTurn
  WithoutReasoning: 400), pass now; TestChatToolTurnWithoutReasoning
  NotForMistral and the Mistral/MessageReasoning tests pass.
- gofmt -l clean; go vet -tags nogui ./internal/gateway on darwin,
  GOOS=linux, GOOS=windows.
- go test -tags nogui -count=1 ./... under a temp HOME: all ok.
- Real use: the built binary's gateway in a sandbox HOME with only the
  DeepSeek provider. Old: last tool turn missing 400, earlier one
  missing (stream) 400, plain answer 200. New: all three 200.
2026-10-10 14:14:47 +08:00
yetone d7186e51b9 gateway: Gemini's thoughtSignature stays on the call and text it signed through translation, and goes back instead of the skip value (#1445, XYenon)
What changed: parseGemini keeps a functionCall's and a text part's
thoughtSignature. geminiParts and buildCodeAssistSent write them back; a
later call of a signed step goes without one, and only an unsigned step
or Claude on Antigravity gets skip_thought_signature_validator. The Code
Assist decoder puts a call's signature in its id (signedID, as chat does
since #687) and a text's in KTextSig; the Gemini encoder and renderer
give them to a Gemini client where Gemini put them, with a clean id.
Chat, Messages and Responses renderers leave a signature-only text part
out.

Why: a Gemini client on a Code Assist or translated path had every call's
signature replaced by the skip value and text signatures dropped.

Run: the new tests in reasoning_state_gemini_test.go (Gemini's
documented thought-signature shapes) fail on the old code and pass now; a
Chat client's call id carries the signature back to Google, and no other
API's client gets the text's. 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 baecbb1be0 provider, gateway: Cursor moved onto its 0.2.x plugin gets Fast back, in the agent picker (#954) and for a Routing group's member, on the models Cursor has a fast variant of (#1360, loosheng: 插件 0.2.x 后 Cursor 的快速模式不见了,保存 cursor/<model>:fast 报 "has no fast mode magpie can ask for")
Plugin 0.2.x lists Cursor's picker once per context size (claude-opus-5-5@300k, @1m) and no -fast model, so CanFast, which looked for a -fast sibling, said no for every model: FastFor in route.go, canFast in the group editor, SetFastPick and cleanFast all go through it. The plugin itself still ran service_tier priority as the fast variant. opencode-cursor-auth 0.2.2 (magpie-community/plugins fb253f9) now says fast on a model listed at a size Cursor has a fast variant at; host.js passes it on as plugin.Model.Fast, CanFast takes it, and a plugin before 0.2.2 is still read by its -fast sibling. The Cursor mover asks for 0.2.2. On the way a fast request translated for a moved Cursor (Anthropic, Responses, chat not streamed) lost its service_tier: buildChat sets it only for host "cursor", and a moved provider's host is empty; buildHost names it.

Tested: the fake plugin lists sized models with fast on one (FAKE_FAST=tier); TestCursorPluginGroupFast (CanFast per size, @1m:fast refused, a group's @300k:fast sends priority), TestCursorPluginGroupFastSibling (the old -fast list), TestCursorPluginFastPick (moved: picker fast on chat, chat streamed, Responses and Anthropic sends priority, codex's doesn't). Without groupfast.go, host.js's fast or buildHost they fail. go test -race -tags nogui on gateway, provider, plugin, agent, gui; go vet, GOOS=linux/windows vet and build. With the built binary under a temp HOME, the real npm 0.2.2 plugin and Cursor's API answered by a preload (a picker fixture, the agent API's Run caught): /api/state offers fastFor on @300k and composer-2.5, not @1m or grok; /api/groups canFast the same; saving @1m:fast is refused, @300k:fast saved; opencode's picked @300k reaches Cursor's Run with fast=true on chat, Anthropic and Responses, codex's with fast=false. origin/main's binary in the same HOME offers none and refuses @300k. Not tried with a real Cursor account.
2026-10-09 05:32:36 +08:00
yetone 2ab69d0f87 gateway: MiniMax's thinking reaches Codex as reasoning, folded, not as the answer's text (#1267, pluo)
MiniMax's own Chat API (api.minimax.io, api.minimaxi.com), which Codex's
Responses requests to a MiniMax key are translated onto, gives a model's
thinking at the head of the text between <think>…</think>. The Chat decoder
only knew Gemini's leading <thought>…</thought>, so the thinking went to
Codex as message text. A leading <think> block is now thinking too, however
its tags fall across chunks; a tag later in the text stays text.

MiniMax asks for that thinking back in the assistant's text on later turns
(interleaved thinking), which it got before only because it was taken for
text. On MiniMax's own hosts it now goes back between <think> tags; a relay
serving MiniMax's models, and every other Chat upstream, is sent what it was
before.

Verified: TestMiniMaxThinkTagsReachCodexAsReasoning (Codex /v1/responses
through the gateway to a fake Chat upstream with MiniMax-shaped chunks),
TestMiniMaxThinkingGoesBackInTags and TestChatThinkTags fail on the old
chat.go (message text "<think>\nThe user greets me…</think>\n\nHello!",
items [message]; assistant content "Hello!" without the thinking) and pass
with it. The chunk shape is from MiniMax's OpenAI-compatible docs; no real
MiniMax key was tried.
2026-10-08 16:51:47 +08:00
yetone 7067fce5ec gateway: a turn's parallel tool calls split over two assistant messages keep their results on Chat, Cursor and Devin (#1275)
An Anthropic request may send one turn's tool_use blocks in consecutive
assistant messages, answered by one user message. buildChat's
pairToolMessages, cursorMessages and buildDevin each closed the first
message's calls at the second one: the calls were answered "interrupted"
and the real results went out as a stray user message (Chat) or were
dropped (Cursor, Devin). joinSplitCalls now joins an assistant message
onto an assistant message before it that made tool calls, as Anthropic
reads them, so the calls are pending together. Responses, Messages,
Kiro and Gemini/Code Assist already kept the results.

Tests (split_calls_test.go): Chat, Cursor and Devin split cases fail on
main and pass now; a truly unanswered call of a split turn still gets
the synthetic result; text after a call in its own message; two text-only
assistant messages unchanged; Responses guard.
2026-10-08 16:47:52 +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
forever bed306ae60 gateway: reasoning off reaches Gemini 3 at its lowest level, and Google refusing minimal no longer stops a provider's thoughts (#1062)
* gateway: reasoning off goes to Gemini 3 at its lowest level where it has no minimal, and Google refusing minimal no longer stops the provider's thoughts until restart

With reasoning off, a request to Gemini's OpenAI-compatible API (AI
Studio's, or a proxy in front of it on this machine or the LAN) went with
reasoning_effort minimal, since Gemini 3 can't stop thinking.
gemini-3.8-flash has no minimal: models.dev gives its levels as low,
medium and high, and Google answers minimal with 400 "Thinking level is
unsupported: THINKING_LEVEL_MINIMAL". The message names thinking, so
refusesThinkingConfig took it for thinking_config turned away and marked
that field unfit for the provider. Until magpie restarted, nothing sent to
the provider asked for Gemini's thoughts again, on any model, and a client
that asked to see them got none. The turn itself was asked again with no
reasoning_effort, at the model's default level.

  * Reasoning off goes at the model's lowest level where its levels are
    known and have no minimal, and at minimal where they have it or aren't
    known (Request.OffLevel, geminiOffLevel). gemini-3.8-flash on AI
    Studio goes at low, in one request.
  * Where the levels aren't known (a proxy's own name for the model),
    Google's 400 for minimal is told apart from thinking_config turned
    away (geminiMinimalRefused, which also matches gemini-3.1-pro-preview's
    "thinking_level MINIMAL is not supported by this model" at
    generateContent). It is remembered as the model refusing reasoning off
    (offRefused, as for other vendors), and the model is asked again at its
    lowest level, low when none are known, and so from then on.
    thinking_config is kept, and the next turn that thinks gets the
    model's thoughts.
  * An effort of minimal set on the request, which fitFor keeps where the
    levels aren't known, is turned away the same way and asked again at
    low by the existing offEffort step, with its thinking_config.

Passthrough (a Chat client calling AI Studio itself) is unchanged: it fits
the effort to the model's levels where they're known, and has no retry for
a proxy whose levels aren't.

Tests, with what upstream's gateway gives:
  * TestGeminiThinkingOffAtItsLowest: an Anthropic client's turn with
    thinking disabled, then one thinking at high, then disabled again, to
    a fake Gemini that answers minimal with the 400 above, in its literal
    bytes. With the levels known, the first turn goes at [low]; not known,
    at [minimal low]. Either way the thinking turn then sends
    thinking_config {include_thoughts: true, thinking_level: high} and
    gets a thinking block, and the last turn goes at low in one request.
    Upstream sends [minimal <nil>] both ways.
  * TestAIStudioThinking: "off at its lowest" sends reasoning_effort low.
    Upstream sends minimal.
Each part was also broken on its own, and each break fails a test:
buildChat ignoring OffLevel ("reasoning_effort = "minimal", want "low"",
and [minimal minimal <nil>]), the loop never setting it ([minimal minimal
<nil>] both ways), no check for the refusal of minimal ([minimal <nil>]
with the levels not known), and geminiOffLevel ignoring the refusal
([minimal minimal <nil>]) or the known levels ([minimal low]).

Verified on 443f1cbc: gofmt -l, go vet ./..., go build, GOOS=linux go
build -tags nogui and GOOS=windows go build pass; go test -tags nogui
./... passes, and -race -count=20 on the tests above.

Live, with gemini-3.8-flash through a proxy on this machine in front of
Vertex AI's OpenAI-compatible API, the gateway in a temporary HOME (AI
Studio itself wasn't tried: there was no key for it). Upstream sent the
off turn at minimal, got the 400 and asked again with no
reasoning_effort; the thinking turn after it went as reasoning_effort high
with no thinking_config, and no thoughts came back. With this change the
off turn went at low in one request, the thinking turn with thinking_config
at high, and the last off turn at low. Under a name whose levels aren't
known, the first off turn went minimal, then low, and the next at low at
once. The thoughts reached the client as thinking with the next commit,
which reads how that endpoint marks them.

* gateway: Gemini's thoughts streamed from Vertex AI's OpenAI-compatible API reach the client as thinking, not as the start of the answer

A proxy on this machine or the LAN in front of Gemini is asked for the
model's thoughts as AI Studio is, in thinking_config. In front of Vertex
AI's OpenAI-compatible API, the thoughts don't come in AI Studio's
<thought> tags: each comes in a chunk of its own, the thought as the
delta's content, and the chunk is marked
"extra_content": {"google": {"thought": true}}. chatDecoder read only the
content, so the thoughts were streamed to the client as the first part of
the answer.

  * A chunk marked as a thought is thinking (KThink).

A whole reply from that API carries its thoughts in <think> tags instead.
That isn't changed: the gateway streams from the upstream when it
translates, and a Chat client's own request is passed through as it is.

Tests, with what upstream's gateway gives:
  * TestGeminiThoughtsMarkedInExtraContent: that API's stream for "你好"
    at high with the thoughts asked for, in its literal bytes
    (testdata/vertex_openai_thoughts.sse), to an Anthropic client: a
    thinking block that starts "**Acknowledging Greeting**", then the
    text "你好!很高兴与你交流。请问有什么我可以帮你的吗?". Upstream gives
    thinking "" and the thought at the head of the text.

Verified on 443f1cbc: gofmt -l, go vet ./..., go build, GOOS=linux go
build -tags nogui and GOOS=windows go build pass; go test -tags nogui
./... passes, and -race -count=20 on the tests of this and the previous
commit.

Live, through the proxy and temporary HOME of the previous commit, a turn
thinking at high gave a thinking block of 238 characters, and the answer
apart from it.
2026-10-07 18:51:01 +08:00
yetone 86f48071cc gateway: an image or a PDF sent as Gemini's inline_data, or as a Chat Completions file part, reaches the model, and a Gemini stream gets no keepalive comment (#934, handong66)
/v1beta read a part's fields only as camelCase, while Google's API takes
their proto names too (inline_data, mime_type, file_data, function_call,
system_instruction, generation_config…), which agy and raw SDK calls
send: the image was left out, the call still answered 200, and the model
made up what it held. geminiCamel spells a request's fields in camelCase
before anything reads it, keeping the caller's own keys (a call's args, a
result's response, the schemas) as they are.

A Chat Completions {type: file} part (file_data as a data: URL or bare
base64, or a file_id) was dropped; it is now the request's file, which
Antigravity and other Gemini upstreams are given as inline data and the
others are told of ([attachment application/pdf]).

A held stream's keepalive comment went to Gemini clients too, which
agy fails on ("invalid stream chunk: : keepalive"); a Gemini stream gets
none, as geminiEncoder.keepalive already sent none.

TestGeminiSnakeCaseParts, TestGeminiSnakeCaseImageReachesUpstream,
TestChatFilePart and TestHeldGeminiStreamSendsNoComment are new and each
fails without the change. go vet, go build (GOOS=linux nogui, GOOS=windows)
and go test -tags nogui under a temp HOME pass (TestSavedButSignedOutClaudeServed,
in a package this doesn't touch, failed once on a 5s timeout and passes alone).
2026-10-06 01:09:29 +08:00
sundjly f55a13f23e gateway: a translated reply cut off mid-stream goes on where the upstream has a real prefill (#853)
* gateway: a Chat upstream gets a mended tool exchange — Kimi turns a broken one away 400 ("tool_call_id is not found"): a turn's tool results all go ahead of its own text, in the calls' order; a result whose call is gone gets a synthetic call (unknown_tool) so it survives; an unanswered call gets a synthetic error result; a thinking-only assistant turn, which an aborted stream leaves behind, is dropped

* gateway: a translated reply whose stream the upstream cuts off mid-way goes on instead of failing — the same conversation is asked again with what the client already has of the reply sent back as its last message, for the model to go on from (vk-relay dropping Kimi K3 and DeepSeek streams mid-reply: "API Error: Server error mid-response"). The reply so far goes back with its reasoning for models that read reasoning_content back (Kimi, DeepSeek), a full echo of it is dropped, and the continuation's fresh thinking isn't shown again; the client waits with keepalives between tries, up to two. A reply a tool call of has begun can't be prefilled, and a refusal isn't asked again: both end with the error in the stream, as they used to. A stream's own error event mid-reply ends its read at once rather than waiting on a vendor that keeps the connection open. TestStreamCutMidReplyContinues (reply goes on, one message), TestStreamCutContinuationEchoDropped, TestStreamCutAfterToolCallEndsAsBefore, TestStreamCutContinuesOnlySoLong, TestStreamCutMidThinkingContinues(WithoutReasoning), TestStreamErrorMidReplyContinuesAtOnce and TestContinuationUnecho cover it; TestStreamErrorKeptOpenFailsOverAtOnce and the severed-stream tests pass unchanged. go vet ./internal/gateway, go build (darwin, GOOS=linux, GOOS=windows), go test of gateway, provider, catalog and imagemcp pass.

* gateway: a Chat upstream's mended tool exchange — an orphaned or late result reaches the model as a user message, the Responses path's policy, so no call is made up and no id is used twice; an empty assistant is dropped only inside a pending exchange, where it would break adjacency, and passes through outside one; a second answer to a call is dropped, the first stands; the session replay harness gives way to fixed fixtures

* gateway: a cut reply is asked to go on only where the upstream goes on from a prefill — a trailing assistant message isn't one on most Chat APIs: the model answers it again from the start, reworded, and the client, an exact echo alone dropped, kept its part and the re-answer spliced as one reply with no error to tell (api.deepseek.com did so 5 times in 6). It goes on only where the prefill is real: an Anthropic Messages upstream natively (a model that turns one away answers 400 and the reply ends as it used to; the newest Claude among them), a Chat one in its vendor's own mode — DeepSeek's prefix, asked of its /beta endpoint with "prefix": true on the message, Kimi's "partial": true — a relay on this machine or the LAN serving one of their models taken to front the vendor, as geminiCompat takes one to front Gemini; everywhere else the reply ends with the error, as it used to, for the agent to try the turn again. reasoning_content goes back with the prefill by the same decision (reasoningBack named any kimi model on any host); the prefill's trailing whitespace, which Anthropic turns the request away for, is trimmed, the client having it already; and the tries' usages are summed into the reply's, the client's and the ledger's, where only the last try's was kept while the vendor billed each (a cut try's is only what it said before the cut). New tests: a re-answering upstream is never asked to go on (the client reads the error, not the garble), DeepSeek's /beta prefix mode and Kimi's partial on the wire, an Anthropic upstream's native prefill (text, thinking-only, whitespace trimmed, a refused prefill ending as it used to), the tries' usages summed, chatPrefill and prefillHow themselves. go vet, builds (darwin, nogui) and go test -count=1 -race ./internal/gateway pass (2146; gui's TestSetPortMovesTheGateway fails on main too).

* tests: three environment- and drift-broken suites pass again — port: a moved gateway finishes the connections it has (Relisten's handover), so answers() pooled a keep-alive one from its start-up polls and the old port answered from it forever; it now dials with keep-alive off, asking what the test means to: does the old port take NEW connections. plugin: TestBunIsGivenTheSystemsRoots read the shell's ambient NODE_EXTRA_CA_CERTS as the user's own (it wins by design); the test sets its own. accounts: forgetting the account in use puts the one left first since 30d952cf, which updated the provider and GUI tests but not accounts_plugin_cli_test.go; it now expects that. All three failed on upstream/main on a machine with a proxy CA configured; the full nogui suite passes.
2026-10-05 17:25:15 +08:00
yetone 88fd366efb gateway: Gemini's thought signatures come back on its tool calls, through Pi and every other client (#687) — Pi on the built-in Google Gemini (an API key, gemini-3.8-flash at high) failed the turn after every tool call with 400 "Function call is missing a thought_signature in functionCall parts … default_api:bash, position 3". Gemini 3 signs the first call of each step it thinks through and wants the signature back; its OpenAI-compatible API gives it in tool_calls[].extra_content.google.thought_signature, which magpie relayed to Pi as it came, and Pi's openai-completions (like the AI SDK) keeps a call's id but drops extra_content, so the call went back unsigned. magpie's own translation (Claude Code, Codex, Gemini CLI on the same provider) never read the field at all. Now a call Gemini signed reaches the client with an id carrying the signature (<id>__ts__<signature as base64url>, letters, digits, _ and - only), which every client sends back as given: a Chat request relayed to Gemini has it taken off the call's and the result's ids and put in extra_content, and parse does the same for a translated request (the signature on the call's Part, given back by buildChat). A turn with no signature at all — another model's calls, or an id a client shortened — goes to Gemini with skip_thought_signature_validator on its calls, the value Google documents and the Code Assist path already sends; a later call of a signed step goes without, as Gemini signs the first. Any other upstream gets the calls' own ids, never the long ones. TestGeminiThoughtSignatureThroughPi (streamed and whole) and TestGeminiThoughtSignatureThroughAnthropic, against an upstream that checks signatures as Google does, fail on the old code with the issue's 400 and pass; TestGeminiCallsWithoutSignature and TestSignedID cover the fallback, other upstreams and the id's round trip. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./internal/gateway/... under a temp HOME pass. Not tried against generativelanguage.googleapis.com: there is no Gemini API key on this machine. 2026-10-03 22:34:36 +08:00
sundjly 2e1fcb8a77 gateway: a Chat upstream gets a mended tool exchange — strict ones (Kimi) answered a broken one 400 "tool_call_id is not found" (#554)
Relaying Claude Code (or Codex via Responses) to a Chat Completions upstream that checks the tool exchange strictly — Kimi answers 400 "tool_call_id is not found" — got stuck once a history tripped it, since every retry resent it. buildChat now puts a turn's tool results ahead of its own text and images, and pairToolMessages mends the built messages for every Chat upstream (Zed's xAI path included; Chat→Chat passthrough never reaches it): an assistant's tool messages go in its calls' order; a second answer to a call is dropped, the first standing; a result answering no pending call (already answered and closed, compacted away, never sent, or an empty id) becomes user text — joined to the user message just before it — as orphanedToolOutputs does on the Responses path, so no call is made up and no id is used twice; an unanswered call gets a synthetic "unavailable: the turn was interrupted" result; an assistant message with nothing in it is dropped only inside a pending exchange, and passes through outside one. A well-formed exchange is built byte-identical to before. chat_tool_pairing_test.go (order, gathering across user messages, orphan, late result, duplicate, empty id, unanswered call, thinking-only inside and outside an exchange, a session-shaped fixture, a clean exchange; checked for Kimi's adjacency and for ids used once) is new — 9 of its 11 tests fail without the change; TestTextOnlyModelOmitsToolImages' responses-to-chat case now expects the orphaned output as user text without its id. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME and go test -race ./internal/gateway pass. (#554)
2026-10-02 23:02:08 +08:00
yetone 1ea43274b0 gateway: Mistral's thinking, sent as typed parts in a Chat reply's content, reaches a Chat client as reasoning_content and a string content, and a translated one as thinking (#483: OpenCode's 'Invalid magpie/openai-compatible-chat stream event' with GLM on api.mistral.ai) — Mistral streams a reasoning model's thinking as delta.content = [{"type":"thinking","thinking":[{"type":"text","text":…}]},{"type":"text","text":"ok"}], thinking and text sometimes in one delta, and message.content so when not streamed; magpie relayed it as it came, the Chat contract has a string or null there, and the AI SDK OpenCode reads Chat with turned the first such chunk away and gave the request up (499 in the usage log). A relayed chunk or whole reply whose content is parts now has its thinking in reasoning_content, after any already there, and its text as a string content; a delta of thinking alone goes without content. Spoken to Claude Code's API or Codex's, such a chunk wasn't read at all, its thinking and text lost; it is now thinking and then text. Replies of every other upstream pass byte for byte, streamed or not. Prompts and headers are unchanged. TestMistralPartsStreamFlattened, TestMistralPartsWholeFlattened and TestMistralPartsTranslated (Anthropic, Responses) fail without the change; TestChatRelayWithoutPartsUntouched keeps other replies byte for byte. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass. 2026-10-02 06:07:57 +08:00
TechnoHouse e76f119048 gateway: report cache writes in Chat usage (#429)
Claude Code reports cache writes, and the gateway retains them in Usage. Usage.chat() leaves them out of the response, so OpenAI-compatible clients count those tokens as ordinary input. Emit prompt_tokens_details.cache_write_tokens and keep prompt_tokens as the total prompt.

TestClaudeChatCacheWrites drives Claude stream usage through both Chat response modes. It fails without the serializer change. go vet, the gateway/redaction race tests, the provider account race tests, the no-GUI build, and go test ./... pass, except TestPluginModelListThroughAccountProxy, TestPluginProxy and TestPluginSOCKSProxy: they fail on main too on the test machine, whose DNS resolves .invalid names. A local live client run records cache writes on a cold turn and cache reads on a later turn.
2026-10-01 23:08:30 +08:00
yetone a97643bcc8 gateway: a translated or relayed stream keeps its client alive while its provider is (#436, congee949: Chat → Responses dropped the upstream's ": keepalive" and Codex hit "idle timeout waiting for SSE" on a live connection) — a reply magpie translates was read event by event and written only when an event had something for the client, so a provider's SSE keepalives, and events with nothing to translate, reached no one, and a reply that thought quietly for five minutes ended in Codex's idle timeout and a retry. Now, whenever the provider is heard from and the client has heard nothing for a second, magpie sends the client a keepalive in its own protocol: response.in_progress again on Responses (Codex's timeout counts events, never a comment — a sandboxed codex 0.159.2 on a fake provider sending only comments timed out, one sending response.in_progress didn't), ping on Anthropic (as Anthropic does; Claude Code's watchdog counts it), an SSE comment on Chat Completions, nothing on Gemini (Google's SDK can't read past one). A provider that sends nothing at all is not covered for, so a dead connection still ends at the client's timeout. A reply relayed from the Claude subscription's bridge, Kiro, Cursor, Devin, search, Qoder, Zed or Command Code is kept alive every 15s while it goes quiet, for up to 5 minutes since its last event. Native passthrough is unchanged, and prompts and headers are unchanged. The routing trace no longer drops a request still going for the 60 finished after it: the oldest finished ones go first, unless more than 120 are going at once. TestTranslatedStreamKeepsClientAlive (the issue's repro: 20ms keepalives, 150ms idle timeout; Chat → Responses, Chat → Anthropic, Responses → Chat), TestRelayKeepsClientAlive and TestTraceKeepsInflight fail without the change; TestTranslatedSilenceStillTimesOut keeps a silent provider uncovered. In a sandbox CODEX_HOME, codex exec through the gateway on a provider sending 6s of keepalives with stream_idle_timeout_ms 2500 answers, and without the change fails with idle timeout waiting for SSE. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass. 2026-10-01 22:36:36 +08:00