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
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The bounded `doctor.mjs` subprocess collector shared by the two doctor
3
+ * runners: the in-app report (`doctor-report.ts`, the `wsl_doctor` tool) and
4
+ * the `/wsl-doctor` command. Both used to carry their own spawn, deadline and
5
+ * stream handling; the command's copy concatenated per-chunk
6
+ * `toString("utf8")` (splitting a multi-byte character at a chunk boundary),
7
+ * had no output cap, and checked the JSON prefix before the deadline. One
8
+ * collector now owns all three rules:
9
+ *
10
+ * - the deadline kills the child and settles the run as timed out;
11
+ * - stdout + stderr are capped, and crossing the cap kills the run;
12
+ * - streams are decoded with a `StringDecoder` (`setEncoding("utf8")`), so a
13
+ * chunk boundary never splits a code point;
14
+ * - a grandchild that inherited the pipes cannot hold the collector past the
15
+ * bounded drain window after the doctor itself exits.
16
+ *
17
+ * This is a TypeScript source built to `lib/doctor-process.js`; edit THIS file
18
+ * and run `pnpm run build` — the artifact under `lib/` is generated, and
19
+ * `pnpm test` fails when it drifts.
20
+ *
21
+ * @module dsh-plugin-wsl-env/doctor-process
22
+ */
23
+ import { spawn } from "node:child_process";
24
+ /**
25
+ * How much of one doctor stream the collector retains. The `--json` report is
26
+ * a few dozen KiB; the cap exists so a runaway child cannot grow the Host's
27
+ * memory without bound.
28
+ */
29
+ export const DOCTOR_OUTPUT_LIMIT_BYTES = 4 * 1024 * 1024;
30
+ /**
31
+ * How long after the doctor exits the collector waits for its pipes. A
32
+ * grandchild that inherited the pipes can keep them open forever; the report
33
+ * on stdout is complete once the doctor itself has exited, so the wait is
34
+ * bounded instead of following the pipes to EOF.
35
+ */
36
+ export const DOCTOR_DRAIN_GRACE_MS = 500;
37
+ /**
38
+ * Run the doctor CLI asynchronously and collect its streams.
39
+ *
40
+ * `spawnSync` would block the Host's event loop for the whole run — up to the
41
+ * deadline, with no way to cancel and every other tool stalled behind it — so
42
+ * the collector spawns, arms a deadline and the caller's abort signal, and
43
+ * settles on the child's exit plus a bounded drain window. A grandchild that
44
+ * inherits the pipes cannot hold the collector past that window.
45
+ *
46
+ * @param argv - the node argv (script path first).
47
+ * @param options - the child env, the deadline, and the caller's signal.
48
+ * @returns the finished run, including the spawn failure when it never started.
49
+ */
50
+ export function runDoctorProcess(argv, options) {
51
+ return new Promise((resolvePromise) => {
52
+ let stdout = "";
53
+ let stderr = "";
54
+ let timedOut = false;
55
+ let overLimit = false;
56
+ let spawnError;
57
+ let exit;
58
+ let drainTimer;
59
+ let settled = false;
60
+ const child = spawn(process.execPath, argv, {
61
+ stdio: ["ignore", "pipe", "pipe"],
62
+ windowsHide: true,
63
+ ...(options.env === undefined ? {} : { env: options.env }),
64
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
65
+ });
66
+ const settle = () => {
67
+ if (settled)
68
+ return;
69
+ settled = true;
70
+ clearTimeout(deadlineTimer);
71
+ if (drainTimer !== undefined)
72
+ clearTimeout(drainTimer);
73
+ resolvePromise({
74
+ stdout,
75
+ stderr,
76
+ status: exit?.status ?? null,
77
+ signal: exit?.signal ?? null,
78
+ timedOut,
79
+ overLimit,
80
+ ...(spawnError === undefined ? {} : { spawnError }),
81
+ });
82
+ };
83
+ const kill = () => {
84
+ try {
85
+ child.kill();
86
+ }
87
+ catch {
88
+ // An already-exited child: the exit handler settles the run.
89
+ }
90
+ };
91
+ const deadlineTimer = setTimeout(() => {
92
+ timedOut = true;
93
+ kill();
94
+ }, options.timeoutMs);
95
+ /**
96
+ * Append one already-decoded chunk under the shared cap.
97
+ *
98
+ * @param chunk - the decoded text.
99
+ * @param which - the stream it came from.
100
+ */
101
+ const capture = (chunk, which) => {
102
+ if (settled)
103
+ return;
104
+ if (which === "stdout")
105
+ stdout += chunk;
106
+ else
107
+ stderr += chunk;
108
+ if (stdout.length + stderr.length > DOCTOR_OUTPUT_LIMIT_BYTES) {
109
+ overLimit = true;
110
+ kill();
111
+ }
112
+ };
113
+ // A StringDecoder, so a multi-byte code point split across two chunks is
114
+ // reassembled instead of becoming two replacement characters.
115
+ child.stdout?.setEncoding("utf8");
116
+ child.stderr?.setEncoding("utf8");
117
+ child.stdout?.on("data", (chunk) => capture(chunk, "stdout"));
118
+ child.stderr?.on("data", (chunk) => capture(chunk, "stderr"));
119
+ child.on("error", (error) => {
120
+ // A spawn failure never reaches `exit`; an abort is reported with the
121
+ // same event, so the marker is normalized into a plain message.
122
+ spawnError = error.name === "AbortError"
123
+ ? new Error("doctor run aborted")
124
+ : error;
125
+ if (exit === undefined)
126
+ settle();
127
+ });
128
+ child.on("exit", (code, signalName) => {
129
+ exit = { status: code, signal: signalName ?? null };
130
+ // The report is complete at exit; give the pipes one bounded window to
131
+ // flush (a grandchild holding them must not stall the collector).
132
+ drainTimer = setTimeout(settle, DOCTOR_DRAIN_GRACE_MS);
133
+ });
134
+ child.on("close", () => {
135
+ if (exit !== undefined)
136
+ settle();
137
+ });
138
+ });
139
+ }
@@ -1,119 +1,15 @@
1
1
  import { sharedAgent } from "./agent-shared.js";
