@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
@@ -296,6 +296,12 @@ function ensureLaunchShim(resolvedExecutable: string, resourceDirectory: string)
296
296
  return shimExecutable;
297
297
  }
298
298
 
299
+ function isChromiumExecutablePath(filePath: string): boolean {
300
+ return /^(?:google-chrome|google chrome|chrome|chromium-browser|chromium|msedge|microsoft-edge|microsoft edge)(?:-(?:stable|beta|dev|canary))?(?:\.exe)?$/i.test(
301
+ path.basename(filePath)
302
+ );
303
+ }
304
+
299
305
  /** Discover existing installations only. Never downloads or uses a personal profile. */
300
306
  export function resolveChromiumRuntime(configured?: string): PreparedBrowserRuntime | null {
301
307
  const candidates = configured ? [configured] : process.platform === 'darwin'
@@ -315,12 +321,13 @@ export function resolveChromiumRuntime(configured?: string): PreparedBrowserRunt
315
321
  export function resolveBrowserRuntime(): PreparedBrowserRuntime {
316
322
  const configured = process.env.CAUSYNE_BROWSER_EXECUTABLE?.trim()
317
323
  || process.env.CAMOUFOX_EXECUTABLE_PATH?.trim();
318
- const candidates = configured
319
- ? [resolveCandidateExecutablePath(path.resolve(configured))]
324
+ const resolvedConfigured = configured ? path.resolve(configured) : undefined;
325
+ const candidates = resolvedConfigured
326
+ ? [resolveCandidateExecutablePath(resolvedConfigured)]
320
327
  : candidateExecutables().map(resolveCandidateExecutablePath);
321
328
  const executablePath = candidates.find(existsSync);
322
- if (configured && /(?:chrome|chromium|msedge)(?:\.exe)?$/i.test(path.basename(configured))) {
323
- const chromium = resolveChromiumRuntime(configured);
329
+ if (resolvedConfigured && isChromiumExecutablePath(resolvedConfigured)) {
330
+ const chromium = resolveChromiumRuntime(resolvedConfigured);
324
331
  if (chromium) return chromium;
325
332
  }
326
333
  if (!executablePath) {
@@ -377,14 +384,15 @@ export function isBrowserRuntimeInstalled(): boolean {
377
384
  try {
378
385
  const configured = process.env.CAUSYNE_BROWSER_EXECUTABLE?.trim()
379
386
  || process.env.CAMOUFOX_EXECUTABLE_PATH?.trim();
380
- const candidates = configured
381
- ? [resolveCandidateExecutablePath(path.resolve(configured))]
387
+ const resolvedConfigured = configured ? path.resolve(configured) : undefined;
388
+ const candidates = resolvedConfigured
389
+ ? [resolveCandidateExecutablePath(resolvedConfigured)]
382
390
  : candidateExecutables().map(resolveCandidateExecutablePath);
383
391
  // Match launch-time discovery: Chromium is a supported installed runtime
384
392
  // too. The former Camoufox-only check suppressed host verification even
385
393
  // when resolveBrowserRuntime could launch the installed Chrome browser.
386
- if (configured && /(?:chrome|chromium|msedge)(?:\.exe)?$/i.test(path.basename(configured))) {
387
- return resolveChromiumRuntime(path.resolve(configured)) !== null;
394
+ if (resolvedConfigured && isChromiumExecutablePath(resolvedConfigured)) {
395
+ return resolveChromiumRuntime(resolvedConfigured) !== null;
388
396
  }
389
397
  const hasCamoufox = candidates.some(candidate => {
390
398
  try {
@@ -155,6 +155,11 @@ export function validateExtractSchema(schema) {
155
155
  }
156
156
  return { ok: true };
157
157
  }
158
+ function boundedFiniteInteger(value, fallback, min, max) {
159
+ const numeric = typeof value === 'string' && !value.trim() ? Number.NaN : Number(value ?? fallback);
160
+ const base = Number.isFinite(numeric) ? Math.floor(numeric) : fallback;
161
+ return Math.max(min, Math.min(max, base));
162
+ }
158
163
  function coerceSchemaValue(raw, type) {
159
164
  if (raw == null)
160
165
  return null;
@@ -229,6 +234,12 @@ export function isDeadContextError(err) {
229
234
  || msg.includes('Context closed')
230
235
  || msg.includes('Browser closed');
231
236
  }
237
+ export function isExecutionContextDestroyedError(err) {
238
+ const msg = errorMessage(err);
239
+ return msg.includes('Execution context was destroyed')
240
+ || msg.includes('Cannot find context with specified id')
241
+ || msg.includes('Frame was detached');
242
+ }
232
243
  export function isPageCrashedError(err) {
233
244
  const msg = errorMessage(err);
234
245
  return msg.includes('Page crashed')
@@ -771,7 +782,7 @@ export class CausyneBrowser {
771
782
  ...windowSnapshot(state.lastSnapshot, offset),
772
783
  tabId: state.id,
773
784
  url: state.page.url(),
774
- title: await state.page.title(),
785
+ title: await this.safePageTitle(state.page),
775
786
  refsCount: state.refs.size,
776
787
  ...(state.lastStructure ? { structure: state.lastStructure } : {})
777
788
  };
@@ -1464,18 +1475,18 @@ export class CausyneBrowser {
1464
1475
  ? (expandSearchMacro(action.macro, action.query ?? action.text ?? '') ?? undefined)
1465
1476
  : action.url;
1466
1477
  const state = await this.createTab(initialUrl);
1467
- return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1478
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
1468
1479
  }
1469
1480
  if (action.type === 'listTabs' || action.type === 'list_tabs') {
1470
1481
  const data = await Promise.all([...this.tabs.values()].filter(tab => !tab.page.isClosed() && !tab.crashed).map(async (tab) => ({
1471
- tabId: tab.id, active: tab.id === this.activeTabId, url: tab.page.url(), title: await tab.page.title()
1482
+ tabId: tab.id, active: tab.id === this.activeTabId, url: tab.page.url(), title: await this.safePageTitle(tab.page)
1472
1483
  })));
1473
1484
  return { action: action.type, data };
1474
1485
  }
1475
1486
  const requested = this.requestedTab(action);
1476
1487
  const state = requested ?? await this.activeTab();
1477
1488
  if (action.type === 'switchTab' || action.type === 'switch_tab') {
1478
- return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1489
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
1479
1490
  }
1480
1491
  if (action.type === 'closeTab' || action.type === 'close_tab') {
1481
1492
  await state.page.close();
@@ -1491,13 +1502,13 @@ export class CausyneBrowser {
1491
1502
  }
1492
1503
  if (action.type === 'goto' || action.type === 'open' || action.type === 'navigate') {
1493
1504
  await this.navigateWithMacroFallback(state, action);
1494
- return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1505
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
1495
1506
  }
1496
1507
  if (action.type === 'preview') {
1497
1508
  if (typeof action.filePath !== 'string')
1498
1509
  throw new Error('preview requires filePath');
1499
1510
  await this.preview(state, action.filePath, workspace);
1500
- return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title(), output: 'Rendered in an isolated internal preview. This browser-only origin is not user-openable. Start a real local server with sysRunBg if the user needs an interactive URL.' };
1511
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page), output: 'Rendered in an isolated internal preview. This browser-only origin is not user-openable. Start a real local server with sysRunBg if the user needs an interactive URL.' };
1501
1512
  }
1502
1513
  if (action.type === 'snapshot' || action.type === 'scrape') {
1503
1514
  const snapshot = await this.snapshot(action.offset ?? 0);
@@ -1553,7 +1564,7 @@ export class CausyneBrowser {
1553
1564
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Pressed ${normalizedKey}` };
1554
1565
  }
1555
1566
  if (action.type === 'scroll') {
1556
- const amount = Math.max(1, Math.min(10_000, Math.floor(action.amount ?? 700)));
1567
+ const amount = boundedFiniteInteger(action.amount, 700, 1, 10_000);
1557
1568
  const direction = action.direction ?? 'down';
1558
1569
  const x = direction === 'left' ? -amount : direction === 'right' ? amount : 0;
1559
1570
  const y = direction === 'up' ? -amount : direction === 'down' ? amount : 0;
@@ -1561,7 +1572,7 @@ export class CausyneBrowser {
1561
1572
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Scrolled ${direction} ${amount}px` };
1562
1573
  }
1563
1574
  if (action.type === 'wait') {
1564
- const waitTimeout = Math.max(50, Math.min(30_000, Number(action.timeout ?? action.amount ?? 1_000)));
1575
+ const waitTimeout = boundedFiniteInteger(action.timeout ?? action.amount, 1_000, 50, 30_000);
1565
1576
  if (action.selector) {
1566
1577
  const validationErr = selectorValidationError(action.selector);
1567
1578
  if (validationErr)
@@ -1673,7 +1684,24 @@ export class CausyneBrowser {
1673
1684
  throw new Error(`Unsupported browser action: ${action.type}`);
1674
1685
  }
1675
1686
  state.refs.clear();
1676
- return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1687
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
1688
+ }
1689
+ /** Reads page.title() safely even if an immediate client redirect destroyed the mid-flight execution context. */
1690
+ async safePageTitle(page) {
1691
+ try {
1692
+ return await page.title();
1693
+ }
1694
+ catch (error) {
1695
+ if (!isExecutionContextDestroyedError(error))
1696
+ throw error;
1697
+ try {
1698
+ await page.waitForLoadState('domcontentloaded', { timeout: 2000 });
1699
+ return await page.title();
1700
+ }
1701
+ catch {
1702
+ return '';
1703
+ }
1704
+ }
1677
1705
  }
1678
1706
  touch() {
1679
1707
  if (this.idleTimer)
@@ -177,6 +177,12 @@ export function validateExtractSchema(schema: unknown): { ok: boolean; error?: s
177
177
  return { ok: true };
178
178
  }
179
179
 
180
+ function boundedFiniteInteger(value: unknown, fallback: number, min: number, max: number): number {
181
+ const numeric = typeof value === 'string' && !value.trim() ? Number.NaN : Number(value ?? fallback);
182
+ const base = Number.isFinite(numeric) ? Math.floor(numeric) : fallback;
183
+ return Math.max(min, Math.min(max, base));
184
+ }
185
+
180
186
  function coerceSchemaValue(raw: string | null, type?: string): unknown {
181
187
  if (raw == null) return null;
182
188
  if (type === 'string' || !type) return String(raw).trim();
@@ -293,6 +299,13 @@ export function isDeadContextError(err: unknown): boolean {
293
299
  || msg.includes('Browser closed');
294
300
  }
295
301
 
302
+ export function isExecutionContextDestroyedError(err: unknown): boolean {
303
+ const msg = errorMessage(err);
304
+ return msg.includes('Execution context was destroyed')
305
+ || msg.includes('Cannot find context with specified id')
306
+ || msg.includes('Frame was detached');
307
+ }
308
+
296
309
  export function isPageCrashedError(err: unknown): boolean {
297
310
  const msg = errorMessage(err);
298
311
  return msg.includes('Page crashed')
@@ -1040,7 +1053,7 @@ export class CausyneBrowser {
1040
1053
  ...windowSnapshot(state.lastSnapshot, offset),
1041
1054
  tabId: state.id,
1042
1055
  url: state.page.url(),
1043
- title: await state.page.title(),
1056
+ title: await this.safePageTitle(state.page),
1044
1057
  refsCount: state.refs.size,
1045
1058
  ...(state.lastStructure ? { structure: state.lastStructure } : {})
1046
1059
  };
@@ -1685,18 +1698,18 @@ export class CausyneBrowser {
1685
1698
  ? (expandSearchMacro(action.macro, action.query ?? action.text ?? '') ?? undefined)
1686
1699
  : action.url;
1687
1700
  const state = await this.createTab(initialUrl);
1688
- return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1701
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
1689
1702
  }
1690
1703
  if (action.type === 'listTabs' || action.type === 'list_tabs') {
1691
1704
  const data = await Promise.all([...this.tabs.values()].filter(tab => !tab.page.isClosed() && !tab.crashed).map(async tab => ({
1692
- tabId: tab.id, active: tab.id === this.activeTabId, url: tab.page.url(), title: await tab.page.title()
1705
+ tabId: tab.id, active: tab.id === this.activeTabId, url: tab.page.url(), title: await this.safePageTitle(tab.page)
1693
1706
  })));
1694
1707
  return { action: action.type, data };
1695
1708
  }
1696
1709
  const requested = this.requestedTab(action);
1697
1710
  const state = requested ?? await this.activeTab();
1698
1711
  if (action.type === 'switchTab' || action.type === 'switch_tab') {
1699
- return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1712
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
1700
1713
  }
1701
1714
  if (action.type === 'closeTab' || action.type === 'close_tab') {
1702
1715
  await state.page.close();
@@ -1711,12 +1724,12 @@ export class CausyneBrowser {
1711
1724
  }
1712
1725
  if (action.type === 'goto' || action.type === 'open' || action.type === 'navigate') {
1713
1726
  await this.navigateWithMacroFallback(state, action);
1714
- return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1727
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
1715
1728
  }
1716
1729
  if (action.type === 'preview') {
1717
1730
  if (typeof action.filePath !== 'string') throw new Error('preview requires filePath');
1718
1731
  await this.preview(state, action.filePath, workspace);
1719
- return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title(), output: 'Rendered in an isolated internal preview. This browser-only origin is not user-openable. Start a real local server with sysRunBg if the user needs an interactive URL.' };
1732
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page), output: 'Rendered in an isolated internal preview. This browser-only origin is not user-openable. Start a real local server with sysRunBg if the user needs an interactive URL.' };
1720
1733
  }
1721
1734
  if (action.type === 'snapshot' || action.type === 'scrape') {
1722
1735
  const snapshot = await this.snapshot(action.offset ?? 0);
@@ -1770,7 +1783,7 @@ export class CausyneBrowser {
1770
1783
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Pressed ${normalizedKey}` };
1771
1784
  }
1772
1785
  if (action.type === 'scroll') {
1773
- const amount = Math.max(1, Math.min(10_000, Math.floor(action.amount ?? 700)));
1786
+ const amount = boundedFiniteInteger(action.amount, 700, 1, 10_000);
1774
1787
  const direction = action.direction ?? 'down';
1775
1788
  const x = direction === 'left' ? -amount : direction === 'right' ? amount : 0;
1776
1789
  const y = direction === 'up' ? -amount : direction === 'down' ? amount : 0;
@@ -1778,7 +1791,7 @@ export class CausyneBrowser {
1778
1791
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Scrolled ${direction} ${amount}px` };
1779
1792
  }
1780
1793
  if (action.type === 'wait') {
1781
- const waitTimeout = Math.max(50, Math.min(30_000, Number(action.timeout ?? action.amount ?? 1_000)));
1794
+ const waitTimeout = boundedFiniteInteger(action.timeout ?? action.amount, 1_000, 50, 30_000);
1782
1795
  if (action.selector) {
1783
1796
  const validationErr = selectorValidationError(action.selector);
1784
1797
  if (validationErr) throw new Error(validationErr);
@@ -1873,7 +1886,22 @@ export class CausyneBrowser {
1873
1886
  throw new Error(`Unsupported browser action: ${action.type}`);
1874
1887
  }
1875
1888
  state.refs.clear();
1876
- return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
1889
+ return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
1890
+ }
1891
+
1892
+ /** Reads page.title() safely even if an immediate client redirect destroyed the mid-flight execution context. */
1893
+ private async safePageTitle(page: BrowserPage): Promise<string> {
1894
+ try {
1895
+ return await page.title();
1896
+ } catch (error) {
1897
+ if (!isExecutionContextDestroyedError(error)) throw error;
1898
+ try {
1899
+ await page.waitForLoadState('domcontentloaded', { timeout: 2000 });
1900
+ return await page.title();
1901
+ } catch {
1902
+ return '';
1903
+ }
1904
+ }
1877
1905
  }
1878
1906
 
1879
1907
  private touch(): void {
@@ -1,14 +1,20 @@
1
+ import { isIP } from 'node:net';
2
+ import { isPrivateAddress } from './urlPolicy.js';
1
3
  const MAX_PROVIDER_BYTES = 2 * 1024 * 1024;
2
4
  const MAX_RESULTS = 10;
3
5
  const SEARCH_TIMEOUT_MS = 15_000;
4
6
  function decodeEntities(value) {
5
7
  const named = { amp: '&', apos: "'", gt: '>', lt: '<', nbsp: ' ', quot: '"' };
6
8
  return value.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (full, entity) => {
7
- if (entity.startsWith('#x'))
8
- return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
9
- if (entity.startsWith('#'))
10
- return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
11
- return named[entity.toLowerCase()] ?? full;
9
+ const normalized = entity.toLowerCase();
10
+ if (normalized.startsWith('#')) {
11
+ const point = normalized.startsWith('#x')
12
+ ? Number.parseInt(normalized.slice(2), 16)
13
+ : Number.parseInt(normalized.slice(1), 10);
14
+ return Number.isInteger(point) && point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff)
15
+ ? String.fromCodePoint(point) : full;
16
+ }
17
+ return named[normalized] ?? full;
12
18
  });
13
19
  }
14
20
  function cleanMarkup(value) {
@@ -21,6 +27,11 @@ function publicResultUrl(value) {
21
27
  const parsed = new URL(decodeEntities(value));
22
28
  if (!['http:', 'https:'].includes(parsed.protocol))
23
29
  return null;
30
+ const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
31
+ if (parsed.username || parsed.password || host === 'localhost' ||
32
+ host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal') ||
33
+ (isIP(host) !== 0 && isPrivateAddress(host)))
34
+ return null;
24
35
  if (/(^|\.)(bing|duckduckgo)\.com$/i.test(parsed.hostname))
25
36
  return null;
26
37
  return parsed.href;
@@ -49,7 +60,7 @@ export function parseBingRss(xml) {
49
60
  export function parseDuckDuckGoHtml(html) {
50
61
  const results = [];
51
62
  const seen = new Set();
52
- const anchors = [...html.matchAll(/<a\b[^>]*class=["'][^"']*result__a[^"']*["'][^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)];
63
+ const anchors = [...html.matchAll(/<a\b(?=[^>]*\bclass=["'][^"']*\bresult__a\b[^"']*["'])[^>]*\bhref=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)];
53
64
  for (const [index, anchor] of anchors.entries()) {
54
65
  let href = decodeEntities(anchor[1] ?? '');
55
66
  try {
@@ -108,7 +119,7 @@ export async function searchPublicWeb(query, options = {}) {
108
119
  const fetchImpl = options.fetchImpl ?? fetch;
109
120
  const controller = new AbortController();
110
121
  const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
111
- const signal = options.signal ?? controller.signal;
122
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
112
123
  const providers = [
113
124
  {
114
125
  engine: 'duckduckgo-html',
@@ -1,3 +1,5 @@
1
+ import { isIP } from 'node:net';
2
+ import { isPrivateAddress } from './urlPolicy.js';
1
3
  const MAX_PROVIDER_BYTES = 2 * 1024 * 1024;
2
4
  const MAX_RESULTS = 10;
3
5
  const SEARCH_TIMEOUT_MS = 15_000;
@@ -17,9 +19,15 @@ interface SearchOptions {
17
19
  function decodeEntities(value: string): string {
18
20
  const named: Record<string, string> = { amp: '&', apos: "'", gt: '>', lt: '<', nbsp: ' ', quot: '"' };
19
21
  return value.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (full, entity: string) => {
20
- if (entity.startsWith('#x')) return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
21
- if (entity.startsWith('#')) return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
22
- return named[entity.toLowerCase()] ?? full;
22
+ const normalized = entity.toLowerCase();
23
+ if (normalized.startsWith('#')) {
24
+ const point = normalized.startsWith('#x')
25
+ ? Number.parseInt(normalized.slice(2), 16)
26
+ : Number.parseInt(normalized.slice(1), 10);
27
+ return Number.isInteger(point) && point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff)
28
+ ? String.fromCodePoint(point) : full;
29
+ }
30
+ return named[normalized] ?? full;
23
31
  });
24
32
  }
25
33
 
@@ -33,6 +41,10 @@ function publicResultUrl(value: string): string | null {
33
41
  try {
34
42
  const parsed = new URL(decodeEntities(value));
35
43
  if (!['http:', 'https:'].includes(parsed.protocol)) return null;
44
+ const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
45
+ if (parsed.username || parsed.password || host === 'localhost' ||
46
+ host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal') ||
47
+ (isIP(host) !== 0 && isPrivateAddress(host))) return null;
36
48
  if (/(^|\.)(bing|duckduckgo)\.com$/i.test(parsed.hostname)) return null;
37
49
  return parsed.href;
38
50
  } catch {
@@ -59,7 +71,7 @@ export function parseBingRss(xml: string): SearchResult[] {
59
71
  export function parseDuckDuckGoHtml(html: string): SearchResult[] {
60
72
  const results: SearchResult[] = [];
61
73
  const seen = new Set<string>();
62
- const anchors = [...html.matchAll(/<a\b[^>]*class=["'][^"']*result__a[^"']*["'][^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)];
74
+ const anchors = [...html.matchAll(/<a\b(?=[^>]*\bclass=["'][^"']*\bresult__a\b[^"']*["'])[^>]*\bhref=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)];
63
75
  for (const [index, anchor] of anchors.entries()) {
64
76
  let href = decodeEntities(anchor[1] ?? '');
65
77
  try {
@@ -112,7 +124,7 @@ export async function searchPublicWeb(query: string, options: SearchOptions = {}
112
124
  const fetchImpl = options.fetchImpl ?? fetch;
113
125
  const controller = new AbortController();
114
126
  const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
115
- const signal = options.signal ?? controller.signal;
127
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
116
128
  const providers = [
117
129
  {
118
130
  engine: 'duckduckgo-html',
@@ -10,7 +10,7 @@ export function windowSnapshot(snapshot, requestedOffset = 0) {
10
10
  }
11
11
  const contentBudget = MAX_SNAPSHOT_CHARS - SNAPSHOT_TAIL_CHARS - 240;
12
12
  const maximumOffset = Math.max(0, totalChars - SNAPSHOT_TAIL_CHARS);
13
- const offset = Math.min(Math.max(0, Math.floor(requestedOffset)), maximumOffset);
13
+ const offset = Math.min(Math.max(0, Number.isFinite(requestedOffset) ? Math.floor(requestedOffset) : 0), maximumOffset);
14
14
  const chunkEnd = Math.min(offset + contentBudget, maximumOffset);
15
15
  const hasMore = chunkEnd < maximumOffset;
16
16
  const tail = text.slice(-SNAPSHOT_TAIL_CHARS);
@@ -22,7 +22,7 @@ export function windowSnapshot(snapshot: string, requestedOffset = 0): SnapshotW
22
22
 
23
23
  const contentBudget = MAX_SNAPSHOT_CHARS - SNAPSHOT_TAIL_CHARS - 240;
24
24
  const maximumOffset = Math.max(0, totalChars - SNAPSHOT_TAIL_CHARS);
25
- const offset = Math.min(Math.max(0, Math.floor(requestedOffset)), maximumOffset);
25
+ const offset = Math.min(Math.max(0, Number.isFinite(requestedOffset) ? Math.floor(requestedOffset) : 0), maximumOffset);
26
26
  const chunkEnd = Math.min(offset + contentBudget, maximumOffset);
27
27
  const hasMore = chunkEnd < maximumOffset;
28
28
  const tail = text.slice(-SNAPSHOT_TAIL_CHARS);
@@ -23,18 +23,27 @@ function isPrivateIpv4(address) {
23
23
  }
24
24
  function isPrivateIpv6(address) {
25
25
  const normalized = address.toLowerCase().split('%')[0] ?? '';
26
- if (normalized === '::' || normalized === '::1')
26
+ let canonical = normalized;
27
+ try {
28
+ canonical = new URL(`http://[${normalized}]/`).hostname.slice(1, -1);
29
+ }
30
+ catch {
27
31
  return true;
28
- if (normalized.startsWith('fc') || normalized.startsWith('fd') || normalized.startsWith('fe8')
29
- || normalized.startsWith('fe9') || normalized.startsWith('fea') || normalized.startsWith('feb')
30
- || normalized.startsWith('fec') || normalized.startsWith('fed') || normalized.startsWith('fee')
31
- || normalized.startsWith('fef') || normalized.startsWith('ff') || normalized.startsWith('2001:db8:')
32
- || normalized === '2001:db8::' || normalized.startsWith('64:ff9b:'))
32
+ }
33
+ if (canonical === '::' || canonical === '::1')
34
+ return true;
35
+ if (canonical.startsWith('fc') || canonical.startsWith('fd') || canonical.startsWith('fe8')
36
+ || canonical.startsWith('fe9') || canonical.startsWith('fea') || canonical.startsWith('feb')
37
+ || canonical.startsWith('fec') || canonical.startsWith('fed') || canonical.startsWith('fee')
38
+ || canonical.startsWith('fef') || canonical.startsWith('ff') || canonical.startsWith('2001:db8:')
39
+ || canonical === '2001:db8::' || canonical.startsWith('64:ff9b:'))
33
40
  return true;
34
41
  if (normalized.startsWith('::ffff:')) {
35
42
  const mapped = normalized.slice('::ffff:'.length);
36
43
  return isIP(mapped) === 4 ? isPrivateIpv4(mapped) : true;
37
44
  }
45
+ if (canonical.startsWith('::ffff:'))
46
+ return true;
38
47
  return false;
39
48
  }
40
49
  export function isPrivateAddress(address) {
@@ -87,8 +96,9 @@ export async function assertPublicWebUrl(value) {
87
96
  throw new Error('URLs containing credentials are not allowed');
88
97
  if (blockedHostname(url.hostname))
89
98
  throw new Error('Local and internal hostnames are not allowed');
90
- const literalVersion = isIP(url.hostname);
91
- const addresses = literalVersion ? [url.hostname] : await resolvedAddresses(url.hostname);
99
+ const literalHost = url.hostname.replace(/^\[|\]$/g, '');
100
+ const literalVersion = isIP(literalHost);
101
+ const addresses = literalVersion ? [literalHost] : await resolvedAddresses(url.hostname);
92
102
  if (addresses.length === 0 || addresses.some(isPrivateAddress)) {
93
103
  throw new Error('Local, private, link-local, multicast, and reserved network addresses are not allowed');
94
104
  }
@@ -112,8 +122,9 @@ export async function assertBrowserNavigableUrl(value) {
112
122
  }
113
123
  if (blockedHostname(url.hostname))
114
124
  throw new Error('Local and internal hostnames are not allowed');
115
- const literalVersion = isIP(url.hostname);
116
- const addresses = literalVersion ? [url.hostname] : await resolvedAddresses(url.hostname);
125
+ const literalHost = url.hostname.replace(/^\[|\]$/g, '');
126
+ const literalVersion = isIP(literalHost);
127
+ const addresses = literalVersion ? [literalHost] : await resolvedAddresses(url.hostname);
117
128
  if (addresses.length === 0 || addresses.some(isPrivateAddress)) {
118
129
  throw new Error('Local, private, link-local, multicast, and reserved network addresses are not allowed');
119
130
  }
@@ -25,16 +25,23 @@ function isPrivateIpv4(address: string): boolean {
25
25
 
26
26
  function isPrivateIpv6(address: string): boolean {
27
27
  const normalized = address.toLowerCase().split('%')[0] ?? '';
28
- if (normalized === '::' || normalized === '::1') return true;
29
- if (normalized.startsWith('fc') || normalized.startsWith('fd') || normalized.startsWith('fe8')
30
- || normalized.startsWith('fe9') || normalized.startsWith('fea') || normalized.startsWith('feb')
31
- || normalized.startsWith('fec') || normalized.startsWith('fed') || normalized.startsWith('fee')
32
- || normalized.startsWith('fef') || normalized.startsWith('ff') || normalized.startsWith('2001:db8:')
33
- || normalized === '2001:db8::' || normalized.startsWith('64:ff9b:')) return true;
28
+ let canonical = normalized;
29
+ try {
30
+ canonical = new URL(`http://[${normalized}]/`).hostname.slice(1, -1);
31
+ } catch {
32
+ return true;
33
+ }
34
+ if (canonical === '::' || canonical === '::1') return true;
35
+ if (canonical.startsWith('fc') || canonical.startsWith('fd') || canonical.startsWith('fe8')
36
+ || canonical.startsWith('fe9') || canonical.startsWith('fea') || canonical.startsWith('feb')
37
+ || canonical.startsWith('fec') || canonical.startsWith('fed') || canonical.startsWith('fee')
38
+ || canonical.startsWith('fef') || canonical.startsWith('ff') || canonical.startsWith('2001:db8:')
39
+ || canonical === '2001:db8::' || canonical.startsWith('64:ff9b:')) return true;
34
40
  if (normalized.startsWith('::ffff:')) {
35
41
  const mapped = normalized.slice('::ffff:'.length);
36
42
  return isIP(mapped) === 4 ? isPrivateIpv4(mapped) : true;
37
43
  }
44
+ if (canonical.startsWith('::ffff:')) return true;
38
45
  return false;
39
46
  }
40
47
 
@@ -84,8 +91,9 @@ export async function assertPublicWebUrl(value: string): Promise<URL> {
84
91
  if (url.username || url.password) throw new Error('URLs containing credentials are not allowed');
85
92
  if (blockedHostname(url.hostname)) throw new Error('Local and internal hostnames are not allowed');
86
93
 
87
- const literalVersion = isIP(url.hostname);
88
- const addresses = literalVersion ? [url.hostname] : await resolvedAddresses(url.hostname);
94
+ const literalHost = url.hostname.replace(/^\[|\]$/g, '');
95
+ const literalVersion = isIP(literalHost);
96
+ const addresses = literalVersion ? [literalHost] : await resolvedAddresses(url.hostname);
89
97
  if (addresses.length === 0 || addresses.some(isPrivateAddress)) {
90
98
  throw new Error('Local, private, link-local, multicast, and reserved network addresses are not allowed');
91
99
  }
@@ -110,8 +118,9 @@ export async function assertBrowserNavigableUrl(value: string): Promise<URL> {
110
118
 
111
119
  if (blockedHostname(url.hostname)) throw new Error('Local and internal hostnames are not allowed');
112
120
 
113
- const literalVersion = isIP(url.hostname);
114
- const addresses = literalVersion ? [url.hostname] : await resolvedAddresses(url.hostname);
121
+ const literalHost = url.hostname.replace(/^\[|\]$/g, '');
122
+ const literalVersion = isIP(literalHost);
123
+ const addresses = literalVersion ? [literalHost] : await resolvedAddresses(url.hostname);
115
124
  if (addresses.length === 0 || addresses.some(isPrivateAddress)) {
116
125
  throw new Error('Local, private, link-local, multicast, and reserved network addresses are not allowed');
117
126
  }
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
+ const MAX_ACTIVE_PREVIEWS = 128;
4
5
  const MIME = {
5
6
  '.html': 'text/html', '.htm': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
6
7
  '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
@@ -24,10 +25,21 @@ export class WorkspacePreview {
24
25
  throw new Error('Preview requires an HTML file inside the selected workspace');
25
26
  const origin = `https://${randomUUID()}.causyne-preview.invalid`;
26
27
  this.roots.set(origin, path.dirname(target));
28
+ if (this.roots.size > MAX_ACTIVE_PREVIEWS) {
29
+ const oldest = this.roots.keys().next().value;
30
+ if (oldest)
31
+ this.roots.delete(oldest);
32
+ }
27
33
  return `${origin}/${encodeURIComponent(path.basename(target))}`;
28
34
  }
29
35
  async response(rawUrl) {
30
- const url = new URL(rawUrl);
36
+ let url;
37
+ try {
38
+ url = new URL(rawUrl);
39
+ }
40
+ catch {
41
+ return null;
42
+ }
31
43
  const root = this.roots.get(url.origin);
32
44
  if (!root)
33
45
  return null;
@@ -2,6 +2,7 @@ import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
 
5
+ const MAX_ACTIVE_PREVIEWS = 128;
5
6
  const MIME: Record<string, string> = {
6
7
  '.html': 'text/html', '.htm': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
7
8
  '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
@@ -27,11 +28,20 @@ export class WorkspacePreview {
27
28
  if (!within(root, target) || !/\.html?$/i.test(target)) throw new Error('Preview requires an HTML file inside the selected workspace');
28
29
  const origin = `https://${randomUUID()}.causyne-preview.invalid`;
29
30
  this.roots.set(origin, path.dirname(target));
31
+ if (this.roots.size > MAX_ACTIVE_PREVIEWS) {
32
+ const oldest = this.roots.keys().next().value;
33
+ if (oldest) this.roots.delete(oldest);
34
+ }
30
35
  return `${origin}/${encodeURIComponent(path.basename(target))}`;
31
36
  }
32
37
 
33
38
  async response(rawUrl: string): Promise<{ status: number; contentType: string; body: Buffer } | null> {
34
- const url = new URL(rawUrl);
39
+ let url: URL;
40
+ try {
41
+ url = new URL(rawUrl);
42
+ } catch {
43
+ return null;
44
+ }
35
45
  const root = this.roots.get(url.origin);
36
46
  if (!root) return null;
37
47
  const deny = { status: 403, contentType: 'text/plain', body: Buffer.from('Preview asset is outside the allowed scope') };
package/src/cliMode.js CHANGED
@@ -324,7 +324,11 @@ export async function chatMode({ home = false } = {}) {
324
324
  // The idle footer's two facts. Both were already loaded and neither was ever
325
325
  // displayed once the header had scrolled away.
326
326
  cwd: process.cwd(),
327
- contextLimit: resolveCharPool(config.tier, config.maxCharPool)
327
+ contextLimit: resolveCharPool(config.tier, config.maxCharPool, {
328
+ provider: config.provider,
329
+ model: config.model,
330
+ overrideTokens: config.contextTokens || config.maxContextTokens
331
+ })
328
332
  };
329
333
  let surface = home && isInteractive() ? createStageSurface({ config }) : null;
330
334
  const openedHome = Boolean(surface);