dsh-wsl-workspace 0.3.2 → 0.4.2

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":["/**\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,UAA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xB,GAAG,IAAI,cAAc,KAAA,IAAY,EAAE,iBAAiB,IAAI,UAAU,IAAI,CAAC;KACvE,GAAG,IAAI,cAAc,KAAA,IAAY,EAAE,iBAAiB,IAAI,UAAU,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"}
1
+ {"version":3,"file":"shell.js","names":["n","r","e","o","distro: string","linuxCwd: string","windowsCwd: string","username: string | undefined","env: Record<string, string>","flags: string[]","spawnFailureNote: string | undefined","proc: ShellProcess"],"sources":["../node_modules/.pnpm/@oxc-project+runtime@0.82.3/node_modules/@oxc-project/runtime/src/helpers/usingCtx.js","../src/shell.ts"],"sourcesContent":["function _usingCtx() {\n var r = \"function\" == typeof SuppressedError ? SuppressedError : function (r, e) {\n var n = Error();\n return n.name = \"SuppressedError\", n.error = r, n.suppressed = e, n;\n },\n e = {},\n n = [];\n function using(r, e) {\n if (null != e) {\n if (Object(e) !== e) throw new TypeError(\"using declarations can only be used with objects, functions, null, or undefined.\");\n if (r) var o = e[Symbol.asyncDispose || Symbol[\"for\"](\"Symbol.asyncDispose\")];\n if (void 0 === o && (o = e[Symbol.dispose || Symbol[\"for\"](\"Symbol.dispose\")], r)) var t = o;\n if (\"function\" != typeof o) throw new TypeError(\"Object is not disposable.\");\n t && (o = function o() {\n try {\n t.call(e);\n } catch (r) {\n return Promise.reject(r);\n }\n }), n.push({\n v: e,\n d: o,\n a: r\n });\n } else r && n.push({\n d: e,\n a: r\n });\n return e;\n }\n return {\n e: e,\n u: using.bind(null, !1),\n a: using.bind(null, !0),\n d: function d() {\n var o,\n t = this.e,\n s = 0;\n function next() {\n for (; o = n.pop();) try {\n if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);\n if (o.d) {\n var r = o.d.call(o.v);\n if (o.a) return s |= 2, Promise.resolve(r).then(next, err);\n } else s |= 1;\n } catch (r) {\n return err(r);\n }\n if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();\n if (t !== e) throw t;\n }\n function err(n) {\n return t = t !== e ? new r(n, t) : n, next();\n }\n return next();\n }\n };\n}\nmodule.exports = _usingCtx, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","/**\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"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA,SAAS,YAAY;EACnB,IAAI,IAAI,cAAc,OAAO,kBAAkB,kBAAkB,SAAU,KAAG,KAAG;GAC7E,IAAIA,MAAI;AACR,UAAO,IAAE,OAAO,mBAAmB,IAAE,QAAQC,KAAG,IAAE,aAAaC,KAAGF;KAEpE,IAAI,IACJ,IAAI;EACN,SAAS,MAAM,KAAG,KAAG;AACnB,OAAI,QAAQE,KAAG;AACb,QAAI,OAAOA,SAAOA,IAAG,OAAM,IAAI,UAAU;AACzC,QAAID,KA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GACR,UAAU;GACV,QAAQ;GACR,MAAM,QAAQ,KAAK,MAAM,YAAY;AACnC,QAAI,KAAK,WAAW,UAClB,MAAK,SAAS,KAAK,QAAQ,YAAY,QAAQ,QAAQ,WAAW,OAAO,WAAW;AAEtF,SAAK,WAAW,QAAQ;AACxB,SAAK,SAAS,QAAQ;OACpB,UAAmB;AACrB,SAAK,SAAS;AACd,uBAAmB,iBAAiB,OAAO;;GAE7C,kBAAoC;IAClC,MAAM,MAAM,UAAU,OAAO,SAAS;IACtC,MAAM,MAAM,UAAU,OAAO,SAAS;AACtC,mBAAe,IAAI;AACnB,mBAAe,IAAI;IACnB,MAAM,UAAU,IAAI,KAAK,SAAS,IAAI,IAAI,OAAO;IACjD,MAAM,YAAY,IAAI,KAAK,SAAS,KAAK,CAAC,IAAI,KAAK,SAAS,QAAQ,OAAO;IAC3E,MAAM,QAAQ,IAAI,QACb,QAAQ,SAAS,IAAI,GAAG,UAAU,YAAY,YAAY;AAC/D,WAAO;KACL;KACA,OAAO,IAAI,SAAS,IAAI;KACxB,GAAG,IAAI,cAAc,SAAY,EAAE,iBAAiB,IAAI,cAAc;KACtE,GAAG,IAAI,cAAc,SAAY,EAAE,iBAAiB,IAAI,cAAc;;;GAG1E,YAAqB;AACnB,QAAI,KAAK,WAAW,UAAW,QAAO;AACtC,SAAK,SAAS;AACd,YAAQ;AACR,WAAO;;;AAGX,SAAO;;;AAIX,oBAAe"}
@@ -1,8 +1,17 @@
1
1
  import { execFile, execFileSync } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
+
3
4
  //#region src/shared/paths.ts
5
+ /**
6
+ * WSL path helpers shared by the client and host halves. Pure and
7
+ * dependency-free so both planes can import them without a runtime edge.
8
+ */
9
+ /** WSL2 default loopback bridge host: `\\wsl.localhost\<distro>\...`. */
10
+ const WSL_LOCALHOST_HOST = "wsl.localhost";
11
+ /** Legacy WSL interop host: `\\wsl$\<distro>\...`. */
12
+ const WSL_LEGACY_HOST = "wsl$";
4
13
  /** The two UNC hosts WSL exposes a distribution's filesystem under. */
