Commit Graph
27 Commits
Author SHA1 Message Date
yetone 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 d84f58fd2 (#5403) that text counts
as the agent's own (desktopNote), so it is no longer said to the run as
the user's, which was right, but nothing handed it to the run either:
on the Claude subscription route a model that launched a skill saw
"Launching skill: pdf" and never what the skill says. Every skill
launched through magpie's Claude subscription lost its body.

withSkillBodies appends each such body to its Skill call's result (two
skills at once each get their own), else to the result it follows, else
to the last; saidWithResults still leaves it out of the user's words.

Found with a real Claude Code 2.1.316 in a sandbox HOME against the live
gateway: a proxy between them showed the body in the request, and the
model answered as if it had none.

Run (mote, at this tree):
- go test -tags nogui ./internal/gateway -run
  'SkillBod|Desktop|TaskNotice|SaidWith|MidTurn|Notice' -count=1: ok.
- TestSkillBodyRealClaudeCode parses the request Claude Code sent
  (testdata/claude-code-skill-launch.json: its own bytes, trimmed to the
  launch turn, paths shortened) and checks what the run is handed.
- Broken by hand (withSkillBodies returning results as they came):
  TestSkillBodyReachesTheSkillResult and TestSkillBodiesTwoSkills red.
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m: ok
  (1220.8s), at origin/main 6b0b7a96e. Rebased on 8f74442e4, whose
  gateway change is browser.go: -run
  'SkillBod|Browser|ClaudeSub|TaskNotice' ok.

Not tried: a real run through a gateway built from this tree (the
Claude subscription's sign-in would be refreshed by a sandbox copy).

docs/subsystems/claude-subscription-bridge.md says what withSkillBodies
does, beside withTaskNotices.
2026-11-09 08:38:02 +08:00
yetone 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 6b47bce67):
- go test -run TestQoder ./internal/gateway: ok. Fixtures are the literal
  bodies and headers qodercli 1.1.82 sent to a capture server, and its
  own session files, from a sandbox HOME (headless turns, a subagent, a
  second headless session, interactive turns, first title, later title,
  transcript title, suggestion).
- go test -timeout 45m ./internal/gateway and the full suite run after
  the push (mote at load 200 from another suite); a red is filed.
- gofmt -l; GOOS=linux and GOOS=windows go vet ./internal/gateway: clean.
Broken by hand, each red: no qoderSession call in handle; no
named-session guard; no agent check; subagent files not read; array
content not read; no wait for side calls; no newest-file tie-break; a
half-written line taken.

Not tried: the reporter's own account or a real model (fake upstream
only); Qoder in WSL (its files are in the WSL home, not found from the
Windows magpie); a keyed or MAGPIE_ADDR gateway on another machine (not
matched by design). The in-flight Active session (status bar) is not
fed from this. A large session file is read whole once per process.
2026-11-04 16:45:47 +08:00
yetone 01de489de1 search: a ChatGPT account searches for another model by the backend's own search (lucy_85908)
A third-party model in Codex (DeepSeek, MiniMax, ...) had its web
searches made by asking gpt-6-luna on the Codex account to search
through /responses. A ChatGPT account now searches by the ChatGPT
backend's /alpha/search, the request Codex's web.run sends by itself
with no model turn (codex-rs ext/web-search): one search_query, the
account's small model in "model", allowed_callers ["direct"], and
external_web_access from the client's web_search tool (#5018: Codex's
"cached" sends false; live by default). The output's pages are read by
their 80-dash rule and ref_id; the private-use citation marks are dropped.

Measured on a real Plus account (2026-11-03, token not refreshed): 151
alpha/search calls left the 5h window at the same percent, ~1.5-2.2s
each; 51 searches by gpt-6-luna took 0% -> 1% of it, 7-15s each,
~9-17k tokens in (40 of them: 414,585 in, 10,313 out). The backend
answered the same for any "model" (deepseek-v4 too) and any
max_output_tokens.

- Automatic (and searchInTurn) picks the backend's search for a ChatGPT
  account; Settings > Web search offers "<id>/@search" as "its web
  search". "<id>" and "<id>/<model>" saved before still search by that
  model, so a user's pick is unchanged.
