@causyne/agent 1.20.39 → 1.20.42

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.
@@ -27,6 +27,7 @@ import { chatProseWidth, wrappedChatRows } from './textLayout.js';
27
27
  import { activityRows } from './activityLayout.js';
28
28
  import { cleanToolOutputPreview, normalizeHistoricalToolResult } from './toolOutputNormalizer.js';
29
29
  import { formatMarkdownMath } from './markdownMath.js';
30
+ import { renderThinkingFrame } from './thinkingBox.js';
30
31
 
31
32
  // Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
32
33
  // minified output would otherwise become thousands of rows and lock the
@@ -737,8 +738,9 @@ export class ChatRenderer {
737
738
  const elapsedMs = Number(msg.elapsedMs) || 0;
738
739
  const durationText = elapsedMs > 0 ? formatDuration(elapsedMs) : '';
739
740
 
741
+ const tailFrame = this.transcript?.frames?.at(-1);
740
742
  const tailIsReasoning = !this.transcript
741
- || this.transcript.frames?.at(-1)?.meta?.reasoning === true;
743
+ || tailFrame?.meta?.reasoning === true;
742
744
  if (this._activeReasoning && !tailIsReasoning) {
743
745
  this._activeReasoning = false;
744
746
  }
@@ -746,60 +748,94 @@ export class ChatRenderer {
746
748
  if (isStreaming) {
747
749
  if (!this._activeReasoning) {
748
750
  this._activeReasoning = true;
749
- this.frame('reasoning', () => this.renderReasoning(content, { streaming: true, durationText }), { reasoning: true });
751
+ const meta = {
752
+ reasoning: true,
753
+ collapsed: false,
754
+ streaming: true,
755
+ durationText,
756
+ content,
757
+ scrollStart: 0
758
+ };
759
+ this.frame('reasoning', () => this.renderReasoning(meta.content, {
760
+ streaming: true,
761
+ durationText: meta.durationText,
762
+ collapsed: Boolean(meta.collapsed),
763
+ startLine: Number(meta.scrollStart) || 0
764
+ }), meta);
750
765
  } else {
751
- this.updateTailFrame('reasoning', () => this.renderReasoning(content, { streaming: true, durationText }), { reasoning: true });
766
+ const meta = tailFrame?.meta || { reasoning: true };
767
+ meta.streaming = true;
768
+ meta.durationText = durationText;
769
+ meta.content = content;
770
+ if (meta.collapsed === undefined) meta.collapsed = false;
771
+ if (meta.scrollStart === undefined) meta.scrollStart = 0;
772
+ this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
773
+ streaming: true,
774
+ durationText: meta.durationText,
775
+ collapsed: Boolean(meta.collapsed),
776
+ startLine: Number(meta.scrollStart) || 0
777
+ }), meta);
752
778
  }
753
779
  return;
754
780
  }
755
781
 
756
782
  if (this._activeReasoning) {
757
783
  this._activeReasoning = false;
758
- this.updateTailFrame('reasoning', () => this.renderReasoning(content, { streaming: false, durationText }), { reasoning: true, done: true });
784
+ const meta = tailFrame?.meta || { reasoning: true };
785
+ meta.streaming = false;
786
+ meta.done = true;
787
+ meta.durationText = durationText;
788
+ meta.content = content;
789
+ if (meta.collapsed === undefined) meta.collapsed = false;
790
+ if (meta.scrollStart === undefined) meta.scrollStart = 0;
791
+ this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
792
+ streaming: false,
793
+ durationText: meta.durationText,
794
+ collapsed: Boolean(meta.collapsed),
795
+ startLine: Number(meta.scrollStart) || 0
796
+ }), meta);
759
797
  } else if (content.trim()) {
760
- this.frame('reasoning', () => this.renderReasoning(content, { streaming: false, durationText }), { reasoning: true, done: true });
798
+ const meta = {
799
+ reasoning: true,
800
+ done: true,
801
+ streaming: false,
802
+ durationText,
803
+ content,
804
+ collapsed: false,
805
+ scrollStart: 0
806
+ };
807
+ this.frame('reasoning', () => this.renderReasoning(meta.content, {
808
+ streaming: false,
809
+ durationText: meta.durationText,
810
+ collapsed: Boolean(meta.collapsed),
811
+ startLine: Number(meta.scrollStart) || 0
812
+ }), meta);
761
813
  }