5
- const UNC_HOSTS = ["wsl.localhost", "wsl$"];
14
+ const UNC_HOSTS = [WSL_LOCALHOST_HOST, WSL_LEGACY_HOST];
6
15
  /**
7
16
  * Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2
8
17
  * `\\wsl.localhost\<distro>\<linux>` form, the legacy `\\wsl$\<distro>\<linux>`
@@ -18,9 +27,10 @@ function parseWslUnc(raw) {
18
27
  if (!UNC_HOSTS.includes(host)) return null;
19
28
  const distro = segments[1] ?? "";
20
29
  if (distro === "") return null;
30
+ const rest = segments.slice(2).filter((segment) => segment.length > 0);
21
31
  return {
22
32
  distro,
23
- linuxPath: `/${segments.slice(2).filter((segment) => segment.length > 0).join("/")}`
33
+ linuxPath: `/${rest.join("/")}`
24
34
  };
25
35
  }
26
36
  /**
@@ -52,8 +62,10 @@ function joinUnc(distro, linuxPath) {
52
62
  if (!isAbsoluteLinuxPath(linuxPath)) throw new Error(`wsl-workspace: cannot map a non-absolute Linux path "${linuxPath}" to UNC`);
53
63
  if (distro === "" || distro === "." || distro === ".." || /[\\/]/.test(distro)) throw new Error(`wsl-workspace: invalid distribution name "${distro}"`);
54
64
  const normalized = linuxPath.replace(/\/+/g, "/").replace(/\/$/, "");
55
- const windowsSegments = (normalized.startsWith("/") ? normalized.slice(1) : normalized).replace(/\//g, "\\");
56
- return `\\\\wsl.localhost\\${distro}${windowsSegments === "" ? "" : `\\${windowsSegments}`}`;
65
+ const withoutLeading = normalized.startsWith("/") ? normalized.slice(1) : normalized;
66
+ const windowsSegments = withoutLeading.replace(/\//g, "\\");
67
+ const suffix = windowsSegments === "" ? "" : `\\${windowsSegments}`;
68
+ return `\\\\wsl.localhost\\${distro}${suffix}`;
57
69
  }
58
70
  /**
59
71
  * Translate a Windows drive path to the drvfs mount path WSL distributions
@@ -116,15 +128,9 @@ const WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
116
128
  function isValidWslUsername(value) {
117
129
  return WSL_USERNAME_PATTERN.test(value);
118
130
  }
131
+
119
132
  //#endregion
120
133
  //#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
134
  const execFileAsync = promisify(execFile);
129
135
  /** Executable timeout for the short discovery calls. */
130
136
  const DISCOVERY_TIMEOUT_MS = 1e4;
@@ -150,10 +156,11 @@ function decodeWslOutput(buffer) {
150
156
  async function listDistros(wslPath = "wsl.exe") {
151
157
  let stdout;
152
158
  try {
153
- stdout = (await execFileAsync(wslPath, ["-l", "-q"], {
159
+ const result = await execFileAsync(wslPath, ["-l", "-q"], {
154
160
  encoding: "buffer",
155
161
  timeout: DISCOVERY_TIMEOUT_MS
156
- })).stdout;
162
+ });
163
+ stdout = result.stdout;
157
164
  } catch (error) {
158
165
  throw new Error(`wsl-workspace: cannot list WSL distributions (${messageOf(error)}); is WSL installed?`);
159
166
  }
@@ -184,7 +191,7 @@ async function defaultDistro() {
184
191
  const distro = /DistributionName\s+REG_SZ\s+(.+)/i.exec(name.stdout)?.[1]?.trim();
185
192
  return distro === void 0 || distro === "" ? void 0 : distro;
186
193
  } catch {
187
- return;
194
+ return void 0;
188
195
  }
189
196
  }
190
197
  /** Module-level cache for {@link defaultDistroSync} (one registry read per process). */
@@ -222,7 +229,7 @@ function defaultDistroSync() {
222
229
  }
223
230
  return syncDefault;
224
231
  }
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
232
 
