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
@@ -152,7 +152,9 @@ One process per agent, an event loop over stdin plus child pipes and timers:
152
152
  acknowledges them (`ACK|id`) and spawns each request's process group (or
153
153
  performs the FS syscalls directly for `stat`/`read`/`write`).
154
154
  - `KILL|id` and the per-request deadline signal the group: `TERM`, then
155
- `KILL` after a fixed grace; the event loop keeps serving other requests.
155
+ `KILL` after a grace; the event loop keeps serving other requests. Both
156
+ take the cancel path's three seconds (the deadline used to allow 100 ms —
157
+ see the hardening pass below).
156
158
  - stdout/stderr pipes are drained into per-request bounded buffers; the RES
157
159
  line carries the exit code, both buffers and the cut flags.
158
160
  - stdin EOF, `SHUTDOWN` or a fatal IO error runs the same cleanup as today:
@@ -162,7 +164,10 @@ One process per agent, an event loop over stdin plus child pipes and timers:
162
164
  - FS operations use syscalls (stat/lstat/readlink/read/write, atomic rename);
163
165
  no `sh`, `base64`, `stat`, `find` subprocesses. The write path keeps the
164
166
  no-replace and expected-version semantics the host fence relies on, and the
165
- same staging-directory cleanup for killed writes.
167
+ same staging-directory cleanup for killed writes. Mutations serialize with
168
+ each other under `fs_lock`; reads wait for nothing. A `move` on one
169
+ filesystem is a `rename` — the inode keeps its identity — and is copied
170
+ only across filesystems.
166
171
 
167
172
  ## Host integration
168
173
 
@@ -299,6 +304,49 @@ step is the **native shared read agent (v5)** — same packaged binary and
299
304
  protocol, the shell as fallback, roughly 30x on batch reads — not v6. The
300
305
  single-op latency (~22 ms) is the transport, not the FS backend.
301
306
 
307
+ ## Hardening pass (2026-11-24, #74 and #78)
308
+
309
+ A code review with measurements on a real distro found six defects in this
310
+ process model. Each is fixed in `agent/native/spike/src/main.rs` and pinned by
311
+ a check in `agent/native/spike/test.mjs` that fails against the previous
312
+ binary and passes against the rebuilt one, on x86_64 and (under qemu-user) on
313
+ aarch64:
314
+
315
+ - **The stdin feed could deadlock the request thread.** It was written from
316
+ the request's own thread before the output readers started, on the claim
317
+ that "the pipe holds a frame-sized feed". A child that echoes — `cat` with
318
+ 1.25 MiB or more on stdin — filled its stdout pipe, stopped reading, and
319
+ the feed blocked with the wait loop and its timeout queued behind it; the
320
+ host watchdog killed the transport eighteen seconds in. The feed now runs
321
+ on its own thread, after both readers are running.
322
+ - **Every FS frame took `fs_lock`, and the `ACK` followed the lock.** A
323
+ stat queued behind a 32 MiB write waited its full 408 ms. Only mutations
324
+ (`write`, `delete`, `move`, and a batch holding one) take the lock now, and
325
+ the `ACK` reports the dequeue.
326
+ - **One vanished entry failed a whole listing.** A directory under churn
327
+ (a build output directory) failed about a tenth to a third of its listings
328
+ with `notfound` while it existed; an entry whose `lstat` answers `ENOENT`
329
+ is skipped. The shell agent's `find` is tolerated the same way, for the one
330
+ diagnostic that names a vanished entry.
331
+ - **The timeout allowed 100 ms before `KILL`.** A command that cleans up on
332
+ `TERM` was killed first (exit 137). The deadline now takes the cancel
333
+ path's TERM-then-KILL grace.
334
+ - **`move` always copied the file whole.** 106 ms for 256 MiB, under the
335
+ lock. A same-filesystem move is now `rename(2)`, with
336
+ `renameat2(RENAME_NOREPLACE)` for the no-replace guard; `EXDEV` (and a
337
+ filesystem without the flag) falls back to the copy.
338
+ - **Orphan staging directories were never swept.** The shell agent swept its
339
+ own leftovers, under a name the native agent did not use. Both agents now
340
+ stage under `.<base>.<pid>.<token>.tmpdir`, and a write sweeps that target's
341
+ staging directories whose creator's pid is gone — a live pid, and the
342
+ agent's own, are left alone.
343
+
344
+ The packaged binaries (`agent/native/linux-<arch>/dsh-wsl-agent`) were rebuilt
345
+ from this source with the pinned toolchain (1.99.1). They were linked with the
346
+ toolchain's self-contained musl objects rather than by the CI job's
347
+ `musl-gcc`/zig linkers, which this machine does not have; both pass the full
348
+ suite, the aarch64 one under qemu-user, and the session-runtime probe.
349
+
302
350
  ## Why it was built
