dsh-wsl-workspace 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/shell.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"shell.js","names":[],"sources":["../src/shell.ts"],"sourcesContent":["/**\n * WSL Service Provider for the `ctx.shell` capability seam. Every command\n * runs inside one WSL distribution as `wsl.exe -d <distro> [-u <user>]\n * --cd <linux cwd> -e bash -lc <command>`, so the model-facing bash dialect\n * matches the execution world exactly — the \"like direct calls\" experience\n * of a WSL workspace session.\n *\n * The executor is a fresh implementation modeled on\n * `@deepseek-ai/dsh-bash-local` (same deadline fusion, bounded collect,\n * background adaptation) but does NOT register the shared `shell` settings\n * namespace: the host composition already registers it through its own\n * executor, and a second registration from a preset realm would collide.\n * Configuration rides the preset row instead.\n * @module dsh-wsl-workspace/shell\n */\n\nimport { Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport { ShellExecutor } from '@deepseek-ai/dsh-shell'\nimport type {\n CollectedOutput,\n ShellExecRequest,\n ShellExecSpec,\n ShellProcess,\n ShellProcessRead,\n ShellRunResult,\n} from '@deepseek-ai/dsh-shell'\nimport type {\n SubprocessCollect,\n SubprocessHandle,\n SubprocessOutputReader,\n SubprocessSpawnSpec,\n} from '@deepseek-ai/dsh-subprocess'\nimport { clampTimeout, deadline, MAX_TIMER_DELAY_MS, timeoutOf } from '@deepseek-ai/dsh-timeout'\nimport {\n isWindowsPathShaped,\n isValidWslUsername,\n joinUnc,\n parseWslUnc,\n windowsToMntPath,\n} from './shared/paths.ts'\nimport { getWorkspaceUsername } from './shared/wsl-credentials.ts'\nimport { defaultDistroSync } from './shared/wsl.ts'\n\n/**\n * Model-friendly environment overrides (same set `dsh-bash-local` hardcodes):\n * disable colors, pagers, and interactive terminal features that would garble\n * tool output. These values cross into the Linux process through WSLENV.\n */\nconst ENV_OVERRIDES = {\n NO_COLOR: '1',\n TERM: 'dumb',\n PAGER: 'cat',\n GIT_PAGER: 'cat',\n} as const\n\n/** Default SIGTERM→SIGKILL grace period (matches `dsh-bash-local`). */\nconst DEFAULT_GRACE_MS = 3_000\n\n/** Default per-stream spill cap (matches `dsh-bash-local`). */\nconst DEFAULT_MAX_SPILL_BYTES = 64 * 1024 * 1024\n\n/** Plugin config (all optional — `static Config` supplies the defaults). */\nexport interface Config {\n /** Default working directory (a WSL UNC or Linux path); per-call workdir wins. */\n cwd?: string\n /**\n * Default distribution used only when a call's workdir carries no distro\n * (UNC workdirs always do; Linux/Windows drive workdirs do not).\n */\n distro?: string\n /**\n * Linux user bash runs as when the call carries no per-workspace user\n * (`wsl.exe -u <username>`); undefined/empty = the distro default user.\n */\n username?: string\n /** The `wsl.exe` executable (absolute path or PATH name). */\n wslPath?: string\n /** Start bash as a login shell (`-lc`) so user profile PATHs (nvm, cargo…) load. */\n loginShell?: boolean\n /** Default foreground timeout in milliseconds. */\n timeoutMs?: number\n /** Upper bound for per-call timeout overrides. */\n maxTimeoutMs?: number\n /** Per-stream in-memory output cap; overflow spills to a temp file. */\n maxOutputBytes?: number\n /** Per-stream spill-file cap; larger streams retain only their in-memory tail. */\n maxSpillBytes?: number\n /** Grace period for kill escalation and inherited pipes; at most `MAX_TIMER_DELAY_MS`. */\n graceMs?: number\n}\n\n/** The shape after schemastery applied the defaults. */\ntype ResolvedConfig = Required<Omit<Config, 'cwd' | 'distro' | 'username'>> & Pick<Config, 'cwd' | 'distro' | 'username'>\n\n/** Project a settled collect-mode reader into the final CollectedOutput shape. */\nfunction finalOutput(reader: SubprocessOutputReader): CollectedOutput {\n const read = reader.readFrom(0)\n return {\n text: read.text,\n truncated: read.lossy,\n ...read.spillPath !== undefined ? { spillPath: read.spillPath } : {},\n }\n}\n\nfunction assertPositiveFinite(name: string, value: number): void {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`wsl-shell: ${name} must be a positive finite number`)\n }\n}\n\n/**\n * Reject a resolved configuration this executor could not run with, so a\n * stored value is refused where it is written instead of failing at the next\n * command.\n * @param config - the schema-validated configuration.\n * @throws Error naming the field that cannot be used.\n */\nexport function assertServiceableWslConfig(config: Config): void {\n const resolved = config as ResolvedConfig\n assertPositiveFinite('timeoutMs', resolved.timeoutMs)\n assertPositiveFinite('maxTimeoutMs', resolved.maxTimeoutMs)\n assertPositiveFinite('maxOutputBytes', resolved.maxOutputBytes)\n assertPositiveFinite('maxSpillBytes', resolved.maxSpillBytes)\n assertPositiveFinite('graceMs', resolved.graceMs)\n if (resolved.graceMs > MAX_TIMER_DELAY_MS) {\n throw new Error(`wsl-shell: graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`)\n }\n if (resolved.distro !== undefined && resolved.distro.trim() === '') {\n throw new Error('wsl-shell: distro must be a non-empty distribution name')\n }\n if (resolved.username !== undefined && resolved.username !== '' && !isValidWslUsername(resolved.username)) {\n throw new Error('wsl-shell: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\n }\n}\n\n/** One translated execution plan: the Linux world coordinates plus the argv. */\ninterface WslPlan {\n /** Distribution the command runs in. */\n distro: string\n /** Linux working directory handed to `wsl.exe --cd`. */\n linuxCwd: string\n /** A valid Windows directory for the `wsl.exe` process itself. */\n windowsCwd: string\n /** Environment map (ENV_OVERRIDES + caller env + dshEnv) with WSLENV set. */\n env: Record<string, string>\n /** Full argv to hand to `ctx.subprocess`. */\n argv: readonly string[]\n}\n\n/**\n * WSL bash executor over the LOCAL subprocess service: `wsl.exe` is a Windows\n * executable, so the Windows-side spawn, bounded output, spill files, and\n * process-group termination are the local subprocess seam's mechanics; this\n * executor supplies the Linux-world argv, cwd translation, and WSLENV.\n */\nexport class WslShellExecutor extends ShellExecutor {\n static inject = ['subprocess']\n\n static Config: z<Config> = z.object({\n cwd: z.string(),\n distro: z.string(),\n username: z.string(),\n wslPath: z.string().default('wsl.exe'),\n loginShell: z.boolean().default(true),\n timeoutMs: z.number().default(120_000),\n maxTimeoutMs: z.number().default(600_000),\n maxOutputBytes: z.number().default(64_000),\n maxSpillBytes: z.number().default(DEFAULT_MAX_SPILL_BYTES),\n graceMs: z.number().default(DEFAULT_GRACE_MS),\n })\n\n private readonly resolved: ResolvedConfig\n\n /** Validated config (schemastery applied the defaults before construction). */\n get config(): ResolvedConfig {\n return this.resolved\n }\n\n constructor(ctx: Context, config: Config) {\n super(ctx)\n const entry = config as ResolvedConfig\n assertServiceableWslConfig(entry)\n this.resolved = entry\n }\n\n /**\n * Resolve a request into a fully-specified spec: fill `workdir` from\n * `config.cwd`, and `timeoutMs` from `config.timeoutMs`, capped at\n * `config.maxTimeoutMs`. The tool layer calls this before\n * {@link run}/{@link start}, so those methods receive explicit values.\n */\n resolve(request: ShellExecRequest): ShellExecSpec {\n const timeoutMs = clampTimeout(\n request.timeoutMs,\n this.config.timeoutMs,\n this.config.maxTimeoutMs,\n 'wsl-shell: request.timeoutMs',\n )\n const stdoutMaxBytes = request.stdoutMaxBytes ?? this.config.maxOutputBytes\n assertPositiveFinite('request.stdoutMaxBytes', stdoutMaxBytes)\n return {\n command: request.command,\n workdir: request.workdir ?? this.config.cwd ?? process.cwd(),\n timeoutMs,\n stdoutMaxBytes,\n ...request.signal ? { signal: request.signal } : {},\n ...request.stdin !== undefined ? { stdin: request.stdin } : {},\n ...request.env !== undefined ? { env: request.env } : {},\n ...request.dshEnv !== undefined ? { dshEnv: request.dshEnv } : {},\n sandboxPolicy: request.sandboxPolicy,\n }\n }\n\n /**\n * Translate a resolved spec into the Linux execution plan. Fails loud on a\n * workdir that names neither the WSL world (UNC or Linux path) nor a\n * Windows drive path (reached through `/mnt/<drive>`).\n * @param spec - the resolved execution spec.\n * @returns the translated plan, including the complete argv.\n */\n private plan(spec: ShellExecSpec): WslPlan {\n const workdir = spec.workdir\n let distro: string\n let linuxCwd: string\n let windowsCwd: string\n let username: string | undefined\n const unc = parseWslUnc(workdir)\n if (unc !== null) {\n distro = unc.distro\n linuxCwd = unc.linuxPath\n // The `wsl.exe` process itself needs a plain Windows directory: its own\n // cwd is irrelevant (`--cd` sets the Linux side), and spawning with a\n // UNC cwd is a documented Node/Windows edge. SystemRoot always exists.\n windowsCwd = process.env.SystemRoot ?? process.cwd()\n username = this.resolveUser(spec, joinUnc(unc.distro, unc.linuxPath))\n } else if (workdir.startsWith('/')) {\n distro = this.resolveDistro(spec)\n linuxCwd = workdir\n windowsCwd = process.cwd()\n username = this.resolveUser(spec, undefined)\n } else {\n const mnt = windowsToMntPath(workdir)\n if (mnt === null) {\n throw new Error(`wsl-shell: workdir \"${workdir}\" is not in the WSL execution world`)\n }\n distro = this.resolveDistro(spec)\n linuxCwd = mnt\n windowsCwd = workdir\n username = this.resolveUser(spec, undefined)\n }\n const env = this.withWslEnv(spec)\n const argv = [\n this.config.wslPath,\n '-d', distro,\n ...(username !== undefined && username !== '' ? ['-u', username] : []),\n '--cd', linuxCwd,\n '-e', 'bash',\n this.config.loginShell ? '-lc' : '-c',\n spec.command,\n ]\n return { distro, linuxCwd, windowsCwd, env, argv }\n }\n\n /**\n * Resolve the distribution for a workdir that carries none. The chain:\n * the calling session's distribution (`DSH_WSL_DISTRO`, contributed by the\n * host half from the session's UNC workspace cwd — the common case for a\n * model passing a Linux `workdir`), then the configured `distro`, then the\n * host's default distribution (cached registry read) as a last resort for\n * plugin-driven calls with no session. Fails loud when every source is\n * absent rather than guessing a distro the path does not belong to.\n * @param spec - the resolved execution spec (its dshEnv carries the session fact).\n * @returns the distribution name.\n */\n private resolveDistro(spec: ShellExecSpec): string {\n const fromEnv = spec.dshEnv?.DSH_WSL_DISTRO\n if (fromEnv !== undefined && fromEnv !== '') return fromEnv\n const configured = this.config.distro\n if (configured !== undefined && configured !== '') return configured\n const fallback = defaultDistroSync()\n if (fallback !== undefined) return fallback\n throw new Error(\n 'wsl-shell: Linux workdir carries no distribution; no session DSH_WSL_DISTRO, distro config, '\n + 'or default distribution is available',\n )\n }\n\n /**\n * Resolve the Linux user bash runs as. The chain: the calling session's\n * workspace user (`DSH_WSL_USER`, contributed by the host half), then the\n * workspace's stored username when the workdir is a UNC path, then the\n * configured `username`. Absent everywhere, the distribution's default\n * user runs. Invalid values are skipped (they were validated on write;\n * the guard is defense in depth).\n * @param spec - the resolved execution spec (its dshEnv carries the session fact).\n * @param uncKey - canonical UNC key of the workdir when it is a UNC path.\n * @returns the username, or undefined for the distro default user.\n */\n private resolveUser(spec: ShellExecSpec, uncKey: string | undefined): string | undefined {\n const candidates = [\n spec.dshEnv?.DSH_WSL_USER,\n uncKey === undefined ? undefined : getWorkspaceUsername(uncKey),\n this.config.username,\n ]\n for (const candidate of candidates) {\n if (candidate !== undefined && candidate !== '' && isValidWslUsername(candidate)) return candidate\n }\n return undefined\n }\n\n /**\n * Merge the caller env layers and inject `WSLENV` so the Windows-side\n * values reach the Linux process. Windows-path-shaped values get the `/p`\n * translation flag (they become `/mnt/<drive>/…` inside WSL); the ambient\n * `WSLENV` value is preserved and extended.\n * @param spec - the resolved execution spec.\n * @returns the explicit environment map for the spawn.\n */\n private withWslEnv(spec: ShellExecSpec): Record<string, string> {\n const env: Record<string, string> = { ...ENV_OVERRIDES, ...spec.env, ...spec.dshEnv }\n const flags: string[] = []\n for (const [key, value] of Object.entries(env)) {\n if (key.toUpperCase() === 'WSLENV') continue\n flags.push(isWindowsPathShaped(value) ? `${key}/p` : key)\n }\n const ambient = process.env.WSLENV\n const merged = [ambient, flags.join(':')].filter(part => part !== undefined && part !== '').join(':')\n env.WSLENV = merged\n return env\n }\n\n /** Map a plan onto a fully-specified subprocess spawn. */\n private spawnSpec(plan: WslPlan, spec: ShellExecSpec, stdoutMaxBytes: number, signal: AbortSignal | undefined): SubprocessSpawnSpec {\n const collect = (maxBytes: number): SubprocessCollect =>\n ({ maxBytes, spill: { maxBytes: this.config.maxSpillBytes } })\n return {\n argv: plan.argv,\n cwd: plan.windowsCwd,\n stdio: {\n stdin: spec.stdin !== undefined ? { data: spec.stdin } : 'ignore',\n stdout: collect(stdoutMaxBytes),\n stderr: collect(this.config.maxOutputBytes),\n },\n graceMs: this.config.graceMs,\n signal,\n env: plan.env,\n }\n }\n\n /** The collect-mode readers this executor requested (present by construction). */\n private static collected(handle: SubprocessHandle): { stdout: SubprocessOutputReader; stderr: SubprocessOutputReader } {\n const { stdout, stderr } = handle.collected\n /* v8 ignore start -- collect dispositions expose both readers by the seam contract; defensive. */\n if (stdout === undefined || stderr === undefined) {\n throw new Error('wsl-shell: subprocess implementation dropped a requested collect stream')\n }\n /* v8 ignore stop */\n return { stdout, stderr }\n }\n\n /** Run one command in the foreground. */\n async run(spec: ShellExecSpec): Promise<ShellRunResult> {\n const plan = this.plan(spec)\n using d = deadline(spec.signal, spec.timeoutMs, 'WSL_BASH_TIMEOUT')\n const handle = this.ctx.subprocess.spawn(this.spawnSpec(plan, spec, spec.stdoutMaxBytes, d.signal))\n const outcome = await handle.done\n const collected = WslShellExecutor.collected(handle)\n // Only this executor's timeout reason counts as timedOut; outer deadlines count as aborts.\n const timedOut = timeoutOf(d.signal, 'WSL_BASH_TIMEOUT') !== undefined\n const aborted = d.signal.aborted && !timedOut\n return {\n ...outcome,\n timedOut,\n aborted,\n timeoutMs: spec.timeoutMs,\n stdout: finalOutput(collected.stdout),\n stderr: finalOutput(collected.stderr),\n }\n }\n\n /** Start one command in the background and return its live handle. */\n start(spec: ShellExecSpec): ShellProcess {\n const plan = this.plan(spec)\n // Background runs ignore timeoutMs; callers stop them through kill() or spec.signal.\n const running = this.ctx.subprocess.spawn(this.spawnSpec(plan, spec, this.config.maxOutputBytes, spec.signal))\n const collected = WslShellExecutor.collected(running)\n\n // A spawn failure produces no process output, so the subprocess service has\n // nothing to buffer; the note is delivered exactly once through the read path.\n let spawnFailureNote: string | undefined\n const consumeSpawnFailure = (): string => {\n const note = spawnFailureNote ?? ''\n spawnFailureNote = undefined\n return note\n }\n\n let stdoutOffset = 0\n let stderrOffset = 0\n const proc: ShellProcess = {\n status: 'running',\n exitCode: null,\n signal: null,\n done: running.done.then((outcome) => {\n if (proc.status === 'running') {\n proc.status = spec.signal?.aborted === true || outcome.signal !== null ? 'killed' : 'completed'\n }\n proc.exitCode = outcome.exitCode\n proc.signal = outcome.signal\n }, (error: unknown) => {\n proc.status = 'killed'\n spawnFailureNote = `spawn failed: ${String(error)}`\n }),\n readOutput: (): ShellProcessRead => {\n const out = collected.stdout.readFrom(stdoutOffset)\n const err = collected.stderr.readFrom(stderrOffset)\n stdoutOffset = out.nextOffset\n stderrOffset = err.nextOffset\n const errText = err.text.length > 0 ? err.text : consumeSpawnFailure()\n const separator = out.text.length > 0 && !out.text.endsWith('\\n') ? '\\n' : ''\n const delta = out.text\n + (errText.length > 0 ? `${separator}[stderr]\\n${errText}` : '')\n return {\n delta,\n lossy: out.lossy || err.lossy,\n ...out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {},\n ...err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {},\n }\n },\n kill: (): boolean => {\n if (proc.status !== 'running') return false\n proc.status = 'killed'\n running.terminate()\n return true\n },\n }\n return proc\n }\n}\n\nexport default WslShellExecutor\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,gBAAgB;CACpB,UAAU;CACV,MAAM;CACN,OAAO;CACP,WAAW;AACb;;AAGA,MAAM,mBAAmB;;AAGzB,MAAM,0BAA0B,KAAK,OAAO;;AAoC5C,SAAS,YAAY,QAAiD;CACpE,MAAM,OAAO,OAAO,SAAS,CAAC;CAC9B,OAAO;EACL,MAAM,KAAK;EACX,WAAW,KAAK;EAChB,GAAG,KAAK,cAAc,KAAA,IAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;CACrE;AACF;AAEA,SAAS,qBAAqB,MAAc,OAAqB;CAC/D,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,GACtC,MAAM,IAAI,MAAM,cAAc,KAAK,kCAAkC;AAEzE;;;;;;;;AASA,SAAgB,2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;CACT;AACF"}
1
+ {"version":3,"file":"shell.js","names":[],"sources":["../src/shell.ts"],"sourcesContent":["/**\r\n * WSL Service Provider for the `ctx.shell` capability seam. Every command\r\n * runs inside one WSL distribution as `wsl.exe -d <distro> [-u <user>]\r\n * --cd <linux cwd> -e bash -lc <command>`, so the model-facing bash dialect\r\n * matches the execution world exactly — the \"like direct calls\" experience\r\n * of a WSL workspace session.\r\n *\r\n * The executor is a fresh implementation modeled on\r\n * `@deepseek-ai/dsh-bash-local` (same deadline fusion, bounded collect,\r\n * background adaptation) but does NOT register the shared `shell` settings\r\n * namespace: the host composition already registers it through its own\r\n * executor, and a second registration from a preset realm would collide.\r\n * Configuration rides the preset row instead.\r\n * @module dsh-wsl-workspace/shell\r\n */\r\n\r\nimport { Context } from '@deepseek-ai/cordis'\r\nimport z from '@deepseek-ai/schemastery'\r\nimport { ShellExecutor } from '@deepseek-ai/dsh-shell'\r\nimport type {\r\n CollectedOutput,\r\n ShellExecRequest,\r\n ShellExecSpec,\r\n ShellProcess,\r\n ShellProcessRead,\r\n ShellRunResult,\r\n} from '@deepseek-ai/dsh-shell'\r\nimport type {\r\n SubprocessCollect,\r\n SubprocessHandle,\r\n SubprocessOutputReader,\r\n SubprocessSpawnSpec,\r\n} from '@deepseek-ai/dsh-subprocess'\r\nimport { clampTimeout, deadline, MAX_TIMER_DELAY_MS, timeoutOf } from '@deepseek-ai/dsh-timeout'\r\nimport {\r\n isWindowsPathShaped,\r\n isValidWslUsername,\r\n joinUnc,\r\n parseWslUnc,\r\n windowsToMntPath,\r\n} from './shared/paths.ts'\r\nimport { getWorkspaceUsername } from './shared/wsl-credentials.ts'\r\nimport { defaultDistroSync } from './shared/wsl.ts'\r\n\r\n/**\r\n * Model-friendly environment overrides (same set `dsh-bash-local` hardcodes):\r\n * disable colors, pagers, and interactive terminal features that would garble\r\n * tool output. These values cross into the Linux process through WSLENV.\r\n */\r\nconst ENV_OVERRIDES = {\r\n NO_COLOR: '1',\r\n TERM: 'dumb',\r\n PAGER: 'cat',\r\n GIT_PAGER: 'cat',\r\n} as const\r\n\r\n/** Default SIGTERM→SIGKILL grace period (matches `dsh-bash-local`). */\r\nconst DEFAULT_GRACE_MS = 3_000\r\n\r\n/** Default per-stream spill cap (matches `dsh-bash-local`). */\r\nconst DEFAULT_MAX_SPILL_BYTES = 64 * 1024 * 1024\r\n\r\n/** Plugin config (all optional — `static Config` supplies the defaults). */\r\nexport interface Config {\r\n /** Default working directory (a WSL UNC or Linux path); per-call workdir wins. */\r\n cwd?: string\r\n /**\r\n * Default distribution used only when a call's workdir carries no distro\r\n * (UNC workdirs always do; Linux/Windows drive workdirs do not).\r\n */\r\n distro?: string\r\n /**\r\n * Linux user bash runs as when the call carries no per-workspace user\r\n * (`wsl.exe -u <username>`); undefined/empty = the distro default user.\r\n */\r\n username?: string\r\n /** The `wsl.exe` executable (absolute path or PATH name). */\r\n wslPath?: string\r\n /** Start bash as a login shell (`-lc`) so user profile PATHs (nvm, cargo…) load. */\r\n loginShell?: boolean\r\n /** Default foreground timeout in milliseconds. */\r\n timeoutMs?: number\r\n /** Upper bound for per-call timeout overrides. */\r\n maxTimeoutMs?: number\r\n /** Per-stream in-memory output cap; overflow spills to a temp file. */\r\n maxOutputBytes?: number\r\n /** Per-stream spill-file cap; larger streams retain only their in-memory tail. */\r\n maxSpillBytes?: number\r\n /** Grace period for kill escalation and inherited pipes; at most `MAX_TIMER_DELAY_MS`. */\r\n graceMs?: number\r\n}\r\n\r\n/** The shape after schemastery applied the defaults. */\r\ntype ResolvedConfig = Required<Omit<Config, 'cwd' | 'distro' | 'username'>> & Pick<Config, 'cwd' | 'distro' | 'username'>\r\n\r\n/** Project a settled collect-mode reader into the final CollectedOutput shape. */\r\nfunction finalOutput(reader: SubprocessOutputReader): CollectedOutput {\r\n const read = reader.readFrom(0)\r\n return {\r\n text: read.text,\r\n truncated: read.lossy,\r\n ...read.spillPath !== undefined ? { spillPath: read.spillPath } : {},\r\n }\r\n}\r\n\r\nfunction assertPositiveFinite(name: string, value: number): void {\r\n if (!Number.isFinite(value) || value <= 0) {\r\n throw new Error(`wsl-shell: ${name} must be a positive finite number`)\r\n }\r\n}\r\n\r\n/**\r\n * Reject a resolved configuration this executor could not run with, so a\r\n * stored value is refused where it is written instead of failing at the next\r\n * command.\r\n * @param config - the schema-validated configuration.\r\n * @throws Error naming the field that cannot be used.\r\n */\r\nexport function assertServiceableWslConfig(config: Config): void {\r\n const resolved = config as ResolvedConfig\r\n assertPositiveFinite('timeoutMs', resolved.timeoutMs)\r\n assertPositiveFinite('maxTimeoutMs', resolved.maxTimeoutMs)\r\n assertPositiveFinite('maxOutputBytes', resolved.maxOutputBytes)\r\n assertPositiveFinite('maxSpillBytes', resolved.maxSpillBytes)\r\n assertPositiveFinite('graceMs', resolved.graceMs)\r\n if (resolved.graceMs > MAX_TIMER_DELAY_MS) {\r\n throw new Error(`wsl-shell: graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`)\r\n }\r\n if (resolved.distro !== undefined && resolved.distro.trim() === '') {\r\n throw new Error('wsl-shell: distro must be a non-empty distribution name')\r\n }\r\n if (resolved.username !== undefined && resolved.username !== '' && !isValidWslUsername(resolved.username)) {\r\n throw new Error('wsl-shell: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\r\n }\r\n}\r\n\r\n/** One translated execution plan: the Linux world coordinates plus the argv. */\r\ninterface WslPlan {\r\n /** Distribution the command runs in. */\r\n distro: string\r\n /** Linux working directory handed to `wsl.exe --cd`. */\r\n linuxCwd: string\r\n /** A valid Windows directory for the `wsl.exe` process itself. */\r\n windowsCwd: string\r\n /** Environment map (ENV_OVERRIDES + caller env + dshEnv) with WSLENV set. */\r\n env: Record<string, string>\r\n /** Full argv to hand to `ctx.subprocess`. */\r\n argv: readonly string[]\r\n}\r\n\r\n/**\r\n * WSL bash executor over the LOCAL subprocess service: `wsl.exe` is a Windows\r\n * executable, so the Windows-side spawn, bounded output, spill files, and\r\n * process-group termination are the local subprocess seam's mechanics; this\r\n * executor supplies the Linux-world argv, cwd translation, and WSLENV.\r\n */\r\nexport class WslShellExecutor extends ShellExecutor {\r\n static inject = ['subprocess']\r\n\r\n static Config: z<Config> = z.object({\r\n cwd: z.string(),\r\n distro: z.string(),\r\n username: z.string(),\r\n wslPath: z.string().default('wsl.exe'),\r\n loginShell: z.boolean().default(true),\r\n timeoutMs: z.number().default(120_000),\r\n maxTimeoutMs: z.number().default(600_000),\r\n maxOutputBytes: z.number().default(64_000),\r\n maxSpillBytes: z.number().default(DEFAULT_MAX_SPILL_BYTES),\r\n graceMs: z.number().default(DEFAULT_GRACE_MS),\r\n })\r\n\r\n private readonly resolved: ResolvedConfig\r\n\r\n /** Validated config (schemastery applied the defaults before construction). */\r\n get config(): ResolvedConfig {\r\n return this.resolved\r\n }\r\n\r\n constructor(ctx: Context, config: Config) {\r\n super(ctx)\r\n const entry = config as ResolvedConfig\r\n assertServiceableWslConfig(entry)\r\n this.resolved = entry\r\n }\r\n\r\n /**\r\n * Resolve a request into a fully-specified spec: fill `workdir` from\r\n * `config.cwd`, and `timeoutMs` from `config.timeoutMs`, capped at\r\n * `config.maxTimeoutMs`. The tool layer calls this before\r\n * {@link run}/{@link start}, so those methods receive explicit values.\r\n */\r\n resolve(request: ShellExecRequest): ShellExecSpec {\r\n const timeoutMs = clampTimeout(\r\n request.timeoutMs,\r\n this.config.timeoutMs,\r\n this.config.maxTimeoutMs,\r\n 'wsl-shell: request.timeoutMs',\r\n )\r\n const stdoutMaxBytes = request.stdoutMaxBytes ?? this.config.maxOutputBytes\r\n assertPositiveFinite('request.stdoutMaxBytes', stdoutMaxBytes)\r\n return {\r\n command: request.command,\r\n workdir: request.workdir ?? this.config.cwd ?? process.cwd(),\r\n timeoutMs,\r\n stdoutMaxBytes,\r\n ...request.signal ? { signal: request.signal } : {},\r\n ...request.stdin !== undefined ? { stdin: request.stdin } : {},\r\n ...request.env !== undefined ? { env: request.env } : {},\r\n ...request.dshEnv !== undefined ? { dshEnv: request.dshEnv } : {},\r\n sandboxPolicy: request.sandboxPolicy,\r\n }\r\n }\r\n\r\n /**\r\n * Translate a resolved spec into the Linux execution plan. Fails loud on a\r\n * workdir that names neither the WSL world (UNC or Linux path) nor a\r\n * Windows drive path (reached through `/mnt/<drive>`).\r\n * @param spec - the resolved execution spec.\r\n * @returns the translated plan, including the complete argv.\r\n */\r\n private plan(spec: ShellExecSpec): WslPlan {\r\n const workdir = spec.workdir\r\n let distro: string\r\n let linuxCwd: string\r\n let windowsCwd: string\r\n let username: string | undefined\r\n const unc = parseWslUnc(workdir)\r\n if (unc !== null) {\r\n distro = unc.distro\r\n linuxCwd = unc.linuxPath\r\n // The `wsl.exe` process itself needs a plain Windows directory: its own\r\n // cwd is irrelevant (`--cd` sets the Linux side), and spawning with a\r\n // UNC cwd is a documented Node/Windows edge. SystemRoot always exists.\r\n windowsCwd = process.env.SystemRoot ?? process.cwd()\r\n username = this.resolveUser(spec, joinUnc(unc.distro, unc.linuxPath))\r\n } else if (workdir.startsWith('/')) {\r\n distro = this.resolveDistro(spec)\r\n linuxCwd = workdir\r\n windowsCwd = process.cwd()\r\n username = this.resolveUser(spec, undefined)\r\n } else {\r\n const mnt = windowsToMntPath(workdir)\r\n if (mnt === null) {\r\n throw new Error(`wsl-shell: workdir \"${workdir}\" is not in the WSL execution world`)\r\n }\r\n distro = this.resolveDistro(spec)\r\n linuxCwd = mnt\r\n windowsCwd = workdir\r\n username = this.resolveUser(spec, undefined)\r\n }\r\n const env = this.withWslEnv(spec)\r\n // A login shell (`-lc`) loads /etc/profile + the user profile chain, and\r\n // several of those reset the cwd to $HOME (observed on Ubuntu 22.04 with\r\n // a zsh user default: `wsl.exe --cd <dir> -e bash -lc 'pwd'` prints the\r\n // home directory, while `-c` honors `--cd`). The model-facing cwd must\r\n // be the resolved workdir in both modes, so prefix an explicit `cd`\r\n // when the login shell runs. `cd` into a deleted directory fails the\r\n // command exactly like `--cd` would; the failure text is unchanged.\r\n const command = this.config.loginShell\r\n ? `cd '${linuxCwd.replace(/'/g, `'\\\\''`)}' && ${spec.command}`\r\n : spec.command\r\n const argv = [\r\n this.config.wslPath,\r\n '-d', distro,\r\n ...(username !== undefined && username !== '' ? ['-u', username] : []),\r\n '--cd', linuxCwd,\r\n '-e', 'bash',\r\n this.config.loginShell ? '-lc' : '-c',\r\n command,\r\n ]\r\n return { distro, linuxCwd, windowsCwd, env, argv }\r\n }\r\n\r\n /**\r\n * Resolve the distribution for a workdir that carries none. The chain:\r\n * the calling session's distribution (`DSH_WSL_DISTRO`, contributed by the\r\n * host half from the session's UNC workspace cwd — the common case for a\r\n * model passing a Linux `workdir`), then the configured `distro`, then the\r\n * host's default distribution (cached registry read) as a last resort for\r\n * plugin-driven calls with no session. Fails loud when every source is\r\n * absent rather than guessing a distro the path does not belong to.\r\n * @param spec - the resolved execution spec (its dshEnv carries the session fact).\r\n * @returns the distribution name.\r\n */\r\n private resolveDistro(spec: ShellExecSpec): string {\r\n const fromEnv = spec.dshEnv?.DSH_WSL_DISTRO\r\n if (fromEnv !== undefined && fromEnv !== '') return fromEnv\r\n const configured = this.config.distro\r\n if (configured !== undefined && configured !== '') return configured\r\n const fallback = defaultDistroSync()\r\n if (fallback !== undefined) return fallback\r\n throw new Error(\r\n 'wsl-shell: Linux workdir carries no distribution; no session DSH_WSL_DISTRO, distro config, '\r\n + 'or default distribution is available',\r\n )\r\n }\r\n\r\n /**\r\n * Resolve the Linux user bash runs as. The chain: the calling session's\r\n * workspace user (`DSH_WSL_USER`, contributed by the host half), then the\r\n * workspace's stored username when the workdir is a UNC path, then the\r\n * configured `username`. Absent everywhere, the distribution's default\r\n * user runs. Invalid values are skipped (they were validated on write;\r\n * the guard is defense in depth).\r\n * @param spec - the resolved execution spec (its dshEnv carries the session fact).\r\n * @param uncKey - canonical UNC key of the workdir when it is a UNC path.\r\n * @returns the username, or undefined for the distro default user.\r\n */\r\n private resolveUser(spec: ShellExecSpec, uncKey: string | undefined): string | undefined {\r\n const candidates = [\r\n spec.dshEnv?.DSH_WSL_USER,\r\n uncKey === undefined ? undefined : getWorkspaceUsername(uncKey),\r\n this.config.username,\r\n ]\r\n for (const candidate of candidates) {\r\n if (candidate !== undefined && candidate !== '' && isValidWslUsername(candidate)) return candidate\r\n }\r\n return undefined\r\n }\r\n\r\n /**\r\n * Merge the caller env layers and inject `WSLENV` so the Windows-side\r\n * values reach the Linux process. Windows-path-shaped values get the `/p`\r\n * translation flag (they become `/mnt/<drive>/…` inside WSL); the ambient\r\n * `WSLENV` value is preserved and extended.\r\n * @param spec - the resolved execution spec.\r\n * @returns the explicit environment map for the spawn.\r\n */\r\n private withWslEnv(spec: ShellExecSpec): Record<string, string> {\r\n const env: Record<string, string> = { ...ENV_OVERRIDES, ...spec.env, ...spec.dshEnv }\r\n const flags: string[] = []\r\n for (const [key, value] of Object.entries(env)) {\r\n if (key.toUpperCase() === 'WSLENV') continue\r\n flags.push(isWindowsPathShaped(value) ? `${key}/p` : key)\r\n }\r\n const ambient = process.env.WSLENV\r\n const merged = [ambient, flags.join(':')].filter(part => part !== undefined && part !== '').join(':')\r\n env.WSLENV = merged\r\n return env\r\n }\r\n\r\n /** Map a plan onto a fully-specified subprocess spawn. */\r\n private spawnSpec(plan: WslPlan, spec: ShellExecSpec, stdoutMaxBytes: number, signal: AbortSignal | undefined): SubprocessSpawnSpec {\r\n const collect = (maxBytes: number): SubprocessCollect =>\r\n ({ maxBytes, spill: { maxBytes: this.config.maxSpillBytes } })\r\n return {\r\n argv: plan.argv,\r\n cwd: plan.windowsCwd,\r\n stdio: {\r\n stdin: spec.stdin !== undefined ? { data: spec.stdin } : 'ignore',\r\n stdout: collect(stdoutMaxBytes),\r\n stderr: collect(this.config.maxOutputBytes),\r\n },\r\n graceMs: this.config.graceMs,\r\n signal,\r\n env: plan.env,\r\n }\r\n }\r\n\r\n /** The collect-mode readers this executor requested (present by construction). */\r\n private static collected(handle: SubprocessHandle): { stdout: SubprocessOutputReader; stderr: SubprocessOutputReader } {\r\n const { stdout, stderr } = handle.collected\r\n /* v8 ignore start -- collect dispositions expose both readers by the seam contract; defensive. */\r\n if (stdout === undefined || stderr === undefined) {\r\n throw new Error('wsl-shell: subprocess implementation dropped a requested collect stream')\r\n }\r\n /* v8 ignore stop */\r\n return { stdout, stderr }\r\n }\r\n\r\n /** Run one command in the foreground. */\r\n async run(spec: ShellExecSpec): Promise<ShellRunResult> {\r\n const plan = this.plan(spec)\r\n using d = deadline(spec.signal, spec.timeoutMs, 'WSL_BASH_TIMEOUT')\r\n const handle = this.ctx.subprocess.spawn(this.spawnSpec(plan, spec, spec.stdoutMaxBytes, d.signal))\r\n const outcome = await handle.done\r\n const collected = WslShellExecutor.collected(handle)\r\n // Only this executor's timeout reason counts as timedOut; outer deadlines count as aborts.\r\n const timedOut = timeoutOf(d.signal, 'WSL_BASH_TIMEOUT') !== undefined\r\n const aborted = d.signal.aborted && !timedOut\r\n return {\r\n ...outcome,\r\n timedOut,\r\n aborted,\r\n timeoutMs: spec.timeoutMs,\r\n stdout: finalOutput(collected.stdout),\r\n stderr: finalOutput(collected.stderr),\r\n }\r\n }\r\n\r\n /** Start one command in the background and return its live handle. */\r\n start(spec: ShellExecSpec): ShellProcess {\r\n const plan = this.plan(spec)\r\n // Background runs ignore timeoutMs; callers stop them through kill() or spec.signal.\r\n const running = this.ctx.subprocess.spawn(this.spawnSpec(plan, spec, this.config.maxOutputBytes, spec.signal))\r\n const collected = WslShellExecutor.collected(running)\r\n\r\n // A spawn failure produces no process output, so the subprocess service has\r\n // nothing to buffer; the note is delivered exactly once through the read path.\r\n let spawnFailureNote: string | undefined\r\n const consumeSpawnFailure = (): string => {\r\n const note = spawnFailureNote ?? ''\r\n spawnFailureNote = undefined\r\n return note\r\n }\r\n\r\n let stdoutOffset = 0\r\n let stderrOffset = 0\r\n const proc: ShellProcess = {\r\n status: 'running',\r\n exitCode: null,\r\n signal: null,\r\n done: running.done.then((outcome) => {\r\n if (proc.status === 'running') {\r\n proc.status = spec.signal?.aborted === true || outcome.signal !== null ? 'killed' : 'completed'\r\n }\r\n proc.exitCode = outcome.exitCode\r\n proc.signal = outcome.signal\r\n }, (error: unknown) => {\r\n proc.status = 'killed'\r\n spawnFailureNote = `spawn failed: ${String(error)}`\r\n }),\r\n readOutput: (): ShellProcessRead => {\r\n const out = collected.stdout.readFrom(stdoutOffset)\r\n const err = collected.stderr.readFrom(stderrOffset)\r\n stdoutOffset = out.nextOffset\r\n stderrOffset = err.nextOffset\r\n const errText = err.text.length > 0 ? err.text : consumeSpawnFailure()\r\n const separator = out.text.length > 0 && !out.text.endsWith('\\n') ? '\\n' : ''\r\n const delta = out.text\r\n + (errText.length > 0 ? `${separator}[stderr]\\n${errText}` : '')\r\n return {\r\n delta,\r\n lossy: out.lossy || err.lossy,\r\n ...out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {},\r\n ...err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {},\r\n }\r\n },\r\n kill: (): boolean => {\r\n if (proc.status !== 'running') return false\r\n proc.status = 'killed'\r\n running.terminate()\r\n return true\r\n },\r\n }\r\n return proc\r\n }\r\n}\r\n\r\nexport default WslShellExecutor\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,gBAAgB;CACpB,UAAU;CACV,MAAM;CACN,OAAO;CACP,WAAW;AACb;;AAGA,MAAM,mBAAmB;;AAGzB,MAAM,0BAA0B,KAAK,OAAO;;AAoC5C,SAAS,YAAY,QAAiD;CACpE,MAAM,OAAO,OAAO,SAAS,CAAC;CAC9B,OAAO;EACL,MAAM,KAAK;EACX,WAAW,KAAK;EAChB,GAAG,KAAK,cAAc,KAAA,IAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;CACrE;AACF;AAEA,SAAS,qBAAqB,MAAc,OAAqB;CAC/D,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,GACtC,MAAM,IAAI,MAAM,cA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IAAI,CAAC;IACzE;GACF;GACA,YAAqB;IACnB,IAAI,KAAK,WAAW,WAAW,OAAO;IACtC,KAAK,SAAS;IACd,QAAQ,UAAU;IAClB,OAAO;GACT;EACF;EACA,OAAO;CACT;AACF"}
@@ -0,0 +1,228 @@
1
+ import { execFile, execFileSync } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ //#region src/shared/paths.ts
4
+ /** The two UNC hosts WSL exposes a distribution's filesystem under. */
5
+ const UNC_HOSTS = ["wsl.localhost", "wsl$"];
6
+ /**
7
+ * Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2
8
+ * `\\wsl.localhost\<distro>\<linux>` form, the legacy `\\wsl$\<distro>\<linux>`
9
+ * interop form, and forward-slash spellings of either.
10
+ * @param raw - candidate absolute path.
11
+ * @returns the parsed target, or null when the path is not a WSL UNC.
12
+ */
13
+ function parseWslUnc(raw) {
14
+ const normalized = raw.replace(/\\/g, "/").replace(/\/\/+/g, "//");
15
+ if (!normalized.startsWith("//")) return null;
16
+ const segments = normalized.slice(2).split("/");
17
+ const host = (segments[0] ?? "").toLowerCase();
18
+ if (!UNC_HOSTS.includes(host)) return null;
19
+ const distro = segments[1] ?? "";
20
+ if (distro === "") return null;
21
+ return {
22
+ distro,
23
+ linuxPath: `/${segments.slice(2).filter((segment) => segment.length > 0).join("/")}`
24
+ };
25
+ }
26
+ /**
27
+ * Normalize a Linux absolute path for the Host: collapse repeated slashes and
28
+ * strip a trailing slash (root becomes `/`).
29
+ * @param path - absolute Linux path.
30
+ * @returns the normalized path.
31
+ */
32
+ function normalizeLinuxPath(path) {
33
+ const collapsed = path.replace(/\/+/g, "/");
34
+ return collapsed === "/" ? "/" : collapsed.replace(/\/$/, "");
35
+ }
36
+ /**
37
+ * Whether a path is an absolute, non-empty Linux path.
38
+ * @param path - candidate.
39
+ * @returns whether it starts with `/` and contains no NUL.
40
+ */
41
+ function isAbsoluteLinuxPath(path) {
42
+ return path.startsWith("/") && !path.includes("\0");
43
+ }
44
+ /**
45
+ * Join a distro and a Linux absolute path into the WSL2 UNC form used as the
46
+ * workspace identity (`\\wsl.localhost\<distro>\<linux>`, backslash segments).
47
+ * @param distro - distro name.
48
+ * @param linuxPath - absolute Linux path (leading `/`).
49
+ * @returns the UNC path.
50
+ */
51
+ function joinUnc(distro, linuxPath) {
52
+ if (!isAbsoluteLinuxPath(linuxPath)) throw new Error(`wsl-workspace: cannot map a non-absolute Linux path "${linuxPath}" to UNC`);
53
+ if (distro === "" || distro === "." || distro === ".." || /[\\/]/.test(distro)) throw new Error(`wsl-workspace: invalid distribution name "${distro}"`);
54
+ const normalized = linuxPath.replace(/\/+/g, "/").replace(/\/$/, "");
55
+ const windowsSegments = (normalized.startsWith("/") ? normalized.slice(1) : normalized).replace(/\//g, "\\");
56
+ return `\\\\wsl.localhost\\${distro}${windowsSegments === "" ? "" : `\\${windowsSegments}`}`;
57
+ }
58
+ /**
59
+ * Translate a Windows drive path to the drvfs mount path WSL distributions
60
+ * conventionally expose it at (`C:\foo` → `/mnt/c/foo`). Only single-letter
61
+ * drives under `/mnt` are mapped; custom mount points are out of scope.
62
+ * @param path - the candidate Windows path.
63
+ * @returns the `/mnt/<drive>/…` path, or `null` for non-drive paths.
64
+ */
65
+ function windowsToMntPath(path) {
66
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(path);
67
+ if (match === null) return null;
68
+ const rest = (match[2] ?? "").replace(/\\/g, "/").replace(/\/+/g, "/").replace(/\/$/, "");
69
+ return `/mnt/${(match[1] ?? "").toLowerCase()}${rest === "" ? "" : `/${rest}`}`;
70
+ }
71
+ /**
72
+ * Translate a `/mnt/<drive>/…` path back to its Windows drive path.
73
+ * @param linuxPath - the candidate Linux path.
74
+ * @returns the `X:\…` drive path, or `null` when the path is not a drvfs mount.
75
+ */
76
+ function mntToWindowsPath(linuxPath) {
77
+ const match = /^\/mnt\/([a-zA-Z])(?:\/(.*))?$/.exec(linuxPath);
78
+ if (match === null) return null;
79
+ const rest = (match[2] ?? "").replace(/\//g, "\\");
80
+ return `${(match[1] ?? "").toUpperCase()}:\\${rest}`;
81
+ }
82
+ /**
83
+ * Canonical Windows drive path for store keys and cross-realm identity:
84
+ * separators unified to `\`, trailing separator stripped, and the WHOLE path
85
+ * lowercased — Windows paths compare case-insensitively, and the workspace
86
+ * registry may realpath a different casing than the caller spelled (8.3 or
87
+ * on-disk casing), so the store key must collide across casings.
88
+ * @param path - candidate Windows drive path.
89
+ * @returns the canonical form, or `null` when not drive-shaped.
90
+ */
91
+ function canonicalWindowsPath(path) {
92
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(path);
93
+ if (match === null) return null;
94
+ const rest = (match[2] ?? "").replace(/[\\/]+/g, "\\").replace(/\\$/, "").toLowerCase();
95
+ return `${(match[1] ?? "").toLowerCase()}:\\${rest}`;
96
+ }
97
+ /**
98
+ * True when a value is a Windows-shaped path (drive or UNC), which is how
99
+ * the shell executor decides the WSLENV `/p` translation flag: only Windows
100
+ * path values need translation when they cross into the Linux process.
101
+ * @param value - the environment value to classify.
102
+ * @returns whether the value looks like a Windows path.
103
+ */
104
+ function isWindowsPathShaped(value) {
105
+ return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
106
+ }
107
+ /** Linux username shape for `wsl.exe -u`: starts with a letter or underscore, then letters/digits/`_`/`.`/`-` (max 64). */
108
+ const WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
109
+ /**
110
+ * Whether a value is a safe Linux username for `wsl.exe -u`. The check is
111
+ * strict on purpose: a value starting with `-` could be parsed as a wsl.exe
112
+ * option instead of a username.
113
+ * @param value - candidate username.
114
+ * @returns whether it matches the Linux username shape.
115
+ */
116
+ function isValidWslUsername(value) {
117
+ return WSL_USERNAME_PATTERN.test(value);
118
+ }
119
+ //#endregion
120
+ //#region src/shared/wsl.ts
121
+ /**
122
+ * WSL discovery helpers (host side): enumerate installed distributions
123
+ * through `wsl.exe -l -q` and read the default distribution from the Lxss
124
+ * registry key. `wsl.exe` output is UTF-16LE on most builds, so decoding
125
+ * sniffs for NUL bytes before choosing an encoding.
126
+ * @module dsh-wsl-workspace/shared/wsl
127
+ */
128
+ const execFileAsync = promisify(execFile);
129
+ /** Executable timeout for the short discovery calls. */
130
+ const DISCOVERY_TIMEOUT_MS = 1e4;
131
+ const LXSS_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss";
132
+ /** Human text for an unknown rejection. */
133
+ function messageOf(value) {
134
+ return value instanceof Error ? value.message : String(value);
135
+ }
136
+ /**
137
+ * Decode `wsl.exe -l -q` output. Newer builds emit UTF-8; most emit UTF-16LE
138
+ * with NUL bytes interleaved — the NUL probe picks the right one.
139
+ * @param buffer - the raw captured output.
140
+ * @returns the decoded text.
141
+ */
142
+ function decodeWslOutput(buffer) {
143
+ return buffer.includes(0) ? buffer.toString("utf16le") : buffer.toString("utf8");
144
+ }
145
+ /**
146
+ * List installed WSL distributions in `wsl.exe` order.
147
+ * @param wslPath - the `wsl.exe` executable (absolute or PATH name).
148
+ * @returns distribution names, blank lines dropped.
149
+ */
150
+ async function listDistros(wslPath = "wsl.exe") {
151
+ let stdout;
152
+ try {
153
+ stdout = (await execFileAsync(wslPath, ["-l", "-q"], {
154
+ encoding: "buffer",
155
+ timeout: DISCOVERY_TIMEOUT_MS
156
+ })).stdout;
157
+ } catch (error) {
158
+ throw new Error(`wsl-workspace: cannot list WSL distributions (${messageOf(error)}); is WSL installed?`);
159
+ }
160
+ return decodeWslOutput(stdout).split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
161
+ }
162
+ /**
163
+ * Read the user's default distribution from the Lxss registry. Non-fatal:
164
+ * returns `undefined` when the value is absent or unreadable (the caller
165
+ * falls back to list order).
166
+ * @returns the default distribution name, or `undefined`.
167
+ */
168
+ async function defaultDistro() {
169
+ try {
170
+ const value = await execFileAsync("reg.exe", [
171
+ "query",
172
+ LXSS_KEY,
173
+ "/v",
174
+ "DefaultDistribution"
175
+ ], { timeout: DISCOVERY_TIMEOUT_MS });
176
+ const guid = /DefaultDistribution\s+REG_SZ\s+(\{[0-9a-fA-F-]+\})/i.exec(value.stdout)?.[1];
177
+ if (guid === void 0) return void 0;
178
+ const name = await execFileAsync("reg.exe", [
179
+ "query",
180
+ `${LXSS_KEY}\\${guid}`,
181
+ "/v",
182
+ "DistributionName"
183
+ ], { timeout: DISCOVERY_TIMEOUT_MS });
184
+ const distro = /DistributionName\s+REG_SZ\s+(.+)/i.exec(name.stdout)?.[1]?.trim();
185
+ return distro === void 0 || distro === "" ? void 0 : distro;
186
+ } catch {
187
+ return;
188
+ }
189
+ }
190
+ /** Module-level cache for {@link defaultDistroSync} (one registry read per process). */
191
+ let syncDefaultResolved = false;
192
+ let syncDefault;
193
+ /**
194
+ * Synchronous variant of {@link defaultDistro} for executors that must
195
+ * resolve a distribution inside a synchronous plan step. Cached after the
196
+ * first read; non-fatal (returns `undefined` when the registry is
197
+ * unreadable, letting the caller fail loud with its own message).
198
+ * @returns the default distribution name, or `undefined`.
199
+ */
200
+ function defaultDistroSync() {
201
+ if (syncDefaultResolved) return syncDefault;
202
+ syncDefaultResolved = true;
203
+ try {
204
+ const value = execFileSync("reg.exe", [
205
+ "query",
206
+ LXSS_KEY,
207
+ "/v",
208
+ "DefaultDistribution"
209
+ ], { timeout: DISCOVERY_TIMEOUT_MS });
210
+ const guid = /DefaultDistribution\s+REG_SZ\s+(\{[0-9a-fA-F-]+\})/i.exec(String(value))?.[1];
211
+ if (guid === void 0) return void 0;
212
+ const name = execFileSync("reg.exe", [
213
+ "query",
214
+ `${LXSS_KEY}\\${guid}`,
215
+ "/v",
216
+ "DistributionName"
217
+ ], { timeout: DISCOVERY_TIMEOUT_MS });
218
+ const distro = /DistributionName\s+REG_SZ\s+(.+)/i.exec(String(name))?.[1]?.trim();
219
+ syncDefault = distro === void 0 || distro === "" ? void 0 : distro;
220
+ } catch {
221
+ syncDefault = void 0;
222
+ }
223
+ return syncDefault;
224
+ }
225
+ //#endregion
226
+ export { isAbsoluteLinuxPath as a, joinUnc as c, parseWslUnc as d, windowsToMntPath as f, canonicalWindowsPath as i, mntToWindowsPath as l, defaultDistroSync as n, isValidWslUsername as o, listDistros as r, isWindowsPathShaped as s, defaultDistro as t, normalizeLinuxPath as u };
227
+
228
+ //# sourceMappingURL=wsl-C5_mxGPM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wsl-C5_mxGPM.js","names":[],"sources":["../src/shared/paths.ts","../src/shared/wsl.ts"],"sourcesContent":["/**\r\n * WSL path helpers shared by the client and host halves. Pure and\r\n * dependency-free so both planes can import them without a runtime edge.\r\n */\r\n\r\n/** WSL2 default loopback bridge host: `\\\\wsl.localhost\\<distro>\\...`. */\r\nconst WSL_LOCALHOST_HOST = 'wsl.localhost'\r\n/** Legacy WSL interop host: `\\\\wsl$\\<distro>\\...`. */\r\nconst WSL_LEGACY_HOST = 'wsl$'\r\n\r\n/** The two UNC hosts WSL exposes a distribution's filesystem under. */\r\nconst UNC_HOSTS = [WSL_LOCALHOST_HOST, WSL_LEGACY_HOST]\r\n\r\n/** One WSL workspace coordinate parsed out of a UNC path. */\r\nexport interface WslUncTarget {\r\n /** Distro name (e.g. `Ubuntu`) as `wsl -l -q` reports it. */\r\n readonly distro: string\r\n /** Normalized absolute Linux path (leading `/`; no trailing slash except root). */\r\n readonly linuxPath: string\r\n}\r\n\r\n/**\r\n * Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2\r\n * `\\\\wsl.localhost\\<distro>\\<linux>` form, the legacy `\\\\wsl$\\<distro>\\<linux>`\r\n * interop form, and forward-slash spellings of either.\r\n * @param raw - candidate absolute path.\r\n * @returns the parsed target, or null when the path is not a WSL UNC.\r\n */\r\nexport function parseWslUnc(raw: string): WslUncTarget | null {\r\n const normalized = raw.replace(/\\\\/g, '/').replace(/\\/\\/+/g, '//')\r\n if (!normalized.startsWith('//')) return null\r\n const segments = normalized.slice(2).split('/')\r\n const host = (segments[0] ?? '').toLowerCase()\r\n if (!UNC_HOSTS.includes(host)) return null\r\n const distro = segments[1] ?? ''\r\n if (distro === '') return null\r\n const rest = segments.slice(2).filter(segment => segment.length > 0)\r\n return { distro, linuxPath: `/${rest.join('/')}` }\r\n}\r\n\r\n/**\r\n * Whether a path resolves into a WSL distro through either UNC form.\r\n * @param raw - candidate absolute path.\r\n * @returns whether the path parses as a WSL UNC.\r\n */\r\nexport function isWslUnc(raw: string): boolean {\r\n return parseWslUnc(raw) !== null\r\n}\r\n\r\n/**\r\n * Translate a WSL UNC path to the absolute Linux path a process inside the\r\n * distribution can open. Throws on non-WSL input: callers rely on this\r\n * conversion to hand paths to the Linux world, so a silent pass-through\r\n * would hand a Windows path to bash.\r\n * @param uncPath - a path {@link parseWslUnc} accepts.\r\n * @returns the absolute Linux path.\r\n */\r\nexport function uncToLinux(uncPath: string): string {\r\n const parts = parseWslUnc(uncPath)\r\n if (parts === null) {\r\n throw new Error(`wsl-workspace: \"${uncPath}\" is not a WSL UNC path`)\r\n }\r\n return parts.linuxPath\r\n}\r\n\r\n/**\r\n * Normalize a Linux absolute path for the Host: collapse repeated slashes and\r\n * strip a trailing slash (root becomes `/`).\r\n * @param path - absolute Linux path.\r\n * @returns the normalized path.\r\n */\r\nexport function normalizeLinuxPath(path: string): string {\r\n const collapsed = path.replace(/\\/+/g, '/')\r\n return collapsed === '/' ? '/' : collapsed.replace(/\\/$/, '')\r\n}\r\n\r\n/**\r\n * Whether a path is an absolute, non-empty Linux path.\r\n * @param path - candidate.\r\n * @returns whether it starts with `/` and contains no NUL.\r\n */\r\nexport function isAbsoluteLinuxPath(path: string): boolean {\r\n return path.startsWith('/') && !path.includes('\\0')\r\n}\r\n\r\n/**\r\n * Join a distro and a Linux absolute path into the WSL2 UNC form used as the\r\n * workspace identity (`\\\\wsl.localhost\\<distro>\\<linux>`, backslash segments).\r\n * @param distro - distro name.\r\n * @param linuxPath - absolute Linux path (leading `/`).\r\n * @returns the UNC path.\r\n */\r\nexport function joinUnc(distro: string, linuxPath: string): string {\r\n if (!isAbsoluteLinuxPath(linuxPath)) {\r\n throw new Error(`wsl-workspace: cannot map a non-absolute Linux path \"${linuxPath}\" to UNC`)\r\n }\r\n // Defense in depth: a distribution name with separators or dot-dirs would\r\n // escape the `\\\\wsl.localhost\\` share structure (the host route validates\r\n // wire-supplied names too; every other caller passes through here).\r\n if (distro === '' || distro === '.' || distro === '..' || /[\\\\/]/.test(distro)) {\r\n throw new Error(`wsl-workspace: invalid distribution name \"${distro}\"`)\r\n }\r\n const normalized = linuxPath.replace(/\\/+/g, '/').replace(/\\/$/, '')\r\n const withoutLeading = normalized.startsWith('/') ? normalized.slice(1) : normalized\r\n const windowsSegments = withoutLeading.replace(/\\//g, '\\\\')\r\n const suffix = windowsSegments === '' ? '' : `\\\\${windowsSegments}`\r\n return `\\\\\\\\wsl.localhost\\\\${distro}${suffix}`\r\n}\r\n\r\n/**\r\n * Translate a Windows drive path to the drvfs mount path WSL distributions\r\n * conventionally expose it at (`C:\\foo` → `/mnt/c/foo`). Only single-letter\r\n * drives under `/mnt` are mapped; custom mount points are out of scope.\r\n * @param path - the candidate Windows path.\r\n * @returns the `/mnt/<drive>/…` path, or `null` for non-drive paths.\r\n */\r\nexport function windowsToMntPath(path: string): string | null {\r\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\r\n if (match === null) return null\r\n const rest = (match[2] ?? '').replace(/\\\\/g, '/').replace(/\\/+/g, '/').replace(/\\/$/, '')\r\n return `/mnt/${(match[1] ?? '').toLowerCase()}${rest === '' ? '' : `/${rest}`}`\r\n}\r\n\r\n/**\r\n * Translate a `/mnt/<drive>/…` path back to its Windows drive path.\r\n * @param linuxPath - the candidate Linux path.\r\n * @returns the `X:\\…` drive path, or `null` when the path is not a drvfs mount.\r\n */\r\nexport function mntToWindowsPath(linuxPath: string): string | null {\r\n const match = /^\\/mnt\\/([a-zA-Z])(?:\\/(.*))?$/.exec(linuxPath)\r\n if (match === null) return null\r\n const rest = (match[2] ?? '').replace(/\\//g, '\\\\')\r\n return `${(match[1] ?? '').toUpperCase()}:\\\\${rest}`\r\n}\r\n\r\n/**\r\n * Canonical Windows drive path for store keys and cross-realm identity:\r\n * separators unified to `\\`, trailing separator stripped, and the WHOLE path\r\n * lowercased — Windows paths compare case-insensitively, and the workspace\r\n * registry may realpath a different casing than the caller spelled (8.3 or\r\n * on-disk casing), so the store key must collide across casings.\r\n * @param path - candidate Windows drive path.\r\n * @returns the canonical form, or `null` when not drive-shaped.\r\n */\r\nexport function canonicalWindowsPath(path: string): string | null {\r\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\r\n if (match === null) return null\r\n const rest = (match[2] ?? '').replace(/[\\\\/]+/g, '\\\\').replace(/\\\\$/, '').toLowerCase()\r\n return `${(match[1] ?? '').toLowerCase()}:\\\\${rest}`\r\n}\r\n\r\n/**\r\n * True when a value is a Windows-shaped path (drive or UNC), which is how\r\n * the shell executor decides the WSLENV `/p` translation flag: only Windows\r\n * path values need translation when they cross into the Linux process.\r\n * @param value - the environment value to classify.\r\n * @returns whether the value looks like a Windows path.\r\n */\r\nexport function isWindowsPathShaped(value: string): boolean {\r\n return /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\r\n}\r\n\r\n/** Linux username shape for `wsl.exe -u`: starts with a letter or underscore, then letters/digits/`_`/`.`/`-` (max 64). */\r\nconst WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/\r\n\r\n/**\r\n * Whether a value is a safe Linux username for `wsl.exe -u`. The check is\r\n * strict on purpose: a value starting with `-` could be parsed as a wsl.exe\r\n * option instead of a username.\r\n * @param value - candidate username.\r\n * @returns whether it matches the Linux username shape.\r\n */\r\nexport function isValidWslUsername(value: string): boolean {\r\n return WSL_USERNAME_PATTERN.test(value)\r\n}\r\n","/**\n * WSL discovery helpers (host side): enumerate installed distributions\n * through `wsl.exe -l -q` and read the default distribution from the Lxss\n * registry key. `wsl.exe` output is UTF-16LE on most builds, so decoding\n * sniffs for NUL bytes before choosing an encoding.\n * @module dsh-wsl-workspace/shared/wsl\n */\n\nimport { execFile, execFileSync } from 'node:child_process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\n/** Executable timeout for the short discovery calls. */\nconst DISCOVERY_TIMEOUT_MS = 10_000\n\nconst LXSS_KEY = 'HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Lxss'\n\n/** Human text for an unknown rejection. */\nfunction messageOf(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Decode `wsl.exe -l -q` output. Newer builds emit UTF-8; most emit UTF-16LE\n * with NUL bytes interleaved — the NUL probe picks the right one.\n * @param buffer - the raw captured output.\n * @returns the decoded text.\n */\nexport function decodeWslOutput(buffer: Buffer): string {\n return buffer.includes(0) ? buffer.toString('utf16le') : buffer.toString('utf8')\n}\n\n/**\n * List installed WSL distributions in `wsl.exe` order.\n * @param wslPath - the `wsl.exe` executable (absolute or PATH name).\n * @returns distribution names, blank lines dropped.\n */\nexport async function listDistros(wslPath = 'wsl.exe'): Promise<string[]> {\n let stdout: Buffer\n try {\n const result = await execFileAsync(wslPath, ['-l', '-q'], { encoding: 'buffer', timeout: DISCOVERY_TIMEOUT_MS })\n stdout = result.stdout as Buffer\n } catch (error) {\n throw new Error(`wsl-workspace: cannot list WSL distributions (${messageOf(error)}); is WSL installed?`)\n }\n return decodeWslOutput(stdout)\n .split(/\\r?\\n/)\n .map(line => line.trim())\n .filter(line => line.length > 0)\n}\n\n/**\n * Read the user's default distribution from the Lxss registry. Non-fatal:\n * returns `undefined` when the value is absent or unreadable (the caller\n * falls back to list order).\n * @returns the default distribution name, or `undefined`.\n */\nexport async function defaultDistro(): Promise<string | undefined> {\n try {\n const value = await execFileAsync('reg.exe', ['query', LXSS_KEY, '/v', 'DefaultDistribution'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const guid = /DefaultDistribution\\s+REG_SZ\\s+(\\{[0-9a-fA-F-]+\\})/i.exec(value.stdout)?.[1]\n if (guid === undefined) return undefined\n const name = await execFileAsync('reg.exe', ['query', `${LXSS_KEY}\\\\${guid}`, '/v', 'DistributionName'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const distro = /DistributionName\\s+REG_SZ\\s+(.+)/i.exec(name.stdout)?.[1]?.trim()\n return distro === undefined || distro === '' ? undefined : distro\n } catch {\n return undefined\n }\n}\n\n/** Module-level cache for {@link defaultDistroSync} (one registry read per process). */\nlet syncDefaultResolved = false\nlet syncDefault: string | undefined\n\n/**\n * Synchronous variant of {@link defaultDistro} for executors that must\n * resolve a distribution inside a synchronous plan step. Cached after the\n * first read; non-fatal (returns `undefined` when the registry is\n * unreadable, letting the caller fail loud with its own message).\n * @returns the default distribution name, or `undefined`.\n */\nexport function defaultDistroSync(): string | undefined {\n if (syncDefaultResolved) return syncDefault\n syncDefaultResolved = true\n try {\n const value = execFileSync('reg.exe', ['query', LXSS_KEY, '/v', 'DefaultDistribution'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const guid = /DefaultDistribution\\s+REG_SZ\\s+(\\{[0-9a-fA-F-]+\\})/i.exec(String(value))?.[1]\n if (guid === undefined) return undefined\n const name = execFileSync('reg.exe', ['query', `${LXSS_KEY}\\\\${guid}`, '/v', 'DistributionName'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const distro = /DistributionName\\s+REG_SZ\\s+(.+)/i.exec(String(name))?.[1]?.trim()\n syncDefault = distro === undefined || distro === '' ? undefined : distro\n } catch {\n syncDefault = undefined\n }\n return syncDefault\n}\n"],"mappings":";;;;AAWA,MAAM,YAAY,CAAC,iBAAoB,MAAe;;;;;;;;AAiBtD,SAAgB,YAAY,KAAkC;CAC5D,MAAM,aAAa,IAAI,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,UAAU,IAAI;CACjE,IAAI,CAAC,WAAW,WAAW,IAAI,GAAG,OAAO;CACzC,MAAM,WAAW,WAAW,MA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