diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index e21cde65d..d1c98796c 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -33,6 +33,7 @@ something else shows up as drift. | Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#` on Windows, `omp#@wsl:` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) | | WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `@wsl:`, edited through `\\wsl.localhost\`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). The probe runs `sh -l`, which reads `~/.profile` but not `~/.bashrc`, so a command off its PATH is looked for where Node's managers and installers keep one, as `proc.UserBinDirs` does here (`wslbin`): bun, `~/.local/bin`, volta, pnpm, nvm's default then the highest, fnm's default then the highest (`FNM_DIR`, `~/.local/share/fnm`, `~/.fnm`), mise's installs and shims, asdf, `~/.npmrc`'s prefix, cargo, deno and Homebrew (千里不再 on Discord: a Pi from fnm, not run yet so with no `~/.pi`, wasn't found). One on a Windows drive, which WSL's PATH reaches first when the distro's isn't on it, is looked past rather than taken as the only one (`wslcmd`, `wslwin`; `TestWSLProbeFindsNodeManagersBins`, `TestWSLProbeLooksPastWindowsCommand`). The shell isn't asked interactively for `~/.bashrc`'s PATH: under `timeout` such a bash stops itself on WSL and outlives the timeout. Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Antigravity CLI is found by its own `~/.gemini/antigravity-cli` or its `agy` command (mimi001234 on Discord). Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). With Settings' Detect agents in WSL off (`NoWSLAgents`, #1264) magpie starts no wsl.exe at all: `proc.Command`, `CommandContext` and `ProbeContext` refuse one by any name or path with `proc.ErrWSLOff` (`wslOff` in [`proc/wsl.go`](../../internal/proc/wsl.go)), where every command magpie runs is made, so a path past agent's and wslrun's own gates (a request's Claude Code stand-in and classifier, #4872: on a computer without WSL each ask put up Windows' install window) asks nothing either (`TestWSLOffStartsNoWSL`, `TestWSLRunnerRefusedWhenOff`, `TestRunRefusedWhenOff`, `TestWSLStandInAsksNothingWhenOff`). With detection on, the same gate refuses wsl.exe with `proc.ErrNoWSLDistro` while the registry has no distro for the user (`HKCU\Software\Microsoft\Windows\CurrentVersion\Lxss`, a key with a `DistributionName` each, read at every start, so one installed later is listed at once; a read that fails is unknown and wsl.exe is asked as before), and agent's and wslrun's listings take that as none (TraderX219 on X: Windows' own wsl.exe without WSL's package put up its update console every 20 to 30 seconds). A failed run whose output says WSL must be installed or updated (`wsl.exe --update`, the inbox prompt, the optional component missing; `proc.WSLSaid`, told by agent's and wslrun's runners) writes `wsl-update` beside settings.json, and wsl.exe is then refused with `proc.ErrWSLNeedsUpdate` for six hours, by every magpie process, unless WSL's package version or the registered distros change; a refused listing is unknown, so nothing remembered of a distro is forgotten (`TestNoWSLDistroStartsNoWSL`, `TestWSLUpdateBacksOff`, `TestNoWSLDistroRunsNoWSL`, `TestWSLUpdateKeepsDistros`). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go), [`proc/wsl.go`](../../internal/proc/wsl.go) | | WSL folders that are links | Through `\\wsl.localhost` Windows can't follow a link the distro has: with `~/.codex` a link to `/mnt/c/Users//.codex`, a mkdir of it says it exists and nothing below it can be made, written, read or listed (#4502, linusxiong). The probe asks `readlink -f` there where each agent folder, its `skills` and the folders beside them lead (`wslLinkPaths`, `distro.Links`; a `$HOME` that is itself through a link is left as it was) and which drive each Windows mount is (`distro.Drives`). `distro.open` opens a path at or below a link where it leads: on a Windows drive the drive's own path (`C:\Users\\.codex`), elsewhere in the distro through its root again; `native` spells such a path back through the link for the agent. A link `readlink -f` couldn't resolve is never guessed at: its agent is unreached (`Agent.Unreached`), says why in its notice and refuses each change and sync. Every writer goes through it: the agents' own files (`place.join`, `place.open`), the library's targets (`wslOpen`, a `wsl` problem per agent), RTK (`rtkAt`, `agent.WSLOpen`), the Sessions page's reads (`sessions.WSLHome.Open`) and the Copilot CLI's sign-in (`provider.CopilotWSLDirs`). Links deeper than the probed paths aren't resolved (`TestWSLOpenThroughLinks`, `TestWSLAgentFolderIsALink`, `TestWSLAgentFolderLinkUnresolved`, `TestWSLProbeLinks`, `TestWSLFolderIsALinkToC`, `TestRTKWSLFolderIsALink`). | [`wsl.go`](../../internal/agent/wsl.go), [`targets.go`](../../internal/library/targets.go), [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) | +| WSL CLI versions and updates | A twin's CLI is read and updated in its distro, as the host's is (`cliupdate_wsl.go`; mewcoder on X): the Agents row shows the version, the newest and an Update button for every `cliSpecs` kind a distro has a command for, and Update all takes them in. Where the binary is comes from the probe (`distro.Paths`, else the command asked of the distro's PATH); one `wsl.exe -d -e sh` script says where its links lead, its `--version` and exit code (`wslCLIScript`, kept ten minutes in `wslProbes`, asked again by Rescan and after an update), with the CLI's own folder, its npm prefix, `~/.local/bin` and `~/.bun/bin` first on PATH, since `wsl.exe -e` has no login PATH and a node CLI would not find node. How it was installed is read from that Linux path by the same rules (`wslHowInstalled`: its own updater via `cliSpec.self`, Homebrew's Cellar, npm, bun or pnpm; volta, yarn and an npm prefix the user can't write, `/usr/lib`, are left alone), and the update runs in the distro through wsl.exe (`wslRunUpdate`) with a Linux brew asked for its newest in the distro too. A distro that isn't running is never started to be asked: its rows show no version and an update says to start it. Not carried over: the host's proxy settings (the distro has its own network), and Grok Build's newest is read from this computer's channel setting. Kinds with no command of their own (Goose, mu) show nothing, as on the host. | [`cliupdate_wsl.go`](../../internal/agent/cliupdate_wsl.go), [`cliupdate.go`](../../internal/agent/cliupdate.go) | | 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`, `--settings <~/.gemini/antigravity-cli/magpie-settings.json>` and `--model` (no `--model` when the user gives one) while that file's model is magpie's, and unchanged otherwise. magpie writes `modelProvider`, `model` and the custom models (the user's own too, as agy takes the key whole) only into that file of its own, never into agy's `settings.json`: `modelProvider: gemini` there made every agy an API-key session with no Google account, so no remote control, which needs the sign-in (baysonfox on X). A `settings.json` an older magpie wired is given back (the stashed model and provider) at the next `Sync` or pick. `agy remote-control …` and `--remote-control` go through the function and `magpie agy run` as plain agy, on the user's sign-in (`AgyRemote`); remote control inside a session on magpie's models is not possible. 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) | diff --git a/internal/agent/cliupdate.go b/internal/agent/cliupdate.go index c002678dd..b943aa847 100644 --- a/internal/agent/cliupdate.go +++ b/internal/agent/cliupdate.go @@ -239,7 +239,7 @@ var cliSpecs = map[string]cliSpec{ // none is offered there. "penguin": {npm: []string{"@prismshadow/penguin-cli"}, self: func(bin, real string) []string { - if runtime.GOOS == "windows" { + if runtime.GOOS == "windows" && !strings.HasPrefix(real, "/") { // a distro's path is Linux's return nil } if l := strings.ToLower(real); strings.Contains(l, "/.penguin/bin/") || strings.Contains(l, "/.penguin/lib/") { @@ -272,6 +272,9 @@ type updater struct { // reshim is run after the update: the version manager whose shim the // CLI was found as making shims for what it installed reshim []string + // wsl is the distro the CLI is in and the update runs in, "" for this + // machine's (cliupdate_wsl.go) + wsl string } // shown is the update as a person would type it. @@ -786,6 +789,9 @@ func channelVersion(url string) (string, error) { // brewLatest is the version Homebrew has for u, as it last updated itself: // what brew upgrade would install, or newer once it updates first. var brewLatest = func(u *updater) (string, error) { + if u.wsl != "" { + return wslBrewLatest(u) + } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() args := []string{"info", "--json=v2", u.pkg} @@ -799,6 +805,11 @@ var brewLatest = func(u *updater) (string, error) { if err != nil { return "", err } + return brewVersion(out) +} + +// brewVersion is the version brew info --json=v2 says. +func brewVersion(out []byte) (string, error) { var r struct { Formulae []struct { Versions struct{ Stable string } @@ -913,6 +924,9 @@ func (a *Agent) BinPath() string { // update it, with its desktop app's version. ok is false for an agent with // neither a CLI magpie knows nor its app. func (a *Agent) CLI() (c CLI, ok bool) { + if a.WSL != "" { + return a.wslCLIInfo() + } c.App = a.AppVersion() bin, spec := a.cliBin() if bin == "" { @@ -980,7 +994,12 @@ func CLIs(wait time.Duration) (out map[string]CLI, pending bool) { var wg sync.WaitGroup out = map[string]CLI{} for _, a := range Detected() { - if _, ok := cliSpecs[a.ID]; !ok || a.WSL != "" { + kind := a.ID + if a.WSL != "" { + kind, _, _ = strings.Cut(kind, "@") + kind, _, _ = strings.Cut(kind, "#") + } + if _, ok := cliSpecs[kind]; !ok { continue } wg.Add(1) @@ -1118,6 +1137,9 @@ var updateTimeout = 10 * time.Minute // UpdateCLI brings the agent's CLI up to date the way it was installed, and // says what it is afterwards. func (a *Agent) UpdateCLI() (CLI, error) { + if a.WSL != "" { + return a.updateWSL() + } bin, spec := a.cliBin() if bin == "" { return CLI{}, fmt.Errorf("magpie can't find %s's CLI", a.Name) diff --git a/internal/agent/cliupdate_wsl.go b/internal/agent/cliupdate_wsl.go new file mode 100644 index 000000000..233f15bf4 --- /dev/null +++ b/internal/agent/cliupdate_wsl.go @@ -0,0 +1,288 @@ +package agent + +// The version and the update of an agent's CLI inside a WSL distro +// (cliupdate.go's, asked in the distro): where its binary is comes from the +// distro's own probe, how it was installed from that Linux path, and the +// update runs there, through wsl.exe, as the distro's user. A distro that +// isn't running is never started to be asked: its agents show nothing. + +import ( + "errors" + "fmt" + "path" + "strings" + "time" +) + +// wslProbes keeps what a distro said of a CLI (wslCLIScript's output); a +// rescan asks again. +var wslProbes memo + +// wslCLIScript says, for the first of the paths $@ that is a program: where +// it is, where its links lead, what it said to --version and its exit code. +const wslCLIScript = `for c in "$@"; do case "$c" in /*) ;; *) c=$(command -v "$c" 2>/dev/null);; esac + if [ -n "$c" ] && [ -x "$c" ] && [ ! -d "$c" ]; then b="$c"; break; fi; done +[ -n "$b" ] || exit 0 +echo "bin:$b" +r=$(readlink -f "$b" 2>/dev/null || echo "$b") +echo "real:$r" +# wsl.exe -e has no login PATH: a node CLI finds its node beside it, in its +# npm prefix, or where a user's tools are +PATH="$(dirname "$b"):${r%%/lib/node_modules/*}/bin:$HOME/.local/bin:$HOME/.bun/bin:$PATH" +o=$("$b" --version 2>&1 0 { + pkg = spec.npm[0] + } + u := &updater{via: "self", pkg: pkg, cmd: c, latest: spec.latest, wsl: d.Name} + for _, p := range spec.npm { + if n := wslFromNodeModules(d, p, false, bin, real); n != nil && n.via == "npm" { + u.path = n.path + } + } + return u + } + } + if m := brewPath.FindStringSubmatch(real); m != nil && contains(spec.brew, m[2]) { + prefix := real[:strings.Index(real, m[0])] + brew := prefix + "/bin/brew" + if !wslTest(d, "-x", brew) { + brew = "brew" + } + u := &updater{via: "brew", pkg: m[2], cask: m[1] == "Caskroom", brew: brew, wsl: d.Name} + u.cmd = []string{brew, "upgrade", m[2]} + if u.cask { + u.cmd = []string{brew, "upgrade", "--cask", m[2]} + } + return u + } + for _, pkg := range spec.npm { + if u := wslFromNodeModules(d, pkg, spec.scripts, bin, real); u != nil { + return u + } + } + return nil +} + +// wslFromNodeModules is fromNodeModules for a Linux path. +func wslFromNodeModules(d distro, pkg string, scripts bool, bin, real string) *updater { + i := strings.Index(real, "/node_modules/"+pkg+"/") + if i < 0 { + return nil + } + modules := real[:i] + "/node_modules" + lower := strings.ToLower(real + "|" + bin) + switch { + case strings.Contains(lower, "/.bun/"): + bun := path.Join(path.Dir(bin), "bun") + if !wslTest(d, "-x", bun) { + bun = "bun" + } + return &updater{via: "bun", pkg: pkg, wsl: d.Name, path: path.Dir(bun), cmd: withScripts([]string{bun, "add", "-g"}, "bun", pkg, scripts)} + case strings.Contains(lower, "/pnpm/") || strings.Contains(lower, "/.pnpm/"): + return &updater{via: "pnpm", pkg: pkg, wsl: d.Name, cmd: withScripts([]string{"pnpm", "add", "-g"}, "pnpm", pkg, scripts)} + case strings.Contains(lower, "/.volta/") || strings.Contains(lower, "/yarn/") || strings.Contains(lower, "/.yarn/"): + return nil // a manager of its own, which magpie leaves to it + } + lib := path.Dir(modules) + if path.Base(lib) != "lib" { + return nil // not a global install + } + prefix := path.Dir(lib) + if !wslTest(d, "-w", modules) { + return nil // the system's (/usr/lib): npm would want sudo + } + npm := prefix + "/bin/npm" + u := &updater{via: "npm", pkg: pkg, prefix: prefix, wsl: d.Name} + if wslTest(d, "-x", npm) { + u.path = prefix + "/bin" // its own node, not another on PATH + } else { + npm = "npm" + } + u.cmd = withScripts([]string{npm, "install", "-g", "--prefix", prefix}, "npm", pkg, scripts) + return u +} + +// wslBrewLatest is brewLatest's question asked in the distro. +func wslBrewLatest(u *updater) (string, error) { + args := []string{"info", "--json=v2", u.pkg} + if u.cask { + args = []string{"info", "--json=v2", "--cask", u.pkg} + } + out, err := wslRun(30*time.Second, append([]string{"-d", u.wsl, "-e", "env", "HOMEBREW_NO_AUTO_UPDATE=1", "HOMEBREW_NO_ENV_HINTS=1", u.brew}, args...)...) + if err != nil { + return "", err + } + return brewVersion(out) +} + +// wslRunUpdate runs an update in the distro, as its user, with u's folder +// first on PATH, and says what it printed. +var wslRunUpdate = func(timeout time.Duration, u *updater) ([]byte, error) { + args := []string{"-d", u.wsl, "-e", "sh", "-c", `d="$1"; shift; PATH="$d:$HOME/.local/bin:$HOME/.bun/bin:$PATH"; export PATH; exec env NONINTERACTIVE=1 HOMEBREW_NO_ENV_HINTS=1 NO_COLOR=1 CLINE_NO_AUTO_UPDATE=1 "$@" 2>&1`, "sh", u.path} + if u.path == "" { + args[len(args)-1] = "/usr/bin" // wsl.exe drops an empty argument + } + return wslRun(timeout, append(args, u.cmd...)...) +} + +// wslCLI is the CLI of an agent in a running distro: what CliInfo says of +// a host one. +func (a *Agent) wslCLIInfo() (c CLI, ok bool) { + d, kind, ok := a.wslCLIOf() + if !ok { + return c, false + } + spec := cliSpecs[kind] + w, ok := askWSLCLI(d, kind, spec) + if !ok { + return c, false + } + c.Version, c.Path = w.version(), w.bin + u := wslHowInstalled(d, spec, w.bin, w.real) + if u == nil { + return c, true + } + c.Via, c.Command = u.via, u.shown() + c.Latest = latestVersion(u) + c.Update = c.Version != "" && c.Latest != "" && Newer(c.Latest, c.Version) + return c, true +} + +// updateWSL is UpdateCLI for an agent in a distro. +func (a *Agent) updateWSL() (CLI, error) { + d, kind, ok := a.wslCLIOf() + if !ok { + return CLI{}, fmt.Errorf("%s's distro %s isn't running: start it, then update", a.Name, a.WSL) + } + spec := cliSpecs[kind] + w, ok := askWSLCLI(d, kind, spec) + if !ok { + return CLI{}, fmt.Errorf("magpie can't find %s's CLI in %s", a.Name, a.WSL) + } + u := wslHowInstalled(d, spec, w.bin, w.real) + if u == nil { + return CLI{}, fmt.Errorf("magpie can't tell how %s was installed at %s in %s — update it the way you installed it", a.Name, w.bin, a.WSL) + } + if _, busy := updating.LoadOrStore(a.ID, true); busy { + return CLI{}, fmt.Errorf("%s is already being updated", a.Name) + } + defer updating.Delete(a.ID) + before := w.version() + if spec.target && u.via == "self" { + if v := latestVersion(u); Newer(v, before) { + u.cmd = append(u.cmd, v) + } + } + out, err := wslRunUpdate(updateTimeout, u) + wslProbes.forget(d.Name + "\x00" + kind) + if u.via == "brew" { + latests.forget("brew:" + u.pkg) + } + c, _ := a.wslCLIInfo() + if err != nil { + msg := lastLines(string(out), 3) + if msg == "" { + msg = err.Error() + } + return c, fmt.Errorf("%s: %s", u.shown(), msg) + } + if c.Update && c.Version == before { + return c, fmt.Errorf("%s is still %s after %s; %s is out", a.Name, c.Version, u.shown(), c.Latest) + } + // the package says its new version, but that isn't the CLI running + // (cliupdate.go's runsBroken) + if n, _ := askWSLCLI(d, kind, spec); n.code > 0 && n.code != 127 && n.version() == "" { + return c, fmt.Errorf("%s was updated, but %s --version fails: %s — %s", a.Name, path.Base(w.bin), lastLines(n.out, 2), mendHint(u, c.Version)) + } + return c, nil +} diff --git a/internal/agent/cliupdate_wsl_test.go b/internal/agent/cliupdate_wsl_test.go new file mode 100644 index 000000000..4029dc1d1 --- /dev/null +++ b/internal/agent/cliupdate_wsl_test.go @@ -0,0 +1,111 @@ +package agent + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// An agent installed inside a WSL distro has its version read and is +// updated in the distro (@mewcoder on X: "可以支持wsl里的agent版本检测和更新吗"), +// the way the host's is: by the npm that owns it, run through wsl.exe in the +// distro. A distro that isn't running is never asked. +func TestWSLAgentCLIVersionAndUpdate(t *testing.T) { + reg := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"version":"0.2.0"}`)) + })) + oldReg, oldRun := npmRegistry, wslRunUpdate + npmRegistry = reg.URL + "/" + t.Cleanup(func() { + reg.Close() + npmRegistry, wslRunUpdate = oldReg, oldRun + versions, latests, wslProbes = memo{}, memo{}, memo{} + }) + versions, latests, wslProbes = memo{}, memo{}, memo{} + + root := t.TempDir() + os.MkdirAll(filepath.Join(root, "home", "me", ".codex"), 0o755) + const prefix = "/home/me/.nvm/versions/node/v22" + const bin = prefix + "/bin/codex" + const real = prefix + "/lib/node_modules/@openai/codex/bin/codex.js" + fakeWSL(t, "Ubuntu\r\nStopped\r\n", "Ubuntu\r\n", map[string]string{ + "Ubuntu": "home:/home/me\ndir:.codex\nbin:codex " + bin + "\nroute:default via 172.20.0.1 dev eth0\n", + }, map[string]string{"Ubuntu": root}) + + var mu sync.Mutex + version, asked := "0.1.0", map[string]int{} + probe := wslRun + wslRun = func(d time.Duration, args ...string) ([]byte, error) { + mu.Lock() + defer mu.Unlock() + if len(args) > 4 && args[0] == "-d" && args[2] == "-e" { + asked[args[1]]++ + switch args[3] { + case "test": + return nil, nil // writable, and npm is there + case "sh": + if args[4] == "-c" && strings.Contains(args[5], "readlink") { + return []byte("bin:" + bin + "\nreal:" + real + "\ncode:0\nver:codex-cli " + version + " \n"), nil + } + } + } + return probe(d, args...) + } + var ran []string + wslRunUpdate = func(_ time.Duration, u *updater) ([]byte, error) { + mu.Lock() + defer mu.Unlock() + ran = append([]string{u.wsl, u.path}, u.cmd...) + version = "0.2.0" + return nil, nil + } + + ds := wslDistros() + var d distro + for _, x := range ds { + if x.Name == "Ubuntu" { + d = x + } + } + a := wslAgent(wslKindOf("codex"), d) + c, ok := a.CLI() + if !ok || c.Version != "0.1.0" || c.Via != "npm" || c.Latest != "0.2.0" || !c.Update || c.Path != bin { + t.Fatalf("CLI = %+v, %v", c, ok) + } + if !strings.Contains(c.Command, "npm install -g --prefix "+prefix) { + t.Fatalf("command %q", c.Command) + } + if got, _ := CLIs(5 * time.Second); got[a.ID].Version != "0.1.0" { + t.Fatalf("CLIs has no %s: %+v", a.ID, got) + } + + c, err := a.UpdateCLI() + if err != nil { + t.Fatal(err) + } + if c.Version != "0.2.0" || c.Update { + t.Fatalf("after the update: %+v", c) + } + want := []string{"Ubuntu", prefix + "/bin", prefix + "/bin/npm", "install", "-g", "--prefix", prefix, "@openai/codex@latest"} + if strings.Join(ran, " ") != strings.Join(want, " ") { + t.Fatalf("ran %q, want %q", ran, want) + } + + // a distro that isn't running is never asked + stopped := wslAgent(wslKindOf("codex"), distro{Name: "Stopped", Home: "/home/s", Has: map[string]bool{"dir:.codex": true}}) + before := asked["Stopped"] + if _, ok := stopped.CLI(); ok { + t.Fatal("a stopped distro's CLI was read") + } + if _, err := stopped.UpdateCLI(); err == nil { + t.Fatal("a stopped distro was updated") + } + if asked["Stopped"] != before { + t.Fatalf("a stopped distro was asked %d times", asked["Stopped"]-before) + } +} diff --git a/internal/agent/rescan.go b/internal/agent/rescan.go index 92ba53ece..f5ee76c17 100644 --- a/internal/agent/rescan.go +++ b/internal/agent/rescan.go @@ -19,6 +19,7 @@ func Rescan() { // where updates come from is asked again, too: a version published // after magpie started showed no update until the memo ran out (#4980) latests.expireAll() + wslProbes.expireAll() cursorLocalSeen.Lock() cursorLocalSeen.at = time.Time{}