diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index dcb3c6b77..add8cab12 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -29,7 +29,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. A Codex turn that names itself Claude Code is Codex's: OpenAI's Codex plugin for Claude Code (/codex:rescue, /codex:review) runs `codex app-server` with clientInfo "Claude Code", which Codex sends as its originator and User-Agent, and only Codex's turn headers (`x-codex-window-id`, `x-codex-turn-metadata`) tell it apart from Claude Code's own requests (`codexForClaudeCode`); an app that runs Codex as its own engine under its own name (Lody) stays that app. VS Code's Agents window runs `codex app-server` as `vscode_agent_host`, its originator and User-Agent: its calls are counted under VS Code (`vscodeAgentHostUA` in [`vscode.go`](../../internal/agent/vscode.go)), and its turns are Codex's for every Codex rule (`fromCodex`, `hostedCodex`), so one of Codex's own models asked there goes on Codex's sign-in (`codexOwnOffMagpie`) rather than 404; only Codex's own names (`codexNamed`) are kept as Codex's shape for a test asked as Codex (`TestVSCodeAgentHostIsCodex`, `TestVSCodeAgentHostOwnModelGoesOnSignIn`, `TestVSCodeAgentHostNotCodexTestShape`). Claude Science, whose User-Agent is the Anthropic SDK's, is told by its client's `X-Anthropic-Surface: operon` (`isClaudeScience`). It is listed every model as `claude-magpie-` (`scienceModels`; its picker keeps only a `claude-` id whose name isn't a lower-case slug), and a Claude id magpie doesn't serve (its default before a pick, its haiku side tasks) goes to the model its last turn with tools was on, else the first it is listed (`scienceTurn`, kept in `claude-science.model`). | [`gateway.go`](../../internal/gateway/gateway.go) | | WSL under NAT | On Windows, while the gateway listens on loopback alone, `serveWSL` also serves it, in plain HTTP, at each address Windows has on a WSL network (`WSLNets`: the `vEthernet (WSL…)` adapters, looked for every 10s, since WSL's VM brings its adapter up and down). That is where a distro in NAT networking reaches Windows, and what `place` writes into its agents (zaidu259434 on X: Codex in WSL failed with sharing off). `lanGuard` takes a request there as this computer's (`fromWSL`) only when it arrives at that address, from inside that network, with the WSL key: `WSLKey`, a `wsl-` secret in magpie's folder (`wsl-key`, 0600), optionally followed by `-`. It becomes a loopback request carrying `magpie` or `magpie-` (`asFromLoopback`). Anything else there, a Docker Desktop container on the same network included, is judged as another machine's. Windows' firewall still decides whether WSL gets in: WSL's network is a Public one. | [`wsl.go`](../../internal/gateway/wsl.go) | | TLS | `--tls-cert`/`--tls-key` (`MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY`) make `ListenAndServe`, `Relisten` (both through `Server.listen`) and `magpie web`'s page (`ServeTLS`) wrap the listener in `tlsListener`. A connection from another computer is `tls.Server` at once, so its plain HTTP gets net/http's 400. One from this computer (`fromThisComputer`: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (`sniffWait`), and 0x16 makes it TLS, so `URL()`, the agents, MCP servers, `ServedBy` and the healthcheck keep `http://127.0.0.1`. `certFiles.get` reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). `tlsConfig` refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). `Scheme()` gives the scheme of `LANURLs`, a scheme-less `MAGPIE_PUBLIC_URL` and the page's network links. Host and Origin checks (`foreignPage`, `rebound`) don't depend on the scheme. | [`tls.go`](../../internal/gateway/tls.go), [`lan.go`](../../internal/gateway/lan.go) | -| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; a name ending `:latest`, as the ollama CLI asks, is the bare id unless a model is really called that (`ollamaName`); the client then chats on `/v1/chat/completions`, or on Ollama's own `POST /api/chat` and `POST /api/generate` (`ollama_chat.go`, Zed's Ollama provider, super_lalalalala on Discord), which `ollamaChatBody` turns into a `/v1/chat/completions` body handed to the same `handle(provider.Chat)` on a clone of the request, so they are routed, held to a key's models and counted as it is: `messages` with `images` (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's `thinking` as `reasoning_content` and its `tool_calls` given ids where Ollama sent none, a tool result matched to its call by `tool_call_id`, else `tool_name`, else in order (one with no call is a 400), `tools`, `format` (`json` or a schema), `think` (a level is `reasoning_effort`), and `options`' `temperature`, `top_p`, `seed`, `stop`, the two penalties and a positive `num_predict` as `max_tokens` (`num_ctx`, `top_k` and the rest of Ollama's own are dropped); `ollamaWriter` turns the reply into Ollama's NDJSON lines (streamed unless `stream:false`, then one object), tool calls with their `arguments` as an object and an `id`, and a last `done` line with `done_reason` and the token counts, and an error into `{"error":"…"}` with the status `/v1` would give; a request with no messages or prompt is answered `done_reason:"load"`, as Ollama does to warm a model), `/mcp/{name}`, `/mcp/magpie/web-search`, `/mcp/magpie/vision` and `/mcp/magpie/image` with its `/mcp/magpie/image/files/{name}` (magpie's own web search, image recognition and image generation as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/magpie/goroutines` (`goroutineDump`, [`goroutines.go`](../../internal/gateway/goroutines.go), for `magpie goroutines`, #3362) answers every goroutine's stack and wait as text (`runtime/pprof`'s `goroutine` profile at debug 2) to the same callers, through `goroutinesRefused`, and is answered ahead of everything below (`dumpFirst`, around `Handler`'s wrappers and around `lanGuard` in `Front`), since it is asked for while magpie hangs: the allow list reads settings.json under its lock, and `holdCatalog` takes `provider.Hold`'s and `filememo`'s, so a stuck holder of any of them would hold the dump too; a caller `goroutinesRefused` lets in is one those let in anyway, and any other goes through them as before (`TestGoroutineDumpAnswersWhileRequestsWait`). `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A WebSocket upgrade on `/v1/responses`, `/responses` or the Codex backend's `/responses` is Responses over a WebSocket, as Codex speaks it (below, [A Responses WebSocket](#a-responses-websocket)); one on another Codex backend path is answered 426, and a plain GET on `/v1/responses` 405. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. A browser sends a preflight without credentials, so a listed origin's preflight from another computer is let past `lanGuard`'s key check to be answered here (#4931, ggbdpq: a page on another machine got 401 to its preflight and never sent the keyed request); `lanGuard` hands on only an `OPTIONS` with `Access-Control-Request-Method` whose origin is listed (`corsAllowed`). Any other origin's preflight still meets the key check: `corsGuard` passes some unlisted origins on (loopback names, the request's own origin, other schemes), and Codex's backend relay would serve their `OPTIONS` on the user's sign-in (`TestCORSPreflightFromLANReachesNothing`). It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`), and its port hands the gateway's client routes (`ClientPath`) to `Server.Front`, the same lanGuard-over-Handler the gateway's listener serves, each marked by `FromPagePort` so `local` is false for it (`viaPagePort`; `lanGuard` refuses it 403 while magpie isn't shared, saying to call the gateway's own address, and asks a gateway key otherwise): a raw TCP forward or a proxy with no forwarding header reaches that port from loopback, so no request there counts as an agent here (`TestClientPathCoversHandler` fails when a route Handler adds is in neither `ClientPath` nor its list of routes that stay on the gateway's port). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`ollama.go`](../../internal/gateway/ollama.go), [`ollama_chat.go`](../../internal/gateway/ollama_chat.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | +| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; a name ending `:latest`, as the ollama CLI asks, is the bare id unless a model is really called that (`ollamaName`); the client then chats on `/v1/chat/completions`, or on Ollama's own `POST /api/chat` and `POST /api/generate` (`ollama_chat.go`, Zed's Ollama provider, super_lalalalala on Discord), which `ollamaChatBody` turns into a `/v1/chat/completions` body handed to the same `handle(provider.Chat)` on a clone of the request, so they are routed, held to a key's models and counted as it is: `messages` with `images` (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's `thinking` as `reasoning_content` and its `tool_calls` given ids where Ollama sent none, a tool result matched to its call by `tool_call_id`, else `tool_name`, else in order (one with no call is a 400), `tools`, `format` (`json` or a schema), `think` (a level is `reasoning_effort`), and `options`' `temperature`, `top_p`, `seed`, `stop`, the two penalties and a positive `num_predict` as `max_tokens` (`num_ctx`, `top_k` and the rest of Ollama's own are dropped); `ollamaWriter` turns the reply into Ollama's NDJSON lines (streamed unless `stream:false`, then one object), tool calls with their `arguments` as an object and an `id`, and a last `done` line with `done_reason` and the token counts, and an error into `{"error":"…"}` with the status `/v1` would give; a request with no messages or prompt is answered `done_reason:"load"`, as Ollama does to warm a model), `/mcp/{name}`, `/mcp/magpie/web-search`, `/mcp/magpie/vision` and `/mcp/magpie/image` with its `/mcp/magpie/image/files/{name}` (magpie's own web search, image recognition and image generation as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/magpie/goroutines` (`goroutineDump`, [`goroutines.go`](../../internal/gateway/goroutines.go), for `magpie goroutines`, #3362) answers every goroutine's stack and wait as text (`runtime/pprof`'s `goroutine` profile at debug 2) to the same callers, through `goroutinesRefused`, and is answered ahead of everything below (`dumpFirst`, around `Handler`'s wrappers and around `lanGuard` in `Front`), since it is asked for while magpie hangs: the allow list reads settings.json under its lock, and `holdCatalog` takes `provider.Hold`'s and `filememo`'s, so a stuck holder of any of them would hold the dump too; a caller `goroutinesRefused` lets in is one those let in anyway, and any other goes through them as before (`TestGoroutineDumpAnswersWhileRequestsWait`). `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, in the mode its `settings.external_web_access` says (#5018; a ChatGPT account then searches by the same backend search, see [Which providers search for another model](#which-providers-search-for-another-model)), and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A WebSocket upgrade on `/v1/responses`, `/responses` or the Codex backend's `/responses` is Responses over a WebSocket, as Codex speaks it (below, [A Responses WebSocket](#a-responses-websocket)); one on another Codex backend path is answered 426, and a plain GET on `/v1/responses` 405. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. A browser sends a preflight without credentials, so a listed origin's preflight from another computer is let past `lanGuard`'s key check to be answered here (#4931, ggbdpq: a page on another machine got 401 to its preflight and never sent the keyed request); `lanGuard` hands on only an `OPTIONS` with `Access-Control-Request-Method` whose origin is listed (`corsAllowed`). Any other origin's preflight still meets the key check: `corsGuard` passes some unlisted origins on (loopback names, the request's own origin, other schemes), and Codex's backend relay would serve their `OPTIONS` on the user's sign-in (`TestCORSPreflightFromLANReachesNothing`). It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`), and its port hands the gateway's client routes (`ClientPath`) to `Server.Front`, the same lanGuard-over-Handler the gateway's listener serves, each marked by `FromPagePort` so `local` is false for it (`viaPagePort`; `lanGuard` refuses it 403 while magpie isn't shared, saying to call the gateway's own address, and asks a gateway key otherwise): a raw TCP forward or a proxy with no forwarding header reaches that port from loopback, so no request there counts as an agent here (`TestClientPathCoversHandler` fails when a route Handler adds is in neither `ClientPath` nor its list of routes that stay on the gateway's port). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`ollama.go`](../../internal/gateway/ollama.go), [`ollama_chat.go`](../../internal/gateway/ollama_chat.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | | Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider — in a WSL distro, the distro's own, of the ones running now — for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key; a memory call first waits beside the turn it was started with, through `codexLeads`, see the side turns below), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. A provider the user keeps out of found groups (Routing's "Leave out a provider", `provider.SetAutoGroupSkip`, `autoGroupSkip` in providers.json; chenxiang0010 on Discord) is in none of them, so a model one other provider serves is no group; the groups the user made or changed keep it. A request still naming a found group that took away goes to its model from a provider not kept out (`AutoStandIn`), and an agent set to it is moved there (`agent.Reseat`). magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | | 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) | @@ -1153,6 +1153,27 @@ sign-in (5), by googleSearch, and like one is `Own`: its own models search first whoever is named. Before, it searched for its own models only and the picker never listed it (cocoasoda on Discord, `TestAIStudioKeySearchesForOthers`). +A ChatGPT account (Codex's sign-in, `codexSearches`) searches for another +model by the ChatGPT backend's own search, `POST /alpha/search`, +the request Codex's web.run sends by itself with no model turn +(`codexSearch`, codex-rs ext/web-search): one `search_query`, the +account's small model in `model` (the backend answered the same for any), +`allowed_callers: ["direct"]`, and `external_web_access` from the +client's `web_search` tool (`Request.WebAccess`, `withWebAccess`: false +for Codex's "cached", #5018), else true. The output's pages, split on its +80-dash rule, keep their titles and links by the results' `ref_id`, with +the private-use citation marks dropped (`codexPages`). It is magpie's own +pick for the account (`autoSearcherReady`, `searchInTurn` via +`turnModel`) and Settings' `/@search` (`codexSearchModel`, shown as +"its web search"); `` and `/` still search by that model, +which is also what `codexSearchBy` falls back on when the backend's +search fails. lucy_85908 on Discord: on a real Plus account 151 such +searches left the 5-hour window at the same percent, about 2s each, while +51 by gpt-6-luna through /responses took 1% of it, 7-15s each and about +9k tokens in. The fallback model search is still made live: the cached +mode reaches only the backend's search. Covered by +`TestChatGPTAccountSearchesByItsWebSearch`, `TestResponsesWebSearchModeKept` +and `TestCodexPagesRead`. Covered by `TestCommandCodeSearchesForOtherModels`, `TestPluginSearchModelIsASearcher` and `TestSearcherChosen`. diff --git a/internal/gateway/codex_search.go b/internal/gateway/codex_search.go index 34b62aea2..3100e090d 100644 --- a/internal/gateway/codex_search.go +++ b/internal/gateway/codex_search.go @@ -33,6 +33,10 @@ type alphaSearchRequest struct { SearchQuery []alphaQuery `json:"search_query"` ImageQuery []alphaQuery `json:"image_query"` } `json:"commands"` + Settings struct { + // Codex's web_search mode: false "cached", true "live" + ExternalWebAccess json.RawMessage `json:"external_web_access"` + } `json:"settings"` } type alphaQuery struct { @@ -222,7 +226,7 @@ func (s *Server) alphaSearchHere(w http.ResponseWriter, r *http.Request, q alpha writeJSON(w, http.StatusOK, alphaSearchReply{Output: note + "magpie can only search the web for " + q.Model + ": give web.run a search_query. Opening, clicking or finding in a page goes to the ChatGPT backend, for a ChatGPT account's model in magpie."}) return } - ctx := context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, Model: q.Model}) + ctx := withWebAccess(context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, Model: q.Model}), q.Settings.ExternalWebAccess) var said []string for _, query := range queries { found, _, err := s.webSearch(ctx, query) diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index 35bf9565c..40c311a0d 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -257,7 +257,12 @@ type Request struct { ThinkOff bool Parallel *bool // parallel tool calls allowed WebSearch bool // the client offered its provider's own web search - Fast bool // the client asked for priority processing: service_tier priority (Codex's Fast mode) + // WebAccess is the external_web_access of the client's web_search + // tool, as it sent it: Codex's web_search mode (false for "cached", + // true for "live"), which magpie's own search for a model that can't + // is made in (withWebAccess, #5018) + WebAccess json.RawMessage + Fast bool // the client asked for priority processing: service_tier priority (Codex's Fast mode) // Ultrafast is Codex's Ultrafast (service_tier "ultrafast"), which a // ChatGPT account on a plan with it offers on its models; Fast is set // with it, so where there is no Ultrafast the request goes fast diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index 1a58cd30e..4f3eda2f6 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -77,6 +77,9 @@ type rTool struct { Tools []rTool `json:"tools,omitempty"` // a namespace's Execution string `json:"execution,omitempty"` Format *rFormat `json:"format,omitempty"` // a custom tool's + // ExternalWebAccess is a web_search tool's mode: false is Codex's + // "cached", true its "live" + ExternalWebAccess json.RawMessage `json:"external_web_access,omitempty"` } // rFormat is what a custom (freeform) tool's input is: "text", or a @@ -523,6 +526,9 @@ func readResponsesFor(body []byte, facts, keepInstructions bool) (*Request, erro for i, t := range append(q.Tools, found...) { if strings.HasPrefix(t.Type, "web_search") { r.WebSearch = true + if len(t.ExternalWebAccess) > 0 { + r.WebAccess = t.ExternalWebAccess + } } switch t.Type { case "function": diff --git a/internal/gateway/search.go b/internal/gateway/search.go index 8caf435fc..fd68fc947 100644 --- a/internal/gateway/search.go +++ b/internal/gateway/search.go @@ -395,6 +395,10 @@ func autoSearcherReady() (provider.Provider, string, bool, bool) { if m == "" || top >= 0 && (bestReady && !ready || ready == bestReady && r >= top) { continue } + if codexSearches(p) { + // by the backend's search, which spends no model's tokens + m = codexSearchModel + } best, model, top, bestReady = p, m, r, ready } return best, model, bestReady, top >= 0 @@ -438,6 +442,9 @@ func namedSearcher(v string) (*provider.Provider, string, string) { case provider.KimiCodeSearch(p) != "": // it searches with no model return &p, "", "" + case model == codexSearchModel && codexSearches(p): + // by the ChatGPT backend's search + return &p, codexSearchModel, "" } if model != "" && slices.ContainsFunc(searcherModels(p), func(m catalog.Model) bool { return m.ID == model }) && searchableModel(p, model) { return &p, model, "" @@ -474,7 +481,7 @@ func Searchers() []SearcherChoice { if len(ms) == 0 { continue } - out = append(out, SearcherChoice{Provider: p, Small: searcherModel(p), Models: ms, rank: r, ManualOnly: manualOnly, Own: googleAccount(p) || geminiKeySearches(p)}) + out = append(out, SearcherChoice{Provider: p, Small: searcherModel(p), Models: ms, rank: r, ManualOnly: manualOnly, Own: googleAccount(p) || geminiKeySearches(p), Search: codexSearches(p)}) } slices.SortStableFunc(out, func(a, b SearcherChoice) int { return cmp.Compare(a.rank, b.rank) }) return out @@ -512,6 +519,10 @@ type SearcherChoice struct { // Own is a Google sign-in or an AI Studio key, whose Gemini searches // for the provider's own models first, whoever is named (ownSearcher) Own bool + // Search is a ChatGPT account, which searches by the ChatGPT backend's + // search besides its models ("/@search", codexSearchModel): + // magpie's own pick, and what it asks when another fails + Search bool } // RelaysSaidToSearch are the providers on that are said to search by @@ -902,6 +913,15 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit, return said, hits, err } +// turnModel is what c searches with when magpie picks it: a ChatGPT +// account by the backend's search, another by its small model. +func turnModel(c SearcherChoice) string { + if c.Search { + return codexSearchModel + } + return c.Small +} + // searchPick is a searcher a search was asked of. type searchPick struct{ id, model string } @@ -916,7 +936,7 @@ func (s *Server) searchInTurn(ctx context.Context, query string, tried []searchP if c.ManualOnly || c.Small == "" { continue } - if searcherSpent(c.Provider, c.Small) != nil { + if searcherSpent(c.Provider, turnModel(c)) != nil { spent = append(spent, c) } else { turn = append(turn, c) @@ -929,13 +949,14 @@ func (s *Server) searchInTurn(ctx context.Context, query string, tried []searchP if slices.ContainsFunc(tried, func(t searchPick) bool { return t.id == c.Provider.ID }) { continue } - tried = append(tried, searchPick{c.Provider.ID, c.Small}) - next := searcherSpent(c.Provider, c.Small) + m := turnModel(c) + tried = append(tried, searchPick{c.Provider.ID, m}) + next := searcherSpent(c.Provider, m) if next == nil { var said string var hits []Hit - if said, hits, next = s.searchWith(ctx, c.Provider, c.Small, query, searchEffort(c.Provider, c.Small)); next == nil { - return said, hits, searcherOf(c.Provider, c.Small), nil + if said, hits, next = s.searchBy(ctx, c.Provider, m, query, searchEffort(c.Provider, m)); next == nil { + return said, hits, searcherOf(c.Provider, m), nil } } err = errors.Join(err, next) @@ -1021,9 +1042,10 @@ func SearcherFailed() (SearchFailure, bool) { // searcherSpent is why a searcher's model isn't asked: every account or // key of it is out of its allowance (spentModel). nil when it has -// allowance, or searches with no model (a Kimi Code plan's service). +// allowance, or searches with no model (a Kimi Code plan's service, a +// ChatGPT account by the backend's search). func searcherSpent(p provider.Provider, model string) error { - if model == "" || provider.KimiCodeSearch(p) != "" { + if model == "" || model == codexSearchModel || provider.KimiCodeSearch(p) != "" { return nil } back, spent := spentModel(p, model, provider.Anthropic, time.Now()) @@ -1263,7 +1285,7 @@ func textCallRound(tools []Tool, ask round) round { // reply. The first round's failure is a status, as another provider may // take over. func (s *Server) searchReply(w http.ResponseWriter, r *http.Request, from provider.Protocol, name string, req *Request, usage *Usage, ask round) (int, string) { - ctx, cancel := context.WithCancel(context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, Model: unprefixed(req.Model)})) + ctx, cancel := context.WithCancel(withWebAccess(context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, Model: unprefixed(req.Model)}), req.WebAccess)) defer cancel() q := *req q.WebSearch = false diff --git a/internal/gateway/search_api.go b/internal/gateway/search_api.go index 3efadfe7a..aee09523e 100644 --- a/internal/gateway/search_api.go +++ b/internal/gateway/search_api.go @@ -66,9 +66,10 @@ func Searcher() string { } // searcherName is a searcher by its provider and model; a Kimi Code plan, -// which searches with no model, by its name. +// which searches with no model, and a ChatGPT account by the backend's +// search, by its name. func searcherName(p provider.Provider, model string) string { - if model == "" { + if model == "" || model == codexSearchModel { return p.Name } if e, ok := provider.ServedEntryOf(p.ID + "/" + model); ok && e.Name != "" { @@ -94,7 +95,7 @@ func AutoSearcher() string { // searches with no model (a Kimi Code plan's search service). func NamedSearchModel() string { p, m, why := chosenSearcher() - if p == nil || why != "" || m == "" { + if p == nil || why != "" || m == "" || m == codexSearchModel { return "" } return p.ID + "/" + m diff --git a/internal/gateway/search_codex.go b/internal/gateway/search_codex.go new file mode 100644 index 000000000..18549cd20 --- /dev/null +++ b/internal/gateway/search_codex.go @@ -0,0 +1,236 @@ +package gateway + +import ( + "bytes" + "cmp" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "strings" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// A ChatGPT account searches the web for a model that can't by the ChatGPT +// backend's own search, the one Codex's web.run tool runs (AlphaSearchPath), +// not by a model of the account asked to search: the search is answered by +// itself, with no model turn, as Codex asks it (codex-rs ext/web-search, +// tool.rs: a SearchRequest, the response's output given to the model as the +// tool's result). On a real Plus account (2026-11-03) 151 such searches +// left the 5-hour window where it was, each answered in about 2s, while 51 +// searches by gpt-6-luna through /responses (about 9k tokens in each) took +// 1% of it, each in 7-15s (lucy_85908 on Discord). The account's model +// searches only when the backend's search fails, or when Settings names a +// model of it. + +// codexSearchModel is the "model" a ChatGPT account searches with when it +// searches by the backend's search: "/@search" in Settings' +// Searcher. No model id starts with "@". +const codexSearchModel = "@search" + +// codexSearchBudget is the max_output_tokens Codex sends with a search: the +// truncation budget of its models' tool output (10,000 tokens). The backend +// answered the same whatever it was (1,000 to 10,000 tried). +const codexSearchBudget = 10000 + +// codexSearches is whether p searches by the ChatGPT backend's search: a +// ChatGPT account (Codex's sign-in). +func codexSearches(p provider.Provider) bool { + return p.Account != nil && p.Account.Agent == "codex" +} + +// webAccessKey holds the client's web search mode, as Codex sends it in +// external_web_access: false for "cached", true for "live", an object for +// "indexed". +type webAccessKey struct{} + +// withWebAccess is ctx whose searches are made in the mode v says, as the +// client sent it; none sent leaves ctx as it is. +func withWebAccess(ctx context.Context, v json.RawMessage) context.Context { + if len(bytes.TrimSpace(v)) == 0 || string(bytes.TrimSpace(v)) == "null" { + return ctx + } + return context.WithValue(ctx, webAccessKey{}, v) +} + +// webAccess is the external_web_access a search with ctx is sent with: the +// client's (#5018: Codex's web_search = "cached" was dropped, and every +// search went live), else true, a live search, as Codex's "live" sends. +func webAccess(ctx context.Context) json.RawMessage { + if v, ok := ctx.Value(webAccessKey{}).(json.RawMessage); ok { + return v + } + return json.RawMessage("true") +} + +// codexSearchReply is the ChatGPT backend's SearchResponse: output is what +// Codex shows the model, results the pages it names. +type codexSearchReply struct { + Output *string `json:"output"` + Results []struct { + RefID string `json:"ref_id"` + Title string `json:"title"` + URL string `json:"url"` + Snippet string `json:"snippet"` + } `json:"results"` +} + +// codexSearchRule is the line between the pages of a search's output. +var codexSearchRule = "\n" + strings.Repeat("-", 80) + "\n" + +// codexSearchBy searches with a ChatGPT account: by the backend's search, +// then, when it fails, by the account's small model. +func (s *Server) codexSearchBy(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) { + start := time.Now() + said, hits, err := s.codexSearch(ctx, p, query) + logOwnSearch(ctx, p, provider.CodexBase, query, start, len(hits), err) + if err == nil || ctx.Err() != nil { + return said, hits, err + } + m := searcherModel(p) + if m == "" { + return "", nil, err + } + log.Printf("web search on ChatGPT (%s) failed, searching with %s: %v", p.Name, m, err) + said, hits, next := s.searchWith(ctx, p, m, query, searchEffort(p, m)) + if next != nil { + return "", nil, errors.Join(err, next) + } + return said, hits, nil +} + +// codexSearch asks the ChatGPT backend's search, as Codex's web.run does. +func (s *Server) codexSearch(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) { + ctx, cancel := context.WithTimeout(s.metered(p.Via(ctx), p, ""), searchTimeout/2) + defer cancel() + q, err := maskedQuery(ctx, query, &p) + if err != nil { + return "", nil, err + } + // the model a search names is the turn's in Codex; the backend answers + // the same whichever it is, so the account's own small model + model := searcherModel(p) + if model == "" { + model = "gpt-5" + } + body, _ := json.Marshal(map[string]any{ + "id": newUUID(), + "model": model, + "commands": map[string]any{"search_query": []map[string]any{{"q": q}}}, + "settings": map[string]any{ + "allowed_callers": []string{"direct"}, + "external_web_access": webAccess(ctx), + }, + "max_output_tokens": codexSearchBudget, + }) + who := p.Name + ": " + r, err := http.NewRequestWithContext(ctx, http.MethodPost, provider.CodexBase+AlphaSearchPath, bytes.NewReader(body)) + if err != nil { + return "", nil, err + } + r.Header.Set("Content-Type", "application/json") + // a nil body: the search is answered in JSON, not streamed + if err := p.Sign(ctx, r, provider.Responses, nil); err != nil { + return "", nil, errors.New(who + err.Error()) + } + if why, revoked := provider.RevokedSignIn(p.Account, r); revoked { + return "", nil, errors.New(who + why) + } + res, err := s.client.Do(r) + if err != nil { + if ctx.Err() != nil { + return "", nil, fmt.Errorf("%sno answer in time", who) + } + return "", nil, fmt.Errorf("%s%w", who, err) + } + defer res.Body.Close() + noteSignIn(ctx, p.Account, r, res) + b, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20)) + if res.StatusCode >= 300 { + err := errors.New(who + provider.APIError(b, res.Status)) + if res.StatusCode == http.StatusTooManyRequests { + err = cantServe{err} + } + return "", nil, err + } + var out codexSearchReply + if err := json.Unmarshal(b, &out); err != nil || out.Output == nil { + return "", nil, fmt.Errorf("%sunexpected reply: %s", who, provider.APIError(b, res.Status)) + } + pages := codexPages(*out.Output, out) + if len(pages) == 0 { + return "", nil, fmt.Errorf("%s%w", who, errFoundNothing) + } + said, hits := pagesSaid(pages) + return said, hits, nil +} + +// codexPages are the pages a search's output names, in its order: each +// is "Title (URL)", then a line opening with its citation mark (the +// private-use "\ue200cite\ue202turn0search0\ue201") and "[wordlim: N]", +// then what the page says, and a rule of 80 dashes before the next. The +// results name each page's title and address by its ref_id, which the +// mark carries. +func codexPages(output string, out codexSearchReply) []foundPage { + type result struct{ title, url, snippet string } + byRef := map[string]result{} + for _, x := range out.Results { + if x.RefID != "" && x.URL != "" { + byRef[x.RefID] = result{x.Title, x.URL, x.Snippet} + } + } + var pages []foundPage + for _, block := range strings.Split(output, codexSearchRule) { + head, rest, _ := strings.Cut(strings.TrimSpace(block), "\n") + title, link := head, "" + if i := strings.LastIndex(head, " ("); i >= 0 && strings.HasSuffix(head, ")") { + title, link = head[:i], head[i+2:len(head)-1] + } + ref := "" + if i := strings.Index(rest, "\ue202"); i >= 0 { + if j := strings.Index(rest[i:], "\ue201"); j >= 0 { + ref = rest[i+len("\ue202") : i+j] + rest = rest[i+j+len("\ue201"):] + } + } + rest = strings.TrimSpace(rest) + if strings.HasPrefix(rest, "[wordlim:") { + if _, after, ok := strings.Cut(rest, "]"); ok { + rest = after + } + } + text := rest + if r, ok := byRef[ref]; ok { + title, link = cmp.Or(strings.TrimSpace(r.title), title), r.url + if strings.TrimSpace(text) == "" { + text = r.snippet + } + } + if !strings.HasPrefix(link, "http://") && !strings.HasPrefix(link, "https://") { + continue + } + title = searchPlain(title) + if title == "" { + title = link + } + pages = append(pages, foundPage{Title: title, URL: link, Text: clipText(searchPlain(strings.Map(dropPrivateUse, text)), pageText)}) + if len(pages) == searchHits { + break + } + } + return pages +} + +// dropPrivateUse leaves out the private-use characters OpenAI marks +// citations with. +func dropPrivateUse(r rune) rune { + if r >= 0xe000 && r <= 0xf8ff { + return -1 + } + return r +} diff --git a/internal/gateway/search_codex_small_test.go b/internal/gateway/search_codex_small_test.go index ad80a2b95..ae23d8e4f 100644 --- a/internal/gateway/search_codex_small_test.go +++ b/internal/gateway/search_codex_small_test.go @@ -22,12 +22,14 @@ func TestCodexSearchesWithItsCheapModel(t *testing.T) { if err := catalog.SaveLive("codex", provider.CodexBase, list); err != nil { t.Fatal(err) } + // magpie's own pick searches by the backend's search (search_codex.go); + // the cheap model is what it falls back on, and what "codex" names pick := func() (string, string) { p, m, ok := searcher() - if !ok { - t.Fatal("no searcher with a Codex account signed in") + if !ok || m != codexSearchModel { + t.Fatalf("searcher = %s/%s %v, want codex by its web search", p.ID, m, ok) } - return p.ID, m + return p.ID, searcherModel(p) } // no catalog: by the name @@ -61,7 +63,7 @@ func TestCodexSearchesWithItsCheapModel(t *testing.T) { if err := settings.Save(st); err != nil { t.Fatal(err) } - if id, m := pick(); id != "codex" || m != "gpt-6.1-sol" { - t.Fatalf("searcher = %s/%s, want the one Settings names, codex/gpt-6.1-sol", id, m) + if p, m, _ := searcher(); p.ID != "codex" || m != "gpt-6.1-sol" { + t.Fatalf("searcher = %s/%s, want the one Settings names, codex/gpt-6.1-sol", p.ID, m) } } diff --git a/internal/gateway/search_codex_test.go b/internal/gateway/search_codex_test.go new file mode 100644 index 000000000..24a06f804 --- /dev/null +++ b/internal/gateway/search_codex_test.go @@ -0,0 +1,216 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "slices" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// fakeChatGPT stands in for the ChatGPT backend: its search answers with +// the reply a real Plus account got for "Go 1.26" on 2026-11-03 (three of +// its 34 pages), /responses as a model that searched. +type fakeChatGPT struct { + mu sync.Mutex + paths []string + bodies []map[string]any + searchFails bool +} + +func newFakeChatGPT(t *testing.T) *fakeChatGPT { + t.Helper() + reply, err := os.ReadFile("testdata/codex_alpha_search.json") + if err != nil { + t.Fatal(err) + } + f := &fakeChatGPT{} + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q map[string]any + json.Unmarshal(b, &q) + f.mu.Lock() + f.paths = append(f.paths, r.URL.Path) + f.bodies = append(f.bodies, q) + fails := f.searchFails + f.mu.Unlock() + switch { + case strings.HasSuffix(r.URL.Path, "/alpha/search"): + if fails { + http.Error(w, `{"error":{"message":"upstream down"}}`, 502) + return + } + w.Header().Set("Content-Type", "application/json") + w.Write(reply) + case strings.HasSuffix(r.URL.Path, "/responses"): + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"type":"response.created","response":{"id":"r1","model":"gpt-6-luna"}}`, + `data: {"type":"response.output_item.done","item":{"type":"web_search_call","status":"completed","action":{"type":"search","query":"Go 1.26","sources":[{"type":"url","url":"https://go.dev/doc/go1.26"}]}}}`, + `data: {"type":"response.output_text.delta","delta":"Go 1.26 was released on 10 February 2026."}`, + `data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9000,"output_tokens":20}}}`)) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + if err := catalog.SaveLive("codex", provider.CodexBase, []catalog.Model{{ID: "gpt-6.1-sol"}, {ID: "gpt-6-luna"}}); err != nil { + t.Fatal(err) + } + return f +} + +func (f *fakeChatGPT) asked() ([]string, []map[string]any) { + f.mu.Lock() + defer f.mu.Unlock() + paths, bodies := slices.Clone(f.paths), slices.Clone(f.bodies) + f.paths, f.bodies = nil, nil + return paths, bodies +} + +// A ChatGPT account searches for a model that can't (DeepSeek, MiniMax, +// … in Codex) by the ChatGPT backend's own search, the one Codex's web.run +// asks, not by asking gpt-6-luna to search: lucy_85908 on Discord. 151 +// such searches on a real Plus account left its 5-hour window where it +// was, while 51 by gpt-6-luna took 1% of it. The search is made in the +// client's mode (#5018: Codex's web_search = "cached" sends +// external_web_access false), live when none is said. +func TestChatGPTAccountSearchesByItsWebSearch(t *testing.T) { + codexSignedIn(t) + f := newFakeChatGPT(t) + s := New() + + if p, m, ok := searcher(); !ok || p.ID != "codex" || m != codexSearchModel { + t.Fatalf("searcher = %s/%s %v, want codex by its web search", p.ID, m, ok) + } + if got := AutoSearcher(); !strings.HasPrefix(got, "Codex") || strings.Contains(got, "@search") { + t.Fatalf("AutoSearcher = %q", got) + } + said, hits, err := s.webSearch(context.Background(), "Go 1.26") + if err != nil { + t.Fatal(err) + } + paths, bodies := f.asked() + if !slices.Equal(paths, []string{"/backend-api/codex/alpha/search"}) { + t.Fatalf("asked %v, want the backend's search alone, no model", paths) + } + q := bodies[0] + cmds, _ := q["commands"].(map[string]any) + sq, _ := cmds["search_query"].([]any) + set, _ := q["settings"].(map[string]any) + if len(sq) != 1 || sq[0].(map[string]any)["q"] != "Go 1.26" || q["model"] != "gpt-6-luna" || q["id"] == "" || + set["external_web_access"] != true || !slices.Equal(set["allowed_callers"].([]any), []any{"direct"}) { + t.Fatalf("body %v", q) + } + if strings.Contains(string(mustJSON(q)), "magpie") { + t.Fatalf("magpie's own words went to the vendor: %v", q) + } + urls := []string{} + for _, h := range hits { + urls = append(urls, h.URL) + } + if !slices.Equal(urls, []string{"https://golang.google.cn/blog/go1.26", "https://golang-org.appspot.com/go.dev/blog/go1.26", "https://go.dev/doc/devel/release"}) { + t.Fatalf("hits %v", urls) + } + if !strings.Contains(said, "Green Tea garbage collector") || !strings.Contains(said, "go1.27.2") || + strings.ContainsAny(said, "") || strings.Contains(said, "wordlim") || strings.Contains(said, "-----") { + t.Fatalf("said %q", said) + } + + // Codex's cached web search: the search is cached too + if _, _, err := s.webSearch(withWebAccess(context.Background(), json.RawMessage("false")), "Go 1.26"); err != nil { + t.Fatal(err) + } + if _, bodies := f.asked(); bodies[0]["settings"].(map[string]any)["external_web_access"] != false { + t.Fatalf("cached went as %v", bodies[0]["settings"]) + } + + // the backend's search failing: the account's small model searches + f.mu.Lock() + f.searchFails = true + f.mu.Unlock() + said, _, err = s.webSearch(context.Background(), "Go 1.26") + if err != nil || !strings.Contains(said, "10 February 2026") { + t.Fatalf("fallback: %q %v", said, err) + } + paths, bodies = f.asked() + if len(paths) != 2 || !strings.HasSuffix(paths[0], "/alpha/search") || !strings.HasSuffix(paths[1], "/responses") || bodies[1]["model"] != "gpt-6-luna" { + t.Fatalf("fallback asked %v %v", paths, bodies) + } + f.mu.Lock() + f.searchFails = false + f.mu.Unlock() + + // named in Settings: its web search, its small model, a model of it + for _, c := range []struct{ named, path, model string }{ + {"codex/@search", "/alpha/search", ""}, + {"codex", "/responses", "gpt-6-luna"}, + {"codex/gpt-6.1-sol", "/responses", "gpt-6.1-sol"}, + } { + st := settings.Load() + st.Searcher = c.named + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + if _, _, err := s.webSearch(context.Background(), "Go 1.26"); err != nil { + t.Fatalf("%s: %v", c.named, err) + } + paths, bodies := f.asked() + if len(paths) != 1 || !strings.HasSuffix(paths[0], c.path) || c.model != "" && bodies[0]["model"] != c.model { + t.Fatalf("%s: asked %v %v", c.named, paths, bodies) + } + } +} + +// Codex's web_search tool's mode reaches the search magpie makes for a +// model that can't (#5018). +func TestResponsesWebSearchModeKept(t *testing.T) { + for _, c := range []struct{ tool, want string }{ + {`{"type":"web_search","external_web_access":false}`, "false"}, + {`{"type":"web_search","external_web_access":true}`, "true"}, + {`{"type":"web_search"}`, ""}, + } { + r, err := readResponsesFor([]byte(`{"model":"deepseek/deepseek-v4","input":"hi","tools":[`+c.tool+`]}`), false, false) + if err != nil { + t.Fatal(err) + } + if !r.WebSearch || string(r.WebAccess) != c.want { + t.Fatalf("%s: web search %v, access %q", c.tool, r.WebSearch, r.WebAccess) + } + want := c.want + if want == "" { + want = "true" + } + if got := string(webAccess(withWebAccess(context.Background(), r.WebAccess))); got != want { + t.Fatalf("%s: searched with %s", c.tool, got) + } + } +} + +// A search's output is read into pages by the marks Codex's own model +// reads it by; a page with no address is left out. +func TestCodexPagesRead(t *testing.T) { + rule := codexSearchRule + out := "Go (https://go.dev/)\nciteturn0search0 [wordlim: 200] Crawled: today; Build simple software.\n" + rule + + "No address\nciteturn0search9 [wordlim: 200] nothing" + rule + + "Bare (https://example.com/a)\njust text" + var reply codexSearchReply + json.Unmarshal([]byte(`{"results":[{"ref_id":"turn0search0","title":"The Go Programming Language","url":"https://go.dev/"}]}`), &reply) + pages := codexPages(out, reply) + if len(pages) != 2 || pages[0].Title != "The Go Programming Language" || pages[0].URL != "https://go.dev/" || + !strings.Contains(pages[0].Text, "Build simple software.") || strings.Contains(pages[0].Text, "wordlim") || + pages[1].URL != "https://example.com/a" || pages[1].Text != "just text" { + t.Fatalf("%+v", pages) + } +} diff --git a/internal/gateway/search_kimi.go b/internal/gateway/search_kimi.go index b97cb7b06..187ba647b 100644 --- a/internal/gateway/search_kimi.go +++ b/internal/gateway/search_kimi.go @@ -97,11 +97,15 @@ func (s *Server) ownSearch(ctx context.Context, p provider.Provider, query strin } // searchBy searches with one searcher: a Kimi Code plan by its search -// service, any other by its model. +// service, a ChatGPT account named with codexSearchModel by the backend's +// search, any other by its model. func (s *Server) searchBy(ctx context.Context, p provider.Provider, model, query, effort string) (string, []Hit, error) { if provider.KimiCodeSearch(p) != "" { return s.kimiSearch(ctx, p, query) } + if model == codexSearchModel && codexSearches(p) { + return s.codexSearchBy(ctx, p, query) + } return s.searchWith(ctx, p, model, query, effort) } diff --git a/internal/gateway/side_effort.go b/internal/gateway/side_effort.go index 5e3d32cef..af6a06b5d 100644 --- a/internal/gateway/side_effort.go +++ b/internal/gateway/side_effort.go @@ -80,7 +80,7 @@ func VisionEfforts() []string { // asked to search at: the one picked in Settings fitted to its levels, // or "" to send none. func searchEffort(p provider.Provider, model string) string { - if model == "" { + if model == "" || model == codexSearchModel { return "" } return sideEffort(p.ID+"/"+model, settings.Load().SearcherEffort) @@ -98,7 +98,7 @@ func SearchEffortNow() string { // SearchEfforts are the levels of the model that searches now: none for // a Kimi Code plan's search service, which has no model. func SearchEfforts() []string { - if p, m, ok := searcher(); ok && m != "" { + if p, m, ok := searcher(); ok && m != "" && m != codexSearchModel { return ModelEfforts(p.ID + "/" + m) } return nil diff --git a/internal/gateway/testdata/codex_alpha_search.json b/internal/gateway/testdata/codex_alpha_search.json new file mode 100644 index 000000000..7bd608ca0 --- /dev/null +++ b/internal/gateway/testdata/codex_alpha_search.json @@ -0,0 +1,30 @@ +{ + "encrypted_output": "gAAAAABq6X7S1KFurVRJMeXg1usNmFBum9Lacra4awB0FFVvnu4ZPFcfm53Fx6b_", + "output": "Go 1.26 is released - The Go Programming Language (https://golang.google.cn/blog/go1.26)\nciteturn0search0 [wordlim: 200] Published: 8 months ago; Crawled: today; Today the Go team is pleased to release Go 1.26.\n\n# Go 1.26 is released\n\nCarlos Amedee, on behalf of the Go team\n10 February 2026\n\nToday the Go team is pleased to release Go 1.26. You can find its binary archives and installers on the download page.\n\n## Language changes\n\nGo 1.26 introduces two significant refinements to the language syntax and type system.\n\nFirst, the built-in `new` function, which creates a new variable, now allows its operand to be an expression, specifying the initial value of the variable.\n\nA simple example of this change means that code such as this:\n \n `x := int64(300)\n ptr := &x\n `\n\nCan be simplified to:\n \n `ptr := new(int64(300))\n `\n\nSecond, generic types may now refer to themselves in their own type parameter list. This change simplifies the implementation of complex data structures and interfaces.\n\n## Performance improvements\n\nThe previously experimental Green Tea garbage collector is now enabled by default.\n\nThe baseline cgo overhead has been reduced by approximately 30%.\n--------------------------------------------------------------------------------\nGo 1.26 is released - The Go Programming Language (https://golang-org.appspot.com/go.dev/blog/go1.26)\nciteturn0search1 [wordlim: 200] Published: 8 months ago; Crawled: last week; Today the Go team is pleased to release Go 1.26.\n\n# Go 1.26 is released\n\nCarlos Amedee, on behalf of the Go team\n10 February 2026\n\nToday the Go team is pleased to release Go 1.26. You can find its binary archives and installers on the download page.\n\n## Language changes\n\nGo 1.26 introduces two significant refinements to the language syntax and type system.\n\nFirst, the built-in `new` function, which creates a new variable, now allows its operand to be an expression, specifying the initial value of the variable.\n\nA simple example of this change means that code such as this:\n \n `x := int64(300)\n ptr := &x\n `\n\nCan be simplified to:\n \n `ptr := new(int64(300))\n `\n\nSecond, generic types may now refer to themselves in their own type parameter list. This change simplifies the implementation of complex data structures and interfaces.\n\n## Performance improvements\n\nThe previously experimental Green Tea garbage collector is now enabled by default.\n\nThe baseline cgo overhead has been reduced by approximately 30%.\n\nThe compiler can now allocate the backing store for slices on the stack in more situations, which improves performance.\n\n## Tool improvements\n\nThe `go fix` command has been completely rewritten to use the Go analysis framework, and now includes a couple dozen “modernizers”, analyzers that suggest safe fixes to help your code take advantage of newer features of the language and standard library. It also includes the `inline` analyzer, which attempts to inline all calls to each function annotated with a `//go:fix inline` directive. Two upcoming blog posts will address these features in more detail.\n--------------------------------------------------------------------------------\nRelease History - The Go Programming Language (https://go.dev/doc/devel/release)\nciteturn0search2 [wordlim: 200] Crawled: today; Go 1.26.0 is a major release of Go. ... go1.26.7 (released 2026-08-19) includes fixes to the `net/http` package.\n\ngo1.27.2 (released 2026-10-08) includes security fixes to the `go` command, and the `crypto/tls`, `html/template`, `net/http`, `net/textproto`, and `os` packages, as well as bug fixes to the compiler, the linker, the runtime, the `cover` tool, the `go fix` command, vet, and the `compress/flate`, `crypto/mlkem`, `encoding/json`, `encoding/json/v2`, `net/http`, and `os` packages. See the Go 1.27.2 milestone on our issue tracker for details.\n\ngo1.27.3 (released 2026-10-19) includes security fixes to the `crypto/x509` package. See the Go 1.27.3 milestone on our issue tracker for details.\n\n## go1.26.0 (released 2026-02-10)\n\nGo 1.26.0 is a major release of Go. Read the Go 1.26 Release Notes for more information.\n\n### Minor revisions\n\ngo1.26.1 (released 2026-03-05) includes security fixes to the `crypto/x509`, `html/template`, `net/url`, and `os` packages, as well as bug fixes to the `go` command, the `go fix` command, the compiler, and the `os` and `reflect` packages. See the Go 1.26.1 milestone on our issue tracker for details.\n\ngo1.26.2 (released 2026-04-07) includes security fixes to the `go` command, the compiler, and the `archive/tar`, `crypto/tls`, `crypto/x509`, `html/template`, and `os` packages, as well as bug fixes to the `go` command, the `go fix` command, the compiler, the linker, the runtime, and the `net`, `net/http`, and `net/url` packages. See the Go 1.26.2 milestone on our issue tracker for details.\n\ngo1.26.3 (released 2026-05-07) includes security fixes to the `go` command, the `pack` tool, and the `html/template`, `net`, `net/http`, `net/http/httputil`, `net/mail`, and `syscall` packages, as well as bug fixes to the `go` command, the `go fix` command, the compiler, the linker, the runtime, and the `crypto/fips140`, `crypto/tls`, `go/types`, and `os` packages. See the Go 1.26.3 milestone on our issue tracker for details.\n\ngo1.26.4 (released 2026-06-02) includes security fixes to the `crypto/x509`, `mime`, and `net/textproto` packages, as well as bug fixes to the compiler, the runtime, the `go fix` command, and the `crypto/fips140` package. See the Go 1.26.4 milestone on our issue tracker for details.\n\ngo1.26.5 (released 2026-07-07) includes security fixes to the `crypto/tls` and `os` packages, as well as bug fixes to the compiler, the runtime, the `go` command, and the `net`, `os`, and `syscall` packages. See the Go 1.26.5 milestone on our issue tracker for details.\n\ngo1.26.6 (released 2026-08-13) includes security fixes to the `go` command, and the `crypto/tls`, `encoding/asn1`, `encoding/xml`, `html/template`, `net`, `net/http`, and `net/url` packages, as well as bug fixes to the compiler, the linker, the runtime, and the `crypto/tls` and `os` packages. See the Go 1.26.6 milestone on our issue tracker for details.\n\ngo1.26.7 (released 2026-08-19) includes fixes to the `net/http` package. See the Go 1.26.7 milestone on our issue tracker for details.\n\ngo1.26.8 (released 2026-09-01) includes fixes to cgo, the compiler, the runtime, and the `debug/elf` and `os` packages. See the Go 1.26.8 milestone on our issue tracker for details.\n\ngo1.26.9 (released 2026-10-08) includes security fixes to the `go` command, and the `crypto/tls`, `html/template`, `net/http`, `net/textproto`, and `os` packages, as well as bug fixes to the compiler, the linker, the runtime, vet, and the `crypto/mlkem`, `net/http`, and `os` packages. See the Go 1.26.9 milestone on our issue tracker for details.\n\ngo1.26.10 (released 2026-10-19) includes security fixes to the `crypto/x509` package. See the Go 1.26.10 milestone on our issue tracker for details.", + "results": [ + { + "type": "text_result", + "domain": "golang.google.cn", + "ref_id": "turn0search0", + "snippet": "Today the Go team is pleased to release Go 1.26.", + "title": "Go 1.26 is released - The Go Programming Language", + "url": "https://golang.google.cn/blog/go1.26" + }, + { + "type": "text_result", + "domain": "golang-org.appspot.com", + "ref_id": "turn0search1", + "snippet": "Today the Go team is pleased to release Go 1.26.", + "title": "Go 1.26 is released - The Go Programming Language", + "url": "https://golang-org.appspot.com/go.dev/blog/go1.26" + }, + { + "type": "text_result", + "domain": "go.dev", + "ref_id": "turn0search2", + "snippet": "Go 1.26.0 is a major release of Go. ... go1.26.7 (released 2026-08-19) includes fixes to the `net/http` package.", + "title": "Release History - The Go Programming Language", + "url": "https://go.dev/doc/devel/release" + } + ] +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 634e35f9b..ce99604f1 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -594,6 +594,9 @@ type searchChoiceJSON struct { // Own is a Google sign-in or an AI Studio key, which searches for its // own models first Own bool `json:"own,omitempty"` + // Search is a ChatGPT account, which searches by the ChatGPT backend's + // search ("/@search") besides its models + Search bool `json:"search,omitempty"` } type searchVendorJSON struct { @@ -632,7 +635,7 @@ func searchState(s *settingsJSON) { s.SearchChoices = []searchChoiceJSON{} for _, c := range gateway.Searchers() { p := c.Provider - j := searchChoiceJSON{ID: p.ID, Name: p.Name, Icon: p.Icon, Small: c.Small, SmallName: names[p.ID+"/"+c.Small], Models: []modelRef{}, Service: c.Service, Own: c.Own} + j := searchChoiceJSON{ID: p.ID, Name: p.Name, Icon: p.Icon, Small: c.Small, SmallName: names[p.ID+"/"+c.Small], Models: []modelRef{}, Service: c.Service, Own: c.Own, Search: c.Search} for _, m := range c.Models { id := p.ID + "/" + m.ID j.Models = append(j.Models, modelRef{ID: id, Name: cmp.Or(names[id], m.Name, m.ID), Provider: p.ID, PName: p.Name, Icon: p.Icon}) diff --git a/internal/gui/assets/plugins/search/settings.js b/internal/gui/assets/plugins/search/settings.js index aece76a87..6f4b03234 100644 --- a/internal/gui/assets/plugins/search/settings.js +++ b/internal/gui/assets/plugins/search/settings.js @@ -321,7 +321,7 @@ function renderSearcher(s, keep, box) { const [pid, ...rest] = id.split("/"); const c = choices.find((x) => x.id === pid); if (!c) return id; - if (c.service) return `${c.name} · ${t("its web search")}`; + if (c.service || (c.search && rest.join("/") === "@search")) return `${c.name} · ${t("its web search")}`; if (!rest.length) return `${c.name} · ${c.smallName || c.small}`; const m = c.models.find((x) => x.id === id); return `${m ? m.name : rest.join("/")} · ${c.name}`; @@ -376,6 +376,9 @@ function renderSearcher(s, keep, box) { options.push({ value: c.id, label: t("its web search"), note: c.name, icon: c.icon, group: c.name }); continue; } + // a ChatGPT account searches by its own web search, with no model's + // tokens spent (lucy_85908 on Discord); its models stay to be picked + if (c.search) options.push({ value: `${c.id}/@search`, label: t("its web search"), note: c.name, icon: c.icon, group: c.name }); // its small model is offered once (Player on Discord): the model of the // same name below it searched just the same, "/" being // that model named rather than magpie's pick, so a pick saved so is diff --git a/internal/gui/tests/searcher-pick.test.cjs b/internal/gui/tests/searcher-pick.test.cjs index f7042e1b2..8f2eacc2a 100644 --- a/internal/gui/tests/searcher-pick.test.cjs +++ b/internal/gui/tests/searcher-pick.test.cjs @@ -10,7 +10,8 @@ // one named that magpie can't use (turned off) is said in the row, magpie's pick shown instead; // relays said to search are manual-only, including during fallback; a Kimi Code plan, which // searches by its web search with no model, is offered by itself and said to search for its -// own models first. Another setting saved +// own models first; a ChatGPT account is offered by its web search ("/@search", no +// model's tokens spent, lucy_85908 on Discord) besides its small model and models. Another setting saved // keeps the pick (prefsKeep). No click moves the page. English and Chinese, Chromium and // WebKit, with the API faked. Search help covers costs for every provider and // explains current eligibility without claiming a provider can never search. @@ -36,6 +37,9 @@ const choices = [ { id: "relay", name: "MyRelay", icon: "generic", small: "claude-haiku-4-5", models: [ { id: "relay/claude-haiku-4-5", name: "Claude Haiku 4.5", provider: "relay", providerName: "MyRelay" }] }, { id: "kimi", name: "Kimi Code", icon: "kimi", small: "", models: [], service: true }, + { id: "codex", name: "Codex (me@example.com)", icon: "openai", small: "gpt-6-luna", smallName: "GPT-6 Luna", search: true, models: [ + { id: "codex/gpt-6-luna", name: "GPT-6 Luna", provider: "codex", providerName: "Codex (me@example.com)" }, + { id: "codex/gpt-6.1-sol", name: "GPT-6.1 Sol", provider: "codex", providerName: "Codex (me@example.com)" }] }, { id: "antigravity", name: "Antigravity", icon: "antigravity", small: "gemini-3-flash", own: true, models: [ { id: "antigravity/gemini-3-flash", name: "Gemini 3 Flash", provider: "antigravity", providerName: "Antigravity" }] }, ]; @@ -260,12 +264,25 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const kimi = (await page.locator("#list li:not(.group)").allInnerTexts()).filter((x) => x.includes("Kimi Code")); assert.equal(kimi.length, 1, "the plan is offered once, with no model"); assert(kimi[0].includes(w.web)); - const web = page.locator("#list li:not(.group)", { hasText: w.web }); + const web = page.locator("#list li:not(.group)", { hasText: w.web }).filter({ hasText: "Kimi Code" }); await web.scrollIntoViewIfNeeded(); await click(web); await page.waitForFunction((want) => document.querySelector("#searchList button.searcher-pick")?.innerText === want, `Kimi Code · ${w.web}`); assert.equal(posted.at(-1).searcher, "kimi"); + // a ChatGPT account, by its web search: its small model and models + // are still offered + await click(row.locator("button.searcher-pick")); + await page.locator("#pop").waitFor({ state: "visible" }); + const codex = (await page.locator("#list li:not(.group)").allInnerTexts()).filter((x) => x.includes("Codex (me@example.com)")); + assert.equal(codex.filter((x) => x.includes(w.web)).length, 1, codex.join(" | ")); + assert(codex.some((x) => x.includes("GPT-6 Luna")) && codex.some((x) => x.includes("GPT-6.1 Sol")), codex.join(" | ")); + const cweb = page.locator("#list li:not(.group)", { hasText: w.web }).filter({ hasText: "Codex (me@example.com)" }); + await cweb.scrollIntoViewIfNeeded(); + await click(cweb); + await page.waitForFunction((want) => document.querySelector("#searchList button.searcher-pick")?.innerText === want, `Codex (me@example.com) · ${w.web}`); + assert.equal(posted.at(-1).searcher, "codex/@search"); + // back to a provider, by its small model await click(row.locator("button.searcher-pick")); await page.locator("#pop").waitFor({ state: "visible" });