762
814
  }
763
815
 
764
- renderReasoning(content, { streaming = false, durationText = '' } = {}) {
816
+ renderReasoning(content, { streaming = false, durationText = '', collapsed = false, startLine = 0 } = {}) {
765
817
  const width = this.measure();
766
- const rows = content.trim()
767
- ? wrapBlock(content, Math.max(20, width - 4))
768
- : ['Contemplating task and formulating approach…'];
769
-
770
- this.write();
771
- if (streaming) {
772
- this.write(`${paint('warn', GLYPHS.vLine || '│')} ${bold(paint('warn', 'thinking…'))}`);
773
- } else {
774
- const timePart = durationText ? ` · ${durationText}` : '';
775
- this.write(`${paint('muted', GLYPHS.vLine || '│')} ${dim(`thinking${timePart}`)}`);
776
- }
777
-
778
- if (streaming && rows.length > REASONING_LINES) {
779
- const hidden = rows.length - REASONING_LINES;
780
- this.write(`${paint('rule', GLYPHS.vLine || '│')} ${dim(`${GLYPHS.ellipsis} ${hidden} earlier thinking line${hidden === 1 ? '' : 's'}`)}`);
781
- }
782
-
783
- const displayRows = streaming && rows.length > REASONING_LINES
784
- ? rows.slice(rows.length - REASONING_LINES)
785
- : rows.slice(0, REASONING_LINES);
818
+ const rows = renderThinkingFrame(content, {
819
+ width,
820
+ streaming,
821
+ durationText,
822
+ collapsed,
823
+ startLine: Number(startLine) || 0
824
+ });
786
825
 
787
- for (const row of displayRows) {
788
- this.write(`${paint('rule', GLYPHS.vLine || '│')} ${dim(row)}`);
789
- }
826
+ if (rows.length === 0) return;
790
827
 
791
- if (!streaming && rows.length > REASONING_LINES) {
792
- const hidden = rows.length - REASONING_LINES;
793
- this.write(`${paint('rule', GLYPHS.corner || '└')} ${dim(`${GLYPHS.ellipsis} ${hidden} more line${hidden === 1 ? '' : 's'} of reasoning`)}`);
794
- } else if (streaming) {
795
- const timePart = durationText ? ` · ${durationText}` : '';
796
- this.write(`${paint('rule', GLYPHS.corner || '└')} ${bold(paint('warn', 'thinking…'))} ${dim(timePart || 'streaming thoughts')}`);
797
- } else {
798
- this.write(`${paint('rule', GLYPHS.corner || '└')}`);
828
+ this.write();
829
+ for (const row of rows) {
830
+ this.write(row);
799
831
  }
800
832
  this.write();
801
833
  }
802
834
 
835
+ scrollThinkingPanel(key, surface) {
836
+ return false;
837
+ }
838
+
803
839
  onAgentActivity(msg) {
804
840
  const text = String(msg.activity || msg.message || '').trim();
805
841
  if (!text) return;
@@ -1,5 +1,6 @@
1
1
  import { ChatRenderer } from './chatRenderer.js';
2
2
  import { CODE_PANEL_LINES, codePreviewLineCount, defaultPreviewStart, renderCodeProgress } from './codeProgress.js';
3
+ import { calculateThinkingLineCount, DEFAULT_MAX_EXPANDED_LINES } from './thinkingBox.js';
3
4
  function lastStart(event) {
4
5
  return Math.max(0, codePreviewLineCount(event) - CODE_PANEL_LINES);
5
6
  }
@@ -48,6 +49,48 @@ export class CodeStreamRenderer extends ChatRenderer {
48
49
  transcript.changed();
49
50
  return true;
50
51
  }
52
+ /** Scroll only the thinking panel beneath the pointer; leave the chat viewport alone. */
53
+ scrollThinkingPanel(key, surface) {
54
+ const wheel = key.wheel;
55
+ if (key.name !== 'wheel' || !wheel || !surface || !['up', 'down'].includes(wheel.direction))
56
+ return false;
57
+ const transcript = this.transcript;
58
+ if (!transcript || !Number.isFinite(surface.out.rows) || !Number.isFinite(wheel.x) || !Number.isFinite(wheel.y))
59
+ return false;
60
+ const viewport = surface.viewport;
61
+ const screenTop = surface.out.rows - surface.stage.height;
62
+ const localY = wheel.y - screenTop;
63
+ if (localY < 0 || localY >= viewport.viewHeight || wheel.x < 0 || wheel.x >= Math.min(viewport.viewWidth, this.measure()))
64
+ return false;
65
+ const { markers } = transcript.flatten(viewport.viewWidth);
66
+ const absoluteY = viewport.scrollTop + localY;
67
+ const markerIndex = markers.findIndex((marker, index) => marker.row <= absoluteY
68
+ && (index + 1 === markers.length || absoluteY < markers[index + 1].row));
69
+ if (markerIndex < 0)
70
+ return false;
71
+ const marker = markers[markerIndex];
72
+ const frame = transcript.frames.find(item => item.id === marker.id);
73
+ if (!frame || frame.meta?.reasoning !== true || frame.meta?.collapsed)
74
+ return false;
75
+ if (absoluteY >= marker.row + (frame.rows?.length || 0))
76
+ return false;
77
+ const content = typeof frame.meta.content === 'string' ? frame.meta.content : '';
78
+ const totalLines = calculateThinkingLineCount(content, viewport.viewWidth);
79
+ const limit = Math.max(0, totalLines - DEFAULT_MAX_EXPANDED_LINES);
80
+ if (limit === 0)
81
+ return false;
82
+ const currentStart = Number(frame.meta.scrollStart) || 0;
83
+ const next = Math.max(0, Math.min(limit, currentStart + (wheel.direction === 'up' ? -3 : 3)));
84
+ if (next === currentStart)
85
+ return true;
86
+ frame.meta.scrollStart = next;
87
+ frame.rows = null;
88
+ frame.renderedWidth = -1;
89
+ transcript.cache = null;
90
+ transcript.revision++;
91
+ transcript.changed();
92
+ return true;
93
+ }
51
94
  resetTurn() {
52
95
  this._activeReasoning = false;
53
96
  this.activeCode = null;
@@ -1,5 +1,6 @@
1
1
  import { ChatRenderer } from './chatRenderer.js';
2
2
  import { CODE_PANEL_LINES, codePreviewLineCount, defaultPreviewStart, renderCodeProgress, type CodeProgressEvent } from './codeProgress.js';
3
+ import { calculateThinkingLineCount, DEFAULT_MAX_EXPANDED_LINES } from './thinkingBox.js';
3
4
 
4
5
  type RendererEvent = { type: string; [key: string]: unknown };
5
6
  type CodePanelState = { event: CodeProgressEvent; modelNote: string; start: number; followTail: boolean };
@@ -62,6 +63,44 @@ export class CodeStreamRenderer extends ChatRenderer {
62
63
  return true;
63
64
  }
64
65
 
66
+ /** Scroll only the thinking panel beneath the pointer; leave the chat viewport alone. */
67
+ override scrollThinkingPanel(key: CodeWheel, surface: CodeSurface | null): boolean {
68
+ const wheel = key.wheel;
69
+ if (key.name !== 'wheel' || !wheel || !surface || !['up', 'down'].includes(wheel.direction)) return false;
70
+ const transcript = this.transcript as unknown as CodeTranscript | null;
71
+ if (!transcript || !Number.isFinite(surface.out.rows) || !Number.isFinite(wheel.x) || !Number.isFinite(wheel.y)) return false;
72
+ const viewport = surface.viewport;
73
+ const screenTop = (surface.out.rows as number) - surface.stage.height;
74
+ const localY = wheel.y - screenTop;
75
+ if (localY < 0 || localY >= viewport.viewHeight || wheel.x < 0 || wheel.x >= Math.min(viewport.viewWidth, this.measure())) return false;
76
+ const { markers } = transcript.flatten(viewport.viewWidth);
77
+ const absoluteY = viewport.scrollTop + localY;
78
+ const markerIndex = markers.findIndex((marker, index) => marker.row <= absoluteY
79
+ && (index + 1 === markers.length || absoluteY < markers[index + 1]!.row));
80
+ if (markerIndex < 0) return false;
81
+ const marker = markers[markerIndex]!;
82
+ const frame = transcript.frames.find(item => item.id === marker.id);
83
+ if (!frame || frame.meta?.reasoning !== true || frame.meta?.collapsed) return false;
84
+ if (absoluteY >= marker.row + (frame.rows?.length || 0)) return false;
85
+
86
+ const content = typeof frame.meta.content === 'string' ? frame.meta.content : '';
87
+ const totalLines = calculateThinkingLineCount(content, viewport.viewWidth);
88
+ const limit = Math.max(0, totalLines - DEFAULT_MAX_EXPANDED_LINES);
89
+ if (limit === 0) return false;
90
+
91
+ const currentStart = Number(frame.meta.scrollStart) || 0;
92
+ const next = Math.max(0, Math.min(limit, currentStart + (wheel.direction === 'up' ? -3 : 3)));
93
+ if (next === currentStart) return true;
94
+
95
+ frame.meta.scrollStart = next;
96
+ frame.rows = null;
97
+ frame.renderedWidth = -1;
98
+ transcript.cache = null;
99
+ transcript.revision++;
100
+ transcript.changed();
101
+ return true;
102
+ }
103
+
65
104
  override resetTurn(): void {
66
105
  this._activeReasoning = false;
67
106
  this.activeCode = null;
@@ -108,6 +108,24 @@ export function handleMessageMouse(host, loop, event) {
108
108
  if (isMouseMotion(event.sequence))
109
109
  return true;
110
110
  if (mouse.button === 0 && mouse.pressed) {
111
+ const rawMarker = markerAt(surface, mouse);
112
+ if (rawMarker && rawMarker.kind === 'reasoning') {
113
+ const transcript = surface.transcript;
114
+ const frames = transcript?.frames;
115
+ const frame = Array.isArray(frames) ? frames.find(f => f.id === rawMarker.id) : null;
116
+ if (frame && frame.meta && frame.meta.reasoning) {
117
+ frame.meta.collapsed = !frame.meta.collapsed;
118
+ frame.rows = null;
119
+ frame.renderedWidth = -1;
120
+ if (transcript) {
121
+ transcript.cache = null;
122
+ transcript.revision = (transcript.revision || 0) + 1;
123
+ transcript.changed?.();
124
+ }
125
+ host.scheduleDraw();
126
+ return true;
127
+ }
128
+ }
111
129
  // Smart link detection: if the user clicked (or Cmd/Ctrl+Clicked) on a URL or OSC 8 hyperlink,
112
130
  // open the link directly in the system browser instead of popping up the Message Actions modal.
113
131
  const hitLink = detectLinkAtPoint(surface, mouse, marker);
@@ -130,8 +148,8 @@ export function handleMessageMouse(host, loop, event) {
130
148
  }
131
149
  const isMessage = (marker) => (marker.kind === 'user' || marker.kind === 'assistant')
132
150
  && typeof marker.meta?.messageText === 'string';
133
- /** Resolve screen coordinates against the painted viewport, including top padding. */
134
- export function messageAt(surface, point) {
151
+ /** Resolve screen coordinates against the painted viewport to find any frame marker. */
152
+ export function markerAt(surface, point) {
135
153
  if (!surface?.stage.reserved || !Number.isFinite(point.x) || !Number.isFinite(point.y))
136
154
  return null;
137
155
  const mainWidth = sidebarVisible(surface.width) ? sessionMainWidth(surface.width) : surface.width;
@@ -153,12 +171,17 @@ export function messageAt(surface, point) {
153
171
  if (!marker || marker.row > row)
154
172
  continue;
155
173
  const next = flat.markers[i + 1];
156
- if (isMessage(marker) && row < (next?.row ?? flat.rows.length))
174
+ if (row < (next?.row ?? flat.rows.length))
157
175
  return marker;
158
176
  return null;
159
177
  }
160
178
  return null;
161
179
  }
180
+ /** Resolve screen coordinates against the painted viewport, including top padding. */
181
+ export function messageAt(surface, point) {
182
+ const marker = markerAt(surface, point);
183
+ return marker && isMessage(marker) ? marker : null;
184
+ }
162
185
  /** Highlight only the visible non-empty rows of the hovered message, without altering transcript data. */
163
186
  export function markHoveredMessage(rows, surface, contentWidth) {
164
187
  registerStageConsoleGuard(surface);
@@ -22,7 +22,7 @@ export interface MessageMarker {
22
22
  id: number;
23
23
  kind: string;
24
24
  row: number;
25
- meta?: { messageText?: string } | null;
25
+ meta?: { messageText?: string; reasoning?: boolean; collapsed?: boolean } | null;
26
26
  }
27
27
 
28
28
  interface MousePoint { x: number; y: number }
@@ -183,6 +183,35 @@ export function handleMessageMouse(
183
183
  if (isMouseMotion(event.sequence)) return true;
184
184
 
185
185
  if (mouse.button === 0 && mouse.pressed) {
186
+ const rawMarker = markerAt(surface, mouse);
187
+ if (rawMarker && rawMarker.kind === 'reasoning') {
188
+ const transcript = surface.transcript as unknown as {
189
+ frames?: Array<{
190
+ id: number;
191
+ meta?: { reasoning?: boolean; collapsed?: boolean } | null;
192
+ rows?: unknown;
193
+ renderedWidth?: number;
194
+ }>;
195
+ cache?: unknown;
196
+ revision?: number;
197
+ changed?: () => void;
198
+ };
199
+ const frames = transcript?.frames;
200
+ const frame = Array.isArray(frames) ? frames.find(f => f.id === rawMarker.id) : null;
201
+ if (frame && frame.meta && frame.meta.reasoning) {
202
+ frame.meta.collapsed = !frame.meta.collapsed;
203
+ frame.rows = null;
204
+ frame.renderedWidth = -1;
205
+ if (transcript) {
206
+ transcript.cache = null;
207
+ transcript.revision = (transcript.revision || 0) + 1;
208
+ transcript.changed?.();
209
+ }
210
+ host.scheduleDraw();
211
+ return true;
212
+ }
213
+ }
214
+
186
215
  // Smart link detection: if the user clicked (or Cmd/Ctrl+Clicked) on a URL or OSC 8 hyperlink,
187
216
  // open the link directly in the system browser instead of popping up the Message Actions modal.
188
217
  const hitLink = detectLinkAtPoint(surface, mouse, marker);
@@ -208,8 +237,8 @@ const isMessage = (marker: MessageMarker): boolean =>
208
237
  (marker.kind === 'user' || marker.kind === 'assistant')
209
238
  && typeof marker.meta?.messageText === 'string';
210
239
 
211
- /** Resolve screen coordinates against the painted viewport, including top padding. */
212
- export function messageAt(surface: MessageSurface | null, point: MousePoint): MessageMarker | null {
240
+ /** Resolve screen coordinates against the painted viewport to find any frame marker. */
241
+ export function markerAt(surface: MessageSurface | null, point: MousePoint): MessageMarker | null {
213
242
  if (!surface?.stage.reserved || !Number.isFinite(point.x) || !Number.isFinite(point.y)) return null;
214
243
  const mainWidth = sidebarVisible(surface.width) ? sessionMainWidth(surface.width) : surface.width;
215
244
  const leftGutter = (surface.turnRailLayout?.turns?.length ?? 0) > 0 ? 3 : 0;
@@ -226,12 +255,18 @@ export function messageAt(surface: MessageSurface | null, point: MousePoint): Me
226
255
  const marker = flat.markers[i];
227
256
  if (!marker || marker.row > row) continue;
228
257
  const next = flat.markers[i + 1];
229
- if (isMessage(marker) && row < (next?.row ?? flat.rows.length)) return marker;
258
+ if (row < (next?.row ?? flat.rows.length)) return marker;
230
259
  return null;
231
260
  }
232
261
  return null;
233
262
  }
234
263
 
264
+ /** Resolve screen coordinates against the painted viewport, including top padding. */
265
+ export function messageAt(surface: MessageSurface | null, point: MousePoint): MessageMarker | null {
266
+ const marker = markerAt(surface, point);
267
+ return marker && isMessage(marker) ? marker : null;
268
+ }
269
+
235
270
  /** Highlight only the visible non-empty rows of the hovered message, without altering transcript data. */
236
271
  export function markHoveredMessage(
237
272
  rows: string[], surface: MessageSurface, contentWidth: number
package/src/tui/prompt.js CHANGED
@@ -920,6 +920,7 @@ export class ChatPrompt {
920
920
  if (key.name === 'wheel') {
921
921
  if (!viewport || !key.wheel) return true;
922
922
  if (this.renderer?.scrollCodePanel?.(key, this.surface)) return true;
923
+ if (this.renderer?.scrollThinkingPanel?.(key, this.surface)) return true;
923
924
 
924
925
  return handleViewportWheel(key, viewport, this.surface, this);
925
926
  }
@@ -0,0 +1,164 @@
1
+ // Collapsible & auto-scrolling thinking box container for Causyne Agent TUI.
2
+ //
3
+ // Encapsulates streaming reasoning into a bounded, scrolling card container
4
+ // with rounded border framing, auto-scrolling tail pinning, and interactive
5
+ // collapse/expand folding.
6
+ //
7
+ // Pure TypeScript under strict mode.
8
+ // @ts-expect-error theme.js has no TypeScript declaration yet.
9
+ import { paint, bold, dim, GLYPHS, HAS_UNICODE } from './theme.js';
10
+ import { padEnd, truncate, visibleWidth, wrapBlock } from './text.js';
11
+ export const DEFAULT_MAX_STREAMING_LINES = 8;
12
+ export const DEFAULT_MAX_EXPANDED_LINES = 12;
13
+ /**
14
+ * Calculates total wrapped lines for reasoning content under the thinking box budget.
15
+ */
16
+ export function calculateThinkingLineCount(content, width) {
17
+ const text = String(content ?? '').trim();
18
+ if (!text)
19
+ return 0;
20
+ const safeWidth = Math.max(20, Math.floor(width));
21
+ const contentBudget = Math.max(10, safeWidth - 4);
22
+ return wrapBlock(text, contentBudget).length;
23
+ }
24
+ /**
25
+ * Single-line compact badge for collapsed reasoning frames.
26
+ */
27
+ export function renderCollapsedThinkingBadge(options, totalLines) {
28
+ const isStreaming = Boolean(options.streaming);
29
+ const durationText = options.durationText ? String(options.durationText).trim() : '';
30
+ const arrow = HAS_UNICODE ? '▸' : '>';
31
+ if (isStreaming) {
32
+ const timePart = durationText ? ` · ${durationText}` : '';
33
+ return ` ${paint('warn', arrow)} ${bold(paint('warn', 'thinking…'))}${dim(timePart)} ${dim('· click to expand')}`;
34
+ }
35
+ const timePart = durationText ? ` for ${durationText}` : '';
36
+ const lineWord = totalLines === 1 ? 'line' : 'lines';
37
+ return ` ${paint('muted', arrow)} ${dim(`Thought${timePart}`)} ${dim(`(${totalLines} ${lineWord})`)} ${dim('· click to expand')}`;
38
+ }
39
+ /**
40
+ * Builds the top, bottom, and side frame borders for the thinking box.
41
+ */
42
+ export function buildThinkingBoxBorders(title, footer, width, role = 'rule') {
43
+ const w = Math.max(20, Math.floor(width));
44
+ const inner = w - 2; // total space between left and right outer border corners
45
+ const h = GLYPHS.hLine || '─';
46
+ const v = GLYPHS.vLine || '│';
47
+ const tl = GLYPHS.topLeft || '╭';
48
+ const tr = GLYPHS.topRight || '╮';
49
+ const bl = GLYPHS.bottomLeft || '╰';
50
+ const br = GLYPHS.bottomRight || '╯';
51
+ // --- Top Border ---
52
+ const rawTitle = title ? ` ${title} ` : '';
53
+ const titleVis = visibleWidth(rawTitle);
54
+ const maxTitleVis = Math.max(0, inner - 4); // reserve at least 1 leading hLine and 2 trailing hLines
55
+ const safeTitle = titleVis > maxTitleVis ? (rawTitle ? ` ${truncate(title, Math.max(4, maxTitleVis - 2), GLYPHS.ellipsis || '…')} ` : '') : rawTitle;
56
+ const safeTitleVis = visibleWidth(safeTitle);
57
+ const topLead = h;
58
+ const topTrailCount = Math.max(0, inner - 1 - safeTitleVis);
59
+ const topTrail = h.repeat(topTrailCount);
60
+ const top = paint(role, tl + topLead) + safeTitle + paint(role, topTrail + tr);
61
+ // --- Bottom Border ---
62
+ const rawFooter = footer ? ` ${footer} ` : '';
63
+ const footerVis = visibleWidth(rawFooter);
64
+ const maxFooterVis = Math.max(0, inner - 4);
65
+ const safeFooter = footerVis > maxFooterVis ? (rawFooter ? ` ${truncate(footer, Math.max(4, maxFooterVis - 2), GLYPHS.ellipsis || '…')} ` : '') : rawFooter;
66
+ const safeFooterVis = visibleWidth(safeFooter);
67
+ const bottomLead = h;
68
+ const bottomTrailCount = Math.max(0, inner - 1 - safeFooterVis);
69
+ const bottomTrail = h.repeat(bottomTrailCount);
70
+ const bottom = paint(role, bl + bottomLead) + safeFooter + paint(role, bottomTrail + br);
71
+ // --- Middle Row Wrapper ---
72
+ // Format: "│ " + content + " │"
73
+ // content column width = inner - 2 = w - 4
74
+ const contentWidth = Math.max(2, inner - 2);
75
+ const side = paint(role, v);
76
+ const wrapRow = (line) => {
77
+ const truncated = truncate(line, contentWidth, GLYPHS.ellipsis || '…');
78
+ const padded = padEnd(truncated, contentWidth);
79
+ return `${side} ${padded} ${side}`;
80
+ };
81
+ return { top, bottom, wrapRow };
82
+ }
83
+ /**
84
+ * Render a complete thinking frame (either compact collapsed badge or expanded box).
85
+ */
86
+ export function renderThinkingFrame(content, options = {}) {
87
+ const text = String(content ?? '').trim();
88
+ if (!text)
89
+ return [];
90
+ const width = Math.max(20, Math.floor(options.width ?? 80));
91
+ const isStreaming = Boolean(options.streaming);
92
+ const isCollapsed = Boolean(options.collapsed);
93
+ const durationText = options.durationText ? String(options.durationText).trim() : '';
94
+ // Wrap lines for inner box width (w - 4)
95
+ const contentBudget = Math.max(10, width - 4);
96
+ const allRows = wrapBlock(text, contentBudget);
97
+ const totalLines = allRows.length;
98
+ if (isCollapsed) {
99
+ return [renderCollapsedThinkingBadge(options, totalLines)];
100
+ }
101
+ // Expanded Box Mode
102
+ const role = isStreaming ? 'warn' : (options.role ?? 'rule');
103
+ const collapseIndicator = HAS_UNICODE ? '▾' : 'v';
104
+ const collapseHint = dim(`${collapseIndicator} click to collapse`);
105
+ if (isStreaming) {
106
+ const maxLines = options.maxVisibleLines ?? DEFAULT_MAX_STREAMING_LINES;
107
+ const timePart = durationText ? ` · ${durationText}` : '';
108
+ const title = `${bold(paint('warn', 'thinking…'))}${dim(timePart)}`;
109
+ const footer = collapseHint;
110
+ const { top, bottom, wrapRow } = buildThinkingBoxBorders(title, footer, width, role);
111
+ const rows = [top];
112
+ if (totalLines > maxLines) {
113
+ const hiddenCount = totalLines - (maxLines - 1);
114
+ const scrollIndicator = HAS_UNICODE ? '↑' : '^';
115
+ const hiddenNotice = `${paint('rule', scrollIndicator)} ${dim(`${hiddenCount} earlier thinking line${hiddenCount === 1 ? '' : 's'} scrolled`)}`;
116
+ rows.push(wrapRow(hiddenNotice));
117
+ const tailRows = allRows.slice(totalLines - (maxLines - 1));
118
+ for (const row of tailRows) {
119
+ rows.push(wrapRow(dim(row)));
120
+ }
121
+ }
122
+ else {
123
+ for (const row of allRows) {
124
+ rows.push(wrapRow(dim(row)));
125
+ }
126
+ }
127
+ rows.push(bottom);
128
+ return rows;
129
+ }
130
+ // Completed Expanded Mode
131
+ const maxLines = options.maxVisibleLines ?? DEFAULT_MAX_EXPANDED_LINES;
132
+ const timePart = durationText ? ` · ${durationText}` : '';
133
+ const title = `${paint('muted', 'thinking')}${dim(timePart)} ${dim(`(${totalLines} line${totalLines === 1 ? '' : 's'})`)}`;
134
+ const { top, bottom, wrapRow } = buildThinkingBoxBorders(title, collapseHint, width, 'rule');
135
+ const rows = [top];
136
+ if (totalLines > maxLines) {
137
+ const limit = Math.max(0, totalLines - maxLines);
138
+ const start = Math.max(0, Math.min(limit, Math.floor(options.startLine ?? 0)));
139
+ const visible = allRows.slice(start, start + maxLines);
140
+ for (const row of visible) {
141
+ rows.push(wrapRow(dim(row)));
142
+ }
143
+ const hiddenBelow = totalLines - (start + visible.length);
144
+ if (hiddenBelow > 0) {
145
+ const moreNotice = `${GLYPHS.ellipsis || '…'} ${hiddenBelow} more line${hiddenBelow === 1 ? '' : 's'} of reasoning`;
146
+ rows.push(wrapRow(dim(moreNotice)));
147
+ }
148
+ else if (start > 0) {
149
+ const earlierNotice = `${HAS_UNICODE ? '↑' : '^'} ${start} earlier line${start === 1 ? '' : 's'} scrolled above`;
150
+ rows.push(wrapRow(dim(earlierNotice)));
151
+ }
152
+ const upArrow = start > 0 ? (HAS_UNICODE ? '↑ ' : '^ ') : '';
153
+ const downArrow = start + visible.length < totalLines ? (HAS_UNICODE ? ' ↓' : ' v') : '';
154
+ const scrollInfo = `${upArrow}lines ${start + 1}–${start + visible.length} of ${totalLines}${downArrow} · scroll over thinking`;
155
+ rows.push(wrapRow(dim(scrollInfo)));
156
+ }
157
+ else {
158
+ for (const row of allRows) {
159
+ rows.push(wrapRow(dim(row)));
160
+ }
161
+ }
162
+ rows.push(bottom);
163
+ return rows;
164
+ }