dsh-plugin-wsl-env 0.17.1 → 0.19.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.
Files changed (110) hide show
  1. package/CHANGELOG.md +225 -0
  2. package/CONTRIBUTING.md +37 -5
  3. package/README.md +61 -6
  4. package/SUPPORT.md +3 -3
  5. package/agent/native/linux-aarch64/dsh-wsl-agent +0 -0
  6. package/agent/native/linux-x86_64/dsh-wsl-agent +0 -0
  7. package/agent/wsl-agent.sh +331 -11
  8. package/cordis.patch.yml +10 -5
  9. package/docs/AGENT-PROTOCOL-V7.md +175 -0
  10. package/docs/API.md +24 -0
  11. package/docs/ARCHITECTURE.md +20 -6
  12. package/docs/COMPATIBILITY.md +1 -1
  13. package/docs/CONFIGURATION.md +33 -5
  14. package/docs/CONFIGURATION.zh.md +25 -4
  15. package/docs/LIMITATIONS.md +39 -7
  16. package/docs/LIMITATIONS.zh.md +31 -6
  17. package/docs/MIGRATION.md +4 -4
  18. package/docs/PEER-PARITY.md +94 -35
  19. package/docs/QUICKSTART.md +19 -2
  20. package/docs/QUICKSTART.zh.md +16 -1
  21. package/docs/README.zh.md +47 -7
  22. package/docs/RELEASING.md +3 -2
  23. package/docs/REQUIREMENTS.zh.md +11 -6
  24. package/docs/ROADMAP-1.0.md +40 -29
  25. package/docs/ROADMAP.md +10 -6
  26. package/docs/UPSTREAM-FILE-REFERENCE-SEAM.md +6 -1
  27. package/docs/UPSTREAM-FSIO-EXPORT.md +2 -2
  28. package/docs/UPSTREAM-SERVICE-SWAP.md +124 -0
  29. package/docs/UPSTREAM-SESSION-NOTICE.md +3 -1
  30. package/docs/UPSTREAM-TERMINAL-TITLE.md +3 -0
  31. package/docs/root-fs-routing.md +3 -3
  32. package/lib/agent-confined.js +4 -4
  33. package/lib/agent-errors.d.ts +1 -1
  34. package/lib/agent-errors.js +1 -1
  35. package/lib/agent-exec.d.ts +1 -1
  36. package/lib/agent-exec.js +1 -1
  37. package/lib/agent-protocol.d.ts +58 -8
  38. package/lib/agent-protocol.js +40 -7
  39. package/lib/agent-shared.d.ts +1 -1
  40. package/lib/agent-shared.js +1 -1
  41. package/lib/agent.d.ts +171 -1
  42. package/lib/agent.js +448 -288
  43. package/lib/auto-preset.d.ts +1 -1
  44. package/lib/auto-preset.js +1 -1
  45. package/lib/bwrap.d.ts +1 -1
  46. package/lib/bwrap.js +1 -1
  47. package/lib/distro-route.d.ts +1 -1
  48. package/lib/distro-route.js +1 -1
  49. package/lib/doctor-live.d.ts +53 -0
  50. package/lib/doctor-live.js +37 -0
  51. package/lib/file-reference-wsl.d.ts +1 -1
  52. package/lib/file-reference-wsl.js +1 -1
  53. package/lib/fs-decisions.d.ts +1 -1
  54. package/lib/fs-decisions.js +1 -1
  55. package/lib/fs-routing.d.ts +52 -2
  56. package/lib/fs-routing.js +56 -1
  57. package/lib/fs-substrate.d.ts +90 -11
  58. package/lib/fs-substrate.js +202 -1
  59. package/lib/fs.d.ts +1 -1
  60. package/lib/fs.js +1 -1
  61. package/lib/fsio-agent.d.ts +128 -4
  62. package/lib/fsio-agent.js +224 -15
  63. package/lib/fsio-text.d.ts +1 -1
  64. package/lib/fsio-text.js +1 -1
  65. package/lib/git-exec.d.ts +1 -1
  66. package/lib/git-exec.js +1 -1
  67. package/lib/git-route.d.ts +1 -1
  68. package/lib/git-route.js +1 -1
  69. package/lib/index.d.ts +127 -3
  70. package/lib/index.js +301 -99
  71. package/lib/listing.d.ts +1 -1
  72. package/lib/listing.js +1 -1
  73. package/lib/native-agent.d.ts +1 -1
  74. package/lib/native-agent.js +2 -2
  75. package/lib/paths.d.ts +6 -3
  76. package/lib/paths.js +4 -4
  77. package/lib/picker.d.ts +1 -1
  78. package/lib/picker.js +7 -7
  79. package/lib/ports.d.ts +1 -1
  80. package/lib/ports.js +1 -1
  81. package/lib/preflight.d.ts +1 -1
  82. package/lib/preflight.js +1 -1
  83. package/lib/sandbox-core.d.ts +1 -1
  84. package/lib/sandbox-core.js +2 -2
  85. package/lib/sandbox.d.ts +1 -1
  86. package/lib/sandbox.js +1 -1
  87. package/lib/search-exec.d.ts +1 -1
  88. package/lib/search-exec.js +1 -1
  89. package/lib/search-route.d.ts +1 -1
  90. package/lib/search-route.js +1 -1
  91. package/lib/session-runtime.d.ts +1 -1
  92. package/lib/session-runtime.js +2 -2
  93. package/lib/session-scope.d.ts +1 -1
  94. package/lib/session-scope.js +1 -1
  95. package/lib/shell-env.d.ts +1 -1
  96. package/lib/shell-env.js +1 -1
  97. package/lib/shell.d.ts +1 -1
  98. package/lib/shell.js +1 -1
  99. package/lib/subprocess.d.ts +1 -1
  100. package/lib/subprocess.js +2 -2
  101. package/lib/terminal-activity.d.ts +1 -1
  102. package/lib/terminal-activity.js +1 -1
  103. package/lib/terminal-route.d.ts +1 -1
  104. package/lib/terminal-route.js +1 -1
  105. package/lib/watcher.d.ts +1 -1
  106. package/lib/watcher.js +1 -1
  107. package/lib/wsl.d.ts +1 -31
  108. package/lib/wsl.js +1 -21
  109. package/package.json +41 -28
  110. package/scripts/doctor.mjs +34 -11
