@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
@@ -32,34 +32,48 @@ export function isStartupDialog(surface: StartupSurface | null | undefined): boo
32
32
 
33
33
  /** Keep startup pickers readable without letting a long catalogue resize the UI. */
34
34
  export function startupDialogView(layer: StartupLayer, columns: number, terminalRows: number): PlacedView {
35
+ const safeLayer: Partial<StartupLayer> = layer && typeof layer === 'object' ? layer : {};
35
36
  const availableWidth = Number.isFinite(columns) ? Math.max(8, Math.floor(columns) - 1) : 79;
36
37
  const availableHeight = Number.isFinite(terminalRows) ? Math.max(4, Math.floor(terminalRows) - 2) : 20;
37
- const width = Math.min(availableWidth, 96, Math.max(88, Math.floor(layer.width || 0)));
38
+ const requestedWidth = typeof safeLayer.width === 'number' && Number.isFinite(safeLayer.width) ? Math.floor(safeLayer.width) : 0;
39
+ const width = Math.min(availableWidth, 96, Math.max(88, requestedWidth));
38
40
  const height = Math.min(availableHeight, 30);
39
41
  const measuredLayer = {
40
- title: layer.title,
41
- footer: layer.footer,
42
- preferredHeight: () => Math.max(10, layer.preferredHeight()),
43
- body: (innerWidth: number, bodyHeight: number) => layer.body(innerWidth, bodyHeight)
42
+ title: safeLayer.title,
43
+ footer: safeLayer.footer,
44
+ preferredHeight: () => {
45
+ const raw = typeof safeLayer.preferredHeight === 'function' ? safeLayer.preferredHeight() : 14;
46
+ return Math.max(10, Number.isFinite(raw) ? raw : 14);
47
+ },
48
+ body: (innerWidth: number, bodyHeight: number) =>
49
+ typeof safeLayer.body === 'function' ? safeLayer.body(innerWidth, bodyHeight) : []
44
50
  };
45
- const centered = centerRows(panelRows(measuredLayer, width, height) as string[], columns);
46
- const cursor = layer.cursor;
51
+ const centered = centerRows(panelRows(measuredLayer, width, height) as string[], availableWidth + 1);
52
+ const cursor = safeLayer.cursor;
53
+ const safeCursorY = cursor && Number.isFinite(cursor.y) ? Math.max(0, Math.floor(cursor.y)) : null;
54
+ const safeCursorX = cursor && Number.isFinite(cursor.x) ? Math.max(0, Math.floor(cursor.x)) : null;
55
+ const maxRow = Math.max(0, centered.rows.length - 1);
56
+ const maxCol = Math.max(0, availableWidth - 1);
47
57
  return {
48
58
  rows: centered.rows,
49
- caretRow: cursor ? 1 + cursor.y : 0,
50
- caretCol: centered.inset + (cursor ? 2 + cursor.x : 0)
59
+ caretRow: safeCursorY !== null ? Math.min(maxRow, 1 + safeCursorY) : 0,
60
+ caretCol: Math.max(0, Math.min(maxCol, centered.inset + (safeCursorX !== null ? 2 + safeCursorX : 0)))
51
61
  };
52
62
  }
53
63
 
54
64
  /** Center a temporary dialog in the available terminal region. */
55
65
  export function placeDialog(rows: string[], columns: number, height: number, caretRow: number, caretCol: number): PlacedView {
56
- const available = Math.max(1, Math.floor(height));
57
- const shown = rows.slice(0, available);
66
+ const available = Number.isFinite(height) ? Math.max(1, Math.floor(height)) : 1;
67
+ const safeColumns = Number.isFinite(columns) ? Math.max(2, Math.floor(columns)) : 80;
68
+ const safeCaretRow = Number.isFinite(caretRow) ? Math.floor(caretRow) : 0;
69
+ const safeCaretCol = Number.isFinite(caretCol) ? Math.floor(caretCol) : 0;
70
+ const safeRows = Array.isArray(rows) ? rows : [];
71
+ const shown = safeRows.slice(0, available);
58
72
  const top = Math.max(0, Math.floor((available - shown.length) / 2));
59
73
  return {
60
74
  rows: [...Array<string>(top).fill(''), ...shown],
61
- caretRow: top + Math.min(Math.max(0, caretRow), shown.length - 1),
62
- caretCol: Math.max(0, Math.min(caretCol, columns - 2))
75
+ caretRow: top + Math.max(0, Math.min(safeCaretRow, Math.max(0, shown.length - 1))),
76
+ caretCol: Math.max(0, Math.min(safeCaretCol, safeColumns - 2))
63
77
  };
64
78
  }
