dsh-plugin-wsl-env 0.29.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 (78) hide show
  1. package/CHANGELOG.md +342 -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 +454 -110
  9. package/cordis.patch.yml +28 -7
  10. package/docs/AGENT-PROTOCOL-V7.md +4 -2
  11. package/docs/ARCHITECTURE.md +3 -1
  12. package/docs/ARCHITECTURE.zh.md +3 -1
  13. package/docs/COMPATIBILITY.md +1 -1
  14. package/docs/COMPATIBILITY.zh.md +1 -1
  15. package/docs/CONFIGURATION.md +19 -7
  16. package/docs/CONFIGURATION.zh.md +13 -5
  17. package/docs/DIAGNOSTICS.md +31 -5
  18. package/docs/DIAGNOSTICS.zh.md +22 -5
  19. package/docs/LIMITATIONS.md +65 -6
  20. package/docs/LIMITATIONS.zh.md +51 -6
  21. package/docs/PERFORMANCE.md +29 -1
  22. package/docs/PERFORMANCE.zh.md +23 -1
  23. package/docs/QUICKSTART.md +1 -1
  24. package/docs/QUICKSTART.zh.md +1 -1
  25. package/docs/README.zh.md +1 -1
  26. package/docs/RELEASING.md +29 -6
  27. package/docs/RELEASING.zh.md +9 -0
  28. package/docs/adr/0002-native-agent.md +50 -2
  29. package/lib/agent-confined.js +15 -4
  30. package/lib/agent-errors.d.ts +16 -0
  31. package/lib/agent-errors.js +19 -0
  32. package/lib/agent-exec.d.ts +8 -1
  33. package/lib/agent-exec.js +2 -1
  34. package/lib/agent-shared.d.ts +85 -2
  35. package/lib/agent-shared.js +167 -38
  36. package/lib/agent.d.ts +60 -6
  37. package/lib/agent.js +177 -28
  38. package/lib/auto-preset.js +7 -2
  39. package/lib/doctor-live.d.ts +36 -7
  40. package/lib/doctor-live.js +61 -12
  41. package/lib/doctor-process.d.ts +68 -0
  42. package/lib/doctor-process.js +139 -0
  43. package/lib/doctor-report.js +11 -109
  44. package/lib/fs-substrate.js +3 -3
  45. package/lib/fsio-agent.d.ts +57 -6
  46. package/lib/fsio-agent.js +168 -75
  47. package/lib/git-exec.d.ts +7 -1
  48. package/lib/git-exec.js +14 -2
  49. package/lib/native-agent.d.ts +25 -4
  50. package/lib/native-agent.js +52 -9
  51. package/lib/picker.d.ts +2 -1
  52. package/lib/picker.js +30 -13
  53. package/lib/plugin-update.js +18 -14
  54. package/lib/provider-common.d.ts +112 -0
  55. package/lib/provider-common.js +171 -0
  56. package/lib/sandbox-core.js +52 -13
  57. package/lib/search-exec.d.ts +6 -0
  58. package/lib/search-exec.js +10 -2
  59. package/lib/session-runtime.d.ts +46 -1
  60. package/lib/session-runtime.js +57 -7
  61. package/lib/session-scope.d.ts +22 -1
  62. package/lib/session-scope.js +33 -7
  63. package/lib/shell-env.js +125 -12
  64. package/lib/socket-isolation.d.ts +12 -4
  65. package/lib/socket-isolation.js +27 -10
  66. package/lib/status.js +53 -4
  67. package/lib/subprocess.js +3 -3
  68. package/lib/terminal-activity.js +6 -9
  69. package/lib/wsl-doctor-command.js +36 -80
  70. package/lib/wsl-filesystem.d.ts +9 -4
  71. package/lib/wsl-filesystem.js +26 -10
  72. package/lib/wsl-shell.d.ts +27 -17
  73. package/lib/wsl-shell.js +83 -24
  74. package/lib/wsl.d.ts +3 -1
  75. package/lib/wsl.js +82 -7
  76. package/package.json +5 -4
  77. package/scripts/bootstrap.sh +36 -12
  78. package/scripts/doctor.mjs +514 -201
@@ -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.
package/lib/wsl-shell.js CHANGED
@@ -6,7 +6,7 @@ import { isAnotherDistrosUnc, isRelativeWorldPath, toLinuxPath } from "./paths.j
6
6
  import { pinnedDistro } from "./distro-route.js";
7
7
  import { WslSandbox } from "./sandbox.js";
