dsh-wsl-workspace 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,542 +1,574 @@
1
- import { i as joinUnc, n as isValidWslUsername, o as normalizeLinuxPath, s as parseWslUnc, t as isAbsoluteLinuxPath } from "./paths-DBaSmi7x.js";
2
- import { a as getWorkspaceUsername, i as canonicalWslUnc, o as setWorkspaceUsername, r as listDistros, t as defaultDistro } from "./wsl-GjkUifnx.js";
3
- import z from "@deepseek-ai/schemastery";
4
- import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
5
- import { fileURLToPath } from "node:url";
6
- import { dirname, join } from "node:path";
7
- import { homedir } from "node:os";
8
- //#region src/host/variants.ts
9
- /**
10
- * WSL preset-variant generator. For every healthy source preset the roster
11
- * supplies, a `wsl-<id>` variant is materialized under the roster's user
12
- * root: the source composition with its shell/filesystem world replaced by
13
- * the WSL providers, so any mode (standard, minimal, code, cordis, user
14
- * presets) can run on top of a WSL execution world. The execution world is
15
- * therefore orthogonal to the mode instead of a mode itself.
16
- *
17
- * The transformation is text-level on the top-level rows of the composition
18
- * (the shape all shipped presets share), with surgical edits for the known
19
- * special groups; unknown shapes are kept verbatim where possible.
20
- * @module dsh-wsl-workspace/host/variants
21
- */
22
- /** Top-level rows that name the execution world and are replaced by the variant's own. */
23
- const WORLD_ROWS = new Set([
24
- "tool-bash",
25
- "tool-pwsh",
26
- "tool-fs",
27
- "tool-fs-search",
28
- "filesystem",
29
- "persistent-shell"
30
- ]);
31
- /** The injected WSL world group: providers + the bash/fs consumers, entry-local. */
32
- function wslWorldGroup(shellPath, fsPath, includeEditor) {
33
- return [
34
- "# ── WSL execution world (dsh-wsl-workspace variant) ─────────────────────",
35
- "# The shell and fs services are provided entry-locally (the isolate",
36
- "# realm); host services (tools registry, shell-env, jobs) fall through.",
37
- "# tool-fs-search is intentionally absent: the packaged ripgrep runs on",
38
- "# the Windows host and cannot open Linux paths; WSL sessions search with",
39
- "# shell tools instead.",
40
- "- id: wsl-world",
41
- " name: cordis:group",
42
- " group: true",
43
- " isolate:",
44
- " shell: true",
45
- " fs: true",
46
- " config:",
47
- ` - id: shell-wsl`,
48
- ` name: '${shellPath.replace(/'/g, "''")}'`,
49
- " - id: fs-wsl",
50
- ` name: '${fsPath.replace(/'/g, "''")}'`,
51
- " - id: tool-bash",
52
- " name: '@deepseek-ai/dsh-tool-bash'",
53
- " - id: tool-fs",
54
- " name: '@deepseek-ai/dsh-tool-fs'",
55
- ...includeEditor ? [
56
- " - id: str-replace-editor",
57
- " name: '@deepseek-ai/dsh-tool-str-replace-editor'",
58
- " config:",
59
- " maxOutputChars: 16000"
60
- ] : [],
61
- ""
62
- ].join("\n");
63
- }
64
- /**
65
- * The persistent-shell group re-pointed at WSL: the PTY spawns wsl.exe's
66
- * bash instead of a host `bash` (which does not exist on Windows).
67
- */
68
- function persistentShellGroup() {
69
- return [
70
- "# ── persistent shell over WSL (variant) ─────────────────────────────────",
71
- "- id: persistent-shell",
72
- " name: cordis:group",
73
- " group: true",
74
- " isolate:",
75
- " terminals: true",
76
- " config:",
77
- " - id: pty",
78
- " name: '@deepseek-ai/dsh-terminal'",
79
- "",
80
- " - id: terminal-bash",
81
- " name: '@deepseek-ai/dsh-terminal-bash'",
82
- " config:",
83
- " timeoutMs: 300000",
84
- " shellPath: 'wsl.exe'",
85
- " shellArgs: ['-e', 'bash', '-l']",
86
- "",
87
- " - id: persistent-bash",
88
- " name: '@deepseek-ai/dsh-tool-bash-persistent'",
89
- " config:",
90
- " timeoutMs: 300000",
91
- " description: |-",
92
- " Run commands in a bash shell inside the WSL distribution",
93
- " * When invoking this tool, the contents of the \"command\" parameter does NOT need to be XML-escaped.",
94
- " * You don't have access to the internet via this tool.",
95
- " * You do have access to a mirror of common linux and python packages via apt and pip.",
96
- " * State is persistent across command calls and discussions with the user.",
97
- " * To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.",
98
- " * Please avoid commands that may produce a very large amount of output.",
99
- " * Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.",
100
- ""
101
- ].join("\n");
102
- }
103
- /** The sentence appended to a standard-like persona when the variant runs in WSL. */
104
- 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.";
105
- /** The top-level rows of one composition, as (startLine, endLineExclusive) spans. */
106
- function topLevelSpans(lines) {
107
- const spans = [];
108
- let start = -1;
109
- for (let index = 0; index < lines.length; index++) if (lines[index]?.startsWith("- id: ") === true) {
110
- if (start >= 0) spans.push({
111
- start,
112
- end: index
113
- });
114
- start = index;
115
- }
116
- if (start >= 0) spans.push({
117
- start,
118
- end: lines.length
119
- });
120
- return spans;
121
- }
122
- /** The row id of a top-level span, or undefined when the first line is malformed. */
123
- function spanId(lines, span) {
124
- return /^- id: ([A-Za-z0-9_.-]+)/.exec(lines[span.start] ?? "")?.[1];
125
- }
126
- /** Whether a top-level span is a `persona` row with an appendable folded text. */
127
- function appendablePersona(lines, span) {
128
- const block = lines.slice(span.start, span.end).join("\n");
129
- if (!block.includes("complete: true") && /text: [>|-]/.test(block)) {
130
- const textLine = block.split("\n").find((line) => /^(\s*)text: [>|-]/.test(line));
131
- if (textLine !== void 0) {
132
- const indent = /^(\s*)/.exec(textLine)?.[1]?.length ?? 0;
133
- return block.split("\n").some((line) => line.length > indent && /^\s+/.test(line) && !line.includes(":"));
134
- }
135
- }
136
- return false;
137
- }
138
- /** Append the WSL sentence to a persona row's folded text (in place of its last text line). */
139
- function appendPersona(lines, span) {
140
- const block = lines.slice(span.start, span.end);
141
- const textIndex = block.findIndex((line) => /^(\s*)text: [>|-]/.test(line));
142
- if (textIndex < 0) return [...block];
143
- const indent = /^(\s*)/.exec(block[textIndex] ?? "")?.[1]?.length ?? 0;
144
- let lastText = -1;
145
- for (let index = textIndex + 1; index < block.length; index++) {
146
- const line = block[index] ?? "";
147
- if (line.trim() === "") continue;
148
- if (line.length > indent && /^\s+/.test(line)) lastText = index;
149
- }
150
- if (lastText < 0) return [...block];
151
- const updated = [...block];
152
- const textIndent = /^(\s*)/.exec(block[lastText] ?? "")?.[1] ?? " ";
153
- updated.splice(lastText + 1, 0, `${textIndent}${PERSONA_APPEND}`);
154
- return updated;
155
- }
156
- /**
157
- * Transform one source preset composition into its WSL variant: drop the
158
- * execution-world rows, keep everything else verbatim, and append the WSL
159
- * world group (plus the persistent-shell group when the source had one).
160
- * @param source - the source composition text.
161
- * @param shellPath - absolute path of the plugin's built WSL shell provider.
162
- * @param fsPath - absolute path of the plugin's built WSL fs provider.
163
- * @returns the variant composition text.
164
- */
165
- function transformPresetForWsl(source, shellPath, fsPath) {
166
- const lines = source.split("\n");
167
- const spans = topLevelSpans(lines);
168
- const kept = [];
169
- let sawEditor = false;
170
- let sawPersistent = false;
171
- let personaAppended = false;
172
- for (const span of spans) {
173
- const id = spanId(lines, span);
174
- if (id === void 0) {
175
- kept.push(...lines.slice(span.start, span.end));
176
- continue;
177
- }
178
- if (WORLD_ROWS.has(id)) {
179
- if (id === "persistent-shell") sawPersistent = true;
180
- continue;
181
- }
182
- if (id === "persona" && !personaAppended && appendablePersona(lines, span)) {
183
- kept.push(...appendPersona(lines, span));
184
- personaAppended = true;
185
- continue;
186
- }
187
- kept.push(...lines.slice(span.start, span.end));
188
- if (id === "str-replace-editor") sawEditor = true;
189
- }
190
- if (source.includes("str-replace-editor")) sawEditor = true;
191
- const result = [...kept];
192
- if (result.length > 0 && result[result.length - 1] !== "") result.push("");
193
- result.push(wslWorldGroup(shellPath, fsPath, sawEditor));
194
- if (sawPersistent) result.push(persistentShellGroup());
195
- return result.join("\n").replace(/\n{3,}/g, "\n\n").replace(/\n+$/, "\n");
196
- }
197
- /** Whether an id is one of this plugin's own preset directories. */
198
- function isWslVariantId(id) {
199
- return id === "wsl" || /^wsl-[a-z0-9-]+$/.test(id);
200
- }
201
- /** The variant id for one source preset id. */
202
- function variantIdFor(sourceId) {
203
- return `wsl-${sourceId.toLowerCase()}`;
204
- }
205
- //#endregion
206
- //#region src/index.ts
207
- /** The HTTP route this plugin serves (a relative, same-origin path). */
208
- const DEFAULT_ROUTE = "/wsl-workspace/api";
209
- /**
210
- * Bilingual display labels for the shipped source modes, matching the app's
211
- * own built-in copy in each language — note the `code` preset is "PTC 模式"
212
- * in the Chinese copy but "Code mode" in English. The DSH picker localizes
213
- * only the four built-in ids itself; `wsl-*` variant ids render the
214
- * preset.yml text verbatim, so the plugin writes one bilingual string so
215
- * both locales can identify each variant. Custom presets keep their own
216
- * name.
217
- */
218
- const MODE_DISPLAY_LABELS = {
219
- standard: {
220
- en: "Standard mode",
221
- zh: "标准模式"
222
- },
223
- code: {
224
- en: "Code mode",
225
- zh: "PTC 模式"
226
- },
227
- minimal: {
228
- en: "Minimal mode",
229
- zh: "极简模式"
230
- },
231
- cordis: {
232
- en: "Creator mode",
233
- zh: "创造模式"
234
- }
235
- };
236
- /**
237
- * Quote a value as a single-line YAML single-quoted scalar. Plain scalars
238
- * cannot contain `: ` (colon + space), which plain English sentences do —
239
- * written unquoted they make the whole preset.yml unparsable, dropping the
240
- * name, description and order together.
241
- */
242
- function yamlScalar(value) {
243
- return `'${value.replace(/'/g, "''")}'`;
244
- }
245
- /** The variant name for one shipped mode (bilingual) or a custom preset. */
246
- function variantName(presetId, sourceName) {
247
- const labels = MODE_DISPLAY_LABELS[presetId];
248
- return labels === void 0 ? `WSL · ${sourceName}` : `WSL · ${labels.en}(${labels.zh})`;
249
- }
250
- /** The variant description for one shipped mode (bilingual) or a custom preset. */
251
- function variantDescription(presetId) {
252
- const labels = MODE_DISPLAY_LABELS[presetId];
253
- return `WSL execution world for ${labels === void 0 ? presetId : `${labels.en}(${labels.zh})`}: bash and file tools run inside the WSL distribution.`;
254
- }
255
- const MAX_BODY_BYTES = 1024 * 1024;
256
- /** Valid WSL distribution names: one path-safe segment (no separators, no dot-dirs). */
257
- const DISTRO_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/;
258
- /** The loopback hostnames the data route answers to (DNS-rebinding fence). */
259
- const LOOPBACK_HOSTNAMES = new Set([
260
- "localhost",
261
- "127.0.0.1",
262
- "::1",
263
- "::ffff:127.0.0.1"
264
- ]);
265
- /** True when a socket address is loopback (any IPv4/IPv6 spelling). */
266
- function isLoopback(address) {
267
- return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
268
- }
269
- /** The hostname part of a `Host` header value (port and IPv6 brackets stripped). */
270
- function hostNameOf(host) {
271
- if (host.startsWith("[")) {
272
- const end = host.indexOf("]");
273
- return end >= 0 ? host.slice(1, end) : host;
274
- }
275
- return host.split(":")[0] ?? "";
276
- }
277
- /** True when the request's `Host` header names a loopback host. */
278
- function isLoopbackHost(host) {
279
- return host !== void 0 && LOOPBACK_HOSTNAMES.has(hostNameOf(host).toLowerCase());
280
- }
281
- /**
282
- * Validate a wire-supplied distribution name before it becomes a UNC segment:
283
- * an attacker-controlled segment containing separators or `..` would escape
284
- * the `\\wsl.localhost\` share structure into arbitrary UNC paths.
285
- * @param value - the raw wire value.
286
- * @returns the validated distro name.
287
- */
288
- function requireDistro(value) {
289
- if (typeof value !== "string" || !DISTRO_PATTERN.test(value) || value === "." || value === "..") throw new Error("distro must be a valid WSL distribution name");
290
- return value;
291
- }
292
- /** Human text for an unknown rejection. */
293
- function messageOf(value) {
294
- return value instanceof Error ? value.message : String(value);
295
- }
296
- /** Write one JSON envelope. */
297
- function json(res, status, body) {
298
- res.writeHead(status, {
299
- "content-type": "application/json; charset=utf-8",
300
- "cache-control": "no-store",
301
- "x-content-type-options": "nosniff"
302
- });
303
- res.end(JSON.stringify(body));
304
- }
305
- /** Collect and parse the request body, bounded. */
306
- async function readBody(req) {
307
- const chunks = [];
308
- let size = 0;
309
- for await (const chunk of req) {
310
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
311
- size += buffer.length;
312
- if (size > MAX_BODY_BYTES) throw new Error("request body is too large");
313
- chunks.push(buffer);
314
- }
315
- const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
316
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("request body must be a JSON object");
317
- return parsed;
318
- }
319
- /** Normalize a Linux path for the wire (rejecting non-absolute input). */
320
- function requireLinuxPath(value, label) {
321
- if (typeof value !== "string" || !isAbsoluteLinuxPath(value)) throw new Error(`${label} must be an absolute Linux path`);
322
- return normalizeLinuxPath(value);
323
- }
324
- /** Validate a wire-supplied workspace path and return its canonical UNC form. */
325
- function requireWslUnc(value) {
326
- if (typeof value !== "string") throw new Error("path must be a string");
327
- const canonical = canonicalWslUnc(value);
328
- if (canonical === null) throw new Error("path must be a WSL UNC workspace path");
329
- return canonical;
330
- }
331
- /** Resolve one directory listing over the 9P share. */
332
- function listWslDir(distro, linuxPath) {
333
- const entries = readdirSync(joinUnc(distro, linuxPath), { withFileTypes: true }).slice(0, 1e3).map((dirent) => {
334
- const kind = dirent.isDirectory() ? "directory" : dirent.isFile() ? "file" : "other";
335
- return {
336
- name: dirent.name,
337
- kind
338
- };
339
- }).sort((a, b) => {
340
- if (a.kind === "directory" && b.kind !== "directory") return -1;
341
- if (a.kind !== "directory" && b.kind === "directory") return 1;
342
- return a.name.localeCompare(b.name);
343
- });
344
- return {
345
- path: linuxPath,
346
- parent: linuxPath === "/" ? null : linuxPath.split("/").slice(0, -1).join("/") || "/",
347
- entries
348
- };
349
- }
350
- /** Route one method dispatch. */
351
- async function dispatch(method, params) {
352
- switch (method) {
353
- case "listDistros": {
354
- const distros = await listDistros();
355
- const fallback = await defaultDistro();
356
- if (fallback !== void 0 && distros.includes(fallback)) return [fallback, ...distros.filter((name) => name !== fallback)];
357
- return distros;
358
- }
359
- case "listDir": return listWslDir(requireDistro(params.distro), requireLinuxPath(params.path, "path"));
360
- case "check": {
361
- const unc = joinUnc(requireDistro(params.distro), requireLinuxPath(params.path, "path"));
362
- try {
363
- return {
364
- exists: true,
365
- isDirectory: statSync(unc).isDirectory()
366
- };
367
- } catch {
368
- return {
369
- exists: false,
370
- isDirectory: false
371
- };
372
- }
373
- }
374
- case "setUser": {
375
- const path = requireWslUnc(params.path);
376
- const username = params.username;
377
- if (username === void 0 || username === "") setWorkspaceUsername(path, void 0);
378
- else {
379
- if (typeof username !== "string" || !isValidWslUsername(username)) throw new Error("username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*");
380
- setWorkspaceUsername(path, username);
381
- }
382
- return null;
383
- }
384
- default: throw new Error(`unknown method "${method}"`);
385
- }
386
- }
387
- /**
388
- * Materialize a `wsl-<mode>` variant for every healthy source preset, and
389
- * remove this plugin's managed residue: stale variants whose source
390
- * disappeared, plus the legacy standalone `wsl` preset directory (the
391
- * execution world now composes with modes; a standalone WSL mode no longer
392
- * exists). Managed files: rewritten on every boot.
393
- * @param agentPresets - the roster service.
394
- * @param dshHome - the harness home (user preset root parent).
395
- * @param shellPath - absolute path of the plugin's built WSL shell provider.
396
- * @param fsPath - absolute path of the plugin's built WSL fs provider.
397
- */
398
- async function materializeVariants(agentPresets, dshHome, shellPath, fsPath) {
399
- const presets = await agentPresets.list();
400
- const userRoot = join(dshHome, ".agent-presets");
401
- const generated = /* @__PURE__ */ new Set();
402
- for (const preset of presets) {
403
- if (preset.broken !== void 0) continue;
404
- if (isWslVariantId(preset.id)) continue;
405
- const variantId = variantIdFor(preset.id);
406
- const transformed = transformPresetForWsl(await agentPresets.read(preset.id), shellPath, fsPath);
407
- const dir = join(userRoot, variantId);
408
- mkdirSync(dir, { recursive: true });
409
- writeFileSync(join(dir, "agent.cordis.yml"), transformed, "utf8");
410
- const labels = MODE_DISPLAY_LABELS[preset.id];
411
- let name = variantName(preset.id, preset.id);
412
- let orderLine = "";
413
- try {
414
- const meta = readFileSync(join(dirname(preset.path), "preset.yml"), "utf8");
415
- if (labels === void 0) {
416
- const match = /^name:\s*(.+)$/m.exec(meta);
417
- if (match?.[1] !== void 0 && match[1].trim() !== "") name = variantName(preset.id, match[1].trim());
418
- }
419
- const orderMatch = /^order:\s*(\d+)\s*$/m.exec(meta);
420
- if (orderMatch?.[1] !== void 0) orderLine = `order: ${orderMatch[1]}\n`;
421
- } catch {}
422
- writeFileSync(join(dir, "preset.yml"), `name: ${yamlScalar(name)}\n` + orderLine + `description: ${yamlScalar(variantDescription(preset.id))}\n`, "utf8");
423
- generated.add(variantId);
424
- }
425
- for (const entry of readdirSync(userRoot, { withFileTypes: true })) {
426
- if (!entry.isDirectory()) continue;
427
- if (entry.name === "wsl") {
428
- rmSync(join(userRoot, entry.name), {
429
- recursive: true,
430
- force: true
431
- });
432
- continue;
433
- }
434
- if (!/^wsl-[a-z0-9-]+$/.test(entry.name)) continue;
435
- if (!generated.has(entry.name)) rmSync(join(userRoot, entry.name), {
436
- recursive: true,
437
- force: true
438
- });
439
- }
440
- }
441
- /** Function-plugin plugin contract. */
442
- const name = "dsh-wsl-workspace";
443
- /** Required services. */
444
- const inject = ["webServer"];
445
- /** Validated plugin config (schemastery applied the defaults). */
446
- const Config = z.object({ route: z.string().default(DEFAULT_ROUTE) });
447
- /**
448
- * Apply the host half: materialize the `wsl` preset plus a `wsl-<mode>`
449
- * variant for every healthy roster preset, register the data route, and
450
- * contribute the per-session `DSH_WSL_DISTRO` managed-env fact so the WSL
451
- * shell executor can resolve a plain Linux `workdir` to the calling
452
- * session's distribution.
453
- * @param ctx - the host plugin context.
454
- * @param config - the validated configuration.
455
- */
456
- function apply(ctx, config) {
457
- const resolved = config;
458
- const dshHome = process.env.DSH_HOME ?? join(homedir(), ".dsh");
459
- const packageRoot = fileURLToPath(new URL("..", import.meta.url));
460
- const shellPath = join(packageRoot, "lib", "shell.js").replace(/\\/g, "/");
461
- const fsPath = join(packageRoot, "lib", "fs.js").replace(/\\/g, "/");
462
- const agentPresets = ctx.get("agentPresets");
463
- if (agentPresets !== void 0) ctx.effect(() => {
464
- materializeVariants(agentPresets, dshHome, shellPath, fsPath).catch((error) => {
465
- console.error(`dsh-wsl-workspace: WSL preset-variant generation failed: ${messageOf(error)}`);
466
- });
467
- return () => {};
468
- }, "dsh-wsl-workspace: WSL preset variants");
469
- const shellEnv = ctx.get("shellEnv");
470
- if (shellEnv !== void 0) ctx.effect(() => shellEnv.register({
471
- name: "wsl-workspace-distro",
472
- variables: {
473
- DSH_WSL_DISTRO: { description: "The WSL distribution of the calling session workspace, when the session cwd is a WSL UNC path." },
474
- DSH_WSL_USER: { description: "The Linux user of the calling session workspace, when the workspace has one configured." }
475
- },
476
- resolve(execution) {
477
- const cwd = execution.agent?.session.header.cwd;
478
- const unc = cwd === void 0 ? null : parseWslUnc(cwd);
479
- if (unc === null) return {};
480
- const username = getWorkspaceUsername(joinUnc(unc.distro, unc.linuxPath));
481
- return username === void 0 || username === "" ? { DSH_WSL_DISTRO: unc.distro } : {
482
- DSH_WSL_DISTRO: unc.distro,
483
- DSH_WSL_USER: username
484
- };
485
- }
486
- }), "dsh-wsl-workspace: per-session distro env fact");
487
- const webServer = ctx.get("webServer");
488
- ctx.effect(() => webServer.register({
489
- kind: "exact",
490
- path: resolved.route,
491
- handler: async (req, res) => {
492
- if (!isLoopback(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host)) {
493
- json(res, 403, {
494
- ok: false,
495
- error: "loopback-only"
496
- });
497
- return;
498
- }
499
- if (req.method !== "POST") {
500
- json(res, 405, {
501
- ok: false,
502
- error: "method not allowed"
503
- });
504
- return;
505
- }
506
- let body;
507
- try {
508
- body = await readBody(req);
509
- } catch (error) {
510
- json(res, 400, {
511
- ok: false,
512
- error: messageOf(error)
513
- });
514
- return;
515
- }
516
- const method = typeof body.method === "string" ? body.method : "";
517
- const params = body.params === void 0 ? {} : body.params;
518
- if (params === null || typeof params !== "object" || Array.isArray(params)) {
519
- json(res, 400, {
520
- ok: false,
521
- error: "params must be an object"
522
- });
523
- return;
524
- }
525
- try {
526
- json(res, 200, {
527
- ok: true,
528
- value: await dispatch(method, params)
529
- });
530
- } catch (error) {
531
- json(res, 200, {
532
- ok: false,
533
- error: messageOf(error)
534
- });
535
- }
536
- }
537
- }), "dsh-wsl-workspace: dialog data route");
538
- }
539
- //#endregion
540
- export { Config, DEFAULT_ROUTE, apply, inject, name };
541
-
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 } from "node:path";
7
+ import { homedir } from "node:os";
8
+ //#region src/host/variants.ts
9
+ /**
10
+ * WSL preset-variant generator. For every healthy source preset the roster
11
+ * supplies, a `wsl-<id>` variant is materialized under the roster's user
12
+ * root: the source composition with its shell/filesystem world replaced by
13
+ * the WSL providers, so any mode (standard, minimal, code, cordis, user
14
+ * presets) can run on top of a WSL execution world. The execution world is
15
+ * therefore orthogonal to the mode instead of a mode itself.
16
+ *
17
+ * The transformation is text-level on the top-level rows of the composition
18
+ * (the shape all shipped presets share), with surgical edits for the known
19
+ * special groups; unknown shapes are kept verbatim where possible.
20
+ * @module dsh-wsl-workspace/host/variants
21
+ */
22
+ /** Top-level rows that name the execution world and are replaced by the variant's own. */
23
+ const WORLD_ROWS = new Set([
24
+ "tool-bash",
25
+ "tool-pwsh",
26
+ "tool-fs",
27
+ "tool-fs-search",
28
+ "str-replace-editor",
29
+ "filesystem",
30
+ "persistent-shell",
31
+ "custom-bash",
32
+ "bootstrap-filesystem"
33
+ ]);
34
+ /** The injected WSL world group: providers + the bash/fs consumers, entry-local. */
35
+ function wslWorldGroup(shellPath, fsPath, includeEditor) {
36
+ return [
37
+ "# ── WSL execution world (dsh-wsl-workspace variant) ─────────────────────",
38
+ "# The shell and fs services are provided entry-locally (the isolate",
39
+ "# realm); host services (tools registry, shell-env, jobs) fall through.",
40
+ "# tool-fs-search is intentionally absent: the packaged ripgrep runs on",
41
+ "# the Windows host and cannot open Linux paths; WSL sessions search with",
42
+ "# shell tools instead.",
43
+ "- id: wsl-world",
44
+ " name: cordis:group",
45
+ " group: true",
46
+ " isolate:",
47
+ " shell: true",
48
+ " fs: true",
49
+ " config:",
50
+ ` - id: shell-wsl`,
51
+ ` name: '${shellPath.replace(/'/g, "''")}'`,
52
+ " - id: fs-wsl",
53
+ ` name: '${fsPath.replace(/'/g, "''")}'`,
54
+ " - id: tool-bash",
55
+ " name: '@deepseek-ai/dsh-tool-bash'",
56
+ " - id: tool-fs",
57
+ " name: '@deepseek-ai/dsh-tool-fs'",
58
+ ...includeEditor ? [
59
+ " - id: str-replace-editor",
60
+ " name: '@deepseek-ai/dsh-tool-str-replace-editor'",
61
+ " config:",
62
+ " maxOutputChars: 16000"
63
+ ] : [],
64
+ ""
65
+ ].join("\n");
66
+ }
67
+ /** The sentence appended to a standard-like persona when the variant runs in WSL. */
68
+ 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.";
69
+ /** The top-level rows of one composition, as (startLine, endLineExclusive) spans. */
70
+ function topLevelSpans(lines) {
71
+ const spans = [];
72
+ let start = -1;
73
+ for (let index = 0; index < lines.length; index++) if (lines[index]?.startsWith("- id: ") === true) {
74
+ if (start >= 0) spans.push({
75
+ start,
76
+ end: index
77
+ });
78
+ start = index;
79
+ }
80
+ if (start >= 0) spans.push({
81
+ start,
82
+ end: lines.length
83
+ });
84
+ return spans;
85
+ }
86
+ /** The row id of a top-level span, or undefined when the first line is malformed. */
87
+ function spanId(lines, span) {
88
+ return /^- id: ([A-Za-z0-9_.-]+)/.exec(lines[span.start] ?? "")?.[1];
89
+ }
90
+ /** Whether a top-level span is a `persona` row with an appendable folded text. */
91
+ function appendablePersona(lines, span) {
92
+ const block = lines.slice(span.start, span.end).join("\n");
93
+ if (!block.includes("complete: true") && /text: [>|-]/.test(block)) {
94
+ const textLine = block.split("\n").find((line) => /^(\s*)text: [>|-]/.test(line));
95
+ if (textLine !== void 0) {
96
+ const indent = /^(\s*)/.exec(textLine)?.[1]?.length ?? 0;
97
+ return block.split("\n").some((line) => line.length > indent && /^\s+/.test(line) && !line.includes(":"));
98
+ }
99
+ }
100
+ return false;
101
+ }
102
+ /** Append the WSL sentence to a persona row's folded text (in place of its last text line). */
103
+ function appendPersona(lines, span) {
104
+ const block = lines.slice(span.start, span.end);
105
+ const textIndex = block.findIndex((line) => /^(\s*)text: [>|-]/.test(line));
106
+ if (textIndex < 0) return [...block];
107
+ const indent = /^(\s*)/.exec(block[textIndex] ?? "")?.[1]?.length ?? 0;
108
+ let lastText = -1;
109
+ for (let index = textIndex + 1; index < block.length; index++) {
110
+ const line = block[index] ?? "";
111
+ if (line.trim() === "") continue;
112
+ if (line.length > indent && /^\s+/.test(line)) lastText = index;
113
+ }
114
+ if (lastText < 0) return [...block];
115
+ const updated = [...block];
116
+ const textIndent = /^(\s*)/.exec(block[lastText] ?? "")?.[1] ?? " ";
117
+ updated.splice(lastText + 1, 0, `${textIndent}${PERSONA_APPEND}`);
118
+ return updated;
119
+ }
120
+ /**
121
+ * Transform one source preset composition into its WSL variant: drop the
122
+ * execution-world rows, keep everything else verbatim, and append the WSL
123
+ * world group. The persistent-shell group is NOT re-added: it registers the
124
+ * same `bash` tool name as the WSL world's `dsh-tool-bash`, and the tools
125
+ * registry rejects duplicates within one preset layer — the whole variant
126
+ * fails to mount and the session falls back to another preset. Its PTY
127
+ * backend additionally cannot run on this plugin's Windows host
128
+ * (`dsh-subprocess-local`: "terminal inspection is unsupported on platform
129
+ * win32"), so the group could never spawn a shell here anyway. The WSL
130
+ * world's ordinary `bash` tool covers command execution for every variant.
131
+ * @param source - the source composition text.
132
+ * @param shellPath - absolute path of the plugin's built WSL shell provider.
133
+ * @param fsPath - absolute path of the plugin's built WSL fs provider.
134
+ * @returns the variant composition text.
135
+ */
136
+ function transformPresetForWsl(source, shellPath, fsPath) {
137
+ const lines = source.split("\n");
138
+ const spans = topLevelSpans(lines);
139
+ const kept = [];
140
+ let sawEditor = false;
141
+ let personaAppended = false;
142
+ for (const span of spans) {
143
+ const id = spanId(lines, span);
144
+ if (id === void 0) {
145
+ kept.push(...lines.slice(span.start, span.end));
146
+ continue;
147
+ }
148
+ if (WORLD_ROWS.has(id)) continue;
149
+ if (id === "persona" && !personaAppended && appendablePersona(lines, span)) {
150
+ kept.push(...appendPersona(lines, span));
151
+ personaAppended = true;
152
+ continue;
153
+ }
154
+ kept.push(...lines.slice(span.start, span.end));
155
+ if (id === "str-replace-editor") sawEditor = true;
156
+ }
157
+ if (source.includes("str-replace-editor")) sawEditor = true;
158
+ const result = [...kept];
159
+ if (result.length > 0 && result[result.length - 1] !== "") result.push("");
160
+ result.push(wslWorldGroup(shellPath, fsPath, sawEditor));
161
+ return result.join("\n").replace(/\n{3,}/g, "\n\n").replace(/\n+$/, "\n");
162
+ }
163
+ /** Whether an id is one of this plugin's own preset directories. */
164
+ function isWslVariantId(id) {
165
+ return id === "wsl" || /^wsl-[a-z0-9-]+$/.test(id);
166
+ }
167
+ /** The variant id for one source preset id. */
168
+ function variantIdFor(sourceId) {
169
+ return `wsl-${sourceId.toLowerCase()}`;
170
+ }
171
+ //#endregion
172
+ //#region src/index.ts
173
+ /** The HTTP route this plugin serves (a relative, same-origin path). */
174
+ const DEFAULT_ROUTE = "/wsl-workspace/api";
175
+ /**
176
+ * Bilingual display labels for the shipped source modes, matching the app's
177
+ * own built-in copy in each language — note the `code` preset is "PTC 模式"
178
+ * in the Chinese copy but "Code mode" in English. The DSH picker localizes
179
+ * only the four built-in ids itself; `wsl-*` variant ids render the
180
+ * preset.yml text verbatim, so the plugin writes one bilingual string so
181
+ * both locales can identify each variant. Custom presets keep their own
182
+ * name.
183
+ */
184
+ const MODE_DISPLAY_LABELS = {
185
+ standard: {
186
+ en: "Standard mode",
187
+ zh: "标准模式"
188
+ },
189
+ code: {
190
+ en: "Code mode",
191
+ zh: "PTC 模式"
192
+ },
193
+ minimal: {
194
+ en: "Minimal mode",
195
+ zh: "极简模式"
196
+ },
197
+ cordis: {
198
+ en: "Creator mode",
199
+ zh: "创造模式"
200
+ }
201
+ };
202
+ /**
203
+ * Quote a value as a single-line YAML single-quoted scalar. Plain scalars
204
+ * cannot contain `: ` (colon + space), which plain English sentences do —
205
+ * written unquoted they make the whole preset.yml unparsable, dropping the
206
+ * name, description and order together.
207
+ */
208
+ function yamlScalar(value) {
209
+ return `'${value.replace(/'/g, "''")}'`;
210
+ }
211
+ /** The variant name for one shipped mode (bilingual) or a custom preset. */
212
+ function variantName(presetId, sourceName) {
213
+ const labels = MODE_DISPLAY_LABELS[presetId];
214
+ return labels === void 0 ? `WSL · ${sourceName}` : `WSL · ${labels.en}(${labels.zh})`;
215
+ }
216
+ /** The variant description for one shipped mode (bilingual) or a custom preset. */
217
+ function variantDescription(presetId) {
218
+ const labels = MODE_DISPLAY_LABELS[presetId];
219
+ return `WSL execution world for ${labels === void 0 ? presetId : `${labels.en}(${labels.zh})`}: bash and file tools run inside the WSL distribution.`;
220
+ }
221
+ const MAX_BODY_BYTES = 1024 * 1024;
222
+ /** Valid WSL distribution names: one path-safe segment (no separators, no dot-dirs). */
223
+ const DISTRO_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/;
224
+ /** The loopback hostnames the data route answers to (DNS-rebinding fence). */
225
+ const LOOPBACK_HOSTNAMES = new Set([
226
+ "localhost",
227
+ "127.0.0.1",
228
+ "::1",
229
+ "::ffff:127.0.0.1"
230
+ ]);
231
+ /** True when a socket address is loopback (any IPv4/IPv6 spelling). */
232
+ function isLoopback(address) {
233
+ return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
234
+ }
235
+ /** The hostname part of a `Host` header value (port and IPv6 brackets stripped). */
236
+ function hostNameOf(host) {
237
+ if (host.startsWith("[")) {
238
+ const end = host.indexOf("]");
239
+ return end >= 0 ? host.slice(1, end) : host;
240
+ }
241
+ return host.split(":")[0] ?? "";
242
+ }
243
+ /** True when the request's `Host` header names a loopback host. */
244
+ function isLoopbackHost(host) {
245
+ return host !== void 0 && LOOPBACK_HOSTNAMES.has(hostNameOf(host).toLowerCase());
246
+ }
247
+ /**
248
+ * Validate a wire-supplied distribution name before it becomes a UNC segment:
249
+ * an attacker-controlled segment containing separators or `..` would escape
250
+ * the `\\wsl.localhost\` share structure into arbitrary UNC paths.
251
+ * @param value - the raw wire value.
252
+ * @returns the validated distro name.
253
+ */
254
+ function requireDistro(value) {
255
+ if (typeof value !== "string" || !DISTRO_PATTERN.test(value) || value === "." || value === "..") throw new Error("distro must be a valid WSL distribution name");
256
+ return value;
257
+ }
258
+ /** Human text for an unknown rejection. */
259
+ function messageOf(value) {
260
+ return value instanceof Error ? value.message : String(value);
261
+ }
262
+ /** Write one JSON envelope. */
263
+ function json(res, status, body) {
264
+ res.writeHead(status, {
265
+ "content-type": "application/json; charset=utf-8",
266
+ "cache-control": "no-store",
267
+ "x-content-type-options": "nosniff"
268
+ });
269
+ res.end(JSON.stringify(body));
270
+ }
271
+ /** Collect and parse the request body, bounded. */
272
+ async function readBody(req) {
273
+ const chunks = [];
274
+ let size = 0;
275
+ for await (const chunk of req) {
276
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
277
+ size += buffer.length;
278
+ if (size > MAX_BODY_BYTES) throw new Error("request body is too large");
279
+ chunks.push(buffer);
280
+ }
281
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
282
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("request body must be a JSON object");
283
+ return parsed;
284
+ }
285
+ /** Normalize a Linux path for the wire (rejecting non-absolute input). */
286
+ function requireLinuxPath(value, label) {
287
+ if (typeof value !== "string" || !isAbsoluteLinuxPath(value)) throw new Error(`${label} must be an absolute Linux path`);
288
+ return normalizeLinuxPath(value);
289
+ }
290
+ /** Validate a wire-supplied workspace path and return its canonical UNC form. */
291
+ function requireWslUnc(value) {
292
+ if (typeof value !== "string") throw new Error("path must be a string");
293
+ const canonical = canonicalWslUnc(value);
294
+ if (canonical === null) throw new Error("path must be a WSL UNC workspace path");
295
+ return canonical;
296
+ }
297
+ /**
298
+ * Resolve one directory listing for the dialog. The 9P share (`\\wsl.localhost\…`)
299
+ * serves only the ext4 volume: `/mnt/<drive>` (drvfs) reads return Access
300
+ * denied, so drvfs paths are read through their Windows drive spelling and
301
+ * `/mnt` itself is synthesized from the drives present on the host.
302
+ */
303
+ function listWslDir(distro, linuxPath) {
304
+ if (linuxPath === "/mnt") {
305
+ const entries = [];
306
+ for (let i = 0; i < 26; i++) {
307
+ const letter = String.fromCharCode(65 + i);
308
+ try {
309
+ if (statSync(`${letter}:\\`).isDirectory()) entries.push({
310
+ name: letter.toLowerCase(),
311
+ kind: "directory"
312
+ });
313
+ } catch {}
314
+ }
315
+ return {
316
+ path: "/mnt",
317
+ parent: "/",
318
+ entries
319
+ };
320
+ }
321
+ const winPath = mntToWindowsPath(linuxPath);
322
+ const entries = readdirSync(winPath !== null ? winPath : joinUnc(distro, linuxPath), { withFileTypes: true }).slice(0, 1e3).map((dirent) => {
323
+ const kind = dirent.isDirectory() ? "directory" : dirent.isFile() ? "file" : "other";
324
+ return {
325
+ name: dirent.name,
326
+ kind
327
+ };
328
+ }).sort((a, b) => {
329
+ if (a.kind === "directory" && b.kind !== "directory") return -1;
330
+ if (a.kind !== "directory" && b.kind === "directory") return 1;
331
+ return a.name.localeCompare(b.name);
332
+ });
333
+ return {
334
+ path: linuxPath,
335
+ parent: linuxPath === "/" ? null : linuxPath.split("/").slice(0, -1).join("/") || "/",
336
+ entries
337
+ };
338
+ }
339
+ /** Route one method dispatch. */
340
+ async function dispatch(method, params) {
341
+ switch (method) {
342
+ case "listDistros": {
343
+ const distros = await listDistros();
344
+ const fallback = await defaultDistro();
345
+ if (fallback !== void 0 && distros.includes(fallback)) return [fallback, ...distros.filter((name) => name !== fallback)];
346
+ return distros;
347
+ }
348
+ case "listDir": return listWslDir(requireDistro(params.distro), requireLinuxPath(params.path, "path"));
349
+ case "check": {
350
+ const distro = requireDistro(params.distro);
351
+ const path = requireLinuxPath(params.path, "path");
352
+ const winPath = mntToWindowsPath(path);
353
+ const readPath = winPath !== null ? winPath : joinUnc(distro, path);
354
+ try {
355
+ return {
356
+ exists: true,
357
+ isDirectory: statSync(readPath).isDirectory()
358
+ };
359
+ } catch {
360
+ return {
361
+ exists: false,
362
+ isDirectory: false
363
+ };
364
+ }
365
+ }
366
+ case "registerWindows": {
367
+ const distro = requireDistro(params.distro);
368
+ const winPath = mntToWindowsPath(requireLinuxPath(params.linuxPath, "path"));
369
+ if (winPath === null) throw new Error("registerWindows requires a /mnt/<drive> Linux path");
370
+ registerWindowsWorkspace(winPath, distro, typeof params.username === "string" ? params.username : void 0);
371
+ return null;
372
+ }
373
+ case "listWorkspaces": return listWorkspaceKeys();
374
+ case "setUser": {
375
+ const path = requireWslUnc(params.path);
376
+ const username = params.username;
377
+ if (username === void 0 || username === "") setWorkspaceUsername(path, void 0);
378
+ else {
379
+ if (typeof username !== "string" || !isValidWslUsername(username)) throw new Error("username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*");
380
+ setWorkspaceUsername(path, username);
381
+ }
382
+ return null;
383
+ }
384
+ default: throw new Error(`unknown method "${method}"`);
385
+ }
386
+ }
387
+ /**
388
+ * Publish a fully staged preset directory while preserving the last complete
389
+ * variant if publication fails. Stable sibling names also let the next boot
390
+ * recover an interrupted old-to-backup rename before doing new work.
391
+ */
392
+ function publishVariant(staging, dest) {
393
+ const previous = `${dest}.previous`;
394
+ if (!existsSync(dest) && existsSync(previous)) renameSync(previous, dest);
395
+ if (existsSync(previous)) rmSync(previous, {
396
+ recursive: true,
397
+ force: true
398
+ });
399
+ if (existsSync(dest)) renameSync(dest, previous);
400
+ try {
401
+ renameSync(staging, dest);
402
+ } catch (error) {
403
+ if (!existsSync(dest) && existsSync(previous)) renameSync(previous, dest);
404
+ throw error;
405
+ }
406
+ rmSync(previous, {
407
+ recursive: true,
408
+ force: true
409
+ });
410
+ }
411
+ /** Materialize one WSL variant per healthy source preset. */
412
+ async function materializeVariants(agentPresets, dshHome, shellPath, fsPath) {
413
+ const presets = await agentPresets.list();
414
+ const userRoot = join(dshHome, ".agent-presets");
415
+ const generated = /* @__PURE__ */ new Set();
416
+ for (const preset of presets) {
417
+ if (preset.broken !== void 0) continue;
418
+ if (isWslVariantId(preset.id)) continue;
419
+ const variantId = variantIdFor(preset.id);
420
+ const transformed = transformPresetForWsl(await agentPresets.read(preset.id), shellPath, fsPath);
421
+ const dir = join(userRoot, variantId);
422
+ const staging = `${dir}.staging`;
423
+ rmSync(staging, {
424
+ recursive: true,
425
+ force: true
426
+ });
427
+ cpSync(dirname(preset.path), staging, {
428
+ recursive: true,
429
+ force: true
430
+ });
431
+ writeFileSync(join(staging, "agent.cordis.yml"), transformed, "utf8");
432
+ const labels = MODE_DISPLAY_LABELS[preset.id];
433
+ let name = variantName(preset.id, preset.id);
434
+ let orderLine = "";
435
+ try {
436
+ const meta = readFileSync(join(dirname(preset.path), "preset.yml"), "utf8");
437
+ if (labels === void 0) {
438
+ const match = /^name:\s*(.+)$/m.exec(meta);
439
+ if (match?.[1] !== void 0 && match[1].trim() !== "") name = variantName(preset.id, match[1].trim());
440
+ }
441
+ const orderMatch = /^order:\s*(\d+)\s*$/m.exec(meta);
442
+ if (orderMatch?.[1] !== void 0) orderLine = `order: ${orderMatch[1]}\n`;
443
+ } catch {}
444
+ writeFileSync(join(staging, "preset.yml"), `name: ${yamlScalar(name)}\n` + orderLine + `description: ${yamlScalar(variantDescription(preset.id))}\n`, "utf8");
445
+ publishVariant(staging, dir);
446
+ generated.add(variantId);
447
+ }
448
+ for (const entry of readdirSync(userRoot, { withFileTypes: true })) {
449
+ if (!entry.isDirectory()) continue;
450
+ if (entry.name === "wsl") {
451
+ rmSync(join(userRoot, entry.name), {
452
+ recursive: true,
453
+ force: true
454
+ });
455
+ continue;
456
+ }
457
+ if (!/^wsl-[a-z0-9-]+$/.test(entry.name)) continue;
458
+ if (!generated.has(entry.name)) rmSync(join(userRoot, entry.name), {
459
+ recursive: true,
460
+ force: true
461
+ });
462
+ }
463
+ }
464
+ /** Function-plugin plugin contract. */
465
+ const name = "dsh-wsl-workspace";
466
+ /** Required services. */
467
+ const inject = ["webServer"];
468
+ /** Validated plugin config (schemastery applied the defaults). */
469
+ const Config = z.object({ route: z.string().default(DEFAULT_ROUTE) });
470
+ /**
471
+ * Apply the host half: materialize a `wsl-<mode>` variant for every healthy
472
+ * roster preset, register the data route, and
473
+ * contribute the per-session `DSH_WSL_DISTRO` managed-env fact so the WSL
474
+ * shell executor can resolve a plain Linux `workdir` to the calling
475
+ * session's distribution.
476
+ * @param ctx - the host plugin context.
477
+ * @param config - the validated configuration.
478
+ */
479
+ function apply(ctx, config) {
480
+ const resolved = config;
481
+ const dshHome = process.env.DSH_HOME ?? join(homedir(), ".dsh");
482
+ const packageRoot = fileURLToPath(new URL("..", import.meta.url));
483
+ const shellPath = join(packageRoot, "lib", "shell.js").replace(/\\/g, "/");
484
+ const fsPath = join(packageRoot, "lib", "fs.js").replace(/\\/g, "/");
485
+ const agentPresets = ctx.get("agentPresets");
486
+ if (agentPresets !== void 0) ctx.effect(() => {
487
+ materializeVariants(agentPresets, dshHome, shellPath, fsPath).catch((error) => {
488
+ console.error(`dsh-wsl-workspace: WSL preset-variant generation failed: ${messageOf(error)}`);
489
+ });
490
+ return () => {};
491
+ }, "dsh-wsl-workspace: WSL preset variants");
492
+ const shellEnv = ctx.get("shellEnv");
493
+ if (shellEnv !== void 0) ctx.effect(() => shellEnv.register({
494
+ name: "wsl-workspace-distro",
495
+ variables: {
496
+ DSH_WSL_DISTRO: { description: "The WSL distribution of the calling session workspace, when the session cwd is a WSL UNC path." },
497
+ DSH_WSL_USER: { description: "The Linux user of the calling session workspace, when the workspace has one configured." }
498
+ },
499
+ resolve(execution) {
500
+ const cwd = execution.agent?.session.header.cwd;
501
+ const unc = cwd === void 0 ? null : parseWslUnc(cwd);
502
+ if (unc !== null) {
503
+ const username = getWorkspaceUsername(joinUnc(unc.distro, unc.linuxPath));
504
+ return username === void 0 || username === "" ? { DSH_WSL_DISTRO: unc.distro } : {
505
+ DSH_WSL_DISTRO: unc.distro,
506
+ DSH_WSL_USER: username
507
+ };
508
+ }
509
+ if (cwd !== void 0 && /^[A-Za-z]:[\\/]/.test(cwd)) {
510
+ const entry = getWindowsWorkspace(cwd);
511
+ if (entry !== void 0 && entry.distro !== void 0 && entry.distro !== "") return entry.username === void 0 || entry.username === "" ? { DSH_WSL_DISTRO: entry.distro } : {
512
+ DSH_WSL_DISTRO: entry.distro,
513
+ DSH_WSL_USER: entry.username
514
+ };
515
+ }
516
+ return {};
517
+ }
518
+ }), "dsh-wsl-workspace: per-session distro env fact");
519
+ const webServer = ctx.get("webServer");
520
+ ctx.effect(() => webServer.register({
521
+ kind: "exact",
522
+ path: resolved.route,
523
+ handler: async (req, res) => {
524
+ if (!isLoopback(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host)) {
525
+ json(res, 403, {
526
+ ok: false,
527
+ error: "loopback-only"
528
+ });
529
+ return;
530
+ }
531
+ if (req.method !== "POST") {
532
+ json(res, 405, {
533
+ ok: false,
534
+ error: "method not allowed"
535
+ });
536
+ return;
537
+ }
538
+ let body;
539
+ try {
540
+ body = await readBody(req);
541
+ } catch (error) {
542
+ json(res, 400, {
543
+ ok: false,
544
+ error: messageOf(error)
545
+ });
546
+ return;
547
+ }
548
+ const method = typeof body.method === "string" ? body.method : "";
549
+ const params = body.params === void 0 ? {} : body.params;
550
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
551
+ json(res, 400, {
552
+ ok: false,
553
+ error: "params must be an object"
554
+ });
555
+ return;
556
+ }
557
+ try {
558
+ json(res, 200, {
559
+ ok: true,
560
+ value: await dispatch(method, params)
561
+ });
562
+ } catch (error) {
563
+ json(res, 200, {
564
+ ok: false,
565
+ error: messageOf(error)
566
+ });
567
+ }
568
+ }
569
+ }), "dsh-wsl-workspace: dialog data route");
570
+ }
571
+ //#endregion
572
+ export { Config, DEFAULT_ROUTE, apply, inject, name };
573
+
542
574
  //# sourceMappingURL=index.js.map