pi-crew 0.1.32 → 0.1.34

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/docs/architecture.md +3 -3
  2. package/docs/research-phase8-operator-experience-plan.md +819 -0
  3. package/docs/research-phase9-observability-reliability-plan.md +1190 -0
  4. package/docs/research-ui-optimization-plan.md +480 -0
  5. package/package.json +1 -1
  6. package/schema.json +14 -0
  7. package/src/config/config.ts +69 -0
  8. package/src/config/defaults.ts +7 -0
  9. package/src/extension/autonomous-policy.ts +56 -2
  10. package/src/extension/notification-router.ts +116 -0
  11. package/src/extension/notification-sink.ts +51 -0
  12. package/src/extension/register.ts +133 -35
  13. package/src/extension/registration/commands.ts +110 -3
  14. package/src/extension/registration/team-tool.ts +5 -2
  15. package/src/extension/registration/viewers.ts +3 -1
  16. package/src/extension/team-recommendation.ts +16 -8
  17. package/src/runtime/child-pi.ts +1 -0
  18. package/src/runtime/diagnostic-export.ts +107 -0
  19. package/src/runtime/pi-spawn.ts +4 -1
  20. package/src/runtime/task-packet.ts +11 -2
  21. package/src/runtime/task-runner/prompt-builder.ts +3 -0
  22. package/src/schema/config-schema.ts +11 -0
  23. package/src/ui/crew-widget.ts +350 -285
  24. package/src/ui/dashboard-panes/agents-pane.ts +25 -0
  25. package/src/ui/dashboard-panes/health-pane.ts +30 -0
  26. package/src/ui/dashboard-panes/mailbox-pane.ts +10 -0
  27. package/src/ui/dashboard-panes/progress-pane.ts +14 -0
  28. package/src/ui/dashboard-panes/transcript-pane.ts +10 -0
  29. package/src/ui/heartbeat-aggregator.ts +53 -0
  30. package/src/ui/keybinding-map.ts +92 -0
  31. package/src/ui/live-run-sidebar.ts +20 -8
  32. package/src/ui/overlays/agent-picker-overlay.ts +57 -0
  33. package/src/ui/overlays/confirm-overlay.ts +58 -0
  34. package/src/ui/overlays/mailbox-compose-overlay.ts +144 -0
  35. package/src/ui/overlays/mailbox-compose-preview.ts +63 -0
  36. package/src/ui/overlays/mailbox-detail-overlay.ts +122 -0
  37. package/src/ui/pi-ui-compat.ts +57 -0
  38. package/src/ui/powerbar-publisher.ts +128 -94
  39. package/src/ui/render-scheduler.ts +103 -0
  40. package/src/ui/run-action-dispatcher.ts +107 -0
  41. package/src/ui/run-dashboard.ts +418 -372
  42. package/src/ui/run-snapshot-cache.ts +359 -0
  43. package/src/ui/snapshot-types.ts +47 -0
  44. package/src/ui/transcript-cache.ts +94 -0
  45. package/src/ui/transcript-viewer.ts +316 -302
