pi-durable-subagents 1.5.1 → 1.6.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 (64) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +69 -14
  3. package/dist/agent/capabilities.js +19 -11
  4. package/dist/agent/child/live.js +10 -2
  5. package/dist/agent/child.js +1 -1
  6. package/dist/agent/exact/capture.js +22 -2
  7. package/dist/agent/exact/child.js +8 -1
  8. package/dist/agent/exact/session.js +4 -2
  9. package/dist/agent/extension.js +13 -0
  10. package/dist/agent/main/snapshots.js +10 -9
  11. package/dist/agent/main.js +2 -1
  12. package/dist/cli/chaos/stack.js +53 -21
  13. package/dist/cli/control.js +4 -3
  14. package/dist/cli/doctor.js +3 -1
  15. package/dist/cli/drill/index.js +35 -17
  16. package/dist/cli/hold.js +221 -16
  17. package/dist/cli/main.js +7 -2
  18. package/dist/cli/restart.js +14 -2
  19. package/dist/cli/service.js +77 -2
  20. package/dist/cli/smoke.js +10 -6
  21. package/dist/compat/agents.js +47 -13
  22. package/dist/events/log.js +33 -11
  23. package/dist/kernel/cache.js +3 -2
  24. package/dist/kernel/fsx.js +203 -0
  25. package/dist/kernel/ids.js +11 -0
  26. package/dist/kernel/journal.js +42 -25
  27. package/dist/kernel/mailbox.js +7 -4
  28. package/dist/orchestrator/engine.js +49 -46
  29. package/dist/orchestrator/evaluator-client.js +11 -3
  30. package/dist/orchestrator/executor/command.js +21 -6
  31. package/dist/orchestrator/executor/digest.js +2 -2
  32. package/dist/orchestrator/executor/effects/gate.js +291 -56
  33. package/dist/orchestrator/executor/effects/index.js +3 -4
  34. package/dist/orchestrator/executor/effects/output.js +9 -5
  35. package/dist/orchestrator/executor/effects/prepare.js +34 -32
  36. package/dist/orchestrator/executor/effects/worktree-path.js +102 -0
  37. package/dist/orchestrator/executor/ended.js +7 -3
  38. package/dist/orchestrator/executor/index.js +216 -62
  39. package/dist/orchestrator/executor/memory.js +15 -0
  40. package/dist/orchestrator/executor/observe.js +6 -1
  41. package/dist/orchestrator/executor/session.js +10 -4
  42. package/dist/orchestrator/executor/sweep.js +34 -1
  43. package/dist/orchestrator/executor/usage.js +19 -5
  44. package/dist/orchestrator/executor/worktree.js +1 -1
  45. package/dist/orchestrator/main.js +4 -2
  46. package/dist/orchestrator/reader-ledger.js +3 -2
  47. package/dist/orchestrator/settled.js +2 -1
  48. package/dist/orchestrator/snapshot.js +24 -19
  49. package/dist/orchestrator/stats.js +2 -1
  50. package/dist/orchestrator/store.js +3 -2
  51. package/dist/platform/cmdline.js +3 -0
  52. package/dist/platform/command.js +184 -20
  53. package/dist/platform/containment.js +204 -40
  54. package/dist/platform/job.js +1404 -0
  55. package/dist/platform/launch.js +262 -29
  56. package/dist/platform/lease.js +351 -32
  57. package/dist/platform/lock.js +464 -16
  58. package/dist/platform/proctable.js +31 -2
  59. package/dist/platform/windows.js +642 -0
  60. package/dist/requests.js +1 -1
  61. package/dist/types.js +1 -0
  62. package/dist/ui/data.js +7 -6
  63. package/dist/ui/session.js +6 -5
  64. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.6.1
