@causyne/agent 1.20.112 → 1.20.117

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 (169) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +153 -68
  4. package/src/agentLoop.ts +152 -71
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +37 -9
  8. package/src/browser/causyneBrowser.ts +37 -9
  9. package/src/browser/searchProviders.js +18 -7
  10. package/src/browser/searchProviders.ts +17 -5
  11. package/src/browser/snapshotWindow.js +1 -1
  12. package/src/browser/snapshotWindow.ts +1 -1
  13. package/src/browser/urlPolicy.js +21 -10
  14. package/src/browser/urlPolicy.ts +19 -10
  15. package/src/browser/workspacePreview.js +13 -1
  16. package/src/browser/workspacePreview.ts +11 -1
  17. package/src/cliMode.js +5 -1
  18. package/src/computerUse/visionGrounding.js +31 -27
  19. package/src/computerUse/visionGrounding.ts +27 -27
  20. package/src/continuum/ui/continuumPicker.js +14 -6
  21. package/src/continuum/ui/continuumPicker.ts +13 -6
  22. package/src/continuum/ui/continuumPickerView.js +24 -15
  23. package/src/continuum/ui/continuumPickerView.ts +24 -16
  24. package/src/memory/scopedFacts.js +171 -0
  25. package/src/memory/scopedFacts.ts +214 -0
  26. package/src/memory.d.ts +13 -1
  27. package/src/memory.js +9 -12
  28. package/src/observer/advisory.js +32 -22
  29. package/src/observer/advisory.ts +30 -18
  30. package/src/observer/coldObserver.js +21 -33
  31. package/src/observer/coldObserver.ts +20 -33
  32. package/src/observer/evidence.js +20 -13
  33. package/src/observer/evidence.ts +21 -13
  34. package/src/observer.js +47 -12
  35. package/src/observer.ts +50 -18
  36. package/src/perception.js +124 -3
  37. package/src/perception.ts +128 -4
  38. package/src/planCache.js +17 -3
  39. package/src/planCache.ts +17 -3
  40. package/src/pluginsFactory/discovery.js +28 -16
  41. package/src/pluginsFactory/discovery.ts +29 -16
  42. package/src/pluginsFactory/pluginsFactory.js +213 -38
  43. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  44. package/src/pluginsFactory/strategy.js +26 -16
  45. package/src/pluginsFactory/strategy.ts +34 -19
  46. package/src/pluginsFactory/templates.js +183 -62
  47. package/src/pluginsFactory/templates.ts +174 -54
  48. package/src/smartToolsUse.js +4 -5
  49. package/src/smartToolsUse.ts +4 -6
  50. package/src/taskShape.js +49 -7
  51. package/src/taskShape.ts +55 -7
  52. package/src/timeMachine.js +43 -22
  53. package/src/timeMachine.ts +44 -22
  54. package/src/tool-scripts/desktop_act.applescript +1 -0
  55. package/src/toolPacks.js +27 -5
  56. package/src/toolPacks.ts +32 -5
  57. package/src/tools/computerUse.js +23 -10
  58. package/src/tools/computerUse.ts +19 -8
  59. package/src/tools/desktopAct.js +12 -1
  60. package/src/tools/memoryWrite.js +8 -10
  61. package/src/tools/memoryWrite.ts +13 -11
  62. package/src/tools/pluginsFactory.js +108 -5
  63. package/src/tools/pluginsFactory.ts +115 -5
  64. package/src/tui/CausyneRotor.js +24 -10
  65. package/src/tui/CausyneRotor.ts +25 -10
  66. package/src/tui/activityLayout.js +9 -5
  67. package/src/tui/activityLayout.ts +9 -5
  68. package/src/tui/ask.js +34 -14
  69. package/src/tui/banner.js +55 -18
  70. package/src/tui/banner.ts +52 -17
  71. package/src/tui/block.js +47 -20
  72. package/src/tui/block.ts +54 -27
  73. package/src/tui/chatRenderer.js +139 -84
  74. package/src/tui/chatboxClipboard.js +12 -5
  75. package/src/tui/chatboxClipboard.ts +10 -4
  76. package/src/tui/clipboardImage.js +52 -42
  77. package/src/tui/clipboardImage.ts +50 -39
  78. package/src/tui/clipboardSync.js +12 -1
  79. package/src/tui/clipboardSync.ts +9 -1
  80. package/src/tui/codeProgress.js +60 -28
  81. package/src/tui/codeProgress.ts +60 -27
  82. package/src/tui/codeStreamRenderer.js +94 -23
  83. package/src/tui/codeStreamRenderer.ts +92 -23
  84. package/src/tui/commandPresentation.js +9 -2
  85. package/src/tui/commandPresentation.ts +9 -2
  86. package/src/tui/completion.js +45 -23
  87. package/src/tui/composerControls.js +21 -10
  88. package/src/tui/composerControls.ts +18 -10
  89. package/src/tui/composerGeometry.js +6 -4
  90. package/src/tui/composerGeometry.ts +6 -4
  91. package/src/tui/consoleGuard.js +29 -7
  92. package/src/tui/consoleGuard.ts +28 -7
  93. package/src/tui/dialogs.js +134 -71
  94. package/src/tui/diff.js +8 -4
  95. package/src/tui/history.js +6 -5
  96. package/src/tui/home.js +25 -13
  97. package/src/tui/homeView.js +37 -18
  98. package/src/tui/homeView.ts +38 -18
  99. package/src/tui/inlineSlash.js +6 -5
  100. package/src/tui/inlineSlash.ts +6 -5
  101. package/src/tui/keys.js +36 -18
  102. package/src/tui/layout.js +27 -9
  103. package/src/tui/layout.ts +26 -9
  104. package/src/tui/lineEditor.js +49 -23
  105. package/src/tui/markdownMath.js +64 -14
  106. package/src/tui/markdownMath.ts +69 -13
  107. package/src/tui/messageActionPlacement.js +28 -13
  108. package/src/tui/messageActionPlacement.ts +28 -13
  109. package/src/tui/messageInteraction.js +111 -46
  110. package/src/tui/messageInteraction.ts +115 -47
  111. package/src/tui/modelPicker.js +44 -15
  112. package/src/tui/modelPicker.ts +48 -15
  113. package/src/tui/observerPicker.js +56 -13
  114. package/src/tui/observerPicker.ts +73 -30
  115. package/src/tui/overlay.js +79 -35
  116. package/src/tui/overlay.ts +81 -34
  117. package/src/tui/prompt.js +186 -94
  118. package/src/tui/runningLight.js +1 -1
  119. package/src/tui/runningLight.ts +1 -1
  120. package/src/tui/scrollInteraction.js +64 -36
  121. package/src/tui/scrollInteraction.ts +70 -37
  122. package/src/tui/selectList.js +60 -32
  123. package/src/tui/sessionLayout.js +11 -3
  124. package/src/tui/sessionLayout.ts +10 -3
  125. package/src/tui/sessionPicker.js +74 -46
  126. package/src/tui/sessionPicker.ts +73 -48
  127. package/src/tui/sessionPickerView.js +32 -19
  128. package/src/tui/sessionPickerView.ts +31 -18
  129. package/src/tui/sessionSidebar.js +87 -57
  130. package/src/tui/sessionSidebar.ts +90 -54
  131. package/src/tui/setup.js +28 -3
  132. package/src/tui/setup.ts +27 -3
  133. package/src/tui/skillAuthoring.js +11 -5
  134. package/src/tui/skillAuthoring.ts +11 -5
  135. package/src/tui/smartLinkClick.js +75 -23
  136. package/src/tui/smartLinkClick.ts +86 -26
  137. package/src/tui/stage.js +47 -16
  138. package/src/tui/stage.ts +53 -18
  139. package/src/tui/stageSurface.js +232 -51
  140. package/src/tui/statusLine.js +85 -53
  141. package/src/tui/statusLine.ts +82 -46
  142. package/src/tui/terminalInputFramer.js +5 -2
  143. package/src/tui/text.js +117 -46
  144. package/src/tui/text.ts +113 -43
  145. package/src/tui/textLayout.js +6 -4
  146. package/src/tui/textLayout.ts +11 -5
  147. package/src/tui/theme.js +17 -8
  148. package/src/tui/thinkingBox.js +95 -95
  149. package/src/tui/thinkingBox.ts +105 -80
  150. package/src/tui/toolActivityPolicy.js +8 -1
  151. package/src/tui/toolActivityPolicy.ts +7 -1
  152. package/src/tui/toolDisplay.js +15 -6
  153. package/src/tui/toolDisplay.ts +16 -6
  154. package/src/tui/toolOutputNormalizer.js +16 -3
  155. package/src/tui/toolOutputNormalizer.ts +13 -3
  156. package/src/tui/transcript.js +15 -9
  157. package/src/tui/turnRail.js +176 -80
  158. package/src/tui/turnRail.ts +173 -71
  159. package/src/tui/usageCard.js +136 -80
  160. package/src/tui/usageCard.ts +145 -103
  161. package/src/tui/viewport.js +48 -23
  162. package/src/tui/viewport.ts +48 -27
  163. package/src/tui/viewportAnchor.js +2 -2
  164. package/src/tui/viewportAnchor.ts +2 -2
  165. package/src/tui/workspaceFileIndex.js +8 -6
  166. package/src/tui/workspaceFileIndex.ts +8 -6
  167. package/src/tui/workspaceSwitch.js +13 -10
  168. package/src/tui/workspaceSwitch.ts +11 -7
  169. package/src/types/contracts.ts +3 -0
