diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 368553a95..b55b9160f 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -30,7 +30,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | WSL under NAT | On Windows, while the gateway listens on loopback alone, `serveWSL` also serves it, in plain HTTP, at each address Windows has on a WSL network (`WSLNets`: the `vEthernet (WSL…)` adapters, looked for every 10s, since WSL's VM brings its adapter up and down). That is where a distro in NAT networking reaches Windows, and what `place` writes into its agents (zaidu259434 on X: Codex in WSL failed with sharing off). A distro in bridged networking is a peer on the LAN, and its default route is the LAN's router, not Windows: `wslrun.HostAt` takes Windows' address on the bridge's adapter (`vEthernet (WSL_Bridge_Switch)`), the one whose network holds that route (ecalpal_ on Discord). `lanGuard` takes a request there as this computer's (`fromWSL`) only when it arrives at that address, from inside that network, with the WSL key: `WSLKey`, a `wsl-` secret in magpie's folder (`wsl-key`, 0600), optionally followed by `-`. It becomes a loopback request carrying `magpie` or `magpie-` (`asFromLoopback`). Anything else there, a Docker Desktop container on the same network included, is judged as another machine's. Windows' firewall still decides whether WSL gets in: WSL's network is a Public one. | [`wsl.go`](../../internal/gateway/wsl.go) | | TLS | `--tls-cert`/`--tls-key` (`MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY`) make `ListenAndServe`, `Relisten` (both through `Server.listen`) and `magpie web`'s page (`ServeTLS`) wrap the listener in `tlsListener`. A connection from another computer is `tls.Server` at once, so its plain HTTP gets net/http's 400. One from this computer (`fromThisComputer`: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (`sniffWait`), and 0x16 makes it TLS, so `URL()`, the agents, MCP servers, `ServedBy` and the healthcheck keep `http://127.0.0.1`. `certFiles.get` reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). `tlsConfig` refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). `Scheme()` gives the scheme of `LANURLs`, a scheme-less `MAGPIE_PUBLIC_URL` and the page's network links. Host and Origin checks (`foreignPage`, `rebound`) don't depend on the scheme. | [`tls.go`](../../internal/gateway/tls.go), [`lan.go`](../../internal/gateway/lan.go) | | 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`, in the mode its `settings.external_web_access` says (#5018; a ChatGPT account then searches by the same backend search, see [Which providers search for another model](#which-providers-search-for-another-model)), 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. A browser sends a preflight without credentials, so a listed origin's preflight from another computer is let past `lanGuard`'s key check to be answered here (#4931, ggbdpq: a page on another machine got 401 to its preflight and never sent the keyed request); `lanGuard` hands on only an `OPTIONS` with `Access-Control-Request-Method` whose origin is listed (`corsAllowed`). Any other origin's preflight still meets the key check: `corsGuard` passes some unlisted origins on (loopback names, the request's own origin, other schemes), and Codex's backend relay would serve their `OPTIONS` on the user's sign-in (`TestCORSPreflightFromLANReachesNothing`). 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) | +| 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 the asking agent's own subscription in magpie serves (a provider whose `Account.Agent` is the agent: Codex's ChatGPT accounts for Codex, Claude's for Claude Code) goes to that subscription first, found groups on or off (`ownFirst`, `provider.OwnRoute`; freefcw on X: Codex's bare `gpt-6-astra` went to Devin through `auto-gpt-6-astra`, whose soonest-renewing member came first, and with found groups off to the first provider in the order). Not for a group the user made or changed by that name, a found group magpie set one of the agent's fields to (`SetToGroup`, `agent.SetToGroup` over the agent's applied record, #750's bare spelling included), a gateway key held to some models, or a client magpie doesn't know as an agent; an auto stand-in and `agent.Reseat` prefer the agent's own subscription the same way (`AutoStandInFor`, `sameModel`). Otherwise a bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api): 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, an agent with a subscription of its own in magpie is refused it with a 400 naming the providers' ids and `magpie group auto on` (`provider.OffSpread`, `offSpreadRefused`): off, magpie picks no vendor for it. Any other client still gets the first provider in the Providers order that exposes it (`Resolve`), 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 (a signed-in account's and a plugin's too; settings' `ModelIDs`, `magpie model id `, the editor's "Listed as"; [Providers and accounts](providers-accounts.md#runtime-path)) is that id everywhere the gateway names it: `/v1/models` and the lists written into agents (`Available`), `Resolve`, the routing groups and the group magpie finds for it (`auto/`, with every other provider serving that id), a gateway key's models, `X-Magpie-Model` and the usage log's `model`. Only the upstream request differs: every place that sends a wire name reads `settings.Wires()`, which is `ModelWires` with each `ModelIDs` entry turned round (`"/"` → the vendor's own id, wrapped by a `/*` wire), so the body, a Vertex path and the usage log's endpoint carry the vendor's id; an explicit `ModelWires` entry for that id wins. The vendor's reply names its own id, which the usage log, recent calls and the Routing page keep as `served`; the agent gets the id it asked for back in the reply, in every protocol, streamed or whole (`memberWriter` in [`member.go`](../../internal/gateway/member.go), `replyNamingOf`: the reply's `model`, Responses' `response.model`, Anthropic's `message.model`, Gemini's `modelVersion`; issennknight on Discord, whose agent warned that `deepseek-v4.1-flash` came back as `deepseek-v4.1-flash-1017`). The same holds for a group or a `provider/model` id the vendor knows by another name. A reply whose vendor sent the wire name as asked keeps the vendor's name (a dated `-20261017` included). Settings' `replyModel` (Settings › Models › Replies › Model name in replies) picks for every request: `""` the model asked for, `member` the group's member, `vendor` the vendor's own name, as before the asked-for name, each for every agent, Claude Code, Claude Desktop and Codex included (ZoeCats on Discord: in v0.1.2760 `member` still gave those three the model asked for; `TestPluginReplyNamesMember` holds it on a plugin too). A file from before it with `memberModel` on reads as `member`, and `memberModel` is written beside `replyModel` for an older magpie (`normal` in settings.go; `Merge` in settingsapi takes an older page's `memberModel` only when its switch moved). A request's `X-Magpie-Response-Model` (`asked`, `member` or `vendor`) overrides the setting for that request, for every agent (`TestReplyNamesAskedModel`, `TestGeminiReplyNamesAskedModel`, `TestReplyNamesMember`, `TestReplyModelFoldsMemberModel`, `TestReplyModelSaves`). A request still naming `provider/` (an agent's file magpie didn't rewrite) resolves and goes out as it is. A key held to either id passes for both (`modelAllowed` checks the ref, then `OwnModelID`, then `ListedModelID`); a group member passes the same way. An id is given to a model of the provider's chat list or its picks; the image, video and embeddings routes send no wire name, so they are not served under one (`TestLocalModelIDOnEveryRoute`). At an account or a plugin the account's own say of the model is read by the vendor's id: a plugin's API and fetch, Claude Code's `--model`, Antigravity's variant, and which accounts list it and at what levels (`TestLocalModelIDAtAPlugin`, `TestLocalModelIDAtAClaudeAccount`, `TestLocalModelIDAtAnAntigravityAccount`). | [`internal/provider/localid.go`](../../internal/provider/localid.go), [`internal/settings/settings.go`](../../internal/settings/settings.go), [`key_models.go`](../../internal/gateway/key_models.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). A fallback the user unchecked in its own provider's model list is skipped, as a group's member is (`provider.ResolveRoute`, #3911; `fallback_unpicked_test.go`), and so is it where fallbacks are read for careful accounts, native compaction, redaction and Codex's own turns. A fallback can be a routing group (`group/`, 01huadalang on Discord): `planPaused` hands its members to `planLevel` as a request to the group would (`planFallbackGroup`), in the group's own routing and sink, its pause rules applied in `serve`, and its trace rows marked `Fallback` with the group in `Via`. Its turn rules (`ruleFor`, which may ask a classifier) are not applied: the plan is made before the primary is tried, and a classifier call on every request the primary answers costs too much. Each provider/model is tried once a round: a member that is the primary, an earlier fallback or another fallback group's is left out where it came second, so a group holding this provider is no loop (groups have no fallbacks of their own, and a member's are not followed). A group that is gone is passed over. Every place that reads fallbacks (careful accounts, native compaction, redaction, Codex's own turns, Claude's review) reads a group's members through `provider.FallbackModels`. `fallback_group_test.go`. `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576); one left on the default (Smart) in a group that pools (Smart, In turn, Least used, Use before expiry, 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) | @@ -2518,7 +2518,11 @@ the row of the entry that id reaches, with its label, under the bare id. as `GroupFor`) gives the group's row; else `resolveIn` (as `Resolve`) gives the first provider in the Providers order that serves it. So a model several providers serve is listed once, and answered by its group with - found groups on, else by the first provider, as before. + found groups on, else by the first provider, as before. The list is not + per agent: an agent whose own subscription serves the id is answered + there (`ownFirst`, see Model resolution), and with found groups off an + agent with a subscription of its own is refused an id several other + providers serve (`provider.OffSpread`). - An id already in the catalog as is (a group's or a provider's own id) is not listed twice. Group rows themselves add nothing. - The target must be in the list shown: a gateway key held to some models diff --git a/internal/agent/applied.go b/internal/agent/applied.go index 0b8fad061..401fe791c 100644 --- a/internal/agent/applied.go +++ b/internal/agent/applied.go @@ -1069,3 +1069,26 @@ func whatsOff(name, file, k, v, want string) string { return where + " was changed, so magpie's gateway won't take its requests" } } + +// SetToGroup reports whether magpie set one of the agent's fields to the +// routing group gid ("group/"), by its id or its model's name (#750), +// at an effort or not: the user picked that group for the agent. The +// gateway then keeps a bare name the agent asks for by on the group, +// rather than on the agent's own subscription. For gateway.SetToGroup. +func SetToGroup(agent, gid string) bool { + if agent == "" || gid == "" { + return false + } + gid = provider.CanonicalRef(gid) + for _, v := range appliedOf(agent).Fields { + if g := groupNamed(v); g != "" && provider.CanonicalRef(g) == gid { + return true + } + if i := strings.LastIndex(v, ":"); i > 0 && slices.Contains(provider.MemberEfforts, strings.ToLower(v[i+1:])) { + if g := groupNamed(v[:i]); g != "" && provider.CanonicalRef(g) == gid { + return true + } + } + } + return false +} diff --git a/internal/agent/reseat.go b/internal/agent/reseat.go index 5bf7f020e..ab09c6140 100644 --- a/internal/agent/reseat.go +++ b/internal/agent/reseat.go @@ -103,7 +103,7 @@ func Reseat(change func() error) ([]Move, error) { } var to Option if f.Options != nil { - to = sameModel(f.Options(vals), p.ref) + to = sameModel(f.Options(vals), p.ref, p.a.ID) } m := Move{Agent: p.a.Name, Field: f.Label, From: p.ref, To: to.Ref} // the same model elsewhere keeps the agent's suffix after it (omp's @@ -148,9 +148,10 @@ func served(ref string) bool { // (claude-sonnet-4.5 and claude-sonnet-4-5-20250929). For a group magpie // found (group/auto-…), gone as found groups are turned off, a provider // is kept out of them, or its model is down to one provider magpie has, it -// is that model from the first provider still serving it; none for any other routing group, which is -// nobody else's. -func sameModel(opts []Option, ref string) Option { +// is that model from the agent's own subscription when it serves it (agent +// is the agent's id; freefcw on X), else from the first provider still +// serving it; none for any other routing group, which is nobody else's. +func sameModel(opts []Option, ref, agent string) Option { // a group's id carries Claude Code's [1m] mark as a model's does, and // this ref comes from the agent's own settings if gid, ok := provider.GroupIDOf(ref); ok { @@ -160,7 +161,7 @@ func sameModel(opts []Option, ref string) Option { // a provider the user keeps out of found groups last // (provider.SetAutoGroupSkip): skipping it is what took the group skip := provider.AutoGroupSkip() - var kept Option + var first, kept Option for _, o := range opts { if o.Ref == "" || provider.IsGroupRef(o.Ref) || !served(o.Ref) { continue @@ -169,13 +170,19 @@ func sameModel(opts []Option, ref string) Option { if provider.AutoGroupOf(pid, m) != gid { continue } - if !slices.Contains(skip, pid) { + if provider.IsOwn(pid, agent) { return o } + if first.Ref == "" && !slices.Contains(skip, pid) { + first = o + } if kept.Ref == "" { kept = o } } + if first.Ref != "" { + return first + } return kept } pid, model, ok := strings.Cut(ref, "/") diff --git a/internal/agent/reseat_test.go b/internal/agent/reseat_test.go index 10d849431..b48ed3e4e 100644 --- a/internal/agent/reseat_test.go +++ b/internal/agent/reseat_test.go @@ -45,15 +45,15 @@ func TestSameModelTakesTheOneMMarkOffAGroupRef(t *testing.T) { } } opts := []Option{{Value: "magpie/group/auto-gpt-5", Ref: "group/auto-gpt-5"}, {Value: "other/gpt-5", Ref: "other/gpt-5"}} - if got := sameModel(opts, "group/auto-gpt-5[1m]"); got.Ref != "other/gpt-5" { + if got := sameModel(opts, "group/auto-gpt-5[1m]", ""); got.Ref != "other/gpt-5" { t.Errorf("[1m] on the group: %+v", got) } - if got := sameModel(opts, "group/auto-gpt-5"); got.Ref != "other/gpt-5" { + if got := sameModel(opts, "group/auto-gpt-5", ""); got.Ref != "other/gpt-5" { t.Errorf("the bare group: %+v", got) } // a group that is nobody else's still gives nothing (nothing to move to) none := []Option{{Value: "magpie/group/mine", Ref: "group/mine"}, {Value: "other/gpt-5", Ref: "other/gpt-5"}} - if got := sameModel(none, "group/mine[1m]"); got.Ref != "" { + if got := sameModel(none, "group/mine[1m]", ""); got.Ref != "" { t.Errorf("a group of the user's own: %+v", got) } } diff --git a/internal/cli/main.go b/internal/cli/main.go index 14ba5bbe5..4da135c28 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -418,6 +418,9 @@ func run(args []string) error { // a model Claude Code names that magpie doesn't serve goes to the one // it is set to use for that tier gateway.StandIn = agent.StandIn + // a bare name an agent asks for goes to its own subscription, unless + // magpie set the agent to the group magpie found by that name + gateway.SetToGroup = agent.SetToGroup // and its auto mode classifier, on a sonnet tier that follows a main // model /model has moved, to the model it moved to gateway.ClassifierStandIn = agent.ClassifierStandIn diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 5245b54db..9e4ba8b1e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -128,6 +128,39 @@ func startedByAgent(r *http.Request, agent string) bool { // "" leaves the model as asked. Set by main. var StandIn func(agent, model string) string +// SetToGroup reports whether magpie set one of agent's fields to the +// routing group gid ("group/"): the user picked that found group for +// the agent, so a bare model's name it asks for by (#750) stays on the +// group rather than going to the agent's own subscription (ownFirst). Set +// by main; nil reads as no. +var SetToGroup func(agent, gid string) bool + +// ownFirst is where a bare model's id agent asks for goes when the agent's +// own subscription in magpie serves it (provider.OwnRoute; freefcw on X: +// Codex's gpt-6-astra went to Devin through the group magpie found, and +// with found groups off to the first provider in the order). ok is false +// for a key held to some models, whose own rules pick, and for a found +// group magpie set the agent to. +func ownFirst(r *http.Request, agent, m string) (string, bool) { + if _, held := keyHolds(r); held { + return "", false + } + to, group, ok := provider.OwnRoute(agent, m) + if !ok { + return "", false + } + if group != "" && SetToGroup != nil && SetToGroup(agent, group) { + return "", false + } + return to, true +} + +// offSpreadRefused is the error for a bare model's id several providers +// serve, none the agent's own, while found groups are off (provider.OffSpread). +func offSpreadRefused(model string, ids []string) string { + return fmt.Sprintf("%q is served by %s in Magpie and auto groups are off, so Magpie picks none of them: ask for one by its provider/model id, or turn auto groups on (magpie group auto on)", model, strings.Join(ids, ", ")) +} + // wiresKey carries the upstream names in force on a request's context: read // once where the request comes in rather than once per place a name is // looked up, since settings.Load reads and parses the whole file every call @@ -1840,7 +1873,9 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) { } model, _ = askedAt(model) // counted as the model, whatever its effort id := unprefixed(model) - if sid, ok := provider.AutoStandIn(id); ok { + if own, ok := ownFirst(r, agentOf(r), id); ok { + id = own // counted where serve sends it + } else if sid, ok := provider.AutoStandInFor(agentOf(r), id); ok { id = sid } pick := desktopSubagentPick(r, agentOf(r), named, id, body) @@ -2409,10 +2444,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // spelling of a group's model (#750) — is that group, as asked for or // as an agent's config names its stand-in grouped := func(m string) string { + if id, ok := ownFirst(r, agent, m); ok { + // a bare name the agent's own subscription serves: there, + // before a group magpie found or another vendor + return id + } if id, ok := keyGroupFor(r, m); ok { return id } - if id, ok := provider.AutoStandIn(m); ok { + if id, ok := provider.AutoStandInFor(agent, m); ok { // a group magpie found, while the user has those off: its // model from one provider, rather than refused return id @@ -2467,6 +2507,16 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } // any Claude Code subagent's turn, moved or not, for the Routing page's tag subagentID := subagentTurnOf(r, call.Kind, body, desktopPick != nil || subagentEffort != "") + if _, held := keyHolds(r); !held { + // auto groups off: a bare name several vendors serve, none the + // agent's own, goes to none of them (freefcw on X) + if ids := provider.OffSpread(agent, asked); len(ids) > 0 { + call.Status, call.Error = 400, "model on several providers" + writeError(w, from, 400, offSpreadRefused(call.Model, ids)) + turnedAway() + return + } + } p, model, ok := provider.Resolve(asked) // a model the user disabled (#1867) — asked by its id, the model a // sub-agent was put on, a group with every model in it disabled — is diff --git a/internal/gateway/ownfirst_test.go b/internal/gateway/ownfirst_test.go new file mode 100644 index 000000000..08c4d3732 --- /dev/null +++ b/internal/gateway/ownfirst_test.go @@ -0,0 +1,130 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// ownFirstHome: Codex signed in to ChatGPT, whose backend serves +// gpt-6-luna (tierAccounts), and a relay first in the Providers order that +// serves gpt-6-luna too, and glm-6 with a second relay. It returns the +// requests each relay answered. +func ownFirstHome(t *testing.T) (codexTried func() []string, relayHits func() int64) { + t.Helper() + tried := tierAccounts(t, nil, nil) + var hits atomic.Int64 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + hits.Add(1) + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r2","model":"gpt-6-luna"}}`, + `data: {"type":"response.output_text.delta","delta":"relay"}`, + `data: {"type":"response.completed","response":{"id":"r2","usage":{"input_tokens":7,"output_tokens":1}}}`)) + })) + t.Cleanup(up.Close) + for _, p := range []provider.Provider{ + {ID: "relay", Name: "Relay", Key: "k", Responses: up.URL + "/v1", Models: []string{"gpt-6-luna", "glm-6"}}, + {ID: "relay2", Name: "Relay 2", Key: "k", Responses: up.URL + "/v1", Models: []string{"glm-6"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + if err := provider.SetOrder([]string{"relay", "relay2"}); err != nil { + t.Fatal(err) + } + return tried, func() int64 { return hits.Swap(0) } +} + +func postCodex(s *Server, model string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"`+model+`","stream":true,"input":"ping"}`)) + req.Header.Set("Authorization", "Bearer "+TokenFor("codex")) + s.Handler().ServeHTTP(rec, req) + return rec +} + +// freefcw on X: Codex asked for gpt-6-astra by its bare name, which its +// own ChatGPT subscription serves, and magpie sent it to Devin, through +// the group it found (on) or as the first provider in the order (off). A +// bare name Codex's own subscription serves now goes there, found groups +// on or off. +func TestBareNameGoesToTheAgentsOwnSubscription(t *testing.T) { + codexTried, relayHits := ownFirstHome(t) + s := New() + for _, on := range []bool{true, false} { + if err := provider.SetAutoGroups(on); err != nil { + t.Fatal(err) + } + for i := 0; i < 3; i++ { + rec := postCodex(s, "gpt-6-luna") + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") { + t.Fatalf("groups on %v: %d %s", on, rec.Code, rec.Body) + } + if n := relayHits(); n != 0 { + t.Fatalf("groups on %v: the relay was asked %d times", on, n) + } + if len(codexTried()) == 0 { + t.Fatalf("groups on %v: Codex's own account never asked", on) + } + } + } +} + +// Off means off: a bare name two other vendors serve, none of them Codex's +// own subscription, is refused for Codex with what to ask for instead, +// rather than sent to the first of them. Named by its provider, it goes. +func TestBareNameOnSeveralVendorsRefusedWhileGroupsOff(t *testing.T) { + _, relayHits := ownFirstHome(t) + s := New() + if err := provider.SetAutoGroups(false); err != nil { + t.Fatal(err) + } + rec := postCodex(s, "glm-6") + if rec.Code != 400 || !strings.Contains(rec.Body.String(), "relay/glm-6") || !strings.Contains(rec.Body.String(), "magpie group auto on") { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if n := relayHits(); n != 0 { + t.Fatalf("sent anyway, %d times", n) + } + if rec := postCodex(s, "relay2/glm-6"); rec.Code != 200 || relayHits() != 1 { + t.Fatalf("named: %d %s", rec.Code, rec.Body) + } + // on, the found group has it + if err := provider.SetAutoGroups(true); err != nil { + t.Fatal(err) + } + if rec := postCodex(s, "glm-6"); rec.Code != 200 || relayHits() != 1 { + t.Fatalf("on: %d %s", rec.Code, rec.Body) + } +} + +// A found group magpie set the agent to (SetToGroup), which Codex asks +// for by its model's bare name (#750), stays the group's. +func TestBareNameOfAGroupSetOnTheAgentStaysTheGroups(t *testing.T) { + ownFirstHome(t) + old := SetToGroup + t.Cleanup(func() { SetToGroup = old }) + var asked []string + SetToGroup = func(agent, gid string) bool { + asked = append(asked, agent+" "+gid) + return gid == "group/auto-gpt-6-luna" + } + r := httptest.NewRequest("POST", "/v1/responses", nil) + if to, ok := ownFirst(r, "codex", "gpt-6-luna"); ok { + t.Fatalf("set to the group, sent to %s", to) + } + if len(asked) != 1 || asked[0] != "codex group/auto-gpt-6-luna" { + t.Fatalf("asked %v", asked) + } + SetToGroup = func(string, string) bool { return false } + if to, ok := ownFirst(r, "codex", "gpt-6-luna"); !ok || to != "codex/gpt-6-luna" { + t.Fatalf("not set to it: %q %v", to, ok) + } +} diff --git a/internal/provider/group.go b/internal/provider/group.go index d07d268b3..674cdbeca 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -791,7 +791,13 @@ func mergeKey(pid, model string, same map[string]string) string { // provider. ok is false for any other id, a group the user has of that id, // one they removed, and while found groups are on, one there is or that // isn't gone for a provider kept out. -func AutoStandIn(id string) (string, bool) { +func AutoStandIn(id string) (string, bool) { return AutoStandInFor("", id) } + +// AutoStandInFor is AutoStandIn for a request of agent's: the agent's own +// subscription first when it serves the model (freefcw on X: off, Codex's +// gpt-6-astra went to Devin, the first provider in the order), then the +// first provider as AutoStandIn picks. +func AutoStandInFor(agent, id string) (string, bool) { gid, ok := GroupIDOf(id) if !ok || !strings.HasPrefix(gid, "auto-") { return "", false @@ -810,18 +816,24 @@ func AutoStandIn(id string) (string, bool) { return "", false } } - var first string + var first, kept string for _, e := range entries { if AutoGroupOf(e.Provider.ID, e.Model) != gid { continue } - if !slices.Contains(f.AutoGroupSkip, e.Provider.ID) { + if ownAgent(e.Provider, agent) { return e.ID, true } + if kept == "" && !slices.Contains(f.AutoGroupSkip, e.Provider.ID) { + kept = e.ID + } if first == "" { first = e.ID } } + if kept != "" { + return kept, true + } return first, first != "" } diff --git a/internal/provider/ownroute.go b/internal/provider/ownroute.go new file mode 100644 index 000000000..f2cebdc8a --- /dev/null +++ b/internal/provider/ownroute.go @@ -0,0 +1,162 @@ +package provider + +import ( + "slices" + "strings" +) + +// An agent's own subscription first (freefcw on X): Codex, signed in to +// ChatGPT and started by another app (Mirasim), asked for gpt-6-astra by +// its bare name. Devin and Cursor served it too, so the name was the group +// magpie found of it (auto-gpt-6-astra), which put the subscription that +// renews soonest first: Devin. With found groups off the name went to the +// first provider in the Providers order that served it, Devin again when +// it was added first. +// +// A bare model's id an agent asks for, which that agent's own subscription +// in magpie serves (a provider whose Account.Agent is the agent: Codex's +// ChatGPT accounts for Codex, Claude's for Claude Code), now goes to that +// subscription, found groups on or off. What stays as it was: +// - a group the user made, or a found one they changed (no longer Auto), +// named by the bare id: theirs, routed as they set it; +// - a found group magpie set one of the agent's fields to (the gateway's +// SetToGroup asks the agent's record): the user picked it for the agent; +// - an id with a provider in it, or a group's ref (auto/, +// group/): already where the user said; +// - an agent with no subscription of its own in magpie, or one that +// doesn't serve the model. +// +// With found groups off, a bare id several providers serve, none of them +// the asking agent's own subscription, is refused for an agent that has +// one in magpie (OffSpread): off, magpie picks no vendor for it. + +// ownAgent is whether a provider is agent's own subscription: one of +// the agent's sign-ins that magpie serves. Plugins sign in as "plugin", +// never an agent's id. +func ownAgent(p Provider, agent string) bool { + return agent != "" && agent != "plugin" && p.Account != nil && p.Account.Agent == agent +} + +// IsOwn reports whether the provider pid is agent's own subscription. +func IsOwn(pid, agent string) bool { + if agent == "" || agent == "plugin" { + return false + } + p, err := findIn(sharedAll(), pid) + return err == nil && ownAgent(*p, agent) +} + +// bareModelID is id without Claude Code's [1m] mark, and whether it is a model's +// id with no provider in it and no group's ref. +func bareModelID(id string) (string, bool) { + id = strings.TrimSuffix(strings.TrimSpace(id), "[1m]") + if id == "" || strings.Contains(id, "/") || IsGroupRef(id) { + return id, false + } + return id, true +} + +// OwnRoute is where a bare model's id agent asks for goes on the agent's +// own subscription: its "provider/model". group is the found group's ref +// ("group/auto-…") the id named, which the request now goes past, "" when +// it named none (found groups off, or the group removed). ok is false when +// the id isn't bare, the user has a group of their own by it, or no +// subscription of the agent's serves it. +func OwnRoute(agent, id string) (to, group string, ok bool) { + if agent == "" || agent == "plugin" { + return "", "", false + } + if _, bare := bareModelID(id); !bare { + return "", "", false + } + entries := providerEntries() + return ownRouteIn(entries, groupsIn(entries), agent, id) +} + +func ownRouteIn(entries []Entry, all []Group, agent, id string) (to, group string, ok bool) { + id, bare := bareModelID(id) + if !bare { + return "", "", false + } + if gid, found := groupForIn(all, id); found { + g, _ := groupOf(all, strings.TrimPrefix(gid, GroupPrefix)) + if !g.Auto { + return "", "", false // the user's own group: routed as they set it + } + group = gid + } + own := ownEntry(entries, agent, id) + if own == nil { + return "", "", false + } + return own.ID, group, true +} + +// ownEntry is the agent's own subscription's entry for the model id: by +// that id, else by the name vendors agree on (sameModel), as a found group +// merges it. nil for none. +func ownEntry(entries []Entry, agent, id string) *Entry { + var alike *Entry + k := sameModel(id) + for i := range entries { + e := &entries[i] + if e.Group != "" || !ownAgent(e.Provider, agent) { + continue + } + if e.Model == id { + return e + } + if alike == nil && sameModel(e.Model) == k { + alike = e + } + } + return alike +} + +// OffSpread is the providers' ids ("provider/model") serving a bare model +// id that a request of agent's goes to none of, while found groups are +// off: several providers serve it, none of them the agent's own +// subscription, and the agent has one in magpie. Off, magpie picks none of +// them for the agent (freefcw on X); the request names one. nil when found +// groups are on, the id isn't bare or names a group of the user's, one +// provider serves it, or the agent has no subscription of its own here. +func OffSpread(agent, id string) []string { + if agent == "" || agent == "plugin" || AutoGroupsOn() { + return nil + } + if _, bare := bareModelID(id); !bare { + return nil + } + if !slices.ContainsFunc(sharedAll(), func(p Provider) bool { return ownAgent(p, agent) }) { + return nil + } + entries := providerEntries() + return offSpreadIn(entries, groupsIn(entries), heldSettings().ModelSameAs, agent, id) +} + +func offSpreadIn(entries []Entry, all []Group, same map[string]string, agent, id string) []string { + id, _ = bareModelID(id) + if _, found := groupForIn(all, id); found { + return nil + } + if ownEntry(entries, agent, id) != nil { + return nil + } + k := sameModel(id) + var out []string + var seen []string + for _, e := range entries { + if e.Group != "" || mergeKey(e.Provider.ID, e.Model, same) != k && e.Model != id { + continue + } + if slices.Contains(seen, e.Provider.ID) { + continue + } + seen = append(seen, e.Provider.ID) + out = append(out, e.ID) + } + if len(out) < 2 { + return nil + } + return out +} diff --git a/internal/provider/ownroute_test.go b/internal/provider/ownroute_test.go new file mode 100644 index 000000000..326fafed2 --- /dev/null +++ b/internal/provider/ownroute_test.go @@ -0,0 +1,79 @@ +package provider + +import ( + "slices" + "testing" +) + +// ownEntries: Codex's ChatGPT account, Devin's plugin and a relay all +// serve gpt-6-astra (freefcw on X), the relay first in the order; only the +// relay and Devin serve glm-6. +func ownEntries() []Entry { + codex := Provider{ID: "codex", Account: &Account{Agent: "codex", User: "a@example.com"}} + devin := Provider{ID: "devin-plugin", Account: &Account{Agent: "plugin"}} + relay := Provider{ID: "relay"} + e := func(p Provider, m string) Entry { return Entry{ID: p.ID + "/" + m, Model: m, Provider: p} } + return []Entry{ + e(relay, "gpt-6-astra"), e(relay, "glm-6"), + e(devin, "gpt-6-astra"), e(devin, "glm-6"), + e(codex, "gpt-6-astra"), + } +} + +// A bare name the asking agent's own subscription serves goes there, +// whether found groups are on (a group of it found) or off (none), and +// says the found group it went past; a group the user made by that name, +// a provider's id, a group's ref and another agent's request don't. +func TestOwnRoute(t *testing.T) { + entries := ownEntries() + on := autoGroups(entries, nil) + for _, c := range []struct { + name string + groups []Group + agent, id string + to, group string + }{ + {"on", on, "codex", "gpt-6-astra", "codex/gpt-6-astra", "group/auto-gpt-6-astra"}, + {"off", nil, "codex", "gpt-6-astra", "codex/gpt-6-astra", ""}, + {"1m mark", on, "codex", "gpt-6-astra[1m]", "codex/gpt-6-astra", "group/auto-gpt-6-astra"}, + {"another agent", on, "claude", "gpt-6-astra", "", ""}, + {"no agent", on, "", "gpt-6-astra", "", ""}, + {"a plugin", on, "plugin", "gpt-6-astra", "", ""}, + {"not its own", on, "codex", "glm-6", "", ""}, + {"provider named", on, "codex", "relay/gpt-6-astra", "", ""}, + {"group ref", on, "codex", "group/auto-gpt-6-astra", "", ""}, + {"auto ref", on, "codex", "auto/gpt-6-astra", "", ""}, + {"the user's group", []Group{{ID: "gpt-6-astra", Name: "Mine", Members: []string{"relay/gpt-6-astra"}}}, "codex", "gpt-6-astra", "", ""}, + } { + to, group, ok := ownRouteIn(entries, c.groups, c.agent, c.id) + if to != c.to || group != c.group || ok != (c.to != "") { + t.Errorf("%s: %q %q %v, want %q %q", c.name, to, group, ok, c.to, c.group) + } + } + // spelt otherwise by the vendor (sameModel), still its own + dotted := []Entry{{ID: "codex/gpt-6.1-sol", Model: "gpt-6.1-sol", Provider: Provider{ID: "codex", Account: &Account{Agent: "codex"}}}} + if to, _, ok := ownRouteIn(dotted, nil, "codex", "gpt-6-1-sol"); !ok || to != "codex/gpt-6.1-sol" { + t.Errorf("by its vendor's spelling: %q %v", to, ok) + } +} + +// With found groups off, a bare name several providers serve, none of +// them the agent's own, names them all; one the agent's own serves, one +// provider serves, or a group of the user's has, names none. +func TestOffSpread(t *testing.T) { + entries := ownEntries() + if got := offSpreadIn(entries, nil, nil, "codex", "glm-6"); !slices.Equal(got, []string{"relay/glm-6", "devin-plugin/glm-6"}) { + t.Errorf("glm-6: %v", got) + } + if got := offSpreadIn(entries, nil, nil, "codex", "gpt-6-astra"); got != nil { + t.Errorf("its own serves it: %v", got) + } + one := entries[:2] + if got := offSpreadIn(one, nil, nil, "codex", "glm-6"); got != nil { + t.Errorf("one provider: %v", got) + } + mine := []Group{{ID: "glm-6", Name: "Mine", Members: []string{"relay/glm-6"}}} + if got := offSpreadIn(entries, mine, nil, "codex", "glm-6"); got != nil { + t.Errorf("the user's group: %v", got) + } +}