@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
@@ -1,7 +1,8 @@
1
1
  import { writeUserSkill, validateSegment, skillTemplate } from '../userSkills.js';
2
2
  import { invalidateUserSkills } from '../skillsManager.js';
3
+ import { safeDisplay } from './text.js';
3
4
  // @ts-expect-error theme.js has no TypeScript declaration yet.
4
- import { paint, bold, dim } from './theme.js';
5
+ import { paint } from './theme.js';
5
6
  // @ts-expect-error dialogs.js is awaiting TypeScript migration.
6
7
  import { InputLayer, SelectLayer } from './dialogs.js';
7
8
  // @ts-expect-error prompt.js is awaiting TypeScript migration.
@@ -34,10 +35,15 @@ const COMMON_DOMAINS: CommonDomainChoice[] = [
34
35
  { value: '__other__', label: '+ Enter custom category...', description: 'Specify any category name' }
35
36
  ];
36
37
 
38
+ function trimInput(val: unknown): string {
39
+ return typeof val === 'string' ? val.trim() : '';
40
+ }
41
+
37
42
  /**
38
43
  * Interactive wizard hosted on ChatPrompt to scaffold and create a new skill.
39
44
  */
40
45
  export async function runInteractiveSkillWizard(prompt: ChatPrompt): Promise<CreatedUserSkill | null> {
46
+ if (!prompt || typeof prompt.openLayer !== 'function') return null;
41
47
  // Step 1: Select or enter domain/category
42
48
  const chosenDomain = await new Promise<string | null>((resolve) => {
43
49
  let resolved = false;
@@ -76,7 +82,7 @@ export async function runInteractiveSkillWizard(prompt: ChatPrompt): Promise<Cre
76
82
  title: 'create skill · category name',
77
83
  lines: ['Category / domain name (e.g. data, analytics, cloud, tools):'],
78
84
  placeholder: 'category-name',
79
- onSubmit: (val: string) => finish(val.trim().toLowerCase()),
85
+ onSubmit: (val: unknown) => finish(trimInput(val).toLowerCase()),
80
86
  onCancel: () => finish(null)
81
87
  });
82
88
  prompt.openLayer(layer);
@@ -108,7 +114,7 @@ export async function runInteractiveSkillWizard(prompt: ChatPrompt): Promise<Cre
108
114
  'Skill name (lowercase letters, numbers, hyphens — e.g. play-store-release, pr-review):'
109
115
  ],
110
116
  placeholder: 'my-new-skill',
111
- onSubmit: (val: string) => finish(val.trim().toLowerCase()),
117
+ onSubmit: (val: unknown) => finish(trimInput(val).toLowerCase()),
112
118
  onCancel: () => finish(null)
113
119
  });
114
120
  prompt.openLayer(layer);
@@ -139,7 +145,7 @@ export async function runInteractiveSkillWizard(prompt: ChatPrompt): Promise<Cre
139
145
  'Short description: what this skill does and when the agent should use it:'
140
146
  ],
141
147
  placeholder: 'e.g. Prepares and validates Android app bundles for Google Play Store release.',
142
- onSubmit: (val: string) => finish(val.trim()),
148
+ onSubmit: (val: unknown) => finish(trimInput(val)),
143
149
  onCancel: () => finish(null)
144
150
  });
145
151
  prompt.openLayer(layer);
@@ -152,7 +158,7 @@ export async function runInteractiveSkillWizard(prompt: ChatPrompt): Promise<Cre
152
158
  const written = writeUserSkill({ domain, name: skillName, content, overwrite: false });
153
159
  if (!written.ok) {
154
160
  if (typeof prompt.showText === 'function') {
155
- prompt.showText('Skill Creation Failed', written.error || 'Failed to write skill file', { danger: true });
161
+ prompt.showText('Skill Creation Failed', safeDisplay(written.error || 'Failed to write skill file'), { danger: true });
156
162
  }
157
163
  return null;
158
164
  }