@@ -7,70 +7,74 @@
7
7
  // Pure TypeScript under strict mode.
8
8
  // @ts-expect-error theme.js has no TypeScript declaration yet.
9
9
  import { paint, dim, GLYPHS, HAS_UNICODE } from './theme.js';
10
- import { padEnd, truncate, visibleWidth, wrapBlock } from './text.js';
10
+ import { padEnd, safeDisplay, truncate, visibleWidth, wrapBlock } from './text.js';
11
11
  import { renderRunningLight } from './runningLight.js';
12
12
  export const DEFAULT_MAX_STREAMING_LINES = 8;
13
13
  export const DEFAULT_MAX_EXPANDED_LINES = 12;
14
+ function clampThinkingWidth(width) {
15
+ const numeric = Number(width ?? 80);
16
+ return Number.isFinite(numeric) ? Math.max(20, Math.floor(numeric)) : 80;
17
+ }
18
+ function clampMaxVisibleLines(value, fallback) {
19
+ if (value === Number.POSITIVE_INFINITY)
20
+ return Number.POSITIVE_INFINITY;
21
+ const numeric = Number(value ?? fallback);
22
+ return Number.isFinite(numeric) ? Math.max(1, Math.floor(numeric)) : fallback;
23
+ }
24
+ function cleanSingleLine(value) {
25
+ return safeDisplay(String(value ?? '')).replace(/\s+/g, ' ').trim();
26
+ }
27
+ function resolveShimmerNowMs(options) {
28
+ if (typeof options.nowMs === 'number' && Number.isFinite(options.nowMs)) {
29
+ return options.nowMs;
30
+ }
31
+ if (typeof options.tick === 'number' && Number.isFinite(options.tick)) {
32
+ return options.tick * 80;
33
+ }
34
+ return 320;
35
+ }
14
36
  /**
15
37
  * Calculates total wrapped lines for reasoning content under the thinking box budget.
16
38
  */
17
39
  export function calculateThinkingLineCount(content, width) {
18
- const text = String(content ?? '').trim();
40
+ const text = safeDisplay(String(content ?? '')).trim();
19
41
  if (!text)
20
42
  return 0;
21
- const safeWidth = Math.max(20, Math.floor(width));
43
+ const safeWidth = clampThinkingWidth(width);
22
44
  const contentBudget = Math.max(10, safeWidth - 4);
23
45
  return wrapBlock(text, contentBudget, { hang: 0 }).length;
24
46
  }
