@causyne/agent 1.20.112 → 1.20.116

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 (151) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +72 -37
  4. package/src/agentLoop.ts +70 -38
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +7 -2
  8. package/src/browser/causyneBrowser.ts +8 -2
  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/computerUse/visionGrounding.js +31 -27
  18. package/src/computerUse/visionGrounding.ts +27 -27
  19. package/src/continuum/ui/continuumPicker.js +14 -6
  20. package/src/continuum/ui/continuumPicker.ts +13 -6
  21. package/src/continuum/ui/continuumPickerView.js +24 -15
  22. package/src/continuum/ui/continuumPickerView.ts +24 -16
  23. package/src/observer/advisory.js +32 -22
  24. package/src/observer/advisory.ts +30 -18
  25. package/src/observer/coldObserver.js +21 -33
  26. package/src/observer/coldObserver.ts +20 -33
  27. package/src/observer/evidence.js +20 -13
  28. package/src/observer/evidence.ts +21 -13
  29. package/src/observer.js +47 -12
  30. package/src/observer.ts +50 -18
  31. package/src/pluginsFactory/discovery.js +28 -16
  32. package/src/pluginsFactory/discovery.ts +29 -16
  33. package/src/pluginsFactory/pluginsFactory.js +213 -38
  34. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  35. package/src/pluginsFactory/strategy.js +26 -16
  36. package/src/pluginsFactory/strategy.ts +34 -19
  37. package/src/pluginsFactory/templates.js +183 -62
  38. package/src/pluginsFactory/templates.ts +174 -54
  39. package/src/timeMachine.js +43 -22
  40. package/src/timeMachine.ts +44 -22
  41. package/src/tool-scripts/desktop_act.applescript +1 -0
  42. package/src/tools/computerUse.js +23 -10
  43. package/src/tools/computerUse.ts +19 -8
  44. package/src/tools/desktopAct.js +12 -1
  45. package/src/tools/pluginsFactory.js +108 -5
  46. package/src/tools/pluginsFactory.ts +115 -5
  47. package/src/tui/CausyneRotor.js +24 -10
  48. package/src/tui/CausyneRotor.ts +25 -10
  49. package/src/tui/activityLayout.js +9 -5
  50. package/src/tui/activityLayout.ts +9 -5
  51. package/src/tui/ask.js +34 -14
  52. package/src/tui/banner.js +55 -18
  53. package/src/tui/banner.ts +52 -17
  54. package/src/tui/block.js +47 -20
  55. package/src/tui/block.ts +54 -27
  56. package/src/tui/chatRenderer.js +135 -83
  57. package/src/tui/chatboxClipboard.js +12 -5
  58. package/src/tui/chatboxClipboard.ts +10 -4
  59. package/src/tui/clipboardImage.js +52 -42
  60. package/src/tui/clipboardImage.ts +50 -39
  61. package/src/tui/clipboardSync.js +12 -1
  62. package/src/tui/clipboardSync.ts +9 -1
  63. package/src/tui/codeProgress.js +57 -26
  64. package/src/tui/codeProgress.ts +57 -25
  65. package/src/tui/codeStreamRenderer.js +59 -14
  66. package/src/tui/codeStreamRenderer.ts +58 -14
  67. package/src/tui/commandPresentation.js +9 -2
  68. package/src/tui/commandPresentation.ts +9 -2
  69. package/src/tui/completion.js +45 -23
  70. package/src/tui/composerControls.js +21 -10
  71. package/src/tui/composerControls.ts +18 -10
  72. package/src/tui/composerGeometry.js +6 -4
  73. package/src/tui/composerGeometry.ts +6 -4
  74. package/src/tui/consoleGuard.js +29 -7
  75. package/src/tui/consoleGuard.ts +28 -7
  76. package/src/tui/dialogs.js +134 -71
  77. package/src/tui/diff.js +8 -4
  78. package/src/tui/history.js +6 -5
  79. package/src/tui/home.js +25 -13
  80. package/src/tui/homeView.js +37 -18
  81. package/src/tui/homeView.ts +38 -18
  82. package/src/tui/inlineSlash.js +6 -5
  83. package/src/tui/inlineSlash.ts +6 -5
  84. package/src/tui/keys.js +33 -17
  85. package/src/tui/layout.js +27 -9
  86. package/src/tui/layout.ts +26 -9
  87. package/src/tui/lineEditor.js +49 -23
  88. package/src/tui/markdownMath.js +64 -14
  89. package/src/tui/markdownMath.ts +69 -13
  90. package/src/tui/messageActionPlacement.js +28 -13
  91. package/src/tui/messageActionPlacement.ts +28 -13
  92. package/src/tui/messageInteraction.js +111 -46
  93. package/src/tui/messageInteraction.ts +115 -47
  94. package/src/tui/modelPicker.js +44 -15
  95. package/src/tui/modelPicker.ts +48 -15
  96. package/src/tui/observerPicker.js +56 -13
  97. package/src/tui/observerPicker.ts +73 -30
  98. package/src/tui/overlay.js +79 -35
  99. package/src/tui/overlay.ts +81 -34
  100. package/src/tui/prompt.js +162 -94
  101. package/src/tui/runningLight.js +1 -1
  102. package/src/tui/runningLight.ts +1 -1
  103. package/src/tui/scrollInteraction.js +64 -36
  104. package/src/tui/scrollInteraction.ts +70 -37
  105. package/src/tui/selectList.js +60 -32
  106. package/src/tui/sessionLayout.js +11 -3
  107. package/src/tui/sessionLayout.ts +10 -3
  108. package/src/tui/sessionPicker.js +74 -46
  109. package/src/tui/sessionPicker.ts +73 -48
  110. package/src/tui/sessionPickerView.js +32 -19
  111. package/src/tui/sessionPickerView.ts +31 -18
  112. package/src/tui/sessionSidebar.js +87 -57
  113. package/src/tui/sessionSidebar.ts +90 -54
  114. package/src/tui/setup.js +28 -3
  115. package/src/tui/setup.ts +27 -3
  116. package/src/tui/skillAuthoring.js +11 -5
  117. package/src/tui/skillAuthoring.ts +11 -5
  118. package/src/tui/smartLinkClick.js +75 -23
  119. package/src/tui/smartLinkClick.ts +86 -26
  120. package/src/tui/stage.js +47 -16
  121. package/src/tui/stage.ts +53 -18
  122. package/src/tui/stageSurface.js +120 -49
  123. package/src/tui/statusLine.js +85 -53
  124. package/src/tui/statusLine.ts +82 -46
  125. package/src/tui/terminalInputFramer.js +5 -2
  126. package/src/tui/text.js +117 -46
  127. package/src/tui/text.ts +113 -43
  128. package/src/tui/textLayout.js +6 -4
  129. package/src/tui/textLayout.ts +11 -5
  130. package/src/tui/theme.js +17 -8
  131. package/src/tui/thinkingBox.js +95 -95
  132. package/src/tui/thinkingBox.ts +105 -80
  133. package/src/tui/toolActivityPolicy.js +8 -1
  134. package/src/tui/toolActivityPolicy.ts +7 -1
  135. package/src/tui/toolDisplay.js +15 -6
  136. package/src/tui/toolDisplay.ts +16 -6
  137. package/src/tui/toolOutputNormalizer.js +16 -3
  138. package/src/tui/toolOutputNormalizer.ts +13 -3
  139. package/src/tui/transcript.js +15 -9
  140. package/src/tui/turnRail.js +156 -67
  141. package/src/tui/turnRail.ts +155 -58
  142. package/src/tui/usageCard.js +80 -45
  143. package/src/tui/usageCard.ts +81 -46
  144. package/src/tui/viewport.js +48 -23
  145. package/src/tui/viewport.ts +48 -27
  146. package/src/tui/viewportAnchor.js +2 -2
  147. package/src/tui/viewportAnchor.ts +2 -2
  148. package/src/tui/workspaceFileIndex.js +8 -6
  149. package/src/tui/workspaceFileIndex.ts +8 -6
  150. package/src/tui/workspaceSwitch.js +13 -10
  151. package/src/tui/workspaceSwitch.ts +11 -7
