dsh-plugin-wsl-env 0.18.0 → 0.21.0

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 (123) hide show
  1. package/CHANGELOG.md +274 -0
  2. package/CONTRIBUTING.md +37 -5
  3. package/README.md +60 -5
  4. package/SUPPORT.md +3 -3
  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 +331 -11
  8. package/client.d.ts +5 -0
  9. package/client.js +98 -0
  10. package/cordis.patch.yml +66 -1
  11. package/docs/AGENT-PROTOCOL-V7.md +175 -0
  12. package/docs/API.md +25 -0
  13. package/docs/ARCHITECTURE.md +14 -1
  14. package/docs/CONFIGURATION.md +47 -6
  15. package/docs/CONFIGURATION.zh.md +20 -4
  16. package/docs/DIAGNOSTICS.md +83 -0
  17. package/docs/DIAGNOSTICS.zh.md +73 -0
  18. package/docs/LIMITATIONS.md +41 -4
  19. package/docs/LIMITATIONS.zh.md +27 -11
  20. package/docs/MIGRATION.md +4 -4
  21. package/docs/PEER-PARITY.md +50 -33
  22. package/docs/QUICKSTART.md +37 -4
  23. package/docs/QUICKSTART.zh.md +16 -1
  24. package/docs/README.zh.md +43 -4
  25. package/docs/RELEASING.md +4 -1
  26. package/docs/REQUIREMENTS.zh.md +3 -2
  27. package/docs/ROADMAP-1.0.md +75 -19
  28. package/docs/UPSTREAM-FILE-REFERENCE-SEAM.md +8 -1
  29. package/docs/UPSTREAM-OPEN-IN-APP.md +33 -0
  30. package/docs/UPSTREAM-SESSION-NOTICE.md +3 -1
  31. package/docs/UPSTREAM-TERMINAL-TITLE.md +3 -0
  32. package/docs/root-fs-routing.md +3 -3
  33. package/lib/agent-confined.js +4 -4
  34. package/lib/agent-errors.d.ts +1 -1
  35. package/lib/agent-errors.js +1 -1
  36. package/lib/agent-exec.d.ts +1 -1
  37. package/lib/agent-exec.js +1 -1
  38. package/lib/agent-protocol.d.ts +58 -8
  39. package/lib/agent-protocol.js +40 -7
  40. package/lib/agent-shared.d.ts +1 -1
  41. package/lib/agent-shared.js +1 -1
  42. package/lib/agent.d.ts +171 -1
  43. package/lib/agent.js +448 -288
  44. package/lib/auto-preset.d.ts +1 -1
  45. package/lib/auto-preset.js +1 -1
  46. package/lib/bwrap.d.ts +1 -1
  47. package/lib/bwrap.js +1 -1
  48. package/lib/client-host.d.ts +29 -0
  49. package/lib/client-host.js +29 -0
  50. package/lib/cwd-prompt-tool.d.ts +88 -0
  51. package/lib/cwd-prompt-tool.js +94 -0
  52. package/lib/cwd-prompt.d.ts +166 -0
  53. package/lib/cwd-prompt.js +203 -0
  54. package/lib/distro-route.d.ts +1 -1
  55. package/lib/distro-route.js +1 -1
  56. package/lib/doctor-live.d.ts +57 -0
  57. package/lib/doctor-live.js +38 -0
  58. package/lib/file-reference-wsl.d.ts +1 -1
  59. package/lib/file-reference-wsl.js +1 -1
  60. package/lib/fs-decisions.d.ts +1 -1
  61. package/lib/fs-decisions.js +1 -1
  62. package/lib/fs-routing.d.ts +1 -1
  63. package/lib/fs-routing.js +1 -1
  64. package/lib/fs-substrate.d.ts +90 -11
  65. package/lib/fs-substrate.js +202 -1
  66. package/lib/fs.d.ts +1 -1
  67. package/lib/fs.js +1 -1
  68. package/lib/fsio-agent.d.ts +128 -4
  69. package/lib/fsio-agent.js +224 -15
  70. package/lib/fsio-text.d.ts +1 -1
  71. package/lib/fsio-text.js +1 -1
  72. package/lib/git-exec.d.ts +1 -1
  73. package/lib/git-exec.js +1 -1
  74. package/lib/git-route.d.ts +1 -1
  75. package/lib/git-route.js +1 -1
  76. package/lib/index.d.ts +105 -30
  77. package/lib/index.js +272 -130
  78. package/lib/listing.d.ts +1 -1
  79. package/lib/listing.js +1 -1
  80. package/lib/messages.d.ts +157 -0
  81. package/lib/messages.js +199 -0
  82. package/lib/native-agent.d.ts +1 -1
  83. package/lib/native-agent.js +2 -2
  84. package/lib/paths.d.ts +6 -3
  85. package/lib/paths.js +4 -4
  86. package/lib/picker.d.ts +1 -1
  87. package/lib/picker.js +7 -7
  88. package/lib/ports.d.ts +1 -1
  89. package/lib/ports.js +1 -1
  90. package/lib/preflight.d.ts +25 -1
  91. package/lib/preflight.js +112 -12
  92. package/lib/sandbox-core.d.ts +1 -1
  93. package/lib/sandbox-core.js +9 -16
  94. package/lib/sandbox.d.ts +1 -1
  95. package/lib/sandbox.js +1 -1
  96. package/lib/search-exec.d.ts +1 -1
  97. package/lib/search-exec.js +1 -1
  98. package/lib/search-route.d.ts +1 -1
  99. package/lib/search-route.js +1 -1
  100. package/lib/session-runtime.d.ts +1 -1
  101. package/lib/session-runtime.js +2 -2
  102. package/lib/session-scope.d.ts +1 -1
  103. package/lib/session-scope.js +11 -6
  104. package/lib/shell-env.d.ts +26 -1
  105. package/lib/shell-env.js +57 -1
  106. package/lib/shell.d.ts +4 -2
  107. package/lib/shell.js +4 -2
  108. package/lib/subprocess.d.ts +1 -1
  109. package/lib/subprocess.js +2 -2
  110. package/lib/terminal-activity.d.ts +1 -1
  111. package/lib/terminal-activity.js +1 -1
  112. package/lib/terminal-route.d.ts +1 -1
  113. package/lib/terminal-route.js +1 -1
  114. package/lib/update-check.d.ts +197 -0
  115. package/lib/update-check.js +211 -0
  116. package/lib/watcher.d.ts +1 -1
  117. package/lib/watcher.js +1 -1
  118. package/lib/wsl-doctor-tool.d.ts +122 -0
  119. package/lib/wsl-doctor-tool.js +161 -0
  120. package/lib/wsl.d.ts +1 -31
  121. package/lib/wsl.js +1 -21
  122. package/package.json +55 -6
  123. package/scripts/doctor.mjs +1196 -166