228
- //# sourceMappingURL=wsl-C5_mxGPM.js.map
233
+ //#endregion
234
+ export { canonicalWindowsPath, defaultDistro, defaultDistroSync, isAbsoluteLinuxPath, isValidWslUsername, isWindowsPathShaped, joinUnc, listDistros, mntToWindowsPath, normalizeLinuxPath, parseWslUnc, windowsToMntPath };
235
+ //# sourceMappingURL=wsl-6VcgOvF9.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wsl-6VcgOvF9.js","names":["stdout: Buffer","syncDefault: string | undefined"],"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":";;;;;;;;;AAMA,MAAM,qBAAqB;;AAE3B,MAAM,kBAAkB;;AAGxB,MAAM,YAAY,CAAC,oBAAoB;;;;;;;;AAiBvC,SAAgB,YAAY,KAAkC;CAC5D,MAAM,aAAa,IAAI,QAAQ,OAAO,KAAK,QAAQ,UAAU;AAC7D,KAAI,CAAC,WAAW,WAAW,MAAO,QAAO;CACzC,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S;GAAU;GAAM;KAAwB,EAC7F,SAAS;EAEX,MAAM,OAAO,sDAAsD,KAAK,MAAM,UAAU;AACxF,MAAI,SAAS,OAAW,QAAO;EAC/B,MAAM,OAAO,MAAM,cAAc,WAAW;GAAC;GAAS,GAAG,SAAS,IAAI;GAAQ;GAAM;KAAqB,EACvG,SAAS;EAEX,MAAM,SAAS,oCAAoC,KAAK,KAAK,UAAU,IAAI;AAC3E,SAAO,WAAW,UAAa,WAAW,KAAK,SAAY;SACrD;AACN,SAAO;;;;AAKX,IAAI,sBAAsB;AAC1B,IAAIC;;;;;;;;AASJ,SAAgB,oBAAwC;AACtD,KAAI,oBAAqB,QAAO;AAChC,uBAAsB;AACtB,KAAI;EACF,MAAM,QAAQ,aAAa,WAAW;GAAC;GAAS;GAAU;GAAM;KAAwB,EACtF,SAAS;EAEX,MAAM,OAAO,sDAAsD,KAAK,OAAO,UAAU;AACzF,MAAI,SAAS,OAAW,QAAO;EAC/B,MAAM,OAAO,aAAa,WAAW;GAAC;GAAS,GAAG,SAAS,IAAI;GAAQ;GAAM;KAAqB,EAChG,SAAS;EAEX,MAAM,SAAS,oCAAoC,KAAK,OAAO,SAAS,IAAI;AAC5E,gBAAc,WAAW,UAAa,WAAW,KAAK,SAAY;SAC5D;AACN,gBAAc;;AAEhB,QAAO"}
@@ -1,20 +1,13 @@
1
- import { c as joinUnc, d as parseWslUnc, i as canonicalWindowsPath, o as isValidWslUsername } from "./wsl-C5_mxGPM.js";
1
+ import { canonicalWindowsPath, isValidWslUsername, joinUnc, parseWslUnc } from "./wsl-6VcgOvF9.js";
2
2
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { homedir } from "node:os";
5
+
5
6
  //#region src/shared/wsl-credentials.ts
6
- /**
7
- * Per-workspace WSL credentials (host side only). The dialog stores the
8
- * optional Linux username of a WSL workspace under the harness home; the
9
- * per-session env contributor and the WSL shell executor read it back so
10
- * `wsl.exe -u <username>` can run commands as that user. Keys are canonical
11
- * UNC workspace paths. This module touches node builtins, so the browser
12
- * half never imports it.
13
- * @module dsh-wsl-workspace/shared/wsl-credentials
14
- */
15
7
  /** The store file lives under the harness home so both host halves share it. */
16
8
  function storePath() {
17
- return join(process.env.DSH_HOME ?? join(homedir(), ".dsh"), "wsl-workspaces.json");
9
+ const dshHome = process.env.DSH_HOME ?? join(homedir(), ".dsh");
10
+ return join(dshHome, "wsl-workspaces.json");
18
11
  }
19
12
  /** Read the store; a missing or corrupt file reads as empty (never throws). */
