dsh-plugin-wsl-env 0.28.0 → 0.29.1

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 (81) hide show
  1. package/CHANGELOG.md +368 -0
  2. package/CONTRIBUTING.md +68 -12
  3. package/CONTRIBUTING.zh.md +34 -4
  4. package/README.md +1 -1
  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 +15 -4
  8. package/client.js +540 -160
  9. package/cordis.patch.yml +28 -7
  10. package/docs/AGENT-PROTOCOL-V7.md +4 -2
  11. package/docs/API.md +1 -1
  12. package/docs/API.zh.md +1 -1
  13. package/docs/ARCHITECTURE.md +7 -4
  14. package/docs/ARCHITECTURE.zh.md +6 -4
  15. package/docs/COMPATIBILITY.md +1 -1
  16. package/docs/COMPATIBILITY.zh.md +1 -1
  17. package/docs/CONFIGURATION.md +28 -15
  18. package/docs/CONFIGURATION.zh.md +20 -11
  19. package/docs/DIAGNOSTICS.md +45 -19
  20. package/docs/DIAGNOSTICS.zh.md +33 -15
  21. package/docs/LIMITATIONS.md +70 -10
  22. package/docs/LIMITATIONS.zh.md +53 -8
  23. package/docs/PERFORMANCE.md +29 -1
  24. package/docs/PERFORMANCE.zh.md +23 -1
  25. package/docs/QUICKSTART.md +21 -15
  26. package/docs/QUICKSTART.zh.md +13 -11
  27. package/docs/README.zh.md +1 -1
  28. package/docs/RELEASING.md +29 -6
  29. package/docs/RELEASING.zh.md +9 -0
  30. package/docs/adr/0002-native-agent.md +50 -2
  31. package/lib/agent-confined.js +15 -4
  32. package/lib/agent-errors.d.ts +16 -0
  33. package/lib/agent-errors.js +19 -0
  34. package/lib/agent-exec.d.ts +8 -1
  35. package/lib/agent-exec.js +2 -1
  36. package/lib/agent-shared.d.ts +85 -2
  37. package/lib/agent-shared.js +167 -38
  38. package/lib/agent.d.ts +60 -6
  39. package/lib/agent.js +177 -28
  40. package/lib/auto-preset.js +7 -2
  41. package/lib/doctor-live.d.ts +36 -7
  42. package/lib/doctor-live.js +61 -12
  43. package/lib/doctor-process.d.ts +68 -0
  44. package/lib/doctor-process.js +139 -0
  45. package/lib/doctor-report.js +11 -109
  46. package/lib/fs-substrate.js +3 -3
  47. package/lib/fsio-agent.d.ts +57 -6
  48. package/lib/fsio-agent.js +168 -75
  49. package/lib/git-exec.d.ts +7 -1
  50. package/lib/git-exec.js +14 -2
  51. package/lib/native-agent.d.ts +25 -4
  52. package/lib/native-agent.js +52 -9
  53. package/lib/picker.d.ts +2 -1
  54. package/lib/picker.js +30 -13
  55. package/lib/plugin-update.js +18 -14
  56. package/lib/provider-common.d.ts +112 -0
  57. package/lib/provider-common.js +171 -0
  58. package/lib/sandbox-core.js +52 -13
  59. package/lib/search-exec.d.ts +6 -0
  60. package/lib/search-exec.js +10 -2
  61. package/lib/session-runtime.d.ts +46 -1
  62. package/lib/session-runtime.js +57 -7
  63. package/lib/session-scope.d.ts +22 -1
  64. package/lib/session-scope.js +33 -7
  65. package/lib/shell-env.js +125 -12
  66. package/lib/socket-isolation.d.ts +12 -4
  67. package/lib/socket-isolation.js +27 -10
  68. package/lib/status.d.ts +7 -4
  69. package/lib/status.js +72 -16
  70. package/lib/subprocess.js +3 -3
  71. package/lib/terminal-activity.js +6 -9
  72. package/lib/wsl-doctor-command.js +36 -80
  73. package/lib/wsl-filesystem.d.ts +9 -4
  74. package/lib/wsl-filesystem.js +26 -10
  75. package/lib/wsl-shell.d.ts +27 -17
  76. package/lib/wsl-shell.js +83 -24
  77. package/lib/wsl.d.ts +3 -1
  78. package/lib/wsl.js +82 -7
  79. package/package.json +5 -4
  80. package/scripts/bootstrap.sh +36 -12
  81. package/scripts/doctor.mjs +514 -201
package/lib/status.js CHANGED
@@ -14,12 +14,13 @@
14
14
  * restored from the store below;
15
15
  * - `GET /api/wsl-env/status?distro=<name>` — one distro's quick doctor
16
16
  * report, digested to the same shape the `/wsl-doctor` command renders;
17
- * - `POST /api/wsl-env/status?distro=<name>` — the panel's full-check action:
17
+ * - `GET /api/wsl-env/status?distro=<name>&full=1` — one distro's full,
18
+ * read-only doctor report;
19
+ * - `POST /api/wsl-env/status?distro=<name>` — the explicit repair action:
18
20
  * a full doctor run with `--fix-owned`, which sweeps stale session scopes
