@llblab/pi-actors 0.52.1 → 0.53.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.
@@ -11,6 +11,10 @@ import * as Limits from "./limits.js";
11
11
  const RUN_DELIVERY_SCHEMA = "run-delivery-v1";
12
12
  const MEMBER_FIELDS = new Set([
13
13
  "artifacts",
14
+ "parent_run",
15
+ "parent_run_instance_id",
16
+ "parent_state_dir",
17
+ "output",
14
18
  "run",
15
19
  "run_instance_id",
16
20
  "state_dir",
@@ -107,8 +111,32 @@ function parseMember(value) {
107
111
  const record = asRecord(value, "Completion batch member");
108
112
  assertExactFields(record, MEMBER_FIELDS, "Completion batch member");
109
113
  const parsedArtifacts = artifacts(record.artifacts);
114
+ const parentRun = record.parent_run === undefined
115
+ ? undefined
116
+ : boundedString(record.parent_run, "Completion batch member parent_run", 120);
117
+ const parentRunInstanceId = record.parent_run_instance_id === undefined
118
+ ? undefined
119
+ : boundedString(record.parent_run_instance_id, "Completion batch member parent_run_instance_id", 256);
120
+ const parentStateDir = record.parent_state_dir === undefined
121
+ ? undefined
122
+ : boundedString(record.parent_state_dir, "Completion batch member parent_state_dir", 4_096);
123
+ if (Boolean(parentRun) !== Boolean(parentRunInstanceId) ||
124
+ Boolean(parentRun) !== Boolean(parentStateDir)) {
125
+ throw new Error("Completion batch member parent lineage is incomplete");
126
+ }
127
+ const output = record.output === undefined
128
+ ? undefined
129
+ : boundedString(record.output, "Completion batch member output", 4_000);
110
130
  return {
111
131
  ...(parsedArtifacts ? { artifacts: parsedArtifacts } : {}),
132
+ ...(output ? { output } : {}),
133
+ ...(parentRun
134
+ ? {
135
+ parent_run: parentRun,
136
+ parent_run_instance_id: parentRunInstanceId,
137
+ parent_state_dir: parentStateDir,
138
+ }
139
+ : {}),
112
140
  run: boundedString(record.run, "Completion batch member run", 120),
113
141
  run_instance_id: boundedString(record.run_instance_id, "Completion batch member run_instance_id", 256),
114
142
  state_dir: boundedString(record.state_dir, "Completion batch member state_dir", 4_096),
@@ -566,13 +594,79 @@ function compactModelText(value, limit) {
566
594
  const compact = value.replaceAll(/\s+/g, " ").replaceAll("`", "'").trim();
567
595
  return compact.length > limit ? `${compact.slice(0, limit - 1)}…` : compact;
568
596
  }
569
- function formatCompletionMember(member) {
597
+ function memberIdentity(member) {
598
+ return `${member.state_dir}\0${member.run_instance_id}`;
599
+ }
600
+ function completionDepth(member, byIdentity) {
601
+ const visited = new Set();
602
+ let current = member;
603
+ let depth = 0;
604
+ while (current.parent_state_dir && current.parent_run_instance_id) {
605
+ const identity = `${current.parent_state_dir}\0${current.parent_run_instance_id}`;
606
+ if (visited.has(identity))
607
+ break;
608
+ visited.add(identity);
609
+ const parent = byIdentity.get(identity);
610
+ if (!parent)
611
+ break;
612
+ depth += 1;
613
+ current = parent;
614
+ }
615
+ return depth;
616
+ }
617
+ function orderCompletionForest(members) {
618
+ const byIdentity = new Map(members.map((member) => [memberIdentity(member), member]));
619
+ const children = new Map();
620
+ const roots = [];
621
+ for (const member of members) {
622
+ const parentIdentity = member.parent_state_dir && member.parent_run_instance_id
623
+ ? `${member.parent_state_dir}\0${member.parent_run_instance_id}`
624
+ : undefined;
625
+ if (!parentIdentity || !byIdentity.has(parentIdentity)) {
626
+ roots.push(member);
627
+ continue;
628
+ }
629
+ const siblings = children.get(parentIdentity) ?? [];
630
+ siblings.push(member);
631
+ children.set(parentIdentity, siblings);
632
+ }
633
+ const ordered = [];
634
+ const visited = new Set();
635
+ const visit = (member) => {
636
+ const identity = memberIdentity(member);
637
+ if (visited.has(identity))
638
+ return;
639
+ visited.add(identity);
640
+ ordered.push(member);
641
+ for (const child of children.get(identity) ?? [])
642
+ visit(child);
643
+ };
644
+ for (const root of roots)
645
+ visit(root);
646
+ for (const member of members)
647
+ visit(member);
648
+ return ordered;
649
+ }
650
+ function formatModelOutput(value, indent) {
651
+ return value
652
+ .replaceAll("`", "'")
653
+ .split(/\r?\n/u)
654
+ .map((line) => line.trimEnd())
655
+ .filter((line, index, lines) => line || (index > 0 && index < lines.length - 1))
656
+ .map((line) => `${indent} ${line}`)
657
+ .join("\n");
658
+ }
659
+ function formatCompletionMember(member, byIdentity) {
570
660
  const summary = compactModelText(member.summary, 200);
571
661
  const artifactEntries = Object.entries(member.artifacts ?? {}).slice(0, 4);
572
662
  const artifactText = artifactEntries.length === 0
573
663
  ? ""
574
664
  : `; artifacts: ${artifactEntries.map(([name, path]) => `${compactModelText(name, 120)}=\`${compactModelText(path, 320)}\``).join(", ")}`;
575
- return `- \`${compactModelText(member.run, 120)}\` — \`${member.status}\`: ${summary}${artifactText}`;
665
+ const indent = " ".repeat(Math.min(completionDepth(member, byIdentity), 8));
666
+ const output = member.output
667
+ ? `\n${indent} Output:\n${formatModelOutput(member.output, indent)}`
668
+ : "";
669
+ return `${indent}- \`${compactModelText(member.run, 120)}\` — \`${member.status}\`: ${summary}${artifactText}${output}`;
576
670
  }
577
671
  function formatStatusCounts(members) {
578
672
  const counts = new Map();
@@ -594,9 +688,13 @@ export function formatRunCompletionBatchMessage(batch) {
594
688
  `Window: \`${terminalTimes[0]}\` → \`${terminalTimes.at(-1)}\``,
595
689
  `Statuses: \`${formatStatusCounts(safe.members)}\``,
596
690
  ];
597
- const candidateRows = safe.members
691
+ const byIdentity = new Map(safe.members.map((member) => [
692
+ memberIdentity(member),
693
+ member,
694
+ ]));
695
+ const candidateRows = orderCompletionForest(safe.members)
598
696
  .slice(0, Limits.RUN_DELIVERY_MODEL_MAX_MEMBERS)
599
- .map(formatCompletionMember);
697
+ .map((member) => formatCompletionMember(member, byIdentity));
600
698
  const rows = [];
601
699
  for (const row of candidateRows) {
602
700
  const omitted = safe.members.length - rows.length - 1;
@@ -9,18 +9,18 @@ import * as Observability from "./observability.js";
9
9
  import * as Paths from "./paths.js";
10
10
  import * as Pi from "./pi.js";
11
11
  import * as RunDelivery from "./run-delivery.js";
12
+ import * as RunDeliveryLineage from "./run-delivery-lineage.js";
12
13
  export function createRunUiRuntime(deps) {
13
14
  let activeContext;
14
15
  let activeOwnerId;
15
16
  let animationInterval;
16
17
  let deliveryTimeout;
17
18
  let notifyTimeout;
18
- let recoverQueuedBatch = false;
19
19
  let recoverQueuedSteers = false;
20
20
  let running = false;
21
21
  let lastWatcherDiagnosticId = 0;
22
22
  const observation = Observability.createRunUiObservationState();
23
- const deliveryRecoveryDiagnostics = new Set();
23
+ const deliveryObservation = Observability.createRunUiObservationState();
24
24
  const retirementAttempts = new Set();
25
25
  const steerDiagnostics = new Set();
26
26
  const close = () => {
@@ -45,9 +45,7 @@ export function createRunUiRuntime(deps) {
45
45
  if (deliveryTimeout)
46
46
  clearTimeout(deliveryTimeout);
47
47
  deliveryTimeout = undefined;
48
- recoverQueuedBatch = false;
49
48
  recoverQueuedSteers = false;
50
- deliveryRecoveryDiagnostics.clear();
51
49
  steerDiagnostics.clear();
52
50
  if (animationInterval)
53
51
  clearInterval(animationInterval);
@@ -173,12 +171,11 @@ export function createRunUiRuntime(deps) {
173
171
  }
174
172
  }
175
173
  };
176
- const admitCompletionTransitions = (ownerId, transitions) => {
174
+ const admitCompletionTransitions = (ownerId, snapshot) => {
177
175
  const existing = journal(ownerId).completion_batch;
178
176
  if (existing)
179
177
  return true;
180
- const members = Observability.collectRunCompletionBatchMembers(transitions)
181
- .slice(0, Limits.RUN_DELIVERY_BATCH_MAX_MEMBERS);
178
+ const members = Observability.collectRunCompletionBatchMembers(snapshot.transitions, snapshot.summary.runs).slice(0, Limits.RUN_DELIVERY_BATCH_MAX_MEMBERS);
182
179
  if (members.length === 0)
183
180
  return false;
184
181
  RunDelivery.admitRunCompletionBatch({
@@ -189,6 +186,10 @@ export function createRunUiRuntime(deps) {
189
186
  return true;
190
187
  };
191
188
  const isIdle = (ctx) => typeof ctx.isIdle !== "function" || ctx.isIdle();
189
+ const isDeliveryRoot = (ownerId) => {
190
+ const inheritedOwner = RunDeliveryLineage.getProcessDeliveryOwnerId();
191
+ return inheritedOwner === undefined || inheritedOwner === ownerId;
192
+ };
192
193
  let flushCompletionBatch = (_ctx) => false;
193
194
  const flushSteers = (ctx, ownerId) => {
194
195
  const recovering = recoverQueuedSteers;
@@ -273,10 +274,19 @@ export function createRunUiRuntime(deps) {
273
274
  return false;
274
275
  const sink = Pi.createNotificationSink(deps.pi, ctx);
275
276
  retireCandidateRuns(ctx, snapshot.summary);
276
- const hasCompletionCandidates = Observability.collectRunCompletionBatchMembers(snapshot.transitions).length > 0;
277
- const hasCompletionBatch = Boolean(journal(ownerId).completion_batch);
277
+ const deliverySnapshot = isDeliveryRoot(ownerId)
278
+ ? Observability.readRunDeliverySnapshot(deliveryObservation, ownerId)
279
+ : undefined;
280
+ const hasCompletionCandidates = deliverySnapshot
281
+ ? Observability.collectRunCompletionBatchMembers(deliverySnapshot.transitions, deliverySnapshot.summary.runs).length > 0
282
+ : false;
283
+ const hasCompletionBatch = isDeliveryRoot(ownerId) &&
284
+ Boolean(journal(ownerId).completion_batch);
278
285
  admitSteerEvents(ctx, ownerId, snapshot.attentionEvents);
279
286
  Observability.pruneRunUiObservationState(observation, snapshot);
287
+ if (deliverySnapshot) {
288
+ Observability.pruneRunUiObservationState(deliveryObservation, deliverySnapshot);
289
+ }
280
290
  if (!terminalOnly) {
281
291
  Observability.deliverRunAttentionNotifications(snapshot.attentionEvents.filter((event) => !Observability.isRunSteerAttentionEvent(event)), sink);
282
292
  }
@@ -333,27 +343,34 @@ export function createRunUiRuntime(deps) {
333
343
  },
334
344
  });
335
345
  flushCompletionBatch = (ctx) => {
336
- if (!running || activeContext !== ctx || deps.getActiveContext() !== ctx)
337
- return false;
338
346
  const ownerId = activeOwnerId;
339
- if (!ownerId)
347
+ if (!running || !ownerId)
348
+ return false;
349
+ try {
350
+ if (Pi.getSessionId(ctx) !== ownerId)
351
+ return false;
352
+ }
353
+ catch {
340
354
  return false;
355
+ }
341
356
  if (flushSteers(ctx, ownerId))
342
357
  return true;
358
+ if (!isDeliveryRoot(ownerId))
359
+ return false;
343
360
  let batch = journal(ownerId).completion_batch;
344
361
  if (!batch) {
345
- const snapshot = Observability.readRunUiSnapshot(observation, ownerId);
346
- admitCompletionTransitions(ownerId, snapshot.transitions);
347
- Observability.pruneRunUiObservationState(observation, snapshot);
362
+ const snapshot = Observability.readRunDeliverySnapshot(deliveryObservation, ownerId);
363
+ admitCompletionTransitions(ownerId, snapshot);
364
+ Observability.pruneRunUiObservationState(deliveryObservation, snapshot);
348
365
  batch = journal(ownerId).completion_batch;
349
366
  }
350
367
  if (!batch)
351
368
  return false;
352
369
  if (batch.phase === "presented") {
353
370
  finishPresentedBatch(ownerId, batch);
354
- const snapshot = Observability.readRunUiSnapshot(observation, ownerId);
355
- admitCompletionTransitions(ownerId, snapshot.transitions);
356
- Observability.pruneRunUiObservationState(observation, snapshot);
371
+ const snapshot = Observability.readRunDeliverySnapshot(deliveryObservation, ownerId);
372
+ admitCompletionTransitions(ownerId, snapshot);
373
+ Observability.pruneRunUiObservationState(deliveryObservation, snapshot);
357
374
  batch = journal(ownerId).completion_batch;
358
375
  if (!batch)
359
376
  return false;
@@ -362,27 +379,16 @@ export function createRunUiRuntime(deps) {
362
379
  return true;
363
380
  const content = RunDelivery.formatRunCompletionBatchMessage(batch);
364
381
  if (batch.phase === "queued") {
365
- if (!recoverQueuedBatch)
366
- return true;
367
- recoverQueuedBatch = false;
368
- const evidence = Pi.inspectRunCompletionBatchSessionEvidence(ctx, batch.batch_id, content);
369
- if (evidence.status === "present")
370
- return true;
371
- if (evidence.status !== "absent") {
372
- const diagnosticKey = `${batch.batch_id}:${evidence.status}:${evidence.reason ?? ""}`;
373
- if (!deliveryRecoveryDiagnostics.has(diagnosticKey)) {
374
- deliveryRecoveryDiagnostics.add(diagnosticKey);
375
- ctx.ui.notify(`Actor completion recovery is ${evidence.status}: ${evidence.reason ?? "conflicting session evidence"}. Batch ${batch.batch_id} remains queued.`, "warning");
376
- }
377
- return true;
378
- }
379
- if (!RunDelivery.resetRunCompletionBatchPending({
382
+ if (!RunDelivery.markRunCompletionBatchPresented({
380
383
  batchId: batch.batch_id,
381
384
  ownerId,
382
385
  tempDir: Paths.EXTENSION_RUNTIME_PATHS.tempDir,
383
386
  }))
384
387
  return true;
385
- batch = journal(ownerId).completion_batch;
388
+ const accepted = journal(ownerId).completion_batch;
389
+ if (accepted)
390
+ finishPresentedBatch(ownerId, accepted);
391
+ return flushCompletionBatch(ctx);
386
392
  }
387
393
  if (!isIdle(ctx))
388
394
  return true;
@@ -405,19 +411,33 @@ export function createRunUiRuntime(deps) {
405
411
  })) {
406
412
  throw new Error("Completion batch changed before queue acknowledgment");
407
413
  }
408
- recoverQueuedBatch = false;
414
+ if (!RunDelivery.markRunCompletionBatchPresented({
415
+ batchId: batch.batch_id,
416
+ ownerId,
417
+ tempDir: Paths.EXTENSION_RUNTIME_PATHS.tempDir,
418
+ })) {
419
+ throw new Error("Completion batch changed before durable acceptance");
420
+ }
421
+ const accepted = journal(ownerId).completion_batch;
422
+ if (accepted)
423
+ finishPresentedBatch(ownerId, accepted);
424
+ ctx.ui.notify(`Actor completions ready: ${batch.members.length}`, "info");
409
425
  return true;
410
426
  };
411
427
  return {
412
428
  close,
413
429
  flushCompletionBatch,
414
430
  projectContext(messages, ctx) {
415
- if (!running || activeContext !== ctx || deps.getActiveContext() !== ctx) {
431
+ const ownerId = activeOwnerId;
432
+ if (!running || !ownerId)
416
433
  return messages;
434
+ try {
435
+ if (Pi.getSessionId(ctx) !== ownerId)
436
+ return messages;
417
437
  }
418
- const ownerId = activeOwnerId;
419
- if (!ownerId)
438
+ catch {
420
439
  return messages;
440
+ }
421
441
  const steerContext = Pi.dedupeRunSteerContext(messages);
422
442
  let contextMessages = steerContext.messages;
423
443
  for (const steer of journal(ownerId).steers) {
@@ -486,7 +506,6 @@ export function createRunUiRuntime(deps) {
486
506
  close();
487
507
  activeContext = ctx;
488
508
  activeOwnerId = ownerId;
489
- recoverQueuedBatch = true;
490
509
  recoverQueuedSteers = true;
491
510
  running = true;
492
511
  try {
@@ -223,6 +223,7 @@ export function createRecipeToolReloadWatcher(runtime, deps = {}) {
223
223
  let rootWatcher;
224
224
  let parentWatcher;
225
225
  let failureNotified = false;
226
+ let notifyAfterReload = false;
226
227
  const setWatchStatus = (watchStatus) => runtime.setWatchStatus?.(watchStatus);
227
228
  const close = () => {
228
229
  const closingRoot = rootWatcher;
@@ -234,6 +235,7 @@ export function createRecipeToolReloadWatcher(runtime, deps = {}) {
234
235
  if (reloadTimeout)
235
236
  clearTimeout(reloadTimeout);
236
237
  reloadTimeout = undefined;
238
+ notifyAfterReload = false;
237
239
  setWatchStatus("closed");
238
240
  };
239
241
  const reportCallbackError = (error) => {
@@ -256,15 +258,19 @@ export function createRecipeToolReloadWatcher(runtime, deps = {}) {
256
258
  reportCallbackError(error);
257
259
  }
258
260
  };
259
- const scheduleReload = (ctx) => {
261
+ const scheduleReload = (ctx, notifyActiveChange = false) => {
260
262
  failureNotified = false;
263
+ notifyAfterReload ||= notifyActiveChange;
261
264
  if (reloadTimeout)
262
265
  clearTimeout(reloadTimeout);
263
266
  reloadTimeout = setTimeout(() => {
264
267
  reloadTimeout = undefined;
265
268
  try {
266
269
  runtime.loadTools(ctx, deps.getResolutionContext?.());
267
- ctx.ui.notify("Recipe tools refreshed from ~/.pi/agent/recipes", "info");
270
+ if (notifyAfterReload) {
271
+ ctx.ui.notify("Recipe tools refreshed from ~/.pi/agent/recipes", "info");
272
+ }
273
+ notifyAfterReload = false;
268
274
  }
269
275
  catch (error) {
270
276
  notifyFailure(ctx);
@@ -295,7 +301,7 @@ export function createRecipeToolReloadWatcher(runtime, deps = {}) {
295
301
  parentWatcher = undefined;
296
302
  watcher.close();
297
303
  watchRoot(ctx, recipeRoot);
298
- scheduleReload(ctx);
304
+ scheduleReload(ctx, true);
299
305
  });
300
306
  parentWatcher = watcher;
301
307
  setWatchStatus("watching_parent");
@@ -319,17 +325,19 @@ export function createRecipeToolReloadWatcher(runtime, deps = {}) {
319
325
  return;
320
326
  }
321
327
  try {
322
- const watcher = watchPath(recipeRoot, () => {
328
+ const watcher = watchPath(recipeRoot, (_event, changedFile) => {
323
329
  if (rootWatcher !== watcher)
324
330
  return;
325
331
  if (!pathExists(recipeRoot)) {
326
332
  rootWatcher = undefined;
327
333
  watcher.close();
328
- scheduleReload(ctx);
334
+ scheduleReload(ctx, true);
329
335
  watchParent(ctx, recipeRoot);
330
336
  return;
331
337
  }
332
- scheduleReload(ctx);
338
+ const relativeChange = changedFile ? String(changedFile) : "";
339
+ const firstSegment = relativeChange.split(/[\\/]/u)[0];
340
+ scheduleReload(ctx, Boolean(relativeChange) && firstSegment !== "drafts");
333
341
  });
334
342
  rootWatcher = watcher;
335
343
  setWatchStatus("watching_root");
@@ -1,47 +1,40 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * Build the JavaScript-only distributive tree.
5
- *
6
- * This is intentionally standalone: it is package/build glue, not reusable
7
- * actor-domain behavior. It cleans dist, compiles TypeScript, mirrors runtime
8
- * assets, and syntax-checks packaged scripts.
4
+ * Builds or verifies the JavaScript-only distributive tree without exposing a
5
+ * partial tree to Pi or destroying the previous distributive on failure.
9
6
  */
10
7
 
11
8
  import { spawnSync } from "node:child_process";
12
9
  import {
13
10
  cpSync,
11
+ existsSync,
14
12
  mkdirSync,
13
+ mkdtempSync,
14
+ readFileSync,
15
15
  readdirSync,
16
+ renameSync,
16
17
  rmSync,
17
18
  writeFileSync,
18
19
  } from "node:fs";
19
- import { join } from "node:path";
20
+ import { join, relative } from "node:path";
21
+
22
+ const DIST_DIR = "dist";
23
+ const checkOnly = process.argv.includes("--check");
20
24
 
21
25
  function run(command, args) {
22
26
  const result = spawnSync(command, args, { stdio: "inherit" });
23
27
  if (result.error) throw result.error;
24
- if (result.status !== 0) process.exit(result.status ?? 1);
28
+ if (result.status !== 0) {
29
+ throw new Error(`${command} exited with status ${result.status ?? "unknown"}.`);
30
+ }
25
31
  }
26
32
 
27
- rmSync("dist", { recursive: true, force: true });
28
- mkdirSync("dist", { recursive: true });
29
-
30
- run(process.execPath, [
31
- join("node_modules", "typescript", "bin", "tsc"),
32
- "-p",
33
- "tsconfig.build.json",
34
- ]);
35
-
36
- mkdirSync(join("dist", "pi-actors"), { recursive: true });
37
- writeFileSync(
38
- join("dist", "pi-actors", "index.js"),
39
- 'export { default } from "../index.js";\n',
40
- "utf8",
41
- );
42
-
43
- for (const dir of ["scripts", "fixtures", "skills"]) {
44
- cpSync(dir, join("dist", dir), { recursive: true });
33
+ function listFiles(root, current = root) {
34
+ return readdirSync(current, { withFileTypes: true }).flatMap((entry) => {
35
+ const path = join(current, entry.name);
36
+ return entry.isDirectory() ? listFiles(root, path) : [relative(root, path)];
37
+ }).sort();
45
38
  }
46
39
 
47
40
  function listModuleScripts(root) {
@@ -52,9 +45,80 @@ function listModuleScripts(root) {
52
45
  });
53
46
  }
54
47
 
55
- const builtScripts = [
56
- ...listModuleScripts(join("dist", "scripts")),
57
- ...listModuleScripts(join("dist", "skills")),
58
- ];
48
+ function normalizeTextFiles(root) {
49
+ const textSuffixes = [".js", ".ts", ".mjs", ".json", ".md"];
50
+ for (const path of listFiles(root)) {
51
+ if (!textSuffixes.some((suffix) => path.endsWith(suffix))) continue;
52
+ const absolutePath = join(root, path);
53
+ const source = readFileSync(absolutePath, "utf8");
54
+ const normalized = source.replace(/\r\n?/g, "\n");
55
+ if (normalized !== source) writeFileSync(absolutePath, normalized, "utf8");
56
+ }
57
+ }
58
+
59
+ function assertTreesEqual(expectedRoot, actualRoot) {
60
+ if (!existsSync(expectedRoot)) {
61
+ throw new Error(`${expectedRoot} is missing; run npm run build.`);
62
+ }
63
+ const expectedFiles = listFiles(expectedRoot);
64
+ const actualFiles = listFiles(actualRoot);
65
+ if (JSON.stringify(expectedFiles) !== JSON.stringify(actualFiles)) {
66
+ throw new Error("dist file inventory is stale; run npm run build.");
67
+ }
68
+ for (const path of expectedFiles) {
69
+ if (!readFileSync(join(expectedRoot, path)).equals(readFileSync(join(actualRoot, path)))) {
70
+ throw new Error(`dist/${path} is stale; run npm run build.`);
71
+ }
72
+ }
73
+ }
74
+
75
+ function replaceDist(candidate) {
76
+ const backup = `.dist-backup-${process.pid}-${Date.now()}`;
77
+ const hadDist = existsSync(DIST_DIR);
78
+ if (hadDist) renameSync(DIST_DIR, backup);
79
+ try {
80
+ renameSync(candidate, DIST_DIR);
81
+ if (hadDist) rmSync(backup, { recursive: true, force: true });
82
+ } catch (error) {
83
+ if (hadDist && existsSync(backup) && !existsSync(DIST_DIR)) {
84
+ renameSync(backup, DIST_DIR);
85
+ }
86
+ throw error;
87
+ }
88
+ }
59
89
 
60
- run(process.execPath, ["--check", ...builtScripts]);
90
+ const candidate = mkdtempSync(join(process.cwd(), ".dist-build-"));
91
+ try {
92
+ run(process.execPath, [
93
+ join("node_modules", "typescript", "bin", "tsc"),
94
+ "-p",
95
+ "tsconfig.build.json",
96
+ "--outDir",
97
+ candidate,
98
+ ]);
99
+
100
+ mkdirSync(join(candidate, "pi-actors"), { recursive: true });
101
+ writeFileSync(
102
+ join(candidate, "pi-actors", "index.js"),
103
+ 'export { default } from "../index.js";\n',
104
+ "utf8",
105
+ );
106
+ normalizeTextFiles(candidate);
107
+ for (const dir of ["scripts", "fixtures", "skills"]) {
108
+ cpSync(dir, join(candidate, dir), { recursive: true });
109
+ }
110
+ const builtScripts = [
111
+ ...listModuleScripts(join(candidate, "scripts")),
112
+ ...listModuleScripts(join(candidate, "skills")),
113
+ ];
114
+ run(process.execPath, ["--check", ...builtScripts]);
115
+
116
+ if (checkOnly) {
117
+ assertTreesEqual(DIST_DIR, candidate);
118
+ console.log("pi-actors: dist is current");
119
+ } else {
120
+ replaceDist(candidate);
121
+ }
122
+ } finally {
123
+ rmSync(candidate, { recursive: true, force: true });
124
+ }
@@ -107,7 +107,7 @@ Run = Recipe + Trace + Control
107
107
  ```
108
108
 
109
109
  1. Spawn with the exact logical Recipe identity and caller-owned values.
110
- 2. Retain the returned `run:<id>` and normally wait for its settled completion batch instead of polling.
110
+ 2. Retain the returned `run:<id>` and normally wait for the root coordinator's settled completion batch instead of polling. Nested actor completions accumulate under their containing top-level Run and arrive in that one tree-compressed batch; descendant sessions do not need notification options.
111
111
  3. Inspect `view=trace` when retained observations or attention matter.
112
112
  4. Inspect `view=control` before diagnosing service readiness, stale work, or saturation.
113
113
  5. Send `message` only for an action declared and consumed by that controlled Recipe.
@@ -110,7 +110,7 @@ Statuses include `running`, `done`, `failed`, `exited`, `cancelled`, and `killed
110
110
 
111
111
  Ambient observation detects root terminal transitions and explicit retained Trace attention. Terminal transitions reconcile before semantic attention. Canonical attention is an in-memory wake hint, not a durable queue: observers prime retained ids at startup, deliver each later retained unseen id once, and bound memory to the current retained set across compaction. Persist durable recovery state or an artifact before emitting attention; compaction may discard older hints and its marker makes that history loss explicit. Terminal follow-up delivery persists handled/failure evidence so reloads retry unhandled transitions without duplicating completed notifications.
112
112
 
113
- Ordinary finite Runs project root terminal results through one completion scheduler. Eligible terminals remain authoritative in Run state while Pi is active; after `agent_settled`, session recovery, or an idle debounce, the scheduler snapshots at most 256 exact generations into one owner-fenced immutable batch. One batch causes one automatic agent turn, exposes at most 64 bounded model-facing rows, and marks member terminals handled only after the exact batch id and content appear in model-bound Pi context. Pending send failures retain bounded retry evidence. On restart, queued recovery inspects only a bounded active Pi session parent chain: exact message evidence waits for presentation without resend, proven absence returns the same batch to pending, and incomplete or conflicting evidence stays queued with a diagnostic. Duplicate exact context envelopes collapse before presentation.
113
+ Ordinary finite Runs project terminal results through one root-coordinator completion scheduler. Every detached runner passes its delivery-root owner and exact parent Run generation to nested actor processes. A descendant terminal remains authoritative but ineligible until its containing top-level Run is terminal; descendant Pi sessions never schedule completion follow-ups. After `agent_settled`, session recovery, or an idle debounce, the root scheduler snapshots the ready trees plus concurrently completed top-level Runs into one owner-fenced immutable batch of at most 256 exact generations. One batch causes one automatic agent turn, renders one visible gray operator card, exposes at most 64 bounded parent-child rows with semantic outputs to the model, and marks member terminals handled after Pi durably accepts the exact batch. Pending send failures retain bounded retry evidence. The narrow crash boundary between acceptance and finalization remains recoverable from bounded active-session evidence, but normal hot delivery never waits on a later context callback and therefore cannot block subsequent epochs. Duplicate exact context envelopes collapse before presentation.
114
114
 
115
115
  Sequence, parallel, repeat, and imported branches are internal execution topology and never own branch-level turns. Each separately launched Run owns its own generation and terminal lifecycle; compatible singleton reuse is not a new launch. Explicit semantic attention may intentionally add a checkpoint turn; Runs marked silent and synchronously acknowledged stop outcomes suppress automatic projection. Large semantic results stay outside compact completion rows and remain available in structured details, execution captures, or artifacts.
116
116