8
8
  import { withBwrapHint } from "./sandbox-core.js";
9
- import { AgentUnavailableError, SpawnError } from "./agent-errors.js";
9
+ import { AgentRequestStateUnknownError, AgentUnavailableError, SpawnError } from "./agent-errors.js";
10
10
  import { agentExecutionHandle } from "./agent-exec.js";
11
11
  import { sharedAgent } from "./agent-shared.js";
12
12
  import { SessionRuntimes, probeSessionRuntime, sessionRuntimes, setSessionNativeAgent } from "./session-runtime.js";
@@ -15,7 +15,21 @@ import { installMessagesLocale, t } from "./messages.js";
15
15
  import { defaultDistro, defaultShell, runCapture, shellArgs, workdirFailure, wslErrorCode } from "./wsl.js";
16
16
  import { validateWritableRootsConfig } from "./writable-roots.js";
17
17
  import { SocketIsolationError, socketMasksFor as resolveSocketMasks } from "./socket-isolation.js";
18
- import { ProviderRuntimeBook, configuredCwd, distroHome, effectiveMaskWindowsDrive, effectiveWritableRoots, resolveOperationDistro, sessionRuntimeWanted } from "./provider-common.js";
18
+ import { ProviderRuntimeBook, SessionEndWatch, configuredCwd, distroHome, effectiveMaskWindowsDrive, effectiveWritableRoots, resolveOperationDistro, sessionRuntimeWanted } from "./provider-common.js";
19
+ /**
20
+ * Whether one rejection is the executor's cue to run the command again on the
21
+ * one-shot `wsl.exe` path: the resident is out AND the command provably never
22
+ * reached a distro process through it. A request that was with the resident
23
+ * when it was lost may have run — {@link AgentRequestStateUnknownError} — and
24
+ * re-running it there would run non-idempotent work twice, or report a create
25
+ * that succeeded as a refusal, so it is not a cue.
26
+ *
27
+ * @param error - the rejection the agent path settled with.
28
+ * @returns true when the command may be retried one-shot.
29
+ */
30
+ function isFallbackCue(error) {
31
+ return error instanceof AgentUnavailableError && !(error instanceof AgentRequestStateUnknownError);
32
+ }
19
33
  /**
20
34
  * Every model shell call gets a rebuilt managed `DSH_*` namespace (see
21
35
  * `dsh-shell-env` / `ctx.shellEnv`). Those names exist only in the Windows-side
@@ -174,9 +188,11 @@ export class WslShellExecutor extends LocalBashExecutor {
174
188
  /**
175
189
  * Run commands through the resident agent when it is up (one long-lived
176
190
  * in-distro process; in-distro timeout semantics), falling back to the
177
- * one-shot `wsl.exe` path whenever the agent is out. `false` never uses
178
- * the agent. The confinement, the output budgets' shapes and the result
179
- * decoration are identical on both paths.
191
+ * one-shot `wsl.exe` path whenever the agent is out and the command had
192
+ * not reached it. A command that was in flight when the resident died is
193
+ * not run again — its state is unknown — and fails saying so. `false`
194
+ * never uses the agent. The confinement, the output budgets' shapes and
195
+ * the result decoration are identical on both paths.
180
196
  */
181
197
  agent: z.boolean().default(true),
182
198
  agentBackend: z.union(["auto", "native", "shell"]).default("auto"),
@@ -184,8 +200,8 @@ export class WslShellExecutor extends LocalBashExecutor {
184
200
  * Run this session's commands in one persistent systemd user scope (ADR
185
201
  * 0001): background processes survive the command that started them, `/tmp`
186
202
  * is the distro's real `/tmp` under workspace-write, and `ps` sees the
187
- * session. The executor holds the runtime until the session's scope
188
- * disposes, then stops it. Requires systemd, a reachable user manager and
203
+ * session. The executor holds the runtime until the session's agent is
204
+ * disposed, then stops it. Requires systemd, a reachable user manager and
189
205
  * `Linger`; the preflight refuses with the remedy when one is missing, and
190
206
  * only a success is cached. Off by default; requires `agent: true`.
191
207
  */
