dsh-wsl-workspace 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.de.md +49 -0
- package/README.es.md +49 -0
- package/README.fr.md +49 -0
- package/README.ja.md +49 -0
- package/README.ko.md +49 -0
- package/README.md +47 -47
- package/README.pt.md +49 -0
- package/README.ru.md +49 -0
- package/README.zh.md +46 -46
- package/lib/client.js +76 -5
- package/lib/client.js.map +1 -1
- package/lib/fs.js +188 -174
- package/lib/fs.js.map +1 -1
- package/lib/index.js +573 -541
- package/lib/index.js.map +1 -1
- package/lib/{paths-DBaSmi7x.js → paths-BDE1NVOv.js} +17 -2
- package/lib/paths-BDE1NVOv.js.map +1 -0
- package/lib/shell.js +382 -381
- package/lib/shell.js.map +1 -1
- package/lib/wsl-C5_mxGPM.js +228 -0
- package/lib/wsl-C5_mxGPM.js.map +1 -0
- package/lib/wsl-DdNPGaPo.js +1019 -0
- package/lib/wsl-DdNPGaPo.js.map +1 -0
- package/lib/wsl-credentials-BI4v5TNZ.js +109 -0
- package/lib/wsl-credentials-BI4v5TNZ.js.map +1 -0
- package/package.json +71 -61
- package/src/client/AddWslWorkspace.tsx +349 -346
- package/src/client/api.ts +124 -104
- package/src/client/index.ts +233 -194
- package/src/fs.ts +247 -228
- package/src/host/variants.ts +164 -199
- package/src/index.ts +93 -27
- package/src/shared/paths.ts +175 -159
- package/src/shared/wsl-credentials.ts +135 -85
- package/src/shell.ts +451 -441
- package/image-1.png +0 -0
- package/image.png +0 -0
- package/lib/paths-DBaSmi7x.js.map +0 -1
- package/lib/wsl-GjkUifnx.js +0 -179
- package/lib/wsl-GjkUifnx.js.map +0 -1
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/host/variants.ts","../src/index.ts"],"sourcesContent":["/**\n * WSL preset-variant generator. For every healthy source preset the roster\n * supplies, a `wsl-<id>` variant is materialized under the roster's user\n * root: the source composition with its shell/filesystem world replaced by\n * the WSL providers, so any mode (standard, minimal, code, cordis, user\n * presets) can run on top of a WSL execution world. The execution world is\n * therefore orthogonal to the mode instead of a mode itself.\n *\n * The transformation is text-level on the top-level rows of the composition\n * (the shape all shipped presets share), with surgical edits for the known\n * special groups; unknown shapes are kept verbatim where possible.\n * @module dsh-wsl-workspace/host/variants\n */\n\n/** Top-level rows that name the execution world and are replaced by the variant's own. */\nconst WORLD_ROWS = new Set(['tool-bash', 'tool-pwsh', 'tool-fs', 'tool-fs-search', 'filesystem', 'persistent-shell'])\n\n/** The injected WSL world group: providers + the bash/fs consumers, entry-local. */\nfunction wslWorldGroup(shellPath: string, fsPath: string, includeEditor: boolean): string {\n return [\n '# ── WSL execution world (dsh-wsl-workspace variant) ─────────────────────',\n '# The shell and fs services are provided entry-locally (the isolate',\n '# realm); host services (tools registry, shell-env, jobs) fall through.',\n '# tool-fs-search is intentionally absent: the packaged ripgrep runs on',\n '# the Windows host and cannot open Linux paths; WSL sessions search with',\n '# shell tools instead.',\n '- id: wsl-world',\n \" name: cordis:group\",\n ' group: true',\n ' isolate:',\n ' shell: true',\n ' fs: true',\n ' config:',\n ` - id: shell-wsl`,\n ` name: '${shellPath.replace(/'/g, \"''\")}'`,\n ' - id: fs-wsl',\n ` name: '${fsPath.replace(/'/g, \"''\")}'`,\n ' - id: tool-bash',\n \" name: '@deepseek-ai/dsh-tool-bash'\",\n ' - id: tool-fs',\n \" name: '@deepseek-ai/dsh-tool-fs'\",\n ...(includeEditor\n ? [\n ' - id: str-replace-editor',\n \" name: '@deepseek-ai/dsh-tool-str-replace-editor'\",\n ' config:',\n ' maxOutputChars: 16000',\n ]\n : []),\n '',\n ].join('\\n')\n}\n\n/**\n * The persistent-shell group re-pointed at WSL: the PTY spawns wsl.exe's\n * bash instead of a host `bash` (which does not exist on Windows).\n */\nfunction persistentShellGroup(): string {\n return [\n '# ── persistent shell over WSL (variant) ─────────────────────────────────',\n '- id: persistent-shell',\n ' name: cordis:group',\n ' group: true',\n ' isolate:',\n ' terminals: true',\n ' config:',\n ' - id: pty',\n \" name: '@deepseek-ai/dsh-terminal'\",\n '',\n ' - id: terminal-bash',\n \" name: '@deepseek-ai/dsh-terminal-bash'\",\n ' config:',\n ' timeoutMs: 300000',\n \" shellPath: 'wsl.exe'\",\n \" shellArgs: ['-e', 'bash', '-l']\",\n '',\n ' - id: persistent-bash',\n \" name: '@deepseek-ai/dsh-tool-bash-persistent'\",\n ' config:',\n ' timeoutMs: 300000',\n ' description: |-',\n ' Run commands in a bash shell inside the WSL distribution',\n ' * When invoking this tool, the contents of the \"command\" parameter does NOT need to be XML-escaped.',\n \" * You don't have access to the internet via this tool.\",\n ' * You do have access to a mirror of common linux and python packages via apt and pip.',\n ' * State is persistent across command calls and discussions with the user.',\n \" * To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.\",\n ' * Please avoid commands that may produce a very large amount of output.',\n \" * Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.\",\n '',\n ].join('\\n')\n}\n\n/** The sentence appended to a standard-like persona when the variant runs in WSL. */\nconst PERSONA_APPEND = ' Your working directory {{cwd}} is inside a WSL (Windows Subsystem for Linux) distribution: the bash tool and the file read/write/edit tools use Linux paths, and the Windows filesystem is reachable as /mnt/<drive> for file migration.'\n\n/** The top-level rows of one composition, as (startLine, endLineExclusive) spans. */\nfunction topLevelSpans(lines: readonly string[]): { start: number; end: number }[] {\n const spans: { start: number; end: number }[] = []\n let start = -1\n for (let index = 0; index < lines.length; index++) {\n if (lines[index]?.startsWith('- id: ') === true) {\n if (start >= 0) spans.push({ start, end: index })\n start = index\n }\n }\n if (start >= 0) spans.push({ start, end: lines.length })\n return spans\n}\n\n/** The row id of a top-level span, or undefined when the first line is malformed. */\nfunction spanId(lines: readonly string[], span: { start: number; end: number }): string | undefined {\n return /^- id: ([A-Za-z0-9_.-]+)/.exec(lines[span.start] ?? '')?.[1]\n}\n\n/** Whether a top-level span is a `persona` row with an appendable folded text. */\nfunction appendablePersona(lines: readonly string[], span: { start: number; end: number }): boolean {\n const block = lines.slice(span.start, span.end).join('\\n')\n if (!block.includes('complete: true') && /text: [>|-]/.test(block)) {\n // Append only when the folded text actually has content lines.\n const textLine = block.split('\\n').find(line => /^(\\s*)text: [>|-]/.test(line))\n if (textLine !== undefined) {\n const indent = /^(\\s*)/.exec(textLine)?.[1]?.length ?? 0\n return block.split('\\n').some(line => line.length > indent && /^\\s+/.test(line) && !line.includes(':'))\n }\n }\n return false\n}\n\n/** Append the WSL sentence to a persona row's folded text (in place of its last text line). */\nfunction appendPersona(lines: readonly string[], span: { start: number; end: number }): string[] {\n const block = lines.slice(span.start, span.end)\n const textIndex = block.findIndex(line => /^(\\s*)text: [>|-]/.test(line))\n if (textIndex < 0) return [...block]\n const indent = /^(\\s*)/.exec(block[textIndex] ?? '')?.[1]?.length ?? 0\n let lastText = -1\n for (let index = textIndex + 1; index < block.length; index++) {\n const line = block[index] ?? ''\n if (line.trim() === '') continue\n if (line.length > indent && /^\\s+/.test(line)) lastText = index\n }\n if (lastText < 0) return [...block]\n const updated = [...block]\n const textIndent = /^(\\s*)/.exec(block[lastText] ?? '')?.[1] ?? ' '\n updated.splice(lastText + 1, 0, `${textIndent}${PERSONA_APPEND}`)\n return updated\n}\n\n/**\n * Transform one source preset composition into its WSL variant: drop the\n * execution-world rows, keep everything else verbatim, and append the WSL\n * world group (plus the persistent-shell group when the source had one).\n * @param source - the source composition text.\n * @param shellPath - absolute path of the plugin's built WSL shell provider.\n * @param fsPath - absolute path of the plugin's built WSL fs provider.\n * @returns the variant composition text.\n */\nexport function transformPresetForWsl(source: string, shellPath: string, fsPath: string): string {\n const lines = source.split('\\n')\n const spans = topLevelSpans(lines)\n const kept: string[] = []\n let sawEditor = false\n let sawPersistent = false\n let personaAppended = false\n for (const span of spans) {\n const id = spanId(lines, span)\n if (id === undefined) {\n kept.push(...lines.slice(span.start, span.end))\n continue\n }\n if (WORLD_ROWS.has(id)) {\n if (id === 'persistent-shell') sawPersistent = true\n continue\n }\n if (id === 'persona' && !personaAppended && appendablePersona(lines, span)) {\n kept.push(...appendPersona(lines, span))\n personaAppended = true\n continue\n }\n kept.push(...lines.slice(span.start, span.end))\n if (id === 'str-replace-editor') sawEditor = true\n }\n if (source.includes('str-replace-editor')) sawEditor = true\n const result = [...kept]\n if (result.length > 0 && result[result.length - 1] !== '') result.push('')\n result.push(wslWorldGroup(shellPath, fsPath, sawEditor))\n if (sawPersistent) result.push(persistentShellGroup())\n return result.join('\\n').replace(/\\n{3,}/g, '\\n\\n').replace(/\\n+$/, '\\n')\n}\n\n/** Whether an id is one of this plugin's own preset directories. */\nexport function isWslVariantId(id: string): boolean {\n return id === 'wsl' || /^wsl-[a-z0-9-]+$/.test(id)\n}\n\n/** The variant id for one source preset id. */\nexport function variantIdFor(sourceId: string): string {\n return `wsl-${sourceId.toLowerCase()}`\n}\n","/**\r\n * Host half of dsh-wsl-workspace. Three responsibilities:\r\n *\r\n * 1. Materialize a `wsl-<mode>` variant for every healthy roster preset\r\n * under `<dshHome>/.agent-presets/` (the roster's auto-scanned user\r\n * root), so the WSL execution world — `shell-wsl` + `fs-wsl` behind one\r\n * entry-local realm, with `tool-bash`/`tool-fs` consumers — composes with\r\n * ANY mode instead of being a mode itself; the legacy standalone `wsl`\r\n * preset directory and stale variants are removed on boot. The preset\r\n * rows name THIS package's built lib files by absolute path, which the\r\n * preset mount resolves to `file:` URLs without relying on bare specifier\r\n * resolution from the preset's home directory.\r\n *\r\n * 2. Serve the browser dialog's data route (`/wsl-workspace/api`):\r\n * distribution discovery, one-level directory listing, path checks, and\r\n * the per-workspace username store — all over the 9P UNC share.\r\n * Loopback-only, matching the sensitivity of the privileged configuration\r\n * surface.\r\n *\r\n * 3. Contribute the per-session `DSH_WSL_DISTRO` managed-env fact so the WSL\r\n * shell executor can resolve a plain Linux `workdir` to the calling\r\n * session's distribution.\r\n * @module dsh-wsl-workspace\r\n */\r\n\r\nimport { Context } from '@deepseek-ai/cordis'\r\nimport z from '@deepseek-ai/schemastery'\r\nimport { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'\r\nimport { fileURLToPath } from 'node:url'\r\nimport { dirname, join } from 'node:path'\r\nimport type { IncomingMessage, ServerResponse } from 'node:http'\r\nimport { homedir } from 'node:os'\r\nimport { joinUnc, normalizeLinuxPath, isAbsoluteLinuxPath, isValidWslUsername, parseWslUnc } from './shared/paths.ts'\r\nimport { canonicalWslUnc, getWorkspaceUsername, setWorkspaceUsername } from './shared/wsl-credentials.ts'\r\nimport { defaultDistro, listDistros } from './shared/wsl.ts'\r\nimport { isWslVariantId, transformPresetForWsl, variantIdFor } from './host/variants.ts'\r\n\r\n/** The HTTP route this plugin serves (a relative, same-origin path). */\r\nexport const DEFAULT_ROUTE = '/wsl-workspace/api'\r\n\r\n/**\r\n * Bilingual display labels for the shipped source modes, matching the app's\r\n * own built-in copy in each language — note the `code` preset is \"PTC 模式\"\r\n * in the Chinese copy but \"Code mode\" in English. The DSH picker localizes\r\n * only the four built-in ids itself; `wsl-*` variant ids render the\r\n * preset.yml text verbatim, so the plugin writes one bilingual string so\r\n * both locales can identify each variant. Custom presets keep their own\r\n * name.\r\n */\r\nconst MODE_DISPLAY_LABELS: Readonly<Record<string, { en: string; zh: string }>> = {\r\n standard: { en: 'Standard mode', zh: '标准模式' },\r\n code: { en: 'Code mode', zh: 'PTC 模式' },\r\n minimal: { en: 'Minimal mode', zh: '极简模式' },\r\n cordis: { en: 'Creator mode', zh: '创造模式' },\r\n}\r\n\r\n/**\r\n * Quote a value as a single-line YAML single-quoted scalar. Plain scalars\r\n * cannot contain `: ` (colon + space), which plain English sentences do —\r\n * written unquoted they make the whole preset.yml unparsable, dropping the\r\n * name, description and order together.\r\n */\r\nfunction yamlScalar(value: string): string {\r\n return `'${value.replace(/'/g, \"''\")}'`\r\n}\r\n\r\n/** The variant name for one shipped mode (bilingual) or a custom preset. */\r\nfunction variantName(presetId: string, sourceName: string): string {\r\n const labels = MODE_DISPLAY_LABELS[presetId]\r\n return labels === undefined ? `WSL · ${sourceName}` : `WSL · ${labels.en}(${labels.zh})`\r\n}\r\n\r\n/** The variant description for one shipped mode (bilingual) or a custom preset. */\r\nfunction variantDescription(presetId: string): string {\r\n const labels = MODE_DISPLAY_LABELS[presetId]\r\n const display = labels === undefined ? presetId : `${labels.en}(${labels.zh})`\r\n return `WSL execution world for ${display}: bash and file tools run inside the WSL distribution.`\r\n}\r\n\r\n/** Plugin config. */\r\nexport interface Config {\r\n /** The route under which the dialog data API is served. */\r\n route?: string\r\n}\r\n\r\n/** The shape after schemastery applied the defaults. */\r\ntype ResolvedConfig = Required<Config>\r\n\r\n/** The `webServer.register` route contract this plugin consumes. */\r\ninterface WebServerRoute {\r\n kind: 'exact'\r\n path: string\r\n handler(req: IncomingMessage, res: ServerResponse): Promise<void>\r\n}\r\n\r\ninterface WebServerService {\r\n register(route: WebServerRoute): () => void\r\n}\r\n\r\n/** The `ctx.shellEnv` registry face this plugin consumes (optional service). */\r\ninterface ShellEnvService {\r\n register(contributor: {\r\n name: string\r\n variables: Readonly<Record<string, { description: string }>>\r\n resolve(execution: {\r\n agent?: { session: { header: { cwd?: string } } }\r\n }): Readonly<Partial<Record<string, string>>>\r\n }): () => void\r\n}\r\n\r\n/** One directory entry the dialog lists. */\r\ninterface WslDirEntryWire {\r\n name: string\r\n kind: 'directory' | 'file' | 'other'\r\n}\r\n\r\n/** One directory level plus its breadcrumb ancestry. */\r\ninterface WslDirListingWire {\r\n path: string\r\n parent: string | null\r\n entries: WslDirEntryWire[]\r\n}\r\n\r\n/** The wire envelope every method answers with. */\r\ntype Envelope<T> = { ok: true; value: T } | { ok: false; error: string }\r\n\r\nconst MAX_BODY_BYTES = 1024 * 1024\r\n\r\n/** Valid WSL distribution names: one path-safe segment (no separators, no dot-dirs). */\r\nconst DISTRO_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/\r\n\r\n/** The loopback hostnames the data route answers to (DNS-rebinding fence). */\r\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1'])\r\n\r\n/** True when a socket address is loopback (any IPv4/IPv6 spelling). */\r\nfunction isLoopback(address: string | undefined): boolean {\r\n return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'\r\n}\r\n\r\n/** The hostname part of a `Host` header value (port and IPv6 brackets stripped). */\r\nfunction hostNameOf(host: string): string {\r\n if (host.startsWith('[')) {\r\n const end = host.indexOf(']')\r\n return end >= 0 ? host.slice(1, end) : host\r\n }\r\n return host.split(':')[0] ?? ''\r\n}\r\n\r\n/** True when the request's `Host` header names a loopback host. */\r\nfunction isLoopbackHost(host: string | undefined): boolean {\r\n return host !== undefined && LOOPBACK_HOSTNAMES.has(hostNameOf(host).toLowerCase())\r\n}\r\n\r\n/**\r\n * Validate a wire-supplied distribution name before it becomes a UNC segment:\r\n * an attacker-controlled segment containing separators or `..` would escape\r\n * the `\\\\wsl.localhost\\` share structure into arbitrary UNC paths.\r\n * @param value - the raw wire value.\r\n * @returns the validated distro name.\r\n */\r\nfunction requireDistro(value: unknown): string {\r\n if (typeof value !== 'string' || !DISTRO_PATTERN.test(value) || value === '.' || value === '..') {\r\n throw new Error('distro must be a valid WSL distribution name')\r\n }\r\n return value\r\n}\r\n\r\n/** Human text for an unknown rejection. */\r\nfunction messageOf(value: unknown): string {\r\n return value instanceof Error ? value.message : String(value)\r\n}\r\n\r\n/** Write one JSON envelope. */\r\nfunction json(res: ServerResponse, status: number, body: Envelope<unknown>): void {\r\n res.writeHead(status, {\r\n 'content-type': 'application/json; charset=utf-8',\r\n 'cache-control': 'no-store',\r\n 'x-content-type-options': 'nosniff',\r\n })\r\n res.end(JSON.stringify(body))\r\n}\r\n\r\n/** Collect and parse the request body, bounded. */\r\nasync function readBody(req: IncomingMessage): Promise<Record<string, unknown>> {\r\n const chunks: Buffer[] = []\r\n let size = 0\r\n for await (const chunk of req) {\r\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\r\n size += buffer.length\r\n if (size > MAX_BODY_BYTES) throw new Error('request body is too large')\r\n chunks.push(buffer)\r\n }\r\n const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown\r\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\r\n throw new Error('request body must be a JSON object')\r\n }\r\n return parsed as Record<string, unknown>\r\n}\r\n\r\n/** Normalize a Linux path for the wire (rejecting non-absolute input). */\r\nfunction requireLinuxPath(value: unknown, label: string): string {\r\n if (typeof value !== 'string' || !isAbsoluteLinuxPath(value)) {\r\n throw new Error(`${label} must be an absolute Linux path`)\r\n }\r\n return normalizeLinuxPath(value)\r\n}\r\n\r\n/** Validate a wire-supplied workspace path and return its canonical UNC form. */\r\nfunction requireWslUnc(value: unknown): string {\r\n if (typeof value !== 'string') throw new Error('path must be a string')\r\n const canonical = canonicalWslUnc(value)\r\n if (canonical === null) throw new Error('path must be a WSL UNC workspace path')\r\n return canonical\r\n}\r\n\r\n/** Resolve one directory listing over the 9P share. */\r\nfunction listWslDir(distro: string, linuxPath: string): WslDirListingWire {\r\n const unc = joinUnc(distro, linuxPath)\r\n const dirents = readdirSync(unc, { withFileTypes: true })\r\n const entries: WslDirEntryWire[] = dirents\r\n .slice(0, 1000)\r\n .map((dirent): WslDirEntryWire => {\r\n const kind: WslDirEntryWire['kind'] = dirent.isDirectory()\r\n ? 'directory'\r\n : dirent.isFile() ? 'file' : 'other'\r\n return { name: dirent.name, kind }\r\n })\r\n .sort((a, b) => {\r\n if (a.kind === 'directory' && b.kind !== 'directory') return -1\r\n if (a.kind !== 'directory' && b.kind === 'directory') return 1\r\n return a.name.localeCompare(b.name)\r\n })\r\n const parent = linuxPath === '/' ? null : linuxPath.split('/').slice(0, -1).join('/') || '/'\r\n return { path: linuxPath, parent, entries }\r\n}\r\n\r\n/** Route one method dispatch. */\r\nasync function dispatch(method: string, params: Record<string, unknown>): Promise<unknown> {\r\n switch (method) {\r\n case 'listDistros': {\r\n const distros = await listDistros()\r\n const fallback = await defaultDistro()\r\n if (fallback !== undefined && distros.includes(fallback)) {\r\n return [fallback, ...distros.filter(name => name !== fallback)]\r\n }\r\n return distros\r\n }\r\n case 'listDir': {\r\n const distro = requireDistro(params.distro)\r\n const path = requireLinuxPath(params.path, 'path')\r\n return listWslDir(distro, path)\r\n }\r\n case 'check': {\r\n const distro = requireDistro(params.distro)\r\n const path = requireLinuxPath(params.path, 'path')\r\n const unc = joinUnc(distro, path)\r\n try {\r\n const info = statSync(unc)\r\n return { exists: true, isDirectory: info.isDirectory() }\r\n } catch {\r\n return { exists: false, isDirectory: false }\r\n }\r\n }\r\n case 'setUser': {\r\n const path = requireWslUnc(params.path)\r\n const username = params.username\r\n if (username === undefined || username === '') {\r\n setWorkspaceUsername(path, undefined)\r\n } else {\r\n if (typeof username !== 'string' || !isValidWslUsername(username)) {\r\n throw new Error('username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\r\n }\r\n setWorkspaceUsername(path, username)\r\n }\r\n return null\r\n }\r\n default:\r\n throw new Error(`unknown method \"${method}\"`)\r\n }\r\n}\r\n\r\n/** The `ctx.agentPresets` roster face this plugin consumes (optional service). */\r\ninterface AgentPresetsService {\r\n list(): Promise<{ id: string; broken?: string; path: string }[]>\r\n read(id: string): Promise<string>\r\n}\r\n\r\n/**\r\n * Materialize a `wsl-<mode>` variant for every healthy source preset, and\r\n * remove this plugin's managed residue: stale variants whose source\r\n * disappeared, plus the legacy standalone `wsl` preset directory (the\r\n * execution world now composes with modes; a standalone WSL mode no longer\r\n * exists). Managed files: rewritten on every boot.\r\n * @param agentPresets - the roster service.\r\n * @param dshHome - the harness home (user preset root parent).\r\n * @param shellPath - absolute path of the plugin's built WSL shell provider.\r\n * @param fsPath - absolute path of the plugin's built WSL fs provider.\r\n */\r\nasync function materializeVariants(\r\n agentPresets: AgentPresetsService,\r\n dshHome: string,\r\n shellPath: string,\r\n fsPath: string,\r\n): Promise<void> {\r\n const presets = await agentPresets.list()\r\n const userRoot = join(dshHome, '.agent-presets')\r\n const generated = new Set<string>()\r\n for (const preset of presets) {\r\n if (preset.broken !== undefined) continue\r\n if (isWslVariantId(preset.id)) continue\r\n const variantId = variantIdFor(preset.id)\r\n const source = await agentPresets.read(preset.id)\r\n const transformed = transformPresetForWsl(source, shellPath, fsPath)\r\n const dir = join(userRoot, variantId)\r\n mkdirSync(dir, { recursive: true })\r\n writeFileSync(join(dir, 'agent.cordis.yml'), transformed, 'utf8')\r\n const labels = MODE_DISPLAY_LABELS[preset.id]\r\n let name = variantName(preset.id, preset.id)\r\n let orderLine = ''\r\n try {\r\n const meta = readFileSync(join(dirname(preset.path), 'preset.yml'), 'utf8')\r\n if (labels === undefined) {\r\n // Custom presets keep their own display name; shipped modes use the\r\n // bilingual labels above so both locales can identify the variant.\r\n const match = /^name:\\s*(.+)$/m.exec(meta)\r\n if (match?.[1] !== undefined && match[1].trim() !== '') {\r\n name = variantName(preset.id, match[1].trim())\r\n }\r\n }\r\n // Inherit the source's declared order so the WSL variants line up with\r\n // the local modes in the roster (standard, PTC, minimal, cordis).\r\n const orderMatch = /^order:\\s*(\\d+)\\s*$/m.exec(meta)\r\n if (orderMatch?.[1] !== undefined) orderLine = `order: ${orderMatch[1]}\\n`\r\n } catch {\r\n // Absent or unreadable display metadata falls back to the id-based name.\r\n }\r\n writeFileSync(\r\n join(dir, 'preset.yml'),\r\n `name: ${yamlScalar(name)}\\n`\r\n + orderLine\r\n + `description: ${yamlScalar(variantDescription(preset.id))}\\n`,\r\n 'utf8',\r\n )\r\n generated.add(variantId)\r\n }\r\n for (const entry of readdirSync(userRoot, { withFileTypes: true })) {\r\n if (!entry.isDirectory()) continue\r\n if (entry.name === 'wsl') {\r\n // The legacy standalone WSL mode: folded into the variants above.\r\n rmSync(join(userRoot, entry.name), { recursive: true, force: true })\r\n continue\r\n }\r\n if (!/^wsl-[a-z0-9-]+$/.test(entry.name)) continue\r\n if (!generated.has(entry.name)) rmSync(join(userRoot, entry.name), { recursive: true, force: true })\r\n }\r\n}\r\n\r\n/** Function-plugin plugin contract. */\r\nexport const name = 'dsh-wsl-workspace'\r\n\r\n/** Required services. */\r\nexport const inject = ['webServer']\r\n\r\n/** Validated plugin config (schemastery applied the defaults). */\r\nexport const Config: z<Config> = z.object({\r\n route: z.string().default(DEFAULT_ROUTE),\r\n})\r\n\r\n/**\r\n * Apply the host half: materialize the `wsl` preset plus a `wsl-<mode>`\r\n * variant for every healthy roster preset, register the data route, and\r\n * contribute the per-session `DSH_WSL_DISTRO` managed-env fact so the WSL\r\n * shell executor can resolve a plain Linux `workdir` to the calling\r\n * session's distribution.\r\n * @param ctx - the host plugin context.\r\n * @param config - the validated configuration.\r\n */\r\nexport function apply(ctx: Context, config: Config): void {\r\n const resolved = config as ResolvedConfig\r\n const dshHome = process.env.DSH_HOME ?? join(homedir(), '.dsh')\r\n const packageRoot = fileURLToPath(new URL('..', import.meta.url))\r\n const shellPath = join(packageRoot, 'lib', 'shell.js').replace(/\\\\/g, '/')\r\n const fsPath = join(packageRoot, 'lib', 'fs.js').replace(/\\\\/g, '/')\r\n\r\n const agentPresets = ctx.get('agentPresets') as unknown as AgentPresetsService | undefined\r\n if (agentPresets !== undefined) {\r\n ctx.effect(() => {\r\n void materializeVariants(agentPresets, dshHome, shellPath, fsPath).catch((error) => {\r\n // Variant generation is best-effort over a live roster: a missing or\r\n // unreadable source preset must not take the whole plugin down, but\r\n // the failure is surfaced loudly rather than hidden.\r\n console.error(`dsh-wsl-workspace: WSL preset-variant generation failed: ${messageOf(error)}`)\r\n })\r\n return () => {}\r\n }, 'dsh-wsl-workspace: WSL preset variants')\r\n }\r\n\r\n const shellEnv = ctx.get('shellEnv') as unknown as ShellEnvService | undefined\r\n if (shellEnv !== undefined) {\r\n ctx.effect(() => shellEnv.register({\r\n name: 'wsl-workspace-distro',\r\n variables: {\r\n DSH_WSL_DISTRO: {\r\n description: 'The WSL distribution of the calling session workspace, when the session cwd is a WSL UNC path.',\r\n },\r\n DSH_WSL_USER: {\r\n description: 'The Linux user of the calling session workspace, when the workspace has one configured.',\r\n },\r\n },\r\n resolve(execution) {\r\n const cwd = execution.agent?.session.header.cwd\r\n const unc = cwd === undefined ? null : parseWslUnc(cwd)\r\n if (unc === null) return {}\r\n const username = getWorkspaceUsername(joinUnc(unc.distro, unc.linuxPath))\r\n return username === undefined || username === ''\r\n ? { DSH_WSL_DISTRO: unc.distro }\r\n : { DSH_WSL_DISTRO: unc.distro, DSH_WSL_USER: username }\r\n },\r\n }), 'dsh-wsl-workspace: per-session distro env fact')\r\n }\r\n\r\n const webServer = ctx.get('webServer') as unknown as WebServerService\r\n ctx.effect(() => webServer.register({\r\n kind: 'exact',\r\n path: resolved.route,\r\n handler: async (req, res) => {\r\n if (!isLoopback(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host)) {\r\n json(res, 403, { ok: false, error: 'loopback-only' })\r\n return\r\n }\r\n if (req.method !== 'POST') {\r\n json(res, 405, { ok: false, error: 'method not allowed' })\r\n return\r\n }\r\n let body: Record<string, unknown>\r\n try {\r\n body = await readBody(req)\r\n } catch (error) {\r\n json(res, 400, { ok: false, error: messageOf(error) })\r\n return\r\n }\r\n const method = typeof body.method === 'string' ? body.method : ''\r\n const params = body.params === undefined ? {} : body.params\r\n if (params === null || typeof params !== 'object' || Array.isArray(params)) {\r\n json(res, 400, { ok: false, error: 'params must be an object' })\r\n return\r\n }\r\n try {\r\n const value = await dispatch(method, params as Record<string, unknown>)\r\n json(res, 200, { ok: true, value })\r\n } catch (error) {\r\n json(res, 200, { ok: false, error: messageOf(error) })\r\n }\r\n },\r\n }), 'dsh-wsl-workspace: dialog data route')\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,aAAa,IAAI,IAAI;CAAC;CAAa;CAAa;CAAW;CAAkB;CAAc;AAAkB,CAAC;;AAGpH,SAAS,cAAc,WAAmB,Q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,IAAI;KAAM,OAAA,MADP,SAAS,QAAQ,MAAiC;IACrC,CAAC;GACpC,SAAS,OAAO;IACd,KAAK,KAAK,KAAK;KAAE,IAAI;KAAO,OAAO,UAAU,KAAK;IAAE,CAAC;GACvD;EACF;CACF,CAAC,GAAG,sCAAsC;AAC5C"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/host/variants.ts","../src/index.ts"],"sourcesContent":["/**\r\n * WSL preset-variant generator. For every healthy source preset the roster\r\n * supplies, a `wsl-<id>` variant is materialized under the roster's user\r\n * root: the source composition with its shell/filesystem world replaced by\r\n * the WSL providers, so any mode (standard, minimal, code, cordis, user\r\n * presets) can run on top of a WSL execution world. The execution world is\r\n * therefore orthogonal to the mode instead of a mode itself.\r\n *\r\n * The transformation is text-level on the top-level rows of the composition\r\n * (the shape all shipped presets share), with surgical edits for the known\r\n * special groups; unknown shapes are kept verbatim where possible.\r\n * @module dsh-wsl-workspace/host/variants\r\n */\r\n\r\n/** Top-level rows that name the execution world and are replaced by the variant's own. */\r\nconst WORLD_ROWS = new Set(['tool-bash', 'tool-pwsh', 'tool-fs', 'tool-fs-search', 'str-replace-editor', 'filesystem', 'persistent-shell', 'custom-bash', 'bootstrap-filesystem'])\r\n\r\n/** The injected WSL world group: providers + the bash/fs consumers, entry-local. */\r\nfunction wslWorldGroup(shellPath: string, fsPath: string, includeEditor: boolean): string {\r\n return [\r\n '# ── WSL execution world (dsh-wsl-workspace variant) ─────────────────────',\r\n '# The shell and fs services are provided entry-locally (the isolate',\r\n '# realm); host services (tools registry, shell-env, jobs) fall through.',\r\n '# tool-fs-search is intentionally absent: the packaged ripgrep runs on',\r\n '# the Windows host and cannot open Linux paths; WSL sessions search with',\r\n '# shell tools instead.',\r\n '- id: wsl-world',\r\n \" name: cordis:group\",\r\n ' group: true',\r\n ' isolate:',\r\n ' shell: true',\r\n ' fs: true',\r\n ' config:',\r\n ` - id: shell-wsl`,\r\n ` name: '${shellPath.replace(/'/g, \"''\")}'`,\r\n ' - id: fs-wsl',\r\n ` name: '${fsPath.replace(/'/g, \"''\")}'`,\r\n ' - id: tool-bash',\r\n \" name: '@deepseek-ai/dsh-tool-bash'\",\r\n ' - id: tool-fs',\r\n \" name: '@deepseek-ai/dsh-tool-fs'\",\r\n // The editor resolves through this entry-local WSL fs. Older editor builds\r\n // pass no cwd, so the provider inherits it from the current tool execution.\r\n // Anchored-family presets require this name during bootstrap.\r\n ...(includeEditor\r\n ? [\r\n ' - id: str-replace-editor',\r\n \" name: '@deepseek-ai/dsh-tool-str-replace-editor'\",\r\n ' config:',\r\n ' maxOutputChars: 16000',\r\n ]\r\n : []),\r\n '',\r\n ].join('\\n')\r\n}\r\n\r\n/** The sentence appended to a standard-like persona when the variant runs in WSL. */\r\nconst PERSONA_APPEND = ' Your working directory {{cwd}} is inside a WSL (Windows Subsystem for Linux) distribution: the bash tool and the file read/write/edit tools use Linux paths, and the Windows filesystem is reachable as /mnt/<drive> for file migration.'\r\n\r\n/** The top-level rows of one composition, as (startLine, endLineExclusive) spans. */\r\nfunction topLevelSpans(lines: readonly string[]): { start: number; end: number }[] {\r\n const spans: { start: number; end: number }[] = []\r\n let start = -1\r\n for (let index = 0; index < lines.length; index++) {\r\n if (lines[index]?.startsWith('- id: ') === true) {\r\n if (start >= 0) spans.push({ start, end: index })\r\n start = index\r\n }\r\n }\r\n if (start >= 0) spans.push({ start, end: lines.length })\r\n return spans\r\n}\r\n\r\n/** The row id of a top-level span, or undefined when the first line is malformed. */\r\nfunction spanId(lines: readonly string[], span: { start: number; end: number }): string | undefined {\r\n return /^- id: ([A-Za-z0-9_.-]+)/.exec(lines[span.start] ?? '')?.[1]\r\n}\r\n\r\n/** Whether a top-level span is a `persona` row with an appendable folded text. */\r\nfunction appendablePersona(lines: readonly string[], span: { start: number; end: number }): boolean {\r\n const block = lines.slice(span.start, span.end).join('\\n')\r\n if (!block.includes('complete: true') && /text: [>|-]/.test(block)) {\r\n // Append only when the folded text actually has content lines.\r\n const textLine = block.split('\\n').find(line => /^(\\s*)text: [>|-]/.test(line))\r\n if (textLine !== undefined) {\r\n const indent = /^(\\s*)/.exec(textLine)?.[1]?.length ?? 0\r\n return block.split('\\n').some(line => line.length > indent && /^\\s+/.test(line) && !line.includes(':'))\r\n }\r\n }\r\n return false\r\n}\r\n\r\n/** Append the WSL sentence to a persona row's folded text (in place of its last text line). */\r\nfunction appendPersona(lines: readonly string[], span: { start: number; end: number }): string[] {\r\n const block = lines.slice(span.start, span.end)\r\n const textIndex = block.findIndex(line => /^(\\s*)text: [>|-]/.test(line))\r\n if (textIndex < 0) return [...block]\r\n const indent = /^(\\s*)/.exec(block[textIndex] ?? '')?.[1]?.length ?? 0\r\n let lastText = -1\r\n for (let index = textIndex + 1; index < block.length; index++) {\r\n const line = block[index] ?? ''\r\n if (line.trim() === '') continue\r\n if (line.length > indent && /^\\s+/.test(line)) lastText = index\r\n }\r\n if (lastText < 0) return [...block]\r\n const updated = [...block]\r\n const textIndent = /^(\\s*)/.exec(block[lastText] ?? '')?.[1] ?? ' '\r\n updated.splice(lastText + 1, 0, `${textIndent}${PERSONA_APPEND}`)\r\n return updated\r\n}\r\n\r\n/**\r\n * Transform one source preset composition into its WSL variant: drop the\r\n * execution-world rows, keep everything else verbatim, and append the WSL\r\n * world group. The persistent-shell group is NOT re-added: it registers the\r\n * same `bash` tool name as the WSL world's `dsh-tool-bash`, and the tools\r\n * registry rejects duplicates within one preset layer — the whole variant\r\n * fails to mount and the session falls back to another preset. Its PTY\r\n * backend additionally cannot run on this plugin's Windows host\r\n * (`dsh-subprocess-local`: \"terminal inspection is unsupported on platform\r\n * win32\"), so the group could never spawn a shell here anyway. The WSL\r\n * world's ordinary `bash` tool covers command execution for every variant.\r\n * @param source - the source composition text.\r\n * @param shellPath - absolute path of the plugin's built WSL shell provider.\r\n * @param fsPath - absolute path of the plugin's built WSL fs provider.\r\n * @returns the variant composition text.\r\n */\r\nexport function transformPresetForWsl(source: string, shellPath: string, fsPath: string): string {\r\n const lines = source.split('\\n')\r\n const spans = topLevelSpans(lines)\r\n const kept: string[] = []\r\n let sawEditor = false\r\n let personaAppended = false\r\n for (const span of spans) {\r\n const id = spanId(lines, span)\r\n if (id === undefined) {\r\n kept.push(...lines.slice(span.start, span.end))\r\n continue\r\n }\r\n if (WORLD_ROWS.has(id)) continue\r\n if (id === 'persona' && !personaAppended && appendablePersona(lines, span)) {\r\n kept.push(...appendPersona(lines, span))\r\n personaAppended = true\r\n continue\r\n }\r\n kept.push(...lines.slice(span.start, span.end))\r\n if (id === 'str-replace-editor') sawEditor = true\r\n }\r\n if (source.includes('str-replace-editor')) sawEditor = true\r\n const result = [...kept]\r\n if (result.length > 0 && result[result.length - 1] !== '') result.push('')\r\n result.push(wslWorldGroup(shellPath, fsPath, sawEditor))\r\n return result.join('\\n').replace(/\\n{3,}/g, '\\n\\n').replace(/\\n+$/, '\\n')\r\n}\r\n\r\n/** Whether an id is one of this plugin's own preset directories. */\r\nexport function isWslVariantId(id: string): boolean {\r\n return id === 'wsl' || /^wsl-[a-z0-9-]+$/.test(id)\r\n}\r\n\r\n/** The variant id for one source preset id. */\r\nexport function variantIdFor(sourceId: string): string {\r\n return `wsl-${sourceId.toLowerCase()}`\r\n}\r\n","/**\r\n * Host half of dsh-wsl-workspace. Three responsibilities:\r\n *\r\n * 1. Materialize a `wsl-<mode>` variant for every healthy roster preset\r\n * under `<dshHome>/.agent-presets/` (the roster's auto-scanned user\r\n * root), so the WSL execution world — `shell-wsl` + `fs-wsl` behind one\r\n * entry-local realm, with `tool-bash`/`tool-fs` consumers — composes with\r\n * ANY mode instead of being a mode itself; the legacy standalone `wsl`\r\n * preset directory and stale variants are removed on boot. The preset\r\n * rows name THIS package's built lib files by absolute path, which the\r\n * preset mount resolves to `file:` URLs without relying on bare specifier\r\n * resolution from the preset's home directory.\r\n *\r\n * 2. Serve the browser dialog's data route (`/wsl-workspace/api`):\r\n * distribution discovery, one-level directory listing, path checks, and\r\n * the per-workspace username store — all over the 9P UNC share.\r\n * Loopback-only, matching the sensitivity of the privileged configuration\r\n * surface.\r\n *\r\n * 3. Contribute the per-session `DSH_WSL_DISTRO` managed-env fact so the WSL\r\n * shell executor can resolve a plain Linux `workdir` to the calling\r\n * session's distribution.\r\n * @module dsh-wsl-workspace\r\n */\r\n\r\nimport { Context } from '@deepseek-ai/cordis'\r\nimport z from '@deepseek-ai/schemastery'\r\nimport { cpSync, existsSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'\r\nimport { fileURLToPath } from 'node:url'\r\nimport { dirname, join } from 'node:path'\r\nimport type { IncomingMessage, ServerResponse } from 'node:http'\r\nimport { homedir } from 'node:os'\r\nimport { joinUnc, mntToWindowsPath, normalizeLinuxPath, isAbsoluteLinuxPath, isValidWslUsername, parseWslUnc } from './shared/paths.ts'\r\nimport { canonicalWslUnc, getWindowsWorkspace, getWorkspaceUsername, listWorkspaceKeys, registerWindowsWorkspace, setWorkspaceUsername } from './shared/wsl-credentials.ts'\r\nimport { defaultDistro, listDistros } from './shared/wsl.ts'\r\nimport { isWslVariantId, transformPresetForWsl, variantIdFor } from './host/variants.ts'\r\n\r\n/** The HTTP route this plugin serves (a relative, same-origin path). */\r\nexport const DEFAULT_ROUTE = '/wsl-workspace/api'\r\n\r\n/**\r\n * Bilingual display labels for the shipped source modes, matching the app's\r\n * own built-in copy in each language — note the `code` preset is \"PTC 模式\"\r\n * in the Chinese copy but \"Code mode\" in English. The DSH picker localizes\r\n * only the four built-in ids itself; `wsl-*` variant ids render the\r\n * preset.yml text verbatim, so the plugin writes one bilingual string so\r\n * both locales can identify each variant. Custom presets keep their own\r\n * name.\r\n */\r\nconst MODE_DISPLAY_LABELS: Readonly<Record<string, { en: string; zh: string }>> = {\r\n standard: { en: 'Standard mode', zh: '标准模式' },\r\n code: { en: 'Code mode', zh: 'PTC 模式' },\r\n minimal: { en: 'Minimal mode', zh: '极简模式' },\r\n cordis: { en: 'Creator mode', zh: '创造模式' },\r\n}\r\n\r\n/**\r\n * Quote a value as a single-line YAML single-quoted scalar. Plain scalars\r\n * cannot contain `: ` (colon + space), which plain English sentences do —\r\n * written unquoted they make the whole preset.yml unparsable, dropping the\r\n * name, description and order together.\r\n */\r\nfunction yamlScalar(value: string): string {\r\n return `'${value.replace(/'/g, \"''\")}'`\r\n}\r\n\r\n/** The variant name for one shipped mode (bilingual) or a custom preset. */\r\nfunction variantName(presetId: string, sourceName: string): string {\r\n const labels = MODE_DISPLAY_LABELS[presetId]\r\n return labels === undefined ? `WSL · ${sourceName}` : `WSL · ${labels.en}(${labels.zh})`\r\n}\r\n\r\n/** The variant description for one shipped mode (bilingual) or a custom preset. */\r\nfunction variantDescription(presetId: string): string {\r\n const labels = MODE_DISPLAY_LABELS[presetId]\r\n const display = labels === undefined ? presetId : `${labels.en}(${labels.zh})`\r\n return `WSL execution world for ${display}: bash and file tools run inside the WSL distribution.`\r\n}\r\n\r\n/** Plugin config. */\r\nexport interface Config {\r\n /** The route under which the dialog data API is served. */\r\n route?: string\r\n}\r\n\r\n/** The shape after schemastery applied the defaults. */\r\ntype ResolvedConfig = Required<Config>\r\n\r\n/** The `webServer.register` route contract this plugin consumes. */\r\ninterface WebServerRoute {\r\n kind: 'exact'\r\n path: string\r\n handler(req: IncomingMessage, res: ServerResponse): Promise<void>\r\n}\r\n\r\ninterface WebServerService {\r\n register(route: WebServerRoute): () => void\r\n}\r\n\r\n/** The `ctx.shellEnv` registry face this plugin consumes (optional service). */\r\ninterface ShellEnvService {\r\n register(contributor: {\r\n name: string\r\n variables: Readonly<Record<string, { description: string }>>\r\n resolve(execution: {\r\n agent?: { session: { header: { cwd?: string } } }\r\n }): Readonly<Partial<Record<string, string>>>\r\n }): () => void\r\n}\r\n\r\n/** One directory entry the dialog lists. */\r\ninterface WslDirEntryWire {\r\n name: string\r\n kind: 'directory' | 'file' | 'other'\r\n}\r\n\r\n/** One directory level plus its breadcrumb ancestry. */\r\ninterface WslDirListingWire {\r\n path: string\r\n parent: string | null\r\n entries: WslDirEntryWire[]\r\n}\r\n\r\n/** The wire envelope every method answers with. */\r\ntype Envelope<T> = { ok: true; value: T } | { ok: false; error: string }\r\n\r\nconst MAX_BODY_BYTES = 1024 * 1024\r\n\r\n/** Valid WSL distribution names: one path-safe segment (no separators, no dot-dirs). */\r\nconst DISTRO_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/\r\n\r\n/** The loopback hostnames the data route answers to (DNS-rebinding fence). */\r\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1'])\r\n\r\n/** True when a socket address is loopback (any IPv4/IPv6 spelling). */\r\nfunction isLoopback(address: string | undefined): boolean {\r\n return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'\r\n}\r\n\r\n/** The hostname part of a `Host` header value (port and IPv6 brackets stripped). */\r\nfunction hostNameOf(host: string): string {\r\n if (host.startsWith('[')) {\r\n const end = host.indexOf(']')\r\n return end >= 0 ? host.slice(1, end) : host\r\n }\r\n return host.split(':')[0] ?? ''\r\n}\r\n\r\n/** True when the request's `Host` header names a loopback host. */\r\nfunction isLoopbackHost(host: string | undefined): boolean {\r\n return host !== undefined && LOOPBACK_HOSTNAMES.has(hostNameOf(host).toLowerCase())\r\n}\r\n\r\n/**\r\n * Validate a wire-supplied distribution name before it becomes a UNC segment:\r\n * an attacker-controlled segment containing separators or `..` would escape\r\n * the `\\\\wsl.localhost\\` share structure into arbitrary UNC paths.\r\n * @param value - the raw wire value.\r\n * @returns the validated distro name.\r\n */\r\nfunction requireDistro(value: unknown): string {\r\n if (typeof value !== 'string' || !DISTRO_PATTERN.test(value) || value === '.' || value === '..') {\r\n throw new Error('distro must be a valid WSL distribution name')\r\n }\r\n return value\r\n}\r\n\r\n/** Human text for an unknown rejection. */\r\nfunction messageOf(value: unknown): string {\r\n return value instanceof Error ? value.message : String(value)\r\n}\r\n\r\n/** Write one JSON envelope. */\r\nfunction json(res: ServerResponse, status: number, body: Envelope<unknown>): void {\r\n res.writeHead(status, {\r\n 'content-type': 'application/json; charset=utf-8',\r\n 'cache-control': 'no-store',\r\n 'x-content-type-options': 'nosniff',\r\n })\r\n res.end(JSON.stringify(body))\r\n}\r\n\r\n/** Collect and parse the request body, bounded. */\r\nasync function readBody(req: IncomingMessage): Promise<Record<string, unknown>> {\r\n const chunks: Buffer[] = []\r\n let size = 0\r\n for await (const chunk of req) {\r\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\r\n size += buffer.length\r\n if (size > MAX_BODY_BYTES) throw new Error('request body is too large')\r\n chunks.push(buffer)\r\n }\r\n const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown\r\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\r\n throw new Error('request body must be a JSON object')\r\n }\r\n return parsed as Record<string, unknown>\r\n}\r\n\r\n/** Normalize a Linux path for the wire (rejecting non-absolute input). */\r\nfunction requireLinuxPath(value: unknown, label: string): string {\r\n if (typeof value !== 'string' || !isAbsoluteLinuxPath(value)) {\r\n throw new Error(`${label} must be an absolute Linux path`)\r\n }\r\n return normalizeLinuxPath(value)\r\n}\r\n\r\n/** Validate a wire-supplied workspace path and return its canonical UNC form. */\r\nfunction requireWslUnc(value: unknown): string {\r\n if (typeof value !== 'string') throw new Error('path must be a string')\r\n const canonical = canonicalWslUnc(value)\r\n if (canonical === null) throw new Error('path must be a WSL UNC workspace path')\r\n return canonical\r\n}\r\n\r\n/**\r\n * Resolve one directory listing for the dialog. The 9P share (`\\\\wsl.localhost\\…`)\r\n * serves only the ext4 volume: `/mnt/<drive>` (drvfs) reads return Access\r\n * denied, so drvfs paths are read through their Windows drive spelling and\r\n * `/mnt` itself is synthesized from the drives present on the host.\r\n */\r\nfunction listWslDir(distro: string, linuxPath: string): WslDirListingWire {\r\n if (linuxPath === '/mnt') {\r\n const entries: WslDirEntryWire[] = []\r\n for (let i = 0; i < 26; i++) {\r\n const letter = String.fromCharCode(65 + i)\r\n try {\r\n const info = statSync(`${letter}:\\\\`)\r\n if (info.isDirectory()) entries.push({ name: letter.toLowerCase(), kind: 'directory' })\r\n } catch {\r\n // Absent drive: skip.\r\n }\r\n }\r\n return { path: '/mnt', parent: '/', entries }\r\n }\r\n const winPath = mntToWindowsPath(linuxPath)\r\n const readPath = winPath !== null ? winPath : joinUnc(distro, linuxPath)\r\n const dirents = readdirSync(readPath, { withFileTypes: true })\r\n const entries: WslDirEntryWire[] = dirents\r\n .slice(0, 1000)\r\n .map((dirent): WslDirEntryWire => {\r\n const kind: WslDirEntryWire['kind'] = dirent.isDirectory()\r\n ? 'directory'\r\n : dirent.isFile() ? 'file' : 'other'\r\n return { name: dirent.name, kind }\r\n })\r\n .sort((a, b) => {\r\n if (a.kind === 'directory' && b.kind !== 'directory') return -1\r\n if (a.kind !== 'directory' && b.kind === 'directory') return 1\r\n return a.name.localeCompare(b.name)\r\n })\r\n const parent = linuxPath === '/' ? null : linuxPath.split('/').slice(0, -1).join('/') || '/'\r\n return { path: linuxPath, parent, entries }\r\n}\r\n\r\n/** Route one method dispatch. */\r\nasync function dispatch(method: string, params: Record<string, unknown>): Promise<unknown> {\r\n switch (method) {\r\n case 'listDistros': {\r\n const distros = await listDistros()\r\n const fallback = await defaultDistro()\r\n if (fallback !== undefined && distros.includes(fallback)) {\r\n return [fallback, ...distros.filter(name => name !== fallback)]\r\n }\r\n return distros\r\n }\r\n case 'listDir': {\r\n const distro = requireDistro(params.distro)\r\n const path = requireLinuxPath(params.path, 'path')\r\n return listWslDir(distro, path)\r\n }\r\n case 'check': {\r\n const distro = requireDistro(params.distro)\r\n const path = requireLinuxPath(params.path, 'path')\r\n // drvfs paths (Access denied over 9P) are checked through their drive spelling.\r\n const winPath = mntToWindowsPath(path)\r\n const readPath = winPath !== null ? winPath : joinUnc(distro, path)\r\n try {\r\n const info = statSync(readPath)\r\n return { exists: true, isDirectory: info.isDirectory() }\r\n } catch {\r\n return { exists: false, isDirectory: false }\r\n }\r\n }\r\n case 'registerWindows': {\r\n // A `/mnt/<drive>` workspace registers under its Windows drive path\r\n // (the registry realpath/stats it, and 9P cannot serve drvfs) with the\r\n // distro stored for the per-session env contributor.\r\n const distro = requireDistro(params.distro)\r\n const linuxPath = requireLinuxPath(params.linuxPath, 'path')\r\n const winPath = mntToWindowsPath(linuxPath)\r\n if (winPath === null) throw new Error('registerWindows requires a /mnt/<drive> Linux path')\r\n const username = typeof params.username === 'string' ? params.username : undefined\r\n registerWindowsWorkspace(winPath, distro, username)\r\n return null\r\n }\r\n case 'listWorkspaces': {\r\n // Every registered WSL workspace key (UNC and Windows drive spellings):\r\n // the client uses the drive keys to recognize `/mnt` workspaces.\r\n return listWorkspaceKeys()\r\n }\r\n case 'setUser': {\r\n const path = requireWslUnc(params.path)\r\n const username = params.username\r\n if (username === undefined || username === '') {\r\n setWorkspaceUsername(path, undefined)\r\n } else {\r\n if (typeof username !== 'string' || !isValidWslUsername(username)) {\r\n throw new Error('username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\r\n }\r\n setWorkspaceUsername(path, username)\r\n }\r\n return null\r\n }\r\n default:\r\n throw new Error(`unknown method \"${method}\"`)\r\n }\r\n}\r\n\r\n/** The `ctx.agentPresets` roster face this plugin consumes (optional service). */\r\ninterface AgentPresetsService {\r\n list(): Promise<{ id: string; broken?: string; path: string }[]>\r\n read(id: string): Promise<string>\r\n}\r\n\r\n/**\r\n * Publish a fully staged preset directory while preserving the last complete\r\n * variant if publication fails. Stable sibling names also let the next boot\r\n * recover an interrupted old-to-backup rename before doing new work.\r\n */\r\nfunction publishVariant(staging: string, dest: string): void {\r\n const previous = `${dest}.previous`\r\n if (!existsSync(dest) && existsSync(previous)) renameSync(previous, dest)\r\n if (existsSync(previous)) rmSync(previous, { recursive: true, force: true })\r\n if (existsSync(dest)) renameSync(dest, previous)\r\n try {\r\n renameSync(staging, dest)\r\n } catch (error) {\r\n if (!existsSync(dest) && existsSync(previous)) renameSync(previous, dest)\r\n throw error\r\n }\r\n rmSync(previous, { recursive: true, force: true })\r\n}\r\n\r\n/** Materialize one WSL variant per healthy source preset. */\r\nasync function materializeVariants(\r\n agentPresets: AgentPresetsService,\r\n dshHome: string,\r\n shellPath: string,\r\n fsPath: string,\r\n): Promise<void> {\r\n const presets = await agentPresets.list()\r\n const userRoot = join(dshHome, '.agent-presets')\r\n const generated = new Set<string>()\r\n for (const preset of presets) {\r\n if (preset.broken !== undefined) continue\r\n if (isWslVariantId(preset.id)) continue\r\n const variantId = variantIdFor(preset.id)\r\n const source = await agentPresets.read(preset.id)\r\n const transformed = transformPresetForWsl(source, shellPath, fsPath)\r\n const dir = join(userRoot, variantId)\r\n const staging = `${dir}.staging`\r\n rmSync(staging, { recursive: true, force: true })\r\n // A preset directory is an opaque, self-contained plugin unit. Mirror it\r\n // without interpreting local code or asset names, then overwrite only the\r\n // two files owned by this generator.\r\n cpSync(dirname(preset.path), staging, { recursive: true, force: true })\r\n writeFileSync(join(staging, 'agent.cordis.yml'), transformed, 'utf8')\r\n const labels = MODE_DISPLAY_LABELS[preset.id]\r\n let name = variantName(preset.id, preset.id)\r\n let orderLine = ''\r\n try {\r\n const meta = readFileSync(join(dirname(preset.path), 'preset.yml'), 'utf8')\r\n if (labels === undefined) {\r\n // Custom presets keep their own display name; shipped modes use the\r\n // bilingual labels above so both locales can identify the variant.\r\n const match = /^name:\\s*(.+)$/m.exec(meta)\r\n if (match?.[1] !== undefined && match[1].trim() !== '') {\r\n name = variantName(preset.id, match[1].trim())\r\n }\r\n }\r\n // Inherit the source's declared order so the WSL variants line up with\r\n // the local modes in the roster (standard, PTC, minimal, cordis).\r\n const orderMatch = /^order:\\s*(\\d+)\\s*$/m.exec(meta)\r\n if (orderMatch?.[1] !== undefined) orderLine = `order: ${orderMatch[1]}\\n`\r\n } catch {\r\n // Absent or unreadable display metadata falls back to the id-based name.\r\n }\r\n writeFileSync(\r\n join(staging, 'preset.yml'),\r\n `name: ${yamlScalar(name)}\\n`\r\n + orderLine\r\n + `description: ${yamlScalar(variantDescription(preset.id))}\\n`,\r\n 'utf8',\r\n )\r\n publishVariant(staging, dir)\r\n generated.add(variantId)\r\n }\r\n for (const entry of readdirSync(userRoot, { withFileTypes: true })) {\r\n if (!entry.isDirectory()) continue\r\n if (entry.name === 'wsl') {\r\n // The legacy standalone WSL mode: folded into the variants above.\r\n rmSync(join(userRoot, entry.name), { recursive: true, force: true })\r\n continue\r\n }\r\n if (!/^wsl-[a-z0-9-]+$/.test(entry.name)) continue\r\n if (!generated.has(entry.name)) rmSync(join(userRoot, entry.name), { recursive: true, force: true })\r\n }\r\n}\r\n\r\n/** Function-plugin plugin contract. */\r\nexport const name = 'dsh-wsl-workspace'\r\n\r\n/** Required services. */\r\nexport const inject = ['webServer']\r\n\r\n/** Validated plugin config (schemastery applied the defaults). */\r\nexport const Config: z<Config> = z.object({\r\n route: z.string().default(DEFAULT_ROUTE),\r\n})\r\n\r\n/**\r\n * Apply the host half: materialize a `wsl-<mode>` variant for every healthy\r\n * roster preset, register the data route, and\r\n * contribute the per-session `DSH_WSL_DISTRO` managed-env fact so the WSL\r\n * shell executor can resolve a plain Linux `workdir` to the calling\r\n * session's distribution.\r\n * @param ctx - the host plugin context.\r\n * @param config - the validated configuration.\r\n */\r\nexport function apply(ctx: Context, config: Config): void {\r\n const resolved = config as ResolvedConfig\r\n const dshHome = process.env.DSH_HOME ?? join(homedir(), '.dsh')\r\n const packageRoot = fileURLToPath(new URL('..', import.meta.url))\r\n const shellPath = join(packageRoot, 'lib', 'shell.js').replace(/\\\\/g, '/')\r\n const fsPath = join(packageRoot, 'lib', 'fs.js').replace(/\\\\/g, '/')\r\n\r\n const agentPresets = ctx.get('agentPresets') as unknown as AgentPresetsService | undefined\r\n if (agentPresets !== undefined) {\r\n ctx.effect(() => {\r\n void materializeVariants(agentPresets, dshHome, shellPath, fsPath).catch((error) => {\r\n // Variant generation is best-effort over a live roster: a missing or\r\n // unreadable source preset must not take the whole plugin down, but\r\n // the failure is surfaced loudly rather than hidden.\r\n console.error(`dsh-wsl-workspace: WSL preset-variant generation failed: ${messageOf(error)}`)\r\n })\r\n return () => {}\r\n }, 'dsh-wsl-workspace: WSL preset variants')\r\n }\r\n\r\n const shellEnv = ctx.get('shellEnv') as unknown as ShellEnvService | undefined\r\n if (shellEnv !== undefined) {\r\n ctx.effect(() => shellEnv.register({\r\n name: 'wsl-workspace-distro',\r\n variables: {\r\n DSH_WSL_DISTRO: {\r\n description: 'The WSL distribution of the calling session workspace, when the session cwd is a WSL UNC path.',\r\n },\r\n DSH_WSL_USER: {\r\n description: 'The Linux user of the calling session workspace, when the workspace has one configured.',\r\n },\r\n },\r\n resolve(execution) {\r\n const cwd = execution.agent?.session.header.cwd\r\n const unc = cwd === undefined ? null : parseWslUnc(cwd)\r\n if (unc !== null) {\r\n const username = getWorkspaceUsername(joinUnc(unc.distro, unc.linuxPath))\r\n return username === undefined || username === ''\r\n ? { DSH_WSL_DISTRO: unc.distro }\r\n : { DSH_WSL_DISTRO: unc.distro, DSH_WSL_USER: username }\r\n }\r\n // A Windows-drive cwd belongs to a `/mnt/<drive>` WSL workspace (9P\r\n // cannot serve drvfs, so those register under their drive path): the\r\n // stored distro drives `wsl.exe -d` for bash.\r\n if (cwd !== undefined && /^[A-Za-z]:[\\\\/]/.test(cwd)) {\r\n const entry = getWindowsWorkspace(cwd)\r\n if (entry !== undefined && entry.distro !== undefined && entry.distro !== '') {\r\n return entry.username === undefined || entry.username === ''\r\n ? { DSH_WSL_DISTRO: entry.distro }\r\n : { DSH_WSL_DISTRO: entry.distro, DSH_WSL_USER: entry.username }\r\n }\r\n }\r\n return {}\r\n },\r\n }), 'dsh-wsl-workspace: per-session distro env fact')\r\n }\r\n\r\n const webServer = ctx.get('webServer') as unknown as WebServerService\r\n ctx.effect(() => webServer.register({\r\n kind: 'exact',\r\n path: resolved.route,\r\n handler: async (req, res) => {\r\n if (!isLoopback(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host)) {\r\n json(res, 403, { ok: false, error: 'loopback-only' })\r\n return\r\n }\r\n if (req.method !== 'POST') {\r\n json(res, 405, { ok: false, error: 'method not allowed' })\r\n return\r\n }\r\n let body: Record<string, unknown>\r\n try {\r\n body = await readBody(req)\r\n } catch (error) {\r\n json(res, 400, { ok: false, error: messageOf(error) })\r\n return\r\n }\r\n const method = typeof body.method === 'string' ? body.method : ''\r\n const params = body.params === undefined ? {} : body.params\r\n if (params === null || typeof params !== 'object' || Array.isArray(params)) {\r\n json(res, 400, { ok: false, error: 'params must be an object' })\r\n return\r\n }\r\n try {\r\n const value = await dispatch(method, params as Record<string, unknown>)\r\n json(res, 200, { ok: true, value })\r\n } catch (error) {\r\n json(res, 200, { ok: false, error: messageOf(error) })\r\n }\r\n },\r\n }), 'dsh-wsl-workspace: dialog data route')\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,aAAa,IAAI,IAAI;CAAC;CAAa;CAAa;CAAW;CAAkB;CAAsB;CAAc;CAAoB;CAAe;AAAsB,CAAC;;AAGjL,SAAS,cAAc,WAAmB,QAAgB,eAAgC;CACxF,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,gBAAgB,UAAU,QAAQ,MAAM,IAAI,EAAE;EAC9C;EACA,gBAAgB,OAAO,QAAQ,MAAM,IAAI,EAAE;EAC3C;EACA;EACA;EACA;EAIA,GAAI,gBACA;GACE;GACA;GACA;GACA;EACF,IACA,CAAC;EACL;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;AAGA,MAAM,iBAAiB;;AAGvB,SAAS,cAAc,OAA4D;CACjF,MAAM,QAA0C,CAAC;CACjD,IAAI,QAAQ;CACZ,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SACxC,IAAI,MAAM,MAAM,EAAE,WAAW,QAAQ,MAAM,MAAM;EAC/C,IAAI,SAAS,GAAG,MAAM,KAAK;GAAE;GAAO,KAAK;EAAM,CAAC;EAChD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AAI,IAAI,WAAW;CACrC,IAAI,aAAa,UAAU,SAAS;EAClC,MAAM;EACN,MAAM,SAAS;EACf,SAAS,OAAO,KAAK,QAAQ;GAC3B,IAAI,CAAC,WAAW,IAAI,OAAO,aAAa,KAAK,CAAC,eAAe,IAAI,QAAQ,IAAI,GAAG;IAC9E,KAAK,KAAK,KAAK;KAAE,IAAI;KAAO,OAAO;IAAgB,CAAC;IACpD;GACF;GACA,IAAI,IAAI,WAAW,QAAQ;IACzB,KAAK,KAAK,KAAK;KAAE,IAAI;KAAO,OAAO;IAAqB,CAAC;IACzD;GACF;GACA,IAAI;GACJ,IAAI;IACF,OAAO,MAAM,SAAS,GAAG;GAC3B,SAAS,OAAO;IACd,KAAK,KAAK,KAAK;KAAE,IAAI;KAAO,OAAO,UAAU,KAAK;IAAE,CAAC;IACrD;GACF;GACA,MAAM,SAAS,OAAO,KAAK,WAAW,WAAW,KAAK,SAAS;GAC/D,MAAM,SAAS,KAAK,WAAW,KAAA,IAAY,CAAC,IAAI,KAAK;GACrD,IAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GAAG;IAC1E,KAAK,KAAK,KAAK;KAAE,IAAI;KAAO,OAAO;IAA2B,CAAC;IAC/D;GACF;GACA,IAAI;IAEF,KAAK,KAAK,KAAK;KAAE,IAAI;KAAM,OAAA,MADP,SAAS,QAAQ,MAAiC;IACrC,CAAC;GACpC,SAAS,OAAO;IACd,KAAK,KAAK,KAAK;KAAE,IAAI;KAAO,OAAO,UAAU,KAAK;IAAE,CAAC;GACvD;EACF;CACF,CAAC,GAAG,sCAAsC;AAC5C"}
|
|
@@ -78,6 +78,21 @@ function mntToWindowsPath(linuxPath) {
|
|
|
78
78
|
return `${(match[1] ?? "").toUpperCase()}:\\${rest}`;
|
|
79
79
|
}
|
|
80
80
|
/**
|
|
81
|
+
* Canonical Windows drive path for store keys and cross-realm identity:
|
|
82
|
+
* separators unified to `\`, trailing separator stripped, and the WHOLE path
|
|
83
|
+
* lowercased — Windows paths compare case-insensitively, and the workspace
|
|
84
|
+
* registry may realpath a different casing than the caller spelled (8.3 or
|
|
85
|
+
* on-disk casing), so the store key must collide across casings.
|
|
86
|
+
* @param path - candidate Windows drive path.
|
|
87
|
+
* @returns the canonical form, or `null` when not drive-shaped.
|
|
88
|
+
*/
|
|
89
|
+
function canonicalWindowsPath(path) {
|
|
90
|
+
const match = /^([A-Za-z]):[\\/](.*)$/.exec(path);
|
|
91
|
+
if (match === null) return null;
|
|
92
|
+
const rest = (match[2] ?? "").replace(/[\\/]+/g, "\\").replace(/\\$/, "").toLowerCase();
|
|
93
|
+
return `${(match[1] ?? "").toLowerCase()}:\\${rest}`;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
81
96
|
* True when a value is a Windows-shaped path (drive or UNC), which is how
|
|
82
97
|
* the shell executor decides the WSLENV `/p` translation flag: only Windows
|
|
83
98
|
* path values need translation when they cross into the Linux process.
|
|
@@ -100,6 +115,6 @@ function isValidWslUsername(value) {
|
|
|
100
115
|
return WSL_USERNAME_PATTERN.test(value);
|
|
101
116
|
}
|
|
102
117
|
//#endregion
|
|
103
|
-
export {
|
|
118
|
+
export { joinUnc as a, parseWslUnc as c, isWindowsPathShaped as i, windowsToMntPath as l, isAbsoluteLinuxPath as n, mntToWindowsPath as o, isValidWslUsername as r, normalizeLinuxPath as s, canonicalWindowsPath as t };
|
|
104
119
|
|
|
105
|
-
//# sourceMappingURL=paths-
|
|
120
|
+
//# sourceMappingURL=paths-BDE1NVOv.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths-BDE1NVOv.js","names":[],"sources":["../src/shared/paths.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"],"mappings":";;AAWA,MAAM,YAAY,CAAC,iBAAoB,MAAe;;;;;;;;AAiBtD,SAAgB,YAAY,KAAkC;CAC5D,MAAM,aAAa,IAAI,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,UAAU,IAAI;CACjE,IAAI,CAAC,WAAW,WAAW,IAAI,GAAG,OAAO;CACzC,MAAM,WAAW,WAAW,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG;CAC9C,MAAM,QAAQ,SAAS,MAAM,GAAA,CAAI,YAAY;CAC7C,IAAI,CAAC,UAAU,SAAS,IAAI,GAAG,OAAO;CACtC,MAAM,SAAS,SAAS,MAAM;CAC9B,IAAI,WAAW,IAAI,OAAO;CAE1B,OAAO;EAAE;EAAQ,WAAW,IADf,SAAS,MAAM,CAAC,CAAC,CAAC,QAAO,YAAW,QAAQ,SAAS,CAC/B,CAAC,CAAC,KAAK,GAAG;CAAI;AACnD;;;;;;;AAiCA,SAAgB,mBAAmB,MAAsB;CAC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