@ferris1225/pi-subagents 6.0.2 → 6.0.4

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