20
13
  function readStore() {
@@ -103,7 +96,7 @@ function getWindowsWorkspace(winPath) {
103
96
  function listWorkspaceKeys() {
104
97
  return Object.keys(readStore());
105
98
  }
106
- //#endregion
107
- export { registerWindowsWorkspace as a, listWorkspaceKeys as i, getWindowsWorkspace as n, setWorkspaceUsername as o, getWorkspaceUsername as r, canonicalWslUnc as t };
108
99
 
109
- //# sourceMappingURL=wsl-credentials-BI4v5TNZ.js.map
100
+ //#endregion
101
+ export { canonicalWslUnc, getWindowsWorkspace, getWorkspaceUsername, listWorkspaceKeys, registerWindowsWorkspace, setWorkspaceUsername };
102
+ //# sourceMappingURL=wsl-credentials-B6wIXsKt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wsl-credentials-B6wIXsKt.js","names":["parsed: unknown","entry: WorkspaceEntry"],"sources":["../src/shared/wsl-credentials.ts"],"sourcesContent":["/**\r\n * Per-workspace WSL credentials (host side only). The dialog stores the\r\n * optional Linux username of a WSL workspace under the harness home; the\r\n * per-session env contributor and the WSL shell executor read it back so\r\n * `wsl.exe -u <username>` can run commands as that user. Keys are canonical\r\n * UNC workspace paths. This module touches node builtins, so the browser\r\n * half never imports it.\r\n * @module dsh-wsl-workspace/shared/wsl-credentials\r\n */\r\n\r\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\r\nimport { homedir } from 'node:os'\r\nimport { dirname, join } from 'node:path'\r\nimport { canonicalWindowsPath, isValidWslUsername, joinUnc, parseWslUnc } from './paths.ts'\r\n\r\n/** One workspace's stored credentials. */\r\ninterface WorkspaceEntry {\r\n /** The Linux user bash runs as inside the distribution (absent = distro default). */\r\n username?: string\r\n /**\r\n * The WSL distribution of a Windows-drive workspace (`/mnt/<drive>` path).\r\n * 9P cannot serve drvfs mounts, so such workspaces register under their\r\n * Windows drive path; this entry is what the per-session env contributor\r\n * uses to hand a distro to the shell executor.\r\n */\r\n distro?: string\r\n}\r\n\r\n/** The stored form: canonical UNC or Windows drive workspace path → credentials. */\r\ntype WorkspaceStore = Record<string, WorkspaceEntry>\r\n\r\n/** The store file lives under the harness home so both host halves share it. */\r\nfunction storePath(): string {\r\n const dshHome = process.env.DSH_HOME ?? join(homedir(), '.dsh')\r\n return join(dshHome, 'wsl-workspaces.json')\r\n}\r\n\r\n/** Read the store; a missing or corrupt file reads as empty (never throws). */\r\nfunction readStore(): WorkspaceStore {\r\n try {\r\n const parsed: unknown = JSON.parse(readFileSync(storePath(), 'utf8'))\r\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return {}\r\n return parsed as WorkspaceStore\r\n } catch {\r\n return {}\r\n }\r\n}\r\n\r\n/**\r\n * Canonicalize any accepted WSL UNC spelling into the store's key form.\r\n * @param path - candidate workspace path (either UNC host form).\r\n * @returns the canonical UNC path, or null when the path is not a WSL UNC.\r\n */\r\nexport function canonicalWslUnc(path: string): string | null {\r\n const parsed = parseWslUnc(path)\r\n return parsed === null ? null : joinUnc(parsed.distro, parsed.linuxPath)\r\n}\r\n\r\n/**\r\n * Read the stored username for a WSL workspace.\r\n * @param uncPath - the workspace path (any accepted WSL UNC spelling).\r\n * @returns the username, or undefined when none is stored.\r\n */\r\nexport function getWorkspaceUsername(uncPath: string): string | undefined {\r\n const key = canonicalWslUnc(uncPath)\r\n if (key === null) return undefined\r\n const username = readStore()[key]?.username\r\n return username === undefined || username === '' ? undefined : username\r\n}\r\n\r\n/**\r\n * Store (or clear) the username of a WSL workspace.\r\n * @param uncPath - the workspace path (any accepted WSL UNC spelling).\r\n * @param username - the username; empty or undefined clears the stored value.\r\n */\r\nexport function setWorkspaceUsername(uncPath: string, username: string | undefined): void {\r\n const key = canonicalWslUnc(uncPath)\r\n if (key === null) throw new Error('wsl-workspace: workspace path is not a WSL UNC path')\r\n const store = readStore()\r\n if (username === undefined || username.trim() === '') {\r\n delete store[key]\r\n } else {\r\n const trimmed = username.trim()\r\n if (!isValidWslUsername(trimmed)) {\r\n throw new Error('wsl-workspace: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\r\n }\r\n store[key] = { username: trimmed }\r\n }\r\n const path = storePath()\r\n mkdirSync(dirname(path), { recursive: true })\r\n writeFileSync(path, JSON.stringify(store, null, 2) + '\\n', 'utf8')\r\n}\r\n\r\n/**\r\n * Register the WSL distribution (and optional Linux username) of a\r\n * Windows-drive workspace (`/mnt/<drive>` path). Keys are canonical Windows\r\n * drive paths; the per-session env contributor reads the entry back so\r\n * `wsl.exe -d <distro>` can run when the session cwd is a drive path.\r\n * @param winPath - the Windows drive path (any spelling).\r\n * @param distro - the WSL distribution the workspace belongs to.\r\n * @param username - optional Linux username (distro default when absent).\r\n */\r\nexport function registerWindowsWorkspace(winPath: string, distro: string, username: string | undefined): void {\r\n const key = canonicalWindowsPath(winPath)\r\n if (key === null) throw new Error('wsl-workspace: workspace path is not a Windows drive path')\r\n const entry: WorkspaceEntry = { distro }\r\n if (username !== undefined && username.trim() !== '') {\r\n const trimmed = username.trim()\r\n if (!isValidWslUsername(trimmed)) {\r\n throw new Error('wsl-workspace: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\r\n }\r\n entry.username = trimmed\r\n }\r\n const store = readStore()\r\n store[key] = entry\r\n const path = storePath()\r\n mkdirSync(dirname(path), { recursive: true })\r\n writeFileSync(path, JSON.stringify(store, null, 2) + '\\n', 'utf8')\r\n}\r\n\r\n/**\r\n * Read the stored credentials of a Windows-drive workspace.\r\n * @param winPath - the Windows drive path (any spelling).\r\n * @returns the stored entry, or undefined when none is registered.\r\n */\r\nexport function getWindowsWorkspace(winPath: string): WorkspaceEntry | undefined {\r\n const key = canonicalWindowsPath(winPath)\r\n if (key === null) return undefined\r\n return readStore()[key]\r\n}\r\n\r\n/** Every stored workspace key (canonical UNC and Windows drive paths). */\r\nexport function listWorkspaceKeys(): string[] {\r\n return Object.keys(readStore())\r\n}\r\n"],"mappings":";;;;;;;AAgCA,SAAS,YAAoB;CAC3B,MAAM,UAAU,QAAQ,IAAI,YAAY,KAAK,WAAW;AACxD,QAAO,KAAK,SAAS;;;AAIvB,SAAS,YAA4B;AACnC,KAAI;EACF,MAAMA,SAAkB,KAAK,MAAM,aAAa,aAAa;AAC7D,MAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,QAAS,QAAO;AACnF,SAAO;SACD;AACN,SAAO;;;;;;;;AASX,SAAgB,gBAAgB,MAA6B;CAC3D,MAAM,SAAS,YAAY;AAC3B,QAAO,WAAW,OAAO,OAAO,QAAQ,OAAO,QAAQ,OAAO;;;;;;;AAQhE,SAAgB,qBAAqB,SAAqC;CACxE,MAAM,MAAM,gBAAgB;AAC5B,KAAI,QAAQ,KAAM,QAAO;CACzB,MAAM,WAAW,YAAY,MAAM;AACnC,QAAO,aAAa,UAAa,aAAa,KAAK,SAAY;;;;;;;AAQjE,SAAgB,qBAAqB,SAAiB,UAAoC;CACxF,MAAM,MAAM,gBAAgB;AAC5B,KAAI,QAAQ,KAAM,OAAM,IAAI,MAAM;CAClC,MAAM,QAAQ;AACd,KAAI,aAAa,UAAa,SAAS,WAAW,GAChD,QAAO,MAAM;MACR;EACL,MAAM,UAAU,SAAS;AACzB,MAAI,CAAC,mBAAmB,SACtB,OAAM,IAAI,MAAM;AAElB,QAAM,OAAO,EAAE,UAAU;;CAE3B,MAAM,OAAO;AACb,WAAU,QAAQ,OAAO,EAAE,WAAW;AACtC,eAAc,MAAM,KAAK,UAAU,OAAO,MAAM,KAAK,MAAM;;;;;;;;;;;AAY7D,SAAgB,yBAAyB,SAAiB,QAAgB,UAAoC;CAC5G,MAAM,MAAM,qBAAqB;AACjC,KAAI,QAAQ,KAAM,OAAM,IAAI,MAAM;CAClC,MAAMC,QAAwB,EAAE;AAChC,KAAI,aAAa,UAAa,SAAS,WAAW,IAAI;EACpD,MAAM,UAAU,SAAS;AACzB,MAAI,CAAC,mBAAmB,SACtB,OAAM,IAAI,MAAM;AAElB,QAAM,WAAW;;CAEnB,MAAM,QAAQ;AACd,OAAM,OAAO;CACb,MAAM,OAAO;AACb,WAAU,QAAQ,OAAO,EAAE,WAAW;AACtC,eAAc,MAAM,KAAK,UAAU,OAAO,MAAM,KAAK,MAAM;;;;;;;AAQ7D,SAAgB,oBAAoB,SAA6C;CAC/E,MAAM,MAAM,qBAAqB;AACjC,KAAI,QAAQ,KAAM,QAAO;AACzB,QAAO,YAAY;;;AAIrB,SAAgB,oBAA8B;AAC5C,QAAO,OAAO,KAAK"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-wsl-workspace",
3
3
  "description": "WSL workspace support for DeepSeek Harness: add a WSL workspace from the web GUI and run the whole agent session (bash + file tools) inside the WSL distribution, VS Code Remote-WSL style. No toolchain install inside WSL required.",
4
- "version": "0.3.2",
4
+ "version": "0.4.2",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -31,9 +31,27 @@
31
31
  "@deepseek-ai/dsh-client-locale",
32
32
  "@deepseek-ai/dsh-client-ui-sidebar"
33
33
  ]
34
+ },
35
+ "compatibility": {
36
+ "dshReleases": {
37
+ "0.1.0-rc.7": "compatible",
38
+ "0.1.0-rc.8": "compatible",
39
+ "0.1.1-rc.1": "compatible",
40
+ "0.1.1-rc.2": "compatible",
41
+ "0.1.2-rc.1": "compatible",
42
+ "0.1.3-alpha.2": "compatible"
43
+ }
34
44
  }
