@causyne/agent 1.20.117 → 1.20.120

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 (82) hide show
  1. package/package.json +7 -2
  2. package/src/agentLoop.js +29 -12
  3. package/src/agentLoop.ts +29 -16
  4. package/src/browser/causyneBrowser.js +231 -136
  5. package/src/browser/causyneBrowser.ts +229 -140
  6. package/src/browser/searchProviders.js +41 -30
  7. package/src/browser/searchProviders.ts +24 -14
  8. package/src/browser/workspacePathSafety.js +50 -0
  9. package/src/browser/workspacePathSafety.ts +50 -0
  10. package/src/browser/workspacePreview.js +27 -4
  11. package/src/browser/workspacePreview.ts +28 -4
  12. package/src/cliMode.js +20 -4
  13. package/src/commands.js +12 -14
  14. package/src/creative/liveBridge.js +34 -1
  15. package/src/creative/liveBridge.ts +28 -1
  16. package/src/observer/evidence.js +23 -0
  17. package/src/observer/evidence.ts +21 -0
  18. package/src/plugins/pluginManager.js +74 -0
  19. package/src/providers/anthropic.js +33 -17
  20. package/src/providers/base.js +14 -0
  21. package/src/providers/dashscope-byok.js +13 -7
  22. package/src/providers/deepseek.js +13 -18
  23. package/src/providers/gemini.js +33 -25
  24. package/src/providers/moonshot.js +13 -12
  25. package/src/providers/ollama.js +21 -21
  26. package/src/providers/openai-compatible.js +12 -19
  27. package/src/providers/openrouter.js +20 -90
  28. package/src/providers/openrouter.ts +31 -94
  29. package/src/providers/qwen-byok.js +13 -7
  30. package/src/providers/toolContracts.js +9 -3
  31. package/src/providers/toolContracts.ts +9 -3
  32. package/src/providers/wireNormalizer.js +238 -0
  33. package/src/providers/wireNormalizer.ts +279 -0
  34. package/src/providers/xai.js +13 -12
  35. package/src/reporting.js +12 -4
  36. package/src/skillsManager.js +3 -2
  37. package/src/skillsManager.ts +3 -2
  38. package/src/tools/browserAutomator.js +13 -1
  39. package/src/tools/browserAutomator.ts +13 -0
  40. package/src/tools/creativeApps.js +2 -1
  41. package/src/tools/creativeApps.ts +2 -1
  42. package/src/tools/gameAssetFetcher.js +130 -26
  43. package/src/tools/gameAssetHarvester.js +80 -58
  44. package/src/tools/nativeEngine.js +1 -1
  45. package/src/tools/nativeEngine.ts +1 -1
  46. package/src/tools/pluginManager.js +17 -2
  47. package/src/tools/registry.js +13 -0
  48. package/src/tools/toolScanner.js +596 -140
  49. package/src/tools/toolScanner.ts +665 -147
  50. package/src/tools/toolSelfRepair.js +243 -114
  51. package/src/tools/toolSelfRepair.ts +262 -111
  52. package/src/tools/webFetch.js +161 -24
  53. package/src/tools/webFetch.ts +157 -22
  54. package/src/tools/webSearch.js +33 -4
  55. package/src/tools/webSearch.ts +27 -4
  56. package/src/tui/composerControls.js +16 -3
  57. package/src/tui/composerControls.ts +14 -3
  58. package/src/tui/prompt.js +122 -16
  59. package/src/tui/sessionPicker.js +132 -35
  60. package/src/tui/sessionPicker.ts +153 -32
  61. package/src/tui/sessionPickerView.js +277 -34
  62. package/src/tui/sessionPickerView.ts +328 -34
  63. package/src/tui/statusLine.js +3 -0
  64. package/src/tui/statusLine.ts +5 -0
  65. package/src/tui/usageCard.js +119 -47
  66. package/src/tui/usageCard.ts +133 -49
  67. package/src/tui/workspaceIdentity.js +133 -0
  68. package/src/tui/workspaceIdentity.ts +146 -0
  69. package/src/tui/workspaceSwitch.js +2 -0
  70. package/src/tui/workspaceSwitch.ts +1 -0
  71. package/src/verification/boundedExplorer.js +119 -0
  72. package/src/verification/cliProbe.js +116 -0
  73. package/src/verification/featureMap.js +78 -0
  74. package/src/verification/interactivePty.js +188 -0
  75. package/src/verification/propertyProbe.js +121 -0
  76. package/src/verification/ptyProbe.js +125 -0
  77. package/src/verification/skillCatalog.d.ts +1 -0
  78. package/src/verification/skillCatalog.js +60 -0
  79. package/src/verification/statechart.js +143 -0
  80. package/src/verification/uiRuntime.js +57 -0
  81. package/src/verificationPlan.js +1 -1
  82. package/src/verificationPlan.ts +1 -1
@@ -10,14 +10,20 @@ import {
10
10
  loadCapabilityPackage
11
11
  } from '../provisioning/capabilityProvisioner.js';
12
12
  import { resolveBrowserRuntime, type PreparedBrowserRuntime } from './browserRuntime.js';
13
- import { assertPublicWebUrl, assertBrowserNavigableUrl } from './urlPolicy.js';
13
+ import { assertPublicWebUrl, assertBrowserNavigableUrl, isLoopbackHost } from './urlPolicy.js';
14
+ import { ensureSafeWorkspaceInputPath, ensureSafeWorkspaceOutputPath } from './workspacePathSafety.js';
14
15
  import { windowSnapshot, type SnapshotWindow } from './snapshotWindow.js';
15
- import { searchPublicWeb } from './searchProviders.js';
16
+ import { searchPublicWeb, publicResultUrl } from './searchProviders.js';
16
17
 
