@ferris1225/pi-subagents 6.0.3 → 6.0.5

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 (39) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +83 -200
  3. package/index.ts +8 -13
  4. package/package.json +1 -1
  5. package/src/configuration/config.ts +2 -6
  6. package/src/configuration/role-migration.ts +3 -14
  7. package/src/configuration/setup.ts +66 -57
  8. package/src/configuration/ui.ts +335 -64
  9. package/src/delegation/agents.ts +5 -6
  10. package/src/delegation/builtin-agents.ts +10 -31
  11. package/src/delegation/dispatch.ts +52 -165
  12. package/src/delegation/prompt.ts +29 -82
  13. package/src/execution/background.ts +2 -2
  14. package/src/execution/run-control.ts +1 -1
  15. package/src/execution/spawn.ts +2 -30
  16. package/src/isolation/worktree.ts +0 -14
  17. package/src/lifecycle/cancellation.ts +4 -8
  18. package/src/lifecycle/completion.ts +9 -21
  19. package/src/lifecycle/dispatch-core.ts +7 -7
  20. package/src/lifecycle/durable.ts +5 -29
  21. package/src/lifecycle/runtime.ts +11 -63
  22. package/src/lifecycle/stop.ts +1 -2
  23. package/src/lifecycle/thread-lifecycle.ts +38 -83
  24. package/src/lifecycle/thread-restore.ts +1 -3
  25. package/src/lifecycle/thread-shared.ts +10 -27
  26. package/src/lifecycle/tools.ts +24 -114
  27. package/src/presentation/announcements.ts +8 -6
  28. package/src/presentation/format.ts +39 -14
  29. package/src/presentation/monitor.ts +697 -758
  30. package/src/presentation/widget.ts +34 -142
  31. package/src/delegation/ownership.ts +0 -98
  32. package/src/delegation/phase-scope.ts +0 -186
  33. package/src/workflow/acceptance.ts +0 -67
  34. package/src/workflow/durable.ts +0 -228
  35. package/src/workflow/engine.ts +0 -816
  36. package/src/workflow/plan.ts +0 -409
  37. package/src/workflow/state.ts +0 -55
  38. package/src/workflow/templates.ts +0 -156
  39. package/src/workflow/tool.ts +0 -254