35
45
  },
36
46
  "license": "MIT",
47
+ "devDependencies": {
48
+ "tsdown": "^0.13.5",
49
+ "typescript": "^5.8.3",
50
+ "@types/node": "^22.15.21"
51
+ },
52
+ "engines": {
53
+ "node": ">=24"
54
+ },
37
55
  "keywords": [
38
56
  "deepseek-harness",
39
57
  "dsh",
@@ -11,10 +11,11 @@
11
11
  * hero picker) converges on the WSL-backed composition automatically.
12
12
  */
13
13
 
14
- import type { ConnectionHandle } from '@deepseek-ai/dsh-api-remotes/client'
15
- // Type-only: pulls the locale plugin's Context merge (ctx.locale), the
16
- // runtime's ClientContext, and the ui-sidebar SlotMap merge (the
17
- // 'sidebar.footer.action' entry) into this program.
14
+ // Type-only: pulls the locale plugin's Context merge (ctx.locale) and the
15
+ // ui-sidebar SlotMap merge (the 'sidebar.footer.action' entry) into this
16
+ // program. Version-dependent services (`remote`, `connection.api`,
17
+ // `uiWorkspace`) are read dynamically via ctx.get() so both DSH v0.1.1-rc.2
18
+ // and v0.1.2-rc.1+ can load this plugin.
18
19
  import type {} from '@deepseek-ai/dsh-client-locale/client'
