@xzzpig/pi-subagents 0.24.0 → 0.24.2

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 (36) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/bundle/{chunk-UFNSLL5D.js → chunk-224WMDIV.js} +86 -10
  3. package/bundle/{chunk-7K3Z6DM7.js → chunk-4UH4WS4G.js} +4 -4
  4. package/bundle/{chunk-KD2IMFN4.js → chunk-BQ2OAB4Q.js} +1 -1
  5. package/bundle/{chunk-F3NSN7UH.js → chunk-CYY5UMJU.js} +9 -4
  6. package/bundle/{chunk-LPVUHUZ7.js → chunk-EUPJB4S7.js} +1 -1
  7. package/bundle/{chunk-T65XRVVM.js → chunk-FG6SQJAR.js} +2 -2
  8. package/bundle/{chunk-MYCL5QEJ.js → chunk-JEA2ZKUA.js} +2 -2
  9. package/bundle/{chunk-RK2HDPLK.js → chunk-LVWU2HOO.js} +1 -1
  10. package/bundle/{chunk-OTLRAB22.js → chunk-O4D5PBVI.js} +3 -3
  11. package/bundle/{chunk-NCWCVJLT.js → chunk-RU522D5W.js} +4 -4
  12. package/bundle/{chunk-3G4JXNZ4.js → chunk-TMHVDPYW.js} +2 -0
  13. package/bundle/{chunk-NTRJDXBC.js → chunk-X6LOM3Z4.js} +2 -2
  14. package/bundle/{chunk-OFGSZBHP.js → chunk-XWWUDWUW.js} +14 -6
  15. package/bundle/index.js +1 -1
  16. package/docs/goal-auto-continuation-gate.md +26 -0
  17. package/node_modules/@xzzpig/pi-components/CHANGELOG.md +12 -0
  18. package/node_modules/@xzzpig/pi-components/README.md +94 -0
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.d.ts +186 -0
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.js +693 -0
  21. package/node_modules/@xzzpig/pi-components/package.json +5 -1
  22. package/package.json +3 -3
  23. package/src/extension/index.js +12 -0
  24. package/src/goal-auto-continue-gate.d.ts +17 -0
  25. package/src/goal-auto-continue-gate.js +61 -0
  26. package/src/goal-auto-continue-state.d.ts +22 -0
  27. package/src/goal-auto-continue-state.js +20 -0
  28. package/src/runs/background/async-execution.d.ts +3 -1
  29. package/src/runs/background/async-execution.js +4 -0
  30. package/src/runs/background/async-job-tracker.js +5 -0
  31. package/src/runs/background/async-status.d.ts +2 -0
  32. package/src/runs/background/async-status.js +2 -0
  33. package/src/runs/background/notify.d.ts +2 -0
  34. package/src/runs/background/notify.js +5 -0
  35. package/src/runs/foreground/subagent-executor.js +4 -0
  36. package/src/shared/types.d.ts +2 -0
