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
@@ -16,7 +16,7 @@ import { watch } from 'node:fs';
16
16
  import { mkdir, readdir, unlink } from 'node:fs/promises';
17
17
  import { resolve, join } from 'node:path';
18
18
  import { setTimeout as delay } from 'node:timers/promises';
19
- import { contentHash } from "../kernel/ids.js";
19
+ import { contentHash, fileId } from "../kernel/ids.js";
20
20
  import { LifecycleFold, planDecisions } from "../kernel/lifecycle.js";
21
21
  import { scanInbox } from "../kernel/mailbox.js";
22
22
  import { orchInbox, pinnedDir } from "../paths.js";
@@ -529,26 +529,28 @@ export class Engine {
529
529
  }
530
530
  for (const req of scanned) {
531
531
  if (view.resolved.has(req.rid) || (view.admitted.has(req.rid) && view.admitted.get(req.rid).hash !== contentHash(req))) {
532
- await unlink(join(orchInbox(this.ledgers.home), `${req.rid}.json`)).catch(error => { if (error.code !== 'ENOENT')
532
+ await unlink(join(orchInbox(this.ledgers.home), `${fileId(req.rid)}.json`)).catch(error => { if (error.code !== 'ENOENT')
533
533
  throw error; });
534
534
  }
535
535
  }
536
536
  await this.deliverWakes();
537
537
  this.consumed = { length: this.intakeSeen, pending: this.lifecycle().open.size > 0 };
538
538
  }
539
+ /** Every valid call address starts with `<wid>` (`<wid>`, `<wid>/<key>`, or `<wid>@<rev>/<key>@<gen>`). */
540
+ workflowOf(to) {
541
+ const wid = typeof to === 'string' ? to.split(/[@/]/)[0] : '';
542
+ return wid ? this.store.workflows.get(wid) : undefined;
543
+ }
539
544
  findCall(to, bareWid = false) {
540
- for (const wf of this.store.workflows.values()) {
541
- // Every address of a call starts with its wid: another workflow's journal need not be decoded.
542
- if (wf.journal.loaded === false && !String(to).startsWith(wf.wid))
543
- continue;
544
- const calls = revisionEntries(wf).filter(e => e.type === 'call' || e.type === 'generation');
545
- // For sends, a bare wid addresses its call when the workflow has exactly one key (stop <wid> means the workflow).
546
- const keys = new Set(calls.map(e => String(e.key)));
547
- const named = calls.findLast(e => to === `${wf.wid}@${wf.revision}/${e.key}@${e.gen}` || to === `${wf.wid}/${e.key}` || (bareWid && to === wf.wid && keys.size === 1));
548
- const entry = named && calls.findLast(e => e.key === named.key);
549
- if (entry)
550
- return { wf, entry };
551
- }
545
+ const wf = this.workflowOf(to);
546
+ if (!wf || (!bareWid && to === wf.wid))
547
+ return undefined;
548
+ const calls = revisionEntries(wf).filter(e => e.type === 'call' || e.type === 'generation');
549
+ // For sends, a bare wid addresses its call when the workflow has exactly one key (stop <wid> means the workflow).
550
+ const keys = new Set(calls.map(e => String(e.key)));
551
+ const named = calls.findLast(e => to === `${wf.wid}@${wf.revision}/${e.key}@${e.gen}` || to === `${wf.wid}/${e.key}` || (bareWid && to === wf.wid && keys.size === 1));
552
+ const entry = named && calls.findLast(e => e.key === named.key);
553
+ return entry ? { wf, entry } : undefined;
552
554
  }
553
555
  /** P25: Explain an unknown send target with the addresses that would work. */
554
556
  unknownCall(to) {
@@ -563,15 +565,21 @@ export class Engine {
563
565
  const rids = req.body.rids;
564
566
  this.lifecycle();
565
567
  const sent = [...new Set(rids)].flatMap(rid => this.sends.get(rid) ?? []).sort((a, b) => a.at - b.at).map(item => item.request);
566
- for (const wf of this.store.workflows.values()) {
567
- const visited = new Set();
568
- for (const target of sent) {
569
- const found = this.findCall(target.body.to, true);
570
- if (!found || found.wf !== wf || visited.has(found.entry.key))
571
- continue;
572
- visited.add(found.entry.key);
573
- await this.executor.forward(req, this.context(wf, found.entry));
568
+ const visited = new Map();
569
+ for (const target of sent) {
570
+ const found = this.findCall(target.body?.to, true);
571
+ if (!found)
572
+ continue;
573
+ let keys = visited.get(found.wf);
574
+ if (!keys) {
575
+ keys = new Set();
576
+ visited.set(found.wf, keys);
574
577
  }
578
+ const key = found.entry.key;
579
+ if (keys.has(key))
580
+ continue;
581
+ keys.add(key);
582
+ await this.executor.forward(req, this.context(found.wf, found.entry));
575
583
  }
576
584
  }
577
585
  async decide(req) {
@@ -642,32 +650,27 @@ export class Engine {
642
650
  await this.startWorkflow(wf);
643
651
  }
644
652
  else if (req.kind === 'send') {
645
- // A generation that took this request is in the workflow it addresses (see findCall).
646
- const to = String(req.body?.to ?? '');
647
- const existing = [...this.store.workflows.values()].filter(wf => wf.journal.loaded !== false || to.startsWith(wf.wid)).flatMap(wf => wf.journal.entries().filter(e => e.type === 'generation' && generationRids(e).includes(req.rid)).map(entry => ({ wf, entry })))[0];
653
+ // A generation, model-choice or live forward that took this request is in the workflow it addresses (see findCall).
654
+ const addressed = this.workflowOf(req.body?.to);
655
+ const existing = addressed?.journal.entries().find(e => e.type === 'generation' && generationRids(e).includes(req.rid));
648
656
  if (existing) {
649
- this.dispatchGeneration(existing.wf, existing.entry);
657
+ this.dispatchGeneration(addressed, existing);
650
658
  return { action: 'apply' };
651
659
  }
652
660
  // A sealed choice was committed before its reply. Replay it even if another request has since opened a generation.
653
- const chosen = [...this.store.workflows.values()].filter(wf => wf.journal.loaded !== false || to.startsWith(wf.wid))
654
- .flatMap(wf => revisionEntries(wf).filter(e => e.type === 'model-choice' && e.rid === req.rid))[0];
661
+ const chosen = addressed && revisionEntries(addressed).find(e => e.type === 'model-choice' && e.rid === req.rid);
655
662
  if (chosen) {
656
663
  await this.note(req.rid, String(chosen.model), 'next-generation');
657
664
  return { action: 'apply' };
658
665
  }
659
- if (req.body?.kind === 'model') {
666
+ if (addressed && req.body?.kind === 'model') {
660
667
  // A live forward may have committed just before a crash, then been refused or superseded before replay.
661
668
  // Keep its original outcome; never turn it into a fresh sealed choice or send it to a newer generation.
662
- for (const wf of this.store.workflows.values()) {
663
- if (wf.journal.loaded === false && !to.startsWith(wf.wid))
664
- continue;
665
- const log = revisionEntries(wf), prior = log.find(e => e.type === 'forward' && e.rid === req.rid && e.envelope?.kind === 'model');
666
- if (!prior)
667
- continue;
668
- const entry = log.find(e => (e.type === 'call' || e.type === 'generation') && `${wf.wid}@${wf.revision}/${e.key}@${e.gen}` === prior.dest);
669
+ const log = revisionEntries(addressed), prior = log.find(e => e.type === 'forward' && e.rid === req.rid && e.envelope?.kind === 'model');
670
+ if (prior) {
671
+ const entry = log.find(e => (e.type === 'call' || e.type === 'generation') && `${addressed.wid}@${addressed.revision}/${e.key}@${e.gen}` === prior.dest);
669
672
  if (entry && !log.some(e => (e.type === JT.sealed || e.type === 'retired') && e.call === prior.dest))
670
- return this.executor.forward(req, this.context(wf, entry));
673
+ return this.executor.forward(req, this.context(addressed, entry));
671
674
  return { action: 'apply' };
672
675
  }
673
676
  }
@@ -770,11 +773,11 @@ export class Engine {
770
773
  return { action: 'reject', reason: 'unknown-workflow' };
771
774
  // A resume releases held work in its scope (one workflow, one session's, or all) and continues parked workflows;
772
775
  // running ones need nothing and final ones are final.
773
- const inScope = (wf) => wid ? wf.wid === wid : origin ? wf.origin === origin : true;
776
+ const scope = wid ? [this.store.workflows.get(wid)] : [...this.store.workflows.values()].filter(wf => origin ? wf.origin === origin : true);
774
777
  const took = (wf) => lazy(wf) ? wf.settled.resumed.includes(req.rid) : wf.journal.entries().some(e => e.type === 'resumed' && e.rid === req.rid);
775
778
  const replayed = this.ledgers.orch.entries().some(e => e.type === 'undrain' && e.rid === req.rid);
776
779
  // Held follow-ups of a finished workflow are released too; they run again through dispatchGeneration below.
777
- const holding = [...this.store.workflows.values()].filter(wf => inScope(wf) && this.held(wf.wid) && (!this.terminal(wf) || this.openFollowUps(wf)));
780
+ const holding = scope.filter(wf => this.held(wf.wid) && (!this.terminal(wf) || this.openFollowUps(wf)));
778
781
  const releasing = replayed || holding.length > 0;
779
782
  const final = (wf) => { const done = this.terminal(wf); return done && done.status !== 'parked' ? String(done.status) : undefined; };
780
783
  const parked = (wf) => this.terminal(wf)?.status === 'parked';
@@ -784,14 +787,14 @@ export class Engine {
784
787
  return { action: 'reject', reason: `terminal:${final(target)} — start a new run` };
785
788
  if (target && !parked(target) && !took(target))
786
789
  return { action: 'reject', reason: 'not-parked: already running' };
787
- if (!target && ![...this.store.workflows.values()].some(wf => inScope(wf) && (parked(wf) || took(wf))))
790
+ if (!target && !scope.some(wf => parked(wf) || took(wf)))
788
791
  return { action: 'reject', reason: 'nothing-to-resume' };
789
792
  }
790
793
  // A1: the pinned files of a finished workflow this resume starts are verified first (a start no longer hashes
791
794
  // them): a changed file refuses the resume before anything is recorded.
792
- for (const wf of this.store.workflows.values()) {
795
+ for (const wf of scope) {
793
796
  const done = this.terminal(wf);
794
- if (!inScope(wf) || !(done?.status === 'parked' || (releasing && !done)))
797
+ if (!(done?.status === 'parked' || (releasing && !done)))
795
798
  continue;
796
799
  try {
797
800
  await this.store.ready(wf);
@@ -802,9 +805,9 @@ export class Engine {
802
805
  }
803
806
  if (releasing && !replayed)
804
807
  await this.ledgers.orch.append('undrain', { rid: req.rid, ...(wid ? { wid } : origin ? { origin } : {}) });
805
- for (const wf of this.store.workflows.values()) {
806
- const done = this.terminal(wf), released = releasing && inScope(wf) && !done && (replayed || holding.includes(wf));
807
- if (!released && !(inScope(wf) && done?.status === 'parked'))
808
+ for (const wf of scope) {
809
+ const done = this.terminal(wf), released = releasing && !done && (replayed || holding.includes(wf));
810
+ if (!released && done?.status !== 'parked')
808
811
  continue;
809
812
  if (!took(wf)) {
810
813
  const n = (!released ? this.states.get(wf.wid)?.ev : undefined) ?? Math.max(0, ...wf.journal.entries().filter(e => e.type === 'ev').map(e => Number(e.n))) + 1;
@@ -821,7 +824,7 @@ export class Engine {
821
824
  await this.startWorkflow(wf);
822
825
  }
823
826
  // A settled workflow not decoded has no generation to run (each ended, its finished attention recorded).
824
- for (const wf of this.store.workflows.values())
827
+ for (const wf of scope)
825
828
  if (!lazy(wf))
826
829
  for (const entry of revisionEntries(wf).filter(e => e.type === 'generation'))
827
830
  this.dispatchGeneration(wf, entry);
@@ -5,6 +5,7 @@ import { appendFile, open, stat } from 'node:fs/promises';
5
5
  import { createInterface } from 'node:readline';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { Containment } from "../platform/containment.js";
8
+ import { winTagArg } from "../platform/windows.js";
8
9
  import { ulid } from "../kernel/ids.js";
9
10
  import { scriptLogPath } from "./snapshot.js";
10
11
  const LOG_LIMIT = 1 << 20, LOG_LINE = 8192, LOG_FULL = '[script.log limit (1 MiB) reached; further console output is dropped]\n';
@@ -14,7 +15,8 @@ const LOG_FULL_BYTES = Buffer.byteLength(LOG_FULL);
14
15
  /** P10, P22: One contained evaluator host, retired before any replacement starts. */
15
16
  export class EvaluatorClient {
16
17
  ledgers;
17
- containment = new Containment();
18
+ containment;
19
+ platform;
18
20
  child;
19
21
  timer;
20
22
  scan = Promise.resolve();
@@ -23,7 +25,11 @@ export class EvaluatorClient {
23
25
  logSizes = new Map();
24
26
  /** Workflows whose script the host runs now (started, not stopped, done or failed). */
25
27
  scripts = new Set();
26
- constructor(ledgers) { this.ledgers = ledgers; }
28
+ constructor(ledgers, options = {}) {
29
+ this.ledgers = ledgers;
30
+ this.containment = options.containment ?? new Containment();
31
+ this.platform = options.platform ?? process.platform;
32
+ }
27
33
  /** P10/P11: Persist one script console line per log event; diagnostics never fail the orchestrator. */
28
34
  log(line) {
29
35
  let event;
@@ -88,8 +94,10 @@ export class EvaluatorClient {
88
94
  await this.retire();
89
95
  const exec = `eval:${ulid()}`;
90
96
  await this.ledgers.orch.append('eval-host', { exec });
97
+ const hostEntry = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../evaluator/host.ts' : '../evaluator/host.js', import.meta.url));
91
98
  const child = await this.containment.spawn({ exec, command: process.execPath,
92
- args: [fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../evaluator/host.ts' : '../evaluator/host.js', import.meta.url))], cwd: this.ledgers.home, env: { DSA_HOME: this.ledgers.home } });
99
+ args: this.platform === 'win32' ? [hostEntry, winTagArg('DSA_EXEC', exec)] : [hostEntry],
100
+ cwd: this.ledgers.home, env: { DSA_HOME: this.ledgers.home } });
93
101
  this.child = child;
94
102
  this.stopping = false;
95
103
  const known = child.start ? [{ pid: child.pid, ppid: process.pid, start: child.start, tag: exec }] : [];
@@ -3,10 +3,21 @@
3
3
  import { delimiter } from "node:path";
4
4
  import { binDir } from "../../paths.js";
5
5
  import { JT } from "../../types.js";
6
- /** EX3: Custom/inherited tools win; the orchestrator's shim is the last PATH entry, never an empty entry. */
7
- export function commandEnvironment(home, id, call, env) {
8
- const bin = binDir(home), PATH = [...(env?.PATH ?? process.env.PATH ?? "").split(delimiter).filter(p => p && p !== bin), bin].join(delimiter);
9
- return { ...process.env, ...env, PATH, DSA_EXEC: id, DSA_CALL: call, DSA_HOME: home };
6
+ import { envValue, mergeEnv } from "../../platform/windows.js";
7
+ /** EX3: Custom/inherited tools win; the orchestrator's shim is the last PATH entry, never an empty entry. Windows names
8
+ * one variable whatever their case: a custom `Path` is the PATH the call got (not a second entry beside the inherited
9
+ * one), `ComSpec`/`COMSPEC` stay one definition, and `DSA_*` here replace any spelling the call passed. `platform` names
10
+ * the rules that apply (default: this process's; tests exercise the Windows rules on another host). */
11
+ export function commandEnvironment(home, id, call, env, options = {}) {
12
+ const platform = options.platform ?? process.platform, windows = platform === "win32";
13
+ const bin = binDir(home), separator = windows ? ";" : delimiter;
14
+ const merged = windows ? mergeEnv(process.env, env) : { ...process.env, ...env };
15
+ const path = windows ? envValue(merged, "PATH") : merged.PATH;
16
+ // A Windows PATH compares case-insensitively too: the same shim directory under another spelling is still one entry.
17
+ const shim = windows ? bin.toLowerCase() : bin;
18
+ const PATH = [...(path ?? "").split(separator).filter(dir => dir && (windows ? dir.toLowerCase() : dir) !== shim), bin].join(separator);
19
+ const overlays = { PATH, DSA_EXEC: id, DSA_CALL: call, DSA_HOME: home };
20
+ return windows ? mergeEnv(merged, overlays) : { ...merged, ...overlays };
10
21
  }
11
22
  export const COMMAND_INTENT = "command-intent";
12
23
  export const COMMAND_STARTED = "command-started";
@@ -47,7 +58,8 @@ export function liveCommandCalls(entries) {
47
58
  }
48
59
  return [...latest].filter(([call, id]) => !ended.has(call) && !withdrawn.has(id)).map(([call]) => call);
49
60
  }
50
- /** Retired command calls without a seal: their processes, if any still run, are ended at the next start. */
61
+ /** Retired command calls without a seal: their processes, if any still run, are ended at the next start. `group` is the
62
+ * Windows job host that owns the attempt's kernel group (absent on POSIX). */
51
63
  export function retiredCommandAttempts(entries) {
52
64
  const retired = new Set(entries.filter(e => e.type === "retired").map(e => String(e.call)));
53
65
  const sealed = new Set(entries.filter(e => e.type === JT.sealed).map(e => String(e.call)));
@@ -55,7 +67,10 @@ export function retiredCommandAttempts(entries) {
55
67
  for (const e of entries)
56
68
  if (e.type === COMMAND_INTENT && retired.has(String(e.call)) && !sealed.has(String(e.call))) {
57
69
  const started = entries.findLast(s => s.type === COMMAND_STARTED && s.id === e.id);
58
- result.push({ call: String(e.call), id: String(e.id), ...(started ? { pid: Number(started.pid), start: String(started.start) } : {}) });
70
+ const group = started?.group;
71
+ result.push({ call: String(e.call), id: String(e.id), ...(started ? { pid: Number(started.pid), start: String(started.start) } : {}),
72
+ ...(Number.isInteger(group?.pid) && typeof group?.start === "string" && group.start
73
+ ? { group: { pid: group.pid, start: group.start } } : {}) });
59
74
  }
60
75
  return result;
61
76
  }