4
+
5
+ - **Standalone `pi` binary safety (#11, #7)**: When `pi` runs as a standalone compiled Bun/SEA binary (`process.execPath` points to `pi` rather than `node`), `launchOrchestrator`, `install-service`, Windows shim unwrapping and `npmCommand` now resolve a real Node.js runtime (`DSA_NODE_BIN` -> verified Node `process.execPath` -> `node`/`nodejs` on `PATH`, preferring `.exe`/`.com` on Windows and wrapping `.cmd` shims through `cmd.exe`), refuse any runtime resolving to `pi` while keeping multi-call shims (`mise`/`volta`/`asdf`) working, and add a hard `DSA_ORCHESTRATOR_LAUNCH` self-spawn guard inside the extension so a misconfigured launch exits immediately instead of spawning recursive headless `pi` sessions.
6
+ - **`pi` 1.5.1+ / 1.6.0 cache-warming compatibility**:
7
+ - Ignore 1-token `CacheWarmer` payloads in exact-fork request capture, exact-child request splicing and `live.json` waiting-state tracking, and stop cache warming inside exact children via `cache_warming_decision`.
8
+ - Account for standalone `type: "usage"` (`cache_warm`) session entries across session usage folds, live `entry_appended` observation, child usage reporting and execution `evidence()` (deduplicated by entry id and scoped to the call's own execution segment).
9
+
10
+ ## 1.6.0
11
+
12
+ - **Native Windows support** (Node.js 22.19+ and 24, no WSL or POSIX tools required; based on #4):
13
+ - **Kernel-released OS locks**: Windows file locks hold an exclusive `FileShare.None` file handle via a cached
14
+ `.NET Framework` helper compiled into a user-private directory (`%LOCALAPPDATA%` or `DSA_HOME`, with bounded
15
+ compile budget, self-healing and PowerShell fallback) so a killed holder releases its lock immediately in the kernel.
16
+ - **Windows Job Objects for commands, `hold` leases and gates**: Command attempts, `hold` leases and gates run inside
17
+ `KILL_ON_JOB_CLOSE` Job Objects owned by a per-launch `.NET Framework` winexe compiled from embedded C# with
18
+ `csc.exe` (no npm dependency or native addon). Compilation is staged and cancellable before durable intent; the
19
+ wrapper is assigned suspended before user code runs, receives exact UTF-16LE specs and normalized 32-bit DWORD exit
20
+ codes, publishes exit/gate records atomically with bounded sharing-violation retries, and tears down cleanly via
21
+ controlled `stop`/`DrainJob` on `--yield` and signals.
22
+ - **Handle-verified process observation and fencing**: Process discovery uses credential-isolated `System.Management`
23
+ `Win32_Process` snapshots with `FreeVirtualMemory` commit-based memory admission; process termination verifies
24
+ `GetProcessTimes` creation identity on open handles, refuses critical processes, fails closed on protected-PID
25
+ `EPERM` snapshot misses, reuses scanned `CommandLine` in `ended` diagnostics, reports budget breakdowns on fence
26
+ timeout, and triggers an immediate sweep retry on fence failure.
27
+ - **Filesystem, worktrees and 64-bit file identities**: Journal, cache, reader-ledger and UI readers preserve full
28
+ 64-bit NTFS `FileId` values as decimal strings; `latest` output publishes atomically without symlink privileges;
29
+ worktree keys reject path-like escapes on every platform, encode Windows-unspellable names (such as `tasks:0` or
30
+ reserved device names) under `.dsa/<wid>/.keys/<hash>`, and match Git worktrees by file-system identity across 8.3
31
+ aliases, casing and path prefixes.
32
+ - **Launchers, environments and Task Scheduler service**: Case-insensitive environment merging (`Path`/`PATH`,
33
+ `ComSpec`/`COMSPEC`), `PATHEXT` resolution, safe npm shim unwrapping (keeping `NODE_PATH`/`NODE_OPTIONS` shims
34
+ intact via verbatim `cmd.exe /d /s /c` quoting while rejecting CR/LF/quote injection), hidden `wscript.exe` Task
35
+ Scheduler service management with locale-independent `schtasks` checks, and `DSA_ORCHESTRATOR_LOG=<file>` for
36
+ capturing detached orchestrator output.
37
+ - **Full 3-OS CI matrix**: Linux, macOS and Windows all run unit tests, real-`pi` E2E suites and `pack:smoke` on
38
+ Node.js 22.19 and 24.
39
+ - **Engine lookup performance**: `Engine.findCall`, `withdraw` and single-target routing use O(1) indexed lookups
40
+ instead of scanning all workflows on every request.
41
+ - Fixed `chaos` scenario config generation (`providers.<name>.slots`) so diagnostic scenarios apply their intended
42
+ concurrency and timing settings.
43
+
3
44
  ## 1.5.1
4
45
 
5
46
  - 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
@@ -1,6 +1,7 @@
1
1
  // Upgrade safety (robustness.md layer 3, AC5): probe every pi surface we use before registering anything.
2
2
  // A missing tier-0 surface disables Durable Subagents with one exact message; a missing UI surface disables only
3
3
  // the UI. Never a silent failure, never a crash of pi.
4
+ import { isNodeProcess, resolveNode, resolvePi } from "../platform/launch.js";
4
5
  export const SURFACES = [
5
6
  ...["on", "registerTool", "appendEntry", "sendMessage", "setModel", "setThinkingLevel"].map(name => ({ tier: 0, where: "ExtensionAPI", name })),
6
7
  { tier: 0, where: "@earendil-works/pi-coding-agent", name: "defineTool" },
@@ -11,26 +12,33 @@ export const SURFACES = [
11
12
  { tier: 2, where: "@earendil-works/pi-tui", name: "wrapTextWithAnsi" },
12
13
  ...["Input", "SelectList", "fuzzyFilter", "matchesKey", "truncateToWidth", "visibleWidth"].map(name => ({ tier: 2, where: "@earendil-works/pi-tui", name })),
13
14
  ];
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"];
17
- /** AC5, P21, issue #1: Check the platform and the surfaces present in pi's modules and extension API; produce exact
18
- * degradation messages. */
19
- export function checkCapabilities(modules, api, version, platform = process.platform) {
15
+ /** The process layer (process tables and tree kill, file locks, the memory probe, command calls, service units) has a
16
+ * native implementation for these platforms; anywhere else every call would fail at spawn, so execution is disabled
17
+ * at load instead. Windows uses PowerShell/CIM for the process table and handle-verified Win32 termination for fencing. */
18
+ export const SUPPORTED_PLATFORMS = ["linux", "darwin", "win32"];
19
+ export function checkCapabilities(modules, api, version, platform = process.platform, runtime = {}) {
20
20
  const has = (s) => s.where === "ExtensionAPI" ? typeof api[s.name] === "function" : modules[s.where]?.[s.name] !== undefined;
21
21
  const missing = SURFACES.filter(s => !has(s));
22
22
  const name = (list) => list.map(s => `${s.where}.${s.name}`).join(", ");
23
23
  const pi = version ? `pi ${version}` : "this pi version";
24
+ const os = SUPPORTED_PLATFORMS.includes(platform);
24
25
  // The evaluator's CPU limit needs worker.cpuUsage and process.threadCpuUsage (Node 22.19); without them a runaway
25
26
  // script would never be stopped, so an older Node disables execution rather than run unguarded.
26
- const node = typeof process.threadCpuUsage === "function";
27
- const os = SUPPORTED_PLATFORMS.includes(platform);
28
- const execution = os && node && !missing.some(s => s.tier === 0), ui = execution && !missing.some(s => s.tier === 2);
27
+ // When pi itself is a standalone compiled binary (e.g. Bun via mise, #11), process.execPath is pi rather than node:
28
+ // check that a real Node.js executable can be resolved via DSA_NODE_BIN or PATH so the orchestrator can start.
29
+ const hostIsNode = runtime.isNode ?? isNodeProcess();
30
+ const node = hostIsNode ? (runtime.hasThreadCpuUsage ?? typeof process.threadCpuUsage === "function") : true;
31
+ const probeEnv = runtime.env ?? process.env;
32
+ const externalNode = os && !hostIsNode ? resolveNode(probeEnv, { platform, versions: { bun: "standalone" }, piPath: runtime.piPath ?? resolvePi(probeEnv, platform).path ?? process.execPath }) : undefined;
33
+ const hasNode = hostIsNode ? node : Boolean(externalNode?.path);
34
+ const execution = os && hasNode && !missing.some(s => s.tier === 0), ui = execution && !missing.some(s => s.tier === 2);
29
35
  const messages = [];
30
36
  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
- else if (!node)
37
+ 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.`);
38
+ else if (hostIsNode && !node)
33
39
  messages.push(`Durable Subagents disabled: it needs Node.js 22.19 or later (this is ${process.version}).`);
40
+ else if (!hostIsNode && !externalNode?.path)
41
+ messages.push(`Durable Subagents disabled: pi is running as a standalone binary, so it needs Node.js 22.19 or later on PATH (or DSA_NODE_BIN) to run the orchestrator (${externalNode?.problem}).`);
34
42
  else if (!execution)
35
43
  messages.push(`Durable Subagents disabled: ${pi} no longer provides ${name(missing.filter(s => s.tier === 0))}. Running workflows are untouched; run \`pi-durable-subagents smoke\` for details.`);
36
44
  else if (!ui)
@@ -3,7 +3,9 @@
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";
8
+ import { isCacheWarmingPayload } from "../exact/capture.js";
7
9
  export const LIVE_FILE = "live.json";
8
10
  const TAIL = 4000, EVERY_MS = 250;
9
11
  const tail = (text) => text.length > TAIL ? text.slice(-TAIL) : text;
@@ -18,7 +20,7 @@ export function registerLive(pi, enabled) {
18
20
  try {
19
21
  const tmp = `${path}.${process.pid}.tmp`;
20
22
  writeFileSync(tmp, JSON.stringify({ ...state, at: last }));
21
- renameSync(tmp, path);
23
+ replacePathSync(tmp, path);
22
24
  }
23
25
  catch { /* Watching is best effort; the session file stays the truth. */ }
24
26
  };
@@ -43,7 +45,13 @@ export function registerLive(pi, enabled) {
43
45
  const waiting = (_event, ctx) => { if (state?.phase !== "waiting")
44
46
  since = Date.now(); publish(ctx, { phase: "waiting", since }); };
45
47
  pi.on("turn_start", waiting);
46
- pi.on("before_provider_request", waiting);
48
+ // Ignore pi 1.5.1+ CacheWarmer refreshes: they fire before_provider_request without a matching message_end,
49
+ // which would leave live.json stuck in "waiting" while a tool is running.
50
+ pi.on("before_provider_request", (event, ctx) => {
51
+ if (isCacheWarmingPayload(event?.payload))
52
+ return;
53
+ waiting(event, ctx);
54
+ });
47
55
  pi.on("message_update", (event, ctx) => {
48
56
  const m = event.message;
49
57
  if (m.role !== "assistant" || !Array.isArray(m.content))
@@ -35,7 +35,7 @@ export function usage(entries, call) {
35
35
  own = call === undefined || String(e.data?.exec ?? '').startsWith(`${call}#`) || !/#\d+\.\d+$/.test(String(e.data?.exec ?? ''));
36
36
  if (!own)
37
37
  continue;
38
- const u = e.type === 'message' && e.message?.role === 'assistant' ? e.message.usage : undefined;
38
+ const u = e.type === 'message' && e.message?.role === 'assistant' ? e.message.usage : e.type === 'usage' ? e.usage : undefined;
39
39
  if (!u || (e.id && seen.has(e.id)))
40
40
  continue;
41
41
  if (e.id)
@@ -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) {
@@ -118,3 +119,22 @@ export function exactCaptureEnabled(config) {
118
119
  }
119
120
  /** The identity of a capture's payload: the sha256 of its serialized bytes. */
120
121
  export const payloadHash = (payload) => contentHash(payload);
122
+ /** Whether a provider payload is pi's 1-token cache-warming refresh (pi 1.5.1+ CacheWarmer).
123
+ * CacheWarmer replays the last request with maxTokens: 1 (clamped to 16 on OpenAI Responses); real turns
124
+ * use the model's maxTokens (thousands). */
125
+ export function isCacheWarmingPayload(payload) {
126
+ if (!payload || typeof payload !== "object")
127
+ return false;
128
+ const p = payload;
129
+ if (p.max_tokens === 1 || p.max_completion_tokens === 1 || p.maxTokens === 1)
130
+ return true;
131
+ if (p.max_output_tokens === 16 || p.max_output_tokens === 1)
132
+ return true;
133
+ const gen = p.generationConfig;
134
+ if (gen && typeof gen === "object" && gen.maxOutputTokens === 1)
135
+ return true;
136
+ const inf = p.inferenceConfig;
137
+ if (inf && typeof inf === "object" && inf.maxTokens === 1)
138
+ return true;
139
+ return false;
140
+ }
@@ -13,6 +13,7 @@
13
13
  import { readFile } from "node:fs/promises";
14
14
  import fs from "node:fs";
15
15
  import { CT, ENV } from "../../types.js";
16
+ import { isCacheWarmingPayload } from "./capture.js";
16
17
  import { splicePayload } from "./splice.js";
17
18
  /** Every refused tool result starts with this text (EX4). */
18
19
  export const EXACT_REFUSAL = "tool refused in exact fork:";
@@ -95,10 +96,16 @@ export function registerExactChild(pi, exact) {
95
96
  }
96
97
  ctx.abort();
97
98
  };
99
+ // pi 1.5.1+ CacheWarmer replays requests with maxTokens: 1 through before_provider_request; splicing the parent's
100
+ // max_tokens over a warm refresh would turn it into a full-length generation. Stop warming inside exact children
101
+ // (no-op on older pi versions that never emit this event).
102
+ pi.on("cache_warming_decision", () => ({ action: "stop" }));
98
103
  // EX4: the request the child would send is replaced by the parent's fields and the concatenated conversation.
99
104
  pi.on("before_provider_request", async (event, ctx) => {
100
105
  const payload = event.payload;
101
- if (!payload || typeof payload !== "object")
106
+ // Defense in depth: even if another extension overrides cache_warming_decision, never splice parent.max_tokens
107
+ // onto a 1-token cache-warming payload.
108
+ if (!payload || typeof payload !== "object" || isCacheWarmingPayload(payload))
102
109
  return;
103
110
  const capture = await captureOf();
104
111
  if (!capture)
@@ -10,7 +10,7 @@
10
10
  import { readFile } from "node:fs/promises";
11
11
  import { join } from "node:path";
12
12
  import { dsaHome } from "../../paths.js";
13
- import { writeCapture } from "./capture.js";
13
+ import { isCacheWarmingPayload, writeCapture } from "./capture.js";
14
14
  import { clone } from "./splice.js";
15
15
  /** The home of the dsa state (the captures live under it): $DSA_HOME or the default state root. */
16
16
  export const homeOf = (env = process.env) => dsaHome(env);
@@ -36,7 +36,9 @@ export async function registerCapture(pi, home) {
36
36
  let writing = Promise.resolve();
37
37
  pi.on("before_provider_request", (event, ctx) => {
38
38
  const payload = event.payload;
39
- if (!payload || typeof payload !== "object")
39
+ // pi 1.5.1+ CacheWarmer replays the last request with maxTokens: 1 (16 on OpenAI Responses) through this hook;
40
+ // never overwrite the real capture with a cache-warming payload or exact children would inherit a 1-token cap.
41
+ if (!payload || typeof payload !== "object" || isCacheWarmingPayload(payload))
40
42
  return;
41
43
  const sessionId = ctx.sessionManager?.getSessionId?.();
42
44
  if (!sessionId)
@@ -15,12 +15,25 @@ const LOADED = Symbol.for("pi-durable-subagents.loaded");
15
15
  /** P21: A child (DSA_EXEC set) without its execution surfaces cannot do its call; it reports the exact message on
16
16
  * stderr and exits 3, so the executor records the message per call and counts a loss (failed after K2) instead of
17
17
  * waiting on a child that will never act. Returns the stderr text, or undefined when the child may proceed. */
18
+ /** Issue #11: Defense in depth against a standalone compiled pi binary ever spawning itself as the orchestrator.
19
+ * launchOrchestrator sets DSA_ORCHESTRATOR_LAUNCH=1; a real Node.js orchestrator deletes it at startup, so seeing
20
+ * it inside the pi extension means pi itself was launched in place of node. */
21
+ export function orchestratorLaunchRefusal(env = process.env) {
22
+ if (!env[ENV.orchestratorLaunch])
23
+ return undefined;
24
+ return "Durable Subagents: refusing to run inside a pi process spawned as the orchestrator (set DSA_NODE_BIN to a Node.js 22.19+ executable or put node on PATH).";
25
+ }
18
26
  export function childRefusal(report, env) {
19
27
  if (!env[ENV.exec] || report.execution)
20
28
  return undefined;
21
29
  return report.messages.join("\n");
22
30
  }
23
31
  export default async function (pi) {
32
+ const loopRefusal = orchestratorLaunchRefusal(process.env);
33
+ if (loopRefusal !== undefined) {
34
+ writeSync(2, `${loopRefusal}\n`);
35
+ process.exit(4);
36
+ }
24
37
  const modules = { "@earendil-works/pi-coding-agent": coding, "@earendil-works/pi-tui": tui, "@earendil-works/pi-ai": ai };
25
38
  const report = checkCapabilities(modules, pi, typeof coding.VERSION === "string" ? String(coding.VERSION) : undefined);
26
39
  if (process.env.DSA_PROBE) {
@@ -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))