diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 014a7db40..07cd1bc4e 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -32,6 +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) | | 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 a92818ed0..ae55148a5 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -198,6 +198,38 @@ it may be a variant's (`deepseek-v4.1-flash[fast]`), and a tagged id is never priced. `TestUserSameGivesTheSpecs`, `TestTaggedIDHasTheModelsSpecs`, `TestSameAsGivesAnUnlistedModelItsSpecs`. +A model can also be listed by an id the user gives it at its provider +(zeewell on X: a relay's `deepseek-v4.1-flash-1017` as +`deepseek-v4.1-flash`, `grok-4.6@500k` as `grok-4.6`): the editor's +Names & levels "Listed as" box beside Same as, `magpie model id + ` (`--reset` takes it back, `magpie model ids` lists +them), settings' `ModelIDs` (`"/": ""`, +`provider.SetModelID`, [`localid.go`](../../internal/provider/localid.go)). +Same as only lends specs and joins found groups; this id is what magpie +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, +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 +`grok-4.6@500k`) is not listed while it is. Giving the id moves what the +user set of the model (picks, contexts, fallbacks, routing groups' +members and rules, the pickers' lists, every per-model setting, gateway +keys' models through `provider.ModelMoved`) to it, but never over a value +the user already has under the new id (`Settings.MoveModel`). Agents' +files are not rewritten: an old `provider/` still resolves and is +asked for as it is. A gateway key held to either id passes for both +(`modelAllowed`). A group's `match` pattern is left as the user wrote it. +Usage records the model by the listed id and `served` by the vendor's; +the price is the own id's first (`ListPrice`). `TestModelIDListedAndAskedForByOwn`, +`TestModelIDLatestWins`, `TestModelIDMovesTheUsersRefs`, +`TestLocalModelIDOnEveryRoute`. + ## Constraints and failure behavior An allowance deliberately not requested (a saved Claude account outside diff --git a/internal/access/model_moved.go b/internal/access/model_moved.go new file mode 100644 index 000000000..a3361ab3a --- /dev/null +++ b/internal/access/model_moved.go @@ -0,0 +1,55 @@ +package access + +import ( + "strings" + + "github.com/yetone/magpie/internal/provider" +) + +// A key held to a provider's model is held to it under the id it is +// listed by (provider.SetModelID): the key's own "/" +// moves to the new id with the model, as the provider's picks and the +// routing groups' refs do, so the user's limit keeps meaning that model. +func init() { provider.ModelMoved = MoveModel } + +// MoveModel gives every key's models that name from ("/", +// letter case aside) to instead. A pattern ("relay/*") is the user's own +// and is left as written. +func MoveModel(from, to string) error { + mu.Lock() + defer mu.Unlock() + keys, err := load() + if err != nil { + return err + } + changed := false + for i := range keys { + ms := keys[i].Models + var out []string + moved := false + for _, m := range ms { + if strings.EqualFold(m, from) { + m, moved = to, true + } + if !containsFold(out, m) { + out = append(out, m) + } + } + if moved { + keys[i].Models, changed = out, true + } + } + if !changed { + return nil + } + return save(keys) +} + +func containsFold(ms []string, m string) bool { + for _, x := range ms { + if strings.EqualFold(x, m) { + return true + } + } + return false +} diff --git a/internal/cli/model_cli.go b/internal/cli/model_cli.go index 06c78ba77..00c996269 100644 --- a/internal/cli/model_cli.go +++ b/internal/cli/model_cli.go @@ -59,6 +59,17 @@ const modelUsage = `usage: id of its own for a provider that has since been deleted, and says when there was no name of its own to take away magpie model wires the names your vendors are asked for models by + magpie model id the id magpie lists the model by, and the provider's own + magpie model id list the model by this id at that provider, e.g. + relay-a/deepseek-v4.1-flash-1017 deepseek-v4.1-flash: agents, + /v1/models, routing groups, the groups magpie finds, gateway keys + and Usage all use it, and relay-a is still asked for + deepseek-v4.1-flash-1017. One id is one model of a provider: the + latest model given an id has it, and a model of the provider's + own with that id is not listed while another is. A provider of + your own (a key) only + magpie model id --reset list it by the provider's own id again + magpie model ids the models you list by an id of your own magpie model names the models you named or narrowed magpie model alias count the model's usage under another model id in Usage, Sessions and the usage summaries, e.g. deepseek-v4.1-flash @@ -139,6 +150,10 @@ func modelCmd(args []string) error { return modelSpec(args[1:]) case "specs": return modelSpecs() + case "id": + return modelID(args[1:]) + case "ids": + return modelIDs() case "alias": return modelUsageAlias(args[1:]) case "aliases": diff --git a/internal/cli/model_id_cli.go b/internal/cli/model_id_cli.go new file mode 100644 index 000000000..cad65d419 --- /dev/null +++ b/internal/cli/model_id_cli.go @@ -0,0 +1,101 @@ +package cli + +import ( + "fmt" + "maps" + "slices" + "strings" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// modelID is `magpie model id`: the id a provider's model is listed, +// routed and counted by in magpie, while the provider is asked for it by +// its own (provider.SetModelID). +func modelID(args []string) error { + if len(args) == 0 || len(args) > 2 { + return fmt.Errorf("%s", modelUsage) + } + if slices.Contains([]string{"-h", "--help", "help"}, args[0]) { + fmt.Println(modelUsage) + return nil + } + p, model, err := modelRef(args[0]) + if err != nil { + return err + } + if len(args) == 1 { + own := p.OwnModelID(model) + if own == model { + if local, ok := localOf(p, model); ok { + fmt.Println(bold.Render(p.ID+"/"+local), muted.Render("· listed as "+local+" · "+p.ID+" is asked for "+model)) + return nil + } + fmt.Println(bold.Render(p.ID+"/"+model), muted.Render("· listed by its own id")) + return nil + } + fmt.Println(bold.Render(p.ID+"/"+model), muted.Render("· "+p.ID+" is asked for "+own)) + return nil + } + id := strings.TrimSpace(args[1]) + if isReset(args[1:]) { + id = "" + } + // the provider's own id of it, before it is listed anew + own := p.OwnModelID(model) + replaced, changed, err := provider.SetModelID(args[0], id) + if err != nil { + return err + } + if !changed { + fmt.Println(muted.Render(p.ID + "/" + model + " is listed so already")) + return nil + } + if id == "" || id == own { + fmt.Println(bold.Render(p.ID+"/"+own), muted.Render("· listed by its own id again")) + return nil + } + fmt.Println(bold.Render(p.ID+"/"+id), muted.Render("· listed, routed and counted so; "+p.ID+" is still asked for "+own)) + if replaced != "" { + fmt.Println(muted.Render(" " + replaced + " had that id: it is listed by its own again")) + } + if n := strings.TrimSpace(settings.Load().ModelWires[p.ID+"/"+id]); n != "" { + fmt.Println(muted.Render(" a wire name of yours is set for " + p.ID + "/" + id + ": it is asked for as " + n + " (magpie model wire --reset takes it off)")) + } + return nil +} + +// localOf is the id the user lists p's model of its own id own by. +func localOf(p *provider.Provider, own string) (string, bool) { + for local, o := range p.ModelIDs() { + if o == own { + return local, true + } + } + return "", false +} + +// modelIDs is `magpie model ids`: every model listed by an id the user +// gave it, with the provider's own. +func modelIDs() error { + ids := settings.Load().ModelIDs + keys := slices.Sorted(maps.Keys(ids)) + w := 0 + for _, k := range keys { + w = max(w, len(k)) + } + n := 0 + for _, k := range keys { + own := strings.TrimSpace(ids[k]) + if own == "" { + continue + } + n++ + fmt.Printf("%-*s %s\n", w, k, muted.Render("is asked for as ")+own) + } + if n == 0 { + fmt.Println(muted.Render("no model is listed by an id of yours yet · magpie model id ")) + } + return nil +} diff --git a/internal/cli/model_id_cli_test.go b/internal/cli/model_id_cli_test.go new file mode 100644 index 000000000..93f5000bb --- /dev/null +++ b/internal/cli/model_id_cli_test.go @@ -0,0 +1,66 @@ +package cli + +import ( + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// magpie model id lists a provider's model by an id of the user's, shows +// it, lists every one under ids and takes it off with --reset; it refuses +// a flag or a bad id taken as one, and a model the provider doesn't have. +func TestModelIDCmd(t *testing.T) { + groupsHome(t) + out, err := runOut(t, "model", "ids") + if err != nil || !strings.Contains(out, "no model is listed by an id of yours yet") { + t.Fatalf("empty list: %q %v", out, err) + } + if out, err = runOut(t, "model", "id", "a/only-a", "solo"); err != nil || !strings.Contains(out, "a/solo") || !strings.Contains(out, "still asked for only-a") { + t.Fatalf("set: %q %v", out, err) + } + if got := settings.Load().ModelIDs; got["a/solo"] != "only-a" || len(got) != 1 { + t.Fatalf("settings: %v", got) + } + p, err := provider.Find("a") + if err != nil { + t.Fatal(err) + } + if got := provider.UpstreamName(*p, "solo"); got != "only-a" { + t.Fatalf("a/solo is asked for as %s", got) + } + for _, ref := range []string{"a/solo", "a/only-a"} { + if out, err = runOut(t, "model", "id", ref); err != nil || !strings.Contains(out, "a/solo") || !strings.Contains(out, "asked for only-a") { + t.Fatalf("show %s: %q %v", ref, out, err) + } + } + if out, err = runOut(t, "model", "ids"); err != nil || !strings.Contains(out, "a/solo") || !strings.Contains(out, "only-a") { + t.Fatalf("list: %q %v", out, err) + } + for _, bad := range [][]string{ + {"model", "id", "a/solo", "--force"}, + {"model", "id", "a/solo", "two words"}, + {"model", "id", "a/nope", "x"}, + {"model", "id", "solo", "x"}, + } { + if _, err := runOut(t, bad...); err == nil { + t.Fatalf("took %v", bad) + } + } + if out, err = runOut(t, "model", "id", "--help"); err != nil || !strings.Contains(out, "magpie model id ") { + t.Fatalf("--help: %q %v", out, err) + } + if got := settings.Load().ModelIDs; len(got) != 1 { + t.Fatalf("a refused id was written: %v", got) + } + if out, err = runOut(t, "model", "id", "a/solo", "--reset"); err != nil || !strings.Contains(out, "its own id again") { + t.Fatalf("reset: %q %v", out, err) + } + if got := settings.Load().ModelIDs; got != nil { + t.Fatalf("after reset: %v", got) + } + if out, err = runOut(t, "model", "id", "a/only-a"); err != nil || !strings.Contains(out, "listed by its own id") { + t.Fatalf("show after reset: %q %v", out, err) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 98258004a..c52470d32 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -141,7 +141,7 @@ type wiresKey struct{} // only where something asks for one: a request refused before any name is // looked up pays for nothing. func withWires(r *http.Request) *http.Request { - load := sync.OnceValue(func() map[string]string { return settings.Shared().ModelWires }) + load := sync.OnceValue(func() map[string]string { return settings.Shared().Wires() }) return r.WithContext(context.WithValue(r.Context(), wiresKey{}, load)) } @@ -152,7 +152,7 @@ func wiresOf(ctx context.Context) map[string]string { if load, ok := ctx.Value(wiresKey{}).(func() map[string]string); ok { return load() } - return settings.Shared().ModelWires + return settings.Shared().Wires() } // standIn is StandIn's model for one magpie shows no entry for: not a @@ -1545,7 +1545,7 @@ func (s *Server) countOn(w http.ResponseWriter, r *http.Request, p provider.Prov } // the names in force, read at most once however many candidates are // counted, and not at all where there are none - wires := sync.OnceValue(func() map[string]string { return settings.Shared().ModelWires }) + wires := sync.OnceValue(func() map[string]string { return settings.Shared().Wires() }) for i, c := range counts { res, err := s.forward(r.Context(), c.p, provider.Anthropic, "/v1/messages/count_tokens", rewriteModel(body, provider.UpstreamNameIn(wires(), c.p.ID, model)), r.Header) if tooMany := (*errRPM)(nil); errors.As(err, &tooMany) { diff --git a/internal/gateway/key_models.go b/internal/gateway/key_models.go index a20af83c0..68897ae0d 100644 --- a/internal/gateway/key_models.go +++ b/internal/gateway/key_models.go @@ -79,15 +79,27 @@ func allows(who access.Identity, ids ...string) bool { return false } -// modelAllowed says the key may use provider p's model. +// modelAllowed says the key may use provider p's model. A model the user lists by an id of their own (provider.SetModelID) is +// the one model by either id, so a key held to one may use the other: +// one written before the id was given, or an agent's old ref to the +// provider's own id. func modelAllowed(who access.Identity, p provider.Provider, model string) bool { - return allows(who, p.ID+"/"+model) + if allows(who, p.ID+"/"+model) { + return true + } + if own := p.OwnModelID(model); own != model { + return allows(who, p.ID+"/"+own) + } + if local := p.ListedModelID(model); local != model { + return allows(who, p.ID+"/"+local) + } + return false } // memberAllowed says the key may use a routing group's member: the model, // or a group it is reached through that the key names. func memberAllowed(who access.Identity, m provider.Member) bool { - return allows(who, append([]string{m.Provider.ID + "/" + m.Model}, m.Path...)...) + return modelAllowed(who, m.Provider, m.Model) || len(m.Path) > 0 && allows(who, m.Path...) } // groupNamed says the key names the routing group g itself. diff --git a/internal/gateway/local_id_test.go b/internal/gateway/local_id_test.go new file mode 100644 index 000000000..1c9ae098a --- /dev/null +++ b/internal/gateway/local_id_test.go @@ -0,0 +1,200 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "slices" + "strconv" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// listing is a relay that lists ids and answers each request with the +// model it was asked for, recording it. +func listing(t *testing.T, a *asked, ids ...string) *httptest.Server { + t.Helper() + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/models") { + var l struct { + Data []map[string]string `json:"data"` + } + for _, id := range ids { + l.Data = append(l.Data, map[string]string{"id": id}) + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(l) + return + } + var b struct { + Model string `json:"model"` + } + json.NewDecoder(r.Body).Decode(&b) + a.add(b.Model) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, `data: {"id":"x","model":`+strconv.Quote(b.Model)+ + `,"choices":[{"index":0,"delta":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],`+ + `"usage":{"prompt_tokens":5,"completion_tokens":3}}`+"\n\n") + io.WriteString(w, "data: [DONE]\n\n") + })) + t.Cleanup(s.Close) + return s +} + +// A model the user lists by an id of their own (zeewell on X: +// deepseek-v4.1-flash-1017 as deepseek-v4.1-flash, grok-4.6@500k as +// grok-4.6) is that id on every route an agent reaches it by — the model +// list, a request by provider/model, by the bare id through the group +// magpie finds, both protocols, a gateway key held to it — and the relay +// is asked for it by its own id, which the usage record keeps as served. +func TestLocalModelIDOnEveryRoute(t *testing.T) { + fresh(t) + var seenA, seenB asked + a := listing(t, &seenA, "deepseek-v4.1-flash-1017", "grok-4.6", "grok-4.6@500k") + b := listing(t, &seenB, "deepseek-v4.1-flash") + for _, r := range []struct { + id string + url string + ids []string + }{ + {"relay-a", a.URL, []string{"deepseek-v4.1-flash-1017", "grok-4.6", "grok-4.6@500k"}}, + {"relay-b", b.URL, []string{"deepseek-v4.1-flash"}}, + } { + if err := provider.Save(provider.Provider{ID: r.id, Name: r.id, Key: "k", Chat: r.url}); err != nil { + t.Fatal(err) + } + var ms []catalog.Model + for _, id := range r.ids { + ms = append(ms, catalog.Model{ID: id}) + } + if err := catalog.SaveLive(r.id, r.url, ms); err != nil { + t.Fatal(err) + } + } + keys, secrets := newCaller(t, "Held") + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"relay-a/grok-4.6@500k"}}); err != nil { + t.Fatal(err) + } + for ref, id := range map[string]string{ + "relay-a/deepseek-v4.1-flash-1017": "deepseek-v4.1-flash", + "relay-a/grok-4.6@500k": "grok-4.6", + } { + if _, _, err := provider.SetModelID(ref, id); err != nil { + t.Fatal(err) + } + } + // the key's model went to the id it is listed by + if ks, _ := access.List(); !slices.Equal(ks[len(ks)-1].Models, []string{"relay-a/grok-4.6"}) { + t.Fatalf("the held key's models: %v", ks[len(ks)-1].Models) + } + + h := New().Handler() + do := func(secret, method, path, body string) *httptest.ResponseRecorder { + t.Helper() + r := httptest.NewRequest(method, path, strings.NewReader(body)) + if secret != "" { + r.Header.Set("Authorization", "Bearer "+secret) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + listed := func(secret string) []string { + t.Helper() + var l struct{ Data []struct{ ID string } } + w := do(secret, "GET", "/v1/models", "") + if err := json.Unmarshal(w.Body.Bytes(), &l); err != nil { + t.Fatal(w.Body.String()) + } + var ids []string + for _, m := range l.Data { + ids = append(ids, m.ID) + } + return ids + } + ids := listed("") + for _, want := range []string{"relay-a/deepseek-v4.1-flash", "relay-a/grok-4.6", "relay-b/deepseek-v4.1-flash", "auto/deepseek-v4.1-flash"} { + if !slices.Contains(ids, want) { + t.Errorf("/v1/models has no %s: %v", want, ids) + } + } + for _, own := range []string{"relay-a/deepseek-v4.1-flash-1017", "relay-a/grok-4.6@500k"} { + if slices.Contains(ids, own) { + t.Errorf("/v1/models lists %s by its own id: %v", own, ids) + } + } + + chat := func(secret, model string) *httptest.ResponseRecorder { + return do(secret, "POST", "/v1/chat/completions", `{"model":"`+model+`","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + } + messages := func(model string) *httptest.ResponseRecorder { + return do("", "POST", "/v1/messages", `{"model":"`+model+`","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}`) + } + for _, c := range []struct { + what string + send func() *httptest.ResponseRecorder + seen *asked + asked string + model string // recorded + }{ + {"chat relay-a/deepseek-v4.1-flash", func() *httptest.ResponseRecorder { return chat("", "relay-a/deepseek-v4.1-flash") }, &seenA, "deepseek-v4.1-flash-1017", "deepseek-v4.1-flash"}, + {"messages relay-a/grok-4.6", func() *httptest.ResponseRecorder { return messages("relay-a/grok-4.6") }, &seenA, "grok-4.6@500k", "grok-4.6"}, + {"an old ref by the own id", func() *httptest.ResponseRecorder { return chat("", "relay-a/deepseek-v4.1-flash-1017") }, &seenA, "deepseek-v4.1-flash-1017", "deepseek-v4.1-flash-1017"}, + {"relay-b's own", func() *httptest.ResponseRecorder { return chat("", "relay-b/deepseek-v4.1-flash") }, &seenB, "deepseek-v4.1-flash", "deepseek-v4.1-flash"}, + {"the held key's model", func() *httptest.ResponseRecorder { return chat(secrets[0], "relay-a/grok-4.6") }, &seenA, "grok-4.6@500k", "grok-4.6"}, + } { + if w := c.send(); w.Code != 200 { + t.Fatalf("%s: %d %s", c.what, w.Code, w.Body.String()) + } + c.seen.wire(t, c.what, []string{c.asked}) + if u := lastUsage(t); u.Provider == "" || u.Model != c.model || u.Served != c.asked { + t.Errorf("%s recorded as %s %s served %s, want %s served %s", c.what, u.Provider, u.Model, u.Served, c.model, c.asked) + } + } + + // the bare id is the group magpie found over both relays + gid, ok := provider.GroupFor("deepseek-v4.1-flash") + if !ok { + t.Fatal("no found group for deepseek-v4.1-flash") + } + _, ms, _ := provider.FindGroup(gid) + var members []string + for _, m := range ms { + members = append(members, m.Provider.ID+"/"+m.Model) + } + slices.Sort(members) + if want := []string{"relay-a/deepseek-v4.1-flash", "relay-b/deepseek-v4.1-flash"}; !slices.Equal(members, want) { + t.Fatalf("%s has %v, want %v", gid, members, want) + } + if w := chat("", "deepseek-v4.1-flash"); w.Code != 200 { + t.Fatalf("the bare id: %d %s", w.Code, w.Body.String()) + } + got := append(seenA.all(), seenB.all()...) + if len(got) != 1 || got[0] != "deepseek-v4.1-flash-1017" && got[0] != "deepseek-v4.1-flash" { + t.Fatalf("the bare id asked %v", got) + } + + // the held key: shown only its model, refused another + if ids := listed(secrets[0]); !slices.Contains(ids, "relay-a/grok-4.6") || slices.Contains(ids, "relay-a/deepseek-v4.1-flash") { + t.Fatalf("the held key lists %v", ids) + } + if w := chat(secrets[0], "relay-a/deepseek-v4.1-flash"); w.Code == 200 { + t.Fatal("the held key used a model it may not") + } + // a key held to the own id (written by hand, or before) is held to + // the model by either id + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"relay-a/deepseek-v4.1-flash-1017"}}); err != nil { + t.Fatal(err) + } + if w := chat(secrets[0], "relay-a/deepseek-v4.1-flash"); w.Code != 200 { + t.Fatalf("a key held to the own id: %d %s", w.Code, w.Body.String()) + } + if w := chat(secrets[0], "relay-a/grok-4.6"); w.Code == 200 { + t.Fatal("a key held to deepseek used grok") + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 38b9456be..d6219e833 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11580,6 +11580,24 @@ function renderModels(p) { same.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") same.blur(); else if (e.key === "Escape") { same.value = sameNow(); same.blur(); } }; sameBox.append(el("span", "", t("Same as")), same); row.append(sameBox); + // the id it is listed by here, asked for by its own (zeewell on X) + const savedID = m.vendor ? m.id : ""; + const idNow = () => prefs[id]?.id ?? savedID; + let idInput = null; + if (m.ids) { + const idBox = el("label", "msame mlocal"); + idInput = input(idNow(), m.vendor || m.id); + idInput.title = t("The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id", { id: m.id, own: m.vendor || m.id }); + idInput.spellcheck = false; + idInput.onchange = () => { + const v = idInput.value.trim(); + if (v === savedID) delete pref().id; else pref().id = v; + drawReset(); + }; + idInput.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") idInput.blur(); else if (e.key === "Escape") { idInput.value = idNow(); idInput.blur(); } }; + idBox.append(el("span", "", t("Listed as")), idInput); + row.append(idBox); + } // its cost to the user, $ per million tokens, as Usage counts it // (#819): a box empty is its list price. The 1-hour cache write, // empty, is 2× input as Anthropic bills it, and only a Claude model @@ -11781,7 +11799,7 @@ function renderModels(p) { const unsaved = el("span", "hint munsaved", t("unsaved")); unsaved.title = t("Made when the provider is saved; Cancel drops it"); const reset = el("button", "text action", t("Restore default")); - reset.title = t("Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price"); + reset.title = t("Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price"); reset.onclick = () => { prefs[id] = {}; if (draft.priceTyped) delete draft.priceTyped[id]; @@ -11796,6 +11814,8 @@ function renderModels(p) { if (m.api) prefs[id].api = ""; if (m.same) prefs[id].same = ""; same.value = sameNow(); + if (savedID) prefs[id].id = ""; + if (idInput) idInput.value = idNow(); if (m.price) prefs[id].ownPrice = true; showPrice(); if (apiSeg) { for (const b of apiSeg.querySelectorAll(".opt")) b.classList.toggle("on", b.dataset.api === apiNow()); slide(apiSeg, "api"); } @@ -11807,7 +11827,7 @@ function renderModels(p) { unsaved.hidden = !prefs[id] && !draft.priceTyped?.[id]; // staged back to its own already, there is nothing to restore const images = prefs[id]?.ownImages ? false : prefs[id]?.images !== undefined ? prefs[id].images !== !!m.ownImages : !!m.imageSet; - const custom = nameNow() !== "" || noneNow() || (prefs[id]?.efforts ? prefs[id].efforts.length > 0 : !!m.kept?.length) || images || apiNow() !== "" || sameNow() !== "" || priceNow() !== null || !!draft.priceTyped?.[id]; + const custom = nameNow() !== "" || noneNow() || (prefs[id]?.efforts ? prefs[id].efforts.length > 0 : !!m.kept?.length) || images || apiNow() !== "" || sameNow() !== "" || idNow() !== "" || priceNow() !== null || !!draft.priceTyped?.[id]; reset.hidden = !custom; }; row.append(unsaved, reset); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 619deafc3..1816d3c11 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2450,7 +2450,7 @@ const I18N = { "Its reasoning levels aren't known: tick the ones it takes": "推理档位未知:勾选它支持的档位", "{id}: {levels}": "{id}:{levels}", "Restore default": "恢复默认", - "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "恢复默认名称、全部推理档位、是否支持图片、请求所用的协议、它等同的模型,以及官方价格", + "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price": "恢复默认名称、全部推理档位、是否支持图片、请求所用的协议、它等同的模型、它自己的 ID,以及官方价格", "What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: its list price, shown greyed. A price set here isn't multiplied by the provider's price rate": "{id} 的价格,单位为美元 / 百万 tokens,用量页按它计费;留空即官方价格(灰字所示)。这里设的价格不再乘以供应商的价格倍率", "Off-peak price, the list's or one set here: the Usage page doubles it from 01:00 to 04:00 and 06:00 to 10:00 UTC, Monday to Friday{x}": "闲时价(官方价格或在此设置的价格):周一至周五 UTC 01:00–04:00 与 06:00–10:00{x},用量页按两倍计", ", except on Chinese public holidays": "(中国法定节假日除外)", @@ -2459,6 +2459,8 @@ const I18N = { "{id} has no list price: give its input and output prices": "{id} 没有官方价格:请填写输入和输出价格", "A price is a number of dollars, 0 or more": "价格是 0 或以上的美元数", "Same as": "等同于", + "Listed as": "列为", + "The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id": "magpie 在这个提供商列出 {id} 所用的 ID:智能体、路由组、magpie 找到的路由组、网关密钥和用量都用它,向提供商请求时仍用 {own}。留空:用它自己的 ID", "The model other providers serve that {id} is the same as: the routing groups magpie finds put them together, and what no list gives for {id} is that model's: its window, reply limit, reasoning levels, images and list price. Empty: by its own id": "{id} 等同于其他供应商的哪个模型:自动发现的路由组会将它们合并;任何列表都没给出的 {id} 信息(上下文窗口、回复上限、推理档位、图片输入和标价)都按那个模型的来。留空则按自身 ID 合并", "The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only": "{id} 请求所用的协议。自动:按供应商模型列表,否则依次尝试已填的各个地址;供应商仅在某协议上提供它时,选择该协议", "{id} is as its provider has it again": "{id} 已恢复为供应商的默认设置", @@ -6664,7 +6666,7 @@ const I18N = { "Its reasoning levels aren't known: tick the ones it takes": "推理檔位未知:勾選它支援的檔位", "{id}: {levels}": "{id}:{levels}", "Restore default": "恢復預設", - "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "恢復預設名稱、全部推理檔位、是否支援圖片、請求所用的協議、它等同的模型,以及官方價格", + "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price": "恢復預設名稱、全部推理檔位、是否支援圖片、請求所用的協議、它等同的模型、它自己的 ID,以及官方價格", "What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: its list price, shown greyed. A price set here isn't multiplied by the provider's price rate": "{id} 的價格,單位為美元 / 百萬 tokens,用量頁按它計費;留空即官方價格(灰字所示)。這裡設的價格不再乘以供應商的價格倍率", "Off-peak price, the list's or one set here: the Usage page doubles it from 01:00 to 04:00 and 06:00 to 10:00 UTC, Monday to Friday{x}": "離峰價(官方價格或在此設定的價格):週一至週五 UTC 01:00–04:00 與 06:00–10:00{x},用量頁按兩倍計", ", except on Chinese public holidays": "(中國法定節假日除外)", @@ -6673,6 +6675,8 @@ const I18N = { "{id} has no list price: give its input and output prices": "{id} 沒有官方價格:請填寫輸入和輸出價格", "A price is a number of dollars, 0 or more": "價格是 0 或以上的美元數", "Same as": "等同於", + "Listed as": "列為", + "The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id": "magpie 在這個供應商列出 {id} 所用的 ID:智慧體、路由組、magpie 找到的路由組、閘道金鑰和用量都用它,向供應商請求時仍用 {own}。留空:用它自己的 ID", "The model other providers serve that {id} is the same as: the routing groups magpie finds put them together, and what no list gives for {id} is that model's: its window, reply limit, reasoning levels, images and list price. Empty: by its own id": "{id} 等同於其他供應商的哪個模型:自動發現的路由組會將它們合併;任何列表都沒給出的 {id} 資訊(上下文視窗、回覆上限、推理檔位、圖片輸入和標價)都按那個模型的來。留空則按自身 ID 合併", "The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only": "{id} 請求所用的協議。自動:按供應商模型列表,否則依次嘗試已填的各個位址;供應商僅在某協議上提供它時,選擇該協議", "{id} is as its provider has it again": "{id} 已恢復為供應商的預設設定", @@ -10896,7 +10900,7 @@ const I18N = { "Its reasoning levels aren't known: tick the ones it takes": "推論レベルが不明です。対応するものにチェックを入れてください", "{id}: {levels}": "{id}:{levels}", "Restore default": "デフォルトに戻す", - "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "元の名前、すべての推論レベル、画像対応の有無、リクエストに使う API、同じモデルの指定、公式価格", + "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price": "元の名前、すべての推論レベル、画像対応の有無、リクエストに使う API、同じモデルの指定、元の ID、公式価格", "What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: its list price, shown greyed. A price set here isn't multiplied by the provider's price rate": "{id} の価格(米ドル / 100 万トークン)。使用量ページはこれで計算します。空欄なら公式価格(灰色で表示)。ここで設定した価格にはプロバイダーの価格倍率は掛かりません", "Off-peak price, the list's or one set here: the Usage page doubles it from 01:00 to 04:00 and 06:00 to 10:00 UTC, Monday to Friday{x}": "公式価格もここで設定した価格もオフピーク料金です。月曜から金曜の UTC 01:00–04:00 と 06:00–10:00{x}は、使用量ページで 2 倍として計算します", ", except on Chinese public holidays": "(中国の法定休日を除く)", @@ -10905,6 +10909,8 @@ const I18N = { "{id} has no list price: give its input and output prices": "{id} には公式価格がありません:入力と出力の価格を入力してください", "A price is a number of dollars, 0 or more": "価格は 0 以上のドル金額です", "Same as": "同じモデル", + "Listed as": "表示 ID", + "The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id": "magpie がこのプロバイダで {id} を一覧に出す ID:エージェント、ルーティンググループ、magpie が見つけるグループ、ゲートウェイキー、使用量はすべてこれを使い、プロバイダへのリクエストは {own} のままです。空欄:元の ID", "The model other providers serve that {id} is the same as: the routing groups magpie finds put them together, and what no list gives for {id} is that model's: its window, reply limit, reasoning levels, images and list price. Empty: by its own id": "{id} と同じである、他のプロバイダが提供するモデルです。magpie が見つけるルーティンググループでまとめられ、どの一覧にもない {id} の情報(コンテキスト長、応答の上限、推論レベル、画像入力、定価)はそのモデルのものを使います。空欄:自身の ID で", "The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only": "{id} へのリクエストに使う API です。自動:ベンダーの一覧に従い、なければプロバイダの各 URL を使います。ベンダーが特定の API でのみ提供している場合はそれを選んでください", "{id} is as its provider has it again": "{id} はプロバイダの設定どおりに戻りました", @@ -15139,7 +15145,7 @@ const I18N = { "Its reasoning levels aren't known: tick the ones it takes": "Seine Reasoning-Stufen sind unbekannt: Kreuzen Sie die unterstützten an", "{id}: {levels}": "{id}: {levels}", "Restore default": "Standard wiederherstellen", - "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "Eigener Name, alle Reasoning-Stufen, Bildunterstützung, die angefragte API, das Modell, dem es entspricht, und der Listenpreis", + "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price": "Eigener Name, alle Reasoning-Stufen, Bildunterstützung, die angefragte API, das Modell, dem es entspricht, die eigene ID und der Listenpreis", "What {id} costs, in US dollars per million tokens, as the Usage page counts it; empty: its list price, shown greyed. A price set here isn't multiplied by the provider's price rate": "Was {id} kostet, in US-Dollar pro Million Tokens, wie die Nutzungsseite rechnet; leer: der Listenpreis (grau). Ein hier gesetzter Preis wird nicht mit dem Preisfaktor des Anbieters multipliziert", "Off-peak price, the list's or one set here: the Usage page doubles it from 01:00 to 04:00 and 06:00 to 10:00 UTC, Monday to Friday{x}": "Listenpreis oder hier gesetzter Preis gilt außerhalb der Spitzenzeit: Montag bis Freitag von 01:00 bis 04:00 und 06:00 bis 10:00 UTC{x} zählt ihn die Nutzungsseite doppelt", ", except on Chinese public holidays": ", außer an chinesischen Feiertagen,", @@ -15148,6 +15154,8 @@ const I18N = { "{id} has no list price: give its input and output prices": "{id} hat keinen Listenpreis: gib Eingabe- und Ausgabepreis an", "A price is a number of dollars, 0 or more": "Ein Preis ist ein Dollarbetrag ab 0", "Same as": "Entspricht", + "Listed as": "Gelistet als", + "The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id": "Die ID, unter der magpie {id} bei diesem Anbieter listet: Agenten, Routing-Gruppen, die von magpie gefundenen Gruppen, Gateway-Schlüssel und die Nutzung verwenden sie, und beim Anbieter wird weiterhin {own} angefragt. Leer: die eigene ID", "The model other providers serve that {id} is the same as: the routing groups magpie finds put them together, and what no list gives for {id} is that model's: its window, reply limit, reasoning levels, images and list price. Empty: by its own id": "Das Modell anderer Anbieter, dem {id} entspricht: Die von magpie gefundenen Weiterleitungsgruppen fassen sie zusammen, und was keine Liste für {id} angibt, wird von diesem Modell übernommen: Kontextfenster, Antwortlimit, Denkstufen, Bildeingabe und Listenpreis. Leer: nach eigener ID", "The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only": "Die API, über die {id} angefragt wird. Automatisch: laut Modellliste des Anbieters, sonst jede hinterlegte URL; wählen Sie eine, wenn der Anbieter es nur dort bereitstellt", "{id} is as its provider has it again": "{id} entspricht wieder der Vorgabe seines Anbieters", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 7b2c11be5..7428dc21d 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -15,8 +15,8 @@ import ( // so a page can't quietly grow back into the core; a change that needs more // raises them and says why in its commit. const ( - appScriptBudget = 1_315_603 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30); 1,315,479 with the provider editor lining its Advanced up with its fields (the owner: 高级这个折叠按钮为什么在一个前不着村后不着店的位置?) and a refresh on each of its accounts (在这里也要加上手动刷新用量的按钮), the core's own editor, with no room added (10-31); 1,315,603 with About's Log row, the path of the log the app writes and an Open for its folder (rayem1w on X), in app.js, its comment cut to one line, with no room added (10-31) - coreScriptBudget = 1_538_678 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31) + appScriptBudget = 1_316_781 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30); 1,315,479 with the provider editor lining its Advanced up with its fields (the owner: 高级这个折叠按钮为什么在一个前不着村后不着店的位置?) and a refresh on each of its accounts (在这里也要加上手动刷新用量的按钮), the core's own editor, with no room added (10-31); 1,315,603 with About's Log row, the path of the log the app writes and an Open for its folder (rayem1w on X), in app.js, its comment cut to one line, with no room added (10-31); 1,316,781 with a provider's model listed by an id of the user's (zeewell on X), the provider editor's Names & levels Listed as box beside Same as, the core's own editor, with no room added (10-31) + coreScriptBudget = 1_539_856 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/providers.go b/internal/gui/providers.go index dac770855..c2c98b5dc 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -57,6 +57,11 @@ type modelJSON struct { Same string `json:"same,omitempty"` // the model the user said it is the same as, for the groups magpie finds (#583) Merge string `json:"merge,omitempty"` // what those groups merge it by when the user says nothing Kind string `json:"kind,omitempty"` // what the user said it makes: image or video (#1399) + // Vendor is the provider's own id of a model the user lists by + // another (provider.SetModelID), "" for one listed by its own; IDs + // says the provider's models can be given ids at all (a key's) + Vendor string `json:"vendor,omitempty"` + IDs bool `json:"ids,omitempty"` // Desktop is the number Claude Desktop's menu says beside this model // (gateway.DesktopNumber), so a row of that menu can be matched to its // provider (#2578): only for a model Claude Desktop, installed here, @@ -822,6 +827,10 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[string } j.NoAPI = p.NoAPIFor(m.ID) j.Same = sames[p.ID+"/"+m.ID] + if own := p.OwnModelID(m.ID); own != m.ID { + j.Vendor = own + } + j.IDs = p.TakesModelIDs() j.Kind = p.ModelKind(m.ID) j.Merge = provider.MergeName(m.ID) j.Desktop = desktop[p.ID+"/"+m.ID] diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index b3b51d82f..31ccf41b4 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -133,6 +133,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { ModelWires: map[string]string{"p/m": "vendor-c/m"}, ModelAPIs: map[string]string{"p/m": "anthropic"}, ModelSameAs: map[string]string{"p/m": "deepseek-v4.1-flash"}, + ModelIDs: map[string]string{"p/flash": "deepseek-v4.1-flash-1017"}, UsageAliases: map[string]string{"deepseek-v4.1-flash": "deepseek-flash"}, UsageCleared: []settings.UsageClear{{Provider: "p", Model: "m", At: 1761600000000}}, ModelKinds: map[string]string{"p/m": "video"}, diff --git a/internal/gui/tests/provider-detect.test.cjs b/internal/gui/tests/provider-detect.test.cjs index fddf6e3bf..91bc9a5af 100644 --- a/internal/gui/tests/provider-detect.test.cjs +++ b/internal/gui/tests/provider-detect.test.cjs @@ -151,7 +151,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "Taken · save to keep", "Ask {model} on {api} only", "Staged in Names & levels and made with the Save; Auto there gives it back", "{model} is asked on {api} once saved", "no URL to ask", "no model to try: type one the vendor serves", "no key is on for this endpoint", "The API {id} is asked on. Auto: as the vendor's list says, else each URL the provider has; pick one when the vendor serves it on that one only", - "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price", + "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price", ].filter((k) => !I18N.zh[k])); assert.deepEqual(missing, [], "every string has its Chinese"); assert.deepEqual(errors, []); diff --git a/internal/gui/tests/provider-listed-as.test.cjs b/internal/gui/tests/provider-listed-as.test.cjs new file mode 100644 index 000000000..81a530065 --- /dev/null +++ b/internal/gui/tests/provider-listed-as.test.cjs @@ -0,0 +1,103 @@ +// A relay's model can be listed by an id of the user's (zeewell on X: +// deepseek-v4.1-flash-1017 as deepseek-v4.1-flash), in the provider +// editor's Names & levels beside Same as: magpie lists, routes and counts +// it by that id, and the relay is still asked for its own. It is staged +// and made with the editor's Save, as the rest of Names & levels is; +// Restore default and an emptied box list it by its own id again. A +// signed-in account's models (ids false) have no such box. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const levels = ["none", "low", "medium", "high"]; + +function serve(lang, posts) { + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + const models = [ + { id: "deepseek-v4.1-flash-1017", name: "deepseek-v4.1-flash-1017", on: true, efforts: levels, images: false, merge: "deepseek-v4-1-flash-1017", ids: true }, + { id: "grok-4.6", name: "grok-4.6", on: true, efforts: levels, images: false, merge: "grok-4-6", ids: true, vendor: "grok-4.6@500k" }, + ]; + const relay = { id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example/v1", responses: "", anthropic: "", models, agents: [], key: { set: true, masked: "sk-…1234" }, ready: true }; + const acct = { id: "acct", name: "Acct", icon: "generic", chat: "https://acct.example/v1", responses: "", anthropic: "", models: [{ id: "m1", name: "m1", on: true, efforts: levels, images: false, merge: "m1" }], agents: [], key: { set: true, masked: "sk-…9999" }, ready: true }; + const providers = { providers: [relay, acct], presets: [], excluded: [], gateway: { running: true, window: true } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/provider/")) { + posts.push({ path: url.pathname, body: route.request().postDataJSON() }); + return json(providers); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + await route.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] }); + }; +} + +const keys = ["Names & levels", "Listed as", "unsaved", "Save", "Restore default"]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang}: the id a model is listed by is staged and made with the provider's Save`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 900, height: 720 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.waitForFunction(() => typeof I18N === "object"); + const L = Object.fromEntries(await page.evaluate(([lang, keys]) => keys.map((k) => [k, lang === "en" ? k : I18N[lang][k]]), [lang, keys])); + for (const k of keys) assert(L[k], `${lang} has ${k}`); + const open = async (id) => { + await page.locator(`.row.provider[data-id="${id}"]`).click(); + if (!(await page.locator(".mnames:not([hidden])").count())) await page.getByRole("button", { name: L["Names & levels"], exact: true }).click(); + }; + const row = (id) => page.locator(".mname", { has: page.locator("code", { hasText: id }) }); + const box = (id) => row(id).getByRole("textbox", { name: L["Listed as"], exact: true }); + await open("relay"); + // empty, it is its own id; one given shows, the own id beneath it + assert.equal(await box("deepseek-v4.1-flash-1017").inputValue(), ""); + assert.equal(await box("deepseek-v4.1-flash-1017").getAttribute("placeholder"), "deepseek-v4.1-flash-1017"); + assert.equal(await box("grok-4.6").inputValue(), "grok-4.6"); + assert.equal(await box("grok-4.6").getAttribute("placeholder"), "grok-4.6@500k"); + const list = await page.locator(".mnames:not([hidden])").elementHandle(); + const y = await page.evaluate(() => scrollY); + await box("deepseek-v4.1-flash-1017").fill("deepseek-v4.1-flash"); + await box("deepseek-v4.1-flash-1017").press("Enter"); + await row("grok-4.6").getByRole("button", { name: L["Restore default"] }).click(); + await page.waitForTimeout(200); + assert.deepEqual(posts, [], "nothing is sent before the Save"); + assert(await list.evaluate((e) => e.isConnected), "the list is not redrawn"); + assert.equal(await page.evaluate(() => scrollY), y, "nothing scrolls the page"); + assert.equal(await box("grok-4.6").inputValue(), "", "Restore default empties it"); + for (const id of ["deepseek-v4.1-flash-1017", "grok-4.6"]) assert(await row(id).getByText(L.unsaved, { exact: true }).isVisible(), id + " says it is unsaved"); + // the box sits in the row as Same as does, no wider than the row + const fits = await row("grok-4.6").evaluate((r) => [...r.querySelectorAll("input")].every((i) => i.getBoundingClientRect().right <= r.getBoundingClientRect().right + 1)); + assert(fits, "the box fits its row"); + await page.getByRole("button", { name: L.Save, exact: true }).click(); + await page.waitForFunction(() => !document.querySelector(".mnames")); + assert.deepEqual(posts.map((p) => p.path), ["/api/provider/save"]); + assert.deepEqual(posts[0].body.modelPrefs["deepseek-v4.1-flash-1017"], { id: "deepseek-v4.1-flash" }); + assert.equal(posts[0].body.modelPrefs["grok-4.6"].id, ""); + // an account's models take none + await open("acct"); + assert.equal(await row("m1").getByRole("textbox", { name: L["Listed as"], exact: true }).count(), 0); + const missing = await page.evaluate(() => ["Listed as", + "The id magpie lists {id} by at this provider: agents, routing groups, the groups magpie finds, gateway keys and Usage all use it, and the provider is still asked for {own}. Empty: its own id", + "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price", + ].flatMap((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l][k]).map((l) => `${l}: ${k}`))); + assert.deepEqual(missing, [], "every string has every language"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/provider-same-as.test.cjs b/internal/gui/tests/provider-same-as.test.cjs index b34f87c5b..aeaa44406 100644 --- a/internal/gui/tests/provider-same-as.test.cjs +++ b/internal/gui/tests/provider-same-as.test.cjs @@ -93,7 +93,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(posts[0].body.modelPrefs, { "deepseek-v4-1-flash-260910": { same: "deepseek-v4.1-flash" }, "ep-2026-sol": { same: "" } }); const missing = await page.evaluate(() => ["Same as", "The model other providers serve that {id} is the same as: the routing groups magpie finds put them together, and what no list gives for {id} is that model's: its window, reply limit, reasoning levels, images and list price. Empty: by its own id", - "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price", + "Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, its own id, and its list price", ].flatMap((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l][k]).map((l) => `${l}: ${k}`))); assert.deepEqual(missing, [], "every string has every language"); assert.deepEqual(errors, []); diff --git a/internal/provider/localid.go b/internal/provider/localid.go new file mode 100644 index 000000000..8b5729138 --- /dev/null +++ b/internal/provider/localid.go @@ -0,0 +1,376 @@ +package provider + +import ( + "errors" + "fmt" + "slices" + "strings" + "unicode" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" +) + +// A model can be listed at its provider by an id the user gives it +// (settings' ModelIDs), for a provider that serves one model under ids of +// its own (zeewell on X: deepseek-v4.1-flash-1017 at one relay, +// grok-4.6@500k at another). Everything magpie lists, picks, groups, finds +// routing groups by, limits a gateway key to and records usage under is +// that id; a request for it goes out under the provider's own, through +// the same wire names (settings' Wires) a ModelWires name goes out by. +// 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. + +// 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. +type localIDs struct { + local map[string]string // own id → the id it is listed by + own map[string]string // the id it is listed by → own id +} + +// modelIDsOf are the ids the user gave the provider pid's models. +func modelIDsOf(pid string) localIDs { + return idsIn(settings.SharedModelIDs(), pid) +} + +func idsIn(all map[string]string, pid string) localIDs { + var l localIDs + if len(all) == 0 { + return l + } + for k, own := range all { + model, ok := strings.CutPrefix(k, pid+"/") + own = strings.TrimSpace(own) + if !ok || model == "" || own == "" || own == model { + continue + } + if l.local == nil { + l.local, l.own = map[string]string{}, map[string]string{} + } + // two ids given one model (a hand-edited file): the first, in + // order, is its + if had, ok := l.local[own]; ok && had < model { + continue + } + if had, ok := l.local[own]; ok { + delete(l.own, had) + } + l.local[own], l.own[model] = model, own + } + return l +} + +func (l localIDs) none() bool { return len(l.own) == 0 } + +// ownOf is the provider's own id of the model listed as model. +func (l localIDs) ownOf(model string) string { + if own, ok := l.own[model]; ok { + return own + } + return model +} + +// list is ms with each model given an id listed by the id the user gave +// it, and a model of the provider's own id one of those is given left +// out while the model given it is listed (the one id is one model). +func (l localIDs) list(ms []catalog.Model) []catalog.Model { + if l.none() || len(ms) == 0 { + return ms + } + has := make(map[string]bool, len(ms)) + for _, m := range ms { + has[m.ID] = true + } + out := make([]catalog.Model, 0, len(ms)) + seen := make(map[string]bool, len(ms)) + for _, m := range ms { + if local, ok := l.local[m.ID]; ok { + if m.Name == "" || m.Name == m.ID { + m.Name = local + } + m.ID = local + } else if own, ok := l.own[m.ID]; ok && has[own] { + continue // listed by the model given its id + } + if seen[m.ID] { + continue + } + seen[m.ID] = true + out = append(out, m) + } + return out +} + +// ids is set (of the provider's own ids) with each given another id by it. +func (l localIDs) ids(set map[string]bool) map[string]bool { + if l.none() { + return set + } + out := make(map[string]bool, len(set)) + for id := range set { + if _, ok := l.local[id]; ok { + continue + } + if own, ok := l.own[id]; ok && set[own] { + continue + } + out[id] = true + } + for own, local := range l.local { + if set[own] { + out[local] = true + } + } + return out +} + +// 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 } + +// 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. +func (p Provider) TakesModelIDs() bool { return p.takesModelIDs() } + +// ids are the ids the user gave p's models, none for a provider that +// takes none. +func (p Provider) ids() localIDs { + if !p.takesModelIDs() { + return localIDs{} + } + return modelIDsOf(p.ID) +} + +// OwnModelID is the provider's own id of its model listed as model: the +// id the vendor is asked for it by, the same as model unless the user +// lists it by another (SetModelID). +func (p Provider) OwnModelID(model string) string { return p.ids().ownOf(model) } + +// ListedModelID is the id p lists its model of its own id own by: the one +// the user gave it, else own. +func (p Provider) ListedModelID(own string) string { + if local, ok := p.ids().local[own]; ok { + return local + } + return own +} + +// ModelIDs are the ids the user lists p's models by, from each one to the +// provider's own id of it. +func (p Provider) ModelIDs() map[string]string { + out := map[string]string{} + for local, own := range p.ids().own { + out[local] = own + } + return out +} + +// rawIDs are the ids of the models the provider itself lists for chat, +// before any is listed by another id, and those the user picked that its +// list doesn't have (typed in, or not fetched yet). +func (p Provider) rawIDs() map[string]bool { + out := map[string]bool{} + for _, m := range p.available() { + out[m.ID] = true + } + for _, id := range p.Models { + if _, given := p.ids().own[id]; !given { + out[id] = true + } + } + return out +} + +// checkModelID is why id can't be one a model is listed by, if it can't. +func checkModelID(id string) error { + switch { + case id == "*" || strings.Contains(id, "*"): + return errors.New(`a model's id can't have "*" in it`) + case strings.HasPrefix(id, "-"): + return fmt.Errorf("a model's id can't start with -, not %q", id) + case strings.IndexFunc(id, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) >= 0: + return fmt.Errorf("a model's id has no spaces in it, not %q", id) + case IsGroupRef(id): + return errors.New("that is a routing group's id, not a model's") + } + return nil +} + +// SetModelID lists a provider's model, spelled "provider/model" by the id +// it is listed by now or by the provider's own, by id instead, and says +// which of its models had the id before (replaced) and whether anything +// changed: what +// magpie lists, picks, groups, routes and records it by, while the +// provider is still asked for it by its own id. A blank id, or the +// provider's own, lists it by its own again. +// +// One id is one model of a provider, so an id already given another of its +// models is that model's no more, which it answers (the latest one given +// it wins): that model is listed by its own id again. A model of the +// provider's own id is not listed while another is listed by it, and an +// agent's or a group's ref to the id reaches the model given it. +// +// What the user picked, grouped, set and said of the model goes with it to +// the new id: its picks, a key's models, its context, the routing groups' +// refs and fallbacks, the pickers' lists and every per-model setting — but +// a setting the user already has under the new id, which stays theirs. +// Agents' own files are not rewritten: a "provider/" they still +// name resolves, and is asked for under that id (Resolve). +func SetModelID(ref, id string) (replaced string, changed bool, err error) { + replaced, changed, err = setModelID(ref, id) + return replaced, changed, touchedIf(changed, err) +} + +func setModelID(ref, id string) (string, bool, error) { + p, model, err := splitRef(ref) + if err != nil { + 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) + } + id = strings.TrimSpace(id) + if id != "" { + if err := checkModelID(id); err != nil { + return "", false, err + } + } + s := settings.Load() + ids := idsIn(s.ModelIDs, p.ID) + raw := p.rawIDs() + // model is the id it is listed by now, or the provider's own + cur, own := model, ids.ownOf(model) + if own == model { + if local, ok := ids.local[model]; ok { + cur = local + } else if !raw[model] { + return "", false, fmt.Errorf("%s has no model %s (magpie provider %s lists them)", p.ID, model, p.ID) + } + } + if id == "" { + id = own + } + if id == cur { + return "", false, nil + } + var replaced string + if had, ok := ids.own[id]; ok && had != own { + // the latest model given the id has it + replaced = had + } + if s.ModelIDs == nil { + s.ModelIDs = map[string]string{} + } + delete(s.ModelIDs, p.ID+"/"+cur) + for k, v := range s.ModelIDs { + // any other id the model went by (a hand-edited file) + if strings.HasPrefix(k, p.ID+"/") && strings.TrimSpace(v) == own { + delete(s.ModelIDs, k) + } + } + if id != own { + s.ModelIDs[p.ID+"/"+id] = own + } + if len(s.ModelIDs) == 0 { + s.ModelIDs = nil + } + if err := moveModelRefs(p.ID, cur, id); err != nil { + return "", false, err + } + s.MoveModel(p.ID+"/"+cur, p.ID+"/"+id) + moveModelLists(&s, p.ID+"/"+cur, p.ID+"/"+id) + if err := settings.Save(s); err != nil { + return "", false, err + } + if ModelMoved != nil { + if err := ModelMoved(p.ID+"/"+cur, p.ID+"/"+id); err != nil { + return replaced, true, err + } + } + return replaced, true, nil +} + +// ModelMoved, when set, gives what another package keeps of a provider's +// model ("/") the id it is listed by now (SetModelID): the +// gateway keys' models (access), which this package can't reach. +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 { + f, err := read() + if err != nil { + return err + } + i := slices.IndexFunc(f.Providers, func(q Provider) bool { return q.ID == pid }) + if i < 0 { + return fmt.Errorf("no provider %q", pid) + } + q := &f.Providers[i] + moved := func(ids []string) []string { + if !slices.Contains(ids, from) { + return ids + } + out := make([]string, 0, len(ids)) + for _, m := range ids { + if m == from { + m = to + } + if !slices.Contains(out, m) { + out = append(out, m) + } + } + 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 + } + delete(q.Contexts, from) + } + ref := func(m string) string { + pre, rest := "", m + if r, ok := strings.CutPrefix(m, "magpie/"); ok { + pre, rest = "magpie/", r + } + if rest == pid+"/"+from { + return pre + pid + "/" + to + } + return m + } + mapModelRefs(&f, ref) + return store(f) +} + +// moveModelLists gives the pickers' lists of the settings (hidden, picked +// for an agent, ordered, fast, Ultrafast) the model from as to. +func moveModelLists(s *settings.Settings, from, to string) { + for _, m := range []map[string][]string{s.HiddenModels, s.PickedModels, s.OrderedModels, s.FastPicks, s.UltraPicks} { + for k, ids := range m { + if !slices.Contains(ids, from) { + continue + } + out := make([]string, 0, len(ids)) + for _, id := range ids { + if id == from { + id = to + } + if !slices.Contains(out, id) { + out = append(out, id) + } + } + m[k] = out + } + } +} diff --git a/internal/provider/localid_test.go b/internal/provider/localid_test.go new file mode 100644 index 000000000..fb0a28c9d --- /dev/null +++ b/internal/provider/localid_test.go @@ -0,0 +1,257 @@ +package provider + +import ( + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" +) + +// localIDHome is two relays of the user's own (zeewell on X): relay-a lists +// deepseek-v4.1-flash-1017 and both grok-4.6 and grok-4.6@500k, relay-b +// deepseek-v4.1-flash. +func localIDHome(t *testing.T) { + t.Helper() + azureHome(t) + for _, r := range []struct { + id string + ids []string + }{ + {"relay-a", []string{"deepseek-v4.1-flash-1017", "grok-4.6", "grok-4.6@500k"}}, + {"relay-b", []string{"deepseek-v4.1-flash"}}, + } { + base := "https://" + r.id + ".example.invalid/v1" + if err := Save(Provider{ID: r.id, Name: r.id, Key: "sk-" + r.id, Chat: base}); err != nil { + t.Fatal(err) + } + var ms []catalog.Model + for _, id := range r.ids { + ms = append(ms, catalog.Model{ID: id}) + } + if err := catalog.SaveLive(r.id, base, ms); err != nil { + t.Fatal(err) + } + } +} + +func findProvider(t *testing.T, id string) Provider { + t.Helper() + p, err := Find(id) + if err != nil { + t.Fatal(err) + } + return *p +} + +func modelIDList(ms []catalog.Model) []string { + var out []string + for _, m := range ms { + out = append(out, m.ID) + } + return out +} + +func setID(t *testing.T, ref, id string) string { + t.Helper() + replaced, changed, err := SetModelID(ref, id) + if err != nil { + t.Fatal(err) + } + if !changed { + t.Fatalf("SetModelID(%q, %q) changed nothing", ref, id) + } + return replaced +} + +// A model given an id is listed, resolved, found in a group with the +// other relay's model of that id, and asked for by its own id. +func TestModelIDListedAndAskedForByOwn(t *testing.T) { + localIDHome(t) + setID(t, "relay-a/deepseek-v4.1-flash-1017", "deepseek-v4.1-flash") + setID(t, "relay-a/grok-4.6@500k", "grok-4.6") + + a := findProvider(t, "relay-a") + // grok-4.6 of relay-a's own is not listed while @500k is listed by it + if got, want := modelIDList(a.Available()), []string{"deepseek-v4.1-flash", "grok-4.6"}; !slices.Equal(got, want) { + t.Fatalf("relay-a lists %v, want %v", got, want) + } + for local, own := range map[string]string{"deepseek-v4.1-flash": "deepseek-v4.1-flash-1017", "grok-4.6": "grok-4.6@500k"} { + if got := a.OwnModelID(local); got != own { + t.Errorf("OwnModelID(%s) = %s, want %s", local, got, own) + } + if got := UpstreamName(a, local); got != own { + t.Errorf("UpstreamName(%s) = %s, want %s: the vendor is asked for its own id", local, got, own) + } + p, model, ok := Resolve("relay-a/" + local) + if !ok || p.ID != "relay-a" || model != local { + t.Errorf("Resolve(relay-a/%s) = %s %s %v", local, p.ID, model, ok) + } + } + // an agent's old ref to the own id still resolves, asked for as is + if p, model, ok := Resolve("relay-a/deepseek-v4.1-flash-1017"); !ok || p.ID != "relay-a" || UpstreamName(p, model) != "deepseek-v4.1-flash-1017" { + t.Errorf("old ref: %s %s %v", p.ID, model, ok) + } + // relay-b's model of its own id is unchanged + if got := UpstreamName(findProvider(t, "relay-b"), "deepseek-v4.1-flash"); got != "deepseek-v4.1-flash" { + t.Errorf("relay-b asked for %s", got) + } + + // the found group has both relays under the one id + gid, ok := GroupFor("deepseek-v4.1-flash") + if !ok { + t.Fatal("no found group for deepseek-v4.1-flash") + } + _, ms, ok := FindGroup(gid) + if !ok { + t.Fatalf("FindGroup(%s)", gid) + } + var members []string + for _, m := range ms { + members = append(members, m.Provider.ID+"/"+m.Model) + } + slices.Sort(members) + if want := []string{"relay-a/deepseek-v4.1-flash", "relay-b/deepseek-v4.1-flash"}; !slices.Equal(members, want) { + t.Fatalf("%s has %v, want %v", gid, members, want) + } + + // reset: listed by its own id again, nothing left in the settings + if _, changed, err := SetModelID("relay-a/deepseek-v4.1-flash", ""); err != nil || !changed { + t.Fatalf("reset: %v %v", changed, err) + } + if _, changed, err := SetModelID("relay-a/grok-4.6", "--reset"); err == nil || changed { + t.Fatalf("a flag taken as an id: %v %v", changed, err) + } + setID(t, "relay-a/grok-4.6", "grok-4.6@500k") + if got := modelIDList(findProvider(t, "relay-a").Available()); !slices.Equal(got, []string{"deepseek-v4.1-flash-1017", "grok-4.6", "grok-4.6@500k"}) { + t.Fatalf("after reset relay-a lists %v", got) + } + if ids := settings.Load().ModelIDs; len(ids) != 0 { + t.Fatalf("after reset ModelIDs = %v", ids) + } +} + +// 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. +func TestModelIDLatestWins(t *testing.T) { + localIDHome(t) + setID(t, "relay-a/grok-4.6@500k", "grok") + if replaced := setID(t, "relay-a/deepseek-v4.1-flash-1017", "grok"); replaced != "grok-4.6@500k" { + t.Fatalf("replaced %q, want grok-4.6@500k", replaced) + } + a := findProvider(t, "relay-a") + if got, want := modelIDList(a.Available()), []string{"grok", "grok-4.6", "grok-4.6@500k"}; !slices.Equal(got, want) { + t.Fatalf("relay-a lists %v, want %v", got, want) + } + if got := a.OwnModelID("grok"); got != "deepseek-v4.1-flash-1017" { + t.Fatalf("grok is %s", got) + } + + // two rows of one save can't take one id + if err := SetModelPrefs("relay-a", map[string]ModelPref{ + "grok-4.6": {ID: refOf("x")}, + "grok-4.6@500k": {ID: refOf("x")}, + }); err == nil || !strings.Contains(err.Error(), "can't both be listed as x") { + t.Fatalf("SetModelPrefs with one id twice: %v", err) + } +} + +func refOf[T any](v T) *T { return &v } + +// What the user picked, grouped and set of the model goes to its new id, +// but a value they already have under that id stays theirs. +func TestModelIDMovesTheUsersRefs(t *testing.T) { + localIDHome(t) + a := findProvider(t, "relay-a") + a.Models = []string{"deepseek-v4.1-flash-1017", "grok-4.6"} + a.Contexts = map[string]int{"deepseek-v4.1-flash-1017": 64000} + if err := Save(a); err != nil { + t.Fatal(err) + } + b := findProvider(t, "relay-b") + b.Fallback = []string{"relay-a/deepseek-v4.1-flash-1017"} + if err := Save(b); err != nil { + t.Fatal(err) + } + if err := SaveGroup(Group{ID: "flash", Name: "Flash", Members: []string{"relay-b/deepseek-v4.1-flash", "relay-a/deepseek-v4.1-flash-1017"}}); err != nil { + t.Fatal(err) + } + s := settings.Load() + s.HiddenModels = map[string][]string{"codex": {"relay-a/deepseek-v4.1-flash-1017"}} + s.ModelOutputs = map[string]int{"relay-a/deepseek-v4.1-flash-1017": 8000} + s.ModelNames = map[string]string{"relay-a/deepseek-v4.1-flash-1017": "old", "relay-a/deepseek-v4.1-flash": "Mine"} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + var moved [][2]string + old := ModelMoved + ModelMoved = func(from, to string) error { moved = append(moved, [2]string{from, to}); return nil } + t.Cleanup(func() { ModelMoved = old }) + + setID(t, "relay-a/deepseek-v4.1-flash-1017", "deepseek-v4.1-flash") + + a = findProvider(t, "relay-a") + if !slices.Equal(a.Models, []string{"deepseek-v4.1-flash", "grok-4.6"}) { + t.Errorf("picks %v", a.Models) + } + if a.Contexts["deepseek-v4.1-flash"] != 64000 || len(a.Contexts) != 1 { + t.Errorf("contexts %v", a.Contexts) + } + if b := findProvider(t, "relay-b"); !slices.Equal(b.Fallback, []string{"relay-a/deepseek-v4.1-flash"}) { + t.Errorf("fallback %v", b.Fallback) + } + g, _, ok := FindGroup(GroupPrefix + "flash") + if !ok || !slices.Equal(g.Members, []string{"relay-b/deepseek-v4.1-flash", "relay-a/deepseek-v4.1-flash"}) { + t.Errorf("group %v %v", g.Members, ok) + } + s = settings.Load() + if got := s.HiddenModels["codex"]; !slices.Equal(got, []string{"relay-a/deepseek-v4.1-flash"}) { + t.Errorf("hidden %v", got) + } + if s.ModelOutputs["relay-a/deepseek-v4.1-flash"] != 8000 { + t.Errorf("outputs %v", s.ModelOutputs) + } + // the user's own value under the new id is never written over + if s.ModelNames["relay-a/deepseek-v4.1-flash"] != "Mine" { + t.Errorf("names %v", s.ModelNames) + } + if !slices.Equal(moved, [][2]string{{"relay-a/deepseek-v4.1-flash-1017", "relay-a/deepseek-v4.1-flash"}}) { + t.Errorf("ModelMoved got %v", moved) + } +} + +// Only a provider of the user's own takes an id, and only one a model +// can have. +func TestModelIDRefused(t *testing.T) { + localIDHome(t) + for _, id := range []string{"a b", "x*", "-x", "group/flash"} { + if _, changed, err := SetModelID("relay-a/grok-4.6", id); err == nil || changed { + t.Errorf("id %q taken: %v", id, changed) + } + } + 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 len(settings.Load().ModelIDs) != 0 { + t.Fatalf("ModelIDs = %v", settings.Load().ModelIDs) + } +} + +// The picks of a provider's list (liveIDs) and its keys' models +// (Serving) are read by the id the model is listed by. +func TestModelIDServingAndPrice(t *testing.T) { + localIDHome(t) + setID(t, "relay-a/deepseek-v4.1-flash-1017", "deepseek-v4.1-flash") + ids := liveIDs("relay-a") + if !ids["deepseek-v4.1-flash"] || ids["deepseek-v4.1-flash-1017"] { + t.Fatalf("liveIDs %v", ids) + } + a := findProvider(t, "relay-a") + if ms := a.liveByID("deepseek-v4.1-flash"); len(ms) != 1 || ms[0].ID != "deepseek-v4.1-flash" { + t.Fatalf("liveByID %v", ms) + } +} diff --git a/internal/provider/modelprefs.go b/internal/provider/modelprefs.go index bad741055..ba2da1d94 100644 --- a/internal/provider/modelprefs.go +++ b/internal/provider/modelprefs.go @@ -512,6 +512,10 @@ type ModelPref struct { // Kind is what the model makes, as SetModelKind takes it: "image", // "video", or "" for what its vendor's list and name say (#1399) Kind *string `json:"kind,omitempty"` + // ID is the id the model is listed by at its provider, as SetModelID + // takes it: "" for the provider's own. It is applied after every + // other change of the save, so those go with the model to its id. + ID *string `json:"id,omitempty"` } // SetModelPrefs makes the changes to a provider's models, by model id, as @@ -581,11 +585,45 @@ func SetModelPrefs(pid string, prefs map[string]ModelPref) error { } } } - return nil + return setModelIDs(pid, prefs, set) }() return touchedIf(changed, err) } +// setModelIDs gives the models of one save the ids it lists them by +// (ModelPref.ID), after everything else it changed. Two of them given one +// id are refused before either is: one id is one model of a provider. +func setModelIDs(pid string, prefs map[string]ModelPref, set func(bool, error) error) error { + to := map[string]string{} + for _, model := range slices.Sorted(maps.Keys(prefs)) { + id := prefs[model].ID + if id == nil { + continue + } + want := strings.TrimSpace(*id) + if want == "" { + continue + } + if other, ok := to[want]; ok { + return fmt.Errorf("%s and %s can't both be listed as %s: one id is one model of a provider", other, model, want) + } + to[want] = model + } + for want, model := range to { + if other := prefs[want].ID; other != nil && want != model && strings.TrimSpace(*other) != want { + return fmt.Errorf("%s is listed as another id in the same save that gives its id to %s: save one, then the other", want, model) + } + } + for _, model := range slices.Sorted(maps.Keys(prefs)) { + if id := prefs[model].ID; id != nil { + if _, c, err := setModelID(pid+"/"+model, *id); set(c, err) != nil { + return err + } + } + } + return nil +} + // setModelSame says which model a provider's model, spelt "provider/model", // is the same as, for one a vendor names its own way (Volcengine Ark's // dated ids, kyzhouxu on #583): the routing groups magpie finds merge it @@ -939,7 +977,7 @@ func ServesModel(p Provider, model string) bool { return p.serves(model) } // model asked for by the name the vendor serves it under is not read as // another one. func UpstreamName(p Provider, model string) string { - return UpstreamNameIn(settings.Load().ModelWires, p.ID, model) + return UpstreamNameIn(settings.Load().Wires(), p.ID, model) } // UpstreamNameIn is UpstreamName over a settings' ModelWires already read, @@ -969,7 +1007,7 @@ func UpstreamNameIn(wires map[string]string, pid, model string) string { // asks for gemini-3.7-flash-high and gemini-3.7-flash-low each by its own, // rather than for the one id whatever level the effort picked. func UpstreamNameAs(p Provider, model, sent string) string { - return UpstreamNameAsIn(settings.Load().ModelWires, p.ID, model, sent) + return UpstreamNameAsIn(settings.Load().Wires(), p.ID, model, sent) } // UpstreamNameAsIn is UpstreamNameAs over a settings' ModelWires already diff --git a/internal/provider/models.go b/internal/provider/models.go index 2721df30d..ea7d78e30 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -34,7 +34,8 @@ func (p Provider) Available() []catalog.Model { if p.DecideOnly() { return p.decideModels() } - ms := p.available() + // by the ids the user lists them by (SetModelID) + ms := p.ids().list(p.available()) if p.Decides() { // a gateway's Jev among its chat models, with its window and input ms = slices.Clone(ms) @@ -163,7 +164,18 @@ func (p Provider) liveByID(model string) []catalog.Model { if !p.lists() { return nil } - return catalog.LiveByID(p.ID, model) + // a model listed by an id the user gave it is in the vendor's list + // under its own (SetModelID) + own := p.OwnModelID(model) + ms := catalog.LiveByID(p.ID, own) + if own == model { + return ms + } + out := slices.Clone(ms) + for i := range out { + out[i].ID = model + } + return out } // lists says whether the provider's fetched list is its own to read: not @@ -294,7 +306,8 @@ func liveIDs(id string) map[string]bool { for _, m := range ms { out[m.ID] = true } - return out + // picks are of the ids the user lists them by (SetModelID) + return modelIDsOf(id).ids(out) } // dropGonePicks takes out of the saved provider's picks those before had @@ -1444,10 +1457,13 @@ func (p Provider) Serves(k KeyAccount, model string) bool { return p.Serving(mod // thousand keys (@NetRozee on X). func (p Provider) Serving(model string) func(KeyAccount) bool { x, ok := p.keyLists() - if !ok { + if !ok || len(x.listed) == 0 { + // no key is listed to any model: every key serves it, and the + // model's own id needn't be looked up return func(KeyAccount) bool { return true } } - keys, found := x.of[model] + // the vendor's lists name the model by its own id (SetModelID) + keys, found := x.of[p.OwnModelID(model)] return func(k KeyAccount) bool { id := keyID(k.Key) return !found || len(keys) == 0 || !x.listed[id] || keys[id] @@ -1877,6 +1893,13 @@ var makerCatalogs = sync.OnceValue(func() []string { // auto-review through the Codex subscription costs nothing too, as OpenAI // serves it a ChatGPT sign-in (codexReviewFree). func (p Provider) ListPrice(model string) (catalog.Price, bool) { + if own := p.OwnModelID(model); own != model { + // a model listed by an id the user gave it is priced as the + // provider's own id of it first, then as the id it is listed by + if pr, ok := p.ListPrice(own); ok { + return pr, true + } + } if pr, ok := p.remotePrice(model); ok { return pr, true } diff --git a/internal/provider/rename.go b/internal/provider/rename.go index 79d5fbe62..fa2f99358 100644 --- a/internal/provider/rename.go +++ b/internal/provider/rename.go @@ -75,11 +75,7 @@ func Rename(from, to string) error { if !sub && !slices.Contains(p.Was, from) { p.Was = append(p.Was, from) } - for j := range f.Providers { - for k, m := range f.Providers[j].Fallback { - f.Providers[j].Fallback[k] = renamedRef(m, from, to) - } - } + mapModelRefs(&f, func(m string) string { return renamedRef(m, from, to) }) for j, id := range f.Order { if id == from { f.Order[j] = to @@ -97,27 +93,6 @@ func Rename(from, to string) error { f.Deleted[j].Into = to } } - for j := range f.Groups { - g := &f.Groups[j] - for k, m := range g.Members { - g.Members[k] = renamedRef(m, from, to) - } - for k := range g.Rules { - g.Rules[k].MapUses(func(u string) string { return renamedRef(u, from, to) }) - } - for k, m := range g.Fast { - g.Fast[k] = renamedRef(m, from, to) - } - for k, m := range g.Placed { - g.Placed[k] = renamedRef(m, from, to) - } - for k, m := range g.Off { - g.Off[k] = renamedRef(m, from, to) - } - g.Weights = renamedWeights(g.Weights, func(m string) string { return renamedRef(m, from, to) }) - g.Classifier = renamedRef(g.Classifier, from, to) - g.Pick = renamedRef(g.Pick, from, to) - } // the vendor's list last fetched goes with it os.Rename(catalog.LivePath(from), catalog.LivePath(to)) os.Rename(catalog.LivePath(decisionsID(from)), catalog.LivePath(decisionsID(to))) @@ -143,6 +118,40 @@ func Rename(from, to string) error { return nil } +// mapModelRefs gives every model ref the file keeps for routing — the +// providers' fallbacks, and the routing groups' members, rules, fast and +// placed members, those turned off, weights, classifiers and picks — as +// to has it: what a provider's rename (Rename) and a model given another +// id at its provider (SetModelID) both rewrite. +func mapModelRefs(f *file, to func(string) string) { + for j := range f.Providers { + for k, m := range f.Providers[j].Fallback { + f.Providers[j].Fallback[k] = to(m) + } + } + for j := range f.Groups { + g := &f.Groups[j] + for k, m := range g.Members { + g.Members[k] = to(m) + } + for k := range g.Rules { + g.Rules[k].MapUses(to) + } + for k, m := range g.Fast { + g.Fast[k] = to(m) + } + for k, m := range g.Placed { + g.Placed[k] = to(m) + } + for k, m := range g.Off { + g.Off[k] = to(m) + } + g.Weights = renamedWeights(g.Weights, to) + g.Classifier = to(g.Classifier) + g.Pick = to(g.Pick) + } +} + // renamedRef is a model id ("provider/model", "magpie/provider/model") // with the provider from named to instead. func renamedRef(ref, from, to string) string { diff --git a/internal/settings/model_ids_test.go b/internal/settings/model_ids_test.go new file mode 100644 index 000000000..6bd10ec56 --- /dev/null +++ b/internal/settings/model_ids_test.go @@ -0,0 +1,54 @@ +package settings + +import ( + "testing" +) + +// Wires is ModelWires with each model the user lists by an id of theirs +// sent as the provider's own: a wire the user gave that id is theirs, a +// provider's "*" wire wraps the own id, and the maps are read again when +// they change in place. +func TestWiresTakeModelIDs(t *testing.T) { + s := Settings{ + ModelWires: map[string]string{"r/x": "vendor-x", "p/*": "acct/*"}, + ModelIDs: map[string]string{"r/flash": "flash-1017", "r/x": "x-own", "p/grok": "grok@500k", "r/blank": " "}, + } + w := s.Wires() + for k, want := range map[string]string{"r/flash": "flash-1017", "r/x": "vendor-x", "p/grok": "acct/grok@500k", "p/*": "acct/*"} { + if w[k] != want { + t.Errorf("Wires()[%s] = %q, want %q", k, w[k], want) + } + } + if _, ok := w["r/blank"]; ok { + t.Error("a blank own id is a wire") + } + s.ModelIDs["r/flash"] = "flash-1018" + if got := s.Wires()["r/flash"]; got != "flash-1018" { + t.Errorf("after a change in place: %q", got) + } + if got := (Settings{ModelWires: map[string]string{"a/b": "c"}}).Wires(); len(got) != 1 || got["a/b"] != "c" { + t.Errorf("no ModelIDs: %v", got) + } +} + +// MoveModel moves every per-model setting but ModelIDs to the new key, +// and keeps one the user already has there. +func TestMoveModelKeepsTheUsersOwn(t *testing.T) { + s := Settings{ + ModelNames: map[string]string{"r/old": "Old", "r/new": "Mine"}, + ModelOutputs: map[string]int{"r/old": 8000}, + ModelIDs: map[string]string{"r/old": "x"}, + } + if !s.MoveModel("r/old", "r/new") { + t.Fatal("nothing moved") + } + if s.ModelNames["r/new"] != "Mine" || s.ModelNames["r/old"] != "Old" { + t.Errorf("names %v", s.ModelNames) + } + if s.ModelOutputs["r/new"] != 8000 || len(s.ModelOutputs) != 1 { + t.Errorf("outputs %v", s.ModelOutputs) + } + if s.ModelIDs["r/old"] != "x" { + t.Errorf("ids %v", s.ModelIDs) + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index df20961b4..6dcee4916 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -10,6 +10,7 @@ package settings import ( "bytes" "encoding/json" + "errors" "fmt" "maps" "math" @@ -852,6 +853,17 @@ type Settings struct { // the routing groups, the usage records and what a call is priced at — // keeps the name magpie knows the model by. ModelWires map[string]string `json:"modelWires,omitempty"` + // ModelIDs are the ids the user lists a provider's models by, from + // "/" to the id the provider + // itself serves it under (zeewell on X: deepseek-v4.1-flash-1017 known + // as deepseek-v4.1-flash). The model is listed, picked, grouped, found + // in routing groups, limited by gateway keys and recorded in usage by + // that id, and a request for it goes out under the provider's own, as + // a ModelWires name does (Wires). Keyed by the id it is known by, so one + // id of a provider is one of its models; a model of the provider's own + // with that id is not listed while another goes by it. Absent leaves + // each model to the provider's id (provider.SetModelID). + ModelIDs map[string]string `json:"modelIDs,omitempty"` // ModelAPIs is the one API a model is asked on at its provider, by // "/": chat, responses or anthropic, for a relay // whose one key serves some models on one and others on another @@ -1279,6 +1291,70 @@ func (s *Settings) KeepOwn(cur Settings) { s.RequestArchiveLocal, s.RequestArchiveLocalMB = cur.RequestArchiveLocal, cur.RequestArchiveLocalMB } +// Wires is ModelWires with the provider's own id of each model the user +// lists by another (ModelIDs): what a request for "/" goes out +// under. A name the user gave the model itself in ModelWires is kept, and a +// provider's "*" name is the provider's own id in its "*". With no ModelIDs +// it is ModelWires itself; else it is made again only when either map holds +// something else than the last time. It is read, never written to. +func (s Settings) Wires() map[string]string { + if len(s.ModelIDs) == 0 { + return s.ModelWires + } + wiresMemo.Lock() + defer wiresMemo.Unlock() + if wiresMemo.out != nil && maps.Equal(wiresMemo.ids, s.ModelIDs) && maps.Equal(wiresMemo.wires, s.ModelWires) { + return wiresMemo.out + } + out := make(map[string]string, len(s.ModelWires)+len(s.ModelIDs)) + maps.Copy(out, s.ModelWires) + for k, own := range s.ModelIDs { + pid, _, ok := strings.Cut(k, "/") + own = strings.TrimSpace(own) + if !ok || own == "" || strings.TrimSpace(s.ModelWires[k]) != "" { + continue + } + if all := strings.TrimSpace(s.ModelWires[pid+"/*"]); all != "" { + own = strings.ReplaceAll(all, "*", own) + } + out[k] = own + } + wiresMemo.ids, wiresMemo.wires, wiresMemo.out = maps.Clone(s.ModelIDs), maps.Clone(s.ModelWires), out + return out +} + +// wiresMemo is the Wires last made, and copies of the two maps it was +// made of: compared by what they hold, as a caller may change its own +// settings' maps in place. +var wiresMemo struct { + sync.Mutex + ids, wires, out map[string]string +} + +// MoveModel moves what the user said of the model keyed from +// ("/") to the key to, in every per-model map but +// ModelIDs, and says whether anything moved. A map with something under +// to already keeps it, and what from had there stays where it was: what +// the user said of the model now keyed to is theirs and is not written +// over. +func (s *Settings) MoveModel(from, to string) bool { + moved := false + PerModelKeys(s, func(name string, m reflect.Value) { + if name == "ModelIDs" || m.IsNil() { + return + } + fk, tk := reflect.ValueOf(from).Convert(m.Type().Key()), reflect.ValueOf(to).Convert(m.Type().Key()) + v := m.MapIndex(fk) + if !v.IsValid() || m.MapIndex(tk).IsValid() { + return + } + m.SetMapIndex(fk, reflect.Value{}) + m.SetMapIndex(tk, v) + moved = true + }) + return moved +} + // RenamePerModel moves what the user said of a provider's models to the id // it has now: in every per-model map (see ModelNames) each key beginning // with from+"/" is rewritten to to+"/", and it says whether any key moved at @@ -1393,6 +1469,52 @@ func Shared() Settings { return s } +// SharedModelIDs is Shared().ModelIDs, read for each model a list is +// built of: only that field is parsed, once per change of the file, and a +// missing file has none without the defaults Shared builds each time. +// Unreadable or unparsable, it is what Shared says. It is shared: the +// caller must not change it. +func SharedModelIDs() map[string]string { + fileMu.RLock() + ids, err := filememo.Read("settings-model-ids", pathNow(), func(b []byte) (map[string]string, error) { + var s struct { + ModelIDs map[string]string `json:"modelIDs"` + } + err := json.Unmarshal(b, &s) + return s.ModelIDs, err + }) + fileMu.RUnlock() + if err == nil { + return ids + } + if errors.Is(err, os.ErrNotExist) { + return nil + } + return Shared().ModelIDs +} + +// pathNow is Path, built again only when what it is built from changed: +// SharedModelIDs is read several times for each list, and Path's joins +// were most of what building one allocated. +func pathNow() string { + k := pathFrom{appdir.Portable(), os.Getenv("XDG_CONFIG_HOME"), os.Getenv("HOME"), os.Getenv("USERPROFILE")} + if m := lastPath.Load(); m != nil && m.from == k { + return m.path + } + path := Path() + lastPath.Store(&pathMemo{k, path}) + return path +} + +type pathFrom struct{ portable, xdg, home, profile string } + +type pathMemo struct { + from pathFrom + path string +} + +var lastPath atomic.Pointer[pathMemo] + // sharedFor is the shared Settings parse keeps for contents b, when it // keeps them. func sharedFor(b []byte) (Settings, bool) { diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index aa1d1dbaa..e7977050a 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -428,7 +428,7 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi // the upstream names in force now, read once for the lot: a row is // judged by the names standing today, which is what Ledger says, and // the rows here are what a reader compares a bill against - wires := settings.Load().ModelWires + wires := settings.Load().Wires() priceOf := Pricer() codexIdentities := sessions.CodexIdentities() rows = make([]Row, 0, len(recs)+len(logs)) diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 413e86d8c..3f0e1a53a 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -750,7 +750,7 @@ func readRequestState(now time.Time) requestState { renamed := provider.UsageRenames().Key() cfg := settings.Load() prices, _ := json.Marshal(cfg.ModelPrices) - wires, _ := json.Marshal(cfg.ModelWires) + wires, _ := json.Marshal(cfg.Wires()) meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), statKey(catalog.CachePath()), clientAgentsKey(), clearedKey()) h := sha256.New() for _, current := range provider.All() { @@ -1056,7 +1056,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now, settle return func(r Record, source string) Row { sent := r.Model if source == "" { - sent = provider.SentNameIn(cfg.ModelWires, r.priceID(), r.Model, r.Effort) + sent = provider.SentNameIn(cfg.Wires(), r.priceID(), r.Model, r.Effort) } row := Row{Record: r, Source: source, Routed: GroupRouted(sent, r.Served)} if r.Served != "" { @@ -1088,7 +1088,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now, settle // cache budget every query priced the whole history again. var gateways []*rowChunk renames := provider.UsageRenames() - priced := newBlockPricer(renames, cfg.ModelWires, price) + priced := newBlockPricer(renames, cfg.Wires(), price) meta := sha256.Sum256([]byte(st.root + "|" + st.meta)) priced.share(meta) for _, packed := range snapshot.blocks { diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index a9f7de9e7..350e87264 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -171,6 +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 のままです。
diff --git a/site/public/docs/start.html b/site/public/docs/start.html index 7f3d35aa5..3956ce94f 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -171,6 +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.
ルーティング先に使われるもの
スマート 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 6bf5d28a9..e8035e0aa 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -171,6 +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。
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 账号排第一;同时重置的账号(免费账号都在月底)再看剩余积分哪个先过期。失败后在休息的排最后。