17
18
  const NAVIGATION_TIMEOUT_MS = 30_000;
18
19
  const ACTION_TIMEOUT_MS = 12_000;
19
20
  const IFRAME_SNAPSHOT_TIMEOUT_MS = 3_000;
20
21
  const IDLE_CLOSE_MS = 120 * 60_000;
22
+
23
+ function workspaceProfileDirectory(workspace: string): string {
24
+ const id = crypto.createHash('sha256').update(path.resolve(workspace)).digest('hex');
25
+ return path.join(capabilityDirectory(), 'browser-profiles', id);
26
+ }
21
27
  const MAX_SEARCH_RESULTS = 10;
22
28
  const MAX_EXTRACT_CHARS = 80_000;
23
29
  const MAX_DOWNLOAD_BYTES = 250 * 1024 * 1024;
@@ -351,7 +357,7 @@ interface BrowserFileChooser {
351
357
  }
352
358
 
353
359
  interface BrowserRoute {
354
- request(): { url(): string };
360
+ request(): { url(): string; frame?(): { url(): string }; isNavigationRequest?(): boolean };
355
361
  continue(): Promise<void>;
356
362
  abort(errorCode?: string): Promise<void>;
357
363
  fulfill?(response: { status: number; contentType: string; body: Buffer }): Promise<void>;
@@ -518,6 +524,20 @@ export class BrowserCapabilityError extends Error {
518
524
  }
519
525
  }
520
526
 
527
+ export class BrowserBatchError extends Error {
528
+ readonly completedActions: BrowserActionResult[];
529
+ readonly failedActionIndex: number;
530
+ readonly failedActionType: string;
531
+
532
+ constructor(error: unknown, completedActions: BrowserActionResult[], index: number, actionType: string) {
533
+ super(`Browser action ${index + 1} (${actionType}) failed: ${errorMessage(error)}`);
534
+ this.name = 'BrowserBatchError';
535
+ this.completedActions = [...completedActions];
536
+ this.failedActionIndex = index;
537
+ this.failedActionType = actionType;
538
+ }
539
+ }
540
+
521
541
  function errorMessage(error: unknown): string {
522
542
  return error instanceof Error ? error.message : String(error);
523
543
  }