2
2
  import { mergeAutoPresetSeam, mergeLiveResidentStatus } from "./doctor-live.js";
3
+ import { nativeBackendFailure } from "./native-agent.js";
4
+ import { sharedAgentNativeNote } from "./agent-shared.js";
3
5
  import { withHostPeerVersions } from "./peer-versions.js";
4
- import { spawn } from "node:child_process";
6
+ import { DOCTOR_OUTPUT_LIMIT_BYTES, runDoctorProcess } from "./doctor-process.js";
5
7
  import { fileURLToPath } from "node:url";
6
8
  import { dirname, join } from "node:path";
7
9
  /** The doctor script this package ships, resolved from the compiled module. */
8
10
  const DOCTOR_SCRIPT = join(dirname(fileURLToPath(import.meta.url)), "..", "scripts", "doctor.mjs");
9
11
  /** How long the doctor subprocess may run before the collector kills it. */
10
12
  const DOCTOR_TIMEOUT_MS = 120_000;
11
- /**
12
- * How much of one doctor stream the collector retains. The `--json` report is
13
- * a few dozen KiB; the cap exists so a runaway child cannot grow the Host's
14
- * memory without bound.
15
- */
16
- const DOCTOR_OUTPUT_LIMIT_BYTES = 4 * 1024 * 1024;
17
- /**
18
- * How long after the doctor exits the collector waits for its pipes. A
19
- * grandchild that inherited the pipes can keep them open forever; the report
20
- * on stdout is complete once the doctor itself has exited, so the wait is
21
- * bounded instead of following the pipes to EOF.
22
- */
23
- const DOCTOR_DRAIN_GRACE_MS = 500;
24
- /**
25
- * Run the doctor CLI asynchronously and collect its streams.
26
- *
27
- * `spawnSync` would block the Host's event loop for the whole run — up to the
28
- * deadline, with no way to cancel and every other tool stalled behind it — so
29
- * the collector spawns, arms a deadline and the caller's abort signal, and
30
- * settles on the child's exit plus a bounded drain window. A grandchild that
31
- * inherits the pipes cannot hold the collector past that window.
32
- *
33
- * @param argv - the node argv (script path first).
34
- * @param options - the child env, the deadline, and the caller's signal.
35
- * @returns the finished run, including the spawn failure when it never started.
36
- */
37
- function runDoctorProcess(argv, options) {
38
- return new Promise((resolvePromise) => {
39
- let stdout = "";
40
- let stderr = "";
41
- let timedOut = false;
42
- let overLimit = false;
43
- let spawnError;
44
- let exit;
45
- let drainTimer;
46
- let settled = false;
47
- const child = spawn(process.execPath, argv, {
48
- stdio: ["ignore", "pipe", "pipe"],
49
- windowsHide: true,
50
- ...(options.env === undefined ? {} : { env: options.env }),
51
- ...(options.signal === undefined ? {} : { signal: options.signal }),
52
- });
53
- const settle = () => {
54
- if (settled)
55
- return;
56
- settled = true;
57
- clearTimeout(deadlineTimer);
58
- if (drainTimer !== undefined)
59
- clearTimeout(drainTimer);
60
- resolvePromise({
61
- stdout,
62
- stderr,
63
- status: exit?.status ?? null,
64
- signal: exit?.signal ?? null,
65
- timedOut,
66
- overLimit,
67
- ...(spawnError === undefined ? {} : { spawnError }),
68
- });
69
- };
70
- const kill = () => {
71
- try {
72
- child.kill();
73
- }
74
- catch {
75
- // An already-exited child: the exit handler settles the run.
76
- }
77
- };
78
- const deadlineTimer = setTimeout(() => {
79
- timedOut = true;
80
- kill();
81
- }, options.timeoutMs);
82
- const capture = (chunk, which) => {
83
- if (settled)
84
- return;
85
- if (which === "stdout")
86
- stdout += chunk;
87
- else
88
- stderr += chunk;
89
- if (stdout.length + stderr.length > DOCTOR_OUTPUT_LIMIT_BYTES) {
90
- overLimit = true;
91
- kill();
92
- }
93
- };
94
- child.stdout?.on("data", (chunk) => capture(chunk.toString("utf8"), "stdout"));
95
- child.stderr?.on("data", (chunk) => capture(chunk.toString("utf8"), "stderr"));
96
- child.on("error", (error) => {
97
- // A spawn failure never reaches `exit`; an abort is reported with the
98
- // same event, so the marker is normalized into a plain message.
99
- spawnError = error.name === "AbortError"
100
- ? new Error("doctor run aborted")
101
- : error;
102
- if (exit === undefined)
103
- settle();
104
- });
105
- child.on("exit", (code, signalName) => {
106
- exit = { status: code, signal: signalName ?? null };
107
- // The report is complete at exit; give the pipes one bounded window to
108
- // flush (a grandchild holding them must not stall the collector).
109
- drainTimer = setTimeout(settle, DOCTOR_DRAIN_GRACE_MS);
110
- });
111
- child.on("close", () => {
112
- if (exit !== undefined)
113
- settle();
114
- });
115
- });
116
- }
117
13
  /**
118
14
  * Collect the doctor's versioned JSON report and merge the live resident's
119
15
  * own lifecycle facts when this process holds one (WSL-313).
@@ -174,6 +70,12 @@ export async function doctorReport(distro, options) {
174
70
  : `exited with code ${run.status ?? run.signal ?? "unknown"}`);
175
71
  throw new Error(`doctor run failed: ${cause}${run.stderr.length > 0 ? ` — ${run.stderr.trim().slice(-400)}` : ""}`);
176
72
  }
177
- const status = options?.liveStatus ?? sharedAgent(distro).status();
178
- return mergeAutoPresetSeam(mergeLiveResidentStatus(report, status));
73
+ // The live resident is shared by (transport, distro); ask for the same pair
74
+ // the child is diagnosing, not the default executable.
75
+ const status = options?.liveStatus ?? sharedAgent(distro, options?.wslPath ?? "wsl.exe").status();
76
+ // The resident the operations run on is the one `sharedAgent` hands out —
77
+ // one instance per distro — and the note says why it is not on the native
78
+ // entry, when the backend asks for one and it is not.
79
+ const nativeNote = options?.liveStatus === undefined ? sharedAgentNativeNote(distro) ?? nativeBackendFailure(distro) : undefined;
80
+ return mergeAutoPresetSeam(mergeLiveResidentStatus(report, status, nativeNote === undefined ? {} : { nativeNote }));
179
81
  }
@@ -224,7 +224,7 @@ export class AgentSubstrate {
224
224
  throw new FsCodedError(`cannot overwrite existing "${target.displayPath}" without reading it first`, "FS_NOT_OBSERVED");
225
225
  }
226
226
  const before = existing !== null && Buffer.byteLength(content, "utf8") < this.diffBasisMaxBytes
227
- ? await this.fs.readTextForDiff(target, this.diffBasisMaxBytes, signal)
227
+ ? await this.fs.readTextForDiff(target, this.diffBasisMaxBytes, signal, existing)
228
228
  : null;
229
229
  await this.fs.writeFileAtomic(linuxPath, content, {
230
230
  mode: existing?.mode,
@@ -357,7 +357,7 @@ export class AgentSubstrate {
357
357
  if (expected && existing.version !== expected.version) {
358
358
  throw new FsCodedError(`cannot delete "${target.displayPath}": file changed since it was read`, "FS_STALE_VERSION");
359
359
  }
360
- const before = await this.fs.readTextForDiff(target, this.diffBasisMaxBytes, signal);
360
+ const before = await this.fs.readTextForDiff(target, this.diffBasisMaxBytes, signal, existing);
361
361
  await this.fs.removeFile(linuxPath, expected?.version, signal, mutationAgent);
362
362
  return { before };
363
363
  });
@@ -422,7 +422,7 @@ export class AgentSubstrate {
422
422
  content = restoreLineEndings(after, original.lineEndings);
423
423
  }
424
424
  const destinationBefore = destinationExisting !== null && Buffer.byteLength(content, "utf8") < this.diffBasisMaxBytes
425
- ? await this.fs.readTextForDiff(destination, this.diffBasisMaxBytes, signal)
425
+ ? await this.fs.readTextForDiff(destination, this.diffBasisMaxBytes, signal, destinationExisting)
426
426
  : null;
427
427
  // A hunk set transforms the text on the way, so the agent cannot copy
428
428
  // the source bytes: publish the patched content through the guarded
@@ -185,13 +185,32 @@ export declare class DistroFs {
185
185
  * The wire type is the entry's own (lstat): a symlink child then gets one
186
186
  * follow-up stat (its target's version and size) plus a realpath (its
187
187
  * identity), and a dangling symlink degrades to the peer's `other` with no
188
- * version — exactly what the peer's null follow-probe produces.
188
+ * version — exactly what the peer's null follow-probe produces. Those
189
+ * follow-ups are collected first and sent together, one batched frame per
190
+ * {@link LINKS_PER_BATCH} links: one at a time, a directory of 200 links
191
+ * cost 400 sequential round trips and about half a second to expand in the
192
+ * GUI file tree, where the same 400 operations in one frame took 5 ms.
189
193
  *
190
194
  * @param target - the resolved directory to list.
191
195
  * @param signal - aborts between children.
192
196
  * @returns the child rows, name-sorted.
193
197
  */
