diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index b64d82bb1..d75d54aad 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -32,7 +32,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; a name ending `:latest`, as the ollama CLI asks, is the bare id unless a model is really called that (`ollamaName`); the client then chats on `/v1/chat/completions`, or on Ollama's own `POST /api/chat` and `POST /api/generate` (`ollama_chat.go`, Zed's Ollama provider, super_lalalalala on Discord), which `ollamaChatBody` turns into a `/v1/chat/completions` body handed to the same `handle(provider.Chat)` on a clone of the request, so they are routed, held to a key's models and counted as it is: `messages` with `images` (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's `thinking` as `reasoning_content` and its `tool_calls` given ids where Ollama sent none, a tool result matched to its call by `tool_call_id`, else `tool_name`, else in order (one with no call is a 400), `tools`, `format` (`json` or a schema), `think` (a level is `reasoning_effort`), and `options`' `temperature`, `top_p`, `seed`, `stop`, the two penalties and a positive `num_predict` as `max_tokens` (`num_ctx`, `top_k` and the rest of Ollama's own are dropped); `ollamaWriter` turns the reply into Ollama's NDJSON lines (streamed unless `stream:false`, then one object), tool calls with their `arguments` as an object and an `id`, and a last `done` line with `done_reason` and the token counts, and an error into `{"error":"…"}` with the status `/v1` would give; a request with no messages or prompt is answered `done_reason:"load"`, as Ollama does to warm a model), `/mcp/{name}`, `/mcp/magpie/web-search`, `/mcp/magpie/vision` and `/mcp/magpie/image` with its `/mcp/magpie/image/files/{name}` (magpie's own web search, image recognition and image generation as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/magpie/goroutines` (`goroutineDump`, [`goroutines.go`](../../internal/gateway/goroutines.go), for `magpie goroutines`, #3362) answers every goroutine's stack and wait as text (`runtime/pprof`'s `goroutine` profile at debug 2) to the same callers, through `goroutinesRefused`, and is answered ahead of everything below (`dumpFirst`, around `Handler`'s wrappers and around `lanGuard` in `Front`), since it is asked for while magpie hangs: the allow list reads settings.json under its lock, and `holdCatalog` takes `provider.Hold`'s and `filememo`'s, so a stuck holder of any of them would hold the dump too; a caller `goroutinesRefused` lets in is one those let in anyway, and any other goes through them as before (`TestGoroutineDumpAnswersWhileRequestsWait`). `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A WebSocket upgrade on `/v1/responses`, `/responses` or the Codex backend's `/responses` is Responses over a WebSocket, as Codex speaks it (below, [A Responses WebSocket](#a-responses-websocket)); one on another Codex backend path is answered 426, and a plain GET on `/v1/responses` 405. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`), and its port hands the gateway's client routes (`ClientPath`) to `Server.Front`, the same lanGuard-over-Handler the gateway's listener serves, each marked by `FromPagePort` so `local` is false for it (`viaPagePort`; `lanGuard` refuses it 403 while magpie isn't shared, saying to call the gateway's own address, and asks a gateway key otherwise): a raw TCP forward or a proxy with no forwarding header reaches that port from loopback, so no request there counts as an agent here (`TestClientPathCoversHandler` fails when a route Handler adds is in neither `ClientPath` nor its list of routes that stay on the gateway's port). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`ollama.go`](../../internal/gateway/ollama.go), [`ollama_chat.go`](../../internal/gateway/ollama_chat.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | | Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider — in a WSL distro, the distro's own, of the ones running now — for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key; a memory call first waits beside the turn it was started with, through `codexLeads`, see the side turns below), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. A provider the user keeps out of found groups (Routing's "Leave out a provider", `provider.SetAutoGroupSkip`, `autoGroupSkip` in providers.json; chenxiang0010 on Discord) is in none of them, so a model one other provider serves is no group; the groups the user made or changed keep it. A request still naming a found group that took away goes to its model from a provider not kept out (`AutoStandIn`), and an agent set to it is moved there (`agent.Reseat`). magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | | A found group's two ids | A group magpie found is listed (`/v1/models`, the catalog, the lists written into agents, the pickers, the CLI and TUI) as `auto/`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). The spelling is the one models.dev gives the model most (`catalog.Spelling`, its `normal` index: `glm-5.3-flash` whether the members serve `glm-5-3-flash`, Ark's dated id or `glm-5.3-flash`), so it no longer follows the order the providers were added in; for a model models.dev doesn't know, the first member's spelling it lists, else the first member's. The group's name comes from the same choice (`autoGroups`): the name models.dev gives that spelling (`catalog.NameOf`), else a vendor's own name for it, else the spelling itself; they were picked apart, a name of `glm-5-3-flash` beside `auto/glm-5.3-flash` (XYenon on Discord, `TestFoundGroupIDAndNameAreOneSpelling`). A found group the user changed keeps the name they saved. Every spelling it was listed by before is still the group (`CanonicalRef`), and `PublicRef` takes one to the spelling now. Its old id `group/auto-` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/` by the old id. An agent field magpie set to `group/auto-`, or to an `auto/` spelt otherwise than the group is listed now, moves to `auto/` on the next `SyncCatalog` (`agent.renameFoundGroups`, `TestFoundGroupMovedOffAnOldSpelling`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays, and is still served. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/` is its model and found groups list as `group/auto-` (`autoRefsOn`). Hand-made groups stay `group/`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) | -| A model's own id at a provider | A model the user lists by an id of theirs at a provider of their own (settings' `ModelIDs`, `magpie model id `, the editor's "Listed as"; [Providers and accounts](providers-accounts.md#runtime-path)) is that id everywhere the gateway names it: `/v1/models` and the lists written into agents (`Available`), `Resolve`, the routing groups and the group magpie finds for it (`auto/`, with every other provider serving that id), a gateway key's models, `X-Magpie-Model` and the usage log's `model`. Only the upstream request differs: every place that sends a wire name reads `settings.Wires()`, which is `ModelWires` with each `ModelIDs` entry turned round (`"/"` → the vendor's own id, wrapped by a `/*` wire), so the body, a Vertex path and the usage log's endpoint carry the vendor's id; an explicit `ModelWires` entry for that id wins. The vendor's reply names its own id, which the usage log keeps as `served`. A request still naming `provider/` (an agent's file magpie didn't rewrite) resolves and goes out as it is. A key held to either id passes for both (`modelAllowed` checks the ref, then `OwnModelID`, then `ListedModelID`); a group member passes the same way. An id is given to a model of the provider's chat list or its picks; the image, video and embeddings routes send no wire name, so they are not served under one (`TestLocalModelIDOnEveryRoute`). | [`internal/provider/localid.go`](../../internal/provider/localid.go), [`internal/settings/settings.go`](../../internal/settings/settings.go), [`key_models.go`](../../internal/gateway/key_models.go) | +| A model's own id at a provider | A model the user lists by an id of theirs at a provider (a signed-in account's and a plugin's too; settings' `ModelIDs`, `magpie model id `, the editor's "Listed as"; [Providers and accounts](providers-accounts.md#runtime-path)) is that id everywhere the gateway names it: `/v1/models` and the lists written into agents (`Available`), `Resolve`, the routing groups and the group magpie finds for it (`auto/`, with every other provider serving that id), a gateway key's models, `X-Magpie-Model` and the usage log's `model`. Only the upstream request differs: every place that sends a wire name reads `settings.Wires()`, which is `ModelWires` with each `ModelIDs` entry turned round (`"/"` → the vendor's own id, wrapped by a `/*` wire), so the body, a Vertex path and the usage log's endpoint carry the vendor's id; an explicit `ModelWires` entry for that id wins. The vendor's reply names its own id, which the usage log keeps as `served`. A request still naming `provider/` (an agent's file magpie didn't rewrite) resolves and goes out as it is. A key held to either id passes for both (`modelAllowed` checks the ref, then `OwnModelID`, then `ListedModelID`); a group member passes the same way. An id is given to a model of the provider's chat list or its picks; the image, video and embeddings routes send no wire name, so they are not served under one (`TestLocalModelIDOnEveryRoute`). At an account or a plugin the account's own say of the model is read by the vendor's id: a plugin's API and fetch, Claude Code's `--model`, Antigravity's variant, and which accounts list it and at what levels (`TestLocalModelIDAtAPlugin`, `TestLocalModelIDAtAClaudeAccount`, `TestLocalModelIDAtAnAntigravityAccount`). | [`internal/provider/localid.go`](../../internal/provider/localid.go), [`internal/settings/settings.go`](../../internal/settings/settings.go), [`key_models.go`](../../internal/gateway/key_models.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). A fallback the user unchecked in its own provider's model list is skipped, as a group's member is (`provider.ResolveRoute`, #3911; `fallback_unpicked_test.go`), and so is it where fallbacks are read for careful accounts, native compaction, redaction and Codex's own turns. A fallback can be a routing group (`group/`, 01huadalang on Discord): `planPaused` hands its members to `planLevel` as a request to the group would (`planFallbackGroup`), in the group's own routing and sink, its pause rules applied in `serve`, and its trace rows marked `Fallback` with the group in `Via`. Its turn rules (`ruleFor`, which may ask a classifier) are not applied: the plan is made before the primary is tried, and a classifier call on every request the primary answers costs too much. Each provider/model is tried once a round: a member that is the primary, an earlier fallback or another fallback group's is left out where it came second, so a group holding this provider is no loop (groups have no fallbacks of their own, and a member's are not followed). A group that is gone is passed over. Every place that reads fallbacks (careful accounts, native compaction, redaction, Codex's own turns, Claude's review) reads a group's members through `provider.FallbackModels`. `fallback_group_test.go`. `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576); one left on the default (Smart) in a group that pools (Smart, In turn, Least used, Weekly pace, Free first, Speed first, a plugin's) takes the outer group's, as a provider left on the default does (`provider.Group.Within`, set on `Member.Via`, so the trace's `Subs` and the Routing page read the routing that applies, #3847). In a group In order, By weight or Manual it stays Smart. `TestFreeFirstReachesAGroupInItLeftOnTheDefault`. So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first), `fast` (speed first) or, a group's only, `cheap` (cheapest first). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). `weight` on a provider spreads its keys by each key's `Weight` and a subscription's accounts by each account's (`AccountWeights`, rubbzha on X): `keyWeight` gives a seat its `Weight`, 1 when none is set, and `routes.Weighted` takes them by smooth weighted round robin, a resting one leaving the round and a kept conversation staying as Stays says (`TestWeightedKeys`, `TestAccountWeightSharesRequests`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | | Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). One with no limit still counts its requests out in a lane of `Limit` 0, which never waits, so `Lanes` (`/v1/magpie/concurrency`, the GUI's `/api/lanes`) says how many run there too and the Providers page's pill shows it (chentuoyan on Discord, `TestLanesCountWithNoLimit`); a limit set while they are out counts them. `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 6450b40c8..41814d6f8 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -211,10 +211,15 @@ lists, picks, groups, finds groups by (`auto/` with every other provider serving it), limits gateway keys to and records usage under, while the vendor is asked for its own id: `Settings.Wires()` turns each entry round into a wire name, so every place a `ModelWires` name goes out -sends it, and an explicit `ModelWires` entry for the same id wins. Only a -provider of the user's own takes one (`TakesModelIDs`); an account's or a -plugin's requests are built from its own list's id, which no wire name -reaches. One id is one model of a provider: the latest given it has it, +sends it, and an explicit `ModelWires` entry for the same id wins. A signed-in +account's and a plugin's provider take one too; only a provider that just +decides doesn't (`TakesModelIDs`). Their body goes out by the wire name as +any provider's, and what is read of the model by the vendor's id is read +by `OwnModelID`: a plugin's model (`pluginModel`, so its API, tiers and +prices), Claude Code's run on a Claude account, Code Assist's and +Antigravity's variant (`codeAssistBody`, `SentNameOnIn`), and an +account's own list, levels and tiers (`Account.Lists` in the fallback, +`Levels`, `Tiers`, `AccountServes`). One id is one model of a provider: the latest given it has it, and the one before is listed by its own id again (the CLI names it; the editor refuses two rows given one id in one save). A model of the provider's own id that another is listed by (`grok-4.6` beside diff --git a/internal/gateway/antigravity_pool_test.go b/internal/gateway/antigravity_pool_test.go index 86f3cfca7..606c37b9a 100644 --- a/internal/gateway/antigravity_pool_test.go +++ b/internal/gateway/antigravity_pool_test.go @@ -12,6 +12,7 @@ import ( "time" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" ) // Discovery and routing agree when a new model is available only to a @@ -72,4 +73,19 @@ func TestAntigravityPoolRoutesDiscoveredModels(t *testing.T) { } } } + + // listed by an id of the user's own (SetModelID), the model is still + // the one each account's own list names, levels and all + s := settings.Load() + s.ModelIDs = map[string]string{"antigravity/my-opus": "claude-opus-5-5"} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + on, _, left := perKeyOf(*p, "my-opus", provider.Chat) + if len(on) != 1 || on[0].p.Account.User != "new@example.com" || len(left) != 1 { + t.Fatalf("my-opus: eligible=%d, not listed=%d; expected only new@example.com", len(on), len(left)) + } + if !takesEffort(on[0], "high") || takesEffort(on[0], "xhigh") { + t.Error("my-opus: routing did not use the account's own reasoning levels") + } } diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 0c4802cb4..413735b66 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -4784,7 +4784,9 @@ func (s *Server) serveClaudeSubscription(w http.ResponseWriter, r *http.Request, } return nil, nil, err } - return s.subscription.start(ctx, req, model, dir, owner, from) + // Claude Code is asked for the model by Anthropic's id, not one + // the user lists it by (SetModelID): no wire name reaches its run + return s.subscription.start(ctx, req, p.OwnModelID(model), dir, owner, from) } return s.serveSubscription(w, r, from, "Claude Code", model, owner, body, usage, start) } diff --git a/internal/gateway/codeassist.go b/internal/gateway/codeassist.go index f84041e79..b6328556a 100644 --- a/internal/gateway/codeassist.go +++ b/internal/gateway/codeassist.go @@ -282,6 +282,10 @@ func codeAssistID(model, effort, agent string) string { // in force is looked up against the very id the envelope is addressed to: // asking twice reads the vendor's catalogue twice over for one answer. func codeAssistBody(p provider.Provider, r *Request, model string, wires map[string]string) []byte { + // a model the user lists by an id of theirs (SetModelID) is the + // account's own model: its envelope, the variant the effort picks and + // a name for the whole provider are of the vendor's id + model = p.OwnModelID(model) sent := codeAssistID(model, r.Effort, p.Account.Agent) if p.Account.Agent == "antigravity" && !p.PromptAsWritten { // the lines Google turns away, broken up; the request the diff --git a/internal/gateway/effort_accounts.go b/internal/gateway/effort_accounts.go index 4d8ccb68a..b644ed9b6 100644 --- a/internal/gateway/effort_accounts.go +++ b/internal/gateway/effort_accounts.go @@ -74,7 +74,9 @@ func takesEffort(c candidate, e string) bool { return true } } - if levels, ok := c.p.Account.Levels(c.model); ok && !slices.Contains(levels, e) { + // the account's list names its models by the vendor's id, not one the + // user lists one by (SetModelID) + if levels, ok := c.p.Account.Levels(c.p.OwnModelID(c.model)); ok && !slices.Contains(levels, e) { return false } return true @@ -178,7 +180,7 @@ func takesTier(c candidate, t string) bool { if c.p.Account == nil { return true } - tiers, ok := c.p.Account.Tiers(c.model) + tiers, ok := c.p.Account.Tiers(c.p.OwnModelID(c.model)) // by the vendor's id, as Levels return !ok || slices.Contains(tiers, t) } diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 8b0ef767f..4bdc797a9 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -275,8 +275,11 @@ func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (ou }) // an account whose plan lacks the model (a Free one behind a Plus) // would only answer 400; it is tried only when none lists it + // (by the vendor's own id: an account's list names its models by + // theirs, not by one the user lists one by) + own := p.OwnModelID(model) for _, c := range all { - if c.p.Account.Lists(model) { + if c.p.Account.Lists(own) { out = append(out, c) } else { left = append(left, c) diff --git a/internal/gateway/local_id_plugin_test.go b/internal/gateway/local_id_plugin_test.go new file mode 100644 index 000000000..8769e9c96 --- /dev/null +++ b/internal/gateway/local_id_plugin_test.go @@ -0,0 +1,209 @@ +package gateway + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/testenv" +) + +// A plugin's model listed by an id of the user's own (zeewell on X: +// Cursor's deepseek-v41-flash-1017, Devin's, WorkBuddy's) is listed and +// asked for by that id, on each of the plugin's APIs, and the plugin's +// fetch is still asked for the model by the id its own list gives it — +// in the body, the URL and the model header the plugin reads. +func TestLocalModelIDAtAPlugin(t *testing.T) { + bun := testenv.Bun(t) + fresh(t) + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + + type seen struct{ path, model, body string } + var mu sync.Mutex + var got []seen + up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + got = append(got, seen{r.URL.RequestURI(), r.Header.Get("X-Plugin-Model"), string(b)}) + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + switch { + case r.URL.Path == "/v1/chat/completions": + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"hi from chat"},"finish_reason":null}]}`+"\n\n") + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n") + case r.URL.Path == "/v1/messages": + for _, e := range []string{ + `{"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"fake-claude","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`, + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi from claude"}}`, + `{"type":"content_block_stop","index":0}`, + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`, + `{"type":"message_stop"}`, + } { + fmt.Fprintf(w, "data: %s\n\n", e) + } + case strings.HasPrefix(r.URL.Path, "/v1/models/"): + fmt.Fprint(w, `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"hi from gemini"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":2}}`+"\n\n") + default: + w.WriteHeader(404) + } + })) + defer up.Close() + + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + if _, err := plugin.APIKey(ctx, "fakeco", 0, nil, "k1", plugin.NewAccount); err != nil { + t.Fatal(err) + } + + listedAs := map[string]string{"fake-1": "my-flash", "fake-claude": "my-claude", "fake-gemini": "my-gemini"} + for own, id := range listedAs { + if _, changed, err := provider.SetModelID("fakeco/"+own, id); err != nil || !changed { + t.Fatalf("SetModelID(fakeco/%s, %s) = %v, %v", own, id, changed, err) + } + } + p, err := provider.Find("fakeco") + if err != nil || !p.IsPlugin() || !p.TakesModelIDs() { + t.Fatalf("Find = %+v, %v", p, err) + } + for model, want := range map[string]provider.Protocol{"my-flash": provider.Chat, "my-claude": provider.Anthropic, "my-gemini": provider.CodeAssist} { + if apis := p.APIs(model); len(apis) != 1 || apis[0] != want { + t.Fatalf("APIs(%s) = %v", model, apis) + } + } + + s := New() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil)) + var l struct{ Data []struct{ ID string } } + if err := json.Unmarshal(rec.Body.Bytes(), &l); err != nil { + t.Fatal(rec.Body.String()) + } + var ids []string + for _, m := range l.Data { + ids = append(ids, m.ID) + } + for own, id := range listedAs { + if !slices.Contains(ids, "fakeco/"+id) || slices.Contains(ids, "fakeco/"+own) { + t.Errorf("/v1/models lists fakeco's %s as: %v", own, ids) + } + } + + for _, c := range []struct{ model, own, text, path string }{ + {"fakeco/my-flash", "fake-1", "hi from chat", "/v1/chat/completions"}, + {"fakeco/my-claude", "fake-claude", "hi from claude", "/v1/messages"}, + {"fakeco/my-gemini", "fake-gemini", "hi from gemini", "/v1/models/fake-gemini:streamGenerateContent?alt=sse"}, + } { + code, body := postAs(t, s, "", `{"model":"`+c.model+`","messages":[{"role":"user","content":"hello"}]}`) + if code != 200 || !strings.Contains(body, c.text) { + t.Fatalf("%s: %d %s", c.model, code, body) + } + mu.Lock() + last := got[len(got)-1] + mu.Unlock() + if last.path != c.path || last.model != c.own || strings.Contains(last.body, "my-") { + t.Fatalf("%s reached the plugin's vendor as %+v", c.model, last) + } + if r := lastUsage(t); r.Model != strings.TrimPrefix(c.model, "fakeco/") { + t.Errorf("%s was counted as %q", c.model, r.Model) + } + } +} + +// An Antigravity family the user lists by an id of theirs goes out as the +// variant of the vendor's id the effort picks, not as the family's bare id +// a wire name gives it. +func TestLocalModelIDAtAnAntigravityAccount(t *testing.T) { + fresh(t) + if err := os.MkdirAll(filepath.Dir(catalog.LivePath("antigravity")), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(catalog.LivePath("antigravity"), []byte(`{"models":[{"id":"flash-9-low"},{"id":"flash-9-high"}]}`), 0o644); err != nil { + t.Fatal(err) + } + catalog.Reset() + t.Cleanup(catalog.Reset) + s := settings.Load() + s.ModelIDs = map[string]string{"antigravity/my-flash": "flash-9"} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + p := provider.Provider{ID: "antigravity", Account: &provider.Account{Agent: "antigravity", User: "u"}} + r, err := parseChat([]byte(`{"model":"antigravity/my-flash","stream":true,"reasoning_effort":"low","messages":[{"role":"user","content":"hi"}]}`)) + if err != nil { + t.Fatal(err) + } + var env struct{ Model string } + if err := json.Unmarshal(codeAssistBody(p, r, "my-flash", settings.Load().Wires()), &env); err != nil { + t.Fatal(err) + } + if env.Model != "flash-9-low" { + t.Fatalf("my-flash at low went out as %q, want flash-9-low", env.Model) + } +} + +// A Claude account's model the user lists by an id of theirs is run in +// Claude Code by Anthropic's id: no wire name reaches the run. +func TestLocalModelIDAtAClaudeAccount(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script stands in for Claude Code") + } + fresh(t) + s := settings.Load() + s.ModelIDs = map[string]string{"claude/my-sonnet": "claude-sonnet-5"} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + dir := t.TempDir() + argv := filepath.Join(dir, "argv") + testenv.Program(t, filepath.Join(dir, "claude"), `#!/bin/sh +echo "$@" > '`+argv+`' +read -r line +echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}' +echo '{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}' +echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}}' +echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}}' +echo '{"type":"stream_event","event":{"type":"message_stop"}}' +`) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + srv := New() + t.Cleanup(srv.subscription.abortAll) + p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}} + if own := p.OwnModelID("my-sonnet"); own != "claude-sonnet-5" { + t.Fatalf("OwnModelID(my-sonnet) = %q", own) + } + body := `{"model":"claude/my-sonnet","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"hi"}]}` + rec := httptest.NewRecorder() + var u Usage + srv.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, p, "my-sonnet", []byte(body), &u) + b, err := os.ReadFile(argv) + if err != nil { + t.Fatalf("Claude Code never ran: %v; %s", err, rec.Body.String()) + } + if args := string(b); !strings.Contains(args, "claude-sonnet-5") || strings.Contains(args, "my-sonnet") { + t.Fatalf("Claude Code ran as: %s", args) + } +} diff --git a/internal/provider/account_models.go b/internal/provider/account_models.go index fd71c308f..5d15006dd 100644 --- a/internal/provider/account_models.go +++ b/internal/provider/account_models.go @@ -19,9 +19,16 @@ import ( // account's name, a key's KeyID) is let serve model: true when it has no // list of its own, and for a model Codex calls by itself that no list can // hold (codexOwnHidden). +// +// A model the user lists by an id of theirs (SetModelID) is in the list +// by that id, or by the vendor's own one a list kept from before has. func (p Provider) AccountServes(ref, model string) bool { ms, ok := p.AccountModels[accountKey(ref)] - return !ok || len(ms) == 0 || slices.Contains(ms, model) || codexOwnHidden(p, model) + if !ok || len(ms) == 0 || slices.Contains(ms, model) || codexOwnHidden(p, model) { + return true + } + own := p.OwnModelID(model) + return own != model && slices.Contains(ms, own) } // codexOwnHidden says model is one a Codex account serves that its list diff --git a/internal/provider/localid.go b/internal/provider/localid.go index 8b5729138..3188e8d77 100644 --- a/internal/provider/localid.go +++ b/internal/provider/localid.go @@ -21,9 +21,15 @@ import ( // It is ModelWires turned round: a wire keeps magpie's id and changes the // one sent, this keeps the one sent and changes magpie's. // -// Only a provider of the user's own (a key) takes one: an account's or a -// plugin's requests are built by its own backend or plugin from the id it -// lists, which no wire name reaches. +// An account's and a plugin's provider take one too (zeewell on X: +// SuperGrok's grok-4.6@500k as grok-4.6, Cursor's, Devin's and +// WorkBuddy's plugin models). The body's model goes out by the wire name +// as at any provider, and what is read of the model by the vendor's id +// is read by the own id: a plugin's model (pluginModel, so its APIs, +// tiers and prices), Claude Code's run on a Claude account (the +// gateway's serveClaudeSubscription), Code Assist's and Antigravity's +// sent id (codeAssistBody, SentNameOnIn), and an account's own list +// (Account.Lists in the gateway's fallback, AccountServes). // localIDs are the ids the user lists a provider's models by: from the // provider's own id to the one the user gave, and back. @@ -129,12 +135,13 @@ func (l localIDs) ids(set map[string]bool) map[string]bool { } // takesModelIDs is whether the user can list p's models by ids of their -// own: a provider of theirs, whose requests carry a wire name. -func (p Provider) takesModelIDs() bool { return p.Account == nil } +// own: every provider with a chat list of its own, a key's, an account's +// or a plugin's. A provider that only decides (DecideOnly) lists Jev's +// models and nothing else. +func (p Provider) takesModelIDs() bool { return !p.DecideOnly() } // TakesModelIDs is whether p's models can be listed by ids the user gives -// them (SetModelID): a provider of the user's own, not an account's or a -// plugin's. +// them (SetModelID). func (p Provider) TakesModelIDs() bool { return p.takesModelIDs() } // ids are the ids the user gave p's models, none for a provider that @@ -232,7 +239,7 @@ func setModelID(ref, id string) (string, bool, error) { return "", false, err } if !p.takesModelIDs() { - return "", false, fmt.Errorf("%s is a signed-in account or a plugin's: its requests ask for the id its list gives, so its models can't be listed by another", p.Name) + return "", false, fmt.Errorf("%s only decides for the routing groups: it has no models of its own to list by another id", p.Name) } id = strings.TrimSpace(id) if id != "" { @@ -279,7 +286,7 @@ func setModelID(ref, id string) (string, bool, error) { if len(s.ModelIDs) == 0 { s.ModelIDs = nil } - if err := moveModelRefs(p.ID, cur, id); err != nil { + if err := moveModelRefs(p.ID, cur, id, p.Account != nil); err != nil { return "", false, err } s.MoveModel(p.ID+"/"+cur, p.ID+"/"+id) @@ -303,17 +310,18 @@ var ModelMoved func(from, to string) error // moveModelRefs gives every ref the providers file keeps to the provider // pid's model from as to: its picks, those set aside and listed when // picked, a key's models and its context, the fallbacks and the routing -// groups' refs. -func moveModelRefs(pid, from, to string) error { +// groups' refs. A signed-in account's or a plugin's provider is kept +// there only once the user has set something on it (withPicks): with +// none kept (account), only the other providers' refs to it move. +func moveModelRefs(pid, from, to string, account bool) error { f, err := read() if err != nil { return err } i := slices.IndexFunc(f.Providers, func(q Provider) bool { return q.ID == pid }) - if i < 0 { + if i < 0 && !account { return fmt.Errorf("no provider %q", pid) } - q := &f.Providers[i] moved := func(ids []string) []string { if !slices.Contains(ids, from) { return ids @@ -329,15 +337,18 @@ func moveModelRefs(pid, from, to string) error { } return out } - q.Models, q.PickedFrom, q.Delisted = moved(q.Models), moved(q.PickedFrom), moved(q.Delisted) - for k, ms := range q.AccountModels { - q.AccountModels[k] = moved(ms) - } - if n, ok := q.Contexts[from]; ok { - if _, has := q.Contexts[to]; !has { - q.Contexts[to] = n + if i >= 0 { + q := &f.Providers[i] + q.Models, q.PickedFrom, q.Delisted = moved(q.Models), moved(q.PickedFrom), moved(q.Delisted) + for k, ms := range q.AccountModels { + q.AccountModels[k] = moved(ms) + } + if n, ok := q.Contexts[from]; ok { + if _, has := q.Contexts[to]; !has { + q.Contexts[to] = n + } + delete(q.Contexts, from) } - delete(q.Contexts, from) } ref := func(m string) string { pre, rest := "", m diff --git a/internal/provider/localid_test.go b/internal/provider/localid_test.go index fb0a28c9d..d16be1725 100644 --- a/internal/provider/localid_test.go +++ b/internal/provider/localid_test.go @@ -1,6 +1,8 @@ package provider import ( + "os" + "path/filepath" "slices" "strings" "testing" @@ -233,8 +235,11 @@ func TestModelIDRefused(t *testing.T) { if _, _, err := SetModelID("relay-a/nope", "x"); err == nil { t.Error("an unknown model took an id") } - if (Provider{Account: &Account{}}).TakesModelIDs() { - t.Error("an account takes ids") + if !(Provider{Account: &Account{}}).TakesModelIDs() { + t.Error("an account takes no ids") + } + if (Provider{Decide: "https://decide.example.invalid"}).TakesModelIDs() { + t.Error("a provider that only decides takes ids") } if len(settings.Load().ModelIDs) != 0 { t.Fatalf("ModelIDs = %v", settings.Load().ModelIDs) @@ -255,3 +260,43 @@ func TestModelIDServingAndPrice(t *testing.T) { t.Fatalf("liveByID %v", ms) } } + +// An account's model listed by an id of the user's own (zeewell on X: +// SuperGrok's grok-4.6@500k as grok-4.6) is read by the vendor's id where +// the account's own say of it is: the account's picks kept from before, +// and the variant an Antigravity family goes out as at an effort. +func TestModelIDAtAnAccount(t *testing.T) { + prefsHome(t) + if err := os.MkdirAll(filepath.Dir(catalog.LivePath("antigravity")), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(catalog.LivePath("antigravity"), []byte(`{"models":[{"id":"flash-9-low"},{"id":"flash-9-high"}]}`), 0o644); err != nil { + t.Fatal(err) + } + catalog.Reset() + t.Cleanup(catalog.Reset) + s := settings.Load() + s.ModelIDs = map[string]string{"antigravity/my-flash": "flash-9", "grok/grok-4.6": "grok-4.6@500k"} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + + g := Provider{ID: "grok", Account: &Account{Agent: "grok"}, AccountModels: map[string][]string{"a@b.c": {"grok-4.6@500k"}}} + if own := g.OwnModelID("grok-4.6"); own != "grok-4.6@500k" { + t.Fatalf("the account is asked for grok-4.6 by %q", own) + } + if !g.AccountServes("a@b.c", "grok-4.6") { + t.Error("the account's pick of grok-4.6@500k doesn't serve it listed as grok-4.6") + } + if g.AccountServes("a@b.c", "grok-4.7") { + t.Error("the account's picks serve a model it didn't pick") + } + + wires := settings.Load().Wires() + if got := SentNameOnIn(wires, "antigravity", "antigravity", "my-flash", "low"); got != "flash-9-low" { + t.Errorf("flash-9 listed as my-flash, at low, goes out as %q; want flash-9-low", got) + } + if got, want := SentNameOnIn(wires, "antigravity", "antigravity", "my-flash", ""), AntigravitySentID("flash-9", ""); got != want { + t.Errorf("flash-9 listed as my-flash, at no effort, goes out as %q; want the family's default %s", got, want) + } +} diff --git a/internal/provider/modelprefs.go b/internal/provider/modelprefs.go index ba2da1d94..1d7a66c92 100644 --- a/internal/provider/modelprefs.go +++ b/internal/provider/modelprefs.go @@ -1066,6 +1066,14 @@ func SentNameIn(wires map[string]string, pid, model, effort string) string { // the route, which is holding the provider, asks about the account and lets // the gateway's dispatch (codeAssistID, on the same agent) be the one rule. func SentNameOnIn(wires map[string]string, pid, account, model, effort string) string { + if account == "antigravity" { + // a family the user lists by an id of theirs (SetModelID) goes + // out as the variant of its own id the effort picks, as the + // gateway's envelope does (codeAssistBody) + if own := modelIDsOf(pid).ownOf(model); own != model { + return UpstreamNameAsIn(wires, pid, own, antigravitySentID(account, own, effort)) + } + } return UpstreamNameAsIn(wires, pid, model, antigravitySentID(account, model, effort)) } diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index ae6993e2f..8fc208d59 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -18,6 +18,7 @@ import ( "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/probelog" + "github.com/yetone/magpie/internal/settings" ) // A plugin's provider (see internal/plugin) is a subscription like the @@ -231,12 +232,26 @@ var npmBase = map[string]string{ "@ai-sdk/deepseek": "https://api.deepseek.com/v1", } +// pluginModel is the model of pp's list by the id id, which is the +// plugin's own or one the user lists it by at magpie's provider of pp +// (SetModelID): what the plugin says of its model (its API, tiers, price) +// holds under either. func pluginModel(pp plugin.Provider, id string) (plugin.Model, bool) { for _, m := range pp.Models { if m.ID == id { return m, true } } + if len(settings.SharedModelIDs()) == 0 { + return plugin.Model{}, false + } + if own := modelIDsOf(PluginID(pp.ID)).ownOf(id); own != id { + for _, m := range pp.Models { + if m.ID == own { + return m, true + } + } + } return plugin.Model{}, false } diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index bcd09aceb..2f1e0b814 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -171,7 +171,7 @@

1 つのモデルを複数のプロバイダで

グループとは、1 つまたは複数のプロバイダのモデルを、エージェントが 1 つとして選べるようにまとめたものです。ピッカーの Routing groups の下に group/<id> として表示されます。2 つのプロバイダが同じ名前で提供しているモデルは、それだけでグループになります。Routing タブの New group では、好きなモデルを組み合わせてグループを作れます。グループで何ができるかは、最初のモデルが基準になります。

何もしなくてもできるグループ。 すでに持っているモデルを提供する 2 つ目のプロバイダを追加すると(Claude サブスクリプションと Copilot の Claude Opus、DeepSeek 自身の API と OpenRouter の DeepSeek など)、magpie はそれを提供するすべてのプロバイダにまたがるグループ auto/<model>(モデル自身の ID。例: auto/claude-opus-4.6。以前の group/auto-… も引き続き使えます)を自動で作ります。名前はベンダーごとの表記の違い(deepseek/deepseek-chat、deepseek-chat)を吸収して照合されます。エージェントにこれを選ぶとリクエストがすべてに分散されます。不要なものは magpie group rm で非表示にできます。
-
プロバイダ独自の id に自分の id を。 プロバイダによっては deepseek-v4.1-flash-1017 や grok-4.6@500k のような独自の id でモデルを提供します。プロバイダの編集画面の 名前と推論レベル で、同じモデル の隣の 表示 ID に使いたい id を入れて 保存、または magpie model id relay/grok-4.6@500k grok-4.6 を実行します。以後 magpie は一覧、ルーティング、他のプロバイダの grok-4.6 とまとめた auto/grok-4.6 グループ、ゲートウェイキーの制限、使用量の記録をすべて grok-4.6 で行い、プロバイダには grok-4.6@500k で問い合わせます。1 つのプロバイダで 1 つの id は 1 つのモデルです。最後に付けたものが有効で、その間プロバイダ自身のその id のモデルは一覧から外れます。magpie model id relay/grok-4.6 --reset で元に戻し、magpie model ids で一覧を表示します。キーで追加したプロバイダ向けで、サブスクリプションやプラグインのモデルは元の id のままです。
+
プロバイダ独自の id に自分の id を。 プロバイダによっては deepseek-v4.1-flash-1017 や grok-4.6@500k のような独自の id でモデルを提供します。プロバイダの編集画面の 名前と推論レベル で、同じモデル の隣の 表示 ID に使いたい id を入れて 保存、または magpie model id relay/grok-4.6@500k grok-4.6 を実行します。以後 magpie は一覧、ルーティング、他のプロバイダの grok-4.6 とまとめた auto/grok-4.6 グループ、ゲートウェイキーの制限、使用量の記録をすべて grok-4.6 で行い、プロバイダには grok-4.6@500k で問い合わせます。1 つのプロバイダで 1 つの id は 1 つのモデルです。最後に付けたものが有効で、その間プロバイダ自身のその id のモデルは一覧から外れます。magpie model id relay/grok-4.6 --reset で元に戻し、magpie model ids で一覧を表示します。サインインしたサブスクリプションやプラグインのプロバイダでも同じです(magpie model id cursor/deepseek-v41-flash-1017 deepseek-v4.1-flash)。アカウントやプラグインには引き続き元の id で問い合わせます。
diff --git a/site/public/docs/start.html b/site/public/docs/start.html index b817ed699..6cb565ad2 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -171,7 +171,7 @@

One model over several providers

A group is several models, from one provider or many, that an agent picks as one: group/<id>, under Routing groups in the picker. A model two of your providers serve under the same name becomes a group on its own; New group in the Routing tab makes one of any models you like. The first model answers for what the group can do.

Groups you get without doing anything. Add a second provider that serves a model you already have — Claude Opus from your Claude subscription and from Copilot, DeepSeek from its own API and from OpenRouter — and magpie makes it a group by itself, auto/<model> (the model's own id, as in auto/claude-opus-4.6; the older group/auto-… id still works), over every provider that serves it. The name is matched however each vendor spells it (deepseek/deepseek-chat, deepseek-chat). Pick it for an agent to spread its requests over all of them; magpie group rm hides one you don’t want.
-
One model under the provider's odd id. Some providers serve a model under an id of their own, deepseek-v4.1-flash-1017 or grok-4.6@500k. Give it the id you want in the provider's editor, under Names & levels, in Listed as beside Same as, then Save; or run magpie model id relay/grok-4.6@500k grok-4.6. magpie then lists it, routes it, joins it to the auto/grok-4.6 group with your other providers' grok-4.6, holds gateway keys to it and counts its usage as grok-4.6, and still asks the provider for grok-4.6@500k. One id is one model of a provider: the last one you give it to has it, and the provider's own model of that id is left out of the list while it does. magpie model id relay/grok-4.6 --reset takes it back, and magpie model ids lists them. It is for providers you added with a key; a subscription's or a plugin's models keep their ids.
+
One model under the provider's odd id. Some providers serve a model under an id of their own, deepseek-v4.1-flash-1017 or grok-4.6@500k. Give it the id you want in the provider's editor, under Names & levels, in Listed as beside Same as, then Save; or run magpie model id relay/grok-4.6@500k grok-4.6. magpie then lists it, routes it, joins it to the auto/grok-4.6 group with your other providers' grok-4.6, holds gateway keys to it and counts its usage as grok-4.6, and still asks the provider for grok-4.6@500k. One id is one model of a provider: the last one you give it to has it, and the provider's own model of that id is left out of the list while it does. magpie model id relay/grok-4.6 --reset takes it back, and magpie model ids lists them. It works for a subscription you signed in to and a plugin's provider too (magpie model id cursor/deepseek-v41-flash-1017 deepseek-v4.1-flash): the account or the plugin is still asked for its own id.
ルーティング先に使われるもの
スマート smartデフォルトです。メンバーのアカウントとキーをまとめて扱い(グループ内のグループは 1 つとして扱います。下記参照)、クォータに余裕のあるサブスクリプションのうち、利用枠が最も早く更新されるもの。基準は週の枠です。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は 5 時間枠で判断されるため、それより後に週の枠が更新されるものすべてより先になります。リセットのないクレジット(WorkBuddy のパッケージはそれぞれの日に失効します)は、残りのうち最も早く失効する時点で判断されるため、クレジットが最も早く失効する WorkBuddy アカウントが先になります。同時に更新されるアカウント(無料アカウントはすべて月末)は、その後に残りのクレジットが先に失効するものが先になります。失敗後に休止中のものは最後に回ります。
diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index c21d561fb..8bd3e09a1 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -171,7 +171,7 @@

跨供应商的同一个模型

路由组是几个模型(来自一个或多个供应商),Agent 把它当作一个来选:group/<id>,在选择列表的 路由组 下面。两个供应商用同一个名字提供的模型会自动成组;在 路由 标签页点 新建组 可以把任意模型组到一起。排第一的模型决定这个组对外的能力。

不用手动建的组。再加一个供应商,只要它提供的模型和已有的同名(比如 Claude 订阅和 Copilot 都有 Claude Opus,DeepSeek 官方 API 和 OpenRouter 都有 DeepSeek),magpie 就会自动把它们组成一个路由组:auto/<模型>(模型自己的 id,比如 auto/claude-opus-4.6;以前的 group/auto-… 也照样能用),包含所有提供这个模型的供应商。名字按各家不同的写法匹配(deepseek/deepseek-chat 和 deepseek-chat 算同一个)。给 Agent 选这个组,请求就会分摊到这些供应商上;不想要的可以用 magpie group rm 隐藏。
-
给供应商的怪名字起个自己的 id。有的供应商用自己的 id 提供模型,比如 deepseek-v4.1-flash-1017、grok-4.6@500k。在供应商编辑页的 名称与推理档位 里,等同于 旁边的 列为 填上你想要的 id,再点 保存;或者运行 magpie model id relay/grok-4.6@500k grok-4.6。之后 magpie 列出、路由、把它和其他供应商的 grok-4.6 合进 auto/grok-4.6 组、限制网关密钥、记录用量,都用 grok-4.6,向供应商请求时仍然发 grok-4.6@500k。一个供应商里一个 id 只对应一个模型:最后设上的那个生效,期间供应商自己叫这个 id 的模型不再列出。magpie model id relay/grok-4.6 --reset 改回来,magpie model ids 列出全部。只适用于用密钥添加的供应商;订阅和插件的模型保持原 id。
+
给供应商的怪名字起个自己的 id。有的供应商用自己的 id 提供模型,比如 deepseek-v4.1-flash-1017、grok-4.6@500k。在供应商编辑页的 名称与推理档位 里,等同于 旁边的 列为 填上你想要的 id,再点 保存;或者运行 magpie model id relay/grok-4.6@500k grok-4.6。之后 magpie 列出、路由、把它和其他供应商的 grok-4.6 合进 auto/grok-4.6 组、限制网关密钥、记录用量,都用 grok-4.6,向供应商请求时仍然发 grok-4.6@500k。一个供应商里一个 id 只对应一个模型:最后设上的那个生效,期间供应商自己叫这个 id 的模型不再列出。magpie model id relay/grok-4.6 --reset 改回来,magpie model ids 列出全部。登录的订阅和插件的供应商也一样(magpie model id cursor/deepseek-v41-flash-1017 deepseek-v4.1-flash):账号或插件收到的仍是它自己的 id。
RoutingWhat goes first
Smart smartThe default. Over the members’ accounts and keys together (a group in the group as one, see below): of the subscriptions with quota to spare, the one whose allowance renews soonest. The week decides; an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later. Credits with no reset (WorkBuddy’s packages, each ending on its own day) count as renewing when the soonest of those left run out, so the WorkBuddy account whose credits end first goes first; accounts renewing together (free ones at the month’s end) go by whose credits left end first after that. One resting after a failure goes last.
路由谁排在前面
智能 smart默认。把成员的账号和 Key 放在一起排(组里的路由组算一个,见下文):还有余量的订阅里,额度最先重置的排第一。看周额度的重置时间;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)看它的 5 小时重置,所以排在所有更晚重置的周额度前面。没有重置时间的积分(WorkBuddy 的积分包,各自到期)按剩余积分最早过期的时间算,所以积分最先过期的 WorkBuddy 账号排第一;同时重置的账号(免费账号都在月底)再看剩余积分哪个先过期。失败后在休息的排最后。