@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
@@ -134,6 +134,8 @@ const SUPERSCRIPT_DIGITS = {
134
134
  * Convert the interior of a LaTeX math expression into readable terminal text.
135
135
  */
136
136
  export function renderLatexExpression(rawExpr) {
137
+ if (typeof rawExpr !== 'string')
138
+ return '';
137
139
  let out = rawExpr.trim();
138
140
  if (!out)
139
141
  return '';
@@ -170,25 +172,25 @@ export function renderLatexExpression(rawExpr) {
170
172
  .replace(/\\%/g, '%')
171
173
  .replace(/\\_/g, '_');
172
174
  // 4. Replace named functions and Greek/math symbols
173
- out = out.replace(/\\([a-zA-Z]+)(\s*)/g, (full, name, trailingSpace) => {
175
+ out = out.replace(/\\([a-zA-Z]+)(\s*)/g, (full, name, trailingSpace, offset, source) => {
174
176
  if (FUNCTION_MACROS.has(name)) {
175
177
  return name + (trailingSpace || '');
176
178
  }
177
- const sym = GREEK_AND_SYMBOLS[name];
179
+ const sym = Object.hasOwn(GREEK_AND_SYMBOLS, name) ? GREEK_AND_SYMBOLS[name] : undefined;
178
180
  if (sym !== undefined) {
179
- // Preserve a space if the symbol is a binary relation/operator and had trailing space,
180
- // or if the next character would otherwise run into an operator.
181
- return sym + (trailingSpace.length > 0 && /^[∈∉⊂⊆⊃⊇∪∩≤≥≠≈≡∼≃≅∝×·±∓÷→←↔⇒⇐⇔↦]$/.test(sym) ? ' ' : '');
181
+ const nextChar = source[offset + full.length] ?? '';
182
+ const suppressSpace = nextChar === '' || /^[,.;:!?)\]}_^]$/.test(nextChar);
183
+ return sym + (trailingSpace.length > 0 && !suppressSpace ? ' ' : '');
182
184
  }
183
185
  return full;
184
186
  });
185
187
  // 5. Simplify braced subscripts and superscripts
186
188
  out = out
187
- .replace(/_\{([a-zA-Z0-9α-ωΑ-Ω+-]+)\}/g, '_$1')
189
+ .replace(/_\{([a-zA-Z0-9α-ωΑ-Ω]+)\}/g, '_$1')
188
190
  .replace(/_\{([^{}]+)\}/g, '_($1)')
189
191
  .replace(/\^\{([0-9])\}/g, (_m, d) => SUPERSCRIPT_DIGITS[d] ?? `^${d}`)
190
192
  .replace(/\^([23])(?![0-9])/g, (_m, d) => SUPERSCRIPT_DIGITS[d] ?? `^${d}`)
191
- .replace(/\^\{([a-zA-Z0-9α-ωΑ-Ω+-]+)\}/g, '^$1')
193
+ .replace(/\^\{([a-zA-Z0-9α-ωΑ-Ω]+)\}/g, '^$1')
192
194
  .replace(/\^\{([^{}]+)\}/g, '^($1)');
193
195
  return out.replace(/\s{2,}/g, ' ').trim();
194
196
  }
@@ -225,19 +227,67 @@ function isLikelyInlineMath(inner) {
225
227
  return true;
226
228
  return false;
227
229
  }
230
+ function hasOddPrecedingBackslashes(text, index) {
231
+ let count = 0;
232
+ for (let i = index - 1; i >= 0 && text.charCodeAt(i) === 92; i--) {
233
+ count++;
234
+ }
235
+ return count % 2 === 1;
236
+ }
237
+ function replaceEscapedMathDelimiters(text, open, close) {
238
+ if (!text.includes(open) || !text.includes(close))
239
+ return text;
240
+ let out = '';
241
+ let cursor = 0;
242
+ while (cursor < text.length) {
243
+ const openIdx = text.indexOf(open, cursor);
244
+ if (openIdx === -1)
245
+ break;
246
+ if (hasOddPrecedingBackslashes(text, openIdx)) {
247
+ out += text.slice(cursor, openIdx + 1);
248
+ cursor = openIdx + 1;
249
+ continue;
250
+ }
251
+ let searchFrom = openIdx + open.length;
252
+ let closeIdx = -1;
253
+ while (searchFrom < text.length) {
254
+ const candidate = text.indexOf(close, searchFrom);
255
+ if (candidate === -1) {
256
+ closeIdx = -1;
257
+ break;
258
+ }
259
+ if (hasOddPrecedingBackslashes(text, candidate)) {
260
+ searchFrom = candidate + 1;
261
+ continue;
262
+ }
263
+ closeIdx = candidate;
264
+ break;
265
+ }
266
+ if (closeIdx === -1) {
267
+ // No unescaped closing delimiter exists anywhere after this point; linear early exit.
268
+ break;
269
+ }
270
+ const expr = text.slice(openIdx + open.length, closeIdx);
271
+ out += text.slice(cursor, openIdx);
272
+ out += expr ? renderLatexExpression(expr) : text.slice(openIdx, closeIdx + close.length);
273
+ cursor = closeIdx + close.length;
274
+ }
275
+ return cursor === 0 ? text : out + text.slice(cursor);
276
+ }
228
277
  /**
229
278
  * Format LaTeX math spans inside a markdown prose line (after code spans and
230
279
  * links have already been stashed).
231
280
  */
232
281
  export function formatMarkdownMath(text) {
233
- if (!text || (!text.includes('$') && !text.includes('\\')))
234
- return text;
282
+ if (typeof text !== 'string' || !text || (!text.includes('$') && !text.includes('\\'))) {
283
+ return typeof text === 'string' ? text : '';
284
+ }
235
285
  let out = text;
236
- // 1. Display math $$...$$
237
- out = out.replace(/\$\$((?:[^$]|\\\$)+?)\$\$/g, (_m, expr) => renderLatexExpression(expr));
238
- // 2. Explicit LaTeX delimiters \[...\] and \(...\)
239
- out = out.replace(/\\\[([\s\S]+?)\\\]/g, (_m, expr) => renderLatexExpression(expr));
240
- out = out.replace(/\\\(([\s\S]+?)\\\)/g, (_m, expr) => renderLatexExpression(expr));
286
+ // 1. Display math $$...$$ (disjoint alternation prevents polynomial ReDoS)
287
+ out = out.replace(/\$\$((?:[^$\\]|\\[\s\S]|\$(?!\$))+?)\$\$/g, (_m, expr) => renderLatexExpression(expr));
288
+ // 2. Explicit LaTeX delimiters \[...\] and \(...\) in guaranteed O(N) time
289
+ out = replaceEscapedMathDelimiters(out, '\\[', '\\]');
290
+ out = replaceEscapedMathDelimiters(out, '\\(', '\\)');
241
291
  // 3. Inline math $...$
242
292
  out = out.replace(/(?<![\\$\w])\$(?!\s)((?:[^$\n\\]|\\.)+?)(?<!\s)\$(?![$\d])/g, (full, expr) => {
243
293
  if (!isLikelyInlineMath(expr))
@@ -138,6 +138,7 @@ const SUPERSCRIPT_DIGITS: Readonly<Record<string, string>> = {
138
138
  * Convert the interior of a LaTeX math expression into readable terminal text.
139
139
  */
140
140
  export function renderLatexExpression(rawExpr: string): string {
141
+ if (typeof rawExpr !== 'string') return '';
141
142
  let out = rawExpr.trim();
142
143
  if (!out) return '';
143
144
 
@@ -178,26 +179,26 @@ export function renderLatexExpression(rawExpr: string): string {
178
179
  .replace(/\\_/g, '_');
179
180
 
180
181
  // 4. Replace named functions and Greek/math symbols
181
- out = out.replace(/\\([a-zA-Z]+)(\s*)/g, (full, name: string, trailingSpace: string) => {
182
+ out = out.replace(/\\([a-zA-Z]+)(\s*)/g, (full, name: string, trailingSpace: string, offset: number, source: string) => {
182
183
  if (FUNCTION_MACROS.has(name)) {
183
184
  return name + (trailingSpace || '');
184
185
  }
185
- const sym = GREEK_AND_SYMBOLS[name];
186
+ const sym = Object.hasOwn(GREEK_AND_SYMBOLS, name) ? GREEK_AND_SYMBOLS[name] : undefined;
186
187
  if (sym !== undefined) {
187
- // Preserve a space if the symbol is a binary relation/operator and had trailing space,
188
- // or if the next character would otherwise run into an operator.
189
- return sym + (trailingSpace.length > 0 && /^[∈∉⊂⊆⊃⊇∪∩≤≥≠≈≡∼≃≅∝×·±∓÷→←↔⇒⇐⇔↦]$/.test(sym) ? ' ' : '');
188
+ const nextChar = source[offset + full.length] ?? '';
189
+ const suppressSpace = nextChar === '' || /^[,.;:!?)\]}_^]$/.test(nextChar);
190
+ return sym + (trailingSpace.length > 0 && !suppressSpace ? ' ' : '');
190
191
  }
191
192
  return full;
192
193
  });
193
194
 
194
195
  // 5. Simplify braced subscripts and superscripts
195
196
  out = out
196
- .replace(/_\{([a-zA-Z0-9α-ωΑ-Ω+-]+)\}/g, '_$1')
197
+ .replace(/_\{([a-zA-Z0-9α-ωΑ-Ω]+)\}/g, '_$1')
197
198
  .replace(/_\{([^{}]+)\}/g, '_($1)')
198
199
  .replace(/\^\{([0-9])\}/g, (_m, d: string) => SUPERSCRIPT_DIGITS[d] ?? `^${d}`)
199
200
  .replace(/\^([23])(?![0-9])/g, (_m, d: string) => SUPERSCRIPT_DIGITS[d] ?? `^${d}`)
200
- .replace(/\^\{([a-zA-Z0-9α-ωΑ-Ω+-]+)\}/g, '^$1')
201
+ .replace(/\^\{([a-zA-Z0-9α-ωΑ-Ω]+)\}/g, '^$1')
201
202
  .replace(/\^\{([^{}]+)\}/g, '^($1)');
202
203
 
203
204
  return out.replace(/\s{2,}/g, ' ').trim();
@@ -233,21 +234,76 @@ function isLikelyInlineMath(inner: string): boolean {
233
234
  return false;
234
235
  }
235
236
 
237
+ function hasOddPrecedingBackslashes(text: string, index: number): boolean {
238
+ let count = 0;
239
+ for (let i = index - 1; i >= 0 && text.charCodeAt(i) === 92; i--) {
240
+ count++;
241
+ }
242
+ return count % 2 === 1;
243
+ }
244
+
245
+ function replaceEscapedMathDelimiters(text: string, open: string, close: string): string {
246
+ if (!text.includes(open) || !text.includes(close)) return text;
247
+
248
+ let out = '';
249
+ let cursor = 0;
250
+
251
+ while (cursor < text.length) {
252
+ const openIdx = text.indexOf(open, cursor);
253
+ if (openIdx === -1) break;
254
+ if (hasOddPrecedingBackslashes(text, openIdx)) {
255
+ out += text.slice(cursor, openIdx + 1);
256
+ cursor = openIdx + 1;
257
+ continue;
258
+ }
259
+
260
+ let searchFrom = openIdx + open.length;
261
+ let closeIdx = -1;
262
+ while (searchFrom < text.length) {
263
+ const candidate = text.indexOf(close, searchFrom);
264
+ if (candidate === -1) {
265
+ closeIdx = -1;
266
+ break;
267
+ }
268
+ if (hasOddPrecedingBackslashes(text, candidate)) {
269
+ searchFrom = candidate + 1;
270
+ continue;
271
+ }
272
+ closeIdx = candidate;
273
+ break;
274
+ }
275
+
276
+ if (closeIdx === -1) {
277
+ // No unescaped closing delimiter exists anywhere after this point; linear early exit.
278
+ break;
279
+ }
280
+
281
+ const expr = text.slice(openIdx + open.length, closeIdx);
282
+ out += text.slice(cursor, openIdx);
283
+ out += expr ? renderLatexExpression(expr) : text.slice(openIdx, closeIdx + close.length);
284
+ cursor = closeIdx + close.length;
285
+ }
286
+
287
+ return cursor === 0 ? text : out + text.slice(cursor);
288
+ }
289
+
236
290
  /**
237
291
  * Format LaTeX math spans inside a markdown prose line (after code spans and
238
292
  * links have already been stashed).
239
293
  */
240
294
  export function formatMarkdownMath(text: string): string {
241
- if (!text || (!text.includes('$') && !text.includes('\\'))) return text;
295
+ if (typeof text !== 'string' || !text || (!text.includes('$') && !text.includes('\\'))) {
296
+ return typeof text === 'string' ? text : '';
297
+ }
242
298
 
243
299
  let out = text;
244
300
 
245
- // 1. Display math $$...$$
246
- out = out.replace(/\$\$((?:[^$]|\\\$)+?)\$\$/g, (_m, expr: string) => renderLatexExpression(expr));
301
+ // 1. Display math $$...$$ (disjoint alternation prevents polynomial ReDoS)
302
+ out = out.replace(/\$\$((?:[^$\\]|\\[\s\S]|\$(?!\$))+?)\$\$/g, (_m, expr: string) => renderLatexExpression(expr));
247
303
 
248
- // 2. Explicit LaTeX delimiters \[...\] and \(...\)
249
- out = out.replace(/\\\[([\s\S]+?)\\\]/g, (_m, expr: string) => renderLatexExpression(expr));
250
- out = out.replace(/\\\(([\s\S]+?)\\\)/g, (_m, expr: string) => renderLatexExpression(expr));
304
+ // 2. Explicit LaTeX delimiters \[...\] and \(...\) in guaranteed O(N) time
305
+ out = replaceEscapedMathDelimiters(out, '\\[', '\\]');
306
+ out = replaceEscapedMathDelimiters(out, '\\(', '\\)');
251
307
 
252
308
  // 3. Inline math $...$
253
309
  out = out.replace(/(?<![\\$\w])\$(?!\s)((?:[^$\n\\]|\\.)+?)(?<!\s)\$(?![$\d])/g, (full, expr: string) => {
@@ -5,20 +5,31 @@ import { HAS_COLOR } from './theme.js';
5
5
  function dimBackdropRow(row) {
6
6
  if (!row || !row.trim())
7
7
  return row;
8
- return `\x1b[2m${row.replace(/\x1b\[0m/g, '\x1b[0m\x1b[2m')}\x1b[0m`;
8
+ return `\x1b[2m${row.replace(/\x1b\[(?:0|22)?m/g, '$&\x1b[2m')}\x1b[0m`;
9
+ }
10
+ function closeSgr(row) {
11
+ return row.includes('\x1b[') && !row.endsWith('\x1b[0m') ? `${row}\x1b[0m` : row;
9
12
  }
10
13
  /**
11
14
  * Overlay a message action menu in the transcript viewport with adaptive,
12
15
  * context-aware positioning and elevated backdrop isolation.
13
16
  */
14
17
  export function placeMessageActionPanel(viewportRows, panel, contentWidth, stageTop, anchorY, count, options) {
15
- if (!panel.length || viewportRows.length < panel.length || contentWidth < 8) {
18
+ if (!Array.isArray(viewportRows) || !Array.isArray(panel)) {
19
+ return { rows: Array.isArray(viewportRows) ? viewportRows : [], layout: null };
20
+ }
21
+ if (!panel.length || viewportRows.length < panel.length || !Number.isFinite(contentWidth) || contentWidth < 8) {
16
22
  return { rows: viewportRows, layout: null };
17
23
  }
24
+ const safeContentWidth = Math.floor(contentWidth);
25
+ const safeStageTop = Number.isFinite(stageTop) ? Math.floor(stageTop) : 0;
26
+ const safeCount = Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0;
18
27
  const totalRows = viewportRows.length;
19
28
  const panelHeight = panel.length;
20
- const width = Math.min(contentWidth, Math.max(...panel.map(visibleWidth)));
21
- const x = Math.max(0, Math.floor((contentWidth - width) / 2));
29
+ const width = Math.min(safeContentWidth, Math.max(0, ...panel.map(r => visibleWidth(r ?? ''))));
30
+ if (width <= 0)
31
+ return { rows: viewportRows, layout: null };
32
+ const x = Math.max(0, Math.floor((safeContentWidth - width) / 2));
22
33
  // Vertical constraints and comfortable ergonomic margins
23
34
  const maxAllowedY = totalRows - panelHeight;
24
35
  const topMargin = Math.max(1, Math.floor(totalRows * 0.05));
@@ -27,9 +38,12 @@ export function placeMessageActionPanel(viewportRows, panel, contentWidth, stage
27
38
  const opticalCenterY = Math.max(topMargin, Math.floor(maxAllowedY * 0.40));
28
39
  let targetY;
29
40
  if (options?.messageBounds) {
30
- const { startRow, endRow } = options.messageBounds;
31
- const msgTop = Math.max(0, Math.min(totalRows - 1, startRow));
32
- const msgBottom = Math.max(0, Math.min(totalRows - 1, endRow));
41
+ const startRow = Number.isFinite(options.messageBounds.startRow) ? Math.floor(options.messageBounds.startRow) : 0;
42
+ const endRow = Number.isFinite(options.messageBounds.endRow) ? Math.floor(options.messageBounds.endRow) : startRow;
43
+ const lo = Math.min(startRow, endRow);
44
+ const hi = Math.max(startRow, endRow);
45
+ const msgTop = Math.max(0, Math.min(totalRows - 1, lo));
46
+ const msgBottom = Math.max(0, Math.min(totalRows - 1, hi));
33
47
  const msgCenter = Math.floor((msgTop + msgBottom) / 2);
34
48
  // If message is near the bottom of viewport (bottom rows or starting below the max panel top):
35
49
  // Never squash the popup against the bottom composer! Float upward into the clear reading zone.
@@ -54,8 +68,8 @@ export function placeMessageActionPanel(viewportRows, panel, contentWidth, stage
54
68
  targetY = Math.round(0.75 * msgIdealY + 0.25 * opticalCenterY);
55
69
  }
56
70
  }
57
- else if (anchorY !== null) {
58
- const anchor = anchorY - stageTop;
71
+ else if (anchorY !== null && Number.isFinite(anchorY)) {
72
+ const anchor = anchorY - safeStageTop;
59
73
  if (anchor >= totalRows - 2) {
60
74
  // Click at the extreme bottom edge: float upward into the reading zone
61
75
  targetY = Math.max(topMargin, Math.min(maxAllowedY - bottomMargin, opticalCenterY + 2));
@@ -68,7 +82,7 @@ export function placeMessageActionPanel(viewportRows, panel, contentWidth, stage
68
82
  else {
69
83
  targetY = opticalCenterY;
70
84
  }
71
- const y = Math.max(0, Math.min(maxAllowedY, targetY));
85
+ const y = Math.max(0, Math.min(maxAllowedY, Number.isFinite(targetY) ? Math.floor(targetY) : opticalCenterY));
72
86
  const shouldDim = options?.dimBackdrop === true;
73
87
  const rows = viewportRows.slice();
74
88
  for (let r = 0; r < rows.length; r++) {
@@ -84,9 +98,10 @@ export function placeMessageActionPanel(viewportRows, panel, contentWidth, stage
84
98
  const leftPrefix = padEnd(truncate(baseRow, x, ''), x);
85
99
  const cardChunk = padEnd(truncate(panel[panelIdx] ?? '', width, ''), width);
86
100
  const rightSuffix = sliceFromColumn(baseRow, x + width);
87
- const styledLeft = shouldDim ? dimBackdropRow(leftPrefix) : leftPrefix;
101
+ const styledLeft = shouldDim ? dimBackdropRow(leftPrefix) : closeSgr(leftPrefix);
102
+ const styledCard = closeSgr(cardChunk);
88
103
  const styledRight = shouldDim ? dimBackdropRow(rightSuffix) : rightSuffix;
89
- rows[r] = `${styledLeft}${cardChunk}${styledRight}`;
104
+ rows[r] = `${styledLeft}${styledCard}${styledRight}`;
90
105
  }
91
- return { rows, layout: { x, y: stageTop + y, width, count } };
106
+ return { rows, layout: { x, y: safeStageTop + y, width, count: safeCount } };
92
107
  }
@@ -21,7 +21,11 @@ export interface MessageActionPlacement {
21
21
 
22
22
  function dimBackdropRow(row: string): string {
23
23
  if (!row || !row.trim()) return row;
24
- return `\x1b[2m${row.replace(/\x1b\[0m/g, '\x1b[0m\x1b[2m')}\x1b[0m`;
24
+ return `\x1b[2m${row.replace(/\x1b\[(?:0|22)?m/g, '$&\x1b[2m')}\x1b[0m`;
25
+ }
26
+
27
+ function closeSgr(row: string): string {
28
+ return row.includes('\x1b[') && !row.endsWith('\x1b[0m') ? `${row}\x1b[0m` : row;
25
29
  }
26
30
 
27
31
  /**
@@ -37,14 +41,21 @@ export function placeMessageActionPanel(
37
41
  count: number,
38
42
  options?: MessageActionPlacementOptions
39
43
  ): MessageActionPlacement {
40
- if (!panel.length || viewportRows.length < panel.length || contentWidth < 8) {
44
+ if (!Array.isArray(viewportRows) || !Array.isArray(panel)) {
45
+ return { rows: Array.isArray(viewportRows) ? viewportRows : [], layout: null };
46
+ }
47
+ if (!panel.length || viewportRows.length < panel.length || !Number.isFinite(contentWidth) || contentWidth < 8) {
41
48
  return { rows: viewportRows, layout: null };
42
49
  }
43
50
 
51
+ const safeContentWidth = Math.floor(contentWidth);
52
+ const safeStageTop = Number.isFinite(stageTop) ? Math.floor(stageTop) : 0;
53
+ const safeCount = Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0;
44
54
  const totalRows = viewportRows.length;
45
55
  const panelHeight = panel.length;
46
- const width = Math.min(contentWidth, Math.max(...panel.map(visibleWidth)));
47
- const x = Math.max(0, Math.floor((contentWidth - width) / 2));
56
+ const width = Math.min(safeContentWidth, Math.max(0, ...panel.map(r => visibleWidth(r ?? ''))));
57
+ if (width <= 0) return { rows: viewportRows, layout: null };
58
+ const x = Math.max(0, Math.floor((safeContentWidth - width) / 2));
48
59
 
49
60
  // Vertical constraints and comfortable ergonomic margins
50
61
  const maxAllowedY = totalRows - panelHeight;
@@ -57,9 +68,12 @@ export function placeMessageActionPanel(
57
68
  let targetY: number;
58
69
 
59
70
  if (options?.messageBounds) {
60
- const { startRow, endRow } = options.messageBounds;
61
- const msgTop = Math.max(0, Math.min(totalRows - 1, startRow));
62
- const msgBottom = Math.max(0, Math.min(totalRows - 1, endRow));
71
+ const startRow = Number.isFinite(options.messageBounds.startRow) ? Math.floor(options.messageBounds.startRow) : 0;
72
+ const endRow = Number.isFinite(options.messageBounds.endRow) ? Math.floor(options.messageBounds.endRow) : startRow;
73
+ const lo = Math.min(startRow, endRow);
74
+ const hi = Math.max(startRow, endRow);
75
+ const msgTop = Math.max(0, Math.min(totalRows - 1, lo));
76
+ const msgBottom = Math.max(0, Math.min(totalRows - 1, hi));
63
77
  const msgCenter = Math.floor((msgTop + msgBottom) / 2);
64
78
 
65
79
  // If message is near the bottom of viewport (bottom rows or starting below the max panel top):
@@ -81,8 +95,8 @@ export function placeMessageActionPanel(
81
95
  const msgIdealY = msgCenter - Math.floor(panelHeight / 2);
82
96
  targetY = Math.round(0.75 * msgIdealY + 0.25 * opticalCenterY);
83
97
  }
84
- } else if (anchorY !== null) {
85
- const anchor = anchorY - stageTop;
98
+ } else if (anchorY !== null && Number.isFinite(anchorY)) {
99
+ const anchor = anchorY - safeStageTop;
86
100
  if (anchor >= totalRows - 2) {
87
101
  // Click at the extreme bottom edge: float upward into the reading zone
88
102
  targetY = Math.max(topMargin, Math.min(maxAllowedY - bottomMargin, opticalCenterY + 2));
@@ -94,7 +108,7 @@ export function placeMessageActionPanel(
94
108
  targetY = opticalCenterY;
95
109
  }
96
110
 
97
- const y = Math.max(0, Math.min(maxAllowedY, targetY));
111
+ const y = Math.max(0, Math.min(maxAllowedY, Number.isFinite(targetY) ? Math.floor(targetY) : opticalCenterY));
98
112
  const shouldDim = options?.dimBackdrop === true;
99
113
  const rows = viewportRows.slice();
100
114
 
@@ -113,11 +127,12 @@ export function placeMessageActionPanel(
113
127
  const cardChunk = padEnd(truncate(panel[panelIdx] ?? '', width, ''), width);
114
128
  const rightSuffix = sliceFromColumn(baseRow, x + width);
115
129
 
116
- const styledLeft = shouldDim ? dimBackdropRow(leftPrefix) : leftPrefix;
130
+ const styledLeft = shouldDim ? dimBackdropRow(leftPrefix) : closeSgr(leftPrefix);
131
+ const styledCard = closeSgr(cardChunk);
117
132
  const styledRight = shouldDim ? dimBackdropRow(rightSuffix) : rightSuffix;
118
133
 
119
- rows[r] = `${styledLeft}${cardChunk}${styledRight}`;
134
+ rows[r] = `${styledLeft}${styledCard}${styledRight}`;
120
135
  }
121
136
 
122
- return { rows, layout: { x, y: stageTop + y, width, count } };
137
+ return { rows, layout: { x, y: safeStageTop + y, width, count: safeCount } };
123
138
  }