dsh-wsl-workspace 0.3.2 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,924 +1,1002 @@
1
- import { a as isAbsoluteLinuxPath, c as joinUnc, d as parseWslUnc, l as mntToWindowsPath, o as isValidWslUsername, r as listDistros, t as defaultDistro, u as normalizeLinuxPath } from "./wsl-C5_mxGPM.js";
2
- import { a as registerWindowsWorkspace, i as listWorkspaceKeys, n as getWindowsWorkspace, o as setWorkspaceUsername, r as getWorkspaceUsername, t as canonicalWslUnc } from "./wsl-credentials-BI4v5TNZ.js";
3
- import z from "@deepseek-ai/schemastery";
4
- import { cpSync, existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
5
- import { fileURLToPath } from "node:url";
6
- import { dirname, join, posix } from "node:path";
7
- import { homedir } from "node:os";
8
- import { readFile, readdir, stat } from "node:fs/promises";
9
- //#region src/host/variants.ts
10
- /**
11
- * WSL preset-variant generator. For every healthy source preset the roster
12
- * supplies, a `wsl-<id>` variant is materialized under the roster's user
13
- * root: the source composition with its shell/filesystem world replaced by
14
- * the WSL providers, so any mode (standard, minimal, code, cordis, user
15
- * presets) can run on top of a WSL execution world. The execution world is
16
- * therefore orthogonal to the mode instead of a mode itself.
17
- *
18
- * The transformation is text-level on the top-level rows of the composition
19
- * (the shape all shipped presets share), with surgical edits for the known
20
- * special groups; unknown shapes are kept verbatim where possible.
21
- * @module dsh-wsl-workspace/host/variants
22
- */
23
- /** Top-level rows that name the execution world and are replaced by the variant's own. */
24
- const WORLD_ROWS = new Set([
25
- "tool-bash",
26
- "tool-pwsh",
27
- "tool-fs",
28
- "tool-fs-search",
29
- "str-replace-editor",
30
- "filesystem",
31
- "persistent-shell",
32
- "custom-bash",
33
- "bootstrap-filesystem"
34
- ]);
35
- /** The injected WSL world group: providers + the bash/fs consumers, entry-local. */
36
- function wslWorldGroup(shellPath, fsPath, includeEditor) {
37
- return [
38
- "# ── WSL execution world (dsh-wsl-workspace variant) ─────────────────────",
39
- "# The shell and fs services are provided entry-locally (the isolate",
40
- "# realm); host services (tools registry, shell-env, jobs) fall through.",
41
- "# tool-fs-search is intentionally absent: the packaged ripgrep runs on",
42
- "# the Windows host and cannot open Linux paths; WSL sessions search with",
43
- "# shell tools instead.",
44
- "- id: wsl-world",
45
- " name: cordis:group",
46
- " group: true",
47
- " isolate:",
48
- " shell: true",
49
- " fs: true",
50
- " config:",
51
- ` - id: shell-wsl`,
52
- ` name: '${shellPath.replace(/'/g, "''")}'`,
53
- " - id: fs-wsl",
54
- ` name: '${fsPath.replace(/'/g, "''")}'`,
55
- " - id: tool-bash",
56
- " name: '@deepseek-ai/dsh-tool-bash'",
57
- " - id: tool-fs",
58
- " name: '@deepseek-ai/dsh-tool-fs'",
59
- ...includeEditor ? [
60
- " - id: str-replace-editor",
61
- " name: '@deepseek-ai/dsh-tool-str-replace-editor'",
62
- " config:",
63
- " maxOutputChars: 16000"
64
- ] : [],
65
- ""
66
- ].join("\n");
67
- }
68
- /** The sentence appended to a standard-like persona when the variant runs in WSL. */
69
- const 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.";
70
- /** The top-level rows of one composition, as (startLine, endLineExclusive) spans. */
71
- function topLevelSpans(lines) {
72
- const spans = [];
73
- let start = -1;
74
- for (let index = 0; index < lines.length; index++) if (lines[index]?.startsWith("- id: ") === true) {
75
- if (start >= 0) spans.push({
76
- start,
77
- end: index
78
- });
79
- start = index;
80
- }
81
- if (start >= 0) spans.push({
82
- start,
83
- end: lines.length
84
- });
85
- return spans;
86
- }
87
- /** The row id of a top-level span, or undefined when the first line is malformed. */
88
- function spanId(lines, span) {
89
- return /^- id: ([A-Za-z0-9_.-]+)/.exec(lines[span.start] ?? "")?.[1];
90
- }
91
- /** Whether a top-level span is a `persona` row with an appendable folded text. */
92
- function appendablePersona(lines, span) {
93
- const block = lines.slice(span.start, span.end).join("\n");
94
- if (!block.includes("complete: true") && /text: [>|-]/.test(block)) {
95
- const textLine = block.split("\n").find((line) => /^(\s*)text: [>|-]/.test(line));
96
- if (textLine !== void 0) {
97
- const indent = /^(\s*)/.exec(textLine)?.[1]?.length ?? 0;
98
- return block.split("\n").some((line) => line.length > indent && /^\s+/.test(line) && !line.includes(":"));
99
- }
100
- }
101
- return false;
102
- }
103
- /** Append the WSL sentence to a persona row's folded text (in place of its last text line). */
104
- function appendPersona(lines, span) {
105
- const block = lines.slice(span.start, span.end);
106
- const textIndex = block.findIndex((line) => /^(\s*)text: [>|-]/.test(line));
107
- if (textIndex < 0) return [...block];
108
- const indent = /^(\s*)/.exec(block[textIndex] ?? "")?.[1]?.length ?? 0;
109
- let lastText = -1;
110
- for (let index = textIndex + 1; index < block.length; index++) {
111
- const line = block[index] ?? "";
112
- if (line.trim() === "") continue;
113
- if (line.length > indent && /^\s+/.test(line)) lastText = index;
114
- }
115
- if (lastText < 0) return [...block];
116
- const updated = [...block];
117
- const textIndent = /^(\s*)/.exec(block[lastText] ?? "")?.[1] ?? " ";
118
- updated.splice(lastText + 1, 0, `${textIndent}${PERSONA_APPEND}`);
119
- return updated;
120
- }
121
- /**
122
- * Transform one source preset composition into its WSL variant: drop the
123
- * execution-world rows, keep everything else verbatim, and append the WSL
124
- * world group. The persistent-shell group is NOT re-added: it registers the
125
- * same `bash` tool name as the WSL world's `dsh-tool-bash`, and the tools
126
- * registry rejects duplicates within one preset layer — the whole variant
127
- * fails to mount and the session falls back to another preset. Its PTY
128
- * backend additionally cannot run on this plugin's Windows host
129
- * (`dsh-subprocess-local`: "terminal inspection is unsupported on platform
130
- * win32"), so the group could never spawn a shell here anyway. The WSL
131
- * world's ordinary `bash` tool covers command execution for every variant.
132
- * @param source - the source composition text.
133
- * @param shellPath - absolute path of the plugin's built WSL shell provider.
134
- * @param fsPath - absolute path of the plugin's built WSL fs provider.
135
- * @returns the variant composition text.
136
- */
137
- function transformPresetForWsl(source, shellPath, fsPath) {
138
- const lines = source.split("\n");
139
- const spans = topLevelSpans(lines);
140
- const kept = [];
141
- let sawEditor = false;
142
- let personaAppended = false;
143
- for (const span of spans) {
144
- const id = spanId(lines, span);
145
- if (id === void 0) {
146
- kept.push(...lines.slice(span.start, span.end));
147
- continue;
148
- }
149
- if (WORLD_ROWS.has(id)) continue;
150
- if (id === "persona" && !personaAppended && appendablePersona(lines, span)) {
151
- kept.push(...appendPersona(lines, span));
152
- personaAppended = true;
153
- continue;
154
- }
155
- kept.push(...lines.slice(span.start, span.end));
156
- if (id === "str-replace-editor") sawEditor = true;
157
- }
158
- if (source.includes("str-replace-editor")) sawEditor = true;
159
- const result = [...kept];
160
- if (result.length > 0 && result[result.length - 1] !== "") result.push("");
161
- result.push(wslWorldGroup(shellPath, fsPath, sawEditor));
162
- return result.join("\n").replace(/\n{3,}/g, "\n\n").replace(/\n+$/, "\n");
163
- }
164
- /** Whether an id is one of this plugin's own preset directories. */
165
- function isWslVariantId(id) {
166
- return id === "wsl" || /^wsl-[a-z0-9-]+$/.test(id);
167
- }
168
- /** The variant id for one source preset id. */
169
- function variantIdFor(sourceId) {
170
- return `wsl-${sourceId.toLowerCase()}`;
171
- }
172
- //#endregion
173
- //#region src/host/wsl-skills.ts
174
- /**
175
- * WSL workspace skill provider (host half).
176
- *
177
- * DSH's shipped skill-filesystem provider scans only the session cwd's
178
- * project root (the nearest `.git` ancestor) for `.dsh/skills` / `.agents/skills`
179
- * and never descends into nested projects. A WSL workspace whose project
180
- * folders live below the registered workspace root therefore shows an empty
181
- * skill catalog, even though the same layout works when the session cwd is
182
- * the project folder itself (issue #10).
183
- *
184
- * This provider mirrors the host's discovery rules for WSL UNC session
185
- * workspaces: it starts at the session cwd's nearest `.git` ancestor (the
186
- * host's project-root rule; the cwd itself when no ancestor has a `.git`
187
- * marker), then walks that root (depth- and budget-bounded), collects every
188
- * `.dsh/skills` and `.agents/skills` directory it finds — including nested
189
- * projects — and publishes their skills with the same
190
- * project ranks and sources the host uses, so precedence and duplicate
191
- * resolution behave identically. Non-WSL lookups return nothing and leave
192
- * the host's own providers untouched.
193
- *
194
- * All filesystem reads go through `node:fs` against the `\\wsl.localhost\…`
195
- * 9P share (the same substrate `WslFileSystem` uses); an injectable IO face
196
- * keeps the discovery logic unit-testable without a live distro.
197
- *
198
- * @module dsh-wsl-workspace/host/wsl-skills
199
- */
200
- /** Project ranks copied from @deepseek-ai/dsh-skill-filesystem so WSL and host entries interleave identically. */
201
- const PROJECT_DSH_RANK = 100;
202
- const PROJECT_AGENTS_RANK = 200;
203
- /** How many directory levels below the workspace root are scanned. */
204
- const MAX_SCAN_DEPTH = 4;
205
- /** Maximum distinct skill directories published per lookup. */
206
- const MAX_SKILL_ROOTS = 64;
207
- /** Maximum directories visited per lookup (an absolute blast-radius cap). */
208
- const MAX_VISITED_DIRECTORIES = 4096;
209
- /** How many parent levels above the session cwd are searched for a `.git` project marker. */
210
- const MAX_ANCESTOR_WALK = 64;
211
- /** Kebab-case skill names, matching the host grammar. */
212
- const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
213
- /** Directory names that never contain project skill roots (safe to prune while walking). */
214
- const PRUNED_DIRECTORY_NAMES = new Set([
215
- ".git",
216
- ".hg",
217
- ".svn",
218
- ".bzr",
219
- "node_modules",
220
- ".venv",
221
- "venv",
222
- ".tox",
223
- ".pants.d",
224
- ".next",
225
- ".nuxt",
226
- "dist",
227
- "build",
228
- "out",
229
- "coverage",
230
- "__pycache__",
231
- ".mypy_cache",
232
- ".pytest_cache",
233
- ".ruff_cache",
234
- ".cache",
235
- ".idea",
236
- ".vscode",
237
- ".serverless",
238
- ".terraform",
239
- ".yarn",
240
- ".pnpm-store"
241
- ]);
242
- /** The node:fs/promises implementation the provider uses in production. */
243
- const nodeSkillIo = {
244
- readdir: async (path, options) => readdir(path, options),
245
- readFile: async (path, options) => readFile(path, options),
246
- stat: async (path) => stat(path)
247
- };
248
- /**
249
- * Locate the nearest ancestor of `linuxDir` (the directory itself included)
250
- * containing a `.git` marker, mirroring the host skill-filesystem's
251
- * project-root rule. `.git` may be a directory or a worktree pointer file;
252
- * existence is enough. Bounded so a pathological path cannot spin the walk.
253
- * @param distro - the WSL distribution name.
254
- * @param linuxDir - the session cwd's absolute Linux path.
255
- * @param io - filesystem face.
256
- * @returns the project root's Linux path, or `undefined` when no ancestor carries a `.git`.
257
- */
258
- async function nearestGitAncestor(distro, linuxDir, io) {
259
- let current = linuxDir;
260
- for (let levels = 0; levels <= MAX_ANCESTOR_WALK; levels += 1) {
261
- try {
262
- await io.stat(joinUnc(distro, posix.join(current, ".git")));
263
- return current;
264
- } catch {}
265
- const parent = posix.dirname(current);
266
- if (parent === current) return void 0;
267
- current = parent;
268
- }
269
- }
270
- /**
271
- * Scan a WSL workspace root for nested skill directories.
272
- * @param distro - the WSL distribution name.
273
- * @param linuxRoot - the workspace's absolute Linux path.
274
- * @param io - filesystem face.
275
- * @returns discovered skill directories, bounded by depth and budget.
276
- */
277
- async function discoverSkillRoots(distro, linuxRoot, io) {
278
- const roots = [];
279
- const visited = /* @__PURE__ */ new Set();
280
- let frontier = [[linuxRoot, 0]];
281
- while (frontier.length > 0 && roots.length < MAX_SKILL_ROOTS) {
282
- const next = [];
283
- for (const [dir, depth] of frontier) {
284
- if (visited.size >= MAX_VISITED_DIRECTORIES) return roots;
285
- if (visited.has(dir)) continue;
286
- visited.add(dir);
287
- if (roots.length < MAX_SKILL_ROOTS) {
288
- const directoryRoots = await skillRootsOfDirectory(distro, dir, io);
289
- roots.push(...directoryRoots.slice(0, MAX_SKILL_ROOTS - roots.length));
290
- }
291
- if (depth >= MAX_SCAN_DEPTH) continue;
292
- let entries;
293
- try {
294
- entries = await io.readdir(joinUnc(distro, dir), { withFileTypes: true });
295
- } catch {
296
- continue;
297
- }
298
- for (const entry of entries) {
299
- if (!entry.isDirectory()) continue;
300
- if (PRUNED_DIRECTORY_NAMES.has(entry.name)) continue;
301
- if (entry.name.startsWith(".") && entry.name !== ".dsh" && entry.name !== ".agents") continue;
302
- if (entry.name === ".dsh" || entry.name === ".agents") continue;
303
- next.push([posix.join(dir, entry.name), depth + 1]);
304
- }
305
- }
306
- frontier = next;
307
- }
308
- return roots;
309
- }
310
- /**
311
- * Publish the skill roots of one scanned directory (its `.dsh/skills` and
312
- * `.agents/skills`, each with the host's project ranks).
313
- * @param distro - the WSL distribution name.
314
- * @param linuxDir - the scanned directory's Linux path.
315
- * @param io - filesystem face.
316
- * @returns the directory's skill roots that exist.
317
- */
318
- async function skillRootsOfDirectory(distro, linuxDir, io) {
319
- const result = [];
320
- for (const [marker, source, rank] of [[
321
- ".dsh",
322
- "project-dsh",
323
- PROJECT_DSH_RANK
324
- ], [
325
- ".agents",
326
- "project-agents",
327
- PROJECT_AGENTS_RANK
328
- ]]) {
329
- const path = joinUnc(distro, posix.join(linuxDir, marker, "skills"));
330
- try {
331
- if ((await io.stat(path)).isDirectory()) result.push({
332
- path,
333
- source,
334
- rank
335
- });
336
- } catch {}
337
- }
338
- return result;
339
- }
340
- /** List one skills directory's entries (directory bundles and flat `.md` skills). */
341
- async function listSkillEntries(root, io) {
342
- let dirents;
343
- try {
344
- dirents = await io.readdir(root.path, { withFileTypes: true });
345
- } catch {
346
- return [];
347
- }
348
- const entries = [];
349
- for (const entry of dirents) if (entry.isDirectory()) entries.push({
350
- name: entry.name,
351
- kind: "bundle",
352
- path: join(root.path, entry.name, "SKILL.md")
353
- });
354
- else if (entry.isFile() && entry.name.endsWith(".md")) entries.push({
355
- name: entry.name.slice(0, -3),
356
- kind: "flat",
357
- path: join(root.path, entry.name)
358
- });
359
- return entries.sort((a, b) => a.name.localeCompare(b.name));
360
- }
361
- /** Read and parse one skill file; `undefined` when missing or unparsable. */
362
- async function readSkill(path, io, signal) {
363
- signal?.throwIfAborted();
364
- let raw;
365
- try {
366
- raw = await io.readFile(path, { encoding: "utf8" });
367
- } catch {
368
- return;
369
- }
370
- signal?.throwIfAborted();
371
- return parseSkillFrontmatter(raw, path);
372
- }
373
- /**
374
- * Parse the frontmatter subset skill files use: `---` fenced YAML with
375
- * `name` / `description` / `whenToUse` / `user-invocable` /
376
- * `disable-model-invocation`. Host-incompatible files are skipped, matching
377
- * the shipped provider's leniency: a bad file must not fail the catalog.
378
- */
379
- function parseSkillFrontmatter(raw, path) {
380
- const firstLineEnd = raw.indexOf("\n");
381
- if (firstLineEnd < 0) return void 0;
382
- if (raw.slice(0, firstLineEnd).replace(/\r$/, "") !== "---") return void 0;
383
- const start = firstLineEnd + 1;
384
- const closing = findFrontmatterEnd(raw, start);
385
- if (closing === void 0) return void 0;
386
- const fields = /* @__PURE__ */ new Map();
387
- for (const line of raw.slice(start, closing).split("\n")) {
388
- const match = /^([A-Za-z0-9-]+):\s*(.*)$/.exec(line.replace(/\r$/, ""));
389
- if (match === null) continue;
390
- const value = match[2]?.trim() ?? "";
391
- if (value !== "") fields.set(match[1] ?? "", unquote(value));
392
- }
393
- const name = fields.get("name") ?? "";
394
- const description = fields.get("description") ?? "";
395
- if (!SKILL_NAME.test(name) || description === "") return;
396
- const whenToUse = fields.get("whenToUse");
397
- return {
398
- name,
399
- description,
400
- ...whenToUse !== void 0 && whenToUse !== "" ? { whenToUse } : {},
401
- invocation: {
402
- modelInvocable: !frontmatterBoolean(fields, "disable-model-invocation"),
403
- userInvocable: frontmatterBoolean(fields, "user-invocable", true)
404
- },
405
- content: raw.slice(closing + 1).trim()
406
- };
407
- }
408
- /** Locate the closing `---` line of a frontmatter block. */
409
- function findFrontmatterEnd(raw, start) {
410
- let lineStart = start;
411
- while (lineStart <= raw.length) {
412
- const nextNewline = raw.indexOf("\n", lineStart);
413
- const lineEnd = nextNewline < 0 ? raw.length : nextNewline;
414
- if (raw.slice(lineStart, lineEnd).replace(/\r$/, "") === "---") return lineEnd + 1;
415
- if (nextNewline < 0) return void 0;
416
- lineStart = nextNewline + 1;
417
- }
418
- }
419
- /** Strip one level of matching quotes from a scalar value. */
420
- function unquote(value) {
421
- if (value.length >= 2) {
422
- const first = value[0];
423
- const last = value[value.length - 1];
424
- if (first === "\"" && last === "\"" || first === "'" && last === "'") return value.slice(1, -1);
425
- }
426
- return value;
427
- }
428
- /** Boolean semantics for `user-invocable` / `disable-model-invocation` (matches the host parser). */
429
- function frontmatterBoolean(fields, key, dflt = false) {
430
- const value = fields.get(key);
431
- if (value === void 0) return dflt;
432
- switch (value.toLowerCase()) {
433
- case "true":
434
- case "yes":
435
- case "on":
436
- case "1": return true;
437
- case "false":
438
- case "no":
439
- case "off":
440
- case "0": return false;
441
- default: return dflt;
442
- }
443
- }
444
- /**
445
- * The WSL workspace skill provider. Registered on the host's `ctx.skills`
446
- * registry; serves only lookups whose cwd is a WSL UNC workspace path.
447
- */
448
- var WslSkillsProvider = class {
449
- name = "wsl-workspace";
450
- control;
451
- io;
452
- constructor(control, io = nodeSkillIo) {
453
- this.control = control;
454
- this.io = io;
455
- }
456
- /**
457
- * Discover nested project skills for a WSL UNC session workspace.
458
- * @param options - lookup options; `cwd` selects the WSL workspace.
459
- * @returns candidates for every `.dsh/skills` / `.agents/skills` under the
460
- * session's scan root — the nearest `.git` ancestor of the cwd, else the
461
- * cwd itself — or an empty array for non-WSL lookups.
462
- */
463
- async list(options) {
464
- this.control.signal.throwIfAborted();
465
- options.signal?.throwIfAborted();
466
- const unc = options.cwd === void 0 ? null : parseWslUnc(options.cwd);
467
- if (unc === null) return [];
468
- const scanRoot = await nearestGitAncestor(unc.distro, unc.linuxPath, this.io) ?? unc.linuxPath;
469
- const roots = await discoverSkillRoots(unc.distro, scanRoot, this.io);
470
- const candidates = [];
471
- for (const root of roots) {
472
- const entries = await listSkillEntries(root, this.io);
473
- for (const entry of entries) {
474
- options.signal?.throwIfAborted();
475
- const parsed = await readSkill(entry.path, this.io, options.signal);
476
- if (parsed === void 0) continue;
477
- candidates.push({
478
- name: parsed.name,
479
- description: parsed.description,
480
- ...parsed.whenToUse !== void 0 ? { whenToUse: parsed.whenToUse } : {},
481
- invocation: parsed.invocation,
482
- source: root.source,
483
- provider: this.name,
484
- rank: root.rank,
485
- locator: {
486
- path: entry.path,
487
- directory: entry.kind === "bundle" ? join(entry.path, "..") : root.path
488
- },
489
- path: entry.path
490
- });
491
- }
492
- }
493
- return candidates;
494
- }
495
- /**
496
- * Load a complete skill body for a previously listed candidate.
497
- * @param candidate - the candidate this provider returned.
498
- * @param options - lookup options whose signal cancels the read.
499
- * @returns the full skill, or `undefined` if the file disappeared.
500
- */
501
- async get(candidate, options) {
502
- this.control.signal.throwIfAborted();
503
- const parsed = await readSkill(candidate.locator.path, this.io, options.signal);
504
- if (parsed === void 0 || parsed.name !== candidate.name) return void 0;
505
- return {
506
- name: parsed.name,
507
- description: parsed.description,
508
- ...parsed.whenToUse !== void 0 ? { whenToUse: parsed.whenToUse } : {},
509
- invocation: parsed.invocation,
510
- source: candidate.source,
511
- provider: candidate.provider,
512
- rank: candidate.rank,
513
- locator: candidate.locator,
514
- path: candidate.path,
515
- content: parsed.content
516
- };
517
- }
518
- };
519
- //#endregion
520
- //#region src/index.ts
521
- /** The HTTP route this plugin serves (a relative, same-origin path). */
522
- const DEFAULT_ROUTE = "/wsl-workspace/api";
523
- /**
524
- * Bilingual display labels for the shipped source modes, matching the app's
525
- * own built-in copy in each language — note the `code` preset is "PTC 模式"
526
- * in the Chinese copy but "Code mode" in English. The DSH picker localizes
527
- * only the four built-in ids itself; `wsl-*` variant ids render the
528
- * preset.yml text verbatim, so the plugin writes one bilingual string so
529
- * both locales can identify each variant. Custom presets keep their own
530
- * name.
531
- */
532
- const MODE_DISPLAY_LABELS = {
533
- standard: {
534
- en: "Standard mode",
535
- zh: "标准模式"
536
- },
537
- code: {
538
- en: "Code mode",
539
- zh: "PTC 模式"
540
- },
541
- minimal: {
542
- en: "Minimal mode",
543
- zh: "极简模式"
544
- },
545
- cordis: {
546
- en: "Creator mode",
547
- zh: "创造模式"
548
- }
549
- };
550
- /**
551
- * Quote a value as a single-line YAML single-quoted scalar. Plain scalars
552
- * cannot contain `: ` (colon + space), which plain English sentences do —
553
- * written unquoted they make the whole preset.yml unparsable, dropping the
554
- * name, description and order together.
555
- */
556
- function yamlScalar(value) {
557
- return `'${value.replace(/'/g, "''")}'`;
558
- }
559
- /** The variant name for one shipped mode (bilingual) or a custom preset. */
560
- function variantName(presetId, sourceName) {
561
- const labels = MODE_DISPLAY_LABELS[presetId];
562
- return labels === void 0 ? `WSL · ${sourceName}` : `WSL · ${labels.en}(${labels.zh})`;
563
- }
564
- /** The variant description for one shipped mode (bilingual) or a custom preset. */
565
- function variantDescription(presetId) {
566
- const labels = MODE_DISPLAY_LABELS[presetId];
567
- return `WSL execution world for ${labels === void 0 ? presetId : `${labels.en}(${labels.zh})`}: bash and file tools run inside the WSL distribution.`;
568
- }
569
- const MAX_BODY_BYTES = 1024 * 1024;
570
- /** Valid WSL distribution names: one path-safe segment (no separators, no dot-dirs). */
571
- const DISTRO_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/;
572
- /** The loopback hostnames the data route answers to (DNS-rebinding fence). */
573
- const LOOPBACK_HOSTNAMES = new Set([
574
- "localhost",
575
- "127.0.0.1",
576
- "::1",
577
- "::ffff:127.0.0.1"
578
- ]);
579
- /** True when a socket address is loopback (any IPv4/IPv6 spelling). */
580
- function isLoopback(address) {
581
- return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
582
- }
583
- /** The hostname part of a `Host` header value (port and IPv6 brackets stripped). */
584
- function hostNameOf(host) {
585
- if (host.startsWith("[")) {
586
- const end = host.indexOf("]");
587
- return end >= 0 ? host.slice(1, end) : host;
588
- }
589
- return host.split(":")[0] ?? "";
590
- }
591
- /** True when the request's `Host` header names a loopback host. */
592
- function isLoopbackHost(host) {
593
- return host !== void 0 && LOOPBACK_HOSTNAMES.has(hostNameOf(host).toLowerCase());
594
- }
595
- /**
596
- * Validate a wire-supplied distribution name before it becomes a UNC segment:
597
- * an attacker-controlled segment containing separators or `..` would escape
598
- * the `\\wsl.localhost\` share structure into arbitrary UNC paths.
599
- * @param value - the raw wire value.
600
- * @returns the validated distro name.
601
- */
602
- function requireDistro(value) {
603
- if (typeof value !== "string" || !DISTRO_PATTERN.test(value) || value === "." || value === "..") throw new Error("distro must be a valid WSL distribution name");
604
- return value;
605
- }
606
- /** Human text for an unknown rejection. */
607
- function messageOf(value) {
608
- return value instanceof Error ? value.message : String(value);
609
- }
610
- /** Write one JSON envelope. */
611
- function json(res, status, body) {
612
- res.writeHead(status, {
613
- "content-type": "application/json; charset=utf-8",
614
- "cache-control": "no-store",
615
- "x-content-type-options": "nosniff"
616
- });
617
- res.end(JSON.stringify(body));
618
- }
619
- /** Collect and parse the request body, bounded. */
620
- async function readBody(req) {
621
- const chunks = [];
622
- let size = 0;
623
- for await (const chunk of req) {
624
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
625
- size += buffer.length;
626
- if (size > MAX_BODY_BYTES) throw new Error("request body is too large");
627
- chunks.push(buffer);
628
- }
629
- const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
630
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("request body must be a JSON object");
631
- return parsed;
632
- }
633
- /** Normalize a Linux path for the wire (rejecting non-absolute input). */
634
- function requireLinuxPath(value, label) {
635
- if (typeof value !== "string" || !isAbsoluteLinuxPath(value)) throw new Error(`${label} must be an absolute Linux path`);
636
- return normalizeLinuxPath(value);
637
- }
638
- /** Validate a wire-supplied workspace path and return its canonical UNC form. */
639
- function requireWslUnc(value) {
640
- if (typeof value !== "string") throw new Error("path must be a string");
641
- const canonical = canonicalWslUnc(value);
642
- if (canonical === null) throw new Error("path must be a WSL UNC workspace path");
643
- return canonical;
644
- }
645
- /**
646
- * Resolve one directory listing for the dialog. The 9P share (`\\wsl.localhost\…`)
647
- * serves only the ext4 volume: `/mnt/<drive>` (drvfs) reads return Access
648
- * denied, so drvfs paths are read through their Windows drive spelling and
649
- * `/mnt` itself is synthesized from the drives present on the host.
650
- */
651
- function listWslDir(distro, linuxPath) {
652
- if (linuxPath === "/mnt") {
653
- const entries = [];
654
- for (let i = 0; i < 26; i++) {
655
- const letter = String.fromCharCode(65 + i);
656
- try {
657
- if (statSync(`${letter}:\\`).isDirectory()) entries.push({
658
- name: letter.toLowerCase(),
659
- kind: "directory"
660
- });
661
- } catch {}
662
- }
663
- return {
664
- path: "/mnt",
665
- parent: "/",
666
- entries
667
- };
668
- }
669
- const winPath = mntToWindowsPath(linuxPath);
670
- const entries = readdirSync(winPath !== null ? winPath : joinUnc(distro, linuxPath), { withFileTypes: true }).slice(0, 1e3).map((dirent) => {
671
- const kind = dirent.isDirectory() ? "directory" : dirent.isFile() ? "file" : "other";
672
- return {
673
- name: dirent.name,
674
- kind
675
- };
676
- }).sort((a, b) => {
677
- if (a.kind === "directory" && b.kind !== "directory") return -1;
678
- if (a.kind !== "directory" && b.kind === "directory") return 1;
679
- return a.name.localeCompare(b.name);
680
- });
681
- return {
682
- path: linuxPath,
683
- parent: linuxPath === "/" ? null : linuxPath.split("/").slice(0, -1).join("/") || "/",
684
- entries
685
- };
686
- }
687
- /** Route one method dispatch. */
688
- async function dispatch(method, params) {
689
- switch (method) {
690
- case "listDistros": {
691
- const distros = await listDistros();
692
- const fallback = await defaultDistro();
693
- if (fallback !== void 0 && distros.includes(fallback)) return [fallback, ...distros.filter((name) => name !== fallback)];
694
- return distros;
695
- }
696
- case "listDir": return listWslDir(requireDistro(params.distro), requireLinuxPath(params.path, "path"));
697
- case "check": {
698
- const distro = requireDistro(params.distro);
699
- const path = requireLinuxPath(params.path, "path");
700
- const winPath = mntToWindowsPath(path);
701
- const readPath = winPath !== null ? winPath : joinUnc(distro, path);
702
- try {
703
- return {
704
- exists: true,
705
- isDirectory: statSync(readPath).isDirectory()
706
- };
707
- } catch {
708
- return {
709
- exists: false,
710
- isDirectory: false
711
- };
712
- }
713
- }
714
- case "registerWindows": {
715
- const distro = requireDistro(params.distro);
716
- const winPath = mntToWindowsPath(requireLinuxPath(params.linuxPath, "path"));
717
- if (winPath === null) throw new Error("registerWindows requires a /mnt/<drive> Linux path");
718
- registerWindowsWorkspace(winPath, distro, typeof params.username === "string" ? params.username : void 0);
719
- return null;
720
- }
721
- case "listWorkspaces": return listWorkspaceKeys();
722
- case "setUser": {
723
- const path = requireWslUnc(params.path);
724
- const username = params.username;
725
- if (username === void 0 || username === "") setWorkspaceUsername(path, void 0);
726
- else {
727
- if (typeof username !== "string" || !isValidWslUsername(username)) throw new Error("username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*");
728
- setWorkspaceUsername(path, username);
729
- }
730
- return null;
731
- }
732
- default: throw new Error(`unknown method "${method}"`);
733
- }
734
- }
735
- /**
736
- * Publish a fully staged preset directory while preserving the last complete
737
- * variant if publication fails. Stable sibling names also let the next boot
738
- * recover an interrupted old-to-backup rename before doing new work.
739
- */
740
- function publishVariant(staging, dest) {
741
- const previous = `${dest}.previous`;
742
- if (!existsSync(dest) && existsSync(previous)) renameSync(previous, dest);
743
- if (existsSync(previous)) rmSync(previous, {
744
- recursive: true,
745
- force: true
746
- });
747
- if (existsSync(dest)) renameSync(dest, previous);
748
- try {
749
- renameSync(staging, dest);
750
- } catch (error) {
751
- if (!existsSync(dest) && existsSync(previous)) renameSync(previous, dest);
752
- throw error;
753
- }
754
- rmSync(previous, {
755
- recursive: true,
756
- force: true
757
- });
758
- }
759
- /** Materialize one WSL variant per healthy source preset. */
760
- async function materializeVariants(agentPresets, dshHome, shellPath, fsPath) {
761
- const presets = await agentPresets.list();
762
- const userRoot = join(dshHome, ".agent-presets");
763
- const generated = /* @__PURE__ */ new Set();
764
- for (const preset of presets) {
765
- if (preset.broken !== void 0) continue;
766
- if (isWslVariantId(preset.id)) continue;
767
- const variantId = variantIdFor(preset.id);
768
- const transformed = transformPresetForWsl(await agentPresets.read(preset.id), shellPath, fsPath);
769
- const dir = join(userRoot, variantId);
770
- const staging = `${dir}.staging`;
771
- rmSync(staging, {
772
- recursive: true,
773
- force: true
774
- });
775
- cpSync(dirname(preset.path), staging, {
776
- recursive: true,
777
- force: true
778
- });
779
- writeFileSync(join(staging, "agent.cordis.yml"), transformed, "utf8");
780
- const labels = MODE_DISPLAY_LABELS[preset.id];
781
- let name = variantName(preset.id, preset.id);
782
- let orderLine = "";
783
- try {
784
- const meta = readFileSync(join(dirname(preset.path), "preset.yml"), "utf8");
785
- if (labels === void 0) {
786
- const match = /^name:\s*(.+)$/m.exec(meta);
787
- if (match?.[1] !== void 0 && match[1].trim() !== "") name = variantName(preset.id, match[1].trim());
788
- }
789
- const orderMatch = /^order:\s*(\d+)\s*$/m.exec(meta);
790
- if (orderMatch?.[1] !== void 0) orderLine = `order: ${orderMatch[1]}\n`;
791
- } catch {}
792
- writeFileSync(join(staging, "preset.yml"), `name: ${yamlScalar(name)}\n` + orderLine + `description: ${yamlScalar(variantDescription(preset.id))}\n`, "utf8");
793
- publishVariant(staging, dir);
794
- generated.add(variantId);
795
- }
796
- for (const entry of readdirSync(userRoot, { withFileTypes: true })) {
797
- if (!entry.isDirectory()) continue;
798
- if (entry.name === "wsl") {
799
- rmSync(join(userRoot, entry.name), {
800
- recursive: true,
801
- force: true
802
- });
803
- continue;
804
- }
805
- if (!/^wsl-[a-z0-9-]+$/.test(entry.name)) continue;
806
- if (!generated.has(entry.name)) rmSync(join(userRoot, entry.name), {
807
- recursive: true,
808
- force: true
809
- });
810
- }
811
- }
812
- /** Function-plugin plugin contract. */
813
- const name = "dsh-wsl-workspace";
814
- /** Required services. */
815
- const inject = ["webServer"];
816
- /** Validated plugin config (schemastery applied the defaults). */
817
- const Config = z.object({ route: z.string().default(DEFAULT_ROUTE) });
818
- /**
819
- * Apply the host half: materialize a `wsl-<mode>` variant for every healthy
820
- * roster preset, register the data route, and
821
- * contribute the per-session `DSH_WSL_DISTRO` managed-env fact so the WSL
822
- * shell executor can resolve a plain Linux `workdir` to the calling
823
- * session's distribution.
824
- * @param ctx - the host plugin context.
825
- * @param config - the validated configuration.
826
- */
827
- function apply(ctx, config) {
828
- const resolved = config;
829
- const dshHome = process.env.DSH_HOME ?? join(homedir(), ".dsh");
830
- const packageRoot = fileURLToPath(new URL("..", import.meta.url));
831
- const shellPath = join(packageRoot, "lib", "shell.js").replace(/\\/g, "/");
832
- const fsPath = join(packageRoot, "lib", "fs.js").replace(/\\/g, "/");
833
- const agentPresets = ctx.get("agentPresets");
834
- if (agentPresets !== void 0) ctx.effect(() => {
835
- materializeVariants(agentPresets, dshHome, shellPath, fsPath).catch((error) => {
836
- console.error(`dsh-wsl-workspace: WSL preset-variant generation failed: ${messageOf(error)}`);
837
- });
838
- return () => {};
839
- }, "dsh-wsl-workspace: WSL preset variants");
840
- const skills = ctx.get("skills");
841
- if (skills !== void 0 && typeof skills.registerProvider === "function") ctx.effect(() => skills.registerProvider((control) => new WslSkillsProvider(control)), "dsh-wsl-workspace: WSL workspace skills provider");
842
- const shellEnv = ctx.get("shellEnv");
843
- if (shellEnv !== void 0) ctx.effect(() => shellEnv.register({
844
- name: "wsl-workspace-distro",
845
- variables: {
846
- DSH_WSL_DISTRO: { description: "The WSL distribution of the calling session workspace, when the session cwd is a WSL UNC path." },
847
- DSH_WSL_USER: { description: "The Linux user of the calling session workspace, when the workspace has one configured." }
848
- },
849
- resolve(execution) {
850
- const cwd = execution.agent?.session.header.cwd;
851
- const unc = cwd === void 0 ? null : parseWslUnc(cwd);
852
- if (unc !== null) {
853
- const username = getWorkspaceUsername(joinUnc(unc.distro, unc.linuxPath));
854
- return username === void 0 || username === "" ? { DSH_WSL_DISTRO: unc.distro } : {
855
- DSH_WSL_DISTRO: unc.distro,
856
- DSH_WSL_USER: username
857
- };
858
- }
859
- if (cwd !== void 0 && /^[A-Za-z]:[\\/]/.test(cwd)) {
860
- const entry = getWindowsWorkspace(cwd);
861
- if (entry !== void 0 && entry.distro !== void 0 && entry.distro !== "") return entry.username === void 0 || entry.username === "" ? { DSH_WSL_DISTRO: entry.distro } : {
862
- DSH_WSL_DISTRO: entry.distro,
863
- DSH_WSL_USER: entry.username
864
- };
865
- }
866
- return {};
867
- }
868
- }), "dsh-wsl-workspace: per-session distro env fact");
869
- const webServer = ctx.get("webServer");
870
- ctx.effect(() => webServer.register({
871
- kind: "exact",
872
- path: resolved.route,
873
- handler: async (req, res) => {
874
- if (!isLoopback(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host)) {
875
- json(res, 403, {
876
- ok: false,
877
- error: "loopback-only"
878
- });
879
- return;
880
- }
881
- if (req.method !== "POST") {
882
- json(res, 405, {
883
- ok: false,
884
- error: "method not allowed"
885
- });
886
- return;
887
- }
888
- let body;
889
- try {
890
- body = await readBody(req);
891
- } catch (error) {
892
- json(res, 400, {
893
- ok: false,
894
- error: messageOf(error)
895
- });
896
- return;
897
- }
898
- const method = typeof body.method === "string" ? body.method : "";
899
- const params = body.params === void 0 ? {} : body.params;
900
- if (params === null || typeof params !== "object" || Array.isArray(params)) {
901
- json(res, 400, {
902
- ok: false,
903
- error: "params must be an object"
904
- });
905
- return;
906
- }
907
- try {
908
- json(res, 200, {
909
- ok: true,
910
- value: await dispatch(method, params)
911
- });
912
- } catch (error) {
913
- json(res, 200, {
914
- ok: false,
915
- error: messageOf(error)
916
- });
917
- }
918
- }
919
- }), "dsh-wsl-workspace: dialog data route");
920
- }
921
- //#endregion
922
- export { Config, DEFAULT_ROUTE, apply, inject, name };
923
-
1
+ import { defaultDistro, isAbsoluteLinuxPath, isValidWslUsername, joinUnc, listDistros, mntToWindowsPath, normalizeLinuxPath, parseWslUnc } from "./wsl-6VcgOvF9.js";
2
+ import { canonicalWslUnc, getWindowsWorkspace, getWorkspaceUsername, listWorkspaceKeys, registerWindowsWorkspace, setWorkspaceUsername } from "./wsl-credentials-B6wIXsKt.js";
3
+ import z from "@deepseek-ai/schemastery";
4
+ import { cpSync, existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+ import { dirname, join, posix } from "node:path";
7
+ import { homedir } from "node:os";
8
+ import { readFile, readdir, stat } from "node:fs/promises";
9
+
10
+ //#region src/host/variants.ts
11
+ /**
12
+ * WSL preset-variant generator. For every healthy source preset the roster
13
+ * supplies, a `wsl-<id>` variant is materialized under the roster's user
14
+ * root: the source composition with its shell/filesystem world replaced by
15
+ * the WSL providers, so any mode (standard, minimal, code, cordis, user
16
+ * presets) can run on top of a WSL execution world. The execution world is
17
+ * therefore orthogonal to the mode instead of a mode itself.
18
+ *
19
+ * The transformation is text-level on the top-level rows of the composition
20
+ * (the shape all shipped presets share), with surgical edits for the known
21
+ * special groups; unknown shapes are kept verbatim where possible.
22
+ * @module dsh-wsl-workspace/host/variants
23
+ */
24
+ /** Top-level rows that name the execution world and are replaced by the variant's own. */
25
+ const WORLD_ROWS = new Set([
26
+ "tool-bash",
27
+ "tool-pwsh",
28
+ "tool-fs",
29
+ "tool-fs-search",
30
+ "str-replace-editor",
31
+ "filesystem",
32
+ "persistent-shell",
33
+ "custom-bash",
34
+ "bootstrap-filesystem"
35
+ ]);
36
+ /** The injected WSL world group: providers + the bash/fs consumers, entry-local. */
37
+ function wslWorldGroup(shellPath, fsPath, includeEditor) {
38
+ return [
39
+ "# ── WSL execution world (dsh-wsl-workspace variant) ─────────────────────",
40
+ "# The shell and fs services are provided entry-locally (the isolate",
41
+ "# realm); host services (tools registry, shell-env, jobs) fall through.",
42
+ "# tool-fs-search is intentionally absent: the packaged ripgrep runs on",
43
+ "# the Windows host and cannot open Linux paths; WSL sessions search with",
44
+ "# shell tools instead.",
45
+ "- id: wsl-world",
46
+ " name: cordis:group",
47
+ " group: true",
48
+ " isolate:",
49
+ " shell: true",
50
+ " fs: true",
51
+ " config:",
52
+ ` - id: shell-wsl`,
53
+ ` name: '${shellPath.replace(/'/g, "''")}'`,
54
+ " - id: fs-wsl",
55
+ ` name: '${fsPath.replace(/'/g, "''")}'`,
56
+ " - id: tool-bash",
57
+ " name: '@deepseek-ai/dsh-tool-bash'",
58
+ " - id: tool-fs",
59
+ " name: '@deepseek-ai/dsh-tool-fs'",
60
+ ...includeEditor ? [
61
+ " - id: str-replace-editor",
62
+ " name: '@deepseek-ai/dsh-tool-str-replace-editor'",
63
+ " config:",
64
+ " maxOutputChars: 16000"
65
+ ] : [],
66
+ ""
67
+ ].join("\n");
68
+ }
69
+ /** The sentence appended to a standard-like persona when the variant runs in WSL. */
70
+ const 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.";
71
+ /** The top-level rows of one composition, as (startLine, endLineExclusive) spans. */
72
+ function topLevelSpans(lines) {
73
+ const spans = [];
74
+ let start = -1;
75
+ for (let index = 0; index < lines.length; index++) if (lines[index]?.startsWith("- id: ") === true) {
76
+ if (start >= 0) spans.push({
77
+ start,
78
+ end: index
79
+ });
80
+ start = index;
81
+ }
82
+ if (start >= 0) spans.push({
83
+ start,
84
+ end: lines.length
85
+ });
86
+ return spans;
87
+ }
88
+ /** The row id of a top-level span, or undefined when the first line is malformed. */
89
+ function spanId(lines, span) {
90
+ return /^- id: ([A-Za-z0-9_.-]+)/.exec(lines[span.start] ?? "")?.[1];
91
+ }
92
+ /** Whether a top-level span is a `persona` row with an appendable folded text. */
93
+ function appendablePersona(lines, span) {
94
+ const block = lines.slice(span.start, span.end).join("\n");
95
+ if (!block.includes("complete: true") && /text: [>|-]/.test(block)) {
96
+ const textLine = block.split("\n").find((line) => /^(\s*)text: [>|-]/.test(line));
97
+ if (textLine !== void 0) {
98
+ const indent = /^(\s*)/.exec(textLine)?.[1]?.length ?? 0;
99
+ return block.split("\n").some((line) => line.length > indent && /^\s+/.test(line) && !line.includes(":"));
100
+ }
101
+ }
102
+ return false;
103
+ }
104
+ /** Append the WSL sentence to a persona row's folded text (in place of its last text line). */
105
+ function appendPersona(lines, span) {
106
+ const block = lines.slice(span.start, span.end);
107
+ const textIndex = block.findIndex((line) => /^(\s*)text: [>|-]/.test(line));
108
+ if (textIndex < 0) return [...block];
109
+ const indent = /^(\s*)/.exec(block[textIndex] ?? "")?.[1]?.length ?? 0;
110
+ let lastText = -1;
111
+ for (let index = textIndex + 1; index < block.length; index++) {
112
+ const line = block[index] ?? "";
113
+ if (line.trim() === "") continue;
114
+ if (line.length > indent && /^\s+/.test(line)) lastText = index;
115
+ }
116
+ if (lastText < 0) return [...block];
117
+ const updated = [...block];
118
+ const textIndent = /^(\s*)/.exec(block[lastText] ?? "")?.[1] ?? " ";
119
+ updated.splice(lastText + 1, 0, `${textIndent}${PERSONA_APPEND}`);
120
+ return updated;
121
+ }
122
+ /**
123
+ * Transform one source preset composition into its WSL variant: drop the
124
+ * execution-world rows, keep everything else verbatim, and append the WSL
125
+ * world group. The persistent-shell group is NOT re-added: it registers the
126
+ * same `bash` tool name as the WSL world's `dsh-tool-bash`, and the tools
127
+ * registry rejects duplicates within one preset layer — the whole variant
128
+ * fails to mount and the session falls back to another preset. Its PTY
129
+ * backend additionally cannot run on this plugin's Windows host
130
+ * (`dsh-subprocess-local`: "terminal inspection is unsupported on platform
131
+ * win32"), so the group could never spawn a shell here anyway. The WSL
132
+ * world's ordinary `bash` tool covers command execution for every variant.
133
+ * @param source - the source composition text.
134
+ * @param shellPath - absolute path of the plugin's built WSL shell provider.
135
+ * @param fsPath - absolute path of the plugin's built WSL fs provider.
136
+ * @returns the variant composition text.
137
+ */
138
+ function transformPresetForWsl(source, shellPath, fsPath) {
139
+ const lines = source.split("\n");
140
+ const spans = topLevelSpans(lines);
141
+ const kept = [];
142
+ let sawEditor = false;
143
+ let personaAppended = false;
144
+ for (const span of spans) {
145
+ const id = spanId(lines, span);
146
+ if (id === void 0) {
147
+ kept.push(...lines.slice(span.start, span.end));
148
+ continue;
149
+ }
150
+ if (WORLD_ROWS.has(id)) continue;
151
+ if (id === "persona" && !personaAppended && appendablePersona(lines, span)) {
152
+ kept.push(...appendPersona(lines, span));
153
+ personaAppended = true;
154
+ continue;
155
+ }
156
+ kept.push(...lines.slice(span.start, span.end));
157
+ if (id === "str-replace-editor") sawEditor = true;
158
+ }
159
+ if (source.includes("str-replace-editor")) sawEditor = true;
160
+ const result = [...kept];
161
+ if (result.length > 0 && result[result.length - 1] !== "") result.push("");
162
+ result.push(wslWorldGroup(shellPath, fsPath, sawEditor));
163
+ return result.join("\n").replace(/\n{3,}/g, "\n\n").replace(/\n+$/, "\n");
164
+ }
165
+ /** Whether an id is one of this plugin's own preset directories. */
166
+ function isWslVariantId(id) {
167
+ return id === "wsl" || /^wsl-[a-z0-9-]+$/.test(id);
168
+ }
169
+ /** The variant id for one source preset id. */
170
+ function variantIdFor(sourceId) {
171
+ return `wsl-${sourceId.toLowerCase()}`;
172
+ }
173
+
174
+ //#endregion
175
+ //#region src/host/wsl-skills.ts
176
+ /** Project ranks copied from @deepseek-ai/dsh-skill-filesystem so WSL and host entries interleave identically. */
177
+ const PROJECT_DSH_RANK = 100;
178
+ const PROJECT_AGENTS_RANK = 200;
179
+ /** How many directory levels below the workspace root are scanned. */
180
+ const MAX_SCAN_DEPTH = 4;
181
+ /** Maximum distinct skill directories published per lookup. */
182
+ const MAX_SKILL_ROOTS = 64;
183
+ /** Maximum directories visited per lookup (an absolute blast-radius cap). */
184
+ const MAX_VISITED_DIRECTORIES = 4096;
185
+ /** How many parent levels above the session cwd are searched for a `.git` project marker. */
186
+ const MAX_ANCESTOR_WALK = 64;
187
+ /** How long a completed lookup is served from cache before the next rescan. */
188
+ const CACHE_TTL_MS = 1e4;
189
+ /** Maximum cached lookups (one entry per distinct scan root across sessions). */
190
+ const CACHE_MAX_ENTRIES = 32;
191
+ /** Kebab-case skill names, matching the host grammar. */
192
+ const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
193
+ /** Directory names that never contain project skill roots (safe to prune while walking). */
194
+ const PRUNED_DIRECTORY_NAMES = new Set([
195
+ ".git",
196
+ ".hg",
197
+ ".svn",
198
+ ".bzr",
199
+ "node_modules",
200
+ ".venv",
201
+ "venv",
202
+ ".tox",
203
+ ".pants.d",
204
+ ".next",
205
+ ".nuxt",
206
+ "dist",
207
+ "build",
208
+ "out",
209
+ "coverage",
210
+ "__pycache__",
211
+ ".mypy_cache",
212
+ ".pytest_cache",
213
+ ".ruff_cache",
214
+ ".cache",
215
+ ".idea",
216
+ ".vscode",
217
+ ".serverless",
218
+ ".terraform",
219
+ ".yarn",
220
+ ".pnpm-store"
221
+ ]);
222
+ /** The node:fs/promises implementation the provider uses in production. */
223
+ const nodeSkillIo = {
224
+ readdir: async (path, options) => readdir(path, options),
225
+ readFile: async (path, options) => readFile(path, options),
226
+ stat: async (path) => stat(path)
227
+ };
228
+ /**
229
+ * Locate the nearest ancestor of `linuxDir` (the directory itself included)
230
+ * containing a `.git` marker, mirroring the host skill-filesystem's
231
+ * project-root rule. `.git` may be a directory or a worktree pointer file;
232
+ * existence is enough. Bounded so a pathological path cannot spin the walk.
233
+ * @param distro - the WSL distribution name.
234
+ * @param linuxDir - the session cwd's absolute Linux path.
235
+ * @param io - filesystem face.
236
+ * @returns the project root's Linux path, or `undefined` when no ancestor carries a `.git`.
237
+ */
238
+ async function nearestGitAncestor(distro, linuxDir, io) {
239
+ let current = linuxDir;
240
+ for (let levels = 0; levels <= MAX_ANCESTOR_WALK; levels += 1) {
241
+ try {
242
+ await io.stat(joinUnc(distro, posix.join(current, ".git")));
243
+ return current;
244
+ } catch {}
245
+ const parent = posix.dirname(current);
246
+ if (parent === current) return void 0;
247
+ current = parent;
248
+ }
249
+ return void 0;
250
+ }
251
+ /**
252
+ * Scan a WSL workspace root for nested skill directories.
253
+ * @param distro - the WSL distribution name.
254
+ * @param linuxRoot - the workspace's absolute Linux path.
255
+ * @param io - filesystem face.
256
+ * @returns discovered skill directories, bounded by depth and budget.
257
+ */
258
+ async function discoverSkillRoots(distro, linuxRoot, io) {
259
+ const roots = [];
260
+ const visited = /* @__PURE__ */ new Set();
261
+ let frontier = [[linuxRoot, 0]];
262
+ while (frontier.length > 0 && roots.length < MAX_SKILL_ROOTS) {
263
+ const next = [];
264
+ for (const [dir, depth] of frontier) {
265
+ if (visited.size >= MAX_VISITED_DIRECTORIES) return roots;
266
+ if (visited.has(dir)) continue;
267
+ visited.add(dir);
268
+ if (roots.length < MAX_SKILL_ROOTS) {
269
+ const directoryRoots = await skillRootsOfDirectory(distro, dir, io);
270
+ roots.push(...directoryRoots.slice(0, MAX_SKILL_ROOTS - roots.length));
271
+ }
272
+ if (depth >= MAX_SCAN_DEPTH) continue;
273
+ let entries;
274
+ try {
275
+ entries = await io.readdir(joinUnc(distro, dir), { withFileTypes: true });
276
+ } catch {
277
+ continue;
278
+ }
279
+ for (const entry of entries) {
280
+ if (PRUNED_DIRECTORY_NAMES.has(entry.name)) continue;
281
+ if (entry.name.startsWith(".") && entry.name !== ".dsh" && entry.name !== ".agents") continue;
282
+ if (entry.name === ".dsh" || entry.name === ".agents") continue;
283
+ const childPath = posix.join(dir, entry.name);
284
+ if (entry.isDirectory()) {
285
+ next.push([childPath, depth + 1]);
286
+ continue;
287
+ }
288
+ if (entry.isSymbolicLink()) try {
289
+ const target = await io.stat(joinUnc(distro, childPath));
290
+ if (target.isDirectory()) next.push([childPath, depth + 1]);
291
+ } catch {}
292
+ }
293
+ }
294
+ frontier = next;
295
+ }
296
+ return roots;
297
+ }
298
+ /**
299
+ * Publish the skill roots of one scanned directory (its `.dsh/skills` and
300
+ * `.agents/skills`, each with the host's project ranks).
301
+ * @param distro - the WSL distribution name.
302
+ * @param linuxDir - the scanned directory's Linux path.
303
+ * @param io - filesystem face.
304
+ * @returns the directory's skill roots that exist.
305
+ */
306
+ async function skillRootsOfDirectory(distro, linuxDir, io) {
307
+ const result = [];
308
+ for (const [marker, source, rank] of [[
309
+ ".dsh",
310
+ "project-dsh",
311
+ PROJECT_DSH_RANK
312
+ ], [
313
+ ".agents",
314
+ "project-agents",
315
+ PROJECT_AGENTS_RANK
316
+ ]]) {
317
+ const path = joinUnc(distro, posix.join(linuxDir, marker, "skills"));
318
+ try {
319
+ const info = await io.stat(path);
320
+ if (info.isDirectory()) result.push({
321
+ path,
322
+ source,
323
+ rank
324
+ });
325
+ } catch {}
326
+ }
327
+ return result;
328
+ }
329
+ /** List one skills directory's entries (directory bundles and flat `.md` skills). */
330
+ async function listSkillEntries(root, io) {
331
+ let dirents;
332
+ try {
333
+ dirents = await io.readdir(root.path, { withFileTypes: true });
334
+ } catch {
335
+ return [];
336
+ }
337
+ const entries = [];
338
+ for (const entry of dirents) if (entry.isDirectory()) entries.push({
339
+ name: entry.name,
340
+ kind: "bundle",
341
+ path: join(root.path, entry.name, "SKILL.md")
342
+ });
343
+ else if (entry.isFile() && entry.name.endsWith(".md")) entries.push({
344
+ name: entry.name.slice(0, -3),
345
+ kind: "flat",
346
+ path: join(root.path, entry.name)
347
+ });
348
+ return entries.sort((a, b) => a.name.localeCompare(b.name));
349
+ }
350
+ /** Read and parse one skill file; `undefined` when missing or unparsable. */
351
+ async function readSkill(path, io, signal) {
352
+ signal?.throwIfAborted();
353
+ let raw;
354
+ try {
355
+ raw = await io.readFile(path, { encoding: "utf8" });
356
+ } catch {
357
+ return void 0;
358
+ }
359
+ signal?.throwIfAborted();
360
+ return parseSkillFrontmatter(raw, path);
361
+ }
362
+ /**
363
+ * Parse the frontmatter subset skill files use: `---` fenced YAML with
364
+ * `name` / `description` / `whenToUse` / `user-invocable` /
365
+ * `disable-model-invocation`. Single-line scalars and block scalars
366
+ * (`|` literal, `>` folded) are understood; anything else is skipped,
367
+ * matching the shipped provider's leniency: a bad file must not fail
368
+ * the catalog.
369
+ */
370
+ function parseSkillFrontmatter(raw, path) {
371
+ if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
372
+ const firstLineEnd = raw.indexOf("\n");
373
+ if (firstLineEnd < 0) return void 0;
374
+ if (raw.slice(0, firstLineEnd).replace(/\r$/, "") !== "---") return void 0;
375
+ const start = firstLineEnd + 1;
376
+ const closing = findFrontmatterEnd(raw, start);
377
+ if (closing === void 0) return void 0;
378
+ const lines = raw.slice(start, closing).split("\n");
379
+ const fields = /* @__PURE__ */ new Map();
380
+ for (let index = 0; index < lines.length; index += 1) {
381
+ const line = (lines[index] ?? "").replace(/\r$/, "");
382
+ const block = /^([A-Za-z0-9-]+):\s*([|>])[+-]?\s*$/.exec(line);
383
+ if (block !== null) {
384
+ const value$1 = parseBlockScalar(lines, index, block[2] === ">");
385
+ index = value$1.nextLineIndex;
386
+ if (value$1.text !== "") fields.set(block[1] ?? "", value$1.text);
387
+ continue;
388
+ }
389
+ const match = /^([A-Za-z0-9-]+):\s*(.*)$/.exec(line);
390
+ if (match === null) continue;
391
+ const value = match[2]?.trim() ?? "";
392
+ if (value !== "") fields.set(match[1] ?? "", unquote(value));
393
+ }
394
+ const name$1 = fields.get("name") ?? "";
395
+ const description = fields.get("description") ?? "";
396
+ if (!SKILL_NAME.test(name$1) || description === "") return void 0;
397
+ const whenToUse = fields.get("whenToUse");
398
+ return {
399
+ name: name$1,
400
+ description,
401
+ ...whenToUse !== void 0 && whenToUse !== "" ? { whenToUse } : {},
402
+ invocation: {
403
+ modelInvocable: !frontmatterBoolean(fields, "disable-model-invocation"),
404
+ userInvocable: frontmatterBoolean(fields, "user-invocable", true)
405
+ },
406
+ content: raw.slice(closing).trim()
407
+ };
408
+ }
409
+ /**
410
+ * Collect a YAML block scalar (`key: |` literal or `key: >` folded) starting
411
+ * at `startIndex`'s following lines. The block runs until the first
412
+ * non-indented, non-blank line; its common indentation is stripped.
413
+ * @returns the scalar text and the index of the last consumed line.
414
+ */
415
+ function parseBlockScalar(lines, startIndex, folded) {
416
+ const collected = [];
417
+ let indent;
418
+ let index = startIndex;
419
+ while (index + 1 < lines.length) {
420
+ index += 1;
421
+ const next = (lines[index] ?? "").replace(/\r$/, "");
422
+ if (next.trim() === "") {
423
+ collected.push("");
424
+ continue;
425
+ }
426
+ const indented = /^([ \t]+)(.*)$/.exec(next);
427
+ if (indented === null) {
428
+ index -= 1;
429
+ break;
430
+ }
431
+ indent ??= indented[1];
432
+ collected.push(indented[1]?.startsWith(indent) === true ? indented[2] : indented[1].replace(/^[ \t]+/, "") + indented[2]);
433
+ }
434
+ while (collected.length > 0 && collected[collected.length - 1] === "") collected.pop();
435
+ const text = (folded ? collected.filter((line) => line !== "").join(" ") : collected.join("\n")).trim();
436
+ return {
437
+ text,
438
+ nextLineIndex: index
439
+ };
440
+ }
441
+ /** Locate the closing `---` line of a frontmatter block. */
442
+ function findFrontmatterEnd(raw, start) {
443
+ let lineStart = start;
444
+ while (lineStart <= raw.length) {
445
+ const nextNewline = raw.indexOf("\n", lineStart);
446
+ const lineEnd = nextNewline < 0 ? raw.length : nextNewline;
447
+ if (raw.slice(lineStart, lineEnd).replace(/\r$/, "") === "---") return lineEnd + 1;
448
+ if (nextNewline < 0) return void 0;
449
+ lineStart = nextNewline + 1;
450
+ }
451
+ return void 0;
452
+ }
453
+ /** Strip one level of matching quotes from a scalar value. */
454
+ function unquote(value) {
455
+ if (value.length >= 2) {
456
+ const first = value[0];
457
+ const last = value[value.length - 1];
458
+ if (first === "\"" && last === "\"" || first === "'" && last === "'") return value.slice(1, -1);
459
+ }
460
+ return value;
461
+ }
462
+ /** Boolean semantics for `user-invocable` / `disable-model-invocation` (matches the host parser). */
463
+ function frontmatterBoolean(fields, key, dflt = false) {
464
+ const value = fields.get(key);
465
+ if (value === void 0) return dflt;
466
+ switch (value.toLowerCase()) {
467
+ case "true":
468
+ case "yes":
469
+ case "on":
470
+ case "1": return true;
471
+ case "false":
472
+ case "no":
473
+ case "off":
474
+ case "0": return false;
475
+ default: return dflt;
476
+ }
477
+ }
478
+ /**
479
+ * The WSL workspace skill provider. Registered on the host's `ctx.skills`
480
+ * registry; serves only lookups whose cwd is a WSL UNC workspace path.
481
+ *
482
+ * Completed `list()` lookups are cached per scan root for CACHE_TTL_MS so
483
+ * repeated catalog builds over the slow 9P share do not rescan the tree;
484
+ * `get()` always re-reads the skill file so body edits are picked up
485
+ * immediately. `control.invalidate` remains reserved for host-driven
486
+ * invalidation; the provider self-invalidates through the TTL.
487
+ */
488
+ var WslSkillsProvider = class {
489
+ name = "wsl-workspace";
490
+ control;
491
+ io;
492
+ now;
493
+ cache = /* @__PURE__ */ new Map();
494
+ constructor(control, io = nodeSkillIo, now = Date.now) {
495
+ this.control = control;
496
+ this.io = io;
497
+ this.now = now;
498
+ }
499
+ /**
500
+ * Discover nested project skills for a WSL UNC session workspace.
501
+ * @param options - lookup options; `cwd` selects the WSL workspace.
502
+ * @returns candidates for every `.dsh/skills` / `.agents/skills` under the
503
+ * session's scan root — the nearest `.git` ancestor of the cwd, else the
504
+ * cwd itself — or an empty array for non-WSL lookups.
505
+ */
506
+ async list(options) {
507
+ this.control.signal.throwIfAborted();
508
+ options.signal?.throwIfAborted();
509
+ const unc = options.cwd === void 0 ? null : parseWslUnc(options.cwd);
510
+ if (unc === null) return [];
511
+ const scanRoot = await nearestGitAncestor(unc.distro, unc.linuxPath, this.io) ?? unc.linuxPath;
512
+ const cacheKey = `${unc.distro}\u0000${scanRoot}`;
513
+ const cached = this.cache.get(cacheKey);
514
+ if (cached !== void 0 && cached.expiresAt > this.now()) {
515
+ this.cache.delete(cacheKey);
516
+ this.cache.set(cacheKey, cached);
517
+ return [...cached.candidates];
518
+ }
519
+ const roots = await discoverSkillRoots(unc.distro, scanRoot, this.io);
520
+ const candidates = [];
521
+ const seenSkills = /* @__PURE__ */ new Set();
522
+ for (const root of roots) {
523
+ const entries = await listSkillEntries(root, this.io);
524
+ for (const entry of entries) {
525
+ options.signal?.throwIfAborted();
526
+ const parsed = await readSkill(entry.path, this.io, options.signal);
527
+ if (parsed === void 0) continue;
528
+ const fingerprint = `${parsed.name}\u0000${parsed.content}`;
529
+ if (seenSkills.has(fingerprint)) continue;
530
+ seenSkills.add(fingerprint);
531
+ candidates.push({
532
+ name: parsed.name,
533
+ description: parsed.description,
534
+ ...parsed.whenToUse !== void 0 ? { whenToUse: parsed.whenToUse } : {},
535
+ invocation: parsed.invocation,
536
+ source: root.source,
537
+ provider: this.name,
538
+ rank: root.rank,
539
+ locator: {
540
+ path: entry.path,
541
+ directory: entry.kind === "bundle" ? join(entry.path, "..") : root.path
542
+ },
543
+ path: entry.path
544
+ });
545
+ }
546
+ }
547
+ this.cache.set(cacheKey, {
548
+ expiresAt: this.now() + CACHE_TTL_MS,
549
+ candidates
550
+ });
551
+ while (this.cache.size > CACHE_MAX_ENTRIES) {
552
+ const oldest = this.cache.keys().next().value;
553
+ if (oldest === void 0) break;
554
+ this.cache.delete(oldest);
555
+ }
556
+ return candidates;
557
+ }
558
+ /**
559
+ * Load a complete skill body for a previously listed candidate.
560
+ * @param candidate - the candidate this provider returned.
561
+ * @param options - lookup options whose signal cancels the read.
562
+ * @returns the full skill, or `undefined` if the file disappeared.
563
+ */
564
+ async get(candidate, options) {
565
+ this.control.signal.throwIfAborted();
566
+ const parsed = await readSkill(candidate.locator.path, this.io, options.signal);
567
+ if (parsed === void 0 || parsed.name !== candidate.name) return void 0;
568
+ return {
569
+ name: parsed.name,
570
+ description: parsed.description,
571
+ ...parsed.whenToUse !== void 0 ? { whenToUse: parsed.whenToUse } : {},
572
+ invocation: parsed.invocation,
573
+ source: candidate.source,
574
+ provider: candidate.provider,
575
+ rank: candidate.rank,
576
+ locator: candidate.locator,
577
+ path: candidate.path,
578
+ content: parsed.content
579
+ };
580
+ }
581
+ };
582
+
583
+ //#endregion
584
+ //#region src/index.ts
585
+ /** The HTTP route this plugin serves (a relative, same-origin path). */
586
+ const DEFAULT_ROUTE = "/wsl-workspace/api";
587
+ /**
588
+ * Bilingual display labels for the shipped source modes, matching the app's
589
+ * own built-in copy in each language — note the `code` preset is "PTC 模式"
590
+ * in the Chinese copy but "Code mode" in English. The DSH picker localizes
591
+ * only the four built-in ids itself; `wsl-*` variant ids render the
592
+ * preset.yml text verbatim, so the plugin writes one bilingual string so
593
+ * both locales can identify each variant. Custom presets keep their own
594
+ * name.
595
+ */
596
+ const MODE_DISPLAY_LABELS = {
597
+ standard: {
598
+ en: "Standard mode",
599
+ zh: "标准模式"
600
+ },
601
+ code: {
602
+ en: "Code mode",
603
+ zh: "PTC 模式"
604
+ },
605
+ minimal: {
606
+ en: "Minimal mode",
607
+ zh: "极简模式"
608
+ },
609
+ cordis: {
610
+ en: "Creator mode",
611
+ zh: "创造模式"
612
+ }
613
+ };
614
+ /**
615
+ * Quote a value as a single-line YAML single-quoted scalar. Plain scalars
616
+ * cannot contain `: ` (colon + space), which plain English sentences do —
617
+ * written unquoted they make the whole preset.yml unparsable, dropping the
618
+ * name, description and order together.
619
+ */
620
+ function yamlScalar(value) {
621
+ return `'${value.replace(/'/g, "''")}'`;
622
+ }
623
+ /** The variant name for one shipped mode (bilingual) or a custom preset. */
624
+ function variantName(presetId, sourceName) {
625
+ const labels = MODE_DISPLAY_LABELS[presetId];
626
+ return labels === void 0 ? `WSL · ${sourceName}` : `WSL · ${labels.en}(${labels.zh})`;
627
+ }
628
+ /** The variant description for one shipped mode (bilingual) or a custom preset. */
629
+ function variantDescription(presetId) {
630
+ const labels = MODE_DISPLAY_LABELS[presetId];
631
+ const display = labels === void 0 ? presetId : `${labels.en}(${labels.zh})`;
632
+ return `WSL execution world for ${display}: bash and file tools run inside the WSL distribution.`;
633
+ }
634
+ const MAX_BODY_BYTES = 1024 * 1024;
635
+ /** Valid WSL distribution names: one path-safe segment (no separators, no dot-dirs). */
636
+ const DISTRO_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/;
637
+ /** The loopback hostnames the data route answers to (DNS-rebinding fence). */
638
+ const LOOPBACK_HOSTNAMES = new Set([
639
+ "localhost",
640
+ "127.0.0.1",
641
+ "::1",
642
+ "::ffff:127.0.0.1"
643
+ ]);
644
+ /** True when a socket address is loopback (any IPv4/IPv6 spelling). */
645
+ function isLoopback(address) {
646
+ return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
647
+ }
648
+ /** The hostname part of a `Host` header value (port and IPv6 brackets stripped). */
649
+ function hostNameOf(host) {
650
+ if (host.startsWith("[")) {
651
+ const end = host.indexOf("]");
652
+ return end >= 0 ? host.slice(1, end) : host;
653
+ }
654
+ return host.split(":")[0] ?? "";
655
+ }
656
+ /** True when the request's `Host` header names a loopback host. */
657
+ function isLoopbackHost(host) {
658
+ return host !== void 0 && LOOPBACK_HOSTNAMES.has(hostNameOf(host).toLowerCase());
659
+ }
660
+ /**
661
+ * Validate a wire-supplied distribution name before it becomes a UNC segment:
662
+ * an attacker-controlled segment containing separators or `..` would escape
663
+ * the `\\wsl.localhost\` share structure into arbitrary UNC paths.
664
+ * @param value - the raw wire value.
665
+ * @returns the validated distro name.
666
+ */
667
+ function requireDistro(value) {
668
+ if (typeof value !== "string" || !DISTRO_PATTERN.test(value) || value === "." || value === "..") throw new Error("distro must be a valid WSL distribution name");
669
+ return value;
670
+ }
671
+ /** Human text for an unknown rejection. */
672
+ function messageOf(value) {
673
+ return value instanceof Error ? value.message : String(value);
674
+ }
675
+ /** Write one JSON envelope. */
676
+ function json(res, status, body) {
677
+ res.writeHead(status, {
678
+ "content-type": "application/json; charset=utf-8",
679
+ "cache-control": "no-store",
680
+ "x-content-type-options": "nosniff"
681
+ });
682
+ res.end(JSON.stringify(body));
683
+ }
684
+ /** Collect and parse the request body, bounded. */
685
+ async function readBody(req) {
686
+ const chunks = [];
687
+ let size = 0;
688
+ for await (const chunk of req) {
689
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
690
+ size += buffer.length;
691
+ if (size > MAX_BODY_BYTES) throw new Error("request body is too large");
692
+ chunks.push(buffer);
693
+ }
694
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
695
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("request body must be a JSON object");
696
+ return parsed;
697
+ }
698
+ /** Normalize a Linux path for the wire (rejecting non-absolute input). */
699
+ function requireLinuxPath(value, label) {
700
+ if (typeof value !== "string" || !isAbsoluteLinuxPath(value)) throw new Error(`${label} must be an absolute Linux path`);
701
+ return normalizeLinuxPath(value);
702
+ }
703
+ /** Validate a wire-supplied workspace path and return its canonical UNC form. */
704
+ function requireWslUnc(value) {
705
+ if (typeof value !== "string") throw new Error("path must be a string");
706
+ const canonical = canonicalWslUnc(value);
707
+ if (canonical === null) throw new Error("path must be a WSL UNC workspace path");
708
+ return canonical;
709
+ }
710
+ /**
711
+ * Resolve one directory listing for the dialog. The 9P share (`\\wsl.localhost\…`)
712
+ * serves only the ext4 volume: `/mnt/<drive>` (drvfs) reads return Access
713
+ * denied, so drvfs paths are read through their Windows drive spelling and
714
+ * `/mnt` itself is synthesized from the drives present on the host.
715
+ */
716
+ function listWslDir(distro, linuxPath) {
717
+ if (linuxPath === "/mnt") {
718
+ const entries$1 = [];
719
+ for (let i = 0; i < 26; i++) {
720
+ const letter = String.fromCharCode(65 + i);
721
+ try {
722
+ const info = statSync(`${letter}:\\`);
723
+ if (info.isDirectory()) entries$1.push({
724
+ name: letter.toLowerCase(),
725
+ kind: "directory"
726
+ });
727
+ } catch {}
728
+ }
729
+ return {
730
+ path: "/mnt",
731
+ parent: "/",
732
+ entries: entries$1
733
+ };
734
+ }
735
+ const winPath = mntToWindowsPath(linuxPath);
736
+ const readPath = winPath !== null ? winPath : joinUnc(distro, linuxPath);
737
+ const dirents = readdirSync(readPath, { withFileTypes: true });
738
+ const entries = dirents.slice(0, 1e3).map((dirent) => {
739
+ const kind = dirent.isDirectory() ? "directory" : dirent.isFile() ? "file" : "other";
740
+ return {
741
+ name: dirent.name,
742
+ kind
743
+ };
744
+ }).sort((a, b) => {
745
+ if (a.kind === "directory" && b.kind !== "directory") return -1;
746
+ if (a.kind !== "directory" && b.kind === "directory") return 1;
747
+ return a.name.localeCompare(b.name);
748
+ });
749
+ const parent = linuxPath === "/" ? null : linuxPath.split("/").slice(0, -1).join("/") || "/";
750
+ return {
751
+ path: linuxPath,
752
+ parent,
753
+ entries
754
+ };
755
+ }
756
+ /** Route one method dispatch. */
757
+ async function dispatch(method, params) {
758
+ switch (method) {
759
+ case "listDistros": {
760
+ const distros = await listDistros();
761
+ const fallback = await defaultDistro();
762
+ if (fallback !== void 0 && distros.includes(fallback)) return [fallback, ...distros.filter((name$1) => name$1 !== fallback)];
763
+ return distros;
764
+ }
765
+ case "listDir": {
766
+ const distro = requireDistro(params.distro);
767
+ const path = requireLinuxPath(params.path, "path");
768
+ return listWslDir(distro, path);
769
+ }
770
+ case "check": {
771
+ const distro = requireDistro(params.distro);
772
+ const path = requireLinuxPath(params.path, "path");
773
+ const winPath = mntToWindowsPath(path);
774
+ const readPath = winPath !== null ? winPath : joinUnc(distro, path);
775
+ try {
776
+ const info = statSync(readPath);
777
+ return {
778
+ exists: true,
779
+ isDirectory: info.isDirectory()
780
+ };
781
+ } catch {
782
+ return {
783
+ exists: false,
784
+ isDirectory: false
785
+ };
786
+ }
787
+ }
788
+ case "registerWindows": {
789
+ const distro = requireDistro(params.distro);
790
+ const linuxPath = requireLinuxPath(params.linuxPath, "path");
791
+ const winPath = mntToWindowsPath(linuxPath);
792
+ if (winPath === null) throw new Error("registerWindows requires a /mnt/<drive> Linux path");
793
+ const username = typeof params.username === "string" ? params.username : void 0;
794
+ registerWindowsWorkspace(winPath, distro, username);
795
+ return null;
796
+ }
797
+ case "listWorkspaces": return listWorkspaceKeys();
798
+ case "setUser": {
799
+ const path = requireWslUnc(params.path);
800
+ const username = params.username;
801
+ if (username === void 0 || username === "") setWorkspaceUsername(path, void 0);
802
+ else {
803
+ if (typeof username !== "string" || !isValidWslUsername(username)) throw new Error("username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*");
804
+ setWorkspaceUsername(path, username);
805
+ }
806
+ return null;
807
+ }
808
+ default: throw new Error(`unknown method "${method}"`);
809
+ }
810
+ }
811
+ /**
812
+ * Publish a fully staged preset directory while preserving the last complete
813
+ * variant if publication fails. Stable sibling names also let the next boot
814
+ * recover an interrupted old-to-backup rename before doing new work.
815
+ */
816
+ function publishVariant(staging, dest) {
817
+ const previous = `${dest}.previous`;
818
+ if (!existsSync(dest) && existsSync(previous)) renameSync(previous, dest);
819
+ if (existsSync(previous)) rmSync(previous, {
820
+ recursive: true,
821
+ force: true
822
+ });
823
+ if (existsSync(dest)) renameSync(dest, previous);
824
+ try {
825
+ renameSync(staging, dest);
826
+ } catch (error) {
827
+ if (!existsSync(dest) && existsSync(previous)) renameSync(previous, dest);
828
+ throw error;
829
+ }
830
+ rmSync(previous, {
831
+ recursive: true,
832
+ force: true
833
+ });
834
+ }
835
+ /** Materialize one WSL variant per healthy source preset. */
836
+ async function materializeVariants(agentPresets, dshHome, shellPath, fsPath) {
837
+ const presets = await agentPresets.list();
838
+ const userRoot = join(dshHome, ".agent-presets");
839
+ const generated = /* @__PURE__ */ new Set();
840
+ for (const preset of presets) {
841
+ if (preset.broken !== void 0) continue;
842
+ if (isWslVariantId(preset.id)) continue;
843
+ const variantId = variantIdFor(preset.id);
844
+ const source = await agentPresets.read(preset.id);
845
+ const transformed = transformPresetForWsl(source, shellPath, fsPath);
846
+ const dir = join(userRoot, variantId);
847
+ const staging = `${dir}.staging`;
848
+ rmSync(staging, {
849
+ recursive: true,
850
+ force: true
851
+ });
852
+ cpSync(dirname(preset.path), staging, {
853
+ recursive: true,
854
+ force: true
855
+ });
856
+ writeFileSync(join(staging, "agent.cordis.yml"), transformed, "utf8");
857
+ const labels = MODE_DISPLAY_LABELS[preset.id];
858
+ let name$1 = variantName(preset.id, preset.id);
859
+ let orderLine = "";
860
+ try {
861
+ const meta = readFileSync(join(dirname(preset.path), "preset.yml"), "utf8");
862
+ if (labels === void 0) {
863
+ const match = /^name:\s*(.+)$/m.exec(meta);
864
+ if (match?.[1] !== void 0 && match[1].trim() !== "") name$1 = variantName(preset.id, match[1].trim());
865
+ }
866
+ const orderMatch = /^order:\s*(\d+)\s*$/m.exec(meta);
867
+ if (orderMatch?.[1] !== void 0) orderLine = `order: ${orderMatch[1]}\n`;
868
+ } catch {}
869
+ writeFileSync(join(staging, "preset.yml"), `name: ${yamlScalar(name$1)}\n` + orderLine + `description: ${yamlScalar(variantDescription(preset.id))}\n`, "utf8");
870
+ publishVariant(staging, dir);
871
+ generated.add(variantId);
872
+ }
873
+ for (const entry of readdirSync(userRoot, { withFileTypes: true })) {
874
+ if (!entry.isDirectory()) continue;
875
+ if (entry.name === "wsl") {
876
+ rmSync(join(userRoot, entry.name), {
877
+ recursive: true,
878
+ force: true
879
+ });
880
+ continue;
881
+ }
882
+ if (!/^wsl-[a-z0-9-]+$/.test(entry.name)) continue;
883
+ if (!generated.has(entry.name)) rmSync(join(userRoot, entry.name), {
884
+ recursive: true,
885
+ force: true
886
+ });
887
+ }
888
+ }
889
+ /** Function-plugin plugin contract. */
890
+ const name = "dsh-wsl-workspace";
891
+ /** Required services. */
892
+ const inject = ["webServer"];
893
+ /** Validated plugin config (schemastery applied the defaults). */
894
+ const Config = z.object({ route: z.string().default(DEFAULT_ROUTE) });
895
+ /**
896
+ * Apply the host half: materialize a `wsl-<mode>` variant for every healthy
897
+ * roster preset, register the data route, and
898
+ * contribute the per-session `DSH_WSL_DISTRO` managed-env fact so the WSL
899
+ * shell executor can resolve a plain Linux `workdir` to the calling
900
+ * session's distribution.
901
+ * @param ctx - the host plugin context.
902
+ * @param config - the validated configuration.
903
+ */
904
+ function apply(ctx, config) {
905
+ const resolved = config;
906
+ const dshHome = process.env.DSH_HOME ?? join(homedir(), ".dsh");
907
+ const packageRoot = fileURLToPath(new URL("..", import.meta.url));
908
+ const shellPath = join(packageRoot, "lib", "shell.js").replace(/\\/g, "/");
909
+ const fsPath = join(packageRoot, "lib", "fs.js").replace(/\\/g, "/");
910
+ const agentPresets = ctx.get("agentPresets");
911
+ if (agentPresets !== void 0) ctx.effect(() => {
912
+ materializeVariants(agentPresets, dshHome, shellPath, fsPath).catch((error) => {
913
+ console.error(`dsh-wsl-workspace: WSL preset-variant generation failed: ${messageOf(error)}`);
914
+ });
915
+ return () => {};
916
+ }, "dsh-wsl-workspace: WSL preset variants");
917
+ const skills = ctx.get("skills");
918
+ if (skills !== void 0 && typeof skills.registerProvider === "function") ctx.effect(() => skills.registerProvider((control) => new WslSkillsProvider(control)), "dsh-wsl-workspace: WSL workspace skills provider");
919
+ const shellEnv = ctx.get("shellEnv");
920
+ if (shellEnv !== void 0) ctx.effect(() => shellEnv.register({
921
+ name: "wsl-workspace-distro",
922
+ variables: {
923
+ DSH_WSL_DISTRO: { description: "The WSL distribution of the calling session workspace, when the session cwd is a WSL UNC path." },
924
+ DSH_WSL_USER: { description: "The Linux user of the calling session workspace, when the workspace has one configured." }
925
+ },
926
+ resolve(execution) {
927
+ const cwd = execution.agent?.session.header.cwd;
928
+ const unc = cwd === void 0 ? null : parseWslUnc(cwd);
929
+ if (unc !== null) {
930
+ const username = getWorkspaceUsername(joinUnc(unc.distro, unc.linuxPath));
931
+ return username === void 0 || username === "" ? { DSH_WSL_DISTRO: unc.distro } : {
932
+ DSH_WSL_DISTRO: unc.distro,
933
+ DSH_WSL_USER: username
934
+ };
935
+ }
936
+ if (cwd !== void 0 && /^[A-Za-z]:[\\/]/.test(cwd)) {
937
+ const entry = getWindowsWorkspace(cwd);
938
+ if (entry !== void 0 && entry.distro !== void 0 && entry.distro !== "") return entry.username === void 0 || entry.username === "" ? { DSH_WSL_DISTRO: entry.distro } : {
939
+ DSH_WSL_DISTRO: entry.distro,
940
+ DSH_WSL_USER: entry.username
941
+ };
942
+ }
943
+ return {};
944
+ }
945
+ }), "dsh-wsl-workspace: per-session distro env fact");
946
+ const webServer = ctx.get("webServer");
947
+ ctx.effect(() => webServer.register({
948
+ kind: "exact",
949
+ path: resolved.route,
950
+ handler: async (req, res) => {
951
+ if (!isLoopback(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host)) {
952
+ json(res, 403, {
953
+ ok: false,
954
+ error: "loopback-only"
955
+ });
956
+ return;
957
+ }
958
+ if (req.method !== "POST") {
959
+ json(res, 405, {
960
+ ok: false,
961
+ error: "method not allowed"
962
+ });
963
+ return;
964
+ }
965
+ let body;
966
+ try {
967
+ body = await readBody(req);
968
+ } catch (error) {
969
+ json(res, 400, {
970
+ ok: false,
971
+ error: messageOf(error)
972
+ });
973
+ return;
974
+ }
975
+ const method = typeof body.method === "string" ? body.method : "";
976
+ const params = body.params === void 0 ? {} : body.params;
977
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
978
+ json(res, 400, {
979
+ ok: false,
980
+ error: "params must be an object"
981
+ });
982
+ return;
983
+ }
984
+ try {
985
+ const value = await dispatch(method, params);
986
+ json(res, 200, {
987
+ ok: true,
988
+ value
989
+ });
990
+ } catch (error) {
991
+ json(res, 200, {
992
+ ok: false,
993
+ error: messageOf(error)
994
+ });
995
+ }
996
+ }
997
+ }), "dsh-wsl-workspace: dialog data route");
998
+ }
999
+
1000
+ //#endregion
1001
+ export { Config, DEFAULT_ROUTE, apply, inject, name };
924
1002
  //# sourceMappingURL=index.js.map