package/lib/index.js CHANGED
@@ -44,7 +44,7 @@ import { randomUUID } from "node:crypto";
44
44
  import { LocalBashExecutor } from "@deepseek-ai/dsh-bash-local";
45
45
  import { LocalFileSystem } from "@deepseek-ai/dsh-fs-local";
46
46
  import { FsError } from "@deepseek-ai/dsh-fs";
47
- import { canonicalPath, classifyRunnerFailure, isRunnerSpawnFailure, matchesSignature, SandboxUnavailableError, writableRoots } from "@deepseek-ai/dsh-sandbox";
47
+ import { canonicalPath, classifyRunnerFailure, isRunnerSpawnFailure, matchesSignature, SandboxInvalidRootError, SandboxUnavailableError, writableRoots } from "@deepseek-ai/dsh-sandbox";
48
48
  import { isAnotherDistrosUnc, isRelativeWorldPath, isWorldPathUnder, isWslUnc, posixToUnc, toLinuxPath, toWorldPath, uncToPosix, windowsToLinuxMount } from "./paths.js";
49
49
  import { isConfinedMutation, mutationModeRefusal, outsideDistroRefusal, shareSubstrateRefusal, substrateFailure, workspaceWriteDenial } from "./fs-decisions.js";
50
50
  import { distroOfUnc, isDefaultDistro, pinnedDistro, selectDistro } from "./distro-route.js";
@@ -59,6 +59,10 @@ import { FsCodedError } from "./fsio-text.js";
59
59
  import { confinedAgent } from "./agent-confined.js";
60
60
  import { SessionRuntimes, probeSessionRuntime, sessionRuntimes, setSessionNativeAgent } from "./session-runtime.js";
61
61
  import { configureAgentBackend, ensureNativeSessionAgent } from "./native-agent.js";
62
+ import { mergeLiveResidentStatus } from "./doctor-live.js";
63
+ import { spawnSync } from "node:child_process";
64
+ import { fileURLToPath } from "node:url";
65
+ import { dirname, join } from "node:path";
62
66
  // `runCapture` and distro discovery live in ./wsl.js so the directory picker
63
67
  // can use them without pulling this file's executor and filesystem peers in.
64
68
  import { defaultDistro, defaultShell, linuxHomePath, runCapture, shellArgs, workdirFailure, wslErrorCode } from "./wsl.js";