@@ -0,0 +1,693 @@
1
+ import { AssistantMessageComponent, getMarkdownTheme, ToolExecutionComponent, UserMessageComponent, } from "@earendil-works/pi-coding-agent";
2
+ import { Container, MouseRegion, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui";
3
+ import { ensureTranscriptTheme, safeTerminalText, } from "./transcript.js";
4
+ const DETACHED_TUI = { requestRender() { } };
5
+ const ESC_SEQUENCE = String.fromCharCode(27);
6
+ const BEL_SEQUENCE = String.fromCharCode(7);
7
+ const OSC_133_SEQUENCE = new RegExp(`${ESC_SEQUENCE}]133;[ABC]${BEL_SEQUENCE}`, "g");
8
+ /** Embedded overlays must not leak Pi's shell-integration zone markers. */
9
+ function stripOsc133(lines) {
10
+ return lines.map((line) => line.replace(OSC_133_SEQUENCE, ""));
11
+ }
12
+ /**
13
+ * A click on the native thinking-block affordance. Pi's thinking `MouseRegion`
14
+ * only inspects type/button; coordinates are irrelevant. The presenter uses
15
+ * this through the public `MouseRegion.handleMouse` path so a unified toggle
16
+ * sets the same per-block override a real click would set.
17
+ */
18
+ const THINKING_CLICK_EVENT = {
19
+ type: "click",
20
+ button: "left",
21
+ x: 0,
22
+ y: 0,
23
+ screenX: 0,
24
+ screenY: 0,
25
+ width: 1,
26
+ height: 1,
27
+ shift: false,
28
+ alt: false,
29
+ ctrl: false,
30
+ clickCount: 1,
31
+ };
32
+ /**
33
+ * Collects the public mouse regions Pi's assistant renderer wraps around
34
+ * thinking blocks. Only public `Container.children` is walked (the assistant
35
+ * component's content container and its direct children), so deeper nested
36
+ * regions such as future link affordances are not clicked. The private content
37
+ * container field and region callbacks are never read. `MouseRegion` is a
38
+ * pi-tui peer export, so the host and this package share the same class.
39
+ */
40
+ function collectThinkingMouseRegions(component) {
41
+ const regions = [];
42
+ for (const child of component.children) {
43
+ if (child instanceof MouseRegion) {
44
+ regions.push(child);
45
+ continue;
46
+ }
47
+ if (!(child instanceof Container))
48
+ continue;
49
+ for (const nested of child.children) {
50
+ if (nested instanceof MouseRegion)
51
+ regions.push(nested);
52
+ }
53
+ }
54
+ return regions;
55
+ }
56
+ /**
57
+ * Mirrors the segmentation used by `renderTranscriptLines`: a turn is not a
58
+ * message, and a tool call or a repeated content kind starts a new assistant
59
+ * segment. Each segment carries the entry ids that produced it so the
60
+ * presenter can keep one native component per message across updates.
61
+ */
62
+ function buildPresenterBlocks(entries) {
63
+ const blocks = [];
64
+ let pendingAssistant;
65
+ const latestResults = new Map();
66
+ const finishedTurns = new Set();
67
+ for (const entry of entries) {
68
+ if (entry.type === "tool-result")
69
+ latestResults.set(entry.toolCallId, entry);
70
+ if (entry.type === "turn-boundary" && entry.phase === "end")
71
+ finishedTurns.add(entry.turnId);
72
+ }
73
+ const flushAssistant = () => {
74
+ if (!pendingAssistant)
75
+ return;
76
+ blocks.push(pendingAssistant);
77
+ pendingAssistant = undefined;
78
+ };
79
+ const appendAssistantText = (entry) => {
80
+ const text = safeTerminalText(entry.text);
81
+ if (!text)
82
+ return;
83
+ const field = entry.type === "thinking" ? "thinking" : "text";
84
+ if (pendingAssistant?.[field])
85
+ flushAssistant();
86
+ if (!pendingAssistant) {
87
+ pendingAssistant = {
88
+ kind: "assistant",
89
+ segmentId: entry.id,
90
+ entryIds: [],
91
+ thinking: "",
92
+ text: "",
93
+ streaming: false,
94
+ };
95
+ }
96
+ pendingAssistant[field] = text;
97
+ pendingAssistant.entryIds.push(entry.id);
98
+ pendingAssistant.streaming =
99
+ pendingAssistant.streaming ||
100
+ (entry.streaming && !finishedTurns.has(entry.turnId));
101
+ };
102
+ for (const entry of entries) {
103
+ switch (entry.type) {
104
+ case "turn-boundary":
105
+ flushAssistant();
106
+ if (entry.phase === "start" && blocks.length > 0)
107
+ blocks.push({ kind: "separator" });
108
+ break;
109
+ case "user-message":
110
+ flushAssistant();
111
+ blocks.push({
112
+ kind: "user",
113
+ entryId: entry.id,
114
+ text: safeTerminalText(entry.text),
115
+ });
116
+ break;
117
+ case "thinking":
118
+ case "assistant-text":
119
+ appendAssistantText(entry);
120
+ break;
121
+ case "tool-call": {
122
+ flushAssistant();
123
+ const result = latestResults.get(entry.toolCallId);
124
+ blocks.push({
125
+ kind: "tool",
126
+ entryId: entry.id,
127
+ toolCallId: entry.toolCallId,
128
+ toolName: entry.toolName,
129
+ args: entry.args,
130
+ result: result?.result ?? null,
131
+ isError: result?.isError ?? false,
132
+ streaming: (result?.streaming ?? false) && !finishedTurns.has(entry.turnId),
133
+ });
134
+ break;
135
+ }
136
+ case "tool-result":
137
+ break;
138
+ case "notice":
139
+ flushAssistant();
140
+ blocks.push({
141
+ kind: "notice",
142
+ entryId: entry.id,
143
+ text: safeTerminalText(entry.text),
144
+ tone: entry.tone,
145
+ });
146
+ break;
147
+ default:
148
+ break;
149
+ }
150
+ }
151
+ flushAssistant();
152
+ return blocks;
153
+ }
154
+ function blockIdentity(block) {
155
+ switch (block.kind) {
156
+ case "separator":
157
+ return "separator";
158
+ case "user":
159
+ return `user:${block.entryId}`;
160
+ case "assistant":
161
+ return `assistant:${block.segmentId}`;
162
+ case "tool":
163
+ return `tool:${block.toolCallId}:${block.toolName}`;
164
+ case "notice":
165
+ return `notice:${block.entryId}:${block.tone}:${block.text}`;
166
+ }
167
+ }
168
+ function createAssistantMessage(thinking, text) {
169
+ const content = [
170
+ ...(thinking ? [{ type: "thinking", thinking }] : []),
171
+ ...(text ? [{ type: "text", text }] : []),
172
+ ];
173
+ // Pi's renderer reads only role/content. A transcript segment can combine
174
+ // streamed updates that have no single provider response.
175
+ return { role: "assistant", content };
176
+ }
177
+ function noticeToneColor(tone) {
178
+ switch (tone) {
179
+ case "error":
180
+ return "error";
181
+ case "warning":
182
+ return "warning";
183
+ default:
184
+ return "dim";
185
+ }
186
+ }
187
+ function toComponentResult(value, isError) {
188
+ const payload = value && typeof value === "object"
189
+ ? value
190
+ : {};
191
+ const content = Array.isArray(payload.content)
192
+ ? payload.content.map((part) => ({
193
+ type: part?.type ?? "text",
194
+ text: part?.text,
195
+ data: part?.data,
196
+ mimeType: part?.mimeType,
197
+ }))
198
+ : [];
199
+ return { content, details: payload.details, isError };
200
+ }
201
+ /**
202
+ * Stateless fallback for tool blocks rendered without a live registry. The
203
+ * component is rebuilt per frame, so callers that need persistent tool
204
+ * expansion state should pass `toolComponents`.
205
+ */
206
+ function createAdHocToolComponent(block, options) {
207
+ const component = new ToolExecutionComponent(block.toolName, block.toolCallId, block.args ?? {}, {
208
+ showImages: options.showImages,
209
+ imageWidthCells: options.imageWidthCells,
210
+ }, options.resolveToolDefinition?.(block.toolName), DETACHED_TUI, options.cwd ?? process.cwd());
211
+ component.setArgsComplete();
212
+ component.markExecutionStarted();
213
+ if (block.result) {
214
+ component.updateResult(toComponentResult(block.result, block.isError), block.streaming);
215
+ }
216
+ return component;
217
+ }
218
+ /**
219
+ * Opt-in stateful transcript presenter.
220
+ *
221
+ * It consumes the same `TranscriptEntry` values as `renderTranscriptLines`,
222
+ * but keeps one native `UserMessageComponent` per user entry and one native
223
+ * `AssistantMessageComponent` per assistant message segment. Assistant
224
+ * components are constructed empty and receive content through
225
+ * `updateContent(message, streaming)`, so a host-side thinking-collapse patch
226
+ * observes the real streaming state instead of an already-finished message.
227
+ *
228
+ * The presenter owns its display revision: entry changes, thinking toggles,
229
+ * theme invalidation, width changes, and component-initiated repaint requests
230
+ * all raise it. `render` reuses its line cache only while that revision and
231
+ * the width are unchanged; content is never re-assigned on a pure repaint or
232
+ * resize.
233
+ *
234
+ * Mouse handling is normalized: pass a `TuiMouseEvent` whose `y` is a row in
235
+ * the full transcript (visible row + scroll offset). The presenter maps it to
236
+ * the owning component and forwards it through the component's public
237
+ * `handleMouse`, so Pi's native thinking-block and tool-expansion click paths
238
+ * keep working without private fields.
239
+ */
240
+ export class TranscriptPresenter {
241
+ options;
242
+ assistantComponents = new Map();
243
+ assistantContent = new Map();
244
+ userComponents = new Map();
245
+ userText = new Map();
246
+ toolState = new Map();
247
+ blocks = [];
248
+ blockIdentities = [];
249
+ rows = [];
250
+ renderedToolComponents = new Map();
251
+ cachedFrame = null;
252
+ renderedWidth = 0;
253
+ renderedRevision = -1;
254
+ revisionValue = 0;
255
+ thinkingPreference;
256
+ expandedSegments = new Set();
257
+ attachedTui;
258
+ disposed = false;
259
+ constructor(options) {
260
+ ensureTranscriptTheme();
261
+ this.options = options;
262
+ this.thinkingPreference =
263
+ options.hideThinkingBlock === true ? "hidden" : "auto";
264
+ this.attachedTui = options.tui ?? null;
265
+ }
266
+ /** Latest display revision. */
267
+ get revision() {
268
+ return this.revisionValue;
269
+ }
270
+ /** Retained presenter-owned message components (user + assistant). */
271
+ get componentCount() {
272
+ return this.assistantComponents.size + this.userComponents.size;
273
+ }
274
+ /**
275
+ * The presenter's local thinking preference. This is not the host patch's
276
+ * effective per-message state: in `auto` a collapse patch may still hide a
277
+ * completed message while the preference remains "visible".
278
+ */
279
+ get thinkingVisible() {
280
+ return this.thinkingPreference !== "hidden";
281
+ }
282
+ /** Wires the host TUI that receives repaint requests. */
283
+ attachTui(tui) {
284
+ this.attachedTui = tui;
285
+ }
286
+ /** Stops forwarding repaint requests without discarding retained state. */
287
+ detachTui() {
288
+ this.attachedTui = null;
289
+ }
290
+ /**
291
+ * Marks the display dirty and asks the attached TUI to repaint. Hosts wire
292
+ * tool components' repaint requests here so renderer-driven invalidations
293
+ * bypass the presenter's line cache.
294
+ */
295
+ requestRender() {
296
+ if (this.disposed)
297
+ return;
298
+ this.revisionValue++;
299
+ this.attachedTui?.requestRender();
300
+ }
301
+ /**
302
+ * Synchronizes the presenter with the current entries. Components are
303
+ * created or updated only when their segment/content actually changed; a
304
+ * repeated sync of unchanged entries leaves the display revision alone.
305
+ */
306
+ sync(entries) {
307
+ if (this.disposed)
308
+ return this.revisionValue;
309
+ const blocks = buildPresenterBlocks(entries);
310
+ const identities = blocks.map(blockIdentity);
311
+ let changed = identities.length !== this.blockIdentities.length ||
312
+ identities.some((identity, index) => identity !== this.blockIdentities[index]);
313
+ const seenAssistant = new Set();
314
+ const seenUser = new Set();
315
+ const seenTools = new Set();
316
+ for (const block of blocks) {
317
+ if (block.kind === "assistant") {
318
+ seenAssistant.add(block.segmentId);
319
+ const component = this.ensureAssistantComponent(block.segmentId);
320
+ const previous = this.assistantContent.get(block.segmentId);
321
+ if (!previous ||
322
+ previous.thinking !== block.thinking ||
323
+ previous.text !== block.text ||
324
+ previous.streaming !== block.streaming) {
325
+ component.updateContent(createAssistantMessage(block.thinking, block.text), block.streaming);
326
+ this.assistantContent.set(block.segmentId, {
327
+ thinking: block.thinking,
328
+ text: block.text,
329
+ streaming: block.streaming,
330
+ });
331
+ changed = true;
332
+ }
333
+ if (this.thinkingPreference === "visible") {
334
+ if (!block.thinking) {
335
+ this.expandedSegments.delete(block.segmentId);
336
+ }
337
+ else if (!this.expandedSegments.has(block.segmentId)) {
338
+ this.expandThinking(component);
339
+ this.expandedSegments.add(block.segmentId);
340
+ changed = true;
341
+ }
342
+ }
343
+ continue;
344
+ }
345
+ if (block.kind === "user") {
346
+ seenUser.add(block.entryId);
347
+ const previousText = this.userText.get(block.entryId);
348
+ if (previousText === undefined || previousText !== block.text) {
349
+ this.userComponents.set(block.entryId, new UserMessageComponent(block.text, getMarkdownTheme(), 1));
350
+ this.userText.set(block.entryId, block.text);
351
+ changed = true;
352
+ }
353
+ continue;
354
+ }
355
+ if (block.kind === "tool") {
356
+ seenTools.add(block.toolCallId);
357
+ const previous = this.toolState.get(block.toolCallId);
358
+ if (!previous ||
359
+ previous.args !== block.args ||
360
+ previous.result !== block.result ||
361
+ previous.isError !== block.isError ||
362
+ previous.streaming !== block.streaming) {
363
+ this.toolState.set(block.toolCallId, {
364
+ args: block.args,
365
+ result: block.result,
366
+ isError: block.isError,
367
+ streaming: block.streaming,
368
+ });
369
+ changed = true;
370
+ }
371
+ }
372
+ }
373
+ for (const segmentId of this.assistantComponents.keys()) {
374
+ if (seenAssistant.has(segmentId))
375
+ continue;
376
+ this.assistantComponents.delete(segmentId);
377
+ this.assistantContent.delete(segmentId);
378
+ this.expandedSegments.delete(segmentId);
379
+ }
380
+ for (const entryId of this.userComponents.keys()) {
381
+ if (seenUser.has(entryId))
382
+ continue;
383
+ this.userComponents.delete(entryId);
384
+ this.userText.delete(entryId);
385
+ }
386
+ for (const toolCallId of this.toolState.keys()) {
387
+ if (!seenTools.has(toolCallId))
388
+ this.toolState.delete(toolCallId);
389
+ }
390
+ this.blocks = blocks;
391
+ this.blockIdentities = identities;
392
+ if (changed) {
393
+ // The previous row ranges may reference removed/replaced components;
394
+ // refuse hits until the next render rebuilds the layout.
395
+ this.rows = [];
396
+ this.renderedToolComponents.clear();
397
+ this.requestRender();
398
+ }
399
+ return this.revisionValue;
400
+ }
401
+ /**
402
+ * Renders the synced entries at `width`. When nothing changed since the last
403
+ * frame, the cached frame is returned unchanged.
404
+ */
405
+ render(width) {
406
+ const targetWidth = Math.max(1, width);
407
+ if (this.disposed) {
408
+ return {
409
+ lines: [],
410
+ rows: [],
411
+ totalLines: 0,
412
+ width: targetWidth,
413
+ revision: this.revisionValue,
414
+ };
415
+ }
416
+ if (targetWidth !== this.renderedWidth) {
417
+ this.renderedWidth = targetWidth;
418
+ this.revisionValue++;
419
+ this.cachedFrame = null;
420
+ }
421
+ const startRevision = this.revisionValue;
422
+ if (this.cachedFrame &&
423
+ this.cachedFrame.width === targetWidth &&
424
+ this.renderedRevision === startRevision) {
425
+ return this.cachedFrame;
426
+ }
427
+ const rendered = this.renderBlocks(targetWidth);
428
+ this.rows = rendered.rows;
429
+ this.renderedToolComponents = rendered.toolComponents;
430
+ this.renderedRevision = startRevision;
431
+ const frame = {
432
+ lines: rendered.lines,
433
+ rows: rendered.rows,
434
+ totalLines: rendered.lines.length,
435
+ width: targetWidth,
436
+ revision: startRevision,
437
+ };
438
+ this.cachedFrame = frame;
439
+ return frame;
440
+ }
441
+ /**
442
+ * Routes a normalized mouse event (transcript-space `y`) to the component
443
+ * whose row contains it. Returns whether the component handled the event.
444
+ */
445
+ handleMouse(event) {
446
+ if (this.disposed)
447
+ return false;
448
+ const row = this.rows.find((candidate) => event.y >= candidate.top && event.y < candidate.top + candidate.height);
449
+ if (!row)
450
+ return false;
451
+ const component = this.componentForRow(row);
452
+ if (!component?.handleMouse)
453
+ return false;
454
+ const localEvent = {
455
+ ...event,
456
+ y: event.y - row.top,
457
+ width: this.renderedWidth,
458
+ height: row.height,
459
+ };
460
+ const result = component.handleMouse(localEvent);
461
+ if (!result)
462
+ return false;
463
+ const handled = result.handled === true || "target" in result;
464
+ if (handled)
465
+ this.requestRender();
466
+ return handled;
467
+ }
468
+ /**
469
+ * Applies the presenter's local thinking preference to every retained
470
+ * assistant component.
471
+ *
472
+ * Hiding uses the public `setHideThinkingBlock(true)`, which also clears
473
+ * native per-block overrides. Showing first forces the known collapsed state
474
+ * through the same public setter, then dispatches the native thinking-block
475
+ * click through `MouseRegion.handleMouse`. That sets the same per-block
476
+ * override a user click sets, so completed messages expand even while a
477
+ * host collapse patch keeps auto-collapsing them. No private component field
478
+ * is read and the streaming flag is never faked.
479
+ */
480
+ setThinkingVisible(visible) {
481
+ if (this.disposed)
482
+ return;
483
+ this.thinkingPreference = visible ? "visible" : "hidden";
484
+ if (visible) {
485
+ for (const [segmentId, component] of this.assistantComponents) {
486
+ this.expandThinking(component);
487
+ if (this.assistantContent.get(segmentId)?.thinking) {
488
+ this.expandedSegments.add(segmentId);
489
+ }
490
+ else {
491
+ this.expandedSegments.delete(segmentId);
492
+ }
493
+ }
494
+ }
495
+ else {
496
+ this.expandedSegments.clear();
497
+ for (const component of this.assistantComponents.values()) {
498
+ component.setHideThinkingBlock(true);
499
+ }
500
+ }
501
+ this.requestRender();
502
+ }
503
+ /** Flips the local thinking preference and returns the new visibility. */
504
+ toggleThinkingVisibility() {
505
+ const nextVisible = !this.thinkingVisible;
506
+ this.setThinkingVisible(nextVisible);
507
+ return nextVisible;
508
+ }
509
+ /**
510
+ * Invalidates native components for a theme change and raises the display
511
+ * revision. The host's global theme is never re-initialized here.
512
+ */
513
+ invalidate() {
514
+ if (this.disposed)
515
+ return;
516
+ const invalidated = new Set();
517
+ const invalidate = (component) => {
518
+ if (invalidated.has(component))
519
+ return;
520
+ invalidated.add(component);
521
+ component.invalidate();
522
+ };
523
+ for (const component of this.assistantComponents.values())
524
+ invalidate(component);
525
+ for (const component of this.userComponents.values())
526
+ invalidate(component);
527
+ for (const component of this.renderedToolComponents.values())
528
+ invalidate(component);
529
+ this.requestRender();
530
+ }
531
+ /** Drops retained message components and rendered layout. */
532
+ clear() {
533
+ if (this.disposed)
534
+ return;
535
+ this.dropRetainedState();
536
+ this.requestRender();
537
+ }
538
+ /**
539
+ * Releases every retained component and detaches the TUI. Idempotent; later
540
+ * calls to `sync`, `render`, and `handleMouse` degrade to no-ops.
541
+ */
542
+ dispose() {
543
+ if (this.disposed)
544
+ return;
545
+ this.disposed = true;
546
+ this.dropRetainedState();
547
+ this.attachedTui = null;
548
+ this.cachedFrame = null;
549
+ this.renderedRevision = -1;
550
+ this.revisionValue++;
551
+ }
552
+ dropRetainedState() {
553
+ this.assistantComponents.clear();
554
+ this.assistantContent.clear();
555
+ this.expandedSegments.clear();
556
+ this.userComponents.clear();
557
+ this.userText.clear();
558
+ this.toolState.clear();
559
+ this.renderedToolComponents.clear();
560
+ this.blocks = [];
561
+ this.blockIdentities = [];
562
+ this.rows = [];
563
+ this.cachedFrame = null;
564
+ this.renderedRevision = -1;
565
+ }
566
+ ensureAssistantComponent(segmentId) {
567
+ const existing = this.assistantComponents.get(segmentId);
568
+ if (existing)
569
+ return existing;
570
+ const component = new AssistantMessageComponent(undefined, this.thinkingPreference === "hidden", getMarkdownTheme(), this.options.thinkingLabel ?? "Thinking...", 1);
571
+ this.assistantComponents.set(segmentId, component);
572
+ return component;
573
+ }
574
+ /**
575
+ * Expands every thinking block in `component` through the native public
576
+ * click path. When the host has no thinking `MouseRegion` (an older Pi), it
577
+ * degrades to the public visibility setter.
578
+ */
579
+ expandThinking(component) {
580
+ if (collectThinkingMouseRegions(component).length === 0) {
581
+ component.setHideThinkingBlock(false);
582
+ return;
583
+ }
584
+ // Force a known collapsed render first so each region's click handler
585
+ // records "expand" as its override. Clicking while already expanded would
586
+ // collapse the block instead.
587
+ component.setHideThinkingBlock(true);
588
+ const count = collectThinkingMouseRegions(component).length;
589
+ for (let index = 0; index < count; index++) {
590
+ // The click rebuilds the component's content, so re-collect the current
591
+ // region for this run instead of holding a detached instance.
592
+ collectThinkingMouseRegions(component)[index]?.handleMouse(THINKING_CLICK_EVENT);
593
+ }
594
+ }
595
+ componentForRow(row) {
596
+ switch (row.kind) {
597
+ case "user":
598
+ return this.userComponents.get(row.entryId);
599
+ case "assistant":
600
+ return this.assistantComponents.get(row.segmentId);
601
+ case "tool":
602
+ return this.renderedToolComponents.get(row.toolCallId);
603
+ }
604
+ }
605
+ renderBlocks(width) {
606
+ const theme = this.options.theme;
607
+ const lines = [];
608
+ const rows = [];
609
+ const toolComponents = new Map();
610
+ if (this.blocks.length === 0) {
611
+ return {
612
+ lines: [
613
+ theme.fg("dim", this.options.emptyText ?? "No transcript yet."),
614
+ ],
615
+ rows,
616
+ toolComponents,
617
+ };
618
+ }
619
+ const assistantBadge = theme.bg(this.options.assistantBadgeBackground ?? "customMessageBg", theme.fg(this.options.assistantBadgeForeground ?? "success", theme.bold(` ${this.options.assistantLabel ?? "Assistant"} `)));
620
+ const separator = theme.fg("borderMuted", "────────────────────────────────────────");
621
+ const blankBefore = () => {
622
+ if (lines.length > 0 && lines.at(-1) !== "")
623
+ lines.push("");
624
+ };
625
+ for (const block of this.blocks) {
626
+ switch (block.kind) {
627
+ case "separator":
628
+ blankBefore();
629
+ lines.push(separator);
630
+ break;
631
+ case "user": {
632
+ const component = this.userComponents.get(block.entryId);
633
+ if (!component)
634
+ break;
635
+ const rendered = stripOsc133(component.render(width));
636
+ rows.push({
637
+ kind: "user",
638
+ entryId: block.entryId,
639
+ top: lines.length,
640
+ height: rendered.length,
641
+ });
642
+ lines.push(...rendered);
643
+ break;
644
+ }
645
+ case "assistant": {
646
+ const component = this.assistantComponents.get(block.segmentId);
647
+ if (!component)
648
+ break;
649
+ blankBefore();
650
+ lines.push(assistantBadge);
651
+ const rendered = stripOsc133(component.render(width));
652
+ rows.push({
653
+ kind: "assistant",
654
+ segmentId: block.segmentId,
655
+ entryIds: block.entryIds,
656
+ top: lines.length,
657
+ height: rendered.length,
658
+ });
659
+ lines.push(...rendered);
660
+ break;
661
+ }
662
+ case "tool": {
663
+ blankBefore();
664
+ const component = this.options.toolComponents?.get(block.toolCallId) ??
665
+ createAdHocToolComponent(block, this.options);
666
+ toolComponents.set(block.toolCallId, component);
667
+ const rendered = component.render(width);
668
+ rows.push({
669
+ kind: "tool",
670
+ entryId: block.entryId,
671
+ toolCallId: block.toolCallId,
672
+ top: lines.length,
673
+ height: rendered.length,
674
+ });
675
+ lines.push(...rendered);
676
+ break;
677
+ }
678
+ case "notice": {
679
+ blankBefore();
680
+ const color = noticeToneColor(block.tone);
681
+ for (const noticeLine of block.text.split("\n")) {
682
+ const colored = theme.fg(color, noticeLine);
683
+ lines.push(visibleWidth(colored) > width
684
+ ? truncateToWidth(colored, width, "")
685
+ : colored);
686
+ }
687
+ break;
688
+ }
689
+ }
690
+ }
691
+ return { lines, rows, toolComponents };
692
+ }
693
+ }