Commit Graph
18 Commits
Author SHA1 Message Date
yetone aa3d11d5b7 kimi: a key's booster wallet is read, and a key spending it isn't rested to the month (#5721)
apple_test_src on X (#5721): a Kimi Code key at 98.85% of its month was
rested until the month renews, while Kimi still served it from its
booster wallet. magpie never read the wallet.

readKimiCode now reads booster_wallet (or boosterWallet). A BOOSTER wallet
with an amount over 0 adds an "Extra usage" row: amountLeft, in cents x 1e6,
in the currency of monthlyChargeLimit, else monthlyUsed, else USD. When
something is left, the plan windows are marked Credits. The gateway's full()
then doesn't count a key on its booster as full at the month's 98%. A 429
quota refusal rests it as any refusal does, not until the month renews.
A wallet that is empty, of another type or missing changes nothing.

Tests: TestReadKimiCodeBooster runs on the reporter's literal body
(testdata/kimi-booster-5721.json, where 0 is left: no Credits) and on the
same body with amountLeft injected (snake and camel case). A GIFT wallet
and amount 0 add nothing. TestKimiKeyOnItsBoosterIsNotRestedToTheMonth:
a key with booster left isn't full and its 429 rests it under 24h; a
spent key is still rested by its window.

Run on mote: gofmt -l clean; GOOS=linux and GOOS=windows go vet of
internal/provider and internal/gateway; go test ./internal/provider
./internal/gateway -count=1 -timeout 45m: both ok (154.9s, 951.7s).
Broken by hand: routing.go reverted turns the gateway test red ("a key
on its booster counts as full at the month's 98%"); dropping the Credits
marking turns the provider test red.
Not tried: a real Kimi key with booster balance left (the reporter's
body has 0 left).
2026-11-09 05:06:48 +08:00
yetone f86dd7910a openrouter: list every image model from its Image API, and draw them there
iwinux on Discord: the OpenRouter image picker listed only Nano Banana,
GPT-5.4 Image 2, GPT-5 Image and GPT-5 Image Mini, and asked whether the
protocol was the reason. It wasn't. OpenRouter's GET /api/v1/models lists
only models whose output includes text (454 rows on 2026-11-06, 13 of them
with image output), and that was the only list magpie read. The models
that answer in images alone (FLUX, Seedream, Riverflow, Recraft, GPT
Image, Krea, MAI Image, Qwen Image, Grok Imagine, Hunyuan, Muse) are at
its Image API's GET /api/v1/images/models (63 rows, no key needed), and
every one of them is served by POST /api/v1/images, which magpie already
spoke for FLUX/Seedream/GPT Image ids.

- catalog: openrouter.ai's public drawer list is /images/models; each row
  becomes a drawer with its output modalities, release date, name without
  the "Vendor: " prefix, and image input when it takes one.
- gateway: a model that answers in images only goes to /images, so
  Recraft, Riverflow, Krea, MAI, Muse and Hunyuan (ids ImagesAPI doesn't
  know) no longer go to chat completions. A pixel size is sent as
  aspect_ratio plus resolution (2K/4K by the long side), since no
  /images endpoint lists size and Riverflow refuses one: a real request
  with "size":"1024x1024" got 400 "Sourceful V2 does not support explicit
  pixel sizes. Use resolution and aspect_ratio instead." A ratio goes as
  aspect_ratio; anything else (auto) as size.
- Recraft's vector models answer image/svg+xml: saved as .svg in the
  gateway and in the image MCP (its sibling extOf).

Not listed: openrouter/auto (a router that may answer with an image).
krea/k3-edit is listed but only edits. Image prices are not imported
(OpenRouter prices per image per endpoint). Existing users see the new
models after their next model-list fetch.

Run (mote, at this tree):
- go test -count=1 ./internal/provider/ ./internal/catalog/ ./internal/imagemcp/: ok
- go test -count=1 -run 'Draw|Image|OpenRouter|ViaFor|Aspect|Drawer' ./internal/gateway/: ok
- gofmt -l internal: nothing; go vet of the four packages for darwin,
  GOOS=linux and GOOS=windows: ok
- Real: the worktree's binary in a sandbox HOME (magpie-wt/orimg-scratch,
  only the owner's OpenRouter provider copied in), serve on 127.0.0.1:3471,
  magpie sync: "openrouter (405)" and 63 drawers in its live list,
  Riverflow, Recraft, FLUX, Krea, MAI among them. POST
  /v1/images/generations openrouter/sourceful/riverflow-v2-fast at
  1024x1024: a 1024x1024 WebP back (27KB, 4175 output tokens).

Broken by hand: without the /images/models catalog entry,
TestOpenRouterImageModelsComeFromItsImageAPI fails ("/images/models asked
0 times"); sending size as given, TestOpenRouterImageOnlyModelsDrawAtItsImageAPI
fails (size 1024x1024 sent, aspect_ratio missing).

Not tried: a real draw with Recraft vector (SVG), Krea, xAI or MAI
through magpie; the GUI picker itself with the longer list; Windows and
Linux runs of the tests (vet only).

Reported-by: iwinux
2026-11-06 11:58:35 +08:00
yetone 9feb1024c7 zen: free models are asked as OpenCode 2.2.5 asks them (#3491)
laomao04_65777 on Discord: Zen's free models answered 429 "Free usage limit
reached. Free models work in OpenCode" to the built-in OpenCode Zen provider,
while real OpenCode 2 on the same machine was served. magpie sent OpenCode
1.x's shape. It now sends what OpenCode 2.2.5 sent in a captured request
(internal/provider/testdata/opencode-2.2.5-chat.json, from a recording proxy),
as the zen-free plugin does since plugins d62193c and 8501988:

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

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

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

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

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

Not tried:
- A real 200 from a free model: this egress IP's free allowance is spent.
  The captured 2.2.5 request itself got 429.
- Header order and case: Go's HTTP/1 writes headers sorted, and HTTP/2
  lowercases them, so OpenCode's order cannot be copied.
- Windows' project id against real OpenCode on Windows.
2026-11-01 14:48:19 +08:00
hlyx1 2b067434d7 provider: a Kimi Code membership's k3.1-pro and k3.1-pro-highspeed are priced at the Kimi API's (#4635)
hlyx1's fix (#4635, branch hlyx1/magpie kimi-code-k31-pro-price), asked
to be expedited by matrix0487 on Discord. Kimi Code's plans serve
k3.1-pro and k3.1-pro-highspeed, which models.dev's kimi-code-plan-*
catalogs list at the membership's $0. Neither id was in kimiCodeAPI, so
a membership's call on either was unpriced on Usage. They now map to
kimi-k3.1-pro and kimi-k3.1-pro-highspeed, like k3 to kimi-k3, and the
Requests list names that model (PricedNameFor).

Checked: Kimi Code's own /models answer (internal/catalog/testdata/
kimi-code-cn-models-2026-10-31.json) lists k3.1-pro "K3.1 Pro" and
k3.1-pro-highspeed "K3.1 Pro Highspeed". Kimi's pricing page
(platform.kimi.ai/docs/pricing/chat, read 2026-11-01) and models.dev's
live moonshotai entry both give kimi-k3.1-pro $2 in / $10 out / $0.20
cached / $2 5m write, and kimi-k3.1-pro-highspeed $4 / $20 / $0.20 / $4.
The fixture's new entries match models.dev's api.json in id, name, cost
and canonical_model_id.

The alias stays Kimi Code's (kimiCodePlans): the test's relay catalog
now lists a k3.1-pro of its own at $0.50/$1, which keeps that price, and
PricedNameFor(relay, k3.1-pro) stays k3.1-pro.

Docs: docs/reference.md, docs/subsystems/providers-accounts.md.

Run on mote (Go 1.26.8), at this change rebased on fb3942ee6 (the
pushed head adds only 784b66366, app.js and a GUI test): gofmt -l
clean; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
go vet ./... ok; go test -count=1 -timeout 45m for internal/provider,
usage, gateway, agent, cli, routes, sessions, usageapi: all ok.
TestKimiCodeListPrice and TestKimiCodeCost red with models.go at
origin/main (k3.1-pro {0 0 0 0} false; kimi-code-cn/k3.1-pro
priced=false cost=0, want true 3.264), green with it. Taking the
kimiCodeMember() check out by hand turns PricedNameFor(relay, k3.1-pro)
into kimi-k3.1-pro and the test red.
Full go test ./... at base da0005df8: every package ok but internal/gui,
red on TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
TestMainWindowCorners/macOS_26_SDK (#3949), both open on main and not
touched here.
Not tried: a real Kimi Code membership's k3.1-pro call through the GUI.
2026-11-01 11:19:26 +08:00
yetone 64cdb68035 accounts: import claude reads claude-swap's export (#4532)
StringKe (#4532) is moving from claude-swap (cswap 0.29.0) to magpie,
and `magpie accounts import claude` didn't read cswap's export. It does
now: parseLoginImport takes cswap's format-1 envelope ({version: 1,
swapVersion, encrypted, accounts: [...]}, read from cswap 0.29.0's
transfer.py) and cswapEntry reads each account's
credentials.claudeAiOauth and config.oauthAccount: email, account and
organization uuid, and the organization's name. The tokens are kept as
the file has them; magpie asks Anthropic nothing.

Refused, each with what to do: an encrypted export (decrypt with gpg -d
first), another format version, a Codex entry, and an API-key entry
(added as a key instead). An entry with no refresh token is accessOnly,
as for every other file. cswap's alias becomes the account's name in
magpie (importNames) when the account was added or updated, has no name
yet, and no other account is called that or signed in as it, so the
name stays a selector for one account (the previous commit's rule).

testdata/cswap_0.29.0_export.json is claude-swap 0.29.0's own `cswap
export` output, made from its source in a sandbox HOME in WSL with two
accounts and fake tokens (cswap's add step asked Anthropic once with
the fake refresh token, which it called dead; no real account was
involved).

Run (mote unless said):
- At this commit's tree (on origin/main 47173f593):
  gofmt -l clean; GOOS=linux go vet -tags nogui ./... and GOOS=windows
  go vet ./... ok; go test -timeout 45m ./internal/provider (ok 100.7s),
  ./internal/cli (ok 31.8s), ./internal/gui: red on 11 real-window
  AppKit tests killed at their deadline on mote over ssh (#4125, #2645)
  and TestSettingsSaveKeepsWhatItDoesNotSend's SearchAll, red on main
  (#4514); none touches accounts.
- Rebased on origin/main 7aa67e9e5 (4 commits, none in accounts), then
  at the pushed tree: go test ./internal/provider (ok 163.5s),
  ./internal/cli (ok 55.8s), ./internal/gui -run 'Budget|I18n|Key'
  (ok), gofmt -l clean.
- TestImportCswapExport, TestImportCswapRefusals. Broken by hand, each
  red: no cswapEntry, no importNames, the taken-name check off (red on
  "the team seat took pro's name"), the encrypted check off, no
  organization name.
- CLI in a sandbox HOME in WSL: import of the fixture adds max@x.com and
  team@x.com, a second import says both are in magpie already, the alias
  "work" is team's name, `accounts forget claude work` picks it;
  `accounts import --help`, a missing file and an unknown agent each say
  what's wrong.
- On mote over ssh the same import added one account and failed the
  other on the Keychain ("Unable to obtain authorization", no GUI
  session there), and the failed one was still saved, so the second
  import called it "in magpie already". That's addLogin writing
  logins.json before signing Claude Code in, the same for every import
  and sign-in, not this change; not changed here.
- GUI: login-import in Chromium and WebKit on Linux (WSL), green.

Not tried: an export from a real cswap install with real accounts,
Claude Code running on an imported account, or cswap's encrypted export
decrypted and imported. A cswap account's plan (subscriptionType) isn't
carried: magpie reads it on the first usage read, as for CLIProxyAPI.
2026-10-31 18:22:02 +08:00
yetone ef155a5ca2 provider: a new partner provider starts at the region where the user is, Kimi Code's Global plan abroad (Kimi)
Kimi (a sponsor) reported: "伙伴卡编辑器默认区为 China,建议按用户区域分流".
A partner given only by regions started at its first one, and Kimi
Code's partner card lists China first, so a user abroad was offered the
China plan's endpoints, key page and catalog.

Now, when a partner's first region is China's or Global's and the other
is listed too, a new provider of it starts at the one where the user is:
China's in mainland China, Global's elsewhere. The place is read from
this computer's time zone: LocalZone ($TZ, /etc/localtime) on macOS and
Linux, the registry's TimeZoneKeyName on Windows. Asia/Shanghai,
Asia/Urumqi and their old names (Chongqing, Harbin, Kashgar, PRC) and
Windows' "China Standard Time" are mainland China; Hong Kong, Macau and
Taipei have zones of their own and get Global. Windows' China Standard
Time also covers Hong Kong, which Windows doesn't tell apart. A zone
that can't be read keeps the partner's first region, as before.

It is decided in validPartners, where the partner's default endpoints
are filled in, so every add path takes it: the GUI editor (its region
picker marks the region at the preset's endpoints, and Get a key and the
site link follow), the TUI's and CLI's add (FromPreset). The default
region's key page, site, siteHost and catalog become the preset's with
its endpoints, as atRegionOf does for a provider.

Which regions count: only one with id cn/china/global/intl or named
China, China Mainland, Mainland China, Global or International. Checked
against each partner in site/partners.js: Kimi (China, Global, "Pay as
you go · China", "Pay as you go · Global") switches between its two
plans only; APIKEY.FAN (Default, Direct) gives its own top-level
endpoints, so no region is defaulted; WandAPI, CoreCode, Sidrune and
FastAIToken have no regions. yylx (a built-in preset, not a partner)
lists Auto first and would stay at Auto anyway.

Providers already added keep their region: a provider stores its own
endpoints when it is added, and its region is read from them
(regionOf), so a user who moves keeps theirs. The list kept on disk
from before is fixed at the next fetch, which runs at start.

Tests:
- TestPartnerStartsAtTheUsersRegion, from usemagpie.ai/api/partners as
  served on 2026-10-27 (testdata/partners-2026-10-27.json): abroad Kimi
  Code starts at api.kimi.ai, keys /go/kimi/keys/global, site host
  www.kimi.ai, catalog kimi-code-plan-global; in China and with no zone
  at api.kimi.com and China's; a provider added in China stays there
  after the user is abroad and the list is fetched again; APIKEY.FAN
  starts at its own endpoints either way.
- TestHomeRegion: Kimi's four regions, yylx's Auto first, Global first,
  plans only, no Global; chinaZone for Shanghai, Urumqi, PRC, China
  Standard Time, Hong Kong, Taipei, Singapore, New York, UTC and "".
- Broken by hand: with the region back at p.Regions[0], the test fails
  "abroad: a new Kimi Code provider is at {chat:https://api.kimi.com/
  coding/v1 … catalog:kimi-code-plan-cn}, want {… api.kimi.ai …
  kimi-code-plan-global}" and "the preset's endpoints … aren't its home
  region's". With the key page/site/catalog line dropped, it fails on
  keys https://usemagpie.ai/go/kimi/keys (not …/keys/cn) in China.
- go test -tags nogui -count=1 -timeout 45m ./internal/provider
  ./internal/cli ./internal/tui at 56de2d192 + these two commits: cli
  ok, tui ok. internal/provider has three reds that are already on
  main, and they fail the same way at origin/main 14e4d8040, just
  fetched, run alone -count=3: TestFetchAsksASharedBaseOnce,
  TestFetchAsksOneListOnceForTwoBasesOfIt and
  TestFetchUnionsProtocolListsWithoutChat (#3854). The first run, with
  nothing skipped, also crashed in TestUnreadLoginsWriteErrorsKeepCredentials
  ("close of synctest channel from outside bubble", #3632, red on main),
  so the second run skipped that one test. No full ./... run: the
  machine's disk was full (ENOSPC) from other sessions' caches.
- go build; GOOS=linux go build -tags nogui; GOOS=windows go build.
- Rebased onto 14e4d8040 (45 files changed on main since 56de2d192,
  none of them these): go build, go vet ./internal/provider and
  -run 'TestPartner|TestHomeRegion|TestPreset' ./internal/provider ok
  at the pushed head; the package run above was not repeated there.
- gofmt -l: nothing; go vet, GOOS=linux go vet -tags nogui and
  GOOS=windows go vet on internal/provider: clean; GOOS=windows go build.

Not tried: the Windows registry read on a real Windows machine (the
Windows box didn't answer ssh); the GUI editor with a real partner list
in a sandbox; the GUI suite (no file under internal/gui changed).
2026-10-27 18:45:45 +08:00
yetone 16327872c3 provider: Antigravity's retired 2.5 Flash models are named for themselves again, with no tagDescription to go by (新v学员 on Discord)
新v学员 (#feedback, 10-20; Antigravity on a Google AI Plus plan): three
chips in the subscription's model list read "Gemini 3.5 Flash Lite", and
only one was gemini-3.5-flash-lite; hovering the others showed
gemini-2.5-flash and gemini-2.5-flash-lite.

Cause: Antigravity's fetchAvailableModels still names gemini-2.5-flash,
gemini-2.5-flash-lite (and the hidden -thinking) "Gemini 3.5 Flash Lite".
b68377dae (#1918) renamed them only when their tagDescription named
another family. Google no longer sends a tagDescription for these, and
where it sends one now it is a notice ("GPT-OSS will be removed from
Antigravity on November 2, 2026."), so nothing was renamed. Checked on the
owner's account today: no tagDescription on any Gemini model.

Fix: a model is named for its own id (catalog.NameOf, else its id) when
its name is spelled by another family's id in the list
("Gemini 3.5 Flash Lite" is gemini-3.5-flash-lite), or when its enum
names its own id (MODEL_GOOGLE_GEMINI_2_5_FLASH is gemini-2.5-flash;
models Antigravity names correctly carry MODEL_PLACEHOLDER_M…), which
covers an account whose list has no gemini-3.5-flash-lite. Levels of one
model (gemini-3.7-flash, -low) and a name no id spells, such as
gemini-3-flash-agent "Gemini 3.5 Flash (High)", stay as given. The same
names reach /v1/models, agents' lists and Usage's windows, since all of
them read modelInfo. The GUI's own way of showing what tells same-named
models apart (a77ecbf8a) is unchanged.

Test: TestAntigravityRetiredModelNamedWithoutTag reads
testdata/antigravity-models-2026-10-20.json, the real fetchAvailableModels
reply of today with MIME types and experiments left out. It runs three
cases: the list as given (all three ids that read "Gemini 3.5 Flash
Lite"), the list without gemini-3.5-flash-lite, and the 2.5 models with
placeholder enums. In each, no two models read the same and both 2.5 ids
are named for themselves. On the old google.go it fails in two cases:
"gemini-2.5-flash and gemini-2.5-flash-lite both read "Gemini 3.5 Flash
Lite"", "gemini-2.5-flash is named "Gemini 3.5 Flash Lite", not for
itself", plus the same for Usage's windows. With the enum rule broken by
hand, "no gemini-3.5-flash-lite" fails; with the spelled-name rule
broken, "placeholder enums" fails. TestAntigravityRetiredModelNamedForItself
(#1918's fixture) still passes.

Real use: built with -tags nogui and run as `magpie serve` with
MAGPIE_ADDR=127.0.0.1:3488 in a sandbox HOME, holding only a copy of the
owner's Antigravity login (free tier). /v1/models listed
gemini-2.5-flash "Gemini 2.5 Flash", gemini-2.5-flash-lite "Gemini 2.5
Flash-Lite", gemini-3.5-flash-lite "Gemini 3.5 Flash Lite" and
gemini-3-flash-agent "Gemini 3.5 Flash (High)". Not tried on a Plus account
or in the reporter's Windows/Linux GUI.

Run in a fresh worktree on origin/main e4ac5e871: gofmt -l clean; go vet
./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... all
clean; go build, GOOS=linux go build -tags nogui, GOOS=windows go build
ok; `set -o pipefail; go test -timeout 45m ./...` at load 360-450:
64 packages, 61 ok (internal/provider 806s), 3 red, each already filed:
internal/agent past 45m (TestMorphContextWindow at the deadline, #2544,
#2723), internal/gateway past 45m (TestTierRecordedPerTry at the
deadline, #2870, #2108), internal/middleware TestOnUsageRows
"strategies.seen: took too long" (#2687). None of them reads
Antigravity's names.
No GUI file changed, so the GUI suite was not run.
2026-10-20 02:49:50 +08:00
yetone 934263f543 zen: Test with the public key asks each API for a free model Zen serves on it, and leaves out an API no free model is on (z'x on Discord; #2385)
z'x on Discord: Test on an OpenCode Zen provider with the key public always
failed. Reproduced with Zen's real list: Test asked public for
claude-fable-5 on Messages and gemini-3-flash on Gemini, which public
doesn't reach (Zen's free models alone answer it), and big-pickle on
Responses, a chat-only model. Only chat (big-pickle) could pass, so the
card was red every time.

- testModel: on OpenCode's gateway a model models.dev names no API for
  (no per-model provider.npm) is served on chat alone, so no other
  endpoint is tried with it (a Claude id on Messages still is). This also
  stops a paid key's Responses probe asking big-pickle.
- With public, only a free model (OpenCodeFree) is tried, and with none on
  an API that API is left out of the result; with none on any, one row
  says why (zenPublicNone), and a client-scoped Test says the same.

#2385 itself (deepseek-v4.1-flash-free not offered): the built-in Zen
lists whatever Zen's /models lists, with no table of free ones;
TestZenPublicListsNewFreeModels pins that with the real bytes. The model
was missing in the opencode-zen-free plugin, fixed there (zen-free 0.1.9,
magpie-community/plugins).

Fixtures: testdata/zen_public_models.json is Zen's /inference/v1/models
as the public key read it on 2026-10-15 (one GET, byte for byte);
zen_catalog.json is models.dev's opencode entries for those ids from the
same day's synced catalog.

Run (worktree at origin/main a1f7b8c13, -tags nogui -p 1):
- go test -run 'TestZen|TestOpenCode' ./internal/provider: ok
- the 77 provider tests that call Test, testModel or tiny, plus
  TestZen*/TestOpenCode*: ok
- broken by hand: test.go back to main's, the two new tests kept:
  TestZenPublicTestAsksFreeModels red (responses asked big-pickle,
  anthropic claude-fable-5, gemini gemini-3-flash, all 401; own key's
  Responses model big-pickle); green again with the fix
- gofmt -l clean; go vet -tags nogui ./internal/provider for darwin,
  linux and windows: ok

Not tried: Test against real Zen. The fake answers 401 to a paid model
with public and to a model off its API, as the reporter's red rows say,
but Zen's exact status there wasn't asked. Responses now asks
muse-spark-1.2-contributor-free (first in Zen's list, "deprecated" in
models.dev though Zen lists it); whether Zen still answers it wasn't
asked.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetone d5b1c95c4f provider: the built-in Factory offers Gemini 4 Argon, as droid 0.241.1 does (#2080)
droid 0.241.1's picker has Gemini 4 Argon (provider google, 1M total
context, 65536 output, low/medium/high, images); the built-in's table
stopped at Gemini 3.1 Pro. It goes to /api/llm/g like the other Gemini
models. In droid it is behind a Factory feature flag (Gemini4Argon,
unreleased), so an account it isn't on for may be refused it.

TestFactoryDroid0241Gemini reads droid 0.241.1's picker and Gemini
entries (testdata, byte for byte from @factory/cli-darwin-arm64@0.241.1
bin/droid, the same fixture as the plugin's) and checks every Gemini
model there is offered with droid's name, limits, efforts and images,
on Gemini, in standard's pool.

Moved users get it from plugin 0.1.26 (the next commit raises the
mover's min).

Run: gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
internal/provider and internal/gateway; go test ./internal/provider
./internal/gateway -count=1 (ok, under load average ~260). Broken by
hand: without the row the new test fails. Not tried: a real Factory
account (none here).
2026-10-14 15:17:06 +08:00
yetone f71155591e provider: a provider at a vendor's own endpoint is priced from that endpoint's models.dev catalog (#2052, mengyianx)
A custom provider added by its address alone, with no catalog named, was
priced only by the model's maker. Qwen3.8-27B, whose maker (Alibaba) sells
no such model on any of its seven models.dev catalogs, read "no price is
known for it" even at AMD's own endpoint, where models.dev's amd lists it
at $0, a price.

- catalog: models.dev's provider "api" is read; AtEndpoint names the
  catalogs at a base URL (trailing slash and case ignored).
- provider: EndpointCatalog is the one catalog models.dev lists at one of
  a key's provider's endpoints (an Anthropic base, kept as its root, also
  with /v1), used by ListPrice when the provider has no catalog of its
  own. Never for a subscription's account, never when two catalogs share
  the address (minimax / minimax-coding-plan), never a plan's catalog
  (an id with -plan, or membershipCatalogs), whose $0 is the membership's.
  A user's price and a named catalog still come first; a relay's endpoint
  matches nothing and its model stays unpriced (no reseller guess).
- cli: `magpie model price p/m` with no price gives the two commands that
  set one (p/m and */m); a price from an endpoint's catalog names it.
- gui: the Catalog field's hint says it also sets list prices (en, zh,
  zh-TW, ja, de).
- docs: reference.md's "What a model costs", providers-accounts.md row.

What was run:
- Reporter's exact case, built binary (go build -tags nogui), sandbox
  HOME with a copy of this machine's models.dev cache (2026-10-14, same
  amd entry as the report), providers 001 (relay), 002 and amd at
  https://developer.amd.com.cn/radeon/api/v1:
    001/gpt-5.5      $5/$30, tiers, as before
    001/Qwen3.8-27B  no price, now with the two commands to set one
    002/Qwen3.8-27B  $0/$0, "what models.dev's amd lists at its endpoint"
    amd/Qwen3.8-27B  $0/$0
  The two suggested commands were run and took effect.
- TestEndpointCatalogPrices / TestEndpointCatalogOnlyItsOwn, fixture
  testdata/endpoint_catalog.json trimmed from the real models.dev cache.
  Break checks, each FAILs with the case named:
    ListPrice not using EndpointCatalog -> 002/amd/001 at AMD unpriced,
      EffectivePrice(002, Qwen3.8-27B) unpriced
    plan exclusion removed -> "a plan's endpoint: EndpointCatalog() =
      alibaba-coding-plan", qwen3.5-plus at $0 instead of $0.4/$2.4
    single-match rule removed -> "an endpoint two catalogs share:
      EndpointCatalog() = minimax"
    Account check removed -> "a subscription's account ... = amd"
    Anthropic /v1 match removed -> thinkingmachines unmatched
- GUI: internal/gui/tests/catalog-hint.test.cjs, chromium and webkit, en
  zh zh-TW ja de, widths 1100 and 420: 20/20 pass, plus i18n-keys; with
  the old app.js/i18n.js it fails "one hint names list prices".
- go test -tags nogui -timeout 45m ./internal/catalog ./internal/provider
  ./internal/cli: ok (provider 244s, cli 125s, catalog 3s). gofmt -l
  clean; go vet (darwin), GOOS=linux go vet -tags nogui and GOOS=windows
  go vet -tags nogui on those packages: clean.
2026-10-14 07:51:41 +08:00
yetone 0337ce4bc7 factory: Haiku 5.5 and Mistral Large 4, in droid 0.240.0's picker, are offered, and moved users get plugin 0.1.25 (JL on Discord)
JL (Windows, droid 0.240.0, Factory desktop 0.197.1, magpie 0.1.1226,
opencode-factory-auth 0.1.24): droid and Factory desktop offer
claude-haiku-5-5; droid through magpie couldn't pick it.

droid's models are the registry bundled in its npm binary
(@factory/cli-<platform> 0.240.0, bin/droid). Against 0.233.0's registry,
0.240.0 adds claude-haiku-5-5, mistral-large-4 and gpt-6-astra-ultrafast.
The plugin (magpie-community/plugins e4023d9, published as 0.1.25, npm view
checked) now offers Haiku 5.5 (Anthropic Messages, 872000/128000, efforts
low..max) and Mistral Large 4 (chat completions, x-api-provider mistral,
Droid Core, 524288/64000, images). GPT-6 Astra Ultra Fast stays out: droid
offers it only once the user accepts Factory's high-cost terms.

- migrate_factory.go: the mover's min is 0.1.25, so keepMovedCurrent
  updates moved users (JL is on the plugin).
- factory.go: the built-in had the same gap; its table gets the same two
  rows for users who haven't moved.
- factory_pool_rest_test.go: the plugin's Core list, copied from its
  usage, gains Mistral Large 4.
- TestFactoryDroid0240Models is new; its fixture is droid 0.240.0's
  registry bytes (the same as the plugin's models.test.mjs). It fails with
  the Haiku 5.5 row removed.

Run, under a temp HOME: go test -tags nogui ./... with the machine at load
35-190 (other sessions). Every package passed except five that hit the
10m timeout mid-test (agent, gateway, library, plugin, provider, in
tests that don't touch Factory). Rerun with -timeout 40m: provider ok;
gateway still timed out at load ~130 (TestCodexHeardWithinItsIdleTimeout
failed on its timing, unrelated); -run 'Factory|Moved' on gateway ok.
agent, library and plugin were not rerun to the end; this change
doesn't touch them. gofmt -l clean; GOOS=linux and GOOS=windows go vet
-tags nogui on internal/provider and internal/gateway ok.
Not tried against Factory itself (no Factory account here); droid was read,
not run.
2026-10-14 05:11:19 +08:00
Junjie Zhouandmultica-agent 12d823211e provider: a multi-protocol provider's model catalog keeps every endpoint's models (#1006)
* provider: a multi-protocol provider's catalog is the union of every endpoint's models

A provider whose protocols sit at bases of their own kept only the first
list that answered, so the models of every other endpoint were nowhere in
the product: not in the agents' model lists, not in the catalog the routing
and the per-model preferences read, and not fixable by pinning a model's
protocol, which setModelAPI refuses for a model the provider does not list.
nyownm reported it as #904 and worked around it with one provider per
protocol.

fetchOne now asks every endpoint the provider speaks and merges the lists
by model id, the way fetchPerKey merges the lists of a vendor's keys: the
first list's fields stand, and an image capability both lists answer is
merged. The base kept is still the first protocol's, the one the drawer
list is fetched beside and the models are saved with. A models URL is
still asked alone, one base two protocols share is still asked once, and
a provider with no endpoint answering still fails with every URL it asked
named in the error.

Verified with go test -tags nogui ./internal/provider ./internal/catalog
and ./internal/gateway ./internal/agent, all green. TestFetchUnionsProtocolLists
and TestFetchUnionsProtocolListsWithoutChat fail on the base commit with
the single list the first protocol answered.

* provider: an endpoint that can't be asked keeps the models it listed

A provider whose protocols sit at bases of their own is asked every base
and the lists are merged, so one read that failed saved the union of the
rest as the whole list: the models of the failed base read as gone,
dropGonePicks took them out of the user's picks and stored that, and
nothing brought them back when the endpoint recovered (yetone's review of
#1006, on nyownm's #904). A read that failed says nothing about what the
vendor serves today, the rule fetchPerKey's keys already follow.

fetchOne keeps what each base listed and saves it beside the merged list,
in a new "sides" part of the catalog's live file, and a base it could not
ask takes its own part back for that fetch. What is kept is that base's own
models alone: a model the bases that answered have dropped is dropped here
too, however many of them dropped it and however many bases are down.
Keeping the whole list saved before would bring such a model back, which is
the same fault the other way round. A list saved before this kept no parts,
so a base whose part is missing keeps what no answering base lists, until
the next fetch with every base answering says which they are.

The parts are kept only where more than one base was asked: a single one
that fails is the fetch that fails, and its list is kept as it is, so a
provider of one protocol's cache is the file it was.

fetchOne answers one fetched list now — the models, the base kept for
routing, the parts — rather than three values. fetchPerKey marks the parts
with the keys that saw them, and keeps a plan's own models out of them.

Verified with go test ./internal/provider ./internal/catalog, all green,
and ./internal/gateway ./internal/agent.
TestFetchKeepsTheModelsAFailedProtocolListed,
TestFetchDropsAGoneModelWhileAnotherProtocolFails and
TestFetchKeepsTheModelsAFailedProtocolListedPerKey fail on 952d0b00 with
the model of the failed protocol taken out of the picks.

Co-authored-by: multica-agent <github@multica.ai>

* provider: a base that never answered keeps nothing, and is not saved as one that listed nothing

keepDeadSides read a part missing from the saved sides as the whole list
saved before, and kept what no answering base lists from it. Two things
were wrong with that, and both were reported on #1006 (nyownm's #904):

A base in none of the saved parts is one that has never answered. The
whole list is not its own, so a model its vendor had already dropped was
kept for it, and the keepDeadSides result was saved as sides[base] —
from then on that base had a part, and the model could never be dropped
again. An Anthropic base answering 404 from the start of a provider's
life was enough: one round after the Chat base dropped a model, that
model stayed in the catalog, and dropGonePicks could not take it out of
the user's picks.

The saving is the other half of the same fault. A part is what a base
listed, so one that never answered has none, and writing an empty one
fixes the reading of "never answered" as "listed nothing" for good. Only
a part read out of the file is written back; the list saved without any
parts at all — before this kept them — is the one case where a base may
stand in for a missing part, and what it stands in for is kept for that
fetch alone, never saved as its own.

So keepDeadSides answers two lists now: the models this fetch's list is
made of, and the parts to write beside it. fetchPerKey keeps a model a
key that could not be asked at all owns to the bases that listed it,
read out of the parts saved beside the list: kept as a whole list with
no part saying where it came from it belonged to no base, and was read
as gone the first time that key answered half-way — the same permanent
deletion of a picked model, one round later and needing no new base.

Verified with go test ./internal/provider ./internal/catalog
./internal/gateway ./internal/agent, all green, and -race -count=3 over
./internal/provider with the four failures it already had.
TestFetchDropsAModelWhileAnEndpointHasNeverAnswered and
TestFetchKeepsAModelsBaseAfterItsKeyFailedWhole fail on 6621f73e.

Co-authored-by: multica-agent <github@multica.ai>

* provider: a base that answered without a model does not keep owning it

fetchPerKey gave every model kept for a key that could not be asked at all
to the bases that listed it last time, and a part there said what the
bases listed when one of them had answered this round without it (yetone's
review of #1006, nyownm's #904). With two keys where both were served a
Claude model, and the Anthropic base stopping both of them in the round
the second key was down, sides[anthropic] kept a model the base had
plainly dropped, and the fetch after that read it as a base that couldn't
be asked and held the model one round longer than it should have. It is
self-healing — the next round with the base answering settles it — and it
is the same fault c8fabd70 was written to undo, read from the other side.

sides may only say what the bases listed. A model kept for a failed key
belongs to a base that was not asked this round for any of the model's own
keys: one that was, and answered without the model, has said what it
serves today and no longer owns it. Which is per key, not per provider:
fetchOne answers which of its bases replied, which a model of the second
key alone never saw an answer from, so the base's saying nothing about it
for the first key leaves it that base's. The keys a model is kept under
are read from the list saved before, since add clears the ones of the model
it is adding.

TestFetchDropsAModelABaseStoppedServingWhileAKeyIsDown fails on c8fabd70
with the part holding claude-b, and TestFetchKeepsAModelsBaseAfterItsKeyFailedWhole
goes on passing: the same two keys, a model only one of them sees.

Co-authored-by: multica-agent <github@multica.ai>

* provider, catalog: a page of a model list is not the list (#904)

A /v1/models that answers with has_more is one page of the vendor's
catalog. Read as the whole list, every model of a later page reads as one
the vendor has dropped, and the user's pick of it goes for good, on a
list that never said so. Such a reply is no answer: the base is treated
as one that could not be asked, which keeps what it listed last time
(#904's review of #1006).

OpenRouter's Anthropic base is not asked for the list at all. With the
Anthropic version header its /models answers with the catalog again,
twenty newest first, every id namespaced under `anthropic/`, and the
cursors of the pages after. None of those twenty is an id in OpenRouter's
own catalog, so merged they are entries of the model picker that name no
model: the long, cluttered list #904's reporter wrote of. Its Chat base
is that catalog, whole, and the fetch is one request where it was two.
The rule is OpenRouter's, by host, as the ones after it are scoped to
their vendors.

Co-authored-by: multica-agent <github@multica.ai>

* provider: the OpenRouter rule reads the base being asked (0fb16990)

It read the Chat base's host, so a provider with a Chat base of
OpenRouter's and an Anthropic base of another vendor's had that other
base skipped: its models were in neither the union nor the sides nor the
bases that could not be asked, so no keepDeadSides path found them and
the user's picks of them went for good. `magpie provider set <id>
anthropic=<url>` reaches that shape from the CLI.

The rule is about the vendor whose base is being asked, so that is what
it now reads, together with whether the provider asks at a base of its
own besides it: an OpenRouter Anthropic base alone is still asked, its
reply being the only catalog there would otherwise be, and
catalog.fetchOne is what keeps a page of it from being read as the whole.

Five combinations of the two bases and openrouter.ai, one assertion each;
three of them fail on 0fb16990.

Co-authored-by: multica-agent <github@multica.ai>

* catalog, provider: a model list is followed to its last page, not read as a page (#1006)

A reply with has_more was refused as no answer at all, which is right for a
provider with several bases and wrong for one with a single base: Anthropic's
own preset has no other base to fall back on, so once its list passes twenty
models — about sixteen today — the fetch answered an error and no models,
where main listed the twenty of the first page, and a pick of a model on a
later page went with them. catalog.fetchOne now reads a list to its end: the
first page as the URL stands, and every page after it with limit=1000 and
the after_id the page before ended at, up to twenty pages.

Half a list is still no answer, and that is what the following ends on: a
page that fails, a list that pages without naming the id to carry on from,
one that answers the page just asked again under the same id, and one still
paging at the cap all leave the base as one that could not be asked, which
keeps what it listed last time. The rule lives in catalog.Paged, and the
Kilo gateway's list — OpenRouter's shape, which pages the same way — is paged
by it instead of refused by a guard of its own; the comment on that guard
claimed OpenRouter's /models pages, which neither api.kilo.ai nor
openrouter.ai was answering with on 2026-10-06, and now says so.

One assertion of TestFetchOpenRouterRuleOverTheFourBaseCombinations follows
the rule rather than the old count: OpenRouter's Anthropic base alone is
asked for its first page and the page after it, which is the same page
again, where before it was asked once and refused.

Tests: TestFetchFollowsThePagesOfAList, TestFetchFollowsAPageAListAnswersItsOwnWay,
TestFetchTakesAPagedListAsNoAnswerWhenAPageFails, TestFetchTakesAPagedListWithoutAnIdAsNoAnswer,
TestFetchTakesAListThatPagesWithoutEndAsNoAnswer (catalog);
TestFetchFollowsThePagesOfASingleAnthropicBase (provider, the Anthropic preset's
one base, 25 models 20 to a page) and TestKiloModelsFollowThePagesOfTheList.

Co-authored-by: multica-agent <github@multica.ai>

* provider: OpenRouter's Anthropic base alone is asked, and refused (#1006)

The fake that stands for openrouter.ai answered every cursor with the same
twenty ids under the same last_id, so following the pages of a list stopped
where the rule of catalog.Paged says a list stops being readable, and the
single-base case looked covered: the twenty were refused and the fetch
failed. The endpoint does not answer that way. Asked with the Anthropic
version header on 2026-10-06, /api/v1/models gave those twenty with
has_more and a cursor, and under the cursor 413 more ids with has_more
false — a different set, and the end of the list. The two pages share
nothing, and following them lands deeper in the `anthropic/` namespace
rather than back at the catalog it was namespaced from: of the 433 ids, 4
are in the 466 OpenRouter serves without that header.

So the twenty were not a page to be refused but the first half of a list
that reads to the end, and the end is still not a catalog of models to
serve. The base is still asked — it is the only base there is, and refusing
to ask would leave the provider with nothing at all — and the list it
answers with is now refused as a whole, which is what the old rule did with
one page of it. It fails the fetch like any other base that could not be
asked, so the provider keeps the models it listed last time (#904).

The two replies are kept as they came, under testdata, and a test reads
them back: twenty, then 413, the cursor the first ends at, has_more true
and then false, and not one id of either page in the catalog OpenRouter
serves. The fake pages with after_id, as the endpoint does.

Tests: TestOpenRouterNamespacedPagesAreTheEndpointShape (new),
TestFetchOpenRouterRuleOverTheFourBaseCombinations (the single-base case now
asks exactly the two pages it answers with, keeps no list, and fails),
TestFetchKeepsPicksWhenAModelListIsPaginated, TestFetchDoesNotMergeOpenRouter's
NamespacedList, TestFetchOpenRouterAddsNoNamespacedModelAndKeepsPicks,
TestFetchKeepsAnotherVendorsAnthropicList.

Co-authored-by: multica-agent <github@multica.ai>

* provider: the message for a namespaced list counts nothing (#1006)

The reason a provider whose only base is OpenRouter's Anthropic one is
refused is still the one it was, and the base is still asked and refused
exactly as before: what changed is the sentence the user is left with, and
the comments around it.

That sentence counted the list it refused — "433 of them, of which 4 are
ids OpenRouter serves" — and those counts are of whatever OpenRouter's
catalog was that day, so the number a user reads is wrong tomorrow without
anyone touching it. It now says why the answer is no good and what to do
instead: give this provider OpenRouter's Chat base, which lists those
models under the ids OpenRouter serves, or type the model ids in by hand,
which is what the caller already appends to every base it could not ask.

The comments said the same counts as fact, and cited a probe file that is
not in the repository. The counts stay, marked as what was observed on
2026-10-06, and what does not move is now the point: following the pages
of the list lands deeper in the namespace, not back at the catalog it was
namespaced from. The dead file references are gone, and one test checks
that the message counts nothing at all, so a count cannot creep back in.

Tests: TestFetchOpenRouterRuleOverTheFourBaseCombinations (the message names
the Chat base and the ids to type, and holds no number but the version in
that base's path).

Co-authored-by: multica-agent <github@multica.ai>

* provider: a multi-protocol provider's catalog is the union of every endpoint's models

A provider whose protocols sit at bases of their own kept only the first
list that answered, so the models of every other endpoint were nowhere in
the product: not in the agents' model lists, not in the catalog the routing
and the per-model preferences read, and not fixable by pinning a model's
protocol, which setModelAPI refuses for a model the provider does not list.
nyownm reported it as #904 and worked around it with one provider per
protocol.

fetchOne now asks every endpoint the provider speaks and merges the lists
by model id, the way fetchPerKey merges the lists of a vendor's keys: the
first list's fields stand, and an image capability both lists answer is
merged. The base kept is still the first protocol's, the one the drawer
list is fetched beside and the models are saved with. A models URL is
still asked alone, one base two protocols share is still asked once, and
a provider with no endpoint answering still fails with every URL it asked
named in the error.

Verified with go test -tags nogui ./internal/provider ./internal/catalog
and ./internal/gateway ./internal/agent, all green. TestFetchUnionsProtocolLists
and TestFetchUnionsProtocolListsWithoutChat fail on the base commit with
the single list the first protocol answered.

Co-authored-by: multica-agent <github@multica.ai>

* provider: an endpoint that can't be asked keeps the models it listed

A provider whose protocols sit at bases of their own is asked every base
and the lists are merged, so one read that failed saved the union of the
rest as the whole list: the models of the failed base read as gone,
dropGonePicks took them out of the user's picks and stored that, and
nothing brought them back when the endpoint recovered (yetone's review of
vendor serves today, the rule fetchPerKey's keys already follow.

fetchOne keeps what each base listed and saves it beside the merged list,
in a new "sides" part of the catalog's live file, and a base it could not
ask takes its own part back for that fetch. What is kept is that base's own
models alone: a model the bases that answered have dropped is dropped here
too, however many of them dropped it and however many bases are down.
Keeping the whole list saved before would bring such a model back, which is
the same fault the other way round. A list saved before this kept no parts,
so a base whose part is missing keeps what no answering base lists, until
the next fetch with every base answering says which they are.

The parts are kept only where more than one base was asked: a single one
that fails is the fetch that fails, and its list is kept as it is, so a
provider of one protocol's cache is the file it was.

fetchOne answers one fetched list now — the models, the base kept for
routing, the parts — rather than three values. fetchPerKey marks the parts
with the keys that saw them, and keeps a plan's own models out of them.

Verified with go test ./internal/provider ./internal/catalog, all green,
and ./internal/gateway ./internal/agent.
TestFetchKeepsTheModelsAFailedProtocolListed,
TestFetchDropsAGoneModelWhileAnotherProtocolFails and
TestFetchKeepsTheModelsAFailedProtocolListedPerKey fail on 952d0b00 with
the model of the failed protocol taken out of the picks.

Co-authored-by: multica-agent <github@multica.ai>

* provider: a base that never answered keeps nothing, and is not saved as one that listed nothing

keepDeadSides read a part missing from the saved sides as the whole list
saved before, and kept what no answering base lists from it. Two things
were wrong with that, and both were reported on #1006 (nyownm's #904):

A base in none of the saved parts is one that has never answered. The
whole list is not its own, so a model its vendor had already dropped was
kept for it, and the keepDeadSides result was saved as sides[base] —
from then on that base had a part, and the model could never be dropped
again. An Anthropic base answering 404 from the start of a provider's
life was enough: one round after the Chat base dropped a model, that
model stayed in the catalog, and dropGonePicks could not take it out of
the user's picks.

The saving is the other half of the same fault. A part is what a base
listed, so one that never answered has none, and writing an empty one
fixes the reading of "never answered" as "listed nothing" for good. Only
a part read out of the file is written back; the list saved without any
parts at all — before this kept them — is the one case where a base may
stand in for a missing part, and what it stands in for is kept for that
fetch alone, never saved as its own.

So keepDeadSides answers two lists now: the models this fetch's list is
made of, and the parts to write beside it. fetchPerKey keeps a model a
key that could not be asked at all owns to the bases that listed it,
read out of the parts saved beside the list: kept as a whole list with
no part saying where it came from it belonged to no base, and was read
as gone the first time that key answered half-way — the same permanent
deletion of a picked model, one round later and needing no new base.

Verified with go test ./internal/provider ./internal/catalog
./internal/gateway ./internal/agent, all green, and -race -count=3 over
./internal/provider with the four failures it already had.
TestFetchDropsAModelWhileAnEndpointHasNeverAnswered and
TestFetchKeepsAModelsBaseAfterItsKeyFailedWhole fail on 6621f73e.

Co-authored-by: multica-agent <github@multica.ai>

* provider: a base that answered without a model does not keep owning it

fetchPerKey gave every model kept for a key that could not be asked at all
to the bases that listed it last time, and a part there said what the
bases listed when one of them had answered this round without it (yetone's
review of #1006, nyownm's #904). With two keys where both were served a
Claude model, and the Anthropic base stopping both of them in the round
the second key was down, sides[anthropic] kept a model the base had
plainly dropped, and the fetch after that read it as a base that couldn't
be asked and held the model one round longer than it should have. It is
self-healing — the next round with the base answering settles it — and it
is the same fault c8fabd70 was written to undo, read from the other side.

sides may only say what the bases listed. A model kept for a failed key
belongs to a base that was not asked this round for any of the model's own
keys: one that was, and answered without the model, has said what it
serves today and no longer owns it. Which is per key, not per provider:
fetchOne answers which of its bases replied, which a model of the second
key alone never saw an answer from, so the base's saying nothing about it
for the first key leaves it that base's. The keys a model is kept under
are read from the list saved before, since add clears the ones of the model
it is adding.

TestFetchDropsAModelABaseStoppedServingWhileAKeyIsDown fails on c8fabd70
with the part holding claude-b, and TestFetchKeepsAModelsBaseAfterItsKeyFailedWhole
goes on passing: the same two keys, a model only one of them sees.

Co-authored-by: multica-agent <github@multica.ai>

* provider, catalog: a page of a model list is not the list (#904)

A /v1/models that answers with has_more is one page of the vendor's
catalog. Read as the whole list, every model of a later page reads as one
the vendor has dropped, and the user's pick of it goes for good, on a
list that never said so. Such a reply is no answer: the base is treated
as one that could not be asked, which keeps what it listed last time
(#904's review of #1006).

OpenRouter's Anthropic base is not asked for the list at all. With the
Anthropic version header its /models answers with the catalog again,
twenty newest first, every id namespaced under `anthropic/`, and the
cursors of the pages after. None of those twenty is an id in OpenRouter's
own catalog, so merged they are entries of the model picker that name no
model: the long, cluttered list #904's reporter wrote of. Its Chat base
is that catalog, whole, and the fetch is one request where it was two.
The rule is OpenRouter's, by host, as the ones after it are scoped to
their vendors.

Co-authored-by: multica-agent <github@multica.ai>

* provider: the OpenRouter rule reads the base being asked (0fb16990)

It read the Chat base's host, so a provider with a Chat base of
OpenRouter's and an Anthropic base of another vendor's had that other
base skipped: its models were in neither the union nor the sides nor the
bases that could not be asked, so no keepDeadSides path found them and
the user's picks of them went for good. `magpie provider set <id>
anthropic=<url>` reaches that shape from the CLI.

The rule is about the vendor whose base is being asked, so that is what
it now reads, together with whether the provider asks at a base of its
own besides it: an OpenRouter Anthropic base alone is still asked, its
reply being the only catalog there would otherwise be, and
catalog.fetchOne is what keeps a page of it from being read as the whole.

Five combinations of the two bases and openrouter.ai, one assertion each;
three of them fail on 0fb16990.

Co-authored-by: multica-agent <github@multica.ai>

* catalog, provider: a model list is followed to its last page, not read as a page (#1006)

A reply with has_more was refused as no answer at all, which is right for a
provider with several bases and wrong for one with a single base: Anthropic's
own preset has no other base to fall back on, so once its list passes twenty
models — about sixteen today — the fetch answered an error and no models,
where main listed the twenty of the first page, and a pick of a model on a
later page went with them. catalog.fetchOne now reads a list to its end: the
first page as the URL stands, and every page after it with limit=1000 and
the after_id the page before ended at, up to twenty pages.

Half a list is still no answer, and that is what the following ends on: a
page that fails, a list that pages without naming the id to carry on from,
one that answers the page just asked again under the same id, and one still
paging at the cap all leave the base as one that could not be asked, which
keeps what it listed last time. The rule lives in catalog.Paged, and the
Kilo gateway's list — OpenRouter's shape, which pages the same way — is paged
by it instead of refused by a guard of its own; the comment on that guard
claimed OpenRouter's /models pages, which neither api.kilo.ai nor
openrouter.ai was answering with on 2026-10-06, and now says so.

One assertion of TestFetchOpenRouterRuleOverTheFourBaseCombinations follows
the rule rather than the old count: OpenRouter's Anthropic base alone is
asked for its first page and the page after it, which is the same page
again, where before it was asked once and refused.

Tests: TestFetchFollowsThePagesOfAList, TestFetchFollowsAPageAListAnswersItsOwnWay,
TestFetchTakesAPagedListAsNoAnswerWhenAPageFails, TestFetchTakesAPagedListWithoutAnIdAsNoAnswer,
TestFetchTakesAListThatPagesWithoutEndAsNoAnswer (catalog);
TestFetchFollowsThePagesOfASingleAnthropicBase (provider, the Anthropic preset's
one base, 25 models 20 to a page) and TestKiloModelsFollowThePagesOfTheList.

Co-authored-by: multica-agent <github@multica.ai>

* provider: OpenRouter's Anthropic base alone is asked, and refused (#1006)

The fake that stands for openrouter.ai answered every cursor with the same
twenty ids under the same last_id, so following the pages of a list stopped
where the rule of catalog.Paged says a list stops being readable, and the
single-base case looked covered: the twenty were refused and the fetch
failed. The endpoint does not answer that way. Asked with the Anthropic
version header on 2026-10-06, /api/v1/models gave those twenty with
has_more and a cursor, and under the cursor 413 more ids with has_more
false — a different set, and the end of the list. The two pages share
nothing, and following them lands deeper in the `anthropic/` namespace
rather than back at the catalog it was namespaced from: of the 433 ids, 4
are in the 466 OpenRouter serves without that header.

So the twenty were not a page to be refused but the first half of a list
that reads to the end, and the end is still not a catalog of models to
serve. The base is still asked — it is the only base there is, and refusing
to ask would leave the provider with nothing at all — and the list it
answers with is now refused as a whole, which is what the old rule did with
one page of it. It fails the fetch like any other base that could not be
asked, so the provider keeps the models it listed last time (#904).

The two replies are kept as they came, under testdata, and a test reads
them back: twenty, then 413, the cursor the first ends at, has_more true
and then false, and not one id of either page in the catalog OpenRouter
serves. The fake pages with after_id, as the endpoint does.

Tests: TestOpenRouterNamespacedPagesAreTheEndpointShape (new),
TestFetchOpenRouterRuleOverTheFourBaseCombinations (the single-base case now
asks exactly the two pages it answers with, keeps no list, and fails),
TestFetchKeepsPicksWhenAModelListIsPaginated, TestFetchDoesNotMergeOpenRouter's
NamespacedList, TestFetchOpenRouterAddsNoNamespacedModelAndKeepsPicks,
TestFetchKeepsAnotherVendorsAnthropicList.

Co-authored-by: multica-agent <github@multica.ai>

* provider: the message for a namespaced list counts nothing (#1006)

The reason a provider whose only base is OpenRouter's Anthropic one is
refused is still the one it was, and the base is still asked and refused
exactly as before: what changed is the sentence the user is left with, and
the comments around it.

That sentence counted the list it refused — "433 of them, of which 4 are
ids OpenRouter serves" — and those counts are of whatever OpenRouter's
catalog was that day, so the number a user reads is wrong tomorrow without
anyone touching it. It now says why the answer is no good and what to do
instead: give this provider OpenRouter's Chat base, which lists those
models under the ids OpenRouter serves, or type the model ids in by hand,
which is what the caller already appends to every base it could not ask.

The comments said the same counts as fact, and cited a probe file that is
not in the repository. The counts stay, marked as what was observed on
2026-10-06, and what does not move is now the point: following the pages
of the list lands deeper in the namespace, not back at the catalog it was
namespaced from. The dead file references are gone, and one test checks
that the message counts nothing at all, so a count cannot creep back in.

Tests: TestFetchOpenRouterRuleOverTheFourBaseCombinations (the message names
the Chat base and the ids to type, and holds no number but the version in
that base's path).

Co-authored-by: multica-agent <github@multica.ai>

* provider: the list of a multi-protocol vendor is asked once (#1006)

The dedup added in 952d0b00 is keyed by the base URL as it is configured,
which is neither of the two things that decide whether a list is asked
again: which list URL the request goes to, and what it authenticates with.
Both of a vendor's ends were lost to it. A Chat base and the Anthropic
base of the same remote magpie are two strings, one list — GET /v1/models
— and it was fetched twice, which #1282 says a remote's test does not do.
And one base string serving Chat, Anthropic and Gemini is three requests:
the Chat request refused a 401 took the other two for lists already had,
so a vendor whose models were all there was reported as serving none.

The key is now the list URL and the authentication, in catalog.Listed, and
it gives two rules. A list URL this key has listed is not asked again by
any protocol — the answer is the answer, so …/v1 and the bare host beside
it are one request. And a request already made is not made again, but a
URL refused under one authentication is not refused under the next, so
the Gemini and Anthropic lists of a base whose Chat request was refused
are asked, each with its own. The base string is left out of the key on
purpose: Chat and Responses at one base are one request because both send
Bearer at the same URL, not because the strings match.

A base whose every list was asked already and none answered says so with
catalog.ErrAsked, which the caller reads as "nothing new here" rather
than as a second refusal to put in the message the user reads.

Tests: TestFetchAsksEachAuthenticationAtOneBase, TestFetchAsksOneListOnce
ForTwoBasesOfIt, TestFetchReportsOneRefusalForOneBaseAskedTwice.

Co-authored-by: multica-agent <github@multica.ai>

* provider: a Gemini base that fails once no longer deletes the picked model it listed

The union fetch merges a Gemini base's list like any other protocol's, but
it kept none of the fetch's bookkeeping for it: what it listed was in no
`side`, so the parts saved beside the catalog said no base listed it, and a
base that could not be asked was in no `dead` either, so `keepDeadSides`
never saw it. A picked Gemini model was therefore dropped from the user's
provider for good the first time the Gemini endpoint answered 502 or timed
out — the fault the Anthropic base of the same fetch was fixed for in
#904. A Gemini base also went uncounted in `asked`, so a two-base provider's
parts were saved on the strength of one base asked.

A Gemini base now joins `asked` before it is asked, joins `sides` and
`answered` with what it listed, and joins `dead` when it cannot be asked.
What a failed Gemini base keeps is its own models alone, so a model its list
has really dropped is still dropped from the picks.

Verified at 20ee273aaedc10ab0baf06cffbd826ddc367be3c + this commit, Go
1.26.8, darwin/arm64, under a temporary HOME with GOPATH, GOMODCACHE and
GOCACHE pinned.

Without the change (internal/provider/models.go put back):

    go test ./internal/provider -run 'TestFetchKeepsTheModelsAFailedGeminiBaseListed|TestFetchDropsAGoneGeminiModelWhileAnotherProtocolFails'
    multiproto_models_test.go:713: picks after the Gemini base failed: [gpt-a], want [gpt-a claude-b]
    multiproto_models_test.go:824: picks after the Gemini list dropped a model: [gpt-a gpt-b claude-b claude-c], want [gpt-a gpt-b claude-b]
    FAIL (exit 1)

With it:

    go test ./internal/provider -run 'TestFetchKeepsTheModelsAFailedGeminiBaseListed|TestFetchDropsAGoneGeminiModelWhileAnotherProtocolFails'
    ok (exit 0)

    go test -tags nogui ./internal/provider -count=1
    ok  github.com/yetone/magpie/internal/provider  109.187s (exit 0)

    gofmt -l internal/provider/models.go internal/provider/multiproto_models_test.go   (prints nothing)
    go vet ./internal/provider                                                       (exit 0)
    GOOS=linux go vet -tags nogui ./...                                               (exit 0)
    GOOS=windows go vet ./...                                                         (exit 0)
    go build ./...                                                                     (exit 0)
    GOOS=linux go build -tags nogui ./...                                              (exit 0)
    GOOS=windows go build ./...                                                        (exit 0)

The maintainer's own reproduction of the first failure, run on 20ee273a
before anything was changed, is the same one line and exits 1:

    --- FAIL: TestZZGeminiSideKept (0.04s)
        zz_gem_test.go:81: picks after a protocol failed: [gpt-a], want [gpt-a claude-b]

The whole-repository `go test -tags nogui ./...` was not run: the change
touches only internal/provider, and that package's full suite is green.

Co-authored-by: multica-agent <github@multica.ai>

---------

Co-authored-by: multica-agent <github@multica.ai>
2026-10-13 13:42:56 +08:00
yetoneandmengyianx f31ae38aeb provider: Xiaomi MiMo is priced at xiaomi's list price, not its Token Plans' $0, and pay as you go looks only in xiaomi (#1873)
mengyianx found every pay-as-you-go MiMo call counted at $0.000:
models.dev's xiaomi-token-plan-cn, -sgp and -ams list all nine models
at cost 0 (the plan's per-token charge, not the model's price), the
preset's catalog was "xiaomi-token-plan-cn, xiaomi" at every region, and
catalog.PricedBy takes the first catalog with a cost field. makerCatalogs
puts the plan catalog ahead of xiaomi too, so the maker fallback gave $0
as well.

What changed:
- membershipCatalogs (never read for a price) gains the three
  xiaomi-token-plan catalogs, as #1370 did for Kimi Code. That covers
  ListPrice, MakerPrice and PricedName through makerPriceCatalogs.
  kimiCodeMember now checks a list of Kimi Code's plans of its own
  (kimiCodePlans), so a Xiaomi provider isn't taken for Kimi Code and
  its ids aren't mapped to Kimi's.
- Each Xiaomi region names its own catalog: plan-cn/sgp/ams
  "xiaomi-token-plan-<r>, xiaomi", pay as you go "xiaomi" alone. A plan
  user is priced at the API-equivalent price, the same meaning as #1370.
- PricedBy is unchanged: a catalog that lists a model at $0 still prices
  it at $0 (nvidia, modelscope have truly free models).
- docs/subsystems/providers-accounts.md says so.

Providers saved before this: the preset's own catalog stays
"xiaomi-token-plan-cn, xiaomi", the same string an existing provider
saved with the old default holds. normalize already lets a catalog that
equals the preset's or one of its regions' follow the region the
provider is at (the Tencent Cloud mechanism), on every read, so an old
default at pay-as-you-go reads as "xiaomi" and at Singapore as
"xiaomi-token-plan-sgp, xiaomi"; nothing is written to providers.json
until the user next saves it. Any other catalog the user typed is kept
as typed, and is priced right anyway because the plan catalogs are out
of pricing. The one value that can't be told apart is a bare "xiaomi"
typed at a plan region (the issue's workaround, which was for pay as
you go): it equals the pay-as-you-go region's catalog, so it reads as
that plan's "xiaomi-token-plan-<r>, xiaomi". Its prices are identical
either way; only the model-metadata lookup order differs. That is the
existing rule for every preset with region catalogs, kept rather than
special-cased.

Siblings: scanned the models.dev cache (read only) for catalogs whose
priced models are all or mostly $0. Of those, only kimi-code-plan-* and
xiaomi-token-plan-* are named by any preset or region. stepfun's
*-step-plan catalogs carry no cost at all, so they never shadowed a
price. alibaba/minimax/zai/zhipuai/volcengine/tencent coding and token
plan catalogs are all-$0 on models.dev but no preset uses them.

Tests (internal/provider/xiaomi_price_test.go, fixture
testdata/xiaomi_catalog.json cut from models.dev's real entries):
- TestXiaomiListPrice: every region, the old default, a user's own
  catalogs: mimo-v2.6-flash $0.14/$0.28/$0.0028, mimo-v2.6-pro
  $0.435/$0.87/$0.0036; MakerPrice; EffectivePrice of a saved provider;
  a relay's own $0 model ahead of xiaomi stays $0; a Xiaomi provider is
  not a Kimi Code member.
- TestXiaomiRegionCatalogs: each region resolves to its catalogs from
  the preset's, the old default and another region's; import links at
  each region; FromPreset; a user's catalog kept at two regions.

Broken by hand, each red, then restored:
- membershipCatalogs back to Kimi only: TestXiaomiListPrice FAIL, plan
  regions and MakerPrice at $0.
- region catalogs removed: TestXiaomiRegionCatalogs FAIL (api with the
  old default stays [xiaomi-token-plan-cn xiaomi], imports at sgp/ams
  get cn's).
- both: TestXiaomiListPrice FAIL, api with the old default at $0 (the
  reported bug).
- kimiCodeMember on membershipCatalogs: FAIL "a Xiaomi Token Plan
  provider counts as a Kimi Code membership".
- PricedBy's exact match skipping all-zero costs: FAIL "relay
  mimo-v2.6-flash: ... want its own $0".

Run: gofmt -l (nothing); go vet ./... on darwin, GOOS=linux -tags nogui,
GOOS=windows; go build on all three; go test -tags nogui -count=1
./internal/provider ./internal/catalog ./internal/cli ./internal/gui
./internal/usage, all ok, in a sandbox HOME with pinned caches.
Real use: built binaries before and after, sandbox HOME with a copy of
the real models.dev cache and a providers.json holding the reporter's
saved state. `magpie model price xiaomi/mimo-v2.6-flash` printed $0/$0
before and $0.14/$0.28 after; an old-default provider at Singapore went
$0 -> $0.14/$0.28 and shows catalog "xiaomi-token-plan-sgp, xiaomi";
one with the user's "openrouter, xiaomi" kept it; providers.json was
byte-identical afterwards. Not tried: a real MiMo key or call, the GUI
editor's region switch, the full go test ./... suite.

Co-authored-by: mengyianx <106875577+mengyianx@users.noreply.github.com>
2026-10-13 05:57:40 +08:00
yetone ee657c0969 usage: a Kimi Code membership's k3 is counted at Kimi's API price for kimi-k3, not ≈¥0.000, and kimi-for-coding is unpriced rather than free (#1370, maicent: Kimi Code 的模型计费都是 0)
Why it was 0: magpie already counts a subscription's calls at the API list
price (a Claude or Codex account at its maker's, cf6b82f7). A Kimi Code
provider is looked up in its own models.dev catalog first, and models.dev
lists every model of kimi-code-plan-global / kimi-code-plan-cn at $0 (what
the membership charges per token), so k3, k3-256k, kimi-for-coding and
kimi-for-coding-highspeed were all "priced" at $0. The same $0 catalogs
were also among the maker catalogs, so MakerPrice("k3") was $0 too.

What changed (internal/provider/models.go):
- membershipCatalogs (the two Kimi Code plan catalogs) are never read for a
  price: ListPrice, MakerPrice and PricedName skip them.
- A provider served at a Kimi Code catalog prices its model as the Kimi API
  model it is (kimiCodeAPI), per Kimi Code's docs
  (https://www.kimi.com/code/docs/en/, read 2026-10-09): k3 and k3-256k are
  K3 -> kimi-k3; kimi-for-coding-highspeed is K2.7 Code HighSpeed ->
  kimi-k2.7-code-highspeed. models.dev's canonical_model_id agrees. The
  prices come from moonshotai's catalog, which matches Kimi's pricing page
  (https://platform.kimi.ai/docs/pricing/chat: kimi-k3 $3 in, $15 out,
  $0.30 cached, $3 cache write; kimi-k2.7-code-highspeed $1.90/$8/$0.38).
- kimi-for-coding is K2.8 Preview, which the Kimi API doesn't sell: it has
  no API price, so it is now unpriced (the "—" / "no known price" the GUI
  already shows) instead of ¥0.000. The user can give it a price with
  `magpie model price kimi-code/kimi-for-coding …` or in Names & levels.
- The alias is scoped to Kimi Code providers: a relay's own "k3" keeps its
  own catalog price; Moonshot pay-as-you-go's kimi-k3, an OpenCode free
  model ($0) and Codex's maker price are unchanged.
- PricedNameFor(provider, model): the Requests list's "API price
  reference" names kimi-k3 for a Kimi Code k3 (internal/gui/usage.go).
Docs: reference.md (What a model costs) and providers-accounts.md.

Tests: TestKimiCodeListPrice (internal/provider; fixture
testdata/kimi_code_catalog.json is models.dev's own moonshotai and Kimi Code
plan entries) and TestKimiCodeCost (internal/usage; the reporter's k3 row,
240K in / 78.4K out / 10.0M cached, counted at $4.896 in the ledger and the
summary, kimi-for-coding unpriced, moonshot/kimi-k3 unchanged). Both fail on
the old models.go (every Kimi Code model priced at $0, MakerPrice(k3) $0,
k3 cost=0, unpriced 0); PricedNameFor's check fails with the alias turned
off ("k3-256k").

Run: gofmt -l (empty); go vet -tags nogui, GOOS=linux go vet -tags nogui,
GOOS=windows go vet -tags nogui on internal/provider, internal/usage,
internal/gui; go build, GOOS=linux go build -tags nogui, GOOS=windows go
build; go test -tags nogui -count=1 ./... under a temp HOME with pinned
caches: all ok; -race -count=3 on the new tests ok. No GUI asset changed,
so the Playwright suite wasn't run. Not tried with a real Kimi Code
account or the reporter's usage log.
2026-10-09 11:48:41 +08:00
yetone faab600e50 provider: a tool's root union whose branches are unions themselves folds with their fields kept, so Grok can create a Codex automation (#1271)
xiaocui12: Codex on Grok, "[invalid_client_tool_schema]
mcp__codex_app__automation_update: tool parameter root must be an object
type (root schema is an anyOf/oneOf union with a non-object branch)".
Codex desktop's automation_update (ChatGPT.app 26.930, zod 4's
toJSONSchema with $defs) is a root anyOf of view, delete, create and
update, and create and update are unions on kind themselves. ObjectRoot
dropped those nested branches: the fold kept only mode (const "view") and
id, both required. Grok took the tool but could only view.

A branch that is itself a union is now folded first (on a copy, up to 8
deep); a field the root doesn't define takes each distinct schema the
branches give it, as anyOf when they differ; a field every branch
requires stays required (here only mode).

Verified with the real Grok subscription and the real schema
(testdata, rebuilt with zod 4.1.8 from ChatGPT.app's app.asar): raw, 400
with the reporter's exact message; the old fold, 200 but no tool call when
asked to create an automation; the new fold, 200 and
{"mode":"create","kind":"heartbeat","name":"CI watch","prompt":"check CI",
"status":"ACTIVE","destination":"thread","rrule":"FREQ=MINUTELY;INTERVAL=30"}.
TestObjectRootNestedUnion fails without the change ("no name among
[id mode]", "required = [mode id]", mode leaves out "delete", kind null).
2026-10-08 17:01:22 +08:00
forever b0a96cbbd7 gateway, provider, gui: a Sub2API key given 5h/1d/7d limits is weighed and rested by its own windows, like an account (#1004)
* gateway: a Sub2API key out of its 5h/1d/7d limit ("…限额已用完") rests as out of quota, not a 1-minute rate limit

Sub2API refuses a key that has spent the 5-hour, day or 7-day limit its
owner gave it with 429 "api key 7天限额已用完" (or 日限额, 5小时限额),
typed rate_limit_exceeded. It matched rateWords and not plannedWords
("限额" is not "额度"), so failure() said rate: the key rested a minute,
was tried again, refused again, and sank, for the days its 7-day window
had left. plannedWords now has 限额已用完, so it is failQuota.

The relay's other refusals keep their classes, fixed by the test: the
pool out of accounts (v0.1.149's 503 "No available accounts": other;
later versions' 429 "All available accounts are currently
rate-limited": rate), its upstream's rate limit (rate), the key's own
total quota API_KEY_QUOTA_EXHAUSTED (quota) and the wallet's 403
INSUFFICIENT_BALANCE (credit).

Verified: TestSub2APIKeyLimitIsQuota, with Sub2API v0.1.149's message
bodies. Without the change it fails: "429 {…api key 7天限额已用完…}:
rate, want quota", and the same for 日限额 and 5小时限额.

* provider: a Sub2API key's /v1/usage shows its 5 hours / 1 day / 7 days windows instead of nothing at "remaining"

A Sub2API key its owner gave a 5-hour, day or 7-day spending limit
answers /v1/usage in quota_limited mode with rate_limits — each
window's limit, used and reset_at in dollars — and, without a total
quota of its own, no "remaining". With the Balance URL set to it, the
key's card said `nothing at "remaining" in the reply`.

readSub2APIKeyLimits reads rate_limits into the windows the cards
already name 5 hours, 1 day and 7 days, in USD. A window not started
(used 0, no reset_at) is taken to renew a span from now; a window with
a limit of 0 is none. The card shows them, beside a balance field the
user wrote; with none, Check balance and `magpie provider show` give
what the fullest window has left. A wallet key's reply is unchanged.

KeyAllowance gives routing the same windows, per provider and key: read
behind the request, never waited for, at most once a minute (once for
any number of asks at a time); a failed read keeps the last; after a
restart it is seeded from the card's last reading in quotas.json;
StaleKeyAllowance has it read again at the next ask. ForgetBalances (a
key or Balance URL changed) has every key read again, a read begun
before dropped, the last reading standing until then. Only keys whose
Balance URL is a Sub2API /v1/usage are asked: any other key, and every
account, costs nothing here.

Verified with real bytes of a limited key's reply, its key removed
(testdata/sub2api_usage_key_limits*.json): TestReadSub2APIKeyLimits,
TestSub2APIKeyLimitsOnItsCard, TestKeyAllowance*. Each fails without
its part, e.g. the card without the windows: `Error:nothing at
"remaining" in the reply`; KeyAllowance waiting for the read: "waited
30.0s"; asking every time: "asked 11 times"; a failed read asked again
at once: "asked 22 times after failing"; not seeded: "seeded = [],
false"; any key asked: "asked /api/usage/token"; ForgetBalances
dropping what was read: "after ForgetBalances, and a read begun before
it: []"; leaving a read under way loading: "the key's windows were
never read"; a stale-generation read landing: it replaced 95%; a limit
of 0 taken: "a day's limit of 0 = [{… Used:100 …}]"; Balance from the
first window only: "$300.00" for $80 left.

* gateway, gui: keys whose windows magpie reads are weighed and rested by them, like accounts

Smart, least-used and pace routing weighed only subscriptions by their
windows: weighRouted skipped every key (c.p.Account == nil), so a
Sub2API key beside Codex accounts in a group went by its place in the
order, and, refused for its 7-day limit, rested a quarter of an hour at
a time while the window had days to run.

A key whose own windows magpie reads (KeyAllowance: a Sub2API key given
a 5h/1d/7d limit, its Balance URL /v1/usage) is now weighed as an
account is: fine, low (90%) or spent (98%), the one renewing soonest
first, in a provider and in a group alike, and its trace row carries
them. Out of quota it rests till the window it filled renews, by
candidate.full; when its windows as last read aren't full it rests
quotaRest, and either way they are read again (staleKeyAllowance).
Every other failure of a key backs off as before, never to the window:
the relay out of accounts for everyone (503/429) says nothing of the
key's own spend. capHeld and pooled stay accounts' only. Keys magpie
reads no windows of are ordered exactly as before.

The Routing page tells such a key as it does an account: its row's bar,
used share and renewal, why it went first by its allowance, "Every key
and account here is at 90% or more", and the Smart header. A key not
read yet beside one read is told as weighed with it, not "keys go in
their order" or by its tokens. New strings in en, zh, ja and de.

Other users of the relay draining its accounts don't show in a key's
windows, which count only its spend: they show as the pool's 503/429,
which back off and fall over to the next key, account or fallback.

Verified: TestKeysWeighedByTheirWindows, TestGroupWeighsKeyWindows,
TestKeyOutOfItsWindowRestsUntilReset, TestKeyPoolErrorDoesNotRestForWindow;
and routing-key-windows.test.cjs in Chromium and WebKit (en/zh/ja/de).
Without the change they fail: "smart: kw#a kw#b kw#c"; "the key renewing
first: codex sub2api"; "full: rests 14m59.99s by quota"; "read again:
[]"; backing off to the window: "pool empty: rests 71h59m59.99s by
window (other)"; and on the page "relay-a goes first: keys go in their
order, those that suit the request first." where all are at 90% or
more, or a key not read yet beside one read.

* gateway, provider: a Sub2API key out of its limit is back once its windows read short of full, not only when the window renews

A key refused for its 5h/1d/7d limit rests till the window it filled
renews: days, for the week. Its windows are read again behind the next
requests (a minute apart) and by its card, but nothing lifted the rest
when they came back short of full, so the owner raising the key's limit
in the relay's panel, or resetting its usage, left the key out till the
week turned, though the relay would take it at once. Accounts have this
already: a Codex reset spent tells OnRenewed, and the gateway lifts the
account's rests (renewed).

A key's reading, routing's or its card's, now tells OnRenewed the same
way, as agent "" and the key's KeyAllowanceID, when a window it was full
in (Allowance.Full at SpentShareOf its routing, as candidate.full counts
it) is full no more, or full till sooner. Its first reading, a failed
read, or one that finds it fuller tells nothing. The gateway notes the
key's KeyAllowanceID on its rest out of quota only, so renewed lifts
that rest and no other: the relay out of accounts for everyone (503)
still backs off, and another key still out of its week stays out.

Where nothing weighs the key by its windows, nothing read them again
either: an ordered group weighs each member's keys alone, so a member
with one key, like a provider with one key, never asks for them. After
the one read its 429 starts, the key sat out its week on that reading.
restingOf, which plans a resting key behind the rest, now asks for the
windows of a key resting out of them (agent "" and a user on its rest),
so the next request planned past a minute reads them, behind it, and a
reading short of full brings the key back there too. No card is read
for it, and a key resting for any other reason asks nothing.

Verified: TestKeyAllowanceRenewed (provider) and
TestKeyBackOnceItsWindowIsNotFull (gateway, end to end through the key
cards' reads and restAfter), each failing with a piece of the change
undone: never telling, "its week's limit raised to $1,000: told []" and
"a, its limit raised: still rests by window till …"; telling on any
change, "its first reading, out of its week: told [/sub2api#…]"; a
failed read telling, "a read that failed: told [… …]"; the card not
telling, "its usage reset, read on its card: told [/sub2api#…]"; the
rest not noted, "a, its limit raised: still rests by window"; every
rest of a key noted, "c, the relay out of accounts: …, false"; renewed
not matching the key, "b, still out of its week: …, false". And
TestRestingKeyReadAgainInAnOrderedGroup (gateway: an ordered group, its
first member one key on a fake /v1/usage, no card read after the 429),
failing without restingOf's ask: "its limit raised: still rests by
window till …, its windows read 1 times".

Tried on a real Sub2API v0.1.149 relay, in a sandbox HOME, its key's 7d
limit lowered under its spend for the test and then restored, with
magpie serve on a group ordered: the key, then a local stand-in. The
key answered 429 "api key 7天限额已用完"; it rested by window till its
7d reset, 2026-10-13 00:00 +08:00, and the stand-in served. Planned
again a minute later, still over, it still rested. With the limit back
at $800, the next request was planned with it resting, the stand-in
serving, and read its windows; the one after went to the key, 200.
2026-10-06 18:57:47 +08:00
forever 8005f17551 provider, codex: a ChatGPT account at 100% with credits left keeps Codex signed in (#966)
* provider, codex: a ChatGPT account at 100% with credits left keeps Codex signed in — magpie becomes its provider only while the Codex app itself holds the account

magpie made itself Codex's provider (model_provider = "magpie", #540)
whenever any of the active ChatGPT account's windows read 100%. A Pro
account at 100% on its week with credits left keeps working in the Codex
app: the backend answers every turn (about 490 200s in one day's usage log
at 100%), yet magpie moved Codex off it, and as a provider without
requires_openai_auth the app lost its ChatGPT state ("Sign in to ChatGPT
to start a durable thread", no remote control).

CodexUsedUp now reads codexHeld, which mirrors the Codex app's own
composer block (ChatGPT.app webview bundle, hP and its helpers): the
backend says the account isn't allowed (rate_limit.allowed = false), it
has no credits (has_credits / unlimited), and it isn't a workspace still
within its overage (overage_limit_reached = false, no spend cap, an
ordinary rate_limit_reached). Window percent never decides it. Where the
app goes by what /wham/usage can't show (a statsig gate, the gpt-reserve
fallback, Team's reserve experiment that ignores overage), it counts as
held: a wrong move costs ChatGPT extras, a missed one every turn. A
reading kept through a failed read (keepLast) stops saying held once its
used-up window has started again, as its usage does. NextLogin's account
rotation and its thresholds are unchanged.

A user stuck on the old move (codex.out = 1) is put back beside the
sign-in by the next Sync, as #540 already does once the account has room.

Verification:
- TestCodexUsedUpIsWhatTheAppHolds (real /wham/usage replies, ids
  replaced) fails on the old trigger: 7 subcases, "CodexUsedUp = true,
  want false". Each workspace guard (spend cap, reason, overage, plan
  list, Team reserve) was mutated and fails its own subcase.
- TestCodexHeldKeptOnlyTillTheReset fails without the quota_last change.
- The real Pro account (7-day window 100%, ~28k credits, allowed false):
  CodexUsedUp true before, false after.
- go vet ./...; go build (darwin), GOOS=linux -tags nogui, GOOS=windows;
  go test -tags nogui ./... under a sandbox HOME; -race -count=20 on the
  new and related Codex tests.
- Not run: a live Codex app turn on an account truly held (none at hand),
  Windows/WSL runtime, GUI suites (no GUI change).

* provider: a Codex account at a spend cap or past its overage is held, credits or not; limit_reached counts as not allowed

codexHeld let credits through before the spend cap, so a Team seat at its
cap (spend_control.reached, allowed false) with has_credits read not held
and magpie left Codex on an account the backend refuses. The app's
readiness check (26.930.61225, app-primary) returns limited on
spend_control.reached or credits.overage_limit_reached before it looks at
credits, and treats rate_limit.limit_reached like allowed false; held now
reads the same. A spend cap with the rate limit still allowed (a
workspace's included usage) stays not held.
2026-10-06 14:50:39 +08:00
yetone b00387f9db provider: a Command Code Go account lists the models Command Code has for Go, not ten (01huadalang on Discord: command 账号登录只有十个模型,正确的应该是几十个) — for Go, magpie never asked for a list and showed a table of 10, on the word that Command Code has none; its Provider API's list answers without a key (86 models), and its CLI (1.73.0) offers Go every model its picker shows but the premium ones and those it blocks for Go. A Go account now fetches that list without its key, less the 30 refused, and saves it (56 today); the table, the CLI's whole Go set (57), stands in until then or when the fetch fails. Requests still go to /alpha/generate. TestCommandCodeGoModels fails without the change (10 models). go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./internal/provider pass. 2026-10-01 06:15:04 +08:00