diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 4a1c03cd8..aa44ba7fe 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -26,7 +26,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Part | Responsibility | Source | | --- | --- | --- | -| 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. 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) | +| 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. 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) | diff --git a/internal/agent/vscode.go b/internal/agent/vscode.go index 7a9a69b22..9b14542e6 100644 --- a/internal/agent/vscode.go +++ b/internal/agent/vscode.go @@ -51,6 +51,16 @@ const vscodeDefault = `chat\.defaultModel` // can't change. const vscodeUA = "githubcopilotchat" +// vscodeAgentHostUA is VS Code's Agents window: its agent host runs +// `codex app-server` with clientInfo named vscode_agent_host (VS Code's +// src/vs/platform/agentHost/node/codex/codexAgent.ts), and Codex makes +// that its originator and the start of its User-Agent +// ("vscode_agent_host/0.163.0 (Mac OS …; arm64) … (vscode_agent_host; +// 0.1.0)"). Its calls were listed under that raw name beside VS Code's +// (justruman on Discord). Insiders' and VSCodium's agent host send the +// same name, so they are counted as VS Code too. +const vscodeAgentHostUA = "vscode_agent_host" + // The providers magpie's group can be written for: VS Code's Custom // Endpoint, and the OpenAI Compatible one of the Copilot Chat VSCodium // installs. @@ -99,7 +109,7 @@ type vscodeKind struct { } var ( - vscodeStable = vscodeKind{id: "vscode", name: "VS Code", folder: "Code", bin: "code", aliases: []string{"vs-code", "copilot-chat", "vscode-chat"}, ua: []string{vscodeUA}} + vscodeStable = vscodeKind{id: "vscode", name: "VS Code", folder: "Code", bin: "code", aliases: []string{"vs-code", "copilot-chat", "vscode-chat"}, ua: []string{vscodeUA, vscodeAgentHostUA}} vscodeInsiders = vscodeKind{id: "vscode-insiders", name: "VS Code Insiders", folder: "Code - Insiders", bin: "code-insiders", aliases: []string{"vs-code-insiders", "code-insiders"}} vscodiumKind = vscodeKind{id: "vscodium", name: "VSCodium", folder: "VSCodium", bin: "codium", aliases: []string{"codium", "vscodium-chat"}, exts: ".vscode-oss"} ) diff --git a/internal/agent/vscode_test.go b/internal/agent/vscode_test.go index ba24362b9..5c783b4e8 100644 --- a/internal/agent/vscode_test.go +++ b/internal/agent/vscode_test.go @@ -234,6 +234,18 @@ func TestVSCodeUA(t *testing.T) { } } +// VS Code's Agents window runs Codex under the name vscode_agent_host, +// its User-Agent and originator: its calls are VS Code's, not a row of +// their own named vscode_agent_host (justruman on Discord). VS Code's +// Copilot-proxied Codex and Claude names are not it. +func TestVSCodeAgentHostUA(t *testing.T) { + for _, ua := range []string{"vscode_agent_host/0.163.0 (Mac OS 26.2.0; arm64) unknown (vscode_agent_host; 0.1.0)", "vscode_agent_host"} { + if got := usage.AgentOf(ua); got != "vscode" { + t.Errorf("%q: %q", ua, got) + } + } +} + // VS Code Insiders is its own row (wani on Discord): its User folder is // "Code - Insiders" beside VS Code's "Code", connected it writes only there, // and its models send a token of its own, since its chat's User-Agent is diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 1626cf758..aaf54e20d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4959,7 +4959,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid seen[k] = vs } } - provider.SawClient(provider.ClientCodex, seen) + if codexNamed(in) { + provider.SawClient(provider.ClientCodex, seen) + } } if p.Account == nil && biliProxied(req.URL.Path) { // a billion-context proxy put in front of the provider (#3052) @@ -5119,7 +5121,20 @@ func claudeCodeHeader(k string) bool { // desktop app or ACP adapter — by the User-Agent (codex_cli_rs/0.159.2 // (Mac OS 26.6.0; arm64) kitty, Codex Desktop/0.162.3 …) or the originator it gives // (codex_cli_rs, codex_exec, codex_vscode, Codex Desktop, acp-extension-codex). +// VS Code's Agents window runs `codex app-server` under the name +// vscode_agent_host, which Codex sends as both: those are Codex's turns +// too, though they are counted under VS Code (agent.vscodeAgentHostUA). +// Without it one of Codex's own models asked there was answered 404 +// "magpie knows no model" rather than going on Codex's sign-in +// (codexOwnOffMagpie; justruman on Discord). func fromCodex(in http.Header) bool { + return codexNamed(in) || hostedCodex(in) +} + +// codexNamed is a request whose User-Agent or originator is one of Codex's +// own names, not an app's that runs it: only those are Codex's shape for +// a test asked as Codex (provider.SawClient). +func codexNamed(in http.Header) bool { for _, v := range []string{in.Get("User-Agent"), in.Get("originator")} { v = strings.ToLower(v) if strings.HasPrefix(v, "codex") || strings.HasPrefix(v, "acp-extension-codex") { @@ -5129,6 +5144,19 @@ func fromCodex(in http.Header) bool { return false } +// hostedCodex is a Codex an app runs under the app's own name and that +// name only Codex is run under: VS Code's agent host (its codexAgent.ts +// CLIENT_INFO). An app that runs Codex as its own engine under a name it +// uses for more than that (Lody) is not told apart this way. +func hostedCodex(in http.Header) bool { + for _, v := range []string{in.Get("User-Agent"), in.Get("originator")} { + if strings.HasPrefix(strings.ToLower(strings.TrimSpace(v)), "vscode_agent_host") { + return true + } + } + return false +} + // codexAsSent says a Responses request goes to p as Codex sent it, its // model name alone swapped: Codex's own, to a relay set codex=as-sent, // which checks that a request is Codex's own (#1758). diff --git a/internal/gateway/vscode_agent_host_test.go b/internal/gateway/vscode_agent_host_test.go new file mode 100644 index 000000000..e73f8fdf4 --- /dev/null +++ b/internal/gateway/vscode_agent_host_test.go @@ -0,0 +1,99 @@ +package gateway + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// VS Code's Agents window runs `codex app-server` (main at 8fb6054, +// 11-01: @openai/codex 0.163.0) with clientInfo {name: "vscode_agent_host"}, in +// src/vs/platform/agentHost/node/codex/codexAgent.ts. Codex sends the name +// as its originator and at the head of its User-Agent, as it does Claude +// Code's plugin's (TestCodexPluginForClaudeCodeIsCodex). The headers are a +// Codex turn's under that name. +func vscodeAgentHostHeader() http.Header { + return http.Header{ + "User-Agent": {"vscode_agent_host/0.163.0 (Mac OS 26.2.0; arm64) unknown (vscode_agent_host; 0.1.0)"}, + "Originator": {"vscode_agent_host"}, + "X-Codex-Window-Id": {"019a0f7e-0000-7000-8000-000000000001:0"}, + "X-Codex-Turn-Metadata": {`{"turn_id":"019a0f7e-0000-7000-8000-000000000002","sandbox":"none"}`}, + "Session-Id": {"019a0f7e-0000-7000-8000-000000000001"}, + } +} + +// Its turns are Codex's: a Codex rule holds for them. They are not Codex's +// own name, so they never stand for Codex in a test asked as Codex. +func TestVSCodeAgentHostIsCodex(t *testing.T) { + h := vscodeAgentHostHeader() + if !fromCodex(h) { + t.Fatal("VS Code's agent host's Codex turn isn't Codex's") + } + if !fromCodex(http.Header{"Originator": {"vscode_agent_host"}}) { + t.Fatal("by its originator alone, it isn't Codex's") + } + if codexNamed(h) { + t.Fatal("the agent host's name counted as Codex's own") + } + for _, other := range []string{"vscode_codex/0.163.0", "vscode_claude_code/2.1.0", "GitHubCopilotChat/0.69.0"} { + if fromCodex(http.Header{"User-Agent": {other}}) { + t.Errorf("%s counted as Codex", other) + } + } +} + +// One of Codex's own models asked from the Agents window on Codex's +// magpie provider, which no account in magpie serves, goes on Codex's own +// sign-in as the Codex CLI's does (TestCodexOwnModelOnMagpieThreadGoesOnSignIn), +// not 404 "magpie knows no model" (justruman on Discord: 7 of 23 calls +// failed). +func TestVSCodeAgentHostOwnModelGoesOnSignIn(t *testing.T) { + _, models := codexOwnOffMagpieSetup(t, false) + req := codexOnMagpieRequest("127.0.0.1:51000") + for k, v := range vscodeAgentHostHeader() { + req.Header[k] = v + } + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") { + t.Fatalf("got %d %s", rec.Code, rec.Body.String()) + } + if len(*models) != 1 || (*models)[0] != "gpt-6.1-sol" { + t.Fatalf("backend asked for %v", *models) + } +} + +// Its headers go on to a keyed relay as Codex's do, but a test asked as +// Codex still asks as Codex itself: the agent host's name is no Codex +// official client a Codex-only relay lets in. +func TestVSCodeAgentHostNotCodexTestShape(t *testing.T) { + fresh(t) + f := &clientOnlyRelay{} + up := httptest.NewServer(f) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"gpt-5.5"}, + Chat: up.URL + "/v1", Responses: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"relay/gpt-5.5","stream":true,"input":"hi"}`)) + req.Header = vscodeAgentHostHeader() + req.Header.Set("Authorization", "Bearer "+Token) + New().Handler().ServeHTTP(httptest.NewRecorder(), req) + head, _, _ := f.last() + if head.Get("Originator") != "vscode_agent_host" { + t.Fatalf("the relay wasn't sent the agent host's turn as it sent it: %v", head) + } + p, err := provider.Find("relay") + if err != nil { + t.Fatal(err) + } + r := p.TestModels(provider.TestAs(context.Background(), provider.ClientCodex), []string{"gpt-5.5"})[0] + head, _, _ = f.last() + if !r.OK || !strings.HasPrefix(head.Get("User-Agent"), "codex_cli_rs/") { + t.Fatalf("as Codex after the agent host came: %+v, User-Agent %q", r, head.Get("User-Agent")) + } +}