@@ -230,8 +246,11 @@ export class WslShellExecutor extends LocalBashExecutor {
230
246
  this.sessionScopeProbe = (argv) => runCapture(argv);
231
247
  this.writableRootsProbe = (argv) => runCapture(argv);
232
248
  this.socketIsolationProbe = (argv) => runCapture(argv);
233
- // The preset realm disposes when the session ends; the scope must go with
234
- // it, or a dev server outlives the session that started it.
249
+ // The preset realm this row lives in is the PROCESS's, not the session's:
250
+ // upstream disposes it only when the preset definition is unregistered, so
251
+ // this disposer is the process-level backstop. The session's end is the
252
+ // harness's own `agent/disposed`, which the watch wires to a release.
253
+ this.sessionEndWatch = new SessionEndWatch(this, ctx);
235
254
  ctx.effect(() => () => this.disposeSessionRuntimes().catch(() => { }), "wsl session runtimes");
236
255
  }
237
256
  /**
@@ -356,12 +375,13 @@ export class WslShellExecutor extends LocalBashExecutor {
356
375
  * @returns the shared agent.
357
376
  */
358
377
  executionAgent(distro) {
359
- return sharedAgent(distro);
378
+ return sharedAgent(distro, this.wslConfig.wslPath);
360
379
  }
361
380
  /**
362
381
  * The persistent session runtime for one policy, when `sessionSandbox` is
363
- * on. The executor holds one reference per `(session, distro, workspace, policy)` and
364
- * releases them when the session's scope disposes.
382
+ * on. The executor holds one reference per `(session, distro, workspace, policy)`;
383
+ * the session's end (`agent/disposed`, through {@link sessionEndWatch})
384
+ * releases them.
365
385
  *
366
386
  * @param policy - the resolved file-effect policy, when the executor has one.
367
387
  * @param resolved - the resolved spec, for the fallback workspace.
@@ -377,8 +397,15 @@ export class WslShellExecutor extends LocalBashExecutor {
377
397
  const sessionId = policy?.sessionId || resolved.dshEnv?.DSH_SESSION_ID || this.sessionRuntimeOwner;
378
398
  const key = SessionRuntimes.key({ sessionId, distro, workspaceRoot, mode, maskWindowsDrive: effectiveMaskWindowsDrive(config), writableRoots, socketMasks, maskInterop });
379
399
  const held = this.runtimeBook.sessionRuntimeEntries.get(key);
380
- if (held !== undefined)
381
- return held;
400
+ if (held !== undefined) {
401
+ // A session end tears its runtimes down through every holder. One that
402
+ // reached this runtime without this executor must not leave it handing
403
+ // out a closed agent: the stale reference goes, and a resumed session
404
+ // gets a fresh runtime below.
405
+ if (this.sessionRuntimes.holds(held))
406
+ return held;
407
+ this.runtimeBook.sessionRuntimeEntries.delete(key);
408
+ }
382
409
  const entry = this.sessionRuntimes.acquire({
383
410
  sessionId,
384
411
  distro,
@@ -391,6 +418,7 @@ export class WslShellExecutor extends LocalBashExecutor {
391
418
  maskInterop,
392
419
  });
393
420
  this.runtimeBook.sessionRuntimeEntries.set(key, entry);
421
+ this.sessionEndWatch.ensureSweep();
394
422
  return entry;
395
423
  }
396
424
  /**
@@ -429,12 +457,14 @@ export class WslShellExecutor extends LocalBashExecutor {
429
457
  }
430
458
  /**
431
459
  * Release every runtime this executor holds, stopping each scope. Called
432
- * from the session's dispose hook; public so tests and shutdown paths can
433
- * await it.
460
+ * when the row goes away (the preset is unregistered, the app shuts down) —
461
+ * the sessions ended long before, each through {@link sessionEndWatch};
462
+ * public so tests and shutdown paths can await it.
434
463
  *
435
464
  * @returns resolved once every runtime is torn down.
436
465
  */
437
466
  async disposeSessionRuntimes() {
467
+ this.sessionEndWatch.dispose();
438
468
  const entries = [...this.runtimeBook.sessionRuntimeEntries.values()];
439
469
  this.runtimeBook.sessionRuntimeEntries.clear();
440
470
  for (const entry of entries)
@@ -768,9 +798,10 @@ export class WslShellExecutor extends LocalBashExecutor {
768
798
  return await this.executeViaAgent(resolved, distro, shell, writableRoots, socketMasks, maskInterop);
769
799
  }
770
800
  catch (error) {
771
- // Only an out-of-service agent falls back; anything else (a cwd
772
- // refusal, a sandbox refusal) is the command's own verdict.
773
- if (!(error instanceof AgentUnavailableError))
801
+ // Only an out-of-service agent that never took the command falls
802
+ // back; anything else (a cwd refusal, a sandbox refusal, a command
803
+ // whose state is unknown) is the command's own verdict.
804
+ if (!isFallbackCue(error))
774
805
  throw error;
775
806
  }
776
807
  }
