From 2b22425b45188237e808cd7c8f3b65613c79b8cd Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 9 Nov 2026 15:08:29 +0800 Subject: [PATCH] agent: Claude Science in a WSL distro is found and run on magpie from Windows shuitunlulu_ (Discord) has Claude Science in WSL2, and Windows magpie didn't find it. It is now a WSL twin (claude-science@wsl:), found by the probe's claude-science (~/.local/bin or PATH). Its daemon is restarted there through wsl.exe with ANTHROPIC_BASE_URL set, the same steps as this machine's (claudescience.go is now one scienceHost for here and for each distro), and v0.1.3334's keeper puts it back on magpie in each running distro that has a note (claude-science-wsl-.json). With no note, nothing runs in WSL. The daemon takes http only to a loopback address and sends its Claude sign-in as the key. In mirrored networking it gets the gateway's address. Under NAT magpie starts a relay in the distro: socat on 127.0.0.1: to Windows' WSL address. The daemon gets http://127.0.0.1:/; the gateway's lanGuard takes the key off the path (takeWSLPathKey) before fromWSL judges it. Connect says so when the distro has no socat. Disconnect stops the relay with the connections it forked, as one process group. When Windows' firewall keeps WSL out, the row shows the same firewall drift and rule as other WSL agents. Run: - gofmt -l clean - go vet: darwin, GOOS=linux -tags nogui, GOOS=windows (mote) - go test ./internal/agent ./internal/gateway on mote (macOS) - go test ./internal/agent on xiaomi-gpu (Windows 11): 26 FAIL; 25 fail the same at origin/main c7ebb6f8d on that box (#4115, #5019, #3700, #5344, #2808, #4785, #2958, #1827, #4786). The 26th, TestHermesProfilesFollowMagpieModel, passed 5/5 alone on both and failed only in the whole-package run (#4115, #2540). Every ClaudeScience test passed there. - At the pushed head (rebased on 9dd7aabca, which changes neither package): go vet darwin + windows and -run 'ClaudeScience|WSL' of agent and gateway ok on mote. - Full suite, -timeout 45m: not finished at push. It waits on the lock behind other sessions' runs on mote and on magpie-desktop; the packages it changes (agent, gateway) were run above. - Real run against magpie-desktop (Ubuntu 24.04, NAT, claude-science 0.1.72 in ~/.local/bin) from a Windows test binary, with a sandbox XDG_CONFIG_HOME and a stand-in gateway on 127.0.0.1 and 172.17.32.1: - Connect took about 10s, and /proc//environ had ANTHROPIC_BASE_URL=http://127.0.0.1:/wsl-... - The relay outlived wsl.exe (setsid, its own SID). - With the firewall blocking the test binary, the row's drift named the firewall and the New-NetFirewallRule. - With a temporary allow rule for the test binary (removed afterwards), curl in WSL through the relay reached the stand-in with the key path, and no drift showed. - Daemon and relay were killed as a WSL restart would; one keeper pass brought both back. - Disconnect left no relay and no relay forks (a held curl fork included), and the daemon ran without the variable. Broken by hand: - relay := false: the NAT test went red six ways. - Without lanGuard's takeWSLPathKey line: TestWSLKeyInPath got 403. - Check's firewall branch off: TestClaudeScienceInWSLFirewall red. - A plain kill of the relay pid left a fork connecting on the real distro; that is what led to the process-group kill. Not tried: - The real magpie GUI on Windows with this build. - A daemon's own model request through the relay; only curl was sent. - Bridged networking. - A distro without socat; that path was run only in the fake. Reported-by: shuitunlulu_ (Discord) --- docs/subsystems/agent-wiring.md | 2 +- docs/subsystems/gateway-routing.md | 2 +- internal/agent/claudescience.go | 306 +++++++++++++++-------- internal/agent/claudescience_wsl.go | 205 +++++++++++++++ internal/agent/claudescience_wsl_test.go | 249 ++++++++++++++++++ internal/agent/wsl.go | 15 +- internal/gateway/lan.go | 4 +- internal/gateway/wsl.go | 39 ++- internal/gateway/wsl_test.go | 47 ++++ 9 files changed, 763 insertions(+), 106 deletions(-) create mode 100644 internal/agent/claudescience_wsl.go create mode 100644 internal/agent/claudescience_wsl_test.go diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 48db00c1a..f6300b930 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -34,7 +34,7 @@ something else shows up as drift. | Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`), each model's tokens weighed at what magpie bills them where the agent asked for a model magpie wrote (a provider/model id resolves as the gateway resolves it and is weighed at that provider's price, `pricedWeights`, so a Claude model on Copilot has its 1-hour cache write at the 5-minute one Copilot bills, #3435), else at its maker's list ratios (`tune.WeightsFor`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings..autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated tokens against the setting now (fewer or more, the setting itself marked "Your setting now", hayden4608 on Discord), "Fewest tokens" beside the leanest, and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) | | Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. One whose agent keeps the model a new session starts on in a file apart from its provider list says so with `startup` (`config`, `format`, `model`, and `keys` written beside the model as they are) and has no `model`: PiG keeps its providers in `models.json` and `defaultProvider`/`defaultModel` in `settings.json` (str_ on Discord: its row only listed models, where Pi's picks the one it starts on). Its field is `model` again; picking one of magpie's writes `connect`'s keys into `config` and the model and `startup.keys` into `startup.config`, each file stashed under its own `plugin::` (the startup one marked by its first string key, so a model picked in the agent among magpie's, with `defaultProvider` still `magpie`, reads as magpie's). A model of the agent's own picked in it while `connect`'s keys are still in `config` is `Beside`: connected, not drift, and Disconnect leaves that pick and takes the rest out. A magpie without `startup` reads the same module as connect only (`TestPluggedStartupModel`, `TestPluggedStartupOwnPickKept`, `TestPluggedStartupRestoreGone`). `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`; a routing group's, `provider.GroupEndpoints`, the APIs every member relays as it is; carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) | | Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL` and `--model` (no `--model` when the user gives one) while settings.json's model is still magpie's, and unchanged otherwise. PowerShell's asks `magpie agy env` for them, since the Windows app is a GUI program PowerShell doesn't wait for. `Typed` says the function is there; the row then says plain `agy` works in a new terminal, and the `Launch` command is for a terminal open before. agy has no settings-only route: 1.4.7 refuses to start without `GEMINI_API_KEY` in the environment even with a key on the custom model. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`pickedEfforts`, #1003). Antigravity's app has the same field while it is on magpie: its picker lists the gateway's models with no level of its own, so one of Antigravity's families of levels went at its default (MDX-Tom, #4838). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) | -| Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer). The app (0.1.72, Electron) attaches its window to a daemon running; with none it starts its own (`serve --stdio --adopt-install`, `launch_context` `app-child`) in its own environment, without the variable, and its "let the app run it instead" (and its offer once the app updated past the daemon) stops magpie's to do the same (shuitunlulu_ on Discord: Claude Science went back off magpie). So the keeper also puts magpie's daemon back, on the port the other was on, in place of one with another pid, one started for the gateway's old address, or its own older than the program installed (`--version`, asked again only when the file changed) (`scienceStale`), but only when `status` says no session runs in it (`active_frames` and `active_conversations` 0; a status without them is busy), never one launchd or systemd keeps (`launch_context`), and at most three times an hour (`scienceRetakes`). It reads `operon.lock` every 10 s and asks `status` when the lock's pid changed or a minute went by. A window on the daemon stopped shows the app's "stopped from the command line" screen, whose "start it again in the app" attaches it to magpie's. `Check` reads the daemon's `operon.lock`, not `status` (most of a second for a 130 MB Bun program), and calls a daemon with another pid drift until the keeper replaces it. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). | [`claudescience.go`](../../internal/agent/claudescience.go), [`science.go`](../../internal/gateway/science.go) | +| Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer). The app (0.1.72, Electron) attaches its window to a daemon running; with none it starts its own (`serve --stdio --adopt-install`, `launch_context` `app-child`) in its own environment, without the variable, and its "let the app run it instead" (and its offer once the app updated past the daemon) stops magpie's to do the same (shuitunlulu_ on Discord: Claude Science went back off magpie). So the keeper also puts magpie's daemon back, on the port the other was on, in place of one with another pid, one started for the gateway's old address, or its own older than the program installed (`--version`, asked again only when the file changed) (`scienceStale`), but only when `status` says no session runs in it (`active_frames` and `active_conversations` 0; a status without them is busy), never one launchd or systemd keeps (`launch_context`), and at most three times an hour (`scienceRetakes`). It reads `operon.lock` every 10 s and asks `status` when the lock's pid changed or a minute went by. A window on the daemon stopped shows the app's "stopped from the command line" screen, whose "start it again in the app" attaches it to magpie's. `Check` reads the daemon's `operon.lock`, not `status` (most of a second for a 130 MB Bun program), and calls a daemon with another pid drift until the keeper replaces it. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). In a WSL distro (shuitunlulu_ on Discord) it is a WSL twin (`wslKinds`, found by `claude-science` on the probe's PATH, keeping its own notice) whose daemon magpie runs there through `wsl.exe` (`scienceInWSL`, `scienceWSLScript`; the same `scienceHost` steps as this machine's, its note `claude-science-wsl-.json`). The daemon takes http only to a loopback address, so in mirrored networking it gets the gateway's address, and under NAT a relay magpie starts in the distro: `socat` on `127.0.0.1:` to Windows' address on the WSL network (`scienceRelayScript`, its pid and target in `~/.claude-science/magpie-relay`, stopped with its forks as a process group on Disconnect or when the target moved). It is given `http://127.0.0.1:/`, the key in the path, as it sends its own sign-in as the key (gateway-routing's WSL under NAT). Connect says so when the distro has no socat. The keeper runs nothing in WSL until a distro's note exists, then starts both again in each running distro (`wslScienceHosts`). Its `Check` adds the firewall drift any agent pointed at Windows' WSL address gets (`unreachable`), as its one value isn't a model of magpie's, which is what `Drift` asks that of. | [`claudescience.go`](../../internal/agent/claudescience.go), [`claudescience_wsl.go`](../../internal/agent/claudescience_wsl.go), [`science.go`](../../internal/gateway/science.go) | | Claude Code beside its own account | `claude-magpie` (baranwang on X) starts Claude Code through magpie while a plain `claude` stays on the user's own account, nothing switched back and forth. `magpie claude run [args…]` writes `/claude-launch/settings.json` as `claude#launch`, an agent `claudeIn` makes at that folder (`place.dir`) and lists nowhere, so the Agents page, Check and Notice see only the user's settings.json: connected the first time as Connect would (`ConnectHow`), set again when the gateway's address or key moved (`claudeLaunchStale`, the LAN key included), synced after that, with `ANTHROPIC_API_KEY` and the cloud switches (`agentenv.ClaudeProviders`) blanked. It then runs `claude --settings args…` as a child (not exec, so it can tidy after): Claude Code puts a --settings file's env and model over the user's settings.json, a claude.ai sign-in and the shell (tried on 2.1.318). `/model` saves to the user's settings.json, never the --settings file, so `ClaudeLaunchAfter` moves a magpie model picked there into the launch file and gives the user's file its model back while magpie isn't wired into it; it also undoes Claude Code's own one-time `opus` → `opus[1m]` rewrite (`migration_opus_to_opus1m`), which the launch file's 1M opus tier sets off. A Claude alias picked (`sonnet`) stays. On Unix a stopped child stops magpie too (^Z, fg), and its exit code is magpie's; on Windows magpie ignores Ctrl+C while claude runs. The command `claude-magpie` is a launcher beside the `magpie` command (`update.Launchers`): a `#!/bin/sh` `exec` of `Program()`, or on Windows a `.cmd` running `"%~dp0magpie"`. `AddCLI` writes it, and `magpie claude launcher add` puts it there for a command added before; a file by that name without `written by magpie` is never written over. StandIn falls back to the launch file's tiers. | [`claude_launch.go`](../../internal/agent/claude_launch.go), [`claude_launch_cli.go`](../../internal/cli/claude_launch_cli.go), [`claude_run_unix.go`](../../internal/cli/claude_run_unix.go), [`launcher.go`](../../internal/update/launcher.go) | ## Runtime path diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 49bbbb259..0ac636ba1 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). 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) | +| 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`). A client that can only send its own key (Claude Science in WSL, which sends its Claude sign-in) puts the WSL key first in the path instead, `//v1/…`: `takeWSLPathKey` takes it off before `fromWSL` judges the request, and the request goes on without it. 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 the asking agent's own subscription in magpie serves (a provider whose `Account.Agent` is the agent: Codex's ChatGPT accounts for Codex, Claude's for Claude Code) goes to that subscription first, found groups on or off (`ownFirst`, `provider.OwnRoute`; freefcw on X: Codex's bare `gpt-6-astra` went to Devin through `auto-gpt-6-astra`, whose soonest-renewing member came first, and with found groups off to the first provider in the order). Not for a group the user made or changed by that name, a found group magpie set one of the agent's fields to (`SetToGroup`, `agent.SetToGroup` over the agent's applied record, #750's bare spelling included), a gateway key held to some models, or a client magpie doesn't know as an agent; an auto stand-in and `agent.Reseat` prefer the agent's own subscription the same way (`AutoStandInFor`, `sameModel`). Otherwise a bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api): with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, an agent with a subscription of its own in magpie is refused it with a 400 naming the providers' ids and `magpie group auto on` (`provider.OffSpread`, `offSpreadRefused`): off, magpie picks no vendor for it. Any other client still gets the first provider in the Providers order that exposes it (`Resolve`), with no fallback. A provider the user keeps out of found groups (Routing's "Leave out a provider", `provider.SetAutoGroupSkip`, `autoGroupSkip` in providers.json; chenxiang0010 on Discord) is in none of them, so a model one other provider serves is no group; the groups the user made or changed keep it. A request still naming a found group that took away goes to its model from a provider not kept out (`AutoStandIn`), and an agent set to it is moved there (`agent.Reseat`). magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | diff --git a/internal/agent/claudescience.go b/internal/agent/claudescience.go index ce80cbdc8..15f4e039e 100644 --- a/internal/agent/claudescience.go +++ b/internal/agent/claudescience.go @@ -153,14 +153,62 @@ var scienceDir = func() string { return filepath.Join(home, ".claude-science") } -// scienceLock is the daemon running as its lock file says (operon.lock: -// its pid, port and start), false when there is none. It is read where -// status would take seconds — the program is a 130 MB Bun build — as the -// Agents page is drawn; a lock a crash left is taken for the daemon, -// which only Check reads it for. -func scienceLock() (scienceStatus, bool) { +// scienceHost is where a Claude Science daemon runs: this machine +// (scienceHere), or a WSL distro (claudescience_wsl.go), whose daemon +// magpie on Windows starts through wsl.exe. +type scienceHost struct { + id string // the agent's id + bin func() string // its program, "" when it isn't installed + // run runs the program bin with args, a serve with the variable set to + // gw ("": without it), and is what it printed + run func(bin, gw string, args ...string) ([]byte, error) + // dir is the daemon's data folder as magpie opens it + dir func() string + // stat is the program's file, for its version (asked again only when + // it changed) + stat func(bin string) (os.FileInfo, error) + // gw is the address its daemon is given now; ready, when set, readies + // the way there before the daemon is started on it, and on each look + // of the keeper's while it is connected (the relay in a distro under + // NAT) + gw func() string + ready func() error + // unready, when set, takes that way down again (Disconnect) + unready func() error + mark func() string // magpie's note of the daemon it started + keep *scienceKeeper + mu *sync.Mutex // holds one start or stop of its daemon at a time +} + +// scienceHere is this machine's Claude Science. +func scienceHere() *scienceHost { + return &scienceHost{ + id: ScienceID, + bin: func() string { return scienceBin() }, + run: func(bin, gw string, args ...string) ([]byte, error) { + var env []string + if len(args) > 0 && args[0] == "serve" { + env = scienceEnv(gw) + } + return scienceRun(env, bin, args...) + }, + dir: func() string { return scienceDir() }, + stat: os.Stat, + gw: gateway.URL, + mark: scienceMarkPath, + keep: &scienceKeep, + mu: &scienceMu, + } +} + +// lock is the daemon running as its lock file says (operon.lock: its pid, +// port and start), false when there is none. It is read where status +// would take seconds — the program is a 130 MB Bun build — as the Agents +// page is drawn; a lock a crash left is taken for the daemon, which only +// Check reads it for. +func (h *scienceHost) lock() (scienceStatus, bool) { var st scienceStatus - b, err := os.ReadFile(filepath.Join(scienceDir(), "operon.lock")) + b, err := os.ReadFile(filepath.Join(h.dir(), "operon.lock")) if err != nil || json.Unmarshal(b, &st) != nil || st.PID == 0 { return st, false } @@ -168,9 +216,9 @@ func scienceLock() (scienceStatus, bool) { return st, true } -func scienceState(bin string) (scienceStatus, error) { +func (h *scienceHost) state(bin string) (scienceStatus, error) { var st scienceStatus - out, err := scienceRun(nil, bin, "status") + out, err := h.run(bin, "", "status") if err != nil { return st, fmt.Errorf("claude-science status: %w", err) } @@ -190,9 +238,13 @@ type scienceMark struct { func scienceMarkPath() string { return filepath.Join(appdir.Config(), "claude-science.json") } -func readScienceMark() (scienceMark, bool) { +func readScienceMark() (scienceMark, bool) { return scienceHere().readMark() } + +func writeScienceMark(m scienceMark) error { return scienceHere().writeMark(m) } + +func (h *scienceHost) readMark() (scienceMark, bool) { var m scienceMark - b, err := os.ReadFile(scienceMarkPath()) + b, err := os.ReadFile(h.mark()) if err != nil { return m, false } @@ -201,7 +253,15 @@ func readScienceMark() (scienceMark, bool) { return m, true } -func scienceWired() bool { _, ok := readScienceMark(); return ok } +func (h *scienceHost) wired() bool { _, ok := h.readMark(); return ok } + +func (h *scienceHost) writeMark(m scienceMark) error { + b, _ := json.Marshal(m) + if err := os.MkdirAll(filepath.Dir(h.mark()), 0o700); err != nil { + return err + } + return os.WriteFile(h.mark(), b, 0o600) +} // scienceEnv is magpie's environment with the variable set to gw, or // without it for "". @@ -218,42 +278,47 @@ func scienceEnv(gw string) []string { return env } -// scienceMu holds one start or stop of the daemon at a time. +// scienceMu holds one start or stop of this machine's daemon at a time. var scienceMu sync.Mutex -// scienceRestart stops the daemon when it runs and starts it on gw ("": -// without the variable), on the port it was on; only stops it for !start. -// It is the daemon now running. -func scienceRestart(bin, gw string, start bool) (scienceStatus, error) { - was, err := scienceState(bin) +// restart stops the daemon when it runs and starts it on gw ("": without +// the variable), on the port it was on; only stops it for !start. It is +// the daemon now running. +func (h *scienceHost) restart(bin, gw string, start bool) (scienceStatus, error) { + was, err := h.state(bin) if err != nil { return was, err } if was.Running { - if out, err := scienceRun(nil, bin, "stop"); err != nil { + if out, err := h.run(bin, "", "stop"); err != nil { return was, fmt.Errorf("claude-science stop: %w %s", err, strings.TrimSpace(string(out))) } } if !start { return scienceStatus{}, nil } - return scienceServe(bin, gw, was.Port) + return h.serve(bin, gw, was.Port) } -// scienceServe starts the daemon on gw ("": without the variable), on -// port when it isn't 0, and waits till status says it runs. -func scienceServe(bin, gw string, port int) (scienceStatus, error) { +// serve starts the daemon on gw ("": without the variable), on port when +// it isn't 0, and waits till status says it runs. +func (h *scienceHost) serve(bin, gw string, port int) (scienceStatus, error) { + if gw != "" && h.ready != nil { + if err := h.ready(); err != nil { + return scienceStatus{}, err + } + } args := []string{"serve", "--detached", "--no-browser"} if port > 0 { args = append(args, "--port", strconv.Itoa(port)) } - if _, err := scienceRun(scienceEnv(gw), bin, args...); err != nil { - return scienceStatus{}, fmt.Errorf("claude-science serve: %w", err) + if out, err := h.run(bin, gw, args...); err != nil { + return scienceStatus{}, fmt.Errorf("claude-science serve: %w %s", err, strings.TrimSpace(string(out))) } var st scienceStatus for deadline := time.Now().Add(scienceWait); ; { var err error - if st, err = scienceState(bin); err == nil && st.Running { + if st, err = h.state(bin); err == nil && st.Running { return st, nil } if time.Now().After(deadline) { @@ -266,85 +331,100 @@ func scienceServe(bin, gw string, port int) (scienceStatus, error) { // scienceWait is how long a daemon started may take to say it runs. var scienceWait = 30 * time.Second -// scienceOn restarts the daemon on the gateway, and notes it; off -// restarts it without the variable, when it ran, and drops the note. -func scienceOn(on bool) error { - scienceMu.Lock() - defer scienceMu.Unlock() - bin := scienceBin() +func scienceOn(on bool) error { return scienceHere().on(on) } + +// on restarts the daemon on the gateway, and notes it; off restarts it +// without the variable, when it ran, and drops the note. +func (h *scienceHost) on(on bool) error { + h.mu.Lock() + defer h.mu.Unlock() + bin := h.bin() if !on { - if _, wired := readScienceMark(); wired && bin != "" { - st, err := scienceState(bin) + if wired := h.wired(); wired && bin != "" { + st, err := h.state(bin) if err != nil { return err } if st.Running { - if _, err := scienceRestart(bin, "", true); err != nil { + if _, err := h.restart(bin, "", true); err != nil { return err } } } - if err := os.Remove(scienceMarkPath()); err != nil && !os.IsNotExist(err) { + if err := os.Remove(h.mark()); err != nil && !os.IsNotExist(err) { return err } + if h.unready != nil { + return h.unready() + } return nil } if bin == "" { return errors.New(scienceName + " isn't installed (no claude-science found)") } - gw := gateway.URL() + gw := h.gw() + if gw == "" { + return errors.New("magpie couldn't make the key that gives " + scienceName + " in WSL the gateway (wsl-key in magpie's folder)") + } // the daemon magpie started, on this gateway, is left running: Connect // sets the field it connected by again (Pick) - if m, wired := readScienceMark(); wired && m.URL == gw { - if st, err := scienceState(bin); err == nil && st.Running && st.PID == m.PID { + if m, wired := h.readMark(); wired && m.URL == gw { + if st, err := h.state(bin); err == nil && st.Running && st.PID == m.PID { + if h.ready != nil { + return h.ready() + } return nil } } - st, err := scienceRestart(bin, gw, true) + st, err := h.restart(bin, gw, true) if err != nil { return err } - return writeScienceMark(scienceMark{URL: gw, PID: st.PID, Port: st.Port}) + return h.writeMark(scienceMark{URL: gw, PID: st.PID, Port: st.Port}) } -func writeScienceMark(m scienceMark) error { - b, _ := json.Marshal(m) - if err := os.MkdirAll(filepath.Dir(scienceMarkPath()), 0o700); err != nil { - return err - } - return os.WriteFile(scienceMarkPath(), b, 0o600) -} +func scienceCheck() string { return scienceHere().check() } -// scienceCheck is what of the wiring is gone, by the daemon's lock file: a -// daemon running that magpie -// didn't start (the window, opened while none ran, starts its own), or one -// started for the gateway's old address. One not running is no drift: -// KeepClaudeScience starts it. -func scienceCheck() string { - m, wired := readScienceMark() +// check is what of the wiring is gone, by the daemon's lock file: a +// daemon running that magpie didn't start (the window, opened while none +// ran, starts its own), or one started for the gateway's old address. One +// not running is no drift: KeepClaudeScience starts it. +func (h *scienceHost) check() string { + m, wired := h.readMark() if !wired { return "" } - st, running := scienceLock() + st, running := h.lock() if !running { return "" } if st.PID != m.PID { return fmt.Sprintf("%s's daemon (pid %d) was started without magpie's gateway (its window starts its own when none runs); magpie starts its own in its place once no session runs in it", scienceName, st.PID) } - if m.URL != gateway.URL() { - return fmt.Sprintf("%s's daemon was started for the gateway at %s", scienceName, m.URL) + if m.URL != h.gw() { + return fmt.Sprintf("%s's daemon was started for the gateway at %s", scienceName, scienceShown(m.URL)) } return "" } +// scienceShown is a daemon's address as it is said: without the WSL key +// a relay's carries (claudescience_wsl.go). +func scienceShown(gw string) string { + if i := strings.Index(gw, "/wsl-"); i >= 0 { + return gw[:i] + } + return gw +} + // KeepClaudeScience starts the daemon on the gateway, while Claude Science // is connected, whenever it isn't running (after a restart of the // computer, or after it was stopped), and in place of one running that // magpie didn't start or that is older than the program installed now -// (scienceStale), once no session runs in it. It reads the lock file every -// few seconds and asks status (most of a second of a 130 MB Bun program) -// when the lock's pid changed or a minute went by. +// (stale), once no session runs in it. It reads the lock file every few +// seconds and asks status (most of a second of a 130 MB Bun program) +// when the lock's pid changed or a minute went by. It does the same for +// each running WSL distro's Claude Science magpie connected +// (wslScienceHosts), and never starts a stopped distro. func KeepClaudeScience(ctx context.Context) { keepScienceOnce() tick := time.NewTicker(scienceTick) @@ -362,10 +442,10 @@ func KeepClaudeScience(ctx context.Context) { // scienceTick is how often the keeper reads the lock file. const scienceTick = 10 * time.Second -// scienceKeep is what the keeper saw: the lock's pid when it last asked -// status, and when; the program's version by its size and time; the -// times it put its daemon in place of another. -var scienceKeep struct { +// scienceKeeper is what the keeper saw of a host: the lock's pid when it +// last asked status, and when; the program's version by its size and +// time; the times it put its daemon in place of another. +type scienceKeeper struct { asked time.Time lockPID int bin string @@ -375,23 +455,26 @@ var scienceKeep struct { retook []time.Time } +// scienceKeep is this machine's. +var scienceKeep scienceKeeper + // scienceRetakes is how many times in an hour the keeper puts its daemon // in place of another before it leaves the other running: one the user // keeps putting back is theirs. const scienceRetakes = 3 -// scienceVersion is the version of the program at bin, "" unknown, asked -// again only when the file changed (the app updated). -func scienceVersion(bin string) string { - fi, err := os.Stat(bin) +// version is the version of the program at bin, "" unknown, asked again +// only when the file changed (the app updated). +func (h *scienceHost) version(bin string) string { + fi, err := h.stat(bin) if err != nil { return "" } - k := &scienceKeep + k := h.keep if k.bin == bin && k.binSize == fi.Size() && k.binTime.Equal(fi.ModTime()) { return k.version } - out, err := scienceRun(nil, bin, "--version") + out, err := h.run(bin, "", "--version") if err != nil { return "" } @@ -428,51 +511,69 @@ func olderVersion(a, b string) bool { return false } -// scienceStale is why the daemon running isn't the one magpie keeps: one -// it didn't start, one started for the gateway's old address, or its own +// stale is why the daemon running isn't the one magpie keeps: one it +// didn't start, one started for the gateway's old address, or its own // older than the program installed (the app updated, and would offer to // run its own instead); "" when it is. -func scienceStale(bin string, st scienceStatus, m scienceMark, gw string) string { +func (h *scienceHost) stale(bin string, st scienceStatus, m scienceMark, gw string) string { switch { case st.PID != m.PID: return fmt.Sprintf("pid %d isn't the one magpie started", st.PID) case m.URL != gw: - return "it was started for the gateway at " + m.URL + return "it was started for the gateway at " + scienceShown(m.URL) } - if v := scienceVersion(bin); v != "" && olderVersion(st.Version, v) { + if v := h.version(bin); v != "" && olderVersion(st.Version, v) { return fmt.Sprintf("it runs %s and %s is installed", st.Version, v) } return "" } func keepScienceOnce() { - if !scienceWired() { + scienceHere().keepOnce() + for _, h := range wslScienceHosts() { + h.keepOnce() + } +} + +func (h *scienceHost) keepOnce() { + if !h.wired() { return } - scienceMu.Lock() - defer scienceMu.Unlock() - bin := scienceBin() + h.mu.Lock() + defer h.mu.Unlock() + bin := h.bin() if bin == "" { return } - k := &scienceKeep - lock, _ := scienceLock() + k := h.keep + lock, _ := h.lock() if lock.PID == k.lockPID && time.Since(k.asked) < time.Minute { return } - st, err := scienceState(bin) + st, err := h.state(bin) k.asked, k.lockPID = time.Now(), lock.PID if err != nil { return } - gw := gateway.URL() - m, _ := readScienceMark() + gw := h.gw() + if gw == "" { + return + } + m, _ := h.readMark() port := m.Port if st.Running { - why := scienceStale(bin, st, m, gw) + why := h.stale(bin, st, m, gw) // a session running in it would be cut off; a service would start // it again without the variable if why == "" || !st.idle() || st.kept() { + if why == "" && h.ready != nil { + // its way to the gateway, gone with a restart of WSL's VM + // that the daemon came back from (or moved to Windows' + // address there now) + if err := h.ready(); err != nil { + log.Printf("%s (%s): %v", scienceName, h.id, err) + } + } return } cut := time.Now().Add(-time.Hour) @@ -481,21 +582,21 @@ func keepScienceOnce() { return } k.retook = append(k.retook, time.Now()) - log.Printf("%s: starting its daemon on magpie's gateway again: %s", scienceName, why) - if out, err := scienceRun(nil, bin, "stop"); err != nil { - log.Printf("%s: claude-science stop: %v %s", scienceName, err, strings.TrimSpace(string(out))) + log.Printf("%s (%s): starting its daemon on magpie's gateway again: %s", scienceName, h.id, why) + if out, err := h.run(bin, "", "stop"); err != nil { + log.Printf("%s (%s): claude-science stop: %v %s", scienceName, h.id, err, strings.TrimSpace(string(out))) return } port = st.Port } - st, err = scienceServe(bin, gw, port) + st, err = h.serve(bin, gw, port) if err != nil { - log.Printf("%s: starting its daemon on magpie's gateway: %v", scienceName, err) + log.Printf("%s (%s): starting its daemon on magpie's gateway: %v", scienceName, h.id, err) return } k.lockPID = st.PID - if err := writeScienceMark(scienceMark{URL: gw, PID: st.PID, Port: st.Port}); err != nil { - log.Printf("%s: %v", scienceName, err) + if err := h.writeMark(scienceMark{URL: gw, PID: st.PID, Port: st.Port}); err != nil { + log.Printf("%s (%s): %v", scienceName, h.id, err) } } @@ -509,15 +610,18 @@ func ScienceLaunch(bin, gw string) string { return q + " stop; " + scienceVar + "=" + gw + " " + q + " serve --detached" } -func claudeScience() *Agent { +func claudeScience() *Agent { return scienceAgent(scienceHere()) } + +// scienceAgent is the row of h's Claude Science. +func scienceAgent(h *scienceHost) *Agent { return &Agent{ - ID: ScienceID, Name: scienceName, Icon: "claude-color", Aliases: []string{"operon", "science"}, + ID: h.id, Name: scienceName, Icon: "claude-color", Aliases: []string{"operon", "science"}, // its picker lists the gateway's /v1/models as it is shown them // (gateway/science.go), which the row's Models button picks ListsModels: true, - detect: func() bool { return scienceBin() != "" }, + detect: func() bool { return h.bin() != "" }, Launch: func() string { - if bin := scienceBin(); bin != "" && scienceWired() { + if bin := h.bin(); bin != "" && h.wired() && h.id == ScienceID { return ScienceLaunch(bin, gateway.URL()) } return "" @@ -525,20 +629,20 @@ func claudeScience() *Agent { Fields: []Field{{ Key: "provider", Label: "provider", Get: func() string { - if scienceWired() { + if h.wired() { return magpieID } return "" }, - Set: func(v string) error { return scienceOn(v != "") }, + Set: func(v string) error { return h.on(v != "") }, Options: func(map[string]string) []Option { return []Option{{Value: magpieID, Label: "magpie", Icon: "magpie", Note: "magpie restarts its daemon with ANTHROPIC_BASE_URL set to the gateway; a session running in it is cut off"}} }, }}, - Check: scienceCheck, + Check: h.check, Notice: func() string { - if !scienceWired() { + if !h.wired() { return "" } return noticeScience.say("agent", scienceName) diff --git a/internal/agent/claudescience_wsl.go b/internal/agent/claudescience_wsl.go new file mode 100644 index 000000000..569b8322b --- /dev/null +++ b/internal/agent/claudescience_wsl.go @@ -0,0 +1,205 @@ +package agent + +import ( + "fmt" + "net" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/gateway" +) + +// Claude Science in a WSL distro (shuitunlulu_ on Discord): its daemon +// runs in the distro, so magpie on Windows starts it there through +// wsl.exe, with ANTHROPIC_BASE_URL set, as it does this machine's +// (claudescience.go), and keeps it so from the keeper while the distro +// runs; it never starts a stopped distro to. +// +// The daemon takes http only to a loopback address, and sends its Claude +// sign-in as its key. In mirrored (or consomme) networking the distro's +// 127.0.0.1 is Windows', and it is given the gateway's own address. Under +// NAT it is given a relay magpie starts in the distro: socat on +// 127.0.0.1: there, to Windows' address on the WSL +// network, which the gateway listens on while on loopback; the WSL key, +// which it can't send as a key, goes first in the address's path, where +// the gateway takes it off (gateway.takeWSLPathKey). + +// scienceWSLScript runs claude-science in the distro: $1 is the address +// the daemon is given ("": none), the rest its arguments. The program is +// where its installer puts it (~/.local/bin), else on the login PATH. +const scienceWSLScript = `g=$1; shift; b="$HOME/.local/bin/claude-science"; [ -x "$b" ] || b=$(command -v claude-science 2>/dev/null) || { echo "claude-science isn't installed"; exit 127; }; ` + + `if [ -n "$g" ]; then ANTHROPIC_BASE_URL=$g; export ANTHROPIC_BASE_URL; else unset ANTHROPIC_BASE_URL; fi; exec "$b" "$@" /dev/null)" = socat ]; then [ "$was" = "$to" ] && exit 0; kill -TERM -"$pid" 2>/dev/null || kill "$pid" 2>/dev/null; sleep 0.3; fi; rm -f "$pf"; fi; ` + + `[ -z "$to" ] && exit 0; ` + + `command -v socat >/dev/null 2>&1 || { echo "socat isn't installed in the distro (sudo apt install socat)"; exit 3; }; ` + + `mkdir -p "$d"; setsid socat TCP-LISTEN:$port,bind=127.0.0.1,reuseaddr,fork TCP:$to /dev/null 2>&1 & pid=$!; sleep 0.5; ` + + `if [ "$(cat /proc/$pid/comm 2>/dev/null)" = socat ]; then echo "$pid $to" > "$pf"; exit 0; fi; ` + + `echo "socat couldn't listen on 127.0.0.1:$port there (taken by another program?)"; exit 4` + +// scienceWSLKeeps are the keepers' states of the distros' daemons, by +// distro. +var scienceWSLKeeps = struct { + sync.Mutex + keep map[string]*scienceKeeper + mu map[string]*sync.Mutex +}{keep: map[string]*scienceKeeper{}, mu: map[string]*sync.Mutex{}} + +// scienceWSLMark is magpie's note of the daemon it started in distro +// name: one file a distro, as each keeps its own. +func scienceWSLMark(name string) string { + safe := strings.Map(func(r rune) rune { + if r == '-' || r == '_' || r == '.' || r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' { + return r + } + return '_' + }, name) + return filepath.Join(appdir.Config(), "claude-science-wsl-"+safe+".json") +} + +// scienceWSLRun runs script in distro name with args; a var for tests. +var scienceWSLRun = func(name string, timeout time.Duration, script string, args ...string) ([]byte, error) { + return wslRun(timeout, append([]string{"-d", name, "-e", "sh", "-lc", script, "sh"}, args...)...) +} + +// scienceInWSL is the Claude Science of distro d. +func scienceInWSL(d distro) *scienceHost { + scienceWSLKeeps.Lock() + k := scienceWSLKeeps.keep[d.Name] + if k == nil { + k = &scienceKeeper{} + scienceWSLKeeps.keep[d.Name] = k + } + mu := scienceWSLKeeps.mu[d.Name] + if mu == nil { + mu = &sync.Mutex{} + scienceWSLKeeps.mu[d.Name] = mu + } + scienceWSLKeeps.Unlock() + home := d.local(d.Home) + relay := !d.Mirrored && d.Gateway != "" + h := &scienceHost{ + id: ScienceID + "@wsl:" + d.Name, + // found by the probe: the script finds it again where it runs + bin: func() string { + if d.Has["bin:claude-science"] { + return "claude-science" + } + return "" + }, + run: func(_, gw string, args ...string) ([]byte, error) { + out, err := scienceWSLRun(d.Name, 90*time.Second, scienceWSLScript, append([]string{gw}, args...)...) + if err != nil && len(out) > 0 { + err = fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out))) + } + return out, err + }, + dir: func() string { + p, err := d.open(filepath.Join(home, ".claude-science")) + if err != nil { + return filepath.Join(home, ".claude-science") + } + return p + }, + stat: func(string) (os.FileInfo, error) { + return os.Stat(filepath.Join(home, ".local", "bin", "claude-science")) + }, + gw: func() string { + if !relay { + return d.base() + } + k := gateway.WSLKey() + if k == "" { + return "" + } + return "http://127.0.0.1:" + gateway.Port() + "/" + k + }, + mark: func() string { return scienceWSLMark(d.Name) }, + keep: k, + mu: mu, + } + if relay { + to := net.JoinHostPort(d.Gateway, gateway.Port()) + h.ready = func() error { return scienceRelay(d.Name, gateway.Port(), to) } + h.unready = func() error { return scienceRelay(d.Name, gateway.Port(), "") } + } + return h +} + +// scienceRelay starts the relay in distro name on port to to, or stops +// it for to "". +func scienceRelay(name, port, to string) error { + out, err := scienceWSLRun(name, 30*time.Second, scienceRelayScript, port, to) + if err != nil { + if said := strings.TrimSpace(string(out)); said != "" { + return fmt.Errorf("the relay to magpie's gateway in WSL %s: %s", name, said) + } + return fmt.Errorf("the relay to magpie's gateway in WSL %s: %w", name, err) + } + return nil +} + +// scienceIn is Claude Science's row at a place: a WSL distro's +// (wslKinds); there is none elsewhere. +func scienceIn(p place) *Agent { + if p.wsl == nil { + return &Agent{ID: ScienceID, Name: scienceName, detect: func() bool { return false }} + } + h := scienceInWSL(*p.wsl) + a := scienceAgent(h) + notice := a.Notice + d := *p.wsl + // the relay leads to Windows' address on the WSL network, where the + // gateway listens and Windows' firewall may keep WSL out: its row says + // so as any agent pointed there would (reach.go), though its one value + // isn't a model of magpie's, which is what Drift asks that of + check := a.Check + a.Check = func() string { + if c := check(); c != "" || !h.wired() { + return c + } + if u := a.unreachable(a.Fields[0], magpieID); u != nil { + return u.Detail + } + return "" + } + a.Notice = func() string { + if d.noRelay { + return noticeWSLNoRelay.say("distro", d.Name, "net", d.Net, "agent", scienceName) + } + if notice != nil { + return notice() + } + return "" + } + return a +} + +// wslScienceHosts are the Claude Sciences of the running distros magpie +// connected: none, and no wsl.exe run, while it connected none. +func wslScienceHosts() []*scienceHost { + marks, _ := filepath.Glob(filepath.Join(appdir.Config(), "claude-science-wsl-*.json")) + if len(marks) == 0 { + return nil + } + var out []*scienceHost + for _, d := range wslReady(ScienceID) { + h := scienceInWSL(d) + if h.wired() { + out = append(out, h) + } + } + return out +} diff --git a/internal/agent/claudescience_wsl_test.go b/internal/agent/claudescience_wsl_test.go new file mode 100644 index 000000000..4209e1902 --- /dev/null +++ b/internal/agent/claudescience_wsl_test.go @@ -0,0 +1,249 @@ +package agent + +import ( + "net" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/gateway" +) + +// fakeWSLScience is a distro's claude-science and its relay, as magpie +// runs them through wsl.exe (scienceWSLRun). +type fakeWSLScience struct { + *fakeScience + relay []string // where the relay was started to, "" for each stop + broken string // what the relay script says when it fails +} + +func (f *fakeWSLScience) run(name string, _ time.Duration, script string, args ...string) ([]byte, error) { + if name != "Ubuntu" { + panic("ran in " + name) + } + if script == scienceRelayScript { + if f.broken != "" { + return []byte(f.broken + "\n"), &os.PathError{Op: "wsl", Path: name, Err: os.ErrInvalid} + } + f.relay = append(f.relay, args[0]+" "+args[1]) + return nil, nil + } + if script != scienceWSLScript { + panic("ran " + script) + } + var env []string + if args[0] != "" { + env = []string{scienceVar + "=" + args[0]} + } + return f.fakeScience.run(env, "claude-science", args[1:]...) +} + +func scienceDistro(t *testing.T) distro { + t.Setenv("HOME", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + root := t.TempDir() + d := distro{Name: "Ubuntu", Home: "/home/me", Root: root, Running: true, Gateway: "172.17.32.1", Net: "nat", + Has: map[string]bool{"bin:claude-science": true}, Probe: wslProbeVersion} + if err := os.MkdirAll(d.local("/home/me/.claude-science"), 0o700); err != nil { + t.Fatal(err) + } + return d +} + +func fakeScienceIn(t *testing.T, d distro) *fakeWSLScience { + f := &fakeWSLScience{fakeScience: &fakeScience{dir: d.local("/home/me/.claude-science"), running: true, pid: 40, port: 8123}} + f.lock() + oldRun, oldWait := scienceWSLRun, scienceWait + t.Cleanup(func() { scienceWSLRun, scienceWait = oldRun, oldWait }) + scienceWSLRun, scienceWait = f.run, time.Second + // this machine has none: nothing of it may be run + oldBin := scienceBin + t.Cleanup(func() { scienceBin = oldBin }) + scienceBin = func() string { return "" } + scienceWSLKeeps.Lock() + delete(scienceWSLKeeps.keep, d.Name) + scienceWSLKeeps.Unlock() + return f +} + +// Claude Science in a WSL distro under NAT (shuitunlulu_ on Discord): the +// probe finds it in ~/.local/bin, and Connect restarts its daemon there +// through wsl.exe, given the relay magpie starts in the distro to +// Windows' address on the WSL network, with the WSL key in its path, as +// the daemon takes http only to loopback and sends its Claude sign-in as +// its key. The keeper starts it again there; Disconnect restarts it +// without the variable and stops the relay. +func TestClaudeScienceInWSLUnderNAT(t *testing.T) { + if d := parseProbe("Ubuntu", "home:/home/me\nbin:claude-science /home/me/.local/bin/claude-science\n"); d == nil || !wslKindOf(ScienceID).found(*d) { + t.Fatal("the probe's claude-science isn't found") + } + if !strings.Contains(wslProbeScript, "wslcmd claude-science") { + t.Error("the probe doesn't look for claude-science") + } + d := scienceDistro(t) + f := fakeScienceIn(t, d) + a := wslAgent(wslKindOf(ScienceID), d) + if a.ID != "claude-science@wsl:Ubuntu" || !a.Detected() { + t.Fatalf("row %q detected %v", a.ID, a.Detected()) + } + field := a.Field("provider") + if field.Get() != "" || a.Check() != "" { + t.Fatal("connected before Connect") + } + if err := field.Set(magpieID); err != nil { + t.Fatal(err) + } + port := gateway.Port() + key := gateway.WSLKey() + if !strings.HasPrefix(key, "wsl-") { + t.Fatalf("WSL key %q", key) + } + want := "http://127.0.0.1:" + port + "/" + key + if got, ok := f.base(); !ok || got != want { + t.Errorf("its daemon was started on %q (set %v), want %s", got, ok, want) + } + if to := net.JoinHostPort("172.17.32.1", port); !slices.Equal(f.relay, []string{port + " " + to}) { + t.Errorf("relay %q, want one to %s", f.relay, to) + } + if wantCalls := []string{"status", "stop", "serve --detached --no-browser --port 8123", "status"}; !slices.Equal(f.calls, wantCalls) { + t.Errorf("ran %q, want %q", f.calls, wantCalls) + } + if field.Get() != magpieID || a.Check() != "" { + t.Errorf("after Connect: %q, check %q", field.Get(), a.Check()) + } + // its own notice, not the one telling an agent under NAT to have the + // gateway listen beyond loopback + if n := a.Notice(); !strings.Contains(n, "Claude account") { + t.Errorf("notice %q", n) + } + if _, err := os.Stat(scienceWSLMark("Ubuntu")); err != nil { + t.Errorf("no mark of the distro's: %v", err) + } + if _, ok := readScienceMark(); ok { + t.Error("this machine's Claude Science noted as connected") + } + if a.Launch() != "" { + t.Errorf("launch %q: Windows can't start the distro's", a.Launch()) + } + + // WSL restarted: no daemon and no relay; the keeper starts both + f.running, f.calls, f.relay = false, nil, nil + f.lock() + h := scienceInWSL(d) + h.keepOnce() + if got, _ := f.base(); !f.running || got != want || len(f.relay) != 1 { + t.Errorf("keeper: running %v on %q, relay %q, ran %q", f.running, got, f.relay, f.calls) + } + // its own daemon running: the keeper sees the relay is up each time it + // asks status + f.calls, f.relay = nil, nil + h.keep.asked = time.Time{} + h.keepOnce() + if !slices.Equal(f.calls, []string{"status"}) || len(f.relay) != 1 { + t.Errorf("keeper on its own daemon ran %q, relay %q", f.calls, f.relay) + } + + // no socat: Connect says so + f.broken = "socat isn't installed in the distro (sudo apt install socat)" + os.Remove(scienceWSLMark("Ubuntu")) + if err := field.Set(magpieID); err == nil || !strings.Contains(err.Error(), "socat isn't installed") { + t.Errorf("without socat: %v", err) + } + f.broken = "" + if err := field.Set(magpieID); err != nil { + t.Fatal(err) + } + + f.calls, f.relay = nil, nil + if err := field.Set(""); err != nil { + t.Fatal(err) + } + if _, ok := f.base(); ok || !f.running { + t.Errorf("after Disconnect: running %v env %q", f.running, f.env) + } + if !slices.Equal(f.relay, []string{port + " "}) { + t.Errorf("relay after Disconnect %q, want stopped", f.relay) + } + if field.Get() != "" { + t.Error("still connected") + } +} + +// In mirrored networking the distro's 127.0.0.1 is Windows': its daemon +// is given the gateway's own address, and no relay is started. +func TestClaudeScienceInWSLMirrored(t *testing.T) { + d := scienceDistro(t) + d.Mirrored, d.Net = true, "mirrored" + f := fakeScienceIn(t, d) + a := wslAgent(wslKindOf(ScienceID), d) + if err := a.Field("provider").Set(magpieID); err != nil { + t.Fatal(err) + } + if got, _ := f.base(); got != gateway.URL() || len(f.relay) != 0 { + t.Errorf("mirrored: started on %q, relay %q", got, f.relay) + } + if n := a.Notice(); !strings.Contains(n, "Claude account") { + t.Errorf("notice %q", n) + } +} + +// The keeper runs nothing in WSL while no distro's Claude Science is +// connected. +func TestClaudeScienceWSLKeeperIdle(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + old := wslRun + t.Cleanup(func() { wslRun = old }) + wslRun = func(time.Duration, ...string) ([]byte, error) { panic("wsl.exe run") } + if hs := wslScienceHosts(); hs != nil { + t.Errorf("hosts %v", hs) + } + if m := scienceWSLMark(`Ubuntu:24.04/x`); filepath.Base(m) != "claude-science-wsl-Ubuntu_24.04_x.json" { + t.Errorf("mark %s", m) + } +} + +// Under NAT the relay leads to Windows' address on the WSL network: when +// Windows' firewall keeps WSL out there, the row says so with the rule +// that lets it in, as an agent pointed there itself is told; when WSL gets +// through, nothing is said. +func TestClaudeScienceInWSLFirewall(t *testing.T) { + d := scienceDistro(t) + fakeScienceIn(t, d) + fakeWSLNet(t, "172.17.32.1/20") + nat := "http://172.17.32.1:" + gateway.Port() + fakeReach(t, map[string]bool{gateway.URL(): true, nat: true}) + var mu sync.Mutex + inside := "no" + was := wslRun + t.Cleanup(func() { wslRun = was }) + wslRun = func(_ time.Duration, args ...string) ([]byte, error) { + mu.Lock() + defer mu.Unlock() + if slices.Contains(args, wslReachScript) && slices.Contains(args, nat) { + return []byte(inside + "\n"), nil + } + return nil, nil + } + a := wslAgent(wslKindOf(ScienceID), d) + if dr := driftSettled(t, a); dr != nil { + t.Fatalf("not connected: %+v", dr) + } + if err := a.Field("provider").Set(magpieID); err != nil { + t.Fatal(err) + } + dr := driftSettled(t, a) + if dr == nil || !strings.Contains(dr.Detail, "firewall") || !strings.Contains(dr.Detail, "New-NetFirewallRule") { + t.Fatalf("blocked from WSL: %+v", dr) + } + mu.Lock() + inside = "ok" + mu.Unlock() + reachForget() + if dr := driftSettled(t, a); dr != nil { + t.Errorf("WSL gets through: %+v", dr) + } +} diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index f2db0f0ca..f03806694 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -70,6 +70,9 @@ type place struct { // dir is the agent's config folder when magpie keeps one of its own // for it (claude-magpie's launch file, claude_launch.go); "": its own dir string + // wsl is the distro of an agent there, for one magpie runs there + // itself (Claude Science's daemon); nil on this machine + wsl *distro } func here(home string) place { return place{home: home} } @@ -397,7 +400,7 @@ func (d distro) place(id string) place { kind = k } return place{home: d.local(d.Home), id: id, spell: d.native, sys: d.local, base: d.base, cold: !d.Running, version: d.Versions[kind], - reach: d.open, unreached: new(error), chmod: d.chmod} + reach: d.open, unreached: new(error), chmod: d.chmod, wsl: &d} } // chmod takes the group's and others' bits off local, a file in the distro @@ -436,9 +439,15 @@ type wslKind struct { // asleep, when set, is a stopped distro's options for a field, which // must read nothing of its files; nil keeps the live agent's asleep func(key string) func(map[string]string) []Option + // ownNotice keeps the agent's own notice: one that reaches the gateway + // under NAT by a way of its own (Claude Science's relay) + ownNotice bool } var wslKinds = []wslKind{ + // its daemon, which magpie starts there itself (claudescience_wsl.go): + // the probe looks in ~/.local/bin, where its installer puts it + {id: ScienceID, name: scienceName, dir: ".claude-science", bin: "claude-science", in: scienceIn, ownNotice: true}, {id: "codex", name: "Codex", dir: ".codex", bin: "codex", in: codexIn, restart: newNotice("{agent} in WSL {distro} builds its model list at start-up — restart it, the app-server its sessions share ({command} there) and the Codex app's WSL connection to see this."), asleep: func(key string) func(map[string]string) []Option { @@ -905,7 +914,11 @@ func wslAgent(k wslKind, d distro) *Agent { // its requests carry the agent's User-Agent and are counted as its // Windows twin's, so a prompt with none of "its" own seen isn't a bypass a.LastUsed = nil + own := a.Notice a.Notice = func() string { + if k.ownNotice && own != nil { + return own() + } if !d.Mirrored { return d.notMirrored(k.name) } diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index 231c9c28f..7b7413de6 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -447,7 +447,9 @@ func lanGuard(next http.Handler) http.Handler { } r = takePagePort(r) // a WSL distro's agent, at the address Windows has on its network - // (wsl.go), is one of this computer's + // (wsl.go), is one of this computer's; one given the key in its + // path (Claude Science's) has it taken off first + r = takeWSLPathKey(r) if fromWSL(r) { r = asFromLoopback(r) } diff --git a/internal/gateway/wsl.go b/internal/gateway/wsl.go index 846900ffa..8f3b4f272 100644 --- a/internal/gateway/wsl.go +++ b/internal/gateway/wsl.go @@ -174,7 +174,44 @@ func fromWSL(r *http.Request) bool { return false } k := wslKeyHeld() - return k != "" && slices.ContainsFunc(callerKeys(r), func(v string) bool { return wslToken(v, k) != "" }) + if k == "" { + return false + } + if v, _ := r.Context().Value(wslPathKeyCtx{}).(string); wslToken(v, k) != "" { + return true + } + return slices.ContainsFunc(callerKeys(r), func(v string) bool { return wslToken(v, k) != "" }) +} + +// wslPathKeyCtx holds the WSL key a request's path began with +// (takeWSLPathKey). +type wslPathKeyCtx struct{} + +// takeWSLPathKey is r without the WSL key its path begins with, which is +// kept for fromWSL: /wsl-…/v1/messages is /v1/messages. A client that +// can't send the key as its own is given it in the address: Claude Science +// takes only ANTHROPIC_BASE_URL, with no key of magpie's (it sends its +// Claude sign-in as its bearer), and http there only to a loopback +// address, so in a distro under NAT it is given the relay magpie runs +// there (agent/claudescience_wsl.go), http://127.0.0.1:/wsl-…, to +// this address on the WSL network. A path whose first segment isn't the +// key is left as it is. +func takeWSLPathKey(r *http.Request) *http.Request { + seg, rest, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/") + if !strings.HasPrefix(seg, wslKeyPrefix) { + return r + } + if wslToken(seg, wslKeyHeld()) == "" { + return r + } + r2 := r.Clone(context.WithValue(r.Context(), wslPathKeyCtx{}, seg)) + r2.URL.Path = "/" + rest + if raw := r2.URL.RawPath; raw != "" { + _, rawRest, _ := strings.Cut(strings.TrimPrefix(raw, "/"), "/") + r2.URL.RawPath = "/" + rawRest + } + r2.RequestURI = r2.URL.RequestURI() + return r2 } // asFromLoopback is r as a request from this computer: from loopback, its diff --git a/internal/gateway/wsl_test.go b/internal/gateway/wsl_test.go index ec4b9a334..5899b45c8 100644 --- a/internal/gateway/wsl_test.go +++ b/internal/gateway/wsl_test.go @@ -102,6 +102,53 @@ func TestWSLCallerServedWithSharingOff(t *testing.T) { } } +// shuitunlulu_ on Discord: Claude Science in a WSL distro wasn't found or +// connected by magpie on Windows. Its daemon takes only an address +// (ANTHROPIC_BASE_URL, http only to loopback) and sends its Claude sign-in +// as its bearer, so under NAT it is given the relay in the distro with the +// WSL key as the address's first segment. From the WSL network that +// request is served as this computer's at the path without the key, its +// sign-in left as it was; the key in the path from elsewhere, or a wrong +// one, is no WSL request. +func TestWSLKeyInPath(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + fakeWSLNet(t, "172.17.32.1/20") + key := WSLKey() + var seen *http.Request + h := lanGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seen = r })) + call := func(from, path string) (int, string) { + seen = nil + r := httptest.NewRequest("POST", "http://172.17.32.1:3425"+path, nil) + r.RemoteAddr = from + r = r.WithContext(context.WithValue(r.Context(), http.LocalAddrContextKey, &net.TCPAddr{IP: net.ParseIP("172.17.32.1"), Port: 3425})) + r.Header.Set("Authorization", "Bearer sk-ant-oat01-signin") + r.Header.Set("X-Anthropic-Surface", "operon") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code, w.Body.String() + } + const distro = "172.17.38.240:51000" + if code, body := call(distro, "/"+key+"/v1/messages?beta=true"); code != 200 || seen == nil { + t.Fatalf("key in the path: %d %s", code, body) + } + if !local(seen) || seen.URL.Path != "/v1/messages" || seen.URL.RawQuery != "beta=true" || seen.RequestURI != "/v1/messages?beta=true" { + t.Errorf("served as %s at %q (%q)", seen.RemoteAddr, seen.URL.Path, seen.RequestURI) + } + if got := seen.Header.Get("Authorization"); got != "Bearer sk-ant-oat01-signin" || !claudeSignIn(seen) || agentOf(seen) != ScienceID { + t.Errorf("sign-in %q, agent %q", got, agentOf(seen)) + } + for name, c := range map[string]struct{ from, path string }{ + "no key": {distro, "/v1/messages"}, + "a wrong key": {distro, "/" + key[:len(key)-1] + "x/v1/messages"}, + "another network": {"192.168.1.20:5000", "/" + key + "/v1/messages"}, + } { + if code, body := call(c.from, c.path); code != http.StatusForbidden || !strings.Contains(body, "isn't shared") { + t.Errorf("%s: %d %s, want refused as another machine's", name, code, body) + } + } +} + // The gateway on loopback also listens at each address Windows has on a // WSL network, comes or goes with it, and stops when sharing puts it on // every address anyway. [::1] stands for the WSL network's address here.