194
198
  listChildren(target: ResolvedTarget, signal?: AbortSignal): Promise<ChildRow[]>;
199
+ /**
200
+ * Give the listing's symlink children their targets' identity: the row's
201
+ * type, version and size from a following stat, and its target key from the
202
+ * realpath. A link whose target cannot be stat'ed — dangling, or a record
203
+ * that will not parse — keeps the dangling shape the caller seeded.
204
+ *
205
+ * A batch-capable resident gets every follow-up in one frame per
206
+ * {@link LINKS_PER_BATCH} links; anything else keeps the serial road of one
207
+ * stat and one realpath per link, which is the only one it can serve.
208
+ *
209
+ * @param links - the symlink children, each with the index of its row.
210
+ * @param entries - the rows, updated in place.
211
+ * @param signal - aborts between frames.
212
+ */
213
+ private followLinks;
195
214
  /**
196
215
  * Stat the target as a regular file or refuse, mirroring the peer's
197
216
  * `statRegularFile` messages.
@@ -205,9 +224,18 @@ export declare class DistroFs {
205
224
  /**
206
225
  * Read the whole file's bytes through windowed frames.
207
226
  *
227
+ * A window is never wider than one frame should be, cap or no cap: with a
228
+ * finite cap the first request used to ask for `maxBytes + 1` bytes at
229
+ * once, which cancelled the windowing — an edit's diff basis, bounded at
230
+ * 10 MiB, arrived as one multi-megabyte frame however the unbounded read
231
+ * was chunked.
232
+ *
208
233
  * @param target - the resolved file.
209
234
  * @param signal - the caller's cancellation.
210
235
  * @param maxBytes - inclusive byte cap on the complete content.
236
+ * @param first - the first window, already read by a caller that sent it
237
+ * ahead of the stat's answer ({@link readWholePipelined}); the loop then
238
+ * continues from its end.
211
239
  * @returns the file's bytes.
212
240
  */
