dsh-wsl-workspace 0.4.3 → 0.7.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.
@@ -1 +1 @@
1
- {"version":3,"file":"wsl-6VcgOvF9.js","names":["stdout: Buffer","syncDefault: string | undefined"],"sources":["../src/shared/paths.ts","../src/shared/wsl.ts"],"sourcesContent":["/**\n * WSL path helpers shared by the client and host halves. Pure and\n * dependency-free so both planes can import them without a runtime edge.\n */\n\n/** WSL2 default loopback bridge host: `\\\\wsl.localhost\\<distro>\\...`. */\nconst WSL_LOCALHOST_HOST = 'wsl.localhost'\n/** Legacy WSL interop host: `\\\\wsl$\\<distro>\\...`. */\nconst WSL_LEGACY_HOST = 'wsl$'\n\n/** The two UNC hosts WSL exposes a distribution's filesystem under. */\nconst UNC_HOSTS = [WSL_LOCALHOST_HOST, WSL_LEGACY_HOST]\n\n/** One WSL workspace coordinate parsed out of a UNC path. */\nexport interface WslUncTarget {\n /** Distro name (e.g. `Ubuntu`) as `wsl -l -q` reports it. */\n readonly distro: string\n /** Normalized absolute Linux path (leading `/`; no trailing slash except root). */\n readonly linuxPath: string\n}\n\n/**\n * Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2\n * `\\\\wsl.localhost\\<distro>\\<linux>` form, the legacy `\\\\wsl$\\<distro>\\<linux>`\n * interop form, and forward-slash spellings of either.\n * @param raw - candidate absolute path.\n * @returns the parsed target, or null when the path is not a WSL UNC.\n */\nexport function parseWslUnc(raw: string): WslUncTarget | null {\n const normalized = raw.replace(/\\\\/g, '/').replace(/\\/\\/+/g, '//')\n if (!normalized.startsWith('//')) return null\n const segments = normalized.slice(2).split('/')\n const host = (segments[0] ?? '').toLowerCase()\n if (!UNC_HOSTS.includes(host)) return null\n const distro = segments[1] ?? ''\n if (distro === '') return null\n const rest = segments.slice(2).filter(segment => segment.length > 0)\n return { distro, linuxPath: `/${rest.join('/')}` }\n}\n\n/**\n * Whether a path resolves into a WSL distro through either UNC form.\n * @param raw - candidate absolute path.\n * @returns whether the path parses as a WSL UNC.\n */\nexport function isWslUnc(raw: string): boolean {\n return parseWslUnc(raw) !== null\n}\n\n/**\n * Translate a WSL UNC path to the absolute Linux path a process inside the\n * distribution can open. Throws on non-WSL input: callers rely on this\n * conversion to hand paths to the Linux world, so a silent pass-through\n * would hand a Windows path to bash.\n * @param uncPath - a path {@link parseWslUnc} accepts.\n * @returns the absolute Linux path.\n */\nexport function uncToLinux(uncPath: string): string {\n const parts = parseWslUnc(uncPath)\n if (parts === null) {\n throw new Error(`wsl-workspace: \"${uncPath}\" is not a WSL UNC path`)\n }\n return parts.linuxPath\n}\n\n/**\n * Normalize a Linux absolute path for the Host: collapse repeated slashes and\n * strip a trailing slash (root becomes `/`).\n * @param path - absolute Linux path.\n * @returns the normalized path.\n */\nexport function normalizeLinuxPath(path: string): string {\n const collapsed = path.replace(/\\/+/g, '/')\n return collapsed === '/' ? '/' : collapsed.replace(/\\/$/, '')\n}\n\n/**\n * Whether a path is an absolute, non-empty Linux path.\n * @param path - candidate.\n * @returns whether it starts with `/` and contains no NUL.\n */\nexport function isAbsoluteLinuxPath(path: string): boolean {\n return path.startsWith('/') && !path.includes('\\0')\n}\n\n/**\n * Join a distro and a Linux absolute path into the WSL2 UNC form used as the\n * workspace identity (`\\\\wsl.localhost\\<distro>\\<linux>`, backslash segments).\n * @param distro - distro name.\n * @param linuxPath - absolute Linux path (leading `/`).\n * @returns the UNC path.\n */\nexport function joinUnc(distro: string, linuxPath: string): string {\n if (!isAbsoluteLinuxPath(linuxPath)) {\n throw new Error(`wsl-workspace: cannot map a non-absolute Linux path \"${linuxPath}\" to UNC`)\n }\n // Defense in depth: a distribution name with separators or dot-dirs would\n // escape the `\\\\wsl.localhost\\` share structure (the host route validates\n // wire-supplied names too; every other caller passes through here).\n if (distro === '' || distro === '.' || distro === '..' || /[\\\\/]/.test(distro)) {\n throw new Error(`wsl-workspace: invalid distribution name \"${distro}\"`)\n }\n const normalized = linuxPath.replace(/\\/+/g, '/').replace(/\\/$/, '')\n const withoutLeading = normalized.startsWith('/') ? normalized.slice(1) : normalized\n const windowsSegments = withoutLeading.replace(/\\//g, '\\\\')\n const suffix = windowsSegments === '' ? '' : `\\\\${windowsSegments}`\n return `\\\\\\\\wsl.localhost\\\\${distro}${suffix}`\n}\n\n/**\n * Translate a Windows drive path to the drvfs mount path WSL distributions\n * conventionally expose it at (`C:\\foo` → `/mnt/c/foo`). Only single-letter\n * drives under `/mnt` are mapped; custom mount points are out of scope.\n * @param path - the candidate Windows path.\n * @returns the `/mnt/<drive>/…` path, or `null` for non-drive paths.\n */\nexport function windowsToMntPath(path: string): string | null {\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/\\\\/g, '/').replace(/\\/+/g, '/').replace(/\\/$/, '')\n return `/mnt/${(match[1] ?? '').toLowerCase()}${rest === '' ? '' : `/${rest}`}`\n}\n\n/**\n * Translate a `/mnt/<drive>/…` path back to its Windows drive path.\n * @param linuxPath - the candidate Linux path.\n * @returns the `X:\\…` drive path, or `null` when the path is not a drvfs mount.\n */\nexport function mntToWindowsPath(linuxPath: string): string | null {\n const match = /^\\/mnt\\/([a-zA-Z])(?:\\/(.*))?$/.exec(linuxPath)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/\\//g, '\\\\')\n return `${(match[1] ?? '').toUpperCase()}:\\\\${rest}`\n}\n\n/**\n * Canonical Windows drive path for store keys and cross-realm identity:\n * separators unified to `\\`, trailing separator stripped, and the WHOLE path\n * lowercased — Windows paths compare case-insensitively, and the workspace\n * registry may realpath a different casing than the caller spelled (8.3 or\n * on-disk casing), so the store key must collide across casings.\n * @param path - candidate Windows drive path.\n * @returns the canonical form, or `null` when not drive-shaped.\n */\nexport function canonicalWindowsPath(path: string): string | null {\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/[\\\\/]+/g, '\\\\').replace(/\\\\$/, '').toLowerCase()\n return `${(match[1] ?? '').toLowerCase()}:\\\\${rest}`\n}\n\n/**\n * True when a value is a Windows-shaped path (drive or UNC), which is how\n * the shell executor decides the WSLENV `/p` translation flag: only Windows\n * path values need translation when they cross into the Linux process.\n * @param value - the environment value to classify.\n * @returns whether the value looks like a Windows path.\n */\nexport function isWindowsPathShaped(value: string): boolean {\n return /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\n/** Linux username shape for `wsl.exe -u`: starts with a letter or underscore, then letters/digits/`_`/`.`/`-` (max 64). */\nconst WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/\n\n/**\n * Whether a value is a safe Linux username for `wsl.exe -u`. The check is\n * strict on purpose: a value starting with `-` could be parsed as a wsl.exe\n * option instead of a username.\n * @param value - candidate username.\n * @returns whether it matches the Linux username shape.\n */\nexport function isValidWslUsername(value: string): boolean {\n return WSL_USERNAME_PATTERN.test(value)\n}\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,MAAM,WAAW,WAAW,MAAM,GAAG,MAAM;CAC3C,MAAM,QAAQ,SAAS,MAAM,IAAI;AACjC,KAAI,CAAC,UAAU,SAAS,MAAO,QAAO;CACtC,MAAM,SAAS,SAAS,MAAM;AAC9B,KAAI,WAAW,GAAI,QAAO;CAC1B,MAAM,OAAO,SAAS,MAAM,GAAG,QAAO,YAAW,QAAQ,SAAS;AAClE,QAAO;EAAE;EAAQ,WAAW,IAAI,KAAK,KAAK;;;;;;;;;AAkC5C,SAAgB,mBAAmB,MAAsB;CACvD,MAAM,YAAY,KAAK,QAAQ,QAAQ;AACvC,QAAO,cAAc,MAAM,MAAM,UAAU,QAAQ,OAAO;;;;;;;AAQ5D,SAAgB,oBAAoB,MAAuB;AACzD,QAAO,KAAK,WAAW,QAAQ,CAAC,KAAK,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B,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
+ {"version":3,"file":"wsl-CECXiGZH.js","names":["stdout: Buffer","syncDefault: string | undefined"],"sources":["../src/shared/paths.ts","../src/shared/wsl.ts"],"sourcesContent":["/**\n * WSL path helpers shared by the client and host halves. Pure and\n * dependency-free so both planes can import them without a runtime edge.\n */\n\n/** WSL2 default loopback bridge host: `\\\\wsl.localhost\\<distro>\\...`. */\nconst WSL_LOCALHOST_HOST = 'wsl.localhost'\n/** Legacy WSL interop host: `\\\\wsl$\\<distro>\\...`. */\nconst WSL_LEGACY_HOST = 'wsl$'\n\n/** The two UNC hosts WSL exposes a distribution's filesystem under. */\nconst UNC_HOSTS = [WSL_LOCALHOST_HOST, WSL_LEGACY_HOST]\n\n/** One WSL workspace coordinate parsed out of a UNC path. */\nexport interface WslUncTarget {\n /** Distro name (e.g. `Ubuntu`) as `wsl -l -q` reports it. */\n readonly distro: string\n /** Normalized absolute Linux path (leading `/`; no trailing slash except root). */\n readonly linuxPath: string\n}\n\n/**\n * Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2\n * `\\\\wsl.localhost\\<distro>\\<linux>` form, the legacy `\\\\wsl$\\<distro>\\<linux>`\n * interop form, and forward-slash spellings of either.\n * @param raw - candidate absolute path.\n * @returns the parsed target, or null when the path is not a WSL UNC.\n */\nexport function parseWslUnc(raw: string): WslUncTarget | null {\n const normalized = raw.replace(/\\\\/g, '/').replace(/\\/\\/+/g, '//')\n if (!normalized.startsWith('//')) return null\n const segments = normalized.slice(2).split('/')\n const host = (segments[0] ?? '').toLowerCase()\n if (!UNC_HOSTS.includes(host)) return null\n const distro = segments[1] ?? ''\n if (distro === '') return null\n const rest = segments.slice(2).filter(segment => segment.length > 0)\n return { distro, linuxPath: `/${rest.join('/')}` }\n}\n\n/**\n * Whether a path resolves into a WSL distro through either UNC form.\n * @param raw - candidate absolute path.\n * @returns whether the path parses as a WSL UNC.\n */\nexport function isWslUnc(raw: string): boolean {\n return parseWslUnc(raw) !== null\n}\n\n/**\n * Translate a WSL UNC path to the absolute Linux path a process inside the\n * distribution can open. Throws on non-WSL input: callers rely on this\n * conversion to hand paths to the Linux world, so a silent pass-through\n * would hand a Windows path to bash.\n * @param uncPath - a path {@link parseWslUnc} accepts.\n * @returns the absolute Linux path.\n */\nexport function uncToLinux(uncPath: string): string {\n const parts = parseWslUnc(uncPath)\n if (parts === null) {\n throw new Error(`wsl-workspace: \"${uncPath}\" is not a WSL UNC path`)\n }\n return parts.linuxPath\n}\n\n/**\n * Normalize a Linux absolute path for the Host: collapse repeated slashes and\n * strip a trailing slash (root becomes `/`).\n * @param path - absolute Linux path.\n * @returns the normalized path.\n */\nexport function normalizeLinuxPath(path: string): string {\n const collapsed = path.replace(/\\/+/g, '/')\n return collapsed === '/' ? '/' : collapsed.replace(/\\/$/, '')\n}\n\n/**\n * Whether a path is an absolute, non-empty Linux path.\n * @param path - candidate.\n * @returns whether it starts with `/` and contains no NUL.\n */\nexport function isAbsoluteLinuxPath(path: string): boolean {\n return path.startsWith('/') && !path.includes('\\0')\n}\n\n/**\n * Join a distro and a Linux absolute path into the WSL2 UNC form used as the\n * workspace identity (`\\\\wsl.localhost\\<distro>\\<linux>`, backslash segments).\n * @param distro - distro name.\n * @param linuxPath - absolute Linux path (leading `/`).\n * @returns the UNC path.\n */\nexport function joinUnc(distro: string, linuxPath: string): string {\n if (!isAbsoluteLinuxPath(linuxPath)) {\n throw new Error(`wsl-workspace: cannot map a non-absolute Linux path \"${linuxPath}\" to UNC`)\n }\n // Defense in depth: a distribution name with separators or dot-dirs would\n // escape the `\\\\wsl.localhost\\` share structure (the host route validates\n // wire-supplied names too; every other caller passes through here).\n if (distro === '' || distro === '.' || distro === '..' || /[\\\\/]/.test(distro)) {\n throw new Error(`wsl-workspace: invalid distribution name \"${distro}\"`)\n }\n const normalized = linuxPath.replace(/\\/+/g, '/').replace(/\\/$/, '')\n const withoutLeading = normalized.startsWith('/') ? normalized.slice(1) : normalized\n const windowsSegments = withoutLeading.replace(/\\//g, '\\\\')\n const suffix = windowsSegments === '' ? '' : `\\\\${windowsSegments}`\n return `\\\\\\\\wsl.localhost\\\\${distro}${suffix}`\n}\n\n/**\n * Translate a Windows drive path to the drvfs mount path WSL distributions\n * conventionally expose it at (`C:\\foo` → `/mnt/c/foo`). Only single-letter\n * drives under `/mnt` are mapped; custom mount points are out of scope.\n * @param path - the candidate Windows path.\n * @returns the `/mnt/<drive>/…` path, or `null` for non-drive paths.\n */\nexport function windowsToMntPath(path: string): string | null {\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/\\\\/g, '/').replace(/\\/+/g, '/').replace(/\\/$/, '')\n return `/mnt/${(match[1] ?? '').toLowerCase()}${rest === '' ? '' : `/${rest}`}`\n}\n\n/**\n * Translate a `/mnt/<drive>/…` path back to its Windows drive path.\n * @param linuxPath - the candidate Linux path.\n * @returns the `X:\\…` drive path, or `null` when the path is not a drvfs mount.\n */\nexport function mntToWindowsPath(linuxPath: string): string | null {\n const match = /^\\/mnt\\/([a-zA-Z])(?:\\/(.*))?$/.exec(linuxPath)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/\\//g, '\\\\')\n return `${(match[1] ?? '').toUpperCase()}:\\\\${rest}`\n}\n\n/**\n * Canonical Windows drive path for store keys and cross-realm identity:\n * separators unified to `\\`, trailing separator stripped, and the WHOLE path\n * lowercased — Windows paths compare case-insensitively, and the workspace\n * registry may realpath a different casing than the caller spelled (8.3 or\n * on-disk casing), so the store key must collide across casings.\n * @param path - candidate Windows drive path.\n * @returns the canonical form, or `null` when not drive-shaped.\n */\nexport function canonicalWindowsPath(path: string): string | null {\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/[\\\\/]+/g, '\\\\').replace(/\\\\$/, '').toLowerCase()\n return `${(match[1] ?? '').toLowerCase()}:\\\\${rest}`\n}\n\n/**\n * True when a value is a Windows-shaped path (drive or UNC), which is how\n * the shell executor decides the WSLENV `/p` translation flag: only Windows\n * path values need translation when they cross into the Linux process.\n * @param value - the environment value to classify.\n * @returns whether the value looks like a Windows path.\n */\nexport function isWindowsPathShaped(value: string): boolean {\n return /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\n/** Linux username shape for `wsl.exe -u`: starts with a letter or underscore, then letters/digits/`_`/`.`/`-` (max 64). */\nconst WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/\n\n/**\n * Whether a value is a safe Linux username for `wsl.exe -u`. The check is\n * strict on purpose: a value starting with `-` could be parsed as a wsl.exe\n * option instead of a username.\n * @param value - candidate username.\n * @returns whether it matches the Linux username shape.\n */\nexport function isValidWslUsername(value: string): boolean {\n return WSL_USERNAME_PATTERN.test(value)\n}\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,MAAM,WAAW,WAAW,MAAM,GAAG,MAAM;CAC3C,MAAM,QAAQ,SAAS,MAAM,IAAI;AACjC,KAAI,CAAC,UAAU,SAAS,MAAO,QAAO;CACtC,MAAM,SAAS,SAAS,MAAM;AAC9B,KAAI,WAAW,GAAI,QAAO;CAC1B,MAAM,OAAO,SAAS,MAAM,GAAG,QAAO,YAAW,QAAQ,SAAS;AAClE,QAAO;EAAE;EAAQ,WAAW,IAAI,KAAK,KAAK;;;;;;;;;;;AAoB5C,SAAg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;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,4 +1,4 @@
1
- import { canonicalWindowsPath, isValidWslUsername, joinUnc, parseWslUnc } from "./wsl-6VcgOvF9.js";
1
+ import { canonicalWindowsPath, isValidWslUsername, joinUnc, parseWslUnc } from "./wsl-CECXiGZH.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";
@@ -99,4 +99,4 @@ function listWorkspaceKeys() {
99
99
 
100
100
  //#endregion
101
101
  export { canonicalWslUnc, getWindowsWorkspace, getWorkspaceUsername, listWorkspaceKeys, registerWindowsWorkspace, setWorkspaceUsername };
102
- //# sourceMappingURL=wsl-credentials-B6wIXsKt.js.map
102
+ //# sourceMappingURL=wsl-credentials-BJXc9tfi.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"wsl-credentials-B6wIXsKt.js","names":["parsed: unknown","entry: WorkspaceEntry"],"sources":["../src/shared/wsl-credentials.ts"],"sourcesContent":["/**\n * Per-workspace WSL credentials (host side only). The dialog stores the\n * optional Linux username of a WSL workspace under the harness home; the\n * per-session env contributor and the WSL shell executor read it back so\n * `wsl.exe -u <username>` can run commands as that user. Keys are canonical\n * UNC workspace paths. This module touches node builtins, so the browser\n * half never imports it.\n * @module dsh-wsl-workspace/shared/wsl-credentials\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport { canonicalWindowsPath, isValidWslUsername, joinUnc, parseWslUnc } from './paths.ts'\n\n/** One workspace's stored credentials. */\ninterface WorkspaceEntry {\n /** The Linux user bash runs as inside the distribution (absent = distro default). */\n username?: string\n /**\n * The WSL distribution of a Windows-drive workspace (`/mnt/<drive>` path).\n * 9P cannot serve drvfs mounts, so such workspaces register under their\n * Windows drive path; this entry is what the per-session env contributor\n * uses to hand a distro to the shell executor.\n */\n distro?: string\n}\n\n/** The stored form: canonical UNC or Windows drive workspace path → credentials. */\ntype WorkspaceStore = Record<string, WorkspaceEntry>\n\n/** The store file lives under the harness home so both host halves share it. */\nfunction storePath(): string {\n const dshHome = process.env.DSH_HOME ?? join(homedir(), '.dsh')\n return join(dshHome, 'wsl-workspaces.json')\n}\n\n/** Read the store; a missing or corrupt file reads as empty (never throws). */\nfunction readStore(): WorkspaceStore {\n try {\n const parsed: unknown = JSON.parse(readFileSync(storePath(), 'utf8'))\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return {}\n return parsed as WorkspaceStore\n } catch {\n return {}\n }\n}\n\n/**\n * Canonicalize any accepted WSL UNC spelling into the store's key form.\n * @param path - candidate workspace path (either UNC host form).\n * @returns the canonical UNC path, or null when the path is not a WSL UNC.\n */\nexport function canonicalWslUnc(path: string): string | null {\n const parsed = parseWslUnc(path)\n return parsed === null ? null : joinUnc(parsed.distro, parsed.linuxPath)\n}\n\n/**\n * Read the stored username for a WSL workspace.\n * @param uncPath - the workspace path (any accepted WSL UNC spelling).\n * @returns the username, or undefined when none is stored.\n */\nexport function getWorkspaceUsername(uncPath: string): string | undefined {\n const key = canonicalWslUnc(uncPath)\n if (key === null) return undefined\n const username = readStore()[key]?.username\n return username === undefined || username === '' ? undefined : username\n}\n\n/**\n * Store (or clear) the username of a WSL workspace.\n * @param uncPath - the workspace path (any accepted WSL UNC spelling).\n * @param username - the username; empty or undefined clears the stored value.\n */\nexport function setWorkspaceUsername(uncPath: string, username: string | undefined): void {\n const key = canonicalWslUnc(uncPath)\n if (key === null) throw new Error('wsl-workspace: workspace path is not a WSL UNC path')\n const store = readStore()\n if (username === undefined || username.trim() === '') {\n delete store[key]\n } else {\n const trimmed = username.trim()\n if (!isValidWslUsername(trimmed)) {\n throw new Error('wsl-workspace: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\n }\n store[key] = { username: trimmed }\n }\n const path = storePath()\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(store, null, 2) + '\\n', 'utf8')\n}\n\n/**\n * Register the WSL distribution (and optional Linux username) of a\n * Windows-drive workspace (`/mnt/<drive>` path). Keys are canonical Windows\n * drive paths; the per-session env contributor reads the entry back so\n * `wsl.exe -d <distro>` can run when the session cwd is a drive path.\n * @param winPath - the Windows drive path (any spelling).\n * @param distro - the WSL distribution the workspace belongs to.\n * @param username - optional Linux username (distro default when absent).\n */\nexport function registerWindowsWorkspace(winPath: string, distro: string, username: string | undefined): void {\n const key = canonicalWindowsPath(winPath)\n if (key === null) throw new Error('wsl-workspace: workspace path is not a Windows drive path')\n const entry: WorkspaceEntry = { distro }\n if (username !== undefined && username.trim() !== '') {\n const trimmed = username.trim()\n if (!isValidWslUsername(trimmed)) {\n throw new Error('wsl-workspace: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\n }\n entry.username = trimmed\n }\n const store = readStore()\n store[key] = entry\n const path = storePath()\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(store, null, 2) + '\\n', 'utf8')\n}\n\n/**\n * Read the stored credentials of a Windows-drive workspace.\n * @param winPath - the Windows drive path (any spelling).\n * @returns the stored entry, or undefined when none is registered.\n */\nexport function getWindowsWorkspace(winPath: string): WorkspaceEntry | undefined {\n const key = canonicalWindowsPath(winPath)\n if (key === null) return undefined\n return readStore()[key]\n}\n\n/** Every stored workspace key (canonical UNC and Windows drive paths). */\nexport function listWorkspaceKeys(): string[] {\n return Object.keys(readStore())\n}\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"}
1
+ {"version":3,"file":"wsl-credentials-BJXc9tfi.js","names":["parsed: unknown","entry: WorkspaceEntry"],"sources":["../src/shared/wsl-credentials.ts"],"sourcesContent":["/**\n * Per-workspace WSL credentials (host side only). The dialog stores the\n * optional Linux username of a WSL workspace under the harness home; the\n * per-session env contributor and the WSL shell executor read it back so\n * `wsl.exe -u <username>` can run commands as that user. Keys are canonical\n * UNC workspace paths. This module touches node builtins, so the browser\n * half never imports it.\n * @module dsh-wsl-workspace/shared/wsl-credentials\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport { canonicalWindowsPath, isValidWslUsername, joinUnc, parseWslUnc } from './paths.ts'\n\n/** One workspace's stored credentials. */\ninterface WorkspaceEntry {\n /** The Linux user bash runs as inside the distribution (absent = distro default). */\n username?: string\n /**\n * The WSL distribution of a Windows-drive workspace (`/mnt/<drive>` path).\n * 9P cannot serve drvfs mounts, so such workspaces register under their\n * Windows drive path; this entry is what the per-session env contributor\n * uses to hand a distro to the shell executor.\n */\n distro?: string\n}\n\n/** The stored form: canonical UNC or Windows drive workspace path → credentials. */\ntype WorkspaceStore = Record<string, WorkspaceEntry>\n\n/** The store file lives under the harness home so both host halves share it. */\nfunction storePath(): string {\n const dshHome = process.env.DSH_HOME ?? join(homedir(), '.dsh')\n return join(dshHome, 'wsl-workspaces.json')\n}\n\n/** Read the store; a missing or corrupt file reads as empty (never throws). */\nfunction readStore(): WorkspaceStore {\n try {\n const parsed: unknown = JSON.parse(readFileSync(storePath(), 'utf8'))\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return {}\n return parsed as WorkspaceStore\n } catch {\n return {}\n }\n}\n\n/**\n * Canonicalize any accepted WSL UNC spelling into the store's key form.\n * @param path - candidate workspace path (either UNC host form).\n * @returns the canonical UNC path, or null when the path is not a WSL UNC.\n */\nexport function canonicalWslUnc(path: string): string | null {\n const parsed = parseWslUnc(path)\n return parsed === null ? null : joinUnc(parsed.distro, parsed.linuxPath)\n}\n\n/**\n * Read the stored username for a WSL workspace.\n * @param uncPath - the workspace path (any accepted WSL UNC spelling).\n * @returns the username, or undefined when none is stored.\n */\nexport function getWorkspaceUsername(uncPath: string): string | undefined {\n const key = canonicalWslUnc(uncPath)\n if (key === null) return undefined\n const username = readStore()[key]?.username\n return username === undefined || username === '' ? undefined : username\n}\n\n/**\n * Store (or clear) the username of a WSL workspace.\n * @param uncPath - the workspace path (any accepted WSL UNC spelling).\n * @param username - the username; empty or undefined clears the stored value.\n */\nexport function setWorkspaceUsername(uncPath: string, username: string | undefined): void {\n const key = canonicalWslUnc(uncPath)\n if (key === null) throw new Error('wsl-workspace: workspace path is not a WSL UNC path')\n const store = readStore()\n if (username === undefined || username.trim() === '') {\n delete store[key]\n } else {\n const trimmed = username.trim()\n if (!isValidWslUsername(trimmed)) {\n throw new Error('wsl-workspace: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\n }\n store[key] = { username: trimmed }\n }\n const path = storePath()\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(store, null, 2) + '\\n', 'utf8')\n}\n\n/**\n * Register the WSL distribution (and optional Linux username) of a\n * Windows-drive workspace (`/mnt/<drive>` path). Keys are canonical Windows\n * drive paths; the per-session env contributor reads the entry back so\n * `wsl.exe -d <distro>` can run when the session cwd is a drive path.\n * @param winPath - the Windows drive path (any spelling).\n * @param distro - the WSL distribution the workspace belongs to.\n * @param username - optional Linux username (distro default when absent).\n */\nexport function registerWindowsWorkspace(winPath: string, distro: string, username: string | undefined): void {\n const key = canonicalWindowsPath(winPath)\n if (key === null) throw new Error('wsl-workspace: workspace path is not a Windows drive path')\n const entry: WorkspaceEntry = { distro }\n if (username !== undefined && username.trim() !== '') {\n const trimmed = username.trim()\n if (!isValidWslUsername(trimmed)) {\n throw new Error('wsl-workspace: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\n }\n entry.username = trimmed\n }\n const store = readStore()\n store[key] = entry\n const path = storePath()\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(store, null, 2) + '\\n', 'utf8')\n}\n\n/**\n * Read the stored credentials of a Windows-drive workspace.\n * @param winPath - the Windows drive path (any spelling).\n * @returns the stored entry, or undefined when none is registered.\n */\nexport function getWindowsWorkspace(winPath: string): WorkspaceEntry | undefined {\n const key = canonicalWindowsPath(winPath)\n if (key === null) return undefined\n return readStore()[key]\n}\n\n/** Every stored workspace key (canonical UNC and Windows drive paths). */\nexport function listWorkspaceKeys(): string[] {\n return Object.keys(readStore())\n}\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,W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AC/E,MAAM,MAAM,qBAAqB;AACjC,KAAI,QAAQ,KAAM,QAAO;AACzB,QAAO,YAAY;;;AAIrB,SAAgB,oBAA8B;AAC5C,QAAO,OAAO,KAAK"}
@@ -0,0 +1,139 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { defineTool } from "@deepseek-ai/dsh-tools";
3
+
4
+ //#region src/host/wsl-jobs.ts
5
+ /** The tool name this plugin registers. */
6
+ const TOOL_NAME = "bash_background";
7
+ /**
8
+ * The defaults, kept as data as well as schema fields: a world row that mounts
9
+ * this plugin without a `config:` block hands `apply` an *undefined* config, and
10
+ * schemastery's defaults are not applied on that path. The `wsl-search` entry
11
+ * learned this from a live session; this one learned it the same way, which is
12
+ * why both read their defaults from one place.
13
+ */
14
+ const DEFAULTS = { timeoutMs: 15e3 };
15
+ /** Validated plugin config. */
16
+ const Config = z.object({ timeoutMs: z.number().default(DEFAULTS.timeoutMs) });
17
+ /** Services this tool registers into (all three are read with `get`). */
18
+ const inject = ["tools"];
19
+ /**
20
+ * Turn one finished background process into the registry's outcome shape.
21
+ * @param process - the settled shell process handle.
22
+ * @returns the job outcome with a kind-specific detail line.
23
+ */
24
+ function outcomeOf(process) {
25
+ const detail = process.signal !== null ? `signal: ${process.signal}` : process.exitCode !== null ? `exit code: ${process.exitCode}` : void 0;
26
+ const status = process.status === "killed" ? "killed" : process.status === "completed" ? "completed" : "failed";
27
+ return detail === void 0 ? { status } : {
28
+ status,
29
+ detail
30
+ };
31
+ }
32
+ /**
33
+ * Render one consuming output read as the string the registry hands to
34
+ * `job_output`. The delta is the payload; a lossy read and any full-stream spill
35
+ * files are named, because the consumer cannot see them otherwise.
36
+ * @param read - the shell provider's incremental read.
37
+ * @returns the text for this read.
38
+ */
39
+ function renderRead(read) {
40
+ const parts = [read.delta];
41
+ if (read.lossy) parts.push("[output truncated: unread bytes were dropped]");
42
+ if (read.stdoutSpillPath !== void 0) parts.push(`[full stdout: ${read.stdoutSpillPath}]`);
43
+ if (read.stderrSpillPath !== void 0) parts.push(`[full stderr: ${read.stderrSpillPath}]`);
44
+ return parts.filter((part) => part !== "").join("\n");
45
+ }
46
+ /**
47
+ * Register the world's background-bash producer.
48
+ *
49
+ * The tool returns the registry's job id immediately; `job_output` reads the
50
+ * stream and `job_kill` cancels it, exactly as for the host's one-shot tool.
51
+ * @param ctx - plugin context; registrations are effects scoped to it.
52
+ * @param config - plugin configuration; a row without a `config:` block mounts
53
+ * this plugin with none, and {@link DEFAULTS} then supplies every knob.
54
+ */
55
+ function apply(ctx, config) {
56
+ const resolved = {
57
+ ...DEFAULTS,
58
+ ...config === void 0 ? {} : config
59
+ };
60
+ const tools = ctx.get("tools");
61
+ if (tools === void 0) return;
62
+ const tool = defineTool({
63
+ name: TOOL_NAME,
64
+ description: "Run one command in the background inside this WSL distribution and return a job id immediately. Read its output with job_output and stop it with job_kill. The `bash` tool is a persistent shell and takes `command` only - it has no `run_in_background` parameter, so this tool is its equivalent.",
65
+ parameters: {
66
+ command: {
67
+ type: "string",
68
+ required: true,
69
+ description: "The bash command to run in the background."
70
+ },
71
+ workdir: {
72
+ type: "string",
73
+ description: "Linux working directory for the command. Defaults to the session workspace; a relative path resolves against it."
74
+ }
75
+ },
76
+ timeoutMs: resolved.timeoutMs,
77
+ output: {
78
+ schema: {
79
+ type: "object",
80
+ additionalProperties: false,
81
+ properties: { jobId: {
82
+ type: "string",
83
+ required: true
84
+ } }
85
+ },
86
+ render: (_args, value) => [{
87
+ type: "text",
88
+ text: `started background job ${value.jobId}`
89
+ }]
90
+ },
91
+ async execute(args, exec) {
92
+ const jobs = ctx.get("jobs");
93
+ if (jobs === void 0) throw new Error("background jobs unavailable: this deployment mounts no jobs registry (load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs)");
94
+ const shell = ctx.get("shell");
95
+ if (shell === void 0 || typeof shell.start !== "function" || typeof shell.resolve !== "function") throw new Error("background jobs unavailable: the WSL world provides no shell with background support");
96
+ if (exec.signal?.aborted === true) {
97
+ const error = /* @__PURE__ */ new Error("tool call aborted");
98
+ error.name = "AbortError";
99
+ throw error;
100
+ }
101
+ const shellEnv = ctx.get("shellEnv");
102
+ const dshEnv = typeof shellEnv?.collect === "function" ? shellEnv.collect(exec) : void 0;
103
+ const workdir = args.workdir ?? exec.agent?.session?.header?.cwd;
104
+ const request = {
105
+ command: args.command,
106
+ ...workdir === void 0 ? {} : { workdir },
107
+ ...dshEnv === void 0 ? {} : { dshEnv }
108
+ };
109
+ const jobId = jobs.start({
110
+ kind: "bash",
111
+ label: args.command,
112
+ ...exec.agent === void 0 ? {} : { owner: exec.agent },
113
+ run: () => {
114
+ const process = shell.start(shell.resolve(request));
115
+ return {
116
+ cancel: () => {
117
+ process.kill();
118
+ },
119
+ done: process.done.then(() => outcomeOf(process)),
120
+ readOutput: () => renderRead(process.readOutput())
121
+ };
122
+ }
123
+ });
124
+ return { jobId: String(jobId) };
125
+ },
126
+ presentCall: (args) => ({
127
+ card: "generic",
128
+ title: `Bash (background) ${args.command}`,
129
+ kind: "execute",
130
+ rawInput: args.command
131
+ })
132
+ });
133
+ tools.register(tool);
134
+ }
135
+ var wsl_jobs_default = apply;
136
+
137
+ //#endregion
138
+ export { Config, TOOL_NAME, apply, wsl_jobs_default as default, inject, outcomeOf, renderRead };
139
+ //# sourceMappingURL=wsl-jobs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wsl-jobs.js","names":["DEFAULTS: Required<Config>","Config: z<Config>","resolved: Required<Config>"],"sources":["../src/host/wsl-jobs.ts"],"sourcesContent":["/**\n * The WSL world's tracked background jobs.\n *\n * DSH's one-shot `bash` tool is what *starts* a tracked job: `run_in_background:\n * true` calls `ctx.jobs.start(...)` around a `ctx.shell.start(...)` handle, and\n * the host's `job_list` / `job_output` / `job_kill` tools read that registry. A\n * WSL world replaces that tool with the host's *persistent* shell — whose schema\n * declares only `command` — so nothing in a WSL session produced a job. Worse,\n * the parameter schema does not forbid extra properties, so a\n * `run_in_background: true` argument was silently accepted and ignored: the\n * command ran in the foreground and `job_list` stayed empty. A real session found\n * exactly that, after this plugin's own shell description suggested the\n * parameter.\n *\n * This module restores the producer, and only the producer. The registry owns\n * identity, lifecycle, authorization and completion notices; this plugin's shell\n * provider already implements the background process handle (`start()`); the tool\n * bridges the two and nothing else.\n *\n * It is mounted only where it is needed: a world that keeps the *one-shot* bash\n * row (the platform-capability fallback) already gets `run_in_background` from\n * the host tool, so the row is omitted there.\n *\n * @module dsh-wsl-workspace/host/wsl-jobs\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport { defineTool } from '@deepseek-ai/dsh-tools'\n\n/** The tool name this plugin registers. */\nexport const TOOL_NAME = 'bash_background'\n\n/** Plugin config. */\nexport interface Config {\n /** Cooperative tool-call budget in milliseconds for the *start* call itself. */\n timeoutMs?: number\n}\n\n/**\n * The defaults, kept as data as well as schema fields: a world row that mounts\n * this plugin without a `config:` block hands `apply` an *undefined* config, and\n * schemastery's defaults are not applied on that path. The `wsl-search` entry\n * learned this from a live session; this one learned it the same way, which is\n * why both read their defaults from one place.\n */\nconst DEFAULTS: Required<Config> = {\n timeoutMs: 15_000,\n}\n\n/** Validated plugin config. */\nexport const Config: z<Config> = z.object({\n timeoutMs: z.number().default(DEFAULTS.timeoutMs),\n})\n\n/** Services this tool registers into (all three are read with `get`). */\nexport const inject = ['tools']\n\n/** The tool-execution face this tool reads. */\ninterface ToolExecution {\n signal?: AbortSignal\n agent?: {\n session?: { header?: { cwd?: string } }\n }\n}\n\n/** The `ctx.tools` face. */\ninterface ToolsRegistryFace {\n register(tool: unknown): void\n}\n\n/** One background process handle, as this plugin's shell provider returns it. */\ninterface ShellProcessFace {\n readonly status: 'running' | 'completed' | 'killed'\n readonly exitCode: number | null\n readonly signal: NodeJS.Signals | null\n readonly done: Promise<void>\n readOutput(): { delta: string; lossy: boolean; stdoutSpillPath?: string; stderrSpillPath?: string }\n kill(): boolean\n}\n\n/** The `ctx.shell` face: resolve a request, then start it in the background. */\ninterface ShellFace {\n resolve(request: { command: string; workdir?: string; dshEnv?: Record<string, string> }): unknown\n start(spec: unknown): ShellProcessFace\n}\n\n/** The `ctx.jobs` face: identity and lifecycle for one produced job. */\ninterface JobsFace {\n start(spec: {\n kind: string\n label: string\n owner?: unknown\n run(): {\n cancel(reason?: string): void\n done: Promise<{ status: 'completed' | 'killed' | 'failed'; detail?: string }>\n readOutput?(): string\n }\n }): unknown\n}\n\n/** The `ctx.shellEnv` face, read opportunistically like the host tool does. */\ninterface ShellEnvFace {\n collect(exec: unknown): Record<string, string> | undefined\n}\n\n/**\n * Turn one finished background process into the registry's outcome shape.\n * @param process - the settled shell process handle.\n * @returns the job outcome with a kind-specific detail line.\n */\nexport function outcomeOf(process: ShellProcessFace): { status: 'completed' | 'killed' | 'failed'; detail?: string } {\n const detail = process.signal !== null\n ? `signal: ${process.signal}`\n : process.exitCode !== null ? `exit code: ${process.exitCode}` : undefined\n const status = process.status === 'killed' ? 'killed' : process.status === 'completed' ? 'completed' : 'failed'\n return detail === undefined ? { status } : { status, detail }\n}\n\n/**\n * Render one consuming output read as the string the registry hands to\n * `job_output`. The delta is the payload; a lossy read and any full-stream spill\n * files are named, because the consumer cannot see them otherwise.\n * @param read - the shell provider's incremental read.\n * @returns the text for this read.\n */\nexport function renderRead(read: { delta: string; lossy: boolean; stdoutSpillPath?: string; stderrSpillPath?: string }): string {\n const parts = [read.delta]\n if (read.lossy) parts.push('[output truncated: unread bytes were dropped]')\n if (read.stdoutSpillPath !== undefined) parts.push(`[full stdout: ${read.stdoutSpillPath}]`)\n if (read.stderrSpillPath !== undefined) parts.push(`[full stderr: ${read.stderrSpillPath}]`)\n return parts.filter(part => part !== '').join('\\n')\n}\n\n/**\n * Register the world's background-bash producer.\n *\n * The tool returns the registry's job id immediately; `job_output` reads the\n * stream and `job_kill` cancels it, exactly as for the host's one-shot tool.\n * @param ctx - plugin context; registrations are effects scoped to it.\n * @param config - plugin configuration; a row without a `config:` block mounts\n * this plugin with none, and {@link DEFAULTS} then supplies every knob.\n */\nexport function apply(ctx: Context, config?: Config): void {\n const resolved: Required<Config> = { ...DEFAULTS, ...config === undefined ? {} : config }\n const tools = ctx.get('tools') as unknown as ToolsRegistryFace | undefined\n if (tools === undefined) return\n const tool = defineTool({\n name: TOOL_NAME,\n description: 'Run one command in the background inside this WSL distribution and return a job id immediately. Read its output with job_output and stop it with job_kill. The `bash` tool is a persistent shell and takes `command` only - it has no `run_in_background` parameter, so this tool is its equivalent.',\n parameters: {\n command: {\n type: 'string',\n required: true,\n description: 'The bash command to run in the background.',\n },\n workdir: {\n type: 'string',\n description: 'Linux working directory for the command. Defaults to the session workspace; a relative path resolves against it.',\n },\n },\n timeoutMs: resolved.timeoutMs,\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n jobId: { type: 'string', required: true },\n },\n },\n render: (_args: unknown, value: { jobId: string }) => [{\n type: 'text',\n text: `started background job ${value.jobId}`,\n }],\n },\n async execute(args: { command: string; workdir?: string }, exec: ToolExecution) {\n const jobs = ctx.get('jobs') as unknown as JobsFace | undefined\n if (jobs === undefined) {\n throw new Error('background jobs unavailable: this deployment mounts no jobs registry (load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs)')\n }\n const shell = ctx.get('shell') as unknown as ShellFace | undefined\n if (shell === undefined || typeof shell.start !== 'function' || typeof shell.resolve !== 'function') {\n throw new Error('background jobs unavailable: the WSL world provides no shell with background support')\n }\n if (exec.signal?.aborted === true) {\n const error = new Error('tool call aborted')\n error.name = 'AbortError'\n throw error\n }\n const shellEnv = ctx.get('shellEnv') as unknown as ShellEnvFace | undefined\n const dshEnv = typeof shellEnv?.collect === 'function' ? shellEnv.collect(exec) : undefined\n // The session workspace is the default, exactly as the persistent `bash`\n // tool's shell starts there: this plugin's shell provider falls back to its\n // own configured cwd (or the host process's), which in a WSL world is a\n // Windows directory the distribution cannot use.\n const workdir = args.workdir ?? exec.agent?.session?.header?.cwd\n const request = {\n command: args.command,\n ...workdir === undefined ? {} : { workdir },\n ...dshEnv === undefined ? {} : { dshEnv },\n }\n const jobId = jobs.start({\n kind: 'bash',\n label: args.command,\n ...exec.agent === undefined ? {} : { owner: exec.agent },\n run: () => {\n const process = shell.start(shell.resolve(request))\n return {\n cancel: () => {\n process.kill()\n },\n done: process.done.then(() => outcomeOf(process)),\n readOutput: () => renderRead(process.readOutput()),\n }\n },\n })\n return { jobId: String(jobId) }\n },\n presentCall: (args: { command: string }) => ({\n card: 'generic',\n title: `Bash (background) ${args.command}`,\n kind: 'execute',\n rawInput: args.command,\n }),\n })\n tools.register(tool)\n}\n\nexport default apply\n"],"mappings":";;;;;AA+BA,MAAa,YAAY;;;;;;;;AAezB,MAAMA,WAA6B,EACjC,WAAW;;AAIb,MAAaC,SAAoB,EAAE,OAAO,EACxC,WAAW,EAAE,SAAS,QAAQ,SAAS;;AAIzC,MAAa,SAAS,CAAC;;;;;;AAuDvB,SAAgB,UAAU,SAA2F;CACnH,MAAM,SAAS,QAAQ,WAAW,OAC9B,WAAW,QAAQ,WACnB,QAAQ,aAAa,OAAO,cAAc,QAAQ,aAAa;CACnE,MAAM,SAAS,QAAQ,WAAW,WAAW,WAAW,QAAQ,WAAW,cAAc,cAAc;AACvG,QAAO,WAAW,SAAY,EAAE,WAAW;EAAE;EAAQ;;;;;;;;;;AAUvD,SAAgB,WAAW,MAAqG;CAC9H,MAAM,QAAQ,CAAC,KAAK;AACpB,KAAI,KAAK,MAAO,OAAM,KAAK;AAC3B,KAAI,KAAK,oBAAoB,OAAW,OAAM,KAAK,iBAAiB,KAAK,gBAAgB;AACzF,KAAI,KAAK,oBAAoB,OAAW,OAAM,KAAK,iBAAiB,KAAK,gBAAgB;AACzF,QAAO,MAAM,QAAO,SAAQ,SAAS,IAAI,KAAK;;;;;;;;;;;AAYhD,SAAgB,MAAM,KAAc,QAAuB;CACzD,MAAMC,WAA6B;EAAE,GAAG;EAAU,GAAG,WAAW,SAAY,KAAK;;CACjF,MA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;;;;AAI3C,UAAO,EAAE,OAAO,OAAO;;EAEzB,cAAc,UAA+B;GAC3C,MAAM;GACN,OAAO,qBAAqB,KAAK;GACjC,MAAM;GACN,UAAU,KAAK;;;AAGnB,OAAM,SAAS;;AAGjB,uBAAe"}
@@ -0,0 +1,64 @@
1
+ import { defaultDistroSync, isValidWslUsername, parseWslUnc, windowsToMntPath } from "./wsl-CECXiGZH.js";
2
+ import { spawn } from "node:child_process";
3
+
4
+ //#region src/host/wsl-relay.ts
5
+ /** Shell signals whose arrival means this relay should take the shell down. */
6
+ const FORWARDED_SIGNALS = [
7
+ "SIGINT",
8
+ "SIGTERM",
9
+ "SIGHUP",
10
+ "SIGBREAK"
11
+ ];
12
+ /** POSIX single-quote a path so the `cd` command reaches bash as one word. */
13
+ function quote(path) {
14
+ return `'${path.replace(/'/g, `'\\''`)}'`;
15
+ }
16
+ /** Fail loudly: the PTY has no other way to tell the model what went wrong. */
17
+ function fail(message) {
18
+ console.error(`dsh-wsl-workspace: ${message}`);
19
+ process.exit(1);
20
+ }
21
+ /** The distribution this shell belongs to. */
22
+ function resolveDistro(uncDistro) {
23
+ if (uncDistro !== void 0 && uncDistro !== "") return uncDistro;
24
+ const fromEnv = process.env.DSH_WSL_DISTRO;
25
+ if (fromEnv !== void 0 && fromEnv !== "") return fromEnv;
26
+ const fallback = defaultDistroSync();
27
+ if (fallback !== void 0 && fallback !== "") return fallback;
28
+ return fail("persistent shell: the session cwd carries no distribution, DSH_WSL_DISTRO is unset and no WSL default is readable");
29
+ }
30
+ /** The workspace user, when one is configured and safe for `wsl.exe -u`. */
31
+ function resolveUser() {
32
+ const user$1 = process.env.DSH_WSL_USER;
33
+ if (user$1 === void 0 || user$1 === "") return void 0;
34
+ if (!isValidWslUsername(user$1)) fail(`persistent shell: refusing the malformed username "${user$1}"`);
35
+ return user$1;
36
+ }
37
+ const cwd = process.cwd();
38
+ const unc = parseWslUnc(cwd);
39
+ const distro = resolveDistro(unc?.distro);
40
+ const user = resolveUser();
41
+ const linuxCwd = unc !== null ? unc.linuxPath : windowsToMntPath(cwd) ?? void 0;
42
+ const command = `${linuxCwd === void 0 ? "" : `cd ${quote(linuxCwd)} && `}exec bash -i`;
43
+ const argv = [
44
+ "wsl.exe",
45
+ "-d",
46
+ distro,
47
+ ...user === void 0 ? [] : ["-u", user],
48
+ "--cd",
49
+ cwd,
50
+ "-e",
51
+ "bash",
52
+ "-lc",
53
+ command
54
+ ];
55
+ const child = spawn(argv[0] ?? "wsl.exe", argv.slice(1), { stdio: "inherit" });
56
+ child.on("error", (error) => fail(`persistent shell: cannot start ${argv[0] ?? "wsl.exe"} (${error.message})`));
57
+ child.on("exit", (code, signal) => process.exit(signal === null ? code ?? 0 : 1));
58
+ for (const signal of FORWARDED_SIGNALS) process.on(signal, () => {
59
+ if (child.exitCode === null && child.signalCode === null) child.kill(signal);
60
+ });
61
+
62
+ //#endregion
63
+ export { };
64
+ //# sourceMappingURL=wsl-relay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wsl-relay.js","names":["FORWARDED_SIGNALS: NodeJS.Signals[]","user"],"sources":["../src/host/wsl-relay.ts"],"sourcesContent":["/**\n * Persistent-shell relay for WSL sessions.\n *\n * `@deepseek-ai/dsh-terminal-bash` is a config-driven PTY backend: the world\n * decides `shellPath`/`shellArgs`, and the backend spawns that command with the\n * session's cwd — which for a WSL session is a `\\\\wsl.localhost\\…` path this\n * Windows side can hand to a process. This script *is* that command: it reads\n * the coordinates the preset cannot know (the distribution and optional user\n * come from the session, not from the mode), then hands its own stdio — the\n * PTY — to `wsl.exe`, so the model gets a stateful shell inside the\n * distribution instead of one process per call.\n *\n * The inner shell is started as `bash -lc '<cd …> && exec bash -i'`: the login\n * pass loads `/etc/profile` and the user profile (PATH and friends), and the\n * interactive shell that replaces it keeps the session directory. A plain\n * `bash -l` can be sent to `$HOME` by a profile — that is why the one-shot\n * executor in `src/shell.ts` prefixes an explicit `cd` too.\n *\n * Resolution mirrors that executor: the UNC cwd names its distribution, else\n * `DSH_WSL_DISTRO` (the per-session fact this plugin publishes), else the\n * host's default distribution; `DSH_WSL_USER` selects `wsl.exe -u`. Every\n * failure is reported on stderr and exits non-zero, so a broken shell surfaces\n * instead of leaving a silent dead terminal.\n *\n * @module dsh-wsl-workspace/host/wsl-relay\n */\n\nimport { spawn } from 'node:child_process'\nimport { isValidWslUsername, parseWslUnc, windowsToMntPath } from '../shared/paths.ts'\nimport { defaultDistroSync } from '../shared/wsl.ts'\n\n/** Shell signals whose arrival means this relay should take the shell down. */\nconst FORWARDED_SIGNALS: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGBREAK']\n\n/** POSIX single-quote a path so the `cd` command reaches bash as one word. */\nfunction quote(path: string): string {\n return `'${path.replace(/'/g, `'\\\\''`)}'`\n}\n\n/** Fail loudly: the PTY has no other way to tell the model what went wrong. */\nfunction fail(message: string): never {\n console.error(`dsh-wsl-workspace: ${message}`)\n process.exit(1)\n}\n\n/** The distribution this shell belongs to. */\nfunction resolveDistro(uncDistro: string | undefined): string {\n if (uncDistro !== undefined && uncDistro !== '') return uncDistro\n const fromEnv = process.env.DSH_WSL_DISTRO\n if (fromEnv !== undefined && fromEnv !== '') return fromEnv\n const fallback = defaultDistroSync()\n if (fallback !== undefined && fallback !== '') return fallback\n return fail('persistent shell: the session cwd carries no distribution, DSH_WSL_DISTRO is unset and no WSL default is readable')\n}\n\n/** The workspace user, when one is configured and safe for `wsl.exe -u`. */\nfunction resolveUser(): string | undefined {\n const user = process.env.DSH_WSL_USER\n if (user === undefined || user === '') return undefined\n if (!isValidWslUsername(user)) fail(`persistent shell: refusing the malformed username \"${user}\"`)\n return user\n}\n\nconst cwd = process.cwd()\nconst unc = parseWslUnc(cwd)\nconst distro = resolveDistro(unc?.distro)\nconst user = resolveUser()\n// The PTY's cwd is what `wsl.exe` inherits; it accepts both the UNC form of its\n// own filesystem and a drive path (mapped to `/mnt/<drive>`), so it is handed\n// through unchanged and only the login shell's `cd` needs the Linux spelling.\nconst linuxCwd = unc !== null ? unc.linuxPath : windowsToMntPath(cwd) ?? undefined\nconst command = `${linuxCwd === undefined ? '' : `cd ${quote(linuxCwd)} && `}exec bash -i`\nconst argv = [\n 'wsl.exe',\n '-d', distro,\n ...user === undefined ? [] : ['-u', user],\n '--cd', cwd,\n '-e', 'bash',\n '-lc', command,\n]\n\nconst child = spawn(argv[0] ?? 'wsl.exe', argv.slice(1), { stdio: 'inherit' })\nchild.on('error', (error: Error) => fail(`persistent shell: cannot start ${argv[0] ?? 'wsl.exe'} (${error.message})`))\nchild.on('exit', (code, signal) => process.exit(signal === null ? code ?? 0 : 1))\nfor (const signal of FORWARDED_SIGNALS) {\n process.on(signal, () => {\n if (child.exitCode === null && child.signalCode === null) child.kill(signal)\n })\n}\n"],"mappings":";;;;;AAgCA,MAAMA,oBAAsC;CAAC;CAAU;CAAW;CAAU;;;AAG5E,SAAS,MAAM,MAAsB;AACnC,QAAO,IAAI,KAAK,QAAQ,MAAM,SAAS;;;AAIzC,SAAS,KAAK,SAAwB;AACpC,SAAQ,MAAM,sBAAsB;AACpC,SAAQ,KAAK;;;AAIf,SAAS,cAAc,WAAuC;AAC5D,KAAI,cAAc,UAAa,cAAc,GAAI,QAAO;CACxD,MAAM,UAAU,QAAQ,IAAI;AAC5B,KAAI,YAAY,UAAa,YAAY,GAAI,QAAO;CACpD,MAAM,WAAW;AACjB,KAAI,aAAa,UAAa,aAAa,GAAI,QAAO;AACtD,QAAO,KAAK;;;AAId,SAAS,cAAkC;CACzC,MAAMC,SAAO,QAAQ,IAAI;AACzB,KAAIA,WAAS,UAAaA,WAAS,GAAI,QAAO;AAC9C,KAAI,CAAC,mBAAmBA,QAAO,MAAK,sDAAsDA,OAAK;AAC/F,QAAOA;;AAGT,MAAM,MAAM,QAAQ;AACpB,MAAM,MAAM,YAAY;AACxB,MAAM,SAAS,cAAc,KAAK;AAClC,MAAM,OAAO;AAIb,MAAM,WAAW,QAAQ,OAAO,IAAI,YAAY,iBAAiB,QAAQ;AACzE,MAAM,UAAU,GAAG,aAAa,SAAY,KAAK,MAAM,MAAM,UAAU,MAAM;AAC7E,MAAM,OAAO;CACX;CACA;CAAM;CACN,GAAG,SAAS,SAAY,KAAK,CAAC,MAAM;CACpC;CAAQ;CACR;CAAM;CACN;CAAO;;AAGT,MAAM,QAAQ,MAAM,KAAK,MAAM,WAAW,KAAK,MAAM,IAAI,EAAE,OAAO;AAClE,MAAM,GAAG,UAAU,UAAiB,KAAK,kCAAkC,KAAK,MAAM,UAAU,IAAI,MAAM,QAAQ;AAClH,MAAM,GAAG,SAAS,MAAM,WAAW,QAAQ,KAAK,WAAW,OAAO,QAAQ,IAAI;AAC9E,KAAK,MAAM,UAAU,kBACnB,SAAQ,GAAG,cAAc;AACvB,KAAI,MAAM,aAAa,QAAQ,MAAM,eAAe,KAAM,OAAM,KAAK"}
@@ -0,0 +1,27 @@
1
+ import { SandboxProvider } from "@deepseek-ai/dsh-sandbox";
2
+
3
+ //#region src/host/wsl-sandbox.ts
4
+ /** The WSL world's no-op confinement: the caller's argv, unchanged. */
5
+ var WslSandboxProvider = class extends SandboxProvider {
6
+ constructor(ctx) {
7
+ super(ctx);
8
+ }
9
+ /**
10
+ * Hand back the caller's own argv.
11
+ * @param argv - the command the caller wants to run.
12
+ * @returns the same argv, with the world's honest enforcement claim.
13
+ */
14
+ confine(argv) {
15
+ return {
16
+ argv: [...argv],
17
+ enforcement: "partial",
18
+ denialSignatures: [],
19
+ runnerFailureRules: []
20
+ };
21
+ }
22
+ };
23
+ var wsl_sandbox_default = WslSandboxProvider;
24
+
25
+ //#endregion
26
+ export { WslSandboxProvider, wsl_sandbox_default as default };
27
+ //# sourceMappingURL=wsl-sandbox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wsl-sandbox.js","names":[],"sources":["../src/host/wsl-sandbox.ts"],"sourcesContent":["/**\n * The WSL world's `sandbox` capability.\n *\n * DSH's confinement seam wraps a command so the host's runner enforces the file\n * policy. That runner describes Windows paths: asked to confine a command whose\n * policy carries a `\\\\wsl.localhost\\…` workspace root it fails outright\n * (`GetNamedSecurityInfoW failed (Win32 1)` — the ACL of a 9P path cannot be\n * read), and even where it worked it could not bound a process that executes on\n * the Linux kernel side. That is why this plugin's bash tool has never gone\n * through it, and why the host's persistent-shell group cannot be reused as-is:\n * its backend calls `sandbox.confine()` before spawning.\n *\n * So the world declares its own provider: commands run unconfined by the\n * Windows runner — the distribution is the boundary — while the file tools keep\n * enforcing the policy themselves, at the resolved real path, in\n * `src/fs.ts`. `enforcement: 'partial'` records that split honestly: within this\n * world the policy is enforced for file effects, not by the wrapped command.\n *\n * @module dsh-wsl-workspace/host/wsl-sandbox\n */\n\nimport { SandboxProvider } from '@deepseek-ai/dsh-sandbox'\nimport type { ConfinedArgv } from '@deepseek-ai/dsh-sandbox'\nimport type { Context } from '@deepseek-ai/cordis'\n\n/** The WSL world's no-op confinement: the caller's argv, unchanged. */\nexport class WslSandboxProvider extends SandboxProvider {\n constructor(ctx: Context) {\n super(ctx)\n }\n\n /**\n * Hand back the caller's own argv.\n * @param argv - the command the caller wants to run.\n * @returns the same argv, with the world's honest enforcement claim.\n */\n override confine(argv: readonly string[]): ConfinedArgv {\n return {\n argv: [...argv],\n enforcement: 'partial',\n denialSignatures: [],\n runnerFailureRules: [],\n }\n }\n}\n\nexport default WslSandboxProvider\n"],"mappings":";;;;AA0BA,IAAa,qBAAb,cAAwC,gBAAgB;CACtD,YAAY,KAAc;AACxB,QAAM;;;;;;;CAQR,AAAS,QAAQ,MAAuC;AACtD,SAAO;GACL,MAAM,CAAC,GAAG;GACV,aAAa;GACb,kBAAkB;GAClB,oBAAoB;;;;AAK1B,0BAAe"}