@@ -795,8 +826,10 @@ export class WslShellExecutor extends LocalBashExecutor {
795
826
  }
796
827
  /**
797
828
  * The agent-backed execution path: one long-lived in-distro process, the
798
- * confinement argv unchanged, the handle shape unchanged. Any
799
- * {@link AgentUnavailableError} propagates for the caller's fallback.
829
+ * confinement argv unchanged, the handle shape unchanged. An
830
+ * {@link AgentUnavailableError} for a command the resident never took
831
+ * settles the handle with the one-shot retry instead; one for a command
832
+ * that was in flight when the resident was lost propagates.
800
833
  *
801
834
  * @param resolved - the resolved spec from {@link WslShellExecutor.execute}.
802
835
  * @param distro - the resolved distro name.
@@ -863,6 +896,14 @@ export class WslShellExecutor extends LocalBashExecutor {
863
896
  });
864
897
  }
865
898
  : undefined,
899
+ // Upstream's own handle calls `onProcessDone` as it settles; without
900
+ // this the stamp `onStarted` left would never be applied to the handle
901
+ // (a background process would report no sandbox facts) and never be
902
+ // released — every confined command through the resident would keep its
903
+ // handle, output buffers included, in `processFacts` for good.
904
+ onSettled: (proc, error) => {
905
+ this.onProcessDone(proc, proc.observed.stderr.readFrom(0).text, error !== undefined, error);
906
+ },
866
907
  });
867
908
  const decorated = WslShellExecutor.decorateResult(execution, (result) => {
868
909
  this.throwIfDistroUnavailable(result, distro);
@@ -893,13 +934,31 @@ export class WslShellExecutor extends LocalBashExecutor {
893
934
  }, (error) => {
894
935
  if (resolved.signal?.aborted === true)
895
936
  resolved.signal.throwIfAborted();
937
+ /**
938
+ * Run the command again on the one-shot path and settle with that
939
+ * handle's result. The agent handle stamped confinement facts for a run
940
+ * that never happened through it, so the stamp goes before the retry;
941
+ * the one-shot handle stamps and settles its own.
942
+ *
943
+ * @returns the one-shot result.
944
+ */
945
+ const retryOneShot = () => {
946
+ this.processFacts.delete(execution);
947
+ return this.executeOneShot(resolved, distro, shell, writableRoots, socketMasks, maskInterop).then((fallback) => fallback.result());
948
+ };
896
949
  // The native agent reports a missing workdir as a spawn failure without
897
950
  // naming it. Retry that command on the one-shot path, whose `--cd`
898
951
  // warning names the directory — the failure path pays the extra spawn,
899
952
  // the hot path does not.
900
- if (error instanceof SpawnError) {
901
- return this.executeOneShot(resolved, distro, shell, writableRoots, socketMasks, maskInterop).then((fallback) => fallback.result());
902
- }
953
+ if (error instanceof SpawnError)
954
+ return retryOneShot();
955
+ // The resident refused the command before running it — dead, backing off
956
+ // after a death, or its handshake failed. `WslAgent.exec` is async, so
957
+ // that refusal always arrives here, through `result()`, never as the
958
+ // synchronous throw `execute` catches. A command that WAS with the
959
+ // resident when it was lost is not a cue: see `isFallbackCue`.
960
+ if (isFallbackCue(error))
961
+ return retryOneShot();
903
962
  throw error;
904
963
  });
905
964
  // The agent handle IS the upstream execution shape at runtime; its typedef
package/lib/wsl.d.ts CHANGED
@@ -102,10 +102,12 @@ export declare function parseDistroList(stdout: string): string[];
102
102
  * @throws when no distro is installed.
103
103
  */
104
104
  export declare function defaultDistro(options?: WslCallOptions): Promise<string>;
105
+ /** Test hook: forget the shared home and shell probes. */
106
+ export declare function resetWslProbeCacheForTests(): void;
105
107
  /**
106
108
  * The Linux home directory of a distro's default user, as a Linux path. `$HOME`
107
109
  * is set by `wsl.exe` itself from the distro's default user, so this needs no
108
- * passwd parsing.
110
+ * passwd parsing. Resolved once per `(wslPath, distro)` per process.
109
111
  *
110
112
  * @param distro - distro name.
111
113
  * @param options - the `wsl.exe` path and optional cancellation.