illuma-agents 1.0.18 → 1.0.19

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.
@@ -0,0 +1,582 @@
1
+ /**
2
+ * Browser Automation Tools for Ranger Browser Extension
3
+ *
4
+ * These tools allow the LLM to interact with the browser through the
5
+ * ranger-browser extension. They generate structured actions that are
6
+ * sent to the extension via SSE streaming for execution.
7
+ *
8
+ * The extension handles:
9
+ * - DOM extraction with element indexing
10
+ * - Click, type, hover, scroll actions
11
+ * - Navigation and page context
12
+ * - Visual element highlighting
13
+ */
14
+
15
+ import { z } from 'zod';
16
+ import { tool, DynamicStructuredTool } from '@langchain/core/tools';
17
+
18
+ // ============================================
19
+ // Tool Schemas
20
+ // ============================================
21
+
22
+ /**
23
+ * Enhanced click schema that supports both index-based and coordinate-based clicking
24
+ */
25
+ const BrowserClickSchema = z.object({
26
+ index: z.number().optional().describe(
27
+ 'The index of the element to click, as shown in the page context (e.g., [0], [1], [2]). ' +
28
+ 'Use the element index from the interactive elements list provided in the page context. ' +
29
+ 'Either index OR coordinates must be provided.'
30
+ ),
31
+ coordinates: z.object({
32
+ x: z.number().describe('X coordinate in viewport pixels'),
33
+ y: z.number().describe('Y coordinate in viewport pixels'),
34
+ }).optional().describe(
35
+ 'Coordinates for clicking elements that lack semantic info (marked with ⚠️). ' +
36
+ 'The coordinates are provided in the element listing as coords:(x,y). ' +
37
+ 'Either index OR coordinates must be provided.'
38
+ ),
39
+ visualDescription: z.string().optional().describe(
40
+ 'Description of what the element looks like visually. Used when clicking by appearance ' +
41
+ '(e.g., "blue button in top right corner", "hamburger menu icon")'
42
+ ),
43
+ reason: z.string().optional().describe(
44
+ 'Brief explanation of why you are clicking this element (for user transparency)'
45
+ ),
46
+ });
47
+
48
+ const BrowserTypeSchema = z.object({
49
+ index: z.number().describe(
50
+ 'The index of the input element to type into, as shown in the page context'
51
+ ),
52
+ text: z.string().describe(
53
+ 'The text to type into the input field'
54
+ ),
55
+ clear: z.boolean().optional().describe(
56
+ 'Whether to clear the existing content before typing (default: false)'
57
+ ),
58
+ pressEnter: z.boolean().optional().describe(
59
+ 'Whether to press Enter after typing (useful for search fields, default: false)'
60
+ ),
61
+ });
62
+
63
+ const BrowserNavigateSchema = z.object({
64
+ url: z.string().describe(
65
+ 'The URL to navigate to. Can be a full URL or a relative path.'
66
+ ),
67
+ reason: z.string().optional().describe(
68
+ 'Brief explanation of why you are navigating to this URL'
69
+ ),
70
+ });
71
+
72
+ const BrowserScrollSchema = z.object({
73
+ direction: z.enum(['up', 'down', 'left', 'right']).describe(
74
+ 'The direction to scroll'
75
+ ),
76
+ amount: z.number().optional().describe(
77
+ 'The amount to scroll in pixels (default: 500)'
78
+ ),
79
+ });
80
+
81
+ const BrowserExtractSchema = z.object({
82
+ query: z.string().optional().describe(
83
+ 'Optional query to filter extracted content. If provided, only content related to the query will be extracted.'
84
+ ),
85
+ selector: z.string().optional().describe(
86
+ 'Optional CSS selector to extract content from a specific element'
87
+ ),
88
+ });
89
+
90
+ const BrowserHoverSchema = z.object({
91
+ index: z.number().describe(
92
+ 'The index of the element to hover over, as shown in the page context'
93
+ ),
94
+ });
95
+
96
+ const BrowserWaitSchema = z.object({
97
+ duration: z.number().optional().describe(
98
+ 'Duration to wait in milliseconds (default: 1000)'
99
+ ),
100
+ reason: z.string().optional().describe(
101
+ 'Why we are waiting (e.g., "for page to load", "for animation to complete")'
102
+ ),
103
+ });
104
+
105
+ const BrowserGoBackSchema = z.object({
106
+ reason: z.string().optional().describe(
107
+ 'Brief explanation of why you are going back'
108
+ ),
109
+ });
110
+
111
+ const BrowserScreenshotSchema = z.object({
112
+ fullPage: z.boolean().optional().describe(
113
+ 'Whether to capture the full page or just the viewport (default: viewport only)'
114
+ ),
115
+ reason: z.string().optional().describe(
116
+ 'Why you need a screenshot (e.g., "to identify visual elements", "to analyze page layout")'
117
+ ),
118
+ });
119
+
120
+ // ============================================
121
+ // Tool Implementations
122
+ // ============================================
123
+
124
+ /**
125
+ * Browser click tool - clicks an element by index or coordinates
126
+ * Supports both semantic (index-based) and vision (coordinate-based) clicking
127
+ */
128
+ export function createBrowserClickTool(): DynamicStructuredTool<typeof BrowserClickSchema> {
129
+ return tool<typeof BrowserClickSchema>(
130
+ async ({ index, coordinates, visualDescription, reason }) => {
131
+ // Validate that at least one targeting method is provided
132
+ if (index === undefined && !coordinates) {
133
+ return JSON.stringify({
134
+ type: 'error',
135
+ error: 'Either index or coordinates must be provided to click an element',
136
+ });
137
+ }
138
+
139
+ // Return a structured action for the extension to execute
140
+ // The actual execution happens in the browser extension
141
+ return JSON.stringify({
142
+ type: 'browser_action',
143
+ action: {
144
+ type: 'click',
145
+ ...(index !== undefined && { index }),
146
+ ...(coordinates && { coordinates }),
147
+ ...(visualDescription && { visualDescription }),
148
+ reason,
149
+ },
150
+ // Signal that this requires browser execution
151
+ requiresBrowserExecution: true,
152
+ });
153
+ },
154
+ {
155
+ name: EBrowserTools.CLICK,
156
+ description: `Click an interactive element on the current page.
157
+
158
+ **Two ways to target elements:**
159
+
160
+ 1. **By index (preferred)**: Use the element's index number from the interactive elements list
161
+ - Format: [index] {semantic role} <tag>text</tag>
162
+ - Example: browser_click({ index: 5 }) to click element [5]
163
+
164
+ 2. **By coordinates (vision fallback)**: For elements marked with ⚠️ that lack semantic info
165
+ - Use the coords:(x,y) shown after the ⚠️ marker
166
+ - Example: browser_click({ coordinates: { x: 150, y: 200 } })
167
+
168
+ **When to use coordinates:**
169
+ - Elements marked with ⚠️ have poor semantic understanding
170
+ - Icon-only buttons without labels
171
+ - Custom canvas/SVG elements
172
+ - When you identify an element visually in a screenshot
173
+
174
+ Example: If element shows \`[12] {button} <div>⚠️ [left side, small, clickable] coords:(45,120)\`
175
+ Use either: browser_click({ index: 12 }) or browser_click({ coordinates: { x: 45, y: 120 } })`,
176
+ schema: BrowserClickSchema,
177
+ }
178
+ );
179
+ }
180
+
181
+ /**
182
+ * Browser type tool - types text into an input field
183
+ */
184
+ export function createBrowserTypeTool(): DynamicStructuredTool<typeof BrowserTypeSchema> {
185
+ return tool<typeof BrowserTypeSchema>(
186
+ async ({ index, text, clear, pressEnter }) => {
187
+ return JSON.stringify({
188
+ type: 'browser_action',
189
+ action: {
190
+ type: 'type',
191
+ index,
192
+ text,
193
+ clear: clear ?? false,
194
+ pressEnter: pressEnter ?? false,
195
+ },
196
+ requiresBrowserExecution: true,
197
+ });
198
+ },
199
+ {
200
+ name: EBrowserTools.TYPE,
201
+ description: `Type text into an input field on the current page.
202
+
203
+ Use this tool when you need to:
204
+ - Fill in a text input or textarea
205
+ - Enter a search query
206
+ - Fill out form fields
207
+
208
+ The element index comes from the page context's interactive elements list.
209
+ Set 'clear: true' to clear existing content before typing.
210
+ Set 'pressEnter: true' to submit after typing (useful for search fields).
211
+
212
+ Example: To type "hello world" into a search field shown as "[2]<input>Search...</input>",
213
+ use index: 2, text: "hello world"`,
214
+ schema: BrowserTypeSchema,
215
+ }
216
+ );
217
+ }
218
+
219
+ /**
220
+ * Browser navigate tool - navigates to a URL
221
+ */
222
+ export function createBrowserNavigateTool(): DynamicStructuredTool<typeof BrowserNavigateSchema> {
223
+ return tool<typeof BrowserNavigateSchema>(
224
+ async ({ url, reason }) => {
225
+ return JSON.stringify({
226
+ type: 'browser_action',
227
+ action: {
228
+ type: 'navigate',
229
+ url,
230
+ reason,
231
+ },
232
+ requiresBrowserExecution: true,
233
+ });
234
+ },
235
+ {
236
+ name: EBrowserTools.NAVIGATE,
237
+ description: `Navigate to a specific URL in the browser.
238
+
239
+ Use this tool when you need to:
240
+ - Go to a specific website
241
+ - Navigate to a different page
242
+ - Open a new URL
243
+
244
+ Provide the full URL including the protocol (https://).
245
+
246
+ Example: browser_navigate({ url: "https://www.google.com" })`,
247
+ schema: BrowserNavigateSchema,
248
+ }
249
+ );
250
+ }
251
+
252
+ /**
253
+ * Browser scroll tool - scrolls the page
254
+ */
255
+ export function createBrowserScrollTool(): DynamicStructuredTool<typeof BrowserScrollSchema> {
256
+ return tool<typeof BrowserScrollSchema>(
257
+ async ({ direction, amount }) => {
258
+ return JSON.stringify({
259
+ type: 'browser_action',
260
+ action: {
261
+ type: 'scroll',
262
+ scroll: {
263
+ direction,
264
+ amount: amount ?? 500,
265
+ },
266
+ },
267
+ requiresBrowserExecution: true,
268
+ });
269
+ },
270
+ {
271
+ name: EBrowserTools.SCROLL,
272
+ description: `Scroll the current page in a specified direction.
273
+
274
+ Use this tool when you need to:
275
+ - See more content on the page
276
+ - Scroll to find elements not currently visible
277
+ - Navigate long pages
278
+
279
+ Default scroll amount is 500 pixels. Adjust as needed.
280
+
281
+ Example: browser_scroll({ direction: "down", amount: 800 })`,
282
+ schema: BrowserScrollSchema,
283
+ }
284
+ );
285
+ }
286
+
287
+ /**
288
+ * Browser extract tool - extracts content from the page
289
+ */
290
+ export function createBrowserExtractTool(): DynamicStructuredTool<typeof BrowserExtractSchema> {
291
+ return tool<typeof BrowserExtractSchema>(
292
+ async ({ query, selector }) => {
293
+ return JSON.stringify({
294
+ type: 'browser_action',
295
+ action: {
296
+ type: 'extract',
297
+ query,
298
+ selector,
299
+ },
300
+ requiresBrowserExecution: true,
301
+ });
302
+ },
303
+ {
304
+ name: EBrowserTools.EXTRACT,
305
+ description: `Extract text content from the current page.
306
+
307
+ Use this tool when you need to:
308
+ - Get specific information from the page
309
+ - Extract text that matches a query
310
+ - Read content from a specific element
311
+
312
+ If no query or selector is provided, extracts the main page content.
313
+ Use a CSS selector to extract from a specific element.
314
+ Use a query to filter for relevant content.
315
+
316
+ Example: browser_extract({ query: "price" }) - extracts content related to pricing`,
317
+ schema: BrowserExtractSchema,
318
+ }
319
+ );
320
+ }
321
+
322
+ /**
323
+ * Browser hover tool - hovers over an element
324
+ */
325
+ export function createBrowserHoverTool(): DynamicStructuredTool<typeof BrowserHoverSchema> {
326
+ return tool<typeof BrowserHoverSchema>(
327
+ async ({ index }) => {
328
+ return JSON.stringify({
329
+ type: 'browser_action',
330
+ action: {
331
+ type: 'hover',
332
+ index,
333
+ },
334
+ requiresBrowserExecution: true,
335
+ });
336
+ },
337
+ {
338
+ name: EBrowserTools.HOVER,
339
+ description: `Hover over an element to reveal tooltips or dropdown menus.
340
+
341
+ Use this tool when you need to:
342
+ - Reveal a dropdown menu
343
+ - Show a tooltip
344
+ - Trigger hover effects
345
+
346
+ Example: browser_hover({ index: 3 }) - hovers over element at index 3`,
347
+ schema: BrowserHoverSchema,
348
+ }
349
+ );
350
+ }
351
+
352
+ /**
353
+ * Browser wait tool - waits for a specified duration
354
+ */
355
+ export function createBrowserWaitTool(): DynamicStructuredTool<typeof BrowserWaitSchema> {
356
+ return tool<typeof BrowserWaitSchema>(
357
+ async ({ duration, reason }) => {
358
+ return JSON.stringify({
359
+ type: 'browser_action',
360
+ action: {
361
+ type: 'wait',
362
+ duration: duration ?? 1000,
363
+ reason,
364
+ },
365
+ requiresBrowserExecution: true,
366
+ });
367
+ },
368
+ {
369
+ name: EBrowserTools.WAIT,
370
+ description: `Wait for a specified duration before the next action.
371
+
372
+ Use this tool when you need to:
373
+ - Wait for a page to load
374
+ - Wait for an animation to complete
375
+ - Add delay between actions
376
+
377
+ Default wait time is 1000ms (1 second).
378
+
379
+ Example: browser_wait({ duration: 2000, reason: "waiting for page to load" })`,
380
+ schema: BrowserWaitSchema,
381
+ }
382
+ );
383
+ }
384
+
385
+ /**
386
+ * Browser go back tool - navigates back in history
387
+ */
388
+ export function createBrowserGoBackTool(): DynamicStructuredTool<typeof BrowserGoBackSchema> {
389
+ return tool<typeof BrowserGoBackSchema>(
390
+ async ({ reason }) => {
391
+ return JSON.stringify({
392
+ type: 'browser_action',
393
+ action: {
394
+ type: 'back',
395
+ reason,
396
+ },
397
+ requiresBrowserExecution: true,
398
+ });
399
+ },
400
+ {
401
+ name: EBrowserTools.BACK,
402
+ description: `Navigate back to the previous page in browser history.
403
+
404
+ Use this tool when you need to:
405
+ - Return to a previous page
406
+ - Undo a navigation
407
+
408
+ Example: browser_back({ reason: "returning to search results" })`,
409
+ schema: BrowserGoBackSchema,
410
+ }
411
+ );
412
+ }
413
+
414
+ /**
415
+ * Browser screenshot tool - captures a screenshot
416
+ */
417
+ export function createBrowserScreenshotTool(): DynamicStructuredTool<typeof BrowserScreenshotSchema> {
418
+ return tool<typeof BrowserScreenshotSchema>(
419
+ async ({ fullPage }) => {
420
+ return JSON.stringify({
421
+ type: 'browser_action',
422
+ action: {
423
+ type: 'screenshot',
424
+ fullPage: fullPage ?? false,
425
+ },
426
+ requiresBrowserExecution: true,
427
+ });
428
+ },
429
+ {
430
+ name: EBrowserTools.SCREENSHOT,
431
+ description: `Capture a screenshot of the current page.
432
+
433
+ Use this tool when you need to:
434
+ - Capture the current state of a page
435
+ - Document visual elements
436
+ - Verify page appearance
437
+
438
+ Set fullPage: true to capture the entire page (may be large).
439
+ Default captures only the visible viewport.
440
+
441
+ Example: browser_screenshot({ fullPage: false })`,
442
+ schema: BrowserScreenshotSchema,
443
+ }
444
+ );
445
+ }
446
+
447
+ // ============================================
448
+ // Tool Collection
449
+ // ============================================
450
+
451
+ export type BrowserToolsConfig = {
452
+ /** Enable click tool */
453
+ enableClick?: boolean;
454
+ /** Enable type tool */
455
+ enableType?: boolean;
456
+ /** Enable navigate tool */
457
+ enableNavigate?: boolean;
458
+ /** Enable scroll tool */
459
+ enableScroll?: boolean;
460
+ /** Enable extract tool */
461
+ enableExtract?: boolean;
462
+ /** Enable hover tool */
463
+ enableHover?: boolean;
464
+ /** Enable wait tool */
465
+ enableWait?: boolean;
466
+ /** Enable back tool */
467
+ enableBack?: boolean;
468
+ /** Enable screenshot tool */
469
+ enableScreenshot?: boolean;
470
+ };
471
+
472
+ /**
473
+ * Create all browser automation tools
474
+ *
475
+ * IMPORTANT: These tools should ONLY be registered when:
476
+ * 1. The request comes from a browser extension that can execute them
477
+ * 2. The client has indicated browser capability (e.g., via header or parameter)
478
+ *
479
+ * DO NOT register these for normal web UI users - they cannot execute browser actions.
480
+ *
481
+ * Detection in Ranger API:
482
+ * - Check for `X-Ranger-Browser-Extension: true` header
483
+ * - Or check for `browserCapable: true` in request body
484
+ * - Or check user agent for extension identifier
485
+ *
486
+ * @example
487
+ * // In Ranger API endpoint:
488
+ * const hasBrowserExtension = req.headers['x-ranger-browser-extension'] === 'true';
489
+ * const tools = hasBrowserExtension
490
+ * ? [...normalTools, ...createBrowserTools()]
491
+ * : normalTools;
492
+ */
493
+ export function createBrowserTools(config: BrowserToolsConfig = {}): DynamicStructuredTool[] {
494
+ const tools: DynamicStructuredTool[] = [];
495
+
496
+ // Enable all by default
497
+ const {
498
+ enableClick = true,
499
+ enableType = true,
500
+ enableNavigate = true,
501
+ enableScroll = true,
502
+ enableExtract = true,
503
+ enableHover = true,
504
+ enableWait = true,
505
+ enableBack = true,
506
+ enableScreenshot = true,
507
+ } = config;
508
+
509
+ if (enableClick) tools.push(createBrowserClickTool());
510
+ if (enableType) tools.push(createBrowserTypeTool());
511
+ if (enableNavigate) tools.push(createBrowserNavigateTool());
512
+ if (enableScroll) tools.push(createBrowserScrollTool());
513
+ if (enableExtract) tools.push(createBrowserExtractTool());
514
+ if (enableHover) tools.push(createBrowserHoverTool());
515
+ if (enableWait) tools.push(createBrowserWaitTool());
516
+ if (enableBack) tools.push(createBrowserGoBackTool());
517
+ if (enableScreenshot) tools.push(createBrowserScreenshotTool());
518
+
519
+ return tools;
520
+ }
521
+
522
+ /**
523
+ * Browser tool name constants
524
+ * Use these instead of magic strings
525
+ */
526
+ export const EBrowserTools = {
527
+ CLICK: 'browser_click',
528
+ TYPE: 'browser_type',
529
+ NAVIGATE: 'browser_navigate',
530
+ SCROLL: 'browser_scroll',
531
+ EXTRACT: 'browser_extract',
532
+ HOVER: 'browser_hover',
533
+ WAIT: 'browser_wait',
534
+ BACK: 'browser_back',
535
+ SCREENSHOT: 'browser_screenshot',
536
+ } as const;
537
+
538
+ /**
539
+ * Get browser tool names for filtering/identification
540
+ */
541
+ export const BROWSER_TOOL_NAMES = [
542
+ EBrowserTools.CLICK,
543
+ EBrowserTools.TYPE,
544
+ EBrowserTools.NAVIGATE,
545
+ EBrowserTools.SCROLL,
546
+ EBrowserTools.EXTRACT,
547
+ EBrowserTools.HOVER,
548
+ EBrowserTools.WAIT,
549
+ EBrowserTools.BACK,
550
+ EBrowserTools.SCREENSHOT,
551
+ ] as const;
552
+
553
+ export type BrowserToolName = typeof BROWSER_TOOL_NAMES[number];
554
+
555
+ /**
556
+ * Check if a tool call is a browser action
557
+ */
558
+ export function isBrowserToolCall(toolName: string): toolName is BrowserToolName {
559
+ return BROWSER_TOOL_NAMES.includes(toolName as BrowserToolName);
560
+ }
561
+
562
+ /**
563
+ * Check if request indicates browser extension capability
564
+ * Use this to conditionally register browser tools
565
+ *
566
+ * @example
567
+ * // In Express middleware or endpoint:
568
+ * if (hasBrowserCapability(req.headers)) {
569
+ * tools.push(...createBrowserTools());
570
+ * }
571
+ */
572
+ export function hasBrowserCapability(headers: Record<string, string | string[] | undefined>): boolean {
573
+ const extensionHeader = headers['x-ranger-browser-extension'];
574
+ const capableHeader = headers['x-ranger-browser-capable'];
575
+
576
+ return (
577
+ extensionHeader === 'true' ||
578
+ capableHeader === 'true' ||
579
+ (Array.isArray(extensionHeader) && extensionHeader.includes('true')) ||
580
+ (Array.isArray(capableHeader) && capableHeader.includes('true'))
581
+ );
582
+ }