19
20
  import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'
20
21
  import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
@@ -25,7 +26,7 @@ import { zh, en } from './locales.ts'
25
26
  import { canonicalWindowsPath, isWslUnc, joinUnc, mntToWindowsPath } from '../shared/paths.ts'
26
27
 
27
28
  /** Required services (cordis fiber inject). */
28
- export const inject = ['slots', 'locale', 'connection', 'sessions', 'workspaces']
29
+ export const inject = ['slots', 'locale', 'sessions', 'workspaces']
29
30
 
30
31
  /** The legacy standalone WSL preset id (folded into the mode variants). */
31
32
  const LEGACY_WSL_PRESET_ID = 'wsl'
@@ -38,26 +39,141 @@ const LEGACY_WSL_PRESET_ID = 'wsl'
38
39
  */
39
40
  interface WslSessionsFace {
40
41
  list: {
41
- getSnapshot(): { ids: string[]; byId: Record<string, { blank: boolean; cwd?: string; agentPreset?: string }> }
42
+ getSnapshot(): {
43
+ ids: string[]
44
+ byId: Record<string, {
45
+ blank: boolean
46
+ cwd?: string
47
+ /** v0.1.1-rc.2 direct field */
48
+ agentPreset?: string
49
+ /** v0.1.2-rc.1+ projection value */
50
+ projectionValues?: Readonly<{ agentPreset?: string | null }>
51
+ }>
52
+ }
42
53
  subscribe(fn: () => void): () => void
43
54
  }
44
- noteAgentPreset(sessionId: string, agentPreset: string): void
55
+ /** v0.1.1-rc.2 only — absent in v0.1.2-rc.1+ (projection auto-syncs). */
56
+ noteAgentPreset?(sessionId: string, agentPreset: string): void
45
57
  }
46
58
 
47
- /** Minimal workspaces-service face (create + start-session only). */
59
+ /** Minimal workspaces-service face (create only; startSession moved out in v0.1.2-rc.1+). */
48
60
  interface WslWorkspacesFace {
49
61
  create(input: { path: string }): Promise<{ workspaceId: string }>
62
+ /** v0.1.1-rc.2 only — removed in v0.1.2-rc.1+. */
63
+ startSession?(workspaceId?: string): void
64
+ }
65
+
66
+ /** v0.1.2-rc.1+ only — replaces `workspaces.startSession`. */
67
+ interface WslUiWorkspaceFace {
50
68
  startSession(workspaceId?: string): void
51
69
  }
52
70
 
71
+ /** v0.1.2-rc.1+ agentPresets 命名空间服务(经 ctx.get('remote.agentPresets') 动态取,免 inject、无 associate 陷阱)。 */
72
+ interface WslAgentPresetsNamespace {
73
+ list(): Promise<{ ok: boolean; value?: { presets: { id: string; broken?: string; isDefault?: boolean }[] }; error?: { message: string } }>
74
+ select(sessionId: string, presetId: string): Promise<{ ok: boolean }>
75
+ }
76
+
77
+ /** 旧版 connection 服务最小接口(v0.1.1-rc.2 及更早),api 属性承载远程调用。 */
78
+ interface WslLegacyConnection {
79
+ api?: {
80
+ agentPresets: {
81
+ list(input: Record<string, never>): Promise<{ result: { ok: boolean; value?: { presets: { id: string; broken?: string; isDefault?: boolean }[] }; error?: { message: string } } }>
82
+ select(input: { sessionId: string; agentPreset: string }): Promise<{ result: { ok: boolean } }>
83
+ }
84
+ }
85
+ }
53
86
  /**
54
87
  * Mount the sidebar action and the auto-binding effect.
55
88
  * @param ctx - the browser plugin context.
56
89
  */
