Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
proc: magpie on Windows finds fnm's node and npx (#2685)
yetone5b4da5bee34c
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex 1a511788e..72aa12502 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -121,7 +121,7 @@ something else shows up as drift.- MothX's folder is `$MOTHX_DIR` as it is (no `~`), else `%APPDATA%\mothx` on Windows, else `~/.mothx`; a WSL distro's is its `~/.mothx` ([`mothx.go`](../../internal/agent/mothx.go)). Its `thinkingFormat` is `openai` unless the user set one: with it empty, MothX picks Qwen's `enable_thinking`, DeepSeek's `thinking` or Doubao's levels by the model id, which for magpie's ids says nothing of the vendor that serves them. MothX's `/model` and `/statusline … global` rewrite the whole file, so Disconnect after one takes out magpie's provider, the pick and a `providers` left empty (MothX omits an empty one), and keeps the rest.- PenguinHarness's file is `$PENGUIN_HOME` (else `~/.penguin/data`, on Windows too) `/<project>/.project_config.toml`, the Project `$PENGUIN_PROJECT_ID` when it is a folder's name (`agentenv.NotPaths`, so a relative name isn't dropped as a path), else `default_project`; a WSL distro's is its `~/.penguin/data/default_project` ([`penguin.go`](../../internal/agent/penguin.go)). Magpie's models are `[[models]]` array entries with `provider = "magpie"`, replaced together where the first one was by `edit.SetTOMLArrayTables`, which leaves the user's entries, the blank lines between them and the file's time alone when nothing changed (Penguin's server reads the file again on every mtime change). `default_model` is spelled `{ provider = …, model_id = … }` as Penguin's own writer (smol-toml) spells it; that writer rewrites the whole file, so Disconnect takes out magpie's provider, entries and a vision model on them rather than putting back a copy. A default naming no entry is refused by Penguin, so entries go in before `default_model` and out after it.- Zoo Code's provider profiles are in VS Code's secret storage, so magpie writes a settings file for it (`magpie-import.json` in Zoo Code's `globalStorage/zoocodeorganization.zoo-code/settings`, not magpie's folder, so a sync keeps an address the user moved it to) and points Zoo Code's `zoo-code.autoImportSettingsPath` at it in VS Code's `settings.json` and each profile's, a user's own path stashed and put back ([`zoocode.go`](../../internal/agent/zoocode.go)). Zoo Code imports it on each start (`importSettingsFromPath`), merging it over the user's profiles and making `magpie` the current one. Disconnect stops the import and deletes the file; the profile already imported stays in Zoo Code, where magpie can't reach it.-- An agent is detected by its config file, its folder, or its command on magpie's PATH (`Detected`). That PATH is the login shell's plus the folders users' tools go in (`proc.UserPath`: `~/.local/bin`, npm's prefixes, the Node nvm's default alias resolves to (the highest installed when it names none), bun, Homebrew, ...), so a CLI a terminal doesn't find can still be found and listed: an npm install under a Node the terminal no longer uses. `/api/agents/cli` then gives where it is (`path`) and `offPath` when the login shell's PATH (`proc.LoginPath`) lacks its folder, and the Agents row says "Not on your terminal's PATH", its tip naming the file (悠悠哥 on Discord: Codex 0.162.1 listed with no codex on PATH and no `~/.codex`). An unknown login PATH says nothing. A folder another tool writes too doesn't count (`dirShared`): Pi's for omp, `~/.copilot` for the Copilot CLI, which GitHub Copilot's JetBrains and VS Code plugins also write, and Qoder's and Qoder CN's, which Qoder's JetBrains plugin fills, and `~/.cursor` for Cursor CLI, which the Cursor editor makes on its own (`TestCursorFolderFromTheEditorIsNotTheCLI`, @G_Z_Y on X); only `cli-config.json` or `cursor-agent` finds Cursor CLI. A config file another tool writes first counts only when `pathOwn` says it is the agent's: Qoder's `settings.json` holding `enabledPlugins` alone is the plugin's (`qoderPluginOnly`; #1495, `TestCopilotFolderFromAnIDEPluginIsNotTheCLI`, `TestQoderSettingsFromAnIDEPluginIsNotTheCLI`). The Qoder app (the desktop app, which runs Qoder's CLI as its agent with the same folder) is found by the `.qoder-app-status.json` it writes there (`sign`, `qoderApp`; #2138, `TestQoderAppIsQoder`), as its `settings.json` can be its bundled plugin's `enabledPlugins` alone. Only the GUI and `daemon install` widen the PATH so; `magpie serve`, `web`, `tui` and the CLI keep the one they were started with, so an agent's CLI (`cliBin`, which its version and `omp`'s max effort are read from) is looked for in those folders (`proc.FindTool`) on every system when it isn't on the PATH, not only on Windows (whqtian on Discord: omp under `~/.bun/bin` on Ubuntu read as no version and offered xhigh in place of max; `TestOmpVersionOffPath`).+- An agent is detected by its config file, its folder, or its command on magpie's PATH (`Detected`). That PATH is the login shell's plus the folders users' tools go in (`proc.UserPath`: `~/.local/bin`, npm's prefixes, the Node nvm's default alias resolves to (the highest installed when it names none), bun, Homebrew, ...; on Windows the registry's PATH plus the Node fnm's default alias names, `%APPDATA%\fnm\aliases\default` or under `FNM_DIR`, which fnm puts on a terminal's PATH from the shell profile and never in the registry, #2685), so a CLI a terminal doesn't find can still be found and listed: an npm install under a Node the terminal no longer uses. `/api/agents/cli` then gives where it is (`path`) and `offPath` when the login shell's PATH (`proc.LoginPath`) lacks its folder, and the Agents row says "Not on your terminal's PATH", its tip naming the file (悠悠哥 on Discord: Codex 0.162.1 listed with no codex on PATH and no `~/.codex`). An unknown login PATH says nothing. A folder another tool writes too doesn't count (`dirShared`): Pi's for omp, `~/.copilot` for the Copilot CLI, which GitHub Copilot's JetBrains and VS Code plugins also write, and Qoder's and Qoder CN's, which Qoder's JetBrains plugin fills, and `~/.cursor` for Cursor CLI, which the Cursor editor makes on its own (`TestCursorFolderFromTheEditorIsNotTheCLI`, @G_Z_Y on X); only `cli-config.json` or `cursor-agent` finds Cursor CLI. A config file another tool writes first counts only when `pathOwn` says it is the agent's: Qoder's `settings.json` holding `enabledPlugins` alone is the plugin's (`qoderPluginOnly`; #1495, `TestCopilotFolderFromAnIDEPluginIsNotTheCLI`, `TestQoderSettingsFromAnIDEPluginIsNotTheCLI`). The Qoder app (the desktop app, which runs Qoder's CLI as its agent with the same folder) is found by the `.qoder-app-status.json` it writes there (`sign`, `qoderApp`; #2138, `TestQoderAppIsQoder`), as its `settings.json` can be its bundled plugin's `enabledPlugins` alone. Only the GUI and `daemon install` widen the PATH so; `magpie serve`, `web`, `tui` and the CLI keep the one they were started with, so an agent's CLI (`cliBin`, which its version and `omp`'s max effort are read from) is looked for in those folders (`proc.FindTool`) on every system when it isn't on the PATH, not only on Windows (whqtian on Discord: omp under `~/.bun/bin` on Ubuntu read as no version and offered xhigh in place of max; `TestOmpVersionOffPath`).- Detection goes by an agent's folder, which an uninstall leaves behind, so an agent found by that alone is shown as gone (`CLIMissing`; #843, #2177, #2173): its CLI is on no PATH and in none of `proc.FindTool`'s folders nor where its own installer puts it (`~/.claude/local`, `~/.codex/packages/standalone`, `~/.opencode/bin`, Hermes' `hermes-agent` checkout), and nothing else that reads the folder is here (`cliHeld`): its desktop app (`HasApp`), an editor's extension (`~/.<editor>/extensions/<id>-*`: `anthropic.claude-code`, `openai.chatgpt`, `saoudrizwan.claude-dev`), Claude.app, OpenCode.app and Goose.app on a Mac, a JetBrains IDE's settings (its AI Assistant's agents and Cline's plugin) or Zed's `external_agents` (its Claude Code and Codex adapters). Where magpie can't tell (every shared folder, `cliShared`, on Windows, whose readers can be a Store app, a portable editor or a PATH only a shell profile sets, #1482, and there too one a desktop app of the agent's reads, `desktopApps`: DeepSeek Harness Desktop installs to any folder and puts its `dsh.cmd` in one the user picks, #2300, #2304; OpenCode and Goose off a Mac, Gemini, an agent detected its own way or by a command name other tools share, one with no install command but `cliOnly`'s Hermes), it is never gone. A gone row in the GUI shows "CLI not found" and none of its settings, nor Apply again; while connected it keeps its switch and Disconnect, and it folds under Not set up once not. Get started never offers it (`connectKind` is "no"). The TUI leaves it out and `magpie ls` says "CLI not found" (`TestCLIMissing*`, `agent-cli-missing.test.cjs`, `getting-started.test.cjs`).- Tests never touch the real machine. `TestMain` uses `testenv`, which points HOME, USERPROFILE, the XDG folders and APPDATA into a temporary folder, clears `agentenv.Vars` and puts failing stand-ins for keychain tools and agent CLIs on PATH. Agent-specific side effects (Aside, the Zed keychain, Codex's usage check) are also stubbed in `TestMain`.diff --git a/docs/subsystems/library.md b/docs/subsystems/library.mdindex 79a106481..1eb9cf7e4 100644--- a/docs/subsystems/library.md+++ b/docs/subsystems/library.md@@ -19,7 +19,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.| Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first, so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) || Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid and Cline. A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away, and what it made is listed in the project's `.gitignore`. | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go) || Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). A set can be kept in a file of the user's own instead of `instruction-sets/` (`InstrSet.File`, 新v学员 on Discord): `~/.agents/AGENTS.md`, which Droid and omp read too. `textPath` reads it, `putText` keeps it aside and writes it but never removes it, removing the set lets go of it, and `linkable` refuses a file magpie writes into (an agent's own instructions, a file with the marker line), the library's own and another set's. The app's `KeepLinked` looks at the file every 30 s and writes a change into the agents (`SyncLinked`). A set's text is read without magpie's part (`setText`), and an agent whose instructions file is, links followed, the file the set on is kept in (`isSetFile`: `instructions.md` linked to `~/.claude/CLAUDE.md`, or both linked to one dotfile) gets no part written into it, and one written before is taken out with every part nested in it: read with its part, each sync wrote the whole file into that part again and it doubled, to gigabytes (#2349, `TestInstructionsSetLinkedToAgentsFile`). `Collect` carries the set's text, not where its file is; `Put` keeps this computer's file for the set and never empties it for a text not carried. Alma's file is `~/.config/alma/USER.md`, which its main chat reads into its system prompt as its owner's profile (0.4.164's `out/main/index.js`; a workspace's `USER.md` is read instead), and whose leading front matter (`name`, `telegram_id`, `discord_id`) is who its bots answer to (#2315, Jie211). The target is a `Profile`: magpie's part goes after the user's, so the front matter stays first, and `ImportInstructions` refuses it, as moving it out would take that front matter out of the file and into every agent's (`TestAlmaInstructionsKeepTheProfile`, `TestAlmaProfileIsNotImported`, `library-alma-profile.test.cjs`). | [`instructions.go`](../../internal/library/instructions.go) |-| MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/<name>`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and the row says "signed in in Claude Code (Ubuntu)" instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/<name>` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:<port>/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) |+| MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A command named bare that magpie's PATH lacks is started from where `proc.FindTool` finds it (fnm's Nodes on Windows among the folders), with that folder on the check's PATH, since npx's package runs the node beside it by name (`stdioProgram`, #2685, `TestStdioProgramFindsWhatPathLacks`). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/<name>`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and the row says "signed in in Claude Code (Ubuntu)" instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/<name>` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:<port>/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) || Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree/<ref>/<path>`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- <url> <ref>` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), and a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go) || Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`), in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills), go first, marked official: `magpie-setup` has an agent set magpie up as the user asks through its commands (providers, accounts, agents, routing groups and rules, gateway keys and limits, models, the library), and `magpie-quota` lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Their commands live in magpie's CLI, so a change to a command either uses gets the skill updated in that repository. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) || Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) |diff --git a/internal/library/mcp_check.go b/internal/library/mcp_check.goindex 7122612d5..8b20799b6 100644--- a/internal/library/mcp_check.go+++ b/internal/library/mcp_check.go@@ -13,6 +13,7 @@ import ("net/url""os""os/exec"+ "path/filepath""runtime""slices""strings"@@ -491,6 +492,43 @@ func checkStdio(ctx context.Context, s *Server) ServerHealth {return *first}+// stdioProgram is the program checkStdio starts for a server's command,+// and the folder it was found in when magpie's PATH lacks it. A bare name+// PATH doesn't have is looked for as a terminal would find it+// (proc.FindTool: the folders a user's tools are installed in, fnm's Nodes+// among them, #2685), and that folder goes on the child's PATH, as it is+// on a terminal's: npx's package runs the node beside it by name. A path+// is taken as it is.+func stdioProgram(name string) (prog, found string) {+ if name == "" || strings.ContainsAny(name, `/\`) {+ return name, ""+ }+ if _, err := exec.LookPath(name); err == nil {+ return name, ""+ }+ if p := proc.FindTool(name); p != "" {+ return p, filepath.Dir(p)+ }+ return name, ""+}++// withPath is env with dir after the folders its PATH has (Path, as+// Windows spells it, too).+func withPath(env []string, dir string) []string {+ out := slices.Clone(env)+ for i := len(out) - 1; i >= 0; i-- {+ k, v, ok := strings.Cut(out[i], "=")+ if ok && (k == "PATH" || runtime.GOOS == "windows" && strings.EqualFold(k, "PATH")) {+ if v != "" {+ v += string(os.PathListSeparator)+ }+ out[i] = k + "=" + v + dir+ return out+ }+ }+ return append(out, "PATH="+dir)+}+// checkStdioAt starts the command on this machine, or in WSL distro.func checkStdioAt(ctx context.Context, s *Server, distro string) ServerHealth {// started as the agents start it: in the environment magpie has, with@@ -502,8 +540,11 @@ func checkStdioAt(ctx context.Context, s *Server, distro string) ServerHealth {var cmd *exec.Cmdvar t wslrun.Toolstop := func() {}+ found := ""if distro == "" {- cmd = proc.Command(s.Command, s.Args...)+ var prog string+ prog, found = stdioProgram(s.Command)+ cmd = proc.Command(prog, s.Args...)} else {var err errort, err = wslrun.In(distro, s.Command)@@ -537,6 +578,9 @@ func checkStdioAt(ctx context.Context, s *Server, distro string) ServerHealth {cmd.Env = append(cmd.Env, "PWD="+d)}}+ if found != "" {+ cmd.Env = withPath(cmd.Env, found)+ }var names []stringfor k, v := range env {cmd.Env = append(cmd.Env, k+"="+v)diff --git a/internal/library/mcp_check_path_test.go b/internal/library/mcp_check_path_test.gonew file mode 100644index 000000000..da8477862--- /dev/null+++ b/internal/library/mcp_check_path_test.go@@ -0,0 +1,64 @@+package library++import (+ "os"+ "path/filepath"+ "runtime"+ "slices"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/proc"+ "github.com/yetone/magpie/internal/testenv"+)++// #2685: a bare npx the check's PATH lacks is the one a terminal would run+// (proc.FindTool, the folders a user's tools are installed in, fnm's+// Nodes on Windows among them), and its folder goes on the child's PATH,+// where the node it runs by name is. A path, and a name PATH has, are+// started as they are.+func TestStdioProgramFindsWhatPathLacks(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ t.Setenv("PATH", t.TempDir())+ proc.Forget()+ bin := filepath.Join(home, ".local", "bin")+ name := "magpie-fake-npx"+ file := name+ if runtime.GOOS == "windows" {+ file += ".cmd"+ }+ testenv.Program(t, filepath.Join(bin, file), "#!/bin/sh\necho hi\n")+ prog, found := stdioProgram(name)+ if !strings.EqualFold(prog, filepath.Join(bin, file)) || !strings.EqualFold(found, bin) {+ t.Fatalf("stdioProgram(%q) = %q, %q; want %q found in %q", name, prog, found, filepath.Join(bin, file), bin)+ }+ abs := filepath.Join(home, "elsewhere", file)+ if prog, found := stdioProgram(abs); prog != abs || found != "" {+ t.Fatalf("a path: stdioProgram = %q, %q; want it as it is", prog, found)+ }+ if prog, found := stdioProgram("magpie-no-such-tool"); prog != "magpie-no-such-tool" || found != "" {+ t.Fatalf("nowhere: stdioProgram = %q, %q; want the name, for notfound", prog, found)+ }+ t.Setenv("PATH", bin)+ proc.Forget()+ if prog, found := stdioProgram(name); prog != name || found != "" {+ t.Fatalf("on PATH: stdioProgram = %q, %q; want the name as it is", prog, found)+ }+}++func TestWithPath(t *testing.T) {+ sep := string(os.PathListSeparator)+ key := "PATH"+ if runtime.GOOS == "windows" {+ key = "Path" // as os.Environ spells it there+ }+ got := withPath([]string{"A=1", key + "=x" + sep + "y"}, "z")+ if want := []string{"A=1", key + "=x" + sep + "y" + sep + "z"}; !slices.Equal(got, want) {+ t.Fatalf("withPath = %q, want %q", got, want)+ }+ if got := withPath([]string{"A=1"}, "z"); !slices.Equal(got, []string{"A=1", "PATH=z"}) {+ t.Fatalf("no PATH: withPath = %q", got)+ }+}diff --git a/internal/proc/nodever.go b/internal/proc/nodever.gonew file mode 100644index 000000000..da2b1356e--- /dev/null+++ b/internal/proc/nodever.go@@ -0,0 +1,168 @@+package proc++import (+ "os"+ "path/filepath"+ "slices"+ "strconv"+ "strings"+)++// Node version managers' folders read the same on every system: the+// version folders a manager keeps, highest first, and fnm's Windows layout+// (fnmWin*), which magpie's own PATH and FindTool use on Windows and the+// tests take on any system.++// nodeVersions are the names of the version folders under root that have+// a folder bin (root/<version>/<bin>), highest version first (nodeVersionLess); a name that is+// no version (mise's "lts", "latest") after every one that is.+func nodeVersions(root, bin string) []string {+ es, _ := os.ReadDir(root)+ var names []string+ for _, e := range es {+ if st, err := os.Stat(filepath.Join(root, e.Name(), bin)); err == nil && st.IsDir() {+ names = append(names, e.Name())+ }+ }+ slices.SortStableFunc(names, func(a, b string) int {+ switch {+ case nodeVersionLess(b, a):+ return -1+ case nodeVersionLess(a, b):+ return 1+ }+ return strings.Compare(a, b)+ })+ return names+}++// parseNodeVersion reads v22.12.0 (or 22.12.0, mise's, or 22, a partial+// one) as its numbers; false for a name that isn't one.+func parseNodeVersion(s string) ([3]int, int, bool) {+ var v [3]int+ parts := strings.Split(strings.TrimPrefix(s, "v"), ".")+ if len(parts) > 3 || parts[0] == "" {+ return v, 0, false+ }+ for i, p := range parts {+ n, err := strconv.Atoi(p)+ if err != nil || n < 0 {+ return v, 0, false+ }+ v[i] = n+ }+ return v, len(parts), true+}++// nodeVersionLess says a is a lower version than b, by number: v9 before+// v22. A name that is no version is lower than one that is.+func nodeVersionLess(a, b string) bool {+ va, _, oka := parseNodeVersion(a)+ vb, _, okb := parseNodeVersion(b)+ if oka != okb {+ return okb+ }+ return oka && slices.Compare(va[:], vb[:]) < 0+}++func isDir(p string) bool {+ st, err := os.Stat(p)+ return err == nil && st.IsDir()+}++// fnm on Windows (#2685). A version's programs are in its installation+// folder itself — node-versions\<v>\installation\node.exe, npx.cmd — with+// no bin under it as on macOS and Linux, and aliases\default is a junction+// to the default version's installation folder (fnm's symlink_dir is+// junction::create there). A terminal set up with `fnm env` has its own+// link to aliases\default first on PATH, so its node, npx and the npm+// shims beside them are found; magpie, started from the Start menu, has+// the registry's PATH only and had none of them. An npx.cmd run by its+// full path started too, but the package it fetched runs `node` from+// PATH, and the server died with cmd's "'node' is not recognized".++// fnmWinRoots are the folders fnm keeps its Node versions in on Windows+// that exist here, the one fnm uses first: FNM_DIR, else its default,+// the data folder's fnm (etcetera's Windows data_dir, home\AppData\Roaming,+// which APPDATA names), else the legacy ~\.fnm.+func fnmWinRoots(home, appdata, fnmDir string) []string {+ var roots []string+ if filepath.IsAbs(fnmDir) {+ roots = append(roots, fnmDir)+ }+ if filepath.IsAbs(appdata) {+ roots = append(roots, filepath.Join(appdata, "fnm"))+ }+ if filepath.IsAbs(home) {+ roots = append(roots, filepath.Join(home, "AppData", "Roaming", "fnm"), filepath.Join(home, ".fnm"))+ }+ var have []string+ for _, r := range roots {+ if isDir(r) && !slices.ContainsFunc(have, func(h string) bool { return strings.EqualFold(h, r) }) {+ have = append(have, r)+ }+ }+ return have+}++// fnmWinBins are the folders of the Node versions fnm keeps in dir on+// Windows: the default alias's (aliases\default, as it stands: a junction+// Stat follows) first, then each installation folder, newest first.+func fnmWinBins(dir string) []string {+ var bins []string+ if def := filepath.Join(dir, "aliases", "default"); isDir(def) {+ bins = append(bins, def)+ }+ root := filepath.Join(dir, "node-versions")+ for _, n := range nodeVersions(root, "installation") {+ bins = append(bins, filepath.Join(root, n, "installation"))+ }+ return bins+}++// fnmWinUse is the folder of fnm's Node in dir a terminal gets on Windows:+// the default alias's; with no default alias, the highest installed. ""+// when the default leads nowhere: fnm's "system" alias points at a folder+// that can't exist (Z:\_fnm_\...), and such a terminal runs the system's+// Node, which PATH has already.+func fnmWinUse(dir string) string {+ def := filepath.Join(dir, "aliases", "default")+ if isDir(def) {+ return def+ }+ if _, err := os.Lstat(def); err == nil {+ return ""+ }+ root := filepath.Join(dir, "node-versions")+ if ns := nodeVersions(root, "installation"); len(ns) > 0 {+ return filepath.Join(root, ns[0], "installation")+ }+ return ""+}++// fnmWinPath is the folder of fnm's Node a terminal gets, in the root fnm+// uses (fnmWinRoots, fnmWinUse); none when fnm isn't here.+func fnmWinPath(home, appdata, fnmDir string) []string {+ if roots := fnmWinRoots(home, appdata, fnmDir); len(roots) > 0 {+ if d := fnmWinUse(roots[0]); d != "" {+ return []string{d}+ }+ }+ return nil+}++// addPath adds the folders PATH lacks, after the ones it has.+func addPath(dirs []string) {+ cur := filepath.SplitList(os.Getenv("PATH"))+ seen := map[string]bool{}+ for _, d := range cur {+ seen[d] = true+ }+ for _, d := range dirs {+ if d != "" && filepath.IsAbs(d) && !seen[d] {+ seen[d] = true+ cur = append(cur, d)+ }+ }+ os.Setenv("PATH", strings.Join(cur, string(os.PathListSeparator)))+}diff --git a/internal/proc/nodever_other.go b/internal/proc/nodever_other.goindex 609a07158..df32075bd 100644--- a/internal/proc/nodever_other.go+++ b/internal/proc/nodever_other.go@@ -49,58 +49,6 @@ func nvmBins(dir string) (bins []string, def string, system bool) {return bins, def, system}-// nodeVersions are the names of the version folders under root that have-// a folder bin (root/<version>/<bin>), highest version first (nodeVersionLess); a name that is-// no version (mise's "lts", "latest") after every one that is.-func nodeVersions(root, bin string) []string {- es, _ := os.ReadDir(root)- var names []string- for _, e := range es {- if st, err := os.Stat(filepath.Join(root, e.Name(), bin)); err == nil && st.IsDir() {- names = append(names, e.Name())- }- }- slices.SortStableFunc(names, func(a, b string) int {- switch {- case nodeVersionLess(b, a):- return -1- case nodeVersionLess(a, b):- return 1- }- return strings.Compare(a, b)- })- return names-}--// parseNodeVersion reads v22.12.0 (or 22.12.0, mise's, or 22, a partial-// one) as its numbers; false for a name that isn't one.-func parseNodeVersion(s string) ([3]int, int, bool) {- var v [3]int- parts := strings.Split(strings.TrimPrefix(s, "v"), ".")- if len(parts) > 3 || parts[0] == "" {- return v, 0, false- }- for i, p := range parts {- n, err := strconv.Atoi(p)- if err != nil || n < 0 {- return v, 0, false- }- v[i] = n- }- return v, len(parts), true-}--// nodeVersionLess says a is a lower version than b, by number: v9 before-// v22. A name that is no version is lower than one that is.-func nodeVersionLess(a, b string) bool {- va, _, oka := parseNodeVersion(a)- vb, _, okb := parseNodeVersion(b)- if oka != okb {- return okb- }- return oka && slices.Compare(va[:], vb[:]) < 0-}-// nvmDefault is the installed version (one of names, highest first) nvm's// default alias resolves to, as nvm.sh does when a shell loads it// (nvm_auto use → nvm_resolve_local_alias default): alias/default, then@@ -235,8 +183,3 @@ func nodeBins(root string) []string {}return bins}--func isDir(p string) bool {- st, err := os.Stat(p)- return err == nil && st.IsDir()-}diff --git a/internal/proc/nodever_test.go b/internal/proc/nodever_test.gonew file mode 100644index 000000000..9fca567f8--- /dev/null+++ b/internal/proc/nodever_test.go@@ -0,0 +1,116 @@+package proc++import (+ "os"+ "path/filepath"+ "slices"+ "testing"+)++// fnmWin lays fnm out at root as it is on Windows (#2685): each version's+// programs in node-versions\<v>\installation itself, no bin, and+// aliases\default leading to def's installation folder (a junction there,+// a symlink here; a folder of its own where neither can be made). "" for+// def leaves the alias out.+func fnmWin(t *testing.T, root, def string, versions ...string) {+ t.Helper()+ for _, v := range versions {+ inst := filepath.Join(root, "node-versions", v, "installation")+ if err := os.MkdirAll(inst, 0o755); err != nil {+ t.Fatal(err)+ }+ for _, f := range []string{"node.exe", "npx.cmd"} {+ if err := os.WriteFile(filepath.Join(inst, f), nil, 0o644); err != nil {+ t.Fatal(err)+ }+ }+ }+ if def == "" {+ return+ }+ alias := filepath.Join(root, "aliases", "default")+ if err := os.MkdirAll(filepath.Dir(alias), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(filepath.Join(root, "node-versions", def, "installation"), alias); err != nil {+ if err := os.MkdirAll(alias, 0o755); err != nil {+ t.Fatal(err)+ }+ }+}++// fnm's Windows folders in the order a terminal reaches them: the default+// alias's, as it stands (where the reporter's npx.cmd is), then each+// installation folder by version number, v24 before v9.+func TestFnmWinBins(t *testing.T) {+ root := filepath.Join(t.TempDir(), "fnm")+ fnmWin(t, root, "v20.18.0", "v9.11.2", "v24.19.0", "v20.18.0")+ if err := os.MkdirAll(filepath.Join(root, "node-versions", "v25.0.0"), 0o755); err != nil {+ t.Fatal(err) // being installed: no installation folder yet+ }+ inst := func(v string) string { return filepath.Join(root, "node-versions", v, "installation") }+ want := []string{filepath.Join(root, "aliases", "default"), inst("v24.19.0"), inst("v20.18.0"), inst("v9.11.2")}+ if got := fnmWinBins(root); !slices.Equal(got, want) {+ t.Fatalf("fnmWinBins = %q\nwant %q", got, want)+ }+ if got, want := fnmWinUse(root), filepath.Join(root, "aliases", "default"); got != want {+ t.Fatalf("fnmWinUse = %q, want the default alias %q", got, want)+ }+ if _, err := os.Stat(filepath.Join(fnmWinUse(root), "node.exe")); err != nil {+ t.Fatalf("no node.exe in the default alias's folder: %v", err)+ }+}++// With no default alias a terminal's fnm has no Node of its own; magpie+// takes the highest installed, as it does for nvm. A default that leads+// nowhere is fnm's "system" alias (Z:\_fnm_\...): the system's Node, which+// PATH has already, so none.+func TestFnmWinUseWithoutDefault(t *testing.T) {+ root := filepath.Join(t.TempDir(), "fnm")+ fnmWin(t, root, "", "v9.11.2", "v22.12.0")+ if got, want := fnmWinUse(root), filepath.Join(root, "node-versions", "v22.12.0", "installation"); got != want {+ t.Fatalf("no default: fnmWinUse = %q, want %q", got, want)+ }+ alias := filepath.Join(root, "aliases", "default")+ if err := os.MkdirAll(filepath.Dir(alias), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(filepath.Join(t.TempDir(), "_fnm_", "Nothing", "installation"), alias); err != nil {+ t.Skipf("no symlink here: %v", err)+ }+ if got := fnmWinUse(root); got != "" {+ t.Fatalf(`"system" default: fnmWinUse = %q, want none`, got)+ }+}++// fnm's root on Windows: FNM_DIR, else %APPDATA%\fnm (etcetera's+// data_dir), else the legacy ~\.fnm; the folder a terminal gets is the+// default alias's in the first of them. Given as Windows sets them, under+// a temp folder.+func TestFnmWinPath(t *testing.T) {+ home := t.TempDir()+ appdata := filepath.Join(home, "AppData", "Roaming")+ roaming := filepath.Join(appdata, "fnm")+ if got := fnmWinPath(home, appdata, ""); got != nil {+ t.Fatalf("no fnm: fnmWinPath = %q", got)+ }+ fnmWin(t, roaming, "v24.19.0", "v24.19.0")+ if got, want := fnmWinPath(home, appdata, ""), []string{filepath.Join(roaming, "aliases", "default")}; !slices.Equal(got, want) {+ t.Fatalf("APPDATA's fnm: fnmWinPath = %q, want %q", got, want)+ }+ // APPDATA unset or relative: the home's AppData\Roaming, where etcetera+ // puts it+ if got := fnmWinRoots(home, "AppData", ""); !slices.Equal(got, []string{roaming}) {+ t.Fatalf("relative APPDATA: fnmWinRoots = %q, want %q", got, []string{roaming})+ }+ legacy := filepath.Join(home, ".fnm")+ fnmWin(t, legacy, "v18.0.0", "v18.0.0")+ moved := filepath.Join(home, "D", "fnm")+ fnmWin(t, moved, "v22.12.0", "v22.12.0")+ if got, want := fnmWinRoots(home, appdata, moved), []string{moved, roaming, legacy}; !slices.Equal(got, want) {+ t.Fatalf("fnmWinRoots = %q, want %q", got, want)+ }+ if got, want := fnmWinPath(home, appdata, moved), []string{filepath.Join(moved, "aliases", "default")}; !slices.Equal(got, want) {+ t.Fatalf("FNM_DIR: fnmWinPath = %q, want %q", got, want)+ }+}diff --git a/internal/proc/path_other.go b/internal/proc/path_other.goindex 81c841e3a..2839f6ef6 100644--- a/internal/proc/path_other.go+++ b/internal/proc/path_other.go@@ -456,19 +456,3 @@ func parseShellEnv(s, mark string) (string, map[string]string) {}return f[0], vars}--// addPath adds the folders PATH lacks, after the ones it has.-func addPath(dirs []string) {- cur := filepath.SplitList(os.Getenv("PATH"))- seen := map[string]bool{}- for _, d := range cur {- seen[d] = true- }- for _, d := range dirs {- if d != "" && filepath.IsAbs(d) && !seen[d] {- seen[d] = true- cur = append(cur, d)- }- }- os.Setenv("PATH", strings.Join(cur, string(os.PathListSeparator)))-}diff --git a/internal/proc/path_windows.go b/internal/proc/path_windows.goindex 6729b1a96..6fd54109c 100644--- a/internal/proc/path_windows.go+++ b/internal/proc/path_windows.go@@ -10,13 +10,22 @@ import ("github.com/yetone/magpie/internal/appdir")-// UserPath has nothing to do on Windows: an app started from the Start menu-// gets the user's PATH from the registry, as a terminal does.-func UserPath() {}+// UserPath gives magpie, and what it starts, the Node a terminal has from+// fnm (#2685). An app started from the Start menu gets the user's PATH from+// the registry, as a terminal does, but fnm puts its Node on PATH from the+// shell's profile (`fnm env | Invoke-Expression`) and never in the+// registry: an MCP server run with npx, even by npx.cmd's full path, died+// with "'node' is not recognized" once the package it fetched ran node.+// The folder fnm's default alias names is added after the ones PATH has.+func UserPath() {+ home, _ := os.UserHomeDir()+ addPath(fnmWinPath(home, appdir.Getenv("APPDATA"), os.Getenv("FNM_DIR")))+}// UserBinDirs are the folders a user's command-line tools are installed in// that exist here — npm's global one, bun's, volta's, pnpm's, mise's-// shims, the standalone installers' — for finding one PATH doesn't reach.+// shims, the standalone installers', each Node version of fnm's, its+// default first — for finding one PATH doesn't reach.func UserBinDirs() []string {home, _ := os.UserHomeDir()// mise's data folder: MISE_DATA_DIR, else XDG_DATA_HOME's mise (which@@ -36,6 +45,9 @@ func UserBinDirs() []string {filepath.Join(appdir.Getenv("LOCALAPPDATA"), "pnpm"),filepath.Join(mise, "shims"),}+ for _, r := range fnmWinRoots(home, appdir.Getenv("APPDATA"), os.Getenv("FNM_DIR")) {+ known = append(known, fnmWinBins(r)...)+ }var have []stringfor _, d := range known {if st, err := os.Stat(d); filepath.IsAbs(d) && err == nil && st.IsDir() {diff --git a/internal/proc/path_windows_test.go b/internal/proc/path_windows_test.gonew file mode 100644index 000000000..22edaa62b--- /dev/null+++ b/internal/proc/path_windows_test.go@@ -0,0 +1,67 @@+package proc++import (+ "os"+ "path/filepath"+ "slices"+ "strings"+ "testing"+)++// #2685: an MCP server started by fnm's npx.cmd, by its full path, runs+// the package it fetched, which runs `node` by name. A terminal's fnm put+// node's folder on PATH; magpie's PATH, the registry's, didn't have it,+// and the server exited 1 with cmd's "'node' is not recognized as an+// internal or external command, operable program or batch file." After+// UserPath the child finds fnm's node, and FindTool finds a bare npx.+func TestUserPathFnmNode(t *testing.T) {+ home := t.TempDir()+ appdata := filepath.Join(home, "AppData", "Roaming")+ t.Setenv("USERPROFILE", home)+ t.Setenv("APPDATA", appdata)+ t.Setenv("FNM_DIR", "")+ sys := filepath.Join(os.Getenv("SystemRoot"), "System32")+ t.Setenv("PATH", sys)+ root := filepath.Join(appdata, "fnm")+ inst := filepath.Join(root, "node-versions", "v24.19.0", "installation")+ if err := os.MkdirAll(inst, 0o755); err != nil {+ t.Fatal(err)+ }+ // npx's package bin, as npm's cmd shim runs it: node from PATH+ npx := filepath.Join(inst, "npx.cmd")+ for p, s := range map[string]string{npx: "@echo off\r\nnode %*\r\n", filepath.Join(inst, "node.cmd"): "@echo fnm node %*\r\n"} {+ if err := os.WriteFile(p, []byte(s), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ alias := filepath.Join(root, "aliases", "default")+ if err := os.MkdirAll(filepath.Dir(alias), 0o755); err != nil {+ t.Fatal(err)+ }+ // a junction, as fnm makes it+ if out, err := Command("cmd", "/c", "mklink", "/J", alias, inst).CombinedOutput(); err != nil {+ t.Fatalf("mklink /J: %v %s", err, out)+ }+ run := func() (string, error) {+ cmd := Command(npx, "-y", "chrome-devtools-mcp@latest")+ cmd.Dir = t.TempDir() // cmd looks in its folder before PATH+ out, err := cmd.CombinedOutput()+ return strings.TrimSpace(string(out)), err+ }+ if out, err := run(); err == nil {+ t.Fatalf("before UserPath node was found already (%q): the test proves nothing", out)+ }++ UserPath()+ if dirs := filepath.SplitList(os.Getenv("PATH")); !slices.Contains(dirs, alias) {+ t.Fatalf("PATH after UserPath = %q, want fnm's default alias %q on it", dirs, alias)+ }+ if out, err := run(); err != nil || out != "fnm node -y chrome-devtools-mcp@latest" {+ t.Fatalf("npx.cmd by its full path: %v %q, want fnm's node run", err, out)+ }+ t.Setenv("PATH", sys)+ Forget()+ if got := FindTool("npx"); !strings.EqualFold(got, filepath.Join(alias, "npx.cmd")) {+ t.Fatalf("FindTool(npx) = %q, want the default alias's %q", got, filepath.Join(alias, "npx.cmd"))+ }+}