@llblab/pi-actors 0.40.0 → 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.
Files changed (45) hide show
  1. package/AGENTS.md +3 -3
  2. package/BACKLOG.md +22 -1
  3. package/CHANGELOG.md +31 -0
  4. package/README.md +5 -4
  5. package/dist/index.js +30 -51
  6. package/dist/lib/inspector-overlay.d.ts +84 -0
  7. package/dist/lib/inspector-overlay.js +627 -0
  8. package/dist/lib/inspector.d.ts +17 -33
  9. package/dist/lib/inspector.js +98 -151
  10. package/dist/lib/limits.d.ts +3 -0
  11. package/dist/lib/limits.js +3 -0
  12. package/dist/lib/observability.d.ts +1 -1
  13. package/dist/lib/observability.js +2 -2
  14. package/dist/lib/pi.d.ts +1 -1
  15. package/dist/lib/pi.js +2 -2
  16. package/dist/lib/prompts.d.ts +1 -1
  17. package/dist/lib/prompts.js +3 -3
  18. package/dist/lib/recipes-context.d.ts +5 -0
  19. package/dist/lib/recipes-context.js +15 -0
  20. package/dist/lib/session-evidence.d.ts +45 -0
  21. package/dist/lib/session-evidence.js +204 -0
  22. package/dist/lib/tools-response.d.ts +3 -0
  23. package/dist/lib/tools-response.js +31 -0
  24. package/dist/scripts/async-runner.mjs +40 -5
  25. package/dist/scripts/coordinator.mjs +55 -9
  26. package/dist/skills/actors/SKILL.md +10 -9
  27. package/dist/skills/swarm/SKILL.md +4 -2
  28. package/docs/README.md +1 -0
  29. package/docs/actor-inspector.md +72 -0
  30. package/docs/async-runs.md +2 -2
  31. package/index.ts +32 -63
  32. package/lib/inspector-overlay.ts +735 -0
  33. package/lib/inspector.ts +132 -204
  34. package/lib/limits.ts +3 -0
  35. package/lib/observability.ts +3 -3
  36. package/lib/pi.ts +3 -3
  37. package/lib/prompts.ts +3 -3
  38. package/lib/recipes-context.ts +25 -0
  39. package/lib/session-evidence.ts +302 -0
  40. package/lib/tools-response.ts +33 -0
  41. package/package.json +1 -1
  42. package/scripts/async-runner.mjs +40 -5
  43. package/scripts/coordinator.mjs +55 -9
  44. package/skills/actors/SKILL.md +10 -9
  45. package/skills/swarm/SKILL.md +4 -2
