pi-durable-subagents 1.5.0 → 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 +38 -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 +69 -35
  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 +221 -63
  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 +7 -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 +29 -22
  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
@@ -7,14 +7,25 @@
7
7
  // end it. Without lingering the user manager stops its scopes at logout, while a plain detached process survives it
8
8
  // (KillUserProcesses=no, the usual default): it starts as a plain detached process then.
9
9
  import { spawn } from "node:child_process";
10
- import { accessSync, constants, existsSync, statSync } from "node:fs";
10
+ import { accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, statSync } from "node:fs";
11
11
  import { userInfo } from "node:os";
12
- import { delimiter, isAbsolute, join } from "node:path";
13
- /** Whether `path` is a regular file this process may execute. */
14
- export function executableFile(path) {
12
+ import { delimiter, dirname, extname, isAbsolute, join, normalize, resolve, win32 } from "node:path";
13
+ import { comspec, envValue, IS_WINDOWS, winTagArg } from "./windows.js";
14
+ const WINDOWS_EXECUTABLE = new Set([".exe", ".com", ".cmd", ".bat"]);
15
+ /** Whether `path` is a regular file this process may execute. On Windows only a PE image or a batch file is directly
16
+ * executable; the extensionless `pi` (a POSIX shell script an npm install also writes) is not. `platform` names the
17
+ * rules that apply (default: this process's; tests exercise the Windows rules on another host). */
18
+ export function executableFile(path, platform = process.platform) {
15
19
  try {
16
20
  if (!statSync(path).isFile())
17
21
  return false;
22
+ if (platform === "win32") {
23
+ const ext = extname(path).toLowerCase();
24
+ if (!WINDOWS_EXECUTABLE.has(ext))
25
+ return false;
26
+ accessSync(path, constants.F_OK);
27
+ return true;
28
+ }
18
29
  accessSync(path, constants.X_OK);
19
30
  return true;
20
31
  }
@@ -22,17 +33,110 @@ export function executableFile(path) {
22
33
  return false;
23
34
  }
24
35
  }
25
- /** The first executable `name` in the directories of `PATH`, unresolved (a package-manager shim stays a shim). */
26
- export function findOnPath(name, PATH) {
27
- for (const dir of (PATH ?? "").split(delimiter)) {
28
- if (!dir || !isAbsolute(dir))
36
+ /** An absolute path under the given platform's rules: a Windows drive or UNC root is absolute only to `win32`. */
37
+ const absolute = (path, platform) => platform === "win32" ? isAbsolute(path) || win32.isAbsolute(path) : isAbsolute(path);
38
+ /** PATH directories. Windows separators are `;`, but POSIX-style test setups prepend `dir:...`; split those too, without
39
+ * cutting a `C:` drive prefix (a colon at index 1 after a letter). */
40
+ function pathDirs(PATH, platform) {
41
+ if (platform !== "win32")
42
+ return (PATH ?? "").split(delimiter);
43
+ const out = [];
44
+ for (const part of (PATH ?? "").split(";")) {
45
+ let start = 0;
46
+ for (let i = 0; i < part.length; i++)
47
+ if (part[i] === ":" && !(i === 1 && /[A-Za-z]/.test(part[0]))) {
48
+ out.push(part.slice(start, i));
49
+ start = i + 1;
50
+ }
51
+ out.push(part.slice(start));
52
+ }
53
+ return out;
54
+ }
55
+ /** The first executable `name` in the directories of `PATH`, unresolved (a package-manager shim stays a shim). Windows
56
+ * looks through PATHEXT: `pi` resolves to `pi.cmd`/`pi.exe`, never the extensionless POSIX shim beside them. */
57
+ export function findOnPath(name, PATH, options = {}) {
58
+ const platform = options.platform ?? process.platform;
59
+ const exts = platform === "win32" && !extname(name)
60
+ ? (options.pathext ?? envValue(process.env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map(ext => ext.toLowerCase()).filter(ext => WINDOWS_EXECUTABLE.has(ext))
61
+ : [""];
62
+ for (const dir of pathDirs(PATH, platform)) {
63
+ if (!dir || !absolute(dir, platform))
29
64
  continue;
30
- const file = join(dir, name);
31
- if (executableFile(file))
32
- return file;
65
+ for (const ext of exts) {
66
+ const file = join(dir, name + ext);
67
+ if (executableFile(file, platform))
68
+ return file;
69
+ }
70
+ }
71
+ return undefined;
72
+ }
73
+ /** What a spawn actually runs. An npm `.cmd` shim is not a PE image and Node cannot start it directly; the shim names
74
+ * the node script it runs, so that script runs under this Node instead and argv stays an argv (no shell quoting).
75
+ * A bare name is looked up on the command's own PATH (`options.env`), not this process's: the command's PATH may have
76
+ * the shim the caller's has not (a call's prepended `$DSA_HOME/bin`). */
77
+ /** Quote one argument for `cmd.exe /d /s /c ""path" "arg""` (passed with `windowsVerbatimArguments: true`).
78
+ * Wrapping every token in double quotes ensures cmd.exe treats spaces and metacharacters (`&`, `|`, `<`, `>`, `(`, `)`,
79
+ * `^`) literally both on the outer cmd.exe command line and when a batch shim forwards `%*` to Node. Embedded CR, LF or
80
+ * double quotes cannot be safely escaped for cmd.exe batch parsing (CVE-2024-27980 / BatBadBut) and are refused. */
81
+ function quoteCmdBatchArg(value) {
82
+ if (/[\r\n"]/.test(value))
83
+ throw new Error("Windows .cmd/.bat arguments cannot contain CR, LF or double quotes");
84
+ return `"${value}"`;
85
+ }
86
+ export function execTarget(command, args, options = {}) {
87
+ const platform = options.platform ?? process.platform, env = options.env ?? process.env;
88
+ if (platform !== "win32")
89
+ return { command, args: [...args] };
90
+ // A bare name is looked up through PATHEXT (`pi` → `pi.cmd`), the way the command's own shell would find it.
91
+ const resolved = !isAbsolute(command) && !/[\\/]/.test(command)
92
+ ? findOnPath(command, envValue(env, "PATH"), { platform, pathext: envValue(env, "PATHEXT") }) ?? command
93
+ : command;
94
+ if (!/\.(cmd|bat)$/i.test(resolved))
95
+ return { command: resolved, args: [...args] };
96
+ const script = shimScript(resolved);
97
+ if (script)
98
+ return { command: process.execPath, args: [script, ...args] };
99
+ // Outer quotes satisfy `cmd.exe /s /c`, which unconditionally strips the first and last `"` from the command string,
100
+ // leaving `"path" "arg1" ...` intact for cmd.exe and batch `%*` forwarding. Callers pass `windowsVerbatimArguments: true`.
101
+ const inner = [quoteCmdBatchArg(resolved), ...args.map(quoteCmdBatchArg)].join(" ");
102
+ return { command: comspec(env), args: ["/d", "/s", "/c", `"${inner}"`], verbatim: true };
103
+ }
104
+ /** The node script a generated `.cmd`/`.bat` shim runs, when it names one (`%dp0%` is the shim's directory).
105
+ * Shims that customize NODE_PATH or NODE_OPTIONS (e.g. pnpm global shims) are not unwrapped so their environment
106
+ * setup runs through cmd.exe instead of being silently dropped. */
107
+ export function shimScript(file) {
108
+ let text;
109
+ try {
110
+ text = readFileSync(file, "utf8");
111
+ }
112
+ catch {
113
+ return undefined;
114
+ }
115
+ if (/^\s*@?\s*set\s+"?NODE_(?:PATH|OPTIONS)=/im.test(text))
116
+ return undefined;
117
+ const dir = dirname(file);
118
+ for (const match of text.matchAll(/"([^"\r\n]+\.(?:js|mjs|cjs))"|'([^'\r\n]+\.(?:js|mjs|cjs))'/gi)) {
119
+ const raw = match[1] ?? match[2];
120
+ const rel = raw.replace(/^%~?dp0%?[\\/]*/i, "");
121
+ const resolved = rel !== raw
122
+ ? resolve(dir, process.platform === "win32" ? rel : rel.replace(/\\/g, "/"))
123
+ : normalize(raw.replace(/%~?dp0%?/gi, dir));
124
+ if (isAbsolute(resolved) && existsSync(resolved))
125
+ return resolved;
33
126
  }
34
127
  return undefined;
35
128
  }
129
+ /** The command processor a string command/gate runs through on this platform. */
130
+ export function shellTarget(command, exec, platform = process.platform) {
131
+ // A command line is readable across processes on Windows (the environment is not): the versioned ASCII marker lets
132
+ // recovery find a gate whose identity was never journaled, without mutating env.DSA_EXEC or breaking on `&`/quotes/Unicode.
133
+ return platform === "win32"
134
+ ? { command: exec ? `(if 0==1 echo ${winTagArg("DSA_EXEC", exec)} ) & ${command}` : command, args: [], shell: true }
135
+ : { command: "/bin/sh", args: ["-c", command] };
136
+ }
137
+ /** The PATH (and PATHEXT) of an environment under this platform's naming rules: a Windows environment spells it `Path`
138
+ * as often as `PATH`, and both are the one variable. POSIX reads `PATH` exactly. */
139
+ const envPath = (env) => IS_WINDOWS ? envValue(env, "PATH") : env.PATH;
36
140
  /** The `pi` the orchestrator launches subagents with: DSA_PI_BIN when set (it must be an executable file), else the
37
141
  * first `pi` on PATH. `problem` says why there is none. */
38
142
  export function resolvePi(env) {
@@ -42,8 +146,8 @@ export function resolvePi(env) {
42
146
  return { path: given, source: "DSA_PI_BIN" };
43
147
  return { problem: `DSA_PI_BIN=${given} is not an absolute path to an executable file` };
44
148
  }
45
- const found = findOnPath("pi", env.PATH);
46
- return found ? { path: found, source: "PATH" } : { problem: `pi was not found on PATH (${env.PATH || "unset"}) and DSA_PI_BIN is not set` };
149
+ const PATH = envPath(env), found = findOnPath("pi", PATH, { pathext: IS_WINDOWS ? envValue(env, "PATHEXT") : undefined });
150
+ return found ? { path: found, source: "PATH" } : { problem: `pi was not found on PATH (${PATH || "unset"}) and DSA_PI_BIN is not set` };
47
151
  }
48
152
  /** The starter cannot start an orchestrator that could launch no subagent. */
49
153
  export class PiNotFound extends Error {
@@ -100,6 +204,23 @@ export async function scopeRunner(env, options = {}) {
100
204
  function started(child) {
101
205
  return new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
102
206
  }
207
+ /** What the detached orchestrator's stdio is: discarded, unless DSA_ORCHESTRATOR_LOG names a file to append its stdout
208
+ * and stderr to. The orchestrator has no terminal, so without the log a start that fails before it records anything
209
+ * (`orchestrator` entry, `orchestrator-exit` reason) leaves no trace at all; the diagnostics of a failover drill,
210
+ * chaos scenario or a CI e2e case need it. An unusable path never fails the start: it falls back to "discarded". */
211
+ function orchestratorStdio(env) {
212
+ const log = env.DSA_ORCHESTRATOR_LOG;
213
+ if (!log)
214
+ return { stdio: "ignore", fds: [] };
215
+ try {
216
+ mkdirSync(dirname(log), { recursive: true });
217
+ const fd = openSync(log, "a", 0o600);
218
+ return { stdio: ["ignore", fd, fd], fds: [fd] };
219
+ }
220
+ catch {
221
+ return { stdio: "ignore", fds: [] };
222
+ }
223
+ }
103
224
  /** The variables the executor sets for one call's processes (a subagent, a command call, a gate). An orchestrator
104
225
  * started from inside a call (its CLI, a command that runs `start`) never carries them: with the call's DSA_EXEC it
105
226
  * would be one of that call's processes, and the call's fence (its end, a stop) would kill it. */
@@ -121,17 +242,30 @@ export async function launchOrchestrator(entry, env, options) {
121
242
  const childEnv = { ...orchestratorEnv(env), DSA_HOME: options.home, ...(pi.path ? { DSA_PI_BIN: pi.path } : {}) };
122
243
  const node = options.node ?? process.execPath, run = options.spawn ?? spawn;
123
244
  const runner = await scopeRunner(env, options);
124
- if (runner) {
245
+ const diagnostic = orchestratorStdio(childEnv);
246
+ // The child holds its own copies of the descriptors; ours are closed once it has started (a failed start closes them).
247
+ const close = () => { for (const fd of diagnostic.fds) {
125
248
  try {
126
- const child = run(runner, [...SCOPE_ARGS, "--description", "pi-durable-subagents orchestrator", "--", node, entry], { detached: true, stdio: "ignore", env: childEnv });
127
- await started(child);
128
- child.unref();
129
- return { pid: child.pid, scope: true, ...(pi.path ? { pi: pi.path } : {}) };
249
+ closeSync(fd);
130
250
  }
131
- catch { /* fall back to a plain detached process */ }
251
+ catch { /* already closed */ }
252
+ } };
253
+ try {
254
+ if (runner) {
255
+ try {
256
+ const child = run(runner, [...SCOPE_ARGS, "--description", "pi-durable-subagents orchestrator", "--", node, entry], { detached: true, stdio: diagnostic.stdio, env: childEnv });
257
+ await started(child);
258
+ child.unref();
259
+ return { pid: child.pid, scope: true, ...(pi.path ? { pi: pi.path } : {}) };
260
+ }
261
+ catch { /* fall back to a plain detached process */ }
262
+ }
263
+ const child = run(node, [entry], { detached: true, stdio: diagnostic.stdio, env: childEnv });
264
+ await started(child);
265
+ child.unref();
266
+ return { pid: child.pid, scope: false, ...(pi.path ? { pi: pi.path } : {}) };
267
+ }
268
+ finally {
269
+ close();
132
270
  }
133
- const child = run(node, [entry], { detached: true, stdio: "ignore", env: childEnv });
134
- await started(child);
135
- child.unref();
136
- return { pid: child.pid, scope: false, ...(pi.path ? { pi: pi.path } : {}) };
137
271
  }