@@ -14,7 +14,7 @@
14
14
  //
15
15
  // Pure Node. No dependency, no shell.
16
16
 
17
- import { visibleWidth } from './text.js';
17
+ import { truncate, visibleWidth } from './text.js';
18
18
  import { writeClipboardSync, readClipboardSync } from './clipboardSync.js';
19
19
 
20
20
  /** Split into code points, so one emoji is one editable unit. */
@@ -22,6 +22,10 @@ function toCodePoints(text) {
22
22
  return Array.from(String(text == null ? '' : text));
23
23
  }
24
24
 
25
+ function normalizeNewlines(text) {
26
+ return String(text == null ? '' : text).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
27
+ }
28
+
25
29
  // A "word" for word-wise movement. Deliberately generous: an identifier, a
26
30
  // path segment and a flag should each move as one unit.
27
31
  const WORD_CHARACTER = /[\p{L}\p{N}_-]/u;
@@ -48,7 +52,7 @@ export class LineEditor {
48
52
  // -------------------------------------------------------------------------
49
53
 
50
54
  setText(text) {
51
- this.lines = String(text == null ? '' : text).split('\n').map(toCodePoints);
55
+ this.lines = normalizeNewlines(text).split('\n').map(toCodePoints);
52
56
  if (this.lines.length === 0) this.lines = [[]];
53
57
  this.line = this.lines.length - 1;
54
58
  this.col = this.lines[this.line].length;
@@ -70,14 +74,25 @@ export class LineEditor {
70
74
  );
71
75
  }
72
76
 
77
+ _clampPos(pos) {
78
+ const maxLine = Math.max(0, this.lines.length - 1);
79
+ const rawLine = Number.isFinite(pos?.line) ? Math.floor(pos.line) : 0;
80
+ const line = Math.max(0, Math.min(maxLine, rawLine));
81
+ const maxCol = this.lines[line]?.length ?? 0;
82
+ const rawCol = Number.isFinite(pos?.col) ? Math.floor(pos.col) : 0;
83
+ const col = Math.max(0, Math.min(maxCol, rawCol));
84
+ return { line, col };
85
+ }
86
+
73
87
  getSelectionRange() {
74
88
  if (!this.hasSelection || !this.selectionAnchor) return null;
75
- const a = this.selectionAnchor;
76
- const b = { line: this.line, col: this.col };
89
+ const a = this._clampPos(this.selectionAnchor);
90
+ const b = this._clampPos({ line: this.line, col: this.col });
91
+ if (a.line === b.line && a.col === b.col) return null;
77
92
  if (a.line < b.line || (a.line === b.line && a.col <= b.col)) {
78
- return { start: { line: a.line, col: a.col }, end: { line: b.line, col: b.col } };
93
+ return { start: a, end: b };
79
94
  }
80
- return { start: { line: b.line, col: b.col }, end: { line: a.line, col: a.col } };
95
+ return { start: b, end: a };
81
96
  }
82
97
 
83
98
  getSelectedText() {
@@ -132,7 +147,7 @@ export class LineEditor {
132
147
  /** Insert text at the cursor. Embedded newlines split the line, as a paste does. */
133
148
  insert(text) {
134
149
  if (this.hasSelection) this.deleteSelection();
135
- const normalized = String(text == null ? '' : text).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
150
+ const normalized = normalizeNewlines(text);
136
151
  const parts = normalized.split('\n');
137
152
  const current = this.lines[this.line];
138
153
  const before = current.slice(0, this.col);
@@ -213,8 +228,10 @@ export class LineEditor {
213
228
 
214
229
  moveTo(line, col, extend = false) {
215
230
  this._trackSelection(extend);
216
- this.line = Math.max(0, Math.min(this.lines.length - 1, line));
217
- this.col = Math.max(0, Math.min(this.lines[this.line].length, col));
231
+ const safeLine = Number.isFinite(line) ? Math.floor(line) : this.line;
232
+ const safeCol = Number.isFinite(col) ? Math.floor(col) : this.col;
233
+ this.line = Math.max(0, Math.min(this.lines.length - 1, safeLine));
234
+ this.col = Math.max(0, Math.min(this.lines[this.line].length, safeCol));
218
235
  }
219
236
 
220
237
  moveLeft(extend = false) {
@@ -292,11 +309,15 @@ export class LineEditor {
292
309
  // memory for. Killed text goes to a ring so Ctrl+Y can put it back.
293
310
  // -------------------------------------------------------------------------
294
311
 
312
+ _killSelection() {
313
+ this.killRing = this.getSelectedText();
314
+ this.deleteSelection();
315
+ if (this.killRing) writeClipboardSync(this.killRing);
316
+ }
317
+
295
318
  killToEnd() {
296
319
  if (this.hasSelection) {
297
- this.killRing = this.getSelectedText();
298
- this.deleteSelection();
299
- if (this.killRing) writeClipboardSync(this.killRing);
320
+ this._killSelection();
300
321
  return;
301
322
  }
302
323
  const line = this.lines[this.line];
@@ -307,9 +328,7 @@ export class LineEditor {
307
328
 
308
329
  killToStart() {
309
330
  if (this.hasSelection) {
310
- this.killRing = this.getSelectedText();
311
- this.deleteSelection();
312
- if (this.killRing) writeClipboardSync(this.killRing);
331
+ this._killSelection();
313
332
  return;
314
333
  }
315
334
  const line = this.lines[this.line];
@@ -321,9 +340,15 @@ export class LineEditor {
321
340
 
322
341
  killWordLeft() {
323
342
  if (this.hasSelection) {
324
- this.killRing = this.getSelectedText();
325
- this.deleteSelection();
326
- if (this.killRing) writeClipboardSync(this.killRing);
343
+ this._killSelection();
344
+ return;
345
+ }
346
+ if (this.col === 0) {
347
+ if (this.line > 0) {
348
+ this.killRing = '\n';
349
+ this.backspace();
350
+ writeClipboardSync(this.killRing);
351
+ }
327
352
  return;
328
353
  }
329
354
  const start = this.col;
@@ -355,14 +380,15 @@ export class LineEditor {
355
380
  * redraw leave debris on screen.
356
381
  */
357
382
  render(width, continuation = '') {
358
- const usable = Math.max(8, width);
383
+ const usable = Number.isFinite(width) && width > 0 ? Math.max(8, Math.floor(width)) : 8;
359
384
  const rows = [];
360
385
  let cursorRow = 0;
361
386
  let cursorCol = 0;
362
387
  const range = this.getSelectionRange();
363
388
 
364
389
  for (let index = 0; index < this.lines.length; index++) {
365
- const prefix = index === 0 ? '' : continuation;
390
+ const rawPrefix = index === 0 ? '' : String(continuation ?? '');
391
+ const prefix = visibleWidth(rawPrefix) >= usable ? truncate(rawPrefix, usable - 1, '') : rawPrefix;
366
392
  const prefixWidth = visibleWidth(prefix);
367
393
  const budget = Math.max(1, usable - prefixWidth);
368
394
  const line = this.lines[index];
@@ -385,7 +411,7 @@ export class LineEditor {
385
411
  used = 0;
386
412
  }
387
413
  cursorRow = rows.length;
388
- cursorCol = prefixWidth + used;
414
+ cursorCol = Math.min(usable - 1, prefixWidth + used);
389
415
  placed = true;
390
416
  }
391
417
  break;
@@ -418,7 +444,7 @@ export class LineEditor {
418
444
 
419
445
  if (isCurrentLine && pos === this.col && !placed) {
420
446
  cursorRow = rows.length;
421
- cursorCol = prefixWidth + used;
447
+ cursorCol = Math.min(usable - 1, prefixWidth + used);
422
448
  placed = true;
423
449
  }
424
450
 
@@ -432,7 +458,7 @@ export class LineEditor {
432
458
  rows.push(row);
433
459
  if (isCurrentLine && !placed) {
434
460
  cursorRow = rows.length - 1;
435
- cursorCol = prefixWidth + used;
461
+ cursorCol = Math.min(usable - 1, prefixWidth + used);
436
462
  }
437
463
  }
438
464
 
@@ -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
  }