47
+ function stripTrailingEllipsis(value) {
48
+ let text = cleanSingleLine(value);
49
+ while (text.endsWith('…') || text.endsWith('...')) {
50
+ text = (text.endsWith('...') ? text.slice(0, -3) : text.slice(0, -1)).trimEnd();
51
+ }
52
+ return text.trim();
53
+ }
54
+ const COMPLETED_ACTIVITY_LABELS = new Map([
55
+ ['thinking', 'Thought'],
56
+ ['analyzing', 'Analyzed'],
57
+ ['executing', 'Executed'],
58
+ ['editing', 'Edited'],
59
+ ['planning', 'Planned'],
60
+ ['researching', 'Researched'],
61
+ ['synthesizing', 'Synthesized'],
62
+ ['processing', 'Processed']
63
+ ]);
25
64
  /**
26
65
  * Resolves dynamic contextual activity labels for streaming and completed badges.
27
66
  */
28
67
  export function resolveActivityLabels(options) {
29
- const raw = (options.activity || options.title || 'thinking')
30
- .replace(/…|\.\.\.$/, '')
31
- .trim()
32
- .toLowerCase();
33
- let active = options.title ? options.title.trim() : `${raw}…`;
34
- if (!options.title) {
35
- if (raw === 'thinking')
36
- active = 'thinking…';
37
- else if (raw === 'analyzing')
38
- active = 'analyzing…';
39
- else if (raw === 'executing')
40
- active = 'executing…';
41
- else if (raw === 'editing')
42
- active = 'editing…';
43
- else if (raw === 'planning')
44
- active = 'planning…';
45
- else if (raw === 'researching')
46
- active = 'researching…';
47
- else if (raw === 'synthesizing')
48
- active = 'synthesizing…';
49
- else if (raw === 'processing')
50
- active = 'processing…';
51
- else
52
- active = `${raw}…`;
53
- }
54
- let completed = options.completedTitle ? options.completedTitle.trim() : '';
68
+ const safeOptions = options && typeof options === 'object' ? options : {};
69
+ const cleanedActivity = stripTrailingEllipsis(safeOptions.activity);
70
+ const cleanedTitle = stripTrailingEllipsis(safeOptions.title);
71
+ const raw = (cleanedActivity || cleanedTitle || 'thinking').toLowerCase();
72
+ const rawTitle = cleanedTitle && safeOptions.title ? cleanSingleLine(safeOptions.title) : '';
73
+ const active = rawTitle || `${raw}…`;
74
+ let completed = safeOptions.completedTitle ? cleanSingleLine(safeOptions.completedTitle) : '';
55
75
  if (!completed) {
56
- if (raw === 'thinking')
57
- completed = 'Thought';
58
- else if (raw === 'analyzing')
59
- completed = 'Analyzed';
60
- else if (raw === 'executing')
61
- completed = 'Executed';
62
- else if (raw === 'editing')
63
- completed = 'Edited';
64
- else if (raw === 'planning')
65
- completed = 'Planned';
66
- else if (raw === 'researching')
67
- completed = 'Researched';
68
- else if (raw === 'synthesizing')
69
- completed = 'Synthesized';
70
- else if (raw === 'processing')
71
- completed = 'Processed';
72
- else
73
- completed = raw.charAt(0).toUpperCase() + raw.slice(1);
76
+ completed =
77
+ COMPLETED_ACTIVITY_LABELS.get(raw) ?? raw.charAt(0).toUpperCase() + raw.slice(1);
74
78
  }
75
79
  return { activeLabel: active, completedLabel: completed };
76
80
  }
