diff --git a/docs/reference.md b/docs/reference.md index 6f08a85c7..16ca22e7f 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -3903,6 +3903,7 @@ application: - /decisions - /audio - /videos + - /realtime - /muse-code/models - /backend-api/codex - /alpha/search diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 86697cf35..acb7860fe 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -38,7 +38,7 @@ removed records stay and turning them on again restores the groups as they were. | 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) | | HTTPS | With Settings → Network and sharing → HTTPS on (settings `HTTPS`, `magpie https on`; zhangly1 on X) `TLSOn` is true, so the listener serves other computers TLS as with mTLS, without a client certificate asked. Without `--tls-cert`, `settingsCert` serves the pair imported to `/https` (`ImportCert`: PEM in any split, the leaf the key matches first; refuses an encrypted key, a mismatch, an expired leaf; read again through `certFiles`), else `ownServerCert` from magpie's CA (made when HTTPS is turned on). A WSL distro's connection is sniffed, so its plain HTTP still works. `GET /magpie-ca.crt` (`caFile`) serves the CA to any address `lanGuard` lets in without a key (`caFileOpen`), 404 before one exists. The Settings routes (`internal/gui/https.go`) refuse a page from another computer that would flip the switch under itself (`errFarPage`). `TestHTTPSOtherComputer`, `TestHTTPSThisComputerPlain`, `TestHTTPSImportedCert`, `TestHTTPSCAFile`, `TestSettingsHTTPSFarPage`, `https-settings.test.cjs`. | [`https.go`](../../internal/gateway/https.go), [`tls.go`](../../internal/gateway/tls.go) | | mTLS | With Settings → Network and sharing → Require a client certificate on (settings `MTLS`, `magpie mtls on`; hhdaxia on X, #5596), other computers reach the gateway and `magpie web`'s page only over TLS with a client certificate magpie's own CA (`internal/mtls`, `MTLSStore`: `ca.pem`, `ca-key.pem`, `clients.json` under the settings folder) issued and hasn't revoked. `tlsServer.config(strict)` is asked per connection, so the switch needs no relisten: without `--tls-cert` it serves a certificate the CA signs in memory for this computer's names, addresses and the SNI name (`ownServerCert`, made again when they or the CA change, or after a day), and with mTLS on even without `--tls-cert` the listener serves TLS. A peer that isn't this computer or a WSL distro (`fromWSLNet`) is asked `RequireAndVerifyClientCert` and its handshake ended when `VerifyConnection`'s `Admits` fails. The guards (`lanGuard`, and `ClientCertGuard` on the page) then refuse 403 every request `NeedsClientCert` names: plain HTTP, a proxy's or tunnel's on loopback (`proxied`, unless `MAGPIE_TRUST_PROXY=1` says the proxy checks certificates itself), the page port (`viaPagePort`), a connection made before the switch, a certificate revoked since its handshake. This computer (`local`, `ownAddress`) and a WSL agent with the WSL key (`fromWSL`) are answered as before. The Settings routes (`internal/gui/mtls.go`) never let a page from another computer shut itself out: without a certificate it can't turn mTLS on, and it can't revoke or issue again the certificate it came with (`pageCert`, `errOwnCert`). Not handled: a `.p12` for browsers, and a proxy that can't check certificates itself. `TestMTLSOtherComputerHandshake`, `TestMTLSGuardEveryRoute`, `TestMTLSThisComputerAndProxies`, `TestMTLSToggleWithoutRelisten`, `TestMTLSRevokeMidConnection`, `TestClientCertGuardPage`, `TestSettingsMTLSPageLockout`. | [`mtls.go`](../../internal/gateway/mtls.go), [`tls.go`](../../internal/gateway/tls.go), [`internal/mtls`](../../internal/mtls/mtls.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. Obsidian's `app://obsidian.md` (`appOrigin`) is also answered with CORS headers, keyless: Copilot for Obsidian streams through its window's fetch, which reads no reply without them, and the origin is one only Obsidian's own window sends, so it gets no more than its calls without an Origin get, and from the network it still needs a key (`TestCORSObsidian`, shirotokiren on X); `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) | +| 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. A WebSocket upgrade on `/v1/realtime` or `/realtime` is a Realtime API session (below, [A Realtime session](#a-realtime-session)). 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. Obsidian's `app://obsidian.md` (`appOrigin`) is also answered with CORS headers, keyless: Copilot for Obsidian streams through its window's fetch, which reads no reply without them, and the origin is one only Obsidian's own window sends, so it gets no more than its calls without an Origin get, and from the network it still needs a key (`TestCORSObsidian`, shirotokiren on X); `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 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) | @@ -3092,6 +3092,46 @@ serves it on `/v1/responses`, `/responses` and the Codex backend's leg between the two magpies (below). A socket's conversation doesn't outlive the socket or the gateway. +## A Realtime session + +`GET /v1/realtime?model=…` (and `/realtime`) with a WebSocket upgrade is the +Realtime API, as OpenAI's and DashScope's realtime models take it +(`realtime` in [`realtime.go`](../../internal/gateway/realtime.go); +gaubeebangeel on X: a Qwen Token Plan's realtime voice). A request without +the upgrade is answered 426. The model is resolved as a chat's (`idOff`, +`modelOff`, a key's models and accounts, `onKeys`, `probeOne`); a bare id +no provider lists goes to the one DashScope provider turned on +(`resolveRealtimeModel`), and a routing group is a 400, since a session +goes to one model. The session opens at the provider's realtime address +(`realtimeURL`): a DashScope base (`…/compatible-mode/v1`, Qwen's, +Bailian's and both Token Plans') at `/api-ws/v1/realtime` on the same host, +as Alibaba gives the Token Plan's `qwen-audio-3.0-realtime-plus` +(https://platform.qianwenai.com/docs/token-plan/best-practices/realtime-voice), +any other at base + `/realtime`. It is signed as the provider's requests +are (`Sign`, `stampUA`, the provider's proxy and RPM through `metered`), +each try in turn until one opens, and a vendor's refusal is answered with +its status and message before the client is upgraded. The client's +subprotocols go on less `openai-insecure-api-key.*`, +`openai-organization.*` and `openai-project.*`, and `OpenAI-Beta` too. + +The upgrade passes the whole handler, so the allow list, `lanGuard`'s key +and `rebound`, and `corsGuard` judge it as any request; past them an +`Origin` must be the address the upgrade was sent to (`sameOriginSocket`, +as coder/websocket's own `Accept` checks), since a browser's WebSocket +isn't held by CORS (`TestRealtimeGuards`: a foreign page, `null`, a +localhost subdomain and a rebound name are refused before any vendor is +dialled). A session opened with a gateway key is closed once the key is no +longer on (`realtimeKeyCheck`). Frames go both ways as they came; a +client's text frame is masked as the settings say (failing closed: the +session ends with a policy-violation close), the vendor's get the values +back, and audio frames (`input_audio_buffer.append`, `*audio.delta`) are +neither (`TestRealtimeMasked`). Each `response.done` with `usage` is a row +in the usage ledger, operation `realtime`, its cached input as +`CacheRead`; the session is one call on the Routing page with the sum. +Either side's close is given to the other with its code and reason. When +the gateway ends, every session is closed going away (`realtimeSessions`), +since its connection was taken from the server. + ## A Responses request that names the response it follows A Responses client may send only its new input with `previous_response_id` diff --git a/internal/gateway/cors_test.go b/internal/gateway/cors_test.go index ecae92918..8eda9e1d1 100644 --- a/internal/gateway/cors_test.go +++ b/internal/gateway/cors_test.go @@ -241,6 +241,7 @@ func TestForeignPagesRefused(t *testing.T) { {"POST", "/v1/decisions", `{"model":"plan/m1","input":"hi","questions":[{"type":"predicate","instructions":"is it?"}]}`}, {"POST", "/v1/audio/transcriptions", "--b\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nplan/m1\r\n--b--\r\n"}, {"POST", "/v1/audio/speech", `{"model":"plan/m1","input":"hi","voice":"coral"}`}, + {"GET", "/v1/realtime?model=plan/m1", ""}, {"POST", "/v1/images/generations", `{"model":"plan/m1","prompt":"hi"}`}, {"POST", "/v1/videos", `{"model":"plan/m1","prompt":"hi"}`}, {"POST", CodexPath + "/responses", `{"model":"plan/m1","input":"hi"}`}, diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 311cd55a1..f456ef99a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -601,6 +601,8 @@ type Server struct { unread unreadConns // sockets are the Responses WebSockets being served (responses_ws.go) sockets clientSockets + // realtimes are the Realtime API sessions being served (realtime.go) + realtimes realtimeSessions // what it serves other computers TLS with, nil without (tls.go) tls *tlsServer // the images described for models that can't see them (vision.go); @@ -981,7 +983,10 @@ func (s *Server) ListenAndServe(ctx context.Context) error { // a socket's connection was taken from the server (hijacked), so // Shutdown doesn't wait for it: each ends after its turn in flight sockets := make(chan struct{}) - go func() { defer close(sockets); s.sockets.drain(c) }() + // a realtime session has no turn to wait for: it is closed going + // away, and its client opens a new one + s.realtimes.end() + go func() { defer close(sockets); s.sockets.drain(c); s.realtimes.wait(c) }() if err := srv.Shutdown(c); err != nil { // the requests still answering are cut where they are, and // an agent streaming one reads a reply broken off (Codex: @@ -1152,6 +1157,8 @@ func (s *Server) routes() *routeMux { // speech to text, for a client's voice input (#2053) mux.HandleFunc("POST /v1/audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions")) mux.HandleFunc("POST /audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions")) + mux.HandleFunc("GET /v1/realtime", s.realtime) + mux.HandleFunc("GET /realtime", s.realtime) mux.HandleFunc("POST /v1/audio/translations", s.transcribe("/audio/translations", "translations")) mux.HandleFunc("POST /audio/translations", s.transcribe("/audio/translations", "translations")) mux.HandleFunc("POST /v1/audio/speech", s.speak) @@ -1187,7 +1194,7 @@ func (s *Server) routes() *routeMux { mux.HandleFunc("GET /v1beta/models", s.geminiModels) mux.HandleFunc("POST /v1beta/models/{call...}", s.gemini) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/decisions, /v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech and /v1beta/models/*") + writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/decisions, /v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech, /v1/realtime (WebSocket) and /v1beta/models/*") }) return mux } @@ -1216,7 +1223,7 @@ var catalogSize stamped[struct{}, int] func (s *Server) info(w http.ResponseWriter, r *http.Request) { out := map[string]any{"name": "magpie", "version": Version, "models": catalogSize.get(struct{}{}, func() int { return len(provider.Catalog()) }), "window": Window, - "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, MemoryMCPPath, SessionsMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}} + "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/realtime", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, MemoryMCPPath, SessionsMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}} // which process serves, for another magpie on this computer to name it // on its Routing page (#2606); not told to another machine if local(r) { diff --git a/internal/gateway/lan_test.go b/internal/gateway/lan_test.go index b713e0853..f03d03326 100644 --- a/internal/gateway/lan_test.go +++ b/internal/gateway/lan_test.go @@ -441,6 +441,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) { {"POST", "/v1/images/generations"}, {"POST", "/v1/images/edits"}, {"POST", "/v1/embeddings"}, {"POST", "/v1/rerank"}, {"POST", "/v1/decisions"}, {"POST", "/v1/audio/transcriptions"}, {"POST", "/v1/audio/translations"}, {"POST", "/v1/audio/speech"}, + {"GET", "/v1/realtime?model=m"}, {"GET", "/realtime?model=m"}, {"POST", "/v1/videos"}, {"GET", "/v1/videos/v1"}, {"GET", "/v1/videos/v1/content"}, {"POST", "/_magpie/claude-mcp/tok"}, {"POST", "/mcp/neon"}, {"POST", CodexPath + "/responses"}, {"GET", CodexCatalogPath}, @@ -450,7 +451,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) { call := func(method, path, from string, hdr ...string) (int, string) { r := httptest.NewRequest(method, path, strings.NewReader("{}")) r.RemoteAddr = from - if path == "/v1/responses" || path == "/responses" { + if path == "/v1/responses" || path == "/responses" || strings.Contains(path, "realtime?") { r.Header.Set("Connection", "Upgrade") r.Header.Set("Upgrade", "websocket") r.Header.Set("Sec-WebSocket-Version", "13") diff --git a/internal/gateway/oneport.go b/internal/gateway/oneport.go index 796f0a6da..acca38644 100644 --- a/internal/gateway/oneport.go +++ b/internal/gateway/oneport.go @@ -26,7 +26,7 @@ func (s *Server) Front() http.Handler { var clientPrefixes = []string{ "/v1", "/v1beta", "/models", "/chat/completions", "/responses", "/messages", - "/images", "/embeddings", "/rerank", "/decisions", "/audio", "/videos", + "/images", "/embeddings", "/rerank", "/decisions", "/audio", "/videos", "/realtime", "/muse-code/models", CodexPath, AlphaSearchPath, "/mcp", // the key page (KeyPagePath): a key's holder opens it at the address // they give their agents diff --git a/internal/gateway/readonly_test.go b/internal/gateway/readonly_test.go index 7f3fe8875..ca52aef8c 100644 --- a/internal/gateway/readonly_test.go +++ b/internal/gateway/readonly_test.go @@ -56,6 +56,7 @@ var readOnlyRefused = []string{ "POST /v1/audio/transcriptions", "POST /audio/transcriptions", "POST /v1/audio/translations", "POST /audio/translations", "POST /v1/audio/speech", "POST /audio/speech", + "GET /v1/realtime", "GET /realtime", "POST /v1/videos", "POST /videos", "GET /v1/videos/{id}", "GET /videos/{id}", "GET /v1/videos/{id}/content", "GET /videos/{id}/content", "POST " + NativePath + "{provider}/{path...}", "GET " + NativePath + "{provider}/{path...}", "DELETE " + NativePath + "{provider}/{path...}", diff --git a/internal/gateway/realtime.go b/internal/gateway/realtime.go new file mode 100644 index 000000000..298f660e5 --- /dev/null +++ b/internal/gateway/realtime.go @@ -0,0 +1,647 @@ +package gateway + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/url" + "slices" + "strings" + "sync" + "time" + + "github.com/coder/websocket" + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/gwmw" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// The Realtime API over a WebSocket: GET /v1/realtime?model=… with +// Upgrade: websocket, as OpenAI's Realtime API and DashScope's (Qwen's) +// realtime models take it (gaubeebangeel on X: a Qwen Token Plan's +// realtime voice through magpie). Alibaba sells the Token Plan's +// realtime voice model, qwen-audio-3.0-realtime-plus, on the plan's own +// host at /api-ws/v1/realtime with the plan's sk-sp- key +// (platform.qianwenai.com/docs/token-plan/best-practices/realtime-voice). +// +// The session goes to one model's provider, over its keys or accounts as +// a chat would, and is passed on frame by frame both ways; magpie reads +// the frames only to mask what goes out (as the settings say), put the +// masked values back in what comes in, and count each response.done's +// usage. The upgrade comes through the whole handler, so the allow list, +// the gateway key and its models and accounts, the Origin and Host +// checks judge it as they judge any request; a page from another origin +// can't open one at all (a browser's WebSocket isn't held by CORS), and a +// session opened with a key ends when the key is no longer on. +// +// A provider's realtime address is its OpenAI-style base's: DashScope's +// (…/compatible-mode/v1) at /api-ws/v1/realtime on the same host, any +// other at base + /realtime (OpenAI's /v1/realtime). + +var ( + // realtimeDial bounds the upstream handshake + realtimeDial = 30 * time.Second + // realtimeKeyCheck is how often a session opened with a gateway key + // looks whether the key is still on + realtimeKeyCheck = 5 * time.Second +) + +// realtimeReadLimit is the largest frame read either way: a few seconds +// of base64 audio is well under it. +const realtimeReadLimit = 32 << 20 + +// realtimeSessions are the sessions being served; their connections were +// taken from the server (hijacked), so they are closed when it ends. +type realtimeSessions struct { + mu sync.Mutex + m map[*websocket.Conn]bool + closing bool + // running counts the handlers serving a session, for end's caller to + // wait for (wait); idle is closed when it is back at none + running int + idle chan struct{} +} + +func (rs *realtimeSessions) enter() { + rs.mu.Lock() + rs.running++ + rs.mu.Unlock() +} + +func (rs *realtimeSessions) leave() { + rs.mu.Lock() + defer rs.mu.Unlock() + if rs.running--; rs.running == 0 && rs.idle != nil { + close(rs.idle) + rs.idle = nil + } +} + +func (rs *realtimeSessions) add(c *websocket.Conn) bool { + rs.mu.Lock() + defer rs.mu.Unlock() + if rs.closing { + return false + } + if rs.m == nil { + rs.m = map[*websocket.Conn]bool{} + } + rs.m[c] = true + return true +} + +func (rs *realtimeSessions) remove(c *websocket.Conn) { + rs.mu.Lock() + defer rs.mu.Unlock() + delete(rs.m, c) +} + +func (rs *realtimeSessions) ending() bool { + rs.mu.Lock() + defer rs.mu.Unlock() + return rs.closing +} + +// end closes every session going away; a client opens a new one to the +// gateway serving the port then. +func (rs *realtimeSessions) end() { + rs.mu.Lock() + rs.closing = true + all := make([]*websocket.Conn, 0, len(rs.m)) + for c := range rs.m { + all = append(all, c) + } + rs.mu.Unlock() + for _, c := range all { + go c.Close(websocket.StatusGoingAway, "magpie is restarting") + } +} + +// wait waits for every session's handler to have returned, or ctx. +func (rs *realtimeSessions) wait(ctx context.Context) { + rs.mu.Lock() + if rs.running == 0 { + rs.mu.Unlock() + return + } + if rs.idle == nil { + rs.idle = make(chan struct{}) + } + idle := rs.idle + rs.mu.Unlock() + select { + case <-idle: + case <-ctx.Done(): + } +} + +// realtime serves GET /v1/realtime. +func (s *Server) realtime(w http.ResponseWriter, r *http.Request) { + if !wantsSocket(r) { + w.Header().Set("Upgrade", "websocket") + writeError(w, provider.Chat, http.StatusUpgradeRequired, "the Realtime API is a WebSocket: open GET /v1/realtime?model=/ with Upgrade: websocket") + return + } + s.realtimes.enter() + defer s.realtimes.leave() + start := time.Now() + asked := strings.TrimSpace(r.URL.Query().Get("model")) + who := callerOf(r) + call := Call{Time: start, From: provider.Chat, To: provider.Chat, Agent: who.agent, Via: who.via, Model: asked, headers: headerLogOf(r.Context())} + usage.Saw(agentOf(r)) + refuse := func(code int, msg string) { + call.Status, call.Error, call.Millis = code, msg, time.Since(start).Milliseconds() + writeError(w, provider.Chat, code, msg) + s.record(call) + } + // a page of another origin (the library's check, made before anything + // is dialled): corsGuard let a page on this computer by, which a + // browser's WebSocket isn't held from by CORS + if !sameOriginSocket(r) { + refuse(http.StatusForbidden, "magpie opens a realtime session only for a client that isn't a web page, or a page at magpie's own address") + return + } + if s.realtimes.ending() { + refuse(http.StatusServiceUnavailable, "magpie is restarting") + return + } + if asked == "" { + refuse(http.StatusBadRequest, "name the model: /v1/realtime?model=/ (qwen-token-plan/qwen-audio-3.0-realtime-plus, openai/gpt-realtime)") + return + } + if msg, off := idOff(asked); off { + refuse(http.StatusForbidden, msg) + return + } + if _, _, isGroup := provider.FindGroup(asked); isGroup { + refuse(http.StatusBadRequest, "a realtime session goes to one model: name a model, not the routing group "+asked) + return + } + p, model, code, msg := resolveRealtimeModel(asked) + if code != 0 { + refuse(code, msg) + return + } + if msg, off := modelOff(p, model, asked); off { + refuse(http.StatusForbidden, msg) + return + } + if keyWho, held := keyHolds(r); held && !modelAllowed(keyWho, p, model) { + st, msg := keyModelRefusal(w, keyWho, asked) + refuse(st, msg) + return + } + tries, code, msg := s.onKeys(r, p, model, asked) + if code != 0 { + refuse(code, msg) + return + } + if keyWho, held := accountHolds(r); held { + tries = slices.DeleteFunc(tries, func(c candidate) bool { return !accountAllowed(keyWho, c) }) + if len(tries) == 0 { + refuse(http.StatusForbidden, keyAccountsError(keyWho, asked)) + return + } + } + tries = probeOne(tries) // of those resting, only the one back soonest (#1799) + + // the session lives past the handshake: its context ends when the + // handler returns + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + offered := realtimeSubprotocols(r.Header) + var up *websocket.Conn + var c candidate + var skipped []string + for i, try := range tries { + last := i == len(tries)-1 + call.Provider, call.Model = try.p.ID, asked + u, why := realtimeURL(try.p, try.model) + var err error + code := http.StatusBadRequest + if why != "" { + err = errors.New(why) + } else { + up, code, err = s.dialRealtime(ctx, r, try.p, u, offered) + } + if err == nil { + c = try + break + } + if !last && r.Context().Err() == nil { + skipped = append(skipped, try.label()+": "+err.Error()) + continue + } + call.Fallback = strings.Join(skipped, "; ") + msg := err.Error() + if len(skipped) > 0 { + msg += " (tried first: " + call.Fallback + ")" + } + refuse(code, msg) + return + } + call.Fallback = strings.Join(skipped, "; ") + defer up.CloseNow() + up.SetReadLimit(realtimeReadLimit) + + // what goes out is masked, unless the provider is set to go unmasked; + // fails closed before the client is answered + var mask *realtimeMask + if !c.unmasked() { + mctx, m, err := maskingFor(r.Context()) + if err != nil { + up.Close(websocket.StatusGoingAway, "") + refuse(maskStatus(err), err.Error()) + return + } + if m != nil { + mask = &realtimeMask{ctx: mctx, m: m} + } + } + + var accept []string + if sp := up.Subprotocol(); sp != "" { + accept = []string{sp} + } + client, err := websocket.Accept(w, r, &websocket.AcceptOptions{Subprotocols: accept}) + if err != nil { + up.Close(websocket.StatusGoingAway, "") + call.Status, call.Error, call.Millis = http.StatusBadRequest, "the client's WebSocket handshake failed: "+err.Error(), time.Since(start).Milliseconds() + s.record(call) + return + } + defer client.CloseNow() + client.SetReadLimit(realtimeReadLimit) + if !s.realtimes.add(client) { + client.Close(websocket.StatusGoingAway, "magpie is restarting") + up.Close(websocket.StatusGoingAway, "") + return + } + defer s.realtimes.remove(client) + + // a session opened with a gateway key ends once the key isn't on + if keyWho := access.Caller(r.Context()); keyWho.KeyID != "" { + go func() { + t := time.NewTicker(realtimeKeyCheck) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + if !access.Current(keyWho) { + log.Printf("realtime: the gateway key %s is no longer on, so its session to %s is closed", keyWho.KeyName, c.p.ID) + go up.Close(websocket.StatusPolicyViolation, "") + client.Close(websocket.StatusPolicyViolation, "the gateway key this session was opened with is no longer on") + return + } + } + } + }() + } + + sess := &realtimeSession{s: s, r: r, c: c, asked: asked, mask: mask} + status, why := sess.pipe(ctx, client, up) + call.Status, call.Millis, call.Usage = status, time.Since(start).Milliseconds(), sess.total + call.Error = cmpOr(why, sess.lastErr) + s.record(call) +} + +// sameOriginSocket: the upgrade has no Origin (a program's client), or +// one at the address it was sent to, as coder/websocket's own check +// takes it. +func sameOriginSocket(r *http.Request) bool { + origin := r.Header.Get("Origin") + if origin == "" { + return true + } + u, err := url.Parse(origin) + return err == nil && u.Host != "" && strings.EqualFold(u.Host, r.Host) +} + +// realtimeSubprotocols are the subprotocols the client offered, less +// the ones a browser carries an OpenAI key or organization in, which are +// never passed on. +func realtimeSubprotocols(h http.Header) []string { + var out []string + for _, v := range h.Values("Sec-WebSocket-Protocol") { + for _, p := range strings.Split(v, ",") { + p = strings.TrimSpace(p) + if p == "" || strings.HasPrefix(p, "openai-insecure-api-key.") || strings.HasPrefix(p, "openai-organization.") || strings.HasPrefix(p, "openai-project.") { + continue + } + out = append(out, p) + } + } + return out +} + +// resolveRealtimeModel finds the model's provider as a chat's is found; +// a bare id no provider lists (the Token Plan's hosts list nothing) goes +// to the one DashScope provider turned on, when there is one. +func resolveRealtimeModel(asked string) (provider.Provider, string, int, string) { + if p, model, ok := provider.Resolve(asked); ok { + return p, model, 0, "" + } + if off, isOff := provider.SwitchedOff(asked); isOff { + return provider.Provider{}, "", http.StatusNotFound, switchedOff(off, asked) + } + if strings.Contains(asked, "/") { + return provider.Provider{}, "", http.StatusNotFound, unknownModel(asked, "") + } + var found []provider.Provider + for _, p := range provider.All() { + if p.On() && !p.DecideOnly() && dashScopeBase(p.OpenAIBase()) { + found = append(found, p) + } + } + switch len(found) { + case 1: + return found[0], asked, 0, "" + case 0: + return provider.Provider{}, "", http.StatusNotFound, unknownModel(asked, "") + } + ids := make([]string, len(found)) + for i, p := range found { + ids[i] = p.ID + "/" + asked + } + return provider.Provider{}, "", http.StatusNotFound, fmt.Sprintf("more than one provider may serve %s: name one, as %s", asked, strings.Join(ids, " or ")) +} + +func dashScopeBase(base string) bool { + return strings.HasSuffix(strings.TrimRight(base, "/"), "/compatible-mode/v1") +} + +// realtimeURL is where the provider takes a realtime session for model, +// or why it takes none. +func realtimeURL(p provider.Provider, model string) (string, string) { + base := strings.TrimRight(p.OpenAIBase(), "/") + if base == "" { + return "", p.Name + " has no OpenAI-style API, so no Realtime API" + } + u, err := url.Parse(base) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") { + return "", p.Name + "'s address isn't one a WebSocket is opened at" + } + if dashScopeBase(base) { + u.Path = strings.TrimSuffix(strings.TrimRight(u.Path, "/"), "/compatible-mode/v1") + "/api-ws/v1/realtime" + } else { + u.Path = strings.TrimRight(u.Path, "/") + "/realtime" + } + q := u.Query() + q.Set("model", model) + u.RawQuery = q.Encode() + return u.String(), "" +} + +// dialRealtime opens the session at the provider's realtime address, +// signed as its requests are. Its connection lives as long as ctx; the +// handshake has realtimeDial. A refusal's code is the vendor's. +func (s *Server) dialRealtime(ctx context.Context, r *http.Request, p provider.Provider, u string, subprotocols []string) (*websocket.Conn, int, error) { + ctx = s.metered(p.Via(ctx), p, "") // counted against its MaxRPM (rpm.go) + dctx, cancel := context.WithCancel(ctx) + timer := time.AfterFunc(realtimeDial, cancel) + defer timer.Stop() + req, err := http.NewRequestWithContext(dctx, http.MethodGet, u, nil) + if err != nil { + cancel() + return nil, http.StatusBadRequest, err + } + stampUA(dctx, p, req.Header) + if p.IsRemoteMagpie() { + req.Header.Set("User-Agent", "magpie/"+Version) + passOnCaller(dctx, req) + } + // OpenAI's beta Realtime API asks for its header + if v := r.Header.Get("OpenAI-Beta"); v != "" { + req.Header.Set("OpenAI-Beta", v) + } + if err := p.Sign(dctx, req, provider.Chat, nil); err != nil { + cancel() + return nil, http.StatusBadGateway, err + } + conn, res, err := websocket.Dial(dctx, u, &websocket.DialOptions{ + HTTPClient: &http.Client{Transport: s.client.Transport, CheckRedirect: provider.KeepsCredentials}, + HTTPHeader: req.Header, + Subprotocols: subprotocols, + }) + if err != nil { + timedOut := !timer.Stop() && ctx.Err() == nil + cancel() + host := provider.HostOf(u) + if res != nil && res.StatusCode >= 300 { + var b []byte + if res.Body != nil { + b, _ = io.ReadAll(io.LimitReader(res.Body, 64<<10)) + res.Body.Close() + } + hint := "" + if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed { + hint = " — " + p.Name + " may not serve the Realtime API" + } + return nil, res.StatusCode, fmt.Errorf("%s: %d %s%s%s", host, res.StatusCode, http.StatusText(res.StatusCode), vendorSaid(vendorMessage(bytes.TrimSpace(b))), hint) + } + if timedOut { + return nil, http.StatusGatewayTimeout, fmt.Errorf("%s didn't open the session in %s", host, realtimeDial) + } + return nil, http.StatusBadGateway, fmt.Errorf("%s: %v", host, err) + } + // the connection is the session's: cancel ends it with ctx + context.AfterFunc(ctx, cancel) + return conn, http.StatusSwitchingProtocols, nil +} + +// realtimeMask masks the client's frames and puts the values back in the +// vendor's. +type realtimeMask struct { + ctx context.Context + m gwmw.Masker +} + +// out is a client's frame masked, or the error to hold it back for. +func (rm *realtimeMask) out(b []byte) ([]byte, error) { + got, err := gwmw.Safely(func() []byte { + var hits []gwmw.Hit + switch t := rm.m.(type) { + case gwmw.ContextTeller: + b, hits = t.JSONHitsContext(rm.ctx, b) + case gwmw.Teller: + b, hits = t.JSONHits(b) + default: + b, _ = rm.m.JSON(b) + return b + } + if err := blocked(hitsOf(hits)); err != nil { + panic(err) + } + return b + }) + return got, err +} + +// in is a vendor's frame with the masked values back. +func (rm *realtimeMask) in(b []byte) []byte { + return []byte(rm.m.Restore(string(b), true)) +} + +// audioFrame: a frame that carries base64 audio and nothing else, which +// isn't masked (a run of base64 can look like a key) or read for values. +func audioFrame(typ string) bool { + return typ == "input_audio_buffer.append" || strings.HasSuffix(typ, "audio.delta") +} + +type realtimeSession struct { + s *Server + r *http.Request + c candidate + asked string + mask *realtimeMask + + mu sync.Mutex + total Usage + lastErr string +} + +// pipe passes frames both ways until one side ends, then closes the +// other with the same code; it gives the session's status and, for one +// that broke, why. +func (rs *realtimeSession) pipe(ctx context.Context, client, up *websocket.Conn) (int, string) { + type end struct { + fromClient bool + err error + } + ends := make(chan end, 2) + go func() { ends <- end{true, rs.copy(ctx, client, up, true)} }() + go func() { ends <- end{false, rs.copy(ctx, up, client, false)} }() + e := <-ends + code, reason := websocket.CloseStatus(e.err), "" + var ce websocket.CloseError + if errors.As(e.err, &ce) { + reason = ce.Reason + } + status, why := http.StatusOK, "" + host := provider.HostOf(rs.c.p.OpenAIBase()) + var held realtimeHeld + switch { + case errors.As(e.err, &held): + // a frame masking held back: the session ends, nothing of it sent + status, why = maskStatus(held.err), held.err.Error() + code, reason = websocket.StatusPolicyViolation, trimReason(why) + case code == -1 || code == websocket.StatusNoStatusRcvd || code == websocket.StatusAbnormalClosure || code == websocket.StatusTLSHandshake: + if e.fromClient { + code, reason = websocket.StatusGoingAway, "" + } else { + status, why = http.StatusBadGateway, host+" ended the session: "+e.err.Error() + code, reason = websocket.StatusInternalError, trimReason(why) + } + case !e.fromClient && code != websocket.StatusNormalClosure && code != websocket.StatusGoingAway: + status, why = http.StatusBadGateway, fmt.Sprintf("%s closed the session %d %s", host, code, reason) + } + // both closed at once: each waits for its peer's close frame + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); client.Close(code, reason) }() + go func() { defer wg.Done(); up.Close(code, reason) }() + wg.Wait() + <-ends + return status, why +} + +// trimReason fits a close frame's reason, 123 bytes at most. +func trimReason(s string) string { + if len(s) <= 123 { + return s + } + s = s[:120] + for len(s) > 0 && !utf8Start(s[len(s)-1]) { + s = s[:len(s)-1] + } + if len(s) > 0 { + s = s[:len(s)-1] + } + return s + "…" +} + +func utf8Start(b byte) bool { return b&0xC0 != 0x80 } + +// realtimeHeld is a client's frame masking wouldn't let go. +type realtimeHeld struct{ err error } + +func (h realtimeHeld) Error() string { return h.err.Error() } + +// copy passes from's frames to to, masking a client's and counting the +// vendor's usage, until from ends. +func (rs *realtimeSession) copy(ctx context.Context, from, to *websocket.Conn, fromClient bool) error { + for { + typ, b, err := from.Read(ctx) + if err != nil { + return err + } + if typ == websocket.MessageText { + kind := gjson.GetBytes(b, "type").String() + switch { + case audioFrame(kind): + case fromClient && rs.mask != nil: + if b, err = rs.mask.out(b); err != nil { + return realtimeHeld{err} + } + case !fromClient: + rs.heard(kind, b) + if rs.mask != nil { + b = rs.mask.in(b) + } + } + } + if err := to.Write(ctx, typ, b); err != nil { + return err + } + } +} + +// heard counts a vendor event: a response.done's usage is recorded as a +// call of its own in the usage ledger, an error kept for the record. +func (rs *realtimeSession) heard(kind string, b []byte) { + switch kind { + case "error": + rs.mu.Lock() + rs.lastErr = gjson.GetBytes(b, "error.message").String() + rs.mu.Unlock() + case "response.done": + u := gjson.GetBytes(b, "response.usage") + if !u.Exists() { + return + } + in, out := int(u.Get("input_tokens").Int()), int(u.Get("output_tokens").Int()) + cached := int(u.Get("input_token_details.cached_tokens").Int()) + if cached == 0 { + cached = int(u.Get("input_tokens_details.cached_tokens").Int()) + } + cached = min(cached, in) + in -= cached // the ledger's input leaves out what was read from the cache + rs.mu.Lock() + rs.total.Input += in + rs.total.Output += out + rs.total.CacheRead += cached + rs.mu.Unlock() + c := rs.c + keyID, keyName := "", "" + if c.p.Account == nil && c.p.Key != "" { + keyID, keyName = provider.KeyID(c.p.Key), c.p.KeyName + } + who := callerOf(rs.r) + status := http.StatusOK + if st := gjson.GetBytes(b, "response.status").String(); st == "failed" { + status = http.StatusBadGateway + } + appendUsage(rs.r, usage.Record{Operation: "realtime", Time: time.Now(), Agent: who.agent, Via: who.via, Provider: c.p.ID, Host: c.p.Where(), Model: c.model, Requested: rs.asked, + ProviderKeyID: keyID, ProviderKeyName: keyName, ProviderAccount: accountOf(c.p), + Input: in, Output: out, CacheRead: cached, Status: status, Session: sessionOf(rs.r.Header)}) + } +} diff --git a/internal/gateway/realtime_test.go b/internal/gateway/realtime_test.go new file mode 100644 index 000000000..04b301121 --- /dev/null +++ b/internal/gateway/realtime_test.go @@ -0,0 +1,357 @@ +package gateway + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/coder/websocket" + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/budget" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" +) + +// rtUp is a realtime vendor: DashScope's /api-ws/v1/realtime and OpenAI's +// /v1/realtime. Each text frame comes back as {"type":"echo","got":…}, +// a binary frame as it came, a response.create gets a response.done with +// usage, and {"type":"close.me"} closes the session 1000 "bye". +type rtUp struct { + mu sync.Mutex + opened []*http.Request + frames []string + closed chan websocket.StatusCode // how each session's client side ended + url string +} + +func (u *rtUp) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api-ws/v1/realtime" && r.URL.Path != "/v1/realtime" { + http.Error(w, `{"error":{"message":"no such path"}}`, http.StatusNotFound) + return + } + if r.Header.Get("Authorization") != "Bearer sk-sp-k" { + http.Error(w, `{"error":{"message":"bad key"}}`, http.StatusUnauthorized) + return + } + u.mu.Lock() + u.opened = append(u.opened, r.Clone(context.Background())) + u.mu.Unlock() + c, err := websocket.Accept(w, r, &websocket.AcceptOptions{Subprotocols: []string{"realtime"}}) + if err != nil { + return + } + defer c.CloseNow() + ctx := context.Background() + for { + typ, b, err := c.Read(ctx) + if err != nil { + u.closed <- websocket.CloseStatus(err) + return + } + if typ == websocket.MessageBinary { + c.Write(ctx, typ, b) + continue + } + u.mu.Lock() + u.frames = append(u.frames, string(b)) + u.mu.Unlock() + switch gjson.GetBytes(b, "type").String() { + case "close.me": + c.Close(websocket.StatusNormalClosure, "bye") + u.closed <- websocket.StatusNormalClosure + return + case "response.create": + c.Write(ctx, websocket.MessageText, []byte(`{"type":"response.audio.delta","delta":"QUJD"}`)) + c.Write(ctx, websocket.MessageText, []byte(`{"type":"response.done","response":{"status":"completed","usage":{"input_tokens":100,"output_tokens":20,"input_token_details":{"cached_tokens":40}}}}`)) + default: + c.Write(ctx, websocket.MessageText, []byte(`{"type":"echo","got":`+string(b)+`}`)) + } + } +} + +func (u *rtUp) sessions() int { + u.mu.Lock() + defer u.mu.Unlock() + return len(u.opened) +} + +// rtServe has a Token Plan provider at the fake's DashScope base and an +// OpenAI-style one at its /v1, and the gateway served as the real server +// does; every session ends before the test's folders go. +func rtServe(t *testing.T) (*rtUp, *Server, *httptest.Server) { + t.Helper() + fresh(t) + u := &rtUp{closed: make(chan websocket.StatusCode, 16)} + up := httptest.NewServer(u) + t.Cleanup(up.Close) + u.url = up.URL + for _, p := range []provider.Provider{ + {ID: "plan", Name: "Plan", Key: "sk-sp-k", Chat: up.URL + "/compatible-mode/v1", Models: []string{"qwen-audio-3.0-realtime-plus"}}, + {ID: "oa", Name: "OA", Key: "sk-sp-k", Chat: up.URL + "/v1", Models: []string{"gpt-realtime"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + s, ts := sockServer(t) + t.Cleanup(func() { + s.realtimes.end() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + s.realtimes.wait(ctx) + }) + return u, s, ts +} + +func rtDial(t *testing.T, ts *httptest.Server, path string, h http.Header, protos ...string) (*websocket.Conn, *http.Response, error) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + c, resp, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(ts.URL, "http")+path, &websocket.DialOptions{HTTPHeader: h, Subprotocols: protos}) + if err == nil { + t.Cleanup(func() { c.CloseNow() }) + } + return c, resp, err +} + +func rtRead(t *testing.T, c *websocket.Conn) (websocket.MessageType, string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + typ, b, err := c.Read(ctx) + if err != nil { + t.Fatalf("read: %v", err) + } + return typ, string(b) +} + +func rtSend(t *testing.T, c *websocket.Conn, typ websocket.MessageType, s string) { + t.Helper() + if err := c.Write(context.Background(), typ, []byte(s)); err != nil { + t.Fatal(err) + } +} + +func rtClosed(t *testing.T, u *rtUp) websocket.StatusCode { + t.Helper() + select { + case st := <-u.closed: + return st + case <-time.After(30 * time.Second): + t.Fatal("the vendor's side never ended") + return 0 + } +} + +// A Token Plan's realtime model: the session opens at the plan host's +// /api-ws/v1/realtime with the plan's key and the provider's own model id, +// text and audio frames go both ways as they are, a response.done's usage +// is recorded, and the vendor's close reaches the client with its code. +func TestRealtimeTokenPlanSession(t *testing.T) { + u, _, ts := rtServe(t) + c, resp, err := rtDial(t, ts, "/v1/realtime?model=plan/qwen-audio-3.0-realtime-plus", nil) + if err != nil { + t.Fatalf("%v %v", err, resp) + } + if u.sessions() != 1 { + t.Fatalf("%d sessions", u.sessions()) + } + got := u.opened[0] + if got.URL.Path != "/api-ws/v1/realtime" || got.URL.Query().Get("model") != "qwen-audio-3.0-realtime-plus" { + t.Fatalf("opened %s", got.URL) + } + update := `{"type":"session.update","session":{"modalities":["text","audio"],"voice":"Cherry"}}` + rtSend(t, c, websocket.MessageText, update) + if typ, b := rtRead(t, c); typ != websocket.MessageText || gjson.Get(b, "got").Raw != update { + t.Fatalf("echo %v %s", typ, b) + } + rtSend(t, c, websocket.MessageBinary, "\x00\x01pcm") + if typ, b := rtRead(t, c); typ != websocket.MessageBinary || b != "\x00\x01pcm" { + t.Fatalf("binary %v %q", typ, b) + } + rtSend(t, c, websocket.MessageText, `{"type":"input_audio_buffer.append","audio":"UklGRg=="}`) + rtRead(t, c) + rtSend(t, c, websocket.MessageText, `{"type":"response.create"}`) + if _, b := rtRead(t, c); b != `{"type":"response.audio.delta","delta":"QUJD"}` { + t.Fatalf("delta %s", b) + } + if _, b := rtRead(t, c); gjson.Get(b, "type").String() != "response.done" { + t.Fatalf("done %s", b) + } + rtSend(t, c, websocket.MessageText, `{"type":"close.me"}`) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + _, _, err = c.Read(ctx) + var ce websocket.CloseError + if !errors.As(err, &ce) || ce.Code != websocket.StatusNormalClosure || ce.Reason != "bye" { + t.Fatalf("the client's session ended %v", err) + } + rtClosed(t, u) + + var recs []usage.Record + for i := 0; i < 250; i++ { + if recs = usage.Load(time.Time{}); len(recs) >= 1 { + break + } + time.Sleep(20 * time.Millisecond) + } + if len(recs) != 1 || recs[0].Operation != "realtime" || recs[0].Provider != "plan" || recs[0].Model != "qwen-audio-3.0-realtime-plus" || + recs[0].Requested != "plan/qwen-audio-3.0-realtime-plus" || recs[0].Input != 60 || recs[0].CacheRead != 40 || recs[0].Output != 20 || recs[0].Status != 200 { + t.Fatalf("usage %+v", recs) + } +} + +// An OpenAI-style provider's session opens at base + /realtime; the +// client's subprotocols go on, less one carrying a key, and the vendor's +// choice comes back. A bare id no provider lists goes to the one +// DashScope provider. The client closing ends the vendor's side too. +func TestRealtimeOpenAIStyleAndClientClose(t *testing.T) { + u, _, ts := rtServe(t) + c, resp, err := rtDial(t, ts, "/v1/realtime?model=oa/gpt-realtime", http.Header{"OpenAI-Beta": {"realtime=v1"}}, "realtime", "openai-insecure-api-key.sk-leak") + if err != nil { + t.Fatalf("%v %v", err, resp) + } + got := u.opened[0] + if got.URL.Path != "/v1/realtime" || got.URL.Query().Get("model") != "gpt-realtime" || got.Header.Get("OpenAI-Beta") != "realtime=v1" { + t.Fatalf("opened %s %v", got.URL, got.Header) + } + if p := got.Header.Get("Sec-WebSocket-Protocol"); strings.Contains(p, "sk-leak") || !strings.Contains(p, "realtime") { + t.Fatalf("the vendor was offered %q", p) + } + if c.Subprotocol() != "realtime" { + t.Fatalf("subprotocol %q", c.Subprotocol()) + } + c.Close(websocket.StatusNormalClosure, "") + if st := rtClosed(t, u); st != websocket.StatusNormalClosure { + t.Fatalf("the vendor's side ended %d", st) + } + + c, resp, err = rtDial(t, ts, "/realtime?model=qwen3-livetranslate-flash-realtime", nil) + if err != nil { + t.Fatalf("%v %v", err, resp) + } + if got := u.opened[1]; got.URL.Path != "/api-ws/v1/realtime" || got.URL.Query().Get("model") != "qwen3-livetranslate-flash-realtime" { + t.Fatalf("opened %s", got.URL) + } + c.Close(websocket.StatusNormalClosure, "") + rtClosed(t, u) +} + +// Every guard an HTTP request meets holds a realtime session: no Upgrade +// is told what to send, no model and an unknown one are refused, a web +// page elsewhere, a sandboxed frame (Origin null), a localhost subdomain +// and a rebound name can't open one, a remote caller needs a key, a key +// held to other models is refused, and a vendor's refusal comes back as +// its status. None reaches the vendor but the last. +func TestRealtimeGuards(t *testing.T) { + u, _, ts := rtServe(t) + t.Setenv("MAGPIE_ADDR", "") + t.Setenv("MAGPIE_PUBLIC_URL", "") + budget.Forget() + keys, secrets := newCaller(t, "Laptop", "Held") + if _, err := access.Update("models-key", access.Change{Key: keys[1].ID, Models: []string{"oa/*"}}); err != nil { + t.Fatal(err) + } + res, err := http.Get(ts.URL + "/v1/realtime?model=plan/qwen-audio-3.0-realtime-plus") + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(res.Body) + res.Body.Close() + if res.StatusCode != http.StatusUpgradeRequired || !strings.Contains(string(b), "WebSocket") { + t.Errorf("a plain GET: %d %s", res.StatusCode, b) + } + remote := func(secret string) http.Header { + h := http.Header{"X-Test-Remote": {"192.168.1.9:5000"}} + if secret != "" { + h.Set("Authorization", "Bearer "+secret) + } + return h + } + const plan = "/v1/realtime?model=plan/qwen-audio-3.0-realtime-plus" + refused := func(what, path string, h http.Header, want int) { + t.Helper() + _, resp, err := rtDial(t, ts, path, h) + if err == nil { + t.Errorf("%s opened a session", what) + return + } + if resp == nil || resp.StatusCode != want { + t.Errorf("%s: %v %v, want %d", what, err, resp, want) + } + } + refused("no model", "/v1/realtime", nil, http.StatusBadRequest) + refused("an unknown model", "/v1/realtime?model=nope/x", nil, http.StatusNotFound) + for _, origin := range []string{"https://evil.example", "null", "http://evil.localhost:3425"} { + refused("Origin "+origin, plan, http.Header{"Origin": {origin}}, http.StatusForbidden) + } + _, resp, err := rtDial(t, ts, plan, http.Header{ + "X-Test-Host": {"rebind.attacker.example:3425"}, + "User-Agent": {"Mozilla/5.0 (Macintosh) Chrome/140"}, "Sec-Fetch-Site": {"same-origin"}, "Sec-Fetch-Mode": {"websocket"}, + }) + if err == nil || resp == nil || resp.StatusCode < 400 { + t.Errorf("a rebound page: %v %v", err, resp) + } + refused("a remote caller without a key", plan, remote(""), http.StatusUnauthorized) + refused("a key held to other models", plan, remote(secrets[1]), http.StatusForbidden) + if u.sessions() != 0 { + t.Fatalf("a refused session reached the vendor") + } + + // a key: served + c, resp, err := rtDial(t, ts, plan, remote(secrets[0])) + if err != nil { + t.Fatalf("keyed: %v %v", err, resp) + } + c.Close(websocket.StatusNormalClosure, "") + rtClosed(t, u) + + // the vendor refusing the key: its status and message + if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "sk-sp-wrong", Chat: u.url + "/compatible-mode/v1", Models: []string{"qwen-audio-3.0-realtime-plus"}}); err != nil { + t.Fatal(err) + } + _, resp, err = rtDial(t, ts, plan, nil) + if err == nil || resp == nil || resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("a refused key: %v %v", err, resp) + } + b, _ = io.ReadAll(resp.Body) + if !strings.Contains(string(b), "bad key") { + t.Errorf("the vendor's message: %s", b) + } +} + +// With secrets kept, a client's text frame goes out masked and the +// vendor's frames get the values back; an audio frame goes as it is. +func TestRealtimeMasked(t *testing.T) { + u, _, ts := rtServe(t) + if err := settings.Save(settings.Settings{Redact: true}); err != nil { + t.Fatal(err) + } + c, resp, err := rtDial(t, ts, "/v1/realtime?model=plan/qwen-audio-3.0-realtime-plus", nil) + if err != nil { + t.Fatalf("%v %v", err, resp) + } + secret := "sk-ant-api03-" + strings.Repeat("Ab3x", 20) + rtSend(t, c, websocket.MessageText, `{"type":"conversation.item.create","item":{"type":"message","role":"user","content":[{"type":"input_text","text":"key `+secret+`"}]}}`) + _, b := rtRead(t, c) + if !strings.Contains(b, secret) { + t.Errorf("the echo didn't get the value back: %s", b) + } + u.mu.Lock() + sent := u.frames[0] + u.mu.Unlock() + if strings.Contains(sent, secret) || !strings.Contains(sent, "key ") { + t.Fatalf("the vendor was sent %s", sent) + } + c.Close(websocket.StatusNormalClosure, "") + rtClosed(t, u) +}