@causyne/agent 1.20.0 → 1.20.5

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 (125) hide show
  1. package/README.md +0 -18
  2. package/package.json +1 -1
  3. package/src/acp/client.js +2 -1
  4. package/src/acp/client.ts +2 -1
  5. package/src/acp/server.js +5 -6
  6. package/src/acp/server.ts +4 -6
  7. package/src/agentLoop.d.ts +1 -0
  8. package/src/agentLoop.js +505 -241
  9. package/src/agentLoop.ts +527 -258
  10. package/src/agentPolicy.js +9 -0
  11. package/src/agentPolicy.ts +9 -0
  12. package/src/approvalPolicy.js +55 -0
  13. package/src/approvalPolicy.ts +66 -0
  14. package/src/browser/browserRuntime.js +217 -14
  15. package/src/browser/browserRuntime.ts +255 -14
  16. package/src/browser/causyneBrowser.js +1215 -68
  17. package/src/browser/causyneBrowser.ts +1340 -72
  18. package/src/cliMode.js +52 -29
  19. package/src/commands.js +141 -17
  20. package/src/config.js +22 -12
  21. package/src/continuum/ui/continuumPicker.js +18 -1
  22. package/src/continuum/ui/continuumPicker.ts +19 -1
  23. package/src/dynamicCatalogue.js +87 -20
  24. package/src/dynamicCatalogue.ts +85 -15
  25. package/src/launchIntent.js +40 -0
  26. package/src/launchIntent.ts +49 -0
  27. package/src/memoryManager.js +26 -2
  28. package/src/modelCatalogue.js +2 -0
  29. package/src/planCache.js +320 -11
  30. package/src/planCache.ts +402 -13
  31. package/src/providers/acp.js +67 -1
  32. package/src/providers/acp.ts +65 -2
  33. package/src/providers/antigravity.d.ts +5 -1
  34. package/src/providers/antigravity.js +643 -32
  35. package/src/providers/antigravity.ts +671 -33
  36. package/src/providers/base.d.ts +9 -0
  37. package/src/providers/factory.js +2 -0
  38. package/src/providers/pi.js +157 -0
  39. package/src/providers/pi.ts +144 -0
  40. package/src/provisioning/capabilityProvisioner.js +17 -0
  41. package/src/provisioning/capabilityTools.js +1 -1
  42. package/src/sandbox.js +30 -39
  43. package/src/sessionJournal.js +53 -10
  44. package/src/sessionJournal.ts +64 -10
  45. package/src/taskShape.js +9 -9
  46. package/src/taskShape.ts +9 -9
  47. package/src/timeMachine.js +124 -0
  48. package/src/timeMachine.ts +141 -0
  49. package/src/toolPacks.js +4 -10
  50. package/src/tools/archive.js +196 -59
  51. package/src/tools/archive.ts +220 -0
  52. package/src/tools/browserAutomator.js +78 -9
  53. package/src/tools/browserAutomator.ts +90 -9
  54. package/src/tools/desktopOpen.js +114 -31
  55. package/src/tools/desktopOpen.ts +144 -0
  56. package/src/tools/gitExec.js +5 -3
  57. package/src/tools/nativeEngine.js +4 -3
  58. package/src/tools/nativeEngine.ts +5 -3
  59. package/src/tools/openSourceToolProvisioner.js +5 -4
  60. package/src/tools/openSourceToolProvisioner.ts +5 -4
  61. package/src/tools/registry.js +3 -0
  62. package/src/tools/screenshot.js +55 -71
  63. package/src/tools/screenshot.ts +70 -0
  64. package/src/tools/sysRun.js +284 -117
  65. package/src/tools/sysRun.ts +347 -0
  66. package/src/tools/toolSelfRepair.js +109 -2
  67. package/src/tools/toolSelfRepair.ts +100 -2
  68. package/src/tools/updatePlan.js +49 -1
  69. package/src/tools/updatePlan.ts +43 -1
  70. package/src/tools/viewImage.js +93 -78
  71. package/src/tools/viewImage.ts +116 -0
  72. package/src/tools/webFetch.js +20 -6
  73. package/src/tools/webFetch.ts +26 -6
  74. package/src/tui/block.d.ts +1 -0
  75. package/src/tui/chatRenderer.d.ts +21 -0
  76. package/src/tui/chatRenderer.js +34 -47
  77. package/src/tui/clipboardSync.js +28 -1
  78. package/src/tui/clipboardSync.ts +26 -1
  79. package/src/tui/codeProgress.js +299 -0
  80. package/src/tui/codeProgress.ts +304 -0
  81. package/src/tui/codeStreamRenderer.js +116 -0
  82. package/src/tui/codeStreamRenderer.ts +124 -0
  83. package/src/tui/commandPresentation.js +11 -0
  84. package/src/tui/commandPresentation.ts +18 -0
  85. package/src/tui/completion.js +45 -13
  86. package/src/tui/composerControls.js +66 -0
  87. package/src/tui/composerControls.ts +78 -0
  88. package/src/tui/diff.d.ts +2 -0
  89. package/src/tui/home.js +4 -2
  90. package/src/tui/homeTransition.js +21 -0
  91. package/src/tui/homeTransition.ts +27 -0
  92. package/src/tui/homeView.js +62 -0
  93. package/src/tui/homeView.ts +91 -0
  94. package/src/tui/layout.js +46 -0
  95. package/src/tui/layout.ts +52 -0
  96. package/src/tui/messageActionPlacement.js +16 -0
  97. package/src/tui/messageActionPlacement.ts +25 -0
  98. package/src/tui/messageInteraction.js +221 -0
  99. package/src/tui/messageInteraction.ts +275 -0
  100. package/src/tui/modelPicker.js +4 -24
  101. package/src/tui/modelPicker.ts +4 -20
  102. package/src/tui/mouseHover.js +6 -0
  103. package/src/tui/mouseHover.ts +5 -0
  104. package/src/tui/prompt.js +152 -76
  105. package/src/tui/resizeRecovery.js +15 -0
  106. package/src/tui/resizeRecovery.ts +27 -0
  107. package/src/tui/scrollInteraction.js +97 -0
  108. package/src/tui/scrollInteraction.ts +189 -0
  109. package/src/tui/sessionLayout.js +12 -0
  110. package/src/tui/sessionLayout.ts +12 -0
  111. package/src/tui/sessionPicker.js +111 -16
  112. package/src/tui/sessionPicker.ts +121 -16
  113. package/src/tui/sessionSidebar.js +78 -0
  114. package/src/tui/sessionSidebar.ts +95 -0
  115. package/src/tui/setup.js +1 -1
  116. package/src/tui/setup.ts +1 -1
  117. package/src/tui/stageSurface.js +120 -58
  118. package/src/tui/text.d.ts +5 -0
  119. package/src/tui/textLayout.js +23 -0
  120. package/src/tui/textLayout.ts +28 -0
  121. package/src/tui/viewport.js +204 -279
  122. package/src/tui/viewport.ts +326 -0
  123. package/src/types/contracts.ts +54 -0
  124. package/src/utils/paths.js +5 -4
  125. package/src/utils/paths.ts +5 -5
@@ -7,15 +7,231 @@ import { assertPublicWebUrl } from './urlPolicy.js';
7
7
  import { windowSnapshot } from './snapshotWindow.js';
8
8
  const NAVIGATION_TIMEOUT_MS = 30_000;
9
9
  const ACTION_TIMEOUT_MS = 12_000;
10
+ const IFRAME_SNAPSHOT_TIMEOUT_MS = 3_000;
10
11
  const IDLE_CLOSE_MS = 10 * 60_000;
11
12
  const MAX_SEARCH_RESULTS = 10;
12
13
  const MAX_EXTRACT_CHARS = 80_000;
13
14
  const MAX_DOWNLOAD_BYTES = 250 * 1024 * 1024;
14
15
  const MAX_SCREENSHOT_BYTES = 25 * 1024 * 1024;
16
+ const MAX_SNAPSHOT_NODES = 500;
17
+ const MAX_IFRAMES_TO_PROCESS = 8;
15
18
  const INTERACTIVE_ROLES = new Set([
16
- 'button', 'checkbox', 'combobox', 'link', 'menuitem', 'option', 'radio',
19
+ 'button', 'checkbox', 'combobox', 'link', 'listitem', 'menuitem', 'option', 'radio',
17
20
  'searchbox', 'slider', 'spinbutton', 'switch', 'tab', 'textbox', 'treeitem'
18
21
  ]);
