1ccacad63281094de8a3372d5a507d38f9969e5c
28
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ece12b370d |
search: TinyFish is a built-in search API (Niapyaya on X)
Niapyaya asked on X for TinyFish (tinyfish.ai) among the search APIs. TinyFish has a plain Search API beside its browser agents, so it is added as vendor "tinyfish", following Yuanbao Search ( |
||
|
|
5506c84437 |
gateway: a skill's body reaches the run with its Skill call's result
Claude Code answers a Skill call with "Launching skill: <name>" and sends the skill's SKILL.md after the results, as a text block headed "Base directory for this skill: …". Since |
||
|
|
f8987ce617 |
gateway: Qoder 1.1.82's requests find their session in Qoder's own files
qodercli/qoderclicn 1.1.82 (11-03) stopped sending session-id to a
provider of the user's own, and nothing else in a request names the
session (coderlee233 on Discord). Its requests were recorded with no
session: the Sessions page lost the conversation's title and showed each
title and suggestion side call as a row of its own.
A request from Qoder or Qoder CN (by its agent token) on this computer
that names no session is now matched against Qoder's session files
(sessions.QoderDir/projects/<project>/<id>.jsonl and its subagents'
files): the session whose typed prompts (user lines with humanInput /
origin.kind human) appear most in the request's user text wins, the file
written last on a tie. Qoder's <system-reminder> blocks are left out. A
side call (no tools) no file matches yet is held up to 600ms, since the
first title is asked ~0.1s before Qoder writes the file. The id found
goes on the request as session-id, the header 1.1.81 sent, so it is
grouped and titled as before. A request that names a session (older
Qoder's session-id, X-Magpie-Session) is left as it came. Files are read
incrementally; a half-written last line waits for the next read.
Run (on mote, rebased on origin/main
|
||
|
|
01de489de1 |
search: a ChatGPT account searches for another model by the backend's own search (lucy_85908)
A third-party model in Codex (DeepSeek, MiniMax, ...) had its web searches made by asking gpt-6-luna on the Codex account to search through /responses. A ChatGPT account now searches by the ChatGPT backend's /alpha/search, the request Codex's web.run sends by itself with no model turn (codex-rs ext/web-search): one search_query, the account's small model in "model", allowed_callers ["direct"], and external_web_access from the client's web_search tool (#5018: Codex's "cached" sends false; live by default). The output's pages are read by their 80-dash rule and ref_id; the private-use citation marks are dropped. Measured on a real Plus account (2026-11-03, token not refreshed): 151 alpha/search calls left the 5h window at the same percent, ~1.5-2.2s each; 51 searches by gpt-6-luna took 0% -> 1% of it, 7-15s each, ~9-17k tokens in (40 of them: 414,585 in, 10,313 out). The backend answered the same for any "model" (deepseek-v4 too) and any max_output_tokens. - Automatic (and searchInTurn) picks the backend's search for a ChatGPT account; Settings > Web search offers "<id>/@search" as "its web search". "<id>" and "<id>/<model>" saved before still search by that model, so a user's pick is unchanged. - When the backend's search fails, the account's small model searches (codexSearchBy). - Codex web.run's own search for a non-ChatGPT model (alphaSearchHere) and a Responses request's web_search tool pass their mode on. Run at this head (rebased on origin/main), on mote: - go test ./internal/gateway/... ./internal/gui/ ./internal/agent/ -timeout 45m: gateway and agent ok; gui red only on TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 on mote). After the rebase: the gateway's search tests again ok. - searcher-pick.test.cjs: 22/22, chromium + webkit, en/zh (+ the label is in zh, zh-TW, ja, de). - gofmt -l clean; GOOS=linux go vet gateway, provider; GOOS=windows go vet gateway, gui. - Whole GUI suite on the Linux box (wsl-run): not finished when pushed; its reds so far are WebKit pages this doesn't touch (add-provider, API key palette, Routing headers, click-scroll, Codex resets). Broken by hand, each red: the Automatic switch (TestCodexSearchesWith ItsCheapModel, TestChatGPTAccountSearchesByItsWebSearch), the responses.go mode (TestResponsesWebSearchModeKept), the body's mode, the fallback, and the picker option (searcher-pick). Not tried: a real search through magpie in a sandbox (the request shape was tried by hand against the backend); an account out of its allowance (does alpha/search still answer?); the model fallback still searches live when Codex asked cached. Suggested by lucy_85908 on Discord. |
||
|
|
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 |
||
|
|
d614f21721 |
gateway: a HEIC photo goes to the vendor as JPEG, or PNG with alpha (qikamatata on X)
Pi and Pi Desktop send an iPhone photo dragged in as image/heic, and
DeepSeek flash on WorkBuddy (a plugin's fetch) turned it away; most
vendors take JPEG, PNG, GIF and WebP only.
What: heicAsJPEG (heic.go) runs at the top of Server.serve, after
offAsNone, so every route below sees the converted image: a provider's
own, a plugin's fetch, the describer, every translation. count_tokens
does the same. It walks images through walkImages, the one image walker,
so it covers Chat image_url (string or object), Responses input_image,
Anthropic image blocks and Gemini inlineData, tool results included. It
goes by the bytes (ftyp + an HEVC still's brand), so a HEIC labelled
image/jpeg or image/png is converted too, and a JPEG labelled heic is
left alone. Other fields of the block (detail, cache_control) are kept.
Transparent images go as PNG, opaque ones as JPEG q90.
Cost: a body with no "image/hei" and no base64 ftyp mark ("eXB" + 5
chars, at the same place in any base64 that starts at the file) is not
walked. Caps: 48 MB of base64, 50 MP, the long side written at 4096 px,
one decode at a time, 30 s wait (a late result is cached for the next
turn), a 64 MB / 32 entry cache by sha256, since agents resend a
conversation's images every turn. Any failure, panic included, leaves
the image as it came. Measured on mote (M5 Pro): 12 MP 0.44 s, 24 MP
0.86 s, 48 MP 1.6 s / ~1 GB held, freed at once with FreeOSMemory.
Why gen2brain/h265 v0.2.4: pure Go (release builds are CGO_ENABLED=0),
MIT, no dependencies, SIMD on amd64 and arm64, maintained (latest
2026-10-29). Not chosen: gen2brain/heic (wazero WASM or a libheif dylib
through purego), jdeng/goheif (cgo libde265), OS converters (Windows
needs the paid HEVC extension, Linux tools are often missing).
Tests (heic_test.go, fixtures made on mote with sips, 1.6 KB each):
12 shapes converted with their kept fields, pixels kept, 7 non-HEIC
cases byte-identical, a cut file / a panicking decoder / a timeout go
as they came, and a plugin's fetch (fake plugin, new FAKE_SEES image
model) gets JPEG on /v1/chat/completions and /v1/messages.
Run at this tree (
|
||
|
|
9551fadcb4 |
gateway: reasoning streamed with no count in its usage is marked unknown, not read as none (#4545)
A reply whose stream carried reasoning (reasoning_content, Anthropic thinking deltas) while its usage counted no reasoning tokens was recorded Reasoning 0, ReasoningHidden false: the same record as a reply that never reasoned, and a tool-only one was timed with its reasoning counted as answer. hidesReasoning now takes the usage's reasoning count and marks such a reply ReasoningHidden, the record's existing "the stream doesn't tell how much it reasoned". Reasoning stays the vendor's 0; nothing is estimated, so no new field or Flags bit (rowReasoningHidden 512 is the one it already uses). Who does this, from real bytes and docs: Anthropic's Messages usage has no thinking count at all (output_tokens includes it), so every visible Anthropic-protocol thinking reply was this case. The fixture testdata/reasoning-uncounted-deepseek-anthropic.sse is DeepSeek's Anthropic endpoint as it came on 2026-10-31 (deepseek-v4-pro, thinking on): 33 thinking deltas, "391", usage output_tokens 35 and nothing else. The owner's usage.jsonl has 12 kiro claude-haiku-4.5 rows with paced first_reasoning_ms and reasoning 0, the same case through a plugin. DeepSeek's Chat endpoint does count (completion_tokens_details), and those rows are unchanged. No captured Chat vendor omits the count; the Chat subtests are built from the shape, not a capture. Siblings: Responses, Gemini and Code Assist were already marked hidden whenever reasoning streamed (summaries). The Codex backend's two calls pass its count too (no change for Responses; its call record now reads the count after the sniffed usage is added). The Claude subscription bridge counts thinking from the CLI and is unchanged. What changes for a reader: Decode already leaves a hidden reply with no text untimed, so a thinking + tool-call reply with no count tells no speed now; one with text is timed as before (whole output from first content). The GUI's decodeOf/ledDecode read the same flag; no GUI code changed. Run on mote at base |
||
|
|
0804f2d97d |
search: Tencent Cloud's Yuanbao Search (wsa) is a built-in search API (plugins#509)
chenjiangzi asked for Tencent Cloud's WSA SearchPro (元宝搜索). It is added
as vendor "wsa", following Doubao Search (
|
||
|
|
dca3e2d716 |
search: Doubao Search (Volcengine) as a search API (CyberCaius on Discord)
CyberCaius asked on Discord #help (10-30) for Volcengine's Doubao search under Settings › Models › Search APIs, or a custom API address. Volcengine's Doubao Search Custom (豆包搜索 Custom版, once 联网搜索 / 融合信息搜索, docs.volcengine.com/docs/networked-search/networked-search, the same page as volcengine.com/docs/87772/2272953) can now be added with its API key: - provider.SearchVendors: volcengine, "Doubao Search (Volcengine)", at https://open.feedcoopapi.com, keys at console.volcengine.com/search-infinity/api-key, after DeepSeek. The GUI takes its vendors from SearchVendors, so it shows in the Search API picker with its Get a key link and base URL field; no GUI file changes. - askSearchAPI: POST /search_api/web_search, Bearer key (the default, as the docs and volcengine/mcp-server's askecho_search_infinity send it), body {Query, SearchType: "web", Count: searchHits, Filter: {NeedUrl: true}}. The query is cut to the 100 characters the docs allow. NeedUrl leaves out its 火山如意 cards, which have no URL to cite. - readVolcSearch reads Result.WebResults: Summary as the page's text (the docs recommend it for models; Content is the whole page, Snippet ~200 chars "only for list display"), Snippet when there is no Summary, PublishTime as the page's age, a 1970-01-01 time (its image example's stand-in) as none, and a result with no Url left out. - volcSearchError: its errors are in ResponseMetadata.Error, a code the docs list, and the docs don't say the HTTP status, so the code decides: 10401/10403/10409 rest the key as turned away (403), 10406/10408/ 10410/10412 (free searches spent with none paid, no plan, plan spent) as out of credit (402), 700429 as rate limited (429). Any other code is a plain error, a 200 carrying one included. The key is masked in the error as for every vendor. - A custom address: every search API already takes a base URL (#1580, the field under the key in Settings, url= in the CLI), so an endpoint that answers as Tavily, SearXNG, Brave, Exa, Firecrawl, You.com, DeepSeek or now Doubao Search does can be set there. There is no common format across the vendors (each has its own path, body and reply), so no separate "custom" vendor was added. - Siblings: CLI usage (main.go, search_cli.go's api list and empty-state hint), README.md, README.zh-CN.md, gateway-routing.md's path list and refusal paragraph. The test's reply is the docs' own web-search response example, byte for byte (testdata/volcengine_web_search.json); its error replies are the docs' error example with its "// 该字段为错误码" note taken out (not JSON). Not tried against the real API: no Volcengine search key in this run. Run (worktree on origin/main |
||
|
|
6e331afb45 |
gateway: Claude Desktop's model check goes to the model it names; a relay gets a cache key
CyberCaius on Discord: Claude Desktop said at every start
'Gateway rejected model "magpie-<n>.anthropic.claude-haiku-5-5[1m]"
(HTTP 400)', body "Arouter: prompt_cache_key is required". His
Routing page showed leee/claude-haiku-5-5 served by AnyRouter's
gpt-6.1-sol, with a "." prompt.
Two causes:
- Desktop checks a gateway model as it starts (and from its settings'
Test) with {"model":<it>,"max_tokens":1,"messages":[{"role":"user",
"content":"."}]}, on the shortest id with haiku in it (lWt, JUt and
YT in its app.asar, 2.7032, read from the installed app). desktopTurn
took that small tool-less request for a session title and sent it to
the session's model, AnyRouter's gpt-6.1-sol, so a failure there read
as the haiku rejected. desktopProbe now knows the check, and it goes
to the model it names. Titles still go to the session's model.
- A request translated from an Anthropic client to a Chat or Responses
upstream never had a prompt_cache_key, and AnyRouter refuses one
without. ownCacheKey/cacheKeyOf give it one per conversation (a
hash, in a UUID's shape, of the client's session header, else of its
first user message; it names nothing of magpie) on OpenAI's API with
a key and on providers the user added by address. Presets, signed-in
accounts, plugins, Bedrock and Vertex get nothing new, nor does a
provider whose extraBody (#1604) names prompt_cache_key: the user's
value is the one sent. An upstream whose 400 names the field is asked
again without it and not sent it again (the existing path for Codex's
key); any other 400 is not asked again for magpie's key, so an
unrelated refusal is tried as often as before.
What is sent changes, on purpose, for those providers: the translated
bodies in testdata/upstream_bodies (anthropic-to-chat,
anthropic-to-responses, responses-to-chat and the large one's hash) now
carry the key.
Unticking AnyRouter's Claude models had no part in it: nothing went
to them. The probe was rerouted to the session's pick.
Tests: TestClaudeDesktopProbeAsked (a fake Anthropic "leee" and a fake
Chat relay that answers AnyRouter's 400 without a key: turn, probe of
the haiku alias, title, second turn keeps the key), TestDesktopProbe,
TestOwnCacheKey (scope, extraBody's key left to the user, and a relay
refusing the field asked twice once, then once).
Run (mote):
- go test -tags nogui ./internal/gateway/ -run the new tests,
TestUpstreamBodiesUnchanged, TestExtraBody*, TestOtherBadRequestNot-
AskedAgainAtLow, TestTranslatedEffortMinimalRefused, TestTooFew-
TokensSaidWithSigns, TestHighRiskErrorFallsBack, TestVertex*Retries*
and every *CacheKey* test: ok
- a full ./... run of the first draft at
|
||
|
|
68ee4117af |
gateway: a Gemini model's untyped tool schemas go typed (Vertex refused cua-driver's drag)
kthink on Discord: dsh with cua-driver's MCP tools on Command Code's
google/gemini-3.8-flash (the commandcode plugin), every request 400
INVALID_REQUEST from Vertex: "`mcp__cua-driver__drag` functionDeclaration
`parameters.target` schema didn't specify the schema type field."
cua-driver's drag schema before cua's #4888 has target as an anyOf of an
untyped oneOf and null, and scope a const with no type. Command Code's
gateway turns JSON Schema into Vertex's Schema object, whose type is
required, and an untyped node stays untyped.
geminiToolTypes (forwardOnce, so plugin requests too) is keyed on the
model id (last '/' segment starts with "gemini"), not the provider:
each untyped schema under tools' function.parameters / parameters /
input_schema gets the type its enum/const, keywords or branches say,
null left out; {} or a description alone is a string, a tool root an
object. Mixed-type unions, unresolved $ref/unions and anything under
not/if are left as they came. Written in place after the brace, so the
rest of the body is unchanged. withTypes no longer writes a trailing
comma into an empty {} (it produced invalid JSON there).
Google's own Gemini API / Code Assist (parametersJsonSchema) and
Antigravity (plainSchema) bodies have no such tools and are not walked.
Run at this tree, rebased on origin/main
|
||
|
|
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. |
||
|
|
d155ab1619 |
gateway: a relayed Responses item keeps the id it was added with, so Codex on Copilot shows a message once (echo_ts on Discord)
echo_ts (v0.1.1293, Codex desktop, a GPT model on GitHub Copilot): each commentary paragraph was shown twice; fine around v0.1.1280. Cause: since |
||
|
|
fc78eb5f6b |
gateway: ClinePass's upstream is read from provider_metadata.gateway.routing.finalProvider (#2847, smart-lty)
ClinePass (api.cline.bot) names the provider that answered only in a
Chat choice's provider_metadata.gateway.routing.finalProvider: under
delta in a stream chunk, and under message in a single body. upstreamOf
read only a top-level provider, message.provider and response.provider,
so the Routing page's 上游 column, the request log and the usage ledger
showed nothing for ClinePass.
upstreamOf now also reads finalProvider at those two places, and nowhere
else. A choice's content belongs to the model. providerAttempts inside
routing lists every provider that was tried, not the one that answered.
The cheap pre-check now passes a chunk that carries only
"finalProvider".
Tests:
- TestUpstreamOfClinePass checks:
- the real chunk gives deepseek;
- the same chunk as one body (message) gives deepseek;
- content, tool_call arguments, providerAttempts alone and an
object-valued finalProvider give "";
- a top-level provider still wins.
- TestClinePassUpstreamRecorded serves the real stream through the
Handler on /v1/chat/completions and on /v1/messages (translated). It
checks that the route, the try, Recent() and the usage ledger all say
deepseek.
The fixture testdata/clinepass_stream.sse is a real ClinePass stream:
api.cline.bot, deepseek/deepseek-v4.1-flash, captured 2026-10-02 in the
MIT-licensed wkeking/clinepass-channel-monitor
(internal/channellog/testdata/plain_success.log). It is not the
reporter's own bytes; #2847 has none.
What was run at
|
||
|
|
b6fae8efd8 |
gateway: an advisor magpie leaves out takes its instructions and tool_addition with it, so the model no longer calls a tool it hasn't got (JackChou on Discord)
JackChou: "claude code 使用 advisor 返回找不到对应工具". Claude Code 2.1.300
(its request read from a fake ANTHROPIC_BASE_URL in a sandbox HOME, with
--advisor and a fake key) declares the advisor as the server tool
{"type":"advisor_20260301","name":"advisor","model":…,"defer_loading":true}
and also puts it in the conversation: a {role:"system"} message whose text
ends in "# Advisor Tool … call advisor BEFORE substantive work", and a
{"type":"tool_addition","tool":{"type":"tool_reference","name":"advisor"}}
block.
|
||
|
|
299498dec1 |
gateway: a compaction magpie summarises itself tells the provider it is a local one, not Codex's remote compaction_v2 (#2352, yhxwyzm; #1171, tcxp001)
Codex Desktop 26.1007 marks a compaction for a provider named "OpenAI"
with a compaction_trigger item and turn metadata saying
compaction.implementation "responses_compaction_v2", in both
client_metadata["x-codex-turn-metadata"] and the X-Codex-Turn-Metadata
header. When 原生压缩 is off, magpie replaces the trigger with its own
summary prompt and sends tools [], but it forwarded the metadata
unchanged. The request then said "remote compaction" and carried no
trigger, a shape Codex never sends. Codex 0.162.1, captured in a sandbox
against a provider not named OpenAI, says "responses" for the summary it
asks for; under the name OpenAI it sends the trigger with
"responses_compaction_v2". Neither the #292 test nor the #1171 test
carried client_metadata, so neither saw this.
codexInputAs (both the ChatGPT-backend path and /v1/responses) now sets
implementation to "responses" in the body's turn metadata, and
codexCompact does the same in the header. Every other byte of the
metadata is unchanged, including mcp_attribution and
guardian_credits_requested. With native compaction on, the trigger and
its metadata still go as Codex sent them.
The fixture testdata/codex-26.1007-compaction.json uses the reporter's
own bytes from the Routing page bodies attached to #2352 (on.txt and
off.txt): four history items, among them an mcp__fastctx call with its
list output, and the client_metadata as sent. The fake upstream refuses
with the relay's words when a request says responses_compaction_v2 and
has no trigger.
Not verified against Anyrouter itself. The reporter says the error text
is the same with native compaction on, and there magpie sends the
trigger as an OpenAI-named Codex would; that path is unchanged. If the
relay doesn't take remote compaction at all, this commit doesn't help
there.
Run (worktree on origin/main
|
||
|
|
d46fb1e590 |
gateway: a tool's strict an upstream refuses is asked again without it, and left out after (#1980)
OpenCode 2 sends "strict": false on every tool through @ai-sdk/openai-compatible. thonatos's custom provider turned it away with 400 "Unsupported Chat Completions API field: tools[0].function.strict", which magpie relayed, and OpenCode ended the session. The reporter's @ai-sdk/openai workaround worked only because magpie's Responses->Chat translation leaves strict out. What changed: in passthrough's retry loop, a 400 that names a tool's strict as unsupported, unknown, unrecognized, not permitted or extra_forbidden (toolStrictRefusal, strict_refused.go) is asked once more with strict deleted from Chat tools[].function and Responses tools[] (namespaces recursed), and marked for that provider and API (toolStrictRefused, markUnfit). The next request leaves it out before sending. An upstream that never refused it still gets strict, which the ChatGPT backend needs (#383, TestResponsesToolStrict unchanged). The fix is in the gateway, not in what magpie writes to opencode.json: any client's strict reaches the same refusal. What was run: - Real OpenCode 2.0.25 in a sandbox HOME against a gateway built at the old code and a fake upstream refusing strict: the reporter's exact error ("custom-provider: Unsupported Chat Completions API field: tools[0].function.strict", opencode rc=1). With this change: answered. - TestToolStrictLeftOutWhereRefused with the two recorded OpenCode 2.0.25 requests (Chat and Responses, 12 tools each): first request carries strict, the retry none, the next turn none at once (3 upstream requests), another provider still gets strict. - Broken by hand: without the retry branch both subtests get the 400; without the pre-send check, "next turn: 200, asked 4 times". - TestToolStrictRefusalWordings, with negatives (an invalid schema, an invalid type for strict, an unsupported 'store'). - gofmt -l; go vet darwin, linux -tags nogui, windows; go test -tags nogui ./internal/gateway -count=1 (ok, 324s). Not tried: the reporter's actual upstream vendor (not named in the issue); the Responses refusal wording is assumed to match the Chat one. A translated request (Chat->Responses) that an upstream refuses for strict isn't retried by this. |
||
|
|
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. |
||
|
|
1e080cc7e7 |
gateway: the saved Anthropic-to-Responses body carries the image's detail auto that the commit before it sends (#1474)
TestUpstreamBodiesUnchanged (
|
||
|
|
403f3845e2 |
gateway: Codex's spawn_agent names every model also when Codex hands it to the lead through a tool search, as it does on 0.162 (Gearclickist on Discord)
Gearclickist, after v0.1.1214: the lead still saw only five models for
its subagents. v0.1.1214 (
|
||
|
|
5b87087423 |
gateway: Qoder's queue (code 10605) is a 503 with Retry-After for users still on the built-in, not "sign in again" (plugins #98)
What changed: qoderFailure (internal/gateway/qoder.go) read every 401/403
as "Qoder: the sign-in lapsed — sign in again". It now reads Qoder's own
code first, whatever the HTTP status, the way Qoder.app's client does
(the QoderErrorCode table in its qoder-agent-sdk worker,
qoder-worker-runtime.obf.mjs) and as @magpie-community/opencode-qoder-auth
0.2.14 does (plugins f573cfd):
- 10605, or a queue state (in "queue" or in the message as JSON) with
isQueued true or serviceAvailable false: 503 "Qoder is busy for
<model> (this plan's queue: <tier>); try again in <n>s", with
Retry-After from retryAfterSeconds rounded up (30s when absent).
- 110, 112-119, 122 (usage or credits used up): 429.
- 406, 416, 430, 80411, 80412, 100400, 100401, 100403 (refusals of the
request; Qoder's table has no 100402): 400 with Qoder's words.
- 105 or no code on a 401/403: the 401 "sign in again" as before.
Both the HTTP status path (askQoder) and the in-stream statusCodeValue
path (decodeQoder) go through it. Event gets a Wait field for a KError,
and relayStatus's fail and serveQoder's first-round failure send it as
Retry-After (retryAfterOn); askQoderWait is askQoder that also returns
the wait, and askQoder (the round searchRounds uses) wraps it. Zed and
Command Code share relayStatus and never set Wait, so they are
unchanged.
Why: a real Qoder trial account had every chat answered
403 {"code":"10605",...} (Qoder's model queue) and was told to sign in
again, which can't help. The plugin was fixed in 0.2.14 for moved users;
this is the same fix for users still signed in through the built-in. The
built-in never marked an account lapsed from a refused chat (only from a
refused refresh, provider/qoder.go), and now a 10605 doesn't even return
the 401: the gateway's busy() reads the 503 as busy (failOther), so a
group asks it again after the pause, no shorter than its Retry-After
(noteBusy/retryAfter), and the agent gets the Retry-After too.
Run:
- New tests in internal/gateway/qoder_busy_test.go, the fixture
testdata/qoder_queued_10605.json taken byte for byte from plugins #98:
TestQoderQueuedIsBusy (serveQoder, HTTP 403 and in-stream 403, stream
and not: 503, Retry-After 30, the busy words, no "sign in", busy() true,
retryAfter 30s), TestQoderQueueWait, TestQoderErrorCodes. With the old
401/403 rule put back at the top of qoderFailure all three FAIL
("got 401 ... want 503"); with retryAfterOn made a no-op
TestQoderQueuedIsBusy FAILs on Retry-After "" in both subtests. Restored,
they pass.
- go test -tags nogui ./internal/provider ok (458s). go test -tags nogui
-timeout 40m ./internal/gateway (the default 10m ran out under the
machine's load): every test passed except TestCodexHeardWithinItsIdleTimeout,
which failed with the body #1800 already describes (Codex got member
a's server_is_overloaded under load); it passes 10 of 10 alone
(-count=10) and is on the Codex passthrough path, which this doesn't
touch. Noted on #1800.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./... ok; go build, GOOS=linux go build -tags nogui,
GOOS=windows go build ok.
- Not run: the rest of go test ./... (only the two packages touched);
a real 10605 through the built-in (the queue had reopened when the
plugin shipped); no Qoder parity test exists in
internal/gateway/plugin_*_test.go to extend.
|
||
|
|
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
|
||
|
|
cfa280a6c2 |
provider, gateway, gui: You.com can be added as a search API, with no key for its free search or with a key (#1626, brainsparker)
A model's web search, when no provider can search, goes to the search APIs the user added; each of them needed a key except a SearXNG of the user's own. You.com answers with no key too, so it is one a user can add in one step. - provider: SearchVendor has KeyOptional (You.com, SearXNG); Ready and check let a vendor that has it go with no key. You.com is listed between Firecrawl and SearXNG, its keys at you.com/platform. - gateway: with no key, GET https://api.you.com/v1/agents/search?query= &count=6 (YouFreeSearch); with a key, POST https://ydc-index.io/v1/search {"query","count"} with X-API-Key, as its API reference says; with a base URL of the user's own and no key, GET <url>/v1/agents/search. Both replies are read from results.web then results.news: the snippets, else the description, and page_age. You.com's errors are a code beside a message, so the message is what the user is told (a 402 "prepaid credit balance has been depleted" is a refused key, the next key or API is asked). Its requests carry the User-Agent tag You.com asked for, "youdotcom-integration/yetone-magpie", after magpie's own. - gui: Settings › Web search lets You.com be added with the key empty, its placeholder saying so (zh, zh-TW, ja, de). - cli: magpie search add you [<key>]; the help lists it. New network addresses: api.you.com (keyless) and ydc-index.io (keyed), asked only when the user adds You.com, with the search query only. Checked against the real service on 10-11: a keyless GET to api.you.com/v1/agents/search answered 200 (testdata/you/free_search.json is that reply, cut to 3 hits), and a real run through askSearchAPIKeys returned 6 pages. ydc-index.io/v1/search answered 402 with no key (testdata/you/keyed_402.json, real bytes) and 403 to a made-up key. The keyless endpoint isn't in the API reference; You.com's own docs pages for third-party tools describe it (free, 100 a day per address, no account), as LiteLLM, ragflow and AnythingLLM use it. you.com/terms bars automated use of its website and apps, not the API. The keyed request shape is from its API reference only: no key with credit was tried. Run: go test -tags nogui . ./internal/gui/ ./internal/provider/ ./internal/backup/ green; ./internal/gateway/ green but TestTurnDoneSaidAtTheTurnsEnd (#1629, fixed in its own commit); search-api.test.cjs in Chromium and WebKit, en/zh, 980/420px green; gui-ja, gui-de and i18n-keys green; gofmt -l; go vet -tags nogui for linux, windows and darwin. The tests make no network request (a stub RoundTripper). Without the change, TestYouSearch, TestYouKeyOutOfCredit, TestYouNeedsNoKey and TestSearchCLIYouWithoutKey fail, and with the GUI's keyOptional check taken out search-api.test.cjs fails in all four Chromium runs (Add sends nothing). |
||
|
|
ae70d8eac8 |
routing: a group's rule can hold by the folder the agent works in (Cario0x on X)
Cario0x on X asked to route by the project being worked on. A group's rule now has a "folders" condition: it matches when the request's working folder is one of the listed folders or inside one. It combines (AND) with the existing conditions: tokens, images, intent, time, agents and quota. - gateway/workdir.go reads the folder each agent states in its own request: - Claude Code: "Primary working directory", including "(was …)" after a move. - Codex: <environment_context><cwd>. - Pi: <cwd>. - OpenCode: <env> "Working directory". The last one stated wins. Assistant text and tool results are ignored. A request that states no folder matches no folder rule: unknown, never empty. - provider/rulefolder.go matches a folder only at a path boundary. - ~ is the home folder. - C:\x is the same folder as /mnt/c/x, and \\wsl$\Distro\x as /x. - Case is ignored on macOS and Windows, and always for a drive. - A rule's folder must be a whole path. Pause rules can't have folders. - The trace's RuleHit.Folder makes the Routing page say "The agent works in …". - GUI: an "in folder" condition in the group editor, hidden on pause rules. Strings in zh, zh-TW, ja and de. - CLI: `magpie group rule add … folders=~/oss,"~/My Project"`. The TUI shows the condition. - Docs: docs/subsystems/gateway-routing.md and site start.html (en, zh, ja). Fixtures are real requests from Claude Code 2.1.296, Codex 0.162.0 and Pi 1.1.0, run in a sandbox from a folder named "a&b <c> 中文" or "My Proj", with the sandbox path replaced. Run at this head: - go test ./... green. - gofmt -l clean. - go vet green for darwin, GOOS=linux -tags nogui and GOOS=windows. - GUI routing-folder.test.cjs: chromium and webkit, en, zh, zh-TW, ja and de, 1100px and 390px (no horizontal scroll). It fails on the old routing.js. - Related routing, group and i18n GUI tests: 85/85. - Full GUI suite: 5611/5631 under --test-concurrency=6. Rerun alone, every failure passes except: - skill-install-agents-all (chromium, 420px), which is red on origin/main too: #1554. - The menu-scroll track flake, which flakes on main as well: #1550. - e2e: a sandbox HOME, a dev build and fake upstreams, with real Claude Code 2.1.296 (`claude -p --model group/fd`). - From proj/acme/web, rule 1 matched and the request went to kb. - From proj/acme-old, no rule matched and the request went to ka. The trace and UI showed the folder. |
||
|
|
ca0867e412 |
gateway: a Grok model's 2500.0 in a call's arguments reaches the agent as 2500, on every route and protocol, deltas and done alike (#1431, timonwong)
Grok's models (grok-4.6, grok-4.7) write a whole number in a tool call's
arguments with a fraction of zeros. Codex reads exec_command's
yield_time_ms and max_output_tokens as u64/usize and write_stdin's
session_id as i32, though their schemas say "number", and serde turned the
whole call away ("failed to parse function arguments: invalid type:
floating point `2500.0`, expected u64 at line 1 column 77"; `17277.0`,
expected i32), so the turn stopped at its first command. Reported 11 of 11
turns through a sub2api relay in front of grok-4.6 and grok-4.7.
What changed (grok_integral.go):
- grokModel/grokServed: a Grok model is one whose id, as magpie names it
or as it is sent upstream, has a last `/` segment beginning "grok"
(relay/grok-4.6, x-ai/grok-4, the plugin's grok-4.7).
- wholeNums: a streaming scanner over the arguments' JSON text. A number
written with a fraction of zeros and no exponent loses the fraction
(2500.0 -> 2500, -3.00 -> -3, [1.0,2.0] -> [1,2]). Strings, keys, other
fractions (2.5, 2.50) and exponents (1.0e3) stay as written. It holds
only a run of ".0…" until the next byte, so arguments cut into deltas
anywhere come out the same as whole, and the deltas add up to what the
done events say.
- Relayed (passthrough): intTidy, beside nsTidy and built like it, on
Responses (function_call items, argument deltas and done, the completed
response, a whole reply), Chat (tool_calls deltas and messages) and
Messages (tool_use input and input_json_delta), streamed or whole. A
line that carries no call passes as it came. Plugin-served Grok and the
built-in subscription go through the same passthrough.
- Translated: translate sets Request.Grok; encoder() wraps the client's
encoder in wholeEncoder (outside usageEncoder) and render() rewrites the
Result's calls (wholeResult), so every client protocol is covered at
those two choke points.
- Any other model's reply is relayed byte for byte, as before.
- gateway-routing.md says so, and lists the tests.
Scope, against the reporter's 9fd6855b: that commit rewrote only fields a
tool schema typed "integer" or a fixed list of Codex's (codexInts), only
on Responses, and left deltas as they came, so the deltas disagreed with
the done events, and the list missed Codex's other integers (shell's
timeout_ms, sleep's duration_ms, tool_search's limit, the multi-agent
tools' timeout_ms). Codex's own schemas say "number", and JSON has one number type, so 2500 is the same value as
2500.0 for every client; this drops the zero fraction everywhere in a
Grok model's call arguments instead. Its rollout fixtures are kept
verbatim (testdata/grok_integral_args) and its test helpers adapted.
Tests: TestWholeNumsAnyCut (every split point and byte by byte),
TestGrokCallsGiveCodexIntegers (relayed Responses, streamed with deltas
cut whole, byte by byte and at every '.'/zero, and whole),
TestGrokCallsGiveCodexIntegersTranslated (Chat upstream -> Codex),
TestGrokCallsGiveIntegersOnEveryProtocol (Chat relayed, Messages relayed,
Messages translated from Chat), TestGrokCallsByUpstreamName,
TestGrokPluginCallsGiveCodexIntegers (fake plugin, $FAKE_GROK),
TestOnlyGrokCallsGetIntegers (gpt-5.5 byte for byte on Responses, Chat
and Messages relayed; translated keeps 2500.0), TestGrokModel. Each
recorded case checks that the field Codex's own error names is now an
integer of the Rust type it named, wherever Codex reads the call.
With grokModel forced false, every Grok test fails; with the delta
rewriting turned off (intTidy and wholeEncoder), every streamed case
fails on deltas != done.
Run: gofmt -l (clean); go vet -tags nogui ./... on darwin, GOOS=linux
and GOOS=windows; go build ./... and GOOS=linux/windows -tags nogui
builds; go test -tags nogui ./... under a temp HOME; -race -count=3 on
the new tests. End to end: the built binary (`serve`, sandbox HOME, port
47812) in front of a fake upstream streaming 2500.0 a byte per delta on
Responses and Chat; a client reading /v1/responses and
/v1/chat/completions, streamed and whole, got integers in deltas,
arguments.done, output_item.done, completed and output for grok-4.6
(relayed) and grok-4.7 (translated from Chat), and 2500.0 unchanged for
gpt-5.5. The same client against a binary of the parent commit failed
all 12 Grok checks.
Not verified: a real Grok model or a real Codex turn; Messages and Chat
Grok replies have not been seen in the field; a relayed Messages
tool_use input that is rewritten has its keys re-marshalled in sorted
order; exponent forms (2.5e3) are left as written.
Co-authored-by: timonwong <timon86.wang@gmail.com>
|
||
|
|
586f2bce8f |
context: magpie inspects the context window of every request, session and agent
The gateway reads each request's prompt into its parts (system prompt, tools and MCP servers, memory, files, tool results, chat), measured against the model's window and calibrated to the tokens the vendor counted. Routing shows a request's window as a card: a 400-cell grid by part, a hover naming what is largest in a cell, and the contents by part. The Usage page's Context tab scores each agent out of 100 (cache reuse, how lean it starts, how fast it grows, how reliably it answers), tags it (lean, cache-friendly, mcp-heavy, compacts, near-full…), and draws each session's growth with its latest request's card. Older Safari (15) gets media-query and solid-colour fallbacks for the card's container queries and color-mix. |
||
|
|
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
|
||
|
|
963d8d9d88 |
gateway: a provider that turns Codex's image tool away with a bare 400 is asked again without it, and isn't offered it again once that works, so a plain chat no longer breaks on it; a ChatGPT sign-in, openai.com and a Codex backend that takes it still get it (#949, cjyrainbow)
Since #870, magpie's provider in Codex's config carries x-openai-actor-authorization, so Codex offers its image_gen namespace tool on every request. A vendor's Responses API that can't take it, a relay's included, answered "bad response status code 400" to "只回复 OK". After a bare 400 (one that names no field or message magpie already knows to drop), a provider other than a ChatGPT sign-in or openai.com is asked once more without the tool. This works both passed through (the namespace) and translated (image_gen__imagegen flat). If the retry answers, the provider is marked unfit for tool:image_gen. If it doesn't, the tool goes back and the vendor's 400 stands, and the cache-key guess runs on the request as it was. The header stays as #870 wrote it. image_tool_test.go is new. Its fixture is the image_gen tool Codex 0.160.0 sent to a capture server with magpie's provider table and catalog. TestImageToolLeftOutWhereRefused (translated, passed through) fails with the reporter's 400 when gateway.go is reverted, and so does TestImageToolKeptOverAnotherRefusal. TestImageToolKeptForChatGPT fails when the ChatGPT exemption is dropped. docs/subsystems/gateway-routing.md has the rule. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass. |