🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(hetero-agents): find and run agents installed in WSL; Windows install paths for Cursor and dsh (#23670)
Lobehub Codere57ac79e1f3b
diff --git a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.tsindex 5e651a5bb34..ac163a5fd3e 100644--- a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts+++ b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts@@ -384,7 +384,7 @@ export class CodexAppServerClient {const child = spawnManaged(spawnPlan.command, spawnPlan.args, {cwd: this.options.cwd,detached: process.platform !== 'win32',- env: this.options.env,+ env: spawnPlan.env ?? this.options.env,stdio: ['pipe', 'pipe', 'pipe'],});const processGeneration = { child, generation, stdoutBuffer: '' };diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.tsindex 97bdd0cd635..1d496e7478a 100644--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts@@ -455,7 +455,7 @@ export const listHeterogeneousAgentModels = async (const { stderr, stdout } = await execFilePromise(spawnPlan.command, spawnPlan.args, {cwd,encoding: 'utf8',- env: env as NodeJS.ProcessEnv,+ env: spawnPlan.env ?? (env as NodeJS.ProcessEnv),maxBuffer: MODEL_CATALOG_MAX_BUFFER,timeout: MODEL_CATALOG_TIMEOUT_MS,windowsHide: true,diff --git a/packages/heterogeneous-agents/src/quota-sampler/antigravityQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/antigravityQuota.tsindex b8696107805..f00a928c2c6 100644--- a/packages/heterogeneous-agents/src/quota-sampler/antigravityQuota.ts+++ b/packages/heterogeneous-agents/src/quota-sampler/antigravityQuota.ts@@ -91,7 +91,7 @@ export const fetchAntigravityQuota = async (const query = execFilePromise(plan.command, plan.args, {cwd: tmpdir(),encoding: 'utf8',- env,+ env: plan.env ?? env,killSignal: 'SIGKILL',maxBuffer: 1024 * 1024,timeout: 20_000,diff --git a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.tsindex 894a444959d..09259e3fb73 100644--- a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts+++ b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts@@ -533,16 +533,17 @@ const requestViaRpc = async <T>(settleError(new Error(`${failureMessage}: RPC timed out`), true);}, timeoutMs);- void resolveCliSpawnPlan(options.command ?? 'codex', rpcArgs)+ const childEnv: NodeJS.ProcessEnv = {+ ...process.env,+ ...options.env,+ ...(options.codexHomePath ? { CODEX_HOME: options.codexHomePath } : {}),+ };+ void resolveCliSpawnPlan(options.command ?? 'codex', rpcArgs, childEnv).then((spawnPlan) => {if (finished) return;child = spawn(spawnPlan.command, spawnPlan.args, {- env: {- ...process.env,- ...options.env,- ...(options.codexHomePath ? { CODEX_HOME: options.codexHomePath } : {}),- },+ env: spawnPlan.env ?? childEnv,stdio: ['pipe', 'pipe', 'pipe'],windowsHide: true,});diff --git a/packages/heterogeneous-agents/src/rpc/piRpcClient.ts b/packages/heterogeneous-agents/src/rpc/piRpcClient.tsindex 4a7ffbd42bd..c838908e769 100644--- a/packages/heterogeneous-agents/src/rpc/piRpcClient.ts+++ b/packages/heterogeneous-agents/src/rpc/piRpcClient.ts@@ -220,7 +220,7 @@ export class PiRpcClient {plan.args,{cwd: this.options.cwd,- env: this.options.env,+ env: plan.env ?? this.options.env,killSignal: 'SIGKILL',signal: this.probeAbort.signal,timeout: 5000,diff --git a/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts b/packages/heterogeneous-agents/src/rpc/rpcStdioClient.tsindex 60582cba2a0..b03fc6b0528 100644--- a/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts+++ b/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts@@ -126,7 +126,7 @@ export class RpcStdioClient {const child = spawnManaged(spawnPlan.command, spawnPlan.args, {cwd: this.options.cwd,detached: process.platform !== 'win32' && (this.options.detached ?? true),- env: this.options.env,+ env: spawnPlan.env ?? this.options.env,stdio: ['pipe', 'pipe', 'pipe'],});this.child = child;diff --git a/packages/heterogeneous-agents/src/scan/scanHost.ts b/packages/heterogeneous-agents/src/scan/scanHost.tsindex 03b2577c314..e16a9878922 100644--- a/packages/heterogeneous-agents/src/scan/scanHost.ts+++ b/packages/heterogeneous-agents/src/scan/scanHost.ts@@ -161,10 +161,10 @@ export const resolveRemotePlatformRuntime = async (const validatedPath = status.path;const env = buildRemotePlatformEnvironment(status, baseEnv);- const prepareSpawn = async (args: string[]): Promise<RemotePlatformSpawnPlan> => ({- ...(await resolveCliSpawnPlan(validatedPath, args, env)),- env,- });+ const prepareSpawn = async (args: string[]): Promise<RemotePlatformSpawnPlan> => {+ const plan = await resolveCliSpawnPlan(validatedPath, args, env);+ return { ...plan, env: plan.env ?? env };+ };return {available: true,diff --git a/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts b/packages/heterogeneous-agents/src/spawn/acpStdioClient.tsindex 7a5a5103231..aefe1d233da 100644--- a/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts+++ b/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts@@ -112,7 +112,7 @@ export class AcpStdioClient {const child = spawnManaged(spawnPlan.command, spawnPlan.args, {cwd: this.options.cwd,detached,- env: this.options.env,+ env: spawnPlan.env ?? this.options.env,stdio: ['pipe', 'pipe', 'pipe'],});this.child = child;diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex 3358832f112..63105d4c39b 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -26,6 +26,7 @@ import {import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';import { readClaudeCodeSessionCost } from './claudeCodeSessionCost';import { resolveCliSpawnPlan } from './cliSpawn';+import { buildWslSpawnPlan, getSettledWslPathEnv, getWslPathEnv, parseWslCommand } from './wsl';const CLAUDE_SDK_DISALLOWED_TOOLS = ['AskUserQuestion', 'Monitor', 'ScheduleWakeup'] as const;const DEFAULT_INACTIVITY_TIMEOUT_MS = 5 * 60 * 1000;@@ -51,6 +52,14 @@ export const resolveClaudeSdkExecutablePath = async (env: NodeJS.ProcessEnv,platform: NodeJS.Platform = process.platform,): Promise<string> => {+ // A WSL command reaches the SDK verbatim (it has no `.js` extension, so the SDK+ // hands it to `spawnClaudeCodeCliProcess` as the command). Learn the distro's+ // PATH now, while still async, for that synchronous spawn hook.+ const wslCommand = parseWslCommand(commandPath);+ if (wslCommand) {+ await getWslPathEnv(wslCommand.distro);+ return commandPath;+ }if (platform !== 'win32' || !/\.(?:bat|cmd)$/i.test(commandPath)) return commandPath;// The Agent SDK spawns native paths directly and runs JavaScript paths with@@ -235,12 +244,17 @@ export const spawnClaudeCodeCliProcess = (},platform: NodeJS.Platform = process.platform,): SdkSpawnedProcess => {- const child: ChildProcess = spawnManaged(options.command, options.args, {+ // The SDK types env as a plain string map; this repo augments ProcessEnv+ // with required keys, which no spawn caller carries.+ const sdkEnv = options.env as NodeJS.ProcessEnv;+ const wslCommand = parseWslCommand(options.command);+ const plan = wslCommand+ ? buildWslSpawnPlan(wslCommand, options.args, sdkEnv, getSettledWslPathEnv(wslCommand.distro))+ : { args: options.args, command: options.command, env: sdkEnv };+ const child: ChildProcess = spawnManaged(plan.command, plan.args, {cwd: options.cwd,detached: platform !== 'win32',- // The SDK types env as a plain string map; this repo augments ProcessEnv- // with required keys, which no spawn caller carries.- env: options.env as NodeJS.ProcessEnv,+ env: plan.env ?? sdkEnv,signal: options.signal,stdio: ['pipe', 'pipe', 'pipe'],windowsHide: true,@@ -251,8 +265,8 @@ export const spawnClaudeCodeCliProcess = (child.stderr?.on('data', (chunk: Buffer | string) => hooks.onStderr(chunk.toString()));hooks.onProcessSpawn?.({- args: [options.command, ...options.args],- command: options.command,+ args: [plan.command, ...plan.args],+ command: plan.command,pid: child.pid,});diff --git a/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts b/packages/heterogeneous-agents/src/spawn/cliSpawn.test.tsindex 1a8f2f87e7f..19474e080c1 100644--- a/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts+++ b/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts@@ -160,6 +160,47 @@ describe('cliSpawn', () => {expect(execFileMock).not.toHaveBeenCalled();});+ it("runs Cursor's agent.cmd launcher as its PowerShell script, without cmd.exe", async () => {+ platformMock.mockReturnValue('win32');+ vi.stubEnv('SystemRoot', 'C:\\Windows');+ const shimPath = 'C:\\Users\\Hanam\\AppData\\Local\\cursor-agent\\agent.cmd';+ const scriptPath = 'C:\\Users\\Hanam\\AppData\\Local\\cursor-agent\\agent.ps1';+ existingPaths(shimPath, scriptPath);+ readFileMock.mockResolvedValue(+ '@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0agent.ps1" %*\r\n',+ );++ const { resolveCliSpawnPlan } = await import('./cliSpawn');+ await expect(resolveCliSpawnPlan(shimPath, ['acp'])).resolves.toEqual({+ args: [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-ExecutionPolicy',+ 'Bypass',+ '-File',+ scriptPath,+ 'acp',+ ],+ command: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',+ });+ expect(execFileMock).not.toHaveBeenCalled();+ vi.unstubAllEnvs();+ });++ it('leaves a PowerShell launcher alone when its script is missing', async () => {+ platformMock.mockReturnValue('win32');+ const shimPath = 'C:\\Users\\Hanam\\AppData\\Local\\cursor-agent\\agent.cmd';+ existingPaths(shimPath);+ readFileMock.mockResolvedValue('@echo off\r\npowershell -File "%~dp0agent.ps1" %*\r\n');++ const { resolveCliSpawnPlan } = await import('./cliSpawn');+ await expect(resolveCliSpawnPlan(shimPath, ['acp'])).resolves.toEqual({+ args: ['acp'],+ command: shimPath,+ });+ });+it('resolves a .cmd npm shim that invokes node.exe plus a JS bin', async () => {platformMock.mockReturnValue('win32');const shimPath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\gemini.cmd';diff --git a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts b/packages/heterogeneous-agents/src/spawn/cliSpawn.tsindex 427c2fd4fa6..2d5ea97bf74 100644--- a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts+++ b/packages/heterogeneous-agents/src/spawn/cliSpawn.ts@@ -3,6 +3,8 @@ import { access, readFile } from 'node:fs/promises';import { platform } from 'node:os';import path from 'node:path';+import { buildWslSpawnPlan, getWslPathEnv, parseWslCommand } from './wsl';+const WINDOWS_EXE_EXT_PATTERN = /\.exe$/i;// `CreateProcess` limit, which is what this plan is spawned through: the plan// always names a real executable (an `.exe`, or `node.exe` plus the script a@@ -17,6 +19,12 @@ const WINDOWS_NODE_EXE_PATTERN = /(?:^|[\\/])node(?:\.exe)?$/i;export interface CliSpawnPlan {args: string[];command: string;+ /**+ * The environment to spawn with, when the plan needs a different one from the+ * env it was given (a WSL launch forwards the agent's variables via `WSLENV`).+ * Spawn sites pass `plan.env ?? env`.+ */+ env?: NodeJS.ProcessEnv;}interface WindowsShimTarget {@@ -238,6 +246,48 @@ const inferWindowsExecutableFromShim = async (}};+/**+ * A `.cmd` that only hands off to a PowerShell script (Cursor's Windows+ * `agent.cmd` runs `powershell … -File "%~dp0….ps1" %*`). Run the script with+ * `powershell.exe -File` directly: still no cmd.exe, and `-File` binds every+ * following argument as a literal string, never as PowerShell code.+ */+const inferWindowsPowerShellShimTarget = async (+ shimPath: string,+ source: string,+ env?: NodeJS.ProcessEnv,+): Promise<WindowsShimTarget | undefined> => {+ const match = source.match(+ /\b(powershell|pwsh)(?:\.exe)?\b[^\r\n]*?-File\s+"?(%(?:~dp0|dp0%))?\\?([^"\r\n]+?\.ps1)"?/i,+ );+ if (!match) return;++ const [, host, relativeToShim, scriptToken] = match;+ const script = relativeToShim+ ? joinShimRelativePath(shimPath, scriptToken!)+ : scriptToken!.replaceAll('/', '\\');+ if (!path.win32.isAbsolute(script) || !(await fileExists(script))) return;++ const systemRoot = env?.SystemRoot || process.env.SystemRoot || 'C:\\Windows';+ const command =+ host!.toLowerCase() === 'pwsh'+ ? 'pwsh.exe'+ : path.win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');++ return {+ argsPrefix: [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-ExecutionPolicy',+ 'Bypass',+ '-File',+ script,+ ],+ command,+ };+};+const inferWindowsNpmShimTarget = async (shimPath: string,env?: NodeJS.ProcessEnv,@@ -249,7 +299,8 @@ const inferWindowsNpmShimTarget = async (const source = await readFile(shimPath, 'utf8');return ((await inferWindowsNodeScriptFromShim(shimPath, source, env)) ??- (await inferWindowsExecutableFromShim(shimPath, source))+ (await inferWindowsExecutableFromShim(shimPath, source)) ??+ (await inferWindowsPowerShellShimTarget(shimPath, source, env)));} catch {return;@@ -294,6 +345,20 @@ export const resolveCliSpawnPlan = async (env?: NodeJS.ProcessEnv,): Promise<CliSpawnPlan> => {const trimmedCommand = command.trim();++ const wslCommand = parseWslCommand(trimmedCommand);+ if (wslCommand) {+ if (!isWindows()) throw new Error(`A WSL command only runs on Windows: ${trimmedCommand}`);+ const wslPlan = buildWslSpawnPlan(+ wslCommand,+ args,+ env,+ await getWslPathEnv(wslCommand.distro),+ );+ assertWindowsCommandLineFits(wslPlan);+ return wslPlan;+ }+if (!isWindows() || !trimmedCommand) return { args, command };const target = isPathLikeCommand(trimmedCommand)diff --git a/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.ts b/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.tsindex 1c13bad45db..afb37935baa 100644--- a/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.ts+++ b/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.ts@@ -4,7 +4,11 @@ import { DSH_MIN_VERSION, resolveDshSpawnCommand } from './dshAcpSession';const { detectValidatedCommand } = vi.hoisted(() => ({ detectValidatedCommand: vi.fn() }));-vi.mock('./resolveCliCommand', () => ({ detectValidatedCommand }));+// The WSL fallback only runs on Windows; here it hands the native result back.+vi.mock('./resolveCliCommand', () => ({+ detectInWslWhenMissing: async (status: unknown) => status,+ detectValidatedCommandCandidates: detectValidatedCommand,+}));describe('resolveDshSpawnCommand', () => {beforeEach(() => detectValidatedCommand.mockReset());@@ -24,7 +28,7 @@ describe('resolveDshSpawnCommand', () => {pathEnv: 'C:\\Users\\x\\AppData\\Roaming\\npm;C:\\Windows',version: DSH_MIN_VERSION,});- expect(detectValidatedCommand).toHaveBeenCalledWith('dsh', expect.any(Object), env);+ expect(detectValidatedCommand).toHaveBeenCalledWith(['dsh'], expect.any(Object), env);});it('falls back to the bare command when detection fails or finds an old CLI', async () => {diff --git a/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts b/packages/heterogeneous-agents/src/spawn/dshAcpSession.tsindex 7f334f80559..cf34d7aa0fe 100644--- a/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts+++ b/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts@@ -1,3 +1,6 @@+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';@@ -12,7 +15,7 @@ import {import type { AcpRpcMessage } from './acpStdioClient';import { AcpServerRequestError } from './acpStdioClient';import type { CliCommandStatus, ResolvedHeteroCommand } from './resolveCliCommand';-import { detectValidatedCommand } from './resolveCliCommand';+import { detectInWslWhenMissing, detectValidatedCommandCandidates } from './resolveCliCommand';/*** DeepSeek Harness over the Agent Client Protocol.@@ -52,15 +55,36 @@ const isSupportedDshVersion = (version: string | undefined): boolean => {* `--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`. 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 status = await detectValidatedCommand(- command,- { validatePattern: DSH_VERSION_PATTERN },+ const isDefaultCommand = command.trim() === DSH_COMMAND;+ const validation = { validatePattern: DSH_VERSION_PATTERN };+ const nativeStatus = await detectValidatedCommandCandidates(+ isDefaultCommand ? [command, ...getDshWellKnownPaths()] : [command],+ validation,env,);+ const status = isDefaultCommand+ ? await detectInWslWhenMissing(nativeStatus, [DSH_COMMAND], validation)+ : nativeStatus;if (!status.available || isSupportedDshVersion(status.version)) return status;return {...status,diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex 1fd68becd31..d5d19fa1bd4 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 { findWslCommandCandidates, invalidateWslCache, isWslCommand } from './wsl';/*** Shared resolver for external CLI-agent binaries.@@ -224,6 +225,8 @@ const getCurrentLoginShellPath = async (): Promise<string | undefined> => {* fresh scan.*/export const invalidateLoginShellPathCache = (): void => {+ // A Rescan must also see agents installed inside WSL since the last scan.+ invalidateWslCache();cachedShellPath = undefined;shellPathGeneration += 1;shellPathPromise = undefined;@@ -480,7 +483,7 @@ const execProbe = async (}return execFilePromise(spawnPlan.command, spawnPlan.args, {- env,+ env: spawnPlan.env ?? env,timeout: 5000,windowsHide: true,});@@ -649,8 +652,9 @@ export const detectValidatedCommandCandidates = async (lastStatus = inheritedStatus;// Invalid Windows shell expressions must not trigger even the registry- // helper processes used for PATH recovery.- if (!isProbeableCommand(command)) continue;+ // helper processes used for PATH recovery. A WSL command runs on the WSL+ // side's own PATH, so a recovered Windows PATH can't help it either.+ if (!isProbeableCommand(command) || isWslCommand(command)) continue;if (!recoveryAttempted) {recoveryAttempted = true;@@ -861,6 +865,15 @@ const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[];}case 'cursor': {+ // Cursor's Windows installer (`irm 'https://cursor.com/install?win32=true' | iex`)+ // puts its `agent.cmd` launcher in `%LOCALAPPDATA%\cursor-agent` and only adds+ // that to the registry User PATH, which an already-running app never sees.+ if (platform() === 'win32') {+ const localAppData = process.env.LOCALAPPDATA;+ if (!localAppData) return [];++ return [path.win32.join(localAppData, 'cursor-agent', 'agent.cmd')];+ }if (platform() !== 'darwin' && platform() !== 'linux') return [];return [path.join(homedir(), '.local', 'bin', 'agent'),@@ -972,12 +985,39 @@ export const detectHeterogeneousCliCommand = async (// default command: the well-known paths hold the *default* binary, so applying// 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 commands =- command.trim() === DEFAULT_HETERO_COMMAND[agentType]- ? [command, ...getWellKnownCommandPaths(agentType)]- : [command];+ const isDefaultCommand = command.trim() === DEFAULT_HETERO_COMMAND[agentType];+ const commands = isDefaultCommand ? [command, ...getWellKnownCommandPaths(agentType)] : [command];++ const status = await detectValidatedCommandCandidates(commands, validator, probeEnv);+ if (!isDefaultCommand) return status;++ return detectInWslWhenMissing(status, WSL_COMMAND_NAMES[agentType] ?? [command], validator);+};++// Cursor's installer creates `agent` and the unambiguous `cursor-agent` alias.+const WSL_COMMAND_NAMES: Partial<Record<HeterogeneousCliAgentType, string[]>> = {+ cursor: ['agent', 'cursor-agent'],+};++/**+ * When nothing on the Windows side answers, look for the command inside WSL.+ * Only then: probing a distro may boot its VM, which a user whose agents are+ * all on Windows should never pay for. A hit is a `wsl://` command that+ * `resolveCliSpawnPlan` launches through `wsl.exe`. No-op off Windows.+ */+export const detectInWslWhenMissing = async (+ status: CliCommandStatus,+ commandNames: string[],+ options: ValidateOptions,+): Promise<CliCommandStatus> => {+ if (status.available || !isWindows()) return status;++ const candidates: string[] = [];+ for (const name of commandNames) candidates.push(...(await findWslCommandCandidates(name)));+ if (candidates.length === 0) return status;- return detectValidatedCommandCandidates(commands, validator, probeEnv);+ const wslStatus = await detectValidatedCommandCandidates(candidates, options);+ return wslStatus.available ? wslStatus : status;};/**diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.windowsFallbacks.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.windowsFallbacks.test.tsnew file mode 100644index 00000000000..68d205cc810--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.windowsFallbacks.test.ts@@ -0,0 +1,138 @@+import * as childProcess from 'node:child_process';+import * as fsPromises from 'node:fs/promises';+import type * as os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// Installers that leave a CLI off the running app's PATH, and the WSL fallback+// that must stay out of the way when Windows already has the agent. Mocks+// precede the module import because it captures `promisify(execFile)`.+vi.mock('node:os', async () => {+ const actual = await vi.importActual<typeof os>('node:os');+ return { ...actual, platform: vi.fn(() => 'win32') };+});+vi.mock('node:child_process', () => ({ exec: vi.fn(), execFile: vi.fn(), spawn: vi.fn() }));+vi.mock('node:fs/promises', async () => {+ const actual = await vi.importActual<typeof fsPromises>('node:fs/promises');+ return { ...actual, access: vi.fn(), readFile: vi.fn() };+});++const execFileMock = vi.mocked(childProcess.execFile);+const spawnMock = vi.mocked(childProcess.spawn);+const accessMock = vi.mocked(fsPromises.access);+const readFileMock = vi.mocked(fsPromises.readFile);++/**+ * Answer execFile by program name; anything unanswered fails like a missing binary.+ * The promisified callers read `{ stdout }`, the callback callers stringify it.+ */+const answerExecFile = (answer: (file: string, args: string[]) => string | undefined) => {+ execFileMock.mockImplementation(((file: string, args: any, opts: any, cb: any) => {+ const callback = typeof opts === 'function' ? opts : cb;+ const stdout = answer(file, args);+ if (stdout === undefined) callback(new Error(`not found: ${file}`), { stderr: '', stdout: '' });+ else callback(null, { stderr: '', stdout, toString: () => stdout });+ return {} as any;+ }) as any);+};++const existingPaths = (...paths: string[]) => {+ const known = new Set(paths.map((filePath) => filePath.toLowerCase()));+ accessMock.mockImplementation(async (filePath) => {+ if (!known.has(String(filePath).toLowerCase())) throw new Error('missing');+ });+};++const importModule = () => import('./resolveCliCommand');++describe('Windows install locations off PATH', () => {+ const localAppData = 'C:\\Users\\me\\AppData\\Local';+ const appData = 'C:\\Users\\me\\AppData\\Roaming';++ beforeEach(async () => {+ (await importModule()).invalidateLoginShellPathCache();+ execFileMock.mockReset();+ spawnMock.mockReset();+ readFileMock.mockReset();+ vi.stubEnv('PATH', 'C:\\Windows');+ vi.stubEnv('LOCALAPPDATA', localAppData);+ vi.stubEnv('APPDATA', appData);+ vi.stubEnv('SystemRoot', 'C:\\Windows');+ // No WSL on this machine: wsl.exe can't be started.+ spawnMock.mockImplementation(() => {+ throw new Error('spawn wsl.exe ENOENT');+ });+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ vi.resetModules();+ });++ it("finds Cursor's launcher in %LOCALAPPDATA%\\cursor-agent and validates it via PowerShell", async () => {+ const launcher = path.win32.join(localAppData, 'cursor-agent', 'agent.cmd');+ const script = path.win32.join(localAppData, 'cursor-agent', 'agent.ps1');+ existingPaths(launcher, script);+ readFileMock.mockResolvedValue(+ '@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0agent.ps1" %*\r\n',+ );+ answerExecFile((file, args) =>+ file.endsWith('powershell.exe') && args.includes(script) && args.at(-1) === '--help'+ ? 'Usage: agent [options] [command] [prompt...]\n\nStart the Cursor Agent'+ : undefined,+ );++ const { detectHeterogeneousCliCommand } = await importModule();++ await expect(detectHeterogeneousCliCommand('cursor', 'agent')).resolves.toMatchObject({+ available: true,+ path: launcher,+ });+ });++ it('finds a global npm install of the DeepSeek Harness CLI', async () => {+ const shim = path.win32.join(appData, 'npm', 'dsh.cmd');+ const entry = path.win32.join(+ appData,+ 'npm',+ 'node_modules',+ '@deepseek-ai',+ 'dsh',+ 'bin',+ 'dsh.js',+ );+ const nodeExe = 'C:\\Program Files\\nodejs\\node.exe';+ existingPaths(shim, entry, nodeExe);+ readFileMock.mockResolvedValue(+ '@ECHO off\r\n"%_prog%" "%dp0%\\node_modules\\@deepseek-ai\\dsh\\bin\\dsh.js" %*\r\n',+ );+ answerExecFile((file, args) => {+ if (file === 'where' && args[0] === 'node') return `${nodeExe}\r\n`;+ if (file === nodeExe && args.at(-1) === '--version') return '0.9.0\n';+ return undefined;+ });++ const { detectDshCommand } = await import('./dshAcpSession');++ await expect(detectDshCommand()).resolves.toMatchObject({ available: true, path: shim });+ });++ it('does not wake WSL when Windows already has the agent', async () => {+ const codex = 'C:\\tools\\codex.exe';+ existingPaths(codex);+ answerExecFile((file, args) => {+ if (file === 'where' && args[0] === 'codex') return `${codex}\r\n`;+ if (file === codex) return 'codex-cli 0.50.0';+ return undefined;+ });++ const { detectHeterogeneousCliCommand } = await importModule();++ await expect(detectHeterogeneousCliCommand('codex', 'codex')).resolves.toMatchObject({+ available: true,+ path: codex,+ });+ expect(spawnMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 723e35d9838..f65687f091f 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -613,7 +613,7 @@ const spawnCliAgent = async (const proc = spawnManaged(cliSpawnPlan.command, cliSpawnPlan.args, {cwd,detached,- env: childEnv,+ env: cliSpawnPlan.env ?? childEnv,stdio: ['pipe', 'pipe', 'pipe'],});diff --git a/packages/heterogeneous-agents/src/spawn/wsl.integration.test.ts b/packages/heterogeneous-agents/src/spawn/wsl.integration.test.tsnew file mode 100644index 00000000000..ce7dd1ffccf--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/wsl.integration.test.ts@@ -0,0 +1,110 @@+import { execFile } from 'node:child_process';+import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import * as os from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';++import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveCliSpawnPlan } from './cliSpawn';+import { detectDshCommand } from './dshAcpSession';+import { detectHeterogeneousCliCommand, invalidateLoginShellPathCache } from './resolveCliCommand';++// The whole Windows → WSL chain, run for real on a POSIX host: detection asks a+// stand-in `wsl.exe` (which execs inside this machine instead of a distro), the+// probe script runs in a real login shell, validation and launch go through the+// real spawn plan. Only `platform()` is faked.+vi.mock('node:os', async () => {+ const actual = await vi.importActual<typeof os>('node:os');+ return { ...actual, platform: vi.fn(() => 'win32') };+});++const execFileAsync = promisify(execFile);+const isPosix = process.platform !== 'win32';++let root: string;+const wslExe = () => `${root}\\System32\\wsl.exe`;++const writeExecutable = async (file: string, source: string) => {+ await mkdir(path.posix.dirname(file), { recursive: true });+ await writeFile(file, source);+ await chmod(file, 0o755);+};++beforeAll(async () => {+ if (!isPosix) return;+ root = await mkdtemp(path.join(os.tmpdir(), 'lobehub-wsl-'));++ // `wsl.exe --list --quiet` and `wsl.exe --distribution <d> --exec <cmd> …`, at+ // `${SystemRoot}\\System32\\wsl.exe` — on this POSIX host, one file next to `root`.+ await writeExecutable(+ wslExe(),+ `#!/bin/sh+if [ "$1" = "--list" ]; then printf 'FakeLinux\\n'; exit 0; fi+[ "$1" = "--distribution" ] && [ "$2" = "FakeLinux" ] || exit 2+shift 2+[ "$1" = "--exec" ] || exit 2+shift+exec "$@"+`,+ );+ await writeExecutable(+ path.join(root, 'linux-bin', 'agent'),+ `#!/bin/sh+case "$1" in+ --help) printf 'Usage: agent [options] [command] [prompt...]\\n\\nStart the Cursor Agent\\n' ;;+ *) printf 'cursor-run:%s\\n' "$*" ;;+esac+`,+ );+ await writeExecutable(path.join(root, 'linux-bin', 'dsh'), "#!/bin/sh\nprintf '0.9.0\\n'\n");+});++afterAll(async () => {+ if (!root) return;+ await rm(root, { force: true, recursive: true });+ await rm(wslExe(), { force: true });+});++beforeEach(() => {+ invalidateLoginShellPathCache();+ vi.stubEnv('SystemRoot', root);+ vi.stubEnv('LOCALAPPDATA', path.join(root, 'no-such-dir'));+ vi.stubEnv('APPDATA', path.join(root, 'no-such-dir'));+ // The fake distro's login shell inherits this PATH, as a real one has its own.+ vi.stubEnv('PATH', `${path.join(root, 'linux-bin')}:${process.env.PATH}`);+ vi.stubEnv('SHELL', '/bin/sh');+});++describe.runIf(isPosix)('agents inside WSL, end to end', () => {+ it('finds Cursor in WSL when Windows has none, and launches it through wsl.exe', async () => {+ const status = await detectHeterogeneousCliCommand('cursor', 'agent');++ expect(status).toMatchObject({+ available: true,+ path: `wsl://FakeLinux${path.join(root, 'linux-bin', 'agent')}`,+ });++ const plan = await resolveCliSpawnPlan(status.path!, ['acp', '--trust'], process.env);+ expect(plan.command).toBe(wslExe());++ const { stdout } = await execFileAsync(plan.command, plan.args, { env: plan.env });+ expect(stdout.trim()).toBe('cursor-run:acp --trust');+ });++ it('finds the DeepSeek Harness CLI in WSL', async () => {+ const status = await detectDshCommand();++ expect(status).toMatchObject({+ available: true,+ path: `wsl://FakeLinux${path.join(root, 'linux-bin', 'dsh')}`,+ version: '0.9.0',+ });+ });++ it('reports a CLI missing from both sides as unavailable', async () => {+ const status = await detectHeterogeneousCliCommand('qoder', 'qodercli');++ expect(status.available).toBe(false);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/wsl.test.ts b/packages/heterogeneous-agents/src/spawn/wsl.test.tsnew file mode 100644index 00000000000..33b239a7902--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/wsl.test.ts@@ -0,0 +1,240 @@+import * as childProcess from 'node:child_process';+import { EventEmitter } from 'node:events';+import * as os from 'node:os';+import { PassThrough } from 'node:stream';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ buildWslSpawnPlan,+ decodeWslOutput,+ findWslCommandCandidates,+ formatWslCommand,+ getSettledWslPathEnv,+ getWslPathEnv,+ invalidateWslCache,+ parseWslCommand,+ parseWslDistroList,+ parseWslProbeOutput,+ toWslPath,+} from './wsl';++vi.mock('node:os', async () => {+ const actual = await vi.importActual<typeof os>('node:os');+ return { ...actual, platform: vi.fn(() => 'win32') };+});+vi.mock('node:child_process', async () => {+ const actual = await vi.importActual<typeof childProcess>('node:child_process');+ return { ...actual, spawn: vi.fn() };+});++const platformMock = vi.mocked(os.platform);+const spawnMock = vi.mocked(childProcess.spawn);++interface FakeWslRun {+ args: string[];+ input: string;+}++/** Answer each wsl.exe run from `respond`; records argv and what was piped to stdin. */+const fakeWsl = (respond: (args: string[]) => { code?: number; stdout?: Buffer | string }) => {+ const runs: FakeWslRun[] = [];+ spawnMock.mockImplementation(((_command: string, args: string[]) => {+ const child = new EventEmitter() as childProcess.ChildProcess;+ const stdout = new PassThrough();+ const stdin = new PassThrough();+ const run: FakeWslRun = { args, input: '' };+ runs.push(run);+ stdin.on('data', (chunk) => (run.input += chunk.toString()));+ Object.assign(child, { kill: vi.fn(), stdin, stdout });++ stdin.on('finish', () => {+ const { code = 0, stdout: output = '' } = respond(args);+ stdout.end(output);+ setImmediate(() => child.emit('close', code));+ });+ return child;+ }) as never);+ return runs;+};++const probeOutput = (lines: string[]) => ['Welcome to Ubuntu', '', ...lines, ''].join('\n');++beforeEach(() => {+ invalidateWslCache();+ platformMock.mockReturnValue('win32');+ spawnMock.mockReset();+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('wsl commands', () => {+ it('round-trips a distro and a linux path', () => {+ const command = formatWslCommand({+ distro: 'Ubuntu-24.04',+ linuxPath: '/home/me/.local/bin/agent',+ });++ expect(command).toBe('wsl://Ubuntu-24.04/home/me/.local/bin/agent');+ expect(parseWslCommand(command)).toEqual({+ distro: 'Ubuntu-24.04',+ linuxPath: '/home/me/.local/bin/agent',+ });+ });++ it('rejects anything that is not a wsl:// command', () => {+ expect(parseWslCommand('agent')).toBeUndefined();+ expect(parseWslCommand('C:\\tools\\agent.exe')).toBeUndefined();+ expect(parseWslCommand('wsl://Ubuntu')).toBeUndefined();+ expect(parseWslCommand('wsl:///home/me/agent')).toBeUndefined();+ });++ it('translates Windows paths into the distro', () => {+ expect(toWslPath('C:\\Users\\me\\project')).toBe('/mnt/c/Users/me/project');+ expect(toWslPath('D:/work')).toBe('/mnt/d/work');+ expect(toWslPath('\\\\wsl.localhost\\Ubuntu\\home\\me')).toBe('/home/me');+ expect(toWslPath('\\\\wsl$\\Ubuntu\\tmp\\x')).toBe('/tmp/x');+ expect(toWslPath('--model')).toBe('--model');+ expect(toWslPath('acp')).toBe('acp');+ });+});++describe('buildWslSpawnPlan', () => {+ const command = { distro: 'Ubuntu', linuxPath: '/home/me/.local/bin/agent' };++ it('runs the linux binary through wsl.exe with the login PATH and translated path args', () => {+ const plan = buildWslSpawnPlan(+ command,+ ['acp', '--mcp-config', 'C:\\Temp\\mcp.json', '--workspace=C:\\repo'],+ undefined,+ '/home/me/.nvm/versions/node/v22/bin:/usr/bin',+ );++ expect(plan.command).toMatch(/[\\/]System32[\\/]wsl\.exe$/);+ expect(plan.args).toEqual([+ '--distribution',+ 'Ubuntu',+ '--exec',+ 'env',+ 'PATH=/home/me/.nvm/versions/node/v22/bin:/usr/bin',+ '/home/me/.local/bin/agent',+ 'acp',+ '--mcp-config',+ '/mnt/c/Temp/mcp.json',+ '--workspace=/mnt/c/repo',+ ]);+ });++ it('forwards the variables the spawn site set through WSLENV, not argv', () => {+ vi.stubEnv('LOBEHUB_JWT', 'inherited-token');+ vi.stubEnv('HOMEPATH', '\\Users\\me');+ const env = {+ ...process.env,+ CUSTOM_FLAG: '1',+ HOME: 'C:\\Users\\me',+ PATH: 'C:\\Windows',+ WSLENV: 'EXISTING/p',+ };++ const plan = buildWslSpawnPlan(command, [], env, undefined);+ const forwarded = plan.env!.WSLENV!.split(':');++ expect(forwarded).toContain('EXISTING/p');+ expect(forwarded).toContain('CUSTOM_FLAG/u');+ expect(forwarded).toContain('LOBEHUB_JWT/u');+ expect(forwarded.some((entry) => /^(?:HOME|PATH|HOMEPATH)\//i.test(entry))).toBe(false);+ expect(plan.args.join(' ')).not.toContain('inherited-token');+ });+});++describe('probe output', () => {+ it('reads the PATH and absolute command paths, skipping banners and aliases', () => {+ const probe = parseWslProbeOutput(+ probeOutput([+ '__LOBEHUB_WSL_PATH__=/home/me/.local/bin:/usr/bin',+ '__LOBEHUB_WSL_CMD__=agent=/home/me/.local/bin/agent',+ '__LOBEHUB_WSL_CMD__=claude=alias claude=~/.claude/local/claude',+ '__LOBEHUB_WSL_CMD__=dsh=/home/me/.nvm/versions/node/v22/bin/dsh',+ ]),+ );++ 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'],+ ]);+ });++ it('decodes the UTF-16 distro list of older wsl.exe builds and drops Docker Desktop', () => {+ const utf16 = Buffer.from('\uFEFFUbuntu\r\ndocker-desktop\r\nDebian\r\n', 'utf16le');++ expect(parseWslDistroList(decodeWslOutput(utf16))).toEqual(['Ubuntu', 'Debian']);+ expect(parseWslDistroList(decodeWslOutput(Buffer.from('Ubuntu\n')))).toEqual(['Ubuntu']);+ });+});++describe('findWslCommandCandidates', () => {+ it('finds the command in every distro that has it, default distro first', async () => {+ const runs = fakeWsl((args) => {+ if (args[0] === '--list') return { stdout: 'Ubuntu\nDebian\n' };+ if (args[1] === 'Ubuntu') {+ return {+ stdout: probeOutput([+ '__LOBEHUB_WSL_PATH__=/home/me/bin:/usr/bin',+ '__LOBEHUB_WSL_CMD__=agent=/home/me/.local/bin/agent',+ ]),+ };+ }+ return { stdout: probeOutput(['__LOBEHUB_WSL_PATH__=/usr/bin']) };+ });++ await expect(findWslCommandCandidates('agent')).resolves.toEqual([+ 'wsl://Ubuntu/home/me/.local/bin/agent',+ ]);+ // The probe script goes in over stdin, so Windows quoting never touches it.+ const probe = runs.find((run) => run.args[1] === 'Ubuntu')!;+ expect(probe.args.slice(0, 6)).toEqual([+ '--distribution',+ 'Ubuntu',+ '--exec',+ 'sh',+ '-s',+ '--',+ ]);+ expect(probe.args).toEqual(expect.arrayContaining(['agent', 'dsh', 'cursor-agent']));+ expect(probe.input).toContain('-ilc');+ // 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');+ expect(getSettledWslPathEnv('Ubuntu')).toBe('/home/me/bin:/usr/bin');+ expect(runs).toHaveLength(3);+ });++ it('finds nothing without WSL, and never asks off Windows', async () => {+ fakeWsl(() => ({ code: 1 }));+ await expect(findWslCommandCandidates('agent')).resolves.toEqual([]);++ platformMock.mockReturnValue('darwin');+ spawnMock.mockReset();+ await expect(findWslCommandCandidates('agent')).resolves.toEqual([]);+ expect(spawnMock).not.toHaveBeenCalled();+ });++ it('retries a distro whose probe failed instead of pinning the failure', async () => {+ let attempt = 0;+ fakeWsl((args) => {+ if (args[0] === '--list') return { stdout: 'Ubuntu\n' };+ attempt += 1;+ return attempt === 1+ ? { code: 1 }+ : { 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',+ ]);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/wsl.ts b/packages/heterogeneous-agents/src/spawn/wsl.tsnew file mode 100644index 00000000000..39308cfe083--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/wsl.ts@@ -0,0 +1,355 @@+import { spawn } from 'node:child_process';+import { platform } from 'node:os';++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>`+ * (e.g. `wsl://Ubuntu/home/me/.local/bin/agent`).+ *+ * That string travels through every place a resolved command path already+ * goes (the validator, `resolveHeteroSpawnCommand`, the session options), and+ * `resolveCliSpawnPlan` turns it into a `wsl.exe` launch at the last step:+ *+ * 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.+ * - 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+ * `WSLENV`, never on the command line, so tokens stay out of the process+ * list.+ */++export const WSL_COMMAND_PREFIX = 'wsl://';++export interface WslCommand {+ distro: string;+ linuxPath: string;+}++export const isWslCommand = (command: string): boolean =>+ command.trim().toLowerCase().startsWith(WSL_COMMAND_PREFIX);++export const parseWslCommand = (command: string): WslCommand | undefined => {+ const trimmed = command.trim();+ if (!isWslCommand(trimmed)) return;++ const rest = trimmed.slice(WSL_COMMAND_PREFIX.length);+ const slash = rest.indexOf('/');+ if (slash <= 0) return;++ const linuxPath = rest.slice(slash);+ if (linuxPath.length < 2) return;+ return { distro: rest.slice(0, slash), linuxPath };+};++export const formatWslCommand = ({ distro, linuxPath }: WslCommand): string =>+ `${WSL_COMMAND_PREFIX}${distro}${linuxPath}`;++// Concatenated rather than `path.win32.join`ed: SystemRoot is already a Windows+// path, and this keeps a test's stand-in root usable on a POSIX host.+export const getWslExecutable = (env: NodeJS.ProcessEnv = process.env): string =>+ `${(env.SystemRoot || env.SYSTEMROOT || 'C:\\Windows').replace(/[\\/]+$/, '')}\\System32\\wsl.exe`;++/**+ * `C:\Users\me\x` → `/mnt/c/Users/me/x`; `\\wsl.localhost\Ubuntu\home\me` →+ * `/home/me`. Anything that is not an absolute Windows path is returned+ * unchanged.+ */+export const toWslPath = (value: string): string => {+ const drive = value.match(/^([A-Za-z]):[\\/](.*)$/s);+ if (drive) {+ const rest = drive[2]!.replaceAll('\\', '/');+ return `/mnt/${drive[1]!.toLowerCase()}${rest ? `/${rest}` : ''}`;+ }++ const unc = value.match(/^\\\\wsl(?:\$|\.localhost)\\[^\\]+(\\.*)?$/i);+ if (unc) return (unc[1] ?? '\\').replaceAll('\\', '/');++ return value;+};++/** Translates a whole-path argument and the value of a `--flag=<path>` argument. */+const toWslArg = (arg: string): string => {+ const translated = toWslPath(arg);+ if (translated !== arg) return translated;++ const flag = arg.match(/^(--?[\w-]+=)(.+)$/s);+ if (!flag) return arg;+ const value = toWslPath(flag[2]!);+ return value === flag[2] ? arg : `${flag[1]}${value}`;+};++// Windows-side values that would break the Linux side if they crossed over.+const NEVER_FORWARDED = new Set([+ 'appdata',+ 'comspec',+ 'home',+ 'homedrive',+ 'homepath',+ 'localappdata',+ 'path',+ 'pathext',+ 'programdata',+ 'programfiles',+ 'programfiles(x86)',+ 'pwd',+ 'shell',+ 'systemroot',+ 'temp',+ 'tmp',+ 'userprofile',+ 'windir',+ 'wslenv',+]);++// Credentials and settings an agent reads, forwarded even when the spawn site+// inherited them unchanged from its own process.+const FORWARDED_PREFIXES = [+ 'ANTHROPIC_',+ 'CLAUDE_',+ 'CODEX_',+ 'CURSOR_',+ 'DEEPSEEK_',+ 'DSH_',+ 'LOBEHUB_',+ 'OPENAI_',+];+const FORWARDED_PROXY = /^(?:all|http|https|no)_proxy$/i;+const ENV_NAME = /^[A-Za-z_]\w*$/;++const collectForwardedEnvNames = (env: NodeJS.ProcessEnv): string[] =>+ Object.keys(env).filter((name) => {+ if (!ENV_NAME.test(name) || NEVER_FORWARDED.has(name.toLowerCase())) return false;+ if (env[name] === undefined) return false;+ return (+ env[name] !== process.env[name] ||+ FORWARDED_PREFIXES.some((prefix) => name.toUpperCase().startsWith(prefix)) ||+ FORWARDED_PROXY.test(name)+ );+ });++const mergeWslEnv = (current: string | undefined, names: string[]): string => {+ const entries = (current ?? '').split(':').filter(Boolean);+ const present = new Set(entries.map((entry) => entry.split('/')[0]!.toLowerCase()));+ for (const name of names) {+ if (!present.has(name.toLowerCase())) entries.push(`${name}/u`);+ }+ return entries.join(':');+};++export interface WslSpawnPlan {+ args: string[];+ command: string;+ env?: NodeJS.ProcessEnv;+}++export const buildWslSpawnPlan = (+ { distro, linuxPath }: WslCommand,+ args: string[],+ env: NodeJS.ProcessEnv | undefined,+ pathEnv: string | undefined,+): WslSpawnPlan => {+ const forwarded = env ? collectForwardedEnvNames(env) : [];+ return {+ args: [+ '--distribution',+ distro,+ '--exec',+ ...(pathEnv ? ['env', `PATH=${pathEnv}`] : []),+ linuxPath,+ ...args.map(toWslArg),+ ],+ command: getWslExecutable(env),+ env: env && forwarded.length > 0 ? { ...env, WSLENV: mergeWslEnv(env.WSLENV, forwarded) } : env,+ };+};++// ---------------------------------------------------------------------------+// 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;++const PATH_MARKER = '__LOBEHUB_WSL_PATH__=';+const COMMAND_MARKER = '__LOBEHUB_WSL_CMD__=';++/** Every command name detection may look for inside a distro. */+const WSL_PROBED_COMMANDS = [+ ...new Set([+ ...HETEROGENEOUS_AGENT_CONFIGS.map((config) => config.defaultCommand),+ // DeepSeek Harness, and Cursor's unambiguous alias for `agent`.+ 'cursor-agent',+ 'dsh',+ ]),+].filter((name) => /^[\w.-]+$/.test(name));++/**+ * 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.+ */+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+`;++interface WslRunOptions {+ env?: NodeJS.ProcessEnv;+ input?: string;+ timeout: number;+}++const runWsl = (args: string[], { env, input, timeout }: WslRunOptions): Promise<Buffer> =>+ new Promise((resolve, reject) => {+ let settled = false;+ const finish = (error: Error | undefined, output?: Buffer) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ if (error) reject(error);+ else resolve(output!);+ };++ const child = spawn(getWslExecutable(env), args, {+ // wsl.exe's own messages are UTF-16 unless asked otherwise.+ env: { ...(env ?? process.env), WSL_UTF8: '1' },+ stdio: ['pipe', 'pipe', 'ignore'],+ windowsHide: true,+ });+ const chunks: Buffer[] = [];+ const timer = setTimeout(() => {+ child.kill();+ finish(new Error('Timed out waiting for WSL'));+ }, timeout);++ child.stdout?.on('data', (chunk: Buffer) => chunks.push(chunk));+ child.on('error', (error) => finish(error));+ child.on('close', (code) => {+ if (code === 0) finish(undefined, Buffer.concat(chunks));+ else finish(new Error(`wsl.exe exited with code ${code}`));+ });+ child.stdin?.on('error', () => {});+ child.stdin?.end(input ?? '');+ });++/** Older wsl.exe builds ignore WSL_UTF8 and still answer in UTF-16LE. */+export const decodeWslOutput = (output: Buffer): string =>+ (output.includes(0) ? output.toString('utf16le') : output.toString('utf8')).replace(+ /^\uFEFF/,+ '',+ );++export const parseWslDistroList = (output: string): string[] =>+ output+ .split(/\r?\n/)+ .map((line) => line.replaceAll('\0', '').trim())+ // Docker Desktop's backing distros run no user tools.+ .filter((name) => name && !/^docker-desktop/i.test(name));++export interface WslDistroProbe {+ commands: Map<string, string>;+ pathEnv?: string;+}++export const parseWslProbeOutput = (output: string): WslDistroProbe => {+ const commands = new Map<string, string>();+ let pathEnv: string | undefined;++ for (const rawLine of output.split(/\r?\n/)) {+ const line = rawLine.trim();+ if (line.startsWith(PATH_MARKER)) {+ pathEnv = line.slice(PATH_MARKER.length) || undefined;+ } else if (line.startsWith(COMMAND_MARKER)) {+ const entry = line.slice(COMMAND_MARKER.length);+ 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);+ }+ }++ return { commands, pathEnv };+};++let distrosPromise: Promise<string[]> | undefined;+const distroProbes = new Map<string, Promise<WslDistroProbe | undefined>>();+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(() => []);+ return distrosPromise;+};++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,+ timeout: WSL_PROBE_TIMEOUT_MS,+ })+ .then((output) => {+ const result = parseWslProbeOutput(decodeWslOutput(output));+ settledPathEnv.set(distro, result.pathEnv);+ return result;+ })+ .catch(() => {+ // Don't pin a failure (a distro that was still booting): the next scan retries.+ distroProbes.delete(distro);+ return undefined;+ });+ distroProbes.set(distro, probe);+ }+ return probe;+};++/** Drop what was learned about WSL so a Rescan sees agents installed since. */+export const invalidateWslCache = (): void => {+ distrosPromise = undefined;+ distroProbes.clear();+ settledPathEnv.clear();+};++/**+ * The `wsl://` locations of `command` in every distro whose login shell+ * resolves it, in the order `wsl.exe --list` gives (the default distro first).+ * Empty off Windows.+ */+export const findWslCommandCandidates = async (command: string): Promise<string[]> => {+ if (platform() !== 'win32') return [];++ 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 })] : [];+ });+};++/** The login-shell PATH of `distro`, probing it if this process hasn't yet. */+export const getWslPathEnv = async (distro: string): Promise<string | undefined> =>+ (await probeWslDistro(distro))?.pathEnv;++/**+ * The login-shell PATH already learned for `distro`, for spawn sites that must+ * stay synchronous (the Claude Agent SDK's spawn hook). Call `getWslPathEnv`+ * beforehand on the async side.+ */+export const getSettledWslPathEnv = (distro: string): string | undefined =>+ settledPathEnv.get(distro);