pi-durable-subagents 1.5.1 → 1.6.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 (55) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +69 -14
  3. package/dist/agent/capabilities.js +5 -4
  4. package/dist/agent/child/live.js +2 -1
  5. package/dist/agent/exact/capture.js +3 -2
  6. package/dist/agent/main/snapshots.js +10 -9
  7. package/dist/agent/main.js +2 -1
  8. package/dist/cli/chaos/stack.js +53 -21
  9. package/dist/cli/control.js +4 -3
  10. package/dist/cli/doctor.js +3 -1
  11. package/dist/cli/drill/index.js +35 -17
  12. package/dist/cli/hold.js +221 -16
  13. package/dist/cli/restart.js +14 -2
  14. package/dist/cli/service.js +77 -2
  15. package/dist/cli/smoke.js +10 -6
  16. package/dist/compat/agents.js +46 -13
  17. package/dist/events/log.js +33 -11
  18. package/dist/kernel/cache.js +3 -2
  19. package/dist/kernel/fsx.js +203 -0
  20. package/dist/kernel/ids.js +11 -0
  21. package/dist/kernel/journal.js +42 -25
  22. package/dist/kernel/mailbox.js +7 -4
  23. package/dist/orchestrator/engine.js +49 -46
  24. package/dist/orchestrator/evaluator-client.js +11 -3
  25. package/dist/orchestrator/executor/command.js +21 -6
  26. package/dist/orchestrator/executor/effects/gate.js +291 -56
  27. package/dist/orchestrator/executor/effects/index.js +3 -4
  28. package/dist/orchestrator/executor/effects/output.js +9 -5
  29. package/dist/orchestrator/executor/effects/prepare.js +34 -32
  30. package/dist/orchestrator/executor/effects/worktree-path.js +102 -0
  31. package/dist/orchestrator/executor/ended.js +7 -3
  32. package/dist/orchestrator/executor/index.js +216 -62
  33. package/dist/orchestrator/executor/memory.js +15 -0
  34. package/dist/orchestrator/executor/session.js +4 -3
  35. package/dist/orchestrator/executor/sweep.js +34 -1
  36. package/dist/orchestrator/executor/worktree.js +1 -1
  37. package/dist/orchestrator/main.js +4 -2
  38. package/dist/orchestrator/reader-ledger.js +3 -2
  39. package/dist/orchestrator/settled.js +2 -1
  40. package/dist/orchestrator/snapshot.js +24 -19
  41. package/dist/orchestrator/stats.js +2 -1
  42. package/dist/orchestrator/store.js +3 -2
  43. package/dist/platform/cmdline.js +3 -0
  44. package/dist/platform/command.js +184 -20
  45. package/dist/platform/containment.js +204 -40
  46. package/dist/platform/job.js +1404 -0
  47. package/dist/platform/launch.js +157 -23
  48. package/dist/platform/lease.js +351 -32
  49. package/dist/platform/lock.js +464 -16
  50. package/dist/platform/proctable.js +31 -2
  51. package/dist/platform/windows.js +642 -0
  52. package/dist/requests.js +1 -1
  53. package/dist/ui/data.js +7 -6
  54. package/dist/ui/session.js +6 -5
  55. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.6.0