@@ -74,7 +74,8 @@ function isLikelyBareWebDomain(token) {
74
74
  if (!host.includes('.') || host.startsWith('.') || host.endsWith('.'))
75
75
  return false;
76
76
  for (const suffix of KNOWN_HOST_SUFFIXES) {
77
- if (host === suffix || host.endsWith(suffix))
77
+ const dotSuffix = suffix.startsWith('.') ? suffix : `.${suffix}`;
78
+ if (host === suffix || host.endsWith(dotSuffix))
78
79
  return true;
79
80
  }
80
81
  const parts = host.split('.');
@@ -92,7 +93,11 @@ function isLikelyBareWebDomain(token) {
92
93
  return true;
93
94
  }
94
95
  export function resolveFullUrlFromMessage(candidate, rawMessageText) {
96
+ if (typeof candidate !== 'string')
97
+ return '';
95
98
  const cleaned = candidate.trim();
99
+ if (!cleaned)
100
+ return '';
96
101
  const isTruncated = cleaned.endsWith('…') || cleaned.endsWith('...');
97
102
  const prefix = cleaned
98
103
  .replace(/(?:…|\.{2,})+$/, '')
@@ -139,9 +144,11 @@ function findUnclosedOsc8Url(rawRow) {
139
144
  * along with their exact visible column intervals `[startCol, endCol]` on a single row.
140
145
  */
141
146
  export function extractRowLinks(rawRow, rowIndex = 0, rawMessageText, prevRawRow) {
142
- if (!rawRow)
147
+ if (typeof rawRow !== 'string' || !rawRow)
143
148
  return [];
144
149
  const links = [];
150
+ const csiRe = /\x1b\[[0-?]*[ -/]*[@-~]/y;
151
+ const oscRe = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/y;
145
152
  let col = 0;
146
153
  let i = 0;
147
154
  let activeOsc8Url = findUnclosedOsc8Url(prevRawRow);
@@ -171,6 +178,17 @@ export function extractRowLinks(rawRow, rowIndex = 0, rawMessageText, prevRawRow
171
178
  if (endOffset !== -1) {
172
179
  const urlParam = afterParams.slice(0, endOffset);
173
180
  if (urlParam.length > 0) {
181
+ if (activeOsc8Url && col > osc8StartCol) {
182
+ const resolvedPrev = resolveFullUrlFromMessage(activeOsc8Url.endsWith('…') ? osc8Label || activeOsc8Url : activeOsc8Url, rawMessageText);
183
+ links.push({
184
+ url: resolvedPrev,
185
+ label: osc8Label,
186
+ startCol: osc8StartCol,
187
+ endCol: col - 1,
188
+ row: rowIndex,
189
+ isOsc8: true
190
+ });
191
+ }
174
192
  activeOsc8Url = urlParam;
175
193
  osc8StartCol = col;
176
194
  osc8Label = '';
@@ -196,12 +214,14 @@ export function extractRowLinks(rawRow, rowIndex = 0, rawMessageText, prevRawRow
196
214
  }
197
215
  }
198
216
  if (rawRow[i] === '\x1b') {
199
- const csi = /^\x1b\[[0-?]*[ -/]*[@-~]/.exec(rawRow.slice(i));
217
+ csiRe.lastIndex = i;
218
+ const csi = csiRe.exec(rawRow);
200
219
  if (csi) {
201
220
  i += csi[0].length;
202
221
  continue;
203
222
  }
204
- const osc = /^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/.exec(rawRow.slice(i));
223
+ oscRe.lastIndex = i;
224
+ const osc = oscRe.exec(rawRow);
205
225
  if (osc) {
206
226
  i += osc[0].length;
207
227
  continue;
@@ -267,22 +287,47 @@ export function extractRowLinks(rawRow, rowIndex = 0, rawMessageText, prevRawRow
267
287
  * Check if a screen point `(point.x, point.y)` lands on a clickable URL/link in the transcript.
268
288
  */
269
289
  export function detectLinkAtPoint(surface, point, marker) {
270
- if (!surface?.stage.reserved || !Number.isFinite(point.x) || !Number.isFinite(point.y))
290
+ if (!surface?.stage?.reserved
291
+ || !surface.transcript?.flatten
292
+ || !point
293
+ || typeof point !== 'object'
294
+ || !Number.isFinite(point.x)
295
+ || !Number.isFinite(point.y)) {
296
+ return null;
297
+ }
298
+ const surfaceWidth = Number.isFinite(surface.width) ? Math.floor(surface.width) : 0;
299
+ const rawViewW = Number.isFinite(surface.viewport?.viewWidth) ? surface.viewport.viewWidth : surface.viewport?.width;
300
+ const rawViewH = Number.isFinite(surface.viewport?.viewHeight) ? surface.viewport.viewHeight : surface.viewport?.height;
301
+ const viewportWidth = Number.isFinite(rawViewW) ? Math.floor(rawViewW) : 0;
302
+ const viewportHeight = Number.isFinite(rawViewH) ? Math.floor(rawViewH) : 0;
303
+ const stageHeight = Number.isFinite(surface.stage.height) ? Math.floor(surface.stage.height) : 0;
304
+ if (surfaceWidth <= 0 || viewportWidth <= 0 || viewportHeight <= 0 || stageHeight <= 0)
271
305
  return null;
272
- const mainWidth = sidebarVisible(surface.width) ? sessionMainWidth(surface.width) : surface.width;
306
+ const px = Math.floor(point.x);
307
+ const py = Math.floor(point.y);
308
+ const isHome = Boolean(surface.homeInfo);
309
+ const mainWidth = sidebarVisible(surfaceWidth, isHome, surface.env)
310
+ ? sessionMainWidth(surfaceWidth, isHome, surface.env)
311
+ : surfaceWidth;
273
312
  const leftGutter = (surface.turnRailLayout?.turns?.length ?? 0) > 0 ? 3 : 0;
274
- if (point.x < leftGutter || point.x >= Math.min(mainWidth, surface.viewport.width + leftGutter))
313
+ if (px < leftGutter || px >= Math.min(mainWidth, viewportWidth + leftGutter))
314
+ return null;
315
+ const outRows = Number.isFinite(surface.out?.rows) && surface.out?.rows > 0
316
+ ? Math.floor(surface.out?.rows)
317
+ : stageHeight;
318
+ const top = Math.max(0, outRows - stageHeight);
319
+ const viewRow = py - top;
320
+ if (viewRow < 0 || viewRow >= viewportHeight)
275
321
  return null;
276
- const top = Math.max(0, (surface.out.rows || surface.stage.height) - surface.stage.height);
277
- const viewRow = point.y - top;
278
- if (viewRow < 0 || viewRow >= surface.viewport.height)
322
+ const scrollTop = Number.isFinite(surface.viewport?.scrollTop) ? Math.max(0, Math.floor(surface.viewport.scrollTop)) : 0;
323
+ const flat = surface.transcript.flatten(viewportWidth);
324
+ if (!Array.isArray(flat?.rows))
279
325
  return null;
280
- const flat = surface.transcript.flatten(surface.viewport.width);
281
- const visible = Math.max(0, Math.min(surface.viewport.height, flat.rows.length - surface.viewport.scrollTop));
282
- const padding = surface.viewport.height - visible;
326
+ const visible = Math.max(0, Math.min(viewportHeight, flat.rows.length - scrollTop));
327
+ const padding = viewportHeight - visible;
283
328
  if (viewRow < padding)
284
329
  return null;
285
- const row = surface.viewport.scrollTop + viewRow - padding;
330
+ const row = scrollTop + viewRow - padding;
286
331
  const rawRow = flat.rows[row];
287
332
  if (!rawRow)
288
333
  return null;
@@ -291,7 +336,7 @@ export function detectLinkAtPoint(surface, point, marker) {
291
336
  const links = extractRowLinks(rawRow, row, rawMessageText, prevRawRow);
292
337
  if (!links.length)
293
338
  return null;
294
- const col = point.x - leftGutter;
339
+ const col = px - leftGutter;
295
340
  for (const link of links) {
296
341
  if (col >= link.startCol && col <= link.endCol) {
297
342
  return link;
@@ -305,17 +350,22 @@ let lastOpenedAt = 0;
305
350
  * Open an HTTP/HTTPS/file URL in the system default browser or handler without blocking the TUI.
306
351
  */
307
352
  export function openDetectedLink(url, options = {}) {
308
- if (!url || !/^(?:https?|file):\/\//i.test(url))
353
+ if (typeof url !== 'string'
354
+ || !url
355
+ || /[\x00-\x1f\x7f\s]/.test(url)
356
+ || !/^(?:https?|file):\/\//i.test(url)) {
309
357
  return false;
310
- const now = options.now ?? Date.now();
311
- const debounceMs = options.debounceMs ?? 800;
312
- if (url === lastOpenedUrl && now - lastOpenedAt < debounceMs) {
358
+ }
359
+ const safeOptions = options && typeof options === 'object' ? options : {};
360
+ const now = typeof safeOptions.now === 'number' && Number.isFinite(safeOptions.now) ? safeOptions.now : Date.now();
361
+ const debounceMs = typeof safeOptions.debounceMs === 'number' && Number.isFinite(safeOptions.debounceMs)
362
+ ? Math.max(0, safeOptions.debounceMs)
363
+ : 800;
364
+ if (url === lastOpenedUrl && now >= lastOpenedAt && now - lastOpenedAt < debounceMs) {
313
365
  return true;
314
366
  }
315
- lastOpenedUrl = url;
316
- lastOpenedAt = now;
317
- const platform = options.platform ?? process.platform;
318
- const spawnFn = options.spawnImpl ?? spawn;
367
+ const platform = safeOptions.platform ?? process.platform;
368
+ const spawnFn = safeOptions.spawnImpl ?? spawn;
319
369
  let command;
320
370
  let args;
321
371
  if (platform === 'darwin') {
@@ -341,6 +391,8 @@ export function openDetectedLink(url, options = {}) {
341
391
  // Ignore missing browser opener errors on headless hosts.
342
392
  });
343
393
  child.unref?.();
394
+ lastOpenedUrl = url;
395
+ lastOpenedAt = now;
344
396
  return true;
345
397
  }
346
398
  catch {
@@ -14,9 +14,11 @@ export interface DetectedLink {
14
14
 
15
15
  export interface SmartLinkSurface {
16
16
  width: number;
17
+ env?: { CAUSYNE_SIDEBAR?: string };
18
+ homeInfo?: unknown;
17
19
  out: { rows?: number };
18
20
  stage: { height: number; reserved: boolean };
19
- viewport: { height: number; width: number; scrollTop: number };
21
+ viewport: { height?: number; width?: number; viewHeight?: number; viewWidth?: number; scrollTop: number };
20
22
  transcript: { flatten(width: number): { rows: string[]; markers: MessageMarker[] } };
21
23
  turnRailLayout?: { turns?: unknown[] } | null;
22
24
  }
@@ -100,7 +102,8 @@ function isLikelyBareWebDomain(token: string): boolean {
100
102
  if (!host.includes('.') || host.startsWith('.') || host.endsWith('.')) return false;
101
103
 
102
104
  for (const suffix of KNOWN_HOST_SUFFIXES) {
103
- if (host === suffix || host.endsWith(suffix)) return true;
105
+ const dotSuffix = suffix.startsWith('.') ? suffix : `.${suffix}`;
106
+ if (host === suffix || host.endsWith(dotSuffix)) return true;
104
107
  }
105
108
 
106
109
  const parts = host.split('.');
@@ -120,7 +123,9 @@ function isLikelyBareWebDomain(token: string): boolean {
120
123
  }
121
124
 
122
125
  export function resolveFullUrlFromMessage(candidate: string, rawMessageText?: string): string {
126
+ if (typeof candidate !== 'string') return '';
123
127
  const cleaned = candidate.trim();
128
+ if (!cleaned) return '';
124
129
  const isTruncated = cleaned.endsWith('…') || cleaned.endsWith('...');
125
130
  const prefix = cleaned
126
131
  .replace(/(?:…|\.{2,})+$/, '')
@@ -173,8 +178,10 @@ export function extractRowLinks(
173
178
  rawMessageText?: string,
174
179
  prevRawRow?: string
175
180
  ): DetectedLink[] {
176
- if (!rawRow) return [];
181
+ if (typeof rawRow !== 'string' || !rawRow) return [];
177
182
  const links: DetectedLink[] = [];
183
+ const csiRe = /\x1b\[[0-?]*[ -/]*[@-~]/y;
184
+ const oscRe = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/y;
178
185
 
179
186
  let col = 0;
180
187
  let i = 0;
@@ -206,6 +213,20 @@ export function extractRowLinks(
206
213
  if (endOffset !== -1) {
207
214
  const urlParam = afterParams.slice(0, endOffset);
208
215
  if (urlParam.length > 0) {
216
+ if (activeOsc8Url && col > osc8StartCol) {
217
+ const resolvedPrev = resolveFullUrlFromMessage(
218
+ activeOsc8Url.endsWith('…') ? osc8Label || activeOsc8Url : activeOsc8Url,
219
+ rawMessageText
220
+ );
221
+ links.push({
222
+ url: resolvedPrev,
223
+ label: osc8Label,
224
+ startCol: osc8StartCol,
225
+ endCol: col - 1,
226
+ row: rowIndex,
227
+ isOsc8: true
228
+ });
229
+ }
209
230
  activeOsc8Url = urlParam;
210
231
  osc8StartCol = col;
211
232
  osc8Label = '';
@@ -234,12 +255,14 @@ export function extractRowLinks(
234
255
  }
235
256
 
236
257
  if (rawRow[i] === '\x1b') {
237
- const csi = /^\x1b\[[0-?]*[ -/]*[@-~]/.exec(rawRow.slice(i));
258
+ csiRe.lastIndex = i;
259
+ const csi = csiRe.exec(rawRow);
238
260
  if (csi) {
239
261
  i += csi[0].length;
240
262
  continue;
241
263
  }
242
- const osc = /^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/.exec(rawRow.slice(i));
264
+ oscRe.lastIndex = i;
265
+ const osc = oscRe.exec(rawRow);
243
266
  if (osc) {
244
267
  i += osc[0].length;
245
268
  continue;
@@ -318,21 +341,48 @@ export function detectLinkAtPoint(
318
341
  point: { x: number; y: number },
319
342
  marker?: MessageMarker | null
320
343
  ): DetectedLink | null {
321
- if (!surface?.stage.reserved || !Number.isFinite(point.x) || !Number.isFinite(point.y)) return null;
322
- const mainWidth = sidebarVisible(surface.width) ? sessionMainWidth(surface.width) : surface.width;
344
+ if (
345
+ !surface?.stage?.reserved
346
+ || !surface.transcript?.flatten
347
+ || !point
348
+ || typeof point !== 'object'
349
+ || !Number.isFinite(point.x)
350
+ || !Number.isFinite(point.y)
351
+ ) {
352
+ return null;
353
+ }
354
+ const surfaceWidth = Number.isFinite(surface.width) ? Math.floor(surface.width) : 0;
355
+ const rawViewW = Number.isFinite(surface.viewport?.viewWidth) ? surface.viewport.viewWidth : surface.viewport?.width;
356
+ const rawViewH = Number.isFinite(surface.viewport?.viewHeight) ? surface.viewport.viewHeight : surface.viewport?.height;
357
+ const viewportWidth = Number.isFinite(rawViewW) ? Math.floor(rawViewW as number) : 0;
358
+ const viewportHeight = Number.isFinite(rawViewH) ? Math.floor(rawViewH as number) : 0;
359
+ const stageHeight = Number.isFinite(surface.stage.height) ? Math.floor(surface.stage.height) : 0;
360
+ if (surfaceWidth <= 0 || viewportWidth <= 0 || viewportHeight <= 0 || stageHeight <= 0) return null;
361
+
362
+ const px = Math.floor(point.x);
363
+ const py = Math.floor(point.y);
364
+ const isHome = Boolean(surface.homeInfo);
365
+ const mainWidth = sidebarVisible(surfaceWidth, isHome, surface.env)
366
+ ? sessionMainWidth(surfaceWidth, isHome, surface.env)
367
+ : surfaceWidth;
323
368
  const leftGutter = (surface.turnRailLayout?.turns?.length ?? 0) > 0 ? 3 : 0;
324
- if (point.x < leftGutter || point.x >= Math.min(mainWidth, surface.viewport.width + leftGutter)) return null;
325
-
326
- const top = Math.max(0, (surface.out.rows || surface.stage.height) - surface.stage.height);
327
- const viewRow = point.y - top;
328
- if (viewRow < 0 || viewRow >= surface.viewport.height) return null;
329
-
330
- const flat = surface.transcript.flatten(surface.viewport.width);
331
- const visible = Math.max(0, Math.min(surface.viewport.height, flat.rows.length - surface.viewport.scrollTop));
332
- const padding = surface.viewport.height - visible;
369
+ if (px < leftGutter || px >= Math.min(mainWidth, viewportWidth + leftGutter)) return null;
370
+
371
+ const outRows = Number.isFinite(surface.out?.rows) && (surface.out?.rows as number) > 0
372
+ ? Math.floor(surface.out?.rows as number)
373
+ : stageHeight;
374
+ const top = Math.max(0, outRows - stageHeight);
375
+ const viewRow = py - top;
376
+ if (viewRow < 0 || viewRow >= viewportHeight) return null;
377
+
378
+ const scrollTop = Number.isFinite(surface.viewport?.scrollTop) ? Math.max(0, Math.floor(surface.viewport.scrollTop)) : 0;
379
+ const flat = surface.transcript.flatten(viewportWidth);
380
+ if (!Array.isArray(flat?.rows)) return null;
381
+ const visible = Math.max(0, Math.min(viewportHeight, flat.rows.length - scrollTop));
382
+ const padding = viewportHeight - visible;
333
383
  if (viewRow < padding) return null;
334
384
 
335
- const row = surface.viewport.scrollTop + viewRow - padding;
385
+ const row = scrollTop + viewRow - padding;
336
386
  const rawRow = flat.rows[row];
337
387
  if (!rawRow) return null;
338
388
 
@@ -341,7 +391,7 @@ export function detectLinkAtPoint(
341
391
  const links = extractRowLinks(rawRow, row, rawMessageText, prevRawRow);
342
392
  if (!links.length) return null;
343
393
 
344
- const col = point.x - leftGutter;
394
+ const col = px - leftGutter;
345
395
  for (const link of links) {
346
396
  if (col >= link.startCol && col <= link.endCol) {
347
397
  return link;
@@ -364,18 +414,26 @@ export interface OpenLinkOptions {
364
414
  * Open an HTTP/HTTPS/file URL in the system default browser or handler without blocking the TUI.
365
415
  */
366
416
  export function openDetectedLink(url: string, options: OpenLinkOptions = {}): boolean {
367
- if (!url || !/^(?:https?|file):\/\//i.test(url)) return false;
417
+ if (
418
+ typeof url !== 'string'
419
+ || !url
420
+ || /[\x00-\x1f\x7f\s]/.test(url)
421
+ || !/^(?:https?|file):\/\//i.test(url)
422
+ ) {
423
+ return false;
424
+ }
368
425
 
369
- const now = options.now ?? Date.now();
370
- const debounceMs = options.debounceMs ?? 800;
371
- if (url === lastOpenedUrl && now - lastOpenedAt < debounceMs) {
426
+ const safeOptions: OpenLinkOptions = options && typeof options === 'object' ? options : {};
427
+ const now = typeof safeOptions.now === 'number' && Number.isFinite(safeOptions.now) ? safeOptions.now : Date.now();
428
+ const debounceMs = typeof safeOptions.debounceMs === 'number' && Number.isFinite(safeOptions.debounceMs)
429
+ ? Math.max(0, safeOptions.debounceMs)
430
+ : 800;
431
+ if (url === lastOpenedUrl && now >= lastOpenedAt && now - lastOpenedAt < debounceMs) {
372
432
  return true;
373
433
  }
374
- lastOpenedUrl = url;
375
- lastOpenedAt = now;
376
434
 
377
- const platform = options.platform ?? process.platform;
378
- const spawnFn = options.spawnImpl ?? spawn;
435
+ const platform = safeOptions.platform ?? process.platform;
436
+ const spawnFn = safeOptions.spawnImpl ?? spawn;
379
437
 
380
438
  let command: string;
381
439
  let args: string[];
@@ -401,6 +459,8 @@ export function openDetectedLink(url: string, options: OpenLinkOptions = {}): bo
401
459
  // Ignore missing browser opener errors on headless hosts.
402
460
  });
403
461
  child.unref?.();
462
+ lastOpenedUrl = url;
463
+ lastOpenedAt = now;
404
464
  return true;
405
465
  } catch {
406
466
  return false;
package/src/tui/stage.js CHANGED
@@ -54,12 +54,14 @@ const ERASE_BELOW = '\x1b[J';
54
54
  * CAUSYNE_STAGE: off | auto | <rows> | <pct>%
55
55
  */
56
56
  export function stageHeight(out = process.stdout, env = process.env) {
57
- const setting = String(env.CAUSYNE_STAGE ?? 'auto').trim().toLowerCase();
57
+ const safeEnv = env && typeof env === 'object' ? env : {};
58
+ const setting = String(safeEnv.CAUSYNE_STAGE ?? 'auto').trim().toLowerCase();
58
59
  if (setting === 'off' || setting === '0' || setting === 'false')
59
60
  return 0;
60
- const rows = Number(out && out.rows);
61
- if (!Number.isFinite(rows) || rows <= 0)
61
+ const rawRows = Number(out && out.rows);
62
+ if (!Number.isFinite(rawRows) || rawRows <= 0)
62
63
  return 0;
64
+ const rows = Math.floor(rawRows);
63
65
  // The seam: never take the last row of the user's screen. It costs one row
64
66
  // and it is the difference between "a region" and "the screen".
65
67
  const ceiling = rows - 1;
@@ -81,13 +83,14 @@ export function stageHeight(out = process.stdout, env = process.env) {
81
83
  * answer is the scrollback renderer rather than a stage that misbehaves.
82
84
  */
83
85
  export function stageEnabled(out = process.stdout, env = process.env) {
86
+ const safeEnv = env && typeof env === 'object' ? env : {};
84
87
  if (!out || !out.isTTY)
85
88
  return false;
86
- if (String(env.TERM || '') === 'dumb')
89
+ if (String(safeEnv.TERM || '') === 'dumb')
87
90
  return false;
88
- if (env.CAUSYNE_SIMPLE_INPUT === '1')
91
+ if (safeEnv.CAUSYNE_SIMPLE_INPUT === '1')
89
92
  return false;
90
- return stageHeight(out, env) > 0;
93
+ return stageHeight(out, safeEnv) > 0;
91
94
  }
92
95
  export class Stage {
93
96
  out;
@@ -99,7 +102,11 @@ export class Stage {
99
102
  prev;
100
103
  caret;
101
104
  stats;
102
- constructor({ out = process.stdout, env = process.env, height = 0 } = {}) {
105
+ constructor(options = {}) {
106
+ const opts = options && typeof options === 'object' ? options : {};
107
+ const out = opts.out ?? process.stdout;
108
+ const env = opts.env && typeof opts.env === 'object' ? opts.env : process.env;
109
+ const height = opts.height ?? 0;
103
110
  this.out = out;
104
111
  this.env = env;
105
112
  // The CEILING, not the size. A band claimed by printing newlines costs the
@@ -107,7 +114,7 @@ export class Stage {
107
114
  // it has something to put in and grows from there. Sizing it to the screen
108
115
  // is free on an alternate screen — which is what opencode is — and on a
109
116
  // reserved band it is 73 rows of void and a banner scrolled out of sight.
110
- this.maxHeight = height > 0 ? Math.floor(height) : stageHeight(out, env);
117
+ this.maxHeight = Number.isFinite(height) && height > 0 ? Math.floor(height) : stageHeight(out, env);
111
118
  // Rows actually claimed. Zero until reserve().
112
119
  this.height = 0;
113
120
  this.reserved = false;
@@ -155,7 +162,8 @@ export class Stage {
155
162
  reserve(rows = this.maxHeight) {
156
163
  if (this.reserved || this.maxHeight < 1)
157
164
  return false;
158
- const claim = Math.max(1, Math.min(Math.floor(rows), this.maxHeight));
165
+ const requested = Number.isFinite(rows) ? Math.floor(rows) : this.maxHeight;
166
+ const claim = Math.max(1, Math.min(requested, this.maxHeight));
159
167
  this.write('\n'.repeat(claim));
160
168
  this.stats.claimed += claim;
161
169
  this.reserved = true;
@@ -179,7 +187,7 @@ export class Stage {
179
187
  * (b) permits to move it.
180
188
  */
181
189
  grow(delta) {
182
- if (!this.reserved || delta <= 0)
190
+ if (!this.reserved || !Number.isFinite(delta) || delta <= 0)
183
191
  return 0;
184
192
  const room = this.maxHeight - this.height;
185
193
  const claim = Math.min(Math.floor(delta), room);
@@ -208,6 +216,8 @@ export class Stage {
208
216
  const out = new Array(this.height);
209
217
  for (let i = 0; i < this.height; i++) {
210
218
  let row = rows && rows[i] != null ? String(rows[i]) : '';
219
+ if (row.includes('\r'))
220
+ row = row.replace(/\r/g, '');
211
221
  if (row.includes('\n'))
212
222
  row = row.split('\n')[0] ?? '';
213
223
  out[i] = visibleWidth(row) <= limit ? row : truncate(row, limit, '');
@@ -215,7 +225,9 @@ export class Stage {
215
225
  return out;
216
226
  }
217
227
  moveTo(row) {
218
- const target = Math.max(0, Math.min(row, this.height - 1));
228
+ if (!Number.isFinite(row) || this.height <= 0)
229
+ return;
230
+ const target = Math.max(0, Math.min(Math.floor(row), this.height - 1));
219
231
  const delta = target - this.cursor;
220
232
  // CUU/CUD only. Never a newline: on the band's last row a newline scrolls
221
233
  // the terminal, which would move the whole block out from under the diff.
@@ -240,6 +252,17 @@ export class Stage {
240
252
  this.invalidate();
241
253
  return true;
242
254
  }
255
+ unclosedOsc8Term(row) {
256
+ if (!row.includes('\x1b]8;'))
257
+ return '';
258
+ const osc8Re = /\x1b\]8;[^;]*;([^\x07\x1b]*)(\x07|\x1b\\)/g;
259
+ let active = '';
260
+ let match;
261
+ while ((match = osc8Re.exec(row)) !== null) {
262
+ active = (match[1] ?? '').length > 0 ? (match[2] ?? '\x1b\\') : '';
263
+ }
264
+ return active;
265
+ }
243
266
  /**
244
267
  * Repaint the band. Rows that did not change cost nothing.
245
268
  *
@@ -247,11 +270,12 @@ export class Stage {
247
270
  * idle frame is free.
248
271
  */
249
272
  paint(rows, caret = null) {
250
- if (!this.reserved)
273
+ if (!this.reserved || this.height <= 0)
251
274
  return 0;
252
275
  const next = this.normalize(rows);
276
+ const rawCol = caret && Number.isFinite(caret.col) ? Math.floor(caret.col) : 0;
253
277
  const target = caret && Number.isFinite(caret.row)
254
- ? { row: Math.max(0, Math.min(Math.floor(caret.row), this.height - 1)), col: Math.max(0, Math.min(Math.max(0, this.width() - 2), Math.floor(caret.col) || 0)), hideCursor: Boolean(caret.hideCursor) }
278
+ ? { row: Math.max(0, Math.min(Math.floor(caret.row), this.height - 1)), col: Math.max(0, Math.min(Math.max(0, this.width() - 2), rawCol)), hideCursor: Boolean(caret.hideCursor) }
255
279
  : { row: this.height - 1, col: 0, hideCursor: Boolean(caret?.hideCursor) };
256
280
  const changed = [];
257
281
  for (let i = 0; i < this.height; i++) {
@@ -266,7 +290,11 @@ export class Stage {
266
290
  this.write(SYNC_ON + HIDE_CURSOR + NOWRAP_ON);
267
291
  for (const i of changed) {
268
292
  this.moveTo(i);
269
- this.write('\r' + (next[i] ?? '') + ERASE_LINE);
293
+ const content = next[i] ?? '';
294
+ const osc8Term = this.unclosedOsc8Term(content);
295
+ const osc8Reset = osc8Term ? `\x1b]8;;${osc8Term}` : '';
296
+ const reset = content.includes('\x1b') && !content.endsWith('\x1b[0m') ? '\x1b[0m' : '';
297
+ this.write('\r' + content + osc8Reset + reset + ERASE_LINE);
270
298
  }
271
299
  this.moveTo(target.row);
272
300
  this.write('\r');
@@ -294,7 +322,9 @@ export class Stage {
294
322
  this.moveTo(0);
295
323
  this.write('\r' + ERASE_BELOW + SHOW_CURSOR + '\x1b[0 q' + SYNC_OFF);
296
324
  this.reserved = false;
325
+ this.height = 0;
297
326
  this.cursor = 0;
327
+ this.caret = { row: 0, col: 0 };
298
328
  this.prev = [];
299
329
  }
300
330
  /**
@@ -331,7 +361,7 @@ export class Stage {
331
361
  * (ChatPrompt already settles resize at 60ms).
332
362
  */
333
363
  resize(height = 0, claim = 0) {
334
- const next = height > 0 ? Math.floor(height) : stageHeight(this.out, this.env);
364
+ const next = Number.isFinite(height) && height > 0 ? Math.floor(height) : stageHeight(this.out, this.env);
335
365
  const wasReserved = this.reserved;
336
366
  if (wasReserved)
337
367
  this.collapse();
@@ -339,8 +369,9 @@ export class Stage {
339
369
  this.height = 0;
340
370
  if (next < 1)
341
371
  return false;
372
+ const nextClaim = Number.isFinite(claim) && claim > 0 ? Math.floor(claim) : next;
342
373
  if (wasReserved)
343
- return this.reserve(claim > 0 ? claim : next);
374
+ return this.reserve(nextClaim);
344
375
  return false;
345
376
  }
346
377
  /**