213
241
  private readWhole;
@@ -229,15 +257,27 @@ export declare class DistroFs {
229
257
  */
230
258
  private statThenReadWhole;
231
259
  /**
232
- * The protocol-7 batch path for {@link readWholeText}: the stat and the
233
- * first read window ride ONE FSB frame — the GUI preview's dominant
234
- * shape — and further windows stay single reads.
260
+ * The protocol-7 road for {@link readWholeText}: the stat and the first
261
+ * read window go out together, each in its own frame, and neither answer
262
+ * is awaited until both are written.
263
+ *
264
+ * They used to share one batched frame. That put the window's bytes
265
+ * through base64 twice — once inside the batch's record and once around
266
+ * the whole record stream — for a read of 1 MiB: 40 ms against 25 ms for
267
+ * a plain read frame. Sending the two frames back to back keeps the one
268
+ * host round trip without it: a resident that serves requests concurrently
269
+ * runs them side by side, and a serial one already finds the second frame
270
+ * in its pipe when it finishes the first.
271
+ *
272
+ * The stat is still judged first. A target that is missing or not a regular
273
+ * file refuses through the stat's own failure, whatever the read answers —
274
+ * including a read that never answers, as one of a FIFO would not.
235
275
  *
236
276
  * @param target - the resolved file.
237
277
  * @param signal - aborts the read.
238
278
  * @returns the file's bytes.
239
279
  */
240
- private readWholeBatched;
280
+ private readWholePipelined;
241
281
  /**
242
282
  * Read a whole regular file as raw bytes, bounded by `maxBytes`.
243
283
  *
@@ -406,11 +446,22 @@ export declare class DistroFs {
406
446
  * one (binary, at/above the bound, vanished), so the write still succeeds
407
447
  * and presentation falls back to a whole-file diff.
408
448
  *
449
+ * `known` is the stat the caller already made for its own guard: the write
450
+ * paths read the target once for type, mode and version, and this basis
451
+ * used to stat it a second time on every overwrite. The basis is best
452
+ * effort, so judging the bound from that earlier row (and letting a raced
453
+ * read degrade to null) is within its contract.
454
+ *
409
455
  * @param target - the resolved file.
410
456
  * @param maxBytes - exclusive upper bound for the held basis.
411
457
  * @param signal - cancellation propagates, unlike I/O failure.
458
+ * @param known - the caller's already-fetched stat row, or null when the
459
+ * target was known absent.
412
460
  * @returns the LF-normalized text, or null.
413
461
  */
414
- readTextForDiff(target: ResolvedTarget, maxBytes: number, signal?: AbortSignal): Promise<string | null>;
462
+ readTextForDiff(target: ResolvedTarget, maxBytes: number, signal?: AbortSignal, known?: {
463
+ type: string;
464
+ size: number;
465
+ } | null): Promise<string | null>;
415
466
  }
416
467
  export {};