@@ -1,758 +1,697 @@
1
- /**
2
- * Sub-agent monitor: a module-level singleton store that tracks subagent runs
3
- * for the current turn.
4
- *
5
- * The store notifies wait/status consumers on every mutation. Each run carries
6
- * timing information plus a concise activity string ("thinking",
7
- * "read src/index.ts", ...). Settled rows stay until the next beginTurn so the
8
- * footer can count them beside live siblings; the widget ignores them. Tool
9
- * results are the durable user-facing record.
10
- */
11
-
12
- import { stripVTControlCharacters } from "node:util";
13
- import type { Theme } from "@earendil-works/pi-coding-agent";
14
- import { visibleWidth } from "@earendil-works/pi-tui";
15
- import { emptyUsage, type UsageStats } from "../execution/run-control.ts";
16
- import type { WorkflowRun } from "../workflow/state.ts";
17
- import type { IsolationMode, WorktreeFinalizationStatus } from "../isolation/worktree.ts";
18
-
19
- // ---------------------------------------------------------------------------
20
- // Types
21
- // ---------------------------------------------------------------------------
22
-
23
- export type RunStatus = "queued" | "running" | "interrupting" | "parked" | "done" | "failed";
24
-
25
- /** A queued run is preparing its child process; execution has no capacity wait. */
26
- export type RunWaitReason = "starting";
27
-
28
- export function isRunActiveStatus(status: RunStatus): boolean {
29
- return status === "queued" || status === "running" || status === "interrupting";
30
- }
31
-
32
- /** Durable integration projection of a worktree-isolated run: pending before
33
- * settlement, finalizing while the patch is applied/cleaned up, then the
34
- * terminal WorktreeFinalizationStatus. */
35
- export type RunIntegrationStatus = "pending" | "finalizing" | WorktreeFinalizationStatus;
36
-
37
- /** Workflow membership of a run: which graph, and which node of it. Rendered so
38
- * a workflow's nodes read as one group in the widget and the status view. */
39
- export interface RunWorkflowTag {
40
- workflowId: number;
41
- name: string;
42
- nodeId: string;
43
- }
44
-
45
- export interface RunView {
46
- id: number;
47
- agent: string;
48
- task: string;
49
- /** Short content label derived from the task (paths/symbols), shown next to
50
- * the agent name so concurrent same-agent runs are told apart by what they
51
- * are doing, not just by their run id. */
52
- label?: string;
53
- model?: string;
54
- /** Selected model ref when the run handed off to current main. */
55
- modelFallbackFrom?: string;
56
- /** Effective thinking strength this run was launched with (setup override or role default). */
57
- thinking?: string;
58
- isolation?: IsolationMode;
59
- integrationStatus?: RunIntegrationStatus;
60
- worktreeId?: string;
61
- status: RunStatus;
62
- /** What a queued run is actually waiting for; see RunWaitReason. */
63
- waitReason?: RunWaitReason;
64
- usage: UsageStats;
65
- /** Concise current activity ("thinking", "read src/index.ts"); last writer wins. */
66
- activity?: string;
67
- /** Newest-last rolling window of recent activity lines, so a progress query
68
- * answers "what has it been doing" without reading child artifacts. */
69
- recentActivity?: string[];
70
- /** Epoch ms when this logical run first started executing. */
71
- startedAt?: number;
72
- /** Epoch ms when the current active segment started. */
73
- activeSince?: number;
74
- /** Cumulative active execution time from closed segments; parked time is excluded. */
75
- elapsedMs: number;
76
- /** Epoch ms when the latest active segment stopped. */
77
- endedAt?: number;
78
- /** Workflow membership, when this run is a node of a `subagent_workflow` graph. */
79
- workflow?: RunWorkflowTag;
80
- }
81
-
82
- export interface RunChainMeta {
83
- isolation?: IsolationMode;
84
- worktreeId?: string;
85
- /** Set for nodes the workflow runner dispatches. */
86
- workflow?: RunWorkflowTag;
87
- /** Initial startup state before the child emits activity. */
88
- waitReason?: RunWaitReason;
89
- }
90
-
91
- // ---------------------------------------------------------------------------
92
- // Formatting helpers
93
- // ---------------------------------------------------------------------------
94
-
95
- const TASK_SUMMARY_MAX = 80;
96
- const TASK_SUMMARY_ELLIPSIS = "…";
97
- /** Columns reserved at the END of a truncated summary so the distinguishing
98
- * keywords (paths, symbols, ...) survive; the head gets the rest. */
99
- const TASK_SUMMARY_TAIL_MAX = 28;
100
- /** Tail share of a non-default maxWidth (narrow summaries keep a usable tail). */
101
- const TASK_SUMMARY_TAIL_SHARE = 0.35;
102
- const TASK_SUMMARY_TAIL_MIN = 8;
103
- const TASK_SUMMARY_KEY_SEP = " · ";
104
- /** kebab/snake words that are task boilerplate, never distinguishing signal. */
105
- const KEY_FRAGMENT_STOPWORDS = new Set([
106
- "self-contained",
107
- "read-only",
108
- "write-only",
109
- "auto-fix",
110
- "re-review",
111
- "one-line",
112
- "pre-commit",
113
- ]);
114
- const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
115
-
116
- interface KeyFragment {
117
- text: string;
118
- index: number;
119
- }
120
-
121
- /**
122
- * Pull the most distinguishing fragments out of a task: file paths, quoted
123
- * phrases, camelCase/PascalCase symbols and kebab/snake compounds. Sorted by
124
- * first occurrence and deduped (a path covers its own sub-fragments). These
125
- * are what make parallel tasks of the same agent look different.
126
- */
127
- function extractKeyFragments(text: string): string[] {
128
- const fragments: KeyFragment[] = [];
129
- const add = (re: RegExp, group = 0): void => {
130
- for (const m of text.matchAll(re)) {
131
- const g = m[group];
132
- if (g === undefined) continue;
133
- fragments.push({ text: g, index: m.index ?? 0 });
134
- }
135
- };
136
- // Quoted phrases first (highest signal).
137
- add(/["'`]([^"'`]{4,60})["'`]/g, 1);
138
- // Paths with a known extension (src/index.ts, build/out.js.map).
139
- add(/(?<![A-Za-z0-9_.-])[A-Za-z0-9_.-]+\.[A-Za-z0-9]{1,5}(?![A-Za-z0-9_.-])/g);
140
- // Paths with a slash but no extension (src/components, .github/workflows).
141
- add(/(?<![A-Za-z0-9_.-])[A-Za-z0-9_.-]+(?:[\\/][A-Za-z0-9_.-]+)+(?![\\/])/g);
142
- // camelCase / PascalCase identifiers (function or type names).
143
- add(/\b[a-z][a-zA-Z0-9]*[A-Z][a-zA-Z0-9]*\b/g);
144
- // snake_case / kebab-case compound words.
145
- add(/\b[a-z][a-z0-9]+[-_][a-z0-9][a-z0-9_-]*\b/g);
146
-
147
- fragments.sort((a, b) => a.index - b.index);
148
- const seen = new Set<string>();
149
- const out: string[] = [];
150
- for (const f of fragments) {
151
- const t = f.text.trim();
152
- if (t.length < 4 || KEY_FRAGMENT_STOPWORDS.has(t)) continue;
153
- if (seen.has(t)) continue;
154
- // A longer fragment (the full path) covers its own sub-fragments.
155
- if (out.some((o) => o.includes(t) || t.includes(o))) continue;
156
- seen.add(t);
157
- out.push(t);
158
- }
159
- return out;
160
- }
161
-
162
- function takeGraphemes(segments: string[], maxWidth: number): string {
163
- let width = 0;
164
- const out: string[] = [];
165
- for (const segment of segments) {
166
- const segmentWidth = visibleWidth(segment);
167
- if (width + segmentWidth > maxWidth) break;
168
- out.push(segment);
169
- width += segmentWidth;
170
- }
171
- return out.join("");
172
- }
173
-
174
- function tailGraphemes(segments: string[], maxWidth: number): string {
175
- let width = 0;
176
- const tail: string[] = [];
177
- for (let i = segments.length - 1; i >= 0; i--) {
178
- const segmentWidth = visibleWidth(segments[i]);
179
- if (width + segmentWidth > maxWidth) break;
180
- tail.unshift(segments[i]);
181
- width += segmentWidth;
182
- }
183
- return tail.join("");
184
- }
185
-
186
- /**
187
- * One-line task preview, capped by `maxWidth` display columns (default 80).
188
- * `keysOnly` (default): extracted key fragments (paths, quoted phrases,
189
- * symbols) are shown bare — the agent name is already displayed next to the
190
- * task line, so templated prose ("scout: trace how ...") adds nothing.
191
- * `keysOnly: false` keeps the prose as `head…tail` (used for completion
192
- * messages, where the Task line is the reader's only context).
193
- * Grapheme-safe — CJK, ZWJ emoji and combining sequences are never split.
194
- */
195
- export function formatTaskSummary(task: string, maxWidth: number = TASK_SUMMARY_MAX, keysOnly = true): string {
196
- if (maxWidth <= 0) return "";
197
- const oneLine = stripVTControlCharacters(task).replace(/\s+/g, " ").trim();
198
- if (visibleWidth(oneLine) <= maxWidth) return oneLine;
199
-
200
- const segments = [...graphemeSegmenter.segment(oneLine)].map((s) => s.segment);
201
- const ellipsisWidth = visibleWidth(TASK_SUMMARY_ELLIPSIS);
202
-
203
- if (keysOnly) {
204
- const fragments = extractKeyFragments(oneLine);
205
- if (fragments.length > 0) {
206
- const keyMax = maxWidth - 1;
207
- let keys = "";
208
- for (const fragment of fragments) {
209
- const piece = keys ? `${TASK_SUMMARY_KEY_SEP}${fragment}` : fragment;
210
- const total = keys + piece;
211
- if (visibleWidth(total) > keyMax) {
212
- // Budget exhausted: keep what fits, unless nothing fits yet.
213
- if (!keys) {
214
- // A single over-long fragment keeps its tail
215
- // (extension/symbol) and is prefixed with the ellipsis.
216
- const fragmentSegments = [...graphemeSegmenter.segment(piece)].map((s) => s.segment);
217
- keys = `${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(fragmentSegments, keyMax - ellipsisWidth)}`;
218
- }
219
- break;
220
- }
221
- keys = total;
222
- }
223
- return keys;
224
- }
225
- }
226
-
227
- // No distinctive fragments (or prose mode): fall back to head…tail.
228
- const tailMax = Math.max(
229
- TASK_SUMMARY_TAIL_MIN,
230
- Math.min(TASK_SUMMARY_TAIL_MAX, Math.round(maxWidth * TASK_SUMMARY_TAIL_SHARE)),
231
- );
232
- const headMax = maxWidth - ellipsisWidth - tailMax;
233
- if (headMax <= 0) {
234
- return `${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(segments, maxWidth - ellipsisWidth)}`;
235
- }
236
- return `${takeGraphemes(segments, headMax)}${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(segments, tailMax)}`;
237
- }
238
-
239
- /** Max display width of a run's content label. */
240
- const RUN_LABEL_MAX = 32;
241
-
242
- /**
243
- * Short content label for a run, derived from its task: the single most
244
- * distinguishing fragment so concurrent same-agent runs are told apart by WHAT
245
- * they do, not just their run id. A file/directory path outranks other
246
- * fragment kinds (a kebab-case word like "edge-case" never beats
247
- * "src/config.ts"); a long path keeps its tail (the filename is the
248
- * recognisable part); a task with no recognizable fragment falls back to a
249
- * head slice of its prose. Grapheme-safe.
250
- */
251
- export function runLabel(task: string): string {
252
- const oneLine = stripVTControlCharacters(task).replace(/\s+/g, " ").trim();
253
- const fragments = extractKeyFragments(oneLine);
254
- const fragment = fragments.find((candidate) => /[\\/]|\.[A-Za-z0-9]{1,5}$/.test(candidate)) ?? fragments[0];
255
- const src = fragment ?? oneLine;
256
- if (visibleWidth(src) <= RUN_LABEL_MAX) return src;
257
- const chars = [...graphemeSegmenter.segment(src)].map((s) => s.segment);
258
- // A path/symbol fragment keeps its tail (filename/symbol is recognisable);
259
- // a prose fallback keeps its head.
260
- return fragment
261
- ? `${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(chars, RUN_LABEL_MAX - 1)}`
262
- : `${takeGraphemes(chars, RUN_LABEL_MAX - 1)}${TASK_SUMMARY_ELLIPSIS}`;
263
- }
264
-
265
- /** Narrow an already-extracted run label to a smaller budget, keeping its
266
- * tail: runLabel tail-weights path fragments because the filename is the
267
- * recognisable part, and a second squeeze must not trade that tail away.
268
- * Grapheme-safe. */
269
- export function shrinkRunLabel(text: string, maxWidth: number): string {
270
- if (maxWidth <= 0) return "";
271
- if (visibleWidth(text) <= maxWidth) return text;
272
- const chars = [...graphemeSegmenter.segment(text)].map((s) => s.segment);
273
- return `${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(chars, maxWidth - 1)}`;
274
- }
275
-
276
- function formatTokens(count: number): string {
277
- if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
278
- if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`;
279
- return String(count);
280
- }
281
-
282
- /** Token flow in the pi-footer vocabulary: ↑input ↓output, R cache-read,
283
- * W cache-write; zero components are omitted. No cost — callers place it as
284
- * its own droppable part. */
285
- export function formatUsageTokens(usage: UsageStats | undefined): string | undefined {
286
- if (!usage) return undefined;
287
- const parts: string[] = [];
288
- if (usage.input) parts.push(`↑${formatTokens(usage.input)}`);
289
- if (usage.output) parts.push(`↓${formatTokens(usage.output)}`);
290
- if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`);
291
- if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`);
292
- return parts.length > 0 ? parts.join(" ") : undefined;
293
- }
294
-
295
- export function formatUsageCompact(usage: UsageStats): string {
296
- return [formatUsageTokens(usage), usageCostPart(usage)].filter(Boolean).join(" ");
297
- }
298
-
299
- /** Cost as its own droppable part: `$0.0421`, undefined when nothing accrued. */
300
- function usageCostPart(usage: UsageStats | undefined): string | undefined {
301
- return usage?.cost ? `$${usage.cost.toFixed(4)}` : undefined;
302
- }
303
-
304
- /** Aggregate usage across several runs (chain steps or a completion group). */
305
- export function sumUsage(parts: readonly UsageStats[]): UsageStats {
306
- const total: UsageStats = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 };
307
- for (const part of parts) {
308
- total.input += part.input;
309
- total.output += part.output;
310
- total.cacheRead += part.cacheRead;
311
- total.cacheWrite += part.cacheWrite;
312
- total.cost += part.cost;
313
- total.contextTokens += part.contextTokens;
314
- total.turns += part.turns;
315
- }
316
- return total;
317
- }
318
-
319
- export function formatDuration(ms: number): string {
320
- const totalSeconds = Math.max(0, Math.floor(ms / 1000));
321
- if (totalSeconds < 60) return `${totalSeconds}s`;
322
- const minutes = Math.floor(totalSeconds / 60);
323
- const seconds = totalSeconds % 60;
324
- // Seconds stay visible at every magnitude: a long-running chain is judged
325
- // by whether it is still moving, and "5s ago" is exactly that signal.
326
- if (minutes < 60) return `${minutes}m${String(seconds).padStart(2, "0")}s`;
327
- const hours = Math.floor(minutes / 60);
328
- return `${hours}h${String(minutes % 60).padStart(2, "0")}m${String(seconds).padStart(2, "0")}s`;
329
- }
330
-
331
- function elapsedMilliseconds(run: RunView, now: number = Date.now()): number {
332
- let elapsed = run.elapsedMs ?? 0;
333
- if (run.activeSince !== undefined) elapsed += Math.max(0, now - run.activeSince);
334
- // Keep formatting tolerant of older/synthetic RunView values that predate
335
- // segmented timing and carry only startedAt/endedAt.
336
- if (elapsed === 0 && run.startedAt !== undefined && run.activeSince === undefined) {
337
- elapsed = Math.max(0, (run.endedAt ?? now) - run.startedAt);
338
- }
339
- return elapsed;
340
- }
341
-
342
- export function formatElapsed(run: RunView, now: number = Date.now()): string {
343
- if (run.startedAt === undefined && run.elapsedMs <= 0) return "";
344
- return formatDuration(elapsedMilliseconds(run, now));
345
- }
346
-
347
- /** Max length of the argument target inside a formatted activity line. */
348
- const ACTIVITY_TARGET_MAX = 60;
349
-
350
- const REDACTED = "<redacted>";
351
-
352
- /** Remove credentials embedded in otherwise ordinary activity strings such as
353
- * shell commands and HTTP headers. */
354
- function redactSensitiveText(value: string): string {
355
- let text = stripVTControlCharacters(value);
356
- text = text.replace(
357
- /(\bauthorization\s*:\s*(?:bearer|basic)\s+)([^\s'"`;,]+)/giu,
358
- `$1${REDACTED}`,
359
- );
360
- text = text.replace(
361
- /(\bbearer\s+)([A-Za-z0-9._~+/=-]{6,})/giu,
362
- `$1${REDACTED}`,
363
- );
364
- text = text.replace(
365
- /(\b(?:api[-_]?key|apikey|access[-_]?token|refresh[-_]?token|token|password|passwd|secret|credential|cookie)\b\s*(?:=|:)\s*)(?:"[^"]*"|'[^']*'|[^\s;&,]+)/giu,
366
- `$1${REDACTED}`,
367
- );
368
- text = text.replace(
369
- /((?:--?(?:api[-_]?key|access[-_]?token|token|password|secret|credential))\s+)(?:"[^"]*"|'[^']*'|\S+)/giu,
370
- `$1${REDACTED}`,
371
- );
372
- return text.replace(
373
- /\b(?:sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9]{8,}|AKIA[A-Z0-9]{16})\b/gu,
374
- REDACTED,
375
- );
376
- }
377
-
378
- /** Monitor activity is returned to the parent model and rendered in the terminal,
379
- * so treat every live string as untrusted before it reaches store state. */
380
- function sanitizeActivityText(value: string): string {
381
- return redactSensitiveText(value).replace(/\s+/g, " ").trim();
382
- }
383
-
384
- function shortTarget(value: unknown): string {
385
- if (typeof value !== "string") return "";
386
- const oneLine = sanitizeActivityText(value);
387
- // Slice by code point so emoji / CJK-ext never leave a lone surrogate.
388
- const chars = [...oneLine];
389
- return chars.length > ACTIVITY_TARGET_MAX ? `${chars.slice(0, ACTIVITY_TARGET_MAX - 1).join("")}…` : oneLine;
390
- }
391
-
392
- /** A code-mode script's first meaningful line: the earliest line that is not
393
- * blank and not a `//` comment, shortened like any other activity target. */
394
- function scriptLine(value: unknown): string {
395
- if (typeof value !== "string") return "";
396
- const line = value
397
- .split("\n")
398
- .map((part) => part.trim())
399
- .find((part) => part.length > 0 && !part.startsWith("//"));
400
- return line ? shortTarget(line) : "";
401
- }
402
-
403
- /** Newest-last rolling window of what a run has been doing, surfaced to the
404
- * parent model as a progress trail. */
405
- const RECENT_ACTIVITY_MAX = 6;
406
-
407
- /** Concise "what is it doing" text for a tool call: the tool name plus its single
408
- * most telling argument (path, command, pattern, ...) — never a raw JSON blob. */
409
- export function formatToolActivity(toolName: string, args: unknown): string {
410
- const a = (typeof args === "object" && args !== null ? args : {}) as Record<string, unknown>;
411
- const pick = (...keys: string[]): string => {
412
- for (const key of keys) {
413
- const s = shortTarget(a[key]);
414
- if (s) return s;
415
- }
416
- return "";
417
- };
418
- let target: string;
419
- switch (toolName) {
420
- // Pi ships one shell tool per platform flavor, all with a `command`
421
- // parameter: a Windows parent that swapped bash for powershell must still
422
- // show the command it is running, not a bare tool name.
423
- case "bash":
424
- case "powershell":
425
- case "shell":
426
- target = pick("command");
427
- break;
428
- case "read":
429
- case "edit":
430
- case "write":
431
- case "ls":
432
- target = pick("path", "file", "filePath");
433
- break;
434
- case "grep":
435
- case "find":
436
- target = pick("pattern", "query", "path");
437
- break;
438
- case "codemode":
439
- // A script is source, not a target: name its first meaningful line so the
440
- // trail shows what the child is doing instead of a code blob.
441
- target = scriptLine(a.code);
442
- break;
443
- case "subagent":
444
- target = pick("agent", "task");
445
- break;
446
- default:
447
- target = pick("path", "command", "query", "pattern", "url", "file", "task");
448
- }
449
- const safeToolName = sanitizeActivityText(toolName) || "tool";
450
- return target ? `${safeToolName} ${target}` : safeToolName;
451
- }
452
-
453
- // ---------------------------------------------------------------------------
454
- // MonitorStore
455
- // ---------------------------------------------------------------------------
456
-
457
- export class MonitorStore {
458
- private runs: RunView[] = [];
459
- private workflows = new Map<number, WorkflowRun>();
460
-
461
- updateWorkflow(run: WorkflowRun): void {
462
- this.workflows.set(run.id, run);
463
- this.notify();
464
- }
465
-
466
- getWorkflows(): WorkflowRun[] {
467
- return [...this.workflows.values()];
468
- }
469
- private nextId = 1;
470
- private subscribers = new Set<() => void>();
471
-
472
- beginTurn(): void {
473
- for (const [id, run] of this.workflows) {
474
- if (run.state !== "running") this.workflows.delete(id);
475
- }
476
- // Clear finished runs from a previous turn, but keep active and parked
477
- // threads so concurrent work is not wiped between parent turns.
478
- this.runs = this.runs.filter(
479
- (r) => isRunActiveStatus(r.status) || r.status === "parked",
480
- );
481
- this.notify();
482
- }
483
-
484
- /** Reserve a stable id for a durable result that must remain independently
485
- * addressable without appearing as a live monitor row. */
486
- reserveRunId(): number {
487
- return this.nextId++;
488
- }
489
-
490
- /** Keep newly allocated ids above a restored id so reload-restored threads
491
- * never collide with runs started in the current process. */
492
- ensureNextIdAbove(id: number): void {
493
- if (id >= this.nextId) this.nextId = id + 1;
494
- }
495
-
496
- /** Re-register a durable thread restored from a previous process. The row
497
- * keeps its stable id and historical elapsed time. */
498
- restoreRun(view: Pick<RunView, "id" | "agent" | "task" | "status"> & Partial<RunView>): void {
499
- if (this.find(view.id)) return;
500
- this.runs.push({
501
- label: runLabel(view.task),
502
- usage: emptyUsage(),
503
- elapsedMs: 0,
504
- ...view,
505
- });
506
- this.ensureNextIdAbove(view.id);
507
- this.notify();
508
- }
509
-
510
- addRun(agent: string, task: string, model?: string, thinking?: string, meta?: RunChainMeta): number {
511
- const id = this.reserveRunId();
512
- this.runs.push({
513
- id,
514
- agent,
515
- task,
516
- // A graph node is identified by its graph and node id: the task text it
517
- // actually runs is interpolated with upstream answers, which makes a
518
- // fragment-extracted label read like noise.
519
- label: meta?.workflow ? `${meta.workflow.name}/${meta.workflow.nodeId}` : runLabel(task),
520
- model,
521
- thinking,
522
- status: "queued",
523
- waitReason: meta?.waitReason ?? "starting",
524
- usage: emptyUsage(),
525
- elapsedMs: 0,
526
- ...(meta?.isolation ? { isolation: meta.isolation, integrationStatus: meta.isolation === "worktree" ? "pending" : undefined, ...(meta.worktreeId ? { worktreeId: meta.worktreeId } : {}) } : {}),
527
- ...(meta?.workflow ? { workflow: meta.workflow } : {}),
528
- });
529
- this.notify();
530
- return id;
531
- }
532
-
533
- setStatus(id: number, status: RunStatus): void {
534
- const run = this.find(id);
535
- if (!run) return;
536
- const previousStatus = run.status;
537
- const wasExecuting = previousStatus === "running" || previousStatus === "interrupting";
538
- const isExecuting = status === "running" || status === "interrupting";
539
- const now = Date.now();
540
- run.status = status;
541
- if (status !== "queued") run.waitReason = undefined;
542
- if (isExecuting && !wasExecuting) {
543
- run.startedAt ??= now;
544
- run.activeSince = now;
545
- run.endedAt = undefined;
546
- } else if (!isExecuting && wasExecuting && run.activeSince !== undefined) {
547
- run.elapsedMs += Math.max(0, now - run.activeSince);
548
- run.activeSince = undefined;
549
- }
550
- if ((status === "parked" || status === "done" || status === "failed") && run.endedAt === undefined) {
551
- run.endedAt = now;
552
- }
553
- this.notify();
554
- }
555
- /** Record what a still-queued run is actually waiting for, at the exact
556
- * transition owned by the caller (lane wait begins, child process starts). */
557
- setWaitReason(id: number, waitReason: RunWaitReason): void {
558
- const run = this.find(id);
559
- if (!run || run.status !== "queued" || run.waitReason === waitReason) return;
560
- run.waitReason = waitReason;
561
- this.notify();
562
- }
563
-
564
- setUsage(id: number, usage: UsageStats, model?: string): void {
565
- const run = this.find(id);
566
- if (!run) return;
567
- run.usage = { ...usage };
568
- if (model) run.model = model;
569
- this.notify();
570
- }
571
-
572
- /** Record the final actual model and selected-to-main transition. */
573
- setModel(id: number, model?: string, fallbackFrom?: string): void {
574
- const run = this.find(id);
575
- if (!run) return;
576
- if (model) run.model = model;
577
- run.modelFallbackFrom = fallbackFrom;
578
- this.notify();
579
- }
580
-
581
- /** Record the capability-clamped thinking level for the active model. */
582
- setThinking(id: number, thinking?: string): void {
583
- const run = this.find(id);
584
- if (!run || !thinking) return;
585
- run.thinking = thinking;
586
- this.notify();
587
- }
588
-
589
- /** Update the run's current one-line activity (what it is doing now). */
590
- setActivity(id: number, text: string): void {
591
- const run = this.find(id);
592
- if (!run) return;
593
- const safe = sanitizeActivityText(text) || undefined;
594
- // Every streamed thinking/text delta reports the same activity; skip the
595
- // notification (and the widget re-render it triggers) when nothing changed.
596
- if (run.activity === safe) return;
597
- run.activity = safe;
598
- if (safe) this.pushRecentActivity(run, safe);
599
- this.notify();
600
- }
601
-
602
- /** Record a tool starting and update the run's visible activity. */
603
- recordToolStart(id: number, toolName: string, activity: string): void {
604
- const run = this.find(id);
605
- if (!run) return;
606
- const safeToolName = sanitizeActivityText(toolName) || "tool";
607
- const safeActivity = sanitizeActivityText(activity) || safeToolName;
608
- run.activity = safeActivity;
609
- this.pushRecentActivity(run, safeActivity);
610
- this.notify();
611
- }
612
-
613
- /** Record a failed tool; successful completions keep their last activity
614
- * until the next model event supplies a more useful description. */
615
- recordToolEnd(id: number, toolName: string, isError: boolean): void {
616
- const run = this.find(id);
617
- if (!run) return;
618
- if (isError) {
619
- const failed = `✗ ${sanitizeActivityText(toolName) || "tool"} failed`;
620
- run.activity = failed;
621
- this.pushRecentActivity(run, failed);
622
- }
623
- this.notify();
624
- }
625
-
626
- setIsolation(
627
- id: number,
628
- isolation: IsolationMode,
629
- integrationStatus?: RunIntegrationStatus,
630
- worktreeId?: string,
631
- ): void {
632
- const run = this.find(id);
633
- if (!run) return;
634
- run.isolation = isolation;
635
- run.integrationStatus = integrationStatus;
636
- if (worktreeId) run.worktreeId = worktreeId;
637
- this.notify();
638
- }
639
-
640
- getElapsedMs(id: number, now: number = Date.now()): number | undefined {
641
- const run = this.find(id);
642
- return run ? elapsedMilliseconds(run, now) : undefined;
643
- }
644
-
645
- /** Look up a run by id without removing it. */
646
- findRun(id: number): RunView | undefined {
647
- return this.find(id);
648
- }
649
-
650
- /** Remove all runs (used on session shutdown so stale state never leaks
651
- * into the next session). Does not reset the id counter so in-flight
652
- * finishRun calls from the old session remain safe no-ops. */
653
- clear(): void {
654
- this.runs = [];
655
- this.workflows.clear();
656
- this.notify();
657
- }
658
-
659
- /** Remove a run after publication. Returns the removed run. */
660
- removeRun(id: number): RunView | undefined {
661
- const index = this.runs.findIndex((r) => r.id === id);
662
- if (index === -1) return undefined;
663
- const [run] = this.runs.splice(index, 1);
664
- this.notify();
665
- return run;
666
- }
667
-
668
- getRuns(): RunView[] {
669
- return this.runs;
670
- }
671
-
672
- subscribe(cb: () => void): () => void {
673
- this.subscribers.add(cb);
674
- return () => {
675
- this.subscribers.delete(cb);
676
- };
677
- }
678
-
679
- summarize(run: RunView): string {
680
- const usage = formatUsageCompact(run.usage);
681
- const parts = [run.agent];
682
- if (run.model) parts.push(run.model);
683
- if (run.thinking) parts.push(`thinking ${run.thinking}`);
684
- if (run.isolation === "worktree") parts.push(`worktree ${run.integrationStatus ?? "active"}`);
685
- if (usage) parts.push(usage);
686
- const elapsed = formatElapsed(run);
687
- if (elapsed) parts.push(elapsed);
688
- return parts.join(" · ");
689
- }
690
-
691
- private find(id: number): RunView | undefined {
692
- return this.runs.find((r) => r.id === id);
693
- }
694
-
695
- /** Newest-last rolling activity window; consecutive duplicates collapse. */
696
- private pushRecentActivity(run: RunView, text: string): void {
697
- const recent = run.recentActivity ?? [];
698
- if (recent[recent.length - 1] !== text) recent.push(text);
699
- if (recent.length > RECENT_ACTIVITY_MAX) recent.splice(0, recent.length - RECENT_ACTIVITY_MAX);
700
- run.recentActivity = recent;
701
- }
702
-
703
- private notify(): void {
704
- for (const cb of this.subscribers) {
705
- try {
706
- cb();
707
- } catch {
708
- /* subscriber errors must not break the store */
709
- }
710
- }
711
- }
712
- }
713
-
714
- export const monitor = new MonitorStore();
715
-
716
- // ---------------------------------------------------------------------------
717
- // Status icons
718
- // ---------------------------------------------------------------------------
719
-
720
- export function statusIcon(status: RunStatus, theme: Theme): string {
721
- switch (status) {
722
- case "running":
723
- return theme.fg("accent", "●");
724
- case "interrupting":
725
- return theme.fg("warning", "◐");
726
- case "parked":
727
- return theme.fg("dim", "■");
728
- case "done":
729
- return theme.fg("success", "✓");
730
- case "failed":
731
- return theme.fg("error", "✗");
732
- default:
733
- return theme.fg("dim", "○");
734
- }
735
- }
736
-
737
- /** User-facing lifecycle label used by tool/status rendering. */
738
- export function statusLabel(status: RunStatus): string {
739
- switch (status) {
740
- case "queued":
741
- return "queued";
742
- case "running":
743
- return "running";
744
- case "interrupting":
745
- return "interrupting";
746
- case "parked":
747
- return "parked";
748
- case "done":
749
- return "done";
750
- case "failed":
751
- return "stopped";
752
- }
753
- }
754
-
755
- /** Startup label for runs that have not emitted activity yet. */
756
- export function runWaitLabel(run: Pick<RunView, "status" | "waitReason">): string | undefined {
757
- return run.status === "queued" ? "starting" : undefined;
758
- }
1
+ /**
2
+ * Sub-agent monitor: a module-level singleton store that tracks subagent runs
3
+ * for the current turn.
4
+ *
5
+ * The store notifies wait/status consumers on every mutation. Each run carries
6
+ * timing information plus a concise activity string ("thinking",
7
+ * "read src/index.ts", ...). Settled rows stay until the next beginTurn so the
8
+ * footer can count them beside live siblings; the widget ignores them. Tool
9
+ * results are the durable user-facing record.
10
+ */
11
+
12
+ import { stripVTControlCharacters } from "node:util";
13
+ import type { Theme } from "@earendil-works/pi-coding-agent";
14
+ import { visibleWidth } from "@earendil-works/pi-tui";
15
+ import { emptyUsage, type UsageStats } from "../execution/run-control.ts";
16
+ import type { IsolationMode, WorktreeFinalizationStatus } from "../isolation/worktree.ts";
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Types
20
+ // ---------------------------------------------------------------------------
21
+
22
+ /** A queued run is preparing its child process; execution has no capacity wait. */
23
+ export type RunStatus = "queued" | "running" | "interrupting" | "parked" | "done" | "failed";
24
+
25
+ export function isRunActiveStatus(status: RunStatus): boolean {
26
+ return status === "queued" || status === "running" || status === "interrupting";
27
+ }
28
+
29
+ /** Durable integration projection of a worktree-isolated run: pending before
30
+ * settlement, finalizing while the patch is applied/cleaned up, then the
31
+ * terminal WorktreeFinalizationStatus. */
32
+ export type RunIntegrationStatus = "pending" | "finalizing" | WorktreeFinalizationStatus;
33
+
34
+ export interface RunView {
35
+ id: number;
36
+ agent: string;
37
+ task: string;
38
+ /** Short content label derived from the task (paths/symbols), shown next to
39
+ * the agent name so concurrent same-agent runs are told apart by what they
40
+ * are doing, not just by their run id. */
41
+ label?: string;
42
+ model?: string;
43
+ /** Effective thinking strength this run was launched with (setup override or role default). */
44
+ thinking?: string;
45
+ isolation?: IsolationMode;
46
+ integrationStatus?: RunIntegrationStatus;
47
+ worktreeId?: string;
48
+ status: RunStatus;
49
+ usage: UsageStats;
50
+ /** Concise current activity ("thinking", "read src/index.ts"); last writer wins. */
51
+ activity?: string;
52
+ /** Newest-last rolling window of recent activity lines, so a progress query
53
+ * answers "what has it been doing" without reading child artifacts. */
54
+ recentActivity?: string[];
55
+ /** Epoch ms when this logical run first started executing. */
56
+ startedAt?: number;
57
+ /** Epoch ms when the current active segment started. */
58
+ activeSince?: number;
59
+ /** Cumulative active execution time from closed segments; parked time is excluded. */
60
+ elapsedMs: number;
61
+ /** Epoch ms when the latest active segment stopped. */
62
+ endedAt?: number;
63
+ }
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // Formatting helpers
67
+ // ---------------------------------------------------------------------------
68
+
69
+ const TASK_SUMMARY_MAX = 80;
70
+ const TASK_SUMMARY_ELLIPSIS = "…";
71
+ /** Columns reserved at the END of a truncated summary so the distinguishing
72
+ * keywords (paths, symbols, ...) survive; the head gets the rest. */
73
+ const TASK_SUMMARY_TAIL_MAX = 28;
74
+ /** Tail share of a non-default maxWidth (narrow summaries keep a usable tail). */
75
+ const TASK_SUMMARY_TAIL_SHARE = 0.35;
76
+ const TASK_SUMMARY_TAIL_MIN = 8;
77
+ const TASK_SUMMARY_KEY_SEP = " · ";
78
+ /** kebab/snake words that are task boilerplate, never distinguishing signal. */
79
+ const KEY_FRAGMENT_STOPWORDS = new Set([
80
+ "self-contained",
81
+ "read-only",
82
+ "write-only",
83
+ "auto-fix",
84
+ "re-review",
85
+ "one-line",
86
+ "pre-commit",
87
+ ]);
88
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
89
+
90
+ interface KeyFragment {
91
+ text: string;
92
+ index: number;
93
+ }
94
+
95
+ /**
96
+ * Pull the most distinguishing fragments out of a task: file paths, quoted
97
+ * phrases, camelCase/PascalCase symbols and kebab/snake compounds. Sorted by
98
+ * first occurrence and deduped (a path covers its own sub-fragments). These
99
+ * are what make parallel tasks of the same agent look different.
100
+ */
101
+ function extractKeyFragments(text: string): string[] {
102
+ const fragments: KeyFragment[] = [];
103
+ const add = (re: RegExp, group = 0): void => {
104
+ for (const m of text.matchAll(re)) {
105
+ const g = m[group];
106
+ if (g === undefined) continue;
107
+ fragments.push({ text: g, index: m.index ?? 0 });
108
+ }
109
+ };
110
+ // Quoted phrases first (highest signal).
111
+ add(/["'`]([^"'`]{4,60})["'`]/g, 1);
112
+ // Paths with a known extension (src/index.ts, build/out.js.map).
113
+ add(/(?<![A-Za-z0-9_.-])[A-Za-z0-9_.-]+\.[A-Za-z0-9]{1,5}(?![A-Za-z0-9_.-])/g);
114
+ // Paths with a slash but no extension (src/components, .github/workflows).
115
+ add(/(?<![A-Za-z0-9_.-])[A-Za-z0-9_.-]+(?:[\\/][A-Za-z0-9_.-]+)+(?![\\/])/g);
116
+ // camelCase / PascalCase identifiers (function or type names).
117
+ add(/\b[a-z][a-zA-Z0-9]*[A-Z][a-zA-Z0-9]*\b/g);
118
+ // snake_case / kebab-case compound words.
119
+ add(/\b[a-z][a-z0-9]+[-_][a-z0-9][a-z0-9_-]*\b/g);
120
+
121
+ fragments.sort((a, b) => a.index - b.index);
122
+ const seen = new Set<string>();
123
+ const out: string[] = [];
124
+ for (const f of fragments) {
125
+ const t = f.text.trim();
126
+ if (t.length < 4 || KEY_FRAGMENT_STOPWORDS.has(t)) continue;
127
+ if (seen.has(t)) continue;
128
+ // A longer fragment (the full path) covers its own sub-fragments.
129
+ if (out.some((o) => o.includes(t) || t.includes(o))) continue;
130
+ seen.add(t);
131
+ out.push(t);
132
+ }
133
+ return out;
134
+ }
135
+
136
+ function takeGraphemes(segments: string[], maxWidth: number): string {
137
+ let width = 0;
138
+ const out: string[] = [];
139
+ for (const segment of segments) {
140
+ const segmentWidth = visibleWidth(segment);
141
+ if (width + segmentWidth > maxWidth) break;
142
+ out.push(segment);
143
+ width += segmentWidth;
144
+ }
145
+ return out.join("");
146
+ }
147
+
148
+ function tailGraphemes(segments: string[], maxWidth: number): string {
149
+ let width = 0;
150
+ const tail: string[] = [];
151
+ for (let i = segments.length - 1; i >= 0; i--) {
152
+ const segmentWidth = visibleWidth(segments[i]);
153
+ if (width + segmentWidth > maxWidth) break;
154
+ tail.unshift(segments[i]);
155
+ width += segmentWidth;
156
+ }
157
+ return tail.join("");
158
+ }
159
+
160
+ /**
161
+ * One-line task preview, capped by `maxWidth` display columns (default 80).
162
+ * `keysOnly` (default): extracted key fragments (paths, quoted phrases,
163
+ * symbols) are shown bare — the agent name is already displayed next to the
164
+ * task line, so templated prose ("scout: trace how ...") adds nothing.
165
+ * `keysOnly: false` keeps the prose as `head…tail` (used for completion
166
+ * messages, where the Task line is the reader's only context).
167
+ * Grapheme-safe — CJK, ZWJ emoji and combining sequences are never split.
168
+ */
169
+ export function formatTaskSummary(task: string, maxWidth: number = TASK_SUMMARY_MAX, keysOnly = true): string {
170
+ if (maxWidth <= 0) return "";
171
+ const oneLine = stripVTControlCharacters(task).replace(/\s+/g, " ").trim();
172
+ if (visibleWidth(oneLine) <= maxWidth) return oneLine;
173
+
174
+ const segments = [...graphemeSegmenter.segment(oneLine)].map((s) => s.segment);
175
+ const ellipsisWidth = visibleWidth(TASK_SUMMARY_ELLIPSIS);
176
+
177
+ if (keysOnly) {
178
+ const fragments = extractKeyFragments(oneLine);
179
+ if (fragments.length > 0) {
180
+ const keyMax = maxWidth - 1;
181
+ let keys = "";
182
+ for (const fragment of fragments) {
183
+ const piece = keys ? `${TASK_SUMMARY_KEY_SEP}${fragment}` : fragment;
184
+ const total = keys + piece;
185
+ if (visibleWidth(total) > keyMax) {
186
+ // Budget exhausted: keep what fits, unless nothing fits yet.
187
+ if (!keys) {
188
+ // A single over-long fragment keeps its tail
189
+ // (extension/symbol) and is prefixed with the ellipsis.
190
+ const fragmentSegments = [...graphemeSegmenter.segment(piece)].map((s) => s.segment);
191
+ keys = `${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(fragmentSegments, keyMax - ellipsisWidth)}`;
192
+ }
193
+ break;
194
+ }
195
+ keys = total;
196
+ }
197
+ return keys;
198
+ }
199
+ }
200
+
201
+ // No distinctive fragments (or prose mode): fall back to head…tail.
202
+ const tailMax = Math.max(
203
+ TASK_SUMMARY_TAIL_MIN,
204
+ Math.min(TASK_SUMMARY_TAIL_MAX, Math.round(maxWidth * TASK_SUMMARY_TAIL_SHARE)),
205
+ );
206
+ const headMax = maxWidth - ellipsisWidth - tailMax;
207
+ if (headMax <= 0) {
208
+ return `${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(segments, maxWidth - ellipsisWidth)}`;
209
+ }
210
+ return `${takeGraphemes(segments, headMax)}${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(segments, tailMax)}`;
211
+ }
212
+
213
+ /** Max display width of a run's content label. */
214
+ const RUN_LABEL_MAX = 32;
215
+
216
+ /**
217
+ * Short content label for a run, derived from its task: the single most
218
+ * distinguishing fragment so concurrent same-agent runs are told apart by WHAT
219
+ * they do, not just their run id. A file/directory path outranks other
220
+ * fragment kinds (a kebab-case word like "edge-case" never beats
221
+ * "src/config.ts"); a long path keeps its tail (the filename is the
222
+ * recognisable part); a task with no recognizable fragment falls back to a
223
+ * head slice of its prose. Grapheme-safe.
224
+ */
225
+ export function runLabel(task: string): string {
226
+ const oneLine = stripVTControlCharacters(task).replace(/\s+/g, " ").trim();
227
+ const fragments = extractKeyFragments(oneLine);
228
+ const fragment = fragments.find((candidate) => /[\\/]|\.[A-Za-z0-9]{1,5}$/.test(candidate)) ?? fragments[0];
229
+ const src = fragment ?? oneLine;
230
+ if (visibleWidth(src) <= RUN_LABEL_MAX) return src;
231
+ const chars = [...graphemeSegmenter.segment(src)].map((s) => s.segment);
232
+ // A path/symbol fragment keeps its tail (filename/symbol is recognisable);
233
+ // a prose fallback keeps its head.
234
+ return fragment
235
+ ? `${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(chars, RUN_LABEL_MAX - 1)}`
236
+ : `${takeGraphemes(chars, RUN_LABEL_MAX - 1)}${TASK_SUMMARY_ELLIPSIS}`;
237
+ }
238
+
239
+ /** Narrow an already-extracted run label to a smaller budget, keeping its
240
+ * tail: runLabel tail-weights path fragments because the filename is the
241
+ * recognisable part, and a second squeeze must not trade that tail away.
242
+ * Grapheme-safe. */
243
+ export function shrinkRunLabel(text: string, maxWidth: number): string {
244
+ if (maxWidth <= 0) return "";
245
+ if (visibleWidth(text) <= maxWidth) return text;
246
+ const chars = [...graphemeSegmenter.segment(text)].map((s) => s.segment);
247
+ return `${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(chars, maxWidth - 1)}`;
248
+ }
249
+
250
+ function formatTokens(count: number): string {
251
+ if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
252
+ if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`;
253
+ return String(count);
254
+ }
255
+
256
+ /** Token flow in the pi-footer vocabulary: ↑input ↓output, R cache-read,
257
+ * W cache-write; zero components are omitted. No cost — callers place it as
258
+ * its own droppable part. */
259
+ export function formatUsageTokens(usage: UsageStats | undefined): string | undefined {
260
+ if (!usage) return undefined;
261
+ const parts: string[] = [];
262
+ if (usage.input) parts.push(`↑${formatTokens(usage.input)}`);
263
+ if (usage.output) parts.push(`↓${formatTokens(usage.output)}`);
264
+ if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`);
265
+ if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`);
266
+ return parts.length > 0 ? parts.join(" ") : undefined;
267
+ }
268
+
269
+ export function formatUsageCompact(usage: UsageStats): string {
270
+ return [formatUsageTokens(usage), usageCostPart(usage)].filter(Boolean).join(" ");
271
+ }
272
+
273
+ /** Cost as its own droppable part: `$0.0421`, undefined when nothing accrued. */
274
+ function usageCostPart(usage: UsageStats | undefined): string | undefined {
275
+ return usage?.cost ? `$${usage.cost.toFixed(4)}` : undefined;
276
+ }
277
+
278
+ /** Aggregate usage across the runs of a completion group. */
279
+ export function sumUsage(parts: readonly UsageStats[]): UsageStats {
280
+ const total: UsageStats = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 };
281
+ for (const part of parts) {
282
+ total.input += part.input;
283
+ total.output += part.output;
284
+ total.cacheRead += part.cacheRead;
285
+ total.cacheWrite += part.cacheWrite;
286
+ total.cost += part.cost;
287
+ total.contextTokens += part.contextTokens;
288
+ total.turns += part.turns;
289
+ }
290
+ return total;
291
+ }
292
+
293
+ export function formatDuration(ms: number): string {
294
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
295
+ if (totalSeconds < 60) return `${totalSeconds}s`;
296
+ const minutes = Math.floor(totalSeconds / 60);
297
+ const seconds = totalSeconds % 60;
298
+ // Seconds stay visible at every magnitude: a long-running run is judged
299
+ // by whether it is still moving, and "5s ago" is exactly that signal.
300
+ if (minutes < 60) return `${minutes}m${String(seconds).padStart(2, "0")}s`;
301
+ const hours = Math.floor(minutes / 60);
302
+ return `${hours}h${String(minutes % 60).padStart(2, "0")}m${String(seconds).padStart(2, "0")}s`;
303
+ }
304
+
305
+ function elapsedMilliseconds(run: RunView, now: number = Date.now()): number {
306
+ let elapsed = run.elapsedMs ?? 0;
307
+ if (run.activeSince !== undefined) elapsed += Math.max(0, now - run.activeSince);
308
+ // Keep formatting tolerant of older/synthetic RunView values that predate
309
+ // segmented timing and carry only startedAt/endedAt.
310
+ if (elapsed === 0 && run.startedAt !== undefined && run.activeSince === undefined) {
311
+ elapsed = Math.max(0, (run.endedAt ?? now) - run.startedAt);
312
+ }
313
+ return elapsed;
314
+ }
315
+
316
+ export function formatElapsed(run: RunView, now: number = Date.now()): string {
317
+ if (run.startedAt === undefined && run.elapsedMs <= 0) return "";
318
+ return formatDuration(elapsedMilliseconds(run, now));
319
+ }
320
+
321
+ /** Max length of the argument target inside a formatted activity line. */
322
+ const ACTIVITY_TARGET_MAX = 60;
323
+
324
+ const REDACTED = "<redacted>";
325
+
326
+ /** Remove credentials embedded in otherwise ordinary activity strings such as
327
+ * shell commands and HTTP headers. */
328
+ function redactSensitiveText(value: string): string {
329
+ let text = stripVTControlCharacters(value);
330
+ text = text.replace(
331
+ /(\bauthorization\s*:\s*(?:bearer|basic)\s+)([^\s'"`;,]+)/giu,
332
+ `$1${REDACTED}`,
333
+ );
334
+ text = text.replace(
335
+ /(\bbearer\s+)([A-Za-z0-9._~+/=-]{6,})/giu,
336
+ `$1${REDACTED}`,
337
+ );
338
+ text = text.replace(
339
+ /(\b(?:api[-_]?key|apikey|access[-_]?token|refresh[-_]?token|token|password|passwd|secret|credential|cookie)\b\s*(?:=|:)\s*)(?:"[^"]*"|'[^']*'|[^\s;&,]+)/giu,
340
+ `$1${REDACTED}`,
341
+ );
342
+ text = text.replace(
343
+ /((?:--?(?:api[-_]?key|access[-_]?token|token|password|secret|credential))\s+)(?:"[^"]*"|'[^']*'|\S+)/giu,
344
+ `$1${REDACTED}`,
345
+ );
346
+ return text.replace(
347
+ /\b(?:sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9]{8,}|AKIA[A-Z0-9]{16})\b/gu,
348
+ REDACTED,
349
+ );
350
+ }
351
+
352
+ /** Monitor activity is returned to the parent model and rendered in the terminal,
353
+ * so treat every live string as untrusted before it reaches store state. */
354
+ function sanitizeActivityText(value: string): string {
355
+ return redactSensitiveText(value).replace(/\s+/g, " ").trim();
356
+ }
357
+
358
+ function shortTarget(value: unknown): string {
359
+ if (typeof value !== "string") return "";
360
+ const oneLine = sanitizeActivityText(value);
361
+ // Slice by code point so emoji / CJK-ext never leave a lone surrogate.
362
+ const chars = [...oneLine];
363
+ return chars.length > ACTIVITY_TARGET_MAX ? `${chars.slice(0, ACTIVITY_TARGET_MAX - 1).join("")}…` : oneLine;
364
+ }
365
+
366
+ /** A code-mode script's first meaningful line: the earliest line that is not
367
+ * blank and not a `//` comment, shortened like any other activity target. */
368
+ function scriptLine(value: unknown): string {
369
+ if (typeof value !== "string") return "";
370
+ const line = value
371
+ .split("\n")
372
+ .map((part) => part.trim())
373
+ .find((part) => part.length > 0 && !part.startsWith("//"));
374
+ return line ? shortTarget(line) : "";
375
+ }
376
+
377
+ /** Newest-last rolling window of what a run has been doing, surfaced to the
378
+ * parent model as a progress trail. */
379
+ const RECENT_ACTIVITY_MAX = 6;
380
+
381
+ /** Concise "what is it doing" text for a tool call: the tool name plus its single
382
+ * most telling argument (path, command, pattern, ...) — never a raw JSON blob. */
383
+ export function formatToolActivity(toolName: string, args: unknown): string {
384
+ const a = (typeof args === "object" && args !== null ? args : {}) as Record<string, unknown>;
385
+ const pick = (...keys: string[]): string => {
386
+ for (const key of keys) {
387
+ const s = shortTarget(a[key]);
388
+ if (s) return s;
389
+ }
390
+ return "";
391
+ };
392
+ let target: string;
393
+ switch (toolName) {
394
+ // Pi ships one shell tool per platform flavor, all with a `command`
395
+ // parameter: a Windows parent that swapped bash for powershell must still
396
+ // show the command it is running, not a bare tool name.
397
+ case "bash":
398
+ case "powershell":
399
+ case "shell":
400
+ target = pick("command");
401
+ break;
402
+ case "read":
403
+ case "edit":
404
+ case "write":
405
+ case "ls":
406
+ target = pick("path", "file", "filePath");
407
+ break;
408
+ case "grep":
409
+ case "find":
410
+ target = pick("pattern", "query", "path");
411
+ break;
412
+ case "codemode":
413
+ // A script is source, not a target: name its first meaningful line so the
414
+ // trail shows what the child is doing instead of a code blob.
415
+ target = scriptLine(a.code);
416
+ break;
417
+ case "subagent":
418
+ target = pick("agent", "task");
419
+ break;
420
+ default:
421
+ target = pick("path", "command", "query", "pattern", "url", "file", "task");
422
+ }
423
+ const safeToolName = sanitizeActivityText(toolName) || "tool";
424
+ return target ? `${safeToolName} ${target}` : safeToolName;
425
+ }
426
+
427
+ // ---------------------------------------------------------------------------
428
+ // MonitorStore
429
+ // ---------------------------------------------------------------------------
430
+
431
+ export class MonitorStore {
432
+ private runs: RunView[] = [];
433
+ private nextId = 1;
434
+ private subscribers = new Set<() => void>();
435
+
436
+ beginTurn(): void {
437
+ // Clear finished runs from a previous turn, but keep active and parked
438
+ // threads so concurrent work is not wiped between parent turns.
439
+ this.runs = this.runs.filter(
440
+ (r) => isRunActiveStatus(r.status) || r.status === "parked",
441
+ );
442
+ this.notify();
443
+ }
444
+
445
+ /** Reserve a stable id for a durable result that must remain independently
446
+ * addressable without appearing as a live monitor row. */
447
+ reserveRunId(): number {
448
+ return this.nextId++;
449
+ }
450
+
451
+ /** Keep newly allocated ids above a restored id so reload-restored threads
452
+ * never collide with runs started in the current process. */
453
+ ensureNextIdAbove(id: number): void {
454
+ if (id >= this.nextId) this.nextId = id + 1;
455
+ }
456
+
457
+ /** Re-register a durable thread restored from a previous process. The row
458
+ * keeps its stable id and historical elapsed time. */
459
+ restoreRun(view: Pick<RunView, "id" | "agent" | "task" | "status"> & Partial<RunView>): void {
460
+ if (this.find(view.id)) return;
461
+ this.runs.push({
462
+ label: runLabel(view.task),
463
+ usage: emptyUsage(),
464
+ elapsedMs: 0,
465
+ ...view,
466
+ });
467
+ this.ensureNextIdAbove(view.id);
468
+ this.notify();
469
+ }
470
+
471
+ addRun(agent: string, task: string, model?: string, thinking?: string, isolation?: IsolationMode): number {
472
+ const id = this.reserveRunId();
473
+ this.runs.push({
474
+ id,
475
+ agent,
476
+ task,
477
+ label: runLabel(task),
478
+ model,
479
+ thinking,
480
+ status: "queued",
481
+ usage: emptyUsage(),
482
+ elapsedMs: 0,
483
+ ...(isolation ? { isolation, integrationStatus: isolation === "worktree" ? "pending" : undefined } : {}),
484
+ });
485
+ this.notify();
486
+ return id;
487
+ }
488
+
489
+ setStatus(id: number, status: RunStatus): void {
490
+ const run = this.find(id);
491
+ if (!run) return;
492
+ const previousStatus = run.status;
493
+ const wasExecuting = previousStatus === "running" || previousStatus === "interrupting";
494
+ const isExecuting = status === "running" || status === "interrupting";
495
+ const now = Date.now();
496
+ run.status = status;
497
+ if (isExecuting && !wasExecuting) {
498
+ run.startedAt ??= now;
499
+ run.activeSince = now;
500
+ run.endedAt = undefined;
501
+ } else if (!isExecuting && wasExecuting && run.activeSince !== undefined) {
502
+ run.elapsedMs += Math.max(0, now - run.activeSince);
503
+ run.activeSince = undefined;
504
+ }
505
+ if ((status === "parked" || status === "done" || status === "failed") && run.endedAt === undefined) {
506
+ run.endedAt = now;
507
+ }
508
+ this.notify();
509
+ }
510
+ setUsage(id: number, usage: UsageStats, model?: string): void {
511
+ const run = this.find(id);
512
+ if (!run) return;
513
+ run.usage = { ...usage };
514
+ if (model) run.model = model;
515
+ this.notify();
516
+ }
517
+
518
+ /** Record the model of the current attempt. */
519
+ setModel(id: number, model?: string): void {
520
+ const run = this.find(id);
521
+ if (!run || !model) return;
522
+ run.model = model;
523
+ this.notify();
524
+ }
525
+
526
+ /** Record the capability-clamped thinking level for the active model. */
527
+ setThinking(id: number, thinking?: string): void {
528
+ const run = this.find(id);
529
+ if (!run || !thinking) return;
530
+ run.thinking = thinking;
531
+ this.notify();
532
+ }
533
+
534
+ /** Update the run's current one-line activity (what it is doing now). */
535
+ setActivity(id: number, text: string): void {
536
+ const run = this.find(id);
537
+ if (!run) return;
538
+ const safe = sanitizeActivityText(text) || undefined;
539
+ // Every streamed thinking/text delta reports the same activity; skip the
540
+ // notification (and the widget re-render it triggers) when nothing changed.
541
+ if (run.activity === safe) return;
542
+ run.activity = safe;
543
+ if (safe) this.pushRecentActivity(run, safe);
544
+ this.notify();
545
+ }
546
+
547
+ /** Record a tool starting and update the run's visible activity. */
548
+ recordToolStart(id: number, toolName: string, activity: string): void {
549
+ const run = this.find(id);
550
+ if (!run) return;
551
+ const safeToolName = sanitizeActivityText(toolName) || "tool";
552
+ const safeActivity = sanitizeActivityText(activity) || safeToolName;
553
+ run.activity = safeActivity;
554
+ this.pushRecentActivity(run, safeActivity);
555
+ this.notify();
556
+ }
557
+
558
+ /** Record a failed tool; successful completions keep their last activity
559
+ * until the next model event supplies a more useful description. */
560
+ recordToolEnd(id: number, toolName: string, isError: boolean): void {
561
+ const run = this.find(id);
562
+ if (!run) return;
563
+ if (isError) {
564
+ const failed = `✗ ${sanitizeActivityText(toolName) || "tool"} failed`;
565
+ run.activity = failed;
566
+ this.pushRecentActivity(run, failed);
567
+ }
568
+ this.notify();
569
+ }
570
+
571
+ setIsolation(
572
+ id: number,
573
+ isolation: IsolationMode,
574
+ integrationStatus?: RunIntegrationStatus,
575
+ worktreeId?: string,
576
+ ): void {
577
+ const run = this.find(id);
578
+ if (!run) return;
579
+ run.isolation = isolation;
580
+ run.integrationStatus = integrationStatus;
581
+ if (worktreeId) run.worktreeId = worktreeId;
582
+ this.notify();
583
+ }
584
+
585
+ getElapsedMs(id: number, now: number = Date.now()): number | undefined {
586
+ const run = this.find(id);
587
+ return run ? elapsedMilliseconds(run, now) : undefined;
588
+ }
589
+
590
+ /** Look up a run by id without removing it. */
591
+ findRun(id: number): RunView | undefined {
592
+ return this.find(id);
593
+ }
594
+
595
+ /** Remove all runs (used on session shutdown so stale state never leaks
596
+ * into the next session). Does not reset the id counter so in-flight
597
+ * finishRun calls from the old session remain safe no-ops. */
598
+ clear(): void {
599
+ this.runs = [];
600
+ this.notify();
601
+ }
602
+
603
+ /** Remove a run after publication. Returns the removed run. */
604
+ removeRun(id: number): RunView | undefined {
605
+ const index = this.runs.findIndex((r) => r.id === id);
606
+ if (index === -1) return undefined;
607
+ const [run] = this.runs.splice(index, 1);
608
+ this.notify();
609
+ return run;
610
+ }
611
+
612
+ getRuns(): RunView[] {
613
+ return this.runs;
614
+ }
615
+
616
+ subscribe(cb: () => void): () => void {
617
+ this.subscribers.add(cb);
618
+ return () => {
619
+ this.subscribers.delete(cb);
620
+ };
621
+ }
622
+
623
+ summarize(run: RunView): string {
624
+ const usage = formatUsageCompact(run.usage);
625
+ const parts = [run.agent];
626
+ if (run.model) parts.push(run.model);
627
+ if (run.thinking) parts.push(`thinking ${run.thinking}`);
628
+ if (run.isolation === "worktree") parts.push(`worktree ${run.integrationStatus ?? "active"}`);
629
+ if (usage) parts.push(usage);
630
+ const elapsed = formatElapsed(run);
631
+ if (elapsed) parts.push(elapsed);
632
+ return parts.join(" · ");
633
+ }
634
+
635
+ private find(id: number): RunView | undefined {
636
+ return this.runs.find((r) => r.id === id);
637
+ }
638
+
639
+ /** Newest-last rolling activity window; consecutive duplicates collapse. */
640
+ private pushRecentActivity(run: RunView, text: string): void {
641
+ const recent = run.recentActivity ?? [];
642
+ if (recent[recent.length - 1] !== text) recent.push(text);
643
+ if (recent.length > RECENT_ACTIVITY_MAX) recent.splice(0, recent.length - RECENT_ACTIVITY_MAX);
644
+ run.recentActivity = recent;
645
+ }
646
+
647
+ private notify(): void {
648
+ for (const cb of this.subscribers) {
649
+ try {
650
+ cb();
651
+ } catch {
652
+ /* subscriber errors must not break the store */
653
+ }
654
+ }
655
+ }
656
+ }
657
+
658
+ export const monitor = new MonitorStore();
659
+
660
+ // ---------------------------------------------------------------------------
661
+ // Status icons
662
+ // ---------------------------------------------------------------------------
663
+
664
+ export function statusIcon(status: RunStatus, theme: Theme): string {
665
+ switch (status) {
666
+ case "running":
667
+ return theme.fg("accent", "●");
668
+ case "interrupting":
669
+ return theme.fg("warning", "◐");
670
+ case "parked":
671
+ return theme.fg("dim", "■");
672
+ case "done":
673
+ return theme.fg("success", "✓");
674
+ case "failed":
675
+ return theme.fg("error", "✗");
676
+ default:
677
+ return theme.fg("dim", "○");
678
+ }
679
+ }
680
+
681
+ /** User-facing lifecycle label used by tool/status rendering. */
682
+ export function statusLabel(status: RunStatus): string {
683
+ switch (status) {
684
+ case "queued":
685
+ return "starting";
686
+ case "running":
687
+ return "running";
688
+ case "interrupting":
689
+ return "interrupting";
690
+ case "parked":
691
+ return "interrupted";
692
+ case "done":
693
+ return "done";
694
+ case "failed":
695
+ return "stopped";
696
+ }
697
+ }