@@ -135,13 +139,21 @@ async function distroHome(owner, distro) {
135
139
  * The roots a `workspace-write` policy may write under, in the vocabulary this
136
140
  * backend's targets are spelled in.
137
141
  *
138
- * Upstream's {@link writableRoots} grants the workspace plus the platform temp
139
- * areas (`/tmp`, `os.tmpdir()`). A session whose workspace lives inside a
140
- * distro speaks UNC, where neither host spelling matches anything, and the temp
141
- * area that world actually exposes is the distro's own `/tmp` — so that is what
142
- * is granted instead, and the Windows temp dir deliberately is NOT: it lies
143
- * outside the execution world the policy describes. A session whose workspace
144
- * is a Windows folder keeps upstream's grant verbatim.
142
+ * Upstream's {@link writableRoots} grants the workspace, its explicit extra
143
+ * directories (`additionalWritableRoots`), and the platform temp areas (`/tmp`,
144
+ * `os.tmpdir()`). A session whose workspace lives inside a distro speaks UNC,
145
+ * where neither host spelling matches anything, and the temp area that world
146
+ * actually exposes is the distro's own `/tmp` — so that is what is granted
147
+ * instead, and the Windows temp dir deliberately is NOT: it lies outside the
148
+ * execution world the policy describes. A session whose workspace is a Windows
149
+ * folder keeps upstream's grant verbatim.
150
+ *
151
+ * Extra directories follow the same world rule as the temp areas, and the same
152
+ * together-grant contract: an extra root that is a UNC path of the same distro
153
+ * is granted as-is; a Windows-path extra root cannot be granted inside the
154
+ * distro, and upstream's contract is that every backend grants every extra
155
+ * root together — so it fails closed with {@link SandboxInvalidRootError}
156
+ * rather than silently narrowing what `workspace-write` promised.
145
157
  *
146
158
  * @param policy - the per-call file-effect policy.
147
159
  * @param distro - the distro a UNC workspace belongs to.
@@ -153,6 +165,13 @@ function wslWritableRoots(policy, distro) {
153
165
  const roots = new Set([canonicalPath(policy.workspaceRoot)]);
154
166
  if (isWslUnc(policy.workspaceRoot)) {
155
167
  roots.add(canonicalPath(posixToUnc(distro, "/tmp")));
168
+ for (const root of policy.additionalWritableRoots ?? []) {
169
+ const parsed = uncToPosix(root);
170
+ if (parsed === undefined || parsed.distro !== distro) {
171
+ throw new SandboxInvalidRootError(root, `the workspace is inside distro ${JSON.stringify(distro)}; a Windows-path extra directory cannot be granted there`);
172
+ }
173
+ roots.add(canonicalPath(root));
174
+ }
156
175
  }
157
176
  else {
158
177
  for (const root of writableRoots(policy))
@@ -160,6 +179,57 @@ function wslWritableRoots(policy, distro) {
160
179
  }
161
180
  return [...roots];
162
181
  }
182
+ /** The doctor script this package ships, resolved from the compiled module. */
183
+ const DOCTOR_SCRIPT = join(dirname(fileURLToPath(import.meta.url)), "..", "scripts", "doctor.mjs");
184
+ /**
185
+ * Collect the doctor's versioned JSON report and merge the live resident's
186
+ * own lifecycle facts when this process holds one (WSL-313).
187
+ *
188
+ * The doctor CLI is a separate process, so its handshake check can only probe
189
+ * a fresh resident; a live resident's `deaths` and `lastError` are
190
+ * host-process state with no IPC to reach them. This entry point runs from
191
+ * the plugin's own context instead: it collects the report as a subprocess
192
+ * (no plugin code is re-entered) and folds `sharedAgent(distro).status()` in
193
+ * — the sanctioned merge, since a snapshot that answers for no resident
194
+ * changes nothing. Outside the app the singleton was never started, so the
195
+ * returned report is the fresh probe verbatim; inside it, a wedged live
196
+ * resident's failures finally reach the report.
197
+ *
198
+ * @param distro - the distro the doctor examines.
199
+ * @param options - `doctorPath` overrides the shipped script (tests);
200
+ * `liveStatus` overrides the in-process status snapshot (tests).
201
+ * @returns the merged report.
202
+ */
203
+ export async function doctorReport(distro, options) {
204
+ const script = options?.doctorPath ?? DOCTOR_SCRIPT;
205
+ const argv = [script, distro, "--json"];
206
+ if (options?.wslPath !== undefined)
207
+ argv.push("--wsl", options.wslPath);
208
+ // A nonzero doctor exit usually means an environment check FAILED on the
209
+ // machine being examined — that is a valid report, not a broken collection.
210
+ // The stdout is parsed regardless; only a run that produced no versioned
211
+ // report rejects.
212
+ const spawned = spawnSync(process.execPath, argv, {
213
+ timeout: 120_000,
214
+ maxBuffer: 4 * 1024 * 1024,
215
+ windowsHide: true,
216
+ encoding: "utf8",
217
+ ...(options?.envPath !== undefined ? { env: { ...process.env, PATH: `${options.envPath}:${process.env.PATH ?? ""}` } } : {}),
218
+ });
219
+ // A nonzero doctor exit usually means an environment check FAILED on the
220
+ // machine being examined — the versioned report on stdout is still the
221
+ // deliverable, so it parses whenever present. Only a run that produced no
222
+ // report rejects, naming the spawn failure and any stderr tail.
223
+ let report;
224
+ try {
225
+ report = JSON.parse(spawned.stdout);
226
+ }
227
+ catch {
228
+ throw new Error(`doctor run failed: ${spawned.error?.message ?? `exited with code ${spawned.status}`}${spawned.stderr.length > 0 ? ` — ${spawned.stderr.trim().slice(-400)}` : ""}`);
229
+ }
230
+ const status = options?.liveStatus ?? sharedAgent(distro).status();
231
+ return mergeLiveResidentStatus(report, status);
232
+ }
163
233
  /**
164
234
  * The WSL shell executor's validated config — the keys of
165
235
  * {@link WslShellExecutor.Config}, which the upstream `LocalBashExecutor`
@@ -226,6 +296,44 @@ async function sessionRuntimeWanted(value, distro, ensure, cache) {
226
296
  return false;
227
297
  }
228
298
  }
299
+ /**
300
+ * The distro one operation belongs to, shared by the shell and filesystem
301
+ * resolvers: a pinned name wins, `default` goes straight to the probe, the
302
+ * first candidate naming a UNC distro wins, and the probe closes the list.
303
+ * The probe is lazy on purpose — a pinned row never pays for a default-distro
304
+ * probe, and a failing probe fails only the calls that actually needed it.
305
+ * `selectDistro` (distro-route) is the pure sibling whose fallback arrives
306
+ * already resolved; this one owns the probing.
307
+ *
308
+ * @param configured - the row's `distro` value.
309
+ * @param candidates - paths in any coordinate system, strongest evidence first.
310
+ * @param probeDefault - the fallback probe, invoked at most once per call.
311
+ */
312
+ async function resolveOperationDistro(configured, candidates, probeDefault) {
313
+ const pinned = pinnedDistro(configured);
314
+ if (pinned !== undefined)
315
+ return pinned;
316
+ if (!isDefaultDistro(configured)) {
317
+ for (const candidate of candidates) {
318
+ const named = distroOfUnc(candidate);
319
+ if (named !== undefined)
320
+ return named;
321
+ }
322
+ }
323
+ return probeDefault();
324
+ }
325
+ /**
326
+ * The refusal both shell resolvers share: the probes named no shell, and the
327
+ * command must not quietly run under some other interpreter.
328
+ * the probes named no shell, and the
329
+ * command must not quietly run under some other interpreter. The wording is
330
+ * the one `runInDistro` already throws with.
331
+ *
332
+ * @param distro - the distro whose shell could not be resolved.
333
+ */
334
+ const unusableShell = (distro) => new Error(`dsh-plugin-wsl: distro "${distro}" named no usable shell (passwd probe and $SHELL both failed). ` +
335
+ `Check the user's login shell in /etc/passwd (\`getent passwd "$(id -u)"\` inside the distro), ` +
336
+ `or point this row's \`shell\` at an existing absolute path.`);
229
337
  /**
230
338
  * Bash executor that runs every command inside a WSL distro.
231
339
  *
@@ -398,28 +506,23 @@ export class WslShellExecutor extends LocalBashExecutor {
398
506
  */
399
507
  async distroFor(workdir, cwd) {
400
508
  const config = this.config;
401
- const pinned = pinnedDistro(config.distro);
402
- if (pinned !== undefined)
403
- return pinned;
404
- if (!isDefaultDistro(config.distro)) {
405
- for (const candidate of [workdir, cwd ?? configuredCwd(this.config)]) {
406
- const named = distroOfUnc(candidate);
407
- if (named !== undefined)
408
- return named;
409
- }
410
- }
411
- return this.distro();
509
+ return resolveOperationDistro(config.distro, [workdir, cwd ?? configuredCwd(this.config)], () => this.distro());
412
510
  }
413
511
  /**
414
512
  * The shell name for the default/pinned distro, as the shell tool presents
415
513
  * it.
416
514
  *
417
- * @returns the basename of the shell, or `bash` when it cannot be named.
515
+ * @returns the basename of the shell; `shell` while the probe fails, and
516
+ * `bash` for an implausible basename.
418
517
  */
419
518
  async shellName() {
420
519
  // Consumed by the shell tool after upstream change A: it names and describes
421
- // itself from the executor, so a zsh distro is never presented as bash.
422
- const shell = await this.shell();
520
+ // itself from the executor, so a zsh distro is never presented as bash. The
521
+ // naming path must not crash on a failed probe — "shell" is the honest
522
+ // neutral — while an implausible basename keeps the bash fallback below.
523
+ const shell = await this.shell().catch(() => undefined);
524
+ if (shell === undefined)
525
+ return "shell";
423
526
  const base = String(shell ?? "").split("/").pop() ?? "";
424
527
  const name = base.replace(/\.exe$/i, "").replace(/^[-.]+/, "");
425
528
  return /^[a-z0-9_+-]+$/i.test(name) ? name : "bash";
@@ -431,6 +534,8 @@ export class WslShellExecutor extends LocalBashExecutor {
431
534
  *
432
535
  * @param distro - the distro name.
433
536
  * @returns an absolute path to the shell inside the distro.
537
+ * @throws {Error} when neither the config nor the distro names a usable
538
+ * shell — the failure is not cached, so the next call re-probes.
434
539
  */
435
540
  async shellFor(distro) {
436
541
  const config = this.config;
@@ -444,26 +549,32 @@ export class WslShellExecutor extends LocalBashExecutor {
444
549
  const resolved = await defaultShell(distro, { wslPath: config.wslPath });
445
550
  if (resolved !== undefined)
446
551
  this.resolvedShells.set(distro, resolved);
447
- return resolved ?? "bash";
552
+ if (resolved === undefined)
553
+ throw unusableShell(distro);
554
+ return resolved;
448
555
  }
449
556
  /**
450
557
  * The shell for the default/pinned distro: the configured one, else the
451
558
  * login shell, resolved once and cached.
452
559
  *
453
560
  * @returns an absolute path to the shell inside the distro.
561
+ * @throws {Error} when neither the config nor the distro names a usable
562
+ * shell — the failure is not cached, so the next call re-probes.
454
563
  */
455
564
  async shell() {
456
565
  const config = this.config;
457
566
  if (this.resolvedShell.length === 0) {
458
567
  const distro = await this.distro();
459
- // An unresolvable shell is a retry, not a pin: a failed probe (a cold
460
- // distro, a flaky first wsl.exe call) used to cache the "bash"
461
- // placeholder for this executor's lifetime. The runtime fallback below
462
- // keeps the command running; a later call resolves the real shell.
568
+ // An unresolvable shell fails the command loudly: the probes both came
569
+ // back empty (a cold distro, a flaky first wsl.exe call, a musl distro
570
+ // without getent), and running the command under some other interpreter
571
+ // would hide that from the caller. The failure is not cached — a later
572
+ // call re-probes and resolves the real shell once the distro is warm.
463
573
  const resolved = await defaultShell(distro, { wslPath: config.wslPath });
464
574
  if (resolved)
465
575
  this.resolvedShell = resolved;
466
- return resolved ?? "bash";
576
+ else
577
+ throw unusableShell(distro);
467
578
  }
468
579
  return this.resolvedShell;
469
580
  }
@@ -598,7 +709,7 @@ export class WslShellExecutor extends LocalBashExecutor {
598
709
  config.wslPath,
599
710
  ...distroArgs,
600
711
  "--cd",
601
- toLinuxPath(spec.workdir, { distro }),
712
+ toLinuxPath(spec.workdir),
602
713
  // `--exec` is essential, not decoration. Without it wsl.exe hands the
603
714
  // command line to the distro's DEFAULT SHELL, which expands it once before
604
715
  // our own shell ever sees it: `x=1; echo "$x"` arrives as `x=1; echo ""`,
@@ -702,7 +813,7 @@ export class WslShellExecutor extends LocalBashExecutor {
702
813
  const home = await distroHome(this, distro);
703
814
  if (tail === undefined || tail.length === 0)
704
815
  return { ...spec, workdir: home };
705
- return { ...spec, workdir: toLinuxPath(tail, { distro, cwd: home }) };
816
+ return { ...spec, workdir: toLinuxPath(tail, { cwd: home }) };
706
817
  }
707
818
  /**
708
819
  * Decorate a handle's foreground projection in place, memoized once. The
@@ -891,7 +1002,7 @@ export class WslShellExecutor extends LocalBashExecutor {
891
1002
  // coordinate system inside argv(); the agent carries the cwd as a frame
892
1003
  // field, so the SAME conversion happens here — a raw UNC must never
893
1004
  // reach `chdir` (that is the bug this line fixes).
894
- cwd: toLinuxPath(resolved.workdir, { distro }),
1005
+ cwd: toLinuxPath(resolved.workdir),
895
1006
  argv,
896
1007
  env: Object.keys(env).length > 0 ? env : undefined,
897
1008
  timeoutMs: resolved.timeoutMs,
@@ -992,63 +1103,107 @@ export class WslShellExecutor extends LocalBashExecutor {
992
1103
  throw error;
993
1104
  });
994
1105
  }
1106
+ // The confined prepare closes over this slot: the argv builder assigns it,
1107
+ // the fact-stamper and the settlement mapping read it. `executeArgv` runs
1108
+ // the builder before either callback can fire, so the reads always see the
1109
+ // assigned profile (or the run never happened). The mode is captured once
1110
+ // here: the guard above narrowed it, and property narrowings do not reach
1111
+ // closures.
995
1112
  const mode = policy.mode;
996
- let confined;
997
- const execution = await this.executeArgv(resolved, async (signal) => {
998
- // Preparation is async, so it runs under executeArgv's deadline and
999
- // cancellation handling rather than before them. A distro without a
1000
- // usable runner throws here, before anything is spawned. The outer
1001
- // guard narrowed the sandbox in, but narrowings do not reach closures —
1002
- // so the confined sandbox is asserted here, type-level only.
1003
- confined = await this.sandbox.confine(this.distroArgv(resolved, shell), { ...policy, mode }, { distro, signal });
1004
- signal.throwIfAborted();
1005
- return this.argv(resolved, distro, shell, confined.argv);
1006
- }, (process) => {
1007
- // The outer guard cannot narrow the captured profile inside the
1008
- // callback, so the confined shape is asserted once here.
1009
- const profile = confined;
1010
- this.processFacts.set(process, {
1011
- mode,
1012
- enforcement: profile.enforcement,
1013
- denialSignatures: profile.denialSignatures,
1014
- runnerFailureRules: profile.runnerFailureRules,
1015
- runnerProgram: profile.argv[0] ?? "",
1016
- workdir: resolved.workdir,
1017
- windowsDrive: profile.windowsDrive,
1018
- sessionScope: "per-command",
1019
- });
1020
- });
1113
+ const confinement = { profile: undefined };
1114
+ const execution = await this.executeArgv(resolved, (signal) => this.prepareConfinedArgv(resolved, distro, shell, policy, mode, confinement, signal), (process) => this.stampConfinedFacts(resolved, mode, confinement, process));
1021
1115
  return WslShellExecutor.decorateResult(execution, (result) => {
1022
- this.throwIfDistroUnavailable(result, distro);
1023
- this.throwIfWorkdirMissing(result, resolved.workdir);
1024
- if (confined === undefined) {
1025
- return ({ ...result, sandbox: { mode, denied: false, sessionScope: "per-command" } });
1026
- }
1027
- const { enforcement, denialSignatures, runnerFailureRules, windowsDrive } = confined;
1028
- // Runner failure outranks denial because the command did not run at all.
1029
- const runnerFailure = classifyRunnerFailure(result.exitCode, result.stderr.text, runnerFailureRules);
1030
- if (runnerFailure !== undefined)
1031
- throw new SandboxUnavailableError(mode, withBwrapHint(runnerFailure.detail, distro));
1032
- return ({
1033
- ...result,
1034
- sandbox: {
1035
- mode,
1036
- denied: matchesSignature(result.exitCode, result.stderr.text, denialSignatures),
1037
- enforcement,
1038
- windowsDrive,
1039
- sessionScope: "per-command",
1040
- },
1041
- });
1116
+ return this.settleConfinedOneShot(result, distro, resolved, mode, confinement.profile);
1042
1117
  }, (error) => {
1043
1118
  // An upstream abort remains cancellation even when it prevents spawn.
1044
1119
  if (resolved.signal?.aborted === true)
1045
1120
  resolved.signal.throwIfAborted();
1046
- if (confined !== undefined && isRunnerSpawnFailure(error, confined.argv[0], resolved.workdir)) {
1121
+ if (confinement.profile !== undefined && isRunnerSpawnFailure(error, confinement.profile.argv[0], resolved.workdir)) {
1047
1122
  throw new SandboxUnavailableError(mode, withBwrapHint(String(error), distro));
1048
1123
  }
1049
1124
  throw error;
1050
1125
  });
1051
1126
  }
1127
+ /**
1128
+ * The confined one-shot's argv prepare: confine the distro argv under the
1129
+ * policy, keep the resulting profile for the fact-stamper and the settlement
1130
+ * mapping, and hand back the wrapped host argv.
1131
+ *
1132
+ * @param resolved - the resolved spec.
1133
+ * @param distro - the resolved distro name.
1134
+ * @param shell - the resolved distro shell.
1135
+ * @param policy - the confined policy (narrowed in by `executeOneShot`).
1136
+ * @param slot - the closure the builder assigns the profile into.
1137
+ * @param signal - the caller's cancellation.
1138
+ */
1139
+ async prepareConfinedArgv(resolved, distro, shell, policy, mode, slot, signal) {
1140
+ // Preparation is async, so it runs under executeArgv's deadline and
1141
+ // cancellation handling rather than before them. A distro without a
1142
+ // usable runner throws here, before anything is spawned. The outer
1143
+ // guard narrowed the sandbox in, but narrowings do not reach closures —
1144
+ // so the confined sandbox is asserted here, type-level only.
1145
+ const profile = await this.sandbox.confine(this.distroArgv(resolved, shell), { ...policy, mode }, { distro, signal });
1146
+ slot.profile = profile;
1147
+ signal.throwIfAborted();
1148
+ return this.argv(resolved, distro, shell, profile.argv);
1149
+ }
1150
+ /**
1151
+ * Stamp the per-process sandbox facts before `done` settles, so a background
1152
+ * process reports the same mode, denial and enforcement a foreground run
1153
+ * would.
1154
+ *
1155
+ * @param resolved - the resolved spec.
1156
+ * @param mode - the confined policy's mode.
1157
+ * @param slot - the closure holding the assigned profile.
1158
+ * @param process - the spawned handle.
1159
+ */
1160
+ stampConfinedFacts(resolved, mode, slot, process) {
1161
+ // The builder has run before any process callback can fire; the confined
1162
+ // shape is asserted once here, type-level only.
1163
+ const profile = slot.profile;
1164
+ this.processFacts.set(process, {
1165
+ mode,
1166
+ enforcement: profile.enforcement,
1167
+ denialSignatures: profile.denialSignatures,
1168
+ runnerFailureRules: profile.runnerFailureRules,
1169
+ runnerProgram: profile.argv[0] ?? "",
1170
+ workdir: resolved.workdir,
1171
+ windowsDrive: profile.windowsDrive,
1172
+ sessionScope: "per-command",
1173
+ });
1174
+ }
1175
+ /**
1176
+ * Settle one confined one-shot result: the distro and workdir verdicts, the
1177
+ * never-armed honesty stamp, the runner-failure throw, and the denial facts.
1178
+ *
1179
+ * @param result - the settled process result.
1180
+ * @param distro - the resolved distro name.
1181
+ * @param resolved - the resolved spec.
1182
+ * @param mode - the confined policy's mode.
1183
+ * @param confined - the profile the argv prepare armed, when it ran.
1184
+ */
1185
+ settleConfinedOneShot(result, distro, resolved, mode, confined) {
1186
+ this.throwIfDistroUnavailable(result, distro);
1187
+ this.throwIfWorkdirMissing(result, resolved.workdir);
1188
+ if (confined === undefined) {
1189
+ return ({ ...result, sandbox: { mode, denied: false, sessionScope: "per-command" } });
1190
+ }
1191
+ const { enforcement, denialSignatures, runnerFailureRules, windowsDrive } = confined;
1192
+ // Runner failure outranks denial because the command did not run at all.
1193
+ const runnerFailure = classifyRunnerFailure(result.exitCode, result.stderr.text, runnerFailureRules);
1194
+ if (runnerFailure !== undefined)
1195
+ throw new SandboxUnavailableError(mode, withBwrapHint(runnerFailure.detail, distro));
1196
+ return ({
1197
+ ...result,
1198
+ sandbox: {
1199
+ mode,
1200
+ denied: matchesSignature(result.exitCode, result.stderr.text, denialSignatures),
1201
+ enforcement,
1202
+ windowsDrive,
1203
+ sessionScope: "per-command",
1204
+ },
1205
+ });
1206
+ }
1052
1207
  }
1053
1208
  export class WslFileSystem extends LocalFileSystem {
1054
1209
  static inject = ["sandboxPolicy"];
@@ -1415,17 +1570,7 @@ export class WslFileSystem extends LocalFileSystem {
1415
1570
  */
1416
1571
  async distroForPath(path, cwd) {
1417
1572
  const config = this.config;
1418
- const pinned = pinnedDistro(config.distro);
1419
- if (pinned !== undefined)
1420
- return pinned;
1421
- if (!isDefaultDistro(config.distro)) {
1422
- for (const candidate of [path, cwd ?? config.cwd]) {
1423
- const named = distroOfUnc(candidate);
1424
- if (named !== undefined)
1425
- return named;
1426
- }
1427
- }
1428
- return this.distro();
1573
+ return resolveOperationDistro(config.distro, [path, cwd ?? config.cwd], () => this.distro());
1429
1574
  }
1430
1575
  /**
1431
1576
  * The distro a resolved target belongs to. A UNC identity names it outright;
@@ -1446,17 +1591,7 @@ export class WslFileSystem extends LocalFileSystem {
1446
1591
  */
1447
1592
  async distroForPolicy(policy) {
1448
1593
  const config = this.config;
1449
- const pinned = pinnedDistro(config.distro);
1450
- if (pinned !== undefined)
1451
- return pinned;
1452
- if (!isDefaultDistro(config.distro)) {
1453
- for (const candidate of [policy?.workspaceRoot, config.cwd]) {
1454
- const named = distroOfUnc(candidate);
1455
- if (named !== undefined)
1456
- return named;
1457
- }
1458
- }
1459
- return this.distro();
1594
+ return resolveOperationDistro(config.distro, [policy?.workspaceRoot, config.cwd], () => this.distro());
1460
1595
  }
1461
1596
  /**
1462
1597
  * Translate one caller path into the world path, enforcing the distro fence.
@@ -1801,4 +1936,71 @@ export class WslFileSystem extends LocalFileSystem {
1801
1936
  throw this.peerError(error);
1802
1937
  }
1803
1938
  }
1939
+ /**
1940
+ * Apply parsed hunks (protocol 7): hunk matching and application run
1941
+ * in-process through the peer's own `applyHunks` (the same dialect and
1942
+ * `FS_PATCH_MISMATCH` the peer emits), against the distro's bytes, then
1943
+ * publish through the same guarded atomic write an edit takes.
1944
+ *
1945
+ * @param target - the resolved regular file.
1946
+ * @param hunks - ordered hunks from the caller's patch parse.
1947
+ * @param expected - the version the patch was based on.
1948
+ * @param signal - cancels the patch.
1949
+ * @param sandboxPolicy - the per-call policy; omit for the deployment default.
1950
+ * @returns the pre/post text and the published version.
1951
+ */
1952
+ async patchText(target, hunks, expected, signal, sandboxPolicy) {
1953
+ const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
1954
+ const fenced = await this.checkedTarget(target, policy);
1955
+ try {
1956
+ return (await (await this.substrateForTarget(fenced)).patchText(fenced, hunks, expected, signal, policy));
1957
+ }
1958
+ catch (error) {
1959
+ throw this.peerError(error);
1960
+ }
1961
+ }
1962
+ /**
1963
+ * Remove one regular file (protocol 7) after fencing the target by the
1964
+ * per-call policy; the guarded removal re-verifies the expected version
1965
+ * distro-side.
1966
+ *
1967
+ * @param target - the resolved file.
1968
+ * @param expected - the version the removal was based on.
1969
+ * @param signal - cancels the removal.
1970
+ * @param sandboxPolicy - the per-call policy; omit for the deployment default.
1971
+ * @returns the bounded pre-removal text basis.
1972
+ */
1973
+ async deleteFile(target, expected, signal, sandboxPolicy) {
1974
+ const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
1975
+ const fenced = await this.checkedTarget(target, policy);
1976
+ try {
1977
+ return (await (await this.substrateForTarget(fenced)).deleteFile(fenced, expected, signal, policy));
1978
+ }
1979
+ catch (error) {
1980
+ throw this.peerError(error);
1981
+ }
1982
+ }
1983
+ /**
1984
+ * Move one regular file (protocol 7) after fencing BOTH endpoints by the
1985
+ * per-call policy — the destination publishes and the source is removed, so
1986
+ * each must be writable under the same roots.
1987
+ *
1988
+ * @param source - the resolved source.
1989
+ * @param destination - the resolved destination.
1990
+ * @param options - the hunks and the source/destination guards.
1991
+ * @param signal - cancels before publication.
1992
+ * @param sandboxPolicy - the per-call policy; omit for the deployment default.
1993
+ * @returns the bounded source basis and the destination outcome.
1994
+ */
1995
+ async moveFile(source, destination, options, signal, sandboxPolicy) {
1996
+ const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
1997
+ const fencedSource = await this.checkedTarget(source, policy);
1998
+ const fencedDestination = await this.checkedTarget(destination, policy);
1999
+ try {
2000
+ return (await (await this.substrateForTarget(fencedSource)).moveFile(fencedSource, fencedDestination, options, signal, policy));
2001
+ }
2002
+ catch (error) {
2003
+ throw this.peerError(error);
2004
+ }
2005
+ }
1804
2006
  }
package/lib/listing.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * run `pnpm run build` — the artifact under `lib/` is generated, and `pnpm test`
9
9
  * fails when it drifts.
10
10
  *
11
- * @module dsh-plugin-wsl/listing
11
+ * @module dsh-plugin-wsl-env/listing
12
12
  */
13
13
  /** One picker row: a display name, its jump target, and the dot-entry flag. */
14
14
  export interface ListingRow {
package/lib/listing.js CHANGED
@@ -8,7 +8,7 @@
8
8
  * run `pnpm run build` — the artifact under `lib/` is generated, and `pnpm test`
9
9
  * fails when it drifts.
10
10
  *
11
- * @module dsh-plugin-wsl/listing
11
+ * @module dsh-plugin-wsl-env/listing
12
12
  */
13
13
  import { win32 } from "node:path";
14
14
  import { isWslUnc, uncToPosix } from "./paths.js";
@@ -19,7 +19,7 @@
19
19
  * and run `pnpm run build` — the artifact under `lib/` is generated, and
20
20
  * `pnpm test` fails when it drifts.
21
21
  *
22
- * @module dsh-plugin-wsl/native-agent
22
+ * @module dsh-plugin-wsl-env/native-agent
23
23
  */
24
24
  /** The host environment variable naming the native binary to opt in. */
25
25
  export declare const NATIVE_AGENT_ENV = "DSH_WSL_AGENT_NATIVE";
@@ -19,7 +19,7 @@
19
19
  * and run `pnpm run build` — the artifact under `lib/` is generated, and
20
20
  * `pnpm test` fails when it drifts.
21
21
  *
22
- * @module dsh-plugin-wsl/native-agent
22
+ * @module dsh-plugin-wsl-env/native-agent
23
23
  */
24
24
  import { spawn } from "node:child_process";
25
25
  import { createHash } from "node:crypto";
@@ -190,7 +190,7 @@ export async function ensureNativeSessionAgent({ wslPath, distro, setNative, ens
190
190
  const result = await ensure({ wslPath, distro, source: process.env[NATIVE_AGENT_ENV] ?? "" });
191
191
  if (result === undefined) {
192
192
  if (backend === "native") {
193
- throw new Error(`agentBackend: "native" could not prepare a native binary: the packaged binary for this architecture is missing or failed the copy/digest/execute check, and ${NATIVE_AGENT_ENV} is unset or unusable; set a valid ${NATIVE_AGENT_ENV}, or use "auto"/"shell".`);
193
+ throw new Error(`dsh-plugin-wsl-env: agentBackend: "native" could not prepare a native binary: the packaged binary for this architecture is missing or failed the copy/digest/execute check, and ${NATIVE_AGENT_ENV} is unset or unusable; set a valid ${NATIVE_AGENT_ENV}, or use "auto"/"shell".`);
194
194
  }
195
195
  return;
196
196
  }
package/lib/paths.d.ts CHANGED
@@ -17,7 +17,7 @@
17
17
  * `pnpm run build` — the artifact under `lib/` is generated, and `pnpm test`
18
18
  * fails when it drifts.
19
19
  *
20
- * @module dsh-plugin-wsl/paths
20
+ * @module dsh-plugin-wsl-env/paths
21
21
  */
22
22
  /** A distro identity and the Linux path inside it, as {@link uncToPosix} returns. */
23
23
  export interface DistroPath {
@@ -134,10 +134,13 @@ export declare function windowsToLinuxMount(winPath: string): string | undefined
134
134
  * editing the profile is likely to write a plain Linux path.
135
135
  *
136
136
  * @param value - the path to translate.
137
- * @param options - the pinned distro and the fallback directory for relative input.
137
+ * @param options - the fallback directory for relative input (the pinned distro is
138
+ * not an input: the mapping is coordinate-only and reads no pin).
138
139
  * @returns an absolute Linux path, or the input unchanged when it cannot be mapped.
139
140
  */
140
- export declare function toLinuxPath(value: string, options?: WorldPathOptions): string;
141
+ export declare function toLinuxPath(value: string, options?: {
142
+ cwd?: string;
143
+ }): string;
141
144
  /**
142
145
  * Join a requested path onto a workspace root in the distro's Linux
143
146
  * coordinate system: UNC absolutes map to their Linux paths, POSIX absolutes
package/lib/paths.js CHANGED
@@ -17,7 +17,7 @@
17
17
  * `pnpm run build` — the artifact under `lib/` is generated, and `pnpm test`
18
18
  * fails when it drifts.
19
19
  *
20
- * @module dsh-plugin-wsl/paths
20
+ * @module dsh-plugin-wsl-env/paths
21
21
  */
22
22
  /** The WSL UNC share prefix Node can read. `\\wsl$\<distro>\...` is the legacy spelling. */
23
23
  const UNC_RE = /^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(?:\\([\s\S]*))?$/i;
@@ -218,7 +218,8 @@ export function windowsToLinuxMount(winPath) {
218
218
  * editing the profile is likely to write a plain Linux path.
219
219
  *
220
220
  * @param value - the path to translate.
221
- * @param options - the pinned distro and the fallback directory for relative input.
221
+ * @param options - the fallback directory for relative input (the pinned distro is
222
+ * not an input: the mapping is coordinate-only and reads no pin).
222
223
  * @returns an absolute Linux path, or the input unchanged when it cannot be mapped.
223
224
  */
224
225
  export function toLinuxPath(value, options) {
@@ -233,9 +234,8 @@ export function toLinuxPath(value, options) {
233
234
  const mounted = windowsToLinuxMount(text);
234
235
  if (mounted !== undefined)
235
236
  return mounted;
236
- // Relative input is resolved against the configured default workdir.
237
237
  const base = options?.cwd ?? "/";
238
- const baseLinux = toLinuxPath(base, { distro: options?.distro });
238
+ const baseLinux = toLinuxPath(base);
239
239
  return `${baseLinux.replace(/\/+$/, "")}/${text.replace(/^\.\//, "")}`;
240
240
  }
241
241
  /**
package/lib/picker.d.ts CHANGED
@@ -45,7 +45,7 @@
45
45
  * `pnpm run build` — the artifact under `lib/` is generated, and `pnpm test`
46
46
  * fails when it drifts.
47
47
  *
48
- * @module dsh-plugin-wsl/picker
48
+ * @module dsh-plugin-wsl-env/picker
49
49
  */
50
50
  import z from "@deepseek-ai/schemastery";
51
51
  import { DirectoryPicker } from "@deepseek-ai/dsh-host-directory-picker";