- When the backend's search fails, the account's small model searches
  (codexSearchBy).
- Codex web.run's own search for a non-ChatGPT model (alphaSearchHere)
  and a Responses request's web_search tool pass their mode on.

Run at this head (rebased on origin/main), on mote:
- go test ./internal/gateway/... ./internal/gui/ ./internal/agent/
  -timeout 45m: gateway and agent ok; gui red only on
  TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 on mote).
  After the rebase: the gateway's search tests again ok.
- searcher-pick.test.cjs: 22/22, chromium + webkit, en/zh (+ the label
  is in zh, zh-TW, ja, de).
- gofmt -l clean; GOOS=linux go vet gateway, provider; GOOS=windows go
  vet gateway, gui.
- Whole GUI suite on the Linux box (wsl-run): not finished when pushed;
  its reds so far are WebKit pages this doesn't touch (add-provider,
  API key palette, Routing headers, click-scroll, Codex resets).

Broken by hand, each red: the Automatic switch (TestCodexSearchesWith
ItsCheapModel, TestChatGPTAccountSearchesByItsWebSearch), the
responses.go mode (TestResponsesWebSearchModeKept), the body's mode,
the fallback, and the picker option (searcher-pick).

Not tried: a real search through magpie in a sandbox (the request shape
was tried by hand against the backend); an account out of its
allowance (does alpha/search still answer?); the model fallback still
searches live when Codex asked cached.

Suggested by lucy_85908 on Discord.
2026-11-03 15:59:14 +08:00
yetone 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 85e37162e: go vet ./internal/gateway on darwin,
  GOOS=windows and GOOS=linux; go test ./internal/gateway -count=1
  -timeout 45m: ok (969.6s)
- at the pushed head, rebased on 276c806db (which changes host.js, no
  internal/gateway file): go vet ./internal/gateway and go test
  ./internal/gateway -run 'Reasoning|Sealed|Grok|Plugin|Signature'
  -count=1: ok (108.9s). The whole package was not run again there.
- real Grok account (opencode-grok-auth 0.2.3, grok-4.7, effort high)
  through a sandbox magpie built from this tree, Messages client, a
  three-call tool loop (read, read, write the sum), streamed and whole:
  both wrote 462. A mitm capture of each of the 8 upstream requests
  shows the include, and turn N carries N reasoning items
  (encrypted_content 383/179/891 bytes) before their function_calls
  under the plain call ids; every reply was 200.
Broken by hand:
- carryReasoning returning dec unchanged:
  TestGrokReasoningGoesBackThroughOtherAPIs red ("carries 0 items").
- asksSealedReasoning false: TestSealedReasoningAskedOfGrokAlone red
  ("include []" for anthropic, chat, gemini).
Not tried:
- the reporter's broken calls themselves were never reproduced (a real
  10-turn Claude Code run through the live gateway had none); the cause
  is from the diff with Grok Build.
- Claude Desktop itself; a Gemini client end to end (unit-tested only).
- reasoning before a text-only turn is not carried (no call id to ride).
- magpie's own search rounds (search.go) don't know the client's API and
  are left as they were.
No plugin change; the mover's min stays.
2026-11-01 22:21:00 +08:00
yetone 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 (733fac48f + this change), on mote:
- gofmt -l internal: clean
- GOOS=darwin/linux/windows go vet -tags nogui ./internal/gateway
  ./internal/plugin: ok
- CGO_ENABLED=0 go build ./internal/gateway for darwin, linux, windows
  x amd64, arm64: ok
- go test ./internal/gateway ./internal/plugin -count=1 -timeout 45m:
  ok (774s, 134s)
- win-run (Windows amd64) and wsl-run (Linux amd64, AVX2 path):
  go test ./internal/gateway -run HEIC: ok

Broken by hand, each red, then restored:
- no heicAsJPEG call in serve: TestHEICReachesPluginAsJPEG red
- media_type not set for Anthropic: the messages subtests red
- no base64 mark scan: the "labelled jpeg/png" subtests red

