@llblab/pi-actors 0.40.1 → 0.41.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.
@@ -13,6 +13,7 @@ import {
13
13
  existsSync,
14
14
  mkdirSync,
15
15
  readFileSync,
16
+ readdirSync,
16
17
  statSync,
17
18
  } from "node:fs";
18
19
  import { dirname, join, relative } from "node:path";
@@ -31,8 +32,11 @@ async function importRuntimeModule(name) {
31
32
  );
32
33
  }
33
34
 
34
- const { appendRecipeContextToPiArgs, materializePiPrintPromptArg } =
35
- await importRuntimeModule("recipes-context");
35
+ const {
36
+ appendRecipeContextToPiArgs,
37
+ attachPiSessionDir,
38
+ materializePiPrintPromptArg,
39
+ } = await importRuntimeModule("recipes-context");
36
40
  const { buildReviewPreflightDiagnostic, formatReviewPreflightDiagnostic } =
37
41
  await importRuntimeModule("preflight-diagnostics");
38
42
  const { execCommandTemplate } = await importRuntimeModule("command-templates");
@@ -126,11 +130,24 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
126
130
  });
127
131
  }
128
132
 
133
+ function commandSessionFiles(sessionDir) {
134
+ if (!sessionDir) return [];
135
+ try {
136
+ return readdirSync(sessionDir, { withFileTypes: true })
137
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl"))
138
+ .map((entry) => relative(stateDir, join(sessionDir, entry.name)))
139
+ .sort();
140
+ } catch {
141
+ return [];
142
+ }
143
+ }
144
+
129
145
  function commandEvidenceStartRecord({
130
146
  commandDetail,
131
147
  commandId,
132
148
  materialized,
133
149
  options,
150
+ sessionDir,
134
151
  stage,
135
152
  occurrence,
136
153
  }) {
@@ -155,6 +172,7 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
155
172
  ...(materialized.promptBytes
156
173
  ? { prompt_bytes: materialized.promptBytes }
157
174
  : {}),
175
+ ...(sessionDir ? { session_dir: relative(stateDir, sessionDir) } : {}),
158
176
  attempts: [],
159
177
  semantic_acceptance:
160
178
  options?.evidenceContext?.acceptOutput === "review_evidence" ||
@@ -172,6 +190,7 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
172
190
  options,
173
191
  result,
174
192
  rawExitCode,
193
+ sessionDir,
175
194
  stage,
176
195
  occurrence,
177
196
  startedAt,
@@ -234,6 +253,10 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
234
253
  ...(materialized.promptBytes
235
254
  ? { prompt_bytes: materialized.promptBytes }
236
255
  : {}),
256
+ ...(sessionDir ? { session_dir: relative(stateDir, sessionDir) } : {}),
257
+ ...(commandSessionFiles(sessionDir).length > 0
258
+ ? { session_files: commandSessionFiles(sessionDir) }
259
+ : {}),
237
260
  attempts,
238
261
  exit_code: rawExitCode ?? result.code,
239
262
  effective_exit_code: result.code,
@@ -301,21 +324,26 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
301
324
  }
302
325
 
303
326
  async function observedExec(command, args, options) {
327
+ captureCounter += 1;
328
+ const commandId = `command-${String(captureCounter).padStart(3, "0")}`;
304
329
  const contextArgs = appendRecipeContextToPiArgs(
305
330
  command,
306
331
  args,
307
332
  meta.recipe_context_records,
308
333
  options?.actorRecipeContext,
309
334
  );
310
- const materialized = materializePiPrintPromptArg(
335
+ const session = attachPiSessionDir(
311
336
  command,
312
337
  contextArgs,
338
+ join(stateDir, "sessions", commandId),
339
+ );
340
+ const materialized = materializePiPrintPromptArg(
341
+ command,
342
+ session.args,
313
343
  promptFilePath,
314
344
  );
315
345
  const execArgs = materialized.args;
316
346
  const commandDetail = formatCommandDetail(command, execArgs);
317
- captureCounter += 1;
318
- const commandId = `command-${String(captureCounter).padStart(3, "0")}`;
319
347
  const stage =
320
348
  options?.actorRecipeContext?.alias ||
321
349
  options?.actorRecipeContext?.name ||
@@ -346,6 +374,7 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
346
374
  commandId,
347
375
  materialized,
348
376
  options,
377
+ sessionDir: session.sessionDir,
349
378
  stage,
350
379
  occurrence,
351
380
  });
