diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f146be53d..a980dcd0d 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -50,7 +50,7 @@ another for the conversation instead of listing every id | 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. 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) | +| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), OpenAI's unary `/v1/responses/compact` (also without `/v1`; `responses_compact.go`, #7281: relayed as it came to `/responses/compact` under the provider's base only for a key's provider asking the model on Responses, its sealed item's writer remembered as a native compaction's is; any other candidate is left out, and none left is a 400 saying to compact on `/responses`), `/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`). A model its vendor lists with the maker's name left off is merged by the model it is (`mergeKeyIn`, `catalog.Unprefixed`): Kimi Code's `k3.1-pro`, whose entry in the provider's own models.dev catalog names `moonshotai/kimi-k3.1-pro`, is in `auto/kimi-k3.1-pro` with OpenCode Go's and Devin's `kimi-k3.1-pro` (tmr11235 on X, who had to add it by hand). The canonical alone never merges a model, as models.dev gives Kimi Code's `k3.1-pro-highspeed` the canonical `kimi-k3.1-pro` and `k3-256k` `kimi-k3`: the id must be the canonical's with a maker's name (letters) taken off the front, or go on past it to a model models.dev knows by that name before the whole id (`k3.1-pro-highspeed` is `kimi-k3.1-pro-highspeed`; `k3-256k` stays its own). A relay whose catalog says nothing of its `k3.1-pro` is not merged on a guess. The id such a model had a group by before (`auto-k3-1-pro`, Kimi Code with Kimi Code China) is the group's `Former`, so an agent still set to `auto/k3.1-pro` is served (`TestFoundGroupTakesAModelListedWithoutItsMaker`, `TestFoundGroupOfUnprefixedIDsAloneIsTheModels`). 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) | diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 198184813..42d84d70f 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1158,6 +1158,8 @@ func (s *Server) routes() *routeMux { mux.HandleFunc("POST /chat/completions", s.handle(provider.Chat)) mux.HandleFunc("POST /v1/responses", s.handle(provider.Responses)) mux.HandleFunc("POST /responses", s.handle(provider.Responses)) + mux.HandleFunc("POST /v1/responses/compact", s.responsesCompact) + mux.HandleFunc("POST /responses/compact", s.responsesCompact) mux.HandleFunc("GET /v1/responses", s.responsesOverHTTP) mux.HandleFunc("GET /responses", s.responsesOverHTTP) mux.HandleFunc("POST /v1/messages", keepsSignIn(s.handle(provider.Anthropic))) @@ -2670,7 +2672,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // the only place it is counted, and as a plain turn it read as no // compaction at all (shangyuan0818 on Discord), the OTel export left // it to that transcript, and its reply ended the agent's turn - if call.Kind == "" && factsOf(from, plain).compact { + if call.Kind == "" && (factsOf(from, plain).compact || unaryCompact(r)) { call.Kind = KindCompact } // Claude Code's auto mode classifier and AgentSummary name themselves @@ -3341,6 +3343,17 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro return } } + // /responses/compact goes only where it is the provider's own + // route (responses_compact.go, #7281) + if unaryCompact(r) { + var left bool + if cands, pl, left = s.unaryCompactCarriers(cands, pl); !left { + call.Status, call.Error = 400, "unary compaction not served" + writeError(w, from, 400, unaryCompactError(call.Model)) + turnedAway() + return + } + } } var accountHeld bool // every candidate was an account or key the calling key may not use if keyHeld || accHeld { @@ -3769,7 +3782,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // (#1099) var sealedBy *candidate wantWhole := wantsWhole(r.Context()) - if from == provider.Responses && compactionTriggerIn(body) { + if from == provider.Responses && (compactionTriggerIn(body) || unaryCompact(r)) { watch := &compactionWatch{w: w} w = watch defer func() { @@ -6118,6 +6131,13 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P // compaction is on, goes as it came: a translation would leave it out // (#1099) keep := s.keepsCompaction(from, p, model, body) + // /responses/compact goes as it came, and only to a provider that + // has the route (responses_compact.go) + compact := from == provider.Responses && unaryCompact(r) + if compact { + keep, relayable = true, s.compactsUnary(p, model) + relay = relayable + } // Codex's custom tools, to a model that turned them away before // (custom_tool.go, #2656): translated on the client's own API, which // offers them as functions @@ -6184,6 +6204,9 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P } if keep { msg := fmt.Sprintf("%s doesn't serve %s on the Responses API, so Codex's native compaction can't be asked of it", p.Name, model) + if compact { + msg = unaryCompactError(model) + } return writeError(w, from, 400, msg), msg } to := s.usable(p, model) @@ -7167,6 +7190,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. body = withBodyEffort(proto, body, effort) } path := upstreamPath(p, proto, upstream) + if proto == provider.Responses && unaryCompact(r) { + path += "/compact" // responses_compact.go + } if proto == provider.Gemini && p.IsVertex() && geminiWhole { path = provider.VertexWholePath(upstream) // answered as one JSON body } diff --git a/internal/gateway/key_limit.go b/internal/gateway/key_limit.go index 57d7ac029..598326d8b 100644 --- a/internal/gateway/key_limit.go +++ b/internal/gateway/key_limit.go @@ -157,7 +157,7 @@ func protoOfPath(path string) provider.Protocol { return provider.Anthropic case strings.HasPrefix(path, "/v1beta/"): return provider.Gemini - case strings.HasSuffix(path, "/responses"): + case strings.HasSuffix(path, "/responses"), strings.HasSuffix(path, "/responses/compact"): return provider.Responses } return provider.Chat diff --git a/internal/gateway/responses_compact.go b/internal/gateway/responses_compact.go new file mode 100644 index 000000000..79e2d1fb1 --- /dev/null +++ b/internal/gateway/responses_compact.go @@ -0,0 +1,69 @@ +package gateway + +import ( + "context" + "fmt" + "net/http" + + "github.com/yetone/magpie/internal/provider" +) + +// POST /v1/responses/compact (and /responses/compact) is OpenAI's unary +// compaction: the conversation in, one response.compaction object back, +// its compaction item sealed (encrypted_content) by the server that wrote +// it. Pi's Responses compaction extension asks it of a provider set to the +// Responses API (#7281); on the generic route it was the 404 of an unknown +// path, and never reached the upstream. +// +// It is relayed as it came, to /responses/compact under the provider's +// Responses base, only where that is the provider's own API: a key's +// provider whose model is asked on Responses (OpenAI, a relay or a local +// server speaking it, another magpie). Nothing else has the route, and a +// translation can't make the sealed item, so anywhere else — a model on +// Chat or Messages only, a subscription or plugin account — is a 400 +// saying so, as CodexPath's is for magpie's models, for the client to fall +// back to compacting on /responses. Who sealed the item is remembered +// (wroteCheckpoint), so a later /responses carrying it goes back there +// (#1099). A ChatGPT account isn't asked it here: its backend's compaction +// is reached on CodexPath, as Codex sends it. + +type unaryCompactKey struct{} + +// responsesCompact serves POST /v1/responses/compact. +func (s *Server) responsesCompact(w http.ResponseWriter, r *http.Request) { + body, ok := s.requestBody(w, r, provider.Responses) + if !ok { + return + } + body, _, err := requestModel(body) + if err != nil { + writeError(w, provider.Responses, 400, err.Error()) + return + } + r = r.WithContext(context.WithValue(r.Context(), unaryCompactKey{}, true)) + s.serveAgent(w, r, provider.Responses, body) +} + +// unaryCompact is whether r is a /responses/compact request. +func unaryCompact(r *http.Request) bool { + v, _ := r.Context().Value(unaryCompactKey{}).(bool) + return v +} + +// compactsUnary is whether model at p can be asked /responses/compact: a +// key's provider (no account) whose wire carries Responses and asks model +// on it. +func (s *Server) compactsUnary(p provider.Provider, model string) bool { + return p.Account == nil && s.carriesCompaction(p, model) +} + +// unaryCompactCarriers keeps of cands those compactsUnary. +func (s *Server) unaryCompactCarriers(cands []candidate, pl planned) ([]candidate, planned, bool) { + return keepCandidates(cands, pl, func(c candidate) bool { return s.compactsUnary(c.p, c.model) }) +} + +// unaryCompactError is what a /responses/compact for model is told when +// nothing that serves it has the route. +func unaryCompactError(model string) string { + return fmt.Sprintf("/responses/compact is not supported for %s: it is relayed only to a provider whose own API is Responses (an API key's provider asking the model on Responses), and none of those serves %s; compact on /responses instead", model, model) +} diff --git a/internal/gateway/responses_compact_test.go b/internal/gateway/responses_compact_test.go new file mode 100644 index 000000000..95810eaa2 --- /dev/null +++ b/internal/gateway/responses_compact_test.go @@ -0,0 +1,77 @@ +package gateway + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// #7281 (jinpwng): Pi's Responses compaction extension asks POST +// /v1/responses/compact of a provider set to the Responses API. magpie +// answered it the 404 of an unknown path and never asked the upstream. +// From the generic /v1 base URL, and from the bare one, a key's provider +// on Responses is asked once, at /responses/compact under its base, and +// its unary compaction object comes back as it came, the sealed item +// untouched; the next /responses carrying it goes back there (#1099). +func TestResponsesCompactRelayed(t *testing.T) { + const reply = `{"id":"resp_c1","object":"response.compaction","created_at":1,"output":[{"type":"compaction","id":"cmp_1","encrypted_content":"gAAAAopaque=="}],"usage":{"input_tokens":120,"output_tokens":30,"total_tokens":150}}` + for _, path := range []string{"/v1/responses/compact", "/responses/compact"} { + t.Run(path, func(t *testing.T) { + f := &fake{t: t, ctype: "application/json", reply: reply} + setup(t, provider.Responses, f) + // an earlier compaction in the input stays the client's: not + // magpie's summary path (handle's codexCompact) + code, body := post(t, path, `{"model":"fake/m1","instructions":"summarise", + "input":[{"type":"compaction","encrypted_content":"gAAAAearlier=="},{"type":"message","role":"user","content":[{"type":"input_text","text":"fix the bug"}]}]}`) + if code != 200 { + t.Fatalf("%d %s", code, body) + } + if f.calls != 1 || f.path != "/v1/responses/compact" { + t.Fatalf("upstream asked %d times, at %q", f.calls, f.path) + } + var got map[string]any + if err := json.Unmarshal(f.got, &got); err != nil { + t.Fatalf("upstream got %s", f.got) + } + if got["model"] != "m1" || !strings.Contains(string(f.got), "gAAAAearlier==") || strings.Contains(string(f.got), `"stream":true`) { + t.Errorf("upstream got %s", f.got) + } + var out struct { + Object string `json:"object"` + Output []struct { + Type string `json:"type"` + Enc string `json:"encrypted_content"` + } `json:"output"` + } + if err := json.Unmarshal([]byte(body), &out); err != nil || out.Object != "response.compaction" || len(out.Output) != 1 || out.Output[0].Enc != "gAAAAopaque==" { + t.Fatalf("client got %s", body) + } + // who sealed it is remembered, for the next /responses + cp, ok := checkpointOf([]byte(`{"input":[{"type":"compaction","encrypted_content":"gAAAAopaque=="}]}`)) + if !ok || cp.Provider != "fake" { + t.Errorf("sealed by %+v, %v", cp, ok) + } + }) + } +} + +// A model that isn't asked on Responses at its provider has no +// /responses/compact: the client is told so in a 400 it can fall back +// on, not a 404, and the upstream is never asked a translation of it. +func TestResponsesCompactRefusedOffResponses(t *testing.T) { + for _, path := range []string{"/v1/responses/compact", "/responses/compact"} { + t.Run(path, func(t *testing.T) { + f := &fake{t: t, ctype: "application/json", reply: `{}`} + setup(t, provider.Chat, f) + code, body := post(t, path, `{"model":"fake/m1","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}]}`) + if code != 400 || !strings.Contains(body, "/responses/compact is not supported for fake/m1") || !strings.Contains(body, "invalid_request_error") { + t.Fatalf("%d %s", code, body) + } + if f.calls != 0 { + t.Errorf("upstream asked %d times: %s", f.calls, f.got) + } + }) + } +}