@lune_99/pi-subagent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +169 -2
  4. package/docs/capture.json +30 -0
  5. package/docs/previews.md +22 -0
  6. package/docs/reference.md +240 -0
  7. package/docs/subagent-auto-tiers.png +0 -0
  8. package/docs/subagent-inspector.png +0 -0
  9. package/docs/subagent-overview.png +0 -0
  10. package/package.json +82 -5
  11. package/skills/create-lune-subagent/SKILL.md +186 -0
  12. package/src/auto-model.ts +592 -0
  13. package/src/catalog.ts +111 -0
  14. package/src/definition-file.ts +112 -0
  15. package/src/definitions.ts +324 -0
  16. package/src/dock/dock-alert.ts +78 -0
  17. package/src/dock/dock-contribution.ts +318 -0
  18. package/src/extension-tools.ts +46 -0
  19. package/src/index.ts +168 -0
  20. package/src/inspector/details.ts +113 -0
  21. package/src/inspector/inspector.ts +653 -0
  22. package/src/inspector/layout.ts +119 -0
  23. package/src/inspector/transcript.ts +735 -0
  24. package/src/inspector/viewport.ts +62 -0
  25. package/src/inspector/wrap.ts +136 -0
  26. package/src/models.ts +54 -0
  27. package/src/notify/notification-box.ts +381 -0
  28. package/src/notify/notifier.ts +569 -0
  29. package/src/paths.ts +34 -0
  30. package/src/render/lune-theme.ts +68 -0
  31. package/src/render/text.ts +121 -0
  32. package/src/run/guide.ts +26 -0
  33. package/src/run/report-tool.ts +90 -0
  34. package/src/run/run-file.ts +193 -0
  35. package/src/run/run-manager.ts +838 -0
  36. package/src/run/run-session.ts +307 -0
  37. package/src/run/run.ts +681 -0
  38. package/src/run/session-start.ts +283 -0
  39. package/src/run/types.ts +167 -0
  40. package/src/run/worktree.ts +138 -0
  41. package/src/schema.ts +9 -0
  42. package/src/settings/agents-menu.ts +363 -0
  43. package/src/settings/panel.ts +179 -0
  44. package/src/settings/schema.ts +71 -0
  45. package/src/tools/format.ts +375 -0
  46. package/src/tools/subagent-tools.ts +467 -0
