dsh-wsl-workspace 0.3.2 → 0.4.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.md +12 -0
- package/TESTING.md +11 -5
- package/lib/client.js +1053 -1052
- package/lib/client.js.map +1 -1
- package/lib/fs.js +1 -1
- package/lib/index.js +116 -13
- package/lib/index.js.map +1 -1
- package/lib/shell.js +382 -382
- package/lib/{wsl-credentials-BI4v5TNZ.js → wsl-credentials-BwNmfX_y.js} +109 -109
- package/lib/{wsl-credentials-BI4v5TNZ.js.map → wsl-credentials-BwNmfX_y.js.map} +1 -1
- package/lib/{wsl-C5_mxGPM.js → wsl-qwxCKU5O.js} +229 -228
- package/lib/wsl-qwxCKU5O.js.map +1 -0
- package/package.json +13 -2
- package/src/host/wsl-skills.ts +134 -12
- package/src/shared/paths.ts +6 -3
- package/lib/wsl-C5_mxGPM.js.map +0 -1
package/src/host/wsl-skills.ts
CHANGED
|
@@ -11,7 +11,11 @@
|
|
|
11
11
|
* This provider mirrors the host's discovery rules for WSL UNC session
|
|
12
12
|
* workspaces: it starts at the session cwd's nearest `.git` ancestor (the
|
|
13
13
|
* host's project-root rule; the cwd itself when no ancestor has a `.git`
|
|
14
|
-
* marker), then walks that root (depth- and budget-bounded)
|
|
14
|
+
* marker), then walks that root (depth- and budget-bounded). Directory
|
|
15
|
+
* symlinks are followed when the substrate resolves them and pruned safely
|
|
16
|
+
* when it does not — the `\\wsl.localhost` 9P share cannot resolve Linux
|
|
17
|
+
* symlink targets, so linked-in projects stay undiscoverable there today.
|
|
18
|
+
* The walk collects every
|
|
15
19
|
* `.dsh/skills` and `.agents/skills` directory it finds — including nested
|
|
16
20
|
* projects — and publishes their skills with the same
|
|
17
21
|
* project ranks and sources the host uses, so precedence and duplicate
|
|
@@ -42,7 +46,10 @@ const MAX_SKILL_ROOTS = 64
|
|
|
42
46
|
const MAX_VISITED_DIRECTORIES = 4096
|
|
43
47
|
/** How many parent levels above the session cwd are searched for a `.git` project marker. */
|
|
44
48
|
const MAX_ANCESTOR_WALK = 64
|
|
45
|
-
|
|
49
|
+
/** How long a completed lookup is served from cache before the next rescan. */
|
|
50
|
+
const CACHE_TTL_MS = 10_000
|
|
51
|
+
/** Maximum cached lookups (one entry per distinct scan root across sessions). */
|
|
52
|
+
const CACHE_MAX_ENTRIES = 32
|
|
46
53
|
/** Kebab-case skill names, matching the host grammar. */
|
|
47
54
|
const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
48
55
|
|
|
@@ -191,11 +198,26 @@ async function discoverSkillRoots(distro: string, linuxRoot: string, io: WslSkil
|
|
|
191
198
|
continue
|
|
192
199
|
}
|
|
193
200
|
for (const entry of entries) {
|
|
194
|
-
if (!entry.isDirectory()) continue
|
|
195
201
|
if (PRUNED_DIRECTORY_NAMES.has(entry.name)) continue
|
|
196
202
|
if (entry.name.startsWith('.') && entry.name !== '.dsh' && entry.name !== '.agents') continue
|
|
197
203
|
if (entry.name === '.dsh' || entry.name === '.agents') continue
|
|
198
|
-
|
|
204
|
+
const childPath = posix.join(dir, entry.name)
|
|
205
|
+
if (entry.isDirectory()) {
|
|
206
|
+
next.push([childPath, depth + 1])
|
|
207
|
+
continue
|
|
208
|
+
}
|
|
209
|
+
if (entry.isSymbolicLink()) {
|
|
210
|
+
// A project may be linked into the workspace via a directory
|
|
211
|
+
// symlink; follow it when the target is a directory. Symlink
|
|
212
|
+
// cycles stay bounded: every hop increments the depth (capped by
|
|
213
|
+
// MAX_SCAN_DEPTH) and the walk as a whole by MAX_VISITED_DIRECTORIES.
|
|
214
|
+
try {
|
|
215
|
+
const target = await io.stat(joinUnc(distro, childPath))
|
|
216
|
+
if (target.isDirectory()) next.push([childPath, depth + 1])
|
|
217
|
+
} catch {
|
|
218
|
+
// Dangling symlink: nothing to traverse.
|
|
219
|
+
}
|
|
220
|
+
}
|
|
199
221
|
}
|
|
200
222
|
}
|
|
201
223
|
frontier = next
|
|
@@ -263,19 +285,33 @@ async function readSkill(path: string, io: WslSkillIo, signal?: AbortSignal): Pr
|
|
|
263
285
|
/**
|
|
264
286
|
* Parse the frontmatter subset skill files use: `---` fenced YAML with
|
|
265
287
|
* `name` / `description` / `whenToUse` / `user-invocable` /
|
|
266
|
-
* `disable-model-invocation`.
|
|
267
|
-
*
|
|
288
|
+
* `disable-model-invocation`. Single-line scalars and block scalars
|
|
289
|
+
* (`|` literal, `>` folded) are understood; anything else is skipped,
|
|
290
|
+
* matching the shipped provider's leniency: a bad file must not fail
|
|
291
|
+
* the catalog.
|
|
268
292
|
*/
|
|
269
293
|
function parseSkillFrontmatter(raw: string, path: string): ParsedSkill | undefined {
|
|
294
|
+
// Windows editors save UTF-8 with a BOM; a leading BOM must not make the
|
|
295
|
+
// opening `---` line unmatchable and silently drop the skill.
|
|
296
|
+
if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1)
|
|
270
297
|
const firstLineEnd = raw.indexOf('\n')
|
|
271
298
|
if (firstLineEnd < 0) return undefined
|
|
272
299
|
if (raw.slice(0, firstLineEnd).replace(/\r$/, '') !== '---') return undefined
|
|
273
300
|
const start = firstLineEnd + 1
|
|
274
301
|
const closing = findFrontmatterEnd(raw, start)
|
|
275
302
|
if (closing === undefined) return undefined
|
|
303
|
+
const lines = raw.slice(start, closing).split('\n')
|
|
276
304
|
const fields = new Map<string, string>()
|
|
277
|
-
for (
|
|
278
|
-
const
|
|
305
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
306
|
+
const line = (lines[index] ?? '').replace(/\r$/, '')
|
|
307
|
+
const block = /^([A-Za-z0-9-]+):\s*([|>])[+-]?\s*$/.exec(line)
|
|
308
|
+
if (block !== null) {
|
|
309
|
+
const value = parseBlockScalar(lines, index, block[2] === '>')
|
|
310
|
+
index = value.nextLineIndex
|
|
311
|
+
if (value.text !== '') fields.set(block[1] ?? '', value.text)
|
|
312
|
+
continue
|
|
313
|
+
}
|
|
314
|
+
const match = /^([A-Za-z0-9-]+):\s*(.*)$/.exec(line)
|
|
279
315
|
if (match === null) continue
|
|
280
316
|
const value = match[2]?.trim() ?? ''
|
|
281
317
|
if (value !== '') fields.set(match[1] ?? '', unquote(value))
|
|
@@ -298,6 +334,40 @@ function parseSkillFrontmatter(raw: string, path: string): ParsedSkill | undefin
|
|
|
298
334
|
}
|
|
299
335
|
}
|
|
300
336
|
|
|
337
|
+
/**
|
|
338
|
+
* Collect a YAML block scalar (`key: |` literal or `key: >` folded) starting
|
|
339
|
+
* at `startIndex`'s following lines. The block runs until the first
|
|
340
|
+
* non-indented, non-blank line; its common indentation is stripped.
|
|
341
|
+
* @returns the scalar text and the index of the last consumed line.
|
|
342
|
+
*/
|
|
343
|
+
function parseBlockScalar(
|
|
344
|
+
lines: string[],
|
|
345
|
+
startIndex: number,
|
|
346
|
+
folded: boolean,
|
|
347
|
+
): { text: string; nextLineIndex: number } {
|
|
348
|
+
const collected: string[] = []
|
|
349
|
+
let indent: string | undefined
|
|
350
|
+
let index = startIndex
|
|
351
|
+
while (index + 1 < lines.length) {
|
|
352
|
+
index += 1
|
|
353
|
+
const next = (lines[index] ?? '').replace(/\r$/, '')
|
|
354
|
+
if (next.trim() === '') {
|
|
355
|
+
collected.push('')
|
|
356
|
+
continue
|
|
357
|
+
}
|
|
358
|
+
const indented = /^([ \t]+)(.*)$/.exec(next)
|
|
359
|
+
if (indented === null) {
|
|
360
|
+
index -= 1
|
|
361
|
+
break
|
|
362
|
+
}
|
|
363
|
+
indent ??= indented[1]
|
|
364
|
+
collected.push(indented[1]?.startsWith(indent) === true ? indented[2] : indented[1].replace(/^[ \t]+/, '') + indented[2])
|
|
365
|
+
}
|
|
366
|
+
while (collected.length > 0 && collected[collected.length - 1] === '') collected.pop()
|
|
367
|
+
const text = (folded ? collected.filter(line => line !== '').join(' ') : collected.join('\n')).trim()
|
|
368
|
+
return { text, nextLineIndex: index }
|
|
369
|
+
}
|
|
370
|
+
|
|
301
371
|
/** Locate the closing `---` line of a frontmatter block. */
|
|
302
372
|
function findFrontmatterEnd(raw: string, start: number): number | undefined {
|
|
303
373
|
let lineStart = start
|
|
@@ -346,15 +416,25 @@ function frontmatterBoolean(fields: Map<string, string>, key: string, dflt = fal
|
|
|
346
416
|
/**
|
|
347
417
|
* The WSL workspace skill provider. Registered on the host's `ctx.skills`
|
|
348
418
|
* registry; serves only lookups whose cwd is a WSL UNC workspace path.
|
|
419
|
+
*
|
|
420
|
+
* Completed `list()` lookups are cached per scan root for CACHE_TTL_MS so
|
|
421
|
+
* repeated catalog builds over the slow 9P share do not rescan the tree;
|
|
422
|
+
* `get()` always re-reads the skill file so body edits are picked up
|
|
423
|
+
* immediately. `control.invalidate` remains reserved for host-driven
|
|
424
|
+
* invalidation; the provider self-invalidates through the TTL.
|
|
349
425
|
*/
|
|
350
426
|
export class WslSkillsProvider {
|
|
351
427
|
readonly name = 'wsl-workspace'
|
|
352
428
|
private readonly control: WslSkillProviderControl
|
|
353
429
|
private readonly io: WslSkillIo
|
|
430
|
+
private readonly now: () => number
|
|
431
|
+
private readonly cache = new Map<string, { expiresAt: number; candidates: WslSkillCandidate[] }>()
|
|
432
|
+
private readonly refreshing = new Set<string>()
|
|
354
433
|
|
|
355
|
-
constructor(control: WslSkillProviderControl, io: WslSkillIo = nodeSkillIo) {
|
|
434
|
+
constructor(control: WslSkillProviderControl, io: WslSkillIo = nodeSkillIo, now: () => number = Date.now) {
|
|
356
435
|
this.control = control
|
|
357
436
|
this.io = io
|
|
437
|
+
this.now = now
|
|
358
438
|
}
|
|
359
439
|
|
|
360
440
|
/**
|
|
@@ -375,14 +455,50 @@ export class WslSkillsProvider {
|
|
|
375
455
|
// Without a `.git` ancestor the session cwd itself is the scan root (the
|
|
376
456
|
// issue #10 workspace layout).
|
|
377
457
|
const scanRoot = (await nearestGitAncestor(unc.distro, unc.linuxPath, this.io)) ?? unc.linuxPath
|
|
378
|
-
const
|
|
458
|
+
const cacheKey = `${unc.distro}\u0000${scanRoot}`
|
|
459
|
+
const cached = this.cache.get(cacheKey)
|
|
460
|
+
if (cached !== undefined) {
|
|
461
|
+
if (cached.expiresAt > this.now()) {
|
|
462
|
+
this.cache.delete(cacheKey)
|
|
463
|
+
this.cache.set(cacheKey, cached)
|
|
464
|
+
return [...cached.candidates]
|
|
465
|
+
}
|
|
466
|
+
// Expired: serve the stale copy immediately and refresh in the
|
|
467
|
+
// background, so a slow scan (e.g. a distro-root workspace) never
|
|
468
|
+
// blocks the caller. A failed refresh keeps the stale entry and is
|
|
469
|
+
// retried on the next lookup.
|
|
470
|
+
if (!this.refreshing.has(cacheKey)) {
|
|
471
|
+
this.refreshing.add(cacheKey)
|
|
472
|
+
void this.scan(cacheKey, unc.distro, scanRoot, options.signal)
|
|
473
|
+
.catch(() => { /* keep the stale entry; retried on the next lookup */ })
|
|
474
|
+
.finally(() => { this.refreshing.delete(cacheKey) })
|
|
475
|
+
}
|
|
476
|
+
return [...cached.candidates]
|
|
477
|
+
}
|
|
478
|
+
return this.scan(cacheKey, unc.distro, scanRoot, options.signal)
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Run one discovery pass for a scan root and publish it into the cache.
|
|
483
|
+
* @returns the fresh candidates.
|
|
484
|
+
*/
|
|
485
|
+
private async scan(cacheKey: string, distro: string, scanRoot: string, signal?: AbortSignal): Promise<WslSkillCandidate[]> {
|
|
486
|
+
const roots = await discoverSkillRoots(distro, scanRoot, this.io)
|
|
379
487
|
const candidates: WslSkillCandidate[] = []
|
|
488
|
+
const seenSkills = new Set<string>()
|
|
380
489
|
for (const root of roots) {
|
|
381
490
|
const entries = await listSkillEntries(root, this.io)
|
|
382
491
|
for (const entry of entries) {
|
|
383
|
-
|
|
384
|
-
const parsed = await readSkill(entry.path, this.io,
|
|
492
|
+
signal?.throwIfAborted()
|
|
493
|
+
const parsed = await readSkill(entry.path, this.io, signal)
|
|
385
494
|
if (parsed === undefined) continue
|
|
495
|
+
// A project reachable through both its real path and a directory
|
|
496
|
+
// symlink yields aliasing roots whose locators differ; publish each
|
|
497
|
+
// distinct (name, description, body) once so the catalog shows no
|
|
498
|
+
// duplicates.
|
|
499
|
+
const fingerprint = `${parsed.name}\u0000${parsed.description}\u0000${parsed.content}`
|
|
500
|
+
if (seenSkills.has(fingerprint)) continue
|
|
501
|
+
seenSkills.add(fingerprint)
|
|
386
502
|
candidates.push({
|
|
387
503
|
name: parsed.name,
|
|
388
504
|
description: parsed.description,
|
|
@@ -401,6 +517,12 @@ export class WslSkillsProvider {
|
|
|
401
517
|
})
|
|
402
518
|
}
|
|
403
519
|
}
|
|
520
|
+
this.cache.set(cacheKey, { expiresAt: this.now() + CACHE_TTL_MS, candidates })
|
|
521
|
+
while (this.cache.size > CACHE_MAX_ENTRIES) {
|
|
522
|
+
const oldest = this.cache.keys().next().value
|
|
523
|
+
if (oldest === undefined) break
|
|
524
|
+
this.cache.delete(oldest)
|
|
525
|
+
}
|
|
404
526
|
return candidates
|
|
405
527
|
}
|
|
406
528
|
|
package/src/shared/paths.ts
CHANGED
|
@@ -32,10 +32,13 @@ export function parseWslUnc(raw: string): WslUncTarget | null {
|
|
|
32
32
|
const segments = normalized.slice(2).split('/')
|
|
33
33
|
const host = (segments[0] ?? '').toLowerCase()
|
|
34
34
|
if (!UNC_HOSTS.includes(host)) return null
|
|
35
|
-
|
|
35
|
+
// Empty segments (double separators anywhere after the host) are
|
|
36
|
+
// collapsed: `\\wsl.localhost\\Ubuntu\home` and trailing slashes must
|
|
37
|
+
// parse the same as their single-separator spelling.
|
|
38
|
+
const parts = segments.filter(segment => segment.length > 0)
|
|
39
|
+
const distro = parts[1] ?? ''
|
|
36
40
|
if (distro === '') return null
|
|
37
|
-
|
|
38
|
-
return { distro, linuxPath: `/${rest.join('/')}` }
|
|
41
|
+
return { distro, linuxPath: `/${parts.slice(2).join('/')}` }
|
|
39
42
|
}
|
|
40
43
|
|
|
41
44
|
/**
|
package/lib/wsl-C5_mxGPM.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"wsl-C5_mxGPM.js","names":[],"sources":["../src/shared/paths.ts","../src/shared/wsl.ts"],"sourcesContent":["/**\r\n * WSL path helpers shared by the client and host halves. Pure and\r\n * dependency-free so both planes can import them without a runtime edge.\r\n */\r\n\r\n/** WSL2 default loopback bridge host: `\\\\wsl.localhost\\<distro>\\...`. */\r\nconst WSL_LOCALHOST_HOST = 'wsl.localhost'\r\n/** Legacy WSL interop host: `\\\\wsl$\\<distro>\\...`. */\r\nconst WSL_LEGACY_HOST = 'wsl$'\r\n\r\n/** The two UNC hosts WSL exposes a distribution's filesystem under. */\r\nconst UNC_HOSTS = [WSL_LOCALHOST_HOST, WSL_LEGACY_HOST]\r\n\r\n/** One WSL workspace coordinate parsed out of a UNC path. */\r\nexport interface WslUncTarget {\r\n /** Distro name (e.g. `Ubuntu`) as `wsl -l -q` reports it. */\r\n readonly distro: string\r\n /** Normalized absolute Linux path (leading `/`; no trailing slash except root). */\r\n readonly linuxPath: string\r\n}\r\n\r\n/**\r\n * Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2\r\n * `\\\\wsl.localhost\\<distro>\\<linux>` form, the legacy `\\\\wsl$\\<distro>\\<linux>`\r\n * interop form, and forward-slash spellings of either.\r\n * @param raw - candidate absolute path.\r\n * @returns the parsed target, or null when the path is not a WSL UNC.\r\n */\r\nexport function parseWslUnc(raw: string): WslUncTarget | null {\r\n const normalized = raw.replace(/\\\\/g, '/').replace(/\\/\\/+/g, '//')\r\n if (!normalized.startsWith('//')) return null\r\n const segments = normalized.slice(2).split('/')\r\n const host = (segments[0] ?? '').toLowerCase()\r\n if (!UNC_HOSTS.includes(host)) return null\r\n const distro = segments[1] ?? ''\r\n if (distro === '') return null\r\n const rest = segments.slice(2).filter(segment => segment.length > 0)\r\n return { distro, linuxPath: `/${rest.join('/')}` }\r\n}\r\n\r\n/**\r\n * Whether a path resolves into a WSL distro through either UNC form.\r\n * @param raw - candidate absolute path.\r\n * @returns whether the path parses as a WSL UNC.\r\n */\r\nexport function isWslUnc(raw: string): boolean {\r\n return parseWslUnc(raw) !== null\r\n}\r\n\r\n/**\r\n * Translate a WSL UNC path to the absolute Linux path a process inside the\r\n * distribution can open. Throws on non-WSL input: callers rely on this\r\n * conversion to hand paths to the Linux world, so a silent pass-through\r\n * would hand a Windows path to bash.\r\n * @param uncPath - a path {@link parseWslUnc} accepts.\r\n * @returns the absolute Linux path.\r\n */\r\nexport function uncToLinux(uncPath: string): string {\r\n const parts = parseWslUnc(uncPath)\r\n if (parts === null) {\r\n throw new Error(`wsl-workspace: \"${uncPath}\" is not a WSL UNC path`)\r\n }\r\n return parts.linuxPath\r\n}\r\n\r\n/**\r\n * Normalize a Linux absolute path for the Host: collapse repeated slashes and\r\n * strip a trailing slash (root becomes `/`).\r\n * @param path - absolute Linux path.\r\n * @returns the normalized path.\r\n */\r\nexport function normalizeLinuxPath(path: string): string {\r\n const collapsed = path.replace(/\\/+/g, '/')\r\n return collapsed === '/' ? '/' : collapsed.replace(/\\/$/, '')\r\n}\r\n\r\n/**\r\n * Whether a path is an absolute, non-empty Linux path.\r\n * @param path - candidate.\r\n * @returns whether it starts with `/` and contains no NUL.\r\n */\r\nexport function isAbsoluteLinuxPath(path: string): boolean {\r\n return path.startsWith('/') && !path.includes('\\0')\r\n}\r\n\r\n/**\r\n * Join a distro and a Linux absolute path into the WSL2 UNC form used as the\r\n * workspace identity (`\\\\wsl.localhost\\<distro>\\<linux>`, backslash segments).\r\n * @param distro - distro name.\r\n * @param linuxPath - absolute Linux path (leading `/`).\r\n * @returns the UNC path.\r\n */\r\nexport function joinUnc(distro: string, linuxPath: string): string {\r\n if (!isAbsoluteLinuxPath(linuxPath)) {\r\n throw new Error(`wsl-workspace: cannot map a non-absolute Linux path \"${linuxPath}\" to UNC`)\r\n }\r\n // Defense in depth: a distribution name with separators or dot-dirs would\r\n // escape the `\\\\wsl.localhost\\` share structure (the host route validates\r\n // wire-supplied names too; every other caller passes through here).\r\n if (distro === '' || distro === '.' || distro === '..' || /[\\\\/]/.test(distro)) {\r\n throw new Error(`wsl-workspace: invalid distribution name \"${distro}\"`)\r\n }\r\n const normalized = linuxPath.replace(/\\/+/g, '/').replace(/\\/$/, '')\r\n const withoutLeading = normalized.startsWith('/') ? normalized.slice(1) : normalized\r\n const windowsSegments = withoutLeading.replace(/\\//g, '\\\\')\r\n const suffix = windowsSegments === '' ? '' : `\\\\${windowsSegments}`\r\n return `\\\\\\\\wsl.localhost\\\\${distro}${suffix}`\r\n}\r\n\r\n/**\r\n * Translate a Windows drive path to the drvfs mount path WSL distributions\r\n * conventionally expose it at (`C:\\foo` → `/mnt/c/foo`). Only single-letter\r\n * drives under `/mnt` are mapped; custom mount points are out of scope.\r\n * @param path - the candidate Windows path.\r\n * @returns the `/mnt/<drive>/…` path, or `null` for non-drive paths.\r\n */\r\nexport function windowsToMntPath(path: string): string | null {\r\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\r\n if (match === null) return null\r\n const rest = (match[2] ?? '').replace(/\\\\/g, '/').replace(/\\/+/g, '/').replace(/\\/$/, '')\r\n return `/mnt/${(match[1] ?? '').toLowerCase()}${rest === '' ? '' : `/${rest}`}`\r\n}\r\n\r\n/**\r\n * Translate a `/mnt/<drive>/…` path back to its Windows drive path.\r\n * @param linuxPath - the candidate Linux path.\r\n * @returns the `X:\\…` drive path, or `null` when the path is not a drvfs mount.\r\n */\r\nexport function mntToWindowsPath(linuxPath: string): string | null {\r\n const match = /^\\/mnt\\/([a-zA-Z])(?:\\/(.*))?$/.exec(linuxPath)\r\n if (match === null) return null\r\n const rest = (match[2] ?? '').replace(/\\//g, '\\\\')\r\n return `${(match[1] ?? '').toUpperCase()}:\\\\${rest}`\r\n}\r\n\r\n/**\r\n * Canonical Windows drive path for store keys and cross-realm identity:\r\n * separators unified to `\\`, trailing separator stripped, and the WHOLE path\r\n * lowercased — Windows paths compare case-insensitively, and the workspace\r\n * registry may realpath a different casing than the caller spelled (8.3 or\r\n * on-disk casing), so the store key must collide across casings.\r\n * @param path - candidate Windows drive path.\r\n * @returns the canonical form, or `null` when not drive-shaped.\r\n */\r\nexport function canonicalWindowsPath(path: string): string | null {\r\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\r\n if (match === null) return null\r\n const rest = (match[2] ?? '').replace(/[\\\\/]+/g, '\\\\').replace(/\\\\$/, '').toLowerCase()\r\n return `${(match[1] ?? '').toLowerCase()}:\\\\${rest}`\r\n}\r\n\r\n/**\r\n * True when a value is a Windows-shaped path (drive or UNC), which is how\r\n * the shell executor decides the WSLENV `/p` translation flag: only Windows\r\n * path values need translation when they cross into the Linux process.\r\n * @param value - the environment value to classify.\r\n * @returns whether the value looks like a Windows path.\r\n */\r\nexport function isWindowsPathShaped(value: string): boolean {\r\n return /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\r\n}\r\n\r\n/** Linux username shape for `wsl.exe -u`: starts with a letter or underscore, then letters/digits/`_`/`.`/`-` (max 64). */\r\nconst WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/\r\n\r\n/**\r\n * Whether a value is a safe Linux username for `wsl.exe -u`. The check is\r\n * strict on purpose: a value starting with `-` could be parsed as a wsl.exe\r\n * option instead of a username.\r\n * @param value - candidate username.\r\n * @returns whether it matches the Linux username shape.\r\n */\r\nexport function isValidWslUsername(value: string): boolean {\r\n return WSL_USERNAME_PATTERN.test(value)\r\n}\r\n","/**\n * WSL discovery helpers (host side): enumerate installed distributions\n * through `wsl.exe -l -q` and read the default distribution from the Lxss\n * registry key. `wsl.exe` output is UTF-16LE on most builds, so decoding\n * sniffs for NUL bytes before choosing an encoding.\n * @module dsh-wsl-workspace/shared/wsl\n */\n\nimport { execFile, execFileSync } from 'node:child_process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\n/** Executable timeout for the short discovery calls. */\nconst DISCOVERY_TIMEOUT_MS = 10_000\n\nconst LXSS_KEY = 'HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Lxss'\n\n/** Human text for an unknown rejection. */\nfunction messageOf(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Decode `wsl.exe -l -q` output. Newer builds emit UTF-8; most emit UTF-16LE\n * with NUL bytes interleaved — the NUL probe picks the right one.\n * @param buffer - the raw captured output.\n * @returns the decoded text.\n */\nexport function decodeWslOutput(buffer: Buffer): string {\n return buffer.includes(0) ? buffer.toString('utf16le') : buffer.toString('utf8')\n}\n\n/**\n * List installed WSL distributions in `wsl.exe` order.\n * @param wslPath - the `wsl.exe` executable (absolute or PATH name).\n * @returns distribution names, blank lines dropped.\n */\nexport async function listDistros(wslPath = 'wsl.exe'): Promise<string[]> {\n let stdout: Buffer\n try {\n const result = await execFileAsync(wslPath, ['-l', '-q'], { encoding: 'buffer', timeout: DISCOVERY_TIMEOUT_MS })\n stdout = result.stdout as Buffer\n } catch (error) {\n throw new Error(`wsl-workspace: cannot list WSL distributions (${messageOf(error)}); is WSL installed?`)\n }\n return decodeWslOutput(stdout)\n .split(/\\r?\\n/)\n .map(line => line.trim())\n .filter(line => line.length > 0)\n}\n\n/**\n * Read the user's default distribution from the Lxss registry. Non-fatal:\n * returns `undefined` when the value is absent or unreadable (the caller\n * falls back to list order).\n * @returns the default distribution name, or `undefined`.\n */\nexport async function defaultDistro(): Promise<string | undefined> {\n try {\n const value = await execFileAsync('reg.exe', ['query', LXSS_KEY, '/v', 'DefaultDistribution'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const guid = /DefaultDistribution\\s+REG_SZ\\s+(\\{[0-9a-fA-F-]+\\})/i.exec(value.stdout)?.[1]\n if (guid === undefined) return undefined\n const name = await execFileAsync('reg.exe', ['query', `${LXSS_KEY}\\\\${guid}`, '/v', 'DistributionName'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const distro = /DistributionName\\s+REG_SZ\\s+(.+)/i.exec(name.stdout)?.[1]?.trim()\n return distro === undefined || distro === '' ? undefined : distro\n } catch {\n return undefined\n }\n}\n\n/** Module-level cache for {@link defaultDistroSync} (one registry read per process). */\nlet syncDefaultResolved = false\nlet syncDefault: string | undefined\n\n/**\n * Synchronous variant of {@link defaultDistro} for executors that must\n * resolve a distribution inside a synchronous plan step. Cached after the\n * first read; non-fatal (returns `undefined` when the registry is\n * unreadable, letting the caller fail loud with its own message).\n * @returns the default distribution name, or `undefined`.\n */\nexport function defaultDistroSync(): string | undefined {\n if (syncDefaultResolved) return syncDefault\n syncDefaultResolved = true\n try {\n const value = execFileSync('reg.exe', ['query', LXSS_KEY, '/v', 'DefaultDistribution'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const guid = /DefaultDistribution\\s+REG_SZ\\s+(\\{[0-9a-fA-F-]+\\})/i.exec(String(value))?.[1]\n if (guid === undefined) return undefined\n const name = execFileSync('reg.exe', ['query', `${LXSS_KEY}\\\\${guid}`, '/v', 'DistributionName'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const distro = /DistributionName\\s+REG_SZ\\s+(.+)/i.exec(String(name))?.[1]?.trim()\n syncDefault = distro === undefined || distro === '' ? undefined : distro\n } catch {\n syncDefault = undefined\n }\n return syncDefault\n}\n"],"mappings":";;;;AAWA,MAAM,YAAY,CAAC,iBAAoB,MAAe;;;;;;;;AAiBtD,SAAgB,YAAY,KAAkC;CAC5D,MAAM,aAAa,IAAI,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,UAAU,IAAI;CACjE,IAAI,CAAC,WAAW,WAAW,IAAI,GAAG,OAAO;CACzC,MAAM,WAAW,WAAW,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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