package/lib/agent.js CHANGED
@@ -37,11 +37,11 @@
37
37
  * `pnpm run build` — the artifact under `lib/` is generated, and `pnpm test`
38
38
  * fails when it drifts.
39
39
  *
40
- * @module dsh-plugin-wsl/agent
40
+ * @module dsh-plugin-wsl-env/agent
41
41
  */
42
42
  import { spawn } from "node:child_process";
43
43
  import { AgentUnavailableError, BASH_TIMEOUT_REASON, CwdError, SpawnError } from "./agent-errors.js";
44
- import { AGENT_NAME, MAX_FRAME_BYTES, PROTOCOL_VERSION, encodeExecFrame, encodeFsFrame, encodeKill, parseAgentLine } from "./agent-protocol.js";
44
+ import { AGENT_NAME, MAX_FRAME_BYTES, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION, encodeExecFrame, encodeFsbFrame, encodeFsFrame, encodeKill, parseAgentLine } from "./agent-protocol.js";
45
45
  /**
46
46
  * A zeroed per-kind metrics record.
47
47
  * @returns the record.
@@ -194,6 +194,8 @@ export class WslAgent {
194
194
  this.revivalBackoffMs = config.revivalBackoffMs ?? DEFAULT_REVIVAL_BACKOFF_MS;
195
195
  this.idleTimer = null;
196
196
  this.lastError = "";
197
+ this.protocolVersion = 0;
198
+ this.caps = new Set();
197
199
  this.requestMetrics = emptyAgentMetrics();
198
200
  this.prepare = config.prepare;
199
201
  }
@@ -344,74 +346,97 @@ export class WslAgent {
344
346
  }
345
347
  };
346
348
  this.startSettler = settleStart;
347
- child.on("error", (error) => {
348
- if (!current())
349
- return;
350
- this.lastError = String(error);
351
- settleStart(error);
352
- });
353
- // The write side can hit EPIPE after the child exits — a failed
354
- // handshake followed by close(), or a scope stop. The failure is already
355
- // reflected in the state/pending requests; an unhandled stream error
356
- // would crash the host process instead.
357
- child.stdin?.on("error", () => { });
358
- // The resident's own stderr is the only diagnostic a handshake failure
359
- // carries (bwrap's refusal names the missing bind source, a libc
360
- // mismatch names itself); surface a bounded tail on the lastError
361
- // instead of leaving the caller a bare exit code.
362
- let hsErr = "";
363
- child.stderr?.on("data", (chunk) => {
364
- hsErr += String(chunk);
365
- });
366
- child.on("exit", (code, signalName) => {
367
- if (!current()) {
368
- // A stale child's exit: release its pipes, but never touch the
369
- // generation that replaced it.
370
- this.teardownStreams(child);
371
- return;
372
- }
373
- if (this.state === "starting") {
374
- this.lastError = `agent exited during handshake (code=${code} signal=${signalName ?? "none"})${hsErr ? ` stderr=${hsErr.trim().slice(-400)}` : ""}`;
375
- settleStart(new Error(this.lastError));
376
- }
377
- this.handleProcessExit(child, code, signalName);
378
- });
379
- // A bounded line splitter instead of readline: readline accumulates an
380
- // over-long line whole before anyone can object, which is exactly the
381
- // unbounded-capture hole. Protocol lines are ASCII by construction
382
- // (ids, numbers, base64), so chunk-boundary decoding is not a concern.
383
- let buffered = "";
384
- child.stdout.on("data", (chunk) => {
385
- if (!current())
386
- return;
387
- buffered += chunk.toString("utf8");
388
- for (;;) {
389
- const newline = buffered.indexOf("\n");
390
- if (newline === -1) {
391
- if (buffered.length > this.frameCapBytes) {
392
- this.lastError = `agent frame of ${buffered.length} bytes exceeded the ${this.frameCapBytes}-byte protocol cap`;
393
- buffered = "";
394
- child.kill();
395
- }
396
- return;
397
- }
398
- const line = buffered.slice(0, newline);
399
- buffered = buffered.slice(newline + 1);
400
- if (line.length > this.frameCapBytes) {
401
- this.lastError = `agent frame of ${line.length} bytes exceeded the ${this.frameCapBytes}-byte protocol cap`;
349
+ this.wireAgentProcess(child, current, settleStart, handshakeTimer);
350
+ });
351
+ }
352
+ /**
353
+ * The transport's failure and exit wiring, in the order the spawn attaches
354
+ * it: a spawn error, the stdin EPIPE guard, the handshake stderr tail, the
355
+ * exit handler, the stdout reader, then the diagnostic stderr reader.
356
+ *
357
+ * @param child - the freshly spawned transport.
358
+ * @param current - whether this child is still the current generation.
359
+ * @param settleStart - the handshake settler.
360
+ * @param handshakeTimer - the handshake watchdog.
361
+ */
362
+ wireAgentProcess(child, current, settleStart, handshakeTimer) {
363
+ child.on("error", (error) => {
364
+ if (!current())
365
+ return;
366
+ this.lastError = String(error);
367
+ settleStart(error);
368
+ });
369
+ // The write side can hit EPIPE after the child exits — a failed
370
+ // handshake followed by close(), or a scope stop. The failure is already
371
+ // reflected in the state/pending requests; an unhandled stream error
372
+ // would crash the host process instead.
373
+ child.stdin?.on("error", () => { });
374
+ // The resident's own stderr is the only diagnostic a handshake failure
375
+ // carries (bwrap's refusal names the missing bind source, a libc
376
+ // mismatch names itself); surface a bounded tail on the lastError
377
+ // instead of leaving the caller a bare exit code.
378
+ let hsErr = "";
379
+ child.stderr?.on("data", (chunk) => {
380
+ hsErr += String(chunk);
381
+ });
382
+ child.on("exit", (code, signalName) => {
383
+ if (!current()) {
384
+ // A stale child's exit: release its pipes, but never touch the
385
+ // generation that replaced it.
386
+ this.teardownStreams(child);
387
+ return;
388
+ }
389
+ if (this.state === "starting") {
390
+ this.lastError = `agent exited during handshake (code=${code} signal=${signalName ?? "none"})${hsErr ? ` stderr=${hsErr.trim().slice(-400)}` : ""}`;
391
+ settleStart(new Error(this.lastError));
392
+ }
393
+ this.handleProcessExit(child, code, signalName);
394
+ });
395
+ this.readAgentOutput(child, current, settleStart, handshakeTimer);
396
+ child.stderr?.on("data", (chunk) => {
397
+ if (!current())
398
+ return;
399
+ // Diagnostics only; `wsl.exe` and the shell chatter here on failure.
400
+ this.lastError = String(chunk).trim().slice(0, 2000) || this.lastError;
401
+ });
402
+ }
403
+ /**
404
+ * The stdout line splitter: a bounded buffer instead of readline, which
405
+ * accumulates an over-long line whole before anyone can object — exactly the
406
+ * unbounded-capture hole. Protocol lines are ASCII by construction (ids,
407
+ * numbers, base64), so chunk-boundary decoding is not a concern.
408
+ *
409
+ * @param child - the transport to read.
410
+ * @param current - whether this child is still the current generation.
411
+ * @param settleStart - the handshake settler.
412
+ * @param handshakeTimer - the handshake watchdog.
413
+ */
414
+ readAgentOutput(child, current, settleStart, handshakeTimer) {
415
+ let buffered = "";
416
+ child.stdout.on("data", (chunk) => {
417
+ if (!current())
418
+ return;
419
+ buffered += chunk.toString("utf8");
420
+ for (;;) {
421
+ const newline = buffered.indexOf("\n");
422
+ if (newline === -1) {
423
+ if (buffered.length > this.frameCapBytes) {
424
+ this.lastError = `agent frame of ${buffered.length} bytes exceeded the ${this.frameCapBytes}-byte protocol cap`;
402
425
  buffered = "";
403
426
  child.kill();
404
- return;
405
427
  }
406
- this.handleLine(line, settleStart, handshakeTimer);
428
+ return;
407
429
  }
408
- });
409
- child.stderr?.on("data", (chunk) => {
410
- if (!current())
430
+ const line = buffered.slice(0, newline);
431
+ buffered = buffered.slice(newline + 1);
432
+ if (line.length > this.frameCapBytes) {
433
+ this.lastError = `agent frame of ${line.length} bytes exceeded the ${this.frameCapBytes}-byte protocol cap`;
434
+ buffered = "";
435
+ child.kill();
411
436
  return;
412
- // Diagnostics only; `wsl.exe` and the shell chatter here on failure.
413
- this.lastError = String(chunk).trim().slice(0, 2000) || this.lastError;
414
- });
437
+ }
438
+ this.handleLine(line, settleStart, handshakeTimer);
439
+ }
415
440
  });