@@ -0,0 +1,735 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { AssistantMessage, ToolCall } from "@earendil-works/pi-ai";
3
+ import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
4
+ import { visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
5
+
6
+ import { reportColor } from "../notify/notification-box.ts";
7
+ import type { LuneActivityStatus } from "../render/lune-theme.ts";
8
+ import { displayLine, displayLines } from "../render/text.ts";
9
+ import { isUserMessage, stripUserMarker } from "../run/guide.ts";
10
+ import { REPORT_TOOL_NAME } from "../run/report-tool.ts";
11
+ import type { Run, RunningTool } from "../run/run.ts";
12
+ import { AUTO_TIERS, type AutoModelChoice, type AutoRisk, type RunSnapshot } from "../run/types.ts";
13
+ import { formatDuration, formatPercent, ratingText } from "../tools/format.ts";
14
+ import { pad } from "./layout.ts";
15
+ import { headRows, LineWrapCache, tailRows } from "./wrap.ts";
16
+
17
+ /** Rows of a failed call's error, a running call's output or a streamed thought; it is a log, not a pager. */
18
+ const EXCERPT_ROWS = 3;
19
+ const INDENT = " ";
20
+ const COLUMN_GAP = " ";
21
+
22
+ type ToolResult = Extract<AgentMessage, { role: "toolResult" }>;
23
+
24
+ /**
25
+ * The rows of a run's settled messages, the ones that can no longer change.
26
+ *
27
+ * A run's session only appends, so a later transcript that still holds `last` at `count - 1` only
28
+ * adds messages, and the rows grow by theirs.
29
+ */
30
+ interface SettledRows {
31
+ runId: string;
32
+ width: number;
33
+ count: number;
34
+ last: AgentMessage | undefined;
35
+ rows: string[];
36
+ /** Results of every message read so far; a result never comes before its call. */
37
+ results: Map<string, ToolResult>;
38
+ read: number;
39
+ }
40
+
41
+ /**
42
+ * Draws a run's messages for the inspector's right pane with the parent's theme.
43
+ *
44
+ * It renders on its own: Pi's tool renderers read a module-global theme that an extension cannot
45
+ * rely on. Settled messages are drawn once per width; only the live tail (the streamed message, the
46
+ * last assistant message while its tools run, and a retry notice) is drawn again on each frame.
47
+ */
48
+ export class TranscriptRenderer {
49
+ private readonly theme: Theme;
50
+ private readonly wraps = new LineWrapCache();
51
+ private blocks = new WeakMap<object, { width: number; rows: string[] }>();
52
+ private settled: SettledRows | undefined;
53
+
54
+ constructor(theme: Theme) {
55
+ this.theme = theme;
56
+ }
57
+
58
+ render(run: Run, width: number): readonly string[] {
59
+ const messages = run.transcript();
60
+ const settled = this.settledRows(run, messages, width);
61
+ const streamed =
62
+ run.streaming && !messages.includes(run.streaming) ? run.streaming : undefined;
63
+ const lastAssistant =
64
+ streamed ?? messages.findLast((message) => message.role === "assistant");
65
+ const tail: string[] = [];
66
+ const add = (rows: readonly string[]): void => {
67
+ if (rows.length === 0) {
68
+ return;
69
+ }
70
+
71
+ if (settled.rows.length + tail.length > 0) {
72
+ tail.push("");
73
+ }
74
+
75
+ append(tail, rows);
76
+ };
77
+ const context = (message: AgentMessage): BlockContext => ({
78
+ run,
79
+ width,
80
+ results: settled.results,
81
+ pending: run.state === "running" && message === lastAssistant,
82
+ live: message === run.streaming,
83
+ });
84
+
85
+ for (let index = settled.count; index < messages.length; index++) {
86
+ add(this.buildBlock(messages[index]!, context(messages[index]!)));
87
+ }
88
+
89
+ if (streamed) {
90
+ add(this.buildBlock(streamed, context(streamed)));
91
+ }
92
+
93
+ if (run.activity) {
94
+ add(this.wrap(run.activity, width, "warning"));
95
+ }
96
+
97
+ return tail.length === 0 ? settled.rows : [...settled.rows, ...tail];
98
+ }
99
+
100
+ /** Forget every drawn row, for example after the theme changed. */
101
+ clear(): void {
102
+ this.blocks = new WeakMap();
103
+ this.settled = undefined;
104
+ this.wraps.clear();
105
+ }
106
+
107
+ private settledRows(run: Run, messages: readonly AgentMessage[], width: number): SettledRows {
108
+ let settled = this.settled;
109
+
110
+ if (
111
+ !settled ||
112
+ settled.runId !== run.id ||
113
+ settled.width !== width ||
114
+ settled.read > messages.length ||
115
+ (settled.count > 0 && messages[settled.count - 1] !== settled.last)
116
+ ) {
117
+ settled = {
118
+ runId: run.id,
119
+ width,
120
+ count: 0,
121
+ last: undefined,
122
+ // The snapshot never changes, so the auto choice is drawn with the settled rows.
123
+ rows: this.autoRows(run, width),
124
+ results: new Map(),
125
+ read: 0,
126
+ };
127
+ this.settled = settled;
128
+ }
129
+
130
+ for (; settled.read < messages.length; settled.read++) {
131
+ const message = messages[settled.read]!;
132
+
133
+ if (message.role === "toolResult") {
134
+ settled.results.set(message.toolCallId, message);
135
+ }
136
+ }
137
+
138
+ const count = settledCount(run, messages, settled.results);
139
+
140
+ for (; settled.count < count; settled.count++) {
141
+ const message = messages[settled.count]!;
142
+ const rows = this.block(message, {
143
+ run,
144
+ width,
145
+ results: settled.results,
146
+ pending: false,
147
+ live: false,
148
+ });
149
+
150
+ if (rows.length > 0) {
151
+ if (settled.rows.length > 0) {
152
+ settled.rows.push("");
153
+ }
154
+
155
+ append(settled.rows, rows);
156
+ }
157
+
158
+ settled.last = message;
159
+ }
160
+
161
+ return settled;
162
+ }
163
+
164
+ /**
165
+ * How `model: auto` resolved the run, above its first message: the classifier's share for
166
+ * each task tier, highest first, the tier and model the run got, and the thinking rating.
167
+ * The model row keeps only the short mark.
168
+ */
169
+ private autoRows(run: Run, width: number): string[] {
170
+ const snapshot = run.snapshot;
171
+ const auto = snapshot?.autoModel;
172
+
173
+ switch (auto?.by) {
174
+ case undefined:
175
+ return [];
176
+ case "no-classifier":
177
+ return this.wrap(
178
+ "No auto classifier is selected, so the run uses the main agent's model.",
179
+ width,
180
+ "muted",
181
+ );
182
+ case "nothing-to-rate":
183
+ return this.wrap(
184
+ "No auto tier has a model and the thinking is set, so no classifier ran and " +
185
+ "the run uses the main agent's model.",
186
+ width,
187
+ "muted",
188
+ );
189
+ case "classifier-failed":
190
+ return this.wrap(
191
+ `${auto.error} The run uses the main agent's model` +
192
+ (snapshot!.sources.thinking === "parent" ? " and thinking." : "."),
193
+ width,
194
+ "warning",
195
+ );
196
+ case "rating":
197
+ return this.ratingRows(auto, snapshot!, width);
198
+ default:
199
+ // A run that an earlier version started records its auto choice in another form.
200
+ return [];
201
+ }
202
+ }
203
+
204
+ /** Aligned tier rows, or one wrapped entry per tier when the columns do not fit. */
205
+ private ratingRows(
206
+ auto: Extract<AutoModelChoice, { by: "rating" }>,
207
+ snapshot: RunSnapshot,
208
+ width: number,
209
+ ): string[] {
210
+ const { tier, thinking, risk } = auto;
211
+ const model =
212
+ snapshot.model +
213
+ (auto.modelFrom === tier.used
214
+ ? ""
215
+ : auto.modelFrom === "main"
216
+ ? " (main agent's model)"
217
+ : ` (${auto.modelFrom} tier)`);
218
+ // The sort is stable, so equal or missing shares keep the tier order.
219
+ const ranked = AUTO_TIERS.map((level) => ({
220
+ level,
221
+ share: tier.probabilities[level],
222
+ })).sort((a, b) => (b.share ?? -1) - (a.share ?? -1));
223
+ const shares = ranked.some(({ share }) => share !== undefined);
224
+ const levelWidth = Math.max(...AUTO_TIERS.map((level) => level.length));
225
+ const entries = ranked.map(({ level, share }) => ({
226
+ level,
227
+ percent: share === undefined ? "" : formatPercent(share),
228
+ chosen: level === tier.used,
229
+ rated: level === tier.rated && tier.rated !== tier.used,
230
+ }));
231
+ const aligned = entries.map(({ level, percent, chosen, rated }) => {
232
+ const columns =
233
+ pad(level, levelWidth) + (shares ? COLUMN_GAP + percent.padStart(4) : "");
234
+ const mark = chosen
235
+ ? COLUMN_GAP +
236
+ this.theme.fg("accent", "chosen") +
237
+ this.theme.fg("text", ` → ${model}`)
238
+ : rated
239
+ ? COLUMN_GAP + this.theme.fg("muted", "rated")
240
+ : "";
241
+
242
+ // The columns are padded only for a mark after them, so no row ends in spaces.
243
+ return (
244
+ INDENT +
245
+ this.theme.fg(chosen ? "text" : "muted", mark ? columns : columns.trimEnd()) +
246
+ mark
247
+ );
248
+ });
249
+ const rows = aligned.every((row) => visibleWidth(row) <= width)
250
+ ? aligned
251
+ : entries.flatMap(({ level, percent, chosen, rated }) =>
252
+ this.indented(
253
+ [level, percent, chosen ? `chosen → ${model}` : rated ? "rated" : ""]
254
+ .filter(Boolean)
255
+ .join(" · "),
256
+ width,
257
+ chosen ? "text" : "muted",
258
+ ),
259
+ );
260
+ const unsure =
261
+ tier.used === tier.rated
262
+ ? ""
263
+ : ` It was unsure (${formatPercent(tier.confidence)} confidence), so the run ` +
264
+ `uses the ${tier.used} tier.`;
265
+
266
+ return [
267
+ ...this.wrap(
268
+ `${auto.classifier} rated the task ${tier.rated}.${unsure}`,
269
+ width,
270
+ "muted",
271
+ ),
272
+ ...rows,
273
+ // A run that an earlier version started has no thinking or risk rating here.
274
+ ...(risk ? this.wrap(riskLine(risk), width, risk.high ? "warning" : "muted") : []),
275
+ ...(thinking ? this.wrap(`Thinking: ${ratingText(thinking)}`, width, "muted") : []),
276
+ ];
277
+ }
278
+
279
+ /** A settled message's rows, kept per message so switching back to a run redraws nothing. */
280
+ private block(message: AgentMessage, context: BlockContext): string[] {
281
+ const cached = this.blocks.get(message);
282
+
283
+ if (cached?.width === context.width) {
284
+ return cached.rows;
285
+ }
286
+
287
+ const rows = this.buildBlock(message, context);
288
+
289
+ this.blocks.set(message, { width: context.width, rows });
290
+
291
+ return rows;
292
+ }
293
+
294
+ private buildBlock(message: AgentMessage, context: BlockContext): string[] {
295
+ const { width } = context;
296
+
297
+ switch (message.role) {
298
+ case "user": {
299
+ const text =
300
+ typeof message.content === "string"
301
+ ? message.content
302
+ : message.content
303
+ .map((part) => (part.type === "text" ? part.text : "[image]"))
304
+ .join("\n");
305
+ const fromUser = isUserMessage(text);
306
+
307
+ return [
308
+ this.theme.bold(
309
+ this.theme.fg(
310
+ fromUser ? "accent" : "mdHeading",
311
+ fromUser ? "› User" : "› Main agent",
312
+ ),
313
+ ),
314
+ ...this.wrap(stripUserMarker(text), width, "userMessageText"),
315
+ ];
316
+ }
317
+ case "assistant":
318
+ return this.assistantRows(message, context);
319
+ case "toolResult":
320
+ // Drawn with the call that asked for it.
321
+ return [];
322
+ case "compactionSummary":
323
+ return [this.theme.fg("muted", "Context compacted")];
324
+ case "branchSummary":
325
+ return [this.theme.fg("muted", "Branch summary")];
326
+ case "bashExecution":
327
+ return [
328
+ ...wrapTextWithAnsi(
329
+ this.theme.fg("toolTitle", `$ ${clip(message.command)}`),
330
+ width,
331
+ ),
332
+ ...this.excerpt(message.output, width, "toolOutput", "head"),
333
+ ];
334
+ case "custom":
335
+ return message.display
336
+ ? this.wrap(
337
+ typeof message.content === "string"
338
+ ? message.content
339
+ : message.content
340
+ .map((part) => (part.type === "text" ? part.text : ""))
341
+ .join("\n"),
342
+ width,
343
+ "customMessageText",
344
+ )
345
+ : [];
346
+ default:
347
+ return [];
348
+ }
349
+ }
350
+
351
+ private assistantRows(message: AssistantMessage, context: BlockContext): string[] {
352
+ const rows: string[] = [];
353
+ let group: ToolCall[] = [];
354
+ const flushGroup = (): void => {
355
+ if (group.length > 0) {
356
+ append(rows, this.toolGroup(group, context));
357
+ group = [];
358
+ }
359
+ };
360
+
361
+ for (const [index, part] of message.content.entries()) {
362
+ if (part.type === "toolCall") {
363
+ group.push(part);
364
+ continue;
365
+ }
366
+
367
+ flushGroup();
368
+
369
+ if (part.type === "thinking") {
370
+ append(
371
+ rows,
372
+ this.thinkingRows(
373
+ part.redacted ? undefined : part.thinking,
374
+ context.width,
375
+ context.live && index === message.content.length - 1,
376
+ ),
377
+ );
378
+ } else if (part.text.trim() !== "") {
379
+ append(rows, this.wrap(part.text, context.width, "text"));
380
+ }
381
+ }
382
+
383
+ flushGroup();
384
+
385
+ if (message.stopReason === "error") {
386
+ append(
387
+ rows,
388
+ this.wrap(
389
+ `Error: ${message.errorMessage ?? "The model request failed."}`,
390
+ context.width,
391
+ "error",
392
+ ),
393
+ );
394
+ } else if (message.stopReason === "aborted") {
395
+ rows.push(this.theme.fg("muted", "Stopped"));
396
+ }
397
+
398
+ return rows;
399
+ }
400
+
401
+ /** One `Thinking · 12 lines` row; a thought still streaming also shows its newest rows. */
402
+ private thinkingRows(
403
+ thinking: string | undefined,
404
+ width: number,
405
+ streaming: boolean,
406
+ ): string[] {
407
+ const label = (text: string): string =>
408
+ this.theme.italic(this.theme.fg("thinkingText", text));
409
+
410
+ if (thinking === undefined) {
411
+ return [label("Thinking redacted")];
412
+ }
413
+
414
+ const text = thinking.replace(/\s+$/, "");
415
+
416
+ if (text === "") {
417
+ return streaming ? [label("Thinking")] : [];
418
+ }
419
+
420
+ const lines = displayLines(text);
421
+ const rows = [label(`Thinking · ${lines.length} ${lines.length === 1 ? "line" : "lines"}`)];
422
+
423
+ if (streaming) {
424
+ const shown = tailRows(lines, Math.max(1, width - INDENT.length), EXCERPT_ROWS).rows;
425
+
426
+ append(
427
+ rows,
428
+ shown.map((row) => INDENT + label(row)),
429
+ );
430
+ }
431
+
432
+ return rows;
433
+ }
434
+
435
+ private toolGroup(calls: readonly ToolCall[], context: BlockContext): string[] {
436
+ const rows: string[] = [];
437
+
438
+ for (const call of calls) {
439
+ if (call.name !== REPORT_TOOL_NAME) {
440
+ append(rows, this.toolRows(call, context));
441
+ }
442
+ }
443
+
444
+ for (const call of calls) {
445
+ if (call.name === REPORT_TOOL_NAME) {
446
+ append(rows, this.reportRows(call, context));
447
+ }
448
+ }
449
+
450
+ return rows;
451
+ }
452
+
453
+ /**
454
+ * `● read src/a.ts · 0.2s`. A finished call shows no output; a failed call shows the start of
455
+ * its error and a running call the end of its output.
456
+ */
457
+ private toolRows(call: ToolCall, context: BlockContext): string[] {
458
+ const result = context.results.get(call.id);
459
+ const running = context.run.runningTools.get(call.id);
460
+ const status = callStatus(result, running, context.pending);
461
+ const [color, icon] = STATUS_STYLE[status];
462
+ const diff = diffOf(result);
463
+ const meta = [
464
+ diff ? this.diffStat(diff) : undefined,
465
+ status === "cancelled" ? this.theme.fg("dim", "not finished") : undefined,
466
+ result?.durationMs !== undefined
467
+ ? this.theme.fg("dim", formatDuration(result.durationMs))
468
+ : running
469
+ ? this.theme.fg("dim", formatDuration(Date.now() - running.startedAt))
470
+ : undefined,
471
+ ].filter((part) => part !== undefined);
472
+ const separator = this.theme.fg("dim", " · ");
473
+ const head =
474
+ `${this.theme.fg(color, icon)} ${this.theme.bold(this.theme.fg("toolTitle", call.name))} ` +
475
+ this.theme.fg("muted", toolSummary(call)) +
476
+ (meta.length > 0 ? separator + meta.join(separator) : "");
477
+ const rows = wrapTextWithAnsi(head, context.width);
478
+
479
+ if (call.argumentsError) {
480
+ append(rows, this.excerpt(call.argumentsError, context.width, "error", "head"));
481
+ }
482
+
483
+ if (result?.isError) {
484
+ append(rows, this.excerpt(resultText(result), context.width, "error", "head"));
485
+ } else if (!result && running?.partialResult !== undefined) {
486
+ append(
487
+ rows,
488
+ this.excerpt(
489
+ partialText(running.partialResult),
490
+ context.width,
491
+ "toolOutput",
492
+ "tail",
493
+ ),
494
+ );
495
+ }
496
+
497
+ return rows;
498
+ }
499
+
500
+ /**
501
+ * `Report done`. The arguments stream before the call runs, and the main agent gets the report
502
+ * only when the turn ends, so until the call has a result its status is muted and marked.
503
+ */
504
+ private reportRows(call: ToolCall, context: BlockContext): string[] {
505
+ const args = call.arguments as Record<string, unknown>;
506
+ const status = typeof args.status === "string" ? displayLine(args.status) : "report";
507
+ const result = context.results.get(call.id);
508
+ const progress = callStatus(result, context.run.runningTools.get(call.id), context.pending);
509
+ const draft = progress === "running" || progress === "cancelled";
510
+ const mark =
511
+ progress === "running"
512
+ ? this.theme.fg("warning", "writing")
513
+ : progress === "cancelled"
514
+ ? this.theme.fg("muted", "not sent")
515
+ : undefined;
516
+ const rows = [
517
+ `${this.theme.bold(this.theme.fg("toolTitle", "Report"))} ` +
518
+ this.theme.fg(draft ? "muted" : reportColor(status), status) +
519
+ (mark ? this.theme.fg("dim", " · ") + mark : ""),
520
+ ];
521
+
522
+ if (result?.isError) {
523
+ append(rows, this.excerpt(resultText(result), context.width, "error", "head"));
524
+ }
525
+
526
+ if (typeof args.reason === "string" && args.reason.trim() !== "") {
527
+ append(rows, this.indented(`Reason: ${args.reason}`, context.width, "error"));
528
+ }
529
+
530
+ if (typeof args.question === "string" && args.question.trim() !== "") {
531
+ append(rows, this.indented(`Question: ${args.question}`, context.width, "accent"));
532
+ }
533
+
534
+ if (typeof args.summary === "string") {
535
+ append(rows, this.indented(args.summary, context.width, draft ? "muted" : "text"));
536
+ }
537
+
538
+ return rows;
539
+ }
540
+
541
+ /** `+12 −3`: the lines a diff adds and removes. */
542
+ private diffStat(diff: string): string {
543
+ let added = 0;
544
+ let removed = 0;
545
+
546
+ for (const line of diff.split("\n")) {
547
+ if (line.startsWith("+")) {
548
+ added += 1;
549
+ } else if (line.startsWith("-")) {
550
+ removed += 1;
551
+ }
552
+ }
553
+
554
+ return `${this.theme.fg("toolDiffAdded", `+${added}`)} ${this.theme.fg("toolDiffRemoved", `−${removed}`)}`;
555
+ }
556
+
557
+ private wrap(text: string, width: number, color: ThemeColor): string[] {
558
+ const rows: string[] = [];
559
+
560
+ for (const line of displayLines(text.replace(/\s+$/, ""))) {
561
+ for (const row of this.wraps.rows(line, Math.max(1, width))) {
562
+ rows.push(this.theme.fg(color, row));
563
+ }
564
+ }
565
+
566
+ return rows;
567
+ }
568
+
569
+ private indented(text: string, width: number, color: ThemeColor): string[] {
570
+ return this.wrap(text, width - INDENT.length, color).map((row) => INDENT + row);
571
+ }
572
+
573
+ /** The first or the last few rows of a text, with a note of how many lines are left out. */
574
+ private excerpt(
575
+ text: string,
576
+ width: number,
577
+ color: ThemeColor,
578
+ from: "head" | "tail",
579
+ ): string[] {
580
+ const trimmed = text.replace(/\s+$/, "");
581
+
582
+ if (trimmed === "") {
583
+ return [];
584
+ }
585
+
586
+ const lines = displayLines(trimmed);
587
+ const inner = Math.max(1, width - INDENT.length);
588
+ const { rows, hidden } =
589
+ from === "head"
590
+ ? headRows(lines, inner, EXCERPT_ROWS)
591
+ : tailRows(lines, inner, EXCERPT_ROWS);
592
+ const shown = rows.map((row) => INDENT + this.theme.fg(color, row));
593
+
594
+ if (hidden === 0) {
595
+ return shown;
596
+ }
597
+
598
+ const note =
599
+ INDENT +
600
+ this.theme.fg(
601
+ "muted",
602
+ `… ${hidden} ${from === "tail" ? "earlier" : "more"} ${hidden === 1 ? "line" : "lines"}`,
603
+ );
604
+
605
+ return from === "tail" ? [note, ...shown] : [...shown, note];
606
+ }
607
+ }
608
+
609
+ interface BlockContext {
610
+ run: Run;
611
+ width: number;
612
+ results: ReadonlyMap<string, ToolResult>;
613
+ /** The run is still working on this message's tool calls. */
614
+ pending: boolean;
615
+ /** The message is still streaming. */
616
+ live: boolean;
617
+ }
618
+
619
+ const STATUS_STYLE: Record<LuneActivityStatus, [ThemeColor, string]> = {
620
+ running: ["warning", "◐"],
621
+ done: ["success", "●"],
622
+ failed: ["error", "✕"],
623
+ cancelled: ["muted", "○"],
624
+ };
625
+
626
+ /**
627
+ * How many messages from the start can no longer change. Only the last assistant message can: its
628
+ * calls still wait for results, which also covers the streamed message once it is saved.
629
+ */
630
+ function settledCount(
631
+ run: Run,
632
+ messages: readonly AgentMessage[],
633
+ results: ReadonlyMap<string, ToolResult>,
634
+ ): number {
635
+ const streamed = run.streaming ? messages.indexOf(run.streaming) : -1;
636
+
637
+ if (streamed !== -1) {
638
+ return streamed;
639
+ }
640
+
641
+ const last = messages.findLastIndex((message) => message.role === "assistant");
642
+ const message = messages[last];
643
+
644
+ if (
645
+ message?.role === "assistant" &&
646
+ message.content.some((part) => part.type === "toolCall" && !results.has(part.id))
647
+ ) {
648
+ return last;
649
+ }
650
+
651
+ return messages.length;
652
+ }
653
+
654
+ function callStatus(
655
+ result: ToolResult | undefined,
656
+ running: RunningTool | undefined,
657
+ pending: boolean,
658
+ ): LuneActivityStatus {
659
+ if (result) {
660
+ return result.isError ? "failed" : "done";
661
+ }
662
+
663
+ return running || pending ? "running" : "cancelled";
664
+ }
665
+
666
+ /** Appends without spreading, which overflows the call stack for a very long text. */
667
+ function append(target: string[], rows: readonly string[]): void {
668
+ for (const row of rows) {
669
+ target.push(row);
670
+ }
671
+ }
672
+
673
+ /** The words that identify a call: its command, path or pattern, else its arguments as JSON. */
674
+ export function toolSummary(call: ToolCall): string {
675
+ const args = call.arguments as Record<string, unknown>;
676
+
677
+ for (const key of [
678
+ "command",
679
+ "path",
680
+ "file_path",
681
+ "pattern",
682
+ "query",
683
+ "url",
684
+ "runId",
685
+ "task",
686
+ ]) {
687
+ const value = args[key];
688
+
689
+ if (typeof value === "string" && value.trim() !== "") {
690
+ return clip(value);
691
+ }
692
+ }
693
+
694
+ return clip(JSON.stringify(args) ?? "");
695
+ }
696
+
697
+ function clip(text: string): string {
698
+ const line = displayLine(text);
699
+
700
+ return visibleWidth(line) > 80 ? `${line.slice(0, 79)}…` : line;
701
+ }
702
+
703
+ function resultText(result: ToolResult): string {
704
+ return result.content.map((part) => (part.type === "text" ? part.text : "[image]")).join("\n");
705
+ }
706
+
707
+ function partialText(partial: unknown): string {
708
+ const content = (partial as { content?: unknown } | undefined)?.content;
709
+
710
+ if (!Array.isArray(content)) {
711
+ return "";
712
+ }
713
+
714
+ return content
715
+ .map((part: { type?: unknown; text?: unknown }) =>
716
+ part.type === "text" && typeof part.text === "string" ? part.text : "",
717
+ )
718
+ .join("\n");
719
+ }
720
+
721
+ function diffOf(result: ToolResult | undefined): string | undefined {
722
+ const diff = (result?.details as { diff?: unknown } | undefined)?.diff;
723
+
724
+ return typeof diff === "string" && diff.trim() !== "" ? diff : undefined;
725
+ }
726
+
727
+ /** The high-risk answer, with the threshold it was judged at and the floor it set. */
728
+ function riskLine(risk: AutoRisk): string {
729
+ const shares = `${formatPercent(risk.probability)}, threshold ${formatPercent(risk.threshold)}`;
730
+
731
+ return risk.high
732
+ ? `High risk (${shares})` +
733
+ (risk.floor ? `, so the model comes from at least the ${risk.floor} tier.` : ".")
734
+ : `Not high risk (${shares}).`;
735
+ }