@@ -78,17 +82,15 @@ export function resolveActivityLabels(options) {
78
82
  * Single-line compact badge for collapsed reasoning frames.
79
83
  */
80
84
  export function renderCollapsedThinkingBadge(options, totalLines) {
85
+ options = options && typeof options === 'object' ? options : {};
81
86
  const isStreaming = Boolean(options.streaming);
82
- const durationText = options.durationText ? String(options.durationText).trim() : '';
87
+ const durationText = options.durationText ? cleanSingleLine(options.durationText) : '';
83
88
  const arrow = HAS_UNICODE ? '▸' : '>';
84
89
  const { activeLabel, completedLabel } = resolveActivityLabels(options);
90
+ const safeTotalLines = Number.isFinite(totalLines) ? Math.max(0, Math.floor(totalLines)) : 0;
85
91
  if (isStreaming) {
86
92
  const timePart = durationText ? ` · ${durationText}` : '';
87
- const shimmerNowMs = options.nowMs !== undefined
88
- ? options.nowMs
89
- : options.tick !== undefined
90
- ? options.tick * 80
91
- : 320;
93
+ const shimmerNowMs = resolveShimmerNowMs(options);
92
94
  const styledLabel = renderRunningLight(activeLabel, {
93
95
  nowMs: shimmerNowMs,
94
96
  baseRole: 'warn',
@@ -97,14 +99,14 @@ export function renderCollapsedThinkingBadge(options, totalLines) {
97
99
  return `${paint('warn', arrow)} ${styledLabel}${dim(timePart)} ${dim('· click to expand')}`;
98
100
  }
99
101
  const timePart = durationText ? ` for ${durationText}` : '';
100
- const lineWord = totalLines === 1 ? 'line' : 'lines';
101
- return `${paint('muted', arrow)} ${dim(`${completedLabel}${timePart}`)} ${dim(`(${totalLines} ${lineWord})`)} ${dim('· click to expand')}`;
102
+ const lineWord = safeTotalLines === 1 ? 'line' : 'lines';
103
+ return `${paint('muted', arrow)} ${dim(`${completedLabel}${timePart}`)} ${dim(`(${safeTotalLines} ${lineWord})`)} ${dim('· click to expand')}`;
102
104
  }
103
105
  /**
104
106
  * Builds the top, bottom, and side frame borders for the thinking box.
105
107
  */
106
108
  export function buildThinkingBoxBorders(title, footer, width, role = 'rule') {
107
- const w = Math.max(20, Math.floor(width));
109
+ const w = clampThinkingWidth(width);
108
110
  const inner = w - 2; // total space between left and right outer border corners
109
111
  const h = GLYPHS.hLine || '─';
110
112
  const v = GLYPHS.vLine || '│';
@@ -112,26 +114,23 @@ export function buildThinkingBoxBorders(title, footer, width, role = 'rule') {
112
114
  const tr = GLYPHS.topRight || '╮';
113
115
  const bl = GLYPHS.bottomLeft || '╰';
114
116
  const br = GLYPHS.bottomRight || '╯';
117
+ const buildBorderRow = (leftCorner, rightCorner, rawText) => {
118
+ const cleanText = safeDisplay(String(rawText ?? '')).replace(/[\r\n]+/g, ' ');
119
+ const paddedText = cleanText ? ` ${cleanText} ` : '';
120
+ const textVis = visibleWidth(paddedText);
121
+ const maxTextVis = Math.max(0, inner - 4); // reserve at least 1 leading hLine and 2 trailing hLines
122
+ const safeText = textVis > maxTextVis
123
+ ? (paddedText ? ` ${truncate(cleanText, Math.max(4, maxTextVis - 2), GLYPHS.ellipsis || '…')} ` : '')
124
+ : paddedText;
125
+ const closedText = safeText.includes('\x1b[') && !safeText.endsWith('\x1b[0m') ? `${safeText}\x1b[0m` : safeText;
126
+ const safeTextVis = visibleWidth(closedText);
127
+ const trailCount = Math.max(0, inner - 1 - safeTextVis);
128
+ return paint(role, leftCorner + h) + closedText + paint(role, h.repeat(trailCount) + rightCorner);
129
+ };
115
130
  // --- Top Border ---
116
- const rawTitle = title ? ` ${title} ` : '';
117
- const titleVis = visibleWidth(rawTitle);
118
- const maxTitleVis = Math.max(0, inner - 4); // reserve at least 1 leading hLine and 2 trailing hLines
119
- const safeTitle = titleVis > maxTitleVis ? (rawTitle ? ` ${truncate(title, Math.max(4, maxTitleVis - 2), GLYPHS.ellipsis || '…')} ` : '') : rawTitle;
120
- const safeTitleVis = visibleWidth(safeTitle);
121
- const topLead = h;
122
- const topTrailCount = Math.max(0, inner - 1 - safeTitleVis);
123
- const topTrail = h.repeat(topTrailCount);
124
- const top = paint(role, tl + topLead) + safeTitle + paint(role, topTrail + tr);
131
+ const top = buildBorderRow(tl, tr, title);
125
132
  // --- Bottom Border ---
126
- const rawFooter = footer ? ` ${footer} ` : '';
127
- const footerVis = visibleWidth(rawFooter);
128
- const maxFooterVis = Math.max(0, inner - 4);
129
- const safeFooter = footerVis > maxFooterVis ? (rawFooter ? ` ${truncate(footer, Math.max(4, maxFooterVis - 2), GLYPHS.ellipsis || '…')} ` : '') : rawFooter;
130
- const safeFooterVis = visibleWidth(safeFooter);
131
- const bottomLead = h;
132
- const bottomTrailCount = Math.max(0, inner - 1 - safeFooterVis);
133
- const bottomTrail = h.repeat(bottomTrailCount);
134
- const bottom = paint(role, bl + bottomLead) + safeFooter + paint(role, bottomTrail + br);
133
+ const bottom = buildBorderRow(bl, br, footer);
135
134
  // --- Middle Row Wrapper ---
136
135
  // Format: "│ " + content + " │"
137
136
  // content column width = inner - 2 = w - 4
@@ -139,7 +138,10 @@ export function buildThinkingBoxBorders(title, footer, width, role = 'rule') {
139
138
  const side = paint(role, v);
140
139
  const wrapRow = (line) => {
141
140
  const truncated = truncate(line, contentWidth, GLYPHS.ellipsis || '…');
142
- const padded = padEnd(truncated, contentWidth);
141
+ const closed = truncated.includes('\x1b[') && !truncated.endsWith('\x1b[0m')
142
+ ? `${truncated}\x1b[0m`
143
+ : truncated;
144
+ const padded = padEnd(closed, contentWidth);
143
145
  return `${side} ${padded} ${side}`;
144
146
  };
145
147
  return { top, bottom, wrapRow };
@@ -148,13 +150,14 @@ export function buildThinkingBoxBorders(title, footer, width, role = 'rule') {
148
150
  * Render a complete thinking frame (either compact collapsed badge or expanded box).
149
151
  */
150
152
  export function renderThinkingFrame(content, options = {}) {
151
- const text = String(content ?? '').trim();
153
+ const text = safeDisplay(String(content ?? '')).trim();
152
154
  if (!text)
153
155
  return [];
154
- const width = Math.max(20, Math.floor(options.width ?? 80));
156
+ options = options && typeof options === 'object' ? options : {};
157
+ const width = clampThinkingWidth(options.width);
155
158
  const isStreaming = Boolean(options.streaming);
156
159
  const isCollapsed = Boolean(options.collapsed);
157
- const durationText = options.durationText ? String(options.durationText).trim() : '';
160
+ const durationText = options.durationText ? cleanSingleLine(options.durationText) : '';
158
161
  // Wrap lines for inner box width (w - 4) with zero hanging indent
159
162
  const contentBudget = Math.max(10, width - 4);
160
163
  const allRows = wrapBlock(text, contentBudget, { hang: 0 });
@@ -167,14 +170,10 @@ export function renderThinkingFrame(content, options = {}) {
167
170
  const collapseIndicator = HAS_UNICODE ? '▾' : 'v';
168
171
  const collapseHint = dim(`${collapseIndicator} click to collapse`);
169
172
  if (isStreaming) {
170
- const maxLines = options.maxVisibleLines ?? DEFAULT_MAX_STREAMING_LINES;
173
+ const maxLines = clampMaxVisibleLines(options.maxVisibleLines, DEFAULT_MAX_STREAMING_LINES);
171
174
  const timePart = durationText ? ` · ${durationText}` : '';
172
175
  const { activeLabel } = resolveActivityLabels(options);
173
- const shimmerNowMs = options.nowMs !== undefined
174
- ? options.nowMs
175
- : options.tick !== undefined
176
- ? options.tick * 80
177
- : 320;
176
+ const shimmerNowMs = resolveShimmerNowMs(options);
178
177
  const styledActiveLabel = renderRunningLight(activeLabel, {
179
178
  nowMs: shimmerNowMs,
180
179
  baseRole: 'warn',
@@ -195,12 +194,14 @@ export function renderThinkingFrame(content, options = {}) {
195
194
  return wrapRow(shimmered);
196
195
  };
197
196
  if (totalLines > maxLines) {
198
- const hiddenCount = totalLines - (maxLines - 1);
197
+ const tailCount = Math.max(1, maxLines - 1);
198
+ const hiddenCount = Math.max(0, totalLines - tailCount);
199
199
  const scrollIndicator = HAS_UNICODE ? '↑' : '^';
200
- const activityWord = options.activity || options.title ? `${(options.activity || options.title || '').replace(/…|\.\.\.$/, '').trim()} ` : 'thinking ';
200
+ const cleanedLabel = stripTrailingEllipsis(options.activity) || stripTrailingEllipsis(options.title) || 'thinking';
201
+ const activityWord = `${cleanedLabel} `;
201
202
  const hiddenNotice = `${paint('rule', scrollIndicator)} ${dim(`${hiddenCount} earlier ${activityWord}line${hiddenCount === 1 ? '' : 's'} scrolled`)}`;
202
203
  rows.push(wrapRow(hiddenNotice));
203
- const tailRows = allRows.slice(totalLines - (maxLines - 1));
204
+ const tailRows = allRows.slice(totalLines - tailCount);
204
205
  for (let i = 0; i < tailRows.length; i++) {
205
206
  rows.push(renderStreamingRow(tailRows[i], i === tailRows.length - 1));
206
207
  }
@@ -214,21 +215,20 @@ export function renderThinkingFrame(content, options = {}) {
214
215
  return rows;
215
216
  }
216
217
  // Completed Expanded Mode
217
- const maxLines = options.maxVisibleLines ?? DEFAULT_MAX_EXPANDED_LINES;
218
+ const maxLines = clampMaxVisibleLines(options.maxVisibleLines, DEFAULT_MAX_EXPANDED_LINES);
218
219
  const timePart = durationText ? ` · ${durationText}` : '';
219
- const raw = (options.activity || options.title || 'thinking')
220
- .replace(/…|\.\.\.$/, '')
221
- .trim()
222
- .toLowerCase();
223
- const expandedTitleLabel = options.completedTitle
224
- ? options.completedTitle.toLowerCase()
220
+ const raw = (stripTrailingEllipsis(options.activity) || stripTrailingEllipsis(options.title) || 'thinking').toLowerCase();
221
+ const trimmedCompleted = options.completedTitle ? cleanSingleLine(options.completedTitle) : '';
222
+ const expandedTitleLabel = trimmedCompleted
223
+ ? trimmedCompleted.toLowerCase()
225
224
  : (raw === 'thinking' ? 'thinking' : raw);
226
225
  const title = `${paint('muted', expandedTitleLabel)}${dim(timePart)} ${dim(`(${totalLines} line${totalLines === 1 ? '' : 's'})`)}`;
227
226
  const { top, bottom, wrapRow } = buildThinkingBoxBorders(title, collapseHint, width, 'rule');
228
227
  const rows = [top];
229
228
  if (totalLines > maxLines) {
230
229
  const limit = Math.max(0, totalLines - maxLines);
231
- const start = Math.max(0, Math.min(limit, Math.floor(options.startLine ?? 0)));
230
+ const rawStart = Number(options.startLine ?? 0);
231
+ const start = Math.max(0, Math.min(limit, Number.isFinite(rawStart) ? Math.floor(rawStart) : 0));
232
232
  const visible = allRows.slice(start, start + maxLines);
233
233
  for (const row of visible) {
234
234
  rows.push(wrapRow(dim(row)));
@@ -8,7 +8,7 @@
8
8
 
9
9
  // @ts-expect-error theme.js has no TypeScript declaration yet.
10
10
  import { paint, dim, GLYPHS, HAS_UNICODE } from './theme.js';
11
- import { padEnd, truncate, visibleWidth, wrapBlock } from './text.js';
11
+ import { padEnd, safeDisplay, truncate, visibleWidth, wrapBlock } from './text.js';
12
12
  import { renderRunningLight } from './runningLight.js';
13
13
 
14
14
  export interface ThinkingFrameOptions {
@@ -29,17 +29,61 @@ export interface ThinkingFrameOptions {
29
29
  export const DEFAULT_MAX_STREAMING_LINES = 8;
30
30
  export const DEFAULT_MAX_EXPANDED_LINES = 12;
31
31
 
32
+ function clampThinkingWidth(width: number | undefined): number {
33
+ const numeric = Number(width ?? 80);
34
+ return Number.isFinite(numeric) ? Math.max(20, Math.floor(numeric)) : 80;
35
+ }
36
+
37
+ function clampMaxVisibleLines(value: number | undefined, fallback: number): number {
38
+ if (value === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY;
39
+ const numeric = Number(value ?? fallback);
40
+ return Number.isFinite(numeric) ? Math.max(1, Math.floor(numeric)) : fallback;
41
+ }
42
+
43
+ function cleanSingleLine(value: string | undefined): string {
44
+ return safeDisplay(String(value ?? '')).replace(/\s+/g, ' ').trim();
45
+ }
46
+
47
+ function resolveShimmerNowMs(options: ThinkingFrameOptions): number {
48
+ if (typeof options.nowMs === 'number' && Number.isFinite(options.nowMs)) {
49
+ return options.nowMs;
50
+ }
51
+ if (typeof options.tick === 'number' && Number.isFinite(options.tick)) {
52
+ return options.tick * 80;
53
+ }
54
+ return 320;
55
+ }
56
+
32
57
  /**
33
58
  * Calculates total wrapped lines for reasoning content under the thinking box budget.
34
59
  */
35
60
  export function calculateThinkingLineCount(content: string, width: number): number {
36
- const text = String(content ?? '').trim();
61
+ const text = safeDisplay(String(content ?? '')).trim();
37
62
  if (!text) return 0;
38
- const safeWidth = Math.max(20, Math.floor(width));
63
+ const safeWidth = clampThinkingWidth(width);
39
64
  const contentBudget = Math.max(10, safeWidth - 4);
40
65
  return wrapBlock(text, contentBudget, { hang: 0 }).length;
41
66
  }
42
67
 
68
+ function stripTrailingEllipsis(value: string | undefined): string {
69
+ let text = cleanSingleLine(value);
70
+ while (text.endsWith('…') || text.endsWith('...')) {
71
+ text = (text.endsWith('...') ? text.slice(0, -3) : text.slice(0, -1)).trimEnd();
72
+ }
73
+ return text.trim();
74
+ }
75
+
76
+ const COMPLETED_ACTIVITY_LABELS = new Map<string, string>([
77
+ ['thinking', 'Thought'],
78
+ ['analyzing', 'Analyzed'],
79
+ ['executing', 'Executed'],
80
+ ['editing', 'Edited'],
81
+ ['planning', 'Planned'],
82
+ ['researching', 'Researched'],
83
+ ['synthesizing', 'Synthesized'],
84
+ ['processing', 'Processed']
85
+ ]);
86
+
43
87
  /**
44
88
  * Resolves dynamic contextual activity labels for streaming and completed badges.
45
89
  */
@@ -47,35 +91,18 @@ export function resolveActivityLabels(options: ThinkingFrameOptions): {
47
91
  activeLabel: string;
48
92
  completedLabel: string;
49
93
  } {
50
- const raw = (options.activity || options.title || 'thinking')
51
- .replace(/…|\.\.\.$/, '')
52
- .trim()
53
- .toLowerCase();
54
-
55
- let active = options.title ? options.title.trim() : `${raw}…`;
56
- if (!options.title) {
57
- if (raw === 'thinking') active = 'thinking…';
58
- else if (raw === 'analyzing') active = 'analyzing…';
59
- else if (raw === 'executing') active = 'executing…';
60
- else if (raw === 'editing') active = 'editing…';
61
- else if (raw === 'planning') active = 'planning…';
62
- else if (raw === 'researching') active = 'researching…';
63
- else if (raw === 'synthesizing') active = 'synthesizing…';
64
- else if (raw === 'processing') active = 'processing…';
65
- else active = `${raw}…`;
66
- }
94
+ const safeOptions: ThinkingFrameOptions = options && typeof options === 'object' ? options : {};
95
+ const cleanedActivity = stripTrailingEllipsis(safeOptions.activity);
96
+ const cleanedTitle = stripTrailingEllipsis(safeOptions.title);
97
+ const raw = (cleanedActivity || cleanedTitle || 'thinking').toLowerCase();
67
98
 
68
- let completed = options.completedTitle ? options.completedTitle.trim() : '';
99
+ const rawTitle = cleanedTitle && safeOptions.title ? cleanSingleLine(safeOptions.title) : '';
100
+ const active = rawTitle || `${raw}…`;
101
+
102
+ let completed = safeOptions.completedTitle ? cleanSingleLine(safeOptions.completedTitle) : '';
69
103
  if (!completed) {
70
- if (raw === 'thinking') completed = 'Thought';
71
- else if (raw === 'analyzing') completed = 'Analyzed';
72
- else if (raw === 'executing') completed = 'Executed';
73
- else if (raw === 'editing') completed = 'Edited';
74
- else if (raw === 'planning') completed = 'Planned';
75
- else if (raw === 'researching') completed = 'Researched';
76
- else if (raw === 'synthesizing') completed = 'Synthesized';
77
- else if (raw === 'processing') completed = 'Processed';
78
- else completed = raw.charAt(0).toUpperCase() + raw.slice(1);
104
+ completed =
105
+ COMPLETED_ACTIVITY_LABELS.get(raw) ?? raw.charAt(0).toUpperCase() + raw.slice(1);
79
106
  }
80
107
 
81
108
  return { activeLabel: active, completedLabel: completed };
@@ -88,18 +115,16 @@ export function renderCollapsedThinkingBadge(
88
115
  options: ThinkingFrameOptions,
89
116
  totalLines: number
90
117
  ): string {
118
+ options = options && typeof options === 'object' ? options : {};
91
119
  const isStreaming = Boolean(options.streaming);
92
- const durationText = options.durationText ? String(options.durationText).trim() : '';
120
+ const durationText = options.durationText ? cleanSingleLine(options.durationText) : '';
93
121
  const arrow = HAS_UNICODE ? '▸' : '>';
94
122
  const { activeLabel, completedLabel } = resolveActivityLabels(options);
123
+ const safeTotalLines = Number.isFinite(totalLines) ? Math.max(0, Math.floor(totalLines)) : 0;
95
124
 
96
125
  if (isStreaming) {
97
126
  const timePart = durationText ? ` · ${durationText}` : '';
98
- const shimmerNowMs = options.nowMs !== undefined
99
- ? options.nowMs
100
- : options.tick !== undefined
101
- ? options.tick * 80
102
- : 320;
127
+ const shimmerNowMs = resolveShimmerNowMs(options);
103
128
  const styledLabel = renderRunningLight(activeLabel, {
104
129
  nowMs: shimmerNowMs,
105
130
  baseRole: 'warn',
@@ -109,8 +134,8 @@ export function renderCollapsedThinkingBadge(
109
134
  }
110
135
 
111
136
  const timePart = durationText ? ` for ${durationText}` : '';
112
- const lineWord = totalLines === 1 ? 'line' : 'lines';
113
- return `${paint('muted', arrow)} ${dim(`${completedLabel}${timePart}`)} ${dim(`(${totalLines} ${lineWord})`)} ${dim('· click to expand')}`;
137
+ const lineWord = safeTotalLines === 1 ? 'line' : 'lines';
138
+ return `${paint('muted', arrow)} ${dim(`${completedLabel}${timePart}`)} ${dim(`(${safeTotalLines} ${lineWord})`)} ${dim('· click to expand')}`;
114
139
  }
115
140
 
116
141
  /**
@@ -126,7 +151,7 @@ export function buildThinkingBoxBorders(
126
151
  bottom: string;
127
152
  wrapRow: (line: string) => string;
128
153
  } {
129
- const w = Math.max(20, Math.floor(width));
154
+ const w = clampThinkingWidth(width);
130
155
  const inner = w - 2; // total space between left and right outer border corners
131
156
 
132
157
  const h = GLYPHS.hLine || '─';
@@ -136,29 +161,27 @@ export function buildThinkingBoxBorders(
136
161
  const bl = GLYPHS.bottomLeft || '╰';
137
162
  const br = GLYPHS.bottomRight || '╯';
138
163
 
139
- // --- Top Border ---
140
- const rawTitle = title ? ` ${title} ` : '';
141
- const titleVis = visibleWidth(rawTitle);
142
- const maxTitleVis = Math.max(0, inner - 4); // reserve at least 1 leading hLine and 2 trailing hLines
143
- const safeTitle = titleVis > maxTitleVis ? (rawTitle ? ` ${truncate(title, Math.max(4, maxTitleVis - 2), GLYPHS.ellipsis || '…')} ` : '') : rawTitle;
144
- const safeTitleVis = visibleWidth(safeTitle);
164
+ const buildBorderRow = (leftCorner: string, rightCorner: string, rawText: unknown): string => {
165
+ const cleanText = safeDisplay(String(rawText ?? '')).replace(/[\r\n]+/g, ' ');
166
+ const paddedText = cleanText ? ` ${cleanText} ` : '';
167
+ const textVis = visibleWidth(paddedText);
168
+ const maxTextVis = Math.max(0, inner - 4); // reserve at least 1 leading hLine and 2 trailing hLines
169
+ const safeText =
170
+ textVis > maxTextVis
171
+ ? (paddedText ? ` ${truncate(cleanText, Math.max(4, maxTextVis - 2), GLYPHS.ellipsis || '…')} ` : '')
172
+ : paddedText;
173
+ const closedText =
174
+ safeText.includes('\x1b[') && !safeText.endsWith('\x1b[0m') ? `${safeText}\x1b[0m` : safeText;
175
+ const safeTextVis = visibleWidth(closedText);
176
+ const trailCount = Math.max(0, inner - 1 - safeTextVis);
177
+ return paint(role, leftCorner + h) + closedText + paint(role, h.repeat(trailCount) + rightCorner);
178
+ };
145
179
 
146
- const topLead = h;
147
- const topTrailCount = Math.max(0, inner - 1 - safeTitleVis);
148
- const topTrail = h.repeat(topTrailCount);
149
- const top = paint(role, tl + topLead) + safeTitle + paint(role, topTrail + tr);
180
+ // --- Top Border ---
181
+ const top = buildBorderRow(tl, tr, title);
150
182
 
151
183
  // --- Bottom Border ---
152
- const rawFooter = footer ? ` ${footer} ` : '';
153
- const footerVis = visibleWidth(rawFooter);
154
- const maxFooterVis = Math.max(0, inner - 4);
155
- const safeFooter = footerVis > maxFooterVis ? (rawFooter ? ` ${truncate(footer, Math.max(4, maxFooterVis - 2), GLYPHS.ellipsis || '…')} ` : '') : rawFooter;
156
- const safeFooterVis = visibleWidth(safeFooter);
157
-
158
- const bottomLead = h;
159
- const bottomTrailCount = Math.max(0, inner - 1 - safeFooterVis);
160
- const bottomTrail = h.repeat(bottomTrailCount);
161
- const bottom = paint(role, bl + bottomLead) + safeFooter + paint(role, bottomTrail + br);
184
+ const bottom = buildBorderRow(bl, br, footer);
162
185
 
163
186
  // --- Middle Row Wrapper ---
164
187
  // Format: "│ " + content + " │"
@@ -168,7 +191,11 @@ export function buildThinkingBoxBorders(
168
191
 
169
192
  const wrapRow = (line: string): string => {
170
193
  const truncated = truncate(line, contentWidth, GLYPHS.ellipsis || '…');
171
- const padded = padEnd(truncated, contentWidth);
194
+ const closed =
195
+ truncated.includes('\x1b[') && !truncated.endsWith('\x1b[0m')
196
+ ? `${truncated}\x1b[0m`
197
+ : truncated;
198
+ const padded = padEnd(closed, contentWidth);
172
199
  return `${side} ${padded} ${side}`;
173
200
  };
174
201
 
@@ -182,13 +209,14 @@ export function renderThinkingFrame(
182
209
  content: string,
183
210
  options: ThinkingFrameOptions = {}
184
211
  ): string[] {
185
- const text = String(content ?? '').trim();
212
+ const text = safeDisplay(String(content ?? '')).trim();
186
213
  if (!text) return [];
187
214
 
188
- const width = Math.max(20, Math.floor(options.width ?? 80));
215
+ options = options && typeof options === 'object' ? options : {};
216
+ const width = clampThinkingWidth(options.width);
189
217
  const isStreaming = Boolean(options.streaming);
190
218
  const isCollapsed = Boolean(options.collapsed);
191
- const durationText = options.durationText ? String(options.durationText).trim() : '';
219
+ const durationText = options.durationText ? cleanSingleLine(options.durationText) : '';
192
220
 
193
221
  // Wrap lines for inner box width (w - 4) with zero hanging indent
194
222
  const contentBudget = Math.max(10, width - 4);
@@ -205,14 +233,10 @@ export function renderThinkingFrame(
205
233
  const collapseHint = dim(`${collapseIndicator} click to collapse`);
206
234
 
207
235
  if (isStreaming) {
208
- const maxLines = options.maxVisibleLines ?? DEFAULT_MAX_STREAMING_LINES;
236
+ const maxLines = clampMaxVisibleLines(options.maxVisibleLines, DEFAULT_MAX_STREAMING_LINES);
209
237
  const timePart = durationText ? ` · ${durationText}` : '';
210
238
  const { activeLabel } = resolveActivityLabels(options);
211
- const shimmerNowMs = options.nowMs !== undefined
212
- ? options.nowMs
213
- : options.tick !== undefined
214
- ? options.tick * 80
215
- : 320;
239
+ const shimmerNowMs = resolveShimmerNowMs(options);
216
240
  const styledActiveLabel = renderRunningLight(activeLabel, {
217
241
  nowMs: shimmerNowMs,
218
242
  baseRole: 'warn',
@@ -235,13 +259,15 @@ export function renderThinkingFrame(
235
259
  };
236
260
 
237
261
  if (totalLines > maxLines) {
238
- const hiddenCount = totalLines - (maxLines - 1);
262
+ const tailCount = Math.max(1, maxLines - 1);
263
+ const hiddenCount = Math.max(0, totalLines - tailCount);
239
264
  const scrollIndicator = HAS_UNICODE ? '↑' : '^';
240
- const activityWord = options.activity || options.title ? `${(options.activity || options.title || '').replace(/…|\.\.\.$/, '').trim()} ` : 'thinking ';
265
+ const cleanedLabel = stripTrailingEllipsis(options.activity) || stripTrailingEllipsis(options.title) || 'thinking';
266
+ const activityWord = `${cleanedLabel} `;
241
267
  const hiddenNotice = `${paint('rule', scrollIndicator)} ${dim(`${hiddenCount} earlier ${activityWord}line${hiddenCount === 1 ? '' : 's'} scrolled`)}`;
242
268
  rows.push(wrapRow(hiddenNotice));
243
269
 
244
- const tailRows = allRows.slice(totalLines - (maxLines - 1));
270
+ const tailRows = allRows.slice(totalLines - tailCount);
245
271
  for (let i = 0; i < tailRows.length; i++) {
246
272
  rows.push(renderStreamingRow(tailRows[i]!, i === tailRows.length - 1));
247
273
  }
@@ -256,14 +282,12 @@ export function renderThinkingFrame(
256
282
  }
257
283
 
258
284
  // Completed Expanded Mode
259
- const maxLines = options.maxVisibleLines ?? DEFAULT_MAX_EXPANDED_LINES;
285
+ const maxLines = clampMaxVisibleLines(options.maxVisibleLines, DEFAULT_MAX_EXPANDED_LINES);
260
286
  const timePart = durationText ? ` · ${durationText}` : '';
261
- const raw = (options.activity || options.title || 'thinking')
262
- .replace(/…|\.\.\.$/, '')
263
- .trim()
264
- .toLowerCase();
265
- const expandedTitleLabel = options.completedTitle
266
- ? options.completedTitle.toLowerCase()
287
+ const raw = (stripTrailingEllipsis(options.activity) || stripTrailingEllipsis(options.title) || 'thinking').toLowerCase();
288
+ const trimmedCompleted = options.completedTitle ? cleanSingleLine(options.completedTitle) : '';
289
+ const expandedTitleLabel = trimmedCompleted
290
+ ? trimmedCompleted.toLowerCase()
267
291
  : (raw === 'thinking' ? 'thinking' : raw);
268
292
  const title = `${paint('muted', expandedTitleLabel)}${dim(timePart)} ${dim(`(${totalLines} line${totalLines === 1 ? '' : 's'})`)}`;
269
293
 
@@ -272,7 +296,8 @@ export function renderThinkingFrame(
272
296
 
273
297
  if (totalLines > maxLines) {
274
298
  const limit = Math.max(0, totalLines - maxLines);
275
- const start = Math.max(0, Math.min(limit, Math.floor(options.startLine ?? 0)));
299
+ const rawStart = Number(options.startLine ?? 0);
300
+ const start = Math.max(0, Math.min(limit, Number.isFinite(rawStart) ? Math.floor(rawStart) : 0));
276
301
  const visible = allRows.slice(start, start + maxLines);
277
302
 
278
303
  for (const row of visible) {
@@ -25,8 +25,15 @@ export function compactSuccessfulToolResult(stepCount, result, tail, toolName) {
25
25
  if (tail.meta.step !== stepCount || String(tail.meta.tool ?? '') !== String(toolName ?? ''))
26
26
  return false;
27
27
  for (const [key, value] of Object.entries(record)) {
28
- if (METADATA_ONLY.has(key))
28
+ if (METADATA_ONLY.has(key)) {
29
+ if ((key === 'exitCode' || key === 'exit_code') && value != null
30
+ && (typeof value !== 'number' || !Number.isFinite(value) || value !== 0))
31
+ return false;
32
+ if ((key === 'statusCode' || key === 'status_code') && value != null
33
+ && (typeof value !== 'number' || !Number.isFinite(value) || value < 200 || value >= 400))
34
+ return false;
29
35
  continue;
36
+ }
30
37
  if (value == null || value === '' || (Array.isArray(value) && value.length === 0))
31
38
  continue;
32
39
  return false;
@@ -34,7 +34,13 @@ export function compactSuccessfulToolResult(
34
34
  if (tail.meta.step !== stepCount || String(tail.meta.tool ?? '') !== String(toolName ?? '')) return false;
35
35
 
36
36
  for (const [key, value] of Object.entries(record)) {
37
- if (METADATA_ONLY.has(key)) continue;
37
+ if (METADATA_ONLY.has(key)) {
38
+ if ((key === 'exitCode' || key === 'exit_code') && value != null
39
+ && (typeof value !== 'number' || !Number.isFinite(value) || value !== 0)) return false;
40
+ if ((key === 'statusCode' || key === 'status_code') && value != null
41
+ && (typeof value !== 'number' || !Number.isFinite(value) || value < 200 || value >= 400)) return false;
42
+ continue;
43
+ }
38
44
  if (value == null || value === '' || (Array.isArray(value) && value.length === 0)) continue;
39
45
  return false;
40
46
  }