65
79
 
@@ -72,12 +86,17 @@ export function placeHome(
72
86
  caretRow: number,
73
87
  caretCol: number
74
88
  ): PlacedView {
75
- const available = Math.max(1, Math.floor(height));
76
- const logo = centerRows(sessionBanner(info, columns, { height: available }), columns).rows;
89
+ const safeInfo: BannerInfo = info && typeof info === 'object' ? info : {};
90
+ const safePromptRows = Array.isArray(promptRows) ? promptRows : [];
91
+ const safeColumns = Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 80;
92
+ const available = Number.isFinite(height) ? Math.max(1, Math.floor(height)) : 24;
93
+ const safeCaretRow = Number.isFinite(caretRow) ? Math.floor(caretRow) : 0;
94
+ const safeCaretCol = Number.isFinite(caretCol) ? Math.floor(caretCol) : 0;
95
+ const logo = centerRows(sessionBanner(safeInfo, safeColumns, { height: available }), safeColumns).rows;
77
96
  const spacer = available >= 25 ? 2 : 1;
78
97
  // When the window is short, preserve the composer and editing caret first.
79
98
  // The logo yields height; it must never push a wrapped draft off-screen.
80
- const fitted = fitHomeContent(logo, promptRows, available, caretRow, spacer);
99
+ const fitted = fitHomeContent(logo, safePromptRows, available, safeCaretRow, spacer);
81
100
  const required = fitted.logoRows.length + fitted.spacer + fitted.promptRows.length;
82
101
  const top = Math.max(0, Math.floor((available - required) / 2));
83
102
  const rows = [
@@ -86,9 +105,10 @@ export function placeHome(
86
105
  ...Array<string>(fitted.spacer).fill(''),
87
106
  ...fitted.promptRows
88
107
  ];
108
+ const maxRow = Math.max(0, rows.length - 1);
89
109
  return {
90
110
  rows,
91
- caretRow: top + fitted.logoRows.length + fitted.spacer + fitted.caretRow,
92
- caretCol: Math.max(0, Math.min(caretCol, columns - 2))
111
+ caretRow: Math.max(0, Math.min(maxRow, top + fitted.logoRows.length + fitted.spacer + fitted.caretRow)),
112
+ caretCol: Math.max(0, Math.min(safeCaretCol, Math.max(0, safeColumns - 2)))
93
113
  };
94
114
  }
@@ -17,19 +17,20 @@ const COMMAND = /(?:^|[ \t\r\n])\/([a-z0-9_?-]*)$/i;
17
17
  export function detectInlineSlashTrigger(text, cursor) {
18
18
  if (typeof text !== 'string' || !Number.isFinite(cursor))
19
19
  return null;
20
- if (cursor < 0 || cursor > text.length)
20
+ const position = Math.trunc(cursor);
21
+ if (position < 0 || position > text.length)
21
22
  return null;
22
- const before = text.slice(0, cursor);
23
+ const before = text.slice(0, position);
23
24
  const argument = ARGUMENT.exec(before);
24
25
  if (argument) {
25
26
  const fragment = argument[0];
26
- const offset = cursor - fragment.length + fragment.indexOf('/');
27
+ const offset = position - fragment.length + fragment.indexOf('/');
27
28
  const query = argument[2] ?? '';
28
29
  return {
29
30
  kind: 'command-argument',
30
31
  command: argument[1] ?? '',
31
32
  query,
32
- start: cursor - query.length,
33
+ start: position - query.length,
33
34
  tokenStart: offset,
34
35
  inline: before.slice(0, offset).trim().length > 0
35
36
  };
@@ -38,7 +39,7 @@ export function detectInlineSlashTrigger(text, cursor) {
38
39
  if (!command)
39
40
  return null;
40
41
  const fragment = command[0];
41
- const offset = cursor - fragment.length + fragment.indexOf('/');
42
+ const offset = position - fragment.length + fragment.indexOf('/');
42
43
  return {
43
44
  kind: 'command',
44
45
  query: command[1] ?? '',
@@ -40,19 +40,20 @@ const COMMAND = /(?:^|[ \t\r\n])\/([a-z0-9_?-]*)$/i;
40
40
  */
41
41
  export function detectInlineSlashTrigger(text: string, cursor: number): SlashTrigger | null {
42
42
  if (typeof text !== 'string' || !Number.isFinite(cursor)) return null;
43
- if (cursor < 0 || cursor > text.length) return null;
43
+ const position = Math.trunc(cursor);
44
+ if (position < 0 || position > text.length) return null;
44
45
 
45
- const before = text.slice(0, cursor);
46
+ const before = text.slice(0, position);
46
47
  const argument = ARGUMENT.exec(before);
47
48
  if (argument) {
48
49
  const fragment = argument[0];
49
- const offset = cursor - fragment.length + fragment.indexOf('/');
50
+ const offset = position - fragment.length + fragment.indexOf('/');
50
51
  const query = argument[2] ?? '';
51
52
  return {
52
53
  kind: 'command-argument',
53
54
  command: argument[1] ?? '',
54
55
  query,
55
- start: cursor - query.length,
56
+ start: position - query.length,
56
57
  tokenStart: offset,
57
58
  inline: before.slice(0, offset).trim().length > 0
58
59
  };
@@ -61,7 +62,7 @@ export function detectInlineSlashTrigger(text: string, cursor: number): SlashTri
61
62
  const command = COMMAND.exec(before);
62
63
  if (!command) return null;
63
64
  const fragment = command[0];
64
- const offset = cursor - fragment.length + fragment.indexOf('/');
65
+ const offset = position - fragment.length + fragment.indexOf('/');
65
66
  return {
66
67
  kind: 'command',
67
68
  query: command[1] ?? '',
package/src/tui/keys.js CHANGED
@@ -64,11 +64,16 @@ function applyModifier(key, modifier) {
64
64
  */
65
65
  function utf8Length(buffer, offset) {
66
66
  const byte = buffer[offset];
67
- let needed = 1;
68
- if (byte >= 0xf0) needed = 4;
69
- else if (byte >= 0xe0) needed = 3;
70
- else if (byte >= 0xc0) needed = 2;
71
- return offset + needed <= buffer.length ? needed : 0;
67
+ if (byte < 0x80) return 1;
68
+ // Continuation bytes, overlong C0/C1, and > U+10FFFF lead bytes (>= F5)
69
+ // are never valid multi-byte starts; consume one byte rather than wedging input.
70
+ if (byte < 0xc2 || byte > 0xf4) return 1;
71
+ const needed = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : 2;
72
+ for (let i = 1; i < needed; i++) {
73
+ if (offset + i >= buffer.length) return 0;
74
+ if ((buffer[offset + i] & 0xc0) !== 0x80) return 1;
75
+ }
76
+ return needed;
72
77
  }
73
78
 
74
79
  /**
@@ -311,20 +316,21 @@ export class KeyDecoder {
311
316
  const final = text[index];
312
317
  const params = text.slice(2, index);
313
318
  const sequence = text.slice(0, index + 1);
319
+ const byteLength = Buffer.byteLength(sequence, 'utf8');
314
320
  const numbers = params.split(/[;:]/).map((part) => parseInt(part, 10));
315
321
 
316
322
  // SGR mouse: ESC [ < b ; x ; y M|m. `<` is 0x3C, outside the @..~ final
317
323
  // range, so the scan above already found the right final byte.
318
324
  if ((final === 'M' || final === 'm') && params.startsWith('<')) {
319
325
  return this.emitMouse(params.slice(1).split(';').map((n) => parseInt(n, 10)),
320
- final === 'M', sequence, events);
326
+ final === 'M', sequence, events, byteLength);
321
327
  }
322
328
 
323
329
  if (final === '~') {
324
330
  const name = CSI_TILDE_NAMES[numbers[0]];
325
331
  if (name) {
326
332
  events.push(applyModifier(makeKey(name, { sequence }), numbers[1]));
327
- return sequence.length;
333
+ return byteLength;
328
334
  }
329
335
  } else if (final === 'u') {
330
336
  // Kitty keyboard protocol: ESC [ codepoint ; modifiers u
@@ -338,9 +344,14 @@ export class KeyDecoder {
338
344
  }[codepoint];
339
345
  if (controlName) {
340
346
  events.push(applyModifier(makeKey(controlName, { sequence }), numbers[1]));
341
- return sequence.length;
347
+ return byteLength;
342
348
  }
343
- if (Number.isFinite(codepoint) && codepoint >= 32) {
349
+ if (
350
+ Number.isFinite(codepoint) &&
351
+ codepoint >= 32 &&
352
+ codepoint <= 0x10ffff &&
353
+ (codepoint < 0xd800 || codepoint > 0xdfff)
354
+ ) {
344
355
  const character = String.fromCodePoint(codepoint);
345
356
  const key = applyModifier(
346
357
  makeKey('char', { sequence, text: character }),
@@ -350,7 +361,7 @@ export class KeyDecoder {
350
361
  if (key.ctrl || key.alt) key.text = '';
351
362
  if (key.name === 'char' && !key.text) key.name = character.toLowerCase();
352
363
  events.push(key);
353
- return sequence.length;
364
+ return byteLength;
354
365
  }
355
366
  } else if (CSI_FINAL_NAMES[final]) {
356
367
  const key = applyModifier(
@@ -360,13 +371,13 @@ export class KeyDecoder {
360
371
  // ESC [ Z is Shift+Tab and carries no modifier parameter of its own.
361
372
  if (final === 'Z') key.shift = true;
362
373
  events.push(key);
363
- return sequence.length;
374
+ return byteLength;
364
375
  }
365
376
 
366
377
  // Unknown but well-formed: consume it so it can never reach the buffer as
367
378
  // literal text and corrupt the line the user is editing.
368
379
  events.push(makeKey('unknown', { sequence }));
369
- return sequence.length;
380
+ return byteLength;
370
381
  }
371
382
 
372
383
  stepX10Mouse(buffer, offset, events) {
@@ -389,11 +400,11 @@ export class KeyDecoder {
389
400
  * reaching the line the user is editing, and naming it lets a caller act on
390
401
  * it later without another decoder change.
391
402
  */
392
- emitMouse(numbers, pressed, sequence, events) {
403
+ emitMouse(numbers, pressed, sequence, events, byteLength = sequence.length) {
393
404
  const [code, column, row] = numbers;
394
405
  if (!Number.isFinite(code) || !Number.isFinite(column) || !Number.isFinite(row)) {
395
406
  events.push(makeKey('unknown', { sequence }));
396
- return sequence.length;
407
+ return byteLength;
397
408
  }
398
409
 
399
410
  // Modifier bits live in the button code for mouse reports, not in a CSI
@@ -404,14 +415,14 @@ export class KeyDecoder {
404
415
  ctrl: (code & 16) !== 0
405
416
  };
406
417
  // Wire coordinates are 1-based.
407
- const at = { x: column - 1, y: row - 1 };
418
+ const at = { x: Math.max(0, column - 1), y: Math.max(0, row - 1) };
408
419
 
409
420
  if ((code & 64) !== 0) {
410
421
  const direction = ['up', 'down', 'left', 'right'][code & 3];
411
422
  // A wheel report arrives as a press; there is no release to pair it with.
412
423
  if (pressed) {
413
424
  events.push(makeKey('wheel', { sequence, ...modifiers, wheel: { direction, ...at } }));
414
- return sequence.length;
425
+ return byteLength;
415
426
  }
416
427
  }
417
428
 
@@ -419,7 +430,7 @@ export class KeyDecoder {
419
430
  sequence, ...modifiers,
420
431
  mouse: { button: code & 3, pressed, ...at }
421
432
  }));
422
- return sequence.length;
433
+ return byteLength;
423
434
  }
424
435
 
425
436
  stepSS3(buffer, offset, events) {
@@ -468,7 +479,9 @@ function partialSuffixLength(text, marker) {
468
479
  * There is no mode that reports the wheel alone. UX-02.
469
480
  */
470
481
  export function mouseTracking(enabled) {
471
- return enabled ? '\x1b[?1000h\x1b[?1006h' : '\x1b[?1006l\x1b[?1000l';
482
+ // Select SGR encoding before enabling reporting. Disable reporting before
483
+ // tearing down its encoding so no event can arrive as legacy X10 bytes.
484
+ return enabled ? '\x1b[?1006h\x1b[?1000h' : '\x1b[?1000l\x1b[?1006l';
472
485
  }
473
486
 
474
487
  /** Turn bracketed paste on/off. Paired with the editor's lifecycle. */
@@ -501,6 +514,11 @@ export function bracketedPaste(enabled) {
501
514
  * @param {string} letter Single character to test, case-insensitive.
502
515
  * @returns {boolean}
503
516
  */
517
+ export function isMouseMotion(sequence) {
518
+ const code = Number(/^\x1b\[<(\d+);/.exec(sequence || '')?.[1]);
519
+ return Number.isFinite(code) && (code & 32) !== 0;
520
+ }
521
+
504
522
  export function isChar(event, letter) {
505
523
  if (!event || event.ctrl || event.alt || event.meta) return false;
506
524
  const typed = typeof event.text === 'string' && event.text.length > 0
package/src/tui/layout.js CHANGED
@@ -6,41 +6,59 @@ export function composerWidth(columns) {
6
6
  }
7
7
  /** Center one content column without centering each line independently. */
8
8
  export function centerRows(rows, columns) {
9
+ const safeRows = Array.isArray(rows) ? rows : [];
9
10
  const available = Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 80;
10
- const occupied = rows.reduce((widest, row) => Math.max(widest, visibleWidth(row)), 0);
11
+ const maxContent = Math.max(1, available - 1);
12
+ const occupied = safeRows.reduce((widest, row) => Math.max(widest, Math.min(maxContent, visibleWidth(row))), 0);
11
13
  const inset = Math.max(0, Math.floor((available - occupied) / 2));
12
14
  const prefix = ' '.repeat(inset);
13
- return { rows: rows.map(row => row ? prefix + row : ''), inset };
15
+ const limit = Math.max(1, available - inset - 1);
16
+ return {
17
+ rows: safeRows.map(row => (row ? prefix + truncate(row, limit, '') : '')),
18
+ inset
19
+ };
14
20
  }
15
21
  /** Conversation content starts at the left margin while Home stays centered. */
16
22
  export function sessionRows(rows, columns) {
23
+ const safeRows = Array.isArray(rows) ? rows : [];
17
24
  const available = Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 80;
18
25
  const inset = Math.min(3, Math.max(0, available - 3));
19
26
  const prefix = ' '.repeat(inset);
20
27
  return {
21
- rows: rows.map(row => row ? prefix + truncate(row, Math.max(1, available - inset - 1), '') : ''),
28
+ rows: safeRows.map(row => row ? prefix + truncate(row, Math.max(1, available - inset - 1), '') : ''),
22
29
  inset
23
30
  };
24
31
  }
25
32
  /** Leave room for a centered home composition without overflowing small terminals. */
26
33
  export function openingTopGap(rows, introRows) {
27
- if (!Number.isFinite(rows) || rows < 40)
34
+ if (!Number.isFinite(rows) || rows < 40 || introRows === Number.POSITIVE_INFINITY)
28
35
  return 0;
29
- return Math.max(0, Math.min(40, Math.floor((rows - introRows - 8) / 2)));
36
+ const safeRows = Math.floor(rows);
37
+ const safeIntro = Number.isFinite(introRows) ? Math.max(0, Math.floor(introRows)) : 0;
38
+ return Math.max(0, Math.min(40, Math.floor((safeRows - safeIntro - 8) / 2)));
30
39
  }
31
40
  /** Place the home composition as one centered group, with room for the composer below. */
32
41
  export function openingRows(rows, columns, terminalRows) {
42
+ const safeRows = Array.isArray(rows) ? rows : [];
43
+ if (safeRows.length === 0)
44
+ return [];
33
45
  return [
34
- ...Array(openingTopGap(terminalRows, rows.length)).fill(''),
35
- ...centerRows(rows, columns).rows
46
+ ...Array(openingTopGap(terminalRows, safeRows.length)).fill(''),
47
+ ...centerRows(safeRows, columns).rows
36
48
  ];
37
49
  }
50
+ function positiveRequested(requested, fallback) {
51
+ if (!Number.isFinite(requested))
52
+ return fallback;
53
+ const floored = Math.floor(requested);
54
+ return floored > 0 ? floored : fallback;
55
+ }
38
56
  /** Fit every dialog, including text reports, inside the current terminal width. */
39
57
  export function dialogWidth(columns, requested) {
40
58
  const available = Number.isFinite(columns) ? Math.max(4, Math.floor(columns) - 1) : 79;
41
- return Math.max(4, Math.min(available, Math.floor(requested) || available));
59
+ return Math.max(4, Math.min(available, positiveRequested(requested, available)));
42
60
  }
43
61
  export function dialogHeight(available, requested) {
44
62
  const room = Number.isFinite(available) ? Math.max(4, Math.floor(available) - 1) : 20;
45
- return Math.max(4, Math.min(20, room, Math.floor(requested) || room));
63
+ return Math.max(4, Math.min(20, room, positiveRequested(requested, room)));
46
64
  }
package/src/tui/layout.ts CHANGED
@@ -8,45 +8,62 @@ export function composerWidth(columns: number): number {
8
8
 
9
9
  /** Center one content column without centering each line independently. */
10
10
  export function centerRows(rows: string[], columns: number): { rows: string[]; inset: number } {
11
+ const safeRows = Array.isArray(rows) ? rows : [];
11
12
  const available = Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 80;
12
- const occupied = rows.reduce((widest, row) => Math.max(widest, visibleWidth(row)), 0);
13
+ const maxContent = Math.max(1, available - 1);
14
+ const occupied = safeRows.reduce((widest, row) => Math.max(widest, Math.min(maxContent, visibleWidth(row))), 0);
13
15
  const inset = Math.max(0, Math.floor((available - occupied) / 2));
14
16
  const prefix = ' '.repeat(inset);
15
- return { rows: rows.map(row => row ? prefix + row : ''), inset };
17
+ const limit = Math.max(1, available - inset - 1);
18
+ return {
19
+ rows: safeRows.map(row => (row ? prefix + truncate(row, limit, '') : '')),
20
+ inset
21
+ };
16
22
  }
17
23
 
18
24
  /** Conversation content starts at the left margin while Home stays centered. */
19
25
  export function sessionRows(rows: string[], columns: number): { rows: string[]; inset: number } {
26
+ const safeRows = Array.isArray(rows) ? rows : [];
20
27
  const available = Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 80;
21
28
  const inset = Math.min(3, Math.max(0, available - 3));
22
29
  const prefix = ' '.repeat(inset);
23
30
  return {
24
- rows: rows.map(row => row ? prefix + truncate(row, Math.max(1, available - inset - 1), '') : ''),
31
+ rows: safeRows.map(row => row ? prefix + truncate(row, Math.max(1, available - inset - 1), '') : ''),
25
32
  inset
26
33
  };
27
34
  }
28
35
 
29
36
  /** Leave room for a centered home composition without overflowing small terminals. */
30
37
  export function openingTopGap(rows: number, introRows: number): number {
31
- if (!Number.isFinite(rows) || rows < 40) return 0;
32
- return Math.max(0, Math.min(40, Math.floor((rows - introRows - 8) / 2)));
38
+ if (!Number.isFinite(rows) || rows < 40 || introRows === Number.POSITIVE_INFINITY) return 0;
39
+ const safeRows = Math.floor(rows);
40
+ const safeIntro = Number.isFinite(introRows) ? Math.max(0, Math.floor(introRows)) : 0;
41
+ return Math.max(0, Math.min(40, Math.floor((safeRows - safeIntro - 8) / 2)));
33
42
  }
34
43
 
35
44
  /** Place the home composition as one centered group, with room for the composer below. */
36
45
  export function openingRows(rows: string[], columns: number, terminalRows: number): string[] {
46
+ const safeRows = Array.isArray(rows) ? rows : [];
47
+ if (safeRows.length === 0) return [];
37
48
  return [
38
- ...Array<string>(openingTopGap(terminalRows, rows.length)).fill(''),
39
- ...centerRows(rows, columns).rows
49
+ ...Array<string>(openingTopGap(terminalRows, safeRows.length)).fill(''),
50
+ ...centerRows(safeRows, columns).rows
40
51
  ];
41
52
  }
42
53
 
54
+ function positiveRequested(requested: number, fallback: number): number {
55
+ if (!Number.isFinite(requested)) return fallback;
56
+ const floored = Math.floor(requested);
57
+ return floored > 0 ? floored : fallback;
58
+ }
59
+
43
60
  /** Fit every dialog, including text reports, inside the current terminal width. */
44
61
  export function dialogWidth(columns: number, requested: number): number {
45
62
  const available = Number.isFinite(columns) ? Math.max(4, Math.floor(columns) - 1) : 79;
46
- return Math.max(4, Math.min(available, Math.floor(requested) || available));
63
+ return Math.max(4, Math.min(available, positiveRequested(requested, available)));
47
64
  }
48
65
 
49
66
  export function dialogHeight(available: number, requested: number): number {
50
67
  const room = Number.isFinite(available) ? Math.max(4, Math.floor(available) - 1) : 20;
51
- return Math.max(4, Math.min(20, room, Math.floor(requested) || room));
68
+ return Math.max(4, Math.min(20, room, positiveRequested(requested, room)));
52
69
  }
@@ -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