@myrialabs/clopen 0.4.21 → 0.4.22

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 (86) hide show
  1. package/README.md +2 -1
  2. package/backend/artifacts/generate.ts +11 -5
  3. package/backend/auth/permissions.ts +8 -8
  4. package/backend/engine/README.md +11 -8
  5. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  6. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  7. package/backend/engine/docs/adapter-contract.md +66 -2
  8. package/backend/engine/docs/adding-an-engine.md +46 -7
  9. package/backend/engine/docs/frontend-and-chat.md +80 -17
  10. package/backend/engine/docs/lessons-learned.md +126 -7
  11. package/backend/engine/docs/quick-reference.md +12 -3
  12. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  13. package/backend/engine/docs/websocket-routes.md +54 -15
  14. package/backend/engine/install-runner.ts +4 -4
  15. package/backend/engine/resolve-model.ts +87 -0
  16. package/backend/engine/structured-helpers.test.ts +64 -0
  17. package/backend/engine/structured-helpers.ts +105 -13
  18. package/backend/mcp/README.md +32 -11
  19. package/backend/mcp/internal/config.ts +3 -20
  20. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  21. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  22. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  23. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  24. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  25. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  26. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  27. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +146 -0
  28. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +63 -0
  29. package/backend/mcp/internal/servers/browser-automation/context.ts +82 -0
  30. package/backend/mcp/internal/servers/browser-automation/description.ts +59 -0
  31. package/backend/mcp/internal/servers/browser-automation/format.ts +56 -0
  32. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  33. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  34. package/backend/mcp/internal/servers/browser-automation/runner.ts +260 -0
  35. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  36. package/backend/preview/browser/browser-console-manager.ts +310 -156
  37. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  38. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  39. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  40. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  41. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  42. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  43. package/backend/preview/browser/browser-pool.ts +83 -9
  44. package/backend/preview/browser/browser-preview-service.ts +432 -53
  45. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  46. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  47. package/backend/preview/browser/capture-profile.ts +213 -0
  48. package/backend/preview/browser/element-locator.ts +357 -0
  49. package/backend/preview/browser/frame-targeting.ts +92 -0
  50. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  51. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  52. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  53. package/backend/preview/browser/types.ts +397 -37
  54. package/backend/utils/cli.ts +1 -1
  55. package/backend/utils/path-enrich.ts +2 -2
  56. package/backend/ws/README.md +1 -1
  57. package/backend/ws/artifacts/generate.ts +2 -1
  58. package/backend/ws/engine/codex/accounts.ts +1 -1
  59. package/backend/ws/engine/codex/status.ts +1 -1
  60. package/backend/ws/git/branch-name.ts +11 -5
  61. package/backend/ws/git/commit-message.ts +11 -5
  62. package/backend/ws/index.ts +3 -3
  63. package/backend/ws/preview/browser/host.ts +95 -0
  64. package/backend/ws/preview/browser/interact.ts +204 -10
  65. package/backend/ws/preview/browser/native-ui.ts +31 -1
  66. package/backend/ws/preview/browser/tab-info.ts +10 -1
  67. package/backend/ws/preview/browser/tab.ts +43 -0
  68. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  69. package/backend/ws/preview/index.ts +58 -1
  70. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  71. package/backend/ws/stack/index.ts +16 -0
  72. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  73. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  74. package/dist/assets/{index-CEGW8vEt.js → index-DH_GO0Lf.js} +1 -1
  75. package/dist/assets/{index-B8YRz8wG.js → index-igSQ3JaM.js} +1 -1
  76. package/dist/assets/main-BD3-qPfT.css +1 -0
  77. package/dist/assets/{main-D-2ByODy.js → main-D-d8SFfW.js} +384 -358
  78. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  79. package/dist/index.html +2 -2
  80. package/package.json +1 -1
  81. package/shared/types/stores/settings.ts +6 -0
  82. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  83. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  84. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  85. package/backend/ws/system-tools/index.ts +0 -16
  86. package/dist/assets/main-D8I0MfRQ.css +0 -1
@@ -1,793 +1,45 @@
1
1
  /**
2
- * Browser Automation - Custom MCP Server
2
+ * Browser Automation — internal MCP server.
3
3
  *
4
- * Provides comprehensive browser automation tools for AI-driven testing and exploration.
4
+ * One tool. Every capability is an action inside it, so the agent decides what
5
+ * to run and how much to run at once, and a whole interaction can be a single
6
+ * call instead of a round trip per click.
5
7
  */
6
8
 
7
- import { z } from "zod";
8
- import { defineServer } from "../helper";
9
-
10
- // Import handlers
11
- import { listTabsHandler, switchTabHandler, openNewTabHandler, closeTabHandler, navigateHandler, setViewportHandler } from "./browser";
12
- import { actionsHandler } from "./actions";
13
- import { getConsoleLogsHandler, clearConsoleLogsHandler, executeConsoleHandler, takeScreenshotHandler, analyzeDomHandler } from "./inspection";
9
+ import { defineServer } from '../helper';
10
+ import { actionsToolDescription } from './description';
11
+ import { actionsToolSchema } from './schema';
12
+ import { runActions } from './runner';
13
+ import { formatReport } from './format';
14
14
 
