@browserbasehq/orca 3.2.0-preview.1 → 3.2.0-preview.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/cjs/lib/v3/agent/prompts/agentSystemPrompt.d.ts +2 -0
  2. package/dist/cjs/lib/v3/agent/prompts/agentSystemPrompt.js +2 -2
  3. package/dist/cjs/lib/v3/agent/prompts/agentSystemPrompt.js.map +1 -1
  4. package/dist/cjs/lib/v3/agent/tools/{search.js → braveSearch.js} +1 -1
  5. package/dist/cjs/lib/v3/agent/tools/braveSearch.js.map +1 -0
  6. package/dist/cjs/lib/v3/agent/tools/browserbaseSearch.d.ts +13 -0
  7. package/dist/cjs/lib/v3/agent/tools/browserbaseSearch.js +70 -0
  8. package/dist/cjs/lib/v3/agent/tools/browserbaseSearch.js.map +1 -0
  9. package/dist/cjs/lib/v3/agent/tools/index.d.ts +14 -3
  10. package/dist/cjs/lib/v3/agent/tools/index.js +7 -3
  11. package/dist/cjs/lib/v3/agent/tools/index.js.map +1 -1
  12. package/dist/cjs/lib/v3/handlers/v3AgentHandler.js +13 -3
  13. package/dist/cjs/lib/v3/handlers/v3AgentHandler.js.map +1 -1
  14. package/dist/cjs/lib/v3/types/public/agent.d.ts +16 -2
  15. package/dist/cjs/lib/v3/types/public/agent.js.map +1 -1
  16. package/dist/cjs/lib/v3/v3.d.ts +5 -0
  17. package/dist/cjs/lib/v3/v3.js +7 -0
  18. package/dist/cjs/lib/v3/v3.js.map +1 -1
  19. package/dist/cjs/tests/unit/public-api/public-types.test.js.map +1 -1
  20. package/dist/esm/lib/v3/agent/prompts/agentSystemPrompt.d.ts +2 -0
  21. package/dist/esm/lib/v3/agent/prompts/agentSystemPrompt.js +2 -2
  22. package/dist/esm/lib/v3/agent/prompts/agentSystemPrompt.js.map +1 -1
  23. package/dist/esm/lib/v3/agent/tools/{search.js → braveSearch.js} +1 -1
  24. package/dist/esm/lib/v3/agent/tools/braveSearch.js.map +1 -0
  25. package/dist/esm/lib/v3/agent/tools/browserbaseSearch.d.ts +13 -0
  26. package/dist/esm/lib/v3/agent/tools/browserbaseSearch.js +66 -0
  27. package/dist/esm/lib/v3/agent/tools/browserbaseSearch.js.map +1 -0
  28. package/dist/esm/lib/v3/agent/tools/index.d.ts +14 -3
  29. package/dist/esm/lib/v3/agent/tools/index.js +7 -3
  30. package/dist/esm/lib/v3/agent/tools/index.js.map +1 -1
  31. package/dist/esm/lib/v3/handlers/v3AgentHandler.js +14 -4
  32. package/dist/esm/lib/v3/handlers/v3AgentHandler.js.map +1 -1
  33. package/dist/esm/lib/v3/types/public/agent.d.ts +16 -2
  34. package/dist/esm/lib/v3/types/public/agent.js.map +1 -1
  35. package/dist/esm/lib/v3/v3.d.ts +5 -0
  36. package/dist/esm/lib/v3/v3.js +7 -0
  37. package/dist/esm/lib/v3/v3.js.map +1 -1
  38. package/dist/esm/tests/unit/public-api/public-types.test.js.map +1 -1
  39. package/package.json +1 -3
  40. package/dist/cjs/lib/v3/agent/tools/search.js.map +0 -1
  41. package/dist/cjs/tests/unit/rerender-missing-shadows.test.d.ts +0 -1
  42. package/dist/cjs/tests/unit/rerender-missing-shadows.test.js +0 -209
  43. package/dist/cjs/tests/unit/rerender-missing-shadows.test.js.map +0 -1
  44. package/dist/esm/lib/v3/agent/tools/search.js.map +0 -1
  45. package/dist/esm/tests/unit/rerender-missing-shadows.test.d.ts +0 -1
  46. package/dist/esm/tests/unit/rerender-missing-shadows.test.js +0 -207
  47. package/dist/esm/tests/unit/rerender-missing-shadows.test.js.map +0 -1
  48. /package/dist/cjs/lib/v3/agent/tools/{search.d.ts → braveSearch.d.ts} +0 -0
  49. /package/dist/esm/lib/v3/agent/tools/{search.d.ts → braveSearch.d.ts} +0 -0
@@ -10,5 +10,7 @@ export interface AgentSystemPromptOptions {
10
10
  excludeTools?: string[];
11
11
  /** Variables available to the agent for use in act/type tools */
12
12
  variables?: Variables;
13
+ /** Whether the search tool is enabled for this execution */
14
+ useSearch?: boolean;
13
15
  }
14
16
  export declare function buildAgentSystemPrompt(options: AgentSystemPromptOptions): string;
@@ -74,12 +74,12 @@ function buildToolsSection(isHybridMode, hasSearch, excludeTools) {
74
74
  return `<tools>\n${toolLines}\n </tools>`;
75
75
  }
