@llblab/pi-actors 0.40.1 → 0.41.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.
@@ -5,6 +5,37 @@
5
5
  */
6
6
  import * as Limits from "./limits.js";
7
7
  import * as ToolsMailbox from "./tools-mailbox.js";
8
+ export function withLeadingBlankLine(text) {
9
+ if (text.startsWith("\n\n"))
10
+ return text;
11
+ return text.startsWith("\n") ? `\n${text}` : `\n\n${text}`;
12
+ }
13
+ export function spaceToolResult(result) {
14
+ if (!result || typeof result !== "object")
15
+ return result;
16
+ const content = result.content;
17
+ if (!Array.isArray(content))
18
+ return result;
19
+ return {
20
+ ...result,
21
+ content: content.map((item) => item &&
22
+ typeof item === "object" &&
23
+ item.type === "text" &&
24
+ typeof item.text === "string"
25
+ ? {
26
+ ...item,
27
+ text: withLeadingBlankLine(item.text),
28
+ }
29
+ : item),
30
+ };
31
+ }
32
+ export function spaceToolError(error) {
33
+ if (error instanceof Error) {
34
+ error.message = withLeadingBlankLine(error.message);
35
+ return error;
36
+ }
37
+ return new Error(withLeadingBlankLine(String(error)));
38
+ }
8
39
  export function asRecord(value) {
9
40
  return value && typeof value === "object" && !Array.isArray(value)
10
41
  ? value
@@ -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.0
6
6
  ---
7
7
 
8
8
  # Actors (pi-actors)
@@ -125,13 +125,9 @@ 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:
128
+ Actor inspector navigation uses one command: `/actors-inspector-toggle` opens the centered overlay. It exposes explicit Tabs → Filters → List → Detail focus zones over the first run owned by the current session. Tabs use ←/→; ↓ enters Filters; ↑ at the top boundary does nothing. The filter bar contains only selectable controls; arrows move focus, Enter opens a compact value popup anchored beneath that filter, ↑/↓ hover a value, and Enter applies it. A filter cannot move down into an empty list. Accent text marks current values, a light background marks keyboard focus, and opening a nested popup preserves both its blue parent filter and the striped timeline outside the occluded cells. Lists use ↑/↓ and Enter; detail uses ↑/↓ and Enter/←. Escape cancels options or closes the overlay. The list body carries the selected run and live status above compact striped evidence rows; tabs, live refresh, empty states, and key hints remain visible so no subcommand grammar is required.
129
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.
130
+ Communication rows retain bounded body previews, capped noisy room traffic, branch-local inbox state, stable event ids, attention markers, and compact roster summaries. Turn rows come only from persisted owned child-session evidence and show source model/text at a glance. Turn detail remains bounded and includes command/stage, session/prompt/recipe provenance, user/assistant text, persisted thinking or explicit reasoning unavailability, stop/usage/error metadata, correlated tool arguments/results, truncation, and parse diagnostics. Active roster members use the target color, departed members stay muted, and display names come from `actor.join` bodies or branch addresses.
135
131
 
136
132
  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.
137
133
 
@@ -166,6 +162,8 @@ Controls:
166
162
  - `repeat`: repeated node expansion.
167
163
  - `output`: output behavior selection.
168
164
  - 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.
165
+ - 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.
166
+ - 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
167
 
170
168
  Placeholders:
171
169
 
@@ -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.0
6
6
  ---
7
7
 
8
8
  # Swarm
package/docs/README.md CHANGED
@@ -9,6 +9,7 @@ Living index of all documentation in the `/docs` directory.
9
9
  - [template-recipes.md](./template-recipes.md) — Saved JSON/Markdown recipe standard, imports, and reusable command-template graph composition
10
10
  - [async-runs.md](./async-runs.md) — Detached run lifecycle, state files, actor messages, cancellation, and ambient indicators
11
11
  - [actor-messages.md](./actor-messages.md) — Actor/message protocol for symmetric communication primitives
12
+ - [actor-inspector.md](./actor-inspector.md) — Manual owned-run navigation across communication and persisted subagent turns
12
13
  - [tool-registry.md](./tool-registry.md) — Local `pi-actors` registry storage and `register_tool` adaptation
13
14
  - [recipe-library.md](./recipe-library.md) — Packaged standard recipe library such as async subagents, coordinator pipelines, utilities, and music playback
14
15
  - [task-first-recipes.md](./task-first-recipes.md) — Task-first design map for deriving high-level recipes and missing component cells
@@ -0,0 +1,72 @@
1
+ # Actor Inspector
2
+
3
+ The actor inspector is a manually opened, read-only TUI navigator for owned actor runs. It keeps communication evidence and persisted subagent execution evidence in one hierarchy without merging their meanings.
4
+
5
+ ```text
6
+ owned run
7
+ → messages | turns
8
+ → filtered timeline
9
+ → bounded detail
10
+ ```
11
+
12
+ ## Navigation
13
+
14
+ `/actors-inspector-toggle` opens one centered overlay and remains the only command to remember. The first run owned by the current Pi session becomes the active run automatically; an empty session still exposes functional tabs and filters.
15
+
16
+ The overlay exposes an explicit focus hierarchy:
17
+
18
+ ```text
19
+ Run Enter opens owned runs, ↓ enters tabs
20
+ Tabs ←/→ chooses Messages or Turns, Enter opens filter parameters
21
+ Filters ↑/↓ chooses Channel/State or Subagent, Enter opens values to the right
22
+ Values ↑/↓ hovers, Enter applies, Escape returns one menu level
23
+ List ↑/↓ chooses, Enter/→ opens detail
24
+ Detail ↑/↓ scroll, Escape/← returns
25
+ Escape Close (or cancel the active options popup)
26
+ ```
27
+
28
+ Navigation stays bounded by available actions. `↑` on Run does nothing because no higher control exists. `↓` on Tabs enters the timeline only when it contains rows. Empty timelines therefore never receive focus.
29
+
30
+ Selection and focus remain separate visual states. Accent-blue text marks the current tab, active filter popup, and applied option. A light neutral background plus `▶` marks every selectable control or timeline row that currently owns keyboard focus. Opening a popup keeps its parent filter blue so the relationship remains visible. The footer uses accent color only for key names and arrows; descriptions remain muted.
31
+
32
+ The top Run control aligns vertically with the tab labels, names the selected owned run, and colors its textual lifecycle status semantically. Enter opens available owned runs immediately beneath it, overlaying the tab row rather than leaving a detached gap. The timeline no longer renders run metadata as a data row.
33
+
34
+ Filters live behind their tab rather than occupying a permanent row. Non-default filters remain visible as compact suffixes in the tab label, so hidden state never silently changes the timeline. Enter on Messages opens `Channel: <current>`, `State: <current>`, and `From: <current>`; `From` draws its values from the selected run's roster and limits rows to one actor. Enter on Turns opens `Subagent: <current>`. Enter on a parameter opens its alternative values as a second menu to the right while the parent and current value remain visible. Parent and child share their touching border rather than leaving or doubling a spacer column. Escape returns one level at a time. Moving focus never applies a value.
35
+
36
+ Nested menus overlay rather than replace the timeline. Only rows and columns containing menu borders or values occlude underlying cells. When adjacent menus have different heights, the unused corner remains transparent and preserves the separator, striped background, and timeline data beneath it.
37
+
38
+ The overlay uses most of the available terminal width and height. The bordered header keeps both tabs visible, while the list body shows the selected run and its current status above the evidence rows. Evidence rows retain stable alternating backgrounds based on their absolute timeline position, including while scrolling: even rows keep the dark overlay background, while odd rows use the neutral `customMessageBg` stripe. The footer exposes the active keys. Messages retain attention markers and unread filtering and open into bounded detail without leaving the overlay. The overlay refreshes while visible and distinguishes true empty timelines from filtered-empty results; filtered-empty copy points back to Enter on the active tab without moving focus.
39
+
40
+ ## Communication Timeline
41
+
42
+ The communication timeline reads run-local room, direct, branch-inbox, and coordinator/session message evidence. It preserves channel/sender filters, unread state, attention markers, roster-derived sender options, and bounded body previews. Unread remains filterable but does not consume a row column with a separate dot marker.
43
+
44
+ Communication evidence describes messages between actors. It does not prove model execution.
45
+
46
+ ## Turns Timeline
47
+
48
+ Detached child `pi -p` commands receive isolated session storage under their owned run state:
49
+
50
+ ```text
51
+ <run-state>/sessions/command-NNN/*.jsonl
52
+ ```
53
+
54
+ The runner records direct command-template session files in `review-evidence.json`. Coordinator-managed room/swarm participants also persist role/phase-scoped directories under the same `sessions/` root; the inspector discovers those owned files even though the coordinator, rather than the command-template runner, launched them. Explicit caller session policy (`--no-session`, `--session`, `--session-id`, `--session-dir`, or `--fork`) remains authoritative and is not replaced. A command may therefore have no inspector-visible session.
55
+
56
+ The turns timeline follows the latest persisted entry branch in each recorded Pi session and groups:
57
+
58
+ - User input associated with the response;
59
+ - Assistant text and host-persisted thinking blocks;
60
+ - Provider, model, stop reason, usage, and error metadata;
61
+ - Tool calls in assistant source order;
62
+ - Tool results correlated by `toolCallId`, regardless of completion order.
63
+
64
+ Enter opens the selected turn inside the overlay. Detail adds command/stage identity, session and prompt paths, recipe-context reference, tool arguments/results, truncation state, unmatched result counts, and parse diagnostics. ↑/↓ scroll long detail while the footer keeps return/close keys visible.
65
+
66
+ ## Evidence And Privacy Boundary
67
+
68
+ The inspector reads file-backed evidence; it does not reconstruct hidden provider reasoning or claim access to data Pi did not persist. When no explicit thinking block exists, detail shows `reasoning unavailable`.
69
+
70
+ Session text, communication bodies, and structured values remain bounded. Common secret-bearing keys, camelCase/private-key credentials, serialized JSON credentials, and inline credential patterns are redacted before rendering. Malformed JSONL lines, missing parents, cycles, missing sessions, and incomplete tool correlation remain diagnostic states rather than inferred data.
71
+
72
+ Ownership filtering happens before run summaries, communication previews, roster data, or session evidence become visible. Selection and read state reset across Pi sessions. Manifest session paths must resolve canonically beneath the selected owned run's `sessions/` directory; absolute paths, traversal, and symlink escapes remain invisible. The inspector never scans another coordinator session's run state into the current view.
package/index.ts CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  import * as AsyncRuns from "./lib/async-runs.ts";
9
9
  import * as CommandTemplates from "./lib/command-templates.ts";
10
- import * as Inspector from "./lib/inspector.ts";
10
+ import * as InspectorOverlay from "./lib/inspector-overlay.ts";
11
11
  import * as Observability from "./lib/observability.ts";
12
12
  import * as Paths from "./lib/paths.ts";
13
13
  import * as Pi from "./lib/pi.ts";
@@ -15,6 +15,7 @@ import * as Prompts from "./lib/prompts.ts";
15
15
  import * as Runtime from "./lib/runtime.ts";
16
16
  import * as Temp from "./lib/temp.ts";
17
17
  import * as Tools from "./lib/tools.ts";
18
+ import * as ToolsResponse from "./lib/tools-response.ts";
18
19
 
19
20
  export default function toolRegistryExtension(pi: Pi.ExtensionAPI) {
20
21
  let runsAnimationInterval: NodeJS.Timeout | undefined;
@@ -22,7 +23,6 @@ export default function toolRegistryExtension(pi: Pi.ExtensionAPI) {
22
23
  let activeRunContext: Pi.ExtensionContext | undefined;
23
24
  const runUi = Observability.createRunUiObservationState();
24
25
  const retirementAttempts = new Set<string>();
25
- const actorInspector = Inspector.createActorInspectorControllerState();
26
26
  const getRunOwnerId = Pi.getSessionId;
27
27
  const retireCandidateRuns = (
28
28
  ctx: Pi.ExtensionContext,
@@ -47,33 +47,6 @@ export default function toolRegistryExtension(pi: Pi.ExtensionAPI) {
47
47
  "zz-pi-actors-runs",
48
48
  snapshot.status ? ctx.ui.theme.fg("dim", snapshot.status) : undefined,
49
49
  );
50
- ctx.ui.setWidget(
51
- "zz-pi-actors-comms",
52
- actorInspector.visible
53
- ? () => ({
54
- invalidate() {},
55
- render(width: number) {
56
- return Inspector.renderActorInspectorPanel({
57
- stateRoot: Paths.EXTENSION_RUNTIME_PATHS.runStateRoot,
58
- state: actorInspector,
59
- ownerId,
60
- width,
61
- style: {
62
- actor: (text: string) => ctx.ui.theme.fg("accent", text),
63
- muted: (text: string) => ctx.ui.theme.fg("dim", text),
64
- preview: (text: string) => ctx.ui.theme.fg("text", text),
65
- stripe: (text: string) => text,
66
- stripeAlt: (text: string) =>
67
- ctx.ui.theme.bg("customMessageBg", text),
68
- target: (text: string) => ctx.ui.theme.fg("success", text),
69
- type: (text: string) => ctx.ui.theme.fg("warning", text),
70
- },
71
- });
72
- },
73
- })
74
- : undefined,
75
- { placement: "belowEditor" },
76
- );
77
50
  if (!notify) return;
78
51
  const notificationSink = Pi.createNotificationSink(pi, ctx);
79
52
  retireCandidateRuns(ctx, snapshot.summary);
@@ -115,7 +88,7 @@ export default function toolRegistryExtension(pi: Pi.ExtensionAPI) {
115
88
  const execute = definition.execute as (...args: unknown[]) => unknown;
116
89
  return {
117
90
  ...definition,
118
- execute: (...args: unknown[]) => {
91
+ execute: async (...args: unknown[]) => {
119
92
  const nextArgs = [...args];
120
93
  const ctx = nextArgs[4];
121
94
  if (ctx && typeof ctx === "object") {
@@ -124,7 +97,11 @@ export default function toolRegistryExtension(pi: Pi.ExtensionAPI) {
124
97
  getThinkingLevel: () => pi.getThinkingLevel(),
125
98
  };
126
99
  }
127
- return execute(...nextArgs);
100
+ try {
101
+ return ToolsResponse.spaceToolResult(await execute(...nextArgs));
102
+ } catch (error) {
103
+ throw ToolsResponse.spaceToolError(error);
104
+ }
128
105
  },
129
106
  } as T;
130
107
  };
@@ -147,6 +124,8 @@ export default function toolRegistryExtension(pi: Pi.ExtensionAPI) {
147
124
  return { skillPaths };
148
125
  });
149
126
  pi.on("session_start", async (_event, ctx) => {
127
+ // Clear the pre-overlay widget after hot reloads from older pi-actors builds.
128
+ ctx.ui.setWidget("zz-pi-actors-comms", undefined);
150
129
  activeRunContext = ctx;
151
130
  await Temp.prepareExtensionTempDir(Paths.EXTENSION_RUNTIME_PATHS.tempDir);
152
131
  runtime.loadTools(ctx);
@@ -167,39 +146,29 @@ export default function toolRegistryExtension(pi: Pi.ExtensionAPI) {
167
146
  recipeReload.close();
168
147
  });
169
148
  pi.registerCommand("actors-inspector-toggle", {
170
- description: Inspector.ACTOR_INSPECTOR_COMMAND_DESCRIPTIONS.toggle,
171
- handler: async (args, ctx) => {
172
- const result = Inspector.handleActorInspectorToggle(actorInspector, args);
173
- if (result.update) updateRunUi(ctx);
174
- ctx.ui.notify(result.notify, result.type);
175
- },
176
- });
177
- pi.registerCommand("actors-inspector-filter", {
178
- description: Inspector.ACTOR_INSPECTOR_COMMAND_DESCRIPTIONS.filter,
179
- handler: async (args, ctx) => {
180
- const result = Inspector.handleActorInspectorFilter(actorInspector, args);
181
- if (result.update) updateRunUi(ctx);
182
- ctx.ui.notify(result.notify, result.type);
183
- },
184
- });
185
- pi.registerCommand("actors-inspect", {
186
- description: Inspector.ACTOR_INSPECTOR_COMMAND_DESCRIPTIONS.inspect,
187
- handler: async (args, ctx) => {
188
- const previews = Inspector.readActorInspectorPreviews(
189
- Paths.EXTENSION_RUNTIME_PATHS.runStateRoot,
190
- actorInspector.rows,
191
- Inspector.getActorInspectorPreviewOptions(
192
- actorInspector,
193
- getRunOwnerId(ctx),
194
- ),
195
- );
196
- const result = Inspector.handleActorInspectorInspect(
197
- actorInspector,
198
- args,
199
- previews,
149
+ description: "Toggle the keyboard-driven actor inspector overlay",
150
+ handler: async (_args, ctx) => {
151
+ ctx.ui.setWidget("zz-pi-actors-comms", undefined);
152
+ await ctx.ui.custom<void>(
153
+ (tui, theme, _keybindings, done) =>
154
+ new InspectorOverlay.ActorInspectorOverlay({
155
+ done,
156
+ ownerId: getRunOwnerId(ctx),
157
+ stateRoot: Paths.EXTENSION_RUNTIME_PATHS.runStateRoot,
158
+ theme,
159
+ tui,
160
+ }),
161
+ {
162
+ overlay: true,
163
+ overlayOptions: {
164
+ anchor: "center",
165
+ width: "94%",
166
+ minWidth: 72,
167
+ maxHeight: "94%",
168
+ margin: 1,
169
+ },
170
+ },
200
171
  );
201
- if (result.update) updateRunUi(ctx);
202
- ctx.ui.notify(result.notify, result.type);
203
172
  },
204
173
  });
205
174
  pi.on("before_agent_start", async (event) => ({