15
15
  export default defineServer({
16
- name: "browser-automation",
17
- title: "Browser Automation",
18
- description: "Drives the built-in Preview Browser panel — navigate, click, type, and inspect pages, running multiple actions in one call for efficient interaction.",
19
- version: "1.0.0",
16
+ name: 'browser-automation',
17
+ title: 'Browser Automation',
18
+ description:
19
+ 'Drives the built-in Preview Browser — navigate, click, type, drag, swipe and inspect pages, batching whole interactions into a single call.',
20
+ version: '2.0.0',
20
21
  tools: {
21
- // ============================================================================
22
- // Browser Tab Management
23
- // ============================================================================
24
- "list_tabs": {
25
- description: `List all open browser tabs with metadata.
26
-
27
- WHEN TO USE:
28
- - Start of session to see available tabs
29
- - Before switching tabs
30
- - Verify tab state after open/close operations
31
-
32
- OUTPUT: Formatted text with tab index, ID, title, URL, and active indicator (*). Example:
33
- [1] tab-abc123 * Google Search - https://google.com
34
- [2] tab-def456 Calculator - https://calculator.net
35
-
36
- Use exact tab ID from output with switch_tab or close_tab - not the index number.`,
37
- handler: listTabsHandler
38
- },
39
-
40
- "switch_tab": {
41
- description: `Switch browser focus to different tab.
42
-
43
- WHEN TO USE:
44
- - Multi-tab workflows
45
- - Comparing content across tabs
46
- - Managing multiple sessions
47
-
48
- OUTPUT: Confirmation with switched tab's ID, title, and URL.
49
-
50
- Tab ID must be obtained from list_tabs. After switching, previous tab's context is lost - take new screenshot or analyze_dom if needed.`,
51
- schema: {
52
- tabId: z.string().min(1).describe("Tab ID obtained from list_tabs output (e.g., 'tab-abc123')")
53
- },
54
- handler: switchTabHandler
55
- },
56
-
57
- "open_new_tab": {
58
- description: `Create new browser tab with optional URL and viewport configuration.
59
-
60
- WHEN TO USE:
61
- - Starting fresh session
62
- - Opening multiple pages for comparison
63
- - Separating workflows
64
- - Testing risky actions in isolation
65
- - Testing responsive designs across devices
66
-
67
- OUTPUT: Tab ID, title, and URL of newly created tab. New tab automatically becomes active.
68
-
69
- Automatically creates session. New tab is immediately active - no need to switch_tab. If URL provided, waits for page load.
70
-
71
- VIEWPORT MODES:
72
- - desktop: 1920x1080 (default rotation: landscape) - For testing full desktop layouts
73
- - laptop: 1440x900 (default, default rotation: landscape) - Modern 14" laptop viewport
74
- - tablet: 834x1194 (default rotation: portrait) - iPad Pro 11" class viewport
75
- - mobile: 402x874 (default rotation: portrait) - iPhone 16 / modern flagship viewport
76
-
77
- ROTATION:
78
- - portrait: Standard vertical orientation (default for tablet/mobile)
79
- - landscape: Horizontal orientation (default for desktop/laptop)
80
- - Omit rotation to use device-appropriate default`,
81
- schema: {
82
- url: z.string().url().optional().describe("Initial URL with protocol (http:// or https://). Omit for blank tab."),
83
- deviceSize: z.enum(['desktop', 'laptop', 'tablet', 'mobile']).optional().default('laptop').describe("Viewport device size (default: laptop). Choose based on testing needs."),
84
- rotation: z.enum(['portrait', 'landscape']).optional().describe("Screen orientation. If omitted, uses device-appropriate default: landscape for desktop/laptop, portrait for tablet/mobile.")
85
- },
86
- handler: openNewTabHandler
87
- },
88
-
89
- "close_tab": {
90
- description: `Close tab by ID and cleanup session.
91
-
92
- WHEN TO USE:
93
- - Cleanup after completing task
94
- - Managing memory/resources
95
- - Closing tabs no longer needed
96
-
97
- OUTPUT: Confirmation message. If closed tab was active, automatically switches to another tab and returns new active tab info.
98
-
99
- Cannot close last remaining tab (will error). If tab was active, focus moves to another tab - check list_tabs after.`,
100
- schema: {
101
- tabId: z.string().min(1).describe("Tab ID obtained from list_tabs output (e.g., 'tab-abc123')")
102
- },
103
- handler: closeTabHandler
104
- },
105
-
106
- "set_viewport": {
107
- description: `Change viewport settings (device size and rotation) for active tab.
108
-
109
- WHEN TO USE:
110
- - Testing responsive designs across devices
111
- - Switching between mobile and desktop views
112
- - Testing different screen orientations
113
- - Simulating different device types
114
-
115
- OUTPUT: Confirmation with tab ID and new viewport settings.
116
-
117
- VIEWPORT MODES:
118
- - desktop: 1920x1080 - For testing full desktop layouts
119
- - laptop: 1440x900 - Modern 14" laptop viewport
120
- - tablet: 834x1194 - iPad Pro 11" class viewport
121
- - mobile: 402x874 - iPhone 16 / modern flagship viewport
122
-
123
- ROTATION:
124
- - portrait: Standard vertical orientation
125
- - landscape: Horizontal orientation (width and height swapped)
126
-
127
- The viewport change is applied immediately to the active tab. If testing multiple viewports, consider taking screenshots before and after to compare layouts.`,
128
- schema: {
129
- deviceSize: z.enum(['desktop', 'laptop', 'tablet', 'mobile']).optional().describe("Viewport device size. Omit to keep current device size."),
130
- rotation: z.enum(['portrait', 'landscape']).optional().describe("Screen orientation. Omit to keep current rotation.")
131
- },
132
- handler: setViewportHandler
133
- },
134
-
135
- // ============================================================================
136
- // Navigation
137
- // ============================================================================
138
- "navigate": {
139
- description: `Navigate to URL and wait for page load.
140
-
141
- PRIMARY USE: Following links when you have href URL (more efficient than clicking coordinates).
142
-
143
- WHEN TO USE:
144
- - Following links from analyze_dom.navigation.links (use href directly)
145
- - Moving to known URLs
146
- - Multi-page information extraction workflow
147
- - Refreshing with new parameters
148
-
149
- WHEN TO AVOID:
150
- - Don't have URL (must use take_screenshot + click instead)
151
- - Testing click interactions (use actions for actual click testing)
152
-
153
- EFFICIENT WORKFLOW:
154
-
155
- Information extraction across pages:
156
- → navigate(page1)
157
- → analyze_dom(['navigation', 'content'])
158
- → Find link: {text: "Pricing", href: "https://example.com/pricing"}
159
- → navigate(href) ← USE THIS, not click coordinates!
160
- → analyze_dom(['content'])
161
- → Extract information
162
-
163
- Why navigate > click for links:
164
- - Faster: direct URL navigation
165
- - More reliable: no coordinate dependency
166
- - Cleaner: no need for screenshot
167
- - Better for information tasks
168
-
169
- Example - Multi-page extraction:
170
- Task: "Find pricing at loom.com"
171
- → navigate("https://www.loom.com")
172
- → analyze_dom(['navigation'])
173
- → Found: {text: "Pricing", href: "https://www.loom.com/pricing"}
174
- → navigate("https://www.loom.com/pricing") ← Efficient!
175
- → analyze_dom(['content'])
176
- → Extract pricing info
177
-
178
- OUTPUT: Final URL after all redirects complete.
179
-
180
- After navigate, page is completely new:
181
- - Previous analyze_dom data is invalid - re-run on new page
182
- - Pattern for information: navigate → analyze_dom
183
- - Pattern for interaction: navigate → take_screenshot → actions
184
-
185
- Session state (cookies, localStorage) preserved. Timeout 30 seconds. Handles redirects automatically.`,
186
- schema: {
187
- url: z.string().url().describe("Target URL with protocol (http:// or https://). Redirects handled automatically.")
188
- },
189
- handler: navigateHandler
190
- },
191
-
192
- // ============================================================================
193
- // Browser Actions
194
- // ============================================================================
195
- "actions": {
196
- description: `Execute browser interactions in sequence. Each action completes before next begins.
197
-
198
- MANDATORY PLANNING PROTOCOL:
199
-
200
- BEFORE executing ANY action sequence, you MUST follow this protocol:
201
-
202
- 1. STATE THE GOAL
203
- Write down the exact outcome you want to achieve.
204
- Example: "Enter formula (8 × 5) + (12 ÷ 3) - 7 into calculator"
205
- Example: "Fill login form with username and password, then submit"
206
- Example: "Navigate through multi-step checkout process"
207
-
208
- 2. PLAN THE SEQUENCE
209
- List each action and its expected result/state after execution.
210
- IMPORTANT: Write this planning EVEN for TYPE actions - always document your plan.
211
-
212
- Example (Calculator):
213
- Action 1: Click "(" → Display shows "("
214
- Action 2: Click "8" → Display shows "(8"
215
- Action 3: Click "×" → Display shows "(8×"
216
- Action 4: Click "5" → Display shows "(8×5"
217
- Action 5: Click ")" → Display shows "(8×5)"
218
- Action 6: Click "+" → Display shows "(8×5)+"
219
- ... continue for each step
220
-
221
- Example (Form):
222
- Action 1: Click username field → Field focused
223
- Action 2: Type "user@example.com" → Username entered
224
- Action 3: Click password field → Password field focused
225
- Action 4: Type "password123" → Password entered (hidden)
226
- Action 5: Click submit button → Form submitted
227
-
228
- Example (Calculator with TYPE):
229
- Action 1: Click input field → Field focused
230
- Action 2: Type "(15*8)/(4+2)" → Formula entered
231
- Action 3: Click "=" → Result calculated
232
-
233
- 3. VERIFY THE LOGIC
234
- Trace through the sequence mentally:
235
- - Does each action move toward the goal?
236
- - What is the state after each action?
237
- - Are there dependencies between actions?
238
- - Could any action produce unintended results?
239
- - Is this the most efficient approach?
240
-
241
- 4. EFFICIENT ALTERNATIVES:
242
- Before using click sequences, verify:
243
- - Can I TYPE instead of clicking individual buttons?
244
- - Can I NAVIGATE instead of clicking coordinates?
245
- - Is there a simpler single-action approach?
246
-
247
- PREFER:
248
- - TYPE over click sequence (for formulas, text input)
249
- - NAVIGATE over click coordinates (for links)
250
- - Single action over multiple actions (when possible)
251
-
252
- Example - Calculator:
253
- INCORRECT: Click "(" → "1" → "5" → "×" → "8" → ")" → "/" → "(" → "4" → "+" → "2" → ")" → "=" (13 actions)
254
- CORRECT: If input field exists, type "(15*8)/(4+2)" then click "=" (2 actions)
255
-
256
- 5. EXECUTE ONLY AFTER VERIFICATION
257
- Build the action array only after steps 1-4 are complete and verified.
258
-
259
- 6. VERIFY RESULT AFTER EXECUTION
260
- After complex sequences complete:
261
- - Check if result matches your planned input/goal
262
- - If mismatch detected (e.g., planned sin(45) but got sin(42)):
263
- * Acknowledge: "Planned [X] but result shows [Y]"
264
- * Explain likely cause (wrong coordinate, button misidentification, etc.)
265
- * Decide: Continue with corrected understanding OR re-execute if critical
266
- - For calculator/form tasks, verify the final input/output matches expectation
267
-
268
- This protocol applies to ALL sequential actions: calculators, forms, navigation, games, automation workflows, etc.
269
-
270
- COMMON MISTAKES TO AVOID:
271
-
272
- Mistake: Not closing parentheses/brackets before next operation
273
- Example: Click "√" → "64" → "+" results in √(64+...) instead of √64 +
274
- Fix: Plan to close grouping before continuing: "√" → "64" → ")" → "+"
275
-
276
- Mistake: Wrong order in multi-step forms
277
- Example: Type in all fields → click submits → data goes to wrong inputs
278
- Fix: Click field → type → click next field → type (interleave click and type)
279
-
280
- Mistake: Not verifying state between dependent actions
281
- Example: Click modal button → immediately click behind it → clicks wrong element
282
- Fix: Add wait after modal opens, verify state, then continue
283
-
284
- PURPOSE: Perform user-like actions (clicking, typing, scrolling) for INTERACTION TASKS.
285
-
286
- TASK CLASSIFICATION:
287
-
288
- INTERACTION TASKS (use actions):
289
- - UI testing, automation testing
290
- - Form filling that requires interaction
291
- - Button clicking, element interaction
292
- → Workflow: take_screenshot → PLAN → VERIFY → actions
293
-
294
- INFORMATION TASKS (DON'T use actions for navigation):
295
- - Reading content, extracting information
296
- - Following links to other pages
297
- → Workflow: analyze_dom → navigate (use href, NOT click)
298
-
299
- WHEN TO USE:
300
- - After take_screenshot when you have coordinates
301
- - Clicking buttons, typing in forms, scrolling
302
- - Testing interactions, automating workflows
303
- - Solving obstacles (captcha, modals)
304
-
305
- WHEN TO AVOID:
306
- - Information extraction (use analyze_dom instead)
307
- - Following links to navigate (use navigate with href from analyze_dom, not click coordinates)
308
- - Reading text content (analyze_dom.content is faster)
309
-
310
- COORDINATE SOURCE:
311
-
312
- Coordinates come from AI vision analysis of screenshots, NOT from analyze_dom.
313
-
314
- Process for getting coordinates:
315
- 1. Call take_screenshot to capture current page
316
- 2. Use AI vision to identify element positions in screenshot
317
- 3. Determine pixel coordinates (x, y) from visual analysis
318
- 4. Apply PLANNING PROTOCOL before building actions
319
- 5. Use verified coordinates in actions
320
-
321
- Example - Click "Login" button:
322
- Task: Click button labeled "Login"
323
- → take_screenshot (capture page)
324
- → AI vision: "Login button at x=1200, y=45"
325
- → PLAN: Click button → form appears
326
- → VERIFY: Single click achieves goal
327
- → Execute: {type: "click", x: 1200, y: 45}
328
-
329
- Example - Sequential actions with planning:
330
- Task: Calculate (15 × 8) / (4 + 2) - 3²
331
-
332
- APPROACH A - If input field exists (PREFERRED):
333
- → take_screenshot
334
- → PLAN: Type formula directly, then calculate
335
- → VERIFY: Input field accepts text → yes
336
- → Execute: [
337
- {click input field x:640, y:311},
338
- {type "(15*8)/(4+2)-3^2"},
339
- {click equals x:913, y:479}
340
- ]
341
-
342
- APPROACH B - If must use buttons:
343
- → take_screenshot
344
- → PLAN: Each button click in exact order
345
- "(": x:672,y:320 → display "("
346
- "1": x:672,y:449 → display "(1"
347
- "5": x:730,y:405 → display "(15"
348
- ... (continue for all 15+ buttons)
349
- → VERIFY: Sequence produces correct formula
350
- → Execute: [full button sequence with waits]
351
-
352
- Example - Form filling with planning:
353
- Task: Fill and submit login form
354
- → take_screenshot
355
- → PLAN:
356
- 1. Click username field → focused
357
- 2. Type email → entered
358
- 3. Click password field → focused
359
- 4. Type password → entered (hidden)
360
- 5. Click submit → form submitted
361
- → VERIFY: Each field gets correct data in correct order
362
- → Execute: [
363
- {click x:640, y:300},
364
- {type "user@example.com"},
365
- {click x:640, y:380},
366
- {type "password123"},
367
- {click x:640, y:450}
368
- ]
369
-
370
- ACTION TYPES:
371
-
372
- click {x, y, click?: "left"/"right"/"middle"}
373
- Click at coordinates from screenshot AI vision analysis
374
-
375
- type {text?: "string", key?: "Enter", clearFirst?: true}
376
- text: String to type (click input field first)
377
- key: Special key (Enter, Tab, Escape, Backspace, ArrowUp, ArrowDown, etc)
378
- clearFirst: true (default) removes existing text
379
-
380
- move {x, y, steps?: 1}
381
- Move mouse to coordinates from screenshot (hover effects, tooltips)
382
-
383
- scroll {deltaX?: 0, deltaY: 500}
384
- deltaY positive=down, negative=up
385
-
386
- wait {delay: milliseconds}
387
- Pause between actions (use between dependent actions)
388
-
389
- extract_data {selector: "CSS selector"}
390
- Extract text/value from DOM (use after actions complete)
391
-
392
- OUTPUT:
393
- - Success: "Successfully performed N action(s) in sequence"
394
- - With extraction: Returns extracted text/value
395
- - Error: Descriptive message if action fails
396
-
397
- For complex sequences (>10 actions):
398
- - Consider breaking into smaller batches (5-8 actions per batch)
399
- - Take screenshot between batches to verify partial results
400
- - Adjust if needed before continuing
401
-
402
- Obstacle handling (captcha, modal, popup):
403
- - NEVER stop or ask user - solve automatically
404
- - Workflow: take_screenshot → identify → solve/dismiss → verify → continue
405
- - If fails after attempts: report failure, proceed if possible`,
406
- schema: {
407
- actions: z.array(
408
- z.discriminatedUnion("type", [
409
- z.object({
410
- type: z.literal("click"),
411
- x: z.number().describe("X coordinate from screenshot AI vision"),
412
- y: z.number().describe("Y coordinate from screenshot AI vision"),
413
- click: z.enum(["left", "right", "middle"]).optional().describe("Mouse button (default: left)")
414
- }),
415
- z.object({
416
- type: z.literal("type"),
417
- text: z.string().optional().describe("Text to type into focused element"),
418
- key: z.string().optional().describe("Special key (Enter, Tab, Escape, ArrowDown, Backspace, etc)"),
419
- clearFirst: z.boolean().optional().describe("Clear field before typing (default: true)")
420
- }),
421
- z.object({
422
- type: z.literal("move"),
423
- x: z.number().describe("X coordinate from screenshot AI vision"),
424
- y: z.number().describe("Y coordinate from screenshot AI vision"),
425
- steps: z.number().optional().describe("Steps for smooth movement (default: 1)")
426
- }),
427
- z.object({
428
- type: z.literal("scroll"),
429
- deltaX: z.number().optional().describe("Horizontal pixels (positive=right, negative=left)"),
430
- deltaY: z.number().optional().describe("Vertical pixels (positive=down, negative=up)"),
431
- smooth: z.boolean().optional().describe("Smooth animation (default: false)")
432
- }),
433
- z.object({
434
- type: z.literal("wait"),
435
- delay: z.number().describe("Wait duration in milliseconds before next action")
436
- }),
437
- z.object({
438
- type: z.literal("extract_data"),
439
- selector: z.string().describe("CSS selector (e.g., '#username') or element ID to extract data from")
440
- })
441
- ])
442
- ).min(1).describe("Actions to execute in sequence. Apply PLANNING PROTOCOL before building this array.")
443
- },
444
- handler: actionsHandler
445
- },
446
-
447
- // ============================================================================
448
- // Page Inspection
449
- // ============================================================================
450
- "analyze_dom": {
451
- description: `Extract page information - text content, links, structure, and page metadata.
452
-
453
- PRIMARY USE CASES:
454
-
455
- 1. WEBSITE EXPLORATION/CLONING
456
- Task keywords: "explore website", "clone website", "analyze site", "jelajahi website", "get all pages"
457
- → Use ONLY analyze_dom + navigate (NO screenshot needed)
458
- → Workflow: analyze_dom → navigate(href) → analyze_dom → repeat
459
-
460
- Example: "Clone example-company.com"
461
- CORRECT: analyze_dom → get links → navigate to each page → analyze_dom each page
462
- INCORRECT: analyze_dom → take_screenshot (expensive, unnecessary)
463
-
464
- 2. INFORMATION EXTRACTION
465
- Task keywords: "find", "read", "get", "extract", "search content"
466
- → Use analyze_dom for content, navigate for links
467
- → NO screenshot needed unless visual-only content
468
-
469
- 3. CONTENT RESEARCH
470
- Task keywords: "what does page say", "get article", "find documentation"
471
- → analyze_dom is PRIMARY method
472
- → Much faster and cheaper than screenshot
473
-
474
- TASK CLASSIFICATION:
475
-
476
- INFORMATION EXTRACTION TASKS (reading, finding, extracting, exploring):
477
- → PRIMARY: analyze_dom (fast, efficient, no screenshot needed)
478
- → SECONDARY: navigate (if need to follow links - use href, not click)
479
- → AVOID: take_screenshot (expensive, unnecessary for text content)
480
-
481
- Examples:
482
- - "Explore website and all pages" → analyze_dom + navigate only
483
- - "Clone website structure" → analyze_dom + navigate only
484
- - "Find pricing information" → analyze_dom.content
485
- - "Get all navigation links" → analyze_dom.navigation.links
486
- - "Read article summary" → analyze_dom.structure + content
487
- - "Find documentation URL" → analyze_dom.navigation.links → navigate(href)
488
-
489
- INTERACTION TASKS (clicking, typing, testing):
490
- → PRIMARY: take_screenshot (for coordinates)
491
- → SECONDARY: actions (execute interactions)
492
- → SUPPORT: analyze_dom (context only)
493
-
494
- Examples:
495
- - "Click login button" → take_screenshot → actions
496
- - "Fill form" → analyze_dom (optional context) → take_screenshot → actions
497
-
498
- WHEN TO USE:
499
- - Read page content (text, headings, paragraphs)
500
- - Get all links with URLs (for navigation)
501
- - Understand page structure and hierarchy
502
- - Extract form metadata
503
- - Check page properties (iframes, captcha)
504
-
505
- WHEN TO SKIP:
506
- - Need pixel coordinates for clicking (use take_screenshot instead)
507
- - Already have page information and unchanged
508
-
509
- EFFICIENT INFORMATION EXTRACTION WORKFLOW:
510
-
511
- Step 1: navigate to target page
512
- Step 2: analyze_dom (get content, links, structure)
513
- Step 3: If need more pages:
514
- - Find link in navigation.links (has href)
515
- - Use navigate(href) - NOT click coordinates
516
- - Repeat analyze_dom
517
- Step 4: Extract and return information - DONE
518
-
519
- NO screenshot needed for information tasks!
520
-
521
- Example - "Explore/clone website example-company.com":
522
- → open_new_tab("https://example-company.com")
523
- → analyze_dom(['navigation', 'structure', 'content']) - get ALL page info
524
- → Find links: About, Products, Blog, Contact (in navigation.links)
525
- → navigate("https://example-company.com/about")
526
- → analyze_dom(['structure', 'content']) - get About page info
527
- → navigate("https://example-company.com/products")
528
- → analyze_dom(['structure', 'content']) - get Products page info
529
- → Continue for all pages
530
- → DONE (NO screenshot needed at all!)
531
-
532
- Example - "Find pricing information at loom.com":
533
- → open_new_tab("https://www.loom.com")
534
- → analyze_dom(['navigation', 'content'])
535
- → Find pricing link: {text: "Pricing", href: "https://www.loom.com/pricing"}
536
- → navigate("https://www.loom.com/pricing")
537
- → analyze_dom(['content', 'structure'])
538
- → Extract pricing from content.paragraphs
539
- → DONE (no screenshot used!)
540
-
541
- OUTPUT STRUCTURE:
542
-
543
- navigation: {links: [{text, href}]}
544
- - ALL links on page (not just nav menu) - comprehensive extraction
545
- - Deduplicated by href
546
- - Use href with navigate tool (efficient)
547
- - Avoid clicking coordinates for navigation
548
-
549
- structure: {headings: [{level, text, id}], sections: [{heading, summary}]}
550
- - Page organization and hierarchy
551
-
552
- content: {paragraphs: [strings]}
553
- - Text content from various elements (p, div, li, td, span)
554
- - Deduplicated, up to 100 text items
555
- - Primary source for information extraction
556
-
557
- forms: [{formId, action, fields: [{label, type, name, placeholder, required, currentValue}]}]
558
- - Form structure metadata
559
-
560
- summary: {url, title, hasIframes, hasCaptcha, scrollableHeight, viewportHeight}
561
- - Page metadata
562
- - hasIframes/hasCaptcha: may need take_screenshot
563
-
564
- IMPORTANT:
565
-
566
- analyze_dom is PRIMARY method for information extraction tasks.
567
- Use navigate + analyze_dom workflow - more efficient than screenshot + click.
568
- Result becomes stale after navigation - re-run on new pages.`,
569
- schema: {
570
- include: z.array(z.enum(['navigation', 'structure', 'content', 'forms', 'summary'])).optional().describe("Sections to return. Omit for all. Use ['navigation', 'content'] for most reading tasks.")
571
- },
572
- handler: analyzeDomHandler
573
- },
574
-
575
- "take_screenshot": {
576
- description: `Capture viewport screenshot for visual analysis and coordinate determination.
577
-
578
- TASK CLASSIFICATION:
579
-
580
- Ask yourself: Is this an INTERACTION task or INFORMATION task?
581
-
582
- INTERACTION TASKS (clicking, typing, testing):
583
- → USE: take_screenshot (get coordinates via AI vision)
584
- → Keywords: "click", "fill form", "type", "test UI", "automate interaction", "submit"
585
- → THEN: Apply PLANNING PROTOCOL before actions (see actions tool)
586
-
587
- INFORMATION TASKS (reading, finding, exploring):
588
- → DO NOT USE: take_screenshot (expensive, unnecessary)
589
- → Keywords: "explore", "clone", "jelajahi", "find", "read", "get", "extract", "analyze"
590
- → USE INSTEAD: analyze_dom (10x faster, much cheaper)
591
-
592
- WHEN TO USE:
593
- - Need pixel coordinates for clicking/typing (analyze_dom has no coordinates)
594
- - Visual-only content (calculator displays, canvas, images, charts)
595
- - Iframe content (hasIframes=true - analyze_dom can't see inside)
596
- - Obstacles (captcha, popups, modals)
597
- - UI/visual verification (styling, layout, colors)
598
- - Before/after visual comparison
599
-
600
- WHEN TO SKIP:
601
- - Website exploration/cloning (use analyze_dom + navigate only)
602
- - Reading page content (analyze_dom.content is faster)
603
- - Getting links for navigation (analyze_dom.navigation.links)
604
- - Scrolling to "see more content" (analyze_dom already gets all DOM content)
605
- - Information extraction tasks (use analyze_dom instead)
606
- - Navigation (use navigate with href, not click coordinates)
607
- - Already have recent screenshot and page unchanged
608
-
609
- Cost consideration:
610
- - Screenshot is EXPENSIVE (image encoding, AI vision processing)
611
- - analyze_dom is CHEAP (text extraction, no image processing)
612
- - Rule: If task is reading/extracting information → use analyze_dom, NOT screenshot
613
-
614
- COMMON MISTAKES:
615
-
616
- Mistake: Using screenshot for website exploration
617
- Example: "Explore website" → take_screenshot → scroll → screenshot → scroll → screenshot
618
- Fix: Use analyze_dom + navigate only (no screenshot needed)
619
-
620
- Mistake: Screenshot to "see" text content
621
- Example: Want to read page → take_screenshot
622
- Fix: analyze_dom.content gives you all text directly
623
-
624
- Mistake: Screenshot + scroll to see full page
625
- Example: take_screenshot → scroll → screenshot → scroll
626
- Fix: analyze_dom gets entire DOM at once, no scrolling needed
627
-
628
- OUTPUT:
629
- PNG image (base64 encoded) showing visible viewport.
630
-
631
- WORKFLOW AFTER SCREENSHOT:
632
-
633
- After taking screenshot for interaction tasks:
634
- 1. AI vision: Analyze screenshot to identify element positions
635
- 2. Determine pixel coordinates (x, y) for target elements
636
- 3. Apply PLANNING PROTOCOL (see actions tool) before executing:
637
- - STATE THE GOAL
638
- - PLAN THE SEQUENCE (what happens after each action)
639
- - VERIFY THE LOGIC
640
- - EFFICIENT ALTERNATIVES
641
- - VERIFY RESULT after execution
642
- 4. Execute actions only after verification
643
-
644
- Example (INCORRECT) - Website exploration:
645
-
646
- Task: "Explore example-company.com and all pages"
647
- INCORRECT approach (expensive, slow, unnecessary):
648
- → open_new_tab
649
- → take_screenshot (not needed)
650
- → scroll → take_screenshot (repeat 5 times)
651
- → navigate to /about
652
- → take_screenshot (not needed)
653
- → scroll → take_screenshot
654
- Total: 10+ screenshots, very expensive!
655
-
656
- CORRECT approach (fast, efficient):
657
- → open_new_tab
658
- → analyze_dom (get all content + links)
659
- → navigate to /about
660
- → analyze_dom (get all content)
661
- → Continue for other pages
662
- Total: 0 screenshots, 10x faster!
663
-
664
- Example (CORRECT) - Button interaction:
665
-
666
- Task: "Click the login button"
667
- → take_screenshot (need coordinates for interaction)
668
- → AI vision: "Login button at x=1200, y=45"
669
- → PLAN: Click button → login form appears
670
- → VERIFY: Single action achieves goal
671
- → actions([{click, x:1200, y:45}])
672
-
673
- Example (CORRECT) - Sequential calculator actions:
674
-
675
- Task: Enter calculator formula (15 × 8) / (4 + 2)
676
- → take_screenshot (need coordinates for interaction)
677
- → AI vision: Identify all needed buttons and their positions
678
- → CHECK: Is there an input field? If yes, TYPE is more efficient!
679
- → If TYPE available:
680
- PLAN: Click input → type formula → calculate
681
- actions([{click x:640,y:311}, {type "(15*8)/(4+2)"}, {click x:913,y:479}])
682
- → If must use buttons:
683
- PLAN each click: "(" at x:672,y:320 → "1" at x:672,y:449 → ...
684
- VERIFY: Sequence produces correct formula in correct order
685
- actions([full sequence with verification])
686
-
687
- Example (CORRECT) - Form filling:
688
-
689
- Task: "Fill login form"
690
- → take_screenshot (need coordinates for interaction)
691
- → AI vision: username x:640,y:300; password x:640,y:380; submit x:640,y:450
692
- → PLAN:
693
- 1. Click username → focus
694
- 2. Type email → entered
695
- 3. Click password → focus
696
- 4. Type password → entered
697
- 5. Click submit → submitted
698
- → VERIFY: Correct order, correct data, correct targets
699
- → VERIFY RESULT: After execution, confirm form was filled correctly
700
- → actions([sequence])
701
-
702
- OBSTACLE HANDLING:
703
-
704
- When encountering obstacles (captcha, modals, popups, challenges):
705
- - DO NOT stop or ask user
706
- - Attempt to solve/dismiss automatically using AI vision
707
- - Continue original task after resolving
708
-
709
- Captcha workflow:
710
- 1. take_screenshot → identify captcha type
711
- 2. PLAN solution based on type:
712
- - Checkbox: click checkbox, wait, verify
713
- - Image selection: identify matching images, click sequence, verify
714
- - Text/math: solve, input, submit
715
- 3. Execute solution
716
- 4. take_screenshot (verify passed)
717
- 5. Continue task
718
-
719
- Modal/popup workflow:
720
- 1. take_screenshot → identify modal/popup
721
- 2. Find close button or dismiss action
722
- 3. actions([click dismiss])
723
- 4. Continue task
724
-
725
- IMPORTANT:
726
- - Coordinates from AI vision are pixel positions in screenshot
727
- - Can see inside iframes (unlike analyze_dom)
728
- - Always apply PLANNING PROTOCOL before executing sequential actions
729
- - When obstacles appear: solve automatically, never stop
730
- - After actions: take new screenshot to verify or find new elements`,
731
- handler: takeScreenshotHandler
732
- },
733
-
734
- "get_console_logs": {
735
- description: `Retrieve browser console logs for debugging.
736
-
737
- WHEN TO USE:
738
- - Debug JavaScript errors after actions fail
739
- - Monitor API calls or script execution
740
- - Detect client-side errors not visible in UI
741
- - Investigate unexpected behavior
742
-
743
- OUTPUT: Formatted text, most recent first:
744
- [2024-01-27 10:30:45] ERROR: Uncaught TypeError: Cannot read property 'value' of null
745
- [2024-01-27 10:30:44] WARN: Deprecated API usage
746
-
747
- Logs captured from browser console only - not backend logs. Default 20 entries, max 100. Logs persist until cleared or tab closed.`,
748
- schema: {
749
- limit: z.number().min(1).max(100).optional().default(20).describe("Maximum number of log entries to return (min: 1, max: 100, default: 20)")
750
- },
751
- handler: getConsoleLogsHandler
752
- },
753
-
754
- "clear_console_logs": {
755
- description: `Clear console logs from backend storage.
756
-
757
- WHEN TO USE:
758
- - Before important actions to isolate new logs
759
- - Clean slate for debugging specific operations
760
-
761
- OUTPUT: Success confirmation.
762
-
763
- Only clears backend storage, not browser console. Use before actions for clean debugging context.`,
764
- handler: clearConsoleLogsHandler
765
- },
766
-
767
- "execute_console": {
768
- description: `Execute JavaScript in browser console.
769
-
770
- WHEN TO USE:
771
- - Extract dynamic data not in DOM (computed styles, variables, runtime state)
772
- - Access browser APIs (localStorage, sessionStorage)
773
- - Debug page behavior
774
- - Verify JavaScript context
775
-
776
- COMMON COMMANDS:
777
- - document.title
778
- - window.location.href
779
- - localStorage.getItem("key")
780
- - document.querySelector("#id").value
781
- - Array.from(document.querySelectorAll(".item")).map(el => el.textContent)
782
-
783
- OUTPUT: Execution result as JSON string, or error message.
784
-
785
- Has full access to page context. Return value must be JSON-serializable. Use for extraction/debugging, not complex automation.`,
786
- schema: {
787
- command: z.string().min(1).describe("JavaScript expression or statement to execute (e.g., 'document.title', 'window.location.href', 'localStorage.getItem(\"key\")')")
788
- },
789
- handler: executeConsoleHandler
790
- },
791
-
22
+ actions: {
23
+ description: actionsToolDescription,
24
+ schema: actionsToolSchema,
25
+ handler: async (args) => {
26
+ try {
27
+ const report = await runActions(args as any);
28
+ return formatReport(report);
29
+ } catch (error) {
30
+ // Nothing ran: no project context, no tab, no browser. The batch
31
+ // never started, so there is no partial report to render.
32
+ return {
33
+ content: [
34
+ {
35
+ type: 'text' as const,
36
+ text: `Browser actions failed before starting: ${error instanceof Error ? error.message : 'Unknown error'}`
37
+ }
38
+ ],
39
+ isError: true
40
+ };
41
+ }
42
+ }
43
+ }
792
44
  }
793
45
  });