@causyne/agent 1.19.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.
- package/README.md +0 -18
- package/package.json +1 -1
- package/src/acp/client.js +2 -1
- package/src/acp/client.ts +2 -1
- package/src/acp/server.js +5 -6
- package/src/acp/server.ts +4 -6
- package/src/agentLoop.d.ts +1 -0
- package/src/agentLoop.js +505 -241
- package/src/agentLoop.ts +527 -258
- package/src/agentPolicy.js +9 -0
- package/src/agentPolicy.ts +9 -0
- package/src/approvalPolicy.js +55 -0
- package/src/approvalPolicy.ts +66 -0
- package/src/browser/browserRuntime.js +217 -14
- package/src/browser/browserRuntime.ts +255 -14
- package/src/browser/causyneBrowser.js +1215 -68
- package/src/browser/causyneBrowser.ts +1340 -72
- package/src/cliMode.js +66 -37
- package/src/commands.js +343 -72
- package/src/config.js +22 -12
- package/src/continuum/ingest.js +1 -1
- package/src/continuum/ingest.ts +1 -1
- package/src/continuum/ui/continuumPicker.js +18 -1
- package/src/continuum/ui/continuumPicker.ts +19 -1
- package/src/dynamicCatalogue.js +87 -20
- package/src/dynamicCatalogue.ts +85 -15
- package/src/launchIntent.js +40 -0
- package/src/launchIntent.ts +49 -0
- package/src/memoryManager.js +36 -8
- package/src/modelCatalogue.js +2 -0
- package/src/planCache.js +320 -11
- package/src/planCache.ts +402 -13
- package/src/providers/acp.js +67 -1
- package/src/providers/acp.ts +65 -2
- package/src/providers/antigravity.d.ts +5 -1
- package/src/providers/antigravity.js +643 -32
- package/src/providers/antigravity.ts +671 -33
- package/src/providers/base.d.ts +9 -0
- package/src/providers/factory.js +2 -0
- package/src/providers/pi.js +157 -0
- package/src/providers/pi.ts +144 -0
- package/src/provisioning/capabilityProvisioner.js +17 -0
- package/src/provisioning/capabilityTools.js +1 -1
- package/src/sandbox.js +30 -39
- package/src/sessionJournal.js +66 -10
- package/src/sessionJournal.ts +84 -10
- package/src/taskShape.js +9 -9
- package/src/taskShape.ts +9 -9
- package/src/timeMachine.js +124 -0
- package/src/timeMachine.ts +141 -0
- package/src/toolPacks.js +4 -10
- package/src/tools/archive.js +196 -59
- package/src/tools/archive.ts +220 -0
- package/src/tools/browserAutomator.js +78 -9
- package/src/tools/browserAutomator.ts +90 -9
- package/src/tools/desktopOpen.js +114 -31
- package/src/tools/desktopOpen.ts +144 -0
- package/src/tools/gitExec.js +5 -3
- package/src/tools/nativeEngine.js +4 -3
- package/src/tools/nativeEngine.ts +5 -3
- package/src/tools/openSourceToolProvisioner.js +5 -4
- package/src/tools/openSourceToolProvisioner.ts +5 -4
- package/src/tools/registry.js +3 -0
- package/src/tools/screenshot.js +55 -71
- package/src/tools/screenshot.ts +70 -0
- package/src/tools/sysRun.js +284 -117
- package/src/tools/sysRun.ts +347 -0
- package/src/tools/toolSelfRepair.js +109 -2
- package/src/tools/toolSelfRepair.ts +100 -2
- package/src/tools/updatePlan.js +49 -1
- package/src/tools/updatePlan.ts +43 -1
- package/src/tools/viewImage.js +93 -78
- package/src/tools/viewImage.ts +116 -0
- package/src/tools/webFetch.js +20 -6
- package/src/tools/webFetch.ts +26 -6
- package/src/tui/block.d.ts +1 -0
- package/src/tui/chatRenderer.d.ts +21 -0
- package/src/tui/chatRenderer.js +118 -45
- package/src/tui/clipboardSync.js +28 -1
- package/src/tui/clipboardSync.ts +26 -1
- package/src/tui/codeProgress.js +299 -0
- package/src/tui/codeProgress.ts +304 -0
- package/src/tui/codeStreamRenderer.js +116 -0
- package/src/tui/codeStreamRenderer.ts +124 -0
- package/src/tui/commandPresentation.js +11 -0
- package/src/tui/commandPresentation.ts +18 -0
- package/src/tui/completion.js +45 -13
- package/src/tui/composerControls.js +66 -0
- package/src/tui/composerControls.ts +78 -0
- package/src/tui/diff.d.ts +2 -0
- package/src/tui/home.js +4 -2
- package/src/tui/homeTransition.js +21 -0
- package/src/tui/homeTransition.ts +27 -0
- package/src/tui/homeView.js +62 -0
- package/src/tui/homeView.ts +91 -0
- package/src/tui/layout.js +46 -0
- package/src/tui/layout.ts +52 -0
- package/src/tui/messageActionPlacement.js +16 -0
- package/src/tui/messageActionPlacement.ts +25 -0
- package/src/tui/messageInteraction.js +221 -0
- package/src/tui/messageInteraction.ts +275 -0
- package/src/tui/modelPicker.js +13 -0
- package/src/tui/modelPicker.ts +12 -0
- package/src/tui/mouseHover.js +6 -0
- package/src/tui/mouseHover.ts +5 -0
- package/src/tui/prompt.js +199 -52
- package/src/tui/resizeRecovery.js +15 -0
- package/src/tui/resizeRecovery.ts +27 -0
- package/src/tui/scrollInteraction.js +97 -0
- package/src/tui/scrollInteraction.ts +189 -0
- package/src/tui/sessionLayout.js +12 -0
- package/src/tui/sessionLayout.ts +12 -0
- package/src/tui/sessionPicker.js +280 -0
- package/src/tui/sessionPicker.ts +364 -0
- package/src/tui/sessionSidebar.js +78 -0
- package/src/tui/sessionSidebar.ts +95 -0
- package/src/tui/setup.js +1 -1
- package/src/tui/setup.ts +1 -1
- package/src/tui/stageSurface.js +128 -57
- package/src/tui/statusLine.js +5 -5
- package/src/tui/text.d.ts +5 -0
- package/src/tui/textLayout.js +23 -0
- package/src/tui/textLayout.ts +28 -0
- package/src/tui/viewport.js +204 -279
- package/src/tui/viewport.ts +326 -0
- package/src/types/contracts.ts +54 -0
- package/src/utils/paths.js +5 -4
- package/src/utils/paths.ts +5 -5
|
@@ -13,25 +13,315 @@ import { windowSnapshot, type SnapshotWindow } from './snapshotWindow.js';
|
|
|
13
13
|
|
|
14
14
|
const NAVIGATION_TIMEOUT_MS = 30_000;
|
|
15
15
|
const ACTION_TIMEOUT_MS = 12_000;
|
|
16
|
+
const IFRAME_SNAPSHOT_TIMEOUT_MS = 3_000;
|
|
16
17
|
const IDLE_CLOSE_MS = 10 * 60_000;
|
|
17
18
|
const MAX_SEARCH_RESULTS = 10;
|
|
18
19
|
const MAX_EXTRACT_CHARS = 80_000;
|
|
19
20
|
const MAX_DOWNLOAD_BYTES = 250 * 1024 * 1024;
|
|
20
21
|
const MAX_SCREENSHOT_BYTES = 25 * 1024 * 1024;
|
|
22
|
+
const MAX_SNAPSHOT_NODES = 500;
|
|
23
|
+
const MAX_IFRAMES_TO_PROCESS = 8;
|
|
24
|
+
|
|
21
25
|
const INTERACTIVE_ROLES = new Set([
|
|
22
|
-
'button', 'checkbox', 'combobox', 'link', 'menuitem', 'option', 'radio',
|
|
26
|
+
'button', 'checkbox', 'combobox', 'link', 'listitem', 'menuitem', 'option', 'radio',
|
|
23
27
|
'searchbox', 'slider', 'spinbutton', 'switch', 'tab', 'textbox', 'treeitem'
|
|
24
28
|
]);
|
|
25
29
|
|
|
30
|
+
const SKIP_PATTERNS = [
|
|
31
|
+
/datepicker/i, /date.?picker/i, /calendar/i, /^date$/i
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
const IFRAME_SKIP_PATTERNS = [
|
|
35
|
+
/web-pixel/i, /analytics/i, /tracking/i, /gtm/i, /facebook/i,
|
|
36
|
+
/doubleclick/i, /google.*tag/i, /hotjar/i, /segment/i, /sentry/i,
|
|
37
|
+
/recaptcha/i, /gstatic/i, /app-bridge/i, /extensions\.shopifycdn/i,
|
|
38
|
+
/px-iframe/i, /px-captcha/i, /perimeterx/i, /\bcaptcha\b/i, /hcaptcha/i,
|
|
39
|
+
/arkose/i, /funcaptcha/i, /datadome/i
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
const NON_FILLABLE_INPUT_TYPES = new Set([
|
|
43
|
+
'button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit'
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
const KEY_MODIFIER_ALIASES = new Map<string, string>([
|
|
47
|
+
['ctrl', 'Control'],
|
|
48
|
+
['control', 'Control'],
|
|
49
|
+
['cmd', 'Meta'],
|
|
50
|
+
['command', 'Meta'],
|
|
51
|
+
['meta', 'Meta'],
|
|
52
|
+
['option', 'Alt'],
|
|
53
|
+
['esc', 'Escape'],
|
|
54
|
+
['return', 'Enter'],
|
|
55
|
+
['enter', 'Enter'],
|
|
56
|
+
['del', 'Delete']
|
|
57
|
+
]);
|
|
58
|
+
|
|
59
|
+
const SEARCH_MACROS: Record<string, (query: string) => string> = {
|
|
60
|
+
'@google_search': query => `https://www.google.com/search?q=${encodeURIComponent(query || '')}`,
|
|
61
|
+
'@duckduckgo_search': query => `https://duckduckgo.com/?q=${encodeURIComponent(query || '')}`,
|
|
62
|
+
'@bing_search': query => `https://www.bing.com/search?q=${encodeURIComponent(query || '')}`,
|
|
63
|
+
'@github_search': query => `https://github.com/search?q=${encodeURIComponent(query || '')}`,
|
|
64
|
+
'@youtube_search': query => `https://www.youtube.com/results?search_query=${encodeURIComponent(query || '')}`,
|
|
65
|
+
'@amazon_search': query => `https://www.amazon.com/s?k=${encodeURIComponent(query || '')}`,
|
|
66
|
+
'@reddit_search': query => `https://www.reddit.com/search.json?q=${encodeURIComponent(query || '')}&limit=25`,
|
|
67
|
+
'@reddit_subreddit': query => `https://www.reddit.com/r/${encodeURIComponent(query || 'all')}.json?limit=25`,
|
|
68
|
+
'@wikipedia_search': query => `https://en.wikipedia.org/wiki/Special:Search?search=${encodeURIComponent(query || '')}`,
|
|
69
|
+
'@twitter_search': query => `https://twitter.com/search?q=${encodeURIComponent(query || '')}`,
|
|
70
|
+
'@yelp_search': query => `https://www.yelp.com/search?find_desc=${encodeURIComponent(query || '')}`,
|
|
71
|
+
'@spotify_search': query => `https://open.spotify.com/search/${encodeURIComponent(query || '')}`,
|
|
72
|
+
'@netflix_search': query => `https://www.netflix.com/search?q=${encodeURIComponent(query || '')}`,
|
|
73
|
+
'@linkedin_search': query => `https://www.linkedin.com/search/results/all/?keywords=${encodeURIComponent(query || '')}`,
|
|
74
|
+
'@instagram_search': query => `https://www.instagram.com/explore/tags/${encodeURIComponent(query || '')}`,
|
|
75
|
+
'@tiktok_search': query => `https://www.tiktok.com/search?q=${encodeURIComponent(query || '')}`,
|
|
76
|
+
'@twitch_search': query => `https://www.twitch.tv/search?term=${encodeURIComponent(query || '')}`
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export function expandSearchMacro(macro: string, query = ''): string | null {
|
|
80
|
+
const fn = SEARCH_MACROS[String(macro || '').trim()];
|
|
81
|
+
return fn ? fn(String(query ?? '')) : null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function getSupportedSearchMacros(): string[] {
|
|
85
|
+
return Object.keys(SEARCH_MACROS);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function normalizeBrowserKey(key: string): string {
|
|
89
|
+
if (typeof key !== 'string' || !key.trim()) return 'Enter';
|
|
90
|
+
return key
|
|
91
|
+
.split('+')
|
|
92
|
+
.map(part => {
|
|
93
|
+
const trimmed = part.trim();
|
|
94
|
+
return KEY_MODIFIER_ALIASES.get(trimmed.toLowerCase()) ?? trimmed;
|
|
95
|
+
})
|
|
96
|
+
.join('+');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function visibleSelectorCandidate(selector: string): string | null {
|
|
100
|
+
if (typeof selector !== 'string') return null;
|
|
101
|
+
const trimmed = selector.trim();
|
|
102
|
+
if (!trimmed || trimmed.includes(',') || trimmed.includes(':visible')) return null;
|
|
103
|
+
return `${trimmed}:visible`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function selectorValidationError(selector?: string): string | null {
|
|
107
|
+
if (selector === undefined || selector === null) return null;
|
|
108
|
+
if (typeof selector !== 'string' || selector.trim() === '') return 'selector must be a non-empty string';
|
|
109
|
+
if (/^text\s*\(/i.test(selector)) return 'Invalid text selector syntax. Use text=... or a valid CSS selector.';
|
|
110
|
+
const stack: string[] = [];
|
|
111
|
+
let quote: string | null = null;
|
|
112
|
+
let escaped = false;
|
|
113
|
+
const pairs: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
|
|
114
|
+
for (const ch of selector) {
|
|
115
|
+
if (escaped) {
|
|
116
|
+
escaped = false;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (ch === '\\') {
|
|
120
|
+
escaped = true;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (quote) {
|
|
124
|
+
if (ch === quote) quote = null;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (ch === '"' || ch === "'") {
|
|
128
|
+
quote = ch;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (ch === '(' || ch === '[' || ch === '{') stack.push(ch);
|
|
132
|
+
if (ch === ')' || ch === ']' || ch === '}') {
|
|
133
|
+
if (stack.pop() !== pairs[ch]) return `Invalid selector syntax: ${selector}`;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (quote || stack.length > 0) return `Invalid selector syntax: ${selector}`;
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const SUPPORTED_SCHEMA_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'object', 'null']);
|
|
141
|
+
|
|
142
|
+
export interface ExtractPropertySchema {
|
|
143
|
+
type?: string;
|
|
144
|
+
'x-ref'?: string;
|
|
145
|
+
description?: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface ExtractSchema {
|
|
149
|
+
type: string;
|
|
150
|
+
properties: Record<string, ExtractPropertySchema>;
|
|
151
|
+
required?: string[];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function validateExtractSchema(schema: unknown): { ok: boolean; error?: string } {
|
|
155
|
+
if (!schema || typeof schema !== 'object') {
|
|
156
|
+
return { ok: false, error: 'schema must be an object' };
|
|
157
|
+
}
|
|
158
|
+
const candidate = schema as Record<string, unknown>;
|
|
159
|
+
if (candidate.type !== 'object') {
|
|
160
|
+
return { ok: false, error: 'top-level schema must have type: object' };
|
|
161
|
+
}
|
|
162
|
+
if (!candidate.properties || typeof candidate.properties !== 'object' || Array.isArray(candidate.properties)) {
|
|
163
|
+
return { ok: false, error: 'schema must have a properties object' };
|
|
164
|
+
}
|
|
165
|
+
for (const [prop, def] of Object.entries(candidate.properties as Record<string, unknown>)) {
|
|
166
|
+
if (!def || typeof def !== 'object') {
|
|
167
|
+
return { ok: false, error: `property "${prop}" must be an object` };
|
|
168
|
+
}
|
|
169
|
+
const propDef = def as ExtractPropertySchema;
|
|
170
|
+
if (propDef.type && !SUPPORTED_SCHEMA_TYPES.has(propDef.type)) {
|
|
171
|
+
return { ok: false, error: `property "${prop}" has unsupported type "${propDef.type}"` };
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return { ok: true };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function coerceSchemaValue(raw: string | null, type?: string): unknown {
|
|
178
|
+
if (raw == null) return null;
|
|
179
|
+
if (type === 'string' || !type) return String(raw).trim();
|
|
180
|
+
if (type === 'number') {
|
|
181
|
+
const n = parseFloat(String(raw).replace(/[^0-9.eE+-]/g, ''));
|
|
182
|
+
return Number.isFinite(n) ? n : null;
|
|
183
|
+
}
|
|
184
|
+
if (type === 'integer') {
|
|
185
|
+
const n = parseInt(String(raw).replace(/[^0-9-]/g, ''), 10);
|
|
186
|
+
return Number.isFinite(n) ? n : null;
|
|
187
|
+
}
|
|
188
|
+
if (type === 'boolean') {
|
|
189
|
+
const s = String(raw).toLowerCase().trim();
|
|
190
|
+
if (s === 'true' || s === 'yes' || s === '1') return true;
|
|
191
|
+
if (s === 'false' || s === 'no' || s === '0') return false;
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
return raw;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function extractDeterministic(options: {
|
|
198
|
+
schema: ExtractSchema;
|
|
199
|
+
refs: Map<string, BrowserRef>;
|
|
200
|
+
}): Record<string, unknown> {
|
|
201
|
+
const check = validateExtractSchema(options.schema);
|
|
202
|
+
if (!check.ok) throw new Error(check.error ?? 'Invalid extraction schema');
|
|
203
|
+
|
|
204
|
+
const result: Record<string, unknown> = {};
|
|
205
|
+
for (const [prop, def] of Object.entries(options.schema.properties)) {
|
|
206
|
+
const refId = def['x-ref'];
|
|
207
|
+
let value: unknown = null;
|
|
208
|
+
if (refId) {
|
|
209
|
+
const info = options.refs.get(refId);
|
|
210
|
+
const raw = info?.name ? info.name : null;
|
|
211
|
+
if (raw != null) {
|
|
212
|
+
value = def.type && def.type !== 'object' ? coerceSchemaValue(raw, def.type) : raw;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (value == null && Array.isArray(options.schema.required) && options.schema.required.includes(prop)) {
|
|
216
|
+
throw new Error(`required property "${prop}" could not be extracted (x-ref=${refId || 'n/a'})`);
|
|
217
|
+
}
|
|
218
|
+
result[prop] = value;
|
|
219
|
+
}
|
|
220
|
+
return result;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export interface PageStructureField {
|
|
224
|
+
label: string;
|
|
225
|
+
role: string;
|
|
226
|
+
tag: string;
|
|
227
|
+
type: string;
|
|
228
|
+
id?: string;
|
|
229
|
+
name?: string;
|
|
230
|
+
disabled: boolean;
|
|
231
|
+
value?: string;
|
|
232
|
+
options?: Array<{ label: string; value: string; selected: boolean }>;
|
|
233
|
+
optionsTruncated?: boolean;
|
|
234
|
+
ref?: string;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export interface PageStructureForm {
|
|
238
|
+
label?: string;
|
|
239
|
+
id?: string;
|
|
240
|
+
name?: string;
|
|
241
|
+
method: string;
|
|
242
|
+
fields: PageStructureField[];
|
|
243
|
+
fieldsTruncated: boolean;
|
|
244
|
+
submitControls: Array<{ label: string; id?: string; name?: string; disabled: boolean; ref?: string }>;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export interface PageStructureTable {
|
|
248
|
+
label?: string;
|
|
249
|
+
id?: string;
|
|
250
|
+
headers: string[];
|
|
251
|
+
columns: string[];
|
|
252
|
+
rowCount: number;
|
|
253
|
+
rows: string[][];
|
|
254
|
+
rowsTruncated: boolean;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export interface PageStructure {
|
|
258
|
+
forms: PageStructureForm[];
|
|
259
|
+
formsTruncated: boolean;
|
|
260
|
+
tables: PageStructureTable[];
|
|
261
|
+
tablesTruncated: boolean;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export function attachStructureRefs(
|
|
265
|
+
structure: PageStructure | null,
|
|
266
|
+
refs: Map<string, BrowserRef>
|
|
267
|
+
): PageStructure | null {
|
|
268
|
+
if (!structure || !(refs instanceof Map)) return structure;
|
|
269
|
+
const refByRoleAndName = new Map<string, string>();
|
|
270
|
+
for (const [ref, info] of refs) {
|
|
271
|
+
refByRoleAndName.set(`${info.role}:${info.name}:${info.nth}`, ref);
|
|
272
|
+
}
|
|
273
|
+
const assign = (control: { label?: string; ref?: string }, role: string) => {
|
|
274
|
+
if (!control?.label) return;
|
|
275
|
+
const ref = refByRoleAndName.get(`${role}:${control.label}:0`);
|
|
276
|
+
if (ref) control.ref = ref;
|
|
277
|
+
};
|
|
278
|
+
for (const form of structure.forms || []) {
|
|
279
|
+
for (const field of form.fields || []) assign(field, field.role);
|
|
280
|
+
for (const control of form.submitControls || []) assign(control, 'button');
|
|
281
|
+
}
|
|
282
|
+
return structure;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export function isDeadContextError(err: unknown): boolean {
|
|
286
|
+
const msg = errorMessage(err);
|
|
287
|
+
return msg.includes('Target page, context or browser has been closed')
|
|
288
|
+
|| msg.includes('browser has been closed')
|
|
289
|
+
|| msg.includes('Context closed')
|
|
290
|
+
|| msg.includes('Browser closed');
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function isPageCrashedError(err: unknown): boolean {
|
|
294
|
+
const msg = errorMessage(err);
|
|
295
|
+
return msg.includes('Page crashed')
|
|
296
|
+
|| msg.includes('Target crashed')
|
|
297
|
+
|| msg.includes('crashed page');
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
interface BrowserFrame {
|
|
301
|
+
url(): string;
|
|
302
|
+
name(): string;
|
|
303
|
+
locator(selector: string): BrowserLocator;
|
|
304
|
+
getByRole(role: string, options?: Record<string, unknown>): BrowserLocator;
|
|
305
|
+
}
|
|
306
|
+
|
|
26
307
|
interface BrowserLocator {
|
|
27
308
|
first(): BrowserLocator;
|
|
28
309
|
nth(index: number): BrowserLocator;
|
|
29
310
|
click(options?: Record<string, unknown>): Promise<void>;
|
|
311
|
+
dblclick?(options?: Record<string, unknown>): Promise<void>;
|
|
312
|
+
hover?(options?: Record<string, unknown>): Promise<void>;
|
|
313
|
+
focus?(options?: Record<string, unknown>): Promise<void>;
|
|
30
314
|
fill(value: string, options?: Record<string, unknown>): Promise<void>;
|
|
31
315
|
press(key: string, options?: Record<string, unknown>): Promise<void>;
|
|
32
|
-
selectOption(value:
|
|
316
|
+
selectOption(value: unknown, options?: Record<string, unknown>): Promise<unknown>;
|
|
317
|
+
setInputFiles?(files: string | string[], options?: Record<string, unknown>): Promise<void>;
|
|
33
318
|
innerText(options?: Record<string, unknown>): Promise<string>;
|
|
34
319
|
ariaSnapshot(options?: Record<string, unknown>): Promise<string>;
|
|
320
|
+
count?(): Promise<number>;
|
|
321
|
+
isVisible?(options?: Record<string, unknown>): Promise<boolean>;
|
|
322
|
+
boundingBox?(options?: Record<string, unknown>): Promise<{ x: number; y: number; width: number; height: number } | null>;
|
|
323
|
+
evaluate?<T>(fn: (element: any) => T): Promise<T>;
|
|
324
|
+
waitFor?(options?: Record<string, unknown>): Promise<void>;
|
|
35
325
|
}
|
|
36
326
|
|
|
37
327
|
interface BrowserDownload {
|
|
@@ -40,6 +330,10 @@ interface BrowserDownload {
|
|
|
40
330
|
failure(): Promise<string | null>;
|
|
41
331
|
}
|
|
42
332
|
|
|
333
|
+
interface BrowserFileChooser {
|
|
334
|
+
setFiles(files: string | string[]): Promise<void>;
|
|
335
|
+
}
|
|
336
|
+
|
|
43
337
|
interface BrowserRoute {
|
|
44
338
|
request(): { url(): string };
|
|
45
339
|
continue(): Promise<void>;
|
|
@@ -53,25 +347,40 @@ interface BrowserPage {
|
|
|
53
347
|
goto(url: string, options?: Record<string, unknown>): Promise<{ status(): number; headers(): Record<string, string> } | null>;
|
|
54
348
|
waitForLoadState(state: string, options?: Record<string, unknown>): Promise<void>;
|
|
55
349
|
waitForTimeout(milliseconds: number): Promise<void>;
|
|
56
|
-
|
|
350
|
+
waitForSelector?(selector: string, options?: Record<string, unknown>): Promise<unknown>;
|
|
351
|
+
waitForEvent(event: 'download' | 'filechooser', options?: Record<string, unknown>): Promise<any>;
|
|
57
352
|
locator(selector: string): BrowserLocator;
|
|
58
353
|
getByRole(role: string, options?: Record<string, unknown>): BrowserLocator;
|
|
59
|
-
|
|
354
|
+
frames?(): BrowserFrame[];
|
|
355
|
+
mainFrame?(): BrowserFrame;
|
|
356
|
+
frame?(options: { name: string }): BrowserFrame | null;
|
|
357
|
+
evaluate<T>(expression: string | ((arg?: any) => T | Promise<T>), argument?: unknown): Promise<T>;
|
|
60
358
|
route(pattern: string, handler: (route: BrowserRoute) => Promise<void>): Promise<void>;
|
|
61
359
|
setDefaultTimeout(milliseconds: number): void;
|
|
360
|
+
setViewportSize?(size: { width: number; height: number }): Promise<void>;
|
|
62
361
|
goBack(options?: Record<string, unknown>): Promise<unknown>;
|
|
63
362
|
goForward(options?: Record<string, unknown>): Promise<unknown>;
|
|
64
363
|
reload(options?: Record<string, unknown>): Promise<unknown>;
|
|
65
364
|
screenshot(options?: Record<string, unknown>): Promise<Buffer>;
|
|
66
365
|
close(): Promise<void>;
|
|
67
|
-
|
|
68
|
-
|
|
366
|
+
on?(event: string, handler: (...args: any[]) => void): void;
|
|
367
|
+
keyboard: {
|
|
368
|
+
press(key: string): Promise<void>;
|
|
369
|
+
type?(text: string, options?: { delay?: number }): Promise<void>;
|
|
370
|
+
};
|
|
371
|
+
mouse: {
|
|
372
|
+
wheel(deltaX: number, deltaY: number): Promise<void>;
|
|
373
|
+
move?(x: number, y: number): Promise<void>;
|
|
374
|
+
down?(): Promise<void>;
|
|
375
|
+
up?(): Promise<void>;
|
|
376
|
+
};
|
|
69
377
|
}
|
|
70
378
|
|
|
71
379
|
interface BrowserSession {
|
|
72
380
|
newPage(): Promise<BrowserPage>;
|
|
73
381
|
pages(): BrowserPage[];
|
|
74
382
|
close(): Promise<void>;
|
|
383
|
+
isConnected?(): boolean;
|
|
75
384
|
route?(pattern: string, handler: (route: BrowserRoute) => Promise<void>): Promise<void>;
|
|
76
385
|
on?(event: 'page', handler: (page: BrowserPage) => void): void;
|
|
77
386
|
}
|
|
@@ -91,6 +400,8 @@ export interface BrowserRef {
|
|
|
91
400
|
role: string;
|
|
92
401
|
name: string;
|
|
93
402
|
nth: number;
|
|
403
|
+
frameName?: string;
|
|
404
|
+
frameUrl?: string;
|
|
94
405
|
}
|
|
95
406
|
|
|
96
407
|
interface TabState {
|
|
@@ -98,24 +409,59 @@ interface TabState {
|
|
|
98
409
|
page: BrowserPage;
|
|
99
410
|
refs: Map<string, BrowserRef>;
|
|
100
411
|
lastSnapshot: string;
|
|
412
|
+
lastStructure: PageStructure | null;
|
|
413
|
+
crashed?: boolean;
|
|
101
414
|
}
|
|
102
415
|
|
|
416
|
+
export type BrowserActionType =
|
|
417
|
+
| 'newTab' | 'new_tab'
|
|
418
|
+
| 'switchTab' | 'switch_tab'
|
|
419
|
+
| 'listTabs' | 'list_tabs'
|
|
420
|
+
| 'closeTab' | 'close_tab'
|
|
421
|
+
| 'search'
|
|
422
|
+
| 'goto' | 'open' | 'navigate'
|
|
423
|
+
| 'snapshot' | 'scrape'
|
|
424
|
+
| 'click' | 'clickIndex'
|
|
425
|
+
| 'type' | 'typeIndex' | 'fill'
|
|
426
|
+
| 'selectOption' | 'select'
|
|
427
|
+
| 'keyPress' | 'press'
|
|
428
|
+
| 'hover'
|
|
429
|
+
| 'scroll'
|
|
430
|
+
| 'wait'
|
|
431
|
+
| 'viewport'
|
|
432
|
+
| 'back' | 'forward' | 'reload' | 'refresh'
|
|
433
|
+
| 'extract' | 'links' | 'images'
|
|
434
|
+
| 'upload' | 'download' | 'screenshot';
|
|
435
|
+
|
|
103
436
|
export type BrowserAction = {
|
|
104
|
-
type:
|
|
105
|
-
| 'click' | 'clickIndex' | 'type' | 'typeIndex' | 'selectOption' | 'keyPress' | 'scroll'
|
|
106
|
-
| 'back' | 'forward' | 'reload' | 'extract' | 'download' | 'screenshot';
|
|
437
|
+
type: BrowserActionType;
|
|
107
438
|
tabId?: string;
|
|
108
439
|
url?: string;
|
|
440
|
+
macro?: string;
|
|
109
441
|
query?: string;
|
|
110
442
|
ref?: string;
|
|
111
443
|
index?: number;
|
|
112
444
|
selector?: string;
|
|
113
445
|
text?: string;
|
|
114
446
|
value?: string;
|
|
447
|
+
option?: string;
|
|
115
448
|
key?: string;
|
|
449
|
+
mode?: 'fill' | 'keyboard';
|
|
450
|
+
delay?: number;
|
|
451
|
+
submit?: boolean;
|
|
452
|
+
pressEnter?: boolean;
|
|
453
|
+
doubleClick?: boolean;
|
|
116
454
|
direction?: 'up' | 'down' | 'left' | 'right';
|
|
117
455
|
amount?: number;
|
|
118
456
|
offset?: number;
|
|
457
|
+
limit?: number;
|
|
458
|
+
timeout?: number;
|
|
459
|
+
waitForNetwork?: boolean;
|
|
460
|
+
dismissConsent?: boolean;
|
|
461
|
+
width?: number;
|
|
462
|
+
height?: number;
|
|
463
|
+
schema?: ExtractSchema;
|
|
464
|
+
filePath?: string | string[];
|
|
119
465
|
outputFile?: string;
|
|
120
466
|
fullPage?: boolean;
|
|
121
467
|
};
|
|
@@ -127,6 +473,11 @@ export interface BrowserActionResult {
|
|
|
127
473
|
title?: string;
|
|
128
474
|
output?: string;
|
|
129
475
|
data?: unknown;
|
|
476
|
+
structure?: PageStructure | null;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
export interface BrowserRunOptions {
|
|
480
|
+
workspace?: string;
|
|
130
481
|
}
|
|
131
482
|
|
|
132
483
|
interface RuntimeOptions {
|
|
@@ -168,12 +519,13 @@ export function parseAriaRefs(snapshot: string): Map<string, BrowserRef> {
|
|
|
168
519
|
const seen = new Map<string, number>();
|
|
169
520
|
let counter = 1;
|
|
170
521
|
for (const line of String(snapshot ?? '').split('\n')) {
|
|
171
|
-
if (counter >
|
|
522
|
+
if (counter > MAX_SNAPSHOT_NODES) break;
|
|
172
523
|
const match = line.match(/^\s*-\s+([a-z][\w-]*)(?:\s+"([^"]*)")?/i);
|
|
173
524
|
if (!match) continue;
|
|
174
525
|
const role = (match[1] ?? '').toLowerCase();
|
|
175
|
-
if (!INTERACTIVE_ROLES.has(role)) continue;
|
|
176
526
|
const name = match[2] ?? '';
|
|
527
|
+
if (name && SKIP_PATTERNS.some(pattern => pattern.test(name))) continue;
|
|
528
|
+
if (!INTERACTIVE_ROLES.has(role)) continue;
|
|
177
529
|
const key = `${role}:${name}`;
|
|
178
530
|
const nth = seen.get(key) ?? 0;
|
|
179
531
|
seen.set(key, nth + 1);
|
|
@@ -185,18 +537,260 @@ export function parseAriaRefs(snapshot: string): Map<string, BrowserRef> {
|
|
|
185
537
|
export function annotateAriaSnapshot(snapshot: string, refs: Map<string, BrowserRef>): string {
|
|
186
538
|
const queues = new Map<string, string[]>();
|
|
187
539
|
for (const [id, ref] of refs) {
|
|
540
|
+
if (ref.frameName || ref.frameUrl) continue;
|
|
188
541
|
const key = `${ref.role}:${ref.name}`;
|
|
189
542
|
queues.set(key, [...(queues.get(key) ?? []), id]);
|
|
190
543
|
}
|
|
191
544
|
return String(snapshot ?? '').split('\n').map(line => {
|
|
192
545
|
const match = line.match(/^(\s*-\s+)([a-z][\w-]*)(?:\s+"([^"]*)")?/i);
|
|
193
546
|
if (!match) return line;
|
|
194
|
-
const
|
|
547
|
+
const name = match[3] ?? '';
|
|
548
|
+
if (name && SKIP_PATTERNS.some(pattern => pattern.test(name))) return line;
|
|
549
|
+
const key = `${(match[2] ?? '').toLowerCase()}:${name}`;
|
|
195
550
|
const id = queues.get(key)?.shift();
|
|
196
551
|
return id ? `${line} [${id}]` : line;
|
|
197
552
|
}).join('\n');
|
|
198
553
|
}
|
|
199
554
|
|
|
555
|
+
const PAGE_STRUCTURE_EXTRACT_SCRIPT = `(() => {
|
|
556
|
+
const MAX_FORMS = 20;
|
|
557
|
+
const MAX_FIELDS_PER_FORM = 30;
|
|
558
|
+
const MAX_TABLES = 20;
|
|
559
|
+
const MAX_ROWS_PER_TABLE = 50;
|
|
560
|
+
const MAX_CELLS_PER_ROW = 30;
|
|
561
|
+
const MAX_CELL_CHARS = 200;
|
|
562
|
+
const MAX_OPTIONS_PER_SELECT = 30;
|
|
563
|
+
const MAX_LABEL_CHARS = 150;
|
|
564
|
+
const SENSITIVE_FIELD_RE = /password|passwd|pwd|secret|token|api[_-]?key|ssn|credit|card|cvv|cvc/i;
|
|
565
|
+
|
|
566
|
+
function trunc(str, max) {
|
|
567
|
+
if (!str) return '';
|
|
568
|
+
const s = String(str).replace(/\\s+/g, ' ').trim();
|
|
569
|
+
return s.length > max ? s.slice(0, max) + '…' : s;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function isVisible(el) {
|
|
573
|
+
if (!el || !el.getBoundingClientRect) return false;
|
|
574
|
+
if (el.hidden || el.getAttribute('aria-hidden') === 'true') return false;
|
|
575
|
+
const style = window.getComputedStyle(el);
|
|
576
|
+
if (!style || style.display === 'none' || style.visibility === 'hidden') return false;
|
|
577
|
+
const rect = el.getBoundingClientRect();
|
|
578
|
+
return rect.width > 0 || rect.height > 0;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function resolveLabel(el) {
|
|
582
|
+
const ariaLabel = el.getAttribute('aria-label');
|
|
583
|
+
if (ariaLabel) return trunc(ariaLabel, MAX_LABEL_CHARS);
|
|
584
|
+
const labelledBy = el.getAttribute('aria-labelledby');
|
|
585
|
+
if (labelledBy) {
|
|
586
|
+
const text = labelledBy
|
|
587
|
+
.split(/\\s+/)
|
|
588
|
+
.map(id => document.getElementById(id)?.textContent || '')
|
|
589
|
+
.join(' ')
|
|
590
|
+
.trim();
|
|
591
|
+
if (text) return trunc(text, MAX_LABEL_CHARS);
|
|
592
|
+
}
|
|
593
|
+
if (el.id) {
|
|
594
|
+
const escapedId = String(el.id).replace(/"/g, '\\\\"');
|
|
595
|
+
const byFor = document.querySelector('label[for="' + escapedId + '"]');
|
|
596
|
+
if (byFor) return trunc(byFor.textContent, MAX_LABEL_CHARS);
|
|
597
|
+
}
|
|
598
|
+
const parentLabel = el.closest('label');
|
|
599
|
+
if (parentLabel) {
|
|
600
|
+
const clone = parentLabel.cloneNode(true);
|
|
601
|
+
clone.querySelectorAll('input,select,textarea,button').forEach(node => node.remove());
|
|
602
|
+
const text = clone.textContent?.trim();
|
|
603
|
+
if (text) return trunc(text, MAX_LABEL_CHARS);
|
|
604
|
+
}
|
|
605
|
+
const placeholder = el.getAttribute('placeholder');
|
|
606
|
+
if (placeholder) return trunc(placeholder, MAX_LABEL_CHARS);
|
|
607
|
+
const title = el.getAttribute('title');
|
|
608
|
+
if (title) return trunc(title, MAX_LABEL_CHARS);
|
|
609
|
+
return null;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function inferRole(el, tag, type) {
|
|
613
|
+
const explicit = el.getAttribute('role');
|
|
614
|
+
if (explicit) return explicit.toLowerCase();
|
|
615
|
+
if (tag === 'button') return 'button';
|
|
616
|
+
if (tag === 'select') return 'combobox';
|
|
617
|
+
if (tag === 'textarea') return 'textbox';
|
|
618
|
+
if (tag === 'input') {
|
|
619
|
+
if (type === 'submit' || type === 'button' || type === 'reset') return 'button';
|
|
620
|
+
if (type === 'checkbox') return 'checkbox';
|
|
621
|
+
if (type === 'radio') return 'radio';
|
|
622
|
+
if (type === 'search') return 'searchbox';
|
|
623
|
+
if (type === 'number') return 'spinbutton';
|
|
624
|
+
if (type === 'range') return 'slider';
|
|
625
|
+
return 'textbox';
|
|
626
|
+
}
|
|
627
|
+
return null;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function extractField(el) {
|
|
631
|
+
const tag = (el.tagName || '').toLowerCase();
|
|
632
|
+
const type = tag === 'input' ? (el.getAttribute('type') || 'text').toLowerCase() : tag;
|
|
633
|
+
if (type === 'hidden') return null;
|
|
634
|
+
if (!isVisible(el)) return null;
|
|
635
|
+
const name = el.getAttribute('name') || null;
|
|
636
|
+
const id = el.id || null;
|
|
637
|
+
const label = resolveLabel(el);
|
|
638
|
+
const role = inferRole(el, tag, type);
|
|
639
|
+
const accessibleName = trunc(
|
|
640
|
+
el.getAttribute('aria-label') || label || el.value || el.textContent || '',
|
|
641
|
+
MAX_LABEL_CHARS
|
|
642
|
+
) || null;
|
|
643
|
+
const isSensitive = type === 'password'
|
|
644
|
+
|| SENSITIVE_FIELD_RE.test(name || '')
|
|
645
|
+
|| SENSITIVE_FIELD_RE.test(id || '')
|
|
646
|
+
|| SENSITIVE_FIELD_RE.test(el.getAttribute('autocomplete') || '');
|
|
647
|
+
const field = { tag, type };
|
|
648
|
+
if (name) field.name = trunc(name, 80);
|
|
649
|
+
if (id) field.id = trunc(id, 80);
|
|
650
|
+
if (label) field.label = label;
|
|
651
|
+
if (role) field.role = role;
|
|
652
|
+
if (accessibleName) field._accessibleName = accessibleName;
|
|
653
|
+
const placeholder = el.getAttribute('placeholder');
|
|
654
|
+
if (placeholder && placeholder !== label) field.placeholder = trunc(placeholder, MAX_LABEL_CHARS);
|
|
655
|
+
if (el.required || el.getAttribute('aria-required') === 'true') field.required = true;
|
|
656
|
+
if (el.disabled || el.getAttribute('aria-disabled') === 'true') field.disabled = true;
|
|
657
|
+
if (el.readOnly) field.readOnly = true;
|
|
658
|
+
if (type === 'checkbox' || type === 'radio') {
|
|
659
|
+
field.checked = Boolean(el.checked);
|
|
660
|
+
if (el.value && el.value !== 'on') field.value = trunc(el.value, 100);
|
|
661
|
+
} else if (tag === 'select') {
|
|
662
|
+
const opts = Array.from(el.options || []).slice(0, MAX_OPTIONS_PER_SELECT).map(o => ({
|
|
663
|
+
value: trunc(o.value, 100),
|
|
664
|
+
text: trunc(o.text, 100),
|
|
665
|
+
...(o.selected ? { selected: true } : {})
|
|
666
|
+
}));
|
|
667
|
+
field.options = opts;
|
|
668
|
+
if ((el.options || []).length > MAX_OPTIONS_PER_SELECT) field.optionsTruncated = true;
|
|
669
|
+
} else if (tag === 'button' || type === 'submit' || type === 'button' || type === 'reset') {
|
|
670
|
+
const btnText = trunc(el.textContent || el.value || '', 100);
|
|
671
|
+
if (btnText) field.text = btnText;
|
|
672
|
+
} else if (isSensitive) {
|
|
673
|
+
field.value = el.value ? '[REDACTED]' : '';
|
|
674
|
+
field.redacted = true;
|
|
675
|
+
} else if (typeof el.value === 'string' && el.value.length > 0) {
|
|
676
|
+
field.value = trunc(el.value, MAX_CELL_CHARS);
|
|
677
|
+
}
|
|
678
|
+
return field;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
const formEls = Array.from(document.querySelectorAll('form'));
|
|
682
|
+
const forms = [];
|
|
683
|
+
const seenControls = new Set();
|
|
684
|
+
|
|
685
|
+
for (const formEl of formEls.slice(0, MAX_FORMS)) {
|
|
686
|
+
const controls = Array.from(formEl.querySelectorAll('input, select, textarea, button'));
|
|
687
|
+
controls.forEach(c => seenControls.add(c));
|
|
688
|
+
const fields = [];
|
|
689
|
+
for (const ctrl of controls) {
|
|
690
|
+
if (fields.length >= MAX_FIELDS_PER_FORM) break;
|
|
691
|
+
const f = extractField(ctrl);
|
|
692
|
+
if (f) fields.push(f);
|
|
693
|
+
}
|
|
694
|
+
if (fields.length === 0) continue;
|
|
695
|
+
const formObj = { fields };
|
|
696
|
+
if (formEl.id) formObj.id = trunc(formEl.id, 80);
|
|
697
|
+
const fName = formEl.getAttribute('name') || formEl.getAttribute('aria-label');
|
|
698
|
+
if (fName) formObj.name = trunc(fName, 100);
|
|
699
|
+
const action = formEl.getAttribute('action');
|
|
700
|
+
if (action) formObj.action = trunc(action, 200);
|
|
701
|
+
const method = (formEl.getAttribute('method') || 'get').toUpperCase();
|
|
702
|
+
formObj.method = method;
|
|
703
|
+
if (controls.length > MAX_FIELDS_PER_FORM) formObj.fieldsTruncated = true;
|
|
704
|
+
forms.push(formObj);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
if (forms.length < MAX_FORMS) {
|
|
708
|
+
const orphans = Array.from(document.querySelectorAll('input, select, textarea'))
|
|
709
|
+
.filter(el => !seenControls.has(el));
|
|
710
|
+
const orphanFields = [];
|
|
711
|
+
for (const ctrl of orphans) {
|
|
712
|
+
if (orphanFields.length >= MAX_FIELDS_PER_FORM) break;
|
|
713
|
+
const f = extractField(ctrl);
|
|
714
|
+
if (f) orphanFields.push(f);
|
|
715
|
+
}
|
|
716
|
+
if (orphanFields.length > 0) {
|
|
717
|
+
forms.push({ implicit: true, fields: orphanFields });
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const tableEls = Array.from(document.querySelectorAll('table'));
|
|
722
|
+
const tables = [];
|
|
723
|
+
|
|
724
|
+
for (const tableEl of tableEls) {
|
|
725
|
+
if (tables.length >= MAX_TABLES) break;
|
|
726
|
+
if (!isVisible(tableEl)) continue;
|
|
727
|
+
const allRows = Array.from(tableEl.querySelectorAll('tr'));
|
|
728
|
+
if (allRows.length === 0) continue;
|
|
729
|
+
let headers = [];
|
|
730
|
+
const theadRow = tableEl.querySelector('thead tr');
|
|
731
|
+
let bodyStartIdx = 0;
|
|
732
|
+
if (theadRow) {
|
|
733
|
+
headers = Array.from(theadRow.querySelectorAll('th, td'))
|
|
734
|
+
.slice(0, MAX_CELLS_PER_ROW)
|
|
735
|
+
.map(c => trunc(c.textContent, MAX_CELL_CHARS));
|
|
736
|
+
} else {
|
|
737
|
+
const firstRow = allRows[0];
|
|
738
|
+
const ths = firstRow.querySelectorAll('th');
|
|
739
|
+
if (ths.length > 0) {
|
|
740
|
+
headers = Array.from(firstRow.querySelectorAll('th, td'))
|
|
741
|
+
.slice(0, MAX_CELLS_PER_ROW)
|
|
742
|
+
.map(c => trunc(c.textContent, MAX_CELL_CHARS));
|
|
743
|
+
bodyStartIdx = 1;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
const bodyRowEls = theadRow
|
|
747
|
+
? Array.from(tableEl.querySelectorAll('tbody tr'))
|
|
748
|
+
: allRows.slice(bodyStartIdx);
|
|
749
|
+
const rows = [];
|
|
750
|
+
for (const tr of bodyRowEls) {
|
|
751
|
+
if (rows.length >= MAX_ROWS_PER_TABLE) break;
|
|
752
|
+
const cells = Array.from(tr.querySelectorAll('td, th'))
|
|
753
|
+
.slice(0, MAX_CELLS_PER_ROW)
|
|
754
|
+
.map(c => trunc(c.textContent, MAX_CELL_CHARS));
|
|
755
|
+
if (cells.length === 0 || cells.every(c => c === '')) continue;
|
|
756
|
+
if (headers.length > 0 && headers.some(Boolean)) {
|
|
757
|
+
const obj = {};
|
|
758
|
+
cells.forEach((val, idx) => {
|
|
759
|
+
const key = headers[idx] || ('col_' + (idx + 1));
|
|
760
|
+
obj[key] = val;
|
|
761
|
+
});
|
|
762
|
+
rows.push(obj);
|
|
763
|
+
} else {
|
|
764
|
+
rows.push(cells);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
if (headers.length === 0 && rows.length < 2) continue;
|
|
768
|
+
const tableObj = { headers, rows, rowCount: bodyRowEls.length };
|
|
769
|
+
if (tableEl.id) tableObj.id = trunc(tableEl.id, 80);
|
|
770
|
+
const caption = tableEl.querySelector('caption')?.textContent || tableEl.getAttribute('aria-label');
|
|
771
|
+
if (caption) tableObj.caption = trunc(caption, MAX_LABEL_CHARS);
|
|
772
|
+
if (bodyRowEls.length > MAX_ROWS_PER_TABLE) tableObj.rowsTruncated = true;
|
|
773
|
+
tables.push(tableObj);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
return { forms, tables };
|
|
777
|
+
})()`;
|
|
778
|
+
|
|
779
|
+
export async function extractPageStructure(page: BrowserPage): Promise<PageStructure | null> {
|
|
780
|
+
try {
|
|
781
|
+
const raw = await page.evaluate<PageStructure>(PAGE_STRUCTURE_EXTRACT_SCRIPT);
|
|
782
|
+
if (!raw || typeof raw !== 'object' || !Array.isArray(raw.forms) || !Array.isArray(raw.tables)) {
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
785
|
+
if (raw.forms.length === 0 && raw.tables.length === 0) {
|
|
786
|
+
return null;
|
|
787
|
+
}
|
|
788
|
+
return raw;
|
|
789
|
+
} catch {
|
|
790
|
+
return null;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
200
794
|
const SEARCH_EXTRACT_SCRIPT = `(() => {
|
|
201
795
|
const text = value => String(value || '').replace(/\\s+/g, ' ').trim();
|
|
202
796
|
const candidates = [
|
|
@@ -237,8 +831,92 @@ const SEARCH_EXTRACT_SCRIPT = `(() => {
|
|
|
237
831
|
return results;
|
|
238
832
|
})()`;
|
|
239
833
|
|
|
834
|
+
const LINKS_EXTRACT_SCRIPT = `(opts) => {
|
|
835
|
+
const scope = opts && opts.selector ? document.querySelector(opts.selector) : document;
|
|
836
|
+
if (!scope) return { links: [], totalLinks: 0 };
|
|
837
|
+
const anchors = Array.from(scope.querySelectorAll('a[href]'));
|
|
838
|
+
const seen = new Set();
|
|
839
|
+
const all = [];
|
|
840
|
+
for (const a of anchors) {
|
|
841
|
+
let href;
|
|
842
|
+
try {
|
|
843
|
+
href = new URL(a.getAttribute('href'), document.baseURI).href;
|
|
844
|
+
} catch {
|
|
845
|
+
continue;
|
|
846
|
+
}
|
|
847
|
+
if (!href.startsWith('http://') && !href.startsWith('https://')) continue;
|
|
848
|
+
if (seen.has(href)) continue;
|
|
849
|
+
seen.add(href);
|
|
850
|
+
const text = (a.textContent || '').trim().replace(/\\s+/g, ' ').slice(0, 200);
|
|
851
|
+
all.push({ url: href, text: text || undefined });
|
|
852
|
+
}
|
|
853
|
+
const start = (opts && opts.offset) || 0;
|
|
854
|
+
const max = (opts && opts.limit) || 50;
|
|
855
|
+
return { links: all.slice(start, start + max), totalLinks: all.length };
|
|
856
|
+
}`;
|
|
857
|
+
|
|
858
|
+
const IMAGES_EXTRACT_SCRIPT = `(opts) => {
|
|
859
|
+
const max = Math.min(Math.max(Number(opts && opts.limit) || 100, 1), 300);
|
|
860
|
+
const imgs = Array.from(document.querySelectorAll('img'));
|
|
861
|
+
const seen = new Set();
|
|
862
|
+
const out = [];
|
|
863
|
+
for (const img of imgs) {
|
|
864
|
+
const src = img.currentSrc || img.src || '';
|
|
865
|
+
if (!src || src.startsWith('data:') || seen.has(src)) continue;
|
|
866
|
+
const width = Number(img.naturalWidth || img.width || 0);
|
|
867
|
+
const height = Number(img.naturalHeight || img.height || 0);
|
|
868
|
+
seen.add(src);
|
|
869
|
+
out.push({
|
|
870
|
+
src,
|
|
871
|
+
alt: (img.alt || '').trim().slice(0, 200) || undefined,
|
|
872
|
+
width,
|
|
873
|
+
height
|
|
874
|
+
});
|
|
875
|
+
if (out.length >= max) break;
|
|
876
|
+
}
|
|
877
|
+
return out;
|
|
878
|
+
}`;
|
|
879
|
+
|
|
880
|
+
const DISMISS_CONSENT_SCRIPT = `(() => {
|
|
881
|
+
const selectors = [
|
|
882
|
+
'#onetrust-accept-btn-handler',
|
|
883
|
+
'.onetrust-close-btn-handler',
|
|
884
|
+
'#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll',
|
|
885
|
+
'#CybotCookiebotDialogBodyButtonAccept',
|
|
886
|
+
'[data-testid="cookie-policy-dialog-accept-button"]',
|
|
887
|
+
'button[id*="cookie"][id*="accept" i]',
|
|
888
|
+
'button[class*="cookie"][class*="accept" i]',
|
|
889
|
+
'button[aria-label*="Accept all" i]',
|
|
890
|
+
'button[aria-label*="Accept cookies" i]'
|
|
891
|
+
];
|
|
892
|
+
for (const sel of selectors) {
|
|
893
|
+
const el = document.querySelector(sel);
|
|
894
|
+
if (el && typeof el.click === 'function') {
|
|
895
|
+
const rect = el.getBoundingClientRect?.();
|
|
896
|
+
if (!rect || (rect.width > 0 && rect.height > 0)) {
|
|
897
|
+
el.click();
|
|
898
|
+
return true;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
return false;
|
|
903
|
+
})()`;
|
|
904
|
+
|
|
905
|
+
const WAIT_FOR_PAGE_READY_SCRIPT = `(() => {
|
|
906
|
+
return new Promise(resolve => {
|
|
907
|
+
if (document.readyState === 'complete') {
|
|
908
|
+
requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)));
|
|
909
|
+
} else {
|
|
910
|
+
window.addEventListener('load', () => {
|
|
911
|
+
requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)));
|
|
912
|
+
}, { once: true });
|
|
913
|
+
setTimeout(() => resolve(false), 3000);
|
|
914
|
+
}
|
|
915
|
+
});
|
|
916
|
+
})()`;
|
|
917
|
+
|
|
240
918
|
export class CausyneBrowser {
|
|
241
|
-
private
|
|
919
|
+
private workspace: string;
|
|
242
920
|
private readonly ensureBrowserCapability: NonNullable<RuntimeOptions['ensureBrowserCapability']>;
|
|
243
921
|
private readonly loadBrowserEngine: NonNullable<RuntimeOptions['loadBrowserEngine']>;
|
|
244
922
|
private readonly resolveRuntime: NonNullable<RuntimeOptions['resolveRuntime']>;
|
|
@@ -264,13 +942,36 @@ export class CausyneBrowser {
|
|
|
264
942
|
this.validateUrl = options.validateUrl ?? assertPublicWebUrl;
|
|
265
943
|
}
|
|
266
944
|
|
|
267
|
-
|
|
945
|
+
setWorkspace(workspace: string): void {
|
|
946
|
+
if (workspace && typeof workspace === 'string') {
|
|
947
|
+
this.workspace = path.resolve(workspace);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
getWorkspace(): string {
|
|
952
|
+
return this.workspace;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
async run(actions: BrowserAction[], options: BrowserRunOptions = {}): Promise<BrowserActionResult[]> {
|
|
268
956
|
if (!Array.isArray(actions) || actions.length === 0 || actions.length > 40) {
|
|
269
957
|
throw new Error('Browser actions must contain between 1 and 40 operations');
|
|
270
958
|
}
|
|
959
|
+
const activeWorkspace = options.workspace ? path.resolve(options.workspace) : this.workspace;
|
|
271
960
|
await this.start();
|
|
272
961
|
const results: BrowserActionResult[] = [];
|
|
273
|
-
for (const action of actions)
|
|
962
|
+
for (const action of actions) {
|
|
963
|
+
try {
|
|
964
|
+
results.push(await this.runAction(action, activeWorkspace));
|
|
965
|
+
} catch (error) {
|
|
966
|
+
if (isDeadContextError(error)) {
|
|
967
|
+
await this.close();
|
|
968
|
+
await this.start();
|
|
969
|
+
results.push(await this.runAction(action, activeWorkspace));
|
|
970
|
+
} else {
|
|
971
|
+
throw error;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
}
|
|
274
975
|
this.touch();
|
|
275
976
|
return results;
|
|
276
977
|
}
|
|
@@ -302,18 +1003,17 @@ export class CausyneBrowser {
|
|
|
302
1003
|
throw new Error(`Search providers exhausted. ${failures.join('; ')}`);
|
|
303
1004
|
}
|
|
304
1005
|
|
|
305
|
-
async snapshot(offset = 0): Promise<SnapshotWindow & { tabId: string; url: string; title: string; refsCount: number }> {
|
|
1006
|
+
async snapshot(offset = 0): Promise<SnapshotWindow & { tabId: string; url: string; title: string; refsCount: number; structure?: PageStructure | null }> {
|
|
306
1007
|
await this.start();
|
|
307
1008
|
const state = await this.activeTab();
|
|
308
|
-
|
|
309
|
-
state.refs = parseAriaRefs(raw);
|
|
310
|
-
state.lastSnapshot = annotateAriaSnapshot(raw, state.refs);
|
|
1009
|
+
await this.captureSnapshotState(state);
|
|
311
1010
|
return {
|
|
312
1011
|
...windowSnapshot(state.lastSnapshot, offset),
|
|
313
1012
|
tabId: state.id,
|
|
314
1013
|
url: state.page.url(),
|
|
315
1014
|
title: await state.page.title(),
|
|
316
|
-
refsCount: state.refs.size
|
|
1015
|
+
refsCount: state.refs.size,
|
|
1016
|
+
...(state.lastStructure ? { structure: state.lastStructure } : {})
|
|
317
1017
|
};
|
|
318
1018
|
}
|
|
319
1019
|
|
|
@@ -331,8 +1031,24 @@ export class CausyneBrowser {
|
|
|
331
1031
|
if (session) await session.close().catch(() => {});
|
|
332
1032
|
}
|
|
333
1033
|
|
|
1034
|
+
private isSessionHealthy(): boolean {
|
|
1035
|
+
if (!this.session) return false;
|
|
1036
|
+
if (typeof this.session.isConnected === 'function' && !this.session.isConnected()) {
|
|
1037
|
+
return false;
|
|
1038
|
+
}
|
|
1039
|
+
try {
|
|
1040
|
+
this.session.pages();
|
|
1041
|
+
return true;
|
|
1042
|
+
} catch {
|
|
1043
|
+
return false;
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
|
|
334
1047
|
private async start(): Promise<void> {
|
|
335
|
-
if (this.session)
|
|
1048
|
+
if (this.session) {
|
|
1049
|
+
if (this.isSessionHealthy()) return;
|
|
1050
|
+
await this.close();
|
|
1051
|
+
}
|
|
336
1052
|
if (this.starting) return this.starting;
|
|
337
1053
|
this.starting = (async () => {
|
|
338
1054
|
const verdict = await this.ensureBrowserCapability();
|
|
@@ -348,7 +1064,14 @@ export class CausyneBrowser {
|
|
|
348
1064
|
humanize: 0.35,
|
|
349
1065
|
block_webrtc: true,
|
|
350
1066
|
geoip: false,
|
|
351
|
-
enable_cache: true
|
|
1067
|
+
enable_cache: true,
|
|
1068
|
+
...(runtime.executablePath ? { executable_path: runtime.executablePath } : {}),
|
|
1069
|
+
firefox_user_prefs: {
|
|
1070
|
+
'Security.OCSP.enabled': 0
|
|
1071
|
+
},
|
|
1072
|
+
handleSIGTERM: false,
|
|
1073
|
+
handleSIGINT: false,
|
|
1074
|
+
handleSIGHUP: false
|
|
352
1075
|
});
|
|
353
1076
|
if (typeof this.session.route === 'function') {
|
|
354
1077
|
await this.session.route('**/*', route => this.guardRoute(route));
|
|
@@ -378,7 +1101,17 @@ export class CausyneBrowser {
|
|
|
378
1101
|
await page.route('**/*', route => this.guardRoute(route));
|
|
379
1102
|
this.securedPages.add(page);
|
|
380
1103
|
}
|
|
381
|
-
const state: TabState = { id, page, refs: new Map(), lastSnapshot: '' };
|
|
1104
|
+
const state: TabState = { id, page, refs: new Map(), lastSnapshot: '', lastStructure: null };
|
|
1105
|
+
page.on?.('crash', () => {
|
|
1106
|
+
state.crashed = true;
|
|
1107
|
+
});
|
|
1108
|
+
page.on?.('close', () => {
|
|
1109
|
+
this.tabs.delete(id);
|
|
1110
|
+
if (this.activeTabId === id) {
|
|
1111
|
+
const remaining = [...this.tabs.values()].find(tab => !tab.page.isClosed() && !tab.crashed);
|
|
1112
|
+
this.activeTabId = remaining?.id ?? null;
|
|
1113
|
+
}
|
|
1114
|
+
});
|
|
382
1115
|
this.pageStates.set(page, state);
|
|
383
1116
|
this.tabs.set(id, state);
|
|
384
1117
|
this.activeTabId = id;
|
|
@@ -404,25 +1137,148 @@ export class CausyneBrowser {
|
|
|
404
1137
|
|
|
405
1138
|
private async createTab(url?: string): Promise<TabState> {
|
|
406
1139
|
if (!this.session) throw new Error('Browser is not started');
|
|
407
|
-
|
|
1140
|
+
let page: BrowserPage;
|
|
1141
|
+
try {
|
|
1142
|
+
page = await this.session.newPage();
|
|
1143
|
+
} catch (error) {
|
|
1144
|
+
if (isDeadContextError(error)) {
|
|
1145
|
+
await this.close();
|
|
1146
|
+
await this.start();
|
|
1147
|
+
if (!this.session) throw error;
|
|
1148
|
+
page = await this.session.newPage();
|
|
1149
|
+
} else {
|
|
1150
|
+
throw error;
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
const state = await this.registerPage(page);
|
|
408
1154
|
if (url) await this.navigate(state, url);
|
|
409
1155
|
return state;
|
|
410
1156
|
}
|
|
411
1157
|
|
|
412
1158
|
private async activeTab(): Promise<TabState> {
|
|
413
1159
|
const active = this.activeTabId ? this.tabs.get(this.activeTabId) : undefined;
|
|
414
|
-
if (active && !active.page.isClosed()) return active;
|
|
1160
|
+
if (active && !active.page.isClosed() && !active.crashed) return active;
|
|
1161
|
+
for (const candidate of this.tabs.values()) {
|
|
1162
|
+
if (!candidate.page.isClosed() && !candidate.crashed) {
|
|
1163
|
+
this.activeTabId = candidate.id;
|
|
1164
|
+
return candidate;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
415
1167
|
return this.createTab();
|
|
416
1168
|
}
|
|
417
1169
|
|
|
418
1170
|
private requestedTab(action: BrowserAction): TabState | null {
|
|
419
1171
|
if (!action.tabId) return null;
|
|
420
1172
|
const state = this.tabs.get(action.tabId);
|
|
421
|
-
if (!state || state.page.isClosed()) throw new Error(`Unknown or closed browser tab: ${action.tabId}`);
|
|
1173
|
+
if (!state || state.page.isClosed() || state.crashed) throw new Error(`Unknown or closed browser tab: ${action.tabId}`);
|
|
422
1174
|
this.activeTabId = state.id;
|
|
423
1175
|
return state;
|
|
424
1176
|
}
|
|
425
1177
|
|
|
1178
|
+
private async captureSnapshotState(state: TabState): Promise<void> {
|
|
1179
|
+
let raw: string;
|
|
1180
|
+
try {
|
|
1181
|
+
raw = await state.page.locator('body').ariaSnapshot({ timeout: ACTION_TIMEOUT_MS });
|
|
1182
|
+
} catch (error) {
|
|
1183
|
+
if (isDeadContextError(error) || isPageCrashedError(error)) throw error;
|
|
1184
|
+
await state.page.waitForTimeout(400);
|
|
1185
|
+
raw = await state.page.locator('body').ariaSnapshot({ timeout: ACTION_TIMEOUT_MS });
|
|
1186
|
+
}
|
|
1187
|
+
const mainRefs = parseAriaRefs(raw);
|
|
1188
|
+
const annotatedParts = [annotateAriaSnapshot(raw, mainRefs)];
|
|
1189
|
+
const allRefs = new Map(mainRefs);
|
|
1190
|
+
let nextCounter = allRefs.size + 1;
|
|
1191
|
+
|
|
1192
|
+
if (typeof state.page.frames === 'function') {
|
|
1193
|
+
try {
|
|
1194
|
+
const mainFrame = typeof state.page.mainFrame === 'function' ? state.page.mainFrame() : null;
|
|
1195
|
+
const childFrames = state.page.frames().filter(frame => frame !== mainFrame);
|
|
1196
|
+
for (const frame of childFrames.slice(0, MAX_IFRAMES_TO_PROCESS)) {
|
|
1197
|
+
if (nextCounter > MAX_SNAPSHOT_NODES) break;
|
|
1198
|
+
const frameUrl = frame.url();
|
|
1199
|
+
if (!frameUrl || frameUrl === 'about:blank' || frameUrl.startsWith('javascript:') || frameUrl.startsWith('data:')) {
|
|
1200
|
+
continue;
|
|
1201
|
+
}
|
|
1202
|
+
if (IFRAME_SKIP_PATTERNS.some(pattern => pattern.test(frameUrl))) continue;
|
|
1203
|
+
try {
|
|
1204
|
+
const frameYaml = await frame.locator('body').ariaSnapshot({ timeout: IFRAME_SNAPSHOT_TIMEOUT_MS });
|
|
1205
|
+
if (!frameYaml || frameYaml.trim().length < 10) continue;
|
|
1206
|
+
const frameSeen = new Map<string, number>();
|
|
1207
|
+
const frameRefs = new Map<string, BrowserRef>();
|
|
1208
|
+
const frameName = frame.name() || undefined;
|
|
1209
|
+
for (const line of String(frameYaml).split('\n')) {
|
|
1210
|
+
if (nextCounter > MAX_SNAPSHOT_NODES) break;
|
|
1211
|
+
const match = line.match(/^\s*-\s+([a-z][\w-]*)(?:\s+"([^"]*)")?/i);
|
|
1212
|
+
if (!match) continue;
|
|
1213
|
+
const role = (match[1] ?? '').toLowerCase();
|
|
1214
|
+
const name = match[2] ?? '';
|
|
1215
|
+
if (name && SKIP_PATTERNS.some(pattern => pattern.test(name))) continue;
|
|
1216
|
+
if (!INTERACTIVE_ROLES.has(role)) continue;
|
|
1217
|
+
const key = `${role}:${name}`;
|
|
1218
|
+
const nth = frameSeen.get(key) ?? 0;
|
|
1219
|
+
frameSeen.set(key, nth + 1);
|
|
1220
|
+
const id = `e${nextCounter++}`;
|
|
1221
|
+
const ref: BrowserRef = { role, name, nth, frameUrl, ...(frameName ? { frameName } : {}) };
|
|
1222
|
+
frameRefs.set(id, ref);
|
|
1223
|
+
allRefs.set(id, ref);
|
|
1224
|
+
}
|
|
1225
|
+
if (frameRefs.size > 0) {
|
|
1226
|
+
const queues = new Map<string, string[]>();
|
|
1227
|
+
for (const [id, ref] of frameRefs) {
|
|
1228
|
+
const key = `${ref.role}:${ref.name}`;
|
|
1229
|
+
queues.set(key, [...(queues.get(key) ?? []), id]);
|
|
1230
|
+
}
|
|
1231
|
+
const annotatedFrame = String(frameYaml).split('\n').map(line => {
|
|
1232
|
+
const match = line.match(/^(\s*-\s+)([a-z][\w-]*)(?:\s+"([^"]*)")?/i);
|
|
1233
|
+
if (!match) return line;
|
|
1234
|
+
const name = match[3] ?? '';
|
|
1235
|
+
const key = `${(match[2] ?? '').toLowerCase()}:${name}`;
|
|
1236
|
+
const id = queues.get(key)?.shift();
|
|
1237
|
+
return id ? `${line} [${id}]` : line;
|
|
1238
|
+
}).join('\n');
|
|
1239
|
+
annotatedParts.push(`\n--- iframe: ${frameName || frameUrl} ---\n${annotatedFrame}`);
|
|
1240
|
+
}
|
|
1241
|
+
} catch {
|
|
1242
|
+
// Cross-origin or detached iframe; skip gracefully
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
} catch {
|
|
1246
|
+
// Ignore frame enumeration errors
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
const structure = await extractPageStructure(state.page);
|
|
1251
|
+
if (structure) {
|
|
1252
|
+
attachStructureRefs(structure, allRefs);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
state.refs = allRefs;
|
|
1256
|
+
state.lastSnapshot = annotatedParts.join('\n');
|
|
1257
|
+
state.lastStructure = structure;
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
private resolveTargetUrl(action: BrowserAction): { targetUrl: string; macroName?: string; macroQuery?: string } {
|
|
1261
|
+
if (action.macro) {
|
|
1262
|
+
const expanded = expandSearchMacro(action.macro, action.query ?? action.text ?? '');
|
|
1263
|
+
if (!expanded) {
|
|
1264
|
+
throw new Error(`Unsupported search macro: ${action.macro}. Supported macros: ${getSupportedSearchMacros().join(', ')}`);
|
|
1265
|
+
}
|
|
1266
|
+
return { targetUrl: expanded, macroName: action.macro, macroQuery: action.query ?? action.text ?? '' };
|
|
1267
|
+
}
|
|
1268
|
+
if (action.url && action.url.trim().startsWith('@')) {
|
|
1269
|
+
const trimmed = action.url.trim();
|
|
1270
|
+
const spaceIdx = trimmed.indexOf(' ');
|
|
1271
|
+
const macroName = spaceIdx === -1 ? trimmed : trimmed.slice(0, spaceIdx);
|
|
1272
|
+
const inlineQuery = spaceIdx === -1 ? (action.query ?? action.text ?? '') : trimmed.slice(spaceIdx + 1).trim();
|
|
1273
|
+
const expanded = expandSearchMacro(macroName, inlineQuery);
|
|
1274
|
+
if (expanded) {
|
|
1275
|
+
return { targetUrl: expanded, macroName, macroQuery: inlineQuery };
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
if (!action.url) throw new Error(`${action.type} requires url or macro`);
|
|
1279
|
+
return { targetUrl: action.url };
|
|
1280
|
+
}
|
|
1281
|
+
|
|
426
1282
|
private async navigate(state: TabState, value: string): Promise<void> {
|
|
427
1283
|
const url = await this.validateUrl(value);
|
|
428
1284
|
const response = await state.page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
@@ -432,27 +1288,245 @@ export class CausyneBrowser {
|
|
|
432
1288
|
await this.validateUrl(state.page.url());
|
|
433
1289
|
state.refs.clear();
|
|
434
1290
|
state.lastSnapshot = '';
|
|
1291
|
+
state.lastStructure = null;
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
private async navigateWithMacroFallback(state: TabState, action: BrowserAction): Promise<void> {
|
|
1295
|
+
const { targetUrl, macroName, macroQuery } = this.resolveTargetUrl(action);
|
|
1296
|
+
if (macroName === '@google_search' && macroQuery) {
|
|
1297
|
+
const fallbacks = [
|
|
1298
|
+
targetUrl,
|
|
1299
|
+
`https://duckduckgo.com/html/?q=${encodeURIComponent(macroQuery)}`,
|
|
1300
|
+
`https://www.bing.com/search?q=${encodeURIComponent(macroQuery)}`
|
|
1301
|
+
];
|
|
1302
|
+
let lastError: unknown = null;
|
|
1303
|
+
for (let i = 0; i < fallbacks.length; i++) {
|
|
1304
|
+
try {
|
|
1305
|
+
await this.navigate(state, fallbacks[i]!);
|
|
1306
|
+
if (i === 0) {
|
|
1307
|
+
await state.page.waitForTimeout(200);
|
|
1308
|
+
const extracted = await state.page.evaluate<unknown[]>(SEARCH_EXTRACT_SCRIPT).catch(() => []);
|
|
1309
|
+
if (Array.isArray(extracted) && extracted.length === 0) {
|
|
1310
|
+
const currentUrl = state.page.url();
|
|
1311
|
+
if (/google\.[^/]+\/sorry/i.test(currentUrl)) {
|
|
1312
|
+
continue;
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
return;
|
|
1317
|
+
} catch (error) {
|
|
1318
|
+
lastError = error;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
if (lastError) throw lastError;
|
|
1322
|
+
return;
|
|
1323
|
+
}
|
|
1324
|
+
await this.navigate(state, targetUrl);
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
private resolveRefFrame(state: TabState, ref: BrowserRef): BrowserPage | BrowserFrame {
|
|
1328
|
+
if (!ref.frameName && !ref.frameUrl) return state.page;
|
|
1329
|
+
try {
|
|
1330
|
+
if (ref.frameName && typeof state.page.frame === 'function') {
|
|
1331
|
+
const byName = state.page.frame({ name: ref.frameName });
|
|
1332
|
+
if (byName) return byName;
|
|
1333
|
+
}
|
|
1334
|
+
if (ref.frameUrl && typeof state.page.frames === 'function') {
|
|
1335
|
+
const exact = state.page.frames().find(f => f.url() === ref.frameUrl);
|
|
1336
|
+
if (exact) return exact;
|
|
1337
|
+
const prefix = ref.frameUrl.split('?')[0] ?? '';
|
|
1338
|
+
if (prefix) {
|
|
1339
|
+
const byPrefix = state.page.frames().find(f => f.url().startsWith(prefix));
|
|
1340
|
+
if (byPrefix) return byPrefix;
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
} catch {
|
|
1344
|
+
// Fall back to main page
|
|
1345
|
+
}
|
|
1346
|
+
return state.page;
|
|
435
1347
|
}
|
|
436
1348
|
|
|
437
|
-
private locatorFor(state: TabState, action: BrowserAction): BrowserLocator {
|
|
1349
|
+
private async locatorFor(state: TabState, action: BrowserAction): Promise<BrowserLocator> {
|
|
438
1350
|
const refId = action.ref ?? (action.index !== undefined ? `e${action.index}` : undefined);
|
|
439
1351
|
if (refId) {
|
|
440
|
-
|
|
1352
|
+
let ref = state.refs.get(refId);
|
|
1353
|
+
if (!ref && state.refs.size === 0) {
|
|
1354
|
+
await this.captureSnapshotState(state).catch(() => {});
|
|
1355
|
+
ref = state.refs.get(refId);
|
|
1356
|
+
}
|
|
441
1357
|
if (!ref) throw new Error(`Unknown element ref ${refId}. Take a new snapshot before interacting.`);
|
|
442
|
-
|
|
1358
|
+
const target = this.resolveRefFrame(state, ref);
|
|
1359
|
+
return target.getByRole(ref.role, { name: ref.name, exact: true }).nth(ref.nth);
|
|
1360
|
+
}
|
|
1361
|
+
if (action.selector) {
|
|
1362
|
+
const validationErr = selectorValidationError(action.selector);
|
|
1363
|
+
if (validationErr) throw new Error(validationErr);
|
|
1364
|
+
const visibleCandidate = visibleSelectorCandidate(action.selector);
|
|
1365
|
+
if (visibleCandidate) {
|
|
1366
|
+
try {
|
|
1367
|
+
const candidateLocator = state.page.locator(visibleCandidate);
|
|
1368
|
+
if (typeof candidateLocator.count === 'function') {
|
|
1369
|
+
const visibleCount = await candidateLocator.count();
|
|
1370
|
+
if (visibleCount === 1) {
|
|
1371
|
+
return candidateLocator.first();
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
} catch {
|
|
1375
|
+
// Fall back to standard locator
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
return state.page.locator(action.selector).first();
|
|
443
1379
|
}
|
|
444
|
-
if (action.selector) return state.page.locator(action.selector).first();
|
|
445
1380
|
throw new Error(`${action.type} requires a current ref or selector`);
|
|
446
1381
|
}
|
|
447
1382
|
|
|
448
|
-
private async
|
|
1383
|
+
private async assertFillable(locator: BrowserLocator): Promise<void> {
|
|
1384
|
+
if (typeof locator.evaluate !== 'function') return;
|
|
1385
|
+
const check = await locator.evaluate((element: any) => {
|
|
1386
|
+
if (!element || !element.tagName) return { ok: true, reason: '' };
|
|
1387
|
+
const tag = String(element.tagName).toLowerCase();
|
|
1388
|
+
if (tag === 'textarea') return { ok: true, reason: '' };
|
|
1389
|
+
if (tag === 'input') {
|
|
1390
|
+
const inputType = String(element.getAttribute?.('type') || 'text').toLowerCase();
|
|
1391
|
+
const nonFillable = ['button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit'];
|
|
1392
|
+
if (nonFillable.includes(inputType)) {
|
|
1393
|
+
return { ok: false, reason: `Cannot type into <input type="${inputType}">. Use click or selectOption instead.` };
|
|
1394
|
+
}
|
|
1395
|
+
return { ok: true, reason: '' };
|
|
1396
|
+
}
|
|
1397
|
+
if (element.isContentEditable) return { ok: true, reason: '' };
|
|
1398
|
+
const role = String(element.getAttribute?.('role') || '').toLowerCase();
|
|
1399
|
+
if (role === 'textbox' || role === 'searchbox' || role === 'combobox') return { ok: true, reason: '' };
|
|
1400
|
+
return {
|
|
1401
|
+
ok: false,
|
|
1402
|
+
reason: `Target <${tag}> is not an editable input, textarea, or contenteditable element.`
|
|
1403
|
+
};
|
|
1404
|
+
}).catch(() => ({ ok: true, reason: '' }));
|
|
1405
|
+
if (!check.ok) {
|
|
1406
|
+
throw new Error(check.reason);
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
private async performClick(state: TabState, locator: BrowserLocator, doubleClick = false): Promise<void> {
|
|
1411
|
+
if (doubleClick && typeof locator.dblclick === 'function') {
|
|
1412
|
+
await locator.dblclick({ timeout: ACTION_TIMEOUT_MS });
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
try {
|
|
1416
|
+
await locator.click({ timeout: ACTION_TIMEOUT_MS });
|
|
1417
|
+
} catch (clickError) {
|
|
1418
|
+
const msg = errorMessage(clickError);
|
|
1419
|
+
if (msg.includes('intercepts pointer events') || msg.includes('Timeout')) {
|
|
1420
|
+
try {
|
|
1421
|
+
await locator.click({ timeout: 5_000, force: true });
|
|
1422
|
+
return;
|
|
1423
|
+
} catch {
|
|
1424
|
+
if (
|
|
1425
|
+
typeof locator.boundingBox === 'function' &&
|
|
1426
|
+
typeof state.page.mouse.move === 'function' &&
|
|
1427
|
+
typeof state.page.mouse.down === 'function' &&
|
|
1428
|
+
typeof state.page.mouse.up === 'function'
|
|
1429
|
+
) {
|
|
1430
|
+
const box = await locator.boundingBox({ timeout: 2_000 }).catch(() => null);
|
|
1431
|
+
if (box && box.width > 0 && box.height > 0) {
|
|
1432
|
+
const cx = box.x + box.width / 2;
|
|
1433
|
+
const cy = box.y + box.height / 2;
|
|
1434
|
+
await state.page.mouse.move(cx, cy);
|
|
1435
|
+
await state.page.waitForTimeout(30);
|
|
1436
|
+
await state.page.mouse.down();
|
|
1437
|
+
await state.page.waitForTimeout(30);
|
|
1438
|
+
await state.page.mouse.up();
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
throw clickError;
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
private async performType(state: TabState, locator: BrowserLocator, action: BrowserAction): Promise<void> {
|
|
1449
|
+
if (action.text === undefined) throw new Error(`${action.type} requires text`);
|
|
1450
|
+
await this.assertFillable(locator);
|
|
1451
|
+
if (action.mode === 'keyboard' && typeof state.page.keyboard.type === 'function') {
|
|
1452
|
+
await this.performClick(state, locator, false);
|
|
1453
|
+
const delay = Math.max(0, Math.min(500, Number(action.delay ?? 20)));
|
|
1454
|
+
await state.page.keyboard.type(action.text, { delay });
|
|
1455
|
+
} else {
|
|
1456
|
+
await locator.fill(action.text, { timeout: ACTION_TIMEOUT_MS });
|
|
1457
|
+
}
|
|
1458
|
+
if (action.submit || action.pressEnter) {
|
|
1459
|
+
await state.page.keyboard.press('Enter');
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
private async performSelectOption(locator: BrowserLocator, value: string): Promise<void> {
|
|
1464
|
+
try {
|
|
1465
|
+
const selected = await locator.selectOption(value, { timeout: ACTION_TIMEOUT_MS });
|
|
1466
|
+
if (!Array.isArray(selected) || selected.length > 0) return;
|
|
1467
|
+
} catch {
|
|
1468
|
+
// Retry by label
|
|
1469
|
+
}
|
|
1470
|
+
await locator.selectOption({ label: value }, { timeout: ACTION_TIMEOUT_MS });
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
private async performUpload(state: TabState, action: BrowserAction, workspace: string): Promise<BrowserActionResult> {
|
|
1474
|
+
const rawPaths = action.filePath ?? action.value;
|
|
1475
|
+
if (!rawPaths || (Array.isArray(rawPaths) && rawPaths.length === 0)) {
|
|
1476
|
+
throw new Error('upload requires filePath');
|
|
1477
|
+
}
|
|
1478
|
+
const list = Array.isArray(rawPaths) ? rawPaths : [rawPaths];
|
|
1479
|
+
const resolvedFiles: string[] = [];
|
|
1480
|
+
for (const item of list) {
|
|
1481
|
+
const resolved = path.resolve(workspace, String(item));
|
|
1482
|
+
if (!isWithin(workspace, resolved)) {
|
|
1483
|
+
throw new Error('Upload file must stay inside the selected workspace');
|
|
1484
|
+
}
|
|
1485
|
+
const stat = await fs.stat(resolved).catch(() => null);
|
|
1486
|
+
if (!stat || !stat.isFile()) {
|
|
1487
|
+
throw new Error(`Upload file does not exist or is not a regular file: ${resolved}`);
|
|
1488
|
+
}
|
|
1489
|
+
resolvedFiles.push(resolved);
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
const locator = await this.locatorFor(state, action);
|
|
1493
|
+
if (typeof locator.setInputFiles === 'function') {
|
|
1494
|
+
try {
|
|
1495
|
+
await locator.setInputFiles(resolvedFiles, { timeout: ACTION_TIMEOUT_MS });
|
|
1496
|
+
state.refs.clear();
|
|
1497
|
+
return {
|
|
1498
|
+
action: action.type,
|
|
1499
|
+
tabId: state.id,
|
|
1500
|
+
url: state.page.url(),
|
|
1501
|
+
output: `Uploaded ${resolvedFiles.length} file(s)`
|
|
1502
|
+
};
|
|
1503
|
+
} catch {
|
|
1504
|
+
// Fall through to filechooser event
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
const [chooser] = await Promise.all([
|
|
1509
|
+
state.page.waitForEvent('filechooser', { timeout: ACTION_TIMEOUT_MS }) as Promise<BrowserFileChooser>,
|
|
1510
|
+
this.performClick(state, locator, false)
|
|
1511
|
+
]);
|
|
1512
|
+
await chooser.setFiles(resolvedFiles);
|
|
1513
|
+
state.refs.clear();
|
|
1514
|
+
return {
|
|
1515
|
+
action: action.type,
|
|
1516
|
+
tabId: state.id,
|
|
1517
|
+
url: state.page.url(),
|
|
1518
|
+
output: `Uploaded ${resolvedFiles.length} file(s) via file chooser`
|
|
1519
|
+
};
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
private async saveDownload(state: TabState, action: BrowserAction, workspace: string): Promise<BrowserActionResult> {
|
|
449
1523
|
if (!action.outputFile) throw new Error('download requires outputFile');
|
|
450
|
-
const target = path.resolve(
|
|
451
|
-
if (!isWithin(
|
|
452
|
-
const locator = this.locatorFor(state, action);
|
|
1524
|
+
const target = path.resolve(workspace, action.outputFile);
|
|
1525
|
+
if (!isWithin(workspace, target)) throw new Error('Download target must stay inside the selected workspace');
|
|
1526
|
+
const locator = await this.locatorFor(state, action);
|
|
453
1527
|
const [download] = await Promise.all([
|
|
454
|
-
state.page.waitForEvent('download', { timeout: NAVIGATION_TIMEOUT_MS })
|
|
455
|
-
|
|
1528
|
+
state.page.waitForEvent('download', { timeout: NAVIGATION_TIMEOUT_MS }) as Promise<BrowserDownload>,
|
|
1529
|
+
this.performClick(state, locator, false)
|
|
456
1530
|
]);
|
|
457
1531
|
// outputFile is an explicit file destination. Never let a server-selected
|
|
458
1532
|
// filename alter the caller's workspace-scoped target.
|
|
@@ -472,10 +1546,10 @@ export class CausyneBrowser {
|
|
|
472
1546
|
}
|
|
473
1547
|
}
|
|
474
1548
|
|
|
475
|
-
private async saveScreenshot(state: TabState, action: BrowserAction): Promise<BrowserActionResult> {
|
|
1549
|
+
private async saveScreenshot(state: TabState, action: BrowserAction, workspace: string): Promise<BrowserActionResult> {
|
|
476
1550
|
if (!action.outputFile) throw new Error('screenshot requires outputFile');
|
|
477
|
-
const target = path.resolve(
|
|
478
|
-
if (!isWithin(
|
|
1551
|
+
const target = path.resolve(workspace, action.outputFile);
|
|
1552
|
+
if (!isWithin(workspace, target)) throw new Error('Screenshot target must stay inside the selected workspace');
|
|
479
1553
|
const extension = path.extname(target).toLowerCase();
|
|
480
1554
|
if (!['.png', '.jpg', '.jpeg'].includes(extension)) throw new Error('Screenshot outputFile must end in .png, .jpg, or .jpeg');
|
|
481
1555
|
const bytes = await state.page.screenshot({
|
|
@@ -494,22 +1568,27 @@ export class CausyneBrowser {
|
|
|
494
1568
|
}
|
|
495
1569
|
}
|
|
496
1570
|
|
|
497
|
-
private async runAction(action: BrowserAction): Promise<BrowserActionResult> {
|
|
1571
|
+
private async runAction(action: BrowserAction, workspace = this.workspace): Promise<BrowserActionResult> {
|
|
498
1572
|
if (!action || typeof action.type !== 'string') throw new Error('Every browser action needs a type');
|
|
499
|
-
if (action.type === 'newTab') {
|
|
500
|
-
const
|
|
1573
|
+
if (action.type === 'newTab' || action.type === 'new_tab') {
|
|
1574
|
+
const initialUrl = action.macro
|
|
1575
|
+
? (expandSearchMacro(action.macro, action.query ?? action.text ?? '') ?? undefined)
|
|
1576
|
+
: action.url;
|
|
1577
|
+
const state = await this.createTab(initialUrl);
|
|
501
1578
|
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
|
|
502
1579
|
}
|
|
503
|
-
if (action.type === 'listTabs') {
|
|
504
|
-
const data = await Promise.all([...this.tabs.values()].filter(tab => !tab.page.isClosed()).map(async tab => ({
|
|
1580
|
+
if (action.type === 'listTabs' || action.type === 'list_tabs') {
|
|
1581
|
+
const data = await Promise.all([...this.tabs.values()].filter(tab => !tab.page.isClosed() && !tab.crashed).map(async tab => ({
|
|
505
1582
|
tabId: tab.id, active: tab.id === this.activeTabId, url: tab.page.url(), title: await tab.page.title()
|
|
506
1583
|
})));
|
|
507
1584
|
return { action: action.type, data };
|
|
508
1585
|
}
|
|
509
1586
|
const requested = this.requestedTab(action);
|
|
510
1587
|
const state = requested ?? await this.activeTab();
|
|
511
|
-
if (action.type === 'switchTab'
|
|
512
|
-
|
|
1588
|
+
if (action.type === 'switchTab' || action.type === 'switch_tab') {
|
|
1589
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
|
|
1590
|
+
}
|
|
1591
|
+
if (action.type === 'closeTab' || action.type === 'close_tab') {
|
|
513
1592
|
await state.page.close();
|
|
514
1593
|
this.tabs.delete(state.id);
|
|
515
1594
|
if (this.activeTabId === state.id) this.activeTabId = null;
|
|
@@ -520,36 +1599,59 @@ export class CausyneBrowser {
|
|
|
520
1599
|
const active = await this.activeTab();
|
|
521
1600
|
return { action: action.type, tabId: active.id, url: active.page.url(), data: results };
|
|
522
1601
|
}
|
|
523
|
-
if (action.type === 'goto') {
|
|
524
|
-
|
|
525
|
-
await this.navigate(state, action.url);
|
|
1602
|
+
if (action.type === 'goto' || action.type === 'open' || action.type === 'navigate') {
|
|
1603
|
+
await this.navigateWithMacroFallback(state, action);
|
|
526
1604
|
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
|
|
527
1605
|
}
|
|
528
1606
|
if (action.type === 'snapshot' || action.type === 'scrape') {
|
|
529
1607
|
const snapshot = await this.snapshot(action.offset ?? 0);
|
|
530
|
-
return {
|
|
531
|
-
|
|
532
|
-
|
|
1608
|
+
return {
|
|
1609
|
+
action: action.type,
|
|
1610
|
+
tabId: snapshot.tabId,
|
|
1611
|
+
url: snapshot.url,
|
|
1612
|
+
title: snapshot.title,
|
|
1613
|
+
output: snapshot.text,
|
|
1614
|
+
...(snapshot.structure ? { structure: snapshot.structure } : {}),
|
|
1615
|
+
data: {
|
|
1616
|
+
refsCount: snapshot.refsCount,
|
|
1617
|
+
truncated: snapshot.truncated,
|
|
1618
|
+
totalChars: snapshot.totalChars,
|
|
1619
|
+
nextOffset: snapshot.nextOffset,
|
|
1620
|
+
...(snapshot.structure ? { structure: snapshot.structure } : {})
|
|
1621
|
+
}
|
|
1622
|
+
};
|
|
533
1623
|
}
|
|
534
1624
|
if (action.type === 'click' || action.type === 'clickIndex') {
|
|
535
|
-
await this.locatorFor(state, action)
|
|
1625
|
+
const locator = await this.locatorFor(state, action);
|
|
1626
|
+
await this.performClick(state, locator, Boolean(action.doubleClick));
|
|
536
1627
|
state.refs.clear();
|
|
537
1628
|
return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Element clicked' };
|
|
538
1629
|
}
|
|
539
|
-
if (action.type === '
|
|
540
|
-
|
|
541
|
-
|
|
1630
|
+
if (action.type === 'hover') {
|
|
1631
|
+
const locator = await this.locatorFor(state, action);
|
|
1632
|
+
if (typeof locator.hover === 'function') {
|
|
1633
|
+
await locator.hover({ timeout: ACTION_TIMEOUT_MS });
|
|
1634
|
+
} else {
|
|
1635
|
+
await this.performClick(state, locator, false);
|
|
1636
|
+
}
|
|
1637
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Element hovered' };
|
|
1638
|
+
}
|
|
1639
|
+
if (action.type === 'type' || action.type === 'typeIndex' || action.type === 'fill') {
|
|
1640
|
+
const locator = await this.locatorFor(state, action);
|
|
1641
|
+
await this.performType(state, locator, action);
|
|
542
1642
|
return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Text entered' };
|
|
543
1643
|
}
|
|
544
|
-
if (action.type === 'selectOption') {
|
|
545
|
-
const value = action.value ?? action.text;
|
|
546
|
-
if (value === undefined) throw new Error(
|
|
547
|
-
await this.locatorFor(state, action)
|
|
1644
|
+
if (action.type === 'selectOption' || action.type === 'select') {
|
|
1645
|
+
const value = action.value ?? action.option ?? action.text;
|
|
1646
|
+
if (value === undefined) throw new Error(`${action.type} requires value`);
|
|
1647
|
+
const locator = await this.locatorFor(state, action);
|
|
1648
|
+
await this.performSelectOption(locator, value);
|
|
548
1649
|
return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Option selected' };
|
|
549
1650
|
}
|
|
550
|
-
if (action.type === 'keyPress') {
|
|
551
|
-
|
|
552
|
-
|
|
1651
|
+
if (action.type === 'keyPress' || action.type === 'press') {
|
|
1652
|
+
const normalizedKey = normalizeBrowserKey(action.key ?? 'Enter');
|
|
1653
|
+
await state.page.keyboard.press(normalizedKey);
|
|
1654
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), output: `Pressed ${normalizedKey}` };
|
|
553
1655
|
}
|
|
554
1656
|
if (action.type === 'scroll') {
|
|
555
1657
|
const amount = Math.max(1, Math.min(10_000, Math.floor(action.amount ?? 700)));
|
|
@@ -559,16 +1661,101 @@ export class CausyneBrowser {
|
|
|
559
1661
|
await state.page.mouse.wheel(x, y);
|
|
560
1662
|
return { action: action.type, tabId: state.id, url: state.page.url(), output: `Scrolled ${direction} ${amount}px` };
|
|
561
1663
|
}
|
|
562
|
-
if (action.type === '
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
1664
|
+
if (action.type === 'wait') {
|
|
1665
|
+
const waitTimeout = Math.max(50, Math.min(30_000, Number(action.timeout ?? action.amount ?? 1_000)));
|
|
1666
|
+
if (action.selector) {
|
|
1667
|
+
const validationErr = selectorValidationError(action.selector);
|
|
1668
|
+
if (validationErr) throw new Error(validationErr);
|
|
1669
|
+
if (typeof state.page.waitForSelector === 'function') {
|
|
1670
|
+
await state.page.waitForSelector(action.selector, { timeout: waitTimeout });
|
|
1671
|
+
} else {
|
|
1672
|
+
const loc = state.page.locator(action.selector).first();
|
|
1673
|
+
if (typeof loc.waitFor === 'function') {
|
|
1674
|
+
await loc.waitFor({ timeout: waitTimeout });
|
|
1675
|
+
} else {
|
|
1676
|
+
await state.page.waitForTimeout(waitTimeout);
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
} else {
|
|
1680
|
+
if (action.waitForNetwork) {
|
|
1681
|
+
await state.page.waitForLoadState('networkidle', { timeout: waitTimeout }).catch(() => {});
|
|
1682
|
+
}
|
|
1683
|
+
await state.page.evaluate(WAIT_FOR_PAGE_READY_SCRIPT).catch(() => {});
|
|
1684
|
+
await state.page.waitForTimeout(Math.min(waitTimeout, 2_000));
|
|
1685
|
+
}
|
|
1686
|
+
if (action.dismissConsent) {
|
|
1687
|
+
await state.page.evaluate(DISMISS_CONSENT_SCRIPT).catch(() => false);
|
|
1688
|
+
}
|
|
1689
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Wait completed' };
|
|
1690
|
+
}
|
|
1691
|
+
if (action.type === 'viewport') {
|
|
1692
|
+
const width = Math.floor(Number(action.width ?? 1280));
|
|
1693
|
+
const height = Math.floor(Number(action.height ?? 800));
|
|
1694
|
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width < 100 || width > 4000 || height < 100 || height > 4000) {
|
|
1695
|
+
throw new Error('viewport width and height must be between 100 and 4000 pixels');
|
|
1696
|
+
}
|
|
1697
|
+
if (typeof state.page.setViewportSize === 'function') {
|
|
1698
|
+
await state.page.setViewportSize({ width, height });
|
|
1699
|
+
}
|
|
1700
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), output: `Viewport set to ${width}x${height}` };
|
|
1701
|
+
}
|
|
1702
|
+
if (action.type === 'back') {
|
|
1703
|
+
try {
|
|
1704
|
+
await state.page.goBack({ waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
1705
|
+
} catch (error) {
|
|
1706
|
+
if (!errorMessage(error).includes('NS_BINDING_CANCELLED')) throw error;
|
|
1707
|
+
}
|
|
1708
|
+
} else if (action.type === 'forward') {
|
|
1709
|
+
try {
|
|
1710
|
+
await state.page.goForward({ waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
1711
|
+
} catch (error) {
|
|
1712
|
+
if (!errorMessage(error).includes('NS_BINDING_CANCELLED')) throw error;
|
|
1713
|
+
}
|
|
1714
|
+
} else if (action.type === 'reload' || action.type === 'refresh') {
|
|
1715
|
+
await state.page.reload({ waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
1716
|
+
} else if (action.type === 'extract') {
|
|
1717
|
+
if (action.schema) {
|
|
1718
|
+
const check = validateExtractSchema(action.schema);
|
|
1719
|
+
if (!check.ok) throw new Error(`Invalid extract schema: ${check.error}`);
|
|
1720
|
+
if (state.refs.size === 0) {
|
|
1721
|
+
await this.captureSnapshotState(state);
|
|
1722
|
+
}
|
|
1723
|
+
const extracted = extractDeterministic({ schema: action.schema, refs: state.refs });
|
|
1724
|
+
return {
|
|
1725
|
+
action: action.type,
|
|
1726
|
+
tabId: state.id,
|
|
1727
|
+
url: state.page.url(),
|
|
1728
|
+
output: JSON.stringify(extracted),
|
|
1729
|
+
data: extracted
|
|
1730
|
+
};
|
|
1731
|
+
}
|
|
566
1732
|
const selector = action.selector ?? 'body';
|
|
1733
|
+
const validationErr = selectorValidationError(selector);
|
|
1734
|
+
if (validationErr) throw new Error(validationErr);
|
|
567
1735
|
const output = boundedText(await state.page.locator(selector).first().innerText({ timeout: ACTION_TIMEOUT_MS }));
|
|
568
1736
|
return { action: action.type, tabId: state.id, url: state.page.url(), output };
|
|
569
|
-
} else if (action.type === '
|
|
570
|
-
|
|
571
|
-
|
|
1737
|
+
} else if (action.type === 'links') {
|
|
1738
|
+
if (action.selector) {
|
|
1739
|
+
const validationErr = selectorValidationError(action.selector);
|
|
1740
|
+
if (validationErr) throw new Error(validationErr);
|
|
1741
|
+
}
|
|
1742
|
+
const data = await state.page.evaluate(
|
|
1743
|
+
LINKS_EXTRACT_SCRIPT,
|
|
1744
|
+
{ selector: action.selector, offset: action.offset ?? 0, limit: action.limit ?? 50 }
|
|
1745
|
+
);
|
|
1746
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), data };
|
|
1747
|
+
} else if (action.type === 'images') {
|
|
1748
|
+
const data = await state.page.evaluate(IMAGES_EXTRACT_SCRIPT, { limit: action.limit ?? 100 });
|
|
1749
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), data };
|
|
1750
|
+
} else if (action.type === 'upload') {
|
|
1751
|
+
return this.performUpload(state, action, workspace);
|
|
1752
|
+
} else if (action.type === 'download') {
|
|
1753
|
+
return this.saveDownload(state, action, workspace);
|
|
1754
|
+
} else if (action.type === 'screenshot') {
|
|
1755
|
+
return this.saveScreenshot(state, action, workspace);
|
|
1756
|
+
} else {
|
|
1757
|
+
throw new Error(`Unsupported browser action: ${action.type}`);
|
|
1758
|
+
}
|
|
572
1759
|
state.refs.clear();
|
|
573
1760
|
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
|
|
574
1761
|
}
|
|
@@ -582,8 +1769,11 @@ export class CausyneBrowser {
|
|
|
582
1769
|
|
|
583
1770
|
let sharedBrowser: CausyneBrowser | null = null;
|
|
584
1771
|
|
|
585
|
-
export function causyneBrowser(): CausyneBrowser {
|
|
586
|
-
sharedBrowser ??= new CausyneBrowser();
|
|
1772
|
+
export function causyneBrowser(options?: { workspace?: string }): CausyneBrowser {
|
|
1773
|
+
sharedBrowser ??= new CausyneBrowser(options);
|
|
1774
|
+
if (options?.workspace) {
|
|
1775
|
+
sharedBrowser.setWorkspace(options.workspace);
|
|
1776
|
+
}
|
|
587
1777
|
return sharedBrowser;
|
|
588
1778
|
}
|
|
589
1779
|
|
|
@@ -592,3 +1782,81 @@ export async function closeCausyneBrowser(): Promise<void> {
|
|
|
592
1782
|
sharedBrowser = null;
|
|
593
1783
|
if (browser) await browser.close();
|
|
594
1784
|
}
|
|
1785
|
+
|
|
1786
|
+
export interface BrowserSandboxValidationResult {
|
|
1787
|
+
allowed: boolean;
|
|
1788
|
+
risk: 'safe' | 'moderate' | 'dangerous' | 'extreme' | 'forbidden';
|
|
1789
|
+
reason?: string;
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
const INTERACTIVE_BROWSER_ACTIONS = new Set([
|
|
1793
|
+
'click', 'clickIndex',
|
|
1794
|
+
'type', 'typeIndex', 'fill',
|
|
1795
|
+
'selectOption', 'select',
|
|
1796
|
+
'keyPress', 'press',
|
|
1797
|
+
'hover',
|
|
1798
|
+
'upload'
|
|
1799
|
+
]);
|
|
1800
|
+
|
|
1801
|
+
export function validateBrowserActSandbox(
|
|
1802
|
+
args: Record<string, unknown> | undefined,
|
|
1803
|
+
workspaceRoot: string,
|
|
1804
|
+
isInternalUrl: (url: string) => boolean,
|
|
1805
|
+
isPathAllowed: (resolvedPath: string) => boolean
|
|
1806
|
+
): BrowserSandboxValidationResult {
|
|
1807
|
+
const actions = Array.isArray(args?.actions) ? (args.actions as Array<Record<string, unknown>>) : [];
|
|
1808
|
+
let hasDownload = false;
|
|
1809
|
+
for (const action of actions) {
|
|
1810
|
+
if (!action || typeof action !== 'object') continue;
|
|
1811
|
+
const rawUrl = typeof action.url === 'string' ? action.url.trim() : '';
|
|
1812
|
+
const rawMacro = typeof action.macro === 'string' ? action.macro.trim() : '';
|
|
1813
|
+
if (rawMacro) {
|
|
1814
|
+
const expanded = expandSearchMacro(rawMacro, typeof action.query === 'string' ? action.query : '');
|
|
1815
|
+
if (!expanded || isInternalUrl(expanded)) {
|
|
1816
|
+
return { allowed: false, reason: 'Cannot navigate the agent browser to an internal or invalid URL', risk: 'forbidden' };
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
if (rawUrl) {
|
|
1820
|
+
let urlToCheck = rawUrl;
|
|
1821
|
+
if (rawUrl.startsWith('@')) {
|
|
1822
|
+
const spaceIdx = rawUrl.indexOf(' ');
|
|
1823
|
+
const macroName = spaceIdx === -1 ? rawUrl : rawUrl.slice(0, spaceIdx);
|
|
1824
|
+
const query = spaceIdx === -1 ? (typeof action.query === 'string' ? action.query : '') : rawUrl.slice(spaceIdx + 1).trim();
|
|
1825
|
+
const expanded = expandSearchMacro(macroName, query);
|
|
1826
|
+
if (!expanded) {
|
|
1827
|
+
return { allowed: false, reason: 'Cannot navigate the agent browser to an internal or invalid URL', risk: 'forbidden' };
|
|
1828
|
+
}
|
|
1829
|
+
urlToCheck = expanded;
|
|
1830
|
+
}
|
|
1831
|
+
if (isInternalUrl(urlToCheck)) {
|
|
1832
|
+
return { allowed: false, reason: 'Cannot navigate the agent browser to an internal or invalid URL', risk: 'forbidden' };
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
if (action.type === 'download' || action.type === 'screenshot') {
|
|
1836
|
+
const out = typeof action.outputFile === 'string' ? action.outputFile : '';
|
|
1837
|
+
if (!out || !isPathAllowed(path.resolve(workspaceRoot, out))) {
|
|
1838
|
+
return { allowed: false, reason: 'Browser downloads must stay inside the selected workspace', risk: 'forbidden' };
|
|
1839
|
+
}
|
|
1840
|
+
hasDownload = true;
|
|
1841
|
+
}
|
|
1842
|
+
if (action.type === 'upload') {
|
|
1843
|
+
const rawPaths = action.filePath ?? action.value;
|
|
1844
|
+
const list = Array.isArray(rawPaths) ? rawPaths : rawPaths ? [rawPaths] : [];
|
|
1845
|
+
if (list.length === 0) {
|
|
1846
|
+
return { allowed: false, reason: 'Browser uploads must specify a file inside the selected workspace', risk: 'forbidden' };
|
|
1847
|
+
}
|
|
1848
|
+
for (const item of list) {
|
|
1849
|
+
if (typeof item !== 'string' || !item || !isPathAllowed(path.resolve(workspaceRoot, item))) {
|
|
1850
|
+
return { allowed: false, reason: 'Browser uploads must stay inside the selected workspace', risk: 'forbidden' };
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
if (hasDownload) {
|
|
1856
|
+
return { allowed: true, risk: 'extreme', reason: 'Writes browser content to the selected workspace' };
|
|
1857
|
+
}
|
|
1858
|
+
if (actions.some(action => typeof action?.type === 'string' && INTERACTIVE_BROWSER_ACTIONS.has(action.type))) {
|
|
1859
|
+
return { allowed: true, risk: 'dangerous', reason: 'Interacts with a website through the dedicated agent browser' };
|
|
1860
|
+
}
|
|
1861
|
+
return { allowed: true, risk: 'safe' };
|
|
1862
|
+
}
|