22
+ const SKIP_PATTERNS = [
23
+ /datepicker/i, /date.?picker/i, /calendar/i, /^date$/i
24
+ ];
25
+ const IFRAME_SKIP_PATTERNS = [
26
+ /web-pixel/i, /analytics/i, /tracking/i, /gtm/i, /facebook/i,
27
+ /doubleclick/i, /google.*tag/i, /hotjar/i, /segment/i, /sentry/i,
28
+ /recaptcha/i, /gstatic/i, /app-bridge/i, /extensions\.shopifycdn/i,
29
+ /px-iframe/i, /px-captcha/i, /perimeterx/i, /\bcaptcha\b/i, /hcaptcha/i,
30
+ /arkose/i, /funcaptcha/i, /datadome/i
31
+ ];
32
+ const NON_FILLABLE_INPUT_TYPES = new Set([
33
+ 'button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit'
34
+ ]);
35
+ const KEY_MODIFIER_ALIASES = new Map([
36
+ ['ctrl', 'Control'],
37
+ ['control', 'Control'],
38
+ ['cmd', 'Meta'],
39
+ ['command', 'Meta'],
40
+ ['meta', 'Meta'],
41
+ ['option', 'Alt'],
42
+ ['esc', 'Escape'],
43
+ ['return', 'Enter'],
44
+ ['enter', 'Enter'],
45
+ ['del', 'Delete']
46
+ ]);
47
+ const SEARCH_MACROS = {
48
+ '@google_search': query => `https://www.google.com/search?q=${encodeURIComponent(query || '')}`,
49
+ '@duckduckgo_search': query => `https://duckduckgo.com/?q=${encodeURIComponent(query || '')}`,
50
+ '@bing_search': query => `https://www.bing.com/search?q=${encodeURIComponent(query || '')}`,
51
+ '@github_search': query => `https://github.com/search?q=${encodeURIComponent(query || '')}`,
52
+ '@youtube_search': query => `https://www.youtube.com/results?search_query=${encodeURIComponent(query || '')}`,
53
+ '@amazon_search': query => `https://www.amazon.com/s?k=${encodeURIComponent(query || '')}`,
54
+ '@reddit_search': query => `https://www.reddit.com/search.json?q=${encodeURIComponent(query || '')}&limit=25`,
55
+ '@reddit_subreddit': query => `https://www.reddit.com/r/${encodeURIComponent(query || 'all')}.json?limit=25`,
56
+ '@wikipedia_search': query => `https://en.wikipedia.org/wiki/Special:Search?search=${encodeURIComponent(query || '')}`,
57
+ '@twitter_search': query => `https://twitter.com/search?q=${encodeURIComponent(query || '')}`,
58
+ '@yelp_search': query => `https://www.yelp.com/search?find_desc=${encodeURIComponent(query || '')}`,
59
+ '@spotify_search': query => `https://open.spotify.com/search/${encodeURIComponent(query || '')}`,
60
+ '@netflix_search': query => `https://www.netflix.com/search?q=${encodeURIComponent(query || '')}`,
61
+ '@linkedin_search': query => `https://www.linkedin.com/search/results/all/?keywords=${encodeURIComponent(query || '')}`,
62
+ '@instagram_search': query => `https://www.instagram.com/explore/tags/${encodeURIComponent(query || '')}`,
63
+ '@tiktok_search': query => `https://www.tiktok.com/search?q=${encodeURIComponent(query || '')}`,
64
+ '@twitch_search': query => `https://www.twitch.tv/search?term=${encodeURIComponent(query || '')}`
65
+ };
66
+ export function expandSearchMacro(macro, query = '') {
67
+ const fn = SEARCH_MACROS[String(macro || '').trim()];
68
+ return fn ? fn(String(query ?? '')) : null;
69
+ }
70
+ export function getSupportedSearchMacros() {
71
+ return Object.keys(SEARCH_MACROS);
72
+ }
73
+ export function normalizeBrowserKey(key) {
74
+ if (typeof key !== 'string' || !key.trim())
75
+ return 'Enter';
76
+ return key
77
+ .split('+')
78
+ .map(part => {
79
+ const trimmed = part.trim();
80
+ return KEY_MODIFIER_ALIASES.get(trimmed.toLowerCase()) ?? trimmed;
81
+ })
82
+ .join('+');
83
+ }
84
+ export function visibleSelectorCandidate(selector) {
85
+ if (typeof selector !== 'string')
86
+ return null;
87
+ const trimmed = selector.trim();
88
+ if (!trimmed || trimmed.includes(',') || trimmed.includes(':visible'))
89
+ return null;
90
+ return `${trimmed}:visible`;
91
+ }
92
+ export function selectorValidationError(selector) {
93
+ if (selector === undefined || selector === null)
94
+ return null;
95
+ if (typeof selector !== 'string' || selector.trim() === '')
96
+ return 'selector must be a non-empty string';
97
+ if (/^text\s*\(/i.test(selector))
98
+ return 'Invalid text selector syntax. Use text=... or a valid CSS selector.';
99
+ const stack = [];
100
+ let quote = null;
101
+ let escaped = false;
102
+ const pairs = { ')': '(', ']': '[', '}': '{' };
103
+ for (const ch of selector) {
104
+ if (escaped) {
105
+ escaped = false;
106
+ continue;
107
+ }
108
+ if (ch === '\\') {
109
+ escaped = true;
110
+ continue;
111
+ }
112
+ if (quote) {
113
+ if (ch === quote)
114
+ quote = null;
115
+ continue;
116
+ }
117
+ if (ch === '"' || ch === "'") {
118
+ quote = ch;
119
+ continue;
120
+ }
121
+ if (ch === '(' || ch === '[' || ch === '{')
122
+ stack.push(ch);
123
+ if (ch === ')' || ch === ']' || ch === '}') {
124
+ if (stack.pop() !== pairs[ch])
125
+ return `Invalid selector syntax: ${selector}`;
126
+ }
127
+ }
128
+ if (quote || stack.length > 0)
129
+ return `Invalid selector syntax: ${selector}`;
130
+ return null;
131
+ }
132
+ const SUPPORTED_SCHEMA_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'object', 'null']);
133
+ export function validateExtractSchema(schema) {
134
+ if (!schema || typeof schema !== 'object') {
135
+ return { ok: false, error: 'schema must be an object' };
136
+ }
137
+ const candidate = schema;
138
+ if (candidate.type !== 'object') {
139
+ return { ok: false, error: 'top-level schema must have type: object' };
140
+ }
141
+ if (!candidate.properties || typeof candidate.properties !== 'object' || Array.isArray(candidate.properties)) {
142
+ return { ok: false, error: 'schema must have a properties object' };
143
+ }
144
+ for (const [prop, def] of Object.entries(candidate.properties)) {
145
+ if (!def || typeof def !== 'object') {
146
+ return { ok: false, error: `property "${prop}" must be an object` };
147
+ }
148
+ const propDef = def;
149
+ if (propDef.type && !SUPPORTED_SCHEMA_TYPES.has(propDef.type)) {
150
+ return { ok: false, error: `property "${prop}" has unsupported type "${propDef.type}"` };
151
+ }
152
+ }
153
+ return { ok: true };
154
+ }
155
+ function coerceSchemaValue(raw, type) {
156
+ if (raw == null)
157
+ return null;
158
+ if (type === 'string' || !type)
159
+ return String(raw).trim();
160
+ if (type === 'number') {
161
+ const n = parseFloat(String(raw).replace(/[^0-9.eE+-]/g, ''));
162
+ return Number.isFinite(n) ? n : null;
163
+ }
164
+ if (type === 'integer') {
165
+ const n = parseInt(String(raw).replace(/[^0-9-]/g, ''), 10);
166
+ return Number.isFinite(n) ? n : null;
167
+ }
168
+ if (type === 'boolean') {
169
+ const s = String(raw).toLowerCase().trim();
170
+ if (s === 'true' || s === 'yes' || s === '1')
171
+ return true;
172
+ if (s === 'false' || s === 'no' || s === '0')
173
+ return false;
174
+ return null;
175
+ }
176
+ return raw;
177
+ }
178
+ export function extractDeterministic(options) {
179
+ const check = validateExtractSchema(options.schema);
180
+ if (!check.ok)
181
+ throw new Error(check.error ?? 'Invalid extraction schema');
182
+ const result = {};
183
+ for (const [prop, def] of Object.entries(options.schema.properties)) {
184
+ const refId = def['x-ref'];
185
+ let value = null;
186
+ if (refId) {
187
+ const info = options.refs.get(refId);
188
+ const raw = info?.name ? info.name : null;
189
+ if (raw != null) {
190
+ value = def.type && def.type !== 'object' ? coerceSchemaValue(raw, def.type) : raw;
191
+ }
192
+ }
193
+ if (value == null && Array.isArray(options.schema.required) && options.schema.required.includes(prop)) {
194
+ throw new Error(`required property "${prop}" could not be extracted (x-ref=${refId || 'n/a'})`);
195
+ }
196
+ result[prop] = value;
197
+ }
198
+ return result;
199
+ }
200
+ export function attachStructureRefs(structure, refs) {
201
+ if (!structure || !(refs instanceof Map))
202
+ return structure;
203
+ const refByRoleAndName = new Map();
204
+ for (const [ref, info] of refs) {
205
+ refByRoleAndName.set(`${info.role}:${info.name}:${info.nth}`, ref);
206
+ }
207
+ const assign = (control, role) => {
208
+ if (!control?.label)
209
+ return;
210
+ const ref = refByRoleAndName.get(`${role}:${control.label}:0`);
211
+ if (ref)
212
+ control.ref = ref;
213
+ };
214
+ for (const form of structure.forms || []) {
215
+ for (const field of form.fields || [])
216
+ assign(field, field.role);
217
+ for (const control of form.submitControls || [])
218
+ assign(control, 'button');
219
+ }
220
+ return structure;
221
+ }
222
+ export function isDeadContextError(err) {
223
+ const msg = errorMessage(err);
224
+ return msg.includes('Target page, context or browser has been closed')
225
+ || msg.includes('browser has been closed')
226
+ || msg.includes('Context closed')
227
+ || msg.includes('Browser closed');
228
+ }
229
+ export function isPageCrashedError(err) {
230
+ const msg = errorMessage(err);
231
+ return msg.includes('Page crashed')
232
+ || msg.includes('Target crashed')
233
+ || msg.includes('crashed page');
234
+ }
19
235
  export class BrowserCapabilityError extends Error {
20
236
  requiresConsent;
21
237
  constructor(message, requiresConsent = false) {
@@ -40,15 +256,17 @@ export function parseAriaRefs(snapshot) {
40
256
  const seen = new Map();
41
257
  let counter = 1;
42
258
  for (const line of String(snapshot ?? '').split('\n')) {
43
- if (counter > 500)
259
+ if (counter > MAX_SNAPSHOT_NODES)
44
260
  break;
45
261
  const match = line.match(/^\s*-\s+([a-z][\w-]*)(?:\s+"([^"]*)")?/i);
46
262
  if (!match)
47
263
  continue;
48
264
  const role = (match[1] ?? '').toLowerCase();
265
+ const name = match[2] ?? '';
266
+ if (name && SKIP_PATTERNS.some(pattern => pattern.test(name)))
267
+ continue;
49
268
  if (!INTERACTIVE_ROLES.has(role))
50
269
  continue;
51
- const name = match[2] ?? '';
52
270
  const key = `${role}:${name}`;
53
271
  const nth = seen.get(key) ?? 0;
54
272
  seen.set(key, nth + 1);
@@ -59,6 +277,8 @@ export function parseAriaRefs(snapshot) {
59
277
  export function annotateAriaSnapshot(snapshot, refs) {
60
278
  const queues = new Map();
61
279
  for (const [id, ref] of refs) {
280
+ if (ref.frameName || ref.frameUrl)
281
+ continue;
62
282
  const key = `${ref.role}:${ref.name}`;
63
283
  queues.set(key, [...(queues.get(key) ?? []), id]);
64
284
  }
@@ -66,11 +286,252 @@ export function annotateAriaSnapshot(snapshot, refs) {
66
286
  const match = line.match(/^(\s*-\s+)([a-z][\w-]*)(?:\s+"([^"]*)")?/i);
67
287
  if (!match)
68
288
  return line;
69
- const key = `${(match[2] ?? '').toLowerCase()}:${match[3] ?? ''}`;
289
+ const name = match[3] ?? '';
290
+ if (name && SKIP_PATTERNS.some(pattern => pattern.test(name)))
291
+ return line;
292
+ const key = `${(match[2] ?? '').toLowerCase()}:${name}`;
70
293
  const id = queues.get(key)?.shift();
71
294
  return id ? `${line} [${id}]` : line;
72
295
  }).join('\n');
73
296
  }
297
+ const PAGE_STRUCTURE_EXTRACT_SCRIPT = `(() => {
298
+ const MAX_FORMS = 20;
299
+ const MAX_FIELDS_PER_FORM = 30;
300
+ const MAX_TABLES = 20;
301
+ const MAX_ROWS_PER_TABLE = 50;
302
+ const MAX_CELLS_PER_ROW = 30;
303
+ const MAX_CELL_CHARS = 200;
304
+ const MAX_OPTIONS_PER_SELECT = 30;
305
+ const MAX_LABEL_CHARS = 150;
306
+ const SENSITIVE_FIELD_RE = /password|passwd|pwd|secret|token|api[_-]?key|ssn|credit|card|cvv|cvc/i;
307
+
308
+ function trunc(str, max) {
309
+ if (!str) return '';
310
+ const s = String(str).replace(/\\s+/g, ' ').trim();
311
+ return s.length > max ? s.slice(0, max) + '…' : s;
312
+ }
313
+
314
+ function isVisible(el) {
315
+ if (!el || !el.getBoundingClientRect) return false;
316
+ if (el.hidden || el.getAttribute('aria-hidden') === 'true') return false;
317
+ const style = window.getComputedStyle(el);
318
+ if (!style || style.display === 'none' || style.visibility === 'hidden') return false;
319
+ const rect = el.getBoundingClientRect();
320
+ return rect.width > 0 || rect.height > 0;
321
+ }
322
+
323
+ function resolveLabel(el) {
324
+ const ariaLabel = el.getAttribute('aria-label');
325
+ if (ariaLabel) return trunc(ariaLabel, MAX_LABEL_CHARS);
326
+ const labelledBy = el.getAttribute('aria-labelledby');
327
+ if (labelledBy) {
328
+ const text = labelledBy
329
+ .split(/\\s+/)
330
+ .map(id => document.getElementById(id)?.textContent || '')
331
+ .join(' ')
332
+ .trim();
333
+ if (text) return trunc(text, MAX_LABEL_CHARS);
334
+ }
335
+ if (el.id) {
336
+ const escapedId = String(el.id).replace(/"/g, '\\\\"');
337
+ const byFor = document.querySelector('label[for="' + escapedId + '"]');
338
+ if (byFor) return trunc(byFor.textContent, MAX_LABEL_CHARS);
339
+ }
340
+ const parentLabel = el.closest('label');
341
+ if (parentLabel) {
342
+ const clone = parentLabel.cloneNode(true);
343
+ clone.querySelectorAll('input,select,textarea,button').forEach(node => node.remove());
344
+ const text = clone.textContent?.trim();
345
+ if (text) return trunc(text, MAX_LABEL_CHARS);
346
+ }
347
+ const placeholder = el.getAttribute('placeholder');
348
+ if (placeholder) return trunc(placeholder, MAX_LABEL_CHARS);
349
+ const title = el.getAttribute('title');
350
+ if (title) return trunc(title, MAX_LABEL_CHARS);
351
+ return null;
352
+ }
353
+
354
+ function inferRole(el, tag, type) {
355
+ const explicit = el.getAttribute('role');
356
+ if (explicit) return explicit.toLowerCase();
357
+ if (tag === 'button') return 'button';
358
+ if (tag === 'select') return 'combobox';
359
+ if (tag === 'textarea') return 'textbox';
360
+ if (tag === 'input') {
361
+ if (type === 'submit' || type === 'button' || type === 'reset') return 'button';
362
+ if (type === 'checkbox') return 'checkbox';
363
+ if (type === 'radio') return 'radio';
364
+ if (type === 'search') return 'searchbox';
365
+ if (type === 'number') return 'spinbutton';
366
+ if (type === 'range') return 'slider';
367
+ return 'textbox';
368
+ }
369
+ return null;
370
+ }
371
+
372
+ function extractField(el) {
373
+ const tag = (el.tagName || '').toLowerCase();
374
+ const type = tag === 'input' ? (el.getAttribute('type') || 'text').toLowerCase() : tag;
375
+ if (type === 'hidden') return null;
376
+ if (!isVisible(el)) return null;
377
+ const name = el.getAttribute('name') || null;
378
+ const id = el.id || null;
379
+ const label = resolveLabel(el);
380
+ const role = inferRole(el, tag, type);
381
+ const accessibleName = trunc(
382
+ el.getAttribute('aria-label') || label || el.value || el.textContent || '',
383
+ MAX_LABEL_CHARS
384
+ ) || null;
385
+ const isSensitive = type === 'password'
386
+ || SENSITIVE_FIELD_RE.test(name || '')
387
+ || SENSITIVE_FIELD_RE.test(id || '')
388
+ || SENSITIVE_FIELD_RE.test(el.getAttribute('autocomplete') || '');
389
+ const field = { tag, type };
390
+ if (name) field.name = trunc(name, 80);
391
+ if (id) field.id = trunc(id, 80);
392
+ if (label) field.label = label;
393
+ if (role) field.role = role;
394
+ if (accessibleName) field._accessibleName = accessibleName;
395
+ const placeholder = el.getAttribute('placeholder');
396
+ if (placeholder && placeholder !== label) field.placeholder = trunc(placeholder, MAX_LABEL_CHARS);
397
+ if (el.required || el.getAttribute('aria-required') === 'true') field.required = true;
398
+ if (el.disabled || el.getAttribute('aria-disabled') === 'true') field.disabled = true;
399
+ if (el.readOnly) field.readOnly = true;
400
+ if (type === 'checkbox' || type === 'radio') {
401
+ field.checked = Boolean(el.checked);
402
+ if (el.value && el.value !== 'on') field.value = trunc(el.value, 100);
403
+ } else if (tag === 'select') {
404
+ const opts = Array.from(el.options || []).slice(0, MAX_OPTIONS_PER_SELECT).map(o => ({
405
+ value: trunc(o.value, 100),
406
+ text: trunc(o.text, 100),
407
+ ...(o.selected ? { selected: true } : {})
408
+ }));
409
+ field.options = opts;
410
+ if ((el.options || []).length > MAX_OPTIONS_PER_SELECT) field.optionsTruncated = true;
411
+ } else if (tag === 'button' || type === 'submit' || type === 'button' || type === 'reset') {
412
+ const btnText = trunc(el.textContent || el.value || '', 100);
413
+ if (btnText) field.text = btnText;
414
+ } else if (isSensitive) {
415
+ field.value = el.value ? '[REDACTED]' : '';
416
+ field.redacted = true;
417
+ } else if (typeof el.value === 'string' && el.value.length > 0) {
418
+ field.value = trunc(el.value, MAX_CELL_CHARS);
419
+ }
420
+ return field;
421
+ }
422
+
423
+ const formEls = Array.from(document.querySelectorAll('form'));
424
+ const forms = [];
425
+ const seenControls = new Set();
426
+
427
+ for (const formEl of formEls.slice(0, MAX_FORMS)) {
428
+ const controls = Array.from(formEl.querySelectorAll('input, select, textarea, button'));
429
+ controls.forEach(c => seenControls.add(c));
430
+ const fields = [];
431
+ for (const ctrl of controls) {
432
+ if (fields.length >= MAX_FIELDS_PER_FORM) break;
433
+ const f = extractField(ctrl);
434
+ if (f) fields.push(f);
435
+ }
436
+ if (fields.length === 0) continue;
437
+ const formObj = { fields };
438
+ if (formEl.id) formObj.id = trunc(formEl.id, 80);
439
+ const fName = formEl.getAttribute('name') || formEl.getAttribute('aria-label');
440
+ if (fName) formObj.name = trunc(fName, 100);
441
+ const action = formEl.getAttribute('action');
442
+ if (action) formObj.action = trunc(action, 200);
443
+ const method = (formEl.getAttribute('method') || 'get').toUpperCase();
444
+ formObj.method = method;
445
+ if (controls.length > MAX_FIELDS_PER_FORM) formObj.fieldsTruncated = true;
446
+ forms.push(formObj);
447
+ }
448
+
449
+ if (forms.length < MAX_FORMS) {
450
+ const orphans = Array.from(document.querySelectorAll('input, select, textarea'))
451
+ .filter(el => !seenControls.has(el));
452
+ const orphanFields = [];
453
+ for (const ctrl of orphans) {
454
+ if (orphanFields.length >= MAX_FIELDS_PER_FORM) break;
455
+ const f = extractField(ctrl);
456
+ if (f) orphanFields.push(f);
457
+ }
458
+ if (orphanFields.length > 0) {
459
+ forms.push({ implicit: true, fields: orphanFields });
460
+ }
461
+ }
462
+
463
+ const tableEls = Array.from(document.querySelectorAll('table'));
464
+ const tables = [];
465
+
466
+ for (const tableEl of tableEls) {
467
+ if (tables.length >= MAX_TABLES) break;
468
+ if (!isVisible(tableEl)) continue;
469
+ const allRows = Array.from(tableEl.querySelectorAll('tr'));
470
+ if (allRows.length === 0) continue;
471
+ let headers = [];
472
+ const theadRow = tableEl.querySelector('thead tr');
473
+ let bodyStartIdx = 0;
474
+ if (theadRow) {
475
+ headers = Array.from(theadRow.querySelectorAll('th, td'))
476
+ .slice(0, MAX_CELLS_PER_ROW)
477
+ .map(c => trunc(c.textContent, MAX_CELL_CHARS));
478
+ } else {
479
+ const firstRow = allRows[0];
480
+ const ths = firstRow.querySelectorAll('th');
481
+ if (ths.length > 0) {
482
+ headers = Array.from(firstRow.querySelectorAll('th, td'))
483
+ .slice(0, MAX_CELLS_PER_ROW)
484
+ .map(c => trunc(c.textContent, MAX_CELL_CHARS));
485
+ bodyStartIdx = 1;
486
+ }
487
+ }
488
+ const bodyRowEls = theadRow
489
+ ? Array.from(tableEl.querySelectorAll('tbody tr'))
490
+ : allRows.slice(bodyStartIdx);
491
+ const rows = [];
492
+ for (const tr of bodyRowEls) {
493
+ if (rows.length >= MAX_ROWS_PER_TABLE) break;
494
+ const cells = Array.from(tr.querySelectorAll('td, th'))
495
+ .slice(0, MAX_CELLS_PER_ROW)
496
+ .map(c => trunc(c.textContent, MAX_CELL_CHARS));
497
+ if (cells.length === 0 || cells.every(c => c === '')) continue;
498
+ if (headers.length > 0 && headers.some(Boolean)) {
499
+ const obj = {};
500
+ cells.forEach((val, idx) => {
501
+ const key = headers[idx] || ('col_' + (idx + 1));
502
+ obj[key] = val;
503
+ });
504
+ rows.push(obj);
505
+ } else {
506
+ rows.push(cells);
507
+ }
508
+ }
509
+ if (headers.length === 0 && rows.length < 2) continue;
510
+ const tableObj = { headers, rows, rowCount: bodyRowEls.length };
511
+ if (tableEl.id) tableObj.id = trunc(tableEl.id, 80);
512
+ const caption = tableEl.querySelector('caption')?.textContent || tableEl.getAttribute('aria-label');
513
+ if (caption) tableObj.caption = trunc(caption, MAX_LABEL_CHARS);
514
+ if (bodyRowEls.length > MAX_ROWS_PER_TABLE) tableObj.rowsTruncated = true;
515
+ tables.push(tableObj);
516
+ }
517
+
518
+ return { forms, tables };
519
+ })()`;
520
+ export async function extractPageStructure(page) {
521
+ try {
522
+ const raw = await page.evaluate(PAGE_STRUCTURE_EXTRACT_SCRIPT);
523
+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.forms) || !Array.isArray(raw.tables)) {
524
+ return null;
525
+ }
526
+ if (raw.forms.length === 0 && raw.tables.length === 0) {
527
+ return null;
528
+ }
529
+ return raw;
530
+ }
531
+ catch {
532
+ return null;
533
+ }
534
+ }
74
535
  const SEARCH_EXTRACT_SCRIPT = `(() => {
75
536
  const text = value => String(value || '').replace(/\\s+/g, ' ').trim();
76
537
  const candidates = [
@@ -110,6 +571,86 @@ const SEARCH_EXTRACT_SCRIPT = `(() => {
110
571
  }
111
572
  return results;
112
573
  })()`;
574
+ const LINKS_EXTRACT_SCRIPT = `(opts) => {
575
+ const scope = opts && opts.selector ? document.querySelector(opts.selector) : document;
576
+ if (!scope) return { links: [], totalLinks: 0 };
577
+ const anchors = Array.from(scope.querySelectorAll('a[href]'));
578
+ const seen = new Set();
579
+ const all = [];
580
+ for (const a of anchors) {
581
+ let href;
582
+ try {
583
+ href = new URL(a.getAttribute('href'), document.baseURI).href;
584
+ } catch {
585
+ continue;
586
+ }
587
+ if (!href.startsWith('http://') && !href.startsWith('https://')) continue;
588
+ if (seen.has(href)) continue;
589
+ seen.add(href);
590
+ const text = (a.textContent || '').trim().replace(/\\s+/g, ' ').slice(0, 200);
591
+ all.push({ url: href, text: text || undefined });
592
+ }
593
+ const start = (opts && opts.offset) || 0;
594
+ const max = (opts && opts.limit) || 50;
595
+ return { links: all.slice(start, start + max), totalLinks: all.length };
596
+ }`;
597
+ const IMAGES_EXTRACT_SCRIPT = `(opts) => {
598
+ const max = Math.min(Math.max(Number(opts && opts.limit) || 100, 1), 300);
599
+ const imgs = Array.from(document.querySelectorAll('img'));
600
+ const seen = new Set();
601
+ const out = [];
602
+ for (const img of imgs) {
603
+ const src = img.currentSrc || img.src || '';
604
+ if (!src || src.startsWith('data:') || seen.has(src)) continue;
605
+ const width = Number(img.naturalWidth || img.width || 0);
606
+ const height = Number(img.naturalHeight || img.height || 0);
607
+ seen.add(src);
608
+ out.push({
609
+ src,
610
+ alt: (img.alt || '').trim().slice(0, 200) || undefined,
611
+ width,
612
+ height
613
+ });
614
+ if (out.length >= max) break;
615
+ }
616
+ return out;
617
+ }`;
618
+ const DISMISS_CONSENT_SCRIPT = `(() => {
619
+ const selectors = [
620
+ '#onetrust-accept-btn-handler',
621
+ '.onetrust-close-btn-handler',
622
+ '#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll',
623
+ '#CybotCookiebotDialogBodyButtonAccept',
624
+ '[data-testid="cookie-policy-dialog-accept-button"]',
625
+ 'button[id*="cookie"][id*="accept" i]',
626
+ 'button[class*="cookie"][class*="accept" i]',
627
+ 'button[aria-label*="Accept all" i]',
628
+ 'button[aria-label*="Accept cookies" i]'
629
+ ];
630
+ for (const sel of selectors) {
631
+ const el = document.querySelector(sel);
632
+ if (el && typeof el.click === 'function') {
633
+ const rect = el.getBoundingClientRect?.();
634
+ if (!rect || (rect.width > 0 && rect.height > 0)) {
635
+ el.click();
636
+ return true;
637
+ }
638
+ }
639
+ }
640
+ return false;
641
+ })()`;
642
+ const WAIT_FOR_PAGE_READY_SCRIPT = `(() => {
643
+ return new Promise(resolve => {
644
+ if (document.readyState === 'complete') {
645
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)));
646
+ } else {
647
+ window.addEventListener('load', () => {
648
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)));
649
+ }, { once: true });
650
+ setTimeout(() => resolve(false), 3000);
651
+ }
652
+ });
653
+ })()`;
113
654
  export class CausyneBrowser {
114
655
  workspace;
115
656
  ensureBrowserCapability;
@@ -135,14 +676,36 @@ export class CausyneBrowser {
135
676
  this.visible = options.visible ?? process.env.CAUSYNE_BROWSER_VISIBLE === '1';
136
677
  this.validateUrl = options.validateUrl ?? assertPublicWebUrl;
137
678
  }
138
- async run(actions) {
679
+ setWorkspace(workspace) {
680
+ if (workspace && typeof workspace === 'string') {
681
+ this.workspace = path.resolve(workspace);
682
+ }
683
+ }
684
+ getWorkspace() {
685
+ return this.workspace;
686
+ }
687
+ async run(actions, options = {}) {
139
688
  if (!Array.isArray(actions) || actions.length === 0 || actions.length > 40) {
140
689
  throw new Error('Browser actions must contain between 1 and 40 operations');
141
690
  }
691
+ const activeWorkspace = options.workspace ? path.resolve(options.workspace) : this.workspace;
142
692
  await this.start();
143
693
  const results = [];
144
- for (const action of actions)
145
- results.push(await this.runAction(action));
694
+ for (const action of actions) {
695
+ try {
696
+ results.push(await this.runAction(action, activeWorkspace));
697
+ }
698
+ catch (error) {
699
+ if (isDeadContextError(error)) {
700
+ await this.close();
701
+ await this.start();
702
+ results.push(await this.runAction(action, activeWorkspace));
703
+ }
704
+ else {
705
+ throw error;
706
+ }
707
+ }
708
+ }
146
709
  this.touch();
147
710
  return results;
148
711
  }
@@ -177,15 +740,14 @@ export class CausyneBrowser {
177
740
  async snapshot(offset = 0) {
178
741
  await this.start();
179
742
  const state = await this.activeTab();
180
- const raw = await state.page.locator('body').ariaSnapshot({ timeout: ACTION_TIMEOUT_MS });
181
- state.refs = parseAriaRefs(raw);
182
- state.lastSnapshot = annotateAriaSnapshot(raw, state.refs);
743
+ await this.captureSnapshotState(state);
183
744
  return {
184
745
  ...windowSnapshot(state.lastSnapshot, offset),
185
746
  tabId: state.id,
186
747
  url: state.page.url(),
187
748
  title: await state.page.title(),
188
- refsCount: state.refs.size
749
+ refsCount: state.refs.size,
750
+ ...(state.lastStructure ? { structure: state.lastStructure } : {})
189
751
  };
190
752
  }
191
753
  async close() {
@@ -203,9 +765,26 @@ export class CausyneBrowser {
203
765
  if (session)
204
766
  await session.close().catch(() => { });
205
767
  }
768
+ isSessionHealthy() {
769
+ if (!this.session)
770
+ return false;
771
+ if (typeof this.session.isConnected === 'function' && !this.session.isConnected()) {
772
+ return false;
773
+ }
774
+ try {
775
+ this.session.pages();
776
+ return true;
777
+ }
778
+ catch {
779
+ return false;
780
+ }
781
+ }
206
782
  async start() {
207
- if (this.session)
208
- return;
783
+ if (this.session) {
784
+ if (this.isSessionHealthy())
785
+ return;
786
+ await this.close();
787
+ }
209
788
  if (this.starting)
210
789
  return this.starting;
211
790
  this.starting = (async () => {
@@ -224,7 +803,14 @@ export class CausyneBrowser {
224
803
  humanize: 0.35,
225
804
  block_webrtc: true,
226
805
  geoip: false,
227
- enable_cache: true
806
+ enable_cache: true,
807
+ ...(runtime.executablePath ? { executable_path: runtime.executablePath } : {}),
808
+ firefox_user_prefs: {
809
+ 'Security.OCSP.enabled': 0
810
+ },
811
+ handleSIGTERM: false,
812
+ handleSIGINT: false,
813
+ handleSIGHUP: false
228
814
  });
229
815
  if (typeof this.session.route === 'function') {
230
816
  await this.session.route('**/*', route => this.guardRoute(route));
@@ -256,7 +842,17 @@ export class CausyneBrowser {
256
842
  await page.route('**/*', route => this.guardRoute(route));
257
843
  this.securedPages.add(page);
258
844
  }
259
- const state = { id, page, refs: new Map(), lastSnapshot: '' };
845
+ const state = { id, page, refs: new Map(), lastSnapshot: '', lastStructure: null };
846
+ page.on?.('crash', () => {
847
+ state.crashed = true;
848
+ });
849
+ page.on?.('close', () => {
850
+ this.tabs.delete(id);
851
+ if (this.activeTabId === id) {
852
+ const remaining = [...this.tabs.values()].find(tab => !tab.page.isClosed() && !tab.crashed);
853
+ this.activeTabId = remaining?.id ?? null;
854
+ }
855
+ });
260
856
  this.pageStates.set(page, state);
261
857
  this.tabs.set(id, state);
262
858
  this.activeTabId = id;
@@ -284,26 +880,160 @@ export class CausyneBrowser {
284
880
  async createTab(url) {
285
881
  if (!this.session)
286
882
  throw new Error('Browser is not started');
287
- const state = await this.registerPage(await this.session.newPage());
883
+ let page;
884
+ try {
885
+ page = await this.session.newPage();
886
+ }
887
+ catch (error) {
888
+ if (isDeadContextError(error)) {
889
+ await this.close();
890
+ await this.start();
891
+ if (!this.session)
892
+ throw error;
893
+ page = await this.session.newPage();
894
+ }
895
+ else {
896
+ throw error;
897
+ }
898
+ }
899
+ const state = await this.registerPage(page);
288
900
  if (url)
289
901
  await this.navigate(state, url);
290
902
  return state;
291
903
  }
292
904
  async activeTab() {
293
905
  const active = this.activeTabId ? this.tabs.get(this.activeTabId) : undefined;
294
- if (active && !active.page.isClosed())
906
+ if (active && !active.page.isClosed() && !active.crashed)
295
907
  return active;
908
+ for (const candidate of this.tabs.values()) {
909
+ if (!candidate.page.isClosed() && !candidate.crashed) {
910
+ this.activeTabId = candidate.id;
911
+ return candidate;
912
+ }
913
+ }
296
914
  return this.createTab();
297
915
  }
298
916
  requestedTab(action) {
299
917
  if (!action.tabId)
300
918
  return null;
301
919
  const state = this.tabs.get(action.tabId);
302
- if (!state || state.page.isClosed())
920
+ if (!state || state.page.isClosed() || state.crashed)
303
921
  throw new Error(`Unknown or closed browser tab: ${action.tabId}`);
304
922
  this.activeTabId = state.id;
305
923
  return state;
306
924
  }
925
+ async captureSnapshotState(state) {
926
+ let raw;
927
+ try {
928
+ raw = await state.page.locator('body').ariaSnapshot({ timeout: ACTION_TIMEOUT_MS });
929
+ }
930
+ catch (error) {
931
+ if (isDeadContextError(error) || isPageCrashedError(error))
932
+ throw error;
933
+ await state.page.waitForTimeout(400);
934
+ raw = await state.page.locator('body').ariaSnapshot({ timeout: ACTION_TIMEOUT_MS });
935
+ }
936
+ const mainRefs = parseAriaRefs(raw);
937
+ const annotatedParts = [annotateAriaSnapshot(raw, mainRefs)];
938
+ const allRefs = new Map(mainRefs);
939
+ let nextCounter = allRefs.size + 1;
940
+ if (typeof state.page.frames === 'function') {
941
+ try {
942
+ const mainFrame = typeof state.page.mainFrame === 'function' ? state.page.mainFrame() : null;
943
+ const childFrames = state.page.frames().filter(frame => frame !== mainFrame);
944
+ for (const frame of childFrames.slice(0, MAX_IFRAMES_TO_PROCESS)) {
945
+ if (nextCounter > MAX_SNAPSHOT_NODES)
946
+ break;
947
+ const frameUrl = frame.url();
948
+ if (!frameUrl || frameUrl === 'about:blank' || frameUrl.startsWith('javascript:') || frameUrl.startsWith('data:')) {
949
+ continue;
950
+ }
951
+ if (IFRAME_SKIP_PATTERNS.some(pattern => pattern.test(frameUrl)))
952
+ continue;
953
+ try {
954
+ const frameYaml = await frame.locator('body').ariaSnapshot({ timeout: IFRAME_SNAPSHOT_TIMEOUT_MS });
955
+ if (!frameYaml || frameYaml.trim().length < 10)
956
+ continue;
957
+ const frameSeen = new Map();
958
+ const frameRefs = new Map();
959
+ const frameName = frame.name() || undefined;
960
+ for (const line of String(frameYaml).split('\n')) {
961
+ if (nextCounter > MAX_SNAPSHOT_NODES)
962
+ break;
963
+ const match = line.match(/^\s*-\s+([a-z][\w-]*)(?:\s+"([^"]*)")?/i);
964
+ if (!match)
965
+ continue;
966
+ const role = (match[1] ?? '').toLowerCase();
967
+ const name = match[2] ?? '';
968
+ if (name && SKIP_PATTERNS.some(pattern => pattern.test(name)))
969
+ continue;
970
+ if (!INTERACTIVE_ROLES.has(role))
971
+ continue;
972
+ const key = `${role}:${name}`;
973
+ const nth = frameSeen.get(key) ?? 0;
974
+ frameSeen.set(key, nth + 1);
975
+ const id = `e${nextCounter++}`;
976
+ const ref = { role, name, nth, frameUrl, ...(frameName ? { frameName } : {}) };
977
+ frameRefs.set(id, ref);
978
+ allRefs.set(id, ref);
979
+ }
980
+ if (frameRefs.size > 0) {
981
+ const queues = new Map();
982
+ for (const [id, ref] of frameRefs) {
983
+ const key = `${ref.role}:${ref.name}`;
984
+ queues.set(key, [...(queues.get(key) ?? []), id]);
985
+ }
986
+ const annotatedFrame = String(frameYaml).split('\n').map(line => {
987
+ const match = line.match(/^(\s*-\s+)([a-z][\w-]*)(?:\s+"([^"]*)")?/i);
988
+ if (!match)
989
+ return line;
990
+ const name = match[3] ?? '';
991
+ const key = `${(match[2] ?? '').toLowerCase()}:${name}`;
992
+ const id = queues.get(key)?.shift();
993
+ return id ? `${line} [${id}]` : line;
994
+ }).join('\n');
995
+ annotatedParts.push(`\n--- iframe: ${frameName || frameUrl} ---\n${annotatedFrame}`);
996
+ }
997
+ }
998
+ catch {
999
+ // Cross-origin or detached iframe; skip gracefully
1000
+ }
1001
+ }
1002
+ }
1003
+ catch {
1004
+ // Ignore frame enumeration errors
1005
+ }
1006
+ }
1007
+ const structure = await extractPageStructure(state.page);
1008
+ if (structure) {
1009
+ attachStructureRefs(structure, allRefs);
1010
+ }
1011
+ state.refs = allRefs;
1012
+ state.lastSnapshot = annotatedParts.join('\n');
1013
+ state.lastStructure = structure;
1014
+ }
1015
+ resolveTargetUrl(action) {
1016
+ if (action.macro) {
1017
+ const expanded = expandSearchMacro(action.macro, action.query ?? action.text ?? '');
1018
+ if (!expanded) {
1019
+ throw new Error(`Unsupported search macro: ${action.macro}. Supported macros: ${getSupportedSearchMacros().join(', ')}`);
1020
+ }
1021
+ return { targetUrl: expanded, macroName: action.macro, macroQuery: action.query ?? action.text ?? '' };
1022
+ }
1023
+ if (action.url && action.url.trim().startsWith('@')) {
1024
+ const trimmed = action.url.trim();
1025
+ const spaceIdx = trimmed.indexOf(' ');
1026
+ const macroName = spaceIdx === -1 ? trimmed : trimmed.slice(0, spaceIdx);
1027
+ const inlineQuery = spaceIdx === -1 ? (action.query ?? action.text ?? '') : trimmed.slice(spaceIdx + 1).trim();
1028
+ const expanded = expandSearchMacro(macroName, inlineQuery);
1029
+ if (expanded) {
1030
+ return { targetUrl: expanded, macroName, macroQuery: inlineQuery };
1031
+ }
1032
+ }
1033
+ if (!action.url)
1034
+ throw new Error(`${action.type} requires url or macro`);
1035
+ return { targetUrl: action.url };
1036
+ }
307
1037
  async navigate(state, value) {
308
1038
  const url = await this.validateUrl(value);
309
1039
  const response = await state.page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
@@ -314,29 +1044,256 @@ export class CausyneBrowser {
314
1044
  await this.validateUrl(state.page.url());
315
1045
  state.refs.clear();
316
1046
  state.lastSnapshot = '';
1047
+ state.lastStructure = null;
1048
+ }
1049
+ async navigateWithMacroFallback(state, action) {
1050
+ const { targetUrl, macroName, macroQuery } = this.resolveTargetUrl(action);
1051
+ if (macroName === '@google_search' && macroQuery) {
1052
+ const fallbacks = [
1053
+ targetUrl,
1054
+ `https://duckduckgo.com/html/?q=${encodeURIComponent(macroQuery)}`,
1055
+ `https://www.bing.com/search?q=${encodeURIComponent(macroQuery)}`
1056
+ ];
1057
+ let lastError = null;
1058
+ for (let i = 0; i < fallbacks.length; i++) {
1059
+ try {
1060
+ await this.navigate(state, fallbacks[i]);
1061
+ if (i === 0) {
1062
+ await state.page.waitForTimeout(200);
1063
+ const extracted = await state.page.evaluate(SEARCH_EXTRACT_SCRIPT).catch(() => []);
1064
+ if (Array.isArray(extracted) && extracted.length === 0) {
1065
+ const currentUrl = state.page.url();
1066
+ if (/google\.[^/]+\/sorry/i.test(currentUrl)) {
1067
+ continue;
1068
+ }
1069
+ }
1070
+ }
1071
+ return;
1072
+ }
1073
+ catch (error) {
1074
+ lastError = error;
1075
+ }
1076
+ }
1077
+ if (lastError)
1078
+ throw lastError;
1079
+ return;
1080
+ }
1081
+ await this.navigate(state, targetUrl);
317
1082
  }