@@ -357,6 +386,7 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
357
386
  command: commandDetail,
358
387
  ...(materialized.promptFile ? { prompt_file: materialized.promptFile } : {}),
359
388
  ...(materialized.promptBytes ? { prompt_bytes: materialized.promptBytes } : {}),
389
+ ...(session.sessionDir ? { session_dir: relative(stateDir, session.sessionDir) } : {}),
360
390
  });
361
391
  progressRunning();
362
392
  const captureDir = join(stateDir, "captures", commandId);
@@ -400,6 +430,7 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
400
430
  options,
401
431
  result,
402
432
  rawExitCode: rawResult.code,
433
+ sessionDir: session.sessionDir,
403
434
  stage,
404
435
  occurrence,
405
436
  startedAt: startedEvidence.started_at,
@@ -426,6 +457,10 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
426
457
  ...captureDetails(result),
427
458
  ...(materialized.promptFile ? { prompt_file: materialized.promptFile } : {}),
428
459
  ...(materialized.promptBytes ? { prompt_bytes: materialized.promptBytes } : {}),
460
+ ...(session.sessionDir ? { session_dir: relative(stateDir, session.sessionDir) } : {}),
461
+ ...(commandSessionFiles(session.sessionDir).length > 0
462
+ ? { session_files: commandSessionFiles(session.sessionDir) }
463
+ : {}),
429
464
  ...(preflightDiagnostic ? { preflight: preflightDiagnostic } : {}),
430
465
  });
431
466
  outbox(
@@ -238,14 +238,24 @@ function terminateProcessGroup(child, signal) {
238
238
  }
239
239
  }
240
240
 