416
441
  }
417
442
  /**
@@ -424,98 +449,161 @@ export class WslAgent {
424
449
  handleLine(line, settleStart, handshakeTimer) {
425
450
  const message = parseAgentLine(line);
426
451
  switch (message.type) {
427
- case "hello": {
428
- if (message.name !== AGENT_NAME || message.version !== PROTOCOL_VERSION) {
429
- // Settle BEFORE killing: the exit event must not overwrite the real
430
- // reason with the generic handshake message (the fake transports
431
- // emit exit synchronously inside kill(); a real wsl.exe races it).
432
- this.lastError = `agent handshake mismatch: got ${message.name}@${message.version}, want ${AGENT_NAME}@${PROTOCOL_VERSION}`;
433
- settleStart(new Error(this.lastError));
434
- this.process?.kill();
435
- return;
436
- }
437
- if (this.expectedDigest !== undefined && message.digest !== this.expectedDigest) {
438
- // The script is read in place from the distro-visible path — in the
439
- // deployed layout a /mnt/c mirror — so a digest that differs from
440
- // the copy this package shipped means the runtime copy is stale,
441
- // half-synced, or edited. Fail closed with the fix in the message.
442
- this.lastError = `agent digest mismatch: the file the distro read at ${this.scriptPath} hashes to ${message.digest || "(nothing)"}, but this package shipped ${this.expectedDigest} — resync the runtime copy (npm run sync:windows) or reinstall the plugin`;
443
- settleStart(new Error(this.lastError));
444
- this.process?.kill();
445
- return;
446
- }
447
- clearTimeout(handshakeTimer);
448
- this.agentPid = message.pid;
449
- settleStart();
450
- break;
451
- }
452
- case "ack": {
453
- // Dequeue signal: start this request's own budget clock NOW. Armed
454
- // here instead of at submission, a queued request can no longer time
455
- // out on a queue it never chose to join — and its watchdog can never
456
- // kill the shared transport for a stall that was never its own. A
457
- // request cancelled while it was queued is killed only now, when it is
458
- // the one running.
459
- const pending = this.pending.get(message.id);
460
- if (pending) {
461
- pending.started = true;
462
- this.lastAckedSeq = pending.seq;
463
- this.recordAck(pending);
464
- if (pending.cancelled)
465
- this.armCancelSignal(pending);
466
- pending.armWatchdog?.();
467
- }
468
- break;
469
- }
470
- case "result": {
471
- const pending = this.pending.get(message.id);
472
- if (!pending)
473
- break; // answered after its caller gave up — noise
474
- pending.answered = true;
475
- this.clearPending(pending);
476
- this.pending.delete(message.id);
477
- this.rearmIdleTimer();
478
- this.dispatchQueued();
479
- // A cancelled request keeps its entry only until this answer arrives.
480
- if (pending.settled)
481
- break;
482
- pending.settled = true;
483
- pending.resolve({ exitCode: message.exitCode, stdout: message.stdout, stderr: message.stderr, truncated: message.truncated });
484
- break;
485
- }
486
- case "agentError": {
487
- const pending = this.pending.get(message.id);
488
- if (!pending)
489
- break;
490
- pending.answered = true;
491
- this.clearPending(pending);
492
- this.pending.delete(message.id);
493
- this.rearmIdleTimer();
494
- this.dispatchQueued();
495
- if (pending.settled)
496
- break;
497
- pending.settled = true;
498
- // A cwd rejection is the command's own failure, not the agent's — it
499
- // becomes a CwdError so the execution layer can report it exactly like
500
- // the one-shot path's relay text. A `spawn` rejection is the same
501
- // class of failure on the native agent (it cannot distinguish a
502
- // missing workdir), so it gets its own class and the executor retries
503
- // it one-shot.
504
- if (message.reason === "cwd") {
505
- pending.reject(new CwdError(message.message));
506
- }
507
- else if (message.reason === "spawn") {
508
- pending.reject(new SpawnError(message.message));
509
- }
510
- else {
511
- pending.reject(new AgentUnavailableError(`agent rejected request ${message.id} (${message.reason}): ${message.message}`));
512
- }
513
- break;
514
- }
452
+ case "hello":
453
+ this.acceptHandshake(message, settleStart, handshakeTimer);
454
+ return;
455
+ case "ack":
456
+ this.acceptAck(message);
457
+ return;
458
+ case "result":
459
+ this.settleResult(message);
460
+ return;
461
+ case "fsError":
462
+ this.settleFsError(message);
463
+ return;
464
+ case "agentError":
465
+ this.settleAgentError(message);
466
+ return;
515
467
  default:
516
468
  // Garbage after the handshake is logged and dropped: a late RES for an
517
469
  // abandoned request is expected noise, not a broken pipe.
518
- break;
470
+ return;
471
+ }
472
+ }
473
+ /**
474
+ * The agent named itself. A refusal settles BEFORE killing: the exit event
475
+ * must not overwrite the real reason with the generic handshake message (the
476
+ * fake transports emit exit synchronously inside kill(); a real wsl.exe races
477
+ * it).
478
+ *
479
+ * @param message - the agent's HELLO.
480
+ * @param settleStart - the handshake settler.
481
+ * @param handshakeTimer - the handshake watchdog.
482
+ */
483
+ acceptHandshake(message, settleStart, handshakeTimer) {
484
+ const refusal = this.handshakeRefusal(message);
485
+ if (refusal !== undefined) {
486
+ this.lastError = refusal;
487
+ settleStart(new Error(refusal));
488
+ this.process?.kill();
489
+ return;
490
+ }
491
+ clearTimeout(handshakeTimer);
492
+ this.agentPid = message.pid;
493
+ this.protocolVersion = message.version;
494
+ this.caps = new Set(message.caps ?? []);
495
+ settleStart();
496
+ }
497
+ /**
498
+ * Why this HELLO is refused, or undefined when it is accepted: the name and
499
+ * version window first, then the digest of the script the distro actually
500
+ * read.
501
+ *
502
+ * @param message - the agent's HELLO.
503
+ * @returns the refusal reason, or undefined when the handshake is accepted.
504
+ */
505
+ handshakeRefusal(message) {
506
+ if (message.name !== AGENT_NAME || message.version < MIN_PROTOCOL_VERSION || message.version > PROTOCOL_VERSION) {
507
+ return `agent handshake mismatch: got ${message.name}@${message.version}, want ${AGENT_NAME}@${MIN_PROTOCOL_VERSION}..${PROTOCOL_VERSION}`;
508
+ }
509
+ if (this.expectedDigest !== undefined && message.digest !== this.expectedDigest) {
510
+ // The script is read in place from the distro-visible path — in the
511
+ // deployed layout a /mnt/c mirror — so a digest that differs from the
512
+ // copy this package shipped means the runtime copy is stale, half-synced,
513
+ // or edited. Fail closed with the fix in the message.
514
+ return `agent digest mismatch: the file the distro read at ${this.scriptPath} hashes to ${message.digest || "(nothing)"}, but this package shipped ${this.expectedDigest} — resync the runtime copy (npm run sync:windows) or reinstall the plugin`;
515
+ }
516
+ return undefined;
517
+ }
518
+ /**
519
+ * The agent dequeued this request: start its own budget clock NOW. Armed
520
+ * here instead of at submission, a queued request can no longer time out on
521
+ * a queue it never chose to join — and its watchdog can never kill the
522
+ * shared transport for a stall that was never its own. A request cancelled
523
+ * while it was queued is killed only now, when it is the one running.
524
+ *
525
+ * @param message - the agent's ACK.
526
+ */
527
+ acceptAck(message) {
528
+ const pending = this.pending.get(message.id);
529
+ if (pending === undefined)
530
+ return;
531
+ pending.started = true;
532
+ this.lastAckedSeq = pending.seq;
533
+ this.recordAck(pending);
534
+ if (pending.cancelled)
535
+ this.armCancelSignal(pending);
536
+ pending.armWatchdog?.();
537
+ }
538
+ /**
539
+ * Take the entry an answer settles, running the bookkeeping every answer
540
+ * shares: mark it answered, release its timers, drop it from the map, and
541
+ * move the queue on. An answer for an entry the caller already gave up on is
542
+ * noise: it cleans up and settles nothing.
543
+ *
544
+ * @param id - the request id the answer names.
545
+ * @returns the entry to settle, or undefined when there is nothing to settle.
546
+ */
547
+ takeAnswered(id) {
548
+ const pending = this.pending.get(id);
549
+ if (pending === undefined)
550
+ return undefined; // answered after its caller gave up — noise
551
+ pending.answered = true;
552
+ this.clearPending(pending);
553
+ this.pending.delete(id);
554
+ this.rearmIdleTimer();
555
+ this.dispatchQueued();
556
+ return pending.settled ? undefined : pending;
557
+ }
558
+ /**
559
+ * Settle a normal answer. A cancelled request keeps its entry only until this
560
+ * answer arrives.
561
+ *
562
+ * @param message - the agent's RES.
563
+ */
564
+ settleResult(message) {
565
+ const pending = this.takeAnswered(message.id);
566
+ if (pending === undefined)
567
+ return;
568
+ pending.settled = true;
569
+ pending.resolve({ exitCode: message.exitCode, stdout: message.stdout, stderr: message.stderr, truncated: message.truncated });
570
+ }
571
+ /**
572
+ * Protocol 7's structured FS refusal: settle the pending FS request with the
573
+ * reason preserved, so the adapter maps the code directly instead of sniffing
574
+ * a synthesized stderr line.
575
+ *
576
+ * @param message - the agent's FSERR.
577
+ */
578
+ settleFsError(message) {
579
+ const pending = this.takeAnswered(message.id);
580
+ if (pending === undefined)
581
+ return;
582
+ pending.settled = true;
583
+ pending.resolve({ exitCode: 1, stdout: Buffer.alloc(0), stderr: Buffer.from(message.message), truncated: { stdout: false, stderr: false }, reason: message.reason });
584
+ }
585
+ /**
586
+ * A refused request. A cwd rejection is the command's own failure, not the
587
+ * agent's — it becomes a CwdError so the execution layer can report it
588
+ * exactly like the one-shot path's relay text. A `spawn` rejection is the
589
+ * same class of failure on the native agent (it cannot distinguish a missing
590
+ * workdir), so it gets its own class and the executor retries it one-shot.
591
+ *
592
+ * @param message - the agent's ERR.
593
+ */
594
+ settleAgentError(message) {
595
+ const pending = this.takeAnswered(message.id);
596
+ if (pending === undefined)
597
+ return;
598
+ pending.settled = true;
599
+ if (message.reason === "cwd") {
600
+ pending.reject(new CwdError(message.message));
601
+ }
602
+ else if (message.reason === "spawn") {
603
+ pending.reject(new SpawnError(message.message));
604
+ }
605
+ else {
606
+ pending.reject(new AgentUnavailableError(`agent rejected request ${message.id} (${message.reason}): ${message.message}`));
519
607
  }
520
608
  }