4
+
5
+ - **Native Windows support** (Node.js 22.19+ and 24, no WSL or POSIX tools required; based on #4):
6
+ - **Kernel-released OS locks**: Windows file locks hold an exclusive `FileShare.None` file handle via a cached
7
+ `.NET Framework` helper compiled into a user-private directory (`%LOCALAPPDATA%` or `DSA_HOME`, with bounded
8
+ compile budget, self-healing and PowerShell fallback) so a killed holder releases its lock immediately in the kernel.
9
+ - **Windows Job Objects for commands, `hold` leases and gates**: Command attempts, `hold` leases and gates run inside
10
+ `KILL_ON_JOB_CLOSE` Job Objects owned by a per-launch `.NET Framework` winexe compiled from embedded C# with
11
+ `csc.exe` (no npm dependency or native addon). Compilation is staged and cancellable before durable intent; the
12
+ wrapper is assigned suspended before user code runs, receives exact UTF-16LE specs and normalized 32-bit DWORD exit
13
+ codes, publishes exit/gate records atomically with bounded sharing-violation retries, and tears down cleanly via
14
+ controlled `stop`/`DrainJob` on `--yield` and signals.
15
+ - **Handle-verified process observation and fencing**: Process discovery uses credential-isolated `System.Management`
16
+ `Win32_Process` snapshots with `FreeVirtualMemory` commit-based memory admission; process termination verifies
17
+ `GetProcessTimes` creation identity on open handles, refuses critical processes, fails closed on protected-PID
18
+ `EPERM` snapshot misses, reuses scanned `CommandLine` in `ended` diagnostics, reports budget breakdowns on fence
19
+ timeout, and triggers an immediate sweep retry on fence failure.
20
+ - **Filesystem, worktrees and 64-bit file identities**: Journal, cache, reader-ledger and UI readers preserve full
21
+ 64-bit NTFS `FileId` values as decimal strings; `latest` output publishes atomically without symlink privileges;
22
+ worktree keys reject path-like escapes on every platform, encode Windows-unspellable names (such as `tasks:0` or
23
+ reserved device names) under `.dsa/<wid>/.keys/<hash>`, and match Git worktrees by file-system identity across 8.3
24
+ aliases, casing and path prefixes.
25
+ - **Launchers, environments and Task Scheduler service**: Case-insensitive environment merging (`Path`/`PATH`,
26
+ `ComSpec`/`COMSPEC`), `PATHEXT` resolution, safe npm shim unwrapping (keeping `NODE_PATH`/`NODE_OPTIONS` shims
27
+ intact via verbatim `cmd.exe /d /s /c` quoting while rejecting CR/LF/quote injection), hidden `wscript.exe` Task
28
+ Scheduler service management with locale-independent `schtasks` checks, and `DSA_ORCHESTRATOR_LOG=<file>` for
29
+ capturing detached orchestrator output.
30
+ - **Full 3-OS CI matrix**: Linux, macOS and Windows all run unit tests, real-`pi` E2E suites and `pack:smoke` on
31
+ Node.js 22.19 and 24.
32
+ - **Engine lookup performance**: `Engine.findCall`, `withdraw` and single-target routing use O(1) indexed lookups
33
+ instead of scanning all workflows on every request.
34
+ - Fixed `chaos` scenario config generation (`providers.<name>.slots`) so diagnostic scenarios apply their intended
35
+ concurrency and timing settings.
36
+
3
37
  ## 1.5.1
4
38
 
5
39
  - A worktree on an unexpected branch or detached HEAD can no longer block unrelated workflows during startup recovery. If the call already succeeded, recovery keeps its result and files and records one notice that survives restarts. The notice identifies the call, path, expected branch and actual checkout (#10).
package/README.md CHANGED
@@ -34,14 +34,29 @@ pi install npm:pi-durable-subagents
34
34
  pi install git:github.com/purboo/pi-durable-subagents
35
35
  ```
36
36
 
37
- This needs pi 1.0.x and Node.js 22.19 or later, on Linux or macOS. It has
38
- been tested with pi 1.0.2 on Linux. The CI configuration covers Linux and
39
- macOS.
40
-
41
- Windows is not supported: process tracking, file locks, command calls and
42
- the login service exist only for Linux and macOS. On Windows the extension
43
- disables itself when pi loads it, with one message, and registers no tool.
44
- Under Windows, run pi inside WSL.
37
+ This needs pi 1.0.x and Node.js 22.19 or later, on Linux, macOS or Windows.
38
+ It has been tested with pi 1.0.2 on Linux and Windows. The CI configuration
39
+ covers Linux, macOS and Windows.
40
+
41
+ Windows uses native facilities, no WSL and no POSIX tools: the process table
42
+ comes from PowerShell/CIM (`Win32_Process`, identity is pid plus creation
43
+ time, fail-closed on protected-PID reuse), process trees end through
44
+ handle-verified Win32 `TerminateProcess` (`GetProcessTimes` checked on the open
45
+ handle, live creation-ordered descendants only), file locks hold a
46
+ kernel-released exclusive `FileShare.None` file handle (via a cached .NET
47
+ Framework helper compiled under `%LOCALAPPDATA%` with PowerShell fallback),
48
+ command calls, `hold` leases and gates run inside Windows Job Objects
49
+ (`KILL_ON_JOB_CLOSE` kernel-owned groups whose sole handle is held by a small
50
+ .NET Framework executable compiled per launch with `csc.exe`, so the group's
51
+ last handle closing terminates every surviving descendant), and
52
+ `install-service` uses a hidden `wscript.exe` launcher in Task Scheduler.
53
+ Two Windows differences: another process's environment is unreadable, so
54
+ execution identity is the live creation-ordered process tree (a grandchild
55
+ whose parent exited before a scan is not found by the `DSA_EXEC` tag the way
56
+ it is on Linux, while a command attempt's descendants stay in its group), and
57
+ Windows has no POSIX signals, so `stop`/`restart` requests are the graceful
58
+ path (the legacy restart check and handle-verified termination end processes
59
+ directly).
45
60
 
46
61
  The `pi-durable-subagents` command line (below) is optional. Run it without
47
62
  installing through `npx pi-durable-subagents …`, or install it once with
@@ -433,7 +448,7 @@ subagents({ chain: [{ command: ["npm", "test"] }, { agent: "worker", task: "Fix
433
448
  | `command` | An array runs a program with those arguments, never shell syntax: its first element is looked up in the command's `PATH` (exit 127 when there is none), and a shell builtin is not run as a builtin (`["exit", "7"]` looks for a program named `exit`). A string runs through `/bin/sh -c`. |
434
449
  | `cwd` | Its directory, resolved like an agent call's. |
435
450
  | `timeoutMs` | Wall-clock time from its start, including time the orchestrator was down (see the result table). |
436
- | `env` | Variables added to the environment (`DSA_*` names are reserved). |
451
+ | `env` | Variables added to the environment (`DSA_*` names are reserved). On Windows a variable name is one name in any case (`Path` is `PATH`, `ComSpec` is `COMSPEC`): the call's definition replaces the orchestrator's, it is not added beside it. |
437
452
  | `rerun` | `true`: when the process vanished without an exit record (the machine restarted), start it once more instead of ending `unknown`. For idempotent commands. |
438
453
  | `writer` | `true`: take its worktree's writer lock (default `false`). |
439
454
  | `key` | Its key in `tasks`/`chain`, as for agent steps. |
@@ -441,7 +456,38 @@ subagents({ chain: [{ command: ["npm", "test"] }, { agent: "worker", task: "Fix
441
456
  Other call fields (`agent`, `task`, `model`, `tools`, `schema`, `gate`, …)
442
457
  are refused in a command call, and `env`/`rerun` in an agent call. stdin is
443
458
  empty; stdout and stderr go, interleaved, to `output.log` in the attempt's
444
- directory. The command sees the orchestrator's environment plus `env`,
459
+ directory (on Windows the group's host opens it, so no descriptor is held
460
+ here). On Windows the wrapper is the root of a Job Object of its own: it
461
+ is created suspended, assigned to the group before its first instruction, and
462
+ the group's only handle dies with the attempt, so every process the command
463
+ starts is in the group and cannot outlive it (a wrapper crash or a killed job
464
+ host ends the group; a command that is still running keeps running when the
465
+ orchestrator stops). The group is held by a small .NET Framework winexe that
466
+ this package compiles per launch -- in a fresh private directory -- with the
467
+ C# compiler of the framework every supported Windows ships
468
+ (`%SystemRoot%\Microsoft.NET\Framework64|Framework\v4.0.30319\csc.exe`, with
469
+ the 32-bit framework as fallback). That host receives the wrapper's program,
470
+ arguments, working directory and environment as ASCII lines of base64 UTF-16LE
471
+ and decodes every field to its exact code units, so a Unicode path, a curly
472
+ quote, an emoji or an unpaired surrogate reaches Win32 unchanged; a field that
473
+ is not a whole number of them, or that carries a NUL, is refused before
474
+ anything is created. The compilation is foreground and bounded, starts no
475
+ command, and is staged before the attempt's durable intent (its
476
+ `command-intent` record), so a crash or a stop while the compiler runs leaves
477
+ no attempt at all: that cut is unambiguously prelaunch, and an interrupted
478
+ compilation is ended, what it wrote is removed and it is never recorded as a
479
+ failure of the attempt or sealed as one. The orchestrator rechecks its
480
+ proceed/stop decision again after the preparation, immediately before the
481
+ spawn. If the compiler is missing or fails on its own, the start is refused
482
+ closed: no group, no command, and the reason is recorded with the attempt. The attempt's tag is
483
+ also spelled in the owner's own command line, so a successor that finds a
484
+ recorded intent while the owner is still starting -- before the group record
485
+ and the wrapper exist -- still finds the attempt and starts nothing else. Only
486
+ a confirmed retirement lets a start
487
+ fail: when the handshake cannot be completed and the owner cannot be shown to
488
+ have ended, the attempt is adopted and tracked (its identity is recorded, and a
489
+ scan that finds it gone is what lets another attempt start), never reported
490
+ failed while it may still act. The command sees the orchestrator's environment plus `env`,
445
491
  `DSA_CALL` (its call id), `DSA_EXEC` (its attempt) and `DSA_HOME`, so a
446
492
  `pi-durable-subagents` command inside it (`hold`, `run`, `send`) addresses
447
493
  the same home; it cannot force a restart. After merging `env`, the command's
@@ -449,8 +495,14 @@ the same home; it cannot force a restart. After merging `env`, the command's
449
495
  appended once as the last entry. Custom and inherited tools keep precedence,
450
496
  and the CLI shim is still found. Empty entries and earlier copies of the
451
497
  shim directory are removed; an explicitly empty PATH searches only that
452
- directory, not the current directory or system tools. Agent PATH is unchanged
453
- (the shim stays first).
498
+ directory, not the current directory or system tools. On Windows the names
499
+ follow the platform's rule (one variable per name, in any case): `env.Path`
500
+ is the PATH the command gets and no second `PATH` sits beside it, an earlier
501
+ copy of the shim directory in another case is still one entry, `env.ComSpec`
502
+ (or `COMSPEC`) is the processor its string commands run through, and the
503
+ program of an argv command is looked up on that same PATH — so an npm `.cmd`
504
+ shim there is found even when the starting orchestrator's PATH lacked it.
505
+ Agent PATH is unchanged (the shim stays first).
454
506
 
455
507
  | The command | Result |
456
508
  |---|---|
@@ -461,8 +513,11 @@ directory, not the current directory or system tools. Agent PATH is unchanged
461
513
  | vanished without an exit record, no `rerun` | `unknown`, error `Command ended without an exit record` |
462
514
 
463
515
  `data` is `{exitCode, signal, durationMs}` and `output` the last 16 KiB of
464
- `output.log`. Only `stop` controls a command call (it ends the whole process
465
- tree); `steer`, `follow-up`, `answer`, `model` and `notify` are refused with
516
+ `output.log`. A Windows exit status is the whole 32-bit code: a crash such as
517
+ `0xC0000005` reads `Command exited 3221225477`, and the record in the attempt
518
+ directory and the wrapper's own exit carry that same DWORD. Only `stop`
519
+ controls a command call (it ends the whole process tree); `steer`,
520
+ `follow-up`, `answer`, `model` and `notify` are refused with
466
521
  `command call: <kind> is not supported (stop it, or start a new call)`.
467
522
 
468
523
  The deadline counts from the command's start, also while no orchestrator
@@ -11,9 +11,10 @@ export const SURFACES = [
11
11
  { tier: 2, where: "@earendil-works/pi-tui", name: "wrapTextWithAnsi" },
12
12
  ...["Input", "SelectList", "fuzzyFilter", "matchesKey", "truncateToWidth", "visibleWidth"].map(name => ({ tier: 2, where: "@earendil-works/pi-tui", name })),
13
13
  ];
14
- /** The process layer (process tables and tree kill, flock, the memory probe, `/bin/sh` command calls, service units) exists
15
- * only for these platforms; anywhere else every call would fail at spawn, so execution is disabled at load instead. */
16
- export const SUPPORTED_PLATFORMS = ["linux", "darwin"];
14
+ /** The process layer (process tables and tree kill, file locks, the memory probe, command calls, service units) has a
15
+ * native implementation for these platforms; anywhere else every call would fail at spawn, so execution is disabled
16
+ * at load instead. Windows uses PowerShell/CIM for the process table and handle-verified Win32 termination for fencing. */
17
+ export const SUPPORTED_PLATFORMS = ["linux", "darwin", "win32"];
17
18
  /** AC5, P21, issue #1: Check the platform and the surfaces present in pi's modules and extension API; produce exact
18
19
  * degradation messages. */
19
20
  export function checkCapabilities(modules, api, version, platform = process.platform) {
@@ -28,7 +29,7 @@ export function checkCapabilities(modules, api, version, platform = process.plat
28
29
  const execution = os && node && !missing.some(s => s.tier === 0), ui = execution && !missing.some(s => s.tier === 2);
29
30
  const messages = [];
30
31
  if (!os)
31
- messages.push(`Durable Subagents disabled: it runs only on Linux and macOS (this is ${platform}); its process layer (process tracking, file locks, command calls) has no ${platform} implementation. Under Windows, use WSL.`);
32
+ messages.push(`Durable Subagents disabled: it runs only on Linux, macOS and Windows (this is ${platform}); its process layer (process tracking, file locks, command calls) has no ${platform} implementation.`);
32
33
  else if (!node)
33
34
  messages.push(`Durable Subagents disabled: it needs Node.js 22.19 or later (this is ${process.version}).`);
34
35
  else if (!execution)
@@ -3,6 +3,7 @@
3
3
  // live.json (next to the session) holds that ephemeral state. It is not durable state: written without fsync,
4
4
  // replaced atomically (temp + rename), ignored when stale, and never read by the orchestrator.
5
5
  import { renameSync, writeFileSync } from "node:fs";
6
+ import { replacePathSync } from "../../kernel/fsx.js";
6
7
  import { dirname, join } from "node:path";
7
8
  export const LIVE_FILE = "live.json";
8
9
  const TAIL = 4000, EVERY_MS = 250;
@@ -18,7 +19,7 @@ export function registerLive(pi, enabled) {
18
19
  try {
19
20
  const tmp = `${path}.${process.pid}.tmp`;
20
21
  writeFileSync(tmp, JSON.stringify({ ...state, at: last }));
21
- renameSync(tmp, path);
22
+ replacePathSync(tmp, path);
22
23
  }
23
24
  catch { /* Watching is best effort; the session file stays the truth. */ }
24
25
  };
@@ -10,10 +10,11 @@
10
10
  //
11
11
  // A failed write never fails or delays the request: the write happens after the request was handed to the provider
12
12
  // and every error is swallowed.
13
- import { mkdir, open, readdir, readFile, rename, rm, stat } from "node:fs/promises";
13
+ import { mkdir, open, readdir, readFile, rm, stat } from "node:fs/promises";
14
14
  import { join } from "node:path";
15
15
  import { createHash } from "node:crypto";
16
16
  import { contentHash } from "../../kernel/ids.js";
17
+ import { replacePath } from "../../kernel/fsx.js";
17
18
  /** The apis an exact fork can splice (EX4). Every other api falls back to a rebuilt fork. */
18
19
  export const EXACT_APIS = ["anthropic-messages", "openai-responses"];
19
20
  /** `<home>/exact`: the capture directory of every session. */
@@ -49,7 +50,7 @@ export async function writeCapture(home, capture) {
49
50
  finally {
50
51
  await file.close();
51
52
  }
52
- await rename(temp, target);
53
+ await replacePath(temp, target);
53
54
  }
54
55
  /** Read the capture of a session; undefined when there is none (or it is unreadable). */
55
56
  export async function readCapture(home, sessionId) {
@@ -1,7 +1,8 @@
1
- import { closeSync, openSync, readSync, statSync } from "node:fs";
1
+ import { closeSync, openSync, readSync } from "node:fs";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { join } from "node:path";
4
4
  import { liveCommandCalls } from "../../orchestrator/executor/command.js";
5
+ import { statIdentitySync } from "../../kernel/fsx.js";
5
6
  import { forgetJournalSnapshot, journalAppends, readJournalFold, readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
6
7
  import { journalPath } from "../../paths.js";
7
8
  import { CT, JT, askText } from "../../types.js";
@@ -95,7 +96,7 @@ const decided = new Map();
95
96
  function unfinishedJournal(path, known) {
96
97
  let stat;
97
98
  try {
98
- stat = statSync(path);
99
+ stat = statIdentitySync(path);
99
100
  }
100
101
  catch (error) {
101
102
  if (error.code !== "ENOENT")
@@ -104,7 +105,7 @@ function unfinishedJournal(path, known) {
104
105
  return true;
105
106
  } // no done yet
106
107
  const hit = decided.get(path);
107
- if (hit && hit.ino === stat.ino && hit.size === stat.size)
108
+ if (hit && hit.dev === stat.dev && hit.ino === stat.ino && hit.size === stat.size)
108
109
  return hit.unfinished;
109
110
  // Read without keeping the entries in the shared journal cache: a pi process scans every workflow only when no
110
111
  // orchestrator runs, and keeping every journal of the machine cost it hundreds of MB.
@@ -114,7 +115,7 @@ function unfinishedJournal(path, known) {
114
115
  return true;
115
116
  }
116
117
  const unfinished = !read.entries.some(e => e.type === JT.done) || openGeneration(read.entries);
117
- decided.set(path, { ino: read.ino, size: read.size, unfinished });
118
+ decided.set(path, { dev: read.dev, ino: read.ino, size: read.size, unfinished });
118
119
  return unfinished;
119
120
  }
120
121
  /** R3, F4: Whether a journal has a live command attempt (liveCommandCalls: an intent not withdrawn, of a call neither
@@ -124,7 +125,7 @@ const commanded = new Map();
124
125
  function startedCommand(path, known) {
125
126
  let stat;
126
127
  try {
127
- stat = statSync(path);
128
+ stat = statIdentitySync(path);
128
129
  }
129
130
  catch (error) {
130
131
  if (error.code !== "ENOENT")
@@ -132,12 +133,12 @@ function startedCommand(path, known) {
132
133
  commanded.delete(path);
133
134
  return false;
134
135
  }
135
- if (!stat.isFile()) {
136
+ if (!stat.stats.isFile()) {
136
137
  commanded.delete(path);
137
138
  return false;
138
139
  } // unreadable held work stays held
139
140
  const hit = commanded.get(path);
140
- if (hit && hit.ino === stat.ino && hit.size === stat.size)
141
+ if (hit && hit.dev === stat.dev && hit.ino === stat.ino && hit.size === stat.size)
141
142
  return hit.running;
142
143
  let read = known;
143
144
  try {
@@ -152,7 +153,7 @@ function startedCommand(path, known) {
152
153
  return false;
153
154
  }
154
155
  const running = liveCommandCalls(read.entries).length > 0;
155
- commanded.set(path, { ino: read.ino, size: read.size, running });
156
+ commanded.set(path, { dev: read.dev, ino: read.ino, size: read.size, running });
156
157
  return running;
157
158
  }
158
159
  /** P1: Workflow-side pending work shared by every starter: a workflow without JT.done or with an unsealed generation,
@@ -253,7 +254,7 @@ function ask(scan, line) {
253
254
  function answeredAsks(path) {
254
255
  let stat;
255
256
  try {
256
- stat = statSync(path);
257
+ stat = statIdentitySync(path);
257
258
  }
258
259
  catch (error) {
259
260
  if (error.code === "ENOENT") {
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
6
  import { defineTool } from "@earendil-works/pi-coding-agent";
7
7
  import { Outbox, scanInbox } from "../kernel/mailbox.js";
8
+ import { fileId } from "../kernel/ids.js";
8
9
  import { readerLedger } from "../orchestrator/reader-ledger.js";
9
10
  import { OsLock, isLockTimeout } from "../platform/lock.js";
10
11
  import { launchOrchestrator } from "../platform/launch.js";
@@ -89,7 +90,7 @@ export function registerMain(pi, ui) {
89
90
  }
90
91
  function pendingOutbox() { return pendingRids().size > 0; }
91
92
  function pendingRids() {
92
- return pendingReader.read(join(outboxRoot(home), "outbox", `${sender}.jsonl`));
93
+ return pendingReader.read(join(outboxRoot(home), "outbox", `${fileId(sender)}.jsonl`));
93
94
  }
94
95
  /** A background failure goes to pi's UI (a raw stderr write would land inside the TUI's editor); without a UI, stderr. */
95
96
  function report(text) {
@@ -5,6 +5,8 @@ import { fileURLToPath } from "node:url";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
6
  import { captureStart, ProcessTable } from "../../platform/proctable.js";
7
7
  import { Containment } from "../../platform/containment.js";
8
+ import { execTarget } from "../../platform/launch.js";
9
+ import { IS_WINDOWS, isWinStart, killProcess, killProcessSync, killTree, sameCreation } from "../../platform/windows.js";
8
10
  import { readJournalSnapshot } from "../../kernel/journal.js";
9
11
  import { orchLedger, journalPath } from "../../paths.js";
10
12
  import { JT } from "../../types.js";
@@ -29,6 +31,9 @@ export async function until(get, label, ms = 60_000) {
29
31
  }
30
32
  /** Encode a script carried by a real task or main-session prompt. */
31
33
  export function script(steps) { return `#chaos: ${JSON.stringify(steps)}`; }
34
+ /** The scenario's own settings: three provider slots, and a tracker/checkpoint cadence tight enough to observe a child
35
+ * that exits right after its first answer. `providers` maps a name to `{ slots }` (orchestrator/config.ts). */
36
+ export const chaosConfig = { providers: { "dsa-chaos": { slots: 3 } }, k: { trackerMs: 100, checkpointMs: 200, idleExitMs: 2000 } };
32
37
  /** Start an isolated real pi main, retaining RPC and diagnostic evidence. */
33
38
  export function stack(root, inherited) {
34
39
  const home = join(root, "dsa"), cwd = join(root, "work"), agent = join(root, "agent"), session = join(root, "main.jsonl");
@@ -37,20 +42,41 @@ export function stack(root, inherited) {
37
42
  const sibling = (name) => fileURLToPath(new URL(name + (import.meta.url.endsWith(".ts") ? ".ts" : ".js"), import.meta.url));
38
43
  writeFileSync(join(agent, "settings.json"), JSON.stringify({ extensions: [sibling("./provider"), sibling("../../agent/extension"), sibling("./observer")],
39
44
  defaultProvider: "dsa-chaos", defaultModel: "scripted", retry: { enabled: false }, compaction: { enabled: false }, defaultProjectTrust: "always" }));
40
- writeFileSync(join(home, "config.json"), JSON.stringify({ providers: { "dsa-chaos": 3 }, k: { trackerMs: 100, checkpointMs: 200, idleExitMs: 2000 } }));
45
+ writeFileSync(join(home, "config.json"), JSON.stringify(chaosConfig));
41
46
  for (const name of ["writer", "reviewer", "integrator"])
42
47
  writeFileSync(join(cwd, `.pi/agents/${name}.md`), `---\nname: ${name}\ndescription: Chaos ${name}\nmodel: dsa-chaos/scripted\ntools: bash, ask\n---\nFollow the scripted task.\n`);
43
48
  const env = { PATH: inherited.PATH, HOME: join(root, "home"), TMPDIR: root, PI_CODING_AGENT_DIR: agent,
44
- PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1", PI_TELEMETRY: "0", JITI_FS_CACHE: "false", DSA_HOME: home, DSA_CHAOS_ROOT: root, DSA_ORCHESTRATOR_ENTRY: sibling("./host") };
49
+ PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1", PI_TELEMETRY: "0", JITI_FS_CACHE: "false", DSA_HOME: home, DSA_CHAOS_ROOT: root, DSA_ORCHESTRATOR_ENTRY: sibling("./host"),
50
+ // The orchestrator this scenario starts through pi is detached and has no terminal: keep what it says with the rest
51
+ // of the evidence (--keep, or a failure) instead of discarding it.
52
+ DSA_ORCHESTRATOR_LOG: join(root, "orchestrator.log") };
45
53
  const instances = [];
54
+ async function endMainChild(c, startPromise) {
55
+ if (!c.pid)
56
+ return;
57
+ if (IS_WINDOWS) {
58
+ const start = await startPromise.catch(() => "");
59
+ if (isWinStart(start))
60
+ await killTree({ pid: c.pid, start }).catch(() => { });
61
+ else if (c.exitCode === null && c.signalCode === null)
62
+ c.kill("SIGKILL");
63
+ return;
64
+ }
65
+ try {
66
+ process.kill(-c.pid, "SIGKILL");
67
+ }
68
+ catch { }
69
+ }
46
70
  function launch() {
47
- let child, events = [], buffer = "", error, requestId = 0, ready = false;
71
+ let child, childStart = Promise.resolve(""), events = [], buffer = "", error, requestId = 0, ready = false;
48
72
  const start = () => {
49
- child = spawn("pi", ["--mode", "rpc", "--session", session], { cwd, env, stdio: ["pipe", "pipe", "pipe"], detached: true });
73
+ const target = execTarget("pi", ["--mode", "rpc", "--session", session], { env });
74
+ child = spawn(target.command, target.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], detached: true, windowsHide: true, ...(target.verbatim ? { windowsVerbatimArguments: true } : {}) });
50
75
  events = [];
51
76
  buffer = "";
52
77
  error = undefined;
53
78
  const own = child;
79
+ childStart = own.pid ? captureStart(own.pid).catch(() => "") : Promise.resolve("");
54
80
  child.on("error", e => { if (own === child)
55
81
  error = e; });
56
82
  child.stdin.on("error", e => { if (own === child)
@@ -110,16 +136,13 @@ export function stack(root, inherited) {
110
136
  }
111
137
  if (attempt >= 5)
112
138
  throw failure;
113
- try {
114
- process.kill(-child.pid, "SIGKILL");
115
- }
116
- catch { }
139
+ await endMainChild(child, childStart);
117
140
  await until(() => child.exitCode !== null || child.signalCode !== null, "unready main exited", 5_000);
118
141
  start();
119
142
  }
120
143
  }
121
144
  }
122
- const pi = { get child() { return child; }, get events() { return events; }, async prompt(steps) {
145
+ const pi = { get child() { return child; }, get start() { return childStart; }, get events() { return events; }, async prompt(steps) {
123
146
  if (!ready) {
124
147
  await readiness();
125
148
  ready = true;
@@ -136,37 +159,46 @@ export function stack(root, inherited) {
136
159
  const journal = (wid) => readJournalSnapshot(journalPath(home, wid));
137
160
  async function signalHost(signal) {
138
161
  const host = rows(join(root, "hosts.jsonl")).at(-1);
139
- if (!host || await captureStart(host.pid) !== host.start)
162
+ const observed = host ? await captureStart(host.pid).catch(() => "") : "";
163
+ if (!host || !host.start || !(IS_WINDOWS ? sameCreation(observed, host.start) : observed === host.start)) {
140
164
  throw new Error("host identity unavailable");
141
- process.kill(host.pid, signal);
165
+ }
166
+ if (IS_WINDOWS)
167
+ killProcessSync({ pid: host.pid, start: host.start });
168
+ else
169
+ process.kill(host.pid, signal);
142
170
  return host;
143
171
  }
144
172
  async function close() {
145
173
  for (const pi of instances)
146
- if (pi.child.exitCode === null && pi.child.signalCode === null) {
147
- try {
148
- process.kill(-pi.child.pid, "SIGKILL");
149
- }
150
- catch { }
151
- }
174
+ if (pi.child.exitCode === null && pi.child.signalCode === null)
175
+ await endMainChild(pi.child, pi.start);
152
176
  for (const pi of instances) {
153
177
  pi.child.stdin.destroy();
154
178
  pi.child.stdout.destroy();
155
179
  pi.child.stderr.destroy();
156
180
  pi.child.unref();
157
181
  }
158
- for (const host of rows(join(root, "hosts.jsonl")))
159
- if (await captureStart(host.pid) === host.start) {
182
+ for (const host of rows(join(root, "hosts.jsonl"))) {
183
+ if (!host?.start)
184
+ continue;
185
+ if (IS_WINDOWS) {
186
+ if (isWinStart(host.start))
187
+ await killProcess({ pid: host.pid, start: host.start }).catch(() => { });
188
+ continue;
189
+ }
190
+ if (await captureStart(host.pid).catch(() => "") === host.start) {
160
191
  process.kill(host.pid, "SIGCONT");
161
192
  process.kill(host.pid, "SIGTERM");
162
193
  try {
163
- await until(async () => await captureStart(host.pid) !== host.start, "host shutdown", 8000);
194
+ await until(async () => await captureStart(host.pid).catch(() => "") !== host.start, "host shutdown", 8000);
164
195
  }
165
196
  catch {
166
- if (await captureStart(host.pid) === host.start)
197
+ if (await captureStart(host.pid).catch(() => "") === host.start)
167
198
  process.kill(host.pid, "SIGKILL");
168
199
  }
169
200
  }
201
+ }
170
202
  const containment = new Containment(new ProcessTable());
171
203
  for (const created of ledger().filter(e => e.type === JT.created))
172
204
  for (const exec of journal(String(created.wid)).filter(e => e.type === JT.exec))
@@ -14,6 +14,7 @@ import { cliInitiator } from "./restart.js";
14
14
  import { restartInputError } from "../orchestrator/restart.js";
15
15
  import { JT } from "../types.js";
16
16
  import { RequestsBusy, sendIdentified } from "../requests.js";
17
+ import { fileId } from "../kernel/ids.js";
17
18
  /** P1: Start the detached orchestrator only after probing its OS lock (platform/launch.ts: pi resolved here, its own
18
19
  * scope). Throws PiNotFound, starting nothing, when this environment has no pi: an orchestrator started here could
19
20
  * launch no subagent, and a request already published stays pending for the next starter that has pi. A replaced
@@ -125,11 +126,11 @@ export async function submitIdentified(home, rid, kind, body, cond, env = proces
125
126
  async function withSender(home, fn) {
126
127
  await mkdir(home, { recursive: true });
127
128
  const sender = `cli:${userInfo().username}@${hostname()}`;
128
- const locker = new OsLock(), deadline = performance.now() + 10_000;
129
- let lock = await locker.tryAcquire(join(home, `${sender}.lock`));
129
+ const locker = new OsLock(), deadline = performance.now() + (process.platform === "win32" ? 30_000 : 10_000), lockPath = join(home, `${fileId(sender)}.lock`);
130
+ let lock = await locker.tryAcquire(lockPath);
130
131
  while (!lock && performance.now() < deadline) {
131
132
  await delay(50);
132
- lock = await locker.tryAcquire(join(home, `${sender}.lock`));
133
+ lock = await locker.tryAcquire(lockPath);
133
134
  }
134
135
  if (!lock)
135
136
  throw new RequestsBusy("CLI sender is busy; retry the command");
@@ -44,7 +44,9 @@ async function lockHeld(home) {
44
44
  }
45
45
  }
46
46
  /** C2: The command that lists the processes still tagged with an execution identity. */
47
- const stuckProcesses = (exec) => process.platform === "linux" ? `grep -lsz ${quote(`DSA_EXEC=${exec}`)} /proc/*/environ` : `ps -Eww -o pid,command | grep -F ${quote(`DSA_EXEC=${exec}`)}`;
47
+ const stuckProcesses = (exec) => process.platform === "linux" ? `grep -lsz ${quote(`DSA_EXEC=${exec}`)} /proc/*/environ`
48
+ : process.platform === "win32" ? `powershell -NoProfile -Command "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*${exec}*' } | Select-Object ProcessId,CommandLine"`
49
+ : `ps -Eww -o pid,command | grep -F ${quote(`DSA_EXEC=${exec}`)}`;
48
50
  /** Housekeeping: Collect DSA_HOME health facts read-only; `findings` lists only actionable ones, one command each. */
49
51
  export async function doctor(home, env = process.env, now = Date.now()) {
50
52
  const ledger = readJournalSnapshot(orchLedger(home));
@@ -12,6 +12,7 @@ import { readJournalSnapshot } from "../../kernel/journal.js";
12
12
  import { journalPath, orchLedger } from "../../paths.js";
13
13
  import { captureStart, ProcessTable } from "../../platform/proctable.js";
14
14
  import { Containment } from "../../platform/containment.js";
15
+ import { IS_WINDOWS, isWinStart, killProcess, sameCreation } from "../../platform/windows.js";
15
16
  import { JT } from "../../types.js";
16
17
  const A = "drill-a", B = "drill-b", POOL = "failover";
17
18
  /** Steps 1-3 (about 5 s here) must finish before it; 25 s leaves room for a loaded or several times slower machine
@@ -24,6 +25,9 @@ const STEPS = [
24
25
  `${A} answers again; after the probe interval the next call probes it and it is marked available`,
25
26
  `the third call (the probe) starts on ${A} and ends ok there`,
26
27
  ];
28
+ /** The drill's own settings: its two offline providers as one pool, and the probe interval the machine must meet
29
+ * (orchestrator/config.ts validates both). */
30
+ export const drillConfig = (probeMs = DRILL_PROBE_MS) => ({ pools: { [POOL]: [`${A}/m`, `${B}/m`] }, k: { probeMs } });
27
31
  /** Validate drill arguments before allocating a temporary root or starting anything. */
28
32
  export function parseDrill(args) {
29
33
  if (args[0] !== "failover")
@@ -58,10 +62,13 @@ export async function drill(args, inherited = process.env, write = console.log)
58
62
  // pi's retries stay on (a used-up window is noticed while pi retries, as on a real setup), with a short backoff.
59
63
  retry: { enabled: true, baseDelayMs: 200 }, compaction: { enabled: false }, defaultProjectTrust: "always" }));
60
64
  writeFileSync(join(cwd, ".pi/agents/worker.md"), "---\nname: worker\ndescription: Failover drill worker\ntools: bash\n---\nAnswer the task.\n");
61
- writeFileSync(join(home, "config.json"), JSON.stringify({ pools: { [POOL]: [`${A}/m`, `${B}/m`] }, k: { probeMs: DRILL_PROBE_MS } }));
65
+ writeFileSync(join(home, "config.json"), JSON.stringify(drillConfig()));
62
66
  writeFileSync(join(root, "a-exhausted"), "");
63
67
  const env = { PATH: inherited.PATH, HOME: join(root, "home"), TMPDIR: root, PI_CODING_AGENT_DIR: agent,
64
- PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1", PI_TELEMETRY: "0", DSA_HOME: home, DSA_DRILL_ROOT: root };
68
+ PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1", PI_TELEMETRY: "0", DSA_HOME: home, DSA_DRILL_ROOT: root,
69
+ // The drill exists to be diagnosable: keep what the detached orchestrator it starts says, for --keep and for a
70
+ // step that fails (the report names the root).
71
+ DSA_ORCHESTRATOR_LOG: join(root, "orchestrator.log") };
65
72
  const entry = sibling("../main");
66
73
  const cli = (argv) => new Promise((resolve, reject) => {
67
74
  const child = spawn(process.execPath, [entry, ...argv], { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
@@ -259,23 +266,34 @@ export async function drill(args, inherited = process.env, write = console.log)
259
266
  async function cleanup(home) {
260
267
  const ledger = () => readJournalSnapshot(orchLedger(home));
261
268
  const hosts = ledger().filter(e => e.type === "orchestrator" && e.pid).map(e => ({ pid: Number(e.pid), start: e.start ? String(e.start) : undefined }));
262
- const same = async (h) => { const now = await captureStart(h.pid); return now !== "" && (h.start === undefined || now === h.start); };
263
- for (const h of hosts)
264
- if (await same(h)) {
265
- try {
266
- process.kill(h.pid, "SIGTERM");
269
+ if (IS_WINDOWS) {
270
+ // Fail closed against unverified PIDs: only end hosts with a recorded creation token, through handle verification.
271
+ for (const h of hosts)
272
+ if (isWinStart(h.start))
273
+ await killProcess({ pid: h.pid, start: h.start }).catch(() => { });
274
+ }
275
+ else {
276
+ const same = async (h) => {
277
+ const now = await captureStart(h.pid).catch(() => "");
278
+ return now !== "" && (h.start === undefined || (h.start !== "" && now === h.start));
279
+ };
280
+ for (const h of hosts)
281
+ if (await same(h)) {
282
+ try {
283
+ process.kill(h.pid, "SIGTERM");
284
+ }
285
+ catch { }
267
286
  }
268
- catch { }
269
- }
270
- const end = Date.now() + 15_000;
271
- for (const h of hosts) {
272
- while (await same(h) && Date.now() < end)
273
- await delay(100);
274
- if (await same(h)) {
275
- try {
276
- process.kill(h.pid, "SIGKILL");
287
+ const end = Date.now() + 15_000;
288
+ for (const h of hosts) {
289
+ while (await same(h) && Date.now() < end)
290
+ await delay(100);
291
+ if (await same(h)) {
292
+ try {
293
+ process.kill(h.pid, "SIGKILL");
294
+ }
295
+ catch { }
277
296
  }
278
- catch { }
279
297
  }
280
298
  }
281
299
  const containment = new Containment(new ProcessTable());