241
- function runPi(prompt, model, thinking, ttlMs = 0) {
241
+ function sessionKey(value) {
242
+ return String(value).replaceAll(/[^A-Za-z0-9_.-]+/g, "-");
243
+ }
244
+
245
+ function runPi(prompt, model, thinking, ttlMs = 0, sessionDir, ownerSessionId) {
242
246
  return new Promise((resolve) => {
243
247
  const args = [
244
248
  "--tools",
245
249
  "inspect,message",
246
250
  "--no-context-files",
247
251
  "--no-skills",
248
- "--no-session",
252
+ ...(sessionDir
253
+ ? [
254
+ "--session-dir",
255
+ sessionDir,
256
+ ...(ownerSessionId ? ["--session-id", ownerSessionId] : []),
257
+ ]
258
+ : ["--no-session"]),
249
259
  ];
250
260
  if (model) {
251
261
  args.push("--model", model);
@@ -346,7 +356,14 @@ async function synthesize(config, locker) {
346
356
  }
347
357
  const transcript = await readRoomTranscript(config);
348
358
  const prompt = `Synthesize this transcript into a concise Markdown artifact. Mission: ${config.mission}. Include: Title, Consensus, Roles, Protocol, Final Artifact Shape, Next Actions, Open Questions. Use only the transcript evidence below.\n\nTRANSCRIPT:\n${transcript.slice(-24000)}`;
349
- const result = await runPi(prompt, config.model, config.thinking, config.subagentTtlMs);
359
+ const result = await runPi(
360
+ prompt,
361
+ config.model,
362
+ config.thinking,
363
+ config.subagentTtlMs,
364
+ `${runStateDir(config.runId)}/sessions/coordinator-synthesis`,
365
+ config.ownerSessionId,
366
+ );
350
367
  const output = result.stdout.trim();
351
368
  const diagnostics = config.stats
352
369
  ? `\n\n## Diagnostics\n\nparticipant_attempts=${config.stats.participantAttempts}\nparticipant_success=${config.stats.participantSuccess}\nparticipant_failures=${config.stats.participantFailures}\nsynthesis_code=${result.code}\ntranscript_messages=${transcript.trim() ? transcript.split("\n").length : 0}\n`
@@ -443,7 +460,7 @@ async function updateInboxMessagesStatus(runId, branchName, ids, status) {
443
460
  });
444
461
  }
445
462
 
446
- async function executeParticipantPrompt(role, basePrompt, config) {
463
+ async function executeParticipantPrompt(role, basePrompt, config, phase) {
447
464
  const branchName = role.name;
448
465
  const queuedMessages = await claimQueuedInboxMessages(
449
466
  config.runId,
@@ -469,7 +486,14 @@ async function executeParticipantPrompt(role, basePrompt, config) {
469
486
  finalPrompt += inboxSection;
470
487
  }
471
488
 
472
- const result = await runPi(finalPrompt, config.model, config.thinking, config.subagentTtlMs);
489
+ const result = await runPi(
490
+ finalPrompt,
491
+ config.model,
492
+ config.thinking,
493
+ config.subagentTtlMs,
494
+ `${runStateDir(config.runId)}/sessions/${sessionKey(`${role.name}-${phase}`)}`,
495
+ config.ownerSessionId,
496
+ );
473
497
 
474
498
  if (claimedIds.length > 0) {
475
499
  const finalStatus = result.code === 0 ? "handled" : "failed";
@@ -488,7 +512,7 @@ async function participantRound(role, round, config) {
488
512
  const displayName = role.name;
489
513
  const address = `branch:${config.runId}/${role.name}`;
490
514
  const prompt = `You are ${displayName} (${address}), ${role.persona}. Mission: ${config.mission}. Round ${round}/${config.rounds}. First call inspect target=${config.room} view=previews lines=30 and inspect target=${config.room} view=contacts. Then call message once to ${config.room} from ${address} type=chat.message. Body: 2-4 sentences that react to a named participant, propose the next coordination step, and refine the shared artifact. Use contacts for peer names and addresses. End stdout with summary <=160 chars.`;
491
- const result = await executeParticipantPrompt(role, prompt, config);
515
+ const result = await executeParticipantPrompt(role, prompt, config, `round-${round}`);
492
516
  if (config.stats) {
493
517
  config.stats.participantAttempts += 1;
494
518
  if (result.code === 0) config.stats.participantSuccess += 1;
@@ -506,14 +530,28 @@ async function participantJoin(role, config) {
506
530
  const displayName = role.name;
507
531
  const address = `branch:${config.runId}/${role.name}`;
508
532
  const joinPrompt = `You are ${displayName}, ${role.persona}. Mission: ${config.mission}. Call tool message exactly once with to=${shellQuote(config.room)}, from=${shellQuote(address)}, type='actor.join', summary='${displayName} joined', body JSON {"role":${JSON.stringify(role.persona)},"display":${JSON.stringify(displayName)},"caps":["coordination","synthesis"],"claim":"coordinate on mission"}. Then print one short line.`;
509
- await runPi(joinPrompt, config.model, config.thinking, config.subagentTtlMs);
533
+ await runPi(
534
+ joinPrompt,
535
+ config.model,
536
+ config.thinking,
537
+ config.subagentTtlMs,
538
+ `${runStateDir(config.runId)}/sessions/${sessionKey(`${role.name}-join`)}`,
539
+ config.ownerSessionId,
540
+ );
510
541
  }
511
542
 
512
543
  async function participantLeave(role, config) {
513
544
  const displayName = role.name;
514
545
  const address = `branch:${config.runId}/${role.name}`;
515
546
  const leavePrompt = `Call tool message exactly once with to=${shellQuote(config.room)}, from=${shellQuote(address)}, type='actor.leave', summary='${displayName} left', body='finished coordinated work'. Then print goodbye.`;
516
- await runPi(leavePrompt, config.model, config.thinking, config.subagentTtlMs);
547
+ await runPi(
548
+ leavePrompt,
549
+ config.model,
550
+ config.thinking,
551
+ config.subagentTtlMs,
552
+ `${runStateDir(config.runId)}/sessions/${sessionKey(`${role.name}-leave`)}`,
553
+ config.ownerSessionId,
554
+ );
517
555
  }
518
556
 
519
557
  // 1. consensus / swarm mode: iterative chat in a room
@@ -601,7 +639,12 @@ async function runPool(config, locker) {
601
639
 
602
640
  const taskId = assignedTask.task;
603
641
  const prompt = `You are ${role.name}, ${role.persona}. You have been assigned task ${taskId}: "${assignedTask.task}". Solve it as part of the overall mission: ${config.mission}. End your response with a clear summary.`;
604
- const result = await executeParticipantPrompt(role, prompt, config);
642
+ const result = await executeParticipantPrompt(
643
+ role,
644
+ prompt,
645
+ config,
646
+ `task-${taskId}`,
647
+ );
605
648
 
606
649
  process.stdout.write(
607
650
  `[${role.name} completed ${taskId}] code=${result.code}\n${result.stdout}\n`,
@@ -711,6 +754,9 @@ if (!config.model) {
711
754
  process.exit(2);
712
755
  }
713
756
  config.room = `room:${config.runId}`;
757
+ config.ownerSessionId = String(
758
+ (await readJsonFile(`${runStateDir(config.runId)}/run.json`)).ownerId ?? "",
759
+ );
714
760
 
715
761
  const failures = [];
716
762
  const locker = await startLocker(config);
@@ -2,7 +2,7 @@
2
2
  name: actors
3
3
  description: Required practical guide for non-trivial pi-actors use, including parallel actor launches, subagent fanout, and autonomous coordinator workflows. Read before using or changing spawn, message, inspect, actor runs, tools, recipes, command templates, async lifecycle, mailboxes, artifacts, and local orchestration mechanics.
4
4
  metadata:
5
- version: 0.40.1
5
+ version: 0.41.1
6
6
  ---
7
7
 
8
8
  # Actors (pi-actors)
@@ -125,21 +125,13 @@ Views:
125
125
  - `artifacts`: declared artifact paths/status plus the same bounded owned review-evidence manifest when present.
126
126
  - `recipes` target: registry summary for active, shadowed, invalid, disabled, and diagnostic recipe entries.
127
127
 
128
- Actor inspector commands:
129
-
130
- - `/actors-inspector-toggle [rows]`: open/close the compact table or set row count; default is 12 log rows when no size is supplied.
131
- - `/actors-inspector-filter all|room|direct|broadcast|unread|branch <name>|current-branch <name>|mention <text>`: narrow table previews without changing room/run state.
132
- - `/actors-inspect <number>`: open one visible row as a full-message view.
133
-
134
- The table is compact and optimistic by default: bounded body previews, capped noisy room rows, branch-local inbox previews, stable event ids in selected-message details, and an inline roster summary in the form `name/role` that wraps only when needed. Use `unread` for queued branch inbox work and `branch <name>` / `current-branch <name>` for one branch's room/direct/inbox traffic. Rows with `metadata.requires_response=true` show a `!` attention marker. `/actors-inspect <number>` marks that row read for the current session filter. Active roster members use the target color; members that sent `actor.leave` stay visible as inactive/muted participants from the current run. Actor display names come from `actor.join` bodies (`display`) or branch addresses, keeping debugger output plain and name-driven.
135
-
136
- Let terminal notifications arrive. They queue through Pi's follow-up delivery mode, so a busy coordinator finishes its current work before receiving concurrently completed actor results; the host's `followUpMode` controls whether queued results arrive together or one at a time. When a deferred actor result gates the next step, wait for that terminal follow-up instead of scheduling continuation loops, repeatedly inspecting, or mutating the actor's reviewed scope. Idle coordinators still start a normal turn through `triggerTurn: true`. Inspect early only for an operator request, a meaningful actor event, or diagnosis of an overdue or stuck run.
128
+ Let terminal notifications arrive. They queue through Pi's follow-up delivery mode, so a busy coordinator finishes its current work before receiving concurrently completed actor results; the host's `followUpMode` controls whether queued results arrive together or one at a time. File watching accelerates delivery, while a bounded ten-second terminal-only reconciliation pass recovers missed or failed watcher activity without replaying outbox traffic; watcher degradation and rearm remain visible diagnostics. When a deferred actor result gates the next step, wait for that terminal follow-up instead of scheduling continuation loops, repeatedly inspecting, or mutating the actor's reviewed scope. Idle coordinators still start a normal turn through `triggerTurn: true`. Inspect early only for an operator request, a meaningful actor event, or diagnosis of an overdue or stuck run.
137
129
 
138
130
  ## Runtime Communication Rules
139
131
 
140
132
  - Keep one public communication model: `spawn` creates actors, `message` sends typed envelopes, and `inspect` observes. Avoid adding public side channels or storage nouns when a normal actor address/view can express the operation.
141
133
  - Keep route and semantic type separate. Direct, room, coordinator, and session messages may share `type`; delivery behavior comes from `to`.
142
- - Treat inspector-visible communication logs as recipe evidence. Use `inspect room:<run> view=messages|previews`, `inspect run:<id> view=communication`, and the actor inspector table/full-message views to improve mailbox/artifact conventions after real runs.
134
+ - Treat persisted communication logs as recipe evidence. Use `inspect room:<run> view=messages|previews` and `inspect run:<id> view=communication` to improve mailbox/artifact conventions after real runs.
143
135
  - Any UI, summary, or aggregate view that scans run directories must apply coordinator/session ownership filters before exposing summaries or body previews.
144
136
  - Treat `communication.json` as visible actor context, not a global mutable truth table. Run-level snapshots should identify the run actor; branch-local snapshots should identify the branch actor.
145
137
  - Prefer same-run provenance checks on lateral actor routes. If `from` is accepted for room or branch routes, validate that it belongs to the addressed run.
@@ -166,6 +158,8 @@ Controls:
166
158
  - `repeat`: repeated node expansion.
167
159
  - `output`: output behavior selection.
168
160
  - Command stdout/stderr use bounded tails plus complete spill files; tool/run diagnostics expose byte counts, truncation, and spill paths, while pipelines fail with `incomplete pipeline stdin` rather than consuming a partial tail.
161
+ - Detached child `pi -p` commands receive isolated session storage under `sessions/command-NNN` in their owned run state, and command evidence records any resulting JSONL files. Coordinator-managed room/swarm participants use role/phase-scoped directories under the same run-local `sessions/` root so their turns remain discoverable too. Explicit `--no-session`, `--session`, `--session-id`, `--session-dir`, or `--fork` policy remains caller-owned and is never replaced.
162
+ - Persisted child-session inspection follows the latest JSONL entry branch, correlates tool results by call id, bounds previews, and redacts common secret-bearing fields/text. Thinking content is evidence only when Pi persisted an explicit `thinking` block; never infer or advertise hidden reasoning.
169
163
 
170
164
  Placeholders:
171
165
 
@@ -2,7 +2,7 @@
2
2
  name: swarm
3
3
  description: Subagent and actor orchestration with scoped locks, fanout, and quorum consensus. Use before launching multiple parallel actors or subagents for independent implementation, artifact generation, review, delegated audit, coordinated execution, or any workflow that needs autonomous coordinator decomposition and integration.
4
4
  metadata:
5
- version: 0.40.1
5
+ version: 0.41.1
6
6
  ---
7
7
 
8
8
  # Swarm