521
609
  /**
@@ -537,95 +625,121 @@ export class WslAgent {
537
625
  this.state = "idle";
538
626
  return;
539
627
  }
540
- if (!this.rebuildUsed) {
541
- this.rebuildUsed = true;
542
- this.lastError = `agent exited unexpectedly (code=${code} signal=${signalName ?? "none"}); rebuilding once`;
543
- this.state = "idle";
544
- this.startPromise = null;
545
- const carrying = [...this.pending.values()];
546
- this.pending.clear();
547
- // Only provably read-only FS requests ride the rebuild: whatever their
548
- // first execution did, it changed nothing. A command or a write that was
549
- // in flight has UNKNOWN state — replaying it would run non-idempotent
550
- // work a second time, or report a guarded create that actually
551
- // succeeded as a refusal — so it fails with that fact instead. A stale
552
- // watchdog must not survive either: its closure kills `this.process`,
553
- // which after the rebuild is the NEW transport.
554
- const relayable = [];
555
- for (const pending of carrying) {
556
- if (pending.signal?.aborted) {
557
- // Already rejected to its caller by the abort listener; do not
558
- // resurrect it on the rebuilt agent.
559
- this.clearPending(pending);
628
+ if (this.rebuildUsed) {
629
+ this.lastError = `agent exited again (code=${code} signal=${signalName ?? "none"})`;
630
+ this.markDead();
631
+ this.rejectAllPending(this.lastError);
632
+ return;
633
+ }
634
+ this.rebuildUsed = true;
635
+ this.lastError = `agent exited unexpectedly (code=${code} signal=${signalName ?? "none"}); rebuilding once`;
636
+ this.state = "idle";
637
+ this.startPromise = null;
638
+ const carrying = [...this.pending.values()];
639
+ this.pending.clear();
640
+ this.relayOverRebuild(this.partitionForRebuild(carrying));
641
+ }
642
+ /**
643
+ * Sort the requests a dead transport left behind into the three fates the
644
+ * one rebuild allows. Only provably read-only FS requests ride it: whatever
645
+ * their first execution did, it changed nothing. A command or a write that
646
+ * was in flight has UNKNOWN state — replaying it would run non-idempotent
647
+ * work a second time, or report a guarded create that actually succeeded as a
648
+ * refusal — so it fails with that fact instead. An aborted or unsent entry
649
+ * was already answered, or never ran, and settles locally.
650
+ *
651
+ * @param carrying - the entries taken off the map before the rebuild.
652
+ * @returns the entries that ride the rebuild.
653
+ */
654
+ partitionForRebuild(carrying) {
655
+ const relayable = [];
656
+ for (const pending of carrying) {
657
+ if (pending.signal?.aborted) {
658
+ // Already rejected to its caller by the abort listener; do not
659
+ // resurrect it on the rebuilt agent.
660
+ this.clearPending(pending);
661
+ continue;
662
+ }
663
+ if (!pending.sent) {
664
+ this.clearPending(pending);
665
+ if (pending.settled)
560
666
  continue;
561
- }
562
- if (!pending.sent) {
563
- this.clearPending(pending);
564
- if (pending.settled)
565
- continue;
566
- pending.settled = true;
567
- pending.reject(new AgentUnavailableError(`agent exited before request ${pending.id} was sent; it never ran`));
568
- }
569
- else if (isReplayableFrame(pending.lines)) {
570
- if (pending.watchdog) {
571
- clearTimeout(pending.watchdog);
572
- pending.watchdog = null;
573
- }
574
- relayable.push(pending);
575
- }
576
- else {
577
- this.clearPending(pending);
578
- if (pending.settled)
579
- continue;
580
- pending.settled = true;
581
- pending.reject(new AgentUnavailableError(`agent exited while request ${pending.id} was in flight; its state is unknown — inspect the distro before retrying`));
582
- }
667
+ pending.settled = true;
668
+ pending.reject(new AgentUnavailableError(`agent exited before request ${pending.id} was sent; it never ran`));
583
669
  }
584
- this.start()
585
- .then(() => {
586
- for (const pending of relayable) {
587
- if (pending.settled || pending.signal?.aborted)
588
- continue;
589
- const id = `r${this.nextRequestId++}`;
590
- pending.id = id;
591
- pending.seq = Number(id.slice(1));
592
- pending.lines = relabelFrame(pending.lines, id);
593
- pending.sent = false;
594
- pending.started = false;
595
- this.pending.set(id, pending);
596
- // The rebuilt transport can itself be gone by now; a frame that
597
- // cannot be written must fail its caller, not strand the entry.
598
- if (!this.serialRequests && !this.sendPending(pending)) {
599
- this.clearPending(pending);
600
- this.pending.delete(id);
601
- if (pending.settled)
602
- continue;
603
- pending.settled = true;
604
- pending.reject(new AgentUnavailableError(`agent exited before request ${id} could be re-sent; its state is unknown`));
605
- }
670
+ else if (isReplayableFrame(pending.lines)) {
671
+ if (pending.watchdog) {
672
+ clearTimeout(pending.watchdog);
673
+ pending.watchdog = null;
606
674
  }
607
- this.dispatchQueued();
608
- })
609
- .catch((error) => {
610
- for (const pending of relayable) {
675
+ relayable.push(pending);
676
+ }
677
+ else {
678
+ this.clearPending(pending);
679
+ if (pending.settled)
680
+ continue;
681
+ pending.settled = true;
682
+ pending.reject(new AgentUnavailableError(`agent exited while request ${pending.id} was in flight; its state is unknown — inspect the distro before retrying`));
683
+ }
684
+ }
685
+ return relayable;
686
+ }
687
+ /**
688
+ * Start the rebuild and hand it the replayable requests under fresh ids.
689
+ * A stale watchdog must not survive the rebuild: its closure kills
690
+ * `this.process`, which is by then the NEW transport.
691
+ *
692
+ * @param relayable - the requests `partitionForRebuild` cleared to replay.
693
+ */
694
+ relayOverRebuild(relayable) {
695
+ this.start()
696
+ .then(() => {
697
+ for (const pending of relayable) {
698
+ if (pending.settled || pending.signal?.aborted)
699
+ continue;
700
+ const id = `r${this.nextRequestId++}`;
701
+ pending.id = id;
702
+ pending.seq = Number(id.slice(1));
703
+ pending.lines = relabelFrame(pending.lines, id);
704
+ pending.sent = false;
705
+ pending.started = false;
706
+ this.pending.set(id, pending);
707
+ // The rebuilt transport can itself be gone by now; a frame that
708
+ // cannot be written must fail its caller, not strand the entry.
709
+ if (!this.serialRequests && !this.sendPending(pending)) {
611
710
  this.clearPending(pending);
711
+ this.pending.delete(id);
612
712
  if (pending.settled)
613
713
  continue;
614
714
  pending.settled = true;
615
- pending.reject(error);
715
+ pending.reject(new AgentUnavailableError(`agent exited before request ${id} could be re-sent; its state is unknown`));
616
716
  }
617
- this.markDead();
618
- });
619
- return;
620
- }
621
- this.lastError = `agent exited again (code=${code} signal=${signalName ?? "none"})`;
622
- this.markDead();
717
+ }
718
+ this.dispatchQueued();
719
+ })
720
+ .catch((error) => {
721
+ for (const pending of relayable) {
722
+ this.clearPending(pending);
723
+ if (pending.settled)
724
+ continue;
725
+ pending.settled = true;
726
+ pending.reject(error);
727
+ }
728
+ this.markDead();
729
+ });
730
+ }
731
+ /**
732
+ * Fail every entry still on the map: the second death is permanent.
733
+ *
734
+ * @param message - the reason, already stored as `lastError`.
735
+ */
736
+ rejectAllPending(message) {
623
737
  for (const pending of this.pending.values()) {
624
738
  this.clearPending(pending);
625
739
  if (pending.settled)
626
740
  continue;
627
741
  pending.settled = true;
628
- pending.reject(new AgentUnavailableError(this.lastError));
742
+ pending.reject(new AgentUnavailableError(message));
629
743
  }
630
744
  this.pending.clear();
631
745
  }
