ac4af582301a4e8a29245dbba767eba31334ddf9
36
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e0f6eda641 |
gateway: a probe's reply that thinks its 16 tokens and ends unsaid is answered (plugins#827)
Through a Remote magpie, the plain model test of Open Design's
glm-5.3-flash was red. The model always thinks. It spent the test's 16
tokens on that and ended after content_block_stop, with no message_delta
or message_stop. So:
- translate made it a 502 "ended before it was complete";
- the 502 is busy, so the remote retried it and waited out its 60s
patience;
- the asking magpie had given the remote only 20s (testWait), and said
no answer came.
Each step is now fixed for the class, not for this model:
- A reply whose request was capped at a short probe's worth
(cutVoidTokens, 1024) and that spent some of it, then ended cleanly
with nothing saying it ended, ended at its length (endsAtProbeCap).
- This holds in translate, in streamTranslated and in gathered (a
Responses plugin's stream asked whole becomes response.incomplete at
max_output_tokens).
- It covers Anthropic and Responses upstreams only. Gemini always
ends with a finishReason, so a Gemini stream without one stays a cut
(TestGeminiUpstreamEndedShort, asked for 256, caught a wider first
draft).
- A reply asked for more than 1024, or one that spent nothing, is
still the 502.
- A client may say how long it waits (provider.WaitHeader,
X-Magpie-Wait, in seconds). The gateway then takes no same-one retry
pause and no patience round that would end within clientRoom (10s) of
that wait (keptAlive.outlives), so the client gets the error while it
still waits. Like every X-Magpie- header, it is not sent upstream.
- A model test through a remote magpie waits pluginTestWait (60s), as a
plugin's test does here, and sends that wait as X-Magpie-Wait.
Not changed: a stream relayed as it came (passthrough to an agent of the
same protocol) still gets no end added. That is filed as #5736 and named
in gateway-routing.md.
Run, through mote-run:
- At the pushed tree, rebased on origin/main
|
||
|
|
665b9aff12 |
gateway: a reply of several requests tells the last one's prompt, bills them all
Claude Code reads a reply's input, cache_creation and cache_read as how full its conversation is. A reply more than one upstream request made summed all three across them. In the bridge: Claude Code's own ToolSearch/WebSearch going on into the answering message, a TUI message written after its call was told (lateUsage), a cut stream's retry ( |
||
|
|
8cbaeecae9 |
providers: errors=pass sends a vendor's error to the agent as it came, asked once
ne9ko9 on Discord wants errors handled explicitly, not by inference, and a mode that passes them straight through. A custom or API-key provider (no account, an endpoint of its own, not a subscription) now takes `passErrors` in its config: "magpie handles" (the default, unchanged) or "Pass through". Nothing sets it but the user, and an edit that doesn't send it keeps the saved value. With it on, for that provider: - no rewriting: on the client's own API, upstream's status, Content-Type and bytes go out (passError); on another API, the client's shape is built with the vendor's own type, message and raw code and param (a numeric code stays a number). Retry-After and *ratelimit* headers go with it; - no too-long inference, no busy words, no 413 hint, no policy rewording (settle never runs: the try is passing); - no gateway retry: forward()'s Retries loop, refit, firstWait, the loop's re-asks, reloop, empties retry and streamTranslated's cont.again all stop; - no fallback and no rest: the candidate loop's one choke point, newHoldWriter(…, !pass && …), lets the try pass, so nothing after it is tried, and restAfterMarked answers By "off". magpie's own file-id re-ask (dsRetryGone) still runs, as it fixes magpie's own upload, not the vendor's answer. CLI: `magpie provider set <id> errors=pass|magpie`; a bad value is refused and keeps the old one; an account is refused. `provider show` says "errors pass". GUI: Edit → Advanced → Errors, a quiet app-menu picker (openProtoMenu, no native select) with "magpie handles" and "Pass through", shown only where takesPassErrors; zh, zh-TW, ja, de. It is drawn by passerrors.js, imported when the editor draws the row (old-webkit's lazy list names it), and app.js pays for its few lines by two comments cut, so app.js is smaller than before and TestCoreScriptBudget's numbers are unchanged. Tests: - internal/gateway/pass_errors_test.go: TestPassErrorsAskedOnce (503, 429, 404 with numeric codes, alone and as a group's first member: exact bytes and status, asked once, the second member never asked, no rest), TestPassErrorsNotInferred (a too-long 400 byte-for-byte), TestPassErrorsOtherAPI (Anthropic 403 code 20031 to a Chat client, streamed and not). - internal/provider/pass_errors_test.go, internal/cli/errors_cli_test.go. - internal/gui/tests/provider-pass-errors.test.cjs: every language, 1100 and 420 wide, Chromium and WebKit. Run, through mote-run at this commit: - go test -count=1 -timeout 45m ./internal/gateway ./internal/provider ./internal/cli ./internal/gui (at the parent 19c45d5d4's tree): gateway, provider, cli ok; gui red only in TestMainWindowCorners/macOS_26_SDK, mote's macOS 27 (#3949). TestCoreScriptBudget ok. - Rebased on |
||
|
|
19c45d5d4e |
gateway: a vendor's error on the client's own API keeps its status, type, code and fields
ne9ko9 on Discord: an error from a vendor that speaks the client's own API was rebuilt from its status. writeVendorError (via writeErrorSaid) set the type from the status, kept only a string code and param, and dropped every field magpie doesn't know (a numeric code, request_id, extra). That happened in the native relay's error branch (gateway.go), passthrough, translate's and streamTranslated's. Now writeVendorErrorFrom checks the upstream's error shape. When it is the client's own (Chat/Responses to Chat/Responses, Anthropic to Anthropic, Gemini to Gemini) and the body is a JSON error object with a string message, the vendor's status, Content-Type and bytes go to the client, except error.message. Only the message is magpie's: the provider's name before the vendor's words, as before. A describer asking for another model, the Claude sign-in's rewording (claude_signin.go) and the agent read which provider said it there, so taking the name out broke them. The message also carries a note where magpie has one (an account's Explain, a region, the wrong endpoint), a busy relay said so (saysBusy) and a 413's byte-limit hint. A prompt too long for the model (tooLong) is said as the client's API says it: status 400 and type/code, or Gemini's code/status, so the agent compacts. setErrorField splices each change in place, so every other byte is the vendor's. A non-JSON body, or one from another API, is rebuilt as before. For the vendor's message untouched too, the next commit's errors=pass sends the body byte-for-byte. Tests (internal/gateway/kept_error_test.go): - TestSameAPIErrorKeptAsSent: literal bodies with numeric codes (1214, 20031) and extra fields (extra, details, request_id, param) on Chat, Anthropic (403) and Responses. Exact bytes and status. - TestSameAPIOverflowKeepsTheRest: a Zhipu-like 1261 overflow keeps extra and request_id, with code context_length_exceeded. - TestOtherAPIErrorRebuilt: an Anthropic client to a Chat vendor. - TestSetErrorField. Run: - Broken by hand: the new gateway tests copied onto origin/main |
||
|
|
8c733bb362 |
gateway: a bare JSON error line in an event stream is the vendor's error
zRain (Discord #feedback, Windows, v0.1.3039/v0.1.3041) asked
antigravity/gemini-4-argon high. Code Assist answered 200
text/event-stream, a few thinking events, then ended the body with
{"error":{"code":400,"message":"Request contains an invalid argument.","status":"INVALID_ARGUMENT"}}
on a line of its own, no "data:" before it. readSSEAlive and the
passthrough sniffer skip any line that is no SSE field, so the stream
ended with no finishReason and the agent was told "Antigravity: the
reply ended before it was complete" instead of Google's 400.
- sse_bare.go: bareErrors hands such a line (Google's shape, a list
of one, pretty-printed over several lines, OpenAI's {"error":…},
Anthropic's {"type":"error"}) on as the data event it means. Every
other line goes byte for byte, a line under way at once; only a line
starting { or [ waits for its end (held up to 1MB). eventStream wraps
the body with it (passthrough, translated stream and whole reply,
continuation, search), and readSSEAlive wraps every other reader.
- codeassist.go and carriedError take the status the error names
(namedStatus, #4855), so a whole reply's error goes out at 400.
- continuation.go notes that status for routing (namedStatusHeader);
refusal events and Antigravity's own turning away are left as they
were.
- gateway.go: a reply broken off by an error frame that names a 4xx
retryable() calls the request's fault rests nobody, as that 400 does
before the 200.
Plugins: antigravity-cloak only rewrites the request, reads no stream,
so nothing to change there.
Run (mote, at this tree on
|
||
|
|
d45e74d89f |
gateway: a length cut that said nothing is not a completed reply (#2972)
What changed: a Chat reply cut at its length having said nothing — no
text and no call, only thinking, or nothing at all — fails at once, on
the translated paths and on the passthrough Chat→Chat relay, asked
again nowhere: the error in the client's own protocol, a group's next
member asked, nobody rested, and the same one not asked again after a
moment (the void fails the same every ask, as one that didn't stream
does). It fails only past a short probe's worth: a reply that spent no
more than cutVoidTokens, of a request capped at no more, is a probe's
answer — a title's cut is wanted, the response.incomplete it was
(#1466) — and goes as it came. A length cut that said something is
still the truncation it always was.
Why: qoder/dfmodel ended four replies of one dsh turn with 48,000
output tokens each, every one of them reasoning — out == reasoning
exactly each time, 192,000 tokens and 919 seconds for nothing — and dsh
speaks openai-completions while the qoder plugin serves Chat, so all
four were relayed as they came. The relay reads its end now: a stream's
tail is held from the chunk that says why it ended while nothing has
been said in it, and a void fails with the error event in its place, no
finish_reason the agent reads as "continue" having gone out. A reply
asked whole is written once it has ended, for the same verdict. On the
translated paths the check sits beside answersNothing (cutVoidAt,
cutVoid), and holds the end events as the empty reply's already are. The
verdict sits at the reply's end, so a streamed one costs no second read.
What the review asked, and where each landed:
- the reporter's own route: the passthrough Chat→Chat relay fails the
void too, streamed (the error event and [DONE] instead of the finish)
and whole (the error with the status)
- no in-place re-ask: the void's branch is the empty reply's error
without the emptyRetries, and the same-one retries and the patience's
rounds pass it by (cutVoidWords beside didNotStream in passing and
busy), so the upstream is asked once — every test here holds the fix
to that
- a deliberately small max_tokens is no void: the gate is spent past
cutVoidTokens, or the request hadn't capped its reply small
(probeTranslated asks 16, a title less than that)
The repo's own recorded ClinePass stream (16 tokens, all reasoning,
testdata/clinepass_stream.sse) is relayed as it was, on the relay and
translated alike.
Run:
- go test -tags nogui ./internal/gateway/... -count=1: ok
- go test -race -tags nogui ./internal/gateway/ -count=1 (the stream
relays and holds among it): ok
- the five tests of chat_length_nothing_test.go red on the branch's
parent, green here; TestClinePassUpstreamRecorded green before and
after
- gofmt -l clean; go vet clean on darwin, linux, windows
- builds: darwin and windows ok; linux ok for internal/... but the wails
v3 beta 24 module's own linux files (pre-existing, untouched here)
Fixes #2972
Reviewed and ported: rebased on
|
||
|
|
676b143175 |
gateway: a model refused for the user's region is asked once more, then the agent is told Google's restriction on that model (#5182)
taoxiaoxin (#5182) runs magpie v0.1.2738 with the built-in Antigravity provider, calling it with curl. antigravity/gemini-3.8-flash (upstream gemini-3.8-flash-tiered) answers 400 "User location is not supported for the API use.", while claude-sonnet-4-6 and claude-opus-4-6-thinking on the same accounts answer 200. The refusal is per model and comes from where the user is. A new connection doesn't help, and v0.1.2982 still asked every account and then retried the last two more times. - gateway.go: regionAsked counts region refusals per provider and model within a request. The first one goes on as v0.1.2982 does: the next account, or the same one again, on a new connection, which covers ggdayup's stale-edge case. On a second refusal, the provider's other accounts aren't asked that model (notMates), the last one isn't retried (protected), and another provider or model left is asked. Nobody rests (restAfterMarked, v0.1.2982). - fallback.go: regionNote and explained. The agent gets the vendor's words plus: "Google doesn't serve <model> to requests from the region this one left from: a regional restriction on the model, not on the account, so no account rests for it and the provider's other models may still answer. Use another provider for <model>, or give the provider a proxy in a region Google serves (its Proxy setting)". It is added at the four places that word a failed reply through Provider.Explain (translated stream and non-stream, pass-through, count_tokens). It still goes out as the 400 that SDKs don't retry. - docs/subsystems/gateway-routing.md: the bullet says this. Tests: - TestRegionRefusalOfTheModelEndsAfterOneMoreAsk: one and three accounts, stream and not, every ask refused. Exactly 2 asks, then a 400 that carries Google's words and the note. No account rests and no usage is re-read. - TestRegionNote: Google's and OpenAI's wordings. Nothing is added for another 400, or for a 200 that quotes the words. Run on mote (mote-run): - go test -count=1 -run Region ./internal/gateway/: ok, every #5182 test from |
||
|
|
b4a9cd8db5 |
codex: a tool name the ChatGPT backend refuses goes as one it takes, and comes back as the agent's
wing3556 on Discord (11-02): a compaction through a Codex account failed 400 "Codex: Invalid response.create payload: Invalid 'input[83].name': string does not match pattern. Expected a string that matches the pattern '^[a-zA-Z0-9_.-]+\z'." The ChatGPT backend checks every tool name in a request, a call's in input as well as a tool's in tools, and refuses the whole request when one fails. A conversation can hold a call by such a name: a model another provider served wrote one with a space, a colon or non-ASCII in it, and the agent kept it beside its "no such tool" answer. Every request that replayed it, the compaction above all, then failed on Codex. Nothing on the way checked: buildResponses copies a call's name as it is, and redaction keeps names as written. What changed: - provider.CodexToolName: a valid name stays as it is. Otherwise each refused byte becomes "_", the result is cut to 55 and gets "_" plus 8 hex of its sha256, so it is the same on every request and two names never meet. CodexToolNames applies it to tools (namespace children too), function_call/custom_tool_call items, additional_tools and tool_search_output items, and tool_choice. A body with no bad name goes byte for byte. - It runs where every request to the ChatGPT backend passes: codexBody (an account's, translated or relayed) and codexUpstreamOn (Codex's own sign-in, /responses and /responses/compact), beside DeclareSearch. - A tool the agent declared under such a name is called back by its own name: translated replies through decoderFor (now given the request's tools; codexNamesBack), relayed Responses replies through nsTidy's new back map (codexRenamedIn). - docs/subsystems/gateway-routing.md says so beside #1270's paragraph. Not covered: namespaces, the OpenAI API (whose pattern has no "." and a 64 limit), Azure and Copilot Responses, filed as #4875. Run on mote at this head: - TestCodexToolNamesTheBackendTakes and TestCodexToolNamesKeepValid pass. The fake backend refuses a bad name with the reporter's 400 word for word; the test covers Claude Code's compaction on /v1/messages with four bad history names (sent twice, byte-equal), Chat with a declared "search:web" called back by that name, Responses relayed the same, and Codex's own /backend-api/codex/responses. - go test ./internal/provider ./internal/gateway (-timeout 45m): provider ok; gateway ok but TestCodexPoolSaysTheClientsVersion, the red already filed as #4807 (full package run only, another test's Codex identity reaches it); it passes alone at this head. - go vet ./... (darwin) and GOOS=linux/windows CGO_ENABLED=0 go vet -tags nogui ./...: ok. gofmt -l: clean. Broken by hand: - codexBody hook off: compaction red with the reporter's 400. - codexUpstreamOn hook off, decoder restore off, passthrough restore off (together): the codex, chat and responses cases each red. Not tried: wing3556's real conversation (we don't have its bytes, and the agent is unknown; Claude Code is likely). No real ChatGPT account was asked with a bad name, so whether the real backend also limits length is unknown. |
||
|
|
9da9bfabdc |
gateway: Grok's reasoning goes back to it through a Claude, Chat or Gemini client (jenryai on X)
jenryai uses Grok through Claude Desktop and sees repeats and broken tool calls that Grok Build doesn't make. Diffing Grok Build 1.0.67's captured requests against magpie's: Grok Build asks for include ["reasoning.encrypted_content"] and sends every reasoning item, encrypted_content and all, before the function_call it led to. Through a Messages (or Chat, Gemini) client magpie never asked for that reasoning, and those clients have no place to keep a Responses item. So every step of a tool loop reached Grok without the reasoning behind its earlier calls. Now, for a Grok plugin request from a client that isn't Responses: - the request asks for reasoning.encrypted_content (askSealedReasoning); - the sealed reasoning items before a call are kept on disk by hash, the same store as Gemini's thought signatures, and the call's id carries the key: <id>__rk16__<key> (carryReasoning, on both the whole and the streamed paths); - on the way back afterParse strips the key from the call and its result and puts the items in front of that assistant turn (unreasonCalls). buildResponses already sends such sealed parts back. A key magpie no longer has, or an id cut short, goes as before. A Responses client keeps its own items and is unchanged. The test fixture testdata/grok_reasoning_then_call.sse is a real Grok stream (reasoning, then message, then function_call, interleaved). Run (mote): - at the base |
||
|
|
026d4423d0 |
gateway: a Command Code stream that ends with no finish_reason is a cut (#2471)
What changed: a Chat stream of Command Code's whose reply ends with no finish_reason anywhere - esp32gallery's day had 665 requests, 624 ended with one, and the 20 that didn't were turns its slow starts lost to a killed worker, each a ledger 200 with no stop and no error while the client read "Stream ended without finish_reason" - was taken for a turn that ended as it should, silence in the ledger and a bare half-reply for the agent. Its API joins Gemini's OpenAI-compatible one in saysItsEnd: every whole reply of its says its end, so a stream that stops short of a finish_reason is said as the cut it is, in the stream, the same way a relayed Gemini one is (#1644) - and one still held, with nothing of the reply said yet, fails there for the group's next candidate. Another vendor's Chat stream may still end whole with neither a finish_reason nor [DONE]: nothing changes there. Run: Four new tests, the first two red on cef8c1a4a before the change (the cut passing as a whole reply, the next member never asked): TestCommandCodeRelayEndedShort, a half-reply cut ends with "the reply ended before it was complete", no finish_reason filled in; TestCommandCodeTaillessFailsOver, a held lead-only stream fails 502 for the next member; TestAnotherChatStreamWithoutAFinishReasonStaysAsItCame, another vendor's tailless stream goes as it came; and TestCommandCodeRelayWholeStaysWhole, a finished reply is never given a second end. TestGeminiCompatRelayEndedShort and TestGeminiCompatTranslatedEndedShort green throughout. Not tried: a real Command Code upstream (the frames are the reporter's ledger shapes, the host the one balance.go reads). Generated-by: GLM-5.3-Flash (ZCode) |
||
|
|
075dc32474 |
gateway: a plugin's cut-short tool call is retried, not rested for a minute (#2873)
A plugin that reads a model's text-form tool calls ends a turn whose upstream stream died mid-call as a failure, so the gateway can act (magpie-community/plugins#38: the turn ends as an error "the gateway can retry or fail over"). The gateway did neither: the error was classified as an unknown failure, the account was rested for a minute of backoff, and the failure was passed to the client — the retry the plugin engineered never happened, and the user's next attempt met the backoff too (#2873's routing record: status 200, usage null, fail "other", rest "backoff", 60s). What changed: the contract's own error wording ("the model's tool call, written as text, was cut short", shared by the plugins that read text-form calls — packages/trae, packages/qoder's CUT_SHORT) is classified as a failure of its own, "cut". Nobody rests for it and no failure is counted: the same member is asked again once — the plugin's parser reads the same but the cut doesn't come again — then the next member as any failure's is; the last member left keeps its usual same-member retries, and the agent is told only after the retries run out. Why: a cut is transient and nobody's fault — the account is as good as it was, and a minute of backoff only pushed the user's next attempt off the same account the plugin had proven works. Run: the new tests (plugin_cutshort_test.go) fail on the unfixed tree — the failing account is tried once, rested, and its mate answers; with the fix the same member answers on its second try, nobody rests, and every member cutting still ends the turn with nobody rested. Full gateway package green (316s), targeted family green under -race, vet and gofmt clean, builds fine on darwin and windows; the linux cross-build fails in the wails GUI dependency exactly as it does on the unfixed base (needs a native linux build), and the gateway package itself builds for linux. Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
5787d758a7 |
usage: a search a provider's model runs with its own tool is a Web search row
cybercaius on Discord: with magpie's search APIs off, DeepSeek was asked to search, and Usage › Requests showed nothing of it; its purpose list had only All, Connection check and Unmarked. DeepSeek searches by itself on its Anthropic and Responses APIs (searchHosts): Claude Code's web_search_20250305 and Codex's web_search are relayed as sent, and the reply carries server_tool_use and web_search_tool_result blocks (#669), or web_search_call items. magpie read only the reply's tokens. Its Chat API has no search tool, so a Chat client's request there, with the searcher and the APIs off, gets no search at all. searchTally (search_native.go) counts what the reply shows: Anthropic's server_tool_use blocks named web_search and usage.server_tool_use.web_search_requests, the Responses API's web_search_call items. What a stream named as it went (a block's start, an item done, by id), what a whole reply or the stream's end listed, and what the usage said are counted apart and the most is taken, so an item named added, done and again in response.completed is one search. The relay's usage sniffer and both translated readers feed it into an unexported Usage.searches; after the request's own row, logNativeSearches writes one row per search (at most 20): Source search, Kind web_search, the request's agent, provider, host and model, status 200. No query is kept and nothing goes to telemetry: the rows ride the probes' lane as the search API rows do (listed, counted nowhere, not exported). An event is parsed for it only when it holds server_tool_use or web_search_call. The purpose filter needed no change: a search row's kind already gives it Web search (TestSearchRowsListTheirPurpose guards that, and passes on the old code too). The Requests tab shows the row with its model and provider as it shows a plan's own search. Run (mote, at this tree): - go test -count=1 -timeout 45m ./internal/usage ./internal/gateway: ok - go vet ./internal/gateway ./internal/usage, GOOS=windows and GOOS=linux go vet ./internal/gateway: ok; gofmt -l clean Broken by hand: - without this change TestOwnProviderSearchesAreLogged fails: "anthropic whole: 0 search rows, want 1" - counting every streamed web_search_call event instead of the done ones by id: "responses stream: 4 search rows, want 2" Not tried: a real DeepSeek account (the fixtures are #669's DeepSeek reply and Anthropic's documented stream shape); the translated readers' counting has no test of its own; no GUI file changed, so no GUI run. |
||
|
|
046093bf7b |
gateway: a plugin's try with another candidate after it is told so, and gives way to a queue (#4049)
axuhere on X: on free models a request sat behind "模型请求正在排队 · 预计等待超过 10 分钟" with other providers configured for the same model, and asked for magpie to move on to the next provider and say why. |
||
|
|
13f658a37d |
gateway: a translated stream whose provider goes quiet keeps its client alive for up to 30 minutes (youyo.p)
youyo.p on Discord (Windows, magpie 0.1.1609): Claude Code on
/v1/messages, translated to a custom provider's /v1/responses, was
canceled with 499 at ~357s and ~795s while the provider was still open.
Once the provider had begun its reply, a translated stream sent the
client something only when the provider did: the encoder's keepalive
went out on each upstream keepalive, and a provider silent mid-turn
(a long reasoning step sent whole at its end) sent nothing at all.
Now streamTranslated runs keepThroughSilence beside readSSEAlive: every
keepaliveEvery with the provider quiet, the client gets its own
protocol's keepalive through the encoder (Anthropic a ping, Responses
response.in_progress, Chat a comment, Gemini nothing), for up to
translatedQuietLongest (30 min: longer than upstreamHeaderWait's 10, long
enough for a reasoning turn sent whole), then nothing, so a provider
that never answers still ends. Writes from the reader and the ticker go
under one lock. Failover is unchanged: nothing is kept alive once a try
failed, was cut or relooped, and a held try's writes still go through
holdWriter.
Anthropic pings are spaced pingEvery (1 min) apart, comments in
between: Claude Code's 300s event watchdog takes at most 30 pings in a
row, and one ping per upstream keepalive spent them in minutes. Before
message_start the keepalive is a comment, as the SDKs' MessageStream
fails on any event before it.
Sibling: search.go's askTranslated, the other readSSEAlive caller, hands
on a KAlive from the same ticker under the same bound. The relays
(claude_subscription relay/relayEvents) keep keepaliveLongest (5 min)
and are unchanged, as is holdWriter's held comments.
Not changed: a provider that sends headers and then no byte at all is
waited out by notAnAPIReply's first-byte read under the held writer's
comments only, before any encoder exists; that path stays as it was.
A translated try held for failover (holdWriter) has two keepers: the
held writer's own comments, bounded by keepaliveLongest (5 min), and the
encoder's. Its comments bypass the encoder's writer, so for the first 5
minutes such a client can get two keepalives per keepaliveEvery. That is
harmless (comments and spaced pings) and left as is;
TestQuietKeptAliveOnlySoLong now sets both bounds and allows both
keepers' count.
Tests: TestTranslatedSilenceStillTimesOut is replaced by
TestTranslatedSilenceKeptAliveForABound (anthropic from responses,
responses from chat, chat from responses: the provider begins, then is
silent; it waits for 10 keepalives, not a duration, and checks they stop
after the bound, with room both ways). TestTranslatedStreamKeepsClientAlive
bounds pings by pingEvery; TestAnthropicKeepaliveBeforeStartIsAComment;
TestRelayKeepsClientAlive counts comments too; TestSearchQueueKeepsCodexAlive
sets the bound; TestQuietKeptAliveOnlySoLong sets both bounds
(red with the quiet bound removed). Prompts and headers sent upstream are unchanged.
Run at this head (rebased on origin/main
|
||
|
|
b5d17b26e0 |
gateway: Antigravity's 429 to Codex's GPT-5 prompt says why and rests nothing, on the web-search path too (Jodiezzzzzz on X)
From Codex, every call to antigravity/claude-opus-5-5 failed with "exceeded retry limit, last status: 429" while dsh worked on the same account. The call was an agent_created_thread, and the vendor said "Resource has been exhausted (e.g. check quota)". Cause: a Codex thread begun on a GPT-5.x model keeps "You are Codex, an agent based on GPT-5..." as its first developer message after /model, resume -m or a fork, and magpie lifts it into systemInstruction. Antigravity answers that line with a fake 429, whatever quota is left, as it does Claude Code's (#666). Codex also sends a web_search tool every turn, so for an Antigravity model magpie serves search itself (translate -> searchReply -> askTranslated), and that path passed the bare 429 back: no hint, no 400, so Codex retried to its limit. - antigravityTurnsCodexAway: the two Codex GPT-5 opening lines count as a turned-away prompt; antigravityHint picks the Codex hint for them. - antigravityRound wraps the search path's ask, so its 429 and an in-stream refusal get the same 400, hint and no rest as translate's. - antigravityForeseen returns the hint, so a group skips Antigravity for the next 6h saying which prompt. - The Routing page shows the new hint (routing/client.js HINTS) in en, zh, zh-TW, ja and de. - Rest: none. The refusal is about the prompt, not the account (Fail "prompt"); a second account answers the same. Plugins: middleware-antigravity-cloak 0.1.1 (plugins a52d1b3) breaks the two Codex lines with U+200B. Its body says "npm had 0.1.0": wrong, the package is not on npm; dist had 0.1.0 and now has 0.1.1 (6fd1438). No mover applies. Real account (owner's Antigravity, sandbox HOME copy, gateway built from this branch) and real Codex 0.162.1: - codex exec resume <a gpt-5.5 thread> -m antigravity/gemini-3-flash: before, 429 retried to "exceeded retry limit"; after, one request and a 400 with the Codex hint; route try (429, prompt), no rest. - A new Codex chat on the same model: 200. - The two lines with U+200B after the first letter: 200; whole: 400. Broken by hand: - antigravityTurnsCodexAway returning false: the Codex tests go red (Codex got 429; the group's skip doesn't say why). - The antigravityRound wrap removed: the search=true subtests go red ("Codex got 429"). Run: - go test -count=1 -timeout 45m ./internal/gateway/: ok (476s, at 865df2472; main's next three commits touch only GUI files). - go test -count=1 -timeout 45m ./internal/gui/: ok (230s, at the pushed tree on |
||
|
|
592899467b |
gateway: Gemini's reasoning streams as it comes on the last candidate, so Codex isn't left with nothing for the whole of its thinking (LuckymanJC on Discord)
LuckymanJC and kkgg: through magpie the first turn of a Codex session on a Gemini model was very slow or seemed stalled. Measured with fake upstreams through the gateway (Codex Responses -> Chat DeepSeek, Gemini; OpenCode Chat; Anthropic passthrough), first content came within 1-50ms on every path but one: a Gemini model's reasoning was held even on the last candidate (`|| last && modelFamily(c.model) != ""` left Gemini out), so Codex got nothing at all, not even response.created, until the text began, while Claude's and GPT's has gone as it comes there since iTianbao's report. It was held there for #667, a reply that only reasoned being asked again. That re-ask happens in place in streamTranslated, keeping the reasoning the agent has, so it doesn't need the hold. But with the try passing, emptyRetries counted it as past the request's own re-asks and asked only streamRetries (2) times, and TestGeminiEmptyRepliesAskedAgain (three empty replies running) went red. A held try that went through on its reasoning alone (holdWriter.thoughtThrough) is now asked once more in place (streamRetries+1); a never-answering model still makes at most 4 calls (the test's bound is 6). Tests: TestThinkingStreamsWithNoOneElse gets "gemini" (Gemini upstream) and "chat gemini" cases, to Claude Code and Codex. With the old line restored they go red ("thinking held: first thought only 1.75us before the text"). With emptyRetries' new branch broken by hand (streamRetries+0), TestGeminiEmptyRepliesAskedAgain goes red with "an empty reply"; green with both. Run: go test -run 'TestGeminiEmpty|TestThinkingStreams|TestThinkingHeld|TestUncountedEmpty|TestReasoningLoop' ./internal/gateway: ok. Break check repeated at push: the old `|| last && modelFamily(c.model) != ""` turns TestThinkingStreamsWithNoOneElse/{gemini,chat_gemini}/v1/{messages,responses} red ("thinking held: first thought only 1.458µs before the text"). Full suite (go1.26.8 darwin-arm64, rebased on |
||
|
|
df341e7671 |
gateway: a member that answers a stream request with a whole reply is asked once, not again and again (#2455)
An upstream that answers stream:true with a whole JSON reply (a relay that doesn't speak SSE) fails as a 502 "did not stream". magpie read that 502 as a failure a moment may mend: the same-one retries (passing) asked it twice more, then a group's patience (busy, #1418) kept asking it until the budget was spent. The failure is the same however often it is asked. With production pauses that is about 7 requests and 60s at the default Patience, about 14 at 240s; the test's 1ms pauses let the 12 replan rounds run out first, 15 requests (ggbdpq's correction on the issue). busy() and passing() now leave a body that says didNotStream alone, and the four places that word the error (translate, streamTranslated, askTranslated, holdWriter.settle) share that constant. A group still moves on to the next member, whose API may stream; retryable() is unchanged. Patch by ggbdpq (f9e09ca7), applied on main with the docs sentence placed by hand (the hunk no longer applied). Run: - TestStreamlessMemberIsAskedOnce with both exclusions taken out: FAIL, whole and stream ("asked 15 times"); with only busy()'s: FAIL ("asked 13 times"); with only passing()'s: FAIL ("asked 3 times"). Restored: ok (asked once, the agent gets the 502 naming "did not stream"). - TestStreamlessMemberHandsOnToTheNextMember (b, which streams, answers after a): ok. - TestQuietNotAReplyLastFails, TestPatience*, TestStreamOverflow*, TestCodexOverflowInGroupNotAskedAgain, TestAgentGoneInTheRetryPause, TestRelayInputCap, TestOverflowGoesToAMemberWithRoom: ok. - Full suite, go test -tags nogui -timeout 45m ./... (set -o pipefail, sandbox HOME, load ~350) at 0224e826f (these four commits on |
||
|
|
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 (
|
||
|
|
e72b6a3327 |
gateway: preserve cache splits and known 1h writes across updates (#1717)
Keep reported Anthropic cache_creation splits, including pure-5m replies,
through API and subscription parsing and client output. Only positive
counters replace known usage. Completed sums retain all counters and
split presence.
Across continuation tries, search rounds and internal bridge messages,
partial updates add earlier total writes only with a positive total. A
split with counts and zero 1h keeps the current message's known 1h before
adding earlier messages' usage. A zero-filled or absent split keeps the
per-counter rule. Omit a zero-filled partial split with a positive total
from output; retain a reported zero-total split. Split presence and the
parsed update's own count evidence remain separate.
Yetone's zero-filled bridge probe and matching continuation/search probes
failed at 0c9298d with 10 instead of 15 1h writes. Fable's partial-5m and
pure-5m cases failed at e1de9bc7 in bridge, continuation and both search
modes with the same loss. All pass after the repair. The 12-case matrix
matches main's client totals and 1h counts and continuation/search ledger
counts. A renderer test rejects a fabricated 50/0 split on a sparse delta.
Verified under sandbox HOME, pinned Go caches and nogui: focused race,
Darwin vet ./..., Linux/Windows gateway vet, gofmt and diff checks. Archive
mutations removing current-message carry, bypassing each of three callers,
and restoring the fabricated split each fail behavior assertions. Restored
archive passes. Earlier zero-total, unreported-split and pure-5m cases stay
green. No live-provider check in this repair.
Review (yetone's session, landed from the PR's head c4cf224 and 90cdb2f):
the partial-cache probes go red when carryUpdate is reverted by hand,
and the 12-case matrix gives the same client totals and 1h counts as
main
|
||
|
|
a6f908ba58 |
gateway: a Gemini OpenAI-compatible stream that lost its finish_reason is ended by usage, or cut
Linka (Discord #feedback): Gemini's OpenAI-compatible API sends a whole
function call (its thought signature, the usage) in one chunk and the
finish_reason in the next. When the upstream hung up between the two,
magpie relayed a stream that ended with neither, and Pi threw the
complete call away ("Stream ended without finish_reason") and asked the
whole 160k turn again. On a Chat upstream only a failed read was a cut,
so a clean EOF there went on as a stream with no end.
That API counts the usage only on the generation's last chunk(s): the
Vertex fixture (testdata/vertex_openai_thoughts.sse) has it only beside
finish_reason, Linka's frames have it on the call chunk and the finish
chunk, and Google's forum and third-party docs say the same; no Google
doc states it. So for a Chat upstream that is Gemini's (geminiCompat,
saysItsEnd) and ended without a finish_reason:
- its last chunk carried usage: the generation was done and only the
finish_reason was lost. It is filled in (chatTail), "tool_calls" after
a call and "stop" otherwise: relayed, as one chunk before [DONE]
(written only if [DONE] hadn't gone); translated, as the reply's normal
end (tool_use for Claude Code), streamed and unstreamed. Recorded ok.
- no usage at its end: the reply was cut, and the client gets "the reply
ended before it was complete" (errEndedShort), as a Gemini stream's
finishReason is told (#1643, #1644): the relay's error chunk, the
translated stream's error, an unstreamed 502.
A failed read keeps its own "connection lost mid-reply". Other vendors'
Chat streams are unchanged.
Tests (gemini_compat_cut_test.go, Linka's frames): relayed, the call
with usage ends with finish_reason tool_calls then [DONE], text with
usage with stop, the call without usage with the error and no
finish_reason; a whole reply with or without [DONE] goes as it came
with one finish_reason; kimi-k3 with and without usage unchanged.
Translated: with usage one message_stop with stop_reason tool_use and
no error, streamed, and a 200 tool_use unstreamed; without usage one
error and no message_stop, and a 502 unstreamed.
Broken by hand, each red: the relay fill off (relay test: no
finish_reason), the streamed fill off (0 stops, 1 error), the
unstreamed fill off (502), usage ignored in chatTail.finish (every
no-usage case ended as whole, unstreamed 200).
Run: gofmt -l clean; GOOS=darwin/linux/windows go vet -tags nogui ./...
ok; go test -run 'TestGeminiCompat|EndedShort|TestStreamCut|
TestWellFormed|Sniff' ./internal/gateway ok.
Docs: gateway-routing.md says when the finish_reason is filled in.
Full suite: go test -tags nogui -timeout 45m ./... at base
|
||
|
|
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).
|
||
|
|
353464f161 |
gateway: a translated Anthropic or Responses reply that said nothing and counted no token is asked again, then fails, not completed (#2086, tensornull)
tensornull's Codex turn on an Anthropic-compatible proxy (baseAPI anthropic, claude-opus-5-5) ended as response.completed after 21s with no output: the route had status 200, no usage, no served model, no ttft. Codex took it as its turn's end (last_agent_message null) and didn't ask again. No usage and no served model mean the proxy never sent a message_start Claude would have (it counts the prompt and names the model), yet the stream said it ended (message_stop or a stop_reason), so 320af9858's replyEnds read it as whole and errEndedShort didn't apply. Now a reply from an Anthropic or Responses upstream (repliesCounted) that said nothing (no text, call, search or image) and counted no token at all (uncounted) is the empty reply #667 already handles for Gemini: asked again in place, then failed with "an empty reply (the model answered nothing; try again)", which Codex retries. Same in streamTranslated and the unstreamed translate path, for Responses, Messages and Chat clients. Claude's own empty end_turn (after a tool's result) counts its prompt and still completes, as does a Responses reply with usage and no output. Not changed: a reply passed through in its own protocol (Codex asking a Responses provider, Claude Code an Anthropic one) isn't read for this; the passthrough has no empty-reply rule at all, Gemini's included. Verified: - New stream_uncounted_test.go. TestUncountedEmptyReplyFails (message_stop only; pings then message_stop; message_start with no usage then a stop_reason; zero usage), TestUncountedResponsesReplyFails and TestUncountedEmptyReplyFailsEveryClient (Chat streamed, Responses and Chat unstreamed) all FAIL on the old code ("ended response.completed \"completed\", want response.failed", "status 200, want the empty reply's failure") and pass with the change. TestCountedEmptyReplyStillCompletes and the #1933 tests (TestWellFormedStreamsStillComplete, TestMalformed*) pass. - The full go test -tags nogui ./internal/gateway run failed only TestCodexHeadersReachKeyedRelay and TestStandaloneNativeAccounts, whose fake Codex backends answered response.completed with output [] and no usage, which the real backend never sends; their fakes now count tokens, and both pass. Run in a sandbox HOME with pinned caches; gofmt -l; go vet ./internal/gateway for darwin, GOOS=linux -tags nogui and GOOS=windows; GOOS=linux go build -tags nogui and GOOS=windows go build. - Not tried: the reporter's proxy or its real bytes (the report has none); the fixtures are the shapes its route record allows. Not run: the full go test ./... (only internal/gateway changed). |
||
|
|
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.
|
||
|
|
30869e35a7 |
usage, gateway: each request's log row says the service tier asked, the one each try was sent at, and the one the vendor said it ran at (#1784, zhenghaowen0967)
What changed
- usage.Record has tier_asked, tier_sent and tier_served, and the CSV gets
them as its last three columns.
- tier_asked is the client body's service_tier (Claude's speed fast reads
"fast").
- tier_sent is the tier the try's last request actually went out at. It
is noted in forwardOnce after every rewrite (a fast pick's priority,
Ultrafast turned to priority on a plan without it, buildResponses
dropping a tier the host can't take) onto the per-attempt wireAt. So a
handed-on try's own row has its own tier.
- tier_served is only what the reply said: service_tier at the top level,
in response.service_tier, or in an Anthropic usage. It is read by the
relay sniffer and by both translated readers, and is empty when the
reply says nothing. It is never filled in from the ask.
- Codex's own relayed sign-in (codex_backend) records the same three.
- /v1/magpie/route: Route.tier (asked), and each Try has tier and
tierServed. The session route has asked_tier, tier, tier_served and each
try's tier and tier_served.
- docs/reference.md (CSV columns) and gateway-routing.md describe them.
Why
zhenghaowen0967 asked that a request whose Ultrafast was sent as priority
to an account without it show that in usage, per try, without calling
the served tier confirmed unless the reply says so.
What was run
- TestTierRecordedPerTry. With Pro out, the first try is recorded
ultrafast, the second priority, and the final record has asked=ultrafast,
sent=priority and served empty while the fake doesn't echo. With an
echoing fake, served is what it said ("ultrafast", and "default" when
none was asked). It also checks the CSV columns, and the Codex relay path
with priority.
- TestUpstreamTierShapes covers the Chat chunk, Responses
response.completed, a Responses body, an Anthropic message_start and
message_delta usage, null, an over-long tier and non-JSON, as well as
bodyTier per protocol.
- Broke it by hand:
- with forwardOnce's noteWireTier removed, TestTierRecordedPerTry goes
red (route tries' tier empty, TierSent empty);
- with the sniffer's Tier line removed, TestUpstreamTierShapes goes red,
and so does the Codex relay case of TestTierRecordedPerTry.
- go test -tags nogui ./internal/gateway ./internal/usage ./internal/cli;
ledger_test's CSV expectations gain the three empty columns.
- gofmt -l; go vet on darwin; GOOS=linux and GOOS=windows go vet -tags
nogui.
Not done
- The served-tier fixtures are built from the shapes OpenAI and Anthropic
document, not from saved replies. Whether chatgpt.com's Codex backend
echoes service_tier wasn't tried against a real account.
- Bridges that don't go through forwardOnce (the Claude subscription,
Cursor's built-in) leave tier_sent empty.
- There is no price multiplier for priority/ultrafast and no GUI column.
|
||
|
|
2d3b33bb78 |
usage: time tool-only replies only with visible reasoning evidence
Revises #1463 after the hidden-reasoning inflation review. Keep answers separate, retain evidence in routes and cached ledger rows, and exclude sealed or summary-only reasoning even without a token breakdown. Sync the backend and both GUI formulas. Checked real WorkBuddy DeepSeek, Codex and Claude bridge responses in an isolated HOME; sanitized timings and failures are in docs/verification. Chromium/WebKit speed regressions pass (20 tests, five languages). New edge regressions and loop-order check pass under race repetition. Restoring the old formula or removing the hidden guard fails TestVisibleReasoningSpeed. macOS/Linux/Windows vet/build pass. Full-suite verification is recorded in the issue at this head; inherited proxy/Bun 1.3.14 failures are retained, with clean Bun 1.4.2 rerun in progress. No installed app replacement. Rebased onto main by yetone (#1463). Conflicts with main's Own/Retried/ Queued/Tries row fields, HandedOn and the Codex speed floors were resolved by keeping both. The packed row's ReasoningHidden bit was 64, which main has since given to block_price.go's swapKnown, and main's rowHandedOn took 128, filling the uint8: Flags is now uint16 and ReasoningHidden is bit 512 (rowReasoningHidden; #1874's rowOwnCost took 256), read back in row(). The docs/verification notes and their sample JSON are left out of the tree; they stay on the contributor's branch and the issue. Run after the rebase: go test -tags nogui ./internal/usage/ and the gateway's reasoning/speed/TTFT tests, ok. |
||
|
|
17c56ed245 |
gateway: a Gemini reply the upstream cut short ends in an error, not as if whole (#1643, ggbdpq)
What: a translated reply from a Gemini upstream (a custom provider's
Gemini URL, Vertex AI, Factory's generate route) or Code Assist
(Antigravity) whose stream stopped cleanly before the last chunk was
delivered to the client as a whole reply: finish_reason "stop" to a Chat
client, end_turn to Claude Code, 200 to a client that asked for no stream.
The cut check from #1562/#1563 (errEndedShort) only ran for Anthropic and
Responses, since Gemini chunks have no type and there is no [DONE].
Why this way: geminiEnds reads a candidate's finishReason (Code Assist's
inside "response"). The reporter's patch also counted usageMetadata as an
end, but Vertex AI sends usageMetadata on every chunk
({"trafficType":"ON_DEMAND"} until the last; the captured vertexThought
bytes), so a real Vertex stream cut after any chunk would still read as
whole. A chunk with no candidate at all (usage alone, a blocked prompt)
does end the stream: the reply said nothing, and #667's empty-reply path
still handles it (TestGeminiEmptyReplyIsAnError's "no candidate"). An
error chunk still reaches the client as the vendor's own error, because
failed is set and the cut check needs failed == "".
Run:
- New TestGeminiUpstreamEndedShort (Chat and Anthropic clients) and
TestGeminiNonStreamEndedShort use the captured Vertex AI reply cut
after "No, 391 is not prime because it is". Broken by hand (geminiKin
dropped from the two cut checks), both fail: the Chat stream ended
"stop", the Anthropic one end_turn, and the non-streamed one came back
200 whole. With the fix, the Chat and Anthropic streams carry the
error, the non-streamed request gets a 502, and the whole reply is
served as it came.
- TestGeminiEnds: the Vertex usage-only chunk is no end; finishReason,
Code Assist's wrapped one, and no-candidate chunks are.
- go test -tags nogui -count=1 -timeout 40m ./internal/gateway: ok (425s).
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway: clean.
Not run: no real Gemini/Vertex/Antigravity stream cut mid-reply. There is
no reporter's live case; the fixture is a captured Vertex reply cut by
hand. Code Assist is covered by the geminiEnds unit test only, not an
end-to-end Antigravity request. A relay that strips finishReason from
whole Gemini streams would now get the error; none is known.
|
||
|
|
e435fe00f1 |
gateway: a translated Responses reply the upstream cut short ends in an error, not as if whole (#1562, ggbdpq)
What changed: streamTranslated ended a translated reply in "the reply ended before it was complete" when an Anthropic upstream's stream stopped with no stop_reason and no message_stop; a Responses upstream's stream that stopped with no terminal event (no response.completed, response.incomplete, response.failed) was still finished as if whole, and the agent's turn ended a few words in with nothing to say why — the same reply the passthrough already tells apart (sniff.whole, #370). It now ends in the same error, asked again in place where the upstream goes on from a prefill, as an Anthropic cut is. The event that ends a stream is read by its type as the passthrough reads it (upstreamEnds, was anthropicEnds, already lastEvent), so a response.completed carrying no status field still counts as the reply's last. Chat (may end without [DONE] and be whole) and Gemini stay as the passthrough treats them. Run (review, yetone's session): TestResponsesUpstreamEndedShort passes; with the Responses half of the end check taken out by hand it fails ("a cut reply finished as whole", finish_reason "stop", no error). TestRelayStream*, TestRelayStop* ok. The full suite, gofmt and the cross-OS vets are in the series' last commit. Author's run: the red/green above, -race -count=20 on the relay-stop tests, gofmt, go vet and go build on darwin, linux, windows, go test ./... (TestOffline red on the clean baseline too, offline machine). Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> |
||
|
|
8424a004e2 |
gateway: a reply whose reasoning loops before it says anything is asked again once in place, not ended (cdredfox on X)
cdredfox (X, 2108799237324701897): WorkBuddy AI's DeepSeek v4 flash through
magpie often stops half way with "magpie ended this reply: the model's
reasoning was stuck in a loop ... ("OK." "Writing." "Now." "Producing."
"Let me output." ...)". That is the #1359 loop, found correctly; nothing
magpie sends causes it (12 direct runs on the real account, effort
high/max, temperature 0/1/unset, a 900-line file: no loop, the same
"OK. Writing." precursors at the tails), so the model does it on its own
now and then, and the agent's turn ended on it.
When magpie translates the reply into the agent's protocol
(streamTranslated: Claude Code, Codex, Gemini clients) and the loop is in
the reasoning, before any text or call and not on a continuation, the
try is let go and the same request asked again once (loopReasks), the
way an empty reply is (#667): the agent keeps the reasoning it has, the
next try's follows in the same stream. A loop on that try ends the reply
with the error as before. holdWriter.onLoop lets streamTranslated take a
trip before cutLoop ends the stream. A text loop, a loop after a text or
call, and a Chat stream passed through stay ended at once.
Run: go test ./internal/gateway (ok); -race on the loop and empty-reply
tests -count=3 (ok); gofmt; GOOS=linux,windows go vet. On old code
TestReasoningLoopIsAskedAgain and the updated
TestLoopEndsTheReplyOnEveryProtocol/TestLoopEndsWorkBuddysReply fail
(the vendor is asked once). Real account: a sandbox gateway in front of
a proxy signing for WorkBuddy AI (deepseek-v4.1-flash); the proxy
injected the reporter's units into the first real stream, the guard let
it go after 257 lines, the second real request answered, and the agent
got one whole message (Anthropic: message_stop, no error; Responses:
response.completed).
|
||
|
|
64179e7383 |
gateway: Anthropic's redacted_thinking and a thinking block signed with no text go through translation to Messages as they came, each block apart (#1445, XYenon)
What changed: the IR carries a vendor's sealed reasoning (Part.Sealed,
SealedBy) and says where a thinking block begins (KThinkStart) and where a
sealed one is (KSealed). parseAnthropic keeps redacted_thinking raw and
buildAnthropic writes it back raw. decodeAnthropic, the Anthropic encoder,
the collector and renderAnthropic keep each thinking block apart, with its
own signature, including one signed with no text (aBlock still writes
"thinking": "",
|
||
|
|
af1e477d83 |
gateway: a resumed reply to a model that takes no prefill is answered after it, not refused (#1447, Edward4226)
OpenCode Go's Claude models (over Anthropic Messages) refuse a conversation ending with the assistant's message, "This model does not support assistant message prefill. The conversation must end with a user message.", and Volcengine's Agent Plan does too, "The last message cannot be from the assistant for a model that does not support prefill". magpie took every Anthropic upstream to go on from a prefill, so both a client's own resume (Codex sends what it has of a cut reply as the last assistant message) and magpie's own continuation of a cut reply (#853) ended with that refusal. The refusal is about the model, so it is remembered for that provider, model and API in unfit (prefillRefused); the provider's other models, and every upstream that takes a prefill, are unchanged. - A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said, is asked again with a user turn after it ("Continue."), the conversation the refusal asks for, and so from then on: translated (forwardTranslated, whole and streamed) and relayed as is (passthrough, Chat and Responses: the Volcengine case). - An Anthropic client's prefill is its own ask and still gets the refusal as the vendor sent it. - magpie's own continuation is not asked of that model again, and the try it refused ends the reply with what cut it, as a reply that can't go on did before #853, not with the refusal of an ask the client never made. No user-turn continuation there: a re-answer spliced onto the part the client has is the garble continuation.go avoids. The thinking-block refusal in the same report (a signed thinking block with no text) is a separate fix, in its own commit. Tests (prefill_test.go), from the report's literal messages: the issue's Responses repro and a streamed Chat request to an Anthropic upstream (TestTrailingAssistantToNoPrefillModel, also checks another model keeps its prefill), Volcengine's refusal relayed on Responses and Chat (TestTrailingAssistantRelayedToNoPrefillModel), a cut reply (TestStreamCutOnNoPrefillModel), an Anthropic client's prefill (TestAnthropicPrefillToNoPrefillModel), userLastBody. With the refusal unrecognised (the old code's behaviour) the first three fail with the report's "UP: Upstream request failed: [invalid_request_error] This model does not support assistant message prefill…" / "…the reply didn't end with what cut it"; with the remembering removed they fail with "calls 4 … asked one again" and "calls = 2 … asked to go on again". Run: gofmt -l (clean), go vet -tags nogui ./internal/gateway on darwin, GOOS=linux and GOOS=windows, go test -tags nogui ./... under a scratch HOME with pinned caches (all ok). Not run for real: the owner's OpenCode Go key answers 403 "An active OpenCode Go subscription is required", and there is no Volcengine Agent Plan account. |
||
|
|
ea1c5d0457 |
gateway: Antigravity's 429 to a Claude Code / Agent SDK system prompt is the prompt turned away, not a quota, everywhere, and the agent gets 400 (#1425)
Antigravity answers the system prompt of Claude Code and the Claude Agent SDK (Claude Desktop's chats) with 429 "Resource has been exhausted" at whatever quota is left (#666). The detail text already said it was not a quota, but when Antigravity was the last one left (a direct model, the reporter's case) the route still fell through to failureOf: the try was counted 额度用尽 on the Routing page and in the account's tally, and the 429 went to the client, so Claude Desktop asked ten times over. What changed: - codeassist.go: antigravityTurnedAway(p, system, said) needs the Antigravity account, a Claude Code / SDK system prompt and the "resource has been exhausted" words. A real quota 429 ("You have exhausted your capacity ... reset after ...", QUOTA_EXHAUSTED) stays a quota and rests the account as before. turnedAwayStatus = 400 (the Anthropic and OpenAI SDKs retry 408, 409, 429 and 5xx, not 400); ledger ErrType "prompt_turned_away". - gateway.go: such a try is failPrompt (was failRefused in a group, and failQuota as the last), no rest, no usage re-asked, no passing retry, no auto reset. The last one left answers the agent 400 with the vendor's words and the hint; in a group the next member is asked, and if it fails only on a quota the agent is told the turned-away 400. The in-reply (stream error event) form is told the same way. - continuation.go / translate: the hint is appended to the in-reply form too, and the ledger row carries the ErrType. - routing.js: the hint joins HINTS, so the Routing page shows Antigravity's words as "It said: ..." and the explanation on its own line, translated in zh, zh-TW, ja and de (i18n.js). Tests (each fails on the old gateway.go/continuation.go/routing.js): - TestAntigravityTurnedAwayLastIsNoQuota (stream and not): 400, asked once, failPrompt, no rest, ledger 400 prompt_turned_away. - TestAntigravityTurnedAwayInsideTheReplyLast, TestAntigravityTurnedAwayThenAQuota, TestAntigravityQuotaOnAClaudeCodeTurnStaysQuota (scope: a real quota 429 still rests and reaches the agent as 429), TestAntigravityTurnedAwayHintIsTheRoutingPages. - gui/tests/routing-ag-turned-away.test.cjs: row status word, account tally, "It said" line and the hint line, in en/zh/zh-TW/ja/de. The real-quota fixture's words are from public reports, not captured from a real account. Run: gofmt -l internal/ (clean); go vet ./internal/gateway/ and GOOS=linux / GOOS=windows go vet -tags nogui ./internal/gateway/; go build ./..., GOOS=linux and GOOS=windows go build -tags nogui ./...; go test -tags nogui ./internal/gateway/ ./internal/gui/... under a scratch HOME with pinned caches (ok); GUI node tests (new test, routing-*, gui-de, gui-ja, gui-zh-tw, i18n-keys) in Chromium and WebKit. |
||
|
|
9bf20dbfc1 |
gateway: a model a relay serves with tools on Responses alone goes to the provider's Responses URL (#1308, Stevenzc888)
A custom provider with the same relay as its OpenAI compatible and OpenAI
Responses URL: magpie asks a GPT on a relay on Chat Completions first (Pi is
wired on openai-completions for it), and the relay turned Pi's tools away with
400 "gpt-6.1-sol requires Responses for tool calls; this account only supports
Chat Completions". wrongEndpoint didn't know that wording, so the 400 reached
Pi instead of the request going on to the Responses URL. "requires responses"
is now one of its phrases: the model is remembered as not served on that
relay's Chat, and the request (relayed as Pi sent it, or translated from
Claude Code's Messages) is spoken as Responses there, later turns at once.
Where the provider has no Responses URL, the error now says so
("gpt-6.1-sol is served on /v1/responses, which <provider> has no URL for")
rather than the relay's word alone (wrongAPINote reads the error body).
Red before: TestToolsThatNeedResponsesGoThere failed with the user's exact
error ("status 400: ... requires Responses for tool calls; this account only
supports Chat Completions"); TestTranslatedToolsThatNeedResponsesGoThere,
TestToolsThatNeedResponsesNameTheMissingURL and TestWrongEndpoint's new case
failed too. With the phrase but without the note, the missing-URL test fails.
go test -tags nogui ./internal/gateway ./internal/provider pass, and
./internal/agent as a non-root user (as root in Docker its chmod-based
aside_offline tests fail, unrelated); go vet -tags nogui ./internal/gateway
for darwin, linux and windows, and gofmt -l pass (linux, golang:1.26.8 in
Docker: this Mac's syspolicyd is pegged and new binaries hang at launch).
Not tried against the reporter's real relay.
|
||
|
|
b0d456c3b2 |
providers: an OpenCode Go or Zen provider saved with its chat URL alone sends GPT, Grok, Muse Spark and MiniMax on the API OpenCode serves them on, not chat, and "Model does not support this protocol" says which URL was asked (#1215)
The reporter's "OpenCode Go 1x" had only chat=https://opencode.ai/zen/go/v1 and no models.dev catalog (its native_endpoints were /v1/chat/completions for every model). Go serves each model on one API of three, as models.dev's per-model provider.npm says and OpenCode itself asks it (@ai-sdk/openai -> /responses, @ai-sdk/anthropic -> /messages, the rest chat), so with chat the only URL, gpt-6-luna, gpt-5.6-luna, grok-4.6/4.7, minimax-m2.7 and muse-spark-1.2/1.3-contributor had nowhere else to go and Go answered 400 on all three of magpie's entry points. - normalize fills in the other two of Zen's or Go's APIs (/v1 for chat and Responses, the root for Messages) and its catalog, only where the provider has none of its own (openCodeEndpoints); other hosts unchanged. - ListedAPIs reads the per-model API from the list of the gateway the URL is at (opencode-go for /zen/go, opencode for /zen), whatever catalog was saved: Go and Zen serve MiniMax M2.7 on different APIs, and an import at /zen/v1 could be saved with opencode-go's. - A wrong-endpoint error with no other API left now ends "(asked at <url>; <model> is served on /v1/responses, which <provider> has no URL for)". Verified: TestOpenCodeGoModelsGoOnTheirOwnAPI (gateway, all 3 client APIs x 5 models through the handler) and TestOpenCodeEndpointsFilledIn fail without the change with the reporter's exact "OpenCode Go 1x: Model does not support this protocol."; TestOtherRelayKeepsItsOneAPI and the relay cases keep other providers as they were. go test -tags nogui ./... green under a temp HOME; go vet, go build, GOOS=linux/windows builds. Real upstream: probed https://opencode.ai/zen/go/v1 with no key only (grok-4.7 is "not supported for format oa-compat" on chat and "format anthropic" on messages, passes to the key check on responses); no keyed request was made. |
||
|
|
8d3cf5f86e |
gateway: a Gemini reply that says nothing is asked again on the same account before it fails, so a long conversation that ends with only reasoning a few times running goes on instead of stopping the agent (#667, tianshuo886)
antigravity/gemini-3.8-flash, deep into a long Pi session, ended its turn with only its reasoning three times in a row; the request's own tries (3, 1s and 2s apart) ran out, Pi got "an empty reply" and stopped until the user typed continue. streamTranslated now asks such a reply again in place: once while the stream is still held (the request's tries and the next account still follow), up to twice once the agent has the stream, when nothing else would. A model that never answers is asked at most 6 times and still ends with the error. What reasoning the agent already has stays; the next try's follows it in the same message. TestGeminiEmptyRepliesAskedAgain (chat and Anthropic: three empties running end in "hello", one message_start; one that never answers errors within 6 calls) is new and fails without the change. go vet, go build (GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass. |
||
|
|
c5b57b9077 |
gateway, usage, gui: a relay's reply of tool calls ended "end_turn" or "tool_calls" goes on to the calls, a tool_use whose start carries its input keeps it, an Anthropic stream that just stops is an error, and every request says its protocol and the upstream's stop reason (蓝猫 on Discord)
蓝猫's custom Anthropic-protocol provider in front of Grok ended the agent's
turn a few words in with no error, where Alma on the same endpoint ran on.
Replayed from a fake upstream, three ways an Anthropic-shaped relay's
stream was read wrong when magpie translated it for an agent of another
protocol:
- a reply of tool calls whose stop_reason said end_turn, stop or OpenAI's
tool_calls was handed on as finish_reason "stop": the agent ended its
turn instead of running the calls. stopFromAnthropic takes tool_calls,
function_call, length and content_filter; collector.finish makes a
"stop" beside tool calls "tool".
- a tool_use block whose content_block_start carries its whole input,
with no input_json_delta after, lost the input (the call went with {}).
anthropicDecoder emits it, and skips deltas for that block after.
- a stream that ended cleanly with no stop_reason and no message_stop was
finished as a whole reply. streamTranslated now takes it as cut: asked
to go on where it can, else ended with "the reply ended before it was
complete", as the passthrough already did.
Each request now keeps the upstream's own stop reason (Usage.Stop /
usage.Record.stop: stop_reason, finish_reason, a Responses status), from
the passthrough's sniffer and the translated stream, shown as "Upstream
stop reason" in a request's details on Usage › Requests. Each row there
is tagged with the protocol it was sent upstream in, "Chat → Anthropic"
when translated, told from its endpoint, so older rows have it too; the
details say Protocol. en/zh/ja/de, no left border, no select, a click
moves nothing.
relay_stop_test.go's four tests fail without the change (finish_reason
"stop" for tool calls under end_turn/tool_calls/stop, arguments "" for a
whole-input start, a cut stream finished "stop", no stop recorded) and pass
with it; the passthrough case sends "data:" without a space and CRLF.
ledger-protocol.test.cjs passes in Chromium and WebKit, en and zh.
go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test
-tags nogui ./... under a temp HOME pass.
|
||
|
|
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
|