@@ -0,0 +1,735 @@
1
+ /**
2
+ * Keyboard-driven actor inspector overlay.
3
+ * Zones: overlay shell, tabs, owned-run/subagent selection, compact striped rows
4
+ * Owns interactive TUI navigation; evidence parsing remains in inspector/session domains.
5
+ */
6
+
7
+ import * as path from "node:path";
8
+ import { stripVTControlCharacters } from "node:util";
9
+
10
+ import type { Theme } from "@earendil-works/pi-coding-agent";
11
+ import {
12
+ matchesKey,
13
+ truncateToWidth,
14
+ visibleWidth,
15
+ type TUI,
16
+ } from "@earendil-works/pi-tui";
17
+
18
+ import * as Inspector from "./inspector.ts";
19
+
20
+ export type ActorInspectorOverlayTab = "communications" | "turns";
21
+
22
+ export interface ActorInspectorOverlayOptions {
23
+ done: () => void;
24
+ ownerId: string;
25
+ stateRoot: string;
26
+ theme: Theme;
27
+ tui: TUI;
28
+ }
29
+
30
+ export class ActorInspectorOverlay {
31
+ private readonly done: () => void;
32
+ private readonly ownerId: string;
33
+ private readonly stateRoot: string;
34
+ private readonly theme: Theme;
35
+ private readonly tui: TUI;
36
+ private readonly refreshTimer: NodeJS.Timeout;
37
+ private runIndex = 0;
38
+ private communicationChannel: "all" | "broadcast" | "direct" | "room" = "all";
39
+ private communicationFrom = "all";
40
+ private communicationUnread = false;
41
+ private contentStripeIndices: number[] = [];
42
+ private detailCommunication?: Inspector.ActorInspectorPreview;
43
+ private detailOpen = false;
44
+ private detailScroll = 0;
45
+ private detailTurn?: Inspector.ActorInspectorTurnItem;
46
+ private readonly readKeys = new Set<string>();
47
+ private focus: "runs" | "tabs" | "list" | "detail" | "select" = "tabs";
48
+ private filterControlIndex = 0;
49
+ private menuLevel: "run" | "filter" | "value" = "filter";
50
+ private selectorIndex = 0;
51
+ private rowIndex = 0;
52
+ private selectedRun?: string;
53
+ private subagentIndex = 0;
54
+ private tab: ActorInspectorOverlayTab = "communications";
55
+
56
+ constructor(options: ActorInspectorOverlayOptions) {
57
+ this.done = options.done;
58
+ this.ownerId = options.ownerId;
59
+ this.stateRoot = options.stateRoot;
60
+ this.theme = options.theme;
61
+ this.tui = options.tui;
62
+ this.refreshTimer = setInterval(() => this.tui.requestRender(), 1000);
63
+ this.refreshTimer.unref?.();
64
+ }
65
+
66
+ handleInput(data: string): void {
67
+ const runs = this.runs();
68
+ this.ensureSelectedRun(runs);
69
+ if (matchesKey(data, "ctrl+c")) {
70
+ this.done();
71
+ return;
72
+ }
73
+ if (matchesKey(data, "escape")) {
74
+ if (this.focus === "select") {
75
+ if (this.menuLevel === "value") {
76
+ this.menuLevel = "filter";
77
+ this.selectorIndex = this.filterControlIndex;
78
+ } else this.focus = this.menuLevel === "run" ? "runs" : "tabs";
79
+ } else if (this.focus === "detail") this.closeDetail();
80
+ else this.done();
81
+ this.tui.requestRender();
82
+ return;
83
+ }
84
+ if (this.focus === "select") {
85
+ const options = this.menuOptions();
86
+ if (matchesKey(data, "up"))
87
+ this.selectorIndex = Math.max(0, this.selectorIndex - 1);
88
+ else if (matchesKey(data, "down"))
89
+ this.selectorIndex = Math.min(options.length - 1, this.selectorIndex + 1);
90
+ else if (matchesKey(data, "left")) this.backMenu();
91
+ else if (
92
+ matchesKey(data, "return") ||
93
+ (matchesKey(data, "right") && this.menuLevel !== "value")
94
+ )
95
+ this.applyMenuOption(options[this.selectorIndex]);
96
+ this.tui.requestRender();
97
+ return;
98
+ }
99
+ if (this.focus === "detail") {
100
+ if (matchesKey(data, "up")) this.detailScroll = Math.max(0, this.detailScroll - 1);
101
+ else if (matchesKey(data, "down")) this.detailScroll += 1;
102
+ else if (matchesKey(data, "left")) this.closeDetail();
103
+ this.tui.requestRender();
104
+ return;
105
+ }
106
+ if (this.focus === "runs") {
107
+ if (matchesKey(data, "down")) this.focus = "tabs";
108
+ else if (matchesKey(data, "return") && runs.length > 0) this.openRunMenu();
109
+ } else if (this.focus === "tabs") {
110
+ if (matchesKey(data, "left") || matchesKey(data, "right")) {
111
+ this.tab = this.tab === "communications" ? "turns" : "communications";
112
+ this.filterControlIndex = 0;
113
+ this.rowIndex = 0;
114
+ } else if (matchesKey(data, "up")) this.focus = "runs";
115
+ else if (matchesKey(data, "down") && this.listItemCount() > 0)
116
+ this.focus = "list";
117
+ else if (matchesKey(data, "return")) this.openFilterMenu();
118
+ } else if (this.focus === "list") {
119
+ const count = this.tab === "communications" ? this.communicationPreviews().length : this.turnItems().length;
120
+ if (matchesKey(data, "up")) {
121
+ if (this.rowIndex === 0) this.focus = "tabs";
122
+ else this.rowIndex -= 1;
123
+ } else if (matchesKey(data, "down"))
124
+ this.rowIndex = Math.min(Math.max(0, count - 1), this.rowIndex + 1);
125
+ else if (matchesKey(data, "return") || matchesKey(data, "right"))
126
+ this.openDetail();
127
+ }
128
+ this.tui.requestRender();
129
+ }
130
+
131
+ render(width: number): string[] {
132
+ this.ensureSelectedRun(this.runs());
133
+ const safeWidth = Math.max(24, width);
134
+ const innerWidth = Math.max(1, safeWidth - 2);
135
+ const lines: string[] = [];
136
+ lines.push(this.border("╭", " Actor Inspector ", "╮", innerWidth));
137
+ lines.push(this.row(this.renderRunControl(), innerWidth));
138
+ let selector = this.focus === "select"
139
+ ? this.menuLevel === "run"
140
+ ? this.renderMenuBox(
141
+ this.runs().map((run) => `${run.run} · ${run.status}`),
142
+ this.selectorIndex,
143
+ )
144
+ : this.renderFilterMenus(innerWidth)
145
+ : [];
146
+ const selectorAnchor = this.selectorAnchor();
147
+ if (this.menuLevel === "run" && selector.length > 0) {
148
+ const popup = selector[0];
149
+ const popupWidth = visibleWidth(popup);
150
+ const leading = this.fit(
151
+ this.takeVisiblePrefix(this.renderTabs(), selectorAnchor),
152
+ selectorAnchor,
153
+ );
154
+ const trailingWidth = Math.max(0, innerWidth - selectorAnchor - popupWidth);
155
+ const trailing = this.fit(
156
+ this.dropVisiblePrefix(this.renderTabs(), selectorAnchor + popupWidth),
157
+ trailingWidth,
158
+ );
159
+ lines.push(this.row(`${leading}${popup}${trailing}`, innerWidth, true));
160
+ selector = selector.slice(1);
161
+ } else lines.push(this.row(this.renderTabs(), innerWidth));
162
+ const selectorTop = selector[0];
163
+ if (selectorTop) {
164
+ const leadingBorder = "─".repeat(selectorAnchor);
165
+ const remainingBorder = "─".repeat(
166
+ Math.max(0, innerWidth - visibleWidth(selectorTop) - selectorAnchor),
167
+ );
168
+ lines.push(
169
+ `${this.theme.fg("border", `├${leadingBorder}`)}${selectorTop}${this.theme.fg("border", `${remainingBorder}┤`)}`,
170
+ );
171
+ } else lines.push(this.border("├", "", "┤", innerWidth));
172
+ this.contentStripeIndices = [];
173
+ const content = this.detailOpen
174
+ ? this.renderDetail(innerWidth)
175
+ : this.selectedRun
176
+ ? this.renderTimeline(innerWidth)
177
+ : this.renderRunSelector(innerWidth);
178
+ const minContentRows = 16;
179
+ const selectorRows = selector.slice(1);
180
+ for (let index = 0; index < Math.max(content.length, minContentRows); index += 1) {
181
+ const base = content[index] ?? "";
182
+ const stripeIndex = this.contentStripeIndices[index] ?? index;
183
+ const popup = selectorRows[index];
184
+ if (!popup) {
185
+ lines.push(this.stripedRow(base, innerWidth, stripeIndex));
186
+ continue;
187
+ }
188
+ const transparentPrefix = popup.match(/^ +/)?.[0].length ?? 0;
189
+ const visiblePopup = popup.slice(transparentPrefix);
190
+ const popupWidth = visibleWidth(visiblePopup);
191
+ const popupAnchor = selectorAnchor + transparentPrefix;
192
+ const baseWidth = Math.max(0, innerWidth - popupWidth - popupAnchor);
193
+ const leadingBase = this.stripeBackground(
194
+ this.fit(this.takeVisiblePrefix(base, popupAnchor), popupAnchor),
195
+ stripeIndex,
196
+ );
197
+ const preservedBase = this.stripeBackground(
198
+ this.fit(
199
+ this.dropVisiblePrefix(base, popupWidth + popupAnchor),
200
+ baseWidth,
201
+ ),
202
+ stripeIndex,
203
+ );
204
+ lines.push(this.row(`${leadingBase}${visiblePopup}${preservedBase}`, innerWidth, true));
205
+ }
206
+ lines.push(this.border("├", "", "┤", innerWidth));
207
+ lines.push(this.row(this.renderKeyHints(), innerWidth));
208
+ lines.push(this.border("╰", "", "╯", innerWidth));
209
+ return lines;
210
+ }
211
+
212
+ invalidate(): void {}
213
+
214
+ dispose(): void {
215
+ clearInterval(this.refreshTimer);
216
+ }
217
+
218
+ private runs(): Inspector.ActorInspectorRunItem[] {
219
+ return Inspector.readActorInspectorRuns(this.stateRoot, this.ownerId);
220
+ }
221
+
222
+ private ensureSelectedRun(runs: Inspector.ActorInspectorRunItem[]): void {
223
+ if (!this.selectedRun) this.selectedRun = runs[0]?.run;
224
+ }
225
+
226
+ private listItemCount(): number {
227
+ return this.tab === "communications"
228
+ ? this.communicationPreviews().length
229
+ : this.turnItems().length;
230
+ }
231
+
232
+ private selectorAnchor(): number {
233
+ if (this.menuLevel === "run") {
234
+ const runControl = stripVTControlCharacters(this.renderRunControl());
235
+ return Math.max(0, runControl.indexOf("Run:") - 1);
236
+ }
237
+ const label = this.tab === "communications" ? "Messages" : "Turns";
238
+ const tabs = stripVTControlCharacters(this.renderTabs());
239
+ return Math.max(0, tabs.indexOf(label) - 2);
240
+ }
241
+
242
+ private renderKeyHints(): string {
243
+ const hint = (keys: string, description: string) =>
244
+ `${this.theme.fg("accent", keys)}${this.theme.fg("dim", ` ${description}`)}`;
245
+ if (this.focus === "select")
246
+ return this.menuLevel === "value"
247
+ ? ` ${hint("↑↓", "option")} ${hint("enter", "apply")} ${hint("←/esc", "back")}`
248
+ : ` ${hint("↑↓", "option")} ${hint("→/enter", "open")} ${hint("←/esc", "back")}`;
249
+ if (this.focus === "detail")
250
+ return ` ${hint("↑↓", "scroll")} ${hint("←/esc", "back")}`;
251
+ if (this.focus === "list")
252
+ return ` ${hint("↑↓", "row")} ${hint("→/enter", "open")} ${hint("esc", "close")}`;
253
+ return ` ${hint("←→", "navigate")} ${hint("↑↓", "change row")} ${hint("enter", "select")} ${hint("esc", "close")}`;
254
+ }
255
+
256
+ private renderRunControl(): string {
257
+ const run = this.runs().find((item) => item.run === this.selectedRun);
258
+ const focused = this.focus === "runs";
259
+ const active = focused || (this.focus === "select" && this.menuLevel === "run");
260
+ const prefix = active ? this.theme.fg("accent", " [ ") : " ";
261
+ const suffix = active ? this.theme.fg("accent", " ] ") : " ";
262
+ if (!run) {
263
+ const empty = this.theme.fg("muted", `${prefix}Run: none${suffix}`);
264
+ return focused ? this.theme.bg("selectedBg", empty) : empty;
265
+ }
266
+ const statusColor = run.status === "failed"
267
+ ? "error"
268
+ : run.status === "running"
269
+ ? "warning"
270
+ : run.status === "done"
271
+ ? "success"
272
+ : "muted";
273
+ const value = `${prefix}${this.theme.fg("muted", "Run: ")}${this.theme.fg("accent", run.run)}${this.theme.fg("muted", " · ")}${this.theme.fg(statusColor, run.status)}${suffix}`;
274
+ return focused ? this.theme.bg("selectedBg", value) : value;
275
+ }
276
+
277
+ private activeMessageFilters(): string[] {
278
+ return [
279
+ ...(this.communicationChannel === "all" ? [] : [this.communicationChannel]),
280
+ ...(this.communicationUnread ? ["unread"] : []),
281
+ ...(this.communicationFrom === "all" ? [] : [this.communicationFrom]),
282
+ ];
283
+ }
284
+
285
+ private renderTabs(): string {
286
+ const tab = (id: ActorInspectorOverlayTab, label: string) => {
287
+ const selected = this.tab === id;
288
+ const focused = selected && this.focus === "tabs";
289
+ const runActive =
290
+ this.focus === "runs" ||
291
+ (this.focus === "select" && this.menuLevel === "run");
292
+ const display = selected && !runActive ? `[ ${label} ]` : ` ${label} `;
293
+ const value = ` ${display} `;
294
+ if (!selected) return this.theme.fg("muted", value);
295
+ const colored = this.theme.fg("accent", value);
296
+ return focused ? this.theme.bg("selectedBg", colored) : colored;
297
+ };
298
+ const messageFilters = this.activeMessageFilters();
299
+ const subagent = this.subagents()[this.subagentIndex] ?? "all";
300
+ const messagesLabel = `Messages${messageFilters.length > 0 ? ` · ${messageFilters.join(" · ")}` : ""}`;
301
+ const turnsLabel = `Turns${subagent === "all" ? "" : ` · ${subagent}`}`;
302
+ return `${tab("communications", messagesLabel)} ${tab("turns", turnsLabel)}`;
303
+ }
304
+
305
+ private renderRunSelector(width: number): string[] {
306
+ const runs = this.runs();
307
+ if (runs.length === 0) return [this.theme.fg("muted", " No owned actor runs")];
308
+ this.runIndex = Math.min(this.runIndex, runs.length - 1);
309
+ return runs.slice(0, 16).map((run, index) => {
310
+ const selected = index === this.runIndex;
311
+ const prefix = selected ? this.theme.fg("accent", " ▶ ") : " ";
312
+ const label = `${prefix}run:${run.run}`;
313
+ const status = ` ${run.status}`;
314
+ return selected
315
+ ? this.theme.fg("accent", `${label}${status}`)
316
+ : `${label}${this.theme.fg("muted", status)}`;
317
+ });
318
+ }
319
+
320
+ private renderTimeline(width: number): string[] {
321
+ if (!this.selectedRun) return [];
322
+ const run = this.runs().find((item) => item.run === this.selectedRun);
323
+ if (!run) {
324
+ this.selectedRun = undefined;
325
+ return [this.theme.fg("warning", " Selected run is no longer owned by this session")];
326
+ }
327
+ const rows =
328
+ this.tab === "communications"
329
+ ? this.communicationRows()
330
+ : this.turnRows();
331
+ if (rows.length === 0) {
332
+ this.contentStripeIndices = [0];
333
+ const filtered = this.tab === "communications"
334
+ ? this.activeMessageFilters().length > 0
335
+ : (this.subagents()[this.subagentIndex] ?? "all") !== "all";
336
+ return [
337
+ this.theme.fg(
338
+ "muted",
339
+ filtered
340
+ ? " No results for the active filters · Enter on the tab to adjust"
341
+ : this.tab === "communications"
342
+ ? " No messages in this run"
343
+ : " No persisted turns in this run",
344
+ ),
345
+ ];
346
+ }
347
+ this.rowIndex = Math.min(this.rowIndex, rows.length - 1);
348
+ const start = Math.max(
349
+ 0,
350
+ Math.min(this.rowIndex - 7, Math.max(0, rows.length - 15)),
351
+ );
352
+ const visibleRows = rows.slice(start, start + 15);
353
+ this.contentStripeIndices = visibleRows.map((_, offset) => start + offset);
354
+ return visibleRows.map((row, offset) => {
355
+ const index = start + offset;
356
+ const selected = this.focus === "list" && index === this.rowIndex;
357
+ return selected
358
+ ? this.theme.fg("accent", ` ▶ ${row}`)
359
+ : ` ${row}`;
360
+ });
361
+ }
362
+
363
+ private communicationPreviews(): Inspector.ActorInspectorPreview[] {
364
+ if (!this.selectedRun) return [];
365
+ const channels =
366
+ this.communicationChannel === "all"
367
+ ? undefined
368
+ : [this.communicationChannel];
369
+ return Inspector.readActorInspectorPreviews(this.stateRoot, 100, {
370
+ channels,
371
+ currentRunOnly: false,
372
+ ownerId: this.ownerId,
373
+ readKeys: this.readKeys,
374
+ run: this.selectedRun,
375
+ unreadOnly: this.communicationUnread,
376
+ }).filter(
377
+ (preview) =>
378
+ this.communicationFrom === "all" ||
379
+ this.communicationActorLabel(preview.from_display ?? preview.from) ===
380
+ this.communicationFrom,
381
+ );
382
+ }
383
+
384
+ private communicationActorLabel(actor?: string): string {
385
+ const value = actor ?? "unknown";
386
+ if (value.startsWith("run:")) return value.slice("run:".length);
387
+ return value.replace(/^branch:[^/]+\//, "");
388
+ }
389
+
390
+ private communicationFromOptions(): string[] {
391
+ if (!this.selectedRun) return ["all"];
392
+ const actors = Inspector.readActorInspectorRoster(
393
+ this.stateRoot,
394
+ this.selectedRun,
395
+ ).map((member) =>
396
+ this.communicationActorLabel(member.display ?? member.address),
397
+ );
398
+ return ["all", ...new Set(actors)];
399
+ }
400
+
401
+ private communicationRows(): string[] {
402
+ return this.communicationPreviews().map((preview) => {
403
+ const actor = preview.from_display ?? preview.from ?? "unknown";
404
+ const target = preview.channel === "room" ? "#all" : preview.to;
405
+ const text = preview.summary ?? preview.body_preview ?? "(no body)";
406
+ return `${preview.needs_response ? "! " : ""}${actor} → ${target} ${preview.type} ${text}`;
407
+ });
408
+ }
409
+
410
+ private renderDetail(width: number): string[] {
411
+ if (this.tab === "communications") {
412
+ const preview = this.detailCommunication;
413
+ if (!preview) return [this.theme.fg("warning", " Communication row is no longer available")];
414
+ const fields: Array<[string, unknown]> = [
415
+ ["channel", preview.channel],
416
+ ["run", preview.run],
417
+ ["from", preview.from_display ?? preview.from],
418
+ ["to", preview.to],
419
+ ["type", preview.type],
420
+ ["summary", preview.summary],
421
+ ["body", preview.body_preview],
422
+ ["attention", preview.needs_response],
423
+ ["inbox", preview.inbox_status],
424
+ ["timestamp", preview.timestamp],
425
+ ];
426
+ return fields
427
+ .filter(([, value]) => value !== undefined)
428
+ .map(([label, value]) =>
429
+ truncateToWidth(
430
+ ` ${label.padEnd(12, " ")} ${typeof value === "string" ? value : JSON.stringify(value)}`,
431
+ width,
432
+ "…",
433
+ ),
434
+ );
435
+ }
436
+ const turn = this.detailTurn;
437
+ if (!turn) return [this.theme.fg("warning", " Turn row is no longer available")];
438
+ const value = (input: unknown) =>
439
+ typeof input === "string" ? input : JSON.stringify(input);
440
+ const fields: string[] = [
441
+ ` command ${turn.commandId}${turn.stage ? ` · ${turn.stage}` : ""}`,
442
+ ` session ${turn.sessionFile}`,
443
+ ...(turn.promptFile
444
+ ? [` prompt ${turn.promptFile}${turn.promptBytes ? ` · ${turn.promptBytes} bytes` : ""}`]
445
+ : []),
446
+ ...(turn.recipeContext !== undefined
447
+ ? [` recipe context ${value(turn.recipeContext)}`]
448
+ : []),
449
+ ...(turn.userText ? [` user ${turn.userText}`] : []),
450
+ ...(turn.assistantText ? [` assistant ${turn.assistantText}`] : []),
451
+ ` reasoning ${turn.thinking ? "persisted thinking block" : "unavailable"}`,
452
+ ...(turn.thinking ? [` thinking ${turn.thinking}`] : []),
453
+ ...(turn.stopReason ? [` stop reason ${turn.stopReason}`] : []),
454
+ ...(turn.usage !== undefined ? [` usage ${value(turn.usage)}`] : []),
455
+ ...(turn.error ? [` error ${turn.error}`] : []),
456
+ ` tools ${turn.toolCalls.length}`,
457
+ ];
458
+ for (const [index, tool] of turn.toolCalls.entries()) {
459
+ fields.push(
460
+ ` tool ${String(index + 1).padEnd(9, " ")} ${tool.name} · ${tool.id}${tool.resultError ? " · error" : ""}`,
461
+ );
462
+ if (tool.arguments !== undefined)
463
+ fields.push(` arguments ${value(tool.arguments)}`);
464
+ if (tool.result !== undefined) fields.push(` result ${value(tool.result)}`);
465
+ }
466
+ if (turn.unmatchedToolResults > 0)
467
+ fields.push(` unmatched ${turn.unmatchedToolResults}`);
468
+ if (turn.sessionTruncated) fields.push(" session turn list truncated");
469
+ for (const diagnostic of turn.diagnostics)
470
+ fields.push(` diagnostic ${diagnostic}`);
471
+ const maxStart = Math.max(0, fields.length - 16);
472
+ this.detailScroll = Math.min(this.detailScroll, maxStart);
473
+ return fields
474
+ .slice(this.detailScroll, this.detailScroll + 16)
475
+ .map((field) => truncateToWidth(field, width, "…"));
476
+ }
477
+
478
+ private turnItems(): Inspector.ActorInspectorTurnItem[] {
479
+ if (!this.selectedRun) return [];
480
+ const selectedSubagent = this.subagents()[this.subagentIndex];
481
+ return Inspector.readActorInspectorTurns(
482
+ path.join(this.stateRoot, this.selectedRun),
483
+ ).filter(
484
+ (turn) =>
485
+ !selectedSubagent ||
486
+ selectedSubagent === "all" ||
487
+ turn.commandId === selectedSubagent,
488
+ );
489
+ }
490
+
491
+ private turnRows(): string[] {
492
+ return this.turnItems().map(
493
+ (turn) =>
494
+ `${turn.commandId}${turn.stage ? `/${turn.stage}` : ""} ${turn.provider ?? "unknown"}/${turn.model ?? "unknown"} tools:${turn.toolCalls.length} ${turn.assistantText ?? turn.userText ?? "(no text)"}`,
495
+ );
496
+ }
497
+
498
+ private subagents(): string[] {
499
+ if (!this.selectedRun || this.tab !== "turns") return ["all"];
500
+ const ids = Inspector.readActorInspectorTurns(
501
+ path.join(this.stateRoot, this.selectedRun),
502
+ ).map((turn) => turn.commandId);
503
+ return ["all", ...new Set(ids)];
504
+ }
505
+
506
+ private valueOptions(): string[] {
507
+ if (this.tab === "turns") return this.subagents();
508
+ if (this.filterControlIndex === 0)
509
+ return ["all", "room", "direct", "broadcast"];
510
+ if (this.filterControlIndex === 1) return ["all", "unread"];
511
+ return this.communicationFromOptions();
512
+ }
513
+
514
+ private filterOptions(): string[] {
515
+ return this.tab === "communications"
516
+ ? ["Channel", "State", "From"]
517
+ : ["Subagent"];
518
+ }
519
+
520
+ private menuOptions(): string[] {
521
+ if (this.menuLevel === "run") return this.runs().map((run) => run.run);
522
+ if (this.menuLevel === "filter") return this.filterOptions();
523
+ return this.valueOptions();
524
+ }
525
+
526
+ private backMenu(): void {
527
+ if (this.menuLevel === "value") {
528
+ this.menuLevel = "filter";
529
+ this.selectorIndex = this.filterControlIndex;
530
+ return;
531
+ }
532
+ this.focus = this.menuLevel === "run" ? "runs" : "tabs";
533
+ }
534
+
535
+ private openRunMenu(): void {
536
+ const options = this.runs();
537
+ this.selectorIndex = Math.max(0, options.findIndex((run) => run.run === this.selectedRun));
538
+ this.menuLevel = "run";
539
+ this.focus = "select";
540
+ }
541
+
542
+ private openFilterMenu(): void {
543
+ this.selectorIndex = this.filterControlIndex;
544
+ this.menuLevel = "filter";
545
+ this.focus = "select";
546
+ }
547
+
548
+ private applyMenuOption(value?: string): void {
549
+ if (!value) return;
550
+ if (this.menuLevel === "run") {
551
+ this.selectedRun = value;
552
+ this.runIndex = Math.max(0, this.runs().findIndex((run) => run.run === value));
553
+ this.rowIndex = 0;
554
+ this.subagentIndex = 0;
555
+ this.communicationFrom = "all";
556
+ this.focus = "runs";
557
+ return;
558
+ }
559
+ if (this.menuLevel === "filter") {
560
+ this.filterControlIndex = this.selectorIndex;
561
+ const options = this.valueOptions();
562
+ const current = this.currentFilterValue();
563
+ this.selectorIndex = Math.max(0, options.indexOf(current));
564
+ this.menuLevel = "value";
565
+ return;
566
+ }
567
+ if (this.tab === "turns")
568
+ this.subagentIndex = Math.max(0, this.subagents().indexOf(value));
569
+ else if (this.filterControlIndex === 0)
570
+ this.communicationChannel = value as typeof this.communicationChannel;
571
+ else if (this.filterControlIndex === 1)
572
+ this.communicationUnread = value === "unread";
573
+ else this.communicationFrom = value;
574
+ this.rowIndex = 0;
575
+ this.menuLevel = "filter";
576
+ this.selectorIndex = this.filterControlIndex;
577
+ }
578
+
579
+ private filterValue(index: number): string {
580
+ if (this.tab === "turns") return this.subagents()[this.subagentIndex] ?? "all";
581
+ if (index === 0) return this.communicationChannel;
582
+ if (index === 1) return this.communicationUnread ? "unread" : "all";
583
+ return this.communicationFrom;
584
+ }
585
+
586
+ private currentFilterValue(): string {
587
+ return this.filterValue(this.filterControlIndex);
588
+ }
589
+
590
+ private renderMenuBox(
591
+ options: string[],
592
+ focusedIndex: number,
593
+ current?: string,
594
+ parentIndex?: number,
595
+ omitLeftBorder = false,
596
+ omitRightBorder = false,
597
+ ): string[] {
598
+ const contentWidth = Math.max(...options.map((option) => option.length + 4));
599
+ const border = (left: string, right: string) =>
600
+ this.theme.fg(
601
+ "border",
602
+ `${omitLeftBorder ? "" : left}${"─".repeat(contentWidth)}${omitRightBorder ? "" : right}`,
603
+ );
604
+ return [
605
+ border("╭", "╮"),
606
+ ...options.map((option, index) => {
607
+ const focused = index === focusedIndex;
608
+ const row = this.fit(`${focused ? " ▶ " : " "}${option}`, contentWidth);
609
+ const colored = focused || option === current || index === parentIndex
610
+ ? this.theme.fg("accent", row)
611
+ : row;
612
+ const styled = focused || index === parentIndex
613
+ ? this.theme.bg("selectedBg", colored)
614
+ : colored;
615
+ return `${omitLeftBorder ? "" : this.theme.fg("border", "│")}${styled}${omitRightBorder ? "" : this.theme.fg("border", "│")}`;
616
+ }),
617
+ border("╰", "╯"),
618
+ ];
619
+ }
620
+
621
+ private renderFilterMenus(_width: number): string[] {
622
+ const filters = this.filterOptions().map(
623
+ (filter, index) => `${filter}: ${this.filterValue(index)}`,
624
+ );
625
+ const parentFocus = this.menuLevel === "filter" ? this.selectorIndex : -1;
626
+ const parent = this.renderMenuBox(
627
+ filters,
628
+ parentFocus,
629
+ undefined,
630
+ this.menuLevel === "value" ? this.filterControlIndex : undefined,
631
+ );
632
+ if (this.menuLevel !== "value") return parent;
633
+ const parentShared = this.renderMenuBox(
634
+ filters,
635
+ parentFocus,
636
+ undefined,
637
+ this.filterControlIndex,
638
+ false,
639
+ true,
640
+ );
641
+ const child = this.renderMenuBox(
642
+ this.valueOptions(),
643
+ this.selectorIndex,
644
+ this.currentFilterValue(),
645
+ );
646
+ return Array.from({ length: Math.max(parent.length, child.length) }, (_, index) =>
647
+ child[index]
648
+ ? `${parentShared[index] ?? " ".repeat(visibleWidth(parentShared[0]))}${child[index]}`
649
+ : (parent[index] ?? ""),
650
+ );
651
+ }
652
+
653
+ private openDetail(): void {
654
+ if (this.tab === "communications") {
655
+ const preview = this.communicationPreviews()[this.rowIndex];
656
+ this.detailCommunication = preview;
657
+ if (preview) this.readKeys.add(Inspector.inspectorPreviewReadKey(preview));
658
+ } else this.detailTurn = this.turnItems()[this.rowIndex];
659
+ this.detailScroll = 0;
660
+ this.detailOpen = Boolean(this.detailCommunication || this.detailTurn);
661
+ if (this.detailOpen) this.focus = "detail";
662
+ }
663
+
664
+ private closeDetail(): void {
665
+ this.detailOpen = false;
666
+ this.detailCommunication = undefined;
667
+ this.detailTurn = undefined;
668
+ this.detailScroll = 0;
669
+ this.focus = "list";
670
+ }
671
+
672
+ private border(left: string, title: string, right: string, width: number): string {
673
+ const titleText = truncateToWidth(title, width, "");
674
+ const fill = "─".repeat(Math.max(0, width - visibleWidth(titleText)));
675
+ return this.theme.fg("border", `${left}${titleText}${fill}${right}`);
676
+ }
677
+
678
+ private stripeBackground(content: string, index: number): string {
679
+ if (index % 2 === 0) return content;
680
+ const segments = content.split("…");
681
+ return segments
682
+ .map((segment, segmentIndex) =>
683
+ `${this.theme.bg("customMessageBg", segment)}${segmentIndex < segments.length - 1 ? this.theme.bg("customMessageBg", "…") : ""}`,
684
+ )
685
+ .join("");
686
+ }
687
+
688
+ private stripedRow(content: string, width: number, index: number): string {
689
+ return this.row(
690
+ this.stripeBackground(this.fit(content, width), index),
691
+ width,
692
+ true,
693
+ );
694
+ }
695
+
696
+ private row(content: string, width: number, fitted = false): string {
697
+ const body = fitted ? content : this.fit(content, width);
698
+ return `${this.theme.fg("border", "│")}${body}${this.theme.fg("border", "│")}`;
699
+ }
700
+
701
+ private takeVisiblePrefix(content: string, width: number): string {
702
+ const plain = stripVTControlCharacters(content);
703
+ let consumed = 0;
704
+ let result = "";
705
+ for (const character of plain) {
706
+ const characterWidth = visibleWidth(character);
707
+ if (consumed + characterWidth > width) break;
708
+ result += character;
709
+ consumed += characterWidth;
710
+ }
711
+ return result;
712
+ }
713
+
714
+ private dropVisiblePrefix(content: string, width: number): string {
715
+ const plain = stripVTControlCharacters(content);
716
+ let consumed = 0;
717
+ let index = 0;
718
+ for (const character of plain) {
719
+ if (consumed >= width) break;
720
+ consumed += visibleWidth(character);
721
+ index += character.length;
722
+ }
723
+ return plain.slice(index);
724
+ }
725
+
726
+ private fit(content: string, width: number): string {
727
+ // A Component render entry must remain exactly one terminal row. Persisted
728
+ // prompts, messages, and tool results may contain line breaks or tabs;
729
+ // passing those through lets them escape the overlay compositor and corrupt
730
+ // the underlying TUI during tab changes.
731
+ const singleLine = content.replace(/[\r\n\t]/g, " ");
732
+ const bounded = truncateToWidth(singleLine, width, "…");
733
+ return `${bounded}${" ".repeat(Math.max(0, width - visibleWidth(bounded)))}`;
734
+ }
735
+ }