illuma-agents 1.0.31 → 1.0.32

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.
@@ -111,29 +111,26 @@ const BrowserKeypressSchema = zod.z.object({
111
111
  /**
112
112
  * Format browser action result for LLM consumption
113
113
  */
114
- function formatResultForLLM(result, action, actionArgs) {
114
+ function formatResultForLLM(result, action) {
115
115
  if (!result.success && result.error) {
116
- const errorType = result.errorType ? `[${result.errorType}] ` : '';
117
- return `${errorType}Action "${action}" failed: ${result.error}`;
116
+ return `Browser action "${action}" failed: ${result.error}`;
118
117
  }
119
118
  const parts = [];
120
- // Verification result (Skyvern pattern)
121
- if (result.verification) {
122
- const v = result.verification;
123
- if (v.dialogClosed || v.formGone || v.urlChanged) {
124
- parts.push(`✓ ${v.changeDescription}`);
125
- }
126
- else if (!v.significantChange) {
127
- parts.push(`⚠ No change detected`);
128
- }
119
+ if (result.url != null && result.url !== '') {
120
+ parts.push(`**Current URL:** ${result.url}`);
121
+ }
122
+ if (result.title != null && result.title !== '') {
123
+ parts.push(`**Page Title:** ${result.title}`);
124
+ }
125
+ if (result.elementList != null && result.elementList !== '') {
126
+ parts.push(`\n**Interactive Elements:**\n${result.elementList}`);
127
+ }
128
+ if (result.screenshot != null && result.screenshot !== '') {
129
+ parts.push('\n[Screenshot captured and displayed to user]');
130
+ }
131
+ if (parts.length === 0) {
132
+ return `Browser action "${action}" completed successfully.`;
129
133
  }
130
- // Page state
131
- if (result.url)
132
- parts.push(`URL: ${result.url}`);
133
- if (result.title)
134
- parts.push(`Title: ${result.title}`);
135
- if (result.elementList)
136
- parts.push(`\nElements:\n${result.elementList}`);
137
134
  return parts.join('\n');
138
135
  }
139
136
  /**
@@ -176,65 +173,45 @@ function createBrowserTools(options) {
176
173
  // The marker is still returned initially via SSE, but we wait for the callback
177
174
  try {
178
175
  const result = await waitForResult(action, args, toolCallId);
179
- return formatResultForLLM(result, action, args);
176
+ return formatResultForLLM(result, action);
180
177
  }
181
178
  catch (error) {
182
179
  const errorMessage = error instanceof Error ? error.message : String(error);
183
- return `❌ **ACTION FAILED**: Browser action "${action}" failed: ${errorMessage}
184
-
185
- **REQUIRED**: Analyze why the action failed and try an alternative approach.`;
180
+ return `Browser action "${action}" failed: ${errorMessage}`;
186
181
  }
187
182
  };
188
183
  };
189
- // browser_click - PRIMARY action for buttons and links
184
+ // browser_click
190
185
  tools$1.push(tools.tool(createToolFunction('click'), {
191
186
  name: EBrowserTools.CLICK,
192
- description: `Click an element by its [index] from the element list.
193
-
194
- **WHEN TO USE (prioritize this over keypress):**
195
- - Buttons labeled "Send", "Submit", "Save", "OK", "Confirm" CLICK them
196
- - Links (a tags) to navigate
197
- - Checkboxes, radio buttons to select
198
- - Any clickable element that performs an action
199
-
200
- **SEMANTIC ELEMENT IDENTIFICATION:**
201
- - Look for aria-label="Send", aria-label="Submit" for action buttons
202
- - Look for type="submit" for form submission
203
- - Look for button text like "Send", "Submit", "Save"
204
- - For email compose: Find the Send button, DON'T use keyboard shortcuts
205
-
206
- Returns verification: dialog closed, form submitted, URL changed, or NO CHANGE (action may have failed).`,
187
+ description: `Click an element on the current web page by its index number.
188
+ The element list shows clickable items like: [0]<button>Submit</button> [1]<a href="/home">Home</a>
189
+ Use the index number in brackets to click that element.
190
+ After clicking, you receive an updated element list showing the new page state.`,
207
191
  schema: BrowserClickSchema,
208
192
  }));
209
193
  // browser_type
210
194
  tools$1.push(tools.tool(createToolFunction('type'), {
211
195
  name: EBrowserTools.TYPE,
212
- description: `Type text into an input/textarea element by [index].
213
-
214
- **WHEN TO USE:**
215
- - Input fields (fieldType="email", "search", "phone", etc.)
216
- - Textareas for longer content
217
- - Contenteditable divs (like Gmail compose body)
218
-
219
- **OPTIONS:**
220
- - pressEnter: true → Press Enter after typing (for search forms)
221
- - pressEnter: false → Just type without submitting
222
-
223
- **DO NOT use pressEnter to send emails** - find and CLICK the Send button instead.
224
-
225
- Returns verification showing if text was entered or form was submitted.`,
196
+ description: `Type text into an input element on the page.
197
+ Find the input element in the list by its index (e.g., [5]<input placeholder="Search">).
198
+ Set pressEnter: true to submit forms after typing.
199
+ After typing, you receive an updated element list.`,
226
200
  schema: BrowserTypeSchema,
227
201
  }));
228
202
  // browser_navigate
229
203
  tools$1.push(tools.tool(createToolFunction('navigate'), {
230
204
  name: EBrowserTools.NAVIGATE,
231
- description: `Navigate to a URL (include https://). Returns new page's element list.`,
205
+ description: `Navigate to a URL. Always include the full URL with https://.
206
+ After navigation, you receive the new page's element list.`,
232
207
  schema: BrowserNavigateSchema,
233
208
  }));
234
209
  // browser_scroll
235
210
  tools$1.push(tools.tool(createToolFunction('scroll'), {
236
211
  name: EBrowserTools.SCROLL,
237
- description: `Scroll the page. Returns updated element list with newly visible elements.`,
212
+ description: `Scroll the page to reveal more content.
213
+ Use 'down' to scroll down, 'up' to scroll up.
214
+ After scrolling, you receive an updated element list with newly visible elements.`,
238
215
  schema: BrowserScrollSchema,
239
216
  }));
240
217
  // browser_extract
@@ -269,19 +246,27 @@ After going back, you receive the previous page's element list.`,
269
246
  // browser_screenshot
270
247
  tools$1.push(tools.tool(createToolFunction('screenshot'), {
271
248
  name: EBrowserTools.SCREENSHOT,
272
- description: `Capture a screenshot. Use browser_get_page_state for element list.`,
249
+ description: `Capture a screenshot of the current page.
250
+ Returns the page state with a note that screenshot was displayed to the user.
251
+ Use browser_get_page_state to get the element list for automation.`,
273
252
  schema: BrowserScreenshotSchema,
274
253
  }));
275
254
  // browser_get_page_state
276
255
  tools$1.push(tools.tool(createToolFunction('get_page_state'), {
277
256
  name: EBrowserTools.GET_PAGE_STATE,
278
- description: `Get current page URL, title, and interactive elements list with index numbers.`,
257
+ description: `Get the current page state including URL, title, and all interactive elements.
258
+ Use this at the start of a task to see what elements are available.
259
+ Returns a text list of elements with their index numbers for interaction.`,
279
260
  schema: BrowserGetPageStateSchema,
280
261
  }));
281
- // browser_select_option
262
+ // browser_select_option - Skyvern-inspired for robust dropdown handling
282
263
  tools$1.push(tools.tool(createToolFunction('select_option'), {
283
264
  name: EBrowserTools.SELECT_OPTION,
284
- description: `Select an option from a dropdown. Handles both native <select> and custom dropdowns.`,
265
+ description: `Select an option from a dropdown or select element.
266
+ For native <select> elements: finds and selects the option by value/label.
267
+ For custom dropdowns: clicks to open, then clicks the matching option.
268
+ Use this instead of click for dropdowns - it handles both native and custom selects.
269
+ After selection, you receive an updated element list.`,
285
270
  schema: BrowserSelectOptionSchema,
286
271
  }));
287
272
  // browser_upload_file - Skyvern-inspired for file input handling
@@ -293,26 +278,14 @@ The system will download the file and attach it to the input.
293
278
  After upload, you receive an updated element list.`,
294
279
  schema: BrowserUploadFileSchema,
295
280
  }));
296
- // browser_keypress - LAST RESORT for keyboard shortcuts
281
+ // browser_keypress - For keyboard shortcuts and special keys
297
282
  tools$1.push(tools.tool(createToolFunction('keypress'), {
298
283
  name: EBrowserTools.KEYPRESS,
299
- description: `Press keyboard key(s) - USE ONLY AS LAST RESORT after clicking fails.
300
-
301
- **PREFER browser_click OVER keypress:**
302
- - To send email Find and CLICK the Send button
303
- - To submit form CLICK the Submit button
304
- - To close modal → CLICK the X or Cancel button
305
-
306
- **WHEN TO USE keypress:**
307
- - Navigation: "Tab", "ArrowDown", "ArrowUp" in dropdowns
308
- - Escape to close popups if no X button exists
309
- - Control+A, Control+C for select/copy operations
310
- - ONLY use Enter to submit if there's NO visible submit button
311
-
312
- Single keys: "Enter", "Escape", "Tab", "ArrowDown"
313
- Key combos: "Control+A", "Shift+Enter"
314
-
315
- Returns verification showing if page state changed.`,
284
+ description: `Press keyboard key(s) on the page.
285
+ Single keys: "Enter", "Escape", "Tab", "ArrowDown", "ArrowUp", "Backspace", "Delete"
286
+ Key combos: "Control+A" (select all), "Control+C" (copy), "Shift+Enter" (newline)
287
+ Use this for form submission, closing modals, navigating dropdowns.
288
+ After keypress, you receive an updated element list.`,
316
289
  schema: BrowserKeypressSchema,
317
290
  }));
318
291
  return tools$1;
@@ -1 +1 @@
1
- {"version":3,"file":"BrowserTools.cjs","sources":["../../../src/tools/BrowserTools.ts"],"sourcesContent":["import { z } from 'zod';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as _t from '@/types';\n\n/**\n * Browser tool names - keep in sync with ranger-browser extension\n * These tools execute locally in the browser extension, NOT on the server\n */\nexport const EBrowserTools = {\n CLICK: 'browser_click',\n TYPE: 'browser_type',\n NAVIGATE: 'browser_navigate',\n SCROLL: 'browser_scroll',\n EXTRACT: 'browser_extract',\n HOVER: 'browser_hover',\n WAIT: 'browser_wait',\n BACK: 'browser_back',\n SCREENSHOT: 'browser_screenshot',\n GET_PAGE_STATE: 'browser_get_page_state',\n // Skyvern-inspired additions for robust form handling\n SELECT_OPTION: 'browser_select_option',\n UPLOAD_FILE: 'browser_upload_file',\n KEYPRESS: 'browser_keypress',\n} as const;\n\nexport type BrowserToolName =\n (typeof EBrowserTools)[keyof typeof EBrowserTools];\n\n/**\n * Callback function type for waiting on browser action results\n * This allows the server (Ranger) to provide a callback that waits for the extension\n * to POST results back to the server before returning to the LLM.\n *\n * @param action - The browser action (click, type, navigate, etc.)\n * @param args - Arguments for the action\n * @param toolCallId - Unique ID for this tool call (from config.toolCall.id)\n * @returns Promise that resolves with the actual browser result (page state, etc.)\n */\nexport type BrowserToolCallback = (\n action: string,\n args: Record<string, unknown>,\n toolCallId: string\n) => Promise<BrowserActionResult>;\n\n/**\n * Action status - matches Skyvern's ActionStatus\n */\nexport type ActionStatus = 'pending' | 'completed' | 'failed' | 'skipped';\n\n/**\n * Verification status - matches Skyvern's VerificationStatus\n * - complete: Goal achieved\n * - terminate: Goal cannot be achieved, stop\n * - continue: Goal not yet achieved, keep going\n */\nexport type VerificationStatus = 'complete' | 'terminate' | 'continue';\n\n/**\n * Result returned from browser action execution\n */\nexport interface BrowserActionResult {\n success: boolean;\n status?: ActionStatus;\n url?: string;\n title?: string;\n elementList?: string;\n error?: string;\n errorType?: string; // Typed error classification\n screenshot?: string;\n elementDescription?: string;\n // State verification (before/after comparison)\n verification?: {\n urlChanged: boolean;\n titleChanged: boolean;\n elementCountDelta: number;\n significantChange: boolean;\n dialogClosed: boolean;\n formGone: boolean;\n changeDescription: string;\n };\n}\n\n/**\n * Check if browser capability is available based on request headers or context\n * The browser extension sets these headers when connected:\n * - X-Ranger-Browser-Extension: true\n * - X-Ranger-Browser-Capable: true\n */\nexport function hasBrowserCapability(req?: {\n headers?: Record<string, string | string[] | undefined>;\n}): boolean {\n if (!req?.headers) {\n return false;\n }\n\n const browserExtension = req.headers['x-ranger-browser-extension'];\n const browserCapable = req.headers['x-ranger-browser-capable'];\n\n return browserExtension === 'true' || browserCapable === 'true';\n}\n\n// Tool schemas\nconst BrowserClickSchema = z.object({\n index: z\n .number()\n .describe(\n 'The index number [0], [1], etc. of the element to click from the page state element list'\n ),\n});\n\nconst BrowserTypeSchema = z.object({\n index: z\n .number()\n .describe('The index number of the input element to type into'),\n text: z.string().describe('The text to type into the element'),\n pressEnter: z\n .boolean()\n .optional()\n .describe('Whether to press Enter after typing (useful for search forms)'),\n});\n\nconst BrowserNavigateSchema = z.object({\n url: z\n .string()\n .describe('The full URL to navigate to (must include https://)'),\n});\n\nconst BrowserScrollSchema = z.object({\n direction: z\n .enum(['up', 'down', 'left', 'right'])\n .describe('Direction to scroll'),\n amount: z\n .number()\n .optional()\n .describe('Pixels to scroll (default: one viewport height)'),\n});\n\nconst BrowserExtractSchema = z.object({\n query: z\n .string()\n .optional()\n .describe('Optional: specific content to extract from the page'),\n});\n\nconst BrowserHoverSchema = z.object({\n index: z.number().describe('The index number of the element to hover over'),\n});\n\nconst BrowserWaitSchema = z.object({\n duration: z\n .number()\n .optional()\n .describe('Milliseconds to wait (default: 1000)'),\n});\n\nconst BrowserBackSchema = z.object({});\n\nconst BrowserScreenshotSchema = z.object({});\n\nconst BrowserGetPageStateSchema = z.object({});\n\n// Skyvern-inspired schemas for robust form handling\nconst BrowserSelectOptionSchema = z.object({\n index: z\n .number()\n .describe('The index number of the select/dropdown element'),\n value: z\n .string()\n .optional()\n .describe('The value or label of the option to select. For native <select>, use the option text. For custom dropdowns, this is the option label to click.'),\n});\n\nconst BrowserUploadFileSchema = z.object({\n index: z\n .number()\n .describe('The index number of the file input element'),\n fileUrl: z\n .string()\n .describe('URL of the file to upload (the system will download and upload it)'),\n});\n\nconst BrowserKeypressSchema = z.object({\n keys: z\n .string()\n .describe('Key(s) to press. Single key: \"Enter\", \"Escape\", \"Tab\", \"ArrowDown\". Combo: \"Control+A\", \"Shift+Enter\"'),\n});\n\n/**\n * Browser tool response interface\n * This is what the extension returns after executing the action\n */\nexport interface BrowserToolResponse {\n requiresBrowserExecution: true;\n action: string;\n args: Record<string, unknown>;\n toolCallId?: string; // Added to help extension correlate with callback\n}\n\n/**\n * Options for creating browser tools\n */\nexport interface CreateBrowserToolsOptions {\n /**\n * Optional callback that waits for browser action results.\n * When provided, tools will await this callback to get actual results from the extension.\n * When not provided, tools return markers immediately (for non-server contexts).\n */\n waitForResult?: BrowserToolCallback;\n}\n\n/**\n * Format browser action result for LLM consumption\n */\nfunction formatResultForLLM(\n result: BrowserActionResult,\n action: string,\n actionArgs?: Record<string, unknown>\n): string {\n if (!result.success && result.error) {\n const errorType = result.errorType ? `[${result.errorType}] ` : '';\n return `${errorType}Action \"${action}\" failed: ${result.error}`;\n }\n\n const parts: string[] = [];\n\n // Verification result (Skyvern pattern)\n if (result.verification) {\n const v = result.verification;\n if (v.dialogClosed || v.formGone || v.urlChanged) {\n parts.push(`✓ ${v.changeDescription}`);\n } else if (!v.significantChange) {\n parts.push(`⚠ No change detected`);\n }\n }\n\n // Page state\n if (result.url) parts.push(`URL: ${result.url}`);\n if (result.title) parts.push(`Title: ${result.title}`);\n if (result.elementList) parts.push(`\\nElements:\\n${result.elementList}`);\n\n return parts.join('\\n');\n}\n\n/**\n * Create browser tools with optional callback for waiting on results\n *\n * When waitForResult callback is provided:\n * 1. Tool returns marker that triggers extension\n * 2. Tool then awaits callback to get actual results\n * 3. Returns real page state to LLM\n *\n * When no callback:\n * 1. Tool returns marker only (for non-server contexts)\n *\n * NOTE: These tools use TEXT-BASED element lists, NOT screenshots\n * Screenshots would be 100K+ tokens each - element lists are ~100 tokens\n */\nexport function createBrowserTools(\n options?: CreateBrowserToolsOptions\n): DynamicStructuredTool[] {\n const { waitForResult } = options || {};\n const tools: DynamicStructuredTool[] = [];\n\n /**\n * Helper to create tool function that optionally waits for results\n * The toolCallId is extracted from the RunnableConfig passed by LangChain\n */\n const createToolFunction = (action: string) => {\n return async (\n args: Record<string, unknown>,\n config?: { toolCall?: { id?: string } }\n ): Promise<string> => {\n const toolCallId =\n config?.toolCall?.id ??\n `tool_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n\n // Create marker for extension\n const marker: BrowserToolResponse = {\n requiresBrowserExecution: true,\n action,\n args,\n toolCallId,\n };\n\n // If no callback, return marker immediately (extension handles via SSE interception)\n if (!waitForResult) {\n return JSON.stringify(marker);\n }\n\n // With callback: wait for actual results from extension\n // The marker is still returned initially via SSE, but we wait for the callback\n try {\n const result = await waitForResult(action, args, toolCallId);\n return formatResultForLLM(result, action, args);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n return `❌ **ACTION FAILED**: Browser action \"${action}\" failed: ${errorMessage}\n\n**REQUIRED**: Analyze why the action failed and try an alternative approach.`;\n }\n };\n };\n\n // browser_click - PRIMARY action for buttons and links\n tools.push(\n tool(createToolFunction('click'), {\n name: EBrowserTools.CLICK,\n description: `Click an element by its [index] from the element list.\n\n**WHEN TO USE (prioritize this over keypress):**\n- Buttons labeled \"Send\", \"Submit\", \"Save\", \"OK\", \"Confirm\" → CLICK them\n- Links (a tags) to navigate\n- Checkboxes, radio buttons to select\n- Any clickable element that performs an action\n\n**SEMANTIC ELEMENT IDENTIFICATION:**\n- Look for aria-label=\"Send\", aria-label=\"Submit\" for action buttons\n- Look for type=\"submit\" for form submission\n- Look for button text like \"Send\", \"Submit\", \"Save\"\n- For email compose: Find the Send button, DON'T use keyboard shortcuts\n\nReturns verification: dialog closed, form submitted, URL changed, or NO CHANGE (action may have failed).`,\n schema: BrowserClickSchema,\n })\n );\n\n // browser_type\n tools.push(\n tool(createToolFunction('type'), {\n name: EBrowserTools.TYPE,\n description: `Type text into an input/textarea element by [index].\n\n**WHEN TO USE:**\n- Input fields (fieldType=\"email\", \"search\", \"phone\", etc.)\n- Textareas for longer content\n- Contenteditable divs (like Gmail compose body)\n\n**OPTIONS:**\n- pressEnter: true → Press Enter after typing (for search forms)\n- pressEnter: false → Just type without submitting\n\n**DO NOT use pressEnter to send emails** - find and CLICK the Send button instead.\n\nReturns verification showing if text was entered or form was submitted.`,\n schema: BrowserTypeSchema,\n })\n );\n\n // browser_navigate\n tools.push(\n tool(createToolFunction('navigate'), {\n name: EBrowserTools.NAVIGATE,\n description: `Navigate to a URL (include https://). Returns new page's element list.`,\n schema: BrowserNavigateSchema,\n })\n );\n\n // browser_scroll\n tools.push(\n tool(createToolFunction('scroll'), {\n name: EBrowserTools.SCROLL,\n description: `Scroll the page. Returns updated element list with newly visible elements.`,\n schema: BrowserScrollSchema,\n })\n );\n\n // browser_extract\n tools.push(\n tool(createToolFunction('extract'), {\n name: EBrowserTools.EXTRACT,\n description: `Extract content from the current page.\nReturns page URL, title, and element list.`,\n schema: BrowserExtractSchema,\n })\n );\n\n // browser_hover\n tools.push(\n tool(createToolFunction('hover'), {\n name: EBrowserTools.HOVER,\n description: `Hover over an element to reveal tooltips, dropdowns, or other hover-triggered content.\nAfter hovering, you receive an updated element list with any newly revealed elements.`,\n schema: BrowserHoverSchema,\n })\n );\n\n // browser_wait\n tools.push(\n tool(createToolFunction('wait'), {\n name: EBrowserTools.WAIT,\n description: `Wait for a specified duration for page content to load.\nUse this after actions that trigger async content loading.\nAfter waiting, you receive an updated element list.`,\n schema: BrowserWaitSchema,\n })\n );\n\n // browser_back\n tools.push(\n tool(createToolFunction('back'), {\n name: EBrowserTools.BACK,\n description: `Go back to the previous page in browser history.\nAfter going back, you receive the previous page's element list.`,\n schema: BrowserBackSchema,\n })\n );\n\n // browser_screenshot\n tools.push(\n tool(createToolFunction('screenshot'), {\n name: EBrowserTools.SCREENSHOT,\n description: `Capture a screenshot. Use browser_get_page_state for element list.`,\n schema: BrowserScreenshotSchema,\n })\n );\n\n // browser_get_page_state\n tools.push(\n tool(createToolFunction('get_page_state'), {\n name: EBrowserTools.GET_PAGE_STATE,\n description: `Get current page URL, title, and interactive elements list with index numbers.`,\n schema: BrowserGetPageStateSchema,\n })\n );\n\n // browser_select_option\n tools.push(\n tool(createToolFunction('select_option'), {\n name: EBrowserTools.SELECT_OPTION,\n description: `Select an option from a dropdown. Handles both native <select> and custom dropdowns.`,\n schema: BrowserSelectOptionSchema,\n })\n );\n\n // browser_upload_file - Skyvern-inspired for file input handling\n tools.push(\n tool(createToolFunction('upload_file'), {\n name: EBrowserTools.UPLOAD_FILE,\n description: `Upload a file to a file input element.\nProvide the index of the file input and the URL of the file to upload.\nThe system will download the file and attach it to the input.\nAfter upload, you receive an updated element list.`,\n schema: BrowserUploadFileSchema,\n })\n );\n\n // browser_keypress - LAST RESORT for keyboard shortcuts\n tools.push(\n tool(createToolFunction('keypress'), {\n name: EBrowserTools.KEYPRESS,\n description: `Press keyboard key(s) - USE ONLY AS LAST RESORT after clicking fails.\n\n**PREFER browser_click OVER keypress:**\n- To send email → Find and CLICK the Send button\n- To submit form → CLICK the Submit button\n- To close modal → CLICK the X or Cancel button\n\n**WHEN TO USE keypress:**\n- Navigation: \"Tab\", \"ArrowDown\", \"ArrowUp\" in dropdowns\n- Escape to close popups if no X button exists\n- Control+A, Control+C for select/copy operations\n- ONLY use Enter to submit if there's NO visible submit button\n\nSingle keys: \"Enter\", \"Escape\", \"Tab\", \"ArrowDown\"\nKey combos: \"Control+A\", \"Shift+Enter\"\n\nReturns verification showing if page state changed.`,\n schema: BrowserKeypressSchema,\n })\n );\n\n return tools;\n}\n"],"names":["z","tools","tool"],"mappings":";;;;;AAIA;;;AAGG;AACU,M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M,EAAE,yBAAyB;AAClC,KAAA,CAAC,CACH;;IAGDD,OAAK,CAAC,IAAI,CACRC,UAAI,CAAC,kBAAkB,CAAC,eAAe,CAAC,EAAE;QACxC,IAAI,EAAE,aAAa,CAAC,aAAa;AACjC,QAAA,WAAW,EAAE,CAAsF,oFAAA,CAAA;AACnG,QAAA,MAAM,EAAE,yBAAyB;AAClC,KAAA,CAAC,CACH;;IAGDD,OAAK,CAAC,IAAI,CACRC,UAAI,CAAC,kBAAkB,CAAC,aAAa,CAAC,EAAE;QACtC,IAAI,EAAE,aAAa,CAAC,WAAW;AAC/B,QAAA,WAAW,EAAE,CAAA;;;AAGgC,kDAAA,CAAA;AAC7C,QAAA,MAAM,EAAE,uBAAuB;AAChC,KAAA,CAAC,CACH;;IAGDD,OAAK,CAAC,IAAI,CACRC,UAAI,CAAC,kBAAkB,CAAC,UAAU,CAAC,EAAE;QACnC,IAAI,EAAE,aAAa,CAAC,QAAQ;AAC5B,QAAA,WAAW,EAAE,CAAA;;;;;;;;;;;;;;;;AAgBiC,mDAAA,CAAA;AAC9C,QAAA,MAAM,EAAE,qBAAqB;AAC9B,KAAA,CAAC,CACH;AAED,IAAA,OAAOD,OAAK;AACd;;;;;;"}
1
+ {"version":3,"file":"BrowserTools.cjs","sources":["../../../src/tools/BrowserTools.ts"],"sourcesContent":["import { z } from 'zod';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as _t from '@/types';\n\n/**\n * Browser tool names - keep in sync with ranger-browser extension\n * These tools execute locally in the browser extension, NOT on the server\n */\nexport const EBrowserTools = {\n CLICK: 'browser_click',\n TYPE: 'browser_type',\n NAVIGATE: 'browser_navigate',\n SCROLL: 'browser_scroll',\n EXTRACT: 'browser_extract',\n HOVER: 'browser_hover',\n WAIT: 'browser_wait',\n BACK: 'browser_back',\n SCREENSHOT: 'browser_screenshot',\n GET_PAGE_STATE: 'browser_get_page_state',\n // Skyvern-inspired additions for robust form handling\n SELECT_OPTION: 'browser_select_option',\n UPLOAD_FILE: 'browser_upload_file',\n KEYPRESS: 'browser_keypress',\n} as const;\n\nexport type BrowserToolName =\n (typeof EBrowserTools)[keyof typeof EBrowserTools];\n\n/**\n * Callback function type for waiting on browser action results\n * This allows the server (Ranger) to provide a callback that waits for the extension\n * to POST results back to the server before returning to the LLM.\n *\n * @param action - The browser action (click, type, navigate, etc.)\n * @param args - Arguments for the action\n * @param toolCallId - Unique ID for this tool call (from config.toolCall.id)\n * @returns Promise that resolves with the actual browser result (page state, etc.)\n */\nexport type BrowserToolCallback = (\n action: string,\n args: Record<string, unknown>,\n toolCallId: string\n) => Promise<BrowserActionResult>;\n\n/**\n * Result returned from browser action execution\n */\nexport interface BrowserActionResult {\n success: boolean;\n url?: string;\n title?: string;\n elementList?: string; // Text-based element list\n error?: string;\n screenshot?: string; // Base64 screenshot (if requested)\n}\n\n/**\n * Check if browser capability is available based on request headers or context\n * The browser extension sets these headers when connected:\n * - X-Ranger-Browser-Extension: true\n * - X-Ranger-Browser-Capable: true\n */\nexport function hasBrowserCapability(req?: {\n headers?: Record<string, string | string[] | undefined>;\n}): boolean {\n if (!req?.headers) {\n return false;\n }\n\n const browserExtension = req.headers['x-ranger-browser-extension'];\n const browserCapable = req.headers['x-ranger-browser-capable'];\n\n return browserExtension === 'true' || browserCapable === 'true';\n}\n\n// Tool schemas\nconst BrowserClickSchema = z.object({\n index: z\n .number()\n .describe(\n 'The index number [0], [1], etc. of the element to click from the page state element list'\n ),\n});\n\nconst BrowserTypeSchema = z.object({\n index: z\n .number()\n .describe('The index number of the input element to type into'),\n text: z.string().describe('The text to type into the element'),\n pressEnter: z\n .boolean()\n .optional()\n .describe('Whether to press Enter after typing (useful for search forms)'),\n});\n\nconst BrowserNavigateSchema = z.object({\n url: z\n .string()\n .describe('The full URL to navigate to (must include https://)'),\n});\n\nconst BrowserScrollSchema = z.object({\n direction: z\n .enum(['up', 'down', 'left', 'right'])\n .describe('Direction to scroll'),\n amount: z\n .number()\n .optional()\n .describe('Pixels to scroll (default: one viewport height)'),\n});\n\nconst BrowserExtractSchema = z.object({\n query: z\n .string()\n .optional()\n .describe('Optional: specific content to extract from the page'),\n});\n\nconst BrowserHoverSchema = z.object({\n index: z.number().describe('The index number of the element to hover over'),\n});\n\nconst BrowserWaitSchema = z.object({\n duration: z\n .number()\n .optional()\n .describe('Milliseconds to wait (default: 1000)'),\n});\n\nconst BrowserBackSchema = z.object({});\n\nconst BrowserScreenshotSchema = z.object({});\n\nconst BrowserGetPageStateSchema = z.object({});\n\n// Skyvern-inspired schemas for robust form handling\nconst BrowserSelectOptionSchema = z.object({\n index: z\n .number()\n .describe('The index number of the select/dropdown element'),\n value: z\n .string()\n .optional()\n .describe('The value or label of the option to select. For native <select>, use the option text. For custom dropdowns, this is the option label to click.'),\n});\n\nconst BrowserUploadFileSchema = z.object({\n index: z\n .number()\n .describe('The index number of the file input element'),\n fileUrl: z\n .string()\n .describe('URL of the file to upload (the system will download and upload it)'),\n});\n\nconst BrowserKeypressSchema = z.object({\n keys: z\n .string()\n .describe('Key(s) to press. Single key: \"Enter\", \"Escape\", \"Tab\", \"ArrowDown\". Combo: \"Control+A\", \"Shift+Enter\"'),\n});\n\n/**\n * Browser tool response interface\n * This is what the extension returns after executing the action\n */\nexport interface BrowserToolResponse {\n requiresBrowserExecution: true;\n action: string;\n args: Record<string, unknown>;\n toolCallId?: string; // Added to help extension correlate with callback\n}\n\n/**\n * Options for creating browser tools\n */\nexport interface CreateBrowserToolsOptions {\n /**\n * Optional callback that waits for browser action results.\n * When provided, tools will await this callback to get actual results from the extension.\n * When not provided, tools return markers immediately (for non-server contexts).\n */\n waitForResult?: BrowserToolCallback;\n}\n\n/**\n * Format browser action result for LLM consumption\n */\nfunction formatResultForLLM(\n result: BrowserActionResult,\n action: string\n): string {\n if (!result.success && result.error) {\n return `Browser action \"${action}\" failed: ${result.error}`;\n }\n\n const parts: string[] = [];\n\n if (result.url != null && result.url !== '') {\n parts.push(`**Current URL:** ${result.url}`);\n }\n if (result.title != null && result.title !== '') {\n parts.push(`**Page Title:** ${result.title}`);\n }\n if (result.elementList != null && result.elementList !== '') {\n parts.push(`\\n**Interactive Elements:**\\n${result.elementList}`);\n }\n if (result.screenshot != null && result.screenshot !== '') {\n parts.push('\\n[Screenshot captured and displayed to user]');\n }\n\n if (parts.length === 0) {\n return `Browser action \"${action}\" completed successfully.`;\n }\n\n return parts.join('\\n');\n}\n\n/**\n * Create browser tools with optional callback for waiting on results\n *\n * When waitForResult callback is provided:\n * 1. Tool returns marker that triggers extension\n * 2. Tool then awaits callback to get actual results\n * 3. Returns real page state to LLM\n *\n * When no callback:\n * 1. Tool returns marker only (for non-server contexts)\n *\n * NOTE: These tools use TEXT-BASED element lists, NOT screenshots\n * Screenshots would be 100K+ tokens each - element lists are ~100 tokens\n */\nexport function createBrowserTools(\n options?: CreateBrowserToolsOptions\n): DynamicStructuredTool[] {\n const { waitForResult } = options || {};\n const tools: DynamicStructuredTool[] = [];\n\n /**\n * Helper to create tool function that optionally waits for results\n * The toolCallId is extracted from the RunnableConfig passed by LangChain\n */\n const createToolFunction = (action: string) => {\n return async (\n args: Record<string, unknown>,\n config?: { toolCall?: { id?: string } }\n ): Promise<string> => {\n const toolCallId =\n config?.toolCall?.id ??\n `tool_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n\n // Create marker for extension\n const marker: BrowserToolResponse = {\n requiresBrowserExecution: true,\n action,\n args,\n toolCallId,\n };\n\n // If no callback, return marker immediately (extension handles via SSE interception)\n if (!waitForResult) {\n return JSON.stringify(marker);\n }\n\n // With callback: wait for actual results from extension\n // The marker is still returned initially via SSE, but we wait for the callback\n try {\n const result = await waitForResult(action, args, toolCallId);\n return formatResultForLLM(result, action);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n return `Browser action \"${action}\" failed: ${errorMessage}`;\n }\n };\n };\n\n // browser_click\n tools.push(\n tool(createToolFunction('click'), {\n name: EBrowserTools.CLICK,\n description: `Click an element on the current web page by its index number.\nThe element list shows clickable items like: [0]<button>Submit</button> [1]<a href=\"/home\">Home</a>\nUse the index number in brackets to click that element.\nAfter clicking, you receive an updated element list showing the new page state.`,\n schema: BrowserClickSchema,\n })\n );\n\n // browser_type\n tools.push(\n tool(createToolFunction('type'), {\n name: EBrowserTools.TYPE,\n description: `Type text into an input element on the page.\nFind the input element in the list by its index (e.g., [5]<input placeholder=\"Search\">).\nSet pressEnter: true to submit forms after typing.\nAfter typing, you receive an updated element list.`,\n schema: BrowserTypeSchema,\n })\n );\n\n // browser_navigate\n tools.push(\n tool(createToolFunction('navigate'), {\n name: EBrowserTools.NAVIGATE,\n description: `Navigate to a URL. Always include the full URL with https://.\nAfter navigation, you receive the new page's element list.`,\n schema: BrowserNavigateSchema,\n })\n );\n\n // browser_scroll\n tools.push(\n tool(createToolFunction('scroll'), {\n name: EBrowserTools.SCROLL,\n description: `Scroll the page to reveal more content.\nUse 'down' to scroll down, 'up' to scroll up.\nAfter scrolling, you receive an updated element list with newly visible elements.`,\n schema: BrowserScrollSchema,\n })\n );\n\n // browser_extract\n tools.push(\n tool(createToolFunction('extract'), {\n name: EBrowserTools.EXTRACT,\n description: `Extract content from the current page.\nReturns page URL, title, and element list.`,\n schema: BrowserExtractSchema,\n })\n );\n\n // browser_hover\n tools.push(\n tool(createToolFunction('hover'), {\n name: EBrowserTools.HOVER,\n description: `Hover over an element to reveal tooltips, dropdowns, or other hover-triggered content.\nAfter hovering, you receive an updated element list with any newly revealed elements.`,\n schema: BrowserHoverSchema,\n })\n );\n\n // browser_wait\n tools.push(\n tool(createToolFunction('wait'), {\n name: EBrowserTools.WAIT,\n description: `Wait for a specified duration for page content to load.\nUse this after actions that trigger async content loading.\nAfter waiting, you receive an updated element list.`,\n schema: BrowserWaitSchema,\n })\n );\n\n // browser_back\n tools.push(\n tool(createToolFunction('back'), {\n name: EBrowserTools.BACK,\n description: `Go back to the previous page in browser history.\nAfter going back, you receive the previous page's element list.`,\n schema: BrowserBackSchema,\n })\n );\n\n // browser_screenshot\n tools.push(\n tool(createToolFunction('screenshot'), {\n name: EBrowserTools.SCREENSHOT,\n description: `Capture a screenshot of the current page.\nReturns the page state with a note that screenshot was displayed to the user.\nUse browser_get_page_state to get the element list for automation.`,\n schema: BrowserScreenshotSchema,\n })\n );\n\n // browser_get_page_state\n tools.push(\n tool(createToolFunction('get_page_state'), {\n name: EBrowserTools.GET_PAGE_STATE,\n description: `Get the current page state including URL, title, and all interactive elements.\nUse this at the start of a task to see what elements are available.\nReturns a text list of elements with their index numbers for interaction.`,\n schema: BrowserGetPageStateSchema,\n })\n );\n\n // browser_select_option - Skyvern-inspired for robust dropdown handling\n tools.push(\n tool(createToolFunction('select_option'), {\n name: EBrowserTools.SELECT_OPTION,\n description: `Select an option from a dropdown or select element.\nFor native <select> elements: finds and selects the option by value/label.\nFor custom dropdowns: clicks to open, then clicks the matching option.\nUse this instead of click for dropdowns - it handles both native and custom selects.\nAfter selection, you receive an updated element list.`,\n schema: BrowserSelectOptionSchema,\n })\n );\n\n // browser_upload_file - Skyvern-inspired for file input handling\n tools.push(\n tool(createToolFunction('upload_file'), {\n name: EBrowserTools.UPLOAD_FILE,\n description: `Upload a file to a file input element.\nProvide the index of the file input and the URL of the file to upload.\nThe system will download the file and attach it to the input.\nAfter upload, you receive an updated element list.`,\n schema: BrowserUploadFileSchema,\n })\n );\n\n // browser_keypress - For keyboard shortcuts and special keys\n tools.push(\n tool(createToolFunction('keypress'), {\n name: EBrowserTools.KEYPRESS,\n description: `Press keyboard key(s) on the page.\nSingle keys: \"Enter\", \"Escape\", \"Tab\", \"ArrowDown\", \"ArrowUp\", \"Backspace\", \"Delete\"\nKey combos: \"Control+A\" (select all), \"Control+C\" (copy), \"Shift+Enter\" (newline)\nUse this for form submission, closing modals, navigating dropdowns.\nAfter keypress, you receive an updated element list.`,\n schema: BrowserKeypressSchema,\n })\n );\n\n return tools;\n}\n"],"names":["z","tools","tool"],"mappings":";;;;;AAIA;;;AAGG;AACU,MAAA,aAAa,GAA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eAAe,CAAC,EAAE;QACxC,IAAI,EAAE,aAAa,CAAC,aAAa;AACjC,QAAA,WAAW,EAAE,CAAA;;;;AAImC,qDAAA,CAAA;AAChD,QAAA,MAAM,EAAE,yBAAyB;AAClC,KAAA,CAAC,CACH;;IAGDD,OAAK,CAAC,IAAI,CACRC,UAAI,CAAC,kBAAkB,CAAC,aAAa,CAAC,EAAE;QACtC,IAAI,EAAE,aAAa,CAAC,WAAW;AAC/B,QAAA,WAAW,EAAE,CAAA;;;AAGgC,kDAAA,CAAA;AAC7C,QAAA,MAAM,EAAE,uBAAuB;AAChC,KAAA,CAAC,CACH;;IAGDD,OAAK,CAAC,IAAI,CACRC,UAAI,CAAC,kBAAkB,CAAC,UAAU,CAAC,EAAE;QACnC,IAAI,EAAE,aAAa,CAAC,QAAQ;AAC5B,QAAA,WAAW,EAAE,CAAA;;;;AAIkC,oDAAA,CAAA;AAC/C,QAAA,MAAM,EAAE,qBAAqB;AAC9B,KAAA,CAAC,CACH;AAED,IAAA,OAAOD,OAAK;AACd;;;;;;"}
@@ -109,29 +109,26 @@ const BrowserKeypressSchema = z.object({
109
109
  /**
110
110
  * Format browser action result for LLM consumption
111
111
  */
112
- function formatResultForLLM(result, action, actionArgs) {
112
+ function formatResultForLLM(result, action) {
113
113
  if (!result.success && result.error) {
114
- const errorType = result.errorType ? `[${result.errorType}] ` : '';
115
- return `${errorType}Action "${action}" failed: ${result.error}`;
114
+ return `Browser action "${action}" failed: ${result.error}`;
116
115
  }
117
116
  const parts = [];
118
- // Verification result (Skyvern pattern)
119
- if (result.verification) {
120
- const v = result.verification;
121
- if (v.dialogClosed || v.formGone || v.urlChanged) {
122
- parts.push(`✓ ${v.changeDescription}`);
123
- }
124
- else if (!v.significantChange) {
125
- parts.push(`⚠ No change detected`);
126
- }
117
+ if (result.url != null && result.url !== '') {
118
+ parts.push(`**Current URL:** ${result.url}`);
119
+ }
120
+ if (result.title != null && result.title !== '') {
121
+ parts.push(`**Page Title:** ${result.title}`);
122
+ }
123
+ if (result.elementList != null && result.elementList !== '') {
124
+ parts.push(`\n**Interactive Elements:**\n${result.elementList}`);
125
+ }
126
+ if (result.screenshot != null && result.screenshot !== '') {
127
+ parts.push('\n[Screenshot captured and displayed to user]');
128
+ }
129
+ if (parts.length === 0) {
130
+ return `Browser action "${action}" completed successfully.`;
127
131
  }
128
- // Page state
129
- if (result.url)
130
- parts.push(`URL: ${result.url}`);
131
- if (result.title)
132
- parts.push(`Title: ${result.title}`);
133
- if (result.elementList)
134
- parts.push(`\nElements:\n${result.elementList}`);
135
132
  return parts.join('\n');
136
133
  }
137
134
  /**
@@ -174,65 +171,45 @@ function createBrowserTools(options) {
174
171
  // The marker is still returned initially via SSE, but we wait for the callback
175
172
  try {
176
173
  const result = await waitForResult(action, args, toolCallId);
177
- return formatResultForLLM(result, action, args);
174
+ return formatResultForLLM(result, action);
178
175
  }
179
176
  catch (error) {
180
177
  const errorMessage = error instanceof Error ? error.message : String(error);
181
- return `❌ **ACTION FAILED**: Browser action "${action}" failed: ${errorMessage}
182
-
183
- **REQUIRED**: Analyze why the action failed and try an alternative approach.`;
178
+ return `Browser action "${action}" failed: ${errorMessage}`;
184
179
  }
185
180
  };
186
181
  };
187
- // browser_click - PRIMARY action for buttons and links
182
+ // browser_click
188
183
  tools.push(tool(createToolFunction('click'), {
189
184
  name: EBrowserTools.CLICK,
190
- description: `Click an element by its [index] from the element list.
191
-
192
- **WHEN TO USE (prioritize this over keypress):**
193
- - Buttons labeled "Send", "Submit", "Save", "OK", "Confirm" CLICK them
194
- - Links (a tags) to navigate
195
- - Checkboxes, radio buttons to select
196
- - Any clickable element that performs an action
197
-
198
- **SEMANTIC ELEMENT IDENTIFICATION:**
199
- - Look for aria-label="Send", aria-label="Submit" for action buttons
200
- - Look for type="submit" for form submission
201
- - Look for button text like "Send", "Submit", "Save"
202
- - For email compose: Find the Send button, DON'T use keyboard shortcuts
203
-
204
- Returns verification: dialog closed, form submitted, URL changed, or NO CHANGE (action may have failed).`,
185
+ description: `Click an element on the current web page by its index number.
186
+ The element list shows clickable items like: [0]<button>Submit</button> [1]<a href="/home">Home</a>
187
+ Use the index number in brackets to click that element.
188
+ After clicking, you receive an updated element list showing the new page state.`,
205
189
  schema: BrowserClickSchema,
206
190
  }));
207
191
  // browser_type
208
192
  tools.push(tool(createToolFunction('type'), {
209
193
  name: EBrowserTools.TYPE,
210
- description: `Type text into an input/textarea element by [index].
211
-
212
- **WHEN TO USE:**
213
- - Input fields (fieldType="email", "search", "phone", etc.)
214
- - Textareas for longer content
215
- - Contenteditable divs (like Gmail compose body)
216
-
217
- **OPTIONS:**
218
- - pressEnter: true → Press Enter after typing (for search forms)
219
- - pressEnter: false → Just type without submitting
220
-
221
- **DO NOT use pressEnter to send emails** - find and CLICK the Send button instead.
222
-
223
- Returns verification showing if text was entered or form was submitted.`,
194
+ description: `Type text into an input element on the page.
195
+ Find the input element in the list by its index (e.g., [5]<input placeholder="Search">).
196
+ Set pressEnter: true to submit forms after typing.
197
+ After typing, you receive an updated element list.`,
224
198
  schema: BrowserTypeSchema,
225
199
  }));
226
200
  // browser_navigate
227
201
  tools.push(tool(createToolFunction('navigate'), {
228
202
  name: EBrowserTools.NAVIGATE,
229
- description: `Navigate to a URL (include https://). Returns new page's element list.`,
203
+ description: `Navigate to a URL. Always include the full URL with https://.
204
+ After navigation, you receive the new page's element list.`,
230
205
  schema: BrowserNavigateSchema,
231
206
  }));
232
207
  // browser_scroll
233
208
  tools.push(tool(createToolFunction('scroll'), {
234
209
  name: EBrowserTools.SCROLL,
235
- description: `Scroll the page. Returns updated element list with newly visible elements.`,
210
+ description: `Scroll the page to reveal more content.
211
+ Use 'down' to scroll down, 'up' to scroll up.
212
+ After scrolling, you receive an updated element list with newly visible elements.`,
236
213
  schema: BrowserScrollSchema,
237
214
  }));
238
215
  // browser_extract
@@ -267,19 +244,27 @@ After going back, you receive the previous page's element list.`,
267
244
  // browser_screenshot
268
245
  tools.push(tool(createToolFunction('screenshot'), {
269
246
  name: EBrowserTools.SCREENSHOT,
270
- description: `Capture a screenshot. Use browser_get_page_state for element list.`,
247
+ description: `Capture a screenshot of the current page.
248
+ Returns the page state with a note that screenshot was displayed to the user.
249
+ Use browser_get_page_state to get the element list for automation.`,
271
250
  schema: BrowserScreenshotSchema,
272
251
  }));
273
252
  // browser_get_page_state
274
253
  tools.push(tool(createToolFunction('get_page_state'), {
275
254
  name: EBrowserTools.GET_PAGE_STATE,
276
- description: `Get current page URL, title, and interactive elements list with index numbers.`,
255
+ description: `Get the current page state including URL, title, and all interactive elements.
256
+ Use this at the start of a task to see what elements are available.
257
+ Returns a text list of elements with their index numbers for interaction.`,
277
258
  schema: BrowserGetPageStateSchema,
278
259
  }));
279
- // browser_select_option
260
+ // browser_select_option - Skyvern-inspired for robust dropdown handling
280
261
  tools.push(tool(createToolFunction('select_option'), {
281
262
  name: EBrowserTools.SELECT_OPTION,
282
- description: `Select an option from a dropdown. Handles both native <select> and custom dropdowns.`,
263
+ description: `Select an option from a dropdown or select element.
264
+ For native <select> elements: finds and selects the option by value/label.
265
+ For custom dropdowns: clicks to open, then clicks the matching option.
266
+ Use this instead of click for dropdowns - it handles both native and custom selects.
267
+ After selection, you receive an updated element list.`,
283
268
  schema: BrowserSelectOptionSchema,
284
269
  }));
285
270
  // browser_upload_file - Skyvern-inspired for file input handling
@@ -291,26 +276,14 @@ The system will download the file and attach it to the input.
291
276
  After upload, you receive an updated element list.`,
292
277
  schema: BrowserUploadFileSchema,
293
278
  }));
294
- // browser_keypress - LAST RESORT for keyboard shortcuts
279
+ // browser_keypress - For keyboard shortcuts and special keys
295
280
  tools.push(tool(createToolFunction('keypress'), {
296
281
  name: EBrowserTools.KEYPRESS,
297
- description: `Press keyboard key(s) - USE ONLY AS LAST RESORT after clicking fails.
298
-
299
- **PREFER browser_click OVER keypress:**
300
- - To send email Find and CLICK the Send button
301
- - To submit form CLICK the Submit button
302
- - To close modal → CLICK the X or Cancel button
303
-
304
- **WHEN TO USE keypress:**
305
- - Navigation: "Tab", "ArrowDown", "ArrowUp" in dropdowns
306
- - Escape to close popups if no X button exists
307
- - Control+A, Control+C for select/copy operations
308
- - ONLY use Enter to submit if there's NO visible submit button
309
-
310
- Single keys: "Enter", "Escape", "Tab", "ArrowDown"
311
- Key combos: "Control+A", "Shift+Enter"
312
-
313
- Returns verification showing if page state changed.`,
282
+ description: `Press keyboard key(s) on the page.
283
+ Single keys: "Enter", "Escape", "Tab", "ArrowDown", "ArrowUp", "Backspace", "Delete"
284
+ Key combos: "Control+A" (select all), "Control+C" (copy), "Shift+Enter" (newline)
285
+ Use this for form submission, closing modals, navigating dropdowns.
286
+ After keypress, you receive an updated element list.`,
314
287
  schema: BrowserKeypressSchema,
315
288
  }));
316
289
  return tools;
@@ -1 +1 @@
1
- {"version":3,"file":"BrowserTools.mjs","sources":["../../../src/tools/BrowserTools.ts"],"sourcesContent":["import { z } from 'zod';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as _t from '@/types';\n\n/**\n * Browser tool names - keep in sync with ranger-browser extension\n * These tools execute locally in the browser extension, NOT on the server\n */\nexport const EBrowserTools = {\n CLICK: 'browser_click',\n TYPE: 'browser_type',\n NAVIGATE: 'browser_navigate',\n SCROLL: 'browser_scroll',\n EXTRACT: 'browser_extract',\n HOVER: 'browser_hover',\n WAIT: 'browser_wait',\n BACK: 'browser_back',\n SCREENSHOT: 'browser_screenshot',\n GET_PAGE_STATE: 'browser_get_page_state',\n // Skyvern-inspired additions for robust form handling\n SELECT_OPTION: 'browser_select_option',\n UPLOAD_FILE: 'browser_upload_file',\n KEYPRESS: 'browser_keypress',\n} as const;\n\nexport type BrowserToolName =\n (typeof EBrowserTools)[keyof typeof EBrowserTools];\n\n/**\n * Callback function type for waiting on browser action results\n * This allows the server (Ranger) to provide a callback that waits for the extension\n * to POST results back to the server before returning to the LLM.\n *\n * @param action - The browser action (click, type, navigate, etc.)\n * @param args - Arguments for the action\n * @param toolCallId - Unique ID for this tool call (from config.toolCall.id)\n * @returns Promise that resolves with the actual browser result (page state, etc.)\n */\nexport type BrowserToolCallback = (\n action: string,\n args: Record<string, unknown>,\n toolCallId: string\n) => Promise<BrowserActionResult>;\n\n/**\n * Action status - matches Skyvern's ActionStatus\n */\nexport type ActionStatus = 'pending' | 'completed' | 'failed' | 'skipped';\n\n/**\n * Verification status - matches Skyvern's VerificationStatus\n * - complete: Goal achieved\n * - terminate: Goal cannot be achieved, stop\n * - continue: Goal not yet achieved, keep going\n */\nexport type VerificationStatus = 'complete' | 'terminate' | 'continue';\n\n/**\n * Result returned from browser action execution\n */\nexport interface BrowserActionResult {\n success: boolean;\n status?: ActionStatus;\n url?: string;\n title?: string;\n elementList?: string;\n error?: string;\n errorType?: string; // Typed error classification\n screenshot?: string;\n elementDescription?: string;\n // State verification (before/after comparison)\n verification?: {\n urlChanged: boolean;\n titleChanged: boolean;\n elementCountDelta: number;\n significantChange: boolean;\n dialogClosed: boolean;\n formGone: boolean;\n changeDescription: string;\n };\n}\n\n/**\n * Check if browser capability is available based on request headers or context\n * The browser extension sets these headers when connected:\n * - X-Ranger-Browser-Extension: true\n * - X-Ranger-Browser-Capable: true\n */\nexport function hasBrowserCapability(req?: {\n headers?: Record<string, string | string[] | undefined>;\n}): boolean {\n if (!req?.headers) {\n return false;\n }\n\n const browserExtension = req.headers['x-ranger-browser-extension'];\n const browserCapable = req.headers['x-ranger-browser-capable'];\n\n return browserExtension === 'true' || browserCapable === 'true';\n}\n\n// Tool schemas\nconst BrowserClickSchema = z.object({\n index: z\n .number()\n .describe(\n 'The index number [0], [1], etc. of the element to click from the page state element list'\n ),\n});\n\nconst BrowserTypeSchema = z.object({\n index: z\n .number()\n .describe('The index number of the input element to type into'),\n text: z.string().describe('The text to type into the element'),\n pressEnter: z\n .boolean()\n .optional()\n .describe('Whether to press Enter after typing (useful for search forms)'),\n});\n\nconst BrowserNavigateSchema = z.object({\n url: z\n .string()\n .describe('The full URL to navigate to (must include https://)'),\n});\n\nconst BrowserScrollSchema = z.object({\n direction: z\n .enum(['up', 'down', 'left', 'right'])\n .describe('Direction to scroll'),\n amount: z\n .number()\n .optional()\n .describe('Pixels to scroll (default: one viewport height)'),\n});\n\nconst BrowserExtractSchema = z.object({\n query: z\n .string()\n .optional()\n .describe('Optional: specific content to extract from the page'),\n});\n\nconst BrowserHoverSchema = z.object({\n index: z.number().describe('The index number of the element to hover over'),\n});\n\nconst BrowserWaitSchema = z.object({\n duration: z\n .number()\n .optional()\n .describe('Milliseconds to wait (default: 1000)'),\n});\n\nconst BrowserBackSchema = z.object({});\n\nconst BrowserScreenshotSchema = z.object({});\n\nconst BrowserGetPageStateSchema = z.object({});\n\n// Skyvern-inspired schemas for robust form handling\nconst BrowserSelectOptionSchema = z.object({\n index: z\n .number()\n .describe('The index number of the select/dropdown element'),\n value: z\n .string()\n .optional()\n .describe('The value or label of the option to select. For native <select>, use the option text. For custom dropdowns, this is the option label to click.'),\n});\n\nconst BrowserUploadFileSchema = z.object({\n index: z\n .number()\n .describe('The index number of the file input element'),\n fileUrl: z\n .string()\n .describe('URL of the file to upload (the system will download and upload it)'),\n});\n\nconst BrowserKeypressSchema = z.object({\n keys: z\n .string()\n .describe('Key(s) to press. Single key: \"Enter\", \"Escape\", \"Tab\", \"ArrowDown\". Combo: \"Control+A\", \"Shift+Enter\"'),\n});\n\n/**\n * Browser tool response interface\n * This is what the extension returns after executing the action\n */\nexport interface BrowserToolResponse {\n requiresBrowserExecution: true;\n action: string;\n args: Record<string, unknown>;\n toolCallId?: string; // Added to help extension correlate with callback\n}\n\n/**\n * Options for creating browser tools\n */\nexport interface CreateBrowserToolsOptions {\n /**\n * Optional callback that waits for browser action results.\n * When provided, tools will await this callback to get actual results from the extension.\n * When not provided, tools return markers immediately (for non-server contexts).\n */\n waitForResult?: BrowserToolCallback;\n}\n\n/**\n * Format browser action result for LLM consumption\n */\nfunction formatResultForLLM(\n result: BrowserActionResult,\n action: string,\n actionArgs?: Record<string, unknown>\n): string {\n if (!result.success && result.error) {\n const errorType = result.errorType ? `[${result.errorType}] ` : '';\n return `${errorType}Action \"${action}\" failed: ${result.error}`;\n }\n\n const parts: string[] = [];\n\n // Verification result (Skyvern pattern)\n if (result.verification) {\n const v = result.verification;\n if (v.dialogClosed || v.formGone || v.urlChanged) {\n parts.push(`✓ ${v.changeDescription}`);\n } else if (!v.significantChange) {\n parts.push(`⚠ No change detected`);\n }\n }\n\n // Page state\n if (result.url) parts.push(`URL: ${result.url}`);\n if (result.title) parts.push(`Title: ${result.title}`);\n if (result.elementList) parts.push(`\\nElements:\\n${result.elementList}`);\n\n return parts.join('\\n');\n}\n\n/**\n * Create browser tools with optional callback for waiting on results\n *\n * When waitForResult callback is provided:\n * 1. Tool returns marker that triggers extension\n * 2. Tool then awaits callback to get actual results\n * 3. Returns real page state to LLM\n *\n * When no callback:\n * 1. Tool returns marker only (for non-server contexts)\n *\n * NOTE: These tools use TEXT-BASED element lists, NOT screenshots\n * Screenshots would be 100K+ tokens each - element lists are ~100 tokens\n */\nexport function createBrowserTools(\n options?: CreateBrowserToolsOptions\n): DynamicStructuredTool[] {\n const { waitForResult } = options || {};\n const tools: DynamicStructuredTool[] = [];\n\n /**\n * Helper to create tool function that optionally waits for results\n * The toolCallId is extracted from the RunnableConfig passed by LangChain\n */\n const createToolFunction = (action: string) => {\n return async (\n args: Record<string, unknown>,\n config?: { toolCall?: { id?: string } }\n ): Promise<string> => {\n const toolCallId =\n config?.toolCall?.id ??\n `tool_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n\n // Create marker for extension\n const marker: BrowserToolResponse = {\n requiresBrowserExecution: true,\n action,\n args,\n toolCallId,\n };\n\n // If no callback, return marker immediately (extension handles via SSE interception)\n if (!waitForResult) {\n return JSON.stringify(marker);\n }\n\n // With callback: wait for actual results from extension\n // The marker is still returned initially via SSE, but we wait for the callback\n try {\n const result = await waitForResult(action, args, toolCallId);\n return formatResultForLLM(result, action, args);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n return `❌ **ACTION FAILED**: Browser action \"${action}\" failed: ${errorMessage}\n\n**REQUIRED**: Analyze why the action failed and try an alternative approach.`;\n }\n };\n };\n\n // browser_click - PRIMARY action for buttons and links\n tools.push(\n tool(createToolFunction('click'), {\n name: EBrowserTools.CLICK,\n description: `Click an element by its [index] from the element list.\n\n**WHEN TO USE (prioritize this over keypress):**\n- Buttons labeled \"Send\", \"Submit\", \"Save\", \"OK\", \"Confirm\" → CLICK them\n- Links (a tags) to navigate\n- Checkboxes, radio buttons to select\n- Any clickable element that performs an action\n\n**SEMANTIC ELEMENT IDENTIFICATION:**\n- Look for aria-label=\"Send\", aria-label=\"Submit\" for action buttons\n- Look for type=\"submit\" for form submission\n- Look for button text like \"Send\", \"Submit\", \"Save\"\n- For email compose: Find the Send button, DON'T use keyboard shortcuts\n\nReturns verification: dialog closed, form submitted, URL changed, or NO CHANGE (action may have failed).`,\n schema: BrowserClickSchema,\n })\n );\n\n // browser_type\n tools.push(\n tool(createToolFunction('type'), {\n name: EBrowserTools.TYPE,\n description: `Type text into an input/textarea element by [index].\n\n**WHEN TO USE:**\n- Input fields (fieldType=\"email\", \"search\", \"phone\", etc.)\n- Textareas for longer content\n- Contenteditable divs (like Gmail compose body)\n\n**OPTIONS:**\n- pressEnter: true → Press Enter after typing (for search forms)\n- pressEnter: false → Just type without submitting\n\n**DO NOT use pressEnter to send emails** - find and CLICK the Send button instead.\n\nReturns verification showing if text was entered or form was submitted.`,\n schema: BrowserTypeSchema,\n })\n );\n\n // browser_navigate\n tools.push(\n tool(createToolFunction('navigate'), {\n name: EBrowserTools.NAVIGATE,\n description: `Navigate to a URL (include https://). Returns new page's element list.`,\n schema: BrowserNavigateSchema,\n })\n );\n\n // browser_scroll\n tools.push(\n tool(createToolFunction('scroll'), {\n name: EBrowserTools.SCROLL,\n description: `Scroll the page. Returns updated element list with newly visible elements.`,\n schema: BrowserScrollSchema,\n })\n );\n\n // browser_extract\n tools.push(\n tool(createToolFunction('extract'), {\n name: EBrowserTools.EXTRACT,\n description: `Extract content from the current page.\nReturns page URL, title, and element list.`,\n schema: BrowserExtractSchema,\n })\n );\n\n // browser_hover\n tools.push(\n tool(createToolFunction('hover'), {\n name: EBrowserTools.HOVER,\n description: `Hover over an element to reveal tooltips, dropdowns, or other hover-triggered content.\nAfter hovering, you receive an updated element list with any newly revealed elements.`,\n schema: BrowserHoverSchema,\n })\n );\n\n // browser_wait\n tools.push(\n tool(createToolFunction('wait'), {\n name: EBrowserTools.WAIT,\n description: `Wait for a specified duration for page content to load.\nUse this after actions that trigger async content loading.\nAfter waiting, you receive an updated element list.`,\n schema: BrowserWaitSchema,\n })\n );\n\n // browser_back\n tools.push(\n tool(createToolFunction('back'), {\n name: EBrowserTools.BACK,\n description: `Go back to the previous page in browser history.\nAfter going back, you receive the previous page's element list.`,\n schema: BrowserBackSchema,\n })\n );\n\n // browser_screenshot\n tools.push(\n tool(createToolFunction('screenshot'), {\n name: EBrowserTools.SCREENSHOT,\n description: `Capture a screenshot. Use browser_get_page_state for element list.`,\n schema: BrowserScreenshotSchema,\n })\n );\n\n // browser_get_page_state\n tools.push(\n tool(createToolFunction('get_page_state'), {\n name: EBrowserTools.GET_PAGE_STATE,\n description: `Get current page URL, title, and interactive elements list with index numbers.`,\n schema: BrowserGetPageStateSchema,\n })\n );\n\n // browser_select_option\n tools.push(\n tool(createToolFunction('select_option'), {\n name: EBrowserTools.SELECT_OPTION,\n description: `Select an option from a dropdown. Handles both native <select> and custom dropdowns.`,\n schema: BrowserSelectOptionSchema,\n })\n );\n\n // browser_upload_file - Skyvern-inspired for file input handling\n tools.push(\n tool(createToolFunction('upload_file'), {\n name: EBrowserTools.UPLOAD_FILE,\n description: `Upload a file to a file input element.\nProvide the index of the file input and the URL of the file to upload.\nThe system will download the file and attach it to the input.\nAfter upload, you receive an updated element list.`,\n schema: BrowserUploadFileSchema,\n })\n );\n\n // browser_keypress - LAST RESORT for keyboard shortcuts\n tools.push(\n tool(createToolFunction('keypress'), {\n name: EBrowserTools.KEYPRESS,\n description: `Press keyboard key(s) - USE ONLY AS LAST RESORT after clicking fails.\n\n**PREFER browser_click OVER keypress:**\n- To send email → Find and CLICK the Send button\n- To submit form → CLICK the Submit button\n- To close modal → CLICK the X or Cancel button\n\n**WHEN TO USE keypress:**\n- Navigation: \"Tab\", \"ArrowDown\", \"ArrowUp\" in dropdowns\n- Escape to close popups if no X button exists\n- Control+A, Control+C for select/copy operations\n- ONLY use Enter to submit if there's NO visible submit button\n\nSingle keys: \"Enter\", \"Escape\", \"Tab\", \"ArrowDown\"\nKey combos: \"Control+A\", \"Shift+Enter\"\n\nReturns verification showing if page state changed.`,\n schema: BrowserKeypressSchema,\n })\n );\n\n return tools;\n}\n"],"names":[],"mappings":";;;AAIA;;;AAGG;AACU,MAAA,aAAa,GAAG;AAC3B,IAAA,KAAK,EAAE,eAAe;AACtB,IAAA,IAAI,EAAE,cAAc;AACpB,IAAA,QAAQ,EAAE,kBAAkB;AAC5B,IAAA,MAAM,EAAE,gBAAgB;AACxB,IAAA,OAAO,EAAE,iBAAiB;AAC1B,IAAA,KAAK,EAAE,eAAe;AACtB,IAAA,IAAI,EAAE,cAAc;AACpB,IAAA,IAAI,EAAE,cAAc;AACpB,IAAA,UAAU,EAAE,oBAAoB;AAChC,IAAA,cAAc,EAAE,wBAAwB;;AAExC,IAAA,aAAa,EAAE,uBAAuB;AACtC,IAAA,WAAW,EAAE,qBAAqB;AAClC,IAAA,QAAQ,EAAE,kBAAkB;;AA4D9B;;;;;AAKG;AACG,SAAU,oBAAoB,CAAC,GAEpC,EAAA;AACC,IAAA,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE;AACjB,QAAA,OAAO,KAAK;;IAGd,MAAM,gBAAgB,GAAG,GAAG,CAAC,OAAO,CAAC,4BAA4B,CAAC;IAClE,MAAM,cAAc,GAAG,GAAG,CAAC,OAAO,CAAC,0BAA0B,CAAC;AAE9D,IAAA,OAAO,gBAAgB,KAAK,MAAM,IAAI,cAAc,KAAK,MAA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":["import { z } from 'zod';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as _t from '@/types';\n\n/**\n * Browser tool names - keep in sync with ranger-browser extension\n * These tools execute locally in the browser extension, NOT on the server\n */\nexport const EBrowserTools = {\n CLICK: 'browser_click',\n TYPE: 'browser_type',\n NAVIGATE: 'browser_navigate',\n SCROLL: 'browser_scroll',\n EXTRACT: 'browser_extract',\n HOVER: 'browser_hover',\n WAIT: 'browser_wait',\n BACK: 'browser_back',\n SCREENSHOT: 'browser_screenshot',\n GET_PAGE_STATE: 'browser_get_page_state',\n // Skyvern-inspired additions for robust form handling\n SELECT_OPTION: 'browser_select_option',\n UPLOAD_FILE: 'browser_upload_file',\n KEYPRESS: 'browser_keypress',\n} as const;\n\nexport type BrowserToolName =\n (typeof EBrowserTools)[keyof typeof EBrowserTools];\n\n/**\n * Callback function type for waiting on browser action results\n * This allows the server (Ranger) to provide a callback that waits for the extension\n * to POST results back to the server before returning to the LLM.\n *\n * @param action - The browser action (click, type, navigate, etc.)\n * @param args - Arguments for the action\n * @param toolCallId - Unique ID for this tool call (from config.toolCall.id)\n * @returns Promise that resolves with the actual browser result (page state, etc.)\n */\nexport type BrowserToolCallback = (\n action: string,\n args: Record<string, unknown>,\n toolCallId: string\n) => Promise<BrowserActionResult>;\n\n/**\n * Result returned from browser action execution\n */\nexport interface BrowserActionResult {\n success: boolean;\n url?: string;\n title?: string;\n elementList?: string; // Text-based element list\n error?: string;\n screenshot?: string; // Base64 screenshot (if requested)\n}\n\n/**\n * Check if browser capability is available based on request headers or context\n * The browser extension sets these headers when connected:\n * - X-Ranger-Browser-Extension: true\n * - X-Ranger-Browser-Capable: true\n */\nexport function hasBrowserCapability(req?: {\n headers?: Record<string, string | string[] | undefined>;\n}): boolean {\n if (!req?.headers) {\n return false;\n }\n\n const browserExtension = req.headers['x-ranger-browser-extension'];\n const browserCapable = req.headers['x-ranger-browser-capable'];\n\n return browserExtension === 'true' || browserCapable === 'true';\n}\n\n// Tool schemas\nconst BrowserClickSchema = z.object({\n index: z\n .number()\n .describe(\n 'The index number [0], [1], etc. of the element to click from the page state element list'\n ),\n});\n\nconst BrowserTypeSchema = z.object({\n index: z\n .number()\n .describe('The index number of the input element to type into'),\n text: z.string().describe('The text to type into the element'),\n pressEnter: z\n .boolean()\n .optional()\n .describe('Whether to press Enter after typing (useful for search forms)'),\n});\n\nconst BrowserNavigateSchema = z.object({\n url: z\n .string()\n .describe('The full URL to navigate to (must include https://)'),\n});\n\nconst BrowserScrollSchema = z.object({\n direction: z\n .enum(['up', 'down', 'left', 'right'])\n .describe('Direction to scroll'),\n amount: z\n .number()\n .optional()\n .describe('Pixels to scroll (default: one viewport height)'),\n});\n\nconst BrowserExtractSchema = z.object({\n query: z\n .string()\n .optional()\n .describe('Optional: specific content to extract from the page'),\n});\n\nconst BrowserHoverSchema = z.object({\n index: z.number().describe('The index number of the element to hover over'),\n});\n\nconst BrowserWaitSchema = z.object({\n duration: z\n .number()\n .optional()\n .describe('Milliseconds to wait (default: 1000)'),\n});\n\nconst BrowserBackSchema = z.object({});\n\nconst BrowserScreenshotSchema = z.object({});\n\nconst BrowserGetPageStateSchema = z.object({});\n\n// Skyvern-inspired schemas for robust form handling\nconst BrowserSelectOptionSchema = z.object({\n index: z\n .number()\n .describe('The index number of the select/dropdown element'),\n value: z\n .string()\n .optional()\n .describe('The value or label of the option to select. For native <select>, use the option text. For custom dropdowns, this is the option label to click.'),\n});\n\nconst BrowserUploadFileSchema = z.object({\n index: z\n .number()\n .describe('The index number of the file input element'),\n fileUrl: z\n .string()\n .describe('URL of the file to upload (the system will download and upload it)'),\n});\n\nconst BrowserKeypressSchema = z.object({\n keys: z\n .string()\n .describe('Key(s) to press. Single key: \"Enter\", \"Escape\", \"Tab\", \"ArrowDown\". Combo: \"Control+A\", \"Shift+Enter\"'),\n});\n\n/**\n * Browser tool response interface\n * This is what the extension returns after executing the action\n */\nexport interface BrowserToolResponse {\n requiresBrowserExecution: true;\n action: string;\n args: Record<string, unknown>;\n toolCallId?: string; // Added to help extension correlate with callback\n}\n\n/**\n * Options for creating browser tools\n */\nexport interface CreateBrowserToolsOptions {\n /**\n * Optional callback that waits for browser action results.\n * When provided, tools will await this callback to get actual results from the extension.\n * When not provided, tools return markers immediately (for non-server contexts).\n */\n waitForResult?: BrowserToolCallback;\n}\n\n/**\n * Format browser action result for LLM consumption\n */\nfunction formatResultForLLM(\n result: BrowserActionResult,\n action: string\n): string {\n if (!result.success && result.error) {\n return `Browser action \"${action}\" failed: ${result.error}`;\n }\n\n const parts: string[] = [];\n\n if (result.url != null && result.url !== '') {\n parts.push(`**Current URL:** ${result.url}`);\n }\n if (result.title != null && result.title !== '') {\n parts.push(`**Page Title:** ${result.title}`);\n }\n if (result.elementList != null && result.elementList !== '') {\n parts.push(`\\n**Interactive Elements:**\\n${result.elementList}`);\n }\n if (result.screenshot != null && result.screenshot !== '') {\n parts.push('\\n[Screenshot captured and displayed to user]');\n }\n\n if (parts.length === 0) {\n return `Browser action \"${action}\" completed successfully.`;\n }\n\n return parts.join('\\n');\n}\n\n/**\n * Create browser tools with optional callback for waiting on results\n *\n * When waitForResult callback is provided:\n * 1. Tool returns marker that triggers extension\n * 2. Tool then awaits callback to get actual results\n * 3. Returns real page state to LLM\n *\n * When no callback:\n * 1. Tool returns marker only (for non-server contexts)\n *\n * NOTE: These tools use TEXT-BASED element lists, NOT screenshots\n * Screenshots would be 100K+ tokens each - element lists are ~100 tokens\n */\nexport function createBrowserTools(\n options?: CreateBrowserToolsOptions\n): DynamicStructuredTool[] {\n const { waitForResult } = options || {};\n const tools: DynamicStructuredTool[] = [];\n\n /**\n * Helper to create tool function that optionally waits for results\n * The toolCallId is extracted from the RunnableConfig passed by LangChain\n */\n const createToolFunction = (action: string) => {\n return async (\n args: Record<string, unknown>,\n config?: { toolCall?: { id?: string } }\n ): Promise<string> => {\n const toolCallId =\n config?.toolCall?.id ??\n `tool_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n\n // Create marker for extension\n const marker: BrowserToolResponse = {\n requiresBrowserExecution: true,\n action,\n args,\n toolCallId,\n };\n\n // If no callback, return marker immediately (extension handles via SSE interception)\n if (!waitForResult) {\n return JSON.stringify(marker);\n }\n\n // With callback: wait for actual results from extension\n // The marker is still returned initially via SSE, but we wait for the callback\n try {\n const result = await waitForResult(action, args, toolCallId);\n return formatResultForLLM(result, action);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n return `Browser action \"${action}\" failed: ${errorMessage}`;\n }\n };\n };\n\n // browser_click\n tools.push(\n tool(createToolFunction('click'), {\n name: EBrowserTools.CLICK,\n description: `Click an element on the current web page by its index number.\nThe element list shows clickable items like: [0]<button>Submit</button> [1]<a href=\"/home\">Home</a>\nUse the index number in brackets to click that element.\nAfter clicking, you receive an updated element list showing the new page state.`,\n schema: BrowserClickSchema,\n })\n );\n\n // browser_type\n tools.push(\n tool(createToolFunction('type'), {\n name: EBrowserTools.TYPE,\n description: `Type text into an input element on the page.\nFind the input element in the list by its index (e.g., [5]<input placeholder=\"Search\">).\nSet pressEnter: true to submit forms after typing.\nAfter typing, you receive an updated element list.`,\n schema: BrowserTypeSchema,\n })\n );\n\n // browser_navigate\n tools.push(\n tool(createToolFunction('navigate'), {\n name: EBrowserTools.NAVIGATE,\n description: `Navigate to a URL. Always include the full URL with https://.\nAfter navigation, you receive the new page's element list.`,\n schema: BrowserNavigateSchema,\n })\n );\n\n // browser_scroll\n tools.push(\n tool(createToolFunction('scroll'), {\n name: EBrowserTools.SCROLL,\n description: `Scroll the page to reveal more content.\nUse 'down' to scroll down, 'up' to scroll up.\nAfter scrolling, you receive an updated element list with newly visible elements.`,\n schema: BrowserScrollSchema,\n })\n );\n\n // browser_extract\n tools.push(\n tool(createToolFunction('extract'), {\n name: EBrowserTools.EXTRACT,\n description: `Extract content from the current page.\nReturns page URL, title, and element list.`,\n schema: BrowserExtractSchema,\n })\n );\n\n // browser_hover\n tools.push(\n tool(createToolFunction('hover'), {\n name: EBrowserTools.HOVER,\n description: `Hover over an element to reveal tooltips, dropdowns, or other hover-triggered content.\nAfter hovering, you receive an updated element list with any newly revealed elements.`,\n schema: BrowserHoverSchema,\n })\n );\n\n // browser_wait\n tools.push(\n tool(createToolFunction('wait'), {\n name: EBrowserTools.WAIT,\n description: `Wait for a specified duration for page content to load.\nUse this after actions that trigger async content loading.\nAfter waiting, you receive an updated element list.`,\n schema: BrowserWaitSchema,\n })\n );\n\n // browser_back\n tools.push(\n tool(createToolFunction('back'), {\n name: EBrowserTools.BACK,\n description: `Go back to the previous page in browser history.\nAfter going back, you receive the previous page's element list.`,\n schema: BrowserBackSchema,\n })\n );\n\n // browser_screenshot\n tools.push(\n tool(createToolFunction('screenshot'), {\n name: EBrowserTools.SCREENSHOT,\n description: `Capture a screenshot of the current page.\nReturns the page state with a note that screenshot was displayed to the user.\nUse browser_get_page_state to get the element list for automation.`,\n schema: BrowserScreenshotSchema,\n })\n );\n\n // browser_get_page_state\n tools.push(\n tool(createToolFunction('get_page_state'), {\n name: EBrowserTools.GET_PAGE_STATE,\n description: `Get the current page state including URL, title, and all interactive elements.\nUse this at the start of a task to see what elements are available.\nReturns a text list of elements with their index numbers for interaction.`,\n schema: BrowserGetPageStateSchema,\n })\n );\n\n // browser_select_option - Skyvern-inspired for robust dropdown handling\n tools.push(\n tool(createToolFunction('select_option'), {\n name: EBrowserTools.SELECT_OPTION,\n description: `Select an option from a dropdown or select element.\nFor native <select> elements: finds and selects the option by value/label.\nFor custom dropdowns: clicks to open, then clicks the matching option.\nUse this instead of click for dropdowns - it handles both native and custom selects.\nAfter selection, you receive an updated element list.`,\n schema: BrowserSelectOptionSchema,\n })\n );\n\n // browser_upload_file - Skyvern-inspired for file input handling\n tools.push(\n tool(createToolFunction('upload_file'), {\n name: EBrowserTools.UPLOAD_FILE,\n description: `Upload a file to a file input element.\nProvide the index of the file input and the URL of the file to upload.\nThe system will download the file and attach it to the input.\nAfter upload, you receive an updated element list.`,\n schema: BrowserUploadFileSchema,\n })\n );\n\n // browser_keypress - For keyboard shortcuts and special keys\n tools.push(\n tool(createToolFunction('keypress'), {\n name: EBrowserTools.KEYPRESS,\n description: `Press keyboard key(s) on the page.\nSingle keys: \"Enter\", \"Escape\", \"Tab\", \"ArrowDown\", \"ArrowUp\", \"Backspace\", \"Delete\"\nKey combos: \"Control+A\" (select all), \"Control+C\" (copy), \"Shift+Enter\" (newline)\nUse this for form submission, closing modals, navigating dropdowns.\nAfter keypress, you receive an updated element list.`,\n schema: BrowserKeypressSchema,\n })\n );\n\n return tools;\n}\n"],"names":[],"mappings":";;;AAIA;;;AAGG;AACU,MAAA,aAAa,GAAG;AAC3B,IAAA,KAAK,EAAE,eAAe;AACtB,IAAA,IAAI,EAAE,cAAc;AACpB,IAAA,QAAQ,EAAE,kBAAkB;AAC5B,IAAA,MAAM,EAAE,gBAAgB;AACxB,IAAA,OAAO,EAAE,iBAAiB;AAC1B,IAAA,KAAK,EAAE,eAAe;AACtB,IAAA,IAAI,EAAE,cAAc;AACpB,IAAA,IAAI,EAAE,cAAc;AACpB,IAAA,UAAU,EAAE,oBAAoB;AAChC,IAAA,cAAc,EAAE,wBAAwB;;AAExC,IAAA,aAAa,EAAE,uBAAuB;AACtC,IAAA,WAAW,EAAE,qBAAqB;AAClC,IAAA,QAAQ,EAAE,kBAAkB;;AAkC9B;;;;;AAKG;AACG,SAAU,oBAAoB,CAAC,GAEpC,EAAA;AACC,IAAA,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE;AACjB,QAAA,OAAO,KAAK;;IAGd,MAAM,gBAAgB,GAAG,GAAG,CAAC,OAAO,CAAC,4BAA4B,CAAC;IAClE,MAAM,cAAc,GAAG,GAAG,CAAC,OAAO,CAAC,0BAA0B,CAAC;AAE9D,IAAA,OAAO,gBAAgB,KAAK,MAAM,IAAI,cAAc,KAAK,MAAM;AACjE;AAEA;AACA,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;AAClC,IAAA,KAAK,EAAE;AACJ,SA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;AAC7D,QAAA,MAAM,EAAE,uBAAuB;AAChC,KAAA,CAAC,CACH;;IAGD,KAAK,CAAC,IAAI,CACR,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,EAAE;QACzC,IAAI,EAAE,aAAa,CAAC,cAAc;AAClC,QAAA,WAAW,EAAE,CAAA;;AAEuD,yEAAA,CAAA;AACpE,QAAA,MAAM,EAAE,yBAAyB;AAClC,KAAA,CAAC,CACH;;IAGD,KAAK,CAAC,IAAI,CACR,IAAI,CAAC,kBAAkB,CAAC,eAAe,CAAC,EAAE;QACxC,IAAI,EAAE,aAAa,CAAC,aAAa;AACjC,QAAA,WAAW,EAAE,CAAA;;;;AAImC,qDAAA,CAAA;AAChD,QAAA,MAAM,EAAE,yBAAyB;AAClC,KAAA,CAAC,CACH;;IAGD,KAAK,CAAC,IAAI,CACR,IAAI,CAAC,kBAAkB,CAAC,aAAa,CAAC,EAAE;QACtC,IAAI,EAAE,aAAa,CAAC,WAAW;AAC/B,QAAA,WAAW,EAAE,CAAA;;;AAGgC,kDAAA,CAAA;AAC7C,QAAA,MAAM,EAAE,uBAAuB;AAChC,KAAA,CAAC,CACH;;IAGD,KAAK,CAAC,IAAI,CACR,IAAI,CAAC,kBAAkB,CAAC,UAAU,CAAC,EAAE;QACnC,IAAI,EAAE,aAAa,CAAC,QAAQ;AAC5B,QAAA,WAAW,EAAE,CAAA;;;;AAIkC,oDAAA,CAAA;AAC/C,QAAA,MAAM,EAAE,qBAAqB;AAC9B,KAAA,CAAC,CACH;AAED,IAAA,OAAO,KAAK;AACd;;;;"}
@@ -30,39 +30,16 @@ export type BrowserToolName = (typeof EBrowserTools)[keyof typeof EBrowserTools]
30
30
  * @returns Promise that resolves with the actual browser result (page state, etc.)
31
31
  */
32
32
  export type BrowserToolCallback = (action: string, args: Record<string, unknown>, toolCallId: string) => Promise<BrowserActionResult>;
33
- /**
34
- * Action status - matches Skyvern's ActionStatus
35
- */
36
- export type ActionStatus = 'pending' | 'completed' | 'failed' | 'skipped';
37
- /**
38
- * Verification status - matches Skyvern's VerificationStatus
39
- * - complete: Goal achieved
40
- * - terminate: Goal cannot be achieved, stop
41
- * - continue: Goal not yet achieved, keep going
42
- */
43
- export type VerificationStatus = 'complete' | 'terminate' | 'continue';
44
33
  /**
45
34
  * Result returned from browser action execution
46
35
  */
47
36
  export interface BrowserActionResult {
48
37
  success: boolean;
49
- status?: ActionStatus;
50
38
  url?: string;
51
39
  title?: string;
52
40
  elementList?: string;
53
41
  error?: string;
54
- errorType?: string;
55
42
  screenshot?: string;
56
- elementDescription?: string;
57
- verification?: {
58
- urlChanged: boolean;
59
- titleChanged: boolean;
60
- elementCountDelta: number;
61
- significantChange: boolean;
62
- dialogClosed: boolean;
63
- formGone: boolean;
64
- changeDescription: string;
65
- };
66
43
  }
67
44
  /**
68
45
  * Check if browser capability is available based on request headers or context
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "illuma-agents",
3
- "version": "1.0.31",
3
+ "version": "1.0.32",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -42,42 +42,16 @@ export type BrowserToolCallback = (
42
42
  toolCallId: string
43
43
  ) => Promise<BrowserActionResult>;
44
44
 
45
- /**
46
- * Action status - matches Skyvern's ActionStatus
47
- */
48
- export type ActionStatus = 'pending' | 'completed' | 'failed' | 'skipped';
49
-
50
- /**
51
- * Verification status - matches Skyvern's VerificationStatus
52
- * - complete: Goal achieved
53
- * - terminate: Goal cannot be achieved, stop
54
- * - continue: Goal not yet achieved, keep going
55
- */
56
- export type VerificationStatus = 'complete' | 'terminate' | 'continue';
57
-
58
45
  /**
59
46
  * Result returned from browser action execution
60
47
  */
61
48
  export interface BrowserActionResult {
62
49
  success: boolean;
63
- status?: ActionStatus;
64
50
  url?: string;
65
51
  title?: string;
66
- elementList?: string;
52
+ elementList?: string; // Text-based element list
67
53
  error?: string;
68
- errorType?: string; // Typed error classification
69
- screenshot?: string;
70
- elementDescription?: string;
71
- // State verification (before/after comparison)
72
- verification?: {
73
- urlChanged: boolean;
74
- titleChanged: boolean;
75
- elementCountDelta: number;
76
- significantChange: boolean;
77
- dialogClosed: boolean;
78
- formGone: boolean;
79
- changeDescription: string;
80
- };
54
+ screenshot?: string; // Base64 screenshot (if requested)
81
55
  }
82
56
 
83
57
  /**
@@ -213,30 +187,30 @@ export interface CreateBrowserToolsOptions {
213
187
  */
214
188
  function formatResultForLLM(
215
189
  result: BrowserActionResult,
216
- action: string,
217
- actionArgs?: Record<string, unknown>
190
+ action: string
218
191
  ): string {
219
192
  if (!result.success && result.error) {
220
- const errorType = result.errorType ? `[${result.errorType}] ` : '';
221
- return `${errorType}Action "${action}" failed: ${result.error}`;
193
+ return `Browser action "${action}" failed: ${result.error}`;
222
194
  }
223
195
 
224
196
  const parts: string[] = [];
225
197
 
226
- // Verification result (Skyvern pattern)
227
- if (result.verification) {
228
- const v = result.verification;
229
- if (v.dialogClosed || v.formGone || v.urlChanged) {
230
- parts.push(`✓ ${v.changeDescription}`);
231
- } else if (!v.significantChange) {
232
- parts.push(`⚠ No change detected`);
233
- }
198
+ if (result.url != null && result.url !== '') {
199
+ parts.push(`**Current URL:** ${result.url}`);
200
+ }
201
+ if (result.title != null && result.title !== '') {
202
+ parts.push(`**Page Title:** ${result.title}`);
203
+ }
204
+ if (result.elementList != null && result.elementList !== '') {
205
+ parts.push(`\n**Interactive Elements:**\n${result.elementList}`);
206
+ }
207
+ if (result.screenshot != null && result.screenshot !== '') {
208
+ parts.push('\n[Screenshot captured and displayed to user]');
234
209
  }
235
210
 
236
- // Page state
237
- if (result.url) parts.push(`URL: ${result.url}`);
238
- if (result.title) parts.push(`Title: ${result.title}`);
239
- if (result.elementList) parts.push(`\nElements:\n${result.elementList}`);
211
+ if (parts.length === 0) {
212
+ return `Browser action "${action}" completed successfully.`;
213
+ }
240
214
 
241
215
  return parts.join('\n');
242
216
  }
@@ -291,36 +265,23 @@ export function createBrowserTools(
291
265
  // The marker is still returned initially via SSE, but we wait for the callback
292
266
  try {
293
267
  const result = await waitForResult(action, args, toolCallId);
294
- return formatResultForLLM(result, action, args);
268
+ return formatResultForLLM(result, action);
295
269
  } catch (error) {
296
270
  const errorMessage =
297
271
  error instanceof Error ? error.message : String(error);
298
- return `❌ **ACTION FAILED**: Browser action "${action}" failed: ${errorMessage}
299
-
300
- **REQUIRED**: Analyze why the action failed and try an alternative approach.`;
272
+ return `Browser action "${action}" failed: ${errorMessage}`;
301
273
  }
302
274
  };
303
275
  };
304
276
 
305
- // browser_click - PRIMARY action for buttons and links
277
+ // browser_click
306
278
  tools.push(
307
279
  tool(createToolFunction('click'), {
308
280
  name: EBrowserTools.CLICK,
309
- description: `Click an element by its [index] from the element list.
310
-
311
- **WHEN TO USE (prioritize this over keypress):**
312
- - Buttons labeled "Send", "Submit", "Save", "OK", "Confirm" CLICK them
313
- - Links (a tags) to navigate
314
- - Checkboxes, radio buttons to select
315
- - Any clickable element that performs an action
316
-
317
- **SEMANTIC ELEMENT IDENTIFICATION:**
318
- - Look for aria-label="Send", aria-label="Submit" for action buttons
319
- - Look for type="submit" for form submission
320
- - Look for button text like "Send", "Submit", "Save"
321
- - For email compose: Find the Send button, DON'T use keyboard shortcuts
322
-
323
- Returns verification: dialog closed, form submitted, URL changed, or NO CHANGE (action may have failed).`,
281
+ description: `Click an element on the current web page by its index number.
282
+ The element list shows clickable items like: [0]<button>Submit</button> [1]<a href="/home">Home</a>
283
+ Use the index number in brackets to click that element.
284
+ After clicking, you receive an updated element list showing the new page state.`,
324
285
  schema: BrowserClickSchema,
325
286
  })
326
287
  );
@@ -329,20 +290,10 @@ Returns verification: dialog closed, form submitted, URL changed, or NO CHANGE (
329
290
  tools.push(
330
291
  tool(createToolFunction('type'), {
331
292
  name: EBrowserTools.TYPE,
332
- description: `Type text into an input/textarea element by [index].
333
-
334
- **WHEN TO USE:**
335
- - Input fields (fieldType="email", "search", "phone", etc.)
336
- - Textareas for longer content
337
- - Contenteditable divs (like Gmail compose body)
338
-
339
- **OPTIONS:**
340
- - pressEnter: true → Press Enter after typing (for search forms)
341
- - pressEnter: false → Just type without submitting
342
-
343
- **DO NOT use pressEnter to send emails** - find and CLICK the Send button instead.
344
-
345
- Returns verification showing if text was entered or form was submitted.`,
293
+ description: `Type text into an input element on the page.
294
+ Find the input element in the list by its index (e.g., [5]<input placeholder="Search">).
295
+ Set pressEnter: true to submit forms after typing.
296
+ After typing, you receive an updated element list.`,
346
297
  schema: BrowserTypeSchema,
347
298
  })
348
299
  );
@@ -351,7 +302,8 @@ Returns verification showing if text was entered or form was submitted.`,
351
302
  tools.push(
352
303
  tool(createToolFunction('navigate'), {
353
304
  name: EBrowserTools.NAVIGATE,
354
- description: `Navigate to a URL (include https://). Returns new page's element list.`,
305
+ description: `Navigate to a URL. Always include the full URL with https://.
306
+ After navigation, you receive the new page's element list.`,
355
307
  schema: BrowserNavigateSchema,
356
308
  })
357
309
  );
@@ -360,7 +312,9 @@ Returns verification showing if text was entered or form was submitted.`,
360
312
  tools.push(
361
313
  tool(createToolFunction('scroll'), {
362
314
  name: EBrowserTools.SCROLL,
363
- description: `Scroll the page. Returns updated element list with newly visible elements.`,
315
+ description: `Scroll the page to reveal more content.
316
+ Use 'down' to scroll down, 'up' to scroll up.
317
+ After scrolling, you receive an updated element list with newly visible elements.`,
364
318
  schema: BrowserScrollSchema,
365
319
  })
366
320
  );
@@ -410,7 +364,9 @@ After going back, you receive the previous page's element list.`,
410
364
  tools.push(
411
365
  tool(createToolFunction('screenshot'), {
412
366
  name: EBrowserTools.SCREENSHOT,
413
- description: `Capture a screenshot. Use browser_get_page_state for element list.`,
367
+ description: `Capture a screenshot of the current page.
368
+ Returns the page state with a note that screenshot was displayed to the user.
369
+ Use browser_get_page_state to get the element list for automation.`,
414
370
  schema: BrowserScreenshotSchema,
415
371
  })
416
372
  );
@@ -419,16 +375,22 @@ After going back, you receive the previous page's element list.`,
419
375
  tools.push(
420
376
  tool(createToolFunction('get_page_state'), {
421
377
  name: EBrowserTools.GET_PAGE_STATE,
422
- description: `Get current page URL, title, and interactive elements list with index numbers.`,
378
+ description: `Get the current page state including URL, title, and all interactive elements.
379
+ Use this at the start of a task to see what elements are available.
380
+ Returns a text list of elements with their index numbers for interaction.`,
423
381
  schema: BrowserGetPageStateSchema,
424
382
  })
425
383
  );
426
384
 
427
- // browser_select_option
385
+ // browser_select_option - Skyvern-inspired for robust dropdown handling
428
386
  tools.push(
429
387
  tool(createToolFunction('select_option'), {
430
388
  name: EBrowserTools.SELECT_OPTION,
431
- description: `Select an option from a dropdown. Handles both native <select> and custom dropdowns.`,
389
+ description: `Select an option from a dropdown or select element.
390
+ For native <select> elements: finds and selects the option by value/label.
391
+ For custom dropdowns: clicks to open, then clicks the matching option.
392
+ Use this instead of click for dropdowns - it handles both native and custom selects.
393
+ After selection, you receive an updated element list.`,
432
394
  schema: BrowserSelectOptionSchema,
433
395
  })
434
396
  );
@@ -445,27 +407,15 @@ After upload, you receive an updated element list.`,
445
407
  })
446
408
  );
447
409
 
448
- // browser_keypress - LAST RESORT for keyboard shortcuts
410
+ // browser_keypress - For keyboard shortcuts and special keys
449
411
  tools.push(
450
412
  tool(createToolFunction('keypress'), {
451
413
  name: EBrowserTools.KEYPRESS,
452
- description: `Press keyboard key(s) - USE ONLY AS LAST RESORT after clicking fails.
453
-
454
- **PREFER browser_click OVER keypress:**
455
- - To send email Find and CLICK the Send button
456
- - To submit form CLICK the Submit button
457
- - To close modal → CLICK the X or Cancel button
458
-
459
- **WHEN TO USE keypress:**
460
- - Navigation: "Tab", "ArrowDown", "ArrowUp" in dropdowns
461
- - Escape to close popups if no X button exists
462
- - Control+A, Control+C for select/copy operations
463
- - ONLY use Enter to submit if there's NO visible submit button
464
-
465
- Single keys: "Enter", "Escape", "Tab", "ArrowDown"
466
- Key combos: "Control+A", "Shift+Enter"
467
-
468
- Returns verification showing if page state changed.`,
414
+ description: `Press keyboard key(s) on the page.
415
+ Single keys: "Enter", "Escape", "Tab", "ArrowDown", "ArrowUp", "Backspace", "Delete"
416
+ Key combos: "Control+A" (select all), "Control+C" (copy), "Shift+Enter" (newline)
417
+ Use this for form submission, closing modals, navigating dropdowns.
418
+ After keypress, you receive an updated element list.`,
469
419
  schema: BrowserKeypressSchema,
470
420
  })
471
421
  );