@@ -852,9 +872,12 @@ const SEARCH_EXTRACT_SCRIPT = `(() => {
852
872
  const LINKS_EXTRACT_SCRIPT = `(opts) => {
853
873
  const scope = opts && opts.selector ? document.querySelector(opts.selector) : document;
854
874
  if (!scope) return { links: [], totalLinks: 0 };
855
- const anchors = Array.from(scope.querySelectorAll('a[href]'));
875
+ const anchors = scope.querySelectorAll('a[href]');
856
876
  const seen = new Set();
857
- const all = [];
877
+ const links = [];
878
+ const start = (opts && opts.offset) || 0;
879
+ const max = (opts && opts.limit) || 50;
880
+ let totalLinks = 0;
858
881
  for (const a of anchors) {
859
882
  let href;
860
883
  try {
@@ -866,21 +889,23 @@ const LINKS_EXTRACT_SCRIPT = `(opts) => {
866
889
  if (seen.has(href)) continue;
867
890
  seen.add(href);
868
891
  const text = (a.textContent || '').trim().replace(/\\s+/g, ' ').slice(0, 200);
869
- all.push({ url: href, text: text || undefined });
892
+ if (totalLinks >= start && links.length < max) links.push({ url: href, text: text || undefined });
893
+ totalLinks++;
870
894
  }
871
- const start = (opts && opts.offset) || 0;
872
- const max = (opts && opts.limit) || 50;
873
- return { links: all.slice(start, start + max), totalLinks: all.length };
895
+ return { links, totalLinks };
874
896
  }`;
875
897
 
876
- const IMAGES_EXTRACT_SCRIPT = `(opts) => {
898
+ export const IMAGES_EXTRACT_SCRIPT = `(opts) => {
877
899
  const max = Math.min(Math.max(Number(opts && opts.limit) || 100, 1), 300);
878
900
  const imgs = Array.from(document.querySelectorAll('img'));
879
901
  const seen = new Set();
880
902
  const out = [];
881
903
  for (const img of imgs) {
882
904
  const src = img.currentSrc || img.src || '';
883
- if (!src || src.startsWith('data:') || seen.has(src)) continue;
905
+ if (!src || src.length > 4096 || seen.has(src)) continue;
906
+ let parsed;
907
+ try { parsed = new URL(src, document.baseURI); } catch { continue; }
908
+ if (!['http:', 'https:', 'blob:'].includes(parsed.protocol) || parsed.username || parsed.password) continue;
884
909
  const width = Number(img.naturalWidth || img.width || 0);
885
910
  const height = Number(img.naturalHeight || img.height || 0);
886
911
  seen.add(src);
@@ -895,30 +920,17 @@ const IMAGES_EXTRACT_SCRIPT = `(opts) => {
895
920
  return out;
896
921
  }`;
897
922
 
898
- const DISMISS_CONSENT_SCRIPT = `(() => {
899
- const selectors = [
900
- '#onetrust-accept-btn-handler',
901
- '.onetrust-close-btn-handler',
902
- '#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll',
903
- '#CybotCookiebotDialogBodyButtonAccept',
904
- '[data-testid="cookie-policy-dialog-accept-button"]',
905
- 'button[id*="cookie"][id*="accept" i]',
906
- 'button[class*="cookie"][class*="accept" i]',
907
- 'button[aria-label*="Accept all" i]',
908
- 'button[aria-label*="Accept cookies" i]'
909
- ];
910
- for (const sel of selectors) {
911
- const el = document.querySelector(sel);
912
- if (el && typeof el.click === 'function') {
913
- const rect = el.getBoundingClientRect?.();
914
- if (!rect || (rect.width > 0 && rect.height > 0)) {
915
- el.click();
916
- return true;
917
- }
918
- }
919
- }
920
- return false;
921
- })()`;
923
+ const CONSENT_DISMISS_SELECTORS = [
924
+ '#onetrust-accept-btn-handler',
925
+ '.onetrust-close-btn-handler',
926
+ '#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll',
927
+ '#CybotCookiebotDialogBodyButtonAccept',
928
+ '[data-testid="cookie-policy-dialog-accept-button"]',
929
+ 'button[id*="cookie"][id*="accept" i]',
930
+ 'button[class*="cookie"][class*="accept" i]',
931
+ 'button[aria-label*="Accept all" i]',
932
+ 'button[aria-label*="Accept cookies" i]'
933
+ ] as const;
922
934
 
923
935
  const WAIT_FOR_PAGE_READY_SCRIPT = `(() => {
924
936
  return new Promise(resolve => {
@@ -939,17 +951,23 @@ export class CausyneBrowser {
939
951
  private readonly ensureBrowserCapability: NonNullable<RuntimeOptions['ensureBrowserCapability']>;
940
952
  private readonly loadBrowserEngine: NonNullable<RuntimeOptions['loadBrowserEngine']>;
941
953
  private readonly resolveRuntime: NonNullable<RuntimeOptions['resolveRuntime']>;
942
- private readonly profileDirectory: string;
954
+ private profileDirectory: string;
955
+ private readonly pinnedProfileDirectory: boolean;
956
+ private queuedOperations = 0;
943
957
  private readonly visible: boolean;
944
958
  private readonly validateUrl: (value: string) => Promise<URL>;
945
959
  private session: BrowserSession | null = null;
946
960
  private starting: Promise<void> | null = null;
961
+ private operationTail: Promise<void> = Promise.resolve();
947
962
  private tabs = new Map<string, TabState>();
948
963
  private activeTabId: string | null = null;
949
964
  private idleTimer: NodeJS.Timeout | null = null;
965
+ private idleGeneration = 0;
950
966
  private securedPages = new WeakSet<object>();
951
967
  private pageStates = new WeakMap<object, TabState>();
952
968
  private contextRouteInstalled = false;
969
+ private approvedLoopbackOrigins = new Set<string>();
970
+ private pendingLocalNavigation: string | null = null;
953
971
  private lastTarget: { kind: 'preview'; workspace: string; filePath: string } | { kind: 'url'; url: string } | null = null;
954
972
 
955
973
  constructor(options: RuntimeOptions = {}) {
@@ -957,42 +975,77 @@ export class CausyneBrowser {
957
975
  this.ensureBrowserCapability = options.ensureBrowserCapability ?? (() => ensureCapability('browser'));
958
976
  this.loadBrowserEngine = options.loadBrowserEngine ?? (async () => await loadCapabilityPackage('camoufox-js') as BrowserEngineModule);
959
977
  this.resolveRuntime = options.resolveRuntime ?? resolveBrowserRuntime;
960
- this.profileDirectory = path.resolve(options.profileDirectory ?? path.join(capabilityDirectory(), 'browser-profile'));
978
+ this.pinnedProfileDirectory = options.profileDirectory !== undefined;
979
+ this.profileDirectory = path.resolve(options.profileDirectory ?? workspaceProfileDirectory(this.workspace));
961
980
  this.visible = options.visible ?? process.env.CAUSYNE_BROWSER_VISIBLE === '1';
962
981
  this.validateUrl = options.validateUrl ?? assertBrowserNavigableUrl;
963
982
  }
964
983
 
965
984
  setWorkspace(workspace: string): void {
966
- if (workspace && typeof workspace === 'string') {
967
- if (this.workspace !== path.resolve(workspace)) {
968
- this.workspacePreview.clear();
969
- this.lastTarget = null;
970
- }
971
- this.workspace = path.resolve(workspace);
985
+ if (!workspace || typeof workspace !== 'string') return;
986
+ const next = path.resolve(workspace);
987
+ if (next === this.workspace) return;
988
+ if (this.session || this.starting || this.queuedOperations > 0) {
989
+ throw new Error('Cannot switch the workspace of an active browser session; use a workspace-scoped browser');
972
990
  }
991
+ if (this.pinnedProfileDirectory) {
992
+ throw new Error('Cannot switch workspaces with an explicitly configured browser profile');
993
+ }
994
+ this.workspacePreview.clear();
995
+ this.lastTarget = null;
996
+ this.approvedLoopbackOrigins.clear();
997
+ this.pendingLocalNavigation = null;
998
+ this.workspace = next;
999
+ this.profileDirectory = workspaceProfileDirectory(next);
973
1000
  }
974
1001
 
975
1002
  getWorkspace(): string {
976
1003
  return this.workspace;
977
1004
  }
978
1005
 
1006
+ private async enqueueOperation<T>(operation: () => Promise<T>): Promise<T> {
1007
+ this.queuedOperations++;
1008
+ const previous = this.operationTail;
1009
+ let release!: () => void;
1010
+ this.operationTail = new Promise<void>(resolve => { release = resolve; });
1011
+ await previous;
1012
+ try {
1013
+ return await operation();
1014
+ } finally {
1015
+ this.queuedOperations--;
1016
+ release();
1017
+ }
1018
+ }
1019
+
979
1020
  async run(actions: BrowserAction[], options: BrowserRunOptions = {}): Promise<BrowserActionResult[]> {
1021
+ return this.enqueueOperation(() => this.runUnlocked(actions, options));
1022
+ }
1023
+
1024
+ private async runUnlocked(actions: BrowserAction[], options: BrowserRunOptions = {}): Promise<BrowserActionResult[]> {
980
1025
  if (!Array.isArray(actions) || actions.length === 0 || actions.length > 40) {
981
1026
  throw new Error('Browser actions must contain between 1 and 40 operations');
982
1027
  }
983
1028
  const activeWorkspace = options.workspace ? path.resolve(options.workspace) : this.workspace;
1029
+ if (activeWorkspace !== this.workspace) {
1030
+ throw new Error('Browser action workspace must match the isolated browser session workspace');
1031
+ }
984
1032
  await this.start();
985
1033
  const results: BrowserActionResult[] = [];
986
- for (const action of actions) {
1034
+ for (let index = 0; index < actions.length; index++) {
1035
+ const action = actions[index]!;
987
1036
  try {
988
1037
  results.push(await this.runAction(action, activeWorkspace));
989
1038
  } catch (error) {
990
- if (isDeadContextError(error)) {
991
- await this.close();
992
- await this.start();
993
- results.push(await this.runAction(action, activeWorkspace));
994
- } else {
995
- throw error;
1039
+ try {
1040
+ if (isDeadContextError(error) && ['goto', 'open', 'navigate', 'preview', 'snapshot', 'scrape', 'search', 'links', 'images', 'extract', 'listTabs', 'list_tabs'].includes(action.type)) {
1041
+ await this.close();
1042
+ await this.start();
1043
+ results.push(await this.runAction(action, activeWorkspace));
1044
+ } else {
1045
+ throw error;
1046
+ }
1047
+ } catch (finalError) {
1048
+ throw new BrowserBatchError(finalError, results, index, action.type);
996
1049
  }
997
1050
  }
998
1051
  }
@@ -1000,8 +1053,19 @@ export class CausyneBrowser {
1000
1053
  return results;
1001
1054
  }
1002
1055
 
1003
- async search(query: string): Promise<SearchResult[]> {
1004
- const cleaned = String(query ?? '').trim();
1056
+ async search(query: string, options: { skipPublicFallback?: boolean } = {}): Promise<SearchResult[]> {
1057
+ return this.enqueueOperation(async () => {
1058
+ try {
1059
+ return await this.searchUnlocked(query, options);
1060
+ } finally {
1061
+ if (this.session) this.touch();
1062
+ }
1063
+ });
1064
+ }
1065
+
1066
+ private async searchUnlocked(query: string, options: { skipPublicFallback?: boolean } = {}): Promise<SearchResult[]> {
1067
+ if (typeof query !== 'string') throw new Error('Browser search query must be a string');
1068
+ const cleaned = query.trim();
1005
1069
  if (!cleaned || cleaned.length > 1_000) throw new Error('Search query must contain 1-1000 characters');
1006
1070
  const failures: string[] = [];
1007
1071
 
@@ -1019,7 +1083,8 @@ export class CausyneBrowser {
1019
1083
  await state.page.waitForTimeout(500);
1020
1084
  const extracted = await state.page.evaluate<Array<Omit<SearchResult, 'engine'>>>(SEARCH_EXTRACT_SCRIPT);
1021
1085
  if (Array.isArray(extracted) && extracted.length > 0) {
1022
- return extracted.slice(0, MAX_SEARCH_RESULTS).map(result => ({ ...result, engine: target.engine }));
1086
+ const safe = extracted.filter(result => typeof result?.url === 'string' && publicResultUrl(result.url));
1087
+ if (safe.length > 0) return safe.slice(0, MAX_SEARCH_RESULTS).map(result => ({ ...result, engine: target.engine }));
1023
1088
  }
1024
1089
  failures.push(`${target.engine}: no organic results`);
1025
1090
  } catch (error) {
@@ -1030,6 +1095,10 @@ export class CausyneBrowser {
1030
1095
  failures.push(`browser_session: ${errorMessage(browserErr)}`);
1031
1096
  }
1032
1097
 
1098
+ if (options.skipPublicFallback) {
1099
+ throw new Error(`Rendered search providers exhausted. ${failures.join('; ')}`);
1100
+ }
1101
+
1033
1102
  // High-reliability search fallback: query lightweight search providers (DuckDuckGo HTML / Bing RSS) directly
1034
1103
  try {
1035
1104
  const publicResults = await searchPublicWeb(cleaned);
@@ -1045,6 +1114,10 @@ export class CausyneBrowser {
1045
1114
  }
1046
1115
 
1047
1116
  async snapshot(offset = 0): Promise<SnapshotWindow & { tabId: string; url: string; title: string; refsCount: number; structure?: PageStructure | null }> {
1117
+ return this.enqueueOperation(() => this.snapshotUnlocked(offset));
1118
+ }
1119
+
1120
+ private async snapshotUnlocked(offset = 0): Promise<SnapshotWindow & { tabId: string; url: string; title: string; refsCount: number; structure?: PageStructure | null }> {
1048
1121
  await this.start();
1049
1122
  const state = await this.activeTab();
1050
1123
  await this.restoreLastTargetIfBlank(state);
@@ -1060,6 +1133,7 @@ export class CausyneBrowser {
1060
1133
  }
1061
1134
 
1062
1135
  async close(): Promise<void> {
1136
+ this.idleGeneration++;
1063
1137
  if (this.idleTimer) clearTimeout(this.idleTimer);
1064
1138
  this.idleTimer = null;
1065
1139
  const session = this.session;
@@ -1069,6 +1143,8 @@ export class CausyneBrowser {
1069
1143
  this.workspacePreview.clear();
1070
1144
  this.activeTabId = null;
1071
1145
  this.contextRouteInstalled = false;
1146
+ this.approvedLoopbackOrigins.clear();
1147
+ this.pendingLocalNavigation = null;
1072
1148
  this.securedPages = new WeakSet<object>();
1073
1149
  this.pageStates = new WeakMap<object, TabState>();
1074
1150
  if (session) await session.close().catch(() => {});
@@ -1205,18 +1281,27 @@ export class CausyneBrowser {
1205
1281
  }
1206
1282
  const parsed = new URL(url);
1207
1283
  if (parsed.protocol === 'file:') {
1208
- const workspace = await fs.realpath(this.workspace);
1209
- const file = await fs.realpath(fileURLToPath(parsed));
1210
- if (!isWithin(workspace, file)) throw new Error('File is outside the selected workspace');
1211
- await route.continue();
1212
- return;
1284
+ throw new Error('Direct file requests are not allowed; use an isolated workspace preview');
1213
1285
  }
1214
1286
  if (parsed.protocol === 'ws:' || parsed.protocol === 'wss:') {
1215
1287
  parsed.protocol = parsed.protocol === 'wss:' ? 'https:' : 'http:';
1216
- await this.validateUrl(parsed.href);
1217
- } else {
1218
- await this.validateUrl(url);
1219
1288
  }
1289
+ if (isLoopbackHost(parsed.hostname)) {
1290
+ const request = route.request();
1291
+ let sameOriginFrame = false;
1292
+ try {
1293
+ const frameUrl = request.frame?.().url();
1294
+ sameOriginFrame = Boolean(frameUrl && new URL(frameUrl).origin === parsed.origin);
1295
+ } catch { /* Navigation requests can have no active frame. */ }
1296
+ const explicitlyNavigating = this.pendingLocalNavigation === parsed.origin
1297
+ && request.isNavigationRequest?.() === true;
1298
+ const trustedSubresource = sameOriginFrame
1299
+ && (this.approvedLoopbackOrigins.has(parsed.origin) || this.pendingLocalNavigation === parsed.origin);
1300
+ if (!explicitlyNavigating && !trustedSubresource) {
1301
+ throw new Error('A public page cannot request local services without explicit navigation');
1302
+ }
1303
+ }
1304
+ await this.validateUrl(parsed.href);
1220
1305
  await route.continue();
1221
1306
  } catch {
1222
1307
  await route.abort('blockedbyclient');
@@ -1370,7 +1455,14 @@ export class CausyneBrowser {
1370
1455
  private async navigate(state: TabState, value: string): Promise<void> {
1371
1456
  const url = await this.validateUrl(value);
1372
1457
  state.runtimeErrors = [];
1373
- const response = await state.page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
1458
+ if (isLoopbackHost(url.hostname)) this.pendingLocalNavigation = url.origin;
1459
+ let response: Awaited<ReturnType<BrowserPage['goto']>>;
1460
+ try {
1461
+ response = await state.page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
1462
+ } finally {
1463
+ this.pendingLocalNavigation = null;
1464
+ }
1465
+ if (isLoopbackHost(url.hostname)) this.approvedLoopbackOrigins.add(url.origin);
1374
1466
  const status = response?.status() ?? 0;
1375
1467
  if (status >= 400) throw new Error(`Destination returned HTTP ${status}`);
1376
1468
  await state.page.waitForLoadState('domcontentloaded', { timeout: NAVIGATION_TIMEOUT_MS });
@@ -1530,50 +1622,38 @@ export class CausyneBrowser {
1530
1622
  }
1531
1623
  }
1532
1624
 
1533
- private async performClick(state: TabState, locator: BrowserLocator, doubleClick = false): Promise<void> {
1534
- if (doubleClick && typeof locator.dblclick === 'function') {
1625
+ private async performClick(_state: TabState, locator: BrowserLocator, doubleClick = false): Promise<void> {
1626
+ if (doubleClick) {
1627
+ if (typeof locator.dblclick !== 'function') {
1628
+ throw new Error('Browser engine does not support double-click actions');
1629
+ }
1535
1630
  await locator.dblclick({ timeout: ACTION_TIMEOUT_MS });
1536
1631
  return;
1537
1632
  }
1538
- try {
1633
+ // A failed actionability check must not become a forced or synthetic click.
1634
+ // Retrying mutating actions could also submit the same form twice.
1635
+ await locator.click({ timeout: ACTION_TIMEOUT_MS });
1636
+ }
1637
+
1638
+ private async dismissConsentBanner(state: TabState): Promise<boolean> {
1639
+ for (const selector of CONSENT_DISMISS_SELECTORS) {
1640
+ const locator = state.page.locator(selector).first();
1641
+ if (typeof locator.isVisible !== 'function') continue;
1642
+ if (!await locator.isVisible().catch(() => false)) continue;
1643
+ // Do not bypass actionability or retry a potentially mutating click.
1539
1644
  await locator.click({ timeout: ACTION_TIMEOUT_MS });
1540
- } catch (clickError) {
1541
- const msg = errorMessage(clickError);
1542
- if (msg.includes('intercepts pointer events') || msg.includes('Timeout')) {
1543
- try {
1544
- await locator.click({ timeout: 5_000, force: true });
1545
- return;
1546
- } catch {
1547
- if (
1548
- typeof locator.boundingBox === 'function' &&
1549
- typeof state.page.mouse.move === 'function' &&
1550
- typeof state.page.mouse.down === 'function' &&
1551
- typeof state.page.mouse.up === 'function'
1552
- ) {
1553
- const box = await locator.boundingBox({ timeout: 2_000 }).catch(() => null);
1554
- if (box && box.width > 0 && box.height > 0) {
1555
- const cx = box.x + box.width / 2;
1556
- const cy = box.y + box.height / 2;
1557
- await state.page.mouse.move(cx, cy);
1558
- await state.page.waitForTimeout(30);
1559
- await state.page.mouse.down();
1560
- await state.page.waitForTimeout(30);
1561
- await state.page.mouse.up();
1562
- return;
1563
- }
1564
- }
1565
- }
1566
- }
1567
- throw clickError;
1645
+ state.refs.clear();
1646
+ return true;
1568
1647
  }
1648
+ return false;
1569
1649
  }
1570
1650
 
1571
1651
  private async performType(state: TabState, locator: BrowserLocator, action: BrowserAction): Promise<void> {
1572
- if (action.text === undefined) throw new Error(`${action.type} requires text`);
1652
+ if (typeof action.text !== 'string') throw new Error(`${action.type} requires text as a string`);
1573
1653
  await this.assertFillable(locator);
1574
1654
  if (action.mode === 'keyboard' && typeof state.page.keyboard.type === 'function') {
1575
1655
  await this.performClick(state, locator, false);
1576
- const delay = Math.max(0, Math.min(500, Number(action.delay ?? 20)));
1656
+ const delay = boundedFiniteInteger(action.delay, 20, 0, 500);
1577
1657
  await state.page.keyboard.type(action.text, { delay });
1578
1658
  } else {
1579
1659
  await locator.fill(action.text, { timeout: ACTION_TIMEOUT_MS });
@@ -1587,8 +1667,8 @@ export class CausyneBrowser {
1587
1667
  try {
1588
1668
  const selected = await locator.selectOption(value, { timeout: ACTION_TIMEOUT_MS });
1589
1669
  if (!Array.isArray(selected) || selected.length > 0) return;
1590
- } catch {
1591
- // Retry by label
1670
+ } catch (error) {
1671
+ if (!/no option|option.*not found|did not match/i.test(errorMessage(error))) throw error;
1592
1672
  }
1593
1673
  await locator.selectOption({ label: value }, { timeout: ACTION_TIMEOUT_MS });
1594
1674
  }
@@ -1601,7 +1681,8 @@ export class CausyneBrowser {
1601
1681
  const list = Array.isArray(rawPaths) ? rawPaths : [rawPaths];
1602
1682
  const resolvedFiles: string[] = [];
1603
1683
  for (const item of list) {
1604
- const resolved = path.resolve(workspace, String(item));
1684
+ if (typeof item !== 'string' || !item.trim()) throw new Error('upload requires non-empty filePath strings');
1685
+ const resolved = path.resolve(workspace, item);
1605
1686
  if (!isWithin(workspace, resolved)) {
1606
1687
  throw new Error('Upload file must stay inside the selected workspace');
1607
1688
  }
@@ -1609,23 +1690,20 @@ export class CausyneBrowser {
1609
1690
  if (!stat || !stat.isFile()) {
1610
1691
  throw new Error(`Upload file does not exist or is not a regular file: ${resolved}`);
1611
1692
  }
1693
+ await ensureSafeWorkspaceInputPath(workspace, resolved);
1612
1694
  resolvedFiles.push(resolved);
1613
1695
  }
1614
1696
 
1615
1697
  const locator = await this.locatorFor(state, action);
1616
1698
  if (typeof locator.setInputFiles === 'function') {
1617
- try {
1618
- await locator.setInputFiles(resolvedFiles, { timeout: ACTION_TIMEOUT_MS });
1619
- state.refs.clear();
1620
- return {
1621
- action: action.type,
1622
- tabId: state.id,
1623
- url: state.page.url(),
1624
- output: `Uploaded ${resolvedFiles.length} file(s)`
1625
- };
1626
- } catch {
1627
- // Fall through to filechooser event
1628
- }
1699
+ await locator.setInputFiles(resolvedFiles, { timeout: ACTION_TIMEOUT_MS });
1700
+ state.refs.clear();
1701
+ return {
1702
+ action: action.type,
1703
+ tabId: state.id,
1704
+ url: state.page.url(),
1705
+ output: `Uploaded ${resolvedFiles.length} file(s)`
1706
+ };
1629
1707
  }
1630
1708
 
1631
1709
  const [chooser] = await Promise.all([
@@ -1643,9 +1721,10 @@ export class CausyneBrowser {
1643
1721
  }
1644
1722
 
1645
1723
  private async saveDownload(state: TabState, action: BrowserAction, workspace: string): Promise<BrowserActionResult> {
1646
- if (!action.outputFile) throw new Error('download requires outputFile');
1724
+ if (typeof action.outputFile !== 'string' || !action.outputFile.trim()) throw new Error('download requires non-empty outputFile string');
1647
1725
  const target = path.resolve(workspace, action.outputFile);
1648
1726
  if (!isWithin(workspace, target)) throw new Error('Download target must stay inside the selected workspace');
1727
+ await ensureSafeWorkspaceOutputPath(workspace, target);
1649
1728
  const locator = await this.locatorFor(state, action);
1650
1729
  const [download] = await Promise.all([
1651
1730
  state.page.waitForEvent('download', { timeout: NAVIGATION_TIMEOUT_MS }) as Promise<BrowserDownload>,
@@ -1655,7 +1734,6 @@ export class CausyneBrowser {
1655
1734
  // filename alter the caller's workspace-scoped target.
1656
1735
  const finalTarget = target;
1657
1736
  const temporary = `${finalTarget}.part-${crypto.randomUUID()}`;
1658
- await fs.mkdir(path.dirname(finalTarget), { recursive: true });
1659
1737
  try {
1660
1738
  await download.saveAs(temporary);
1661
1739
  const failure = await download.failure();
@@ -1670,18 +1748,18 @@ export class CausyneBrowser {
1670
1748
  }
1671
1749
 
1672
1750
  private async saveScreenshot(state: TabState, action: BrowserAction, workspace: string): Promise<BrowserActionResult> {
1673
- if (!action.outputFile) throw new Error('screenshot requires outputFile');
1751
+ if (typeof action.outputFile !== 'string' || !action.outputFile.trim()) throw new Error('screenshot requires non-empty outputFile string');
1674
1752
  const target = path.resolve(workspace, action.outputFile);
1675
1753
  if (!isWithin(workspace, target)) throw new Error('Screenshot target must stay inside the selected workspace');
1676
1754
  const extension = path.extname(target).toLowerCase();
1677
1755
  if (!['.png', '.jpg', '.jpeg'].includes(extension)) throw new Error('Screenshot outputFile must end in .png, .jpg, or .jpeg');
1756
+ await ensureSafeWorkspaceOutputPath(workspace, target);
1678
1757
  const bytes = await state.page.screenshot({
1679
1758
  fullPage: action.fullPage ?? false,
1680
1759
  type: extension === '.png' ? 'png' : 'jpeg'
1681
1760
  });
1682
1761
  if (bytes.byteLength > MAX_SCREENSHOT_BYTES) throw new Error(`Screenshot exceeds ${MAX_SCREENSHOT_BYTES} bytes`);
1683
1762
  const temporary = `${target}.part-${crypto.randomUUID()}`;
1684
- await fs.mkdir(path.dirname(target), { recursive: true });
1685
1763
  try {
1686
1764
  await fs.writeFile(temporary, bytes, { mode: 0o600 });
1687
1765
  await fs.rename(temporary, target);
@@ -1695,9 +1773,10 @@ export class CausyneBrowser {
1695
1773
  if (!action || typeof action.type !== 'string') throw new Error('Every browser action needs a type');
1696
1774
  if (action.type === 'newTab' || action.type === 'new_tab') {
1697
1775
  const initialUrl = action.macro
1698
- ? (expandSearchMacro(action.macro, action.query ?? action.text ?? '') ?? undefined)
1776
+ ? expandSearchMacro(action.macro, action.query ?? action.text ?? '')
1699
1777
  : action.url;
1700
- const state = await this.createTab(initialUrl);
1778
+ if (action.macro && !initialUrl) throw new Error(`Unsupported search macro: ${action.macro}`);
1779
+ const state = await this.createTab(initialUrl ?? undefined);
1701
1780
  return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
1702
1781
  }
1703
1782
  if (action.type === 'listTabs' || action.type === 'list_tabs') {
@@ -1718,7 +1797,7 @@ export class CausyneBrowser {
1718
1797
  return { action: action.type, tabId: state.id, output: 'Tab closed' };
1719
1798
  }
1720
1799
  if (action.type === 'search') {
1721
- const results = await this.search(action.query ?? action.text ?? '');
1800
+ const results = await this.searchUnlocked(action.query ?? action.text ?? '');
1722
1801
  const active = await this.activeTab();
1723
1802
  return { action: action.type, tabId: active.id, url: active.page.url(), data: results };
1724
1803
  }
@@ -1732,7 +1811,7 @@ export class CausyneBrowser {
1732
1811
  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.' };
1733
1812
  }
1734
1813
  if (action.type === 'snapshot' || action.type === 'scrape') {
1735
- const snapshot = await this.snapshot(action.offset ?? 0);
1814
+ const snapshot = await this.snapshotUnlocked(action.offset ?? 0);
1736
1815
  return {
1737
1816
  action: action.type,
1738
1817
  tabId: snapshot.tabId,
@@ -1761,7 +1840,7 @@ export class CausyneBrowser {
1761
1840
  if (typeof locator.hover === 'function') {
1762
1841
  await locator.hover({ timeout: ACTION_TIMEOUT_MS });
1763
1842
  } else {
1764
- await this.performClick(state, locator, false);
1843
+ throw new Error('Browser engine cannot hover this element');
1765
1844
  }
1766
1845
  return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Element hovered' };
1767
1846
  }
@@ -1772,19 +1851,23 @@ export class CausyneBrowser {
1772
1851
  }
1773
1852
  if (action.type === 'selectOption' || action.type === 'select') {
1774
1853
  const value = action.value ?? action.option ?? action.text;
1775
- if (value === undefined) throw new Error(`${action.type} requires value`);
1854
+ if (typeof value !== 'string') throw new Error(`${action.type} requires a string value`);
1776
1855
  const locator = await this.locatorFor(state, action);
1777
1856
  await this.performSelectOption(locator, value);
1778
1857
  return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Option selected' };
1779
1858
  }
1780
1859
  if (action.type === 'keyPress' || action.type === 'press') {
1781
- const normalizedKey = normalizeBrowserKey(action.key ?? 'Enter');
1860
+ if (typeof action.key !== 'string' || !action.key.trim()) {
1861
+ throw new Error('keyPress requires a non-empty key');
1862
+ }
1863
+ const normalizedKey = normalizeBrowserKey(action.key);
1782
1864
  await state.page.keyboard.press(normalizedKey);
1783
1865
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Pressed ${normalizedKey}` };
1784
1866
  }
1785
1867
  if (action.type === 'scroll') {
1786
1868
  const amount = boundedFiniteInteger(action.amount, 700, 1, 10_000);
1787
1869
  const direction = action.direction ?? 'down';
1870
+ if (!['up', 'down', 'left', 'right'].includes(direction)) throw new Error('Unsupported scroll direction');
1788
1871
  const x = direction === 'left' ? -amount : direction === 'right' ? amount : 0;
1789
1872
  const y = direction === 'up' ? -amount : direction === 'down' ? amount : 0;
1790
1873
  await state.page.mouse.wheel(x, y);
@@ -1802,20 +1885,18 @@ export class CausyneBrowser {
1802
1885
  if (typeof loc.waitFor === 'function') {
1803
1886
  await loc.waitFor({ timeout: waitTimeout });
1804
1887
  } else {
1805
- await state.page.waitForTimeout(waitTimeout);
1888
+ throw new Error('Browser engine cannot wait for selectors');
1806
1889
  }
1807
1890
  }
1808
1891
  } else {
1809
1892
  if (action.waitForNetwork) {
1810
- await state.page.waitForLoadState('networkidle', { timeout: waitTimeout }).catch(() => {});
1893
+ await state.page.waitForLoadState('networkidle', { timeout: waitTimeout });
1811
1894
  }
1812
1895
  await state.page.evaluate(WAIT_FOR_PAGE_READY_SCRIPT).catch(() => {});
1813
1896
  await state.page.waitForTimeout(Math.min(waitTimeout, 2_000));
1814
1897
  }
1815
- if (action.dismissConsent) {
1816
- await state.page.evaluate(DISMISS_CONSENT_SCRIPT).catch(() => false);
1817
- }
1818
- return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Wait completed' };
1898
+ const dismissed = action.dismissConsent ? await this.dismissConsentBanner(state) : false;
1899
+ return { action: action.type, tabId: state.id, url: state.page.url(), output: dismissed ? 'Wait completed; consent banner dismissed' : 'Wait completed' };
1819
1900
  }
1820
1901
  if (action.type === 'viewport') {
1821
1902
  const width = Math.floor(Number(action.width ?? 1280));
@@ -1823,9 +1904,10 @@ export class CausyneBrowser {
1823
1904
  if (!Number.isFinite(width) || !Number.isFinite(height) || width < 100 || width > 4000 || height < 100 || height > 4000) {
1824
1905
  throw new Error('viewport width and height must be between 100 and 4000 pixels');
1825
1906
  }
1826
- if (typeof state.page.setViewportSize === 'function') {
1827
- await state.page.setViewportSize({ width, height });
1907
+ if (typeof state.page.setViewportSize !== 'function') {
1908
+ throw new Error('Browser engine does not support viewport resizing');
1828
1909
  }
1910
+ await state.page.setViewportSize({ width, height });
1829
1911
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Viewport set to ${width}x${height}` };
1830
1912
  }
1831
1913
  if (action.type === 'back') {
@@ -1870,7 +1952,7 @@ export class CausyneBrowser {
1870
1952
  }
1871
1953
  const data = await state.page.evaluate(
1872
1954
  LINKS_EXTRACT_SCRIPT,
1873
- { selector: action.selector, offset: action.offset ?? 0, limit: action.limit ?? 50 }
1955
+ { selector: action.selector, offset: boundedFiniteInteger(action.offset, 0, 0, 100_000), limit: boundedFiniteInteger(action.limit, 50, 1, 200) }
1874
1956
  );
1875
1957
  return { action: action.type, tabId: state.id, url: state.page.url(), data };
1876
1958
  } else if (action.type === 'images') {
@@ -1905,26 +1987,33 @@ export class CausyneBrowser {
1905
1987
  }
1906
1988
 
1907
1989
  private touch(): void {
1990
+ const generation = ++this.idleGeneration;
1908
1991
  if (this.idleTimer) clearTimeout(this.idleTimer);
1909
- this.idleTimer = setTimeout(() => { void this.close(); }, IDLE_CLOSE_MS);
1992
+ this.idleTimer = setTimeout(() => {
1993
+ void this.enqueueOperation(async () => {
1994
+ if (generation === this.idleGeneration) await this.close();
1995
+ });
1996
+ }, IDLE_CLOSE_MS);
1910
1997
  this.idleTimer.unref?.();
1911
1998
  }
1912
1999
  }
1913
2000
 
1914
- let sharedBrowser: CausyneBrowser | null = null;
2001
+ const sharedBrowsers = new Map<string, CausyneBrowser>();
1915
2002
 
1916
2003
  export function causyneBrowser(options?: { workspace?: string }): CausyneBrowser {
1917
- sharedBrowser ??= new CausyneBrowser(options);
1918
- if (options?.workspace) {
1919
- sharedBrowser.setWorkspace(options.workspace);
2004
+ const workspace = path.resolve(options?.workspace ?? process.cwd());
2005
+ let browser = sharedBrowsers.get(workspace);
2006
+ if (!browser) {
2007
+ browser = new CausyneBrowser({ workspace });
2008
+ sharedBrowsers.set(workspace, browser);
1920
2009
  }
1921
- return sharedBrowser;
2010
+ return browser;
1922
2011
  }
1923
2012
 
1924
2013
  export async function closeCausyneBrowser(): Promise<void> {
1925
- const browser = sharedBrowser;
1926
- sharedBrowser = null;
1927
- if (browser) await browser.close();
2014
+ const browsers = [...sharedBrowsers.values()];
2015
+ sharedBrowsers.clear();
2016
+ await Promise.all(browsers.map(browser => browser.close()));
1928
2017
  }
1929
2018
 
1930
2019
  export interface BrowserSandboxValidationResult {
@@ -2005,7 +2094,7 @@ export function validateBrowserActSandbox(
2005
2094
  if (hasDownload) {
2006
2095
  return { allowed: true, risk: 'extreme', reason: 'Writes browser content to the selected workspace' };
2007
2096
  }
2008
- if (actions.some(action => typeof action?.type === 'string' && INTERACTIVE_BROWSER_ACTIONS.has(action.type))) {
2097
+ if (actions.some(action => typeof action?.type === 'string' && (INTERACTIVE_BROWSER_ACTIONS.has(action.type) || (action.type === 'wait' && action.dismissConsent === true)))) {
2009
2098
  return { allowed: true, risk: 'dangerous', reason: 'Interacts with a website through the dedicated agent browser' };
2010
2099
  }
2011
2100
  return { allowed: true, risk: 'safe' };