Not tried: a real Pi -> WorkBuddy request with a real account; a real
iPhone gridded HEIC (only sips files and Apple's 26 MB wallpaper); a HEIC
behind an http URL (not fetched, goes as it came); Anthropic document
blocks, Responses input_file and images/edits.
2026-11-01 15:04:28 +08:00
yetone 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 d0a61b856, then again after rebasing onto
origin/main f1d0c0bfd (gateway and usage packages, gofmt, vet). Pushed on 5174c0970,
which changes only GUI files after that run:
- go test -tags nogui -timeout 45m -count=1 ./internal/gateway/...
  ./internal/usage/...: ok gateway 612s, ok usage 41s; at the
  rebased tree ok gateway 593s, ok usage 42s
- TestStreamedReasoningWithoutCount with the counted check taken out of
  hidesReasoning by hand: red in 4 of 6 subtests (anthropic, chat from
  anthropic, chat tool uncounted, anthropic from chat tool uncounted);
  green restored. "responses from anthropic" was already hidden on the
  old code (the translated Responses stream carries encrypted_content).
- gofmt -l internal/gateway internal/usage: clean; go vet for darwin,
  GOOS=linux and GOOS=windows on both packages: ok.
- node --test reasoning-speed.test.cjs usage-speed-every-row.test.cjs
  (Chromium and WebKit, five languages) on the Linux VM (wsl-run): 16
  pass, 0 fail. On mote the same run had 8 TimeoutErrors at load ~25,
  beside four other sessions' whole GUI suites running 18 to 30 hours;
  no GUI code changes here.

Not tried: a real Claude API key (Anthropic's own endpoint) and Zhipu,
vLLM or Ollama Chat streams; no full go test ./...; no Windows or Linux
run of the tests.
2026-10-31 17:46:51 +08:00
yetone 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 (dca3e2d71), from Tencent's
own docs:
- API-key method (cloud.tencent.com/document/product/1806/130615):
  POST https://api.wsa.cloud.tencent.com/SearchPro with
  Authorization: Bearer <key> and a JSON body {"Query", "Cnt": 10}.
  Keys come from console.cloud.tencent.com/wsapi/index (KeysURL).
- SearchPro (121811): Response.Pages is an array of JSON strings, each
  with title, url, date, passage and content. The text is passage, or
  content when passage is empty or only the title. Tags are stripped.
- Errors (121818/121820, 130615): HTTP 200 with Response.Error{Code,
  Message}. AuthFailure*, UnauthorizedOperation and ResourceNotFound are
  turned away (403); ResourceUnavailable (欠费), LimitExceeded and
  ResourceInsufficient are out of credit (402); RequestLimitExceeded* is
  rate limited (429); others are plain errors, with the key masked.

The fixtures in testdata are the docs' two example replies. 130615's is
shown with its quotes escaped twice, which isn't JSON; they were
unescaped once and nothing else changed. The GUI's picker is built from
SearchVendors, so no GUI file changes. README (en, zh), the CLI help and
gateway-routing.md name it.

Run on mote (mote-run), at the rebased head:
- go test -run 'SearchAPI|WSASearch|Volcengine|Search' ./internal/gateway/
  ./internal/gui/
  ./internal/provider/ ./internal/cli/: ok
- go vet -tags nogui darwin/linux/windows: ok; gofmt -l clean
- GUI (no GUI file changes; the picker reads SearchVendors):
  search-api.test.cjs in Chromium 4/4 ok. Its WebKit cases and
  searcher-pick timed out at browserType.launch (180s) on mote,
  where ~57 WebKit pw_run launches from several sessions hang. Not
  a result about this change; WebKit not run.

Broken by hand, each made TestWSASearchAPI red: the wsaSearchError call
removed, and Cnt dropped from the body.

Not tried: the real API. No WSA key was available, so the request,
reply and error mapping rest on Tencent's docs only. The full go test
./... is to follow.
2026-10-30 14:56:01 +08:00
yetone 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 c941e0877, then rebased on d31710c71):
- TestVolcengineSearchAPI (new): red on the old code (no such vendor).
  Broken by hand six ways, each red with its own message: Summary not read
  (Snippet's text), volcSearchError not called (200 10403 read as "no
  Result in it"), query not cut (150 characters went), NeedUrl dropped
  (body {"Filter":{}}), 1970 age kept, 10412 not mapped (plain error, not
  a refusal). Restored: ok.
- go test -run Search ./internal/gateway/, go test ./internal/provider/
  ./internal/cli/: ok, before and after the rebase.
- gofmt -l internal: nothing. go vet -tags nogui ./... on darwin,
  GOOS=linux, GOOS=windows: ok.
- Not run before the push: the full go test ./... . mote had three other
  sessions' full suites running at load 140-230; it runs after the push
  and its result goes on the report.
2026-10-30 13:28:45 +08:00
yetone 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 98e23350f: every package ok
  but internal/gateway, whose 8 reds are the two draft faults named
  under "Broken by hand", both fixed here
- GOOS=linux and GOOS=windows go vet ./internal/gateway/: ok
- gofmt -l: clean

Broken by hand:
- desktopProbe's branch off: TestClaudeDesktopProbeAsked red, "probe
  went to the relay (1 calls)".
- own key off: TestClaudeDesktopProbeAsked red (turn 400 "prompt_cache_key
  is required"), TestOwnCacheKey red (1 upstream call, want 2).
- extraBody check off (a first draft): TestExtraBodyTranslated red,
  the user's ${sessionId} key replaced by magpie's.
- a first draft retried every 400 once without magpie's key:
  TestOtherBadRequestNotAskedAgainAtLow, TestTranslatedEffortMinimal-
  Refused, TestTooFewTokensSaidWithSigns, TestHighRiskErrorFallsBack,
  TestVertex{Minimal,}RetriesOnlyForVertex red on the extra try; now
  only a 400 naming the field drops it.

No GUI file is reached (gateway only). Not tried: a real AnyRouter
account or a real Claude Desktop against this build; the probe's bytes
come from Desktop 2.7032's app.asar.
Not run: the full suite at this head (shipped at once, as asked; it was
queued behind another session's suite on mote).
2026-10-28 12:48:21 +08:00
yetone 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 8f023b511 (tests and vet run again there; GOMODCACHE/GOCACHE pinned):
- go test ./internal/gateway/ -run 'Gemini|Kimi|Grok|OneOf|PlainSchema|Tool|LoopGuard|Doc' -count=1: ok
- gofmt -l internal/gateway/: clean
- go vet ./internal/gateway/ (darwin), GOOS=linux go vet -tags nogui,
  GOOS=windows go vet: ok; go build ./... for darwin, linux (nogui), windows: ok
- Not run: the full ./... suite (machine load ~200, other sessions' suites).

Broken by hand:
- geminiToolTypes call commented out of forwardOnce:
  TestGeminiToolTypesCuaDriverDrag red on chat, messages and responses.
- emptyObjectAt check replaced by true: TestGeminiToolTypes red, invalid JSON.

Tests: TestGeminiToolTypesCuaDriverDrag uses cua-driver's literal old drag
schema (testdata/cua_driver_drag_untyped.json) through the server on
/v1/chat/completions, /v1/messages and /v1/responses; a GPT model on the
same provider gets the tools byte for byte. TestGeminiToolTypes covers the
type rules, and that claude/gpt/gemma/kimi ids get the body bytes.Equal.

Not tried: a real Command Code account or a real Vertex request; the
schema's acceptance by Vertex is from its documented Schema object and
cua's own Vertex lint (cua-driver-testkit vertex.rs), not a live call.
2026-10-27 01:28:39 +08:00
yetone 43001be863 gateway: a relayed Chat body's unpaired tool calls are paired before Kimi sees them
Paidaixinbao on X: Qoder through magpie on Kimi Code, a conversation
forked at an earlier turn fails on every prompt while a new one works.
A Chat client's body to a Chat upstream was relayed as-is, and only
translated requests had their tool exchanges mended (pairToolMessages).
A forked or stopped history can hold a call with no tool answer, calls
split over two assistant messages, a user turn between a call and its
answer, or an answer to no call. Kimi turns the whole request away with
400 "an assistant message with 'tool_calls' must be followed by tool
messages responding to each 'tool_call_id'..." or "tool_call_id  is not
found". toolPairsOut now pairs such a body on the Chat relay (joining
split calls, answering the unanswered, turning an orphan answer into
user text); a paired body goes out byte for byte.

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

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

Not tried: the real Qoder app and the reporter's own forked history,
so which shape their fork holds is not proven; Qoder's "unsupported
request" text is not magpie's wording. A real Kimi model answer (the
plan has lapsed, only validation was seen). A non-Kimi Chat upstream,
though the rule is OpenAI's too and runs for every Chat relay.
2026-10-26 22:40:48 +08:00
yetone 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 ec7f47432 (v0.1.1287) a Codex turn on Copilot offering
web_search is relayed, not translated. Copilot's /responses gives an item
a new id in every event: output_item.added, each delta, output_item.done
and response.completed's output all differ (checked 2026-10-19 on the
owner's account, gpt-5.5 with web_search, in a sandbox HOME). Codex starts
an item by the added's id and ends one by the done's, so the streamed
message and the finished one were two messages. Translated, magpie's
encoder had given each item one id of its own, so it didn't show before.

Fix: idTidy (itemids.go), in passthrough before phaseTidy for every
relayed Responses stream: each later event's item_id / item.id, and
response.completed/incomplete/failed's output[i].id, take the id the
item was added with. An upstream whose ids agree goes through byte for
byte. docs/subsystems/gateway-routing.md says so.

Tests:
- TestCopilotItemKeepsItsID: a real Copilot reply (testdata, encrypted
  parts cut short) relayed through the handler from a fake Copilot
  (copilotSol now takes a reply); each output item goes by one id.
- TestItemIDsThatAgreeGoAsTheyCame: OpenAI-shaped ids, fed in 7-byte
  pieces, come out unchanged.
Broken by hand (idTidy off in passthrough): TestCopilotItemKeepsItsID
FAIL "item 0 went by 3 ids", items 1-3 by 6, 8, 5. Restored: ok.

Real use: built magpie serve in a sandbox HOME (port 3478, only the
Copilot sign-in copied), the real codex-cli 0.162.1 exec --json with
web_search on copilot/gpt-5.5:
- before: web_search item.started and item.completed under different ids;
- after: same id for each, and the follow-up requests carrying the kept
  ids back to Copilot were answered. A raw stream gave one id per item.
Not tried in the Codex desktop app itself.

Sibling found, not changed: on the translated path a reasoning item with
a non-rs_ id and a summary reaches the client twice (filed #2974; Copilot
gave summary [] in every capture).

Run at b9d1cd36f plus this change: gofmt -l clean; go vet ./... for
darwin, linux (-tags nogui) and windows ok; go test -timeout 45m ./...:
64 packages ok (internal/gateway 2023s), exit 0.
2026-10-20 00:33:40 +08:00
yetone 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 1a3b92688 + this change, on macOS (Go 1.26.8):
- gofmt -l: clean.
- go vet: darwin, linux (-tags nogui) and windows.
- Builds: darwin, linux (nogui) and windows.
- go test -run 'TestUpstream|TestClinePass|TestServed' ./internal/gateway: ok.
- Broken by hand: with the old upstream.go put back, both new tests go
  red ("real ClinePass chunk: upstreamOf = \"\"; want deepseek", plus the
  route, request-log and usage assertions on both paths).
- go test -timeout 45m ./... at load average 420-460 (several sessions'
  suites at once). agent, davsync, gateway, library, plugin and provider
  ran past the 45m timeout. gui was red on load reds that are already
  filed:
  - TestSetAnswersWhileDevinAndProvidersHang: #1375.
  - TestTrayCellClickReleasedPanel: #2645.
  - TestClaudeAccountsSpentFallBackToCodex: #2859, also #2858.
  - TestHostOnBunLackingLibsSaysWhich and TestGatewayHookMixedPiPackage:
    #2865.
  - The package timeouts: #2869.
  Every other package was ok.

Not tried: a live ClinePass account in the real app.
2026-10-19 07:38:46 +08:00
yetone 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.

79f64f028 left the server tool out where the upstream can't run it (a
vendor's model, another provider's advisor) and every translation drops
server tools, but both left the instructions and the tool_addition in place.
The model was told to call advisor() and given no such tool, so it called it
as one of the agent's tools and Claude Code answered "No such tool
available: advisor"; on Messages the tool_addition also named a tool the
request no longer declared.

Where magpie leaves the advisor out, withoutAdvisor (passthrough) drops the
tool_addition/tool_removal/tool_reference naming it, and a message left
empty, and replaces the instructions (up to the end of their reminder or
text) with Claude Code's own "The advisor tool is no longer available;
disregard the earlier advisor instructions." parseAnthropic does the same to
the text on a translation. An advisor that is kept goes as before.

Run: TestAdvisorModelAsTheUpstreamNamesIt (now on the literal 2.1.300 turn
in testdata/claude-code-advisor-turn.json, environment text cut short) and
the new TestAdvisorLeftOutOnTranslation (chat, responses, gemini). Broken by
hand (withoutAdvisor given no names, parseAnthropic not rewriting): both
red, the two left-out passthrough cases and all three translations; green
restored. go test -tags nogui -p 1 -run
'Advisor|Deferred|BillingLine|Shape|Anthropic|ToolSearch|TurnSystem|Passthrough'
./internal/gateway ok. gofmt -l clean; go vet -tags nogui ./internal/gateway
for GOOS darwin, linux, windows.

Not tried: a running magpie with real Claude Code end to end, and a real
vendor upstream; the reporter's provider and model aren't known, so whether
theirs was the passthrough or a translated route is inferred.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone 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 35aa50cfb, -p 1 -tags nogui, sandbox HOME):
- go test ./internal/gateway -run 'TestLocalCompaction|TestNativeCompaction|Native|Compact|TestSearchHistory|TestCodexOpenAIFields|TestCodex|ClientMetadata|Bare': ok (308 tests match the pattern)
- gofmt -l: clean; go vet for darwin, linux and windows: clean
Broken by hand: I turned off the codexInputAs rewrite, and then
separately the header rewrite in codexCompact. Each time
TestLocalCompactionSaysLocal went red on both paths with
400 "Fake: invalid codex request".

Full suite: SUITE_LINE
2026-10-15 23:08:03 +08:00
yetone 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.
2026-10-13 18:11:22 +08:00
congee949 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.
2026-10-13 06:43:50 +08:00
yetoneandump45nose 1e080cc7e7 gateway: the saved Anthropic-to-Responses body carries the image's detail auto that the commit before it sends (#1474)
TestUpstreamBodiesUnchanged (5feadabe, added after ump45nose's branch)
saved the bytes a vendor gets before input_image carried detail, so it
went red with the fix. Re-saved with UPDATE_UPSTREAM_BODIES=1; the only
byte change is "detail":"auto" on the one input_image.

Run: the two new tests fail on the old responses.go and pass on the new;
openai-python's ResponseInputImageParam (pydantic TypeAdapter) refuses
the old shape with "detail Field required" and takes the new one.

Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>
2026-10-13 05:09:18 +08:00
yetone 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 (5d33f060b) widened spawn_agent in the request's
tools only. Codex 0.162 doesn't put it there for a model that can search
tools: with supports_search_tool the multi-agent V1 tools are Deferred
(codex-rs rust-v0.162.1 core/src/tools/spec_plan.rs:1475-1479), the lead
calls tool_search, and spawn_agent, with Codex's five
(core/src/agent/child_config.rs:20 MAX_SPAWN_AGENT_MODEL_OVERRIDES = 5,
used in core/src/tools/handlers/multi_agents_spec.rs:830), arrives in a
tool_search_output item in the conversation. Codex resends that item on
every later turn. magpie's /models entries and Codex's own say
supports_search_tool, so this is the usual case, and the fix never fired.

The limit is only in what Codex writes. find_spawn_agent_model_name
(child_config.rs:318) takes any model of the catalog Codex loaded; the
five also appear in its error text (child_config.rs:335).

spawnAgentModels now widens the spawn_agent in each tool_search_output
in input as well as in tools (moreSpawnTools, shared by both). The added
text is unchanged and stays neutral; base_instructions are untouched.
The same output is widened the same way on each turn, so the history
Codex resends stays byte-stable.

Run:
- Real Codex 0.162.1 in a sandbox HOME/CODEX_HOME, wired by a sandbox
  magpie (`magpie codex fake/m1`, gateway on 127.0.0.1:3593) to a fake
  Responses upstream with 40 models that calls tool_search, then
  spawn_agent with model fake/m12.
  - Before: the lead's searched spawn_agent named fake/m1..m5 only.
  - After: it names all 40, Codex's five then the other 35 under the
    added header.
  - Both times Codex accepted fake/m12 and the child's request reached
    the upstream on m12.
  - The same Codex pointed straight at the fake (no magpie) gave the raw
    request saved as testdata/workdir/codex-0.162.1-tool-search.json
    (sandbox paths replaced).
- TestSpawnAgentNamesEveryModelAfterToolSearch (/v1, CodexPath with a
  magpie lead, CodexPath with a ChatGPT lead and V1) fails on the old
  codex_spawn_models.go in all 3 subtests ("doesn't name fake/m6") and
  passes now.
- go test ./internal/gateway -count=1 under a sandbox HOME: ok.
- gofmt -l clean; go vet ./internal/gateway on darwin, GOOS=linux -tags
  nogui, GOOS=windows.

Not run: a real ChatGPT-account lead at CodexPath (covered by the stub
backend test only), the Codex App, and a V2 lead (V2 keeps spawn_agent in
tools, which v0.1.1214 already covers).
2026-10-13 02:32:23 +08:00
yetone 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.
2026-10-12 23:06:24 +08:00
yetone 5feadabef6 gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.

decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.

Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:

                    CPU in the request's handler    time per request
                    (pprof, per request)            (ns/op)
  anthropic         154ms -> 45ms                   208-212ms -> 52ms
  anthropic, group  178ms -> 51ms                   249-262ms -> 65-67ms
  chat              122ms -> 35ms                   167-254ms -> 50-54ms
  responses         215ms -> 56ms                   294-452ms -> 70ms

TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).

Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
  Responses; direct, through a group, translated to each other protocol,
  with images, thinking, escapes, odd spacing, a repeated key, and four
  2 MB conversations) and compares what the vendor gets with
  testdata/upstream_bodies, recorded on the code before this change
  (all 18 identical; three runs agreed). Breaking decodeJSON's \n
  unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
  json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
  the gateway's, and jsonValid with json.Valid, over seeds, every cut
  and a changed byte at every place of each seed, and 2.5 minutes of
  fuzzing (~1.75M inputs). Breaking the validator's control-byte check
  by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
  origin/main 498b77fbc, with #1667's fix below it: all 48 packages ok
  (gateway 394s).
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway clean.

Not tried: real vendor traffic; Windows and Linux runs (vet only).
2026-10-12 03:28:16 +08:00
yetone 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).
2026-10-11 22:45:11 +08:00
yetone 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.
2026-10-11 10:17:16 +08:00
yetoneandtimonwong 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>
2026-10-10 01:09:31 +08:00
yetone 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.
2026-10-08 05:36:17 +08:00
forever bed306ae60 gateway: reasoning off reaches Gemini 3 at its lowest level, and Google refusing minimal no longer stops a provider's thoughts (#1062)
* gateway: reasoning off goes to Gemini 3 at its lowest level where it has no minimal, and Google refusing minimal no longer stops the provider's thoughts until restart

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

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

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

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

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

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

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

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

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

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

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

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

Live, through the proxy and temporary HOME of the previous commit, a turn
thinking at high gave a thinking block of 238 characters, and the answer
apart from it.
2026-10-07 18:51:01 +08:00
yetone 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.
2026-10-06 03:39:04 +08:00