diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 3ab7348d8..ad02ff4e6 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -27,7 +27,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. 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) | +| 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). A distro in bridged networking is a peer on the LAN, and its default route is the LAN's router, not Windows: `wslrun.HostAt` takes Windows' address on the bridge's adapter (`vEthernet (WSL_Bridge_Switch)`), the one whose network holds that route (ecalpal_ on Discord). `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`, 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) | diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index bb9da3506..a9fd6cbd0 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -1788,10 +1788,11 @@ func parseProbe(name, out string) *distro { // the default route of a distro whose 127.0.0.1 is Windows' is // Windows' own next hop (consomme: 198.18.0.2 under a TUN proxy, // #1230), not Windows: an agent left on it is moved to 127.0.0.1 - // (wslMovedFrom) - if wslrun.HostLoopback(d.Net) { - d.Gateway = "" - } + // (wslMovedFrom). A bridged distro's is the LAN's router: Windows is + // at its address on the bridge's adapter (wslrun.HostAt), and an agent + // an older magpie pointed at the router is written over on the next + // sync, the router being among the addresses it was seen at (Was) + d.Gateway = wslrun.HostAt(d.Net, d.Gateway, gateway.WSLNets()) return d } diff --git a/internal/agent/wsl_bridged_test.go b/internal/agent/wsl_bridged_test.go new file mode 100644 index 000000000..e6c16415b --- /dev/null +++ b/internal/agent/wsl_bridged_test.go @@ -0,0 +1,100 @@ +package agent + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/gateway" +) + +// ecalpal_ on Discord (magpie 0.1.2689, WSL 3.0.3.0, Ubuntu 22.04.5, +// .wslconfig vmSwitch=WSL_Bridge_Switch, networkingMode=Bridged, +// dhcp=false): in bridged networking the distro's default route is the +// LAN's router, 192.168.9.1, while Windows is at 192.168.9.147/24 on +// vEthernet (WSL_Bridge_Switch). magpie wrote the router into wsl.json and +// into Pi's models.json, where nothing listens. Windows' address on the +// bridge is the distro's way to it, and its key is the WSL key that +// address takes. NAT and mirrored keep their own values. +func TestWSLBridgedReachesWindowsOnTheBridge(t *testing.T) { + for _, c := range []struct { + net, cidr, route, want string + }{ + {"bridged", "192.168.9.147/24", "192.168.9.1", "192.168.9.147"}, + {"nat", "172.20.0.1/20", "172.20.0.1", "172.20.0.1"}, + {"mirrored", "192.168.9.147/24", "192.168.9.1", ""}, + } { + fakeWSLNet(t, c.cidr) + d := parseProbe("Ubuntu-22.04", "home:/home/me\ndir:.pi\nroute:default via "+c.route+" dev eth0 proto static\nnet:"+c.net+"\n") + if d == nil || d.Gateway != c.want { + t.Fatalf("%s: %+v", c.net, d) + } + d.mirror("") + want := gateway.URL() + if c.want != "" { + want = "http://" + c.want + ":" + gateway.Port() + } + if d.base() != want { + t.Errorf("%s: %s, want %s", c.net, d.base(), want) + } + } +} + +// One an older magpie set up on the router has its wsl.json and Pi's +// models.json written over once magpie starts again and probes the +// running distro: the address and the key with it. +func TestWSLBridgedOldRouterWrittenOver(t *testing.T) { + root, home := piDistroHome(t, `{"defaultProvider": "xai", "defaultModel": "grok-4.6"}`) + models := filepath.Join(home, ".pi", "agent", "models.json") + // what 0.1.2689 wrote: Pi on the router, with the gateway's token + old := distro{Name: "Ubuntu-22.04", Root: root, Home: "/home/me", Has: map[string]bool{"dir:.pi": true}, + Gateway: "192.168.9.1", Net: "bridged", Running: true} + if err := wslPi(old).Apply("model", "magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + pi := func() map[string]any { + var f struct { + Providers map[string]map[string]any `json:"providers"` + } + if err := json.Unmarshal([]byte(readFile(models)), &f); err != nil { + t.Fatal(err) + } + return f.Providers["magpie"] + } + if p := pi(); p["baseUrl"] != "http://192.168.9.1:"+gateway.Port()+"/v1" { + t.Fatalf("old config: %v", p) + } + + fakeWSL(t, "Ubuntu-22.04\r\n", "Ubuntu-22.04\r\n", map[string]string{ + "Ubuntu-22.04": "home:/home/me\ndir:.pi\nroute:default via 192.168.9.1 dev eth0 proto static\nnet:bridged\n", + }, map[string]string{"Ubuntu-22.04": root}) + os.MkdirAll(filepath.Dir(wslStatePath()), 0o755) + if err := os.WriteFile(wslStatePath(), []byte(`{"Ubuntu-22.04":{"name":"Ubuntu-22.04","home":"/home/me","root":"","has":{"dir:.pi":true},"probe":`+ + jsonInt(wslProbeVersion)+`,"net":"bridged","gateway":"192.168.9.1"}}`), 0o644); err != nil { + t.Fatal(err) + } + fakeWSLNet(t, "192.168.9.147/24") + ds := wslDistros() + if len(ds) != 1 || ds[0].Gateway != "192.168.9.147" || len(ds[0].Was) != 1 || ds[0].Was[0] != "192.168.9.1" { + t.Fatalf("%+v", ds) + } + wslSave() + var saved map[string]distro + if err := json.Unmarshal([]byte(readFile(wslStatePath())), &saved); err != nil || saved["Ubuntu-22.04"].Gateway != "192.168.9.147" { + t.Fatalf("wsl.json: %v\n%s", err, readFile(wslStatePath())) + } + a := wslPi(ds[0]) + if !a.Wired() { + t.Fatalf("not wired: SyncCatalog would leave it: %v live %v\n%s", a.Values(), ds[0].live(), readFile(filepath.Join(home, ".pi", "agent", "settings.json"))) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + p := pi() + if p["baseUrl"] != "http://192.168.9.147:"+gateway.Port()+"/v1" || p["apiKey"] != gateway.WSLKey() || gateway.WSLKey() == "" { + t.Fatalf("after a sync: %v (WSL key %q)", p, gateway.WSLKey()) + } +} + +func jsonInt(n int) string { b, _ := json.Marshal(n); return string(b) } diff --git a/internal/gateway/wsl.go b/internal/gateway/wsl.go index 039de085c..846900ffa 100644 --- a/internal/gateway/wsl.go +++ b/internal/gateway/wsl.go @@ -19,6 +19,7 @@ import ( "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/wslrun" ) // A WSL distro in NAT networking (WSL's default) reaches Windows at the @@ -36,34 +37,11 @@ import ( // of Docker Desktop's, which shares that network, has no key. // WSLNets are the networks Windows has an address on that WSL distros reach -// it through: the IPv4 addresses of the vEthernet (WSL) adapters (named -// "vEthernet (WSL)" or, with the Hyper-V firewall, "vEthernet (WSL (Hyper-V -// firewall))"), there while WSL's VM runs. None off Windows. A var for the -// tests. +// it through (wslrun.Nets): the vEthernet (WSL…) adapters', NAT's and a +// bridged switch's. None off Windows. A var for the tests. var WSLNets = wslNets -func wslNets() []*net.IPNet { - if runtime.GOOS != "windows" { - return nil - } - ifs, err := net.Interfaces() - if err != nil { - return nil - } - var out []*net.IPNet - for _, i := range ifs { - if i.Flags&net.FlagUp == 0 || !strings.Contains(i.Name, "(WSL") { - continue - } - addrs, _ := i.Addrs() - for _, a := range addrs { - if n, ok := a.(*net.IPNet); ok && n.IP.To4() != nil && !n.IP.IsLinkLocalUnicast() { - out = append(out, n) - } - } - } - return out -} +func wslNets() []*net.IPNet { return wslrun.Nets() } // OnWSLNet says base (an agent's gateway URL) names an address Windows has // on a WSL network: where a distro under NAT reaches the gateway. diff --git a/internal/wslrun/hostat_test.go b/internal/wslrun/hostat_test.go new file mode 100644 index 000000000..24e121298 --- /dev/null +++ b/internal/wslrun/hostat_test.go @@ -0,0 +1,75 @@ +package wslrun + +import ( + "net" + "testing" +) + +func ipNet(t *testing.T, cidr string) *net.IPNet { + t.Helper() + ip, n, err := net.ParseCIDR(cidr) + if err != nil { + t.Fatal(err) + } + n.IP = ip + return n +} + +// ecalpal_ on Discord (WSL 3.0.3.0, .wslconfig vmSwitch=WSL_Bridge_Switch, +// networkingMode=Bridged, dhcp=false): the distro's default route is the +// LAN's router, 192.168.9.1, and Windows is at 192.168.9.147/24 on +// vEthernet (WSL_Bridge_Switch). Each mode is checked with its own values. +func TestHostAt(t *testing.T) { + bridge := []*net.IPNet{ipNet(t, "192.168.9.147/24")} + nat := []*net.IPNet{ipNet(t, "172.20.0.1/20")} + both := append(append([]*net.IPNet{}, nat...), bridge...) + for _, c := range []struct { + mode, route string + nets []*net.IPNet + want string + }{ + {"bridged", "192.168.9.1", bridge, "192.168.9.147"}, + {"bridged", "192.168.9.1", both, "192.168.9.147"}, + // a .wslconfig-only bridged WSL (no wslinfo) is told by the network + {"", "192.168.9.1", bridge, "192.168.9.147"}, + // the router on no network Windows has on WSL's adapters: nothing + // tells which is Windows, NAT's adapter being up beside a bridge + {"bridged", "10.0.0.1", bridge, "10.0.0.1"}, + {"bridged", "10.0.0.1", nat, "10.0.0.1"}, + // nothing to tell by: kept + {"bridged", "192.168.9.1", nil, "192.168.9.1"}, + // NAT: the next hop is Windows' own address there + {"nat", "172.20.0.1", nat, "172.20.0.1"}, + {"nat", "172.20.0.1", both, "172.20.0.1"}, + {"nat", "172.20.0.1", nil, "172.20.0.1"}, + {"", "172.20.0.1", nat, "172.20.0.1"}, + // mirrored and consomme: Windows' 127.0.0.1 + {"mirrored", "192.168.9.1", bridge, ""}, + {"consomme", "198.18.0.2", nat, ""}, + {"bridged", "", bridge, ""}, + } { + if got := HostAt(c.mode, c.route, c.nets); got != c.want { + t.Errorf("%s via %s on %v: %q, want %q", c.mode, c.route, c.nets, got, c.want) + } + } +} + +// A WSL command found in a bridged distro reaches Windows at its address on +// the bridge, so a proxy at Windows' 127.0.0.1 is handed on there. +func TestParseProbeBridged(t *testing.T) { + old := Nets + t.Cleanup(func() { Nets = old }) + Nets = func() []*net.IPNet { return []*net.IPNet{ipNet(t, "192.168.9.147/24")} } + out := "bin:/home/me/.local/bin/claude\nroute:default via 192.168.9.1 dev eth0 proto static\nnet:bridged\n" + tool, ok := parseProbe("Ubuntu-22.04", out) + if !ok || tool.Host != "192.168.9.147" { + t.Fatalf("%+v", tool) + } + if p := tool.proxy("http://127.0.0.1:7890"); p != "http://192.168.9.147:7890" { + t.Errorf("proxy: %s", p) + } + tool, _ = parseProbe("Ubuntu", "bin:/usr/bin/claude\nroute:default via 172.20.0.1 dev eth0\nnet:nat\n") + if tool.Host != "172.20.0.1" { + t.Errorf("nat: %+v", tool) + } +} diff --git a/internal/wslrun/wslrun.go b/internal/wslrun/wslrun.go index a5bbd7191..c7e2a6c26 100644 --- a/internal/wslrun/wslrun.go +++ b/internal/wslrun/wslrun.go @@ -316,12 +316,74 @@ func parseProbe(distro, out string) (Tool, bool) { if dir := t.Path[:strings.LastIndex(t.Path, "/")]; dir != "" && !onPath(t.PATH, dir) { t.PATH = dir + ":" + t.PATH } - if HostLoopback(net_) { - t.Host = "" - } + t.Host = HostAt(net_, t.Host, Nets()) return t, true } +// Nets are the networks Windows has an address on that WSL distros reach +// it through: the IPv4 addresses of its vEthernet (WSL…) adapters (NAT's +// "vEthernet (WSL)" or "vEthernet (WSL (Hyper-V firewall))", a bridged +// switch's "vEthernet (WSL_Bridge_Switch)"), there while WSL's VM runs. +// None off Windows. A var for the tests. +var Nets = nets + +func nets() []*net.IPNet { + if runtime.GOOS != "windows" { + return nil + } + ifs, err := net.Interfaces() + if err != nil { + return nil + } + var out []*net.IPNet + for _, i := range ifs { + if i.Flags&net.FlagUp == 0 || !strings.Contains(i.Name, "(WSL") { + continue + } + addrs, _ := i.Addrs() + for _, a := range addrs { + if n, ok := a.(*net.IPNet); ok && n.IP.To4() != nil && !n.IP.IsLinkLocalUnicast() { + out = append(out, n) + } + } + } + return out +} + +// HostAt is the address a distro in networking mode reaches Windows at, +// from its default route's next hop (route) and the networks Windows has +// on WSL's adapters (nets, Nets): "" where its 127.0.0.1 is Windows' +// (HostLoopback). Under NAT the next hop is Windows' address on +// vEthernet (WSL) itself, and is kept. Under bridged networking the +// distro is a peer on the LAN and its next hop is the LAN's router +// (192.168.9.1, ecalpal_ on Discord), not Windows: Windows is at its own +// address on the bridge's adapter, the one whose network holds that +// router. A next hop on no WSL network is kept as it was: NAT's +// vEthernet (WSL) can be up beside a bridge on another subnet, and is +// not where a bridged distro reaches Windows. +func HostAt(mode, route string, nets []*net.IPNet) string { + if HostLoopback(mode) { + return "" + } + ip := net.ParseIP(route) + if ip == nil { + return route + } + var in []*net.IPNet + for _, n := range nets { + if n.IP.Equal(ip) { + return route // Windows' own: NAT's + } + if n.Contains(ip) { + in = append(in, n) + } + } + if len(in) == 1 { + return in[0].IP.String() + } + return route +} + // HostLoopback reports whether 127.0.0.1 inside a WSL 2 distro reaches // Windows' own 127.0.0.1 in networking mode, as wslinfo --networking-mode // prints it: mirrored, and consomme (WSL 2.9's name for what was