@@ -639,12 +753,51 @@ export class WslAgent {
639
753
  *
640
754
  * @param request - the request to register.
641
755
  */
642
- track({ id, kind = "exec", lines, resolve, reject, timeoutMs, signal }) {
756
+ track(request) {
757
+ const { id, kind = "exec", signal } = request;
643
758
  if (this.pending.size >= this.maxPending) {
644
759
  this.noteRejected(kind);
645
- reject(new Error(`the resident agent has ${this.pending.size} requests in flight (max ${this.maxPending}); retry when the queue drains`));
760
+ request.reject(new Error(`the resident agent has ${this.pending.size} requests in flight (max ${this.maxPending}); retry when the queue drains`));
761
+ return;
762
+ }
763
+ const pending = this.newPendingRequest(request, kind);
764
+ this.pending.set(id, pending);
765
+ this.requestMetrics.inFlightMax = Math.max(this.requestMetrics.inFlightMax, this.pending.size);
766
+ if (signal) {
767
+ if (signal.aborted) {
768
+ this.pending.delete(id);
769
+ this.noteRejected(kind);
770
+ request.reject(signal.reason instanceof Error ? signal.reason : new Error("aborted"));
771
+ return;
772
+ }
773
+ this.attachCancellation(pending, signal);
774
+ }
775
+ // A frame that cannot be WRITTEN must fail its caller now. Silently
776
+ // dropping it used to strand the request: nothing would ever answer, the
777
+ // watchdog (armed on an ACK that will not come) had no process to kill,
778
+ // and with no timeout the caller waited forever.
779
+ if (this.serialRequests) {
780
+ this.dispatchQueued();
781
+ }
782
+ else if (!this.sendPending(pending)) {
783
+ this.clearPending(pending);
784
+ this.pending.delete(pending.id);
785
+ this.noteRejected(kind);
786
+ request.reject(new AgentUnavailableError("the agent exited before the request could be sent; it never ran"));
646
787
  return;
647
788
  }
789
+ this.rearmIdleTimer();
790
+ }
791
+ /**
792
+ * Build one pending entry: the caller's settle wrappers (which record the
793
+ * metric once) and, when the request carries a budget, the stuck-request
794
+ * watchdog armed by the agent's ACK.
795
+ *
796
+ * @param request - the request being tracked.
797
+ * @param kind - the metric bucket, with the caller's default resolved.
798
+ * @returns the entry, not yet registered.
799
+ */
800
+ newPendingRequest({ id, lines, resolve, reject, timeoutMs, signal }, kind) {
648
801
  const pending = {
649
802
  id,
650
803
  seq: Number(id.slice(1)),
@@ -690,64 +843,50 @@ export class WslAgent {
690
843
  }
691
844
  : null,
692
845
  };
693
- this.pending.set(id, pending);
694
- this.requestMetrics.inFlightMax = Math.max(this.requestMetrics.inFlightMax, this.pending.size);
695
- if (signal) {
696
- if (signal.aborted) {
697
- this.pending.delete(id);
698
- this.noteRejected(kind);
699
- reject(signal.reason instanceof Error ? signal.reason : new Error("aborted"));
700
- return;
701
- }
702
- pending.onAbort = () => {
703
- pending.cancelled = true;
704
- if (!pending.sent) {
705
- this.pending.delete(pending.id);
706
- this.clearPending(pending);
707
- pending.settled = true;
708
- pending.reject(signal.reason instanceof Error ? signal.reason : new Error("aborted"));
709
- this.rearmIdleTimer();
710
- return;
711
- }
712
- // The frame is the fallback for an agent that cannot be signalled (a
713
- // confined resident, a build without the USR1 trap); the signal is what
714
- // interrupts the command the agent is blocked on right now.
715
- this.writeLines([encodeKill(pending.id)]);
716
- if (pending.settled)
717
- return;
718
- pending.settled = true;
719
- // Keep the entry until the agent answers: a request cancelled while it
720
- // was QUEUED is killed when its ACK arrives, and its late RES only
721
- // cleans the map.
846
+ return pending;
847
+ }
848
+ /**
849
+ * Wire the caller's abort. An unsent request dies immediately; a sent one
850
+ * writes the KILL frame and, when the request is running, arms the signal
851
+ * that interrupts the command where it lives.
852
+ *
853
+ * @param pending - the tracked request.
854
+ * @param signal - the caller's cancellation.
855
+ */
856
+ attachCancellation(pending, signal) {
857
+ pending.onAbort = () => {
858
+ pending.cancelled = true;
859
+ if (!pending.sent) {
860
+ this.pending.delete(pending.id);
722
861
  this.clearPending(pending);
862
+ pending.settled = true;
723
863
  pending.reject(signal.reason instanceof Error ? signal.reason : new Error("aborted"));
724
- // Arm AFTER clearPending: the clear releases the per-request timers,
725
- // and the signal is the one timer that must outlive this rejection.
726
- // A host timeout is excluded: the distro-side watcher already kills
727
- // that command, and a USR1 delivered after it settled would hit the
728
- // request that took its place (observed as an exit-138 "completed").
729
- const reason = pending.signal?.reason;
730
- const timedOut = reason instanceof Error && reason.message === BASH_TIMEOUT_REASON;
731
- if (pending.started && !timedOut)
732
- this.armCancelSignal(pending);
733
- };
734
- signal.addEventListener("abort", pending.onAbort, { once: true });
735
- }
736
- // A frame that cannot be WRITTEN must fail its caller now. Silently
737
- // dropping it used to strand the request: nothing would ever answer, the
738
- // watchdog (armed on an ACK that will not come) had no process to kill,
739
- // and with no timeout the caller waited forever.
740
- if (this.serialRequests) {
741
- this.dispatchQueued();
742
- }
743
- else if (!this.sendPending(pending)) {
864
+ this.rearmIdleTimer();
865
+ return;
866
+ }
867
+ // The frame is the fallback for an agent that cannot be signalled (a
868
+ // confined resident, a build without the USR1 trap); the signal is what
869
+ // interrupts the command the agent is blocked on right now.
870
+ this.writeLines([encodeKill(pending.id)]);
871
+ if (pending.settled)
872
+ return;
873
+ pending.settled = true;
874
+ // Keep the entry until the agent answers: a request cancelled while it
875
+ // was QUEUED is killed when its ACK arrives, and its late RES only
876
+ // cleans the map.
744
877
  this.clearPending(pending);
745
- this.pending.delete(pending.id);
746
- this.noteRejected(kind);
747
- reject(new AgentUnavailableError("the agent exited before the request could be sent; it never ran"));
748
- return;
749
- }
750
- this.rearmIdleTimer();
878
+ pending.reject(signal.reason instanceof Error ? signal.reason : new Error("aborted"));
879
+ // Arm AFTER clearPending: the clear releases the per-request timers,
880
+ // and the signal is the one timer that must outlive this rejection.
881
+ // A host timeout is excluded: the distro-side watcher already kills
882
+ // that command, and a USR1 delivered after it settled would hit the
883
+ // request that took its place (observed as an exit-138 "completed").
884
+ const reason = pending.signal?.reason;
885
+ const timedOut = reason instanceof Error && reason.message === BASH_TIMEOUT_REASON;
886
+ if (pending.started && !timedOut)
887
+ this.armCancelSignal(pending);
888
+ };
889
+ signal.addEventListener("abort", pending.onAbort, { once: true });
751
890
  }
752
891
  /** Send a tracked request, recording dispatch before synchronous responses. */
753
892
  sendPending(pending) {
@@ -817,6 +956,23 @@ export class WslAgent {
817
956
  this.track({ id, kind: "fs", lines, resolve, reject, timeoutMs, signal });
818
957
  });
819
958
  }
959
+ /**
960
+ * Run one batched FS frame (protocol 7): the ordered ops execute in one
961
+ * worker and the resolution is ONE result whose stdout is the per-op
962
+ * record stream (`OK <i>|<b64>` / `BAD <i>|<reason>|<b64>`). The host sends
963
+ * this only to a resident that advertised `batch`; `DistroFs` gates it.
964
+ *
965
+ * @param request - the batch request.
966
+ * @returns the settled batch result.
967
+ */
968
+ async fsb({ ops, timeoutMs = 0, signal }) {
969
+ await this.start();
970
+ const id = `r${this.nextRequestId++}`;
971
+ const lines = encodeFsbFrame({ id, ops, timeoutMs });
972
+ return new Promise((resolve, reject) => {
973
+ this.track({ id, kind: "fs", lines, resolve, reject, timeoutMs, signal });
974
+ });
975
+ }
820
976
  /**
821
977
  * Liveness probe, also used to warm the agent up.
822
978
  *
@@ -966,8 +1122,11 @@ export class WslAgent {
966
1122
  }
967
1123
  this.pending.clear();
968
1124
  }
969
- this.writeLinesSafe(child, ["SHUTDOWN"]);
970
1125
  await new Promise((resolve) => {
1126
+ // The listeners go up before the write: a resident that answers SHUTDOWN
1127
+ // on the tick the write lands — a same-tick pipe, as the test fakes show —
1128
+ // would slip past a later-registered once() and turn every close into the
1129
+ // full kill grace.
971
1130
  const timer = setTimeout(() => {
972
1131
  child.kill("SIGKILL");
973
1132
  resolve();
@@ -976,6 +1135,7 @@ export class WslAgent {
976
1135
  clearTimeout(timer);
977
1136
  resolve();
978
1137
  });
1138
+ this.writeLinesSafe(child, ["SHUTDOWN"]);
979
1139
  });
980
1140
  // The transport is always spawned with pipes, so the streams exist; the
981
1141
  // field's broader type is Node's, not the spawn's.