Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(hetero-agents): find agents in every install folder, and WSL agents behind any shell setup (#23681)

Lobehub Coder16618b1554eb
diff --git a/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.ts b/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.ts
index afb37935baa..dcf5348b264 100644
--- a/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.ts
@@ -4,8 +4,9 @@ import { DSH_MIN_VERSION, resolveDshSpawnCommand } from './dshAcpSession';
const { detectValidatedCommand } = vi.hoisted(() => ({ detectValidatedCommand: vi.fn() }));
-// The WSL fallback only runs on Windows; here it hands the native result back.
+// The install-folder sweep and the WSL fallback hand the native result back.
vi.mock('./resolveCliCommand', () => ({
+ detectInUserBinDirs: async (status: unknown) => status,
detectInWslWhenMissing: async (status: unknown) => status,
detectValidatedCommandCandidates: detectValidatedCommand,
}));
diff --git a/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts b/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts
index cf34d7aa0fe..c70674fc363 100644
--- a/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts
+++ b/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts
@@ -1,6 +1,3 @@
-import { homedir, platform } from 'node:os';
-import path from 'node:path';
-
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import type { HeterogeneousAgentModel } from '@lobechat/types';
import { parseModelTuple } from '@lobechat/types';
@@ -15,7 +12,11 @@ import {
import type { AcpRpcMessage } from './acpStdioClient';
import { AcpServerRequestError } from './acpStdioClient';
import type { CliCommandStatus, ResolvedHeteroCommand } from './resolveCliCommand';
-import { detectInWslWhenMissing, detectValidatedCommandCandidates } from './resolveCliCommand';
+import {
+ detectInUserBinDirs,
+ detectInWslWhenMissing,
+ detectValidatedCommandCandidates,
+} from './resolveCliCommand';
/**
* DeepSeek Harness over the Agent Client Protocol.
@@ -54,36 +55,25 @@ const isSupportedDshVersion = (version: string | undefined): boolean => {
* Find a `dsh` that can run LobeHub turns. An older CLI still answers
* `--version` but has no `acp` profile, so it is reported unavailable here
* rather than failing every turn after the agent was created.
+ *
+ * `dsh` is installed with `npm i -g`, which puts it in whichever global folder
+ * the user's Node setup has: `%APPDATA%\npm`, an nvm-windows or fnm Node's own
+ * folder, a pnpm / bun / Volta global, often off the PATH this app started
+ * with. Those folders are swept before WSL is asked.
*/
-/**
- * `dsh` is installed with `npm i -g`. On Windows that drops `dsh.cmd` in npm's
- * global prefix (`%APPDATA%\npm`), a directory npm's installer only adds to the
- * registry User PATH, so an app started before it never sees it.
- */
-const getDshWellKnownPaths = (): string[] =>
- platform() === 'win32'
- ? [
- path.win32.join(
- process.env.APPDATA || path.win32.join(homedir(), 'AppData', 'Roaming'),
- 'npm',
- 'dsh.cmd',
- ),
- ]
- : [];
-
export const detectDshCommand = async (
command: string = DSH_COMMAND,
env?: NodeJS.ProcessEnv,
): Promise<CliCommandStatus> => {
const isDefaultCommand = command.trim() === DSH_COMMAND;
const validation = { validatePattern: DSH_VERSION_PATTERN };
- const nativeStatus = await detectValidatedCommandCandidates(
- isDefaultCommand ? [command, ...getDshWellKnownPaths()] : [command],
- validation,
- env,
- );
+ const nativeStatus = await detectValidatedCommandCandidates([command], validation, env);
const status = isDefaultCommand
- ? await detectInWslWhenMissing(nativeStatus, [DSH_COMMAND], validation)
+ ? await detectInWslWhenMissing(
+ await detectInUserBinDirs(nativeStatus, [DSH_COMMAND], validation, env),
+ [DSH_COMMAND],
+ validation,
+ )
: nativeStatus;
if (!status.available || isSupportedDshVersion(status.version)) return status;
return {
diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
index adad4a91f58..b17857127ed 100644
--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
@@ -268,8 +268,9 @@ describe('resolveCliCommand', () => {
try {
callExecFile('/Users/x/.grok/bin/agent\n');
callExecFile('Usage: agent [flags]\nGrok CLI agent');
+ callExecFileError(new Error('cursor-agent not found'));
callExecFile('Usage: agent [flags]\nGrok CLI agent');
- callExecFile('Usage: agent [options] [command] [prompt...]\nStart the Cursor Agent');
+ callExecFile('Usage: cursor-agent [options] [command] [prompt...]\nStart the Cursor Agent');
const { detectHeterogeneousCliCommand } = await importModule();
const status = await detectHeterogeneousCliCommand('cursor', 'agent');
@@ -279,9 +280,8 @@ describe('resolveCliCommand', () => {
path: path.join(os.homedir(), '.local', 'bin', 'cursor-agent'),
version: undefined,
});
- expect(execFileMock.mock.calls[1]![1]).toEqual(['--help']);
- expect(execFileMock.mock.calls[2]![1]).toEqual(['--help']);
- expect(execFileMock.mock.calls[3]![1]).toEqual(['--help']);
+ const argv = execFileMock.mock.calls.map((call) => call[1]);
+ expect(argv).toEqual([['agent'], ['--help'], ['cursor-agent'], ['--help'], ['--help']]);
} finally {
process.env.PATH = originalPath;
if (originalShell === undefined) delete process.env.SHELL;
diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
index d5d19fa1bd4..ac369398bb7 100644
--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
@@ -6,6 +6,7 @@ import { promisify } from 'node:util';
import type { LocalHeterogeneousAgentType } from '../config';
import { HETEROGENEOUS_AGENT_CONFIGS } from '../config';
import { resolveCliSpawnPlan } from './cliSpawn';
+import { findCommandInUserBinDirs } from './userBinDirs';
import { findWslCommandCandidates, invalidateWslCache, isWslCommand } from './wsl';
/**
@@ -718,7 +719,8 @@ const HETEROGENEOUS_CLI_AGENT_OPTIONS = {
},
'cursor': {
validateFlag: '--help',
- validatePattern: /^Usage: agent[\s\S]*Cursor Agent/im,
+ // Help names the program as it was invoked: `agent` or its `cursor-agent` alias.
+ validatePattern: /^Usage: (?:cursor-)?agent[\s\S]*Cursor Agent/im,
},
'droid': {
validateHelpArgs: ['exec', '--help'],
@@ -872,7 +874,10 @@ const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[
const localAppData = process.env.LOCALAPPDATA;
if (!localAppData) return [];
- return [path.win32.join(localAppData, 'cursor-agent', 'agent.cmd')];
+ return [
+ path.win32.join(localAppData, 'cursor-agent', 'agent.cmd'),
+ path.win32.join(localAppData, 'cursor-agent', 'cursor-agent.cmd'),
+ ];
}
if (platform() !== 'darwin' && platform() !== 'linux') return [];
return [
@@ -986,17 +991,72 @@ export const detectHeterogeneousCliCommand = async (
// them to a custom command (e.g. `claude-beta`) would silently resolve it to
// stock `claude` instead of reporting the configured command as missing.
const isDefaultCommand = command.trim() === DEFAULT_HETERO_COMMAND[agentType];
- const commands = isDefaultCommand ? [command, ...getWellKnownCommandPaths(agentType)] : [command];
+ if (!isDefaultCommand) return detectValidatedCommandCandidates([command], validator, probeEnv);
+
+ const names = [command, ...(DEFAULT_COMMAND_ALIASES[agentType] ?? [])];
+ const status = await detectValidatedCommandCandidates(
+ [...names, ...getWellKnownCommandPaths(agentType)],
+ validator,
+ probeEnv,
+ );
+ const swept = await detectInUserBinDirs(status, names, validator, probeEnv);
+ return detectInWslWhenMissing(swept, names, validator);
+};
- const status = await detectValidatedCommandCandidates(commands, validator, probeEnv);
- if (!isDefaultCommand) return status;
+// Other names an agent's installer gives the default binary. Cursor's creates
+// `agent` and the unambiguous `cursor-agent` alias, which is the one left
+// standing when another tool's `agent` comes first on PATH.
+const DEFAULT_COMMAND_ALIASES: Partial<Record<HeterogeneousCliAgentType, string[]>> = {
+ cursor: ['cursor-agent'],
+};
- return detectInWslWhenMissing(status, WSL_COMMAND_NAMES[agentType] ?? [command], validator);
+/** Same-environment copy of `env` with `file`'s folder put first on PATH. */
+const withFolderOnPath = (file: string, env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {
+ const base = env ?? process.env;
+ const windows = isWindows();
+ const dir = windows ? path.win32.dirname(file) : path.posix.dirname(file);
+ const delimiter = windows ? ';' : ':';
+ // A copied Windows environment keeps the variable's own spelling (`Path`).
+ // Written back as `PATH`, which Node passes ahead of `Path` to the child.
+ const key =
+ base.PATH === undefined && windows
+ ? Object.keys(base).find((name) => name.toLowerCase() === 'path')
+ : 'PATH';
+ const current = (key && base[key]) || '';
+ const onPath = current
+ .split(delimiter)
+ .some((entry) => (windows ? entry.toLowerCase() === dir.toLowerCase() : entry === dir));
+ return onPath ? base : { ...base, PATH: current ? `${dir}${delimiter}${current}` : dir };
};
-// Cursor's installer creates `agent` and the unambiguous `cursor-agent` alias.
-const WSL_COMMAND_NAMES: Partial<Record<HeterogeneousCliAgentType, string[]>> = {
- cursor: ['agent', 'cursor-agent'],
+/**
+ * When PATH and the agent's own install locations have nothing, look through
+ * the folders every package and version manager installs CLIs into
+ * (`userBinDirs`): an `npm i -g` under nvm or fnm, a bun / pnpm / Volta global,
+ * a Scoop or winget shim. Each hit is validated with its own folder first on
+ * PATH — an npm CLI under nvm is a `#!/usr/bin/env node` script whose `node`
+ * sits beside it — and that PATH is handed to the spawn site with the result.
+ */
+export const detectInUserBinDirs = async (
+ status: CliCommandStatus,
+ commandNames: string[],
+ options: ValidateOptions,
+ probeEnv?: NodeJS.ProcessEnv,
+): Promise<CliCommandStatus> => {
+ if (status.available) return status;
+
+ const candidates = await findCommandInUserBinDirs(commandNames, {
+ env: probeEnv ?? process.env,
+ }).catch(() => []);
+ for (const candidate of candidates) {
+ const found = await detectValidatedCommandInEnvironment(
+ candidate,
+ options,
+ withFolderOnPath(candidate, probeEnv),
+ );
+ if (found.available) return found;
+ }
+ return status;
};
/**
diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.windowsFallbacks.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.windowsFallbacks.test.ts
index 68d205cc810..699637408cd 100644
--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.windowsFallbacks.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.windowsFallbacks.test.ts
@@ -118,6 +118,46 @@ describe('Windows install locations off PATH', () => {
await expect(detectDshCommand()).resolves.toMatchObject({ available: true, path: shim });
});
+ it('finds an agent a package manager put off PATH, and runs it with that folder on PATH', async () => {
+ // `scoop install opencode`: the shim folder reaches PATH only in new shells.
+ vi.stubEnv('SCOOP', 'C:\\Users\\me\\scoop');
+ const shim = 'C:\\Users\\me\\scoop\\shims\\opencode.exe';
+ existingPaths(shim);
+ answerExecFile((file, args) =>
+ file === shim && args.at(-1) === '--version' ? 'opencode v2.2.6\n' : undefined,
+ );
+
+ const { detectHeterogeneousCliCommand } = await importModule();
+
+ await expect(detectHeterogeneousCliCommand('opencode', 'opencode')).resolves.toMatchObject({
+ available: true,
+ path: shim,
+ resolvedPathEnv: 'C:\\Users\\me\\scoop\\shims;C:\\Windows',
+ version: '2.2.6',
+ });
+ // Found on Windows: WSL is never woken.
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it("finds Cursor by its `cursor-agent` alias when that's the name on PATH", async () => {
+ const alias = 'C:\\tools\\cursor-agent.exe';
+ existingPaths(alias);
+ answerExecFile((file, args) => {
+ if (file === 'where' && args[0] === 'cursor-agent') return `${alias}\r\n`;
+ if (file === alias && args.at(-1) === '--help') {
+ return 'Usage: cursor-agent [options] [command] [prompt...]\n\nStart the Cursor Agent';
+ }
+ return undefined;
+ });
+
+ const { detectHeterogeneousCliCommand } = await importModule();
+
+ await expect(detectHeterogeneousCliCommand('cursor', 'agent')).resolves.toMatchObject({
+ available: true,
+ path: alias,
+ });
+ });
+
it('does not wake WSL when Windows already has the agent', async () => {
const codex = 'C:\\tools\\codex.exe';
existingPaths(codex);
diff --git a/packages/heterogeneous-agents/src/spawn/userBinDirs.test.ts b/packages/heterogeneous-agents/src/spawn/userBinDirs.test.ts
new file mode 100644
index 00000000000..d618f360903
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/userBinDirs.test.ts
@@ -0,0 +1,108 @@
+import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { findCommandInUserBinDirs, getUserBinDirs, sortVersionDirsDesc } from './userBinDirs';
+
+describe('sortVersionDirsDesc', () => {
+ it('orders Node version folders newest first, numerically, and drops the rest', () => {
+ expect(sortVersionDirsDesc(['v9.11.2', 'v18.20.0', 'v22.3.0', 'v22.10.1', '.cache'])).toEqual([
+ 'v22.10.1',
+ 'v22.3.0',
+ 'v18.20.0',
+ 'v9.11.2',
+ ]);
+ });
+});
+
+describe('getUserBinDirs on Windows', () => {
+ const home = 'C:\\Users\\me';
+ const env = {
+ APPDATA: 'C:\\Users\\me\\AppData\\Roaming',
+ LOCALAPPDATA: 'C:\\Users\\me\\AppData\\Local',
+ NVM_SYMLINK: 'C:\\nvm4w\\nodejs',
+ ProgramData: 'C:\\ProgramData',
+ ProgramFiles: 'C:\\Program Files',
+ };
+
+ it('covers npm, pnpm, bun, Volta, nvm-windows, fnm, Scoop, winget and Chocolatey', async () => {
+ const dirs = await getUserBinDirs({ env, home, os: 'win32' });
+
+ expect(dirs).toEqual(
+ expect.arrayContaining([
+ 'C:\\Users\\me\\.local\\bin',
+ 'C:\\Users\\me\\AppData\\Roaming\\npm',
+ 'C:\\Users\\me\\AppData\\Local\\pnpm',
+ 'C:\\Users\\me\\.bun\\bin',
+ 'C:\\Users\\me\\AppData\\Local\\Volta\\bin',
+ 'C:\\nvm4w\\nodejs',
+ 'C:\\Users\\me\\AppData\\Roaming\\fnm\\aliases\\default',
+ 'C:\\Users\\me\\scoop\\shims',
+ 'C:\\Users\\me\\AppData\\Local\\Microsoft\\WinGet\\Links',
+ 'C:\\ProgramData\\chocolatey\\bin',
+ ]),
+ );
+ // A standalone installer's folder beats a package manager's shim.
+ expect(dirs.indexOf('C:\\Users\\me\\.local\\bin')).toBeLessThan(
+ dirs.indexOf('C:\\Users\\me\\AppData\\Roaming\\npm'),
+ );
+ });
+
+ it('reads variables case-insensitively, as Windows does, and drops duplicates', async () => {
+ const dirs = await getUserBinDirs({
+ env: { ...env, NVM_SYMLINK: undefined, nvm_symlink: 'D:\\node' },
+ home,
+ os: 'win32',
+ });
+
+ expect(dirs).toContain('D:\\node');
+ expect(new Set(dirs.map((dir) => dir.toLowerCase())).size).toBe(dirs.length);
+ });
+});
+
+describe('findCommandInUserBinDirs on macOS / Linux', () => {
+ let home: string;
+
+ const installAt = async (relativePath: string, mode = 0o755) => {
+ const file = path.join(home, relativePath);
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, '#!/usr/bin/env node\n');
+ await chmod(file, mode);
+ return file;
+ };
+
+ beforeEach(async () => {
+ home = await mkdtemp(path.join(tmpdir(), 'user-bin-dirs-'));
+ });
+
+ afterEach(async () => {
+ await rm(home, { force: true, recursive: true });
+ });
+
+ it("finds a CLI under every nvm Node, the default alias's first", async () => {
+ const old = await installAt('.nvm/versions/node/v18.20.0/bin/codex');
+ const newest = await installAt('.nvm/versions/node/v24.1.0/bin/codex');
+ const current = await installAt('.nvm/versions/node/v22.3.0/bin/codex');
+ await mkdir(path.join(home, '.nvm/alias'), { recursive: true });
+ await writeFile(path.join(home, '.nvm/alias/default'), '22\n');
+
+ await expect(
+ findCommandInUserBinDirs(['codex'], { env: {}, home, os: 'linux' }),
+ ).resolves.toEqual([current, newest, old]);
+ });
+
+ it("finds bun, fnm and .npmrc-prefix globals, and skips files that can't run", async () => {
+ const viaBun = await installAt('.bun/bin/opencode');
+ const viaFnm = await installAt('.local/share/fnm/node-versions/v20.1.0/installation/bin/dsh');
+ const viaPrefix = await installAt('.npm-packages/bin/pi');
+ await installAt('.local/bin/pi', 0o644);
+ await writeFile(path.join(home, '.npmrc'), 'prefix=~/.npm-packages\n');
+
+ const options = { env: {}, home, os: 'linux' as const };
+ await expect(findCommandInUserBinDirs(['opencode'], options)).resolves.toEqual([viaBun]);
+ await expect(findCommandInUserBinDirs(['dsh'], options)).resolves.toEqual([viaFnm]);
+ await expect(findCommandInUserBinDirs(['pi'], options)).resolves.toEqual([viaPrefix]);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/userBinDirs.ts b/packages/heterogeneous-agents/src/spawn/userBinDirs.ts
new file mode 100644
index 00000000000..c1bfff2762e
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/userBinDirs.ts
@@ -0,0 +1,312 @@
+import { constants } from 'node:fs';
+import { access, readdir, readFile } from 'node:fs/promises';
+import { homedir, platform } from 'node:os';
+import path from 'node:path';
+
+/**
+ * Folders that package managers, version managers and standalone installers
+ * put a user's command-line tools in, for finding a CLI that PATH doesn't reach.
+ *
+ * A desktop app started from the Dock, the Start menu or a service manager
+ * gets a lean PATH: nvm, fnm, mise and bun add their folders from a shell
+ * profile, and on Windows an installer's registry PATH edit never reaches a
+ * process started before it. Each agent's own well-known paths only cover the
+ * installers we knew of for that agent; this sweep covers every install method
+ * for every agent, so an `npm i -g` through nvm-windows, a `bun add -g`, a
+ * pnpm or Volta global, a Scoop or winget shim are all found the same way.
+ *
+ * Node's own version folders come in the order a terminal would pick them: the
+ * version manager's default first, then the rest newest first.
+ */
+
+export interface UserBinDirsOptions {
+ env?: NodeJS.ProcessEnv;
+ home?: string;
+ os?: NodeJS.Platform;
+}
+
+/** Read a variable the way Windows does: names are case-insensitive there. */
+const getEnv = (env: NodeJS.ProcessEnv, name: string, os: NodeJS.Platform): string | undefined => {
+ const exact = env[name]?.trim();
+ if (exact || os !== 'win32') return exact || undefined;
+ const lower = name.toLowerCase();
+ const key = Object.keys(env).find(
+ (candidate) => candidate.toLowerCase() === lower && !!env[candidate]?.trim(),
+ );
+ return key ? env[key]!.trim() : undefined;
+};
+
+const pathFor = (os: NodeJS.Platform) => (os === 'win32' ? path.win32 : path.posix);
+
+const readDirNames = async (dir: string): Promise<string[]> => {
+ try {
+ const entries = await readdir(dir);
+ return Array.isArray(entries) ? entries.map(String) : [];
+ } catch {
+ return [];
+ }
+};
+
+const VERSION_DIR = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/;
+
+/** Version folder names (`v22.3.0`, `22.3.0`), newest first; others dropped. */
+export const sortVersionDirsDesc = (names: string[]): string[] =>
+ names
+ .map((name) => ({ match: name.match(VERSION_DIR), name }))
+ .filter((entry): entry is { match: RegExpMatchArray; name: string } => !!entry.match)
+ .sort((a, b) => {
+ for (let index = 1; index <= 3; index += 1) {
+ const diff = Number(b.match[index] ?? 0) - Number(a.match[index] ?? 0);
+ if (diff !== 0) return diff;
+ }
+ return 0;
+ })
+ .map(({ name }) => name);
+
+/**
+ * Put the versions a default alias names (`22`, `v22.3.0`) ahead of the rest.
+ * An alias that names no version (`lts/*`, `node`) leaves the order as it is.
+ */
+const defaultFirst = (versions: string[], alias: string | undefined): string[] => {
+ const wanted = alias?.trim().replace(/^v/, '');
+ if (!wanted || !/^\d/.test(wanted)) return versions;
+ const matches = (version: string) => {
+ const bare = version.replace(/^v/, '');
+ return bare === wanted || bare.startsWith(`${wanted}.`);
+ };
+ return [...versions.filter(matches), ...versions.filter((version) => !matches(version))];
+};
+
+const readFirstLine = async (file: string): Promise<string | undefined> => {
+ try {
+ const content = await readFile(file, 'utf8');
+ return typeof content === 'string' ? content.split(/\r?\n/)[0]?.trim() || undefined : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+/** `prefix=` from the user's `.npmrc`: where `npm i -g` installs when set. */
+const readNpmrcPrefix = async (
+ home: string,
+ os: NodeJS.Platform,
+ env: NodeJS.ProcessEnv,
+): Promise<string | undefined> => {
+ const fromEnv = getEnv(env, 'NPM_CONFIG_PREFIX', os) ?? getEnv(env, 'npm_config_prefix', os);
+ if (fromEnv) return fromEnv;
+
+ let content: unknown;
+ try {
+ content = await readFile(pathFor(os).join(home, '.npmrc'), 'utf8');
+ } catch {
+ return undefined;
+ }
+ if (typeof content !== 'string') return undefined;
+
+ const value = content
+ .match(/^\s*prefix\s*=\s*(.+?)\s*$/m)?.[1]
+ ?.replaceAll(/^["']|["']$/g, '')
+ .trim();
+ if (!value) return undefined;
+ if (value.startsWith('~/') || value.startsWith('~\\')) {
+ return pathFor(os).join(home, value.slice(2));
+ }
+ return pathFor(os).isAbsolute(value) ? value : undefined;
+};
+
+const nodeVersionBins = async (
+ versionsDir: string,
+ alias: string | undefined,
+ toBin: (versionDir: string) => string,
+ os: NodeJS.Platform,
+): Promise<string[]> =>
+ defaultFirst(sortVersionDirsDesc(await readDirNames(versionsDir)), alias).map((version) =>
+ toBin(pathFor(os).join(versionsDir, version)),
+ );
+
+const getWindowsUserBinDirs = async (env: NodeJS.ProcessEnv, home: string): Promise<string[]> => {
+ const os = 'win32';
+ const { join } = path.win32;
+ const get = (name: string) => getEnv(env, name, os);
+ const appData = get('APPDATA') ?? join(home, 'AppData', 'Roaming');
+ const localAppData = get('LOCALAPPDATA') ?? join(home, 'AppData', 'Local');
+ const programData = get('ProgramData') ?? 'C:\\ProgramData';
+ const programFiles = get('ProgramFiles') ?? 'C:\\Program Files';
+
+ // npm's global folder on Windows is the prefix itself, not `<prefix>\bin`.
+ const npmPrefix = await readNpmrcPrefix(home, os, env);
+
+ // nvm-windows keeps each Node under NVM_HOME and links the active one at
+ // NVM_SYMLINK; `npm i -g` installs into that Node's own folder.
+ const nvmHome = get('NVM_HOME');
+ const nvmVersions = nvmHome ? await nodeVersionBins(nvmHome, undefined, (dir) => dir, os) : [];
+
+ // fnm's default alias, then each installed Node (global CLIs live beside node.exe).
+ const fnmRoots = [get('FNM_DIR'), join(appData, 'fnm'), join(localAppData, 'fnm')].filter(
+ (dir): dir is string => !!dir,
+ );
+ const fnmDirs: string[] = [];
+ for (const root of new Set(fnmRoots)) {
+ fnmDirs.push(
+ join(root, 'aliases', 'default'),
+ ...(await nodeVersionBins(
+ join(root, 'node-versions'),
+ undefined,
+ (dir) => join(dir, 'installation'),
+ os,
+ )),
+ );
+ }
+
+ const miseData =
+ get('MISE_DATA_DIR') ??
+ (get('XDG_DATA_HOME') ? join(get('XDG_DATA_HOME')!, 'mise') : join(localAppData, 'mise'));
+ const scoop = get('SCOOP') ?? join(home, 'scoop');
+ const scoopGlobal = get('SCOOP_GLOBAL') ?? join(programData, 'scoop');
+
+ return [
+ // Standalone installers (Claude Code, Devin, …).
+ join(home, '.local', 'bin'),
+ ...(npmPrefix ? [npmPrefix] : []),
+ join(appData, 'npm'),
+ ...(get('PNPM_HOME') ? [get('PNPM_HOME')!] : []),
+ join(localAppData, 'pnpm'),
+ ...(get('BUN_INSTALL') ? [join(get('BUN_INSTALL')!, 'bin')] : []),
+ join(home, '.bun', 'bin'),
+ ...(get('VOLTA_HOME') ? [join(get('VOLTA_HOME')!, 'bin')] : []),
+ join(localAppData, 'Volta', 'bin'),
+ ...(get('NVM_SYMLINK') ? [get('NVM_SYMLINK')!] : []),
+ 'C:\\nvm4w\\nodejs',
+ ...nvmVersions,
+ ...fnmDirs,
+ join(miseData, 'shims'),
+ join(scoop, 'shims'),
+ join(scoopGlobal, 'shims'),
+ join(localAppData, 'Microsoft', 'WinGet', 'Links'),
+ join(programFiles, 'WinGet', 'Links'),
+ join(get('ChocolateyInstall') ?? join(programData, 'chocolatey'), 'bin'),
+ join(programFiles, 'nodejs'),
+ join(home, '.cargo', 'bin'),
+ join(home, '.deno', 'bin'),
+ ];
+};
+
+const getPosixUserBinDirs = async (env: NodeJS.ProcessEnv, home: string): Promise<string[]> => {
+ const os = 'linux';
+ const { join } = path.posix;
+ const get = (name: string) => getEnv(env, name, os);
+ const xdgData = get('XDG_DATA_HOME') ?? join(home, '.local', 'share');
+
+ const npmPrefix = await readNpmrcPrefix(home, os, env);
+
+ const nvmDir = get('NVM_DIR') ?? join(home, '.nvm');
+ const nvmBins = await nodeVersionBins(
+ join(nvmDir, 'versions', 'node'),
+ await readFirstLine(join(nvmDir, 'alias', 'default')),
+ (dir) => join(dir, 'bin'),
+ os,
+ );
+
+ const fnmRoots = [
+ get('FNM_DIR'),
+ join(xdgData, 'fnm'),
+ join(home, 'Library', 'Application Support', 'fnm'),
+ join(home, '.fnm'),
+ ].filter((dir): dir is string => !!dir);
+ const fnmDirs: string[] = [];
+ for (const root of new Set(fnmRoots)) {
+ fnmDirs.push(
+ join(root, 'aliases', 'default', 'bin'),
+ ...(await nodeVersionBins(
+ join(root, 'node-versions'),
+ undefined,
+ (dir) => join(dir, 'installation', 'bin'),
+ os,
+ )),
+ );
+ }
+
+ const miseData = get('MISE_DATA_DIR') ?? join(xdgData, 'mise');
+ const miseNodes = await nodeVersionBins(
+ join(miseData, 'installs', 'node'),
+ undefined,
+ (dir) => join(dir, 'bin'),
+ os,
+ );
+
+ return [
+ join(home, '.local', 'bin'),
+ ...(npmPrefix ? [join(npmPrefix, 'bin')] : []),
+ join(home, '.npm-global', 'bin'),
+ join(home, '.npm', 'bin'),
+ ...(get('BUN_INSTALL') ? [join(get('BUN_INSTALL')!, 'bin')] : []),
+ join(home, '.bun', 'bin'),
+ ...(get('PNPM_HOME') ? [get('PNPM_HOME')!] : []),
+ join(home, 'Library', 'pnpm'),
+ join(xdgData, 'pnpm'),
+ join(get('VOLTA_HOME') ?? join(home, '.volta'), 'bin'),
+ ...nvmBins,
+ ...fnmDirs,
+ join(miseData, 'shims'),
+ ...miseNodes,
+ join(get('ASDF_DATA_DIR') ?? join(home, '.asdf'), 'shims'),
+ join(home, '.cargo', 'bin'),
+ join(home, '.deno', 'bin'),
+ '/opt/homebrew/bin',
+ '/usr/local/bin',
+ '/home/linuxbrew/.linuxbrew/bin',
+ join(home, '.linuxbrew', 'bin'),
+ ];
+};
+
+/** Candidate folders in lookup order, duplicates dropped. Existence isn't checked. */
+export const getUserBinDirs = async ({
+ env = process.env,
+ home = homedir(),
+ os = platform(),
+}: UserBinDirsOptions = {}): Promise<string[]> => {
+ const dirs =
+ os === 'win32' ? await getWindowsUserBinDirs(env, home) : await getPosixUserBinDirs(env, home);
+ const seen = new Set<string>();
+ return dirs.filter((dir) => {
+ const key = os === 'win32' ? dir.toLowerCase() : dir;
+ if (!dir || seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+};
+
+// `.exe` first: a native binary beats a shim beside it. A Windows file without
+// one of these extensions can't be started (npm's extensionless sh shim).
+const WINDOWS_EXTS = ['.exe', '.cmd', '.bat'] as const;
+
+const isRunnableFile = async (file: string, os: NodeJS.Platform): Promise<boolean> => {
+ try {
+ await access(file, os === 'win32' ? constants.F_OK : constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Every runnable file named one of `names` in the user's tool folders, in
+ * folder order then name order. Only files that exist are returned; each still
+ * needs validating, as any folder may hold an unrelated tool of that name.
+ */
+export const findCommandInUserBinDirs = async (
+ names: string[],
+ options: UserBinDirsOptions = {},
+): Promise<string[]> => {
+ const os = options.os ?? platform();
+ const dirs = await getUserBinDirs({ ...options, os });
+ const files = dirs.flatMap((dir) =>
+ names.flatMap((name) =>
+ os === 'win32'
+ ? WINDOWS_EXTS.map((ext) => path.win32.join(dir, `${name}${ext}`))
+ : [path.posix.join(dir, name)],
+ ),
+ );
+ const runnable = await Promise.all(files.map((file) => isRunnableFile(file, os)));
+ return files.filter((_, index) => runnable[index]);
+};
diff --git a/packages/heterogeneous-agents/src/spawn/wsl.test.ts b/packages/heterogeneous-agents/src/spawn/wsl.test.ts
index 33b239a7902..60ced334bb6 100644
--- a/packages/heterogeneous-agents/src/spawn/wsl.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/wsl.test.ts
@@ -118,7 +118,8 @@ describe('buildWslSpawnPlan', () => {
'Ubuntu',
'--exec',
'env',
- 'PATH=/home/me/.nvm/versions/node/v22/bin:/usr/bin',
+ // The binary's own folder first, ahead of the shell PATH.
+ 'PATH=/home/me/.local/bin:/home/me/.nvm/versions/node/v22/bin:/usr/bin',
'/home/me/.local/bin/agent',
'acp',
'--mcp-config',
@@ -127,6 +128,22 @@ describe('buildWslSpawnPlan', () => {
]);
});
+ it("puts an nvm CLI's folder on PATH once, and falls back to a default PATH", () => {
+ const nvmCodex = { distro: 'Ubuntu', linuxPath: '/home/me/.nvm/versions/node/v22/bin/codex' };
+
+ expect(buildWslSpawnPlan(nvmCodex, [], undefined, '/usr/bin').args.slice(3, 5)).toEqual([
+ 'env',
+ 'PATH=/home/me/.nvm/versions/node/v22/bin:/usr/bin',
+ ]);
+ expect(
+ buildWslSpawnPlan(nvmCodex, [], undefined, '/home/me/.nvm/versions/node/v22/bin:/usr/bin')
+ .args[4],
+ ).toBe('PATH=/home/me/.nvm/versions/node/v22/bin:/usr/bin');
+ expect(buildWslSpawnPlan(nvmCodex, [], undefined, undefined).args[4]).toBe(
+ 'PATH=/home/me/.nvm/versions/node/v22/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
+ );
+ });
+
it('forwards the variables the spawn site set through WSLENV, not argv', () => {
vi.stubEnv('LOBEHUB_JWT', 'inherited-token');
vi.stubEnv('HOMEPATH', '\\Users\\me');
@@ -162,8 +179,25 @@ describe('probe output', () => {
expect(probe.pathEnv).toBe('/home/me/.local/bin:/usr/bin');
expect([...probe.commands]).toEqual([
- ['agent', '/home/me/.local/bin/agent'],
- ['dsh', '/home/me/.nvm/versions/node/v22/bin/dsh'],
+ ['agent', ['/home/me/.local/bin/agent']],
+ ['dsh', ['/home/me/.nvm/versions/node/v22/bin/dsh']],
+ ]);
+ });
+
+ it("keeps every location of a command in order, without Windows' own shims", () => {
+ const probe = parseWslProbeOutput(
+ probeOutput([
+ // WSL appends Windows' PATH: Windows npm's sh shim isn't a Linux CLI.
+ '__LOBEHUB_WSL_CMD__=codex=/mnt/c/Users/me/AppData/Roaming/npm/codex',
+ '__LOBEHUB_WSL_CMD__=codex=/home/me/.nvm/versions/node/v22.3.0/bin/codex',
+ '__LOBEHUB_WSL_CMD__=codex=/home/me/.nvm/versions/node/v22.3.0/bin/codex',
+ '__LOBEHUB_WSL_CMD__=codex=/home/me/.nvm/versions/node/v18.20.0/bin/codex',
+ ]),
+ );
+
+ expect(probe.commands.get('codex')).toEqual([
+ '/home/me/.nvm/versions/node/v22.3.0/bin/codex',
+ '/home/me/.nvm/versions/node/v18.20.0/bin/codex',
]);
});
@@ -205,6 +239,9 @@ describe('findWslCommandCandidates', () => {
]);
expect(probe.args).toEqual(expect.arrayContaining(['agent', 'dsh', 'cursor-agent']));
expect(probe.input).toContain('-ilc');
+ // A plain login shell and the install folders back the interactive shell up.
+ expect(probe.input).toContain('sh -lc');
+ expect(probe.input).toContain('/versions/node');
// One probe per distro answers every command and the spawn-time PATH.
await findWslCommandCandidates('dsh');
await expect(getWslPathEnv('Ubuntu')).resolves.toBe('/home/me/bin:/usr/bin');
@@ -222,6 +259,41 @@ describe('findWslCommandCandidates', () => {
expect(spawnMock).not.toHaveBeenCalled();
});
+ it('returns every location of the command, so a broken first one has a fallback', async () => {
+ fakeWsl((args) =>
+ args[0] === '--list'
+ ? { stdout: 'Ubuntu\n' }
+ : {
+ stdout: probeOutput([
+ '__LOBEHUB_WSL_CMD__=codex=/usr/local/bin/codex',
+ '__LOBEHUB_WSL_CMD__=codex=/home/me/.nvm/versions/node/v22.3.0/bin/codex',
+ ]),
+ },
+ );
+
+ await expect(findWslCommandCandidates('codex')).resolves.toEqual([
+ 'wsl://Ubuntu/usr/local/bin/codex',
+ 'wsl://Ubuntu/home/me/.nvm/versions/node/v22.3.0/bin/codex',
+ ]);
+ });
+
+ it('asks for the distro list again after wsl.exe failed to answer it', async () => {
+ let listed = 0;
+ fakeWsl((args) => {
+ if (args[0] === '--list') {
+ listed += 1;
+ // WSL's service still starting after a reboot.
+ return listed === 1 ? { code: 1 } : { stdout: 'Ubuntu\n' };
+ }
+ return { stdout: probeOutput(['__LOBEHUB_WSL_CMD__=agent=/usr/local/bin/agent']) };
+ });
+
+ await expect(findWslCommandCandidates('agent')).resolves.toEqual([]);
+ await expect(findWslCommandCandidates('agent')).resolves.toEqual([
+ 'wsl://Ubuntu/usr/local/bin/agent',
+ ]);
+ });
+
it('retries a distro whose probe failed instead of pinning the failure', async () => {
let attempt = 0;
fakeWsl((args) => {
diff --git a/packages/heterogeneous-agents/src/spawn/wsl.ts b/packages/heterogeneous-agents/src/spawn/wsl.ts
index 39308cfe083..2e329ae1bc6 100644
--- a/packages/heterogeneous-agents/src/spawn/wsl.ts
+++ b/packages/heterogeneous-agents/src/spawn/wsl.ts
@@ -7,9 +7,9 @@ import { HETEROGENEOUS_AGENT_CONFIGS } from '../config';
* Agents installed inside WSL, seen from Windows.
*
* A Windows host can't find a CLI that lives in a WSL distro: `where` only
- * walks the Windows PATH. Detection therefore asks each distro which agent
- * commands its login shell resolves, and reports a hit as a command of the
- * form `wsl://<distro>/<absolute linux path>`
+ * walks the Windows PATH. Detection therefore asks each distro where its
+ * shells and install folders have each agent command (`WSL_PROBE_SCRIPT`), and
+ * reports a hit as a command of the form `wsl://<distro>/<absolute linux path>`
* (e.g. `wsl://Ubuntu/home/me/.local/bin/agent`).
*
* That string travels through every place a resolved command path already
@@ -18,9 +18,10 @@ import { HETEROGENEOUS_AGENT_CONFIGS } from '../config';
*
* wsl.exe --distribution <distro> --exec env PATH=<login PATH> <linux path> …args
*
- * - The login shell's PATH is captured at detection and set explicitly: a
- * `--exec` child gets WSL's bare default PATH, so an nvm-installed node
- * (and with it every `#!/usr/bin/env node` CLI) would not be found.
+ * - The shell's PATH is captured at detection and set explicitly, with the
+ * binary's own folder first: a `--exec` child gets WSL's bare default PATH,
+ * so an nvm-installed node (and with it every `#!/usr/bin/env node` CLI)
+ * would not be found.
* - wsl.exe starts the child in the Windows cwd translated to `/mnt/<drive>`.
* - Absolute Windows paths in the arguments are translated the same way.
* - Variables the spawn site sets for the agent are forwarded through
@@ -152,6 +153,22 @@ export interface WslSpawnPlan {
env?: NodeJS.ProcessEnv;
}
+/** A login shell's PATH, for a distro whose probe printed none. */
+const WSL_DEFAULT_PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin';
+
+/**
+ * The PATH the agent runs with: the distro's shell PATH with the binary's own
+ * folder first. A CLI found in an install folder the shell doesn't put on PATH
+ * (an nvm Node's `bin`, read only by an interactive `.bashrc`) is a
+ * `#!/usr/bin/env node` script whose `node` sits right beside it.
+ */
+export const withWslBinaryFolder = (linuxPath: string, pathEnv: string | undefined): string => {
+ const dir = linuxPath.slice(0, linuxPath.lastIndexOf('/'));
+ const current = pathEnv || WSL_DEFAULT_PATH;
+ if (!dir || current.split(':').includes(dir)) return current;
+ return `${dir}:${current}`;
+};
+
export const buildWslSpawnPlan = (
{ distro, linuxPath }: WslCommand,
args: string[],
@@ -164,7 +181,8 @@ export const buildWslSpawnPlan = (
'--distribution',
distro,
'--exec',
- ...(pathEnv ? ['env', `PATH=${pathEnv}`] : []),
+ 'env',
+ `PATH=${withWslBinaryFolder(linuxPath, pathEnv)}`,
linuxPath,
...args.map(toWslArg),
],
@@ -177,12 +195,21 @@ export const buildWslSpawnPlan = (
// Probing
// ---------------------------------------------------------------------------
-/** A stopped distro boots its VM first, which alone can take several seconds. */
-const WSL_PROBE_TIMEOUT_MS = 20_000;
-const WSL_LIST_TIMEOUT_MS = 5000;
+/**
+ * A stopped distro boots its VM first, which alone can take several seconds;
+ * the probe then gives the user's interactive shell up to
+ * `WSL_INTERACTIVE_SHELL_TIMEOUT_S` and the login shell up to
+ * `WSL_LOGIN_SHELL_TIMEOUT_S`.
+ */
+const WSL_PROBE_TIMEOUT_MS = 30_000;
+const WSL_INTERACTIVE_SHELL_TIMEOUT_S = 10;
+const WSL_LOGIN_SHELL_TIMEOUT_S = 5;
+/** `wsl.exe --list` can wait for WSL's service to start after a reboot. */
+const WSL_LIST_TIMEOUT_MS = 15_000;
const PATH_MARKER = '__LOBEHUB_WSL_PATH__=';
const COMMAND_MARKER = '__LOBEHUB_WSL_CMD__=';
+const SHELL_PATH_MARKER = '__LOBEHUB_WSL_SHELL_PATH__=';
/** Every command name detection may look for inside a distro. */
const WSL_PROBED_COMMANDS = [
@@ -196,14 +223,68 @@ const WSL_PROBED_COMMANDS = [
/**
* Read from stdin by `sh -s`, so nothing in it passes through Windows
- * command-line quoting. Resolves the names in the user's own interactive login
- * shell, where nvm / volta / ~/.local/bin are set up; aliases and functions
- * are skipped by accepting only absolute paths. The interactive shell may print
- * a banner, so results are marked lines.
+ * command-line quoting. Prints the PATH an agent should run with, then every
+ * place each command name (`"$@"`) is found, best first:
+ *
+ * 1. The user's interactive login shell's PATH (`$SHELL -ilc`), where nvm,
+ * volta and `~/.local/bin` are usually set up from `.bashrc` / `.zshrc`.
+ * Only its PATH is taken, under a timeout: an rc file that waits on input,
+ * `exec`s another shell or attaches tmux must not cost the other steps.
+ * 2. A plain login shell's PATH (`sh -l`, `~/.profile`), for when step 1
+ * failed or the user's shell is one this can't drive.
+ * 3. The folders installers put CLIs in whatever PATH says (`dirs` below) —
+ * every nvm / fnm / mise Node, bun, pnpm, Volta, npm's prefix — for a
+ * `.bashrc` that only adds them inside a guard a non-terminal shell skips.
+ *
+ * Anything on a Windows drive is skipped: WSL appends Windows' PATH to its
+ * own, so `command -v codex` there can answer `/mnt/c/…/npm/codex`, Windows'
+ * npm shim, which doesn't run inside Linux. Results are marked lines, as a
+ * shell's rc files may print anything.
*/
-const PROBE_SCRIPT = `lobehub_shell="\${SHELL:-/bin/sh}"
-case "\${lobehub_shell##*/}" in bash|zsh|ksh|sh|dash) ;; *) lobehub_shell=/bin/sh ;; esac
-"$lobehub_shell" -ilc 'printf "\\n${PATH_MARKER}%s\\n" "$PATH"; for c in "$@"; do p=$(command -v "$c" 2>/dev/null) || continue; case "$p" in /*) printf "${COMMAND_MARKER}%s=%s\\n" "$c" "$p" ;; esac; done' lobehub "$@" </dev/null
+export const WSL_PROBE_SCRIPT = `lh_c='${COMMAND_MARKER}'
+lh_to=; command -v timeout >/dev/null 2>&1 && lh_to=timeout
+lh_run() { lh_s=$1; shift; if [ -n "$lh_to" ]; then timeout "$lh_s" "$@"; else "$@"; fi; }
+lh_shell="\${SHELL:-/bin/sh}"
+case "\${lh_shell##*/}" in
+ bash|zsh|ksh|sh|dash) lh_ip=$(lh_run ${WSL_INTERACTIVE_SHELL_TIMEOUT_S} "$lh_shell" -ilc 'printf "\\n${SHELL_PATH_MARKER}%s\\n" "$PATH"' </dev/null 2>/dev/null) ;;
+ fish) lh_ip=$(lh_run ${WSL_INTERACTIVE_SHELL_TIMEOUT_S} "$lh_shell" -ilc 'printf "\\n${SHELL_PATH_MARKER}%s\\n" (string join : $PATH)' </dev/null 2>/dev/null) ;;
+ *) lh_ip= ;;
+esac
+lh_ip=$(printf '%s\\n' "$lh_ip" | sed -n 's/^${SHELL_PATH_MARKER}//p' | tail -n 1)
+lh_lp=$(lh_run ${WSL_LOGIN_SHELL_TIMEOUT_S} sh -lc 'printf "\\n${SHELL_PATH_MARKER}%s\\n" "$PATH"' </dev/null 2>/dev/null | sed -n 's/^${SHELL_PATH_MARKER}//p' | tail -n 1)
+printf '\\n${PATH_MARKER}%s\\n' "\${lh_ip:-$lh_lp}"
+lh_wm=$(awk '$1 ~ /^[A-Za-z]:/ {print $2}' /proc/mounts 2>/dev/null)
+lh_win() { case "$1" in /mnt/[A-Za-z]/*) return 0 ;; esac; for lh_m in $lh_wm; do case "$1" in "$lh_m"/*) return 0 ;; esac; done; return 1; }
+lh_emit() { case "$2" in /*) ;; *) return 0 ;; esac; lh_win "$2" && return 0; [ -f "$2" ] && [ -x "$2" ] && printf '%s%s=%s\\n' "$lh_c" "$1" "$2"; return 0; }
+lh_vs() { ls "$1" 2>/dev/null | sed 's/^v*\\([0-9][0-9.]*\\).*$/\\1 &/;t;d' | sort -t. -k1,1nr -k2,2nr -k3,3nr | cut -d' ' -f2; }
+lh_dirs() {
+ echo "$HOME/.local/bin"
+ lh_np=$(sed -n 's/^[[:space:]]*prefix[[:space:]]*=[[:space:]]*//p' "$HOME/.npmrc" 2>/dev/null | head -n 1 | tr -d "\\"'\\r")
+ case "$lh_np" in "~/"*) echo "$HOME/\${lh_np#??}/bin" ;; /*) echo "$lh_np/bin" ;; esac
+ echo "$HOME/.npm-global/bin"; echo "$HOME/.bun/bin"; echo "$HOME/.local/share/pnpm"; echo "$HOME/.volta/bin"
+ lh_nv="\${NVM_DIR:-$HOME/.nvm}"
+ lh_nd=$(head -n 1 "$lh_nv/alias/default" 2>/dev/null); lh_nd=\${lh_nd#v}
+ case "$lh_nd" in [0-9]*) for lh_v in $(lh_vs "$lh_nv/versions/node"); do case "\${lh_v#v}" in "$lh_nd"|"$lh_nd".*) echo "$lh_nv/versions/node/$lh_v/bin" ;; esac; done ;; esac
+ for lh_v in $(lh_vs "$lh_nv/versions/node"); do echo "$lh_nv/versions/node/$lh_v/bin"; done
+ for lh_r in "$HOME/.local/share/fnm" "$HOME/.fnm"; do [ -d "$lh_r/node-versions" ] || continue; echo "$lh_r/aliases/default/bin"; for lh_v in $(lh_vs "$lh_r/node-versions"); do echo "$lh_r/node-versions/$lh_v/installation/bin"; done; done
+ echo "$HOME/.local/share/mise/shims"
+ for lh_v in $(lh_vs "$HOME/.local/share/mise/installs/node"); do echo "$HOME/.local/share/mise/installs/node/$lh_v/bin"; done
+ echo "$HOME/.asdf/shims"; echo "$HOME/.cargo/bin"; echo "$HOME/.deno/bin"
+ echo /home/linuxbrew/.linuxbrew/bin; echo "$HOME/.linuxbrew/bin"; echo /usr/local/bin; echo /snap/bin
+ for lh_a in .opencode .amp .kimi-code .grok; do echo "$HOME/$lh_a/bin"; done
+}
+lh_ds=$(lh_dirs)
+for lh_name in "$@"; do
+ for lh_p in "$lh_ip" "$lh_lp" "$PATH"; do
+ lh_o=$IFS; IFS=:
+ for lh_d in $lh_p; do IFS=$lh_o; lh_emit "$lh_name" "$lh_d/$lh_name"; done
+ IFS=$lh_o
+ done
+ lh_o=$IFS; IFS='
+'
+ for lh_d in $lh_ds; do IFS=$lh_o; lh_emit "$lh_name" "$lh_d/$lh_name"; done
+ IFS=$lh_o
+done
`;
interface WslRunOptions {
@@ -260,12 +341,17 @@ export const parseWslDistroList = (output: string): string[] =>
.filter((name) => name && !/^docker-desktop/i.test(name));
export interface WslDistroProbe {
- commands: Map<string, string>;
+ /** Each command's locations inside the distro, best first. */
+ commands: Map<string, string[]>;
pathEnv?: string;
}
+// The probe filters these too; this keeps a hand-run probe (or an older one)
+// from handing Windows' own npm shim to a Linux launch.
+const isOnWindowsDrive = (linuxPath: string): boolean => /^\/mnt\/[a-z]\//i.test(linuxPath);
+
export const parseWslProbeOutput = (output: string): WslDistroProbe => {
- const commands = new Map<string, string>();
+ const commands = new Map<string, string[]>();
let pathEnv: string | undefined;
for (const rawLine of output.split(/\r?\n/)) {
@@ -277,7 +363,10 @@ export const parseWslProbeOutput = (output: string): WslDistroProbe => {
const separator = entry.indexOf('=');
const name = entry.slice(0, separator);
const linuxPath = entry.slice(separator + 1);
- if (separator > 0 && linuxPath.startsWith('/')) commands.set(name, linuxPath);
+ if (separator <= 0 || !linuxPath.startsWith('/') || isOnWindowsDrive(linuxPath)) continue;
+ const found = commands.get(name) ?? [];
+ if (!found.includes(linuxPath)) found.push(linuxPath);
+ commands.set(name, found);
}
}
@@ -291,8 +380,13 @@ const settledPathEnv = new Map<string, string | undefined>();
const listWslDistros = (): Promise<string[]> => {
distrosPromise ??= runWsl(['--list', '--quiet'], { timeout: WSL_LIST_TIMEOUT_MS })
.then((output) => parseWslDistroList(decodeWslOutput(output)))
- // No WSL, or WSL without a distro: nothing to find.
- .catch(() => []);
+ .catch(() => {
+ // No WSL, WSL without a distro, or a WSL service still starting after a
+ // reboot: nothing to find this time. Not kept, so the next scan asks
+ // again instead of reporting "no distros" until the app restarts.
+ distrosPromise = undefined;
+ return [];
+ });
return distrosPromise;
};
@@ -300,7 +394,7 @@ const probeWslDistro = (distro: string): Promise<WslDistroProbe | undefined> =>
let probe = distroProbes.get(distro);
if (!probe) {
probe = runWsl(['--distribution', distro, '--exec', 'sh', '-s', '--', ...WSL_PROBED_COMMANDS], {
- input: PROBE_SCRIPT,
+ input: WSL_PROBE_SCRIPT,
timeout: WSL_PROBE_TIMEOUT_MS,
})
.then((output) => {
@@ -326,8 +420,9 @@ export const invalidateWslCache = (): void => {
};
/**
- * The `wsl://` locations of `command` in every distro whose login shell
- * resolves it, in the order `wsl.exe --list` gives (the default distro first).
+ * Every `wsl://` location of `command`: each distro in the order
+ * `wsl.exe --list` gives (the default distro first), and within a distro the
+ * probe's order (shell PATH first, then install folders).
* Empty off Windows.
*/
export const findWslCommandCandidates = async (command: string): Promise<string[]> => {
@@ -336,10 +431,11 @@ export const findWslCommandCandidates = async (command: string): Promise<string[
const distros = await listWslDistros();
const probes = await Promise.all(distros.map((distro) => probeWslDistro(distro)));
- return distros.flatMap((distro, index) => {
- const linuxPath = probes[index]?.commands.get(command);
- return linuxPath ? [formatWslCommand({ distro, linuxPath })] : [];
- });
+ return distros.flatMap((distro, index) =>
+ (probes[index]?.commands.get(command) ?? []).map((linuxPath) =>
+ formatWslCommand({ distro, linuxPath }),
+ ),
+ );
};
/** The login-shell PATH of `distro`, probing it if this process hasn't yet. */