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
@@ -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.