@@ -1,372 +1,418 @@
1
- import * as fs from "node:fs";
2
- import type { TeamRunManifest, TeamTaskState, UsageState } from "../state/types.ts";
3
- import { readCrewAgents } from "../runtime/crew-agent-records.ts";
4
- import type { CrewAgentRecord } from "../runtime/crew-agent-runtime.ts";
5
- import { isDisplayActiveRun, isLikelyOrphanedActiveRun } from "../runtime/process-status.ts";
6
- import { readJsonFileCoalesced } from "../utils/file-coalescer.ts";
7
- import type { CrewTheme } from "./theme-adapter.ts";
8
- import { asCrewTheme, subscribeThemeChange } from "./theme-adapter.ts";
9
- import { applyStatusColor, iconForStatus, type RunStatus } from "./status-colors.ts";
10
- import { pad, truncate } from "../utils/visual.ts";
11
- import { Box, Text } from "./layout-primitives.ts";
12
- import { DynamicCrewBorder } from "./dynamic-border.ts";
13
- import { CrewFooter } from "./crew-footer.ts";
14
- import { aggregateUsage } from "../state/usage.ts";
15
-
16
- interface DashboardComponent {
17
- invalidate(): void;
18
- render(width: number): string[];
19
- handleInput(data: string): void;
20
- }
21
-
22
- export interface RunDashboardOptions {
23
- placement?: "center" | "right";
24
- showModel?: boolean;
25
- showTokens?: boolean;
26
- showTools?: boolean;
27
- }
28
-
29
- export type RunDashboardAction = "status" | "summary" | "artifacts" | "api" | "events" | "agents" | "agent-events" | "agent-output" | "agent-transcript" | "reload";
30
- export interface RunDashboardSelection {
31
- runId: string;
32
- action: RunDashboardAction;
33
- }
34
-
35
- const TASK_READ_TTL_MS = 200;
36
-
37
- function formatAge(iso: string | undefined): string | undefined {
38
- if (!iso) return undefined;
39
- const ms = Math.max(0, Date.now() - new Date(iso).getTime());
40
- if (!Number.isFinite(ms)) return undefined;
41
- if (ms < 1000) return "now";
42
- if (ms < 60_000) return `${Math.floor(ms / 1000)}s`;
43
- if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m`;
44
- return `${Math.floor(ms / 3_600_000)}h`;
45
- }
46
-
47
- function renderLines(lines: string[], width: number): string[] {
48
- const box = new Box(0, 0);
49
- for (const line of lines) {
50
- box.addChild(new Text(line));
51
- }
52
- return box.render(width);
53
- }
54
-
55
- function readProgressPreview(run: TeamRunManifest, maxLines = 5): string[] {
56
- const progress = [...run.artifacts].reverse().find((artifact) => artifact.kind === "progress");
57
- if (!progress || !fs.existsSync(progress.path)) return ["Progress: (none)"];
58
- try {
59
- return ["Progress:", ...fs.readFileSync(progress.path, "utf-8").split(/\r?\n/).filter(Boolean).slice(0, maxLines)];
60
- } catch (error) {
61
- const message = error instanceof Error ? error.message : String(error);
62
- return [`Progress: failed to read (${message})`];
63
- }
64
- }
65
-
66
- function formatTokens(usage: UsageState | undefined): string | undefined {
67
- if (!usage) return undefined;
68
- const total = (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
69
- if (!total) return undefined;
70
- const compact = total >= 1000 ? `${(total / 1000).toFixed(total >= 10_000 ? 0 : 1)}k` : `${total}`;
71
- const parts = [`tok=${compact}`];
72
- if (usage.input) parts.push(`in=${usage.input}`);
73
- if (usage.output) parts.push(`out=${usage.output}`);
74
- if (usage.cacheRead) parts.push(`cache=${usage.cacheRead}`);
75
- if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
76
- return parts.join("/");
77
- }
78
-
79
- function readRunTasks(run: TeamRunManifest): TeamTaskState[] {
80
- const parse = () => {
81
- if (!fs.existsSync(run.tasksPath)) return [];
82
- const parsed = JSON.parse(fs.readFileSync(run.tasksPath, "utf-8"));
83
- return Array.isArray(parsed) ? (parsed as TeamTaskState[]) : [];
84
- };
85
- try {
86
- return readJsonFileCoalesced(run.tasksPath, TASK_READ_TTL_MS, parse);
87
- } catch {
88
- return [];
89
- }
90
- }
91
-
92
- function taskForAgent(tasks: TeamTaskState[], agent: CrewAgentRecord): TeamTaskState | undefined {
93
- return tasks.find((task) => task.id === agent.taskId);
94
- }
95
-
96
- function modelForTask(task: TeamTaskState | undefined): string | undefined {
97
- const attempts = task?.modelAttempts;
98
- if (!attempts?.length) return undefined;
99
- return attempts.find((attempt) => attempt.success)?.model ?? attempts.at(-1)?.model;
100
- }
101
-
102
- function modelForAgent(agent: CrewAgentRecord, task: TeamTaskState | undefined): string | undefined {
103
- return modelForTask(task) ?? agent.model;
104
- }
105
-
106
- function usageForAgent(agent: CrewAgentRecord, task: TeamTaskState | undefined): UsageState | undefined {
107
- return task?.usage ?? agent.usage;
108
- }
109
-
110
- function agentPreviewLine(agent: CrewAgentRecord, task: TeamTaskState | undefined, options: RunDashboardOptions): string {
111
- const stats = [
112
- agent.progress?.activityState,
113
- options.showModel !== false && modelForAgent(agent, task) ? `model=${modelForAgent(agent, task)}` : undefined,
114
- options.showTokens !== false
115
- ? formatTokens(usageForAgent(agent, task)) ?? (agent.progress?.tokens !== undefined ? `tok=${agent.progress.tokens}` : undefined)
116
- : undefined,
117
- options.showTools !== false && agent.progress?.currentTool ? `tool=${agent.progress.currentTool}` : undefined,
118
- options.showTools !== false && agent.toolUses !== undefined ? `${agent.toolUses} tools` : undefined,
119
- agent.progress?.turns !== undefined ? `${agent.progress.turns} turns` : undefined,
120
- agent.progress?.failedTool ? `failedTool=${agent.progress.failedTool}` : undefined,
121
- agent.startedAt ? `age=${formatAge(agent.completedAt ?? agent.startedAt)}` : undefined,
122
- ].filter((part): part is string => Boolean(part));
123
- const recent = agent.progress?.recentOutput?.at(-1);
124
- return `Agent: ${iconForStatus(agent.status)} ${agent.taskId} ${agent.role}->${agent.agent}${stats.length ? ` · ${stats.join(" · ")}` : ""}${recent ? ` ⎿ ${recent}` : ""}`;
125
- }
126
-
127
- function readAgentPreview(run: TeamRunManifest, maxLines = 5, options: RunDashboardOptions = {}): string[] {
128
- try {
129
- const agents = readCrewAgents(run);
130
- const tasks = readRunTasks(run);
131
- if (!agents.length) return ["Agents: (none)"];
132
- const totals = tasks.reduce((acc, task) => {
133
- acc.input += task.usage?.input ?? 0;
134
- acc.output += task.usage?.output ?? 0;
135
- acc.cacheRead += task.usage?.cacheRead ?? 0;
136
- acc.cacheWrite += task.usage?.cacheWrite ?? 0;
137
- acc.cost += task.usage?.cost ?? 0;
138
- return acc;
139
- }, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 } as { input: number; output: number; cacheRead: number; cacheWrite: number; cost: number });
140
- const header = formatTokens(totals) ? `Agents: ${formatTokens(totals)}` : "Agents:";
141
- return [
142
- header,
143
- ...agents
144
- .slice(0, maxLines)
145
- .map((agent) => agentPreviewLine(agent, taskForAgent(tasks, agent), options)),
146
- ...(agents.length > maxLines ? [`Agents: +${agents.length - maxLines} more`] : []),
147
- ];
148
- } catch (error) {
149
- const message = error instanceof Error ? error.message : String(error);
150
- return [`Agents: failed to read (${message})`];
151
- }
152
- }
153
-
154
- function agentsFor(run: TeamRunManifest): CrewAgentRecord[] {
155
- try {
156
- return readCrewAgents(run);
157
- } catch {
158
- return [];
159
- }
160
- }
161
-
162
- function runLabel(run: TeamRunManifest, selected: boolean): string {
163
- const agents = agentsFor(run);
164
- const stale = isLikelyOrphanedActiveRun(run, agents);
165
- const running = agents.find((agent) => agent.status === "running");
166
- const queued = agents.find((agent) => agent.status === "queued");
167
- const step = stale ? "orphaned queued run" : running ? `step ${running.taskId}` : queued ? `queued ${queued.taskId}` : `agents ${agents.length}`;
168
- const status: RunStatus = stale ? "stale" : (run.status as RunStatus);
169
- const marker = selected ? "›" : " ";
170
- return `${marker} ${iconForStatus(status)} ${run.runId.slice(-8)} ${status} | ${run.team}/${run.workflow ?? "none"} | ${step} | ${run.goal}`;
171
- }
172
-
173
- function groupedRuns(runs: TeamRunManifest[]): Array<{ label: string; run?: TeamRunManifest }> {
174
- const active = runs.filter((run) => isDisplayActiveRun(run, agentsFor(run)));
175
- const recent = runs.filter((run) => !isDisplayActiveRun(run, agentsFor(run)));
176
- const rows: Array<{ label: string; run?: TeamRunManifest }> = [];
177
- if (active.length) rows.push({ label: "Active" }, ...active.map((run) => ({ label: run.runId, run })));
178
- if (recent.length) rows.push({ label: "Recent" }, ...recent.map((run) => ({ label: run.runId, run })));
179
- return rows;
180
- }
181
-
182
- function selectedRunFromGrouped(runs: TeamRunManifest[], selected: number): TeamRunManifest | undefined {
183
- return groupedRuns(runs).filter((row) => row.run)[selected]?.run;
184
- }
185
-
186
- function countByStatus(runs: TeamRunManifest[]): string {
187
- const counts = new Map<RunStatus, number>();
188
- for (const run of runs) {
189
- const status: RunStatus = isLikelyOrphanedActiveRun(run, agentsFor(run)) ? "stale" : (run.status as RunStatus);
190
- counts.set(status, (counts.get(status) ?? 0) + 1);
191
- }
192
- return [...counts.entries()].map(([status, count]) => `${status}=${count}`).join(", ") || "none";
193
- }
194
-
195
- export class RunDashboard implements DashboardComponent {
196
- private selected = 0;
197
- private showFullProgress = false;
198
- private readonly runs: TeamRunManifest[];
199
- private readonly done: (selection: RunDashboardSelection | undefined) => void;
200
- private readonly theme: CrewTheme;
201
- private readonly options: RunDashboardOptions;
202
- private cachedWidth = 0;
203
- private cachedVersion = "";
204
- private cachedLines: string[] = [];
205
- private readonly unsubscribeTheme: () => void;
206
-
207
- constructor(
208
- runs: TeamRunManifest[],
209
- done: (selection: RunDashboardSelection | undefined) => void,
210
- theme: unknown = {},
211
- options: RunDashboardOptions = {},
212
- ) {
213
- this.runs = runs;
214
- this.done = done;
215
- this.theme = asCrewTheme(theme);
216
- this.options = options;
217
- this.unsubscribeTheme = subscribeThemeChange(theme, () => this.invalidate());
218
- }
219
-
220
- private buildSignature(): string {
221
- const statuses = this.runs.map((run) => {
222
- const stale = isLikelyOrphanedActiveRun(run, agentsFor(run));
223
- const status: RunStatus = stale ? "stale" : (run.status as RunStatus);
224
- return `${run.runId}:${run.status}:${run.updatedAt}:${status}`;
225
- }).join("|");
226
- return `${this.selected}:${this.showFullProgress ? 1 : 0}:${statuses}`;
227
- }
228
-
229
- invalidate(): void {
230
- this.cachedVersion = "";
231
- this.cachedLines = [];
232
- }
233
-
234
- dispose(): void {
235
- this.unsubscribeTheme();
236
- }
237
-
238
- render(width: number): string[] {
239
- const signature = this.buildSignature();
240
- if (signature !== this.cachedVersion || this.cachedWidth !== width) {
241
- const innerWidth = Math.max(20, width - 4);
242
- const borderWidth = Math.min(innerWidth, Math.max(0, width - 2));
243
- const fg = (color: Parameters<CrewTheme["fg"]>[0], text: string) => this.theme.fg(color, text);
244
- const borderFill = (count: number) => new DynamicCrewBorder(this.theme).render(count)[0];
245
- const border = (left: string, right: string) => `${fg("border", left)}${borderFill(borderWidth)}${fg("border", right)}`;
246
-
247
- const lines = [
248
- border("╭", "╮"),
249
- `│ ${pad(truncate(`${fg("accent", "▐")} ${this.theme.bold(this.options.placement === "right" ? "pi-crew right sidebar (anchored top-right)" : "pi-crew dashboard")}`, innerWidth - 1), innerWidth - 1)}│`,
250
- `│ ${pad(truncate(`Runs: ${this.runs.length} • ${countByStatus(this.runs)}`, innerWidth - 1), innerWidth - 1)}│`,
251
- `│ ${pad(truncate(`↑/↓/j/k select • r reload • p progress • s/u/a/i actions • d agents • e/v/o viewers • q close`, innerWidth - 1), innerWidth - 1)}│`,
252
- border("├", "┤"),
253
- ];
254
- if (this.runs.length === 0) {
255
- lines.push(`│ ${pad(truncate("No runs found.", innerWidth - 1), innerWidth - 1)}│`);
256
- } else {
257
- const rows = groupedRuns(this.runs).slice(0, 16);
258
- const selectableRuns = rows.filter((row) => row.run);
259
- for (const row of rows) {
260
- if (!row.run) {
261
- lines.push(`│ ${pad(truncate(fg("accent", row.label), innerWidth - 1), innerWidth - 1)}│`);
262
- continue;
263
- }
264
- const index = selectableRuns.findIndex((candidate) => candidate.run?.runId === row.run?.runId);
265
- const rowStatus = isLikelyOrphanedActiveRun(row.run, agentsFor(row.run)) ? "stale" : (row.run.status as RunStatus);
266
- const label = runLabel(row.run, index === this.selected);
267
- lines.push(`│ ${pad(applyStatusColor(this.theme, rowStatus, label), innerWidth - 1)}│`);
268
- }
269
- const selectedRun = selectedRunFromGrouped(this.runs, this.selected);
270
- if (selectedRun) {
271
- lines.push(border("├", "┤"));
272
- const details = [
273
- `Selected: ${selectedRun.runId}`,
274
- `Status: ${isLikelyOrphanedActiveRun(selectedRun, agentsFor(selectedRun)) ? "stale" : selectedRun.status} | Team: ${selectedRun.team} | Workflow: ${selectedRun.workflow ?? "none"}`,
275
- `Created: ${selectedRun.createdAt}`,
276
- `Updated: ${selectedRun.updatedAt}`,
277
- `Artifacts: ${selectedRun.artifacts.length} | Workspace: ${selectedRun.workspaceMode}`,
278
- selectedRun.async ? `Async: pid=${selectedRun.async.pid ?? "unknown"} log=${selectedRun.async.logPath}` : "Async: no",
279
- `Goal: ${selectedRun.goal}`,
280
- ];
281
- for (const detail of [
282
- ...details,
283
- ...readAgentPreview(selectedRun, this.showFullProgress ? 20 : 8, this.options),
284
- ...readProgressPreview(selectedRun, this.showFullProgress ? 20 : 5),
285
- ]) {
286
- lines.push(`│ ${pad(truncate(detail, innerWidth - 1), innerWidth - 1)}│`);
287
- }
288
- const selectedTasks = readRunTasks(selectedRun);
289
- const footer = new CrewFooter({
290
- pwd: selectedRun.cwd,
291
- runId: selectedRun.runId,
292
- status: isLikelyOrphanedActiveRun(selectedRun, agentsFor(selectedRun)) ? "stale" : selectedRun.status,
293
- usage: aggregateUsage(selectedTasks),
294
- badges: [`team ${selectedRun.team}`, `workflow ${selectedRun.workflow ?? "none"}`, `${selectedRun.artifacts.length} artifacts`, selectedRun.workspaceMode],
295
- }, this.theme);
296
- lines.push(border("├", "┤"));
297
- for (const footerLine of footer.render(innerWidth - 1)) {
298
- lines.push(`│ ${pad(truncate(footerLine, innerWidth - 1), innerWidth - 1)}│`);
299
- }
300
- }
301
- }
302
- lines.push(border("╰", "╯"));
303
- this.cachedLines = renderLines(lines.map((line) => truncate(line, width)), width);
304
- this.cachedVersion = signature;
305
- this.cachedWidth = width;
306
- }
307
- return this.cachedLines;
308
- }
309
-
310
- handleInput(data: string): void {
311
- if (data === "q" || data === "\u001b") {
312
- this.done(undefined);
313
- return;
314
- }
315
- if (data === "\r" || data === "\n" || data === "s") {
316
- const runId = selectedRunFromGrouped(this.runs, this.selected)?.runId;
317
- this.done(runId ? { runId, action: "status" } : undefined);
318
- return;
319
- }
320
- if (data === "u") {
321
- const runId = selectedRunFromGrouped(this.runs, this.selected)?.runId;
322
- this.done(runId ? { runId, action: "summary" } : undefined);
323
- return;
324
- }
325
- if (data === "a") {
326
- const runId = selectedRunFromGrouped(this.runs, this.selected)?.runId;
327
- this.done(runId ? { runId, action: "artifacts" } : undefined);
328
- return;
329
- }
330
- if (data === "i") {
331
- const runId = selectedRunFromGrouped(this.runs, this.selected)?.runId;
332
- this.done(runId ? { runId, action: "api" } : undefined);
333
- return;
334
- }
335
- if (data === "d") {
336
- const runId = selectedRunFromGrouped(this.runs, this.selected)?.runId;
337
- this.done(runId ? { runId, action: "agents" } : undefined);
338
- return;
339
- }
340
- if (data === "e") {
341
- const runId = selectedRunFromGrouped(this.runs, this.selected)?.runId;
342
- this.done(runId ? { runId, action: "agent-events" } : undefined);
343
- return;
344
- }
345
- if (data === "o") {
346
- const runId = selectedRunFromGrouped(this.runs, this.selected)?.runId;
347
- this.done(runId ? { runId, action: "agent-output" } : undefined);
348
- return;
349
- }
350
- if (data === "v") {
351
- const runId = selectedRunFromGrouped(this.runs, this.selected)?.runId;
352
- this.done(runId ? { runId, action: "agent-transcript" } : undefined);
353
- return;
354
- }
355
- if (data === "r") {
356
- this.done({ runId: selectedRunFromGrouped(this.runs, this.selected)?.runId ?? "", action: "reload" });
357
- return;
358
- }
359
- if (data === "p") {
360
- this.showFullProgress = !this.showFullProgress;
361
- return;
362
- }
363
- if (data === "k" || data === "\u001b[A") {
364
- this.selected = Math.max(0, this.selected - 1);
365
- return;
366
- }
367
- if (data === "j" || data === "\u001b[B") {
368
- const selectableCount = groupedRuns(this.runs).filter((row) => row.run).length;
369
- this.selected = Math.min(Math.max(0, selectableCount - 1), this.selected + 1);
370
- }
371
- }
372
- }
1
+ import * as fs from "node:fs";
2
+ import type { TeamRunManifest, TeamTaskState, UsageState } from "../state/types.ts";
3
+ import { readCrewAgents } from "../runtime/crew-agent-records.ts";
4
+ import type { CrewAgentRecord } from "../runtime/crew-agent-runtime.ts";
5
+ import { isDisplayActiveRun, isLikelyOrphanedActiveRun } from "../runtime/process-status.ts";
6
+ import { readJsonFileCoalesced } from "../utils/file-coalescer.ts";
7
+ import type { CrewTheme } from "./theme-adapter.ts";
8
+ import { asCrewTheme, subscribeThemeChange } from "./theme-adapter.ts";
9
+ import { applyStatusColor, iconForStatus, type RunStatus } from "./status-colors.ts";
10
+ import { pad, truncate } from "../utils/visual.ts";
11
+ import { Box, Text } from "./layout-primitives.ts";
12
+ import { DynamicCrewBorder } from "./dynamic-border.ts";
13
+ import { CrewFooter } from "./crew-footer.ts";
14
+ import { aggregateUsage } from "../state/usage.ts";
15
+ import { renderAgentsPane } from "./dashboard-panes/agents-pane.ts";
16
+ import { renderMailboxPane } from "./dashboard-panes/mailbox-pane.ts";
17
+ import { renderProgressPane } from "./dashboard-panes/progress-pane.ts";
18
+ import { renderTranscriptPane } from "./dashboard-panes/transcript-pane.ts";
19
+ import { renderHealthPane } from "./dashboard-panes/health-pane.ts";
20
+ import { dashboardActionForKey } from "./keybinding-map.ts";
21
+ import type { RunSnapshotCache, RunUiSnapshot } from "./snapshot-types.ts";
22
+
23
+ interface DashboardComponent {
24
+ invalidate(): void;
25
+ render(width: number): string[];
26
+ handleInput(data: string): void;
27
+ }
28
+
29
+ export interface RunDashboardOptions {
30
+ placement?: "center" | "right";
31
+ showModel?: boolean;
32
+ showTokens?: boolean;
33
+ showTools?: boolean;
34
+ snapshotCache?: RunSnapshotCache;
35
+ runProvider?: () => TeamRunManifest[];
36
+ }
37
+
38
+ export type RunDashboardAction = "status" | "summary" | "artifacts" | "api" | "events" | "agents" | "agent-events" | "agent-output" | "agent-transcript" | "mailbox" | "reload" | "mailbox-detail" | "health-recovery" | "health-kill-stale" | "health-diagnostic-export" | "notifications-dismiss";
39
+ export interface RunDashboardSelection {
40
+ runId: string;
41
+ action: RunDashboardAction;
42
+ }
43
+
44
+ const TASK_READ_TTL_MS = 200;
45
+
46
+ function formatAge(iso: string | undefined): string | undefined {
47
+ if (!iso) return undefined;
48
+ const ms = Math.max(0, Date.now() - new Date(iso).getTime());
49
+ if (!Number.isFinite(ms)) return undefined;
50
+ if (ms < 1000) return "now";
51
+ if (ms < 60_000) return `${Math.floor(ms / 1000)}s`;
52
+ if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m`;
53
+ return `${Math.floor(ms / 3_600_000)}h`;
54
+ }
55
+
56
+ function renderLines(lines: string[], width: number): string[] {
57
+ const box = new Box(0, 0);
58
+ for (const line of lines) {
59
+ box.addChild(new Text(line));
60
+ }
61
+ return box.render(width);
62
+ }
63
+
64
+ function readProgressPreview(run: TeamRunManifest, maxLines = 5): string[] {
65
+ const progress = [...run.artifacts].reverse().find((artifact) => artifact.kind === "progress");
66
+ if (!progress || !fs.existsSync(progress.path)) return ["Progress: (none)"];
67
+ try {
68
+ return ["Progress:", ...fs.readFileSync(progress.path, "utf-8").split(/\r?\n/).filter(Boolean).slice(0, maxLines)];
69
+ } catch (error) {
70
+ const message = error instanceof Error ? error.message : String(error);
71
+ return [`Progress: failed to read (${message})`];
72
+ }
73
+ }
74
+
75
+ function formatTokens(usage: UsageState | undefined): string | undefined {
76
+ if (!usage) return undefined;
77
+ const total = (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
78
+ if (!total) return undefined;
79
+ const compact = total >= 1000 ? `${(total / 1000).toFixed(total >= 10_000 ? 0 : 1)}k` : `${total}`;
80
+ const parts = [`tok=${compact}`];
81
+ if (usage.input) parts.push(`in=${usage.input}`);
82
+ if (usage.output) parts.push(`out=${usage.output}`);
83
+ if (usage.cacheRead) parts.push(`cache=${usage.cacheRead}`);
84
+ if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
85
+ return parts.join("/");
86
+ }
87
+
88
+ function snapshotFor(run: TeamRunManifest, snapshotCache?: RunSnapshotCache): RunUiSnapshot | undefined {
89
+ try {
90
+ return snapshotCache?.refreshIfStale(run.runId);
91
+ } catch {
92
+ return snapshotCache?.get(run.runId);
93
+ }
94
+ }
95
+
96
+ function readRunTasks(run: TeamRunManifest, snapshotCache?: RunSnapshotCache): TeamTaskState[] {
97
+ const snapshot = snapshotFor(run, snapshotCache);
98
+ if (snapshot) return snapshot.tasks;
99
+ const parse = () => {
100
+ if (!fs.existsSync(run.tasksPath)) return [];
101
+ const parsed = JSON.parse(fs.readFileSync(run.tasksPath, "utf-8"));
102
+ return Array.isArray(parsed) ? (parsed as TeamTaskState[]) : [];
103
+ };
104
+ try {
105
+ return readJsonFileCoalesced(run.tasksPath, TASK_READ_TTL_MS, parse);
106
+ } catch {
107
+ return [];
108
+ }
109
+ }
110
+
111
+ function taskForAgent(tasks: TeamTaskState[], agent: CrewAgentRecord): TeamTaskState | undefined {
112
+ return tasks.find((task) => task.id === agent.taskId);
113
+ }
114
+
115
+ function modelForTask(task: TeamTaskState | undefined): string | undefined {
116
+ const attempts = task?.modelAttempts;
117
+ if (!attempts?.length) return undefined;
118
+ return attempts.find((attempt) => attempt.success)?.model ?? attempts.at(-1)?.model;
119
+ }
120
+
121
+ function modelForAgent(agent: CrewAgentRecord, task: TeamTaskState | undefined): string | undefined {
122
+ return modelForTask(task) ?? agent.model;
123
+ }
124
+
125
+ function usageForAgent(agent: CrewAgentRecord, task: TeamTaskState | undefined): UsageState | undefined {
126
+ return task?.usage ?? agent.usage;
127
+ }
128
+
129
+ function agentPreviewLine(agent: CrewAgentRecord, task: TeamTaskState | undefined, options: RunDashboardOptions): string {
130
+ const stats = [
131
+ agent.progress?.activityState,
132
+ options.showModel !== false && modelForAgent(agent, task) ? `model=${modelForAgent(agent, task)}` : undefined,
133
+ options.showTokens !== false
134
+ ? formatTokens(usageForAgent(agent, task)) ?? (agent.progress?.tokens !== undefined ? `tok=${agent.progress.tokens}` : undefined)
135
+ : undefined,
136
+ options.showTools !== false && agent.progress?.currentTool ? `tool=${agent.progress.currentTool}` : undefined,
137
+ options.showTools !== false && agent.toolUses !== undefined ? `${agent.toolUses} tools` : undefined,
138
+ agent.progress?.turns !== undefined ? `${agent.progress.turns} turns` : undefined,
139
+ agent.progress?.failedTool ? `failedTool=${agent.progress.failedTool}` : undefined,
140
+ agent.startedAt ? `age=${formatAge(agent.completedAt ?? agent.startedAt)}` : undefined,
141
+ ].filter((part): part is string => Boolean(part));
142
+ const recent = agent.progress?.recentOutput?.at(-1);
143
+ return `Agent: ${iconForStatus(agent.status)} ${agent.taskId} ${agent.role}->${agent.agent}${stats.length ? ` · ${stats.join(" · ")}` : ""}${recent ? ` ⎿ ${recent}` : ""}`;
144
+ }
145
+
146
+ function readAgentPreview(run: TeamRunManifest, maxLines = 5, options: RunDashboardOptions = {}): string[] {
147
+ try {
148
+ const snapshot = snapshotFor(run, options.snapshotCache);
149
+ const agents = snapshot?.agents ?? readCrewAgents(run);
150
+ const tasks = snapshot?.tasks ?? readRunTasks(run, options.snapshotCache);
151
+ if (!agents.length) return ["Agents: (none)"];
152
+ const totals = tasks.reduce((acc, task) => {
153
+ acc.input += task.usage?.input ?? 0;
154
+ acc.output += task.usage?.output ?? 0;
155
+ acc.cacheRead += task.usage?.cacheRead ?? 0;
156
+ acc.cacheWrite += task.usage?.cacheWrite ?? 0;
157
+ acc.cost += task.usage?.cost ?? 0;
158
+ return acc;
159
+ }, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 } as { input: number; output: number; cacheRead: number; cacheWrite: number; cost: number });
160
+ const header = formatTokens(totals) ? `Agents: ${formatTokens(totals)}` : "Agents:";
161
+ return [
162
+ header,
163
+ ...agents
164
+ .slice(0, maxLines)
165
+ .map((agent) => agentPreviewLine(agent, taskForAgent(tasks, agent), options)),
166
+ ...(agents.length > maxLines ? [`Agents: +${agents.length - maxLines} more`] : []),
167
+ ];
168
+ } catch (error) {
169
+ const message = error instanceof Error ? error.message : String(error);
170
+ return [`Agents: failed to read (${message})`];
171
+ }
172
+ }
173
+
174
+ function agentsFor(run: TeamRunManifest, snapshotCache?: RunSnapshotCache): CrewAgentRecord[] {
175
+ const snapshot = snapshotFor(run, snapshotCache);
176
+ if (snapshot) return snapshot.agents;
177
+ try {
178
+ return readCrewAgents(run);
179
+ } catch {
180
+ return [];
181
+ }
182
+ }
183
+
184
+ function runLabel(run: TeamRunManifest, selected: boolean, snapshotCache?: RunSnapshotCache): string {
185
+ const agents = agentsFor(run, snapshotCache);
186
+ const stale = isLikelyOrphanedActiveRun(run, agents);
187
+ const running = agents.find((agent) => agent.status === "running");
188
+ const queued = agents.find((agent) => agent.status === "queued");
189
+ const step = stale ? "orphaned queued run" : running ? `step ${running.taskId}` : queued ? `queued ${queued.taskId}` : `agents ${agents.length}`;
190
+ const status: RunStatus = stale ? "stale" : (run.status as RunStatus);
191
+ const marker = selected ? "›" : " ";
192
+ return `${marker} ${iconForStatus(status)} ${run.runId.slice(-8)} ${status} | ${run.team}/${run.workflow ?? "none"} | ${step} | ${run.goal}`;
193
+ }
194
+
195
+ function groupedRuns(runs: TeamRunManifest[], snapshotCache?: RunSnapshotCache): Array<{ label: string; run?: TeamRunManifest }> {
196
+ const active = runs.filter((run) => isDisplayActiveRun(snapshotFor(run, snapshotCache)?.manifest ?? run, agentsFor(run, snapshotCache)));
197
+ const recent = runs.filter((run) => !isDisplayActiveRun(snapshotFor(run, snapshotCache)?.manifest ?? run, agentsFor(run, snapshotCache)));
198
+ const rows: Array<{ label: string; run?: TeamRunManifest }> = [];
199
+ if (active.length) rows.push({ label: "Active" }, ...active.map((run) => ({ label: run.runId, run })));
200
+ if (recent.length) rows.push({ label: "Recent" }, ...recent.map((run) => ({ label: run.runId, run })));
201
+ return rows;
202
+ }
203
+
204
+ function selectedRunFromGrouped(runs: TeamRunManifest[], selected: number, snapshotCache?: RunSnapshotCache): TeamRunManifest | undefined {
205
+ return groupedRuns(runs, snapshotCache).filter((row) => row.run)[selected]?.run;
206
+ }
207
+
208
+ function countByStatus(runs: TeamRunManifest[], snapshotCache?: RunSnapshotCache): string {
209
+ const counts = new Map<RunStatus, number>();
210
+ for (const run of runs) {
211
+ const snapshot = snapshotFor(run, snapshotCache);
212
+ const displayRun = snapshot?.manifest ?? run;
213
+ const status: RunStatus = isLikelyOrphanedActiveRun(displayRun, snapshot?.agents ?? agentsFor(run, snapshotCache)) ? "stale" : (displayRun.status as RunStatus);
214
+ counts.set(status, (counts.get(status) ?? 0) + 1);
215
+ }
216
+ return [...counts.entries()].map(([status, count]) => `${status}=${count}`).join(", ") || "none";
217
+ }
218
+
219
+ export class RunDashboard implements DashboardComponent {
220
+ private selected = 0;
221
+ private showFullProgress = false;
222
+ private activePane: "agents" | "progress" | "mailbox" | "output" | "health" = "agents";
223
+ private runs: TeamRunManifest[];
224
+ private readonly done: (selection: RunDashboardSelection | undefined) => void;
225
+ private readonly theme: CrewTheme;
226
+ private readonly options: RunDashboardOptions;
227
+ private cachedWidth = 0;
228
+ private cachedVersion = "";
229
+ private cachedLines: string[] = [];
230
+ private readonly unsubscribeTheme: () => void;
231
+
232
+ constructor(
233
+ runs: TeamRunManifest[],
234
+ done: (selection: RunDashboardSelection | undefined) => void,
235
+ theme: unknown = {},
236
+ options: RunDashboardOptions = {},
237
+ ) {
238
+ this.runs = runs;
239
+ this.done = done;
240
+ this.theme = asCrewTheme(theme);
241
+ this.options = options;
242
+ this.unsubscribeTheme = subscribeThemeChange(theme, () => this.invalidate());
243
+ }
244
+
245
+ private refreshRuns(): void {
246
+ if (!this.options.runProvider) return;
247
+ const selectedRunId = this.selectedRunId();
248
+ this.runs = this.options.runProvider();
249
+ if (selectedRunId) {
250
+ const nextIndex = groupedRuns(this.runs, this.options.snapshotCache).filter((row) => row.run).findIndex((row) => row.run?.runId === selectedRunId);
251
+ if (nextIndex >= 0) this.selected = nextIndex;
252
+ }
253
+ }
254
+
255
+ private buildSignature(): string {
256
+ const statuses = this.runs.map((run) => {
257
+ const snapshot = snapshotFor(run, this.options.snapshotCache);
258
+ const displayRun = snapshot?.manifest ?? run;
259
+ const agents = snapshot?.agents ?? agentsFor(run, this.options.snapshotCache);
260
+ const stale = isLikelyOrphanedActiveRun(displayRun, agents);
261
+ const status: RunStatus = stale ? "stale" : (displayRun.status as RunStatus);
262
+ return snapshot?.signature ?? `${displayRun.runId}:${displayRun.status}:${displayRun.updatedAt}:${status}`;
263
+ }).join("|");
264
+ return `${this.selected}:${this.showFullProgress ? 1 : 0}:${this.activePane}:${statuses}`;
265
+ }
266
+
267
+ invalidate(): void {
268
+ this.cachedVersion = "";
269
+ this.cachedLines = [];
270
+ }
271
+
272
+ dispose(): void {
273
+ this.unsubscribeTheme();
274
+ }
275
+
276
+ private selectedRunId(): string | undefined {
277
+ return selectedRunFromGrouped(this.runs, this.selected, this.options.snapshotCache)?.runId;
278
+ }
279
+
280
+ render(width: number): string[] {
281
+ this.refreshRuns();
282
+ const signature = this.buildSignature();
283
+ if (signature !== this.cachedVersion || this.cachedWidth !== width) {
284
+ const innerWidth = Math.max(20, width - 4);
285
+ const borderWidth = Math.min(innerWidth, Math.max(0, width - 2));
286
+ const fg = (color: Parameters<CrewTheme["fg"]>[0], text: string) => this.theme.fg(color, text);
287
+ const borderFill = (count: number) => new DynamicCrewBorder(this.theme).render(count)[0];
288
+ const border = (left: string, right: string) => `${fg("border", left)}${borderFill(borderWidth)}${fg("border", right)}`;
289
+
290
+ const lines = [
291
+ border("╭", "╮"),
292
+ `│ ${pad(truncate(`${fg("accent", "▐")} ${this.theme.bold(this.options.placement === "right" ? "pi-crew right sidebar (anchored top-right)" : "pi-crew dashboard")}`, innerWidth - 1), innerWidth - 1)}│`,
293
+ `│ ${pad(truncate(`Runs: ${this.runs.length} • ${countByStatus(this.runs, this.options.snapshotCache)}`, innerWidth - 1), innerWidth - 1)}│`,
294
+ `│ ${pad(truncate(`↑/↓ select 1 agents 2 progress 3 mailbox 4 output 5 health • s/u/a/i actions • R/K/D health • H hush`, innerWidth - 1), innerWidth - 1)}│`,
295
+ border("├", "┤"),
296
+ ];
297
+ if (this.runs.length === 0) {
298
+ lines.push(`│ ${pad(truncate("No runs found.", innerWidth - 1), innerWidth - 1)}│`);
299
+ } else {
300
+ const rows = groupedRuns(this.runs, this.options.snapshotCache).slice(0, 16);
301
+ const selectableRuns = rows.filter((row) => row.run);
302
+ for (const row of rows) {
303
+ if (!row.run) {
304
+ lines.push(`│ ${pad(truncate(fg("accent", row.label), innerWidth - 1), innerWidth - 1)}│`);
305
+ continue;
306
+ }
307
+ const index = selectableRuns.findIndex((candidate) => candidate.run?.runId === row.run?.runId);
308
+ const rowSnapshot = snapshotFor(row.run, this.options.snapshotCache);
309
+ const rowRun = rowSnapshot?.manifest ?? row.run;
310
+ const rowAgents = rowSnapshot?.agents ?? agentsFor(row.run, this.options.snapshotCache);
311
+ const rowStatus = isLikelyOrphanedActiveRun(rowRun, rowAgents) ? "stale" : (rowRun.status as RunStatus);
312
+ const label = runLabel(rowRun, index === this.selected, this.options.snapshotCache);
313
+ lines.push(`│ ${pad(applyStatusColor(this.theme, rowStatus, label), innerWidth - 1)}│`);
314
+ }
315
+ const selectedRun = selectedRunFromGrouped(this.runs, this.selected, this.options.snapshotCache);
316
+ if (selectedRun) {
317
+ const selectedSnapshot = snapshotFor(selectedRun, this.options.snapshotCache);
318
+ const selectedDisplayRun = selectedSnapshot?.manifest ?? selectedRun;
319
+ const selectedAgents = selectedSnapshot?.agents ?? agentsFor(selectedRun, this.options.snapshotCache);
320
+ lines.push(border("├", ""));
321
+ const details = [
322
+ `Selected: ${selectedDisplayRun.runId}`,
323
+ `Status: ${isLikelyOrphanedActiveRun(selectedDisplayRun, selectedAgents) ? "stale" : selectedDisplayRun.status} | Team: ${selectedDisplayRun.team} | Workflow: ${selectedDisplayRun.workflow ?? "none"}`,
324
+ `Created: ${selectedDisplayRun.createdAt}`,
325
+ `Updated: ${selectedDisplayRun.updatedAt}`,
326
+ `Artifacts: ${selectedDisplayRun.artifacts.length} | Workspace: ${selectedDisplayRun.workspaceMode}`,
327
+ selectedDisplayRun.async ? `Async: pid=${selectedDisplayRun.async.pid ?? "unknown"} log=${selectedDisplayRun.async.logPath}` : "Async: no",
328
+ `Goal: ${selectedDisplayRun.goal}`,
329
+ ];
330
+ const paneLines = selectedSnapshot
331
+ ? this.activePane === "agents"
332
+ ? renderAgentsPane(selectedSnapshot, this.options)
333
+ : this.activePane === "progress"
334
+ ? renderProgressPane(selectedSnapshot)
335
+ : this.activePane === "mailbox"
336
+ ? renderMailboxPane(selectedSnapshot)
337
+ : this.activePane === "health"
338
+ ? renderHealthPane(selectedSnapshot, { isForeground: selectedDisplayRun.async ? false : true })
339
+ : renderTranscriptPane(selectedSnapshot)
340
+ : [
341
+ ...readAgentPreview(selectedDisplayRun, this.showFullProgress ? 20 : 8, this.options),
342
+ ...readProgressPreview(selectedDisplayRun, this.showFullProgress ? 20 : 5),
343
+ ];
344
+ for (const detail of [
345
+ ...details,
346
+ `Pane: ${this.activePane}`,
347
+ ...paneLines,
348
+ ...(this.showFullProgress ? readProgressPreview(selectedDisplayRun, 20) : []),
349
+ ]) {
350
+ lines.push(`│ ${pad(truncate(detail, innerWidth - 1), innerWidth - 1)}│`);
351
+ }
352
+ const selectedTasks = selectedSnapshot?.tasks ?? readRunTasks(selectedDisplayRun, this.options.snapshotCache);
353
+ const footer = new CrewFooter({
354
+ pwd: selectedDisplayRun.cwd,
355
+ runId: selectedDisplayRun.runId,
356
+ status: isLikelyOrphanedActiveRun(selectedDisplayRun, selectedAgents) ? "stale" : selectedDisplayRun.status,
357
+ usage: aggregateUsage(selectedTasks),
358
+ badges: [`team ${selectedDisplayRun.team}`, `workflow ${selectedDisplayRun.workflow ?? "none"}`, `${selectedDisplayRun.artifacts.length} artifacts`, selectedDisplayRun.workspaceMode],
359
+ }, this.theme);
360
+ lines.push(border("├", "┤"));
361
+ for (const footerLine of footer.render(innerWidth - 1)) {
362
+ lines.push(`│ ${pad(truncate(footerLine, innerWidth - 1), innerWidth - 1)}│`);
363
+ }
364
+ }
365
+ }
366
+ lines.push(border("╰", "╯"));
367
+ this.cachedLines = renderLines(lines.map((line) => truncate(line, width)), width);
368
+ this.cachedVersion = signature;
369
+ this.cachedWidth = width;
370
+ }
371
+ return this.cachedLines;
372
+ }
373
+
374
+ handleInput(data: string): void {
375
+ const action = dashboardActionForKey(data, this.activePane);
376
+ const selectedRunId = this.selectedRunId();
377
+ if (action === "close") {
378
+ this.done(undefined);
379
+ return;
380
+ }
381
+ if (action === "select") {
382
+ this.done(selectedRunId ? { runId: selectedRunId, action: "status" } : undefined);
383
+ return;
384
+ }
385
+ if (action === "summary" || action === "artifacts" || action === "api" || action === "agents" || action === "mailbox" || action === "reload" || action === "mailbox-detail" || action === "health-recovery" || action === "health-kill-stale" || action === "health-diagnostic-export" || action === "notifications-dismiss") {
386
+ this.done(selectedRunId ? { runId: selectedRunId, action } : action === "reload" ? { runId: "", action } : undefined);
387
+ return;
388
+ }
389
+ if (action === "events") {
390
+ this.done(selectedRunId ? { runId: selectedRunId, action: "agent-events" } : undefined);
391
+ return;
392
+ }
393
+ if (action === "output") {
394
+ this.done(selectedRunId ? { runId: selectedRunId, action: "agent-output" } : undefined);
395
+ return;
396
+ }
397
+ if (action === "transcript") {
398
+ this.done(selectedRunId ? { runId: selectedRunId, action: "agent-transcript" } : undefined);
399
+ return;
400
+ }
401
+ if (action === "progressToggle") {
402
+ this.showFullProgress = !this.showFullProgress;
403
+ this.invalidate();
404
+ return;
405
+ }
406
+ if (action === "pane-agents") this.activePane = "agents";
407
+ else if (action === "pane-progress") this.activePane = "progress";
408
+ else if (action === "pane-mailbox") this.activePane = "mailbox";
409
+ else if (action === "pane-output") this.activePane = "output";
410
+ else if (action === "pane-health") this.activePane = "health";
411
+ else if (action === "up") this.selected = Math.max(0, this.selected - 1);
412
+ else if (action === "down") {
413
+ const selectableCount = groupedRuns(this.runs, this.options.snapshotCache).filter((row) => row.run).length;
414
+ this.selected = Math.min(Math.max(0, selectableCount - 1), this.selected + 1);
415
+ }
416
+ if (action) this.invalidate();
417
+ }
418
+ }