Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: Ollama's /api/chat and /api/generate, for Zed's Ollama provider (super_lalalalala on Discord)
yetone0fe039f14deb
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 6ef978de9..e996608c2 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -28,7 +28,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).| --- | --- | --- || Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-<agent>` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. Claude Science, whose User-Agent is the Anthropic SDK's, is told by its client's `X-Anthropic-Surface: operon` (`isClaudeScience`). It is listed every model as `claude-magpie-<number>` (`scienceModels`; its picker keeps only a `claude-` id whose name isn't a lower-case slug), and a Claude id magpie doesn't serve (its default before a pick, its haiku side tasks) goes to the model its last turn with tools was on, else the first it is listed (`scienceTurn`, kept in `claude-science.model`). | [`gateway.go`](../../internal/gateway/gateway.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; the client then chats on `/v1/chat/completions`, and Ollama's `/api/chat` and `/api/generate` aren't served), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition 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/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 GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. 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://<id>` (Chromium, the id 32 letters a–p), `moz-extension://<uuid>` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://<uuid>` (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/<token>` 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`). 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), [`internal/settings/origins.go`](../../internal/settings/origins.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` and `/mcp/magpie/vision` (magpie's own web search and image recognition 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/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 GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. 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://<id>` (Chromium, the id 32 letters a–p), `moz-extension://<uuid>` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://<uuid>` (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/<token>` 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`). 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, 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), 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-<slug>`), 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. 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/<model>`: 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`, preferring a spelling models.dev lists), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). Its old id `group/auto-<slug>` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/<model>` (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/<model>` by the old id. An agent field magpie set to `group/auto-<slug>` moves to `auto/<model>` on the next `SyncCatalog` (`agent.renameFoundGroups`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/<model>`. 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/<x>` is its model and found groups list as `group/auto-<slug>` (`autoRefsOn`). Hand-made groups stay `group/<id>`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) || Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). 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) |diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex 417bbdef2..0eb45268a 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -642,6 +642,10 @@ func (s *Server) Handler() http.Handler {mux.HandleFunc("GET /api/version", s.ollamaVersion)mux.HandleFunc("GET /api/tags", s.ollamaTags)mux.HandleFunc("POST /api/show", s.ollamaShow)+ // and its chat routes, for a client that chats only through them+ // (Zed's Ollama provider; ollama_chat.go)+ mux.HandleFunc("POST /api/chat", s.ollamaChat(false))+ mux.HandleFunc("POST /api/generate", s.ollamaChat(true))mux.HandleFunc("GET /v1/magpie/quotas", s.quotas)mux.HandleFunc("GET /v1/magpie/usage", s.usageSummary)mux.HandleFunc("GET /v1/magpie/usage/requests", s.usageRequests)diff --git a/internal/gateway/ollama.go b/internal/gateway/ollama.goindex 56fb98a0f..4921eb503 100644--- a/internal/gateway/ollama.go+++ b/internal/gateway/ollama.go@@ -44,6 +44,21 @@ func (s *Server) ollamaTags(w http.ResponseWriter, r *http.Request) {writeJSON(w, 200, map[string]any{"models": models})}+// ollamaName is the model id a request names: the ollama CLI names a+// model with no tag as name:latest, which is the bare id unless a model is+// really called that.+func ollamaName(r *http.Request, id string) string {+ if _, ok := ollamaEntry(r, id); ok {+ return id+ }+ if bare, cut := strings.CutSuffix(id, ":latest"); cut {+ if _, ok := ollamaEntry(r, bare); ok {+ return bare+ }+ }+ return id+}+// ollamaShow is one model as Ollama's /api/show tells it. A client reads// what it takes from capabilities, its window from model_info's// "<general.architecture>.context_length" (VS Code's Copilot takes 32768@@ -69,6 +84,7 @@ func (s *Server) ollamaShow(w http.ResponseWriter, r *http.Request) {ollamaError(w, http.StatusBadRequest, "model is required")return}+ id = ollamaName(r, id)e, ok := ollamaEntry(r, id)if !ok {ollamaError(w, http.StatusNotFound, "model '"+id+"' not found")diff --git a/internal/gateway/ollama_chat.go b/internal/gateway/ollama_chat.gonew file mode 100644index 000000000..b0926920d--- /dev/null+++ b/internal/gateway/ollama_chat.go@@ -0,0 +1,569 @@+package gateway++import (+ "bytes"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"++ "github.com/tidwall/gjson"+ "github.com/yetone/magpie/internal/provider"+)++// Ollama's own chat routes, POST /api/chat and POST /api/generate, for a+// client that chats only through them (Zed's Ollama provider,+// super_lalalalala on Discord; the ollama CLI). Each request is written+// as a Chat Completions one and served by the very handler+// /v1/chat/completions is (s.handle(provider.Chat)), on the request that+// came in, so lanGuard, corsGuard, the caller's key and the models it may+// use, its limits, routing, fallbacks and usage are /v1/chat/completions'+// own. What comes back is said Ollama's way: NDJSON lines, one per part,+// the last "done": true with done_reason and the token counts, or one+// JSON object when the request says "stream": false (Ollama's API,+// docs/api.md at v0.12.6).++// ollamaMessage is a message as Ollama's /api/chat takes and gives one.+type ollamaMessage struct {+ Role string `json:"role"`+ Content string `json:"content"`+ Thinking string `json:"thinking,omitempty"`+ Images []string `json:"images,omitempty"`+ ToolCalls []ollamaToolCall `json:"tool_calls,omitempty"`+ ToolName string `json:"tool_name,omitempty"`+ ToolCallID string `json:"tool_call_id,omitempty"`+}++// ollamaToolCall is a tool call as Ollama says one: its arguments an+// object, not a JSON string. Zed reads id as required.+type ollamaToolCall struct {+ ID string `json:"id,omitempty"`+ Function struct {+ Index int `json:"index"`+ Name string `json:"name"`+ Arguments json.RawMessage `json:"arguments"`+ } `json:"function"`+}++// ollamaRequest is /api/chat's and /api/generate's request: messages for+// the one, prompt, system and images for the other.+type ollamaRequest struct {+ Model string `json:"model"`+ Messages []ollamaMessage `json:"messages"`+ Prompt string `json:"prompt"`+ System string `json:"system"`+ Images []string `json:"images"`+ Tools json.RawMessage `json:"tools"`+ Format json.RawMessage `json:"format"`+ Options map[string]any `json:"options"`+ Stream *bool `json:"stream"`+ Think any `json:"think"`+}++func (s *Server) ollamaChat(generate bool) http.HandlerFunc {+ chat := s.handle(provider.Chat)+ return func(w http.ResponseWriter, r *http.Request) {+ body, ok := s.requestBody(w, r, provider.Chat)+ if !ok {+ return+ }+ var req ollamaRequest+ if err := json.Unmarshal(body, &req); err != nil {+ ollamaError(w, http.StatusBadRequest, "invalid request: "+err.Error())+ return+ }+ req.Model = strings.TrimSpace(req.Model)+ if req.Model == "" {+ ollamaError(w, http.StatusBadRequest, "model is required")+ return+ }+ req.Model = ollamaName(r, req.Model)+ stream := req.Stream == nil || *req.Stream+ if generate && req.Prompt == "" && len(req.Images) == 0 || !generate && len(req.Messages) == 0 {+ // what Ollama answers a request with nothing to say: the+ // model loaded, which a client asks to warm it up+ if _, ok := ollamaEntry(r, req.Model); !ok {+ ollamaError(w, http.StatusNotFound, "model '"+req.Model+"' not found")+ return+ }+ out := map[string]any{"model": req.Model, "created_at": ollamaNow(), "done": true, "done_reason": "load"}+ if generate {+ out["response"] = ""+ } else {+ out["message"] = map[string]any{"role": "assistant", "content": ""}+ }+ if stream {+ w.Header().Set("Content-Type", "application/x-ndjson")+ }+ writeJSON(w, 200, out)+ return+ }+ cbody, err := ollamaChatBody(req, generate, stream)+ if err != nil {+ ollamaError(w, http.StatusBadRequest, err.Error())+ return+ }+ in := r.Clone(r.Context())+ in.Body, in.ContentLength = io.NopCloser(bytes.NewReader(cbody)), int64(len(cbody))+ in.Header.Set("Content-Type", "application/json")+ in.Header.Del("Content-Encoding")+ in.Header.Del("Content-Length")+ // a reply that comes back compressed couldn't be read here+ in.Header.Del("Accept-Encoding")+ ow := &ollamaWriter{w: w, header: http.Header{}, model: req.Model, generate: generate, stream: stream,+ noThinking: req.Think == false, start: time.Now()}+ chat(ow, in)+ ow.finish()+ }+}++// ollamaChatBody is req as a Chat Completions request.+func ollamaChatBody(req ollamaRequest, generate, stream bool) ([]byte, error) {+ var msgs []map[string]any+ if generate {+ if req.System != "" {+ msgs = append(msgs, map[string]any{"role": "system", "content": req.System})+ }+ msgs = append(msgs, map[string]any{"role": "user", "content": ollamaContent(req.Prompt, req.Images)})+ } else {+ var err error+ if msgs, err = ollamaMessages(req.Messages); err != nil {+ return nil, err+ }+ }+ out := map[string]any{"model": req.Model, "messages": msgs, "stream": stream}+ if stream {+ out["stream_options"] = map[string]any{"include_usage": true}+ }+ if !generate && len(req.Tools) > 0 && !bytes.Equal(bytes.TrimSpace(req.Tools), []byte("null")) {+ // Ollama's tools are Chat Completions' own shape+ out["tools"] = req.Tools+ }+ if f := bytes.TrimSpace(req.Format); len(f) > 0 && !bytes.Equal(f, []byte("null")) && !bytes.Equal(f, []byte(`""`)) {+ var name string+ switch {+ case json.Unmarshal(f, &name) == nil && name == "json":+ out["response_format"] = map[string]any{"type": "json_object"}+ case f[0] == '{':+ out["response_format"] = map[string]any{"type": "json_schema", "json_schema": map[string]any{"name": "response", "schema": json.RawMessage(f)}}+ default:+ return nil, fmt.Errorf("invalid format: %s", f)+ }+ }+ // the options a Chat Completions API takes; the rest (num_ctx, top_k,+ // repeat_penalty, …) are the local runner's, and have no place there+ o := req.Options+ for _, k := range []string{"temperature", "top_p", "seed", "presence_penalty", "frequency_penalty"} {+ if v, ok := o[k]; ok && v != nil {+ out[k] = v+ }+ }+ if v, ok := o["stop"]; ok && v != nil {+ out["stop"] = v+ }+ // -1 is no limit and -2 fill the window, which a Chat API says by+ // leaving max_tokens out+ if n, ok := o["num_predict"].(float64); ok && n > 0 {+ out["max_tokens"] = int(n)+ }+ switch t := req.Think.(type) {+ case string:+ if t != "" {+ out["reasoning_effort"] = t+ }+ case nil, bool:+ default:+ return nil, fmt.Errorf("invalid think value: %v", t)+ }+ return json.Marshal(out)+}++// ollamaMessages are Ollama's messages in Chat Completions' shape. A tool+// call gets an id when it has none (Ollama's have none before 0.12.x),+// and a tool's result is matched to its call by the id it names, else by+// the tool's name, else in order.+func ollamaMessages(in []ollamaMessage) ([]map[string]any, error) {+ type call struct{ id, name string }+ var open []call+ out := make([]map[string]any, 0, len(in))+ for i, m := range in {+ role := strings.ToLower(m.Role)+ switch role {+ case "system", "developer":+ out = append(out, map[string]any{"role": role, "content": m.Content})+ case "user":+ out = append(out, map[string]any{"role": "user", "content": ollamaContent(m.Content, m.Images)})+ case "assistant":+ msg := map[string]any{"role": "assistant", "content": m.Content}+ if m.Thinking != "" {+ msg["reasoning_content"] = m.Thinking+ }+ if len(m.ToolCalls) > 0 {+ calls := make([]map[string]any, 0, len(m.ToolCalls))+ open = open[:0]+ for j, tc := range m.ToolCalls {+ id := tc.ID+ if id == "" {+ id = fmt.Sprintf("call_%d_%d", i, j)+ }+ args := string(bytes.TrimSpace(tc.Function.Arguments))+ var str string+ switch {+ case args == "" || args == "null":+ args = "{}"+ case json.Unmarshal(tc.Function.Arguments, &str) == nil:+ // already a JSON string, as a Chat client sends them+ args = str+ }+ calls = append(calls, map[string]any{"id": id, "type": "function",+ "function": map[string]any{"name": tc.Function.Name, "arguments": args}})+ open = append(open, call{id, tc.Function.Name})+ }+ msg["tool_calls"] = calls+ if m.Content == "" {+ msg["content"] = nil+ }+ }+ out = append(out, msg)+ case "tool":+ id := m.ToolCallID+ pick := -1+ for j, c := range open {+ if id != "" && c.id == id || id == "" && m.ToolName != "" && c.name == m.ToolName {+ pick = j+ break+ }+ }+ if pick < 0 && id == "" && len(open) > 0 {+ pick = 0+ }+ if pick >= 0 {+ id = open[pick].id+ open = append(open[:pick], open[pick+1:]...)+ }+ if id == "" {+ return nil, fmt.Errorf("messages[%d]: a tool result with no tool call before it", i)+ }+ out = append(out, map[string]any{"role": "tool", "tool_call_id": id, "content": m.Content})+ if len(m.Images) > 0 {+ // a Chat tool message carries text alone: its images go+ // in a user message after it+ out = append(out, map[string]any{"role": "user", "content": ollamaContent("", m.Images)})+ }+ default:+ return nil, fmt.Errorf("messages[%d]: unknown role %q", i, m.Role)+ }+ }+ return out, nil+}++// ollamaContent is a message's text with its images, which Ollama sends+// as bare base64, as Chat Completions content parts with data URLs.+func ollamaContent(text string, images []string) any {+ if len(images) == 0 {+ return text+ }+ parts := []map[string]any{}+ if text != "" {+ parts = append(parts, map[string]any{"type": "text", "text": text})+ }+ for _, img := range images {+ url := img+ if !strings.HasPrefix(img, "data:") {+ url = "data:" + ollamaImageType(img) + ";base64," + img+ }+ parts = append(parts, map[string]any{"type": "image_url", "image_url": map[string]any{"url": url}})+ }+ return parts+}++// ollamaImageType is the media type of a base64 image, from its first+// bytes.+func ollamaImageType(b64 string) string {+ head := b64+ if len(head) > 64 {+ head = head[:64]+ }+ raw, _ := base64.StdEncoding.DecodeString(head[:len(head)/4*4])+ if t := http.DetectContentType(raw); strings.HasPrefix(t, "image/") {+ return t+ }+ return "image/png"+}++func ollamaNow() string { return time.Now().UTC().Format(time.RFC3339Nano) }++// ollamaWriter takes what the Chat Completions handler writes, a stream of+// chunks or one completion or an error, and writes it to w as Ollama+// would have.+type ollamaWriter struct {+ w http.ResponseWriter+ header http.Header+ model string+ generate bool+ stream bool+ noThinking bool+ start time.Time++ status int+ sse bool+ buf []byte // a partial SSE line, or the whole body when it isn't a stream+ started bool // the reply's own status and first line are written+ done bool++ content, thinking strings.Builder+ calls []*ollamaToolCall+ args []strings.Builder+ finishReason string+ promptTokens int+ outputTokens int+ firstToken time.Time+}++func (o *ollamaWriter) Header() http.Header { return o.header }++func (o *ollamaWriter) Unwrap() http.ResponseWriter { return o.w }++func (o *ollamaWriter) WriteHeader(code int) {+ if o.status != 0 {+ return+ }+ o.status = code+ o.sse = strings.HasPrefix(o.header.Get("Content-Type"), "text/event-stream")+ // what says why it waits or failed (Retry-After, magpie's own marks)+ // reaches the client as it would on /v1+ for k, vs := range o.header {+ if k == "Retry-After" || strings.HasPrefix(k, "X-") {+ o.w.Header()[k] = vs+ }+ }+}++func (o *ollamaWriter) Write(p []byte) (int, error) {+ if o.status == 0 {+ o.WriteHeader(http.StatusOK)+ }+ o.buf = append(o.buf, p...)+ if !o.sse || o.status >= 300 {+ return len(p), nil+ }+ for {+ i := bytes.IndexByte(o.buf, '\n')+ if i < 0 {+ break+ }+ line := strings.TrimRight(string(o.buf[:i]), "\r")+ o.buf = o.buf[i+1:]+ o.sseLine(line)+ }+ return len(p), nil+}++func (o *ollamaWriter) Flush() {+ if f, ok := o.w.(http.Flusher); ok && o.started {+ f.Flush()+ }+}++// sseLine takes one line of a Chat Completions stream.+func (o *ollamaWriter) sseLine(line string) {+ data, ok := strings.CutPrefix(line, "data:")+ if !ok {+ return+ }+ data = strings.TrimSpace(data)+ if data == "" || data == "[DONE]" {+ return+ }+ if e := gjson.Get(data, "error"); e.Exists() {+ msg := e.Get("message").String()+ if msg == "" {+ msg = e.String()+ }+ o.line(map[string]any{"error": msg})+ o.done = true+ return+ }+ o.chunk(gjson.Parse(data))+}++// chunk takes one stream chunk, or a whole completion (its message where+// a chunk has its delta), and writes what it adds when streaming.+func (o *ollamaWriter) chunk(c gjson.Result) {+ if u := c.Get("usage"); u.IsObject() {+ o.promptTokens, o.outputTokens = int(u.Get("prompt_tokens").Int()), int(u.Get("completion_tokens").Int())+ }+ ch := c.Get("choices.0")+ if !ch.Exists() {+ return+ }+ d := ch.Get("delta")+ if !d.Exists() {+ d = ch.Get("message")+ }+ text := d.Get("content").String()+ think := d.Get("reasoning_content").String()+ if think == "" {+ think = d.Get("reasoning").String()+ }+ if o.noThinking {+ think = ""+ }+ for _, tc := range d.Get("tool_calls").Array() {+ i := len(o.calls)+ if idx := tc.Get("index"); idx.Exists() {+ i = int(idx.Int())+ }+ for len(o.calls) <= i {+ o.calls = append(o.calls, &ollamaToolCall{})+ o.args = append(o.args, strings.Builder{})+ }+ if id := tc.Get("id").String(); id != "" {+ o.calls[i].ID = id+ }+ if n := tc.Get("function.name").String(); n != "" {+ o.calls[i].Function.Name = n+ }+ o.args[i].WriteString(tc.Get("function.arguments").String())+ }+ if f := ch.Get("finish_reason").String(); f != "" {+ o.finishReason = f+ }+ if text == "" && think == "" {+ return+ }+ if o.firstToken.IsZero() {+ o.firstToken = time.Now()+ }+ o.content.WriteString(text)+ o.thinking.WriteString(think)+ if o.stream {+ o.line(o.part(text, think, nil, false))+ }+}++// part is one line of Ollama's reply.+func (o *ollamaWriter) part(text, think string, calls []ollamaToolCall, done bool) map[string]any {+ out := map[string]any{"model": o.model, "created_at": ollamaNow(), "done": done}+ if o.generate {+ out["response"] = text+ if think != "" {+ out["thinking"] = think+ }+ } else {+ msg := map[string]any{"role": "assistant", "content": text}+ if think != "" {+ msg["thinking"] = think+ }+ if len(calls) > 0 {+ msg["tool_calls"] = calls+ }+ out["message"] = msg+ }+ if done {+ reason := "stop"+ if o.finishReason == "length" {+ reason = "length"+ }+ end := time.Now()+ first := o.firstToken+ if first.IsZero() {+ first = end+ }+ out["done_reason"] = reason+ out["total_duration"] = end.Sub(o.start).Nanoseconds()+ out["load_duration"] = 0+ out["prompt_eval_count"] = o.promptTokens+ out["prompt_eval_duration"] = first.Sub(o.start).Nanoseconds()+ out["eval_count"] = o.outputTokens+ out["eval_duration"] = end.Sub(first).Nanoseconds()+ }+ return out+}++// toolCalls are the calls the reply made, their arguments as objects.+func (o *ollamaWriter) toolCalls() []ollamaToolCall {+ var out []ollamaToolCall+ for i, c := range o.calls {+ if c.Function.Name == "" {+ continue+ }+ tc := *c+ tc.Function.Index = i+ if tc.ID == "" {+ tc.ID = fmt.Sprintf("call_%d", i)+ }+ args := strings.TrimSpace(o.args[i].String())+ if args == "" || !json.Valid([]byte(args)) {+ if args != "" {+ // what a model wrote that isn't JSON is kept, as a string+ b, _ := json.Marshal(args)+ args = string(b)+ } else {+ args = "{}"+ }+ }+ tc.Function.Arguments = json.RawMessage(args)+ out = append(out, tc)+ }+ return out+}++// line writes one NDJSON line, the reply's status and type first.+func (o *ollamaWriter) line(v any) {+ if !o.started {+ o.started = true+ o.w.Header().Set("Content-Type", "application/x-ndjson")+ o.w.WriteHeader(http.StatusOK)+ }+ b, _ := json.Marshal(v)+ o.w.Write(append(b, '\n'))+ o.Flush()+}++// finish writes the end of the reply, once the Chat handler is done.+func (o *ollamaWriter) finish() {+ if o.status == 0 {+ o.status = http.StatusOK+ }+ if o.status >= 300 {+ msg := gjson.GetBytes(o.buf, "error.message").String()+ if msg == "" {+ msg = gjson.GetBytes(o.buf, "error").String()+ }+ if msg == "" {+ msg = strings.TrimSpace(string(o.buf))+ }+ if msg == "" {+ msg = http.StatusText(o.status)+ }+ if o.started {+ o.line(map[string]any{"error": msg})+ } else {+ ollamaError(o.w, o.status, msg)+ }+ return+ }+ if !o.sse {+ // one completion, as asked with stream false+ o.chunk(gjson.ParseBytes(o.buf))+ o.buf = nil+ } else if len(o.buf) > 0 {+ o.sseLine(strings.TrimRight(string(o.buf), "\r"))+ }+ if o.done {+ return+ }+ calls := o.toolCalls()+ if o.stream {+ if len(calls) > 0 {+ o.line(o.part("", "", calls, false))+ }+ o.line(o.part("", "", nil, true))+ return+ }+ writeJSON(o.w, 200, o.part(o.content.String(), o.thinking.String(), calls, true))+}diff --git a/internal/gateway/ollama_chat_test.go b/internal/gateway/ollama_chat_test.gonew file mode 100644index 000000000..bd3a6791b--- /dev/null+++ b/internal/gateway/ollama_chat_test.go@@ -0,0 +1,248 @@+package gateway++import (+ "bufio"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"++ "github.com/tidwall/gjson"+)++// ollamaUpstream is a Chat Completions provider that keeps each request+// it is sent in *got (when got isn't nil) and answers with reasoning,+// text and a tool call split over chunks, then usage, streamed or whole+// as asked.+func ollamaUpstream(t *testing.T, got *[]string) *httptest.Server {+ t.Helper()+ var mu sync.Mutex+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ b, _ := io.ReadAll(r.Body)+ if got != nil {+ mu.Lock()+ *got = append(*got, string(b))+ mu.Unlock()+ }+ if !gjson.GetBytes(b, "stream").Bool() {+ w.Header().Set("Content-Type", "application/json")+ io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"seer","choices":[{"index":0,"message":{"role":"assistant","content":"whole answer","reasoning_content":"pondered","tool_calls":[{"id":"call_up","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"a.go\"}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":11,"completion_tokens":7}}`)+ return+ }+ w.Header().Set("Content-Type", "text/event-stream")+ for _, c := range []string{+ `{"choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"let me "}}]}`,+ `{"choices":[{"index":0,"delta":{"reasoning_content":"think"}}]}`,+ `{"choices":[{"index":0,"delta":{"content":"Hello"}}]}`,+ `{"choices":[{"index":0,"delta":{"content":", world"}}]}`,+ `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_up","type":"function","function":{"name":"read_file","arguments":"{\"pa"}}]}}]}`,+ `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"th\":\"a.go\"}"}}]}}]}`,+ `{"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`,+ `{"choices":[],"usage":{"prompt_tokens":11,"completion_tokens":7}}`,+ } {+ io.WriteString(w, "data: "+c+"\n\n")+ w.(http.Flusher).Flush()+ }+ io.WriteString(w, "data: [DONE]\n\n")+ }))+ t.Cleanup(up.Close)+ return up+}++// ollamaCall posts body to path as a client on this computer would, through+// the whole guarded stack.+func ollamaCall(t *testing.T, h http.Handler, path, body string) *httptest.ResponseRecorder {+ t.Helper()+ r := httptest.NewRequest("POST", path, strings.NewReader(body))+ r.RemoteAddr, r.Host = "127.0.0.1:50123", "127.0.0.1:3425"+ r.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ h.ServeHTTP(w, r)+ return w+}++// ndjson is each line of an NDJSON reply.+func ndjson(t *testing.T, body string) []gjson.Result {+ t.Helper()+ var out []gjson.Result+ sc := bufio.NewScanner(strings.NewReader(body))+ for sc.Scan() {+ if !json.Valid(sc.Bytes()) {+ t.Fatalf("not a JSON line: %q in %s", sc.Text(), body)+ }+ out = append(out, gjson.Parse(sc.Text()))+ }+ return out+}++// Zed's Ollama provider (super_lalalalala on Discord) chats on+// /api/chat, which magpie answered 404: it is served now, as+// /v1/chat/completions is, with Zed's own request (crates/ollama+// ChatRequest: stream true, keep_alive, options num_ctx/num_predict/+// temperature, think, tools; an assistant's tool call with an id, a tool+// result named by tool_name alone; a user image as bare base64). The+// provider is sent it as Chat Completions, and the reply comes back as+// Ollama's NDJSON: thinking and text as they arrive, the tool call whole+// with its arguments an object and an id, and a last done line with the+// reason and the token counts.+func TestOllamaChatStreams(t *testing.T) {+ fresh(t)+ var got []string+ ollamaPlan(t, ollamaUpstream(t, &got).URL+"/v1")+ h := lanGuard(New().Handler())+ const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="+ body := `{"model":"plan/seer","messages":[` ++ `{"role":"system","content":"You are Zed."},` ++ `{"role":"user","content":"look","images":["` + png + `"]},` ++ `{"role":"assistant","content":"","tool_calls":[{"id":"t1","function":{"name":"read_file","arguments":{"path":"x.go"}}},{"function":{"name":"grep","arguments":{"q":"y"}}}],"thinking":"hm"},` ++ `{"role":"tool","tool_name":"grep","content":"no match"},` ++ `{"role":"tool","tool_name":"read_file","content":"package x"}` ++ `],"stream":true,"keep_alive":"5m","options":{"num_ctx":32768,"num_predict":512,"temperature":0.3,"top_k":40,"stop":["</end>"]},` ++ `"tools":[{"type":"function","function":{"name":"read_file","description":"Read","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}}],"think":true}`+ w := ollamaCall(t, h, "/api/chat", body)+ if w.Code != 200 || w.Header().Get("Content-Type") != "application/x-ndjson" {+ t.Fatalf("chat: %d %s %s", w.Code, w.Header().Get("Content-Type"), w.Body)+ }+ if len(got) != 1 {+ t.Fatalf("upstream asked %d times", len(got))+ }+ up := gjson.Parse(got[0])+ for k, want := range map[string]string{+ "model": "seer", "stream": "true", "stream_options.include_usage": "true", "max_tokens": "512", "temperature": "0.3", "stop.0": "</end>",+ "messages.0.role": "system", "messages.0.content": "You are Zed.",+ "messages.1.content.0.text": "look", "messages.1.content.1.image_url.url": "data:image/png;base64," + png,+ "messages.2.tool_calls.0.id": "t1", "messages.2.tool_calls.0.function.arguments": `{"path":"x.go"}`,+ "messages.2.tool_calls.1.function.name": "grep", "messages.2.reasoning_content": "hm",+ "messages.3.role": "tool", "messages.3.content": "no match",+ "messages.4.tool_call_id": "t1", "messages.4.content": "package x",+ "tools.0.function.name": "read_file",+ } {+ if g := up.Get(k).String(); g != want {+ t.Errorf("upstream %s = %q, want %q (sent %s)", k, g, want, got[0])+ }+ }+ if id := up.Get("messages.3.tool_call_id").String(); id == "" || id != up.Get("messages.2.tool_calls.1.id").String() {+ t.Errorf("grep's result went with %q, its call has id %q", id, up.Get("messages.2.tool_calls.1.id"))+ }+ for _, k := range []string{"num_ctx", "top_k", "keep_alive", "options", "think", "images"} {+ if up.Get(k).Exists() {+ t.Errorf("upstream was sent Ollama's own %s: %s", k, got[0])+ }+ }++ lines := ndjson(t, w.Body.String())+ var text, think string+ var calls []gjson.Result+ for _, l := range lines[:len(lines)-1] {+ if l.Get("done").Bool() || l.Get("model").String() != "plan/seer" || l.Get("message.role").String() != "assistant" || !l.Get("message.content").Exists() || !l.Get("created_at").Exists() {+ t.Fatalf("part %s", l.Raw)+ }+ text += l.Get("message.content").String()+ think += l.Get("message.thinking").String()+ calls = append(calls, l.Get("message.tool_calls").Array()...)+ }+ if text != "Hello, world" || think != "let me think" {+ t.Errorf("text %q thinking %q", text, think)+ }+ if len(calls) != 1 || calls[0].Get("id").String() != "call_up" || calls[0].Get("function.name").String() != "read_file" || calls[0].Get("function.arguments").Raw != `{"path":"a.go"}` {+ t.Errorf("tool calls %v", calls)+ }+ last := lines[len(lines)-1]+ if !last.Get("done").Bool() || last.Get("done_reason").String() != "stop" || last.Get("prompt_eval_count").Int() != 11 || last.Get("eval_count").Int() != 7 || last.Get("message.content").String() != "" {+ t.Errorf("done line %s", last.Raw)+ }+}++// "stream": false gets one JSON object, the whole reply in it; and with+// think false a model's reasoning isn't told.+func TestOllamaChatWhole(t *testing.T) {+ fresh(t)+ var got []string+ ollamaPlan(t, ollamaUpstream(t, &got).URL+"/v1")+ h := lanGuard(New().Handler())+ w := ollamaCall(t, h, "/api/chat", `{"model":"plan/seer","messages":[{"role":"user","content":"hi"}],"stream":false,"format":"json","think":"high"}`)+ if w.Code != 200 || len(got) != 1 {+ t.Fatalf("chat: %d %s (upstream %d)", w.Code, w.Body, len(got))+ }+ if up := gjson.Parse(got[0]); up.Get("stream").Bool() || up.Get("response_format.type").String() != "json_object" || up.Get("reasoning_effort").String() != "high" {+ t.Errorf("upstream sent %s", got[0])+ }+ r := gjson.Parse(w.Body.String())+ if !r.Get("done").Bool() || r.Get("message.content").String() != "whole answer" || r.Get("message.thinking").String() != "pondered" ||+ r.Get("message.tool_calls.0.function.arguments.path").String() != "a.go" || r.Get("eval_count").Int() != 7 || strings.Count(w.Body.String(), "\n") > 1 {+ t.Errorf("whole reply %s", w.Body)+ }+ w = ollamaCall(t, h, "/api/chat", `{"model":"plan/seer","messages":[{"role":"user","content":"hi"}],"stream":false,"think":false}`)+ if r := gjson.Parse(w.Body.String()); w.Code != 200 || r.Get("message.thinking").Exists() || r.Get("message.content").String() != "whole answer" {+ t.Errorf("think false: %d %s", w.Code, w.Body)+ }+}++// /api/generate takes a prompt, a system prompt and images, and answers+// in "response", streamed or whole; the ollama CLI's name:latest for a+// model with no tag is the model.+func TestOllamaGenerate(t *testing.T) {+ fresh(t)+ var got []string+ ollamaPlan(t, ollamaUpstream(t, &got).URL+"/v1")+ h := lanGuard(New().Handler())+ w := ollamaCall(t, h, "/api/generate", `{"model":"plan/seer:latest","prompt":"why is the sky blue","system":"be brief","images":["/9j/4AAQSkZJRgABAQ=="],"options":{"seed":7,"top_p":0.9,"num_predict":-1}}`)+ if w.Code != 200 || len(got) != 1 {+ t.Fatalf("generate: %d %s", w.Code, w.Body)+ }+ up := gjson.Parse(got[0])+ if up.Get("model").String() != "seer" || up.Get("messages.0.content").String() != "be brief" || up.Get("messages.1.content.0.text").String() != "why is the sky blue" ||+ !strings.HasPrefix(up.Get("messages.1.content.1.image_url.url").String(), "data:image/jpeg;base64,") || up.Get("seed").Int() != 7 || up.Get("top_p").Float() != 0.9 || up.Get("max_tokens").Exists() {+ t.Errorf("upstream sent %s", got[0])+ }+ lines := ndjson(t, w.Body.String())+ var text string+ for _, l := range lines {+ if l.Get("message").Exists() {+ t.Fatalf("generate answered with a message: %s", l.Raw)+ }+ text += l.Get("response").String()+ }+ if text != "Hello, world" || !lines[len(lines)-1].Get("done").Bool() {+ t.Errorf("generate streamed %s", w.Body)+ }+ w = ollamaCall(t, h, "/api/generate", `{"model":"plan/seer","prompt":"hi","stream":false}`)+ if r := gjson.Parse(w.Body.String()); w.Code != 200 || r.Get("response").String() != "whole answer" || !r.Get("done").Bool() {+ t.Errorf("generate whole: %d %s", w.Code, w.Body)+ }+ // nothing to say: the model loaded, as a client warms it up+ w = ollamaCall(t, h, "/api/generate", `{"model":"plan/seer"}`)+ if r := gjson.Parse(w.Body.String()); w.Code != 200 || r.Get("done_reason").String() != "load" || len(got) != 2 {+ t.Errorf("generate with no prompt: %d %s (upstream %d)", w.Code, w.Body, len(got))+ }+}++// A model magpie doesn't serve, and a provider's refusal, are told as+// Ollama tells an error: {"error": "…"} with the status.+func TestOllamaChatErrors(t *testing.T) {+ fresh(t)+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(400)+ io.WriteString(w, `{"error":{"message":"context too long for seer","type":"invalid_request_error"}}`)+ }))+ defer up.Close()+ ollamaPlan(t, up.URL+"/v1")+ h := lanGuard(New().Handler())+ for _, path := range []string{"/api/chat", "/api/generate"} {+ w := ollamaCall(t, h, path, `{"model":"nowhere/none","messages":[{"role":"user","content":"hi"}],"prompt":"hi"}`)+ if e := gjson.Get(w.Body.String(), "error"); w.Code < 400 || e.Type != gjson.String || e.String() == "" {+ t.Errorf("%s, unknown model: %d %s", path, w.Code, w.Body)+ }+ w = ollamaCall(t, h, path, `{"model":"plan/seer","messages":[{"role":"user","content":"hi"}],"prompt":"hi"}`)+ if e := gjson.Get(w.Body.String(), "error"); w.Code != 400 || e.Type != gjson.String || !strings.Contains(e.String(), "context too long") {+ t.Errorf("%s, refused: %d %s", path, w.Code, w.Body)+ }+ }+ if w := ollamaCall(t, h, "/api/chat", `{"model":"plan/seer","messages":[{"role":"tool","content":"orphan"}]}`); w.Code != 400 || gjson.Get(w.Body.String(), "error").Type != gjson.String {+ t.Errorf("a tool result with no call: %d %s", w.Code, w.Body)+ }+}diff --git a/internal/gateway/ollama_test.go b/internal/gateway/ollama_test.goindex 45ded2244..33ef234ff 100644--- a/internal/gateway/ollama_test.go+++ b/internal/gateway/ollama_test.go@@ -10,6 +10,7 @@ import ("strings""testing"+ "github.com/tidwall/gjson""github.com/yetone/magpie/internal/access""github.com/yetone/magpie/internal/provider""github.com/yetone/magpie/internal/settings"@@ -110,6 +111,14 @@ func TestOllamaModelRoutes(t *testing.T) {t.Fatalf("model_info %s: %v", k, s.ModelInfo[k])}}+ // "ollama run plan/plain" asks for plan/plain:latest, and pulls the+ // model when show says it isn't there+ if c, s := show(`{"model":"plan/plain:latest"}`); c != 200 || !slices.Equal(s.Capabilities, []string{"completion", "tools"}) {+ t.Fatalf("show plain:latest: %d %+v", c, s)+ }+ if c, _ := show(`{"model":"plan/nothing:latest"}`); c != 404 {+ t.Fatal("an unknown model:latest:", c)+ }if c, _ := show(`{"model":"plan/nothing"}`); c != 404 {t.Fatal("an unknown model:", c)}@@ -119,10 +128,11 @@ func TestOllamaModelRoutes(t *testing.T) {}// A gateway key held to some models is listed and shown those alone on the-// Ollama routes, as on /v1/models.+// Ollama routes, as on /v1/models, and chats on /api/chat and+// /api/generate with those alone, as on /v1/chat/completions.func TestOllamaRoutesHoldAKey(t *testing.T) {fresh(t)- ollamaPlan(t, "http://127.0.0.1:1/v1")+ ollamaPlan(t, ollamaUpstream(t, nil).URL+"/v1")keys, secrets := newCaller(t, "Held")if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"plan/plain"}}); err != nil {t.Fatal(err)@@ -144,6 +154,21 @@ func TestOllamaRoutesHoldAKey(t *testing.T) {if w := do("POST", "/api/show", `{"model":"plan/plain"}`); w.Code != 200 {t.Fatalf("held key's own model: %d %s", w.Code, w.Body)}+ v1 := do("POST", "/v1/chat/completions", `{"model":"plan/seer","messages":[{"role":"user","content":"hi"}]}`)+ if v1.Code == 200 {+ t.Fatalf("held key chatted with a model it may not use on /v1: %s", v1.Body)+ }+ for _, rt := range [][2]string{+ {"/api/chat", `{"model":"%s","messages":[{"role":"user","content":"hi"}],"stream":false}`},+ {"/api/generate", `{"model":"%s","prompt":"hi","stream":false}`},+ } {+ if w := do("POST", rt[0], fmt.Sprintf(rt[1], "plan/seer")); w.Code != v1.Code || gjson.Get(w.Body.String(), "error").Type != gjson.String {+ t.Fatalf("%s: held key with a model it may not use: %d %s, want %d as /v1 and Ollama's error", rt[0], w.Code, w.Body, v1.Code)+ }+ if w := do("POST", rt[0], fmt.Sprintf(rt[1], "plan/plain")); w.Code != 200 || !strings.Contains(w.Body.String(), `"done":true`) {+ t.Fatalf("%s: held key's own model: %d %s", rt[0], w.Code, w.Body)+ }+ }}// The Ollama routes are guarded as every gateway route is, through the@@ -157,12 +182,14 @@ func TestOllamaRoutesGuarded(t *testing.T) {t.Setenv("MAGPIE_ADDR", "")t.Setenv("MAGPIE_PUBLIC_URL", "")t.Setenv("MAGPIE_TRUST_PROXY", "")- ollamaPlan(t, "http://127.0.0.1:1/v1")+ ollamaPlan(t, ollamaUpstream(t, nil).URL+"/v1")srv := lanGuard(New().Handler())routes := []struct{ method, path, body string }{{"GET", "/api/version", ""},{"GET", "/api/tags", ""},{"POST", "/api/show", `{"model":"plan/seer"}`},+ {"POST", "/api/chat", `{"model":"plan/seer","messages":[{"role":"user","content":"hi"}],"stream":false}`},+ {"POST", "/api/generate", `{"model":"plan/seer","prompt":"hi","stream":false}`},}const gw = "127.0.0.1:3425"browser := []string{"User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15",