57
90
  export function apply(ctx: ClientContext): void {
58
- const { api } = ctx.get('connection') as ConnectionHandle
59
91
  const workspaces = ctx.get('workspaces') as unknown as WslWorkspacesFace
60
92
  const sessions = ctx.get('sessions') as unknown as WslSessionsFace
93
+ // Version-dependent services are resolved ON USE - never through `inject`
94
+ // (a release without the service would refuse to mount the plugin at all)
95
+ // and never once at apply time. This plugin applies before the UI domain
96
+ // that publishes `uiWorkspace` registers its service, so a one-shot read
97
+ // caches `undefined` for the whole page life: on v0.1.2-rc.1+ that silently
98
+ // disabled session creation (see resolveSessionStarter).
99
+ const legacyApi = (): WslLegacyConnection['api'] =>
100
+ (ctx.get('connection') as unknown as WslLegacyConnection | undefined)?.api
101
+ const remoteAgentPresets = (): WslAgentPresetsNamespace | undefined =>
102
+ ctx.get('remote.agentPresets') as unknown as WslAgentPresetsNamespace | undefined
103
+ const uiWorkspaceService = (): WslUiWorkspaceFace | undefined =>
104
+ ctx.get('uiWorkspace') as unknown as WslUiWorkspaceFace | undefined
105
+ const hasNoteAgentPreset = typeof sessions.noteAgentPreset === 'function'
106
+
107
+ /** Unified agent-preset list: new `remote.agentPresets` namespace (v0.1.2-rc.1+) or legacy `connection.api` (v0.1.1-rc.2). */
108
+ const listAgentPresets = async (): Promise<{ ok: boolean; presets: { id: string; broken?: string; isDefault?: boolean }[]; error?: string }> => {
109
+ const agentPresets = remoteAgentPresets()
110
+ if (agentPresets !== undefined) {
111
+ const r = await agentPresets.list()
112
+ if (!r.ok) return { ok: false, presets: [], error: r.error?.message ?? 'list failed' }
113
+ return { ok: true, presets: r.value?.presets ?? [] }
114
+ }
115
+ const api = legacyApi()
116
+ if (api !== undefined) {
117
+ const r = await api.agentPresets.list({})
118
+ if (!r.result.ok) return { ok: false, presets: [], error: r.result.error?.message ?? 'list failed' }
119
+ return { ok: true, presets: r.result.value?.presets ?? [] }
120
+ }
121
+ return { ok: false, presets: [], error: 'no remote api available' }
122
+ }
123
+
124
+ /** Unified agent-preset select: new `agentPresets.select(id, preset)` or legacy `connection.api.select({...})`. */
125
+ const selectAgentPreset = async (sessionId: string, presetId: string): Promise<{ ok: boolean }> => {
126
+ const agentPresets = remoteAgentPresets()
127
+ if (agentPresets !== undefined) {
128
+ return agentPresets.select(sessionId, presetId)
129
+ }
130
+ const api = legacyApi()
131
+ if (api !== undefined) {
132
+ const r = await api.agentPresets.select({ sessionId, agentPreset: presetId })
133
+ return { ok: r.result.ok }
134
+ }
135
+ return { ok: false }
136
+ }
137
+
138
+ /**
139
+ * Resolve how this release opens a session for a workspace - v0.1.2-rc.1+
140
+ * exposes `uiWorkspace.startSession`, v0.1.1-rc.2 keeps it on `workspaces`.
141
+ *
142
+ * Resolved BEFORE the workspace is written. A release that offers neither
143
+ * cannot open a session, and a silent fall-through would leave the workspace
144
+ * behind with an empty `sessionIds` while the dialog still reports success;
145
+ * failing here names the missing capability instead.
146
+ * @returns the starter for the service this release actually exposes.
147
+ * @throws Error naming both candidates when neither service is available.
148
+ */
149
+ const resolveSessionStarter = (): (workspaceId: string) => void | Promise<void> => {
150
+ const ui = uiWorkspaceService()
151
+ if (ui !== undefined) return (workspaceId) => { ui.startSession(workspaceId) }
152
+ const legacyStart = workspaces.startSession
153
+ if (typeof legacyStart === 'function') {
154
+ return (workspaceId) => { Reflect.apply(legacyStart, workspaces, [workspaceId]) }
155
+ }
156
+ throw new Error(
157
+ 'workspace session API unavailable: this DSH release exposes neither '
158
+ + 'uiWorkspace.startSession nor workspaces.startSession',
159
+ )
160
+ }
161
+
162
+ /** Read agent preset — v0.1.2-rc.1+ uses projectionValues; v0.1.1-rc.2 uses direct field. */
163
+ const getAgentPreset = (summary: { agentPreset?: string; projectionValues?: { agentPreset?: string | null } }): string | undefined => {
164
+ if (summary.projectionValues?.agentPreset !== undefined) {
165
+ const v = summary.projectionValues.agentPreset
166
+ return v === null ? undefined : v
167
+ }
168
+ return summary.agentPreset
169
+ }
170
+
171
+ /** Note preset change — v0.1.1-rc.2 calls noteAgentPreset; v0.1.2-rc.1+ is auto-synced via projection. */
172
+ const noteAgentPresetCompat = (sessionId: string, presetId: string): void => {
173
+ if (hasNoteAgentPreset && sessions.noteAgentPreset) {
174
+ sessions.noteAgentPreset(sessionId, presetId)
175
+ }
176
+ }
61
177
 
62
178
  ensureStyles()
63
179
 
@@ -80,13 +196,12 @@ export function apply(ctx: ClientContext): void {
80
196
  checkPreset: async (): Promise<string | undefined> => {
81
197
  let roster
82
198
  try {
83
- const response = await api.agentPresets.list({})
84
- roster = response.result
199
+ roster = await listAgentPresets()
85
200
  } catch (error) {
86
201
  return error instanceof Error ? error.message : String(error)
87
202
  }
88
- if (!roster.ok) return roster.error.message
89
- const healthy = roster.value.presets.find((entry: { id: string; broken?: string }) =>
203
+ if (!roster.ok) return roster.error
204
+ const healthy = roster.presets.find((entry: { id: string; broken?: string }) =>
90
205
  entry.id.startsWith('wsl-') && entry.broken === undefined)
91
206
  if (healthy === undefined) return t('error.presetMissing')
92
207
  return undefined
@@ -96,6 +211,9 @@ export function apply(ctx: ClientContext): void {
96
211
  check: (distro, path) => checkApi(distro, path),
97
212
  createWorkspace: async (linuxPath, username, distro): Promise<string | undefined> => {
98
213
  try {
214
+ // Before any write: without a session starter the workspace below
215
+ // would be created and never opened.
216
+ const startSession = resolveSessionStarter()
99
217
  const winPath = mntToWindowsPath(linuxPath)
100
218
  if (winPath !== null) {
101
219
  // `/mnt/<drive>` workspace: the workspace registry realpath/stats
@@ -106,13 +224,13 @@ export function apply(ctx: ClientContext): void {
106
224
  await registerWindowsApi(linuxPath, distro, username)
107
225
  const canonical = canonicalWindowsPath(winPath)
108
226
  if (canonical !== null) wslWindowsPaths = new Set(wslWindowsPaths).add(canonical)
109
- workspaces.startSession(view.workspaceId)
227
+ await startSession(view.workspaceId)
110
228
  return undefined
111
229
  }
112
230
  const uncPath = joinUnc(distro, linuxPath)
113
231
  const view = await workspaces.create({ path: uncPath })
114
232
  await setWorkspaceUserApi(uncPath, username)
115
- workspaces.startSession(view.workspaceId)
233
+ await startSession(view.workspaceId)
116
234
  return undefined
117
235
  } catch (error) {
118
236
  return error instanceof Error ? error.message : String(error)
@@ -147,18 +265,22 @@ export function apply(ctx: ClientContext): void {
147
265
  let variants = new Set<string>()
148
266
  let defaultPreset: string | undefined
149
267
  const refreshRoster = (): void => {
150
- void api.agentPresets.list({}).then((response: {
151
- result: { ok: boolean; value: { presets: { id: string; broken?: string; isDefault?: boolean }[] } }
268
+ void listAgentPresets().then((result: {
269
+ ok: boolean; presets: { id: string; broken?: string; isDefault?: boolean }[]
152
270
  }) => {
153
- const result = response.result
154
271
  if (!result.ok) return
155
- variants = new Set(result.value.presets
272
+ variants = new Set(result.presets
156
273
  .filter((entry: { id: string; broken?: string }) =>
157
274
  entry.broken === undefined && entry.id.startsWith('wsl-'))
158
275
  .map((entry: { id: string }) => entry.id))
159
- defaultPreset = result.value.presets.find(
276
+ defaultPreset = result.presets.find(
160
277
  (entry: { id: string; isDefault?: boolean }) => entry.isDefault === true,
161
278
  )?.id
279
+ // The roster is an INPUT to binding. It can land after the first pass
280
+ // (and after apply()), and nothing else would re-run that pass: the
281
+ // session store only emits when a session changes, so a blank session
282
+ // that was already there would stay unbound until the user acted.
283
+ maybeBind()
162
284
  }).catch(() => {
163
285
  // A failed roster read leaves the previous mapping; sessions stay on
164
286
  // their current composition until the next refresh.
@@ -173,6 +295,9 @@ export function apply(ctx: ClientContext): void {
173
295
  if (canonical !== null) next.add(canonical)
174
296
  }
175
297
  wslWindowsPaths = next
298
+ // Same late-input rule as the roster: the `/mnt/<drive>` key set
299
+ // decides binding for drive-cwd sessions.
300
+ maybeBind()
176
301
  }).catch(() => {
177
302
  // A failed store read leaves the previous set; sessions stay on
178
303
  // their current composition until the next refresh.
@@ -191,7 +316,7 @@ export function apply(ctx: ClientContext): void {
191
316
  const isWsl = isWslUnc(summary.cwd)
192
317
  || (canonical !== null && wslWindowsPaths.has(canonical))
193
318
  if (!isWsl) continue
194
- const current = summary.agentPreset
319
+ const current = getAgentPreset(summary)
195
320
  if (current !== undefined && current.startsWith('wsl-')) continue
196
321
  // Legacy standalone `wsl` (now folded into the variants): remap it to
197
322
  // the default mode's variant, since the standalone preset no longer
@@ -204,9 +329,9 @@ export function apply(ctx: ClientContext): void {
204
329
  if (!variants.has(target)) continue
205
330
  if (inFlight.has(id) || (attempts.get(id) ?? 0) >= MAX_ATTEMPTS) continue
206
331
  inFlight.add(id)
207
- void api.agentPresets.select({ sessionId: id, agentPreset: target })
208
- .then((response: { result: { ok: boolean } }) => {
209
- if (response.result.ok) sessions.noteAgentPreset(id, target)
332
+ void selectAgentPreset(id, target)
333
+ .then((result: { ok: boolean }) => {
334
+ if (result.ok) noteAgentPresetCompat(id, target)
210
335
  })
211
336
  .catch(() => {
212
337
  // A refused or aborted swap (session already produced output,