303
351
 
304
352
  Built in 0.10.0. The triggers that fired were the long-build/FS-serialization
@@ -110,6 +110,16 @@ export function confinedAgent({ distro, wslPath = "wsl.exe", policy, maskWindows
110
110
  let agent = confinedAgents.get(key);
111
111
  if (agent === undefined) {
112
112
  const linuxRoot = toLinuxPath(policy.workspaceRoot);
113
+ /** The root-creating checklist, run at most once per resident instance. */
114
+ let checklist;
115
+ const prepareRoot = () => {
116
+ checklist ??= runSpawnChecklist({ wslPath, distro, root: linuxRoot }).catch((error) => {
117
+ // A failed checklist is not a verdict: the next start retries it.
118
+ checklist = undefined;
119
+ throw error;
120
+ });
121
+ return checklist.then(() => undefined);
122
+ };
113
123
  agent = new WslAgent({
114
124
  distro,
115
125
  wslPath,
@@ -125,10 +135,11 @@ export function confinedAgent({ distro, wslPath = "wsl.exe", policy, maskWindows
125
135
  // bwrap refuses a missing bind source (WSL-305): on a freshly imported
126
136
  // distro the first write's workspace may not exist yet, and the resident
127
137
  // used to exit during its handshake with a bare code 1. Create the root
128
- // before the first spawn; every later start re-runs it harmlessly.
129
- prepare: policy.mode === "workspace-write"
130
- ? () => runSpawnChecklist({ wslPath, distro, root: linuxRoot }).then(() => undefined)
131
- : undefined,
138
+ // before the first spawn. The memo keeps a later revival from spending
139
+ // another `wsl.exe` round trip; the agent's own start path calls
140
+ // `prepare` on every revival, and the checklist's other facts cannot
141
+ // change under a running resident.
142
+ prepare: policy.mode === "workspace-write" ? prepareRoot : undefined,
132
143
  });
133
144
  confinedAgents.set(key, agent);
134
145
  }
@@ -23,6 +23,22 @@ export declare class AgentUnavailableError extends Error {
23
23
  */
24
24
  constructor(message: string);
25
25
  }
26
+ /**
27
+ * The resident was lost while this request was with it, so the request MAY
28
+ * have run. Still an {@link AgentUnavailableError} — the resident is out — so
29
+ * a caller whose request is read-only (the search and git handles, the picker)
30
+ * keeps its fallback and simply runs the request again. A caller whose request
31
+ * has effects must not: replaying it would run non-idempotent work twice, or
32
+ * report a create that actually succeeded as a refusal. The shell executor
33
+ * therefore lets this one propagate instead of retrying on the one-shot path,
34
+ * and the message tells the model to inspect the distro before retrying.
35
+ */
36
+ export declare class AgentRequestStateUnknownError extends AgentUnavailableError {
37
+ /**
38
+ * @param message - what was in flight, for the log.
39
+ */
40
+ constructor(message: string);
41
+ }
26
42
  /**
27
43
  * The request's workdir could not be entered inside the distro. Carries the
28
44
  * Linux path so a caller can synthesize the same diagnostic the one-shot
@@ -26,6 +26,25 @@ export class AgentUnavailableError extends Error {
26
26
  this.name = "AgentUnavailableError";
27
27
  }
28
28
  }
29
+ /**
30
+ * The resident was lost while this request was with it, so the request MAY
31
+ * have run. Still an {@link AgentUnavailableError} — the resident is out — so
32
+ * a caller whose request is read-only (the search and git handles, the picker)
33
+ * keeps its fallback and simply runs the request again. A caller whose request
34
+ * has effects must not: replaying it would run non-idempotent work twice, or
35
+ * report a create that actually succeeded as a refusal. The shell executor
36
+ * therefore lets this one propagate instead of retrying on the one-shot path,
37
+ * and the message tells the model to inspect the distro before retrying.
38
+ */
39
+ export class AgentRequestStateUnknownError extends AgentUnavailableError {
40
+ /**
41
+ * @param message - what was in flight, for the log.
42
+ */
43
+ constructor(message) {
44
+ super(message);
45
+ this.name = "AgentRequestStateUnknownError";
46
+ }
47
+ }
29
48
  /**
30
49
  * The request's workdir could not be entered inside the distro. Carries the
31
50
  * Linux path so a caller can synthesize the same diagnostic the one-shot
@@ -124,7 +124,7 @@ export interface AgentExecutionHandle {
124
124
  * @returns the execution handle (`status`, `exitCode`, `signal`, `observed`,
125
125
  * `done`, `readOutput`, `kill`, `result`).
126
126
  */
127
- export declare function agentExecutionHandle({ agent, cwd, argv, timeoutMs, maxOutputBytes, env, signal, onStarted }: {
127
+ export declare function agentExecutionHandle({ agent, cwd, argv, timeoutMs, maxOutputBytes, env, signal, onStarted, onSettled }: {
128
128
  /**
129
129
  * The {@link WslAgent}-like runner: `exec` accepting
130
130
  * `{cwd, argv, timeoutMs, env, signal}` and resolving `{exitCode, stdout, stderr}`;
@@ -157,5 +157,12 @@ export declare function agentExecutionHandle({ agent, cwd, argv, timeoutMs, maxO
157
157
  * Provider-facts hook, called synchronously before the handle can settle.
158
158
  */
159
159
  onStarted?: (proc: object) => void;
160
+ /**
161
+ * Settlement hook, called after the status, exit code and signal are
162
+ * stamped and before `done` resolves to anyone else — the point at which
163
+ * upstream's own handle calls its settlement hook. `error` is the failure
164
+ * `result()` rejects with, when there is one.
165
+ */
166
+ onSettled?: (proc: AgentExecutionHandle, error: unknown) => void;
160
167
  }): AgentExecutionHandle;
161
168
  export {};
package/lib/agent-exec.js CHANGED
@@ -54,7 +54,7 @@ function memoryReader(buffer) {
54
54
  * @returns the execution handle (`status`, `exitCode`, `signal`, `observed`,
55
55
  * `done`, `readOutput`, `kill`, `result`).
56
56
  */
57
- export function agentExecutionHandle({ agent, cwd, argv, timeoutMs = 0, maxOutputBytes = 0, env, signal, onStarted }) {
57
+ export function agentExecutionHandle({ agent, cwd, argv, timeoutMs = 0, maxOutputBytes = 0, env, signal, onStarted, onSettled }) {
58
58
  // Our own controller is the kill channel; the caller's signal races it.
59
59
  const controller = new AbortController();
60
60
  let timedOut = false;
@@ -140,6 +140,7 @@ export function agentExecutionHandle({ agent, cwd, argv, timeoutMs = 0, maxOutpu
140
140
  proc.status = exitOutcome.signal !== null || exitOutcome.exitCode === null ? "killed" : "completed";
141
141
  proc.exitCode = exitOutcome.exitCode;
142
142
  proc.signal = exitOutcome.signal;
143
+ onSettled?.(proc, settleError);
143
144
  }),
144
145
  readOutput() {
145
146
  const out = stdoutReader().readFrom(stdoutOffset);
@@ -7,6 +7,23 @@
7
7
  * port snapshot all queue on ONE agent per distro, and the per-distro startup
8
8
  * cost is paid once per process.
9
9
  *
10
+ * One instance per `(wslPath, distro)` for the life of the process, and never a
11
+ * second for that pair: every holder (the executor, the filesystem provider,
12
+ * the picker, the git and search handles, the doctor) addresses the same
13
+ * object, so the state a diagnosis reads is the state the file operations run
14
+ * on. The transport is part of the key because a row with a custom `wslPath`
15
+ * must not keep talking through the default executable. The instance owns
16
+ * its own recovery — one rebuild per death, then a bounded revival — and this
17
+ * module does not second-guess it by swapping in a fresh one, which used to
18
+ * reset that budget at the first death and, at the same time, retire the
19
+ * native entry for good.
20
+ *
21
+ * The ENTRY is chosen per start, not per process: the native binary when the
22
+ * backend allows it and it comes up, the shell script otherwise. The native
23
+ * entry is demoted only on evidence that it is the one at fault — it failed
24
+ * a start and the shell entry then started on the same distro — and only for
25
+ * a while, after which it is tried again.
26
+ *
10
27
  * This is a TypeScript source built to `lib/agent-shared.js`; edit THIS file
11
28
  * and run `pnpm run build` — the artifact under `lib/` is generated, and
12
29
  * `pnpm test` fails when it drifts.
@@ -14,14 +31,80 @@
14
31
  * @module dsh-plugin-wsl-env/agent-shared
15
32
  */
16
33
  import { WslAgent } from "./agent.js";
34
+ /**
35
+ * How long the native entry stays demoted once it failed a start that the
36
+ * shell entry then made on the same distro. A demotion is a verdict about
37
+ * the moment, not the process — a reinstalled or resynced binary, or a cache
38
+ * directory made executable, works without an app restart — so the entry is
39
+ * tried again after this long; a still-broken one costs its next start one
40
+ * failed round trip and is demoted again.
41
+ */
42
+ export declare const NATIVE_DEMOTION_MS = 300000;
43
+ /** What one distro's starts have said so far about its native entry. */
44
+ export interface NativeVerdict {
45
+ /** The native entry failed its last start; the shell entry's next start decides. */
46
+ suspect: boolean;
47
+ /** When a demotion ends, epoch ms; 0 while the entry is not demoted. */
48
+ demotedUntil: number;
49
+ }
50
+ /** @returns a verdict nothing has been said about yet. */
51
+ export declare function freshNativeVerdict(): NativeVerdict;
52
+ /**
53
+ * Whether a start may use the native entry. A suspicion says no: the next
54
+ * start is the shell entry's, and its outcome is what turns the suspicion
55
+ * into a verdict. A demotion says no until it ends.
56
+ *
57
+ * @param verdict - the distro's verdict.
58
+ * @param now - the current time, epoch ms.
59
+ * @returns true when the native entry may be tried.
60
+ */
61
+ export declare function nativeEntryAllowed(verdict: NativeVerdict, now: number): boolean;
62
+ /**
63
+ * Read one start's outcome into the verdict.
64
+ *
65
+ * A failed native start is a suspicion, not a verdict: a distro that is down
66
+ * fails both entries alike, and must not retire a healthy binary. The shell
67
+ * entry starting right after it is the evidence — same distro, one entry up
68
+ * and one down — and that is what demotes the native entry. A native start
69
+ * that succeeds clears both.
70
+ *
71
+ * @param verdict - the distro's verdict; updated in place.
72
+ * @param outcome - how the start ended, and with which entry.
73
+ * @param now - the current time, epoch ms.
74
+ */
75
+ export declare function recordStart(verdict: NativeVerdict, outcome: {
76
+ ok: boolean;
77
+ native: boolean;
78
+ }, now: number): void;
17
79
  /** The agent script as a host-side path, for factories that need both spellings. */
18
80
  export declare const agentScriptPath: string;
19
81
  /** The sha256 of the shipped agent script; every resident verifies its HELLO against it. */
20
82
  export declare const agentScriptDigest: string;
21
83
  /**
22
- * The shared agent for one distro, created on first use.
84
+ * The shared agent for one distro and transport: created on first use, and the
85
+ * same instance on every call after that — through deaths, revivals and a
86
+ * change of entry. Its own lifecycle is the recovery; a caller that finds it
87
+ * unavailable (`status().state === "dead"`) falls back for that call.
88
+ *
89
+ * The transport is part of the identity: a row pointed at a custom `wslPath`
90
+ * must not keep talking through the default executable, and a native entry
91
+ * staged through one transport cannot be assumed reachable through another.
23
92
  *
24
93
  * @param distro - the distro name.
94
+ * @param wslPath - the `wsl.exe` path the row configured.
25
95
  * @returns the shared agent.
26
96
  */
27
- export declare function sharedAgent(distro: string): WslAgent;
97
+ export declare function sharedAgent(distro: string, wslPath?: string): WslAgent;
98
+ /**
99
+ * Why the shared resident is not on the native entry though the backend asks
100
+ * for it, for a diagnosis: the entry is demoted, or it just failed a start.
101
+ * Undefined when neither is the case.
102
+ *
103
+ * @param distro - the distro name.
104
+ * @returns the reason, or undefined.
105
+ */
106
+ export declare function sharedAgentNativeNote(distro: string): string | undefined;
107
+ /**
108
+ * Forget every shared agent and every native verdict; tests only.
109
+ */
110
+ export declare function resetSharedAgents(): void;
@@ -7,6 +7,23 @@
7
7
  * port snapshot all queue on ONE agent per distro, and the per-distro startup
8
8
  * cost is paid once per process.
9
9
  *
10
+ * One instance per `(wslPath, distro)` for the life of the process, and never a
11
+ * second for that pair: every holder (the executor, the filesystem provider,
12
+ * the picker, the git and search handles, the doctor) addresses the same
13
+ * object, so the state a diagnosis reads is the state the file operations run
14
+ * on. The transport is part of the key because a row with a custom `wslPath`
15
+ * must not keep talking through the default executable. The instance owns
16
+ * its own recovery — one rebuild per death, then a bounded revival — and this
17
+ * module does not second-guess it by swapping in a fresh one, which used to
18
+ * reset that budget at the first death and, at the same time, retire the
19
+ * native entry for good.
20
+ *
21
+ * The ENTRY is chosen per start, not per process: the native binary when the
22
+ * backend allows it and it comes up, the shell script otherwise. The native
23
+ * entry is demoted only on evidence that it is the one at fault — it failed
24
+ * a start and the shell entry then started on the same distro — and only for
25
+ * a while, after which it is tried again.
26
+ *
10
27
  * This is a TypeScript source built to `lib/agent-shared.js`; edit THIS file
11
28
  * and run `pnpm run build` — the artifact under `lib/` is generated, and
12
29
  * `pnpm test` fails when it drifts.
@@ -19,56 +36,168 @@ import { readFileSync } from "node:fs";
19
36
  import { fileURLToPath } from "node:url";
20
37
  import { toLinuxPath } from "./paths.js";
21
38
  import { pinnedWindowsEnv, WslAgent } from "./agent.js";
22
- import { configuredAgentBackend, ensureNativeBackend, NATIVE_AGENT_ENV } from "./native-agent.js";
39
+ import { configuredAgentBackend, ensureNativeBackend } from "./native-agent.js";
23
40
  const AGENT_SCRIPT_PATH = fileURLToPath(new URL("../agent/wsl-agent.sh", import.meta.url));
24
- // The script the distro reads must be byte-identical to the copy this
25
- // package shipped: the deployed layout reads it from the /mnt/c mirror, and
26
- // the handshake digest is what catches a stale or half-synced runtime copy.
41
+ // The script the distro reads must be byte-identical to the copy this package
42
+ // shipped: the deployed layout reads it from the /mnt/c mirror, and the
43
+ // handshake digest is what catches a stale or half-synced runtime copy.
27
44
  // Both resident factories (plain and confined) pin it.
28
45
  const AGENT_SCRIPT_DIGEST = createHash("sha256").update(readFileSync(AGENT_SCRIPT_PATH)).digest("hex");
29
46
  const sharedAgents = new Map();
30
- // Distros where the native shared agent failed at runtime; the reads fail open
31
- // to the shell instead of retrying the same broken binary on every call.
32
- const nativeFailed = new Set();
47
+ /** Each distro's verdict on its native entry, created on its first report. */
48
+ const nativeVerdicts = new Map();
49
+ /**
50
+ * How long the native entry stays demoted once it failed a start that the
51
+ * shell entry then made on the same distro. A demotion is a verdict about
52
+ * the moment, not the process — a reinstalled or resynced binary, or a cache
53
+ * directory made executable, works without an app restart — so the entry is
54
+ * tried again after this long; a still-broken one costs its next start one
55
+ * failed round trip and is demoted again.
56
+ */
57
+ export const NATIVE_DEMOTION_MS = 300_000;
58
+ /** @returns a verdict nothing has been said about yet. */
59
+ export function freshNativeVerdict() {
60
+ return { suspect: false, demotedUntil: 0 };
61
+ }
62
+ /**
63
+ * Whether a start may use the native entry. A suspicion says no: the next
64
+ * start is the shell entry's, and its outcome is what turns the suspicion
65
+ * into a verdict. A demotion says no until it ends.
66
+ *
67
+ * @param verdict - the distro's verdict.
68
+ * @param now - the current time, epoch ms.
69
+ * @returns true when the native entry may be tried.
70
+ */
71
+ export function nativeEntryAllowed(verdict, now) {
72
+ if (verdict.suspect)
73
+ return false;
74
+ return verdict.demotedUntil <= now;
75
+ }
76
+ /**
77
+ * Read one start's outcome into the verdict.
78
+ *
79
+ * A failed native start is a suspicion, not a verdict: a distro that is down
80
+ * fails both entries alike, and must not retire a healthy binary. The shell
81
+ * entry starting right after it is the evidence — same distro, one entry up
82
+ * and one down — and that is what demotes the native entry. A native start
83
+ * that succeeds clears both.
84
+ *
85
+ * @param verdict - the distro's verdict; updated in place.
86
+ * @param outcome - how the start ended, and with which entry.
87
+ * @param now - the current time, epoch ms.
88
+ */
89
+ export function recordStart(verdict, outcome, now) {
90
+ if (outcome.ok) {
91
+ if (!outcome.native && verdict.suspect)
92
+ verdict.demotedUntil = now + NATIVE_DEMOTION_MS;
93
+ if (outcome.native || verdict.suspect)
94
+ verdict.suspect = false;
95
+ return;
96
+ }
97
+ if (outcome.native)
98
+ verdict.suspect = true;
99
+ }
33
100
  /** The agent script as a host-side path, for factories that need both spellings. */
34
101
  export const agentScriptPath = AGENT_SCRIPT_PATH;
35
102
  /** The sha256 of the shipped agent script; every resident verifies its HELLO against it. */
36
103
  export const agentScriptDigest = AGENT_SCRIPT_DIGEST;
37
104
  /**
38
- * The shared agent for one distro, created on first use.
105
+ * The distro's verdict.
106
+ *
107
+ * @param distro - the distro the resident serves.
108
+ * @returns the verdict, created on first use.
109
+ */
110
+ function verdictOf(distro) {
111
+ let verdict = nativeVerdicts.get(distro);
112
+ if (verdict === undefined)
113
+ nativeVerdicts.set(distro, (verdict = freshNativeVerdict()));
114
+ return verdict;
115
+ }
116
+ /**
117
+ * The entry one start of the shared resident uses: the native binary when the
118
+ * backend allows it, the verdict permits it and its preparation succeeds;
119
+ * nothing (the instance's own shell entry) otherwise.
120
+ *
121
+ * @param distro - the distro the resident serves.
122
+ * @param wslPath - the transport the row configured.
123
+ * @returns the native entry, or undefined for the shell entry.
124
+ */
125
+ async function prepareSharedEntry(distro, wslPath) {
126
+ if (configuredAgentBackend() === "shell")
127
+ return undefined;
128
+ // Not allowed means one of two things: the native entry just failed — this
129
+ // start finds out whether the distro is the problem or the binary is, by
130
+ // running the shell entry instead — or it is demoted.
131
+ if (!nativeEntryAllowed(verdictOf(distro), Date.now()))
132
+ return undefined;
133
+ const prepared = await ensureNativeBackend({ wslPath, distro, source: process.env.DSH_WSL_AGENT_NATIVE ?? "" });
134
+ if (prepared === undefined)
135
+ return undefined;
136
+ return {
137
+ scriptPath: prepared.path,
138
+ expectedDigest: prepared.digest,
139
+ signalable: false,
140
+ serialRequests: false,
141
+ spawnTransport: ({ wslPath, distro: target, argvPrefix }) => spawn(wslPath, ["-d", target, "--exec", ...argvPrefix, prepared.path], {
142
+ stdio: ["pipe", "pipe", "pipe"],
143
+ windowsHide: true,
144
+ env: pinnedWindowsEnv(process.env),
145
+ }),
146
+ };
147
+ }
148
+ /**
149
+ * The shared agent for one distro and transport: created on first use, and the
150
+ * same instance on every call after that — through deaths, revivals and a
151
+ * change of entry. Its own lifecycle is the recovery; a caller that finds it
152
+ * unavailable (`status().state === "dead"`) falls back for that call.
153
+ *
154
+ * The transport is part of the identity: a row pointed at a custom `wslPath`
155
+ * must not keep talking through the default executable, and a native entry
156
+ * staged through one transport cannot be assumed reachable through another.
39
157
  *
40
158
  * @param distro - the distro name.
159
+ * @param wslPath - the `wsl.exe` path the row configured.
41
160
  * @returns the shared agent.
42
161
  */
43
- export function sharedAgent(distro) {
44
- let agent = sharedAgents.get(distro);
45
- if (agent !== undefined && !agent.unavailable)
46
- return agent;
47
- if (agent !== undefined)
48
- nativeFailed.add(distro);
49
- agent = new WslAgent({
50
- distro,
51
- scriptPath: toLinuxPath(AGENT_SCRIPT_PATH),
52
- expectedDigest: AGENT_SCRIPT_DIGEST,
53
- prepare: async () => {
54
- if (configuredAgentBackend() === "shell" || nativeFailed.has(distro))
55
- return undefined;
56
- const prepared = await ensureNativeBackend({ wslPath: "wsl.exe", distro, source: process.env[NATIVE_AGENT_ENV] ?? "" });
57
- if (prepared === undefined)
58
- return undefined;
59
- return {
60
- scriptPath: prepared.path,
61
- expectedDigest: prepared.digest,
62
- signalable: false,
63
- serialRequests: false,
64
- spawnTransport: ({ wslPath, distro: target, argvPrefix }) => spawn(wslPath, ["-d", target, "--exec", ...argvPrefix, prepared.path], {
65
- stdio: ["pipe", "pipe", "pipe"],
66
- windowsHide: true,
67
- env: pinnedWindowsEnv(process.env),
68
- }),
69
- };
70
- },
71
- });
72
- sharedAgents.set(distro, agent);
162
+ export function sharedAgent(distro, wslPath = "wsl.exe") {
163
+ const key = `${wslPath}\u0000${distro}`;
164
+ let agent = sharedAgents.get(key);
165
+ if (agent === undefined) {
166
+ agent = new WslAgent({
167
+ distro,
168
+ wslPath,
169
+ scriptPath: toLinuxPath(AGENT_SCRIPT_PATH),
170
+ expectedDigest: AGENT_SCRIPT_DIGEST,
171
+ prepare: () => prepareSharedEntry(distro, wslPath),
172
+ onStart: (outcome) => recordStart(verdictOf(distro), outcome, Date.now()),
173
+ });
174
+ sharedAgents.set(key, agent);
175
+ }
73
176
  return agent;
74
177
  }
178
+ /**
179
+ * Why the shared resident is not on the native entry though the backend asks
180
+ * for it, for a diagnosis: the entry is demoted, or it just failed a start.
181
+ * Undefined when neither is the case.
182
+ *
183
+ * @param distro - the distro name.
184
+ * @returns the reason, or undefined.
185
+ */
186
+ export function sharedAgentNativeNote(distro) {
187
+ const verdict = nativeVerdicts.get(distro);
188
+ if (verdict === undefined)
189
+ return undefined;
190
+ if (verdict.demotedUntil > Date.now()) {
191
+ return `the native agent failed to start on this distro while the shell agent started, so reads run on the shell agent; it is tried again in ${Math.ceil((verdict.demotedUntil - Date.now()) / 1000)}s`;
192
+ }
193
+ if (verdict.suspect)
194
+ return "the native agent failed its last start on this distro; the shell agent is tried next";
195
+ return undefined;
196
+ }
197
+ /**
198
+ * Forget every shared agent and every native verdict; tests only.
199
+ */
200
+ export function resetSharedAgents() {
201
+ sharedAgents.clear();
202
+ nativeVerdicts.clear();
203
+ }
package/lib/agent.d.ts CHANGED
@@ -17,6 +17,13 @@
17
17
  * dead, calls reject with {@link AgentUnavailableError} — the executor's cue
18
18
  * to fall back to the one-shot `wsl.exe` path it shipped with, so the worst
19
19
  * case of the agent is "today's behaviour, plus one failed round trip".
20
+ * The cue is exact: a request the resident provably never took rejects with
21
+ * the plain class, while one that was with the resident when it was lost
22
+ * rejects with {@link AgentRequestStateUnknownError} — still unavailable,
23
+ * never safe to replay for a caller whose request has effects.
24
+ * `lastError` is the failure not yet recovered from: an accepted handshake
25
+ * clears it, so a resident that came back is diagnosed by what it is now,
26
+ * not by the crash it survived.
20
27
  * 2. **The in-distro timeout is the real one.** The EXEC frame carries the
21
28
  * timeout in whole seconds and the agent SIGTERMs the child itself, so a
22
29
  * timed-out command dies where it lives instead of leaving an orphan
@@ -156,7 +163,7 @@ interface AgentMetrics {
156
163
  inFlightMax: number;
157
164
  }
158
165
  /** The entry an async preparation may select before the first spawn. */
159
- interface WslAgentPrepared {
166
+ export interface WslAgentPrepared {
160
167
  /** The agent entrypoint (the shell script or the native cache path). */
161
168
  scriptPath: string;
162
169
  /** The HELLO digest to verify. */
@@ -288,12 +295,26 @@ export declare class WslAgent {
288
295
  revivalBackoffMs: number;
289
296
  /** The idle-shutdown timer. */
290
297
  idleTimer: NodeJS.Timeout | null;
298
+ /**
299
+ * When the resident last exchanged a frame with this host, in epoch ms; the
300
+ * construction time before the first one. A resident with no idle shutdown
301
+ * of its own (a session runtime) is still measured by it, so an owner can
302
+ * tell "quiet" from "abandoned".
303
+ */
304
+ lastActivityAt: number;
305
+ /** The frames waiting for the current resident's stdin; see {@link writeLines}. */
306
+ private writes;
291
307
  /** The last failure, for `unavailableReason` and log messages. */
292
308
  lastError: string;
293
309
  /** Cumulative request metrics; see {@link metrics}. */
294
310
  requestMetrics: AgentMetrics;
295
311
  /** The optional async preparation hook. */
296
312
  prepare: (() => Promise<WslAgentPrepared | undefined>) | undefined;
313
+ /** The optional start-outcome hook; see the constructor's `onStart`. */
314
+ onStart: ((outcome: {
315
+ ok: boolean;
316
+ native: boolean;
317
+ }) => void) | undefined;
297
318
  /**
298
319
  * @param config - the agent configuration.
299
320
  */
@@ -373,6 +394,17 @@ export declare class WslAgent {
373
394
  prepare?: () => Promise<WslAgentPrepared | undefined>;
374
395
  /** The first revival delay in ms; doubles per death. Tests shorten it. */
375
396
  revivalBackoffMs?: number;
397
+ /**
398
+ * Told how each start ended and which entry it used. `native` is true
399
+ * when the entry came from the async preparation (the native binary) and
400
+ * false for the instance's default entry (the shell script). A start that
401
+ * ends in a handshake failure or timeout is `ok: false`; a resident that
402
+ * dies after its handshake is not a start, and is not reported here.
403
+ */
404
+ onStart?: (outcome: {
405
+ ok: boolean;
406
+ native: boolean;
407
+ }) => void;
376
408
  });
377
409
  /**
378
410
  * Whether the agent is permanently out — the executor's fallback cue.
@@ -414,6 +446,8 @@ export declare class WslAgent {
414
446
  /**
415
447
  * Spawn the process and run the handshake.
416
448
  *
449
+ * @param native - whether this start runs the prepared entry rather than
450
+ * the instance's default one.
417
451
  * @returns resolved once the state is `ready`.
418
452
  */
419
453
  private beginStart;
@@ -429,10 +463,18 @@ export declare class WslAgent {
429
463
  */
430
464
  private wireAgentProcess;
431
465
  /**
432
- * The stdout line splitter: a bounded buffer instead of readline, which
433
- * accumulates an over-long line whole before anyone can object — exactly the
434
- * unbounded-capture hole. Protocol lines are ASCII by construction (ids,
435
- * numbers, base64), so chunk-boundary decoding is not a concern.
466
+ * The stdout line splitter: a list of the chunks of the line still
467
+ * arriving, instead of readline, which accumulates an over-long line whole
468
+ * before anyone can object — exactly the unbounded-capture hole. Protocol
469
+ * lines are ASCII by construction (ids, numbers, base64), so chunk-boundary
470
+ * decoding is not a concern.
471
+ *
472
+ * The chunks are searched, never a joined string. One growing string made
473
+ * this quadratic — every chunk copied the whole frame so far and scanned
474
+ * it again for the newline — and since this runs on the host's event loop,
475
+ * a 16 MiB read frame arriving in 64 KiB chunks held that loop for about
476
+ * 2.6 seconds. Now a chunk is searched once, and a line is joined once,
477
+ * when its newline has arrived.
436
478
  *
437
479
  * @param child - the transport to read.
438
480
  * @param current - whether this child is still the current generation.
@@ -549,6 +591,18 @@ export declare class WslAgent {
549
591
  * @param message - the reason, already stored as `lastError`.
550
592
  */
551
593
  private rejectAllPending;
594
+ /**
595
+ * The refusal an abandoned entry rejects with. An entry whose frame reached
596
+ * the resident may have run, and its refusal says so — that is what keeps a
597
+ * caller with a non-idempotent request from replaying it. An entry that was
598
+ * never written provably never ran, which is the plain out-of-service cue
599
+ * such a caller may act on.
600
+ *
601
+ * @param pending - the abandoned entry.
602
+ * @param reason - what happened to the resident.
603
+ * @returns the refusal.
604
+ */
605
+ private refusalFor;
552
606
  /**
553
607
  * Register one request's pending entry and write its frame: the shared
554
608
  * request machinery (abort, submission, the ACK-armed watchdog). The
@@ -793,7 +847,7 @@ export declare class WslAgent {
793
847
  * @param lines - the lines to write.
794
848
  */
795
849
  private writeLinesSafe;
796
- /** Restart the idle-shutdown countdown. */
850
+ /** Note the exchange, then restart the idle-shutdown countdown. */
797
851
  private rearmIdleTimer;
798
852
  /**
799
853
  * Detach an entry's timer and abort listener.