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:<distro>), 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-<distro>.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:<gateway port> to Windows' WSL address. The daemon gets http://127.0.0.1:<port>/<WSL key>; 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/mainc7ebb6f8don 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 on9dd7aabca, 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/<daemon>/environ had ANTHROPIC_BASE_URL=http://127.0.0.1:<port>/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)
This commit is contained in:
@@ -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.<model>.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:<id>:<path>` (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-<distro>.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:<gateway port>` 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:<port>/<WSL key>`, 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 `<config>/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 <file> 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
|
||||
|
||||
File diff suppressed because one or more lines are too long
+205
-101
@@ -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)
|
||||
|
||||
@@ -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:<the gateway's port> 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`
|
||||
|
||||
// scienceRelayScript starts the relay: $1 is the port it listens on at
|
||||
// 127.0.0.1, $2 where it leads. One running to the same place is left
|
||||
// running; one to another (Windows' address moved with a restart of WSL)
|
||||
// is stopped first, with the connections it forked (its own process
|
||||
// group, as setsid starts it). Its pid and where it leads are kept in
|
||||
// ~/.claude-science/magpie-relay; a pid there is taken for it only while
|
||||
// /proc says it is socat.
|
||||
const scienceRelayScript = `port=$1; to=$2; d="$HOME/.claude-science"; pf="$d/magpie-relay"; ` +
|
||||
`if [ -r "$pf" ]; then read -r pid was < "$pf"; if [ -n "$pid" ] && [ "$(cat /proc/$pid/comm 2>/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 >/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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
+38
-1
@@ -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:<port>/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
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user