@aoshizuku/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.
package/src/render.ts ADDED
@@ -0,0 +1,592 @@
1
+ // The `agent` tool card, drawn with renderShell: "self" (docs/07 §1).
2
+ //
3
+ // renderCall returns one long-lived component that draws the whole card from the row's shared renderer
4
+ // state at render time; renderResult only records the latest result there. That keeps the header and the
5
+ // progress lines in one block whose height does not jump while the agent runs.
6
+ //
7
+ // A background start's card follows the agent's record instead of its one tool result (docs/07 §1.4): it
8
+ // looks the record up through a CardLink at render time and is redrawn when the record ends.
9
+
10
+ import { readFileSync } from "node:fs";
11
+
12
+ import { getMarkdownTheme, type Theme, type ThemeColor, type ToolRenderers } from "@earendil-works/pi-coding-agent";
13
+ import { type Component, Markdown, truncateToWidth } from "@earendil-works/pi-tui";
14
+
15
+ import { type AgentRecord, isTerminal } from "./manager.js";
16
+ import { displayTokens, type ProgressSnapshot, type UsageTotals } from "./observer.js";
17
+ import { durationOf, formatDuration } from "./result.js";
18
+ import { type AgentStatus, SESSION_ENDED } from "./run.js";
19
+ import { clip } from "./tool-line.js";
20
+
21
+ export interface AgentToolDetails {
22
+ agentId: string;
23
+ type: string;
24
+ description: string;
25
+ status: AgentStatus;
26
+ reason?: string;
27
+ turns: number;
28
+ toolCalls: number;
29
+ durationMs: number;
30
+ usage: UsageTotals;
31
+ /** provider/id actually used. */
32
+ model: string;
33
+ maxTurns?: number;
34
+ sessionFile?: string;
35
+ resultFile?: string;
36
+ truncated: boolean;
37
+ /** Only in onUpdate partial results. */
38
+ progress?: ProgressSnapshot;
39
+ /** 1-based queue position while queued. */
40
+ queuePosition?: number;
41
+ /** A background start: the card shows one line that follows the agent's record (docs/07 §1.4). */
42
+ background?: boolean;
43
+ /** The record's run number when this card started it; a later agent_send run is not this card's. */
44
+ run?: number;
45
+ }
46
+
47
+ export interface AgentCallArgs {
48
+ description?: string;
49
+ prompt?: string;
50
+ agent_type?: string;
51
+ model?: string;
52
+ /** agent_send */
53
+ agent_id?: string;
54
+ message?: string;
55
+ }
56
+
57
+ interface CardResult {
58
+ content: Array<{ type: string; text?: string }>;
59
+ details?: AgentToolDetails;
60
+ isError: boolean;
61
+ partial: boolean;
62
+ }
63
+
64
+ interface CardState {
65
+ card?: AgentCard;
66
+ result?: CardResult;
67
+ /** Background card: the report read from the result file (the record's text is memory only). */
68
+ report?: string;
69
+ }
70
+
71
+ /** What a background card reads from the session's AgentManager. */
72
+ export interface CardSource {
73
+ get(agentId: string): AgentRecord | undefined;
74
+ /** How one run ended, kept per (agent, run) so a later agent_send run does not hide it. */
75
+ runOutcome(agentId: string, run: number): AgentRecord | undefined;
76
+ subscribe(listener: (record: AgentRecord) => void): () => void;
77
+ }
78
+
79
+ /**
80
+ * Connects background cards to the current session's manager (docs/07 §1.4). One per extension instance:
81
+ * session_start attaches the manager, session_shutdown detaches it, and a card asks for its record at render
82
+ * time. A card whose agent has not ended yet registers its row's invalidate here; the record entering a
83
+ * terminal state redraws those rows once. Progress redraws nothing: it is shown in the HUD.
84
+ */
85
+ export class CardLink {
86
+ private source: CardSource | undefined;
87
+ private unsubscribe: (() => void) | undefined;
88
+ /** toolCallId -> the card waiting for its agent to end. A rebuilt row replaces its tool call's entry. */
89
+ private readonly waiting = new Map<string, { agentId: string; invalidate: () => void }>();
90
+ private readonly statuses = new Map<string, AgentStatus>();
91
+
92
+ get attached(): boolean {
93
+ return this.source !== undefined;
94
+ }
95
+
96
+ attach(source: CardSource): void {
97
+ this.unsubscribe?.();
98
+ this.statuses.clear();
99
+ this.source = source;
100
+ this.unsubscribe = source.subscribe((record) => this.changed(record));
101
+ // Rows drawn before session_start (resume, /reload) can find their records now.
102
+ this.redraw(() => true);
103
+ }
104
+
105
+ /** Detach `source`; a no-op when a later session_start already attached another one. */
106
+ detach(source: CardSource): void {
107
+ if (this.source !== source) return;
108
+ this.unsubscribe?.();
109
+ this.unsubscribe = undefined;
110
+ this.source = undefined;
111
+ this.statuses.clear();
112
+ }
113
+
114
+ get(agentId: string): AgentRecord | undefined {
115
+ return this.source?.get(agentId);
116
+ }
117
+
118
+ runOutcome(agentId: string, run: number): AgentRecord | undefined {
119
+ return this.source?.runOutcome(agentId, run);
120
+ }
121
+
122
+ wait(toolCallId: string, agentId: string, invalidate: () => void): void {
123
+ this.waiting.set(toolCallId, { agentId, invalidate });
124
+ }
125
+
126
+ forget(toolCallId: string): void {
127
+ this.waiting.delete(toolCallId);
128
+ }
129
+
130
+ private changed(record: AgentRecord): void {
131
+ const before = this.statuses.get(record.agentId);
132
+ this.statuses.set(record.agentId, record.status);
133
+ if (before === record.status || !isTerminal(record.status)) return;
134
+ this.redraw((agentId) => agentId === record.agentId);
135
+ }
136
+
137
+ /** Drops the matching entries and invalidates their rows; a row whose agent still runs registers again. */
138
+ private redraw(matches: (agentId: string) => boolean): void {
139
+ for (const [toolCallId, entry] of [...this.waiting]) {
140
+ if (!matches(entry.agentId)) continue;
141
+ this.waiting.delete(toolCallId);
142
+ try {
143
+ entry.invalidate();
144
+ } catch {
145
+ // A row that is gone must not break the run that ended.
146
+ }
147
+ }
148
+ }
149
+ }
150
+
151
+ type RenderCall = NonNullable<ToolRenderers["renderCall"]>;
152
+ type RenderResult = NonNullable<ToolRenderers["renderResult"]>;
153
+
154
+ const EMPTY: Component = { render: () => [], invalidate: () => {} };
155
+ const PROMPT_PREVIEW_LINES = 6;
156
+ const REPORT_PREVIEW_LINES = 40;
157
+ const LABEL_MAX = 60;
158
+
159
+ const ICONS: Record<AgentStatus, string> = {
160
+ queued: "●",
161
+ running: "●",
162
+ completed: "✓",
163
+ failed: "✗",
164
+ aborted: "■",
165
+ max_turns: "↻",
166
+ context_limit: "◔",
167
+ };
168
+
169
+ const ICON_COLORS: Record<AgentStatus, "accent" | "warning" | "success" | "error" | "dim" | "muted"> = {
170
+ queued: "muted",
171
+ running: "accent",
172
+ completed: "success",
173
+ failed: "error",
174
+ aborted: "warning",
175
+ max_turns: "warning",
176
+ context_limit: "warning",
177
+ };
178
+
179
+ export function formatTokens(tokens: number): string {
180
+ if (tokens < 1000) return `${tokens} tok`;
181
+ if (tokens < 1_000_000) return `${(tokens / 1000).toFixed(1)}K tok`;
182
+ return `${(tokens / 1_000_000).toFixed(1)}M tok`;
183
+ }
184
+
185
+ export function formatCost(cost: number): string {
186
+ return `$${cost < 1 ? cost.toFixed(3) : cost.toFixed(2)}`;
187
+ }
188
+
189
+ /** description, or the first line of the prompt cut to 60 columns. */
190
+ export function callLabel(args: AgentCallArgs): string {
191
+ const description = args.description?.replace(/\s+/g, " ").trim();
192
+ if (description) return description;
193
+ const firstLine = (args.prompt ?? "").trim().split(/\r?\n/)[0] ?? "";
194
+ return clip(firstLine, LABEL_MAX);
195
+ }
196
+
197
+ /** Gutter convention (pi-shizuku README.md): markers sit in column 0, so rows ignore pi's outputPad. */
198
+ const MARKER_COLUMN = 0;
199
+
200
+ export class AgentCard implements Component {
201
+ args: AgentCallArgs = {};
202
+ theme: Theme | undefined;
203
+ expanded = false;
204
+ /** Left padding shared with pi's other tool rows, so the icon lines up with them. */
205
+ pad = 0;
206
+ /** Where a background card finds its agent's record; undefined draws the start result as is. */
207
+ link: CardLink | undefined;
208
+
209
+ constructor(private readonly state: CardState) {}
210
+
211
+ render(width: number): string[] {
212
+ const theme = this.theme;
213
+ if (!theme || width <= 0) return [];
214
+ const pad = " ".repeat(this.pad);
215
+ const lines = this.lines(theme, Math.max(1, width - this.pad));
216
+ return lines.map((line) => truncateToWidth(pad + line, width));
217
+ }
218
+
219
+ invalidate(): void {
220
+ // Everything is derived from the shared state at render time.
221
+ }
222
+
223
+ private lines(theme: Theme, width: number): string[] {
224
+ const result = this.state.result;
225
+ const details = result?.details;
226
+ const followUp = this.args.agent_id !== undefined;
227
+ const typeName = details?.type ?? this.args.agent_type?.trim() ?? (followUp ? "" : "general");
228
+ const label = details?.description ?? (followUp ? `${this.args.agent_id ?? ""} ← ${clip(firstLine(this.args.message ?? ""), LABEL_MAX)}` : callLabel(this.args));
229
+ const head: Head = (status, extra, faded = false) => {
230
+ // Faded: the whole line in one dim run, extras passed uncolored.
231
+ const fg = faded ? (_color: ThemeColor, text: string) => text : (color: ThemeColor, text: string) => theme.fg(color, text);
232
+ const icon = status === "error" ? fg("error", "✗") : fg(ICON_COLORS[status], ICONS[status]);
233
+ const model = this.args.model?.trim() ? [this.args.model.trim()] : [];
234
+ const parts = [fg("accent", typeName), label, ...(followUp ? [fg("dim", "follow-up")] : []), ...model, ...extra];
235
+ const title = faded ? "Agent" : theme.bold(theme.fg("toolTitle", "Agent"));
236
+ const line = `${icon} ${title} ${parts.filter(Boolean).join(fg("dim", " · "))}`;
237
+ return faded ? theme.fg("dim", line) : line;
238
+ };
239
+
240
+ if (!result) return [head("running", [])];
241
+ const message = result.content.find((part) => part.type === "text")?.text ?? "";
242
+ if (!details) {
243
+ // Thrown before the agent was created (unknown type, invalid model...), or a follow-up that was
244
+ // only queued for a running agent.
245
+ if (result.isError) return [head("error", [theme.fg("error", firstLine(message) || "failed")])];
246
+ return [head("queued", [theme.fg("dim", firstLine(message))])];
247
+ }
248
+ if (details.background && !result.partial) return this.backgroundLines(theme, details, head, width);
249
+ if (result.partial) return this.runningLines(theme, details, head);
250
+ return this.finishedLines(theme, details, resultBody(result), head, width);
251
+ }
252
+
253
+ /** docs/07 §1.4: the start result while the agent runs, then the record's outcome. */
254
+ private backgroundLines(theme: Theme, details: AgentToolDetails, head: Head, width: number): string[] {
255
+ const startLine = (status: AgentStatus, faded = false): string => {
256
+ const where = status === "queued" ? `queued in background${details.queuePosition ? ` (${details.queuePosition})` : ""}` : "running in background";
257
+ const text = `${details.agentId} ${where}`;
258
+ return head(status, [faded ? text : theme.fg("dim", text)], faded);
259
+ };
260
+ const started: AgentStatus = details.status === "queued" ? "queued" : "running";
261
+ if (!this.link) return [startLine(started)];
262
+ const record = backgroundRecord(details, this.link);
263
+ // The record is gone (cleaned up, or not restored yet) or belongs to a later agent_send run.
264
+ if (!record) return [startLine(started, true)];
265
+ if (!isTerminal(record.status)) return [startLine(record.status)];
266
+ const current = recordDetails(record, details);
267
+ const duration = formatDuration(current.durationMs);
268
+ switch (record.status) {
269
+ case "failed":
270
+ return [head("failed", [theme.fg("error", "failed"), theme.fg("dim", clip(record.reason ?? "unknown error", 60)), theme.fg("dim", duration)])];
271
+ case "aborted":
272
+ return [head("aborted", [theme.fg("dim", record.reason === SESSION_ENDED ? "stopped · session ended" : `stopped after ${duration}`)])];
273
+ default:
274
+ return this.finishedLines(theme, current, this.expanded ? backgroundReport(this.state, record) : "", head, width);
275
+ }
276
+ }
277
+
278
+ private runningLines(theme: Theme, details: AgentToolDetails, head: Head): string[] {
279
+ if (details.status === "queued") {
280
+ return [head("queued", [theme.fg("muted", `queued${details.queuePosition ? ` (${details.queuePosition})` : ""}`)])];
281
+ }
282
+ const progress = details.progress;
283
+ const first = head("running", [theme.fg("dim", formatDuration(details.durationMs))]);
284
+ let activity: string;
285
+ if (progress && progress.activeTools.length > 0) {
286
+ activity = progress.activeTools
287
+ .slice(-2)
288
+ .map((tool) => tool.line)
289
+ .join(theme.fg("dim", " · "));
290
+ } else {
291
+ const recent = progress?.recentText.trim().split(/\r?\n/).filter(Boolean).at(-1) ?? "";
292
+ activity = theme.fg("dim", recent || "thinking…");
293
+ }
294
+ const tools = progress?.toolCalls ?? details.toolCalls;
295
+ const turn = (progress?.turns ?? details.turns) + 1;
296
+ const tokens = formatTokens(displayTokens(progress?.usage ?? details.usage));
297
+ const stats = theme.fg("dim", `${tools} tool${tools === 1 ? "" : "s"} · turn ${turn} · ${tokens}`);
298
+ return [first, ` ${theme.fg("dim", "├")} ${activity}`, ` ${theme.fg("dim", "└")} ${stats}`];
299
+ }
300
+
301
+ private finishedLines(
302
+ theme: Theme,
303
+ details: AgentToolDetails,
304
+ report: string,
305
+ head: Head,
306
+ width: number,
307
+ ): string[] {
308
+ const extra: string[] = [];
309
+ switch (details.status) {
310
+ case "completed":
311
+ extra.push(theme.fg("dim", `${details.toolCalls} tool${details.toolCalls === 1 ? "" : "s"}`));
312
+ extra.push(theme.fg("dim", formatTokens(displayTokens(details.usage))));
313
+ break;
314
+ case "failed":
315
+ extra.push(theme.fg("error", `failed: ${clip(details.reason ?? "unknown error", 60)}`));
316
+ break;
317
+ case "aborted":
318
+ extra.push(theme.fg("dim", "stopped"));
319
+ break;
320
+ case "max_turns":
321
+ extra.push(theme.fg("warning", `out of turns${details.maxTurns ? ` (${details.maxTurns})` : ""}`));
322
+ break;
323
+ case "context_limit":
324
+ extra.push(theme.fg("warning", "context full"));
325
+ break;
326
+ default:
327
+ break;
328
+ }
329
+ extra.push(theme.fg("dim", formatDuration(details.durationMs)));
330
+ const first = `${head(details.status, extra)} ${theme.fg("dim", this.expanded ? "▾" : "▸")}`;
331
+ if (!this.expanded) return [first];
332
+
333
+ const bar = theme.fg("dim", "│");
334
+ const lines = [first];
335
+ const meta = [details.agentId, details.model, `${details.turns} turn${details.turns === 1 ? "" : "s"}`];
336
+ if (details.usage.cost > 0) meta.push(formatCost(details.usage.cost));
337
+ lines.push(` ${theme.fg("dim", meta.join(" · "))}`);
338
+
339
+ lines.push(` ${theme.fg("dim", this.args.agent_id !== undefined ? "┌ follow-up" : "┌ prompt")}`);
340
+ const promptLines = (this.args.prompt ?? this.args.message ?? "").replace(/\r\n?/g, "\n").trim().split("\n");
341
+ for (const line of promptLines.slice(0, PROMPT_PREVIEW_LINES)) lines.push(` ${bar} ${line}`);
342
+ if (promptLines.length > PROMPT_PREVIEW_LINES) {
343
+ lines.push(` ${bar} ${theme.fg("dim", `… ${promptLines.length - PROMPT_PREVIEW_LINES} more lines`)}`);
344
+ }
345
+
346
+ lines.push(` ${theme.fg("dim", "├ report")}`);
347
+ const body = reportLines(report, width - 4);
348
+ for (const line of body.slice(0, REPORT_PREVIEW_LINES)) lines.push(` ${bar} ${line}`);
349
+ if (body.length > REPORT_PREVIEW_LINES) {
350
+ const more = `… ${body.length - REPORT_PREVIEW_LINES} more lines${details.resultFile ? ` · ${details.resultFile}` : ""}`;
351
+ lines.push(` ${bar} ${theme.fg("dim", more)}`);
352
+ }
353
+ const tail = details.sessionFile ? `transcript: ${details.sessionFile}` : details.resultFile ? `report: ${details.resultFile}` : "";
354
+ lines.push(` ${theme.fg("dim", `└ ${tail}`)}`);
355
+ return lines;
356
+ }
357
+ }
358
+
359
+ /** The card's first line; `faded` draws it as one dim run (a background card without its record). */
360
+ type Head = (status: AgentStatus | "error", extra: string[], faded?: boolean) => string;
361
+
362
+ function firstLine(text: string): string {
363
+ return text.trim().split(/\r?\n/)[0] ?? "";
364
+ }
365
+
366
+ /**
367
+ * The record of the run a background card started: the live record while that run is going, then the manager's
368
+ * outcome snapshot of that run, so a later agent_send run does not repaint it. A start result without a run
369
+ * number (stored before runs were tracked) follows the latest record. Undefined when the session has no such
370
+ * run (cleaned up, or not restored yet).
371
+ */
372
+ function backgroundRecord(details: AgentToolDetails, link: CardLink): AgentRecord | undefined {
373
+ const record = link.get(details.agentId);
374
+ if (details.run === undefined) return record;
375
+ if (record && record.runs === details.run && !isTerminal(record.status)) return record;
376
+ return link.runOutcome(details.agentId, details.run) ?? (record?.runs === details.run ? record : undefined);
377
+ }
378
+
379
+ /** The card's details rebuilt from its agent's record (docs/07 §1.4). */
380
+ function recordDetails(record: AgentRecord, start: AgentToolDetails): AgentToolDetails {
381
+ return {
382
+ ...start,
383
+ status: record.status,
384
+ reason: record.reason,
385
+ turns: record.stats.turns,
386
+ toolCalls: record.stats.toolCalls,
387
+ durationMs: durationOf(record),
388
+ usage: { ...record.stats.usage },
389
+ model: record.model,
390
+ maxTurns: record.maxTurns ?? start.maxTurns,
391
+ sessionFile: record.sessionFile,
392
+ resultFile: record.resultFile,
393
+ progress: undefined,
394
+ queuePosition: undefined,
395
+ };
396
+ }
397
+
398
+ /** The report of an ended background run: the record's text, or its result file after a restart (read once). */
399
+ function backgroundReport(state: CardState, record: AgentRecord): string {
400
+ if (record.text) return record.text;
401
+ if (state.report === undefined) {
402
+ try {
403
+ state.report = record.resultFile ? readFileSync(record.resultFile, "utf8") : "";
404
+ } catch {
405
+ state.report = "";
406
+ }
407
+ }
408
+ return state.report;
409
+ }
410
+
411
+ /** details of a <subagent-notification> custom message; drives its one-line-per-agent rendering (docs/07 §2). */
412
+ export interface NotificationDetails {
413
+ agents: Array<{
414
+ agentId: string;
415
+ type: string;
416
+ description: string;
417
+ status: AgentStatus;
418
+ reason?: string;
419
+ toolCalls: number;
420
+ durationMs: number;
421
+ resultFile?: string;
422
+ /** First lines of the report, shown when expanded. */
423
+ preview: string[];
424
+ }>;
425
+ }
426
+
427
+ export const NOTIFICATION_PREVIEW_LINES = 20;
428
+
429
+ export function notificationLines(details: NotificationDetails | undefined, expanded: boolean, theme: Theme): string[] {
430
+ const lines: string[] = [];
431
+ for (const agent of details?.agents ?? []) {
432
+ const color = ICON_COLORS[agent.status];
433
+ const tools = `${agent.toolCalls} tool${agent.toolCalls === 1 ? "" : "s"}`;
434
+ let state: string;
435
+ switch (agent.status) {
436
+ case "completed":
437
+ state = `${theme.fg(color, "completed")}${theme.fg("dim", ` · ${tools}`)}`;
438
+ break;
439
+ case "failed":
440
+ state = `${theme.fg(color, "failed")}${theme.fg("dim", ` · ${clip(agent.reason ?? "unknown error", 60)}`)}`;
441
+ break;
442
+ case "max_turns":
443
+ state = theme.fg(color, "out of turns");
444
+ break;
445
+ case "context_limit":
446
+ state = theme.fg(color, "context full");
447
+ break;
448
+ case "aborted":
449
+ state = theme.fg(color, "stopped");
450
+ break;
451
+ default:
452
+ state = theme.fg(color, agent.status);
453
+ }
454
+ lines.push(
455
+ `${theme.fg(color, "●")} ${theme.fg("accent", agent.agentId)} ${theme.fg("accent", agent.type)} ${agent.description} ${state}${theme.fg("dim", ` · ${formatDuration(agent.durationMs)}`)}`,
456
+ );
457
+ if (!expanded) continue;
458
+ for (const line of agent.preview.slice(0, NOTIFICATION_PREVIEW_LINES)) lines.push(` ${theme.fg("dim", "│")} ${line}`);
459
+ if (agent.resultFile) lines.push(` ${theme.fg("dim", `└ ${agent.resultFile}`)}`);
460
+ }
461
+ return lines;
462
+ }
463
+
464
+ /** The text inside <subagent-result>…</subagent-result>. */
465
+ export function resultBody(result: Pick<CardResult, "content">): string {
466
+ const text = result.content
467
+ .filter((part) => part.type === "text")
468
+ .map((part) => part.text ?? "")
469
+ .join("\n");
470
+ const open = text.indexOf(">\n");
471
+ const close = text.lastIndexOf("\n</subagent-result>");
472
+ if (!text.startsWith("<subagent-result") || open === -1 || close <= open) return text;
473
+ return text.slice(open + 2, close);
474
+ }
475
+
476
+ function reportLines(text: string, width: number): string[] {
477
+ try {
478
+ return new Markdown(text, 0, 0, getMarkdownTheme()).render(Math.max(20, width)).map((line) => line.trimEnd());
479
+ } catch {
480
+ // No initialized theme (tests, non-TUI); plain text is fine there.
481
+ return text.split("\n");
482
+ }
483
+ }
484
+
485
+ /**
486
+ * renderCall / renderResult for `agent` and `agent_send`. With a link, background cards follow their agent's
487
+ * record (docs/07 §1.4); without one they draw the start result as is.
488
+ */
489
+ export function agentCardRenderers(link?: CardLink): { renderCall: RenderCall; renderResult: RenderResult } {
490
+ const renderCall: RenderCall = (args, theme, context) => {
491
+ const state = context.state as CardState;
492
+ const card = state.card ?? new AgentCard(state);
493
+ state.card = card;
494
+ card.args = (args ?? {}) as AgentCallArgs;
495
+ card.theme = theme;
496
+ card.expanded = context.expanded;
497
+ card.pad = MARKER_COLUMN;
498
+ card.link = link;
499
+ return card;
500
+ };
501
+
502
+ const renderResult: RenderResult = (result, options, theme, context) => {
503
+ const state = context.state as CardState;
504
+ // pi stores a thrown tool error as `details: {}`, not undefined; only a result that names its agent
505
+ // carries our details, anything else is drawn as a plain error or queued message.
506
+ const raw = result.details as Partial<AgentToolDetails> | undefined;
507
+ const details = raw?.agentId ? (raw as AgentToolDetails) : undefined;
508
+ state.result = {
509
+ content: result.content as CardResult["content"],
510
+ details,
511
+ isError: context.isError,
512
+ partial: options.isPartial,
513
+ };
514
+ if (state.card) {
515
+ state.card.theme = theme;
516
+ state.card.expanded = options.expanded;
517
+ state.card.pad = MARKER_COLUMN;
518
+ }
519
+ if (link && details?.background && !options.isPartial) {
520
+ // Wait for the end while the record runs, or until session_start attaches a manager to look in.
521
+ const record = backgroundRecord(details, link);
522
+ const settled = record ? isTerminal(record.status) : link.attached;
523
+ if (settled) link.forget(context.toolCallId);
524
+ else link.wait(context.toolCallId, details.agentId, context.invalidate);
525
+ }
526
+ return EMPTY;
527
+ };
528
+
529
+ return { renderCall, renderResult };
530
+ }
531
+
532
+ const unlinked = agentCardRenderers();
533
+ export const renderAgentCall: RenderCall = unlinked.renderCall;
534
+ export const renderAgentResult: RenderResult = unlinked.renderResult;
535
+
536
+ interface StopState {
537
+ row?: StopRow;
538
+ result?: { line: string; isError: boolean };
539
+ }
540
+
541
+ /**
542
+ * The `agent_stop` row: `{pad}● Agent Stop (ag-1) · Stopped subagent ag-1 (…) after 1m02s.` A successful stop is
543
+ * dim as a whole: the stopped agent's own card (red ■) carries the outcome (docs/07 §1.4).
544
+ */
545
+ export class StopRow implements Component {
546
+ agentId = "";
547
+ theme: Theme | undefined;
548
+ pad = 0;
549
+
550
+ constructor(private readonly state: StopState) {}
551
+
552
+ render(width: number): string[] {
553
+ const theme = this.theme;
554
+ if (!theme || width <= 0) return [];
555
+ const result = this.state.result;
556
+ const pad = " ".repeat(this.pad);
557
+ if (result && !result.isError) {
558
+ const detail = this.agentId ? ` (${this.agentId})` : "";
559
+ const summary = result.line ? ` · ${result.line}` : "";
560
+ return [truncateToWidth(`${pad}${theme.fg("dim", `● Agent Stop${detail}${summary}`)}`, width, "…")];
561
+ }
562
+ const marker = result ? theme.fg("error", "×") : theme.fg("accent", "●");
563
+ const detail = this.agentId ? ` ${theme.fg("muted", `(${this.agentId})`)}` : "";
564
+ const summary = result?.line ? theme.fg("error", ` · ${result.line}`) : "";
565
+ return [truncateToWidth(`${pad}${marker} ${theme.fg("toolTitle", theme.bold("Agent Stop"))}${detail}${summary}`, width, "…")];
566
+ }
567
+
568
+ invalidate(): void {
569
+ // Everything is derived from the shared state at render time.
570
+ }
571
+ }
572
+
573
+ export const renderStopCall: RenderCall = (args, theme, context) => {
574
+ const state = context.state as StopState;
575
+ const row = state.row ?? new StopRow(state);
576
+ state.row = row;
577
+ row.agentId = ((args as { agent_id?: string } | undefined)?.agent_id ?? "").trim();
578
+ row.theme = theme;
579
+ row.pad = MARKER_COLUMN;
580
+ return row;
581
+ };
582
+
583
+ export const renderStopResult: RenderResult = (result, _options, theme, context) => {
584
+ const state = context.state as StopState;
585
+ const first = result.content.find((part) => part.type === "text");
586
+ state.result = { line: firstLine(first?.type === "text" ? first.text : ""), isError: context.isError };
587
+ if (state.row) {
588
+ state.row.theme = theme;
589
+ state.row.pad = MARKER_COLUMN;
590
+ }
591
+ return EMPTY;
592
+ };