76
76
  function buildAgentSystemPrompt(options) {
77
- const { url, executionInstruction, mode, systemInstructions, isBrowserbase = false, excludeTools, variables, } = options;
77
+ const { url, executionInstruction, mode, systemInstructions, isBrowserbase = false, excludeTools, variables, useSearch = false, } = options;
78
78
  const localeDate = new Date().toLocaleDateString();
79
79
  const isoDate = new Date().toISOString();
80
80
  const cdata = (text) => `<![CDATA[${text}]]>`;
81
81
  const isHybridMode = mode === "hybrid";
82
- const hasSearch = Boolean(process.env.BRAVE_API_KEY);
82
+ const hasSearch = useSearch || Boolean(process.env.BRAVE_API_KEY);
83
83
  // Tools section differs based on mode and excluded tools
84
84
  const toolsSection = buildToolsSection(isHybridMode, hasSearch, excludeTools);
85
85
  // Strategy differs based on mode
@@ -1 +1 @@
1
- {"version":3,"file":"agentSystemPrompt.js","sourceRoot":"","sources":["../../../../../../lib/v3/agent/prompts/agentSystemPrompt.ts"],"names":[],"mappings":";;AAoHA,wDA4JC;AAtPD,SAAS,iBAAiB,CACxB,YAAqB,EACrB,SAAkB,EAClB,YAAuB;IAEvB,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC;IAE/C,MAAM,WAAW,GAAqB;QACpC;YACE,IAAI,EAAE,YAAY;YAClB,WAAW,EAAE,4DAA4D;SAC1E;QACD;YACE,IAAI,EAAE,UAAU;YAChB,WAAW,EACT,+DAA+D;SAClE;QACD;YACE,IAAI,EAAE,OAAO;YACb,WAAW,EACT,qFAAqF;SACxF;QACD;YACE,IAAI,EAAE,MAAM;YACZ,WAAW,EACT,2FAA2F;SAC9F;QACD;YACE,IAAI,EAAE,KAAK;YACX,WAAW,EACT,0LAA0L;SAC7L;QACD,EAAE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C,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE;YACjB,MAAM,WAAW,GACf,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAI,OAAO,IAAI,CAAC;gBACjD,CAAC,CAAC,CAAC,CAAC,WAAW;gBACf,CAAC,CAAC,SAAS,CAAC;YAChB,OAAO,WAAW;gBAChB,CAAC,CAAC,mBAAmB,IAAI,KAAK,WAAW,aAAa;gBACtD,CAAC,CAAC,mBAAmB,IAAI,MAAM,CAAC;QACpC,CAAC,CAAC;aACD,IAAI,CAAC,QAAQ,CAAC;eACN;QACX,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO;;IAEL,uBAAuB;YACf,KAAK,CAAC,oBAAoB,CAAC;iCACN,OAAO,KAAK,UAAU;;;;2DAII,GAAG;;;;;;;;;;;;IAY1D,yBAAyB;;;MAGvB,SAAS,CAAC,CAAC,CAAC,mFAAmF,CAAC,CAAC,CAAC,EAAE;;IAEtG,YAAY;;MAEV,eAAe;MACf,mBAAmB;;IAErB,iBAAiB;IACjB,gBAAgB;;;;;;;;UAQV,CAAC;AACX,CAAC","sourcesContent":["import type { AgentToolMode, Variables } from \"../../types/public/agent.js\";\n\nexport interface AgentSystemPromptOptions {\n url: string;\n executionInstruction: string;\n mode: AgentToolMode;\n systemInstructions?: string;\n /** Whether running on Browserbase (enables captcha solver messaging) */\n isBrowserbase?: boolean;\n /** Tools to exclude from the system prompt */\n excludeTools?: string[];\n /** Variables available to the agent for use in act/type tools */\n variables?: Variables;\n}\n\n/**\n * Builds the system prompt for the agent based on the tool mode.\n *\n * @param options - The prompt configuration options\n * @returns The formatted system prompt string\n */\ninterface ToolDefinition {\n name: string;\n description: string;\n}\n\nfunction buildToolsSection(\n isHybridMode: boolean,\n hasSearch: boolean,\n excludeTools?: string[],\n): string {\n const excludeSet = new Set(excludeTools ?? []);\n\n const hybridTools: ToolDefinition[] = [\n {\n name: \"screenshot\",\n description: \"Take a compressed JPEG screenshot for quick visual context\",\n },\n {\n name: \"ariaTree\",\n description:\n \"Get an accessibility (ARIA) hybrid tree for full page context\",\n },\n {\n name: \"click\",\n description:\n \"Click on an element (PREFERRED - more reliable when element is visible in viewport)\",\n },\n {\n name: \"type\",\n description:\n \"Type text into an element (PREFERRED - more reliable when element is visible in viewport)\",\n },\n {\n name: \"act\",\n description:\n \"Perform a specific atomic action (click, type, etc.) - ONLY use when element is in ariaTree but NOT visible in screenshot. Less reliable but can interact with out-of-viewport elements.\",\n },\n { name: \"dragAndDrop\", description: \"Drag and drop an element\" },\n { name: \"clickAndHold\", description: \"Click and hold on an element\" },\n { name: \"keys\", description: \"Press a keyboard key\" },\n {\n name: \"fillFormVision\",\n description: \"Fill out a form using coordinates\",\n },\n { name: \"think\", description: \"Think about the task\" },\n { name: \"extract\", description: \"Extract structured data\" },\n { name: \"goto\", description: \"Navigate to a URL\" },\n { name: \"wait\", description: \"Wait for a specified time\" },\n { name: \"navback\", description: \"Navigate back in browser history\" },\n { name: \"scroll\", description: \"Scroll the page x pixels up or down\" },\n ];\n\n const domTools: ToolDefinition[] = [\n {\n name: \"screenshot\",\n description: \"Take a compressed JPEG screenshot for quick visual context\",\n },\n {\n name: \"ariaTree\",\n description:\n \"Get an accessibility (ARIA) hybrid tree for full page context\",\n },\n {\n name: \"act\",\n description: \"Perform a specific atomic action (click, type)\",\n },\n { name: \"keys\", description: \"Press a keyboard key\" },\n { name: \"fillForm\", description: \"Fill out a form\" },\n { name: \"think\", description: \"Think about the task\" },\n { name: \"extract\", description: \"Extract structured data\" },\n { name: \"goto\", description: \"Navigate to a URL\" },\n { name: \"wait\", description: \"Wait for a specified time\" },\n { name: \"navback\", description: \"Navigate back in browser history\" },\n { name: \"scroll\", description: \"Scroll the page x pixels up or down\" },\n ];\n\n const baseTools = isHybridMode ? hybridTools : domTools;\n\n if (hasSearch) {\n baseTools.push({\n name: \"search\",\n description:\n \"Perform a web search and return results. Prefer this over navigating to Google and searching within the page for reliability and efficiency.\",\n });\n }\n\n const filteredTools = baseTools.filter((tool) => !excludeSet.has(tool.name));\n\n const toolLines = filteredTools\n .map((tool) => ` <tool name=\"${tool.name}\">${tool.description}</tool>`)\n .join(\"\\n\");\n\n return `<tools>\\n${toolLines}\\n </tools>`;\n}\n\nexport function buildAgentSystemPrompt(\n options: AgentSystemPromptOptions,\n): string {\n const {\n url,\n executionInstruction,\n mode,\n systemInstructions,\n isBrowserbase = false,\n excludeTools,\n variables,\n } = options;\n const localeDate = new Date().toLocaleDateString();\n const isoDate = new Date().toISOString();\n const cdata = (text: string) => `<![CDATA[${text}]]>`;\n\n const isHybridMode = mode === \"hybrid\";\n const hasSearch = Boolean(process.env.BRAVE_API_KEY);\n\n // Tools section differs based on mode and excluded tools\n const toolsSection = buildToolsSection(isHybridMode, hasSearch, excludeTools);\n\n // Strategy differs based on mode\n const strategyItems = isHybridMode\n ? [\n `<item>Tool selection priority: Use specific tools (click, type) when elements are visible in viewport for maximum reliability.</item>`,\n `<item>Always use screenshot to get proper grounding of the coordinates you want to type/click into.</item>`,\n `<item>When interacting with an input, always use the type tool to type into the input, over clicking and then typing into it.</item>`,\n `<item>Use ariaTree as a secondary tool when elements aren't visible in screenshot or to get full page context.</item>`,\n `<item>Only use act when element is in ariaTree but NOT visible in screenshot.</item>`,\n ]\n : [\n `<item>Tool selection priority: Use act tool for all clicking and typing on a page.</item>`,\n `<item>Always check ariaTree first to understand full page content without scrolling - it shows all elements including those below the fold.</item>`,\n `<item>When interacting with an input, always use the act tool to type into the input, over clicking and then typing.</item>`,\n `<item>If an element is present in the ariaTree, use act to interact with it directly - this eliminates the need to scroll.</item>`,\n `<item>Use screenshot for visual confirmation when needed, but rely primarily on ariaTree for element detection.</item>`,\n ];\n\n const strategySection = strategyItems.join(\"\\n \");\n\n const commonStrategyItems = `\n <item>CRITICAL: Use extract ONLY when the task explicitly requires structured data output (e.g., \"get job listings\", \"extract product details\"). For reading page content or understanding elements, always use ${isHybridMode ? \"screenshot or ariaTree\" : \"ariaTree\"} instead - it's faster and more reliable.</item>\n <item>Keep actions atomic and verify outcomes before proceeding.</item>\n <item>For each action, provide clear reasoning about why you're taking that step.</item>\n <item>When you need to input text that could be entered character-by-character or through multiple separate inputs, prefer using the keys tool to type the entire sequence at once. This is more efficient for scenarios like verification codes split across multiple fields, or when virtual keyboards are present but direct typing would be faster.</item>\n `;\n\n // Page understanding protocol differs based on mode\n const pageUnderstandingProtocol = isHybridMode\n ? `<page_understanding_protocol>\n <step_1>\n <title>UNDERSTAND THE PAGE</title>\n <primary_tool>\n <name>screenshot</name>\n <usage>Visual confirmation when needed. Ideally after navigating to a new page.</usage>\n </primary_tool>\n <secondary_tool>\n <name>ariaTree</name>\n <usage>Get complete page context before taking actions</usage>\n <benefit>Eliminates the need to scroll and provides full accessible content</benefit>\n </secondary_tool>\n </step_1>\n </page_understanding_protocol>`\n : `<page_understanding_protocol>\n <step_1>\n <title>UNDERSTAND THE PAGE</title>\n <primary_tool>\n <name>ariaTree</name>\n <usage>Get complete page context before taking actions</usage>\n <benefit>Eliminates the need to scroll and provides full accessible content</benefit>\n </primary_tool>\n <secondary_tool>\n <name>screenshot</name>\n <usage>Visual confirmation when needed. Ideally after navigating to a new page.</usage>\n </secondary_tool>\n </step_1>\n </page_understanding_protocol>`;\n\n // Roadblocks section only shown when running on Browserbase (has captcha solver)\n const roadblocksSection = isBrowserbase\n ? `<roadblocks>\n <note>captchas, popups, etc.</note>\n <captcha>If you see a captcha, use the wait tool. It will automatically be solved by our internal solver.</captcha>\n </roadblocks>`\n : \"\";\n\n // Build customInstructions block only if provided\n const customInstructionsBlock = systemInstructions\n ? `<customInstructions>${cdata(systemInstructions)}</customInstructions>\\n `\n : \"\";\n\n // Build variables section only if variables are provided\n const hasVariables = variables && Object.keys(variables).length > 0;\n const variableToolsNote = isHybridMode\n ? \"Use %variableName% syntax in the type, fillFormVision, or act tool's value/text/action fields.\"\n : \"Use %variableName% syntax in the act or fillForm tool's value/action fields.\";\n const variablesSection = hasVariables\n ? `<variables>\n <note>You have access to the following variables. Use %variableName% syntax to substitute variable values. This is especially important for sensitive data like passwords.</note>\n <usage>${variableToolsNote}</usage>\n <example>To type a password, use: type %password% into the password field</example>\n ${Object.entries(variables)\n .map(([name, v]) => {\n const description =\n typeof v === \"object\" && v !== null && \"value\" in v\n ? v.description\n : undefined;\n return description\n ? `<variable name=\"${name}\">${description}</variable>`\n : `<variable name=\"${name}\" />`;\n })\n .join(\"\\n \")}\n </variables>`\n : \"\";\n\n return `<system>\n <identity>You are a web automation assistant using browser automation tools to accomplish the user's goal.</identity>\n ${customInstructionsBlock}<task>\n <goal>${cdata(executionInstruction)}</goal>\n <date display=\"local\" iso=\"${isoDate}\">${localeDate}</date>\n <note>You may think the date is different due to knowledge cutoff, but this is the actual date.</note>\n </task>\n <page>\n <startingUrl>you are starting your task on this url: ${url}</startingUrl>\n </page>\n <mindset>\n <note>Be very intentional about your action. The initial instruction is very important, and slight variations of the actual goal can lead to failures.</note>\n <importantNote>If something fails to meet a single condition of the task, move on from it rather than seeing if it meets other criteria. We only care that it meets all of it</importantNote>\n <note>When the task is complete, do not seek more information; you have completed the task.</note>\n </mindset>\n <guidelines>\n <item>Always start by understanding the current page state</item>\n <item>Use the screenshot tool to verify page state when needed</item>\n <item>Use appropriate tools for each action</item>\n </guidelines>\n ${pageUnderstandingProtocol}\n <navigation>\n <rule>If you are confident in the URL, navigate directly to it.</rule>\n ${hasSearch ? `<rule>If you are not confident in the URL, use the search tool to find it.</rule>` : ``}\n </navigation>\n ${toolsSection}\n <strategy>\n ${strategySection}\n ${commonStrategyItems}\n </strategy>\n ${roadblocksSection}\n ${variablesSection}\n <completion>\n <note>When you complete the task, explain any information that was found that was relevant to the original task.</note>\n <examples>\n <example>If you were asked for specific flights, list the flights you found.</example>\n <example>If you were asked for information about a product, list the product information you were asked for.</example>\n </examples>\n </completion>\n</system>`;\n}\n"]}
1
+ {"version":3,"file":"agentSystemPrompt.js","sourceRoot":"","sources":["../../../../../../lib/v3/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AgB;;;;;;;;UAQV,CAAC;AACX,CAAC","sourcesContent":["import type { AgentToolMode, Variables } from \"../../types/public/agent.js\";\n\nexport interface AgentSystemPromptOptions {\n url: string;\n executionInstruction: string;\n mode: AgentToolMode;\n systemInstructions?: string;\n /** Whether running on Browserbase (enables captcha solver messaging) */\n isBrowserbase?: boolean;\n /** Tools to exclude from the system prompt */\n excludeTools?: string[];\n /** Variables available to the agent for use in act/type tools */\n variables?: Variables;\n /** Whether the search tool is enabled for this execution */\n useSearch?: boolean;\n}\n\n/**\n * Builds the system prompt for the agent based on the tool mode.\n *\n * @param options - The prompt configuration options\n * @returns The formatted system prompt string\n */\ninterface ToolDefinition {\n name: string;\n description: string;\n}\n\nfunction buildToolsSection(\n isHybridMode: boolean,\n hasSearch: boolean,\n excludeTools?: string[],\n): string {\n const excludeSet = new Set(excludeTools ?? []);\n\n const hybridTools: ToolDefinition[] = [\n {\n name: \"screenshot\",\n description: \"Take a compressed JPEG screenshot for quick visual context\",\n },\n {\n name: \"ariaTree\",\n description:\n \"Get an accessibility (ARIA) hybrid tree for full page context\",\n },\n {\n name: \"click\",\n description:\n \"Click on an element (PREFERRED - more reliable when element is visible in viewport)\",\n },\n {\n name: \"type\",\n description:\n \"Type text into an element (PREFERRED - more reliable when element is visible in viewport)\",\n },\n {\n name: \"act\",\n description:\n \"Perform a specific atomic action (click, type, etc.) - ONLY use when element is in ariaTree but NOT visible in screenshot. Less reliable but can interact with out-of-viewport elements.\",\n },\n { name: \"dragAndDrop\", description: \"Drag and drop an element\" },\n { name: \"clickAndHold\", description: \"Click and hold on an element\" },\n { name: \"keys\", description: \"Press a keyboard key\" },\n {\n name: \"fillFormVision\",\n description: \"Fill out a form using coordinates\",\n },\n { name: \"think\", description: \"Think about the task\" },\n { name: \"extract\", description: \"Extract structured data\" },\n { name: \"goto\", description: \"Navigate to a URL\" },\n { name: \"wait\", description: \"Wait for a specified time\" },\n { name: \"navback\", description: \"Navigate back in browser history\" },\n { name: \"scroll\", description: \"Scroll the page x pixels up or down\" },\n ];\n\n const domTools: ToolDefinition[] = [\n {\n name: \"screenshot\",\n description: \"Take a compressed JPEG screenshot for quick visual context\",\n },\n {\n name: \"ariaTree\",\n description:\n \"Get an accessibility (ARIA) hybrid tree for full page context\",\n },\n {\n name: \"act\",\n description: \"Perform a specific atomic action (click, type)\",\n },\n { name: \"keys\", description: \"Press a keyboard key\" },\n { name: \"fillForm\", description: \"Fill out a form\" },\n { name: \"think\", description: \"Think about the task\" },\n { name: \"extract\", description: \"Extract structured data\" },\n { name: \"goto\", description: \"Navigate to a URL\" },\n { name: \"wait\", description: \"Wait for a specified time\" },\n { name: \"navback\", description: \"Navigate back in browser history\" },\n { name: \"scroll\", description: \"Scroll the page x pixels up or down\" },\n ];\n\n const baseTools = isHybridMode ? hybridTools : domTools;\n\n if (hasSearch) {\n baseTools.push({\n name: \"search\",\n description:\n \"Perform a web search and return results. Prefer this over navigating to Google and searching within the page for reliability and efficiency.\",\n });\n }\n\n const filteredTools = baseTools.filter((tool) => !excludeSet.has(tool.name));\n\n const toolLines = filteredTools\n .map((tool) => ` <tool name=\"${tool.name}\">${tool.description}</tool>`)\n .join(\"\\n\");\n\n return `<tools>\\n${toolLines}\\n </tools>`;\n}\n\nexport function buildAgentSystemPrompt(\n options: AgentSystemPromptOptions,\n): string {\n const {\n url,\n executionInstruction,\n mode,\n systemInstructions,\n isBrowserbase = false,\n excludeTools,\n variables,\n useSearch = false,\n } = options;\n const localeDate = new Date().toLocaleDateString();\n const isoDate = new Date().toISOString();\n const cdata = (text: string) => `<![CDATA[${text}]]>`;\n\n const isHybridMode = mode === \"hybrid\";\n const hasSearch = useSearch || Boolean(process.env.BRAVE_API_KEY);\n\n // Tools section differs based on mode and excluded tools\n const toolsSection = buildToolsSection(isHybridMode, hasSearch, excludeTools);\n\n // Strategy differs based on mode\n const strategyItems = isHybridMode\n ? [\n `<item>Tool selection priority: Use specific tools (click, type) when elements are visible in viewport for maximum reliability.</item>`,\n `<item>Always use screenshot to get proper grounding of the coordinates you want to type/click into.</item>`,\n `<item>When interacting with an input, always use the type tool to type into the input, over clicking and then typing into it.</item>`,\n `<item>Use ariaTree as a secondary tool when elements aren't visible in screenshot or to get full page context.</item>`,\n `<item>Only use act when element is in ariaTree but NOT visible in screenshot.</item>`,\n ]\n : [\n `<item>Tool selection priority: Use act tool for all clicking and typing on a page.</item>`,\n `<item>Always check ariaTree first to understand full page content without scrolling - it shows all elements including those below the fold.</item>`,\n `<item>When interacting with an input, always use the act tool to type into the input, over clicking and then typing.</item>`,\n `<item>If an element is present in the ariaTree, use act to interact with it directly - this eliminates the need to scroll.</item>`,\n `<item>Use screenshot for visual confirmation when needed, but rely primarily on ariaTree for element detection.</item>`,\n ];\n\n const strategySection = strategyItems.join(\"\\n \");\n\n const commonStrategyItems = `\n <item>CRITICAL: Use extract ONLY when the task explicitly requires structured data output (e.g., \"get job listings\", \"extract product details\"). For reading page content or understanding elements, always use ${isHybridMode ? \"screenshot or ariaTree\" : \"ariaTree\"} instead - it's faster and more reliable.</item>\n <item>Keep actions atomic and verify outcomes before proceeding.</item>\n <item>For each action, provide clear reasoning about why you're taking that step.</item>\n <item>When you need to input text that could be entered character-by-character or through multiple separate inputs, prefer using the keys tool to type the entire sequence at once. This is more efficient for scenarios like verification codes split across multiple fields, or when virtual keyboards are present but direct typing would be faster.</item>\n `;\n\n // Page understanding protocol differs based on mode\n const pageUnderstandingProtocol = isHybridMode\n ? `<page_understanding_protocol>\n <step_1>\n <title>UNDERSTAND THE PAGE</title>\n <primary_tool>\n <name>screenshot</name>\n <usage>Visual confirmation when needed. Ideally after navigating to a new page.</usage>\n </primary_tool>\n <secondary_tool>\n <name>ariaTree</name>\n <usage>Get complete page context before taking actions</usage>\n <benefit>Eliminates the need to scroll and provides full accessible content</benefit>\n </secondary_tool>\n </step_1>\n </page_understanding_protocol>`\n : `<page_understanding_protocol>\n <step_1>\n <title>UNDERSTAND THE PAGE</title>\n <primary_tool>\n <name>ariaTree</name>\n <usage>Get complete page context before taking actions</usage>\n <benefit>Eliminates the need to scroll and provides full accessible content</benefit>\n </primary_tool>\n <secondary_tool>\n <name>screenshot</name>\n <usage>Visual confirmation when needed. Ideally after navigating to a new page.</usage>\n </secondary_tool>\n </step_1>\n </page_understanding_protocol>`;\n\n // Roadblocks section only shown when running on Browserbase (has captcha solver)\n const roadblocksSection = isBrowserbase\n ? `<roadblocks>\n <note>captchas, popups, etc.</note>\n <captcha>If you see a captcha, use the wait tool. It will automatically be solved by our internal solver.</captcha>\n </roadblocks>`\n : \"\";\n\n // Build customInstructions block only if provided\n const customInstructionsBlock = systemInstructions\n ? `<customInstructions>${cdata(systemInstructions)}</customInstructions>\\n `\n : \"\";\n\n // Build variables section only if variables are provided\n const hasVariables = variables && Object.keys(variables).length > 0;\n const variableToolsNote = isHybridMode\n ? \"Use %variableName% syntax in the type, fillFormVision, or act tool's value/text/action fields.\"\n : \"Use %variableName% syntax in the act or fillForm tool's value/action fields.\";\n const variablesSection = hasVariables\n ? `<variables>\n <note>You have access to the following variables. Use %variableName% syntax to substitute variable values. This is especially important for sensitive data like passwords.</note>\n <usage>${variableToolsNote}</usage>\n <example>To type a password, use: type %password% into the password field</example>\n ${Object.entries(variables)\n .map(([name, v]) => {\n const description =\n typeof v === \"object\" && v !== null && \"value\" in v\n ? v.description\n : undefined;\n return description\n ? `<variable name=\"${name}\">${description}</variable>`\n : `<variable name=\"${name}\" />`;\n })\n .join(\"\\n \")}\n </variables>`\n : \"\";\n\n return `<system>\n <identity>You are a web automation assistant using browser automation tools to accomplish the user's goal.</identity>\n ${customInstructionsBlock}<task>\n <goal>${cdata(executionInstruction)}</goal>\n <date display=\"local\" iso=\"${isoDate}\">${localeDate}</date>\n <note>You may think the date is different due to knowledge cutoff, but this is the actual date.</note>\n </task>\n <page>\n <startingUrl>you are starting your task on this url: ${url}</startingUrl>\n </page>\n <mindset>\n <note>Be very intentional about your action. The initial instruction is very important, and slight variations of the actual goal can lead to failures.</note>\n <importantNote>If something fails to meet a single condition of the task, move on from it rather than seeing if it meets other criteria. We only care that it meets all of it</importantNote>\n <note>When the task is complete, do not seek more information; you have completed the task.</note>\n </mindset>\n <guidelines>\n <item>Always start by understanding the current page state</item>\n <item>Use the screenshot tool to verify page state when needed</item>\n <item>Use appropriate tools for each action</item>\n </guidelines>\n ${pageUnderstandingProtocol}\n <navigation>\n <rule>If you are confident in the URL, navigate directly to it.</rule>\n ${hasSearch ? `<rule>If you are not confident in the URL, use the search tool to find it.</rule>` : ``}\n </navigation>\n ${toolsSection}\n <strategy>\n ${strategySection}\n ${commonStrategyItems}\n </strategy>\n ${roadblocksSection}\n ${variablesSection}\n <completion>\n <note>When you complete the task, explain any information that was found that was relevant to the original task.</note>\n <examples>\n <example>If you were asked for specific flights, list the flights you found.</example>\n <example>If you were asked for information about a product, list the product information you were asked for.</example>\n </examples>\n </completion>\n</system>`;\n}\n"]}
@@ -74,4 +74,4 @@ const searchTool = (v3) => (0, ai_1.tool)({
74
74
  },
75
75
  });
76
76
  exports.searchTool = searchTool;
77
- //# sourceMappingURL=search.js.map
77
+ //# sourceMappingURL=braveSearch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"braveSearch.js","sourceRoot":"","sources":["../../../../../../lib/v3/agent/tools/braveSearch.ts"],"names":[],"mappings":";;;AAAA,2BAA0B;AAC1B,6BAAwB;AAgCxB,KAAK,UAAU,kBAAkB,CAAC,KAAa;IAC7C,IAAI,CAAC;QACH,MAAM,YAAY,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC;QAC/C,MAAM,QAAQ,GAAG,MAAM,KAAK,CAC1B,oDAAoD,YAAY,EAAE,EAClE;YACE,MAAM,EAAE,KAAK;YACb,OAAO,EAAE;gBACP,MAAM,EAAE,kBAAkB;gBAC1B,iBAAiB,EAAE,MAAM;gBACzB,sBAAsB,EAAE,OAAO,CAAC,GAAG,CAAC,aAAc;aACnD;SACF,CACF,CAAC;QAEF,IAAI,CAAC,QAAQ,CAAC,EAAE,EAA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,KAAK,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,yCAAyC,CAAC;KACtE,CAAC;IACF,OAAO,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE;QAC3B,EAAE,CAAC,MAAM,CAAC;YACR,QAAQ,EAAE,OAAO;YACjB,OAAO,EAAE,4BAA4B;YACrC,KAAK,EAAE,CAAC;YACR,SAAS,EAAE;gBACT,SAAS,EAAE;oBACT,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,CAAC;oBAChC,IAAI,EAAE,QAAQ;iBACf;aACF;SACF,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,kBAAkB,CAAC,KAAK,CAAC,CAAC;QAE/C,EAAE,CAAC,qBAAqB,CAAC;YACvB,IAAI,EAAE,QAAQ;YACd,WAAW,EAAE,KAAK;YAClB,mBAAmB,EAAE,EAAE,KAAK,EAAE;YAC9B,OAAO,EACL,MAAM,CAAC,KAAK,IAAI,SAAS,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,IAAI,CAAC,UAAU;SACtE,CAAC,CAAC;QAEH,OAAO;YACL,GAAG,MAAM;YACT,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;SACtB,CAAC;IACJ,CAAC;CACF,CAAC,CAAC;AAnCQ,QAAA,UAAU,cAmClB","sourcesContent":["import { tool } from \"ai\";\nimport { z } from \"zod\";\nimport type { V3 } from \"../../v3.js\";\n\nexport interface BraveSearchResult {\n title: string;\n url: string;\n description?: string;\n}\n\ninterface SearchResponse {\n data?: {\n results: BraveSearchResult[];\n };\n error?: string;\n}\n\ninterface BraveWebResult {\n title?: string;\n url?: string;\n description?: string;\n age?: string;\n meta_url?: {\n favicon?: string;\n };\n}\n\ninterface BraveApiResponse {\n web?: {\n results?: BraveWebResult[];\n };\n}\n\nasync function performBraveSearch(query: string): Promise<SearchResponse> {\n try {\n const encodedQuery = encodeURIComponent(query);\n const response = await fetch(\n `https://api.search.brave.com/res/v1/web/search?q=${encodedQuery}`,\n {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n \"Accept-Encoding\": \"gzip\",\n \"X-Subscription-Token\": process.env.BRAVE_API_KEY!,\n },\n },\n );\n\n if (!response.ok) {\n return {\n error: `Brave API error: ${response.status} ${response.statusText}`,\n data: { results: [] },\n };\n }\n\n const data = (await response.json()) as BraveApiResponse;\n const results: BraveSearchResult[] = [];\n\n if (data?.web?.results && Array.isArray(data.web.results)) {\n for (const item of data.web.results.slice(0, 5)) {\n if (item.title && item.url) {\n results.push({\n title: item.title,\n url: item.url,\n description: item.description,\n });\n }\n }\n }\n\n return { data: { results } };\n } catch (error) {\n console.error(\"Search error\", error);\n return {\n error: `Error performing search: ${(error as Error).message}`,\n data: { results: [] },\n };\n }\n}\n\nexport const searchTool = (v3: V3) =>\n tool({\n description:\n \"Perform a web search and returns results. Use this tool when you need information from the web or when you are unsure of the exact URL you want to navigate to. This can be used to find the ideal entry point, resulting in a task that is easier to complete due to starting further in the process.\",\n inputSchema: z.object({\n query: z.string().describe(\"The search query to look for on the web\"),\n }),\n execute: async ({ query }) => {\n v3.logger({\n category: \"agent\",\n message: `Agent calling tool: search`,\n level: 1,\n auxiliary: {\n arguments: {\n value: JSON.stringify({ query }),\n type: \"object\",\n },\n },\n });\n\n const result = await performBraveSearch(query);\n\n v3.recordAgentReplayStep({\n type: \"search\",\n instruction: query,\n playwrightArguments: { query },\n message:\n result.error ?? `Found ${result.data?.results.length ?? 0} results`,\n });\n\n return {\n ...result,\n timestamp: Date.now(),\n };\n },\n });\n"]}
@@ -0,0 +1,13 @@
1
+ import type { V3 } from "../../v3.js";
2
+ export interface SearchResult {
3
+ title: string;
4
+ url: string;
5
+ publishedDate?: string;
6
+ }
7
+ export declare const searchTool: (v3: V3, apiKey: string) => import("ai").Tool<{
8
+ query: string;
9
+ }, {
10
+ timestamp: number;
11
+ results: SearchResult[];
12
+ error?: string;
13
+ }>;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.searchTool = void 0;
4
+ const ai_1 = require("ai");
5
+ const zod_1 = require("zod");
6
+ async function performBrowserbaseSearch(v3, query, apiKey, numResults = 5) {
7
+ try {
8
+ const response = await fetch("https://api.browserbase.com/v1/search", {
9
+ method: "POST",
10
+ headers: {
11
+ "Content-Type": "application/json",
12
+ "x-bb-api-key": apiKey,
13
+ },
14
+ body: JSON.stringify({ query, numResults }),
15
+ });
16
+ if (!response.ok) {
17
+ return {
18
+ results: [],
19
+ error: `Browserbase Search API error: ${response.status} ${response.statusText}`,
20
+ };
21
+ }
22
+ const data = (await response.json());
23
+ const results = (data?.results ?? []).map(({ title, url, publishedDate }) => ({
24
+ title: title,
25
+ url: url,
26
+ ...(publishedDate && { publishedDate }),
27
+ }));
28
+ return { results };
29
+ }
30
+ catch (error) {
31
+ v3.logger({
32
+ category: "agent",
33
+ message: `Search error: ${error.message}`,
34
+ level: 0,
35
+ });
36
+ return {
37
+ results: [],
38
+ error: `Error performing search: ${error.message}`,
39
+ };
40
+ }
41
+ }
42
+ const searchTool = (v3, apiKey) => (0, ai_1.tool)({
43
+ description: "Perform a web search and returns results. Use this tool when you need information from the web or when you are unsure of the exact URL you want to navigate to. This can be used to find the ideal entry point, resulting in a task that is easier to complete due to starting further in the process.",
44
+ inputSchema: zod_1.z.object({
45
+ query: zod_1.z.string().describe("The search query to look for on the web"),
46
+ }),
47
+ execute: async ({ query }) => {
48
+ v3.logger({
49
+ category: "agent",
50
+ message: `Agent calling tool: search`,
51
+ level: 1,
52
+ auxiliary: {
53
+ arguments: {
54
+ value: JSON.stringify({ query }),
55
+ type: "object",
56
+ },
57
+ },
58
+ });
59
+ const result = await performBrowserbaseSearch(v3, query, apiKey);
60
+ v3.recordAgentReplayStep({
61
+ type: "search",
62
+ instruction: query,
63
+ playwrightArguments: { query },
64
+ message: result.error ?? `Found ${result.results.length} results`,
65
+ });
66
+ return { ...result, timestamp: Date.now() };
67
+ },
68
+ });
69
+ exports.searchTool = searchTool;
70
+ //# sourceMappingURL=browserbaseSearch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserbaseSearch.js","sourceRoot":"","sources":["../../../../../../lib/v3/agent/tools/browserbaseSearch.ts"],"names":[],"mappings":";;;AAAA,2BAA0B;AAC1B,6BAAwB;AAmBxB,KAAK,UAAU,wBAAwB,CACrC,EAAM,EACN,KAAa,EACb,MAAc,EACd,aAAqB,CAAC;IAEtB,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,uCAAuC,EAAE;YACpE,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACP,cAAc,EAAE,kBAAkB;gBAClC,cAAc,EAAE,MAAM;aACvB;YACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;SAC5C,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,OAAO;gBACL,OAAO,EAAE,EAAE;gBACX,KAAK,EAAE,iCAAiC,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE;aACjF,CAAC;QACJ,CAAC;QAED,MAAM,IAAI,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAA2B,CAAC;QAC/D,MAAM,OAAO,GAAmB,CAAC,IAAI,EAAE,OAAO,IAAI,EAAE,CAAC,CAAC,GAAG,CACvD,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,aAAa,EAAE,EAAE,EAAE,CAAC,CAAC;YAClC,KAAK,EAAE,KAAK;YACZ,GAAG,EAAE,GAAG;YACR,GAAG,CAAC,aAAa,IAAI,EAAE,aAAa,EAAE,CAAC;SACxC,CAAC,CACH,CAAC;QAEF,OAAO,EAAE,OAAO,EAAE,CAAC;IACrB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,EAAE,CAAC,MAAM,CAAC;YACR,QA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cA+BlB","sourcesContent":["import { tool } from \"ai\";\nimport { z } from \"zod\";\nimport type { V3 } from \"../../v3.js\";\n\nexport interface SearchResult {\n title: string;\n url: string;\n publishedDate?: string;\n}\n\ninterface BrowserbaseRawResult {\n title?: string;\n url?: string;\n publishedDate?: string;\n}\n\ninterface BrowserbaseApiResponse {\n results?: BrowserbaseRawResult[];\n}\n\nasync function performBrowserbaseSearch(\n v3: V3,\n query: string,\n apiKey: string,\n numResults: number = 5,\n): Promise<{ results: SearchResult[]; error?: string }> {\n try {\n const response = await fetch(\"https://api.browserbase.com/v1/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-bb-api-key\": apiKey,\n },\n body: JSON.stringify({ query, numResults }),\n });\n\n if (!response.ok) {\n return {\n results: [],\n error: `Browserbase Search API error: ${response.status} ${response.statusText}`,\n };\n }\n\n const data = (await response.json()) as BrowserbaseApiResponse;\n const results: SearchResult[] = (data?.results ?? []).map(\n ({ title, url, publishedDate }) => ({\n title: title,\n url: url,\n ...(publishedDate && { publishedDate }),\n }),\n );\n\n return { results };\n } catch (error) {\n v3.logger({\n category: \"agent\",\n message: `Search error: ${(error as Error).message}`,\n level: 0,\n });\n return {\n results: [],\n error: `Error performing search: ${(error as Error).message}`,\n };\n }\n}\n\nexport const searchTool = (v3: V3, apiKey: string) =>\n tool({\n description:\n \"Perform a web search and returns results. Use this tool when you need information from the web or when you are unsure of the exact URL you want to navigate to. This can be used to find the ideal entry point, resulting in a task that is easier to complete due to starting further in the process.\",\n inputSchema: z.object({\n query: z.string().describe(\"The search query to look for on the web\"),\n }),\n execute: async ({ query }) => {\n v3.logger({\n category: \"agent\",\n message: `Agent calling tool: search`,\n level: 1,\n auxiliary: {\n arguments: {\n value: JSON.stringify({ query }),\n type: \"object\",\n },\n },\n });\n\n const result = await performBrowserbaseSearch(v3, query, apiKey);\n\n v3.recordAgentReplayStep({\n type: \"search\",\n instruction: query,\n playwrightArguments: { query },\n message: result.error ?? `Found ${result.results.length} results`,\n });\n\n return { ...result, timestamp: Date.now() };\n },\n });\n"]}
@@ -14,7 +14,8 @@ import { clickAndHoldTool } from "./clickAndHold.js";
14
14
  import { keysTool } from "./keys.js";
15
15
  import { fillFormVisionTool } from "./fillFormVision.js";
16
16
  import { thinkTool } from "./think.js";
17
- import { searchTool } from "./search.js";
17
+ import { searchTool as browserbaseSearchTool } from "./browserbaseSearch.js";
18
+ import { searchTool as braveSearchTool } from "./braveSearch.js";
18
19
  import type { ToolSet, InferUITools } from "ai";
19
20
  import type { V3 } from "../../v3.js";
20
21
  import type { LogLine } from "../../types/public/logs.js";
@@ -47,12 +48,22 @@ export interface V3AgentToolOptions {
47
48
  * Forwarded to the underlying v3 call's `timeout` option.
48
49
  */
49
50
  toolTimeout?: number;
51
+ /**
52
+ * Whether to enable the Browserbase-powered web search tool.
53
+ * Requires a valid Browserbase API key.
54
+ */
55
+ useSearch?: boolean;
56
+ /**
57
+ * The Browserbase API key used for the search tool.
58
+ * Resolved from BROWSERBASE_API_KEY env var or the Stagehand constructor.
59
+ */
60
+ browserbaseApiKey?: string;
50
61
  }
51
62
  export declare function createAgentTools(v3: V3, options?: V3AgentToolOptions): ToolSet;
52
63
  export type AgentTools = ReturnType<typeof createAgentTools>;
53
64
  /**
54
65
  * Type map of all agent tools for strong typing of tool calls and results.
55
- * Note: `search` is optional as it's only available when BRAVE_API_KEY is configured.
66
+ * Note: `search` is optional enabled via useSearch: true (Browserbase) or BRAVE_API_KEY env var (legacy).
56
67
  */
57
68
  export type AgentToolTypesMap = {
58
69
  act: ReturnType<typeof actTool>;
@@ -68,7 +79,7 @@ export type AgentToolTypesMap = {
68
79
  navback: ReturnType<typeof navBackTool>;
69
80
  screenshot: ReturnType<typeof screenshotTool>;
70
81
  scroll: ReturnType<typeof scrollTool> | ReturnType<typeof scrollVisionTool>;
71
- search?: ReturnType<typeof searchTool>;
82
+ search?: ReturnType<typeof browserbaseSearchTool> | ReturnType<typeof braveSearchTool>;
72
83
  think: ReturnType<typeof thinkTool>;
73
84
  type: ReturnType<typeof typeTool>;
74
85
  wait: ReturnType<typeof waitTool>;
@@ -17,7 +17,8 @@ const clickAndHold_js_1 = require("./clickAndHold.js");
17
17
  const keys_js_1 = require("./keys.js");
18
18
  const fillFormVision_js_1 = require("./fillFormVision.js");
19
19
  const think_js_1 = require("./think.js");
20
- const search_js_1 = require("./search.js");
20
+ const browserbaseSearch_js_1 = require("./browserbaseSearch.js");
21
+ const braveSearch_js_1 = require("./braveSearch.js");
21
22
  /**
22
23
  * Filters tools based on mode and explicit exclusions.
23
24
  * - 'dom' mode: Removes coordinate-based tools (click, type, dragAndDrop, clickAndHold, fillFormVision)
@@ -70,8 +71,11 @@ function createAgentTools(v3, options) {
70
71
  type: (0, type_js_1.typeTool)(v3, provider, variables),
71
72
  wait: (0, wait_js_1.waitTool)(v3, mode),
72
73
  };
73
- if (process.env.BRAVE_API_KEY) {
74
- allTools.search = (0, search_js_1.searchTool)(v3);
74
+ if (options?.useSearch && options.browserbaseApiKey) {
75
+ allTools.search = (0, browserbaseSearch_js_1.searchTool)(v3, options.browserbaseApiKey);
76
+ }
77
+ else if (process.env.BRAVE_API_KEY) {
78
+ allTools.search = (0, braveSearch_js_1.searchTool)(v3);
75
79
  }
76
80
  return filterTools(allTools, mode, excludeTools);
77
81
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../lib/v3/agent/tools/index.ts"],"names":[],"mappings":";;AA2FA,4CAgCC;AA3HD,uCAAqC;AACrC,qCAAmC;AACnC,mDAAiD;AACjD,uCAAqC;AACrC,6CAA2C;AAC3C,+CAA6C;AAC7C,+CAA6C;AAC7C,2CAA2D;AAC3D,6CAA2C;AAC3C,yCAAuC;AACvC,uCAAqC;AACrC,qDAAmD;AACnD,uDAAqD;AACrD,uCAAqC;AACrC,2DAAyD;AACzD,yCAAuC;AACvC,2CAAyC;AAyCzC;;;;;GAKG;AACH,SAAS,WAAW,CAClB,KAAc,EACd,I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AE,QAAQ,CAAC;QAC5C,WAAW,EAAE,IAAA,gCAAe,EAAC,EAAE,EAAE,QAAQ,CAAC;QAC1C,OAAO,EAAE,IAAA,wBAAW,EAAC,EAAE,EAAE,cAAc,EAAE,WAAW,CAAC;QACrD,QAAQ,EAAE,IAAA,0BAAY,EAAC,EAAE,EAAE,cAAc,EAAE,SAAS,EAAE,WAAW,CAAC;QAClE,cAAc,EAAE,IAAA,sCAAkB,EAAC,EAAE,EAAE,QAAQ,EAAE,SAAS,CAAC;QAC3D,IAAI,EAAE,IAAA,kBAAQ,EAAC,EAAE,CAAC;QAClB,IAAI,EAAE,IAAA,kBAAQ,EAAC,EAAE,CAAC;QAClB,OAAO,EAAE,IAAA,wBAAW,EAAC,EAAE,CAAC;QACxB,UAAU,EAAE,IAAA,8BAAc,EAAC,EAAE,CAAC;QAC9B,MAAM,EAAE,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAA,4BAAgB,EAAC,EAAE,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAA,sBAAU,EAAC,EAAE,CAAC;QAC3E,KAAK,EAAE,IAAA,oBAAS,GAAE;QAClB,IAAI,EAAE,IAAA,kBAAQ,EAAC,EAAE,EAAE,QAAQ,EAAE,SAAS,CAAC;QACvC,IAAI,EAAE,IAAA,kBAAQ,EAAC,EAAE,EAAE,IAAI,CAAC;KACzB,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,CAAC;QAC9B,QAAQ,CAAC,MAAM,GAAG,IAAA,sBAAU,EAAC,EAAE,CAAC,CAAC;IACnC,CAAC;IAED,OAAO,WAAW,CAAC,QAAQ,EAAE,IAAI,EAAE,YAAY,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import { gotoTool } from \"./goto.js\";\nimport { actTool } from \"./act.js\";\nimport { screenshotTool } from \"./screenshot.js\";\nimport { waitTool } from \"./wait.js\";\nimport { navBackTool } from \"./navback.js\";\nimport { ariaTreeTool } from \"./ariaTree.js\";\nimport { fillFormTool } from \"./fillform.js\";\nimport { scrollTool, scrollVisionTool } from \"./scroll.js\";\nimport { extractTool } from \"./extract.js\";\nimport { clickTool } from \"./click.js\";\nimport { typeTool } from \"./type.js\";\nimport { dragAndDropTool } from \"./dragAndDrop.js\";\nimport { clickAndHoldTool } from \"./clickAndHold.js\";\nimport { keysTool } from \"./keys.js\";\nimport { fillFormVisionTool } from \"./fillFormVision.js\";\nimport { thinkTool } from \"./think.js\";\nimport { searchTool } from \"./search.js\";\n\nimport type { ToolSet, InferUITools } from \"ai\";\nimport type { V3 } from \"../../v3.js\";\nimport type { LogLine } from \"../../types/public/logs.js\";\nimport type {\n AgentToolMode,\n AgentModelConfig,\n Variables,\n} from \"../../types/public/agent.js\";\n\nexport interface V3AgentToolOptions {\n executionModel?: string | AgentModelConfig;\n logger?: (message: LogLine) => void;\n /**\n * Tool mode determines which set of tools are available.\n * - 'dom' (default): Uses DOM-based tools (act, fillForm) - removes coordinate-based tools\n * - 'hybrid': Uses coordinate-based tools (click, type, dragAndDrop, etc.) - removes fillForm\n */\n mode?: AgentToolMode;\n /**\n * The model provider. Used for model-specific coordinate handling\n */\n provider?: string;\n /**\n * Tools to exclude from the available toolset.\n * These tools will be filtered out after mode-based filtering.\n */\n excludeTools?: string[];\n /**\n * Variables available to the agent for use in act/type tools.\n * When provided, these tools will have an optional useVariable field.\n */\n variables?: Variables;\n /**\n * Timeout in milliseconds for tool calls that invoke v3 methods (act, extract, fillForm, ariaTree).\n * Forwarded to the underlying v3 call's `timeout` option.\n */\n toolTimeout?: number;\n}\n\n/**\n * Filters tools based on mode and explicit exclusions.\n * - 'dom' mode: Removes coordinate-based tools (click, type, dragAndDrop, clickAndHold, fillFormVision)\n * - 'hybrid' mode: Removes DOM-based form tool (fillForm) in favor of coordinate-based fillFormVision\n * - excludeTools: Additional tools to remove from the toolset\n */\nfunction filterTools(\n tools: ToolSet,\n mode: AgentToolMode,\n excludeTools?: string[],\n): ToolSet {\n const filtered: ToolSet = { ...tools };\n\n // Mode-based filtering\n if (mode === \"hybrid\") {\n delete filtered.fillForm;\n } else {\n // DOM mode (default)\n delete filtered.click;\n delete filtered.type;\n delete filtered.dragAndDrop;\n delete filtered.clickAndHold;\n delete filtered.fillFormVision;\n }\n\n if (excludeTools) {\n for (const toolName of excludeTools) {\n delete filtered[toolName];\n }\n }\n\n return filtered;\n}\n\nexport function createAgentTools(v3: V3, options?: V3AgentToolOptions) {\n const executionModel = options?.executionModel;\n const mode = options?.mode ?? \"dom\";\n const provider = options?.provider;\n const excludeTools = options?.excludeTools;\n const variables = options?.variables;\n const toolTimeout = options?.toolTimeout;\n\n const allTools: ToolSet = {\n act: actTool(v3, executionModel, variables, toolTimeout),\n ariaTree: ariaTreeTool(v3, toolTimeout),\n click: clickTool(v3, provider),\n clickAndHold: clickAndHoldTool(v3, provider),\n dragAndDrop: dragAndDropTool(v3, provider),\n extract: extractTool(v3, executionModel, toolTimeout),\n fillForm: fillFormTool(v3, executionModel, variables, toolTimeout),\n fillFormVision: fillFormVisionTool(v3, provider, variables),\n goto: gotoTool(v3),\n keys: keysTool(v3),\n navback: navBackTool(v3),\n screenshot: screenshotTool(v3),\n scroll: mode === \"hybrid\" ? scrollVisionTool(v3, provider) : scrollTool(v3),\n think: thinkTool(),\n type: typeTool(v3, provider, variables),\n wait: waitTool(v3, mode),\n };\n\n if (process.env.BRAVE_API_KEY) {\n allTools.search = searchTool(v3);\n }\n\n return filterTools(allTools, mode, excludeTools);\n}\n\nexport type AgentTools = ReturnType<typeof createAgentTools>;\n\n/**\n * Type map of all agent tools for strong typing of tool calls and results.\n * Note: `search` is optional as it's only available when BRAVE_API_KEY is configured.\n */\nexport type AgentToolTypesMap = {\n act: ReturnType<typeof actTool>;\n ariaTree: ReturnType<typeof ariaTreeTool>;\n click: ReturnType<typeof clickTool>;\n clickAndHold: ReturnType<typeof clickAndHoldTool>;\n dragAndDrop: ReturnType<typeof dragAndDropTool>;\n extract: ReturnType<typeof extractTool>;\n fillForm: ReturnType<typeof fillFormTool>;\n fillFormVision: ReturnType<typeof fillFormVisionTool>;\n goto: ReturnType<typeof gotoTool>;\n keys: ReturnType<typeof keysTool>;\n navback: ReturnType<typeof navBackTool>;\n screenshot: ReturnType<typeof screenshotTool>;\n scroll: ReturnType<typeof scrollTool> | ReturnType<typeof scrollVisionTool>;\n search?: ReturnType<typeof searchTool>;\n think: ReturnType<typeof thinkTool>;\n type: ReturnType<typeof typeTool>;\n wait: ReturnType<typeof waitTool>;\n};\n\n/**\n * Inferred UI tools type for type-safe tool inputs and outputs.\n * Use with UIMessage for full type safety in UI contexts.\n */\nexport type AgentUITools = InferUITools<AgentToolTypesMap>;\n\n/**\n * Union type for all possible agent tool calls.\n * Provides type-safe access to tool call arguments.\n */\nexport type AgentToolCall = {\n [K in keyof AgentToolTypesMap]: {\n toolName: K;\n toolCallId: string;\n args: AgentUITools[K][\"input\"];\n };\n}[keyof AgentToolTypesMap];\n\n/**\n * Union type for all possible agent tool results.\n * Provides type-safe access to tool result values.\n */\nexport type AgentToolResult = {\n [K in keyof AgentToolTypesMap]: {\n toolName: K;\n toolCallId: string;\n result: AgentUITools[K][\"output\"];\n };\n}[keyof AgentToolTypesMap];\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../lib/v3/agent/tools/index.ts"],"names":[],"mappings":";;AAsGA,4CAkCC;AAxID,uCAAqC;AACrC,qCAAmC;AACnC,mDAAiD;AACjD,uCAAqC;AACrC,6CAA2C;AAC3C,+CAA6C;AAC7C,+CAA6C;AAC7C,2CAA2D;AAC3D,6CAA2C;AAC3C,yCAAuC;AACvC,uCAAqC;AACrC,qDAAmD;AACnD,uDAAqD;AACrD,uCAAqC;AACrC,2DAAyD;AACzD,yCAAuC;AACvC,iEAA6E;AAC7E,qDAAiE;AAmDjE;;;;;GAKG;AACH,SAAS,WAAW,CAClB,KAAc,EACd,IAAmB,EACnB,YAAuB;IAEvB,MAAM,QAAQ,GAAY,EAAE,GAAG,K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from \"./act.js\";\nimport { screenshotTool } from \"./screenshot.js\";\nimport { waitTool } from \"./wait.js\";\nimport { navBackTool } from \"./navback.js\";\nimport { ariaTreeTool } from \"./ariaTree.js\";\nimport { fillFormTool } from \"./fillform.js\";\nimport { scrollTool, scrollVisionTool } from \"./scroll.js\";\nimport { extractTool } from \"./extract.js\";\nimport { clickTool } from \"./click.js\";\nimport { typeTool } from \"./type.js\";\nimport { dragAndDropTool } from \"./dragAndDrop.js\";\nimport { clickAndHoldTool } from \"./clickAndHold.js\";\nimport { keysTool } from \"./keys.js\";\nimport { fillFormVisionTool } from \"./fillFormVision.js\";\nimport { thinkTool } from \"./think.js\";\nimport { searchTool as browserbaseSearchTool } from \"./browserbaseSearch.js\";\nimport { searchTool as braveSearchTool } from \"./braveSearch.js\";\n\nimport type { ToolSet, InferUITools } from \"ai\";\nimport type { V3 } from \"../../v3.js\";\nimport type { LogLine } from \"../../types/public/logs.js\";\nimport type {\n AgentToolMode,\n AgentModelConfig,\n Variables,\n} from \"../../types/public/agent.js\";\n\nexport interface V3AgentToolOptions {\n executionModel?: string | AgentModelConfig;\n logger?: (message: LogLine) => void;\n /**\n * Tool mode determines which set of tools are available.\n * - 'dom' (default): Uses DOM-based tools (act, fillForm) - removes coordinate-based tools\n * - 'hybrid': Uses coordinate-based tools (click, type, dragAndDrop, etc.) - removes fillForm\n */\n mode?: AgentToolMode;\n /**\n * The model provider. Used for model-specific coordinate handling\n */\n provider?: string;\n /**\n * Tools to exclude from the available toolset.\n * These tools will be filtered out after mode-based filtering.\n */\n excludeTools?: string[];\n /**\n * Variables available to the agent for use in act/type tools.\n * When provided, these tools will have an optional useVariable field.\n */\n variables?: Variables;\n /**\n * Timeout in milliseconds for tool calls that invoke v3 methods (act, extract, fillForm, ariaTree).\n * Forwarded to the underlying v3 call's `timeout` option.\n */\n toolTimeout?: number;\n /**\n * Whether to enable the Browserbase-powered web search tool.\n * Requires a valid Browserbase API key.\n */\n useSearch?: boolean;\n /**\n * The Browserbase API key used for the search tool.\n * Resolved from BROWSERBASE_API_KEY env var or the Stagehand constructor.\n */\n browserbaseApiKey?: string;\n}\n\n/**\n * Filters tools based on mode and explicit exclusions.\n * - 'dom' mode: Removes coordinate-based tools (click, type, dragAndDrop, clickAndHold, fillFormVision)\n * - 'hybrid' mode: Removes DOM-based form tool (fillForm) in favor of coordinate-based fillFormVision\n * - excludeTools: Additional tools to remove from the toolset\n */\nfunction filterTools(\n tools: ToolSet,\n mode: AgentToolMode,\n excludeTools?: string[],\n): ToolSet {\n const filtered: ToolSet = { ...tools };\n\n // Mode-based filtering\n if (mode === \"hybrid\") {\n delete filtered.fillForm;\n } else {\n // DOM mode (default)\n delete filtered.click;\n delete filtered.type;\n delete filtered.dragAndDrop;\n delete filtered.clickAndHold;\n delete filtered.fillFormVision;\n }\n\n if (excludeTools) {\n for (const toolName of excludeTools) {\n delete filtered[toolName];\n }\n }\n\n return filtered;\n}\n\nexport function createAgentTools(v3: V3, options?: V3AgentToolOptions) {\n const executionModel = options?.executionModel;\n const mode = options?.mode ?? \"dom\";\n const provider = options?.provider;\n const excludeTools = options?.excludeTools;\n const variables = options?.variables;\n const toolTimeout = options?.toolTimeout;\n\n const allTools: ToolSet = {\n act: actTool(v3, executionModel, variables, toolTimeout),\n ariaTree: ariaTreeTool(v3, toolTimeout),\n click: clickTool(v3, provider),\n clickAndHold: clickAndHoldTool(v3, provider),\n dragAndDrop: dragAndDropTool(v3, provider),\n extract: extractTool(v3, executionModel, toolTimeout),\n fillForm: fillFormTool(v3, executionModel, variables, toolTimeout),\n fillFormVision: fillFormVisionTool(v3, provider, variables),\n goto: gotoTool(v3),\n keys: keysTool(v3),\n navback: navBackTool(v3),\n screenshot: screenshotTool(v3),\n scroll: mode === \"hybrid\" ? scrollVisionTool(v3, provider) : scrollTool(v3),\n think: thinkTool(),\n type: typeTool(v3, provider, variables),\n wait: waitTool(v3, mode),\n };\n\n if (options?.useSearch && options.browserbaseApiKey) {\n allTools.search = browserbaseSearchTool(v3, options.browserbaseApiKey);\n } else if (process.env.BRAVE_API_KEY) {\n allTools.search = braveSearchTool(v3);\n }\n\n return filterTools(allTools, mode, excludeTools);\n}\n\nexport type AgentTools = ReturnType<typeof createAgentTools>;\n\n/**\n * Type map of all agent tools for strong typing of tool calls and results.\n * Note: `search` is optional enabled via useSearch: true (Browserbase) or BRAVE_API_KEY env var (legacy).\n */\nexport type AgentToolTypesMap = {\n act: ReturnType<typeof actTool>;\n ariaTree: ReturnType<typeof ariaTreeTool>;\n click: ReturnType<typeof clickTool>;\n clickAndHold: ReturnType<typeof clickAndHoldTool>;\n dragAndDrop: ReturnType<typeof dragAndDropTool>;\n extract: ReturnType<typeof extractTool>;\n fillForm: ReturnType<typeof fillFormTool>;\n fillFormVision: ReturnType<typeof fillFormVisionTool>;\n goto: ReturnType<typeof gotoTool>;\n keys: ReturnType<typeof keysTool>;\n navback: ReturnType<typeof navBackTool>;\n screenshot: ReturnType<typeof screenshotTool>;\n scroll: ReturnType<typeof scrollTool> | ReturnType<typeof scrollVisionTool>;\n search?:\n | ReturnType<typeof browserbaseSearchTool>\n | ReturnType<typeof braveSearchTool>;\n think: ReturnType<typeof thinkTool>;\n type: ReturnType<typeof typeTool>;\n wait: ReturnType<typeof waitTool>;\n};\n\n/**\n * Inferred UI tools type for type-safe tool inputs and outputs.\n * Use with UIMessage for full type safety in UI contexts.\n */\nexport type AgentUITools = InferUITools<AgentToolTypesMap>;\n\n/**\n * Union type for all possible agent tool calls.\n * Provides type-safe access to tool call arguments.\n */\nexport type AgentToolCall = {\n [K in keyof AgentToolTypesMap]: {\n toolName: K;\n toolCallId: string;\n args: AgentUITools[K][\"input\"];\n };\n}[keyof AgentToolTypesMap];\n\n/**\n * Union type for all possible agent tool results.\n * Provides type-safe access to tool result values.\n */\nexport type AgentToolResult = {\n [K in keyof AgentToolTypesMap]: {\n toolName: K;\n toolCallId: string;\n result: AgentUITools[K][\"output\"];\n };\n}[keyof AgentToolTypesMap];\n"]}
@@ -65,8 +65,15 @@ class V3AgentHandler {
65
65
  isBrowserbase: this.v3.isBrowserbase,
66
66
  excludeTools: options.excludeTools,
67
67
  variables: options.variables,
68
+ useSearch: options.useSearch,
68
69
  });
69
- const tools = this.createTools(options.excludeTools, options.variables, options.toolTimeout);
70
+ if (options.useSearch) {
71
+ const bbApiKey = this.v3.browserbaseApiKey;
72
+ if (!bbApiKey) {
73
+ throw new sdkErrors_js_1.MissingEnvironmentVariableError("BROWSERBASE_API_KEY", "agent search (useSearch: true)");
74
+ }
75
+ }
76
+ const tools = this.createTools(options.excludeTools, options.variables, options.toolTimeout, options.useSearch);
70
77
  const allTools = { ...tools, ...this.mcpTools };
71
78
  // Use provided messages for continuation, or start fresh with the instruction
72
79
  const messages = options.messages?.length
@@ -239,7 +246,8 @@ class V3AgentHandler {
239
246
  }
240
247
  catch (error) {
241
248
  // Re-throw validation errors that should propagate to the caller
242
- if (error instanceof sdkErrors_js_1.StreamingCallbacksInNonStreamingModeError) {
249
+ if (error instanceof sdkErrors_js_1.StreamingCallbacksInNonStreamingModeError ||
250
+ error instanceof sdkErrors_js_1.MissingEnvironmentVariableError) {
243
251
  throw error;
244
252
  }
245
253
  // Re-throw abort errors wrapped in AgentAbortError for consistent error typing
@@ -382,7 +390,7 @@ class V3AgentHandler {
382
390
  messages: inputMessages,
383
391
  };
384
392
  }
385
- createTools(excludeTools, variables, toolTimeout) {
393
+ createTools(excludeTools, variables, toolTimeout, useSearch) {
386
394
  const provider = this.llmClient?.getLanguageModel?.()?.provider;
387
395
  return (0, index_js_1.createAgentTools)(this.v3, {
388
396
  executionModel: this.executionModel,
@@ -392,6 +400,8 @@ class V3AgentHandler {
392
400
  excludeTools,
393
401
  variables,
394
402
  toolTimeout,
403
+ useSearch,
404
+ browserbaseApiKey: useSearch ? this.v3.browserbaseApiKey : undefined,
395
405
  });
396
406
  }
397
407
  handleStop(result, maxSteps) {
@@ -1 +1 @@
1
- {"version":3,"file":"v3AgentHandler.js","sourceRoot":"","sources":["../../../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OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC;gBACV,QAAQ,EAAE,OAAO;gBACjB,OAAO,EAAE,+BAA+B,eAAe,CAAC,KAAK,CAAC,EAAE;gBAChE,KAAK,EAAE,CAAC;aACT,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF;AA7kBD,wCA6kBC","sourcesContent":["import { createAgentTools } from \"../agent/tools/index.js\";\nimport { buildAgentSystemPrompt } from \"../agent/prompts/agentSystemPrompt.js\";\nimport { LogLine } from \"../types/public/logs.js\";\nimport { V3 } from \"../v3.js\";\nimport {\n ModelMessage,\n ToolSet,\n wrapLanguageModel,\n stepCountIs,\n LanguageModel,\n type LanguageModelUsage,\n type StepResult,\n type GenerateTextOnStepFinishCallback,\n type StreamTextOnStepFinishCallback,\n type PrepareStepFunction,\n} from \"ai\";\nimport { StagehandZodObject } from \"../zodCompat.js\";\nimport { processMessages } from \"../agent/utils/messageProcessing.js\";\nimport { LLMClient } from \"../llm/LLMClient.js\";\nimport { SessionFileLogger } from \"../flowLogger.js\";\nimport {\n AgentExecuteOptions,\n AgentStreamExecuteOptions,\n AgentExecuteOptionsBase,\n AgentResult,\n AgentContext,\n AgentState,\n AgentStreamResult,\n AgentStreamCallbacks,\n AgentToolMode,\n AgentModelConfig,\n Variables,\n} from \"../types/public/agent.js\";\nimport { V3FunctionName } from \"../types/public/methods.js\";\nimport { mapToolResultToActions } from \"../agent/utils/actionMapping.js\";\nimport {\n MissingLLMConfigurationError,\n StreamingCallbacksInNonStreamingModeError,\n AgentAbortError,\n} from \"../types/public/sdkErrors.js\";\nimport { handleDoneToolCall } from \"../agent/utils/handleDoneToolCall.js\";\n\nfunction getErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Prepends a system message with cache control to the messages array.\n * The cache control providerOptions are used by Anthropic and ignored by other providers.\n */\nfunction prependSystemMessage(\n systemPrompt: string,\n messages: ModelMessage[],\n): ModelMessage[] {\n return [\n {\n role: \"system\",\n content: systemPrompt,\n providerOptions: {\n anthropic: {\n cacheControl: { type: \"ephemeral\" },\n },\n },\n },\n ...messages,\n ];\n}\n\nexport class V3AgentHandler {\n private v3: V3;\n private logger: (message: LogLine) => void;\n private llmClient: LLMClient;\n private executionModel?: string | AgentModelConfig;\n private systemInstructions?: string;\n private mcpTools?: ToolSet;\n private mode: AgentToolMode;\n\n constructor(\n v3: V3,\n logger: (message: LogLine) => void,\n llmClient: LLMClient,\n executionModel?: string | AgentModelConfig,\n systemInstructions?: string,\n mcpTools?: ToolSet,\n mode?: AgentToolMode,\n ) {\n this.v3 = v3;\n this.logger = logger;\n this.llmClient = llmClient;\n this.executionModel = executionModel;\n this.systemInstructions = systemInstructions;\n this.mcpTools = mcpTools;\n this.mode = mode ?? \"dom\";\n }\n\n private async prepareAgent(\n instructionOrOptions: string | AgentExecuteOptionsBase,\n ): Promise<AgentContext> {\n try {\n const options =\n typeof instructionOrOptions === \"string\"\n ? { instruction: instructionOrOptions }\n : instructionOrOptions;\n\n const maxSteps = options.maxSteps || 20;\n\n // Get the initial page URL first (needed for the system prompt)\n const initialPageUrl = (await this.v3.context.awaitActivePage()).url();\n\n // Build the system prompt with mode-aware tool guidance\n const systemPrompt = buildAgentSystemPrompt({\n url: initialPageUrl,\n executionInstruction: options.instruction,\n mode: this.mode,\n systemInstructions: this.systemInstructions,\n isBrowserbase: this.v3.isBrowserbase,\n excludeTools: options.excludeTools,\n variables: options.variables,\n });\n\n const tools = this.createTools(\n options.excludeTools,\n options.variables,\n options.toolTimeout,\n );\n const allTools: ToolSet = { ...tools, ...this.mcpTools };\n\n // Use provided messages for continuation, or start fresh with the instruction\n const messages: ModelMessage[] = options.messages?.length\n ? [...options.messages, { role: \"user\", content: options.instruction }]\n : [{ role: \"user\", content: options.instruction }];\n\n if (!this.llmClient?.getLanguageModel) {\n throw new MissingLLMConfigurationError();\n }\n const baseModel = this.llmClient.getLanguageModel();\n //to do - we likely do not need middleware anymore\n const wrappedModel = wrapLanguageModel({\n model: baseModel,\n middleware: {\n ...SessionFileLogger.createLlmLoggingMiddleware(baseModel.modelId),\n },\n });\n\n if (\n this.mode === \"hybrid\" &&\n !baseModel.modelId.includes(\"gemini-3-flash\") &&\n !baseModel.modelId.includes(\"claude\")\n ) {\n this.logger({\n category: \"agent\",\n message: `Warning: \"${baseModel.modelId}\" may not perform well in hybrid mode. See recommended models: https://docs.stagehand.dev/v3/basics/agent#hybrid-mode`,\n level: 0,\n });\n }\n\n return {\n options,\n maxSteps,\n systemPrompt,\n allTools,\n messages,\n wrappedModel,\n initialPageUrl,\n };\n } catch (error) {\n this.logger({\n category: \"agent\",\n message: `failed to prepare agent: ${error}`,\n level: 0,\n });\n throw error;\n }\n }\n private createPrepareStep(\n userCallback?: PrepareStepFunction<ToolSet>,\n ): PrepareStepFunction<ToolSet> {\n return async (options) => {\n processMessages(options.messages);\n if (userCallback) {\n return userCallback(options);\n }\n return options;\n };\n }\n\n private createStepHandler(\n state: AgentState,\n userCallback?:\n | GenerateTextOnStepFinishCallback<ToolSet>\n | StreamTextOnStepFinishCallback<ToolSet>,\n ) {\n return async (event: StepResult<ToolSet>) => {\n this.logger({\n category: \"agent\",\n message: `Step finished: ${event.finishReason}`,\n level: 2,\n });\n\n if (event.toolCalls && event.toolCalls.length > 0) {\n for (let i = 0; i < event.toolCalls.length; i++) {\n const toolCall = event.toolCalls[i];\n const args = toolCall.input;\n const toolResult = event.toolResults?.[i];\n\n if (event.text && event.text.length > 0) {\n state.collectedReasoning.push(event.text);\n this.logger({\n category: \"agent\",\n message: `reasoning: ${event.text}`,\n level: 1,\n });\n }\n\n if (toolCall.toolName === \"done\") {\n state.completed = true;\n if (args?.taskComplete) {\n const doneReasoning = args.reasoning;\n const allReasoning = state.collectedReasoning.join(\" \");\n state.finalMessage = doneReasoning\n ? `${allReasoning} ${doneReasoning}`.trim()\n : allReasoning || \"Task completed successfully\";\n }\n }\n const mappedActions = mapToolResultToActions({\n toolCallName: toolCall.toolName,\n toolResult,\n args,\n reasoning: event.text || undefined,\n });\n\n for (const action of mappedActions) {\n action.pageUrl = state.currentPageUrl;\n action.timestamp = Date.now();\n state.actions.push(action);\n }\n }\n state.currentPageUrl = (await this.v3.context.awaitActivePage()).url();\n\n // Capture screenshot after tool execution (only for evals)\n if (process.env.EVALS === \"true\") {\n try {\n await this.captureAndEmitScreenshot();\n } catch (e) {\n this.logger({\n category: \"agent\",\n message: `Warning: Failed to capture screenshot: ${getErrorMessage(e)}`,\n level: 1,\n });\n }\n }\n }\n\n if (userCallback) {\n await userCallback(event);\n }\n };\n }\n\n public async execute(\n instructionOrOptions: string | AgentExecuteOptions,\n ): Promise<AgentResult> {\n const startTime = Date.now();\n const options =\n typeof instructionOrOptions === \"object\" ? instructionOrOptions : null;\n const signal = options?.signal;\n\n // Highlight cursor defaults to true for hybrid mode, can be overridden\n const shouldHighlightCursor =\n options?.highlightCursor ?? this.mode === \"hybrid\";\n\n const state: AgentState = {\n collectedReasoning: [],\n actions: [],\n finalMessage: \"\",\n completed: false,\n currentPageUrl: \"\",\n };\n\n let messages: ModelMessage[] = [];\n\n try {\n const {\n options: preparedOptions,\n maxSteps,\n systemPrompt,\n allTools,\n messages: preparedMessages,\n wrappedModel,\n initialPageUrl,\n } = await this.prepareAgent(instructionOrOptions);\n\n // Enable cursor overlay for hybrid mode (coordinate-based interactions)\n if (shouldHighlightCursor && this.mode === \"hybrid\") {\n const page = await this.v3.context.awaitActivePage();\n await page.enableCursorOverlay().catch(() => {});\n }\n\n messages = preparedMessages;\n state.currentPageUrl = initialPageUrl;\n\n const callbacks = (instructionOrOptions as AgentExecuteOptions).callbacks;\n\n if (callbacks) {\n const streamingOnlyCallbacks = [\n \"onChunk\",\n \"onFinish\",\n \"onError\",\n \"onAbort\",\n ];\n const invalidCallbacks = streamingOnlyCallbacks.filter(\n (name) => callbacks[name as keyof typeof callbacks] != null,\n );\n if (invalidCallbacks.length > 0) {\n throw new StreamingCallbacksInNonStreamingModeError(invalidCallbacks);\n }\n }\n\n const result = await this.llmClient.generateText({\n model: wrappedModel,\n messages: prependSystemMessage(systemPrompt, messages),\n tools: allTools,\n stopWhen: (result) => this.handleStop(result, maxSteps),\n temperature: 1,\n toolChoice: \"auto\",\n\n prepareStep: this.createPrepareStep(callbacks?.prepareStep),\n onStepFinish: this.createStepHandler(state, callbacks?.onStepFinish),\n abortSignal: preparedOptions.signal,\n providerOptions: {\n google: { mediaResolution: \"MEDIA_RESOLUTION_HIGH\" },\n openai: { store: false },\n },\n });\n\n const allMessages = [...messages, ...(result.response?.messages || [])];\n const doneResult = await this.ensureDone(\n state,\n wrappedModel,\n allMessages,\n preparedOptions.instruction,\n preparedOptions.output,\n this.logger,\n );\n\n return this.consolidateMetricsAndResult(\n startTime,\n state,\n doneResult.messages,\n result,\n maxSteps,\n doneResult.output,\n );\n } catch (error) {\n // Re-throw validation errors that should propagate to the caller\n if (error instanceof StreamingCallbacksInNonStreamingModeError) {\n throw error;\n }\n\n // Re-throw abort errors wrapped in AgentAbortError for consistent error typing\n if (signal?.aborted) {\n const reason = signal.reason ? String(signal.reason) : \"aborted\";\n throw new AgentAbortError(reason);\n }\n\n const errorMessage = getErrorMessage(error);\n this.logger({\n category: \"agent\",\n message: `Error executing agent task: ${errorMessage}`,\n level: 0,\n });\n\n // For non-abort errors, return a failure result instead of throwing\n return {\n success: false,\n actions: state.actions,\n message: `Failed to execute task: ${errorMessage}`,\n completed: false,\n messages,\n };\n }\n }\n\n public async stream(\n instructionOrOptions: string | AgentStreamExecuteOptions,\n ): Promise<AgentStreamResult> {\n const streamOptions =\n typeof instructionOrOptions === \"object\" ? instructionOrOptions : null;\n\n // Highlight cursor defaults to true for hybrid mode, can be overridden\n const shouldHighlightCursor =\n streamOptions?.highlightCursor ?? this.mode === \"hybrid\";\n\n const {\n options,\n maxSteps,\n systemPrompt,\n allTools,\n messages,\n wrappedModel,\n initialPageUrl,\n } = await this.prepareAgent(instructionOrOptions);\n\n // Enable cursor overlay for hybrid mode (coordinate-based interactions)\n if (shouldHighlightCursor && this.mode === \"hybrid\") {\n const page = await this.v3.context.awaitActivePage();\n await page.enableCursorOverlay().catch(() => {});\n }\n\n const callbacks = (instructionOrOptions as AgentStreamExecuteOptions)\n .callbacks as AgentStreamCallbacks | undefined;\n\n const state: AgentState = {\n collectedReasoning: [],\n actions: [],\n finalMessage: \"\",\n completed: false,\n currentPageUrl: initialPageUrl,\n };\n const startTime = Date.now();\n\n let resolveResult: (value: AgentResult | PromiseLike<AgentResult>) => void;\n let rejectResult: (reason: unknown) => void;\n const resultPromise = new Promise<AgentResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n const handleError = (error: unknown) => {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.logger({\n category: \"agent\",\n message: `Error during streaming: ${errorMessage}`,\n level: 0,\n });\n rejectResult(error);\n };\n\n const streamResult = this.llmClient.streamText({\n model: wrappedModel,\n messages: prependSystemMessage(systemPrompt, messages),\n tools: allTools,\n stopWhen: (result) => this.handleStop(result, maxSteps),\n temperature: 1,\n toolChoice: \"auto\",\n prepareStep: this.createPrepareStep(callbacks?.prepareStep),\n onStepFinish: this.createStepHandler(state, callbacks?.onStepFinish),\n onError: (event) => {\n if (callbacks?.onError) {\n callbacks.onError(event);\n }\n handleError(event.error);\n },\n onChunk: callbacks?.onChunk,\n onFinish: (event) => {\n if (callbacks?.onFinish) {\n callbacks.onFinish(event);\n }\n\n const allMessages = [...messages, ...(event.response?.messages || [])];\n this.ensureDone(\n state,\n wrappedModel,\n allMessages,\n options.instruction,\n options.output,\n this.logger,\n ).then((doneResult) => {\n const result = this.consolidateMetricsAndResult(\n startTime,\n state,\n doneResult.messages,\n event,\n maxSteps,\n doneResult.output,\n );\n resolveResult(result);\n });\n },\n onAbort: (event) => {\n if (callbacks?.onAbort) {\n callbacks.onAbort(event);\n }\n // Reject the result promise with AgentAbortError when stream is aborted\n const reason = options.signal?.reason\n ? String(options.signal.reason)\n : \"Stream was aborted\";\n rejectResult(new AgentAbortError(reason));\n },\n abortSignal: options.signal,\n providerOptions: {\n google: { mediaResolution: \"MEDIA_RESOLUTION_HIGH\" },\n openai: { store: false },\n },\n });\n\n const agentStreamResult = streamResult as AgentStreamResult;\n agentStreamResult.result = resultPromise;\n return agentStreamResult;\n }\n\n private consolidateMetricsAndResult(\n startTime: number,\n state: AgentState,\n inputMessages: ModelMessage[],\n result: {\n text?: string;\n totalUsage?: LanguageModelUsage;\n response?: { messages?: ModelMessage[] };\n steps?: StepResult<ToolSet>[];\n },\n maxSteps?: number,\n output?: Record<string, unknown>,\n ): AgentResult {\n if (!state.finalMessage) {\n const allReasoning = state.collectedReasoning.join(\" \").trim();\n\n if (!state.completed && maxSteps && result.steps?.length >= maxSteps) {\n this.logger({\n category: \"agent\",\n message: `Agent stopped: reached maximum steps (${maxSteps})`,\n level: 1,\n });\n state.finalMessage = `Agent stopped: reached maximum steps (${maxSteps})`;\n } else {\n state.finalMessage = allReasoning || result.text || \"\";\n }\n }\n\n const endTime = Date.now();\n const inferenceTimeMs = endTime - startTime;\n if (result.totalUsage) {\n this.v3.updateMetrics(\n V3FunctionName.AGENT,\n result.totalUsage.inputTokens || 0,\n result.totalUsage.outputTokens || 0,\n result.totalUsage.reasoningTokens || 0,\n result.totalUsage.cachedInputTokens || 0,\n inferenceTimeMs,\n );\n }\n\n return {\n success: state.completed,\n message: state.finalMessage || \"Task execution completed\",\n actions: state.actions,\n completed: state.completed,\n output,\n usage: result.totalUsage\n ? {\n input_tokens: result.totalUsage.inputTokens || 0,\n output_tokens: result.totalUsage.outputTokens || 0,\n reasoning_tokens: result.totalUsage.reasoningTokens || 0,\n cached_input_tokens: result.totalUsage.cachedInputTokens || 0,\n inference_time_ms: inferenceTimeMs,\n }\n : undefined,\n messages: inputMessages,\n };\n }\n\n private createTools(\n excludeTools?: string[],\n variables?: Variables,\n toolTimeout?: number,\n ) {\n const provider = this.llmClient?.getLanguageModel?.()?.provider;\n return createAgentTools(this.v3, {\n executionModel: this.executionModel,\n logger: this.logger,\n mode: this.mode,\n provider,\n excludeTools,\n variables,\n toolTimeout,\n });\n }\n\n private handleStop(\n result: Parameters<ReturnType<typeof stepCountIs>>[0],\n maxSteps: number,\n ): boolean | PromiseLike<boolean> {\n const lastStep = result.steps[result.steps.length - 1];\n if (lastStep?.toolCalls?.some((tc) => tc.toolName === \"done\")) {\n return true;\n }\n return stepCountIs(maxSteps)(result);\n }\n\n /**\n * Ensures the done tool is called at the end of agent execution.\n * Returns the messages and any extracted output from the done call.\n */\n private async ensureDone(\n state: AgentState,\n model: LanguageModel,\n messages: ModelMessage[],\n instruction: string,\n outputSchema?: StagehandZodObject,\n logger?: (message: LogLine) => void,\n ): Promise<{ messages: ModelMessage[]; output?: Record<string, unknown> }> {\n if (state.completed) return { messages };\n\n const doneResult = await handleDoneToolCall({\n model,\n inputMessages: messages,\n instruction,\n outputSchema,\n logger,\n });\n\n state.completed = doneResult.taskComplete;\n state.finalMessage = doneResult.reasoning;\n\n const doneAction = mapToolResultToActions({\n toolCallName: \"done\",\n toolResult: {\n success: true,\n reasoning: doneResult.reasoning,\n taskComplete: doneResult.taskComplete,\n },\n args: {\n reasoning: doneResult.reasoning,\n taskComplete: doneResult.taskComplete,\n },\n reasoning: doneResult.reasoning,\n });\n\n for (const action of doneAction) {\n action.pageUrl = state.currentPageUrl;\n action.timestamp = Date.now();\n state.actions.push(action);\n }\n\n return {\n messages: [...messages, ...doneResult.messages],\n output: doneResult.output,\n };\n }\n\n /**\n * Capture a screenshot and emit it via the event bus\n */\n private async captureAndEmitScreenshot(): Promise<void> {\n try {\n const page = await this.v3.context.awaitActivePage();\n const screenshot = await page.screenshot({ fullPage: false });\n this.v3.bus.emit(\"agent_screenshot_taken_event\", screenshot);\n } catch (error) {\n this.logger({\n category: \"agent\",\n message: `Error capturing screenshot: ${getErrorMessage(error)}`,\n level: 0,\n });\n }\n }\n}\n"]}
1
+ {"version":3,"file":"v3AgentHandler.js","sourceRoot":"","sources":["../../../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AAQ,EAAE,GAAG,UAAU,CAAC,QAAQ,CAAC;YAC/C,MAAM,EAAE,UAAU,CAAC,MAAM;SAC1B,CAAC;IACJ,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,wBAAwB;QACpC,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,eAAe,EAAE,CAAC;YACrD,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;YAC9D,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,8BAA8B,EAAE,UAAU,CAAC,CAAC;QAC/D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC;gBACV,QAAQ,EAAE,OAAO;gBACjB,OAAO,EAAE,+BAA+B,eAAe,CAAC,KAAK,CAAC,EAAE;gBAChE,KAAK,EAAE,CAAC;aACT,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF;AA/lBD,wCA+lBC","sourcesContent":["import { createAgentTools } from \"../agent/tools/index.js\";\nimport { buildAgentSystemPrompt } from \"../agent/prompts/agentSystemPrompt.js\";\nimport { LogLine } from \"../types/public/logs.js\";\nimport { V3 } from \"../v3.js\";\nimport {\n ModelMessage,\n ToolSet,\n wrapLanguageModel,\n stepCountIs,\n LanguageModel,\n type LanguageModelUsage,\n type StepResult,\n type GenerateTextOnStepFinishCallback,\n type StreamTextOnStepFinishCallback,\n type PrepareStepFunction,\n} from \"ai\";\nimport { StagehandZodObject } from \"../zodCompat.js\";\nimport { processMessages } from \"../agent/utils/messageProcessing.js\";\nimport { LLMClient } from \"../llm/LLMClient.js\";\nimport { SessionFileLogger } from \"../flowLogger.js\";\nimport {\n AgentExecuteOptions,\n AgentStreamExecuteOptions,\n AgentExecuteOptionsBase,\n AgentResult,\n AgentContext,\n AgentState,\n AgentStreamResult,\n AgentStreamCallbacks,\n AgentToolMode,\n AgentModelConfig,\n Variables,\n} from \"../types/public/agent.js\";\nimport { V3FunctionName } from \"../types/public/methods.js\";\nimport { mapToolResultToActions } from \"../agent/utils/actionMapping.js\";\nimport {\n MissingLLMConfigurationError,\n MissingEnvironmentVariableError,\n StreamingCallbacksInNonStreamingModeError,\n AgentAbortError,\n} from \"../types/public/sdkErrors.js\";\nimport { handleDoneToolCall } from \"../agent/utils/handleDoneToolCall.js\";\n\nfunction getErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Prepends a system message with cache control to the messages array.\n * The cache control providerOptions are used by Anthropic and ignored by other providers.\n */\nfunction prependSystemMessage(\n systemPrompt: string,\n messages: ModelMessage[],\n): ModelMessage[] {\n return [\n {\n role: \"system\",\n content: systemPrompt,\n providerOptions: {\n anthropic: {\n cacheControl: { type: \"ephemeral\" },\n },\n },\n },\n ...messages,\n ];\n}\n\nexport class V3AgentHandler {\n private v3: V3;\n private logger: (message: LogLine) => void;\n private llmClient: LLMClient;\n private executionModel?: string | AgentModelConfig;\n private systemInstructions?: string;\n private mcpTools?: ToolSet;\n private mode: AgentToolMode;\n\n constructor(\n v3: V3,\n logger: (message: LogLine) => void,\n llmClient: LLMClient,\n executionModel?: string | AgentModelConfig,\n systemInstructions?: string,\n mcpTools?: ToolSet,\n mode?: AgentToolMode,\n ) {\n this.v3 = v3;\n this.logger = logger;\n this.llmClient = llmClient;\n this.executionModel = executionModel;\n this.systemInstructions = systemInstructions;\n this.mcpTools = mcpTools;\n this.mode = mode ?? \"dom\";\n }\n\n private async prepareAgent(\n instructionOrOptions: string | AgentExecuteOptionsBase,\n ): Promise<AgentContext> {\n try {\n const options =\n typeof instructionOrOptions === \"string\"\n ? { instruction: instructionOrOptions }\n : instructionOrOptions;\n\n const maxSteps = options.maxSteps || 20;\n\n // Get the initial page URL first (needed for the system prompt)\n const initialPageUrl = (await this.v3.context.awaitActivePage()).url();\n\n // Build the system prompt with mode-aware tool guidance\n const systemPrompt = buildAgentSystemPrompt({\n url: initialPageUrl,\n executionInstruction: options.instruction,\n mode: this.mode,\n systemInstructions: this.systemInstructions,\n isBrowserbase: this.v3.isBrowserbase,\n excludeTools: options.excludeTools,\n variables: options.variables,\n useSearch: options.useSearch,\n });\n\n if (options.useSearch) {\n const bbApiKey = this.v3.browserbaseApiKey;\n if (!bbApiKey) {\n throw new MissingEnvironmentVariableError(\n \"BROWSERBASE_API_KEY\",\n \"agent search (useSearch: true)\",\n );\n }\n }\n\n const tools = this.createTools(\n options.excludeTools,\n options.variables,\n options.toolTimeout,\n options.useSearch,\n );\n const allTools: ToolSet = { ...tools, ...this.mcpTools };\n\n // Use provided messages for continuation, or start fresh with the instruction\n const messages: ModelMessage[] = options.messages?.length\n ? [...options.messages, { role: \"user\", content: options.instruction }]\n : [{ role: \"user\", content: options.instruction }];\n\n if (!this.llmClient?.getLanguageModel) {\n throw new MissingLLMConfigurationError();\n }\n const baseModel = this.llmClient.getLanguageModel();\n //to do - we likely do not need middleware anymore\n const wrappedModel = wrapLanguageModel({\n model: baseModel,\n middleware: {\n ...SessionFileLogger.createLlmLoggingMiddleware(baseModel.modelId),\n },\n });\n\n if (\n this.mode === \"hybrid\" &&\n !baseModel.modelId.includes(\"gemini-3-flash\") &&\n !baseModel.modelId.includes(\"claude\")\n ) {\n this.logger({\n category: \"agent\",\n message: `Warning: \"${baseModel.modelId}\" may not perform well in hybrid mode. See recommended models: https://docs.stagehand.dev/v3/basics/agent#hybrid-mode`,\n level: 0,\n });\n }\n\n return {\n options,\n maxSteps,\n systemPrompt,\n allTools,\n messages,\n wrappedModel,\n initialPageUrl,\n };\n } catch (error) {\n this.logger({\n category: \"agent\",\n message: `failed to prepare agent: ${error}`,\n level: 0,\n });\n throw error;\n }\n }\n private createPrepareStep(\n userCallback?: PrepareStepFunction<ToolSet>,\n ): PrepareStepFunction<ToolSet> {\n return async (options) => {\n processMessages(options.messages);\n if (userCallback) {\n return userCallback(options);\n }\n return options;\n };\n }\n\n private createStepHandler(\n state: AgentState,\n userCallback?:\n | GenerateTextOnStepFinishCallback<ToolSet>\n | StreamTextOnStepFinishCallback<ToolSet>,\n ) {\n return async (event: StepResult<ToolSet>) => {\n this.logger({\n category: \"agent\",\n message: `Step finished: ${event.finishReason}`,\n level: 2,\n });\n\n if (event.toolCalls && event.toolCalls.length > 0) {\n for (let i = 0; i < event.toolCalls.length; i++) {\n const toolCall = event.toolCalls[i];\n const args = toolCall.input;\n const toolResult = event.toolResults?.[i];\n\n if (event.text && event.text.length > 0) {\n state.collectedReasoning.push(event.text);\n this.logger({\n category: \"agent\",\n message: `reasoning: ${event.text}`,\n level: 1,\n });\n }\n\n if (toolCall.toolName === \"done\") {\n state.completed = true;\n if (args?.taskComplete) {\n const doneReasoning = args.reasoning;\n const allReasoning = state.collectedReasoning.join(\" \");\n state.finalMessage = doneReasoning\n ? `${allReasoning} ${doneReasoning}`.trim()\n : allReasoning || \"Task completed successfully\";\n }\n }\n const mappedActions = mapToolResultToActions({\n toolCallName: toolCall.toolName,\n toolResult,\n args,\n reasoning: event.text || undefined,\n });\n\n for (const action of mappedActions) {\n action.pageUrl = state.currentPageUrl;\n action.timestamp = Date.now();\n state.actions.push(action);\n }\n }\n state.currentPageUrl = (await this.v3.context.awaitActivePage()).url();\n\n // Capture screenshot after tool execution (only for evals)\n if (process.env.EVALS === \"true\") {\n try {\n await this.captureAndEmitScreenshot();\n } catch (e) {\n this.logger({\n category: \"agent\",\n message: `Warning: Failed to capture screenshot: ${getErrorMessage(e)}`,\n level: 1,\n });\n }\n }\n }\n\n if (userCallback) {\n await userCallback(event);\n }\n };\n }\n\n public async execute(\n instructionOrOptions: string | AgentExecuteOptions,\n ): Promise<AgentResult> {\n const startTime = Date.now();\n const options =\n typeof instructionOrOptions === \"object\" ? instructionOrOptions : null;\n const signal = options?.signal;\n\n // Highlight cursor defaults to true for hybrid mode, can be overridden\n const shouldHighlightCursor =\n options?.highlightCursor ?? this.mode === \"hybrid\";\n\n const state: AgentState = {\n collectedReasoning: [],\n actions: [],\n finalMessage: \"\",\n completed: false,\n currentPageUrl: \"\",\n };\n\n let messages: ModelMessage[] = [];\n\n try {\n const {\n options: preparedOptions,\n maxSteps,\n systemPrompt,\n allTools,\n messages: preparedMessages,\n wrappedModel,\n initialPageUrl,\n } = await this.prepareAgent(instructionOrOptions);\n\n // Enable cursor overlay for hybrid mode (coordinate-based interactions)\n if (shouldHighlightCursor && this.mode === \"hybrid\") {\n const page = await this.v3.context.awaitActivePage();\n await page.enableCursorOverlay().catch(() => {});\n }\n\n messages = preparedMessages;\n state.currentPageUrl = initialPageUrl;\n\n const callbacks = (instructionOrOptions as AgentExecuteOptions).callbacks;\n\n if (callbacks) {\n const streamingOnlyCallbacks = [\n \"onChunk\",\n \"onFinish\",\n \"onError\",\n \"onAbort\",\n ];\n const invalidCallbacks = streamingOnlyCallbacks.filter(\n (name) => callbacks[name as keyof typeof callbacks] != null,\n );\n if (invalidCallbacks.length > 0) {\n throw new StreamingCallbacksInNonStreamingModeError(invalidCallbacks);\n }\n }\n\n const result = await this.llmClient.generateText({\n model: wrappedModel,\n messages: prependSystemMessage(systemPrompt, messages),\n tools: allTools,\n stopWhen: (result) => this.handleStop(result, maxSteps),\n temperature: 1,\n toolChoice: \"auto\",\n\n prepareStep: this.createPrepareStep(callbacks?.prepareStep),\n onStepFinish: this.createStepHandler(state, callbacks?.onStepFinish),\n abortSignal: preparedOptions.signal,\n providerOptions: {\n google: { mediaResolution: \"MEDIA_RESOLUTION_HIGH\" },\n openai: { store: false },\n },\n });\n\n const allMessages = [...messages, ...(result.response?.messages || [])];\n const doneResult = await this.ensureDone(\n state,\n wrappedModel,\n allMessages,\n preparedOptions.instruction,\n preparedOptions.output,\n this.logger,\n );\n\n return this.consolidateMetricsAndResult(\n startTime,\n state,\n doneResult.messages,\n result,\n maxSteps,\n doneResult.output,\n );\n } catch (error) {\n // Re-throw validation errors that should propagate to the caller\n if (\n error instanceof StreamingCallbacksInNonStreamingModeError ||\n error instanceof MissingEnvironmentVariableError\n ) {\n throw error;\n }\n\n // Re-throw abort errors wrapped in AgentAbortError for consistent error typing\n if (signal?.aborted) {\n const reason = signal.reason ? String(signal.reason) : \"aborted\";\n throw new AgentAbortError(reason);\n }\n\n const errorMessage = getErrorMessage(error);\n this.logger({\n category: \"agent\",\n message: `Error executing agent task: ${errorMessage}`,\n level: 0,\n });\n\n // For non-abort errors, return a failure result instead of throwing\n return {\n success: false,\n actions: state.actions,\n message: `Failed to execute task: ${errorMessage}`,\n completed: false,\n messages,\n };\n }\n }\n\n public async stream(\n instructionOrOptions: string | AgentStreamExecuteOptions,\n ): Promise<AgentStreamResult> {\n const streamOptions =\n typeof instructionOrOptions === \"object\" ? instructionOrOptions : null;\n\n // Highlight cursor defaults to true for hybrid mode, can be overridden\n const shouldHighlightCursor =\n streamOptions?.highlightCursor ?? this.mode === \"hybrid\";\n\n const {\n options,\n maxSteps,\n systemPrompt,\n allTools,\n messages,\n wrappedModel,\n initialPageUrl,\n } = await this.prepareAgent(instructionOrOptions);\n\n // Enable cursor overlay for hybrid mode (coordinate-based interactions)\n if (shouldHighlightCursor && this.mode === \"hybrid\") {\n const page = await this.v3.context.awaitActivePage();\n await page.enableCursorOverlay().catch(() => {});\n }\n\n const callbacks = (instructionOrOptions as AgentStreamExecuteOptions)\n .callbacks as AgentStreamCallbacks | undefined;\n\n const state: AgentState = {\n collectedReasoning: [],\n actions: [],\n finalMessage: \"\",\n completed: false,\n currentPageUrl: initialPageUrl,\n };\n const startTime = Date.now();\n\n let resolveResult: (value: AgentResult | PromiseLike<AgentResult>) => void;\n let rejectResult: (reason: unknown) => void;\n const resultPromise = new Promise<AgentResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n const handleError = (error: unknown) => {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.logger({\n category: \"agent\",\n message: `Error during streaming: ${errorMessage}`,\n level: 0,\n });\n rejectResult(error);\n };\n\n const streamResult = this.llmClient.streamText({\n model: wrappedModel,\n messages: prependSystemMessage(systemPrompt, messages),\n tools: allTools,\n stopWhen: (result) => this.handleStop(result, maxSteps),\n temperature: 1,\n toolChoice: \"auto\",\n prepareStep: this.createPrepareStep(callbacks?.prepareStep),\n onStepFinish: this.createStepHandler(state, callbacks?.onStepFinish),\n onError: (event) => {\n if (callbacks?.onError) {\n callbacks.onError(event);\n }\n handleError(event.error);\n },\n onChunk: callbacks?.onChunk,\n onFinish: (event) => {\n if (callbacks?.onFinish) {\n callbacks.onFinish(event);\n }\n\n const allMessages = [...messages, ...(event.response?.messages || [])];\n this.ensureDone(\n state,\n wrappedModel,\n allMessages,\n options.instruction,\n options.output,\n this.logger,\n ).then((doneResult) => {\n const result = this.consolidateMetricsAndResult(\n startTime,\n state,\n doneResult.messages,\n event,\n maxSteps,\n doneResult.output,\n );\n resolveResult(result);\n });\n },\n onAbort: (event) => {\n if (callbacks?.onAbort) {\n callbacks.onAbort(event);\n }\n // Reject the result promise with AgentAbortError when stream is aborted\n const reason = options.signal?.reason\n ? String(options.signal.reason)\n : \"Stream was aborted\";\n rejectResult(new AgentAbortError(reason));\n },\n abortSignal: options.signal,\n providerOptions: {\n google: { mediaResolution: \"MEDIA_RESOLUTION_HIGH\" },\n openai: { store: false },\n },\n });\n\n const agentStreamResult = streamResult as AgentStreamResult;\n agentStreamResult.result = resultPromise;\n return agentStreamResult;\n }\n\n private consolidateMetricsAndResult(\n startTime: number,\n state: AgentState,\n inputMessages: ModelMessage[],\n result: {\n text?: string;\n totalUsage?: LanguageModelUsage;\n response?: { messages?: ModelMessage[] };\n steps?: StepResult<ToolSet>[];\n },\n maxSteps?: number,\n output?: Record<string, unknown>,\n ): AgentResult {\n if (!state.finalMessage) {\n const allReasoning = state.collectedReasoning.join(\" \").trim();\n\n if (!state.completed && maxSteps && result.steps?.length >= maxSteps) {\n this.logger({\n category: \"agent\",\n message: `Agent stopped: reached maximum steps (${maxSteps})`,\n level: 1,\n });\n state.finalMessage = `Agent stopped: reached maximum steps (${maxSteps})`;\n } else {\n state.finalMessage = allReasoning || result.text || \"\";\n }\n }\n\n const endTime = Date.now();\n const inferenceTimeMs = endTime - startTime;\n if (result.totalUsage) {\n this.v3.updateMetrics(\n V3FunctionName.AGENT,\n result.totalUsage.inputTokens || 0,\n result.totalUsage.outputTokens || 0,\n result.totalUsage.reasoningTokens || 0,\n result.totalUsage.cachedInputTokens || 0,\n inferenceTimeMs,\n );\n }\n\n return {\n success: state.completed,\n message: state.finalMessage || \"Task execution completed\",\n actions: state.actions,\n completed: state.completed,\n output,\n usage: result.totalUsage\n ? {\n input_tokens: result.totalUsage.inputTokens || 0,\n output_tokens: result.totalUsage.outputTokens || 0,\n reasoning_tokens: result.totalUsage.reasoningTokens || 0,\n cached_input_tokens: result.totalUsage.cachedInputTokens || 0,\n inference_time_ms: inferenceTimeMs,\n }\n : undefined,\n messages: inputMessages,\n };\n }\n\n private createTools(\n excludeTools?: string[],\n variables?: Variables,\n toolTimeout?: number,\n useSearch?: boolean,\n ) {\n const provider = this.llmClient?.getLanguageModel?.()?.provider;\n return createAgentTools(this.v3, {\n executionModel: this.executionModel,\n logger: this.logger,\n mode: this.mode,\n provider,\n excludeTools,\n variables,\n toolTimeout,\n useSearch,\n browserbaseApiKey: useSearch ? this.v3.browserbaseApiKey : undefined,\n });\n }\n\n private handleStop(\n result: Parameters<ReturnType<typeof stepCountIs>>[0],\n maxSteps: number,\n ): boolean | PromiseLike<boolean> {\n const lastStep = result.steps[result.steps.length - 1];\n if (lastStep?.toolCalls?.some((tc) => tc.toolName === \"done\")) {\n return true;\n }\n return stepCountIs(maxSteps)(result);\n }\n\n /**\n * Ensures the done tool is called at the end of agent execution.\n * Returns the messages and any extracted output from the done call.\n */\n private async ensureDone(\n state: AgentState,\n model: LanguageModel,\n messages: ModelMessage[],\n instruction: string,\n outputSchema?: StagehandZodObject,\n logger?: (message: LogLine) => void,\n ): Promise<{ messages: ModelMessage[]; output?: Record<string, unknown> }> {\n if (state.completed) return { messages };\n\n const doneResult = await handleDoneToolCall({\n model,\n inputMessages: messages,\n instruction,\n outputSchema,\n logger,\n });\n\n state.completed = doneResult.taskComplete;\n state.finalMessage = doneResult.reasoning;\n\n const doneAction = mapToolResultToActions({\n toolCallName: \"done\",\n toolResult: {\n success: true,\n reasoning: doneResult.reasoning,\n taskComplete: doneResult.taskComplete,\n },\n args: {\n reasoning: doneResult.reasoning,\n taskComplete: doneResult.taskComplete,\n },\n reasoning: doneResult.reasoning,\n });\n\n for (const action of doneAction) {\n action.pageUrl = state.currentPageUrl;\n action.timestamp = Date.now();\n state.actions.push(action);\n }\n\n return {\n messages: [...messages, ...doneResult.messages],\n output: doneResult.output,\n };\n }\n\n /**\n * Capture a screenshot and emit it via the event bus\n */\n private async captureAndEmitScreenshot(): Promise<void> {\n try {\n const page = await this.v3.context.awaitActivePage();\n const screenshot = await page.screenshot({ fullPage: false });\n this.v3.bus.emit(\"agent_screenshot_taken_event\", screenshot);\n } catch (error) {\n this.logger({\n category: \"agent\",\n message: `Error capturing screenshot: ${getErrorMessage(error)}`,\n level: 0,\n });\n }\n }\n}\n"]}
@@ -275,7 +275,7 @@ export interface AgentExecuteOptionsBase {
275
275
  * - `think` - Agent reasoning/planning step
276
276
  * - `wait` - Wait for time or condition
277
277
  * - `done` - Mark task as complete
278
- * - `search` - Web search (requires BRAVE_API_KEY)
278
+ * - `search` - Web search (requires useSearch: true and BROWSERBASE_API_KEY)
279
279
  *
280
280
  * **Hybrid mode:**
281
281
  * - `click` - Click at specific coordinates
@@ -294,7 +294,7 @@ export interface AgentExecuteOptionsBase {
294
294
  * - `think` - Agent reasoning step
295
295
  * - `wait` - Wait for time/condition
296
296
  * - `done` - Mark task complete
297
- * - `search` - Web search (requires BRAVE_API_KEY)
297
+ * - `search` - Web search (requires useSearch: true and BROWSERBASE_API_KEY)
298
298
  *
299
299
  * @experimental
300
300
  * @example
@@ -359,6 +359,20 @@ export interface AgentExecuteOptionsBase {
359
359
  * @default 45000 (45 seconds)
360
360
  */
361
361
  toolTimeout?: number;
362
+ /**
363
+ * Enable the web search tool powered by Browserbase Search API.
364
+ * Requires a valid Browserbase API key (BROWSERBASE_API_KEY).
365
+ * When set to true, the agent gains access to a `search` tool for web searches.
366
+ *
367
+ * @example
368
+ * ```typescript
369
+ * const result = await agent.execute({
370
+ * instruction: "Find the latest news about AI",
371
+ * useSearch: true,
372
+ * });
373
+ * ```
374
+ */
375
+ useSearch?: boolean;
362
376
  }
363
377
  /**
364
378
  * Options for non-streaming agent execution.