@browserbasehq/orca 3.0.0-preview.0

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 (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +165 -0
  3. package/dist/index.d.ts +1611 -0
  4. package/dist/index.js +28681 -0
  5. package/dist/lib/api.d.ts +23 -0
  6. package/dist/lib/dom/build/scriptContent.d.ts +1 -0
  7. package/dist/lib/inference.d.ts +71 -0
  8. package/dist/lib/inferenceLogUtils.d.ts +12 -0
  9. package/dist/lib/logger.d.ts +54 -0
  10. package/dist/lib/prompt.d.ts +12 -0
  11. package/dist/lib/utils.d.ts +65 -0
  12. package/dist/lib/v3/agent/AgentClient.d.ts +18 -0
  13. package/dist/lib/v3/agent/AgentProvider.d.ts +18 -0
  14. package/dist/lib/v3/agent/AnthropicCUAClient.d.ts +55 -0
  15. package/dist/lib/v3/agent/OpenAICUAClient.d.ts +64 -0
  16. package/dist/lib/v3/agent/StagehandAgent.d.ts +15 -0
  17. package/dist/lib/v3/agent/tools/index.d.ts +229 -0
  18. package/dist/lib/v3/agent/tools/v3-act.d.ts +29 -0
  19. package/dist/lib/v3/agent/tools/v3-ariaTree.d.ts +11 -0
  20. package/dist/lib/v3/agent/tools/v3-close.d.ts +24 -0
  21. package/dist/lib/v3/agent/tools/v3-extract.d.ts +38 -0
  22. package/dist/lib/v3/agent/tools/v3-fillform.d.ts +37 -0
  23. package/dist/lib/v3/agent/tools/v3-goto.d.ts +29 -0
  24. package/dist/lib/v3/agent/tools/v3-navback.d.ts +17 -0
  25. package/dist/lib/v3/agent/tools/v3-screenshot.d.ts +13 -0
  26. package/dist/lib/v3/agent/tools/v3-scroll.d.ts +23 -0
  27. package/dist/lib/v3/agent/tools/v3-wait.d.ts +19 -0
  28. package/dist/lib/v3/agent/utils/cuaKeyMapping.d.ts +10 -0
  29. package/dist/lib/v3/agent/utils/imageCompression.d.ts +18 -0
  30. package/dist/lib/v3/agent/utils/messageProcessing.d.ts +13 -0
  31. package/dist/lib/v3/dom/build/scriptV3Content.d.ts +1 -0
  32. package/dist/lib/v3/dom/genDomScripts.d.ts +1 -0
  33. package/dist/lib/v3/dom/index.d.ts +1 -0
  34. package/dist/lib/v3/dom/piercer.entry.d.ts +1 -0
  35. package/dist/lib/v3/dom/piercer.runtime.d.ts +25 -0
  36. package/dist/lib/v3/handlers/actHandler.d.ts +18 -0
  37. package/dist/lib/v3/handlers/extractHandler.d.ts +29 -0
  38. package/dist/lib/v3/handlers/handlerUtils/actHandlerUtils.d.ts +18 -0
  39. package/dist/lib/v3/handlers/observeHandler.d.ts +15 -0
  40. package/dist/lib/v3/handlers/v3AgentHandler.d.ts +17 -0
  41. package/dist/lib/v3/handlers/v3CuaAgentHandler.d.ts +26 -0
  42. package/dist/lib/v3/index.d.ts +10 -0
  43. package/dist/lib/v3/launch/browserbase.d.ts +8 -0
  44. package/dist/lib/v3/launch/local.d.ts +13 -0
  45. package/dist/lib/v3/llm/AnthropicClient.d.ts +16 -0
  46. package/dist/lib/v3/llm/CerebrasClient.d.ts +17 -0
  47. package/dist/lib/v3/llm/GoogleClient.d.ts +19 -0
  48. package/dist/lib/v3/llm/GroqClient.d.ts +17 -0
  49. package/dist/lib/v3/llm/LLMClient.d.ts +99 -0
  50. package/dist/lib/v3/llm/LLMProvider.d.ts +10 -0
  51. package/dist/lib/v3/llm/OpenAIClient.d.ts +15 -0
  52. package/dist/lib/v3/llm/aisdk.d.ts +15 -0
  53. package/dist/lib/v3/logger.d.ts +48 -0
  54. package/dist/lib/v3/mcp/connection.d.ts +11 -0
  55. package/dist/lib/v3/mcp/utils.d.ts +3 -0
  56. package/dist/lib/v3/tests/default-page-tracking.spec.d.ts +1 -0
  57. package/dist/lib/v3/tests/perform-understudy-method.spec.d.ts +1 -0
  58. package/dist/lib/v3/tests/shadow-iframe.spec.d.ts +1 -0
  59. package/dist/lib/v3/tests/timeouts.spec.d.ts +1 -0
  60. package/dist/lib/v3/tests/v3.config.d.ts +4 -0
  61. package/dist/lib/v3/tests/v3.playwright.config.d.ts +2 -0
  62. package/dist/lib/v3/tests/xpath-for-location-deep.spec.d.ts +1 -0
  63. package/dist/lib/v3/types/act.d.ts +10 -0
  64. package/dist/lib/v3/types/agent.d.ts +132 -0
  65. package/dist/lib/v3/types/api.d.ts +40 -0
  66. package/dist/lib/v3/types/cache.d.ts +71 -0
  67. package/dist/lib/v3/types/context.d.ts +2 -0
  68. package/dist/lib/v3/types/evals.d.ts +71 -0
  69. package/dist/lib/v3/types/evaluator.d.ts +40 -0
  70. package/dist/lib/v3/types/llm.d.ts +11 -0
  71. package/dist/lib/v3/types/log.d.ts +23 -0
  72. package/dist/lib/v3/types/model.d.ts +20 -0
  73. package/dist/lib/v3/types/playwright.d.ts +6 -0
  74. package/dist/lib/v3/types/stagehand.d.ts +113 -0
  75. package/dist/lib/v3/types/stagehandApiErrors.d.ts +18 -0
  76. package/dist/lib/v3/types/stagehandErrors.d.ts +104 -0
  77. package/dist/lib/v3/types.d.ts +176 -0
  78. package/dist/lib/v3/understudy/a11y/snapshot.d.ts +71 -0
  79. package/dist/lib/v3/understudy/cdp.d.ts +58 -0
  80. package/dist/lib/v3/understudy/context.d.ts +120 -0
  81. package/dist/lib/v3/understudy/deepLocator.d.ts +69 -0
  82. package/dist/lib/v3/understudy/executionContextRegistry.d.ts +15 -0
  83. package/dist/lib/v3/understudy/frame.d.ts +63 -0
  84. package/dist/lib/v3/understudy/frameLocator.d.ts +46 -0
  85. package/dist/lib/v3/understudy/frameRegistry.d.ts +100 -0
  86. package/dist/lib/v3/understudy/locator.d.ts +196 -0
  87. package/dist/lib/v3/understudy/page.d.ts +241 -0
  88. package/dist/lib/v3/understudy/piercer.d.ts +4 -0
  89. package/dist/lib/v3/v3.d.ts +156 -0
  90. package/dist/lib/version.d.ts +5 -0
  91. package/package.json +130 -0
@@ -0,0 +1,23 @@
1
+ import { z } from "zod/v3";
2
+ import { StagehandAPIConstructorParams, StartSessionParams, StartSessionResult } from "./v3/types/api";
3
+ import { GotoOptions } from "./v3/types/playwright";
4
+ import { ActOptions, ActResult, AgentConfig, ExtractOptions, ExtractResult, ObserveOptions, Action } from "./v3/types/stagehand";
5
+ import { AgentExecuteOptions, AgentResult } from "@/lib/v3/types/agent";
6
+ export declare class StagehandAPI {
7
+ private apiKey;
8
+ private projectId;
9
+ private sessionId?;
10
+ private modelApiKey;
11
+ private logger;
12
+ private fetchWithCookies;
13
+ constructor({ apiKey, projectId, logger }: StagehandAPIConstructorParams);
14
+ init({ modelName, modelApiKey, domSettleTimeoutMs, verbose, debugDom, systemPrompt, selfHeal, waitForCaptchaSolves, actionTimeoutMs, browserbaseSessionCreateParams, browserbaseSessionID, }: StartSessionParams): Promise<StartSessionResult>;
15
+ act(options: ActOptions | Action): Promise<ActResult>;
16
+ extract<T extends z.AnyZodObject>(options: ExtractOptions<T>): Promise<ExtractResult<T>>;
17
+ observe(options?: ObserveOptions): Promise<Action[]>;
18
+ goto(url: string, options?: GotoOptions): Promise<void>;
19
+ agentExecute(agentConfig: AgentConfig, executeOptions: AgentExecuteOptions): Promise<AgentResult>;
20
+ end(): Promise<Response>;
21
+ private execute;
22
+ private request;
23
+ }
@@ -0,0 +1 @@
1
+ export declare const scriptContent = "(() => {\n // lib/dom/elementCheckUtils.ts\n function isElementNode(node) {\n return node.nodeType === Node.ELEMENT_NODE;\n }\n function isTextNode(node) {\n return node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim());\n }\n\n // lib/dom/xpathUtils.ts\n function getParentElement(node) {\n return isElementNode(node) ? node.parentElement : node.parentNode;\n }\n function getCombinations(attributes, size) {\n const results = [];\n function helper(start, combo) {\n if (combo.length === size) {\n results.push([...combo]);\n return;\n }\n for (let i = start; i < attributes.length; i++) {\n combo.push(attributes[i]);\n helper(i + 1, combo);\n combo.pop();\n }\n }\n helper(0, []);\n return results;\n }\n function isXPathFirstResultElement(xpath, target) {\n try {\n const result = document.evaluate(\n xpath,\n document.documentElement,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null\n );\n return result.snapshotItem(0) === target;\n } catch (error) {\n console.warn(`Invalid XPath expression: ${xpath}`, error);\n return false;\n }\n }\n function escapeXPathString(value) {\n if (value.includes(\"'\")) {\n if (value.includes('\"')) {\n return \"concat(\" + value.split(/('+)/).map((part) => {\n if (part === \"'\") {\n return `\"'\"`;\n } else if (part.startsWith(\"'\") && part.endsWith(\"'\")) {\n return `\"${part}\"`;\n } else {\n return `'${part}'`;\n }\n }).join(\",\") + \")\";\n } else {\n return `\"${value}\"`;\n }\n } else {\n return `'${value}'`;\n }\n }\n async function generateXPathsForElement(element) {\n if (!element) return [];\n const [complexXPath, standardXPath, idBasedXPath] = await Promise.all([\n generateComplexXPath(element),\n generateStandardXPath(element),\n generatedIdBasedXPath(element)\n ]);\n return [standardXPath, ...idBasedXPath ? [idBasedXPath] : [], complexXPath];\n }\n async function generateComplexXPath(element) {\n const parts = [];\n let currentElement = element;\n while (currentElement && (isTextNode(currentElement) || isElementNode(currentElement))) {\n if (isElementNode(currentElement)) {\n const el = currentElement;\n let selector = el.tagName.toLowerCase();\n const attributePriority = [\n \"data-qa\",\n \"data-component\",\n \"data-role\",\n \"role\",\n \"aria-role\",\n \"type\",\n \"name\",\n \"aria-label\",\n \"placeholder\",\n \"title\",\n \"alt\"\n ];\n const attributes = attributePriority.map((attr) => {\n let value = el.getAttribute(attr);\n if (attr === \"href-full\" && value) {\n value = el.getAttribute(\"href\");\n }\n return value ? { attr: attr === \"href-full\" ? \"href\" : attr, value } : null;\n }).filter((attr) => attr !== null);\n let uniqueSelector = \"\";\n for (let i = 1; i <= attributes.length; i++) {\n const combinations = getCombinations(attributes, i);\n for (const combo of combinations) {\n const conditions = combo.map((a) => `@${a.attr}=${escapeXPathString(a.value)}`).join(\" and \");\n const xpath2 = `//${selector}[${conditions}]`;\n if (isXPathFirstResultElement(xpath2, el)) {\n uniqueSelector = xpath2;\n break;\n }\n }\n if (uniqueSelector) break;\n }\n if (uniqueSelector) {\n parts.unshift(uniqueSelector.replace(\"//\", \"\"));\n break;\n } else {\n const parent = getParentElement(el);\n if (parent) {\n const siblings = Array.from(parent.children).filter(\n (sibling) => sibling.tagName === el.tagName\n );\n const index = siblings.indexOf(el) + 1;\n selector += siblings.length > 1 ? `[${index}]` : \"\";\n }\n parts.unshift(selector);\n }\n }\n currentElement = getParentElement(currentElement);\n }\n const xpath = \"//\" + parts.join(\"/\");\n return xpath;\n }\n async function generateStandardXPath(element) {\n const parts = [];\n while (element && (isTextNode(element) || isElementNode(element))) {\n let index = 0;\n let hasSameTypeSiblings = false;\n const siblings = element.parentElement ? Array.from(element.parentElement.childNodes) : [];\n for (let i = 0; i < siblings.length; i++) {\n const sibling = siblings[i];\n if (sibling.nodeType === element.nodeType && sibling.nodeName === element.nodeName) {\n index = index + 1;\n hasSameTypeSiblings = true;\n if (sibling.isSameNode(element)) {\n break;\n }\n }\n }\n if (element.nodeName !== \"#text\") {\n const tagName = element.nodeName.toLowerCase();\n const pathIndex = hasSameTypeSiblings ? `[${index}]` : \"\";\n parts.unshift(`${tagName}${pathIndex}`);\n }\n element = element.parentElement;\n }\n return parts.length ? `/${parts.join(\"/\")}` : \"\";\n }\n async function generatedIdBasedXPath(element) {\n if (isElementNode(element) && element.id) {\n return `//*[@id='${element.id}']`;\n }\n return null;\n }\n\n // types/stagehandErrors.ts\n var StagehandError = class extends Error {\n constructor(message) {\n super(message);\n this.name = this.constructor.name;\n }\n };\n var StagehandDomProcessError = class extends StagehandError {\n constructor(message) {\n super(`Error Processing Dom: ${message}`);\n }\n };\n\n // lib/dom/utils.ts\n function canElementScroll(elem) {\n if (typeof elem.scrollTo !== \"function\") {\n console.warn(\"canElementScroll: .scrollTo is not a function.\");\n return false;\n }\n try {\n const originalTop = elem.scrollTop;\n elem.scrollTo({\n top: originalTop + 100,\n left: 0,\n behavior: \"instant\"\n });\n if (elem.scrollTop === originalTop) {\n throw new StagehandDomProcessError(\"scrollTop did not change\");\n }\n elem.scrollTo({\n top: originalTop,\n left: 0,\n behavior: \"instant\"\n });\n return true;\n } catch (error) {\n console.warn(\"canElementScroll error:\", error.message || error);\n return false;\n }\n }\n function getNodeFromXpath(xpath) {\n return document.evaluate(\n xpath,\n document.documentElement,\n null,\n XPathResult.FIRST_ORDERED_NODE_TYPE,\n null\n ).singleNodeValue;\n }\n function waitForElementScrollEnd(element, idleMs = 100) {\n return new Promise((resolve) => {\n let scrollEndTimer;\n const handleScroll = () => {\n clearTimeout(scrollEndTimer);\n scrollEndTimer = window.setTimeout(() => {\n element.removeEventListener(\"scroll\", handleScroll);\n resolve();\n }, idleMs);\n };\n element.addEventListener(\"scroll\", handleScroll, { passive: true });\n handleScroll();\n });\n }\n\n // lib/dom/process.ts\n function getScrollableElements(topN) {\n const docEl = document.documentElement;\n const scrollableElements = [docEl];\n const allElements = document.querySelectorAll(\"*\");\n for (const elem of allElements) {\n const style = window.getComputedStyle(elem);\n const overflowY = style.overflowY;\n const isPotentiallyScrollable = overflowY === \"auto\" || overflowY === \"scroll\" || overflowY === \"overlay\";\n if (isPotentiallyScrollable) {\n const candidateScrollDiff = elem.scrollHeight - elem.clientHeight;\n if (candidateScrollDiff > 0 && canElementScroll(elem)) {\n scrollableElements.push(elem);\n }\n }\n }\n scrollableElements.sort((a, b) => b.scrollHeight - a.scrollHeight);\n if (topN !== void 0) {\n return scrollableElements.slice(0, topN);\n }\n return scrollableElements;\n }\n async function getScrollableElementXpaths(topN) {\n const scrollableElems = getScrollableElements(topN);\n const xpaths = [];\n for (const elem of scrollableElems) {\n const allXPaths = await generateXPathsForElement(elem);\n const firstXPath = allXPaths?.[0] || \"\";\n xpaths.push(firstXPath);\n }\n return xpaths;\n }\n (() => {\n const closedRoots = /* @__PURE__ */ new WeakMap();\n const nativeAttachShadow = Element.prototype.attachShadow;\n Element.prototype.attachShadow = function(init) {\n const root = nativeAttachShadow.call(this, init);\n if (init.mode === \"closed\") closedRoots.set(this, root);\n return root;\n };\n const backdoor = {\n getClosedRoot: (host) => closedRoots.get(host),\n queryClosed: (host, selector) => {\n const root = closedRoots.get(host);\n return root ? Array.from(root.querySelectorAll(selector)) : [];\n },\n xpathClosed: (host, xp) => {\n const root = closedRoots.get(host);\n if (!root) return [];\n const it = document.evaluate(\n xp,\n root,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null\n );\n const out = [];\n for (let i = 0; i < it.snapshotLength; ++i) {\n const n = it.snapshotItem(i);\n if (n) out.push(n);\n }\n return out;\n }\n };\n if (!(\"__stagehand__\" in window)) {\n Object.defineProperty(window, \"__stagehand__\", {\n value: backdoor,\n enumerable: false,\n writable: false,\n configurable: false\n });\n }\n })();\n window.getScrollableElementXpaths = getScrollableElementXpaths;\n window.getNodeFromXpath = getNodeFromXpath;\n window.waitForElementScrollEnd = waitForElementScrollEnd;\n})();\n";
@@ -0,0 +1,71 @@
1
+ import { z } from "zod/v3";
2
+ import { LogLine } from "./v3/types/log";
3
+ import { LLMClient } from "./v3/llm/LLMClient";
4
+ /** Simple usage shape if your LLM returns usage tokens. */
5
+ interface LLMUsage {
6
+ prompt_tokens: number;
7
+ completion_tokens: number;
8
+ total_tokens: number;
9
+ }
10
+ /**
11
+ * For calls that use a schema: the LLMClient may return { data: T; usage?: LLMUsage }
12
+ */
13
+ export interface LLMParsedResponse<T> {
14
+ data: T;
15
+ usage?: LLMUsage;
16
+ }
17
+ export declare function extract({ instruction, domElements, schema, llmClient, logger, userProvidedInstructions, logInferenceToFile, }: {
18
+ instruction: string;
19
+ domElements: string;
20
+ schema: z.ZodObject<z.ZodRawShape>;
21
+ llmClient: LLMClient;
22
+ userProvidedInstructions?: string;
23
+ logger: (message: LogLine) => void;
24
+ logInferenceToFile?: boolean;
25
+ }): Promise<{
26
+ metadata: {
27
+ completed: boolean;
28
+ progress: string;
29
+ };
30
+ prompt_tokens: number;
31
+ completion_tokens: number;
32
+ inference_time_ms: number;
33
+ }>;
34
+ export declare function observe({ instruction, domElements, llmClient, userProvidedInstructions, logger, logInferenceToFile, }: {
35
+ instruction: string;
36
+ domElements: string;
37
+ llmClient: LLMClient;
38
+ userProvidedInstructions?: string;
39
+ logger: (message: LogLine) => void;
40
+ logInferenceToFile?: boolean;
41
+ }): Promise<{
42
+ elements: {
43
+ elementId: string;
44
+ description: string;
45
+ method: string;
46
+ arguments: string[];
47
+ }[];
48
+ prompt_tokens: number;
49
+ completion_tokens: number;
50
+ inference_time_ms: number;
51
+ }>;
52
+ export declare function act({ instruction, domElements, llmClient, userProvidedInstructions, logger, logInferenceToFile, }: {
53
+ instruction: string;
54
+ domElements: string;
55
+ llmClient: LLMClient;
56
+ userProvidedInstructions?: string;
57
+ logger: (message: LogLine) => void;
58
+ logInferenceToFile?: boolean;
59
+ }): Promise<{
60
+ element: {
61
+ elementId: string;
62
+ description: string;
63
+ method: string;
64
+ arguments: string[];
65
+ };
66
+ prompt_tokens: number;
67
+ completion_tokens: number;
68
+ inference_time_ms: number;
69
+ twoStep: boolean;
70
+ }>;
71
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Appends a new entry to the act_summary.json file, then writes the file back out.
3
+ */
4
+ export declare function appendSummary<T>(inferenceType: string, entry: T): void;
5
+ /**
6
+ * Writes `data` as JSON into a file in `directory`, using a prefix plus timestamp.
7
+ * Returns both the file name and the timestamp used, so you can log them.
8
+ */
9
+ export declare function writeTimestampedTxtFile(directory: string, prefix: string, data: unknown): {
10
+ fileName: string;
11
+ timestamp: string;
12
+ };
@@ -0,0 +1,54 @@
1
+ import pino from "pino";
2
+ import { LogLine } from "./v3/types/log";
3
+ export interface LoggerOptions {
4
+ pretty?: boolean;
5
+ level?: pino.Level;
6
+ destination?: pino.DestinationStream;
7
+ usePino?: boolean;
8
+ }
9
+ /**
10
+ * Creates a configured Pino logger instance
11
+ */
12
+ export declare function createLogger(options?: LoggerOptions): import("pino/pino").Logger<never, boolean>;
13
+ /**
14
+ * StagehandLogger class that wraps Pino for our specific needs
15
+ */
16
+ export declare class StagehandLogger {
17
+ /**
18
+ * We maintain a single shared Pino instance when `usePino` is enabled.
19
+ * This prevents spawning a new worker thread for every Stagehand instance
20
+ * (which happens when `pino-pretty` transport is used), eliminating the
21
+ * memory/RSS growth observed when many Stagehand objects are created and
22
+ * disposed within the same process (e.g. a request-per-instance API).
23
+ */
24
+ private static sharedPinoLogger;
25
+ private logger?;
26
+ private verbose;
27
+ private externalLogger?;
28
+ private usePino;
29
+ private isTest;
30
+ constructor(options?: LoggerOptions, externalLogger?: (logLine: LogLine) => void);
31
+ /**
32
+ * Set the verbosity level
33
+ */
34
+ setVerbosity(level: 0 | 1 | 2): void;
35
+ /**
36
+ * Log a message using our LogLine format
37
+ */
38
+ log(logLine: LogLine): void;
39
+ /**
40
+ * Helper to format auxiliary data for structured logging
41
+ */
42
+ private formatAuxiliaryData;
43
+ /**
44
+ * Convenience methods for different log levels
45
+ */
46
+ error(message: string, data?: Record<string, unknown>): void;
47
+ warn(message: string, data?: Record<string, unknown>): void;
48
+ info(message: string, data?: Record<string, unknown>): void;
49
+ debug(message: string, data?: Record<string, unknown>): void;
50
+ /**
51
+ * Convert a plain object to our auxiliary format
52
+ */
53
+ private convertToAuxiliary;
54
+ }
@@ -0,0 +1,12 @@
1
+ import { ChatMessage } from "./v3/llm/LLMClient";
2
+ export declare function buildUserInstructionsString(userProvidedInstructions?: string): string;
3
+ export declare function buildExtractSystemPrompt(isUsingPrintExtractedDataTool?: boolean, userProvidedInstructions?: string): ChatMessage;
4
+ export declare function buildExtractUserPrompt(instruction: string, domElements: string, isUsingPrintExtractedDataTool?: boolean): ChatMessage;
5
+ export declare function buildMetadataSystemPrompt(): ChatMessage;
6
+ export declare function buildMetadataPrompt(instruction: string, extractionResponse: object): ChatMessage;
7
+ export declare function buildObserveSystemPrompt(userProvidedInstructions?: string): ChatMessage;
8
+ export declare function buildObserveUserMessage(instruction: string, domElements: string): ChatMessage;
9
+ export declare function buildActSystemPrompt(userProvidedInstructions?: string): ChatMessage;
10
+ export declare function buildActPrompt(action: string, supportedActions: string[], variables?: Record<string, string>): string;
11
+ export declare function buildStepTwoPrompt(originalUserAction: string, previousAction: string, supportedActions: string[], variables?: Record<string, string>): string;
12
+ export declare function buildOperatorSystemPrompt(goal: string): ChatMessage;
@@ -0,0 +1,65 @@
1
+ import { Schema } from "@google/genai";
2
+ import { z, ZodTypeAny } from "zod/v3";
3
+ import { LogLine } from "./v3/types/log";
4
+ import { ModelProvider } from "./v3/types/model";
5
+ import { ZodPathSegments } from "./v3/types/stagehand";
6
+ export declare function validateZodSchema(schema: z.ZodTypeAny, data: unknown): boolean;
7
+ /**
8
+ * Detects if the code is running in the Bun runtime environment.
9
+ * @returns {boolean} True if running in Bun, false otherwise.
10
+ */
11
+ export declare function isRunningInBun(): boolean;
12
+ export declare function toGeminiSchema(zodSchema: z.ZodTypeAny): Schema;
13
+ export declare function getZodType(schema: z.ZodTypeAny): string;
14
+ /**
15
+ * Recursively traverses a given Zod schema, scanning for any fields of type `z.string().url()`.
16
+ * For each such field, it replaces the `z.string().url()` with `z.number()`.
17
+ *
18
+ * This function is used internally by higher-level utilities (e.g., transforming entire object schemas)
19
+ * and handles nested objects, arrays, unions, intersections, optionals.
20
+ *
21
+ * @param schema - The Zod schema to transform.
22
+ * @param currentPath - An array of string/number keys representing the current schema path (used internally for recursion).
23
+ * @returns A two-element tuple:
24
+ * 1. The updated Zod schema, with any `.url()` fields replaced by `z.number()`.
25
+ * 2. An array of {@link ZodPathSegments} objects representing each replaced field, including the path segments.
26
+ */
27
+ export declare function transformSchema(schema: z.ZodTypeAny, currentPath: Array<string | number>): [z.ZodTypeAny, ZodPathSegments[]];
28
+ /**
29
+ * Once we get the final extracted object that has numeric IDs in place of URLs,
30
+ * use `injectUrls` to walk the object and replace numeric IDs
31
+ * with the real URL strings from idToUrlMapping. The `path` may include `*`
32
+ * for array indices (indicating "all items in the array").
33
+ */
34
+ export declare function injectUrls(obj: unknown, path: Array<string | number>, idToUrlMapping: Record<string, string>): void;
35
+ /**
36
+ * Mapping from LLM provider names to their corresponding environment variable names for API keys.
37
+ */
38
+ export declare const providerEnvVarMap: Partial<Record<ModelProvider | string, string>>;
39
+ /**
40
+ * Loads an API key for a provider, checking environment variables.
41
+ * @param provider The name of the provider (e.g., 'openai', 'anthropic')
42
+ * @param logger Optional logger for info/error messages
43
+ * @returns The API key if found, undefined otherwise
44
+ */
45
+ export declare function loadApiKeyFromEnv(provider: string | undefined, logger: (logLine: LogLine) => void): string | undefined;
46
+ export declare function trimTrailingTextNode(path: string | undefined): string | undefined;
47
+ export interface JsonSchemaProperty {
48
+ type: string;
49
+ enum?: unknown[];
50
+ items?: JsonSchemaProperty;
51
+ properties?: Record<string, JsonSchemaProperty>;
52
+ required?: string[];
53
+ minimum?: number;
54
+ maximum?: number;
55
+ description?: string;
56
+ }
57
+ export interface JsonSchema extends JsonSchemaProperty {
58
+ type: string;
59
+ }
60
+ /**
61
+ * Converts a JSON Schema object to a Zod schema
62
+ * @param schema The JSON Schema object to convert
63
+ * @returns A Zod schema equivalent to the input JSON Schema
64
+ */
65
+ export declare function jsonSchemaToZod(schema: JsonSchema): ZodTypeAny;
@@ -0,0 +1,18 @@
1
+ import { AgentAction, AgentResult, AgentType, AgentExecutionOptions } from "../types/agent";
2
+ /**
3
+ * Abstract base class for agent clients
4
+ * This provides a common interface for all agent implementations
5
+ */
6
+ export declare abstract class AgentClient {
7
+ type: AgentType;
8
+ modelName: string;
9
+ clientOptions: Record<string, unknown>;
10
+ userProvidedInstructions?: string;
11
+ constructor(type: AgentType, modelName: string, userProvidedInstructions?: string);
12
+ abstract execute(options: AgentExecutionOptions): Promise<AgentResult>;
13
+ abstract captureScreenshot(options?: Record<string, unknown>): Promise<unknown>;
14
+ abstract setViewport(width: number, height: number): void;
15
+ abstract setCurrentUrl(url: string): void;
16
+ abstract setScreenshotProvider(provider: () => Promise<string>): void;
17
+ abstract setActionHandler(handler: (action: AgentAction) => Promise<void>): void;
18
+ }
@@ -0,0 +1,18 @@
1
+ import { AgentType } from "../types/agent";
2
+ import { LogLine } from "../types/log";
3
+ import { ToolSet } from "ai/dist";
4
+ import { AgentClient } from "./AgentClient";
5
+ /**
6
+ * Provider for agent clients
7
+ * This class is responsible for creating the appropriate agent client
8
+ * based on the provider type
9
+ */
10
+ export declare class AgentProvider {
11
+ private logger;
12
+ /**
13
+ * Create a new agent provider
14
+ */
15
+ constructor(logger: (message: LogLine) => void);
16
+ getClient(modelName: string, clientOptions?: Record<string, unknown>, userProvidedInstructions?: string, tools?: ToolSet): AgentClient;
17
+ static getAgentProvider(modelName: string): AgentType;
18
+ }
@@ -0,0 +1,55 @@
1
+ import { AgentAction, AgentExecutionOptions, AgentResult, AgentType, AnthropicContentBlock, AnthropicMessage, AnthropicToolResult, ToolUseItem } from "../types/agent";
2
+ import { LogLine } from "../types/log";
3
+ import { ToolSet } from "ai";
4
+ import { AgentClient } from "./AgentClient";
5
+ export type ResponseInputItem = AnthropicMessage | AnthropicToolResult;
6
+ /**
7
+ * Client for Anthropic's Computer Use API
8
+ * This implementation uses the official Anthropic Messages API for Computer Use
9
+ */
10
+ export declare class AnthropicCUAClient extends AgentClient {
11
+ private apiKey;
12
+ private baseURL?;
13
+ private client;
14
+ lastMessageId?: string;
15
+ private currentViewport;
16
+ private currentUrl?;
17
+ private screenshotProvider?;
18
+ private actionHandler?;
19
+ private thinkingBudget;
20
+ private tools?;
21
+ constructor(type: AgentType, modelName: string, userProvidedInstructions?: string, clientOptions?: Record<string, unknown>, tools?: ToolSet);
22
+ setViewport(width: number, height: number): void;
23
+ setCurrentUrl(url: string): void;
24
+ setScreenshotProvider(provider: () => Promise<string>): void;
25
+ setActionHandler(handler: (action: AgentAction) => Promise<void>): void;
26
+ /**
27
+ * Execute a task with the Anthropic CUA
28
+ * This is the main entry point for the agent
29
+ * @implements AgentClient.execute
30
+ */
31
+ execute(executionOptions: AgentExecutionOptions): Promise<AgentResult>;
32
+ executeStep(inputItems: ResponseInputItem[], logger: (message: LogLine) => void): Promise<{
33
+ actions: AgentAction[];
34
+ message: string;
35
+ completed: boolean;
36
+ nextInputItems: ResponseInputItem[];
37
+ usage: {
38
+ input_tokens: number;
39
+ output_tokens: number;
40
+ inference_time_ms: number;
41
+ };
42
+ }>;
43
+ private createInitialInputItems;
44
+ getAction(inputItems: ResponseInputItem[]): Promise<{
45
+ content: AnthropicContentBlock[];
46
+ id: string;
47
+ usage: Record<string, number>;
48
+ }>;
49
+ takeAction(toolUseItems: ToolUseItem[], logger: (message: LogLine) => void): Promise<AnthropicToolResult[]>;
50
+ private convertToolUseToAction;
51
+ captureScreenshot(options?: {
52
+ base64Image?: string;
53
+ currentUrl?: string;
54
+ }): Promise<string>;
55
+ }
@@ -0,0 +1,64 @@
1
+ import { LogLine } from "../types/log";
2
+ import { AgentAction, AgentResult, AgentType, AgentExecutionOptions, ResponseInputItem, ResponseItem } from "../types/agent";
3
+ import { AgentClient } from "./AgentClient";
4
+ import { ToolSet } from "ai/dist";
5
+ /**
6
+ * Client for OpenAI's Computer Use Assistant API
7
+ * This implementation uses the official OpenAI Responses API for Computer Use
8
+ */
9
+ export declare class OpenAICUAClient extends AgentClient {
10
+ private apiKey;
11
+ private organization?;
12
+ private baseURL;
13
+ private client;
14
+ lastResponseId?: string;
15
+ private currentViewport;
16
+ private currentUrl?;
17
+ private screenshotProvider?;
18
+ private actionHandler?;
19
+ private reasoningItems;
20
+ private environment;
21
+ private tools?;
22
+ constructor(type: AgentType, modelName: string, userProvidedInstructions?: string, clientOptions?: Record<string, unknown>, tools?: ToolSet);
23
+ setViewport(width: number, height: number): void;
24
+ setCurrentUrl(url: string): void;
25
+ setScreenshotProvider(provider: () => Promise<string>): void;
26
+ setActionHandler(handler: (action: AgentAction) => Promise<void>): void;
27
+ /**
28
+ * Execute a task with the OpenAI CUA
29
+ * This is the main entry point for the agent
30
+ * @implements AgentClient.execute
31
+ */
32
+ execute(executionOptions: AgentExecutionOptions): Promise<AgentResult>;
33
+ /**
34
+ * Execute a single step of the agent
35
+ * This coordinates the flow: Request → Get Action → Execute Action
36
+ */
37
+ executeStep(inputItems: ResponseInputItem[], previousResponseId: string | undefined, logger: (message: LogLine) => void): Promise<{
38
+ actions: AgentAction[];
39
+ message: string;
40
+ completed: boolean;
41
+ nextInputItems: ResponseInputItem[];
42
+ responseId: string;
43
+ usage: {
44
+ input_tokens: number;
45
+ output_tokens: number;
46
+ inference_time_ms: number;
47
+ };
48
+ }>;
49
+ private isComputerCallItem;
50
+ private isFunctionCallItem;
51
+ private createInitialInputItems;
52
+ getAction(inputItems: ResponseInputItem[], previousResponseId?: string): Promise<{
53
+ output: ResponseItem[];
54
+ responseId: string;
55
+ usage: Record<string, number>;
56
+ }>;
57
+ takeAction(output: ResponseItem[], logger: (message: LogLine) => void): Promise<ResponseInputItem[]>;
58
+ private convertComputerCallToAction;
59
+ private convertFunctionCallToAction;
60
+ captureScreenshot(options?: {
61
+ base64Image?: string;
62
+ currentUrl?: string;
63
+ }): Promise<string>;
64
+ }
@@ -0,0 +1,15 @@
1
+ import { LogLine } from "../types/log";
2
+ import { AgentExecuteOptions, AgentResult } from "../types/agent";
3
+ import { AgentClient } from "./AgentClient";
4
+ /**
5
+ * Main interface for agent operations in Stagehand
6
+ * This class provides methods for executing tasks with an agent
7
+ */
8
+ export declare class StagehandAgent {
9
+ private client;
10
+ private logger;
11
+ constructor(client: AgentClient, logger: (message: LogLine) => void);
12
+ execute(optionsOrInstruction: AgentExecuteOptions | string): Promise<AgentResult>;
13
+ getModelName(): string;
14
+ getAgentType(): string;
15
+ }
@@ -0,0 +1,229 @@
1
+ import type { V3 } from "@/lib/v3/v3";
2
+ import type { LogLine } from "../../types/log";
3
+ export interface V3AgentToolOptions {
4
+ executionModel?: string;
5
+ logger?: (message: LogLine) => void;
6
+ }
7
+ export declare function createAgentTools(v3: V3, options?: V3AgentToolOptions): {
8
+ act: import("ai/dist").Tool<import("zod/v3").ZodObject<{
9
+ action: import("zod/v3").ZodString;
10
+ }, "strip", import("zod/v3").ZodTypeAny, {
11
+ action?: string;
12
+ }, {
13
+ action?: string;
14
+ }>, {
15
+ success: boolean;
16
+ action: string;
17
+ error?: undefined;
18
+ } | {
19
+ success: boolean;
20
+ error: any;
21
+ action?: undefined;
22
+ }> & {
23
+ execute: (args: {
24
+ action?: string;
25
+ }, options: import("ai/dist").ToolExecutionOptions) => PromiseLike<{
26
+ success: boolean;
27
+ action: string;
28
+ error?: undefined;
29
+ } | {
30
+ success: boolean;
31
+ error: any;
32
+ action?: undefined;
33
+ }>;
34
+ };
35
+ ariaTree: import("ai/dist").Tool<import("zod/v3").ZodObject<{}, "strip", import("zod/v3").ZodTypeAny, {}, {}>, {
36
+ content: string;
37
+ pageUrl: string;
38
+ }> & {
39
+ execute: (args: {}, options: import("ai/dist").ToolExecutionOptions) => PromiseLike<{
40
+ content: string;
41
+ pageUrl: string;
42
+ }>;
43
+ };
44
+ close: import("ai/dist").Tool<import("zod/v3").ZodObject<{
45
+ reasoning: import("zod/v3").ZodString;
46
+ taskComplete: import("zod/v3").ZodBoolean;
47
+ }, "strip", import("zod/v3").ZodTypeAny, {
48
+ reasoning?: string;
49
+ taskComplete?: boolean;
50
+ }, {
51
+ reasoning?: string;
52
+ taskComplete?: boolean;
53
+ }>, {
54
+ success: boolean;
55
+ reasoning: string;
56
+ taskComplete: boolean;
57
+ }> & {
58
+ execute: (args: {
59
+ reasoning?: string;
60
+ taskComplete?: boolean;
61
+ }, options: import("ai/dist").ToolExecutionOptions) => PromiseLike<{
62
+ success: boolean;
63
+ reasoning: string;
64
+ taskComplete: boolean;
65
+ }>;
66
+ };
67
+ extract: import("ai/dist").Tool<import("zod/v3").ZodObject<{
68
+ instruction: import("zod/v3").ZodOptional<import("zod/v3").ZodString>;
69
+ schema: import("zod/v3").ZodOptional<import("zod/v3").ZodString>;
70
+ selector: import("zod/v3").ZodOptional<import("zod/v3").ZodString>;
71
+ }, "strip", import("zod/v3").ZodTypeAny, {
72
+ instruction?: string;
73
+ selector?: string;
74
+ schema?: string;
75
+ }, {
76
+ instruction?: string;
77
+ selector?: string;
78
+ schema?: string;
79
+ }>, {
80
+ success: boolean;
81
+ result: any;
82
+ error?: undefined;
83
+ } | {
84
+ success: boolean;
85
+ error: any;
86
+ result?: undefined;
87
+ }> & {
88
+ execute: (args: {
89
+ instruction?: string;
90
+ selector?: string;
91
+ schema?: string;
92
+ }, options: import("ai/dist").ToolExecutionOptions) => PromiseLike<{
93
+ success: boolean;
94
+ result: any;
95
+ error?: undefined;
96
+ } | {
97
+ success: boolean;
98
+ error: any;
99
+ result?: undefined;
100
+ }>;
101
+ };
102
+ fillForm: import("ai/dist").Tool<import("zod/v3").ZodObject<{
103
+ fields: import("zod/v3").ZodArray<import("zod/v3").ZodObject<{
104
+ action: import("zod/v3").ZodString;
105
+ value: import("zod/v3").ZodString;
106
+ }, "strip", import("zod/v3").ZodTypeAny, {
107
+ value?: string;
108
+ action?: string;
109
+ }, {
110
+ value?: string;
111
+ action?: string;
112
+ }>, "many">;
113
+ }, "strip", import("zod/v3").ZodTypeAny, {
114
+ fields?: {
115
+ value?: string;
116
+ action?: string;
117
+ }[];
118
+ }, {
119
+ fields?: {
120
+ value?: string;
121
+ action?: string;
122
+ }[];
123
+ }>, {
124
+ success: boolean;
125
+ actions: unknown[];
126
+ }> & {
127
+ execute: (args: {
128
+ fields?: {
129
+ value?: string;
130
+ action?: string;
131
+ }[];
132
+ }, options: import("ai/dist").ToolExecutionOptions) => PromiseLike<{
133
+ success: boolean;
134
+ actions: unknown[];
135
+ }>;
136
+ };
137
+ goto: import("ai/dist").Tool<import("zod/v3").ZodObject<{
138
+ url: import("zod/v3").ZodString;
139
+ }, "strip", import("zod/v3").ZodTypeAny, {
140
+ url?: string;
141
+ }, {
142
+ url?: string;
143
+ }>, {
144
+ success: boolean;
145
+ url: string;
146
+ error?: undefined;
147
+ } | {
148
+ success: boolean;
149
+ error: any;
150
+ url?: undefined;
151
+ }> & {
152
+ execute: (args: {
153
+ url?: string;
154
+ }, options: import("ai/dist").ToolExecutionOptions) => PromiseLike<{
155
+ success: boolean;
156
+ url: string;
157
+ error?: undefined;
158
+ } | {
159
+ success: boolean;
160
+ error: any;
161
+ url?: undefined;
162
+ }>;
163
+ };
164
+ navback: import("ai/dist").Tool<import("zod/v3").ZodObject<{
165
+ reasoning: import("zod/v3").ZodString;
166
+ }, "strip", import("zod/v3").ZodTypeAny, {
167
+ reasoning?: string;
168
+ }, {
169
+ reasoning?: string;
170
+ }>, {
171
+ success: boolean;
172
+ }> & {
173
+ execute: (args: {
174
+ reasoning?: string;
175
+ }, options: import("ai/dist").ToolExecutionOptions) => PromiseLike<{
176
+ success: boolean;
177
+ }>;
178
+ };
179
+ screenshot: import("ai/dist").Tool<import("zod/v3").ZodObject<{}, "strip", import("zod/v3").ZodTypeAny, {}, {}>, {
180
+ base64: string;
181
+ timestamp: number;
182
+ pageUrl: string;
183
+ }> & {
184
+ execute: (args: {}, options: import("ai/dist").ToolExecutionOptions) => PromiseLike<{
185
+ base64: string;
186
+ timestamp: number;
187
+ pageUrl: string;
188
+ }>;
189
+ };
190
+ scroll: import("ai/dist").Tool<import("zod/v3").ZodObject<{
191
+ pixels: import("zod/v3").ZodNumber;
192
+ direction: import("zod/v3").ZodEnum<["up", "down"]>;
193
+ }, "strip", import("zod/v3").ZodTypeAny, {
194
+ pixels?: number;
195
+ direction?: "up" | "down";
196
+ }, {
197
+ pixels?: number;
198
+ direction?: "up" | "down";
199
+ }>, {
200
+ success: boolean;
201
+ pixels: number;
202
+ }> & {
203
+ execute: (args: {
204
+ pixels?: number;
205
+ direction?: "up" | "down";
206
+ }, options: import("ai/dist").ToolExecutionOptions) => PromiseLike<{
207
+ success: boolean;
208
+ pixels: number;
209
+ }>;
210
+ };
211
+ wait: import("ai/dist").Tool<import("zod/v3").ZodObject<{
212
+ timeMs: import("zod/v3").ZodNumber;
213
+ }, "strip", import("zod/v3").ZodTypeAny, {
214
+ timeMs?: number;
215
+ }, {
216
+ timeMs?: number;
217
+ }>, {
218
+ success: boolean;
219
+ waited: number;
220
+ }> & {
221
+ execute: (args: {
222
+ timeMs?: number;
223
+ }, options: import("ai/dist").ToolExecutionOptions) => PromiseLike<{
224
+ success: boolean;
225
+ waited: number;
226
+ }>;
227
+ };
228
+ };
229
+ export type AgentTools = ReturnType<typeof createAgentTools>;