318
- locatorFor(state, action) {
1083
+ resolveRefFrame(state, ref) {
1084
+ if (!ref.frameName && !ref.frameUrl)
1085
+ return state.page;
1086
+ try {
1087
+ if (ref.frameName && typeof state.page.frame === 'function') {
1088
+ const byName = state.page.frame({ name: ref.frameName });
1089
+ if (byName)
1090
+ return byName;
1091
+ }
1092
+ if (ref.frameUrl && typeof state.page.frames === 'function') {
1093
+ const exact = state.page.frames().find(f => f.url() === ref.frameUrl);
1094
+ if (exact)
1095
+ return exact;
1096
+ const prefix = ref.frameUrl.split('?')[0] ?? '';
1097
+ if (prefix) {
1098
+ const byPrefix = state.page.frames().find(f => f.url().startsWith(prefix));
1099
+ if (byPrefix)
1100
+ return byPrefix;
1101
+ }
1102
+ }
1103
+ }
1104
+ catch {
1105
+ // Fall back to main page
1106
+ }
1107
+ return state.page;
1108
+ }
1109
+ async locatorFor(state, action) {
319
1110
  const refId = action.ref ?? (action.index !== undefined ? `e${action.index}` : undefined);
320
1111
  if (refId) {
321
- const ref = state.refs.get(refId);
1112
+ let ref = state.refs.get(refId);
1113
+ if (!ref && state.refs.size === 0) {
1114
+ await this.captureSnapshotState(state).catch(() => { });
1115
+ ref = state.refs.get(refId);
1116
+ }
322
1117
  if (!ref)
323
1118
  throw new Error(`Unknown element ref ${refId}. Take a new snapshot before interacting.`);
324
- return state.page.getByRole(ref.role, { name: ref.name, exact: true }).nth(ref.nth);
1119
+ const target = this.resolveRefFrame(state, ref);
1120
+ return target.getByRole(ref.role, { name: ref.name, exact: true }).nth(ref.nth);
325
1121
  }
326
- if (action.selector)
1122
+ if (action.selector) {
1123
+ const validationErr = selectorValidationError(action.selector);
1124
+ if (validationErr)
1125
+ throw new Error(validationErr);
1126
+ const visibleCandidate = visibleSelectorCandidate(action.selector);
1127
+ if (visibleCandidate) {
1128
+ try {
1129
+ const candidateLocator = state.page.locator(visibleCandidate);
1130
+ if (typeof candidateLocator.count === 'function') {
1131
+ const visibleCount = await candidateLocator.count();
1132
+ if (visibleCount === 1) {
1133
+ return candidateLocator.first();
1134
+ }
1135
+ }
1136
+ }
1137
+ catch {
1138
+ // Fall back to standard locator
1139
+ }
1140
+ }
327
1141
  return state.page.locator(action.selector).first();
1142
+ }
328
1143
  throw new Error(`${action.type} requires a current ref or selector`);
329
1144
  }
330
- async saveDownload(state, action) {
1145
+ async assertFillable(locator) {
1146
+ if (typeof locator.evaluate !== 'function')
1147
+ return;
1148
+ const check = await locator.evaluate((element) => {
1149
+ if (!element || !element.tagName)
1150
+ return { ok: true, reason: '' };
1151
+ const tag = String(element.tagName).toLowerCase();
1152
+ if (tag === 'textarea')
1153
+ return { ok: true, reason: '' };
1154
+ if (tag === 'input') {
1155
+ const inputType = String(element.getAttribute?.('type') || 'text').toLowerCase();
1156
+ const nonFillable = ['button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit'];
1157
+ if (nonFillable.includes(inputType)) {
1158
+ return { ok: false, reason: `Cannot type into <input type="${inputType}">. Use click or selectOption instead.` };
1159
+ }
1160
+ return { ok: true, reason: '' };
1161
+ }
1162
+ if (element.isContentEditable)
1163
+ return { ok: true, reason: '' };
1164
+ const role = String(element.getAttribute?.('role') || '').toLowerCase();
1165
+ if (role === 'textbox' || role === 'searchbox' || role === 'combobox')
1166
+ return { ok: true, reason: '' };
1167
+ return {
1168
+ ok: false,
1169
+ reason: `Target <${tag}> is not an editable input, textarea, or contenteditable element.`
1170
+ };
1171
+ }).catch(() => ({ ok: true, reason: '' }));
1172
+ if (!check.ok) {
1173
+ throw new Error(check.reason);
1174
+ }
1175
+ }
1176
+ async performClick(state, locator, doubleClick = false) {
1177
+ if (doubleClick && typeof locator.dblclick === 'function') {
1178
+ await locator.dblclick({ timeout: ACTION_TIMEOUT_MS });
1179
+ return;
1180
+ }
1181
+ try {
1182
+ await locator.click({ timeout: ACTION_TIMEOUT_MS });
1183
+ }
1184
+ catch (clickError) {
1185
+ const msg = errorMessage(clickError);
1186
+ if (msg.includes('intercepts pointer events') || msg.includes('Timeout')) {
1187
+ try {
1188
+ await locator.click({ timeout: 5_000, force: true });
1189
+ return;
1190
+ }
1191
+ catch {
1192
+ if (typeof locator.boundingBox === 'function' &&
1193
+ typeof state.page.mouse.move === 'function' &&
1194
+ typeof state.page.mouse.down === 'function' &&
1195
+ typeof state.page.mouse.up === 'function') {
1196
+ const box = await locator.boundingBox({ timeout: 2_000 }).catch(() => null);
1197
+ if (box && box.width > 0 && box.height > 0) {
1198
+ const cx = box.x + box.width / 2;
1199
+ const cy = box.y + box.height / 2;
1200
+ await state.page.mouse.move(cx, cy);
1201
+ await state.page.waitForTimeout(30);
1202
+ await state.page.mouse.down();
1203
+ await state.page.waitForTimeout(30);
1204
+ await state.page.mouse.up();
1205
+ return;
1206
+ }
1207
+ }
1208
+ }
1209
+ }
1210
+ throw clickError;
1211
+ }
1212
+ }
1213
+ async performType(state, locator, action) {
1214
+ if (action.text === undefined)
1215
+ throw new Error(`${action.type} requires text`);
1216
+ await this.assertFillable(locator);
1217
+ if (action.mode === 'keyboard' && typeof state.page.keyboard.type === 'function') {
1218
+ await this.performClick(state, locator, false);
1219
+ const delay = Math.max(0, Math.min(500, Number(action.delay ?? 20)));
1220
+ await state.page.keyboard.type(action.text, { delay });
1221
+ }
1222
+ else {
1223
+ await locator.fill(action.text, { timeout: ACTION_TIMEOUT_MS });
1224
+ }
1225
+ if (action.submit || action.pressEnter) {
1226
+ await state.page.keyboard.press('Enter');
1227
+ }
1228
+ }
1229
+ async performSelectOption(locator, value) {
1230
+ try {
1231
+ const selected = await locator.selectOption(value, { timeout: ACTION_TIMEOUT_MS });
1232
+ if (!Array.isArray(selected) || selected.length > 0)
1233
+ return;
1234
+ }
1235
+ catch {
1236
+ // Retry by label
1237
+ }
1238
+ await locator.selectOption({ label: value }, { timeout: ACTION_TIMEOUT_MS });
1239
+ }
1240
+ async performUpload(state, action, workspace) {
1241
+ const rawPaths = action.filePath ?? action.value;
1242
+ if (!rawPaths || (Array.isArray(rawPaths) && rawPaths.length === 0)) {
1243
+ throw new Error('upload requires filePath');
1244
+ }
1245
+ const list = Array.isArray(rawPaths) ? rawPaths : [rawPaths];
1246
+ const resolvedFiles = [];
1247
+ for (const item of list) {
1248
+ const resolved = path.resolve(workspace, String(item));
1249
+ if (!isWithin(workspace, resolved)) {
1250
+ throw new Error('Upload file must stay inside the selected workspace');
1251
+ }
1252
+ const stat = await fs.stat(resolved).catch(() => null);
1253
+ if (!stat || !stat.isFile()) {
1254
+ throw new Error(`Upload file does not exist or is not a regular file: ${resolved}`);
1255
+ }
1256
+ resolvedFiles.push(resolved);
1257
+ }
1258
+ const locator = await this.locatorFor(state, action);
1259
+ if (typeof locator.setInputFiles === 'function') {
1260
+ try {
1261
+ await locator.setInputFiles(resolvedFiles, { timeout: ACTION_TIMEOUT_MS });
1262
+ state.refs.clear();
1263
+ return {
1264
+ action: action.type,
1265
+ tabId: state.id,
1266
+ url: state.page.url(),
1267
+ output: `Uploaded ${resolvedFiles.length} file(s)`
1268
+ };
1269
+ }
1270
+ catch {
1271
+ // Fall through to filechooser event
1272
+ }
1273
+ }
1274
+ const [chooser] = await Promise.all([
1275
+ state.page.waitForEvent('filechooser', { timeout: ACTION_TIMEOUT_MS }),
1276
+ this.performClick(state, locator, false)
1277
+ ]);
1278
+ await chooser.setFiles(resolvedFiles);
1279
+ state.refs.clear();
1280
+ return {
1281
+ action: action.type,
1282
+ tabId: state.id,
1283
+ url: state.page.url(),
1284
+ output: `Uploaded ${resolvedFiles.length} file(s) via file chooser`
1285
+ };
1286
+ }
1287
+ async saveDownload(state, action, workspace) {
331
1288
  if (!action.outputFile)
332
1289
  throw new Error('download requires outputFile');
333
- const target = path.resolve(this.workspace, action.outputFile);
334
- if (!isWithin(this.workspace, target))
1290
+ const target = path.resolve(workspace, action.outputFile);
1291
+ if (!isWithin(workspace, target))
335
1292
  throw new Error('Download target must stay inside the selected workspace');
336
- const locator = this.locatorFor(state, action);
1293
+ const locator = await this.locatorFor(state, action);
337
1294
  const [download] = await Promise.all([
338
1295
  state.page.waitForEvent('download', { timeout: NAVIGATION_TIMEOUT_MS }),
339
- locator.click({ timeout: ACTION_TIMEOUT_MS })
1296
+ this.performClick(state, locator, false)
340
1297
  ]);
341
1298
  // outputFile is an explicit file destination. Never let a server-selected
342
1299
  // filename alter the caller's workspace-scoped target.
@@ -358,11 +1315,11 @@ export class CausyneBrowser {
358
1315
  await fs.unlink(temporary).catch(() => { });
359
1316
  }
360
1317
  }
361
- async saveScreenshot(state, action) {
1318
+ async saveScreenshot(state, action, workspace) {
362
1319
  if (!action.outputFile)
363
1320
  throw new Error('screenshot requires outputFile');
364
- const target = path.resolve(this.workspace, action.outputFile);
365
- if (!isWithin(this.workspace, target))
1321
+ const target = path.resolve(workspace, action.outputFile);
1322
+ if (!isWithin(workspace, target))
366
1323
  throw new Error('Screenshot target must stay inside the selected workspace');
367
1324
  const extension = path.extname(target).toLowerCase();
368
1325
  if (!['.png', '.jpg', '.jpeg'].includes(extension))
@@ -384,24 +1341,28 @@ export class CausyneBrowser {
384
1341
  await fs.unlink(temporary).catch(() => { });
385
1342
  }
386
1343
  }
387
- async runAction(action) {
1344
+ async runAction(action, workspace = this.workspace) {
388
1345
  if (!action || typeof action.type !== 'string')
389
1346
  throw new Error('Every browser action needs a type');
390
- if (action.type === 'newTab') {
391
- const state = await this.createTab(action.url);
1347
+ if (action.type === 'newTab' || action.type === 'new_tab') {
1348
+ const initialUrl = action.macro
1349
+ ? (expandSearchMacro(action.macro, action.query ?? action.text ?? '') ?? undefined)
1350
+ : action.url;
1351
+ const state = await this.createTab(initialUrl);
392
1352
  return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
393
1353
  }
394
- if (action.type === 'listTabs') {
395
- const data = await Promise.all([...this.tabs.values()].filter(tab => !tab.page.isClosed()).map(async (tab) => ({
1354
+ if (action.type === 'listTabs' || action.type === 'list_tabs') {
1355
+ const data = await Promise.all([...this.tabs.values()].filter(tab => !tab.page.isClosed() && !tab.crashed).map(async (tab) => ({
396
1356
  tabId: tab.id, active: tab.id === this.activeTabId, url: tab.page.url(), title: await tab.page.title()
397
1357
  })));
398
1358
  return { action: action.type, data };
399
1359
  }
400
1360
  const requested = this.requestedTab(action);
401
1361
  const state = requested ?? await this.activeTab();
402
- if (action.type === 'switchTab')
1362
+ if (action.type === 'switchTab' || action.type === 'switch_tab') {
403
1363
  return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
404
- if (action.type === 'closeTab') {
1364
+ }
1365
+ if (action.type === 'closeTab' || action.type === 'close_tab') {
405
1366
  await state.page.close();
406
1367
  this.tabs.delete(state.id);
407
1368
  if (this.activeTabId === state.id)
@@ -413,39 +1374,61 @@ export class CausyneBrowser {
413
1374
  const active = await this.activeTab();
414
1375
  return { action: action.type, tabId: active.id, url: active.page.url(), data: results };
415
1376
  }
416
- if (action.type === 'goto') {
417
- if (!action.url)
418
- throw new Error('goto requires url');
419
- await this.navigate(state, action.url);
1377
+ if (action.type === 'goto' || action.type === 'open' || action.type === 'navigate') {
1378
+ await this.navigateWithMacroFallback(state, action);
420
1379
  return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
421
1380
  }
422
1381
  if (action.type === 'snapshot' || action.type === 'scrape') {
423
1382
  const snapshot = await this.snapshot(action.offset ?? 0);
424
- return { action: action.type, tabId: snapshot.tabId, url: snapshot.url, title: snapshot.title, output: snapshot.text, data: {
425
- refsCount: snapshot.refsCount, truncated: snapshot.truncated, totalChars: snapshot.totalChars, nextOffset: snapshot.nextOffset
426
- } };
1383
+ return {
1384
+ action: action.type,
1385
+ tabId: snapshot.tabId,
1386
+ url: snapshot.url,
1387
+ title: snapshot.title,
1388
+ output: snapshot.text,
1389
+ ...(snapshot.structure ? { structure: snapshot.structure } : {}),
1390
+ data: {
1391
+ refsCount: snapshot.refsCount,
1392
+ truncated: snapshot.truncated,
1393
+ totalChars: snapshot.totalChars,
1394
+ nextOffset: snapshot.nextOffset,
1395
+ ...(snapshot.structure ? { structure: snapshot.structure } : {})
1396
+ }
1397
+ };
427
1398
  }
428
1399
  if (action.type === 'click' || action.type === 'clickIndex') {
429
- await this.locatorFor(state, action).click({ timeout: ACTION_TIMEOUT_MS });
1400
+ const locator = await this.locatorFor(state, action);
1401
+ await this.performClick(state, locator, Boolean(action.doubleClick));
430
1402
  state.refs.clear();
431
1403
  return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Element clicked' };
432
1404
  }
433
- if (action.type === 'type' || action.type === 'typeIndex') {
434
- if (action.text === undefined)
435
- throw new Error(`${action.type} requires text`);
436
- await this.locatorFor(state, action).fill(action.text, { timeout: ACTION_TIMEOUT_MS });
1405
+ if (action.type === 'hover') {
1406
+ const locator = await this.locatorFor(state, action);
1407
+ if (typeof locator.hover === 'function') {
1408
+ await locator.hover({ timeout: ACTION_TIMEOUT_MS });
1409
+ }
1410
+ else {
1411
+ await this.performClick(state, locator, false);
1412
+ }
1413
+ return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Element hovered' };
1414
+ }
1415
+ if (action.type === 'type' || action.type === 'typeIndex' || action.type === 'fill') {
1416
+ const locator = await this.locatorFor(state, action);
1417
+ await this.performType(state, locator, action);
437
1418
  return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Text entered' };
438
1419
  }
439
- if (action.type === 'selectOption') {
440
- const value = action.value ?? action.text;
1420
+ if (action.type === 'selectOption' || action.type === 'select') {
1421
+ const value = action.value ?? action.option ?? action.text;
441
1422
  if (value === undefined)
442
- throw new Error('selectOption requires value');
443
- await this.locatorFor(state, action).selectOption(value, { timeout: ACTION_TIMEOUT_MS });
1423
+ throw new Error(`${action.type} requires value`);
1424
+ const locator = await this.locatorFor(state, action);
1425
+ await this.performSelectOption(locator, value);
444
1426
  return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Option selected' };
445
1427
  }
446
- if (action.type === 'keyPress') {
447
- await state.page.keyboard.press(action.key ?? 'Enter');
448
- return { action: action.type, tabId: state.id, url: state.page.url(), output: `Pressed ${action.key ?? 'Enter'}` };
1428
+ if (action.type === 'keyPress' || action.type === 'press') {
1429
+ const normalizedKey = normalizeBrowserKey(action.key ?? 'Enter');
1430
+ await state.page.keyboard.press(normalizedKey);
1431
+ return { action: action.type, tabId: state.id, url: state.page.url(), output: `Pressed ${normalizedKey}` };
449
1432
  }
450
1433
  if (action.type === 'scroll') {
451
1434
  const amount = Math.max(1, Math.min(10_000, Math.floor(action.amount ?? 700)));
@@ -455,23 +1438,118 @@ export class CausyneBrowser {
455
1438
  await state.page.mouse.wheel(x, y);
456
1439
  return { action: action.type, tabId: state.id, url: state.page.url(), output: `Scrolled ${direction} ${amount}px` };
457
1440
  }
458
- if (action.type === 'back')
459
- await state.page.goBack({ waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
460
- else if (action.type === 'forward')
461
- await state.page.goForward({ waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
462
- else if (action.type === 'reload')
1441
+ if (action.type === 'wait') {
1442
+ const waitTimeout = Math.max(50, Math.min(30_000, Number(action.timeout ?? action.amount ?? 1_000)));
1443
+ if (action.selector) {
1444
+ const validationErr = selectorValidationError(action.selector);
1445
+ if (validationErr)
1446
+ throw new Error(validationErr);
1447
+ if (typeof state.page.waitForSelector === 'function') {
1448
+ await state.page.waitForSelector(action.selector, { timeout: waitTimeout });
1449
+ }
1450
+ else {
1451
+ const loc = state.page.locator(action.selector).first();
1452
+ if (typeof loc.waitFor === 'function') {
1453
+ await loc.waitFor({ timeout: waitTimeout });
1454
+ }
1455
+ else {
1456
+ await state.page.waitForTimeout(waitTimeout);
1457
+ }
1458
+ }
1459
+ }
1460
+ else {
1461
+ if (action.waitForNetwork) {
1462
+ await state.page.waitForLoadState('networkidle', { timeout: waitTimeout }).catch(() => { });
1463
+ }
1464
+ await state.page.evaluate(WAIT_FOR_PAGE_READY_SCRIPT).catch(() => { });
1465
+ await state.page.waitForTimeout(Math.min(waitTimeout, 2_000));
1466
+ }
1467
+ if (action.dismissConsent) {
1468
+ await state.page.evaluate(DISMISS_CONSENT_SCRIPT).catch(() => false);
1469
+ }
1470
+ return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Wait completed' };
1471
+ }
1472
+ if (action.type === 'viewport') {
1473
+ const width = Math.floor(Number(action.width ?? 1280));
1474
+ const height = Math.floor(Number(action.height ?? 800));
1475
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width < 100 || width > 4000 || height < 100 || height > 4000) {
1476
+ throw new Error('viewport width and height must be between 100 and 4000 pixels');
1477
+ }
1478
+ if (typeof state.page.setViewportSize === 'function') {
1479
+ await state.page.setViewportSize({ width, height });
1480
+ }
1481
+ return { action: action.type, tabId: state.id, url: state.page.url(), output: `Viewport set to ${width}x${height}` };
1482
+ }
1483
+ if (action.type === 'back') {
1484
+ try {
1485
+ await state.page.goBack({ waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
1486
+ }
1487
+ catch (error) {
1488
+ if (!errorMessage(error).includes('NS_BINDING_CANCELLED'))
1489
+ throw error;
1490
+ }
1491
+ }
1492
+ else if (action.type === 'forward') {
1493
+ try {
1494
+ await state.page.goForward({ waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
1495
+ }
1496
+ catch (error) {
1497
+ if (!errorMessage(error).includes('NS_BINDING_CANCELLED'))
1498
+ throw error;
1499
+ }
1500
+ }
1501
+ else if (action.type === 'reload' || action.type === 'refresh') {
463
1502
  await state.page.reload({ waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
1503
+ }
464
1504
  else if (action.type === 'extract') {
1505
+ if (action.schema) {
1506
+ const check = validateExtractSchema(action.schema);
1507
+ if (!check.ok)
1508
+ throw new Error(`Invalid extract schema: ${check.error}`);
1509
+ if (state.refs.size === 0) {
1510
+ await this.captureSnapshotState(state);
1511
+ }
1512
+ const extracted = extractDeterministic({ schema: action.schema, refs: state.refs });
1513
+ return {
1514
+ action: action.type,
1515
+ tabId: state.id,
1516
+ url: state.page.url(),
1517
+ output: JSON.stringify(extracted),
1518
+ data: extracted
1519
+ };
1520
+ }
465
1521
  const selector = action.selector ?? 'body';
1522
+ const validationErr = selectorValidationError(selector);
1523
+ if (validationErr)
1524
+ throw new Error(validationErr);
466
1525
  const output = boundedText(await state.page.locator(selector).first().innerText({ timeout: ACTION_TIMEOUT_MS }));
467
1526
  return { action: action.type, tabId: state.id, url: state.page.url(), output };
468
1527
  }
469
- else if (action.type === 'download')
470
- return this.saveDownload(state, action);
471
- else if (action.type === 'screenshot')
472
- return this.saveScreenshot(state, action);
473
- else
1528
+ else if (action.type === 'links') {
1529
+ if (action.selector) {
1530
+ const validationErr = selectorValidationError(action.selector);
1531
+ if (validationErr)
1532
+ throw new Error(validationErr);
1533
+ }
1534
+ const data = await state.page.evaluate(LINKS_EXTRACT_SCRIPT, { selector: action.selector, offset: action.offset ?? 0, limit: action.limit ?? 50 });
1535
+ return { action: action.type, tabId: state.id, url: state.page.url(), data };
1536
+ }
1537
+ else if (action.type === 'images') {
1538
+ const data = await state.page.evaluate(IMAGES_EXTRACT_SCRIPT, { limit: action.limit ?? 100 });
1539
+ return { action: action.type, tabId: state.id, url: state.page.url(), data };
1540
+ }
1541
+ else if (action.type === 'upload') {
1542
+ return this.performUpload(state, action, workspace);
1543
+ }
1544
+ else if (action.type === 'download') {
1545
+ return this.saveDownload(state, action, workspace);
1546
+ }
1547
+ else if (action.type === 'screenshot') {
1548
+ return this.saveScreenshot(state, action, workspace);
1549
+ }
1550
+ else {
474
1551
  throw new Error(`Unsupported browser action: ${action.type}`);
1552
+ }
475
1553
  state.refs.clear();
476
1554
  return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
477
1555
  }
@@ -483,8 +1561,11 @@ export class CausyneBrowser {
483
1561
  }
484
1562
  }
485
1563
  let sharedBrowser = null;
486
- export function causyneBrowser() {
487
- sharedBrowser ??= new CausyneBrowser();
1564
+ export function causyneBrowser(options) {
1565
+ sharedBrowser ??= new CausyneBrowser(options);
1566
+ if (options?.workspace) {
1567
+ sharedBrowser.setWorkspace(options.workspace);
1568
+ }
488
1569
  return sharedBrowser;
489
1570
  }
490
1571
  export async function closeCausyneBrowser() {
@@ -493,3 +1574,69 @@ export async function closeCausyneBrowser() {
493
1574
  if (browser)
494
1575
  await browser.close();
495
1576
  }
1577
+ const INTERACTIVE_BROWSER_ACTIONS = new Set([
1578
+ 'click', 'clickIndex',
1579
+ 'type', 'typeIndex', 'fill',
1580
+ 'selectOption', 'select',
1581
+ 'keyPress', 'press',
1582
+ 'hover',
1583
+ 'upload'
1584
+ ]);
1585
+ export function validateBrowserActSandbox(args, workspaceRoot, isInternalUrl, isPathAllowed) {
1586
+ const actions = Array.isArray(args?.actions) ? args.actions : [];
1587
+ let hasDownload = false;
1588
+ for (const action of actions) {
1589
+ if (!action || typeof action !== 'object')
1590
+ continue;
1591
+ const rawUrl = typeof action.url === 'string' ? action.url.trim() : '';
1592
+ const rawMacro = typeof action.macro === 'string' ? action.macro.trim() : '';
1593
+ if (rawMacro) {
1594
+ const expanded = expandSearchMacro(rawMacro, typeof action.query === 'string' ? action.query : '');
1595
+ if (!expanded || isInternalUrl(expanded)) {
1596
+ return { allowed: false, reason: 'Cannot navigate the agent browser to an internal or invalid URL', risk: 'forbidden' };
1597
+ }
1598
+ }
1599
+ if (rawUrl) {
1600
+ let urlToCheck = rawUrl;
1601
+ if (rawUrl.startsWith('@')) {
1602
+ const spaceIdx = rawUrl.indexOf(' ');
1603
+ const macroName = spaceIdx === -1 ? rawUrl : rawUrl.slice(0, spaceIdx);
1604
+ const query = spaceIdx === -1 ? (typeof action.query === 'string' ? action.query : '') : rawUrl.slice(spaceIdx + 1).trim();
1605
+ const expanded = expandSearchMacro(macroName, query);
1606
+ if (!expanded) {
1607
+ return { allowed: false, reason: 'Cannot navigate the agent browser to an internal or invalid URL', risk: 'forbidden' };
1608
+ }
1609
+ urlToCheck = expanded;
1610
+ }
1611
+ if (isInternalUrl(urlToCheck)) {
1612
+ return { allowed: false, reason: 'Cannot navigate the agent browser to an internal or invalid URL', risk: 'forbidden' };
1613
+ }
1614
+ }
1615
+ if (action.type === 'download' || action.type === 'screenshot') {
1616
+ const out = typeof action.outputFile === 'string' ? action.outputFile : '';
1617
+ if (!out || !isPathAllowed(path.resolve(workspaceRoot, out))) {
1618
+ return { allowed: false, reason: 'Browser downloads must stay inside the selected workspace', risk: 'forbidden' };
1619
+ }
1620
+ hasDownload = true;
1621
+ }
1622
+ if (action.type === 'upload') {
1623
+ const rawPaths = action.filePath ?? action.value;
1624
+ const list = Array.isArray(rawPaths) ? rawPaths : rawPaths ? [rawPaths] : [];
1625
+ if (list.length === 0) {
1626
+ return { allowed: false, reason: 'Browser uploads must specify a file inside the selected workspace', risk: 'forbidden' };
1627
+ }
1628
+ for (const item of list) {
1629
+ if (typeof item !== 'string' || !item || !isPathAllowed(path.resolve(workspaceRoot, item))) {
1630
+ return { allowed: false, reason: 'Browser uploads must stay inside the selected workspace', risk: 'forbidden' };
1631
+ }
1632
+ }
1633
+ }
1634
+ }
1635
+ if (hasDownload) {
1636
+ return { allowed: true, risk: 'extreme', reason: 'Writes browser content to the selected workspace' };
1637
+ }
1638
+ if (actions.some(action => typeof action?.type === 'string' && INTERACTIVE_BROWSER_ACTIONS.has(action.type))) {
1639
+ return { allowed: true, risk: 'dangerous', reason: 'Interacts with a website through the dedicated agent browser' };
1640
+ }
1641
+ return { allowed: true, risk: 'safe' };
1642
+ }