19
21
  * and purges a broken agent cache, then re-verifies both and answers with
20
22
  * the same digest plus the `fix.*` rows. Nothing outside the plugin's own
21
- * state is touched (no packages, no Windows git config), so the panel
22
- * stays a diagnostic surface that can heal its own residue;
23
+ * state is touched (no packages, no Windows git config);
23
24
  * - `DELETE /api/wsl-env/status[?distro=<name>]` — the panel's clear action:
24
25
  * drops one distro's stored verdict, or every stored verdict when no distro
25
26
  * is named, and answers `{ cleared: <count> }`. Clearing is host-local on
@@ -169,11 +170,12 @@ function countsOf(findings) {
169
170
  * @param digest - the shared digest the command and the tool render.
170
171
  * @param distro - the distro the report answers for.
171
172
  * @param now - the run's timestamp.
172
- * @param repaired - whether the run was the full `--fix-owned` action.
173
+ * @param full - whether the run covered the full doctor scope.
174
+ * @param repaired - whether the run was the `--fix-owned` repair action.
173
175
  * @param source - who started the run.
174
176
  * @returns the panel view.
175
177
  */
176
- function viewOf(digest, distro, now, repaired, source) {
178
+ function viewOf(digest, distro, now, full, repaired, source) {
177
179
  // The fix rows are the repair's own narration, not findings about the
178
180
  // environment: keep them out of the failure/warning lists so a repair does
179
181
  // not double-list its work, and surface them separately.
@@ -211,6 +213,7 @@ function viewOf(digest, distro, now, repaired, source) {
211
213
  return {
212
214
  distro,
213
215
  verdict: digest.verdict === "ready" ? "ready" : "blocked",
216
+ full,
214
217
  repaired,
215
218
  repairs: repaired
216
219
  ? fixes.map((item) => ({
@@ -258,6 +261,13 @@ export function createStatusHandler(options) {
258
261
  const now = options.now ?? (() => Date.now());
259
262
  const statePath = options.statePath ?? defaultStatePath();
260
263
  const verdicts = new Map();
264
+ /**
265
+ * The runs in flight, by distro and mode. A second request for the same
266
+ * run joins it instead of starting another doctor: two concurrent sweeps
267
+ * of one distro saturate `wsl.exe`, and whichever answer landed second
268
+ * used to win the stored result.
269
+ */
270
+ const inflight = new Map();
261
271
  let list;
262
272
  // Restore the last successful results before the first request. The stored
263
273
  // view is the panel's shape; the fields later releases may have added are
@@ -269,6 +279,7 @@ export function createStatusHandler(options) {
269
279
  at: view.checkedAt,
270
280
  view: {
271
281
  ...view,
282
+ full: view.full === true,
272
283
  repairs: Array.isArray(view.repairs) ? view.repairs : [],
273
284
  repairable: Array.isArray(view.repairable) ? view.repairable : [],
274
285
  failures: Array.isArray(view.failures) ? view.failures : [],
@@ -299,8 +310,18 @@ export function createStatusHandler(options) {
299
310
  list = { at: now(), names };
300
311
  return names;
301
312
  };
302
- const check = async (distro, refresh, repair = false, source = "user") => {
313
+ /** Run one doctor for one distro; the single-flight wrapper is {@link check}. */
314
+ const run = async (distro, refresh, mode, source) => {
303
315
  const cached = verdicts.get(distro);
316
+ // A background refresh is the page load's courtesy re-check of a QUICK
317
+ // result. A full diagnosis, or a repair with its before → after
318
+ // evidence, is the user's own doing and is never replaced by a quick
319
+ // one: that replaced the repair button and the evidence sixty seconds
320
+ // after the user last opened the panel. (A failed full run is not
321
+ // protected: it has nothing to keep.)
322
+ if (source === "background" && cached !== undefined && cached.view.verdict !== "error" && (cached.view.full === true || cached.view.repaired === true)) {
323
+ return present(cached.view, true);
324
+ }
304
325
  // A failure is a fact of this moment: it is kept for the list and the
305
326
  // store, but a plain GET re-runs instead of serving it as fresh.
306
327
  if (!refresh && cached !== undefined && cached.view.verdict !== "error" && now() - cached.at < options.cacheMs)
@@ -308,22 +329,28 @@ export function createStatusHandler(options) {
308
329
  const at = now();
309
330
  let view;
310
331
  try {
311
- // A repair needs a full run: `--fix` refuses a scoped one because a
312
- // scoped report cannot re-verify what it did not probe. `--fix-owned`
313
- // keeps the loop on plugin-owned state (scopes, agent cache) — the panel
314
- // never installs packages or rewrites Windows-owned configuration.
315
- const argv = repair
316
- ? ["--json", "--fix", "--fix-owned", "--distro", distro]
317
- : ["--json", "--quick", "--distro", distro];
332
+ // Repairs require the full scope so every changed condition is re-probed.
333
+ // The separate full mode is read-only and never passes a fix flag.
334
+ // One stuck probe must settle inside this run's own budget instead of
335
+ // under the outer kill, so the report names the read that hung: the
336
+ // probe deadline plus one flake retry and the settle delay is 2T + 2s
337
+ // (the settle is the doctor's 2 s), kept strictly below the budget.
338
+ const probeTimeout = Math.ceil((options.timeoutMs - 2_000) / 2) - 1;
339
+ const argv = mode === "repair"
340
+ ? ["--json", "--fix", "--fix-owned", "--probe-timeout", String(probeTimeout), "--distro", distro]
341
+ : mode === "full"
342
+ ? ["--json", "--probe-timeout", String(probeTimeout), "--distro", distro]
343
+ : ["--json", "--quick", "--probe-timeout", String(probeTimeout), "--distro", distro];
318
344
  const raw = await options.runCli(argv, undefined, options.timeoutMs);
319
345
  const report = JSON.parse(raw);
320
346
  const live = mergeTakeoverReport(mergeAutoPresetSeam(report), options.providers?.() ?? []);
321
- view = viewOf(digestReport(live, distro), distro, at, repair, source);
347
+ view = viewOf(digestReport(live, distro), distro, at, mode !== "quick", mode === "repair", source);
322
348
  }
323
349
  catch (error) {
324
350
  view = {
325
351
  distro,
326
352
  verdict: "error",
353
+ full: mode !== "quick",
327
354
  repaired: false,
328
355
  repairs: [],
329
356
  repairable: [],
@@ -348,6 +375,33 @@ export function createStatusHandler(options) {
348
375
  writeStored(statePath, verdicts);
349
376
  return present(view, false);
350
377
  };
378
+ /**
379
+ * Check one distro, at most once at a time per mode: requests for the same
380
+ * distro and mode that arrive while one runs answer with that run's result.
381
+ * A repair is its own mode and never shares a read-only run.
382
+ *
383
+ * @param distro - the distro to check.
384
+ * @param refresh - whether to bypass the stored result.
385
+ * @param mode - the doctor scope.
386
+ * @param source - who started it.
387
+ * @returns the view to present.
388
+ */
389
+ const check = (distro, refresh, mode = "quick", source = "user") => {
390
+ const key = `${distro}\u0000${mode}`;
391
+ const running = inflight.get(key);
392
+ if (running !== undefined)
393
+ return running;
394
+ const pending = run(distro, refresh, mode, source);
395
+ inflight.set(key, pending);
396
+ // The entry leaves with the run whatever its outcome; the promise stored
397
+ // is the one later callers join, never a derived one.
398
+ const forget = () => {
399
+ if (inflight.get(key) === pending)
400
+ inflight.delete(key);
401
+ };
402
+ void pending.then(forget, forget);
403
+ return pending;
404
+ };
351
405
  /**
352
406
  * Drop stored verdicts and persist the change. Clearing is deliberately
353
407
  * independent of `wsl.exe`: it is local housekeeping, and must still work
@@ -409,8 +463,10 @@ export function createStatusHandler(options) {
409
463
  }
410
464
  if (!names.includes(requested))
411
465
  return json({ error: t("statusUnknownDistro", { distro: requested }) }, 400);
412
- const background = !repair && url.searchParams.get("background") === "1";
413
- return json(await check(requested, refresh || repair, repair, background ? "background" : "user"));
466
+ const full = !repair && url.searchParams.get("full") === "1";
467
+ const background = !repair && !full && url.searchParams.get("background") === "1";
468
+ const mode = repair ? "repair" : full ? "full" : "quick";
469
+ return json(await check(requested, refresh || full || repair, mode, background ? "background" : "user"));
414
470
  };
415
471
  }
416
472
  /**
package/lib/subprocess.js CHANGED
@@ -308,7 +308,7 @@ export class WslSubprocessRuntime extends LocalSubprocessRuntime {
308
308
  return async () => {
309
309
  try {
310
310
  const probe = terminalActivityProbe(terminalId);
311
- const result = await sharedAgent(distro).exec({
311
+ const result = await sharedAgent(distro, this.config.wslPath).exec({
312
312
  cwd: probe.cwd,
313
313
  argv: probe.argv,
314
314
  maxOutputBytes: 256,
@@ -383,7 +383,7 @@ export class WslSubprocessRuntime extends LocalSubprocessRuntime {
383
383
  const stdoutCap = spec.stdio.stdout?.maxBytes ?? 0;
384
384
  const stderrCap = spec.stdio.stderr?.maxBytes ?? 0;
385
385
  return gitExecutionHandle({
386
- agent: sharedAgent(gitRewrite.distro),
386
+ agent: sharedAgent(gitRewrite.distro, this.config.wslPath),
387
387
  cwd: gitRewrite.linuxCwd,
388
388
  argv: gitRewrite.gitArgv,
389
389
  env: agentEnv,
@@ -402,7 +402,7 @@ export class WslSubprocessRuntime extends LocalSubprocessRuntime {
402
402
  // (`done`, `collected`, `kill`); the seam's full handle surface is the
403
403
  // one-shot fallback's, so the override's declared return is the cast's.
404
404
  return searchExecutionHandle({
405
- agent: sharedAgent(rewrite.distro),
405
+ agent: sharedAgent(rewrite.distro, this.config.wslPath),
406
406
  cwd: rewrite.linuxCwd,
407
407
  argv: rewrite.rgArgv,
408
408
  distro: rewrite.distro,
@@ -56,17 +56,14 @@ export const TERMINAL_ID_ENV = "DSH_TERMINAL_ID";
56
56
  * @returns the agent `exec` target: the probe script with the id as `$1`.
57
57
  */
58
58
  export function terminalActivityProbe(terminalId) {
59
+ // One pass over every environ, not two forks per /proc entry: the stream is
60
+ // concatenated, NULs become newlines, and grep counts the exact lines —
61
+ // more than one match is "busy". The per-entry loop measured 90-160 ms at
62
+ // 112 processes; this reads in under 10.
59
63
  const script = [
60
64
  "id=$1",
61
- "count=0",
62
- 'for d in /proc/[0-9]*; do',
63
- ' [ -r "$d/environ" ] || continue',
64
- ' if tr "\\000" "\\n" < "$d/environ" 2>/dev/null | grep -qx "DSH_TERMINAL_ID=$id"; then',
65
- " count=$((count+1))",
66
- ' [ "$count" -gt 1 ] && { echo busy; exit 0; }',
67
- " fi",
68
- "done",
69
- "echo idle",
65
+ 'n=$(cat /proc/[0-9]*/environ 2>/dev/null | tr "\\000" "\\n" | grep -c -x "DSH_TERMINAL_ID=$id" || true)',
66
+ '[ "${n:-0}" -gt 1 ] && echo busy || echo idle',
70
67
  ].join("\n");
71
68
  return { cwd: "/", argv: ["sh", "-c", script, "sh", terminalId] };
72
69
  }
@@ -1,39 +1,10 @@
1
- /**
2
- * The `/wsl-doctor` UI command: the human runs the environment doctor through
3
- * the command plane — the browser button drops a `/wsl-doctor` line, the
4
- * commands registry executes it against a session, and the settled text
5
- * renders in the UI detached from model history. No model turn happens: the
6
- * command and its output add no tokens and never enter a request (the
7
- * `dsh-commands` contract), which is the point — the diagnosis must not
8
- * depend on the plugin's model-facing runtime being healthy.
9
- *
10
- * The handler does NOT collect the report in-process. It spawns the
11
- * standalone doctor CLI (`scripts/doctor.mjs --json`) as a host subprocess:
12
- * the CLI loads no peer dependency and no host service (its two peer-tainted
13
- * imports are inlined and drift-pinned by test), so a diagnosis answers even
14
- * when the plugin's own module graph is the thing that is broken. Formatting
15
- * reuses `digestReport`/`renderDigest` from the tool module so the UI command
16
- * and the model tool present identical itemized output.
17
- *
18
- * Grammar: `/wsl-doctor [quick|full|<section>] [--distro <name>]` — an empty
19
- * line means quick. Without an explicit distro the session's own working
20
- * directory names the distro; when that also fails, the CLI's effective
21
- * configuration decides (the shipped preset's `auto` probes every installed
22
- * distro). Unknown tokens settle as a direct command error with usage text.
23
- *
24
- * This is a TypeScript source built to `lib/wsl-doctor-command.js`; edit THIS
25
- * file and run `pnpm run build` — the artifact under `lib/` is generated, and
26
- * `pnpm test` fails when it drifts.
27
- *
28
- * @module dsh-plugin-wsl-env/wsl-doctor-command
29
- */
30
- import { spawn } from "node:child_process";
31
1
  import { dirname, resolve } from "node:path";
32
2
  import { fileURLToPath } from "node:url";
33
3
  import { distroOfUnc } from "./distro-route.js";
34
4
  import { withHostPeerVersions } from "./peer-versions.js";
35
5
  import { digestReport, renderDigest, SECTIONS } from "./wsl-doctor-tool.js";
36
6
  import { mergeAutoPresetSeam } from "./doctor-live.js";
7
+ import { DOCTOR_OUTPUT_LIMIT_BYTES, runDoctorProcess } from "./doctor-process.js";
37
8
  import { installMessagesLocale, t } from "./messages.js";
38
9
  import { mergeTakeoverReport, takeoverSnapshot } from "./takeover-report.js";
39
10
  export const name = "wsl-doctor-command";
@@ -138,57 +109,36 @@ export function parseDoctorInput(rawInput) {
138
109
  * @param timeoutMs - the deadline; tests shrink it to exercise the timeout.
139
110
  * @returns the CLI's stdout (one JSON report).
140
111
  */
141
- export function runDoctorCli(argv, signal, timeoutMs = DOCTOR_CLI_TIMEOUT_MS) {
142
- return new Promise((resolvePromise, rejectPromise) => {
143
- const child = spawn(process.execPath, [DOCTOR_SCRIPT, ...argv], {
144
- env: withHostPeerVersions({ ...process.env, ELECTRON_RUN_AS_NODE: "1" }),
145
- windowsHide: true,
146
- stdio: ["ignore", "pipe", "pipe"],
147
- signal,
148
- });
149
- let stdout = "";
150
- let stderr = "";
151
- let settled = false;
152
- let timedOut = false;
153
- const settle = (finish) => {
154
- if (settled)
155
- return;
156
- settled = true;
157
- clearTimeout(deadline);
158
- finish();
159
- };
160
- const deadline = setTimeout(() => {
161
- timedOut = true;
162
- try {
163
- child.kill();
164
- }
165
- catch {
166
- // Already exited: the close handler settles the run.
167
- }
168
- }, timeoutMs);
169
- child.stdout?.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
170
- child.stderr?.on("data", (chunk) => { stderr += chunk.toString("utf8"); });
171
- child.on("error", (error) => {
172
- // An abort arrives here as an AbortError; normalize it so the settled
173
- // message names the run rather than the DOMException.
174
- settle(() => rejectPromise(error.name === "AbortError" ? new Error(t("doctorCliCancelled", {})) : error));
175
- });
176
- child.on("close", (code, signalName) => {
177
- const text = stdout.trim();
178
- if (text.startsWith("{")) {
179
- settle(() => resolvePromise(text));
180
- return;
181
- }
182
- if (timedOut) {
183
- settle(() => rejectPromise(new Error(t("doctorCliTimeout", { seconds: timeoutMs / 1000 }))));
184
- return;
185
- }
186
- settle(() => rejectPromise(new Error(t("doctorCliNoReport", {
187
- status: String(code ?? signalName ?? "signal"),
188
- detail: stderr.trim().length > 0 ? `: ${stderr.trim().slice(0, 400)}` : "",
189
- }))));
190
- });
112
+ export async function runDoctorCli(argv, signal, timeoutMs = DOCTOR_CLI_TIMEOUT_MS) {
113
+ // The shared collector owns the deadline, the output cap and the decoding,
114
+ // so this runner and the in-app report runner cannot drift apart.
115
+ const run = await runDoctorProcess([DOCTOR_SCRIPT, ...argv], {
116
+ env: withHostPeerVersions({ ...process.env, ELECTRON_RUN_AS_NODE: "1" }),
117
+ timeoutMs,
118
+ ...(signal === undefined ? {} : { signal }),
191
119
  });
120
+ if (signal?.aborted || run.spawnError?.message === "doctor run aborted") {
121
+ throw new Error(t("doctorCliCancelled", {}));
122
+ }
123
+ // The deadline outranks a JSON prefix: a killed run may have flushed a
124
+ // truncated object that still starts with `{`.
125
+ if (run.timedOut)
126
+ throw new Error(t("doctorCliTimeout", { seconds: timeoutMs / 1000 }));
127
+ if (run.overLimit) {
128
+ throw new Error(t("doctorCliNoReport", {
129
+ status: `more than ${DOCTOR_OUTPUT_LIMIT_BYTES} bytes`,
130
+ detail: "",
131
+ }));
132
+ }
133
+ if (run.spawnError !== undefined)
134
+ throw run.spawnError;
135
+ const text = run.stdout.trim();
136
+ if (text.startsWith("{"))
137
+ return text;
138
+ throw new Error(t("doctorCliNoReport", {
139
+ status: String(run.status ?? run.signal ?? "signal"),
140
+ detail: run.stderr.trim().length > 0 ? `: ${run.stderr.trim().slice(0, 400)}` : "",
141
+ }));
192
142
  }
193
143
  /**
194
144
  * Await a promise for at most `ms` milliseconds, returning undefined when the
@@ -383,6 +333,12 @@ export async function apply(ctx) {
383
333
  // one hands the choice to the configuration, whose `auto` sweeps every
384
334
  // installed distro — bounded tightly so it cannot sit "executing".
385
335
  const budget = distro.length > 0 ? DOCTOR_CLI_TIMEOUT_MS : DOCTOR_CLI_SWEEP_TIMEOUT_MS;
336
+ // One stuck probe settles inside the budget instead of under the
337
+ // runner's kill, so the report names the read that hung: the probe
338
+ // deadline plus one flake retry and the settle delay is 2T + 2s (the
339
+ // settle is the doctor's 2 s), kept strictly below the budget.
340
+ const probeTimeout = Math.ceil((budget - 2_000) / 2) - 1;
341
+ argv.push("--probe-timeout", String(probeTimeout));
386
342
  try {
387
343
  const json = await runCli(argv, invocation.signal, budget);
388
344
  return { kind: "success", text: formatDoctorReport(json, distro, takeoverSnapshot(ctx)) };
@@ -10,7 +10,7 @@ import { type SocketIsolation } from "./socket-isolation.js";
10
10
  import type { Context } from "@deepseek-ai/cordis";
11
11
  import type { FileSystem, FsDeleteOutcome, FsDirEntry, FsEditOutcome, FsEditRequest, FsInfo, FsMoveOutcome, FsPathInfo, FsTarget, FsVersion, FsWriteIntent, FsWriteOutcome } from "@deepseek-ai/dsh-fs";
12
12
  import type { SandboxExecutionPolicy, SandboxMode } from "@deepseek-ai/dsh-sandbox";
13
- import { ProviderRuntimeBook } from "./provider-common.js";
13
+ import { ProviderRuntimeBook, SessionEndWatch } from "./provider-common.js";
14
14
  type PatchHunks = Parameters<FileSystem["patchText"]>[1];
15
15
  type MoveFileOptions = Parameters<FileSystem["moveFile"]>[2];
16
16
  /**
@@ -288,6 +288,8 @@ export declare class WslFileSystem extends LocalFileSystem {
288
288
  sessionRuntimes: SessionRuntimes;
289
289
  /** Isolates calls that have no session identity. */
290
290
  sessionRuntimeOwner: string;
291
+ /** Ends the session runtimes with their sessions; see `SessionEndWatch`. */
292
+ sessionEndWatch: SessionEndWatch;
291
293
  /** The preflight's host runner; tests substitute it. */
292
294
  sessionScopeProbe: (argv: string[]) => Promise<string>;
293
295
  /** The one-time writable-root check's runner; tests substitute it. */
@@ -392,7 +394,8 @@ export declare class WslFileSystem extends LocalFileSystem {
392
394
  * The persistent session runtime for one confined mutation, when
393
395
  * `sessionSandbox` is on. The key is the shell executor's key for the same
394
396
  * session/policy, so the write and the commands share one agent, one mount
395
- * view and one scope; the provider holds a reference until the session ends.
397
+ * view and one scope; the provider holds a reference until the session ends
398
+ * (`agent/disposed`, through {@link sessionEndWatch}).
396
399
  *
397
400
  * @param policy - the resolved confined policy.
398
401
  * @param distro - the resolved distro name.
@@ -423,8 +426,10 @@ export declare class WslFileSystem extends LocalFileSystem {
423
426
  */
424
427
  wantsSessionRuntime(distro: string): Promise<boolean>;
425
428
  /**
426
- * Release every runtime this provider holds. Called from the preset's
427
- * dispose effect; public so tests and shutdown paths can await it.
429
+ * Release every runtime this provider holds. Called when the row goes away
430
+ * (the preset is unregistered, the app shuts down) — the sessions ended long
431
+ * before, each through {@link sessionEndWatch}; public so tests and shutdown
432
+ * paths can await it.
428
433
  *
429
434
  * @returns resolved once every reference is released.
430
435
  */
@@ -19,7 +19,7 @@ import { installMessagesLocale } from "./messages.js";
19
19
  import { defaultDistro, runCapture } from "./wsl.js";
20
20
  import { validateWritableRootsConfig } from "./writable-roots.js";
21
21
  import { SocketIsolationError, socketMasksFor as resolveSocketMasks } from "./socket-isolation.js";
22
- import { ProviderRuntimeBook, distroHome, effectiveWritableRoots, resolveOperationDistro, sessionRuntimeWanted, wslWritableRoots } from "./provider-common.js";
22
+ import { ProviderRuntimeBook, distroHome, effectiveWritableRoots, resolveOperationDistro, sessionRuntimeWanted, wslWritableRoots, SessionEndWatch } from "./provider-common.js";
23
23
  /**
24
24
  * Filesystem backend over a WSL distro's UNC share.
25
25
  *
@@ -185,8 +185,12 @@ export class WslFileSystem extends LocalFileSystem {
185
185
  this.sessionScopeProbe = (argv) => runCapture(argv);
186
186
  this.writableRootsProbe = (argv) => runCapture(argv);
187
187
  this.socketIsolationProbe = (argv) => runCapture(argv);
188
- // The preset's disposer releases the runtime; the shell executor's effect
189
- // releases its own reference, so the scope stops after the last one.
188
+ // The preset realm this row lives in is the PROCESS's, not the session's:
189
+ // upstream disposes it only when the preset definition is unregistered, so
190
+ // this disposer is the process-level backstop. The session's end is the
191
+ // harness's own `agent/disposed`, which the watch wires to a release — for
192
+ // this provider's reference and the shell executor's alike.
193
+ this.sessionEndWatch = new SessionEndWatch(this, ctx);
190
194
  ctx.effect(() => () => this.disposeSessionRuntimes().catch(() => { }), "wsl fs session runtimes");
191
195
  }
192
196
  /**
@@ -209,7 +213,7 @@ export class WslFileSystem extends LocalFileSystem {
209
213
  */
210
214
  async publicationAgent() {
211
215
  if (this.agentInstance === undefined) {
212
- this.agentInstance = sharedAgent(await this.distro());
216
+ this.agentInstance = sharedAgent(await this.distro(), this.wslConfig.wslPath);
213
217
  }
214
218
  return this.agentInstance;
215
219
  }
@@ -227,7 +231,7 @@ export class WslFileSystem extends LocalFileSystem {
227
231
  const cached = this.agentInstances.get(distro);
228
232
  if (cached !== undefined)
229
233
  return cached;
230
- const agent = sharedAgent(distro);
234
+ const agent = sharedAgent(distro, this.wslConfig.wslPath);
231
235
  this.agentInstances.set(distro, agent);
232
236
  return agent;
233
237
  }
@@ -351,7 +355,8 @@ export class WslFileSystem extends LocalFileSystem {
351
355
  * The persistent session runtime for one confined mutation, when
352
356
  * `sessionSandbox` is on. The key is the shell executor's key for the same
353
357
  * session/policy, so the write and the commands share one agent, one mount
354
- * view and one scope; the provider holds a reference until the session ends.
358
+ * view and one scope; the provider holds a reference until the session ends
359
+ * (`agent/disposed`, through {@link sessionEndWatch}).
355
360
  *
356
361
  * @param policy - the resolved confined policy.
357
362
  * @param distro - the resolved distro name.
@@ -366,8 +371,15 @@ export class WslFileSystem extends LocalFileSystem {
366
371
  const sessionId = policy.sessionId || this.sessionRuntimeOwner;
367
372
  const key = SessionRuntimes.key({ sessionId, distro, workspaceRoot, mode: policy.mode, maskWindowsDrive: config.maskWindowsDrive, writableRoots, socketMasks, maskInterop });
368
373
  const held = this.runtimeBook.sessionRuntimeEntries.get(key);
369
- if (held !== undefined)
370
- return held;
374
+ if (held !== undefined) {
375
+ // A session end tears its runtimes down through every holder. One that
376
+ // reached this runtime without this provider must not leave it handing
377
+ // out a closed agent: the stale reference goes, and a resumed session
378
+ // gets a fresh runtime below.
379
+ if (this.sessionRuntimes.holds(held))
380
+ return held;
381
+ this.runtimeBook.sessionRuntimeEntries.delete(key);
382
+ }
371
383
  const entry = this.sessionRuntimes.acquire({
372
384
  sessionId,
373
385
  distro,
@@ -380,6 +392,7 @@ export class WslFileSystem extends LocalFileSystem {
380
392
  maskInterop,
381
393
  });
382
394
  this.runtimeBook.sessionRuntimeEntries.set(key, entry);
395
+ this.sessionEndWatch.ensureSweep();
383
396
  return entry;
384
397
  }
385
398
  /**
@@ -413,12 +426,15 @@ export class WslFileSystem extends LocalFileSystem {
413
426
  return sessionRuntimeWanted(config.sessionSandbox, distro, () => this.ensureSessionRuntimeUsable(distro), this.runtimeBook.autoSessionScope);
414
427
  }
415
428
  /**
416
- * Release every runtime this provider holds. Called from the preset's
417
- * dispose effect; public so tests and shutdown paths can await it.
429
+ * Release every runtime this provider holds. Called when the row goes away
430
+ * (the preset is unregistered, the app shuts down) — the sessions ended long
431
+ * before, each through {@link sessionEndWatch}; public so tests and shutdown
432
+ * paths can await it.
418
433
  *
419
434
  * @returns resolved once every reference is released.
420
435
  */
421
436
  async disposeSessionRuntimes() {
437
+ this.sessionEndWatch.dispose();
422
438
  const entries = [...this.runtimeBook.sessionRuntimeEntries.values()];
423
439
  this.runtimeBook.sessionRuntimeEntries.clear();
424
440
  for (const entry of entries)
@@ -6,7 +6,7 @@ import { SessionRuntimes } from "./session-runtime.js";
6
6
  import type { AgentBackend } from "./native-agent.js";
7
7
  import type { SessionRuntimeEntry } from "./session-runtime.js";
8
8
  import { type SocketIsolation } from "./socket-isolation.js";
9
- import { ProviderRuntimeBook } from "./provider-common.js";
9
+ import { ProviderRuntimeBook, SessionEndWatch } from "./provider-common.js";
10
10
  import type { Context } from "@deepseek-ai/cordis";
11
11
  import type { SandboxExecutionPolicy, SandboxMode } from "@deepseek-ai/dsh-sandbox";
12
12
  import type { SubprocessSpawnSpec } from "@deepseek-ai/dsh-subprocess";
@@ -244,9 +244,11 @@ export declare class WslShellExecutor extends LocalBashExecutor {
244
244
  /**
245
245
  * Run commands through the resident agent when it is up (one long-lived
246
246
  * in-distro process; in-distro timeout semantics), falling back to the
247
- * one-shot `wsl.exe` path whenever the agent is out. `false` never uses
248
- * the agent. The confinement, the output budgets' shapes and the result
249
- * decoration are identical on both paths.
247
+ * one-shot `wsl.exe` path whenever the agent is out and the command had
248
+ * not reached it. A command that was in flight when the resident died is
249
+ * not run again — its state is unknown — and fails saying so. `false`
250
+ * never uses the agent. The confinement, the output budgets' shapes and
251
+ * the result decoration are identical on both paths.
250
252
  */
251
253
  agent: z<boolean, boolean, "defined">;
252
254
  agentBackend: z<"auto" | "native" | "shell", "auto" | "native" | "shell", "defined">;
@@ -254,8 +256,8 @@ export declare class WslShellExecutor extends LocalBashExecutor {
254
256
  * Run this session's commands in one persistent systemd user scope (ADR
255
257
  * 0001): background processes survive the command that started them, `/tmp`
256
258
  * is the distro's real `/tmp` under workspace-write, and `ps` sees the
257
- * session. The executor holds the runtime until the session's scope
258
- * disposes, then stops it. Requires systemd, a reachable user manager and
259
+ * session. The executor holds the runtime until the session's agent is
260
+ * disposed, then stops it. Requires systemd, a reachable user manager and
259
261
  * `Linger`; the preflight refuses with the remedy when one is missing, and
260
262
  * only a success is cached. Off by default; requires `agent: true`.
261
263
  */
@@ -379,9 +381,11 @@ export declare class WslShellExecutor extends LocalBashExecutor {
379
381
  /**
380
382
  * Run commands through the resident agent when it is up (one long-lived
381
383
  * in-distro process; in-distro timeout semantics), falling back to the
382
- * one-shot `wsl.exe` path whenever the agent is out. `false` never uses
383
- * the agent. The confinement, the output budgets' shapes and the result
384
- * decoration are identical on both paths.
384
+ * one-shot `wsl.exe` path whenever the agent is out and the command had
385
+ * not reached it. A command that was in flight when the resident died is
386
+ * not run again — its state is unknown — and fails saying so. `false`
387
+ * never uses the agent. The confinement, the output budgets' shapes and
388
+ * the result decoration are identical on both paths.
385
389
  */
386
390
  agent: z<boolean, boolean, "defined">;
387
391
  agentBackend: z<"auto" | "native" | "shell", "auto" | "native" | "shell", "defined">;
@@ -389,8 +393,8 @@ export declare class WslShellExecutor extends LocalBashExecutor {
389
393
  * Run this session's commands in one persistent systemd user scope (ADR
390
394
  * 0001): background processes survive the command that started them, `/tmp`
391
395
  * is the distro's real `/tmp` under workspace-write, and `ps` sees the
392
- * session. The executor holds the runtime until the session's scope
393
- * disposes, then stops it. Requires systemd, a reachable user manager and
396
+ * session. The executor holds the runtime until the session's agent is
397
+ * disposed, then stops it. Requires systemd, a reachable user manager and
394
398
  * `Linger`; the preflight refuses with the remedy when one is missing, and
395
399
  * only a success is cached. Off by default; requires `agent: true`.
396
400
  */
@@ -414,6 +418,8 @@ export declare class WslShellExecutor extends LocalBashExecutor {
414
418
  sessionRuntimes: SessionRuntimes;
415
419
  /** Isolates calls that have no session identity. */
416
420
  sessionRuntimeOwner: string;
421
+ /** Ends the session runtimes with their sessions; see `SessionEndWatch`. */
422
+ sessionEndWatch: SessionEndWatch;
417
423
  /** The preflight's host runner; tests substitute it. */
418
424
  sessionScopeProbe: (argv: string[]) => Promise<string>;
419
425
  /** The one-time writable-root check's runner; tests substitute it. */
@@ -511,8 +517,9 @@ export declare class WslShellExecutor extends LocalBashExecutor {
511
517
  executionAgent(distro: string): WslAgent;
512
518
  /**
513
519
  * The persistent session runtime for one policy, when `sessionSandbox` is
514
- * on. The executor holds one reference per `(session, distro, workspace, policy)` and
515
- * releases them when the session's scope disposes.
520
+ * on. The executor holds one reference per `(session, distro, workspace, policy)`;
521
+ * the session's end (`agent/disposed`, through {@link sessionEndWatch})
522
+ * releases them.
516
523
  *
517
524
  * @param policy - the resolved file-effect policy, when the executor has one.
518
525
  * @param resolved - the resolved spec, for the fallback workspace.
@@ -548,8 +555,9 @@ export declare class WslShellExecutor extends LocalBashExecutor {
548
555
  wantsSessionRuntime(distro: string): Promise<boolean>;
549
556
  /**
550
557
  * Release every runtime this executor holds, stopping each scope. Called
551
- * from the session's dispose hook; public so tests and shutdown paths can
552
- * await it.
558
+ * when the row goes away (the preset is unregistered, the app shuts down) —
559
+ * the sessions ended long before, each through {@link sessionEndWatch};
560
+ * public so tests and shutdown paths can await it.
553
561
  *
554
562
  * @returns resolved once every runtime is torn down.
555
563
  */
@@ -751,8 +759,10 @@ export declare class WslShellExecutor extends LocalBashExecutor {
751
759
  throwIfWorkdirInAnotherDistro(workdir: string, distro: string): void;
752
760
  /**
753
761
  * The agent-backed execution path: one long-lived in-distro process, the
754
- * confinement argv unchanged, the handle shape unchanged. Any
755
- * {@link AgentUnavailableError} propagates for the caller's fallback.
762
+ * confinement argv unchanged, the handle shape unchanged. An
763
+ * {@link AgentUnavailableError} for a command the resident never took
764
+ * settles the handle with the one-shot retry instead; one for a command
765
+ * that was in flight when the resident was lost propagates.
756
766
  *
757
767
  * @param resolved - the resolved spec from {@link WslShellExecutor.execute}.
758
768
  * @param distro - the resolved distro name.