@browserbasehq/orca 3.0.9-alpha-2 → 3.0.9-alpha-4

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 (3) hide show
  1. package/dist/index.d.ts +13 -14
  2. package/dist/index.js +327 -170
  3. package/package.json +4 -5
package/dist/index.d.ts CHANGED
@@ -2123,6 +2123,9 @@ declare class StagehandEvalError extends StagehandError {
2123
2123
  declare class StagehandDomProcessError extends StagehandError {
2124
2124
  constructor(message: string);
2125
2125
  }
2126
+ declare class StagehandLocatorError extends StagehandError {
2127
+ constructor(action: string, selector: string, message: string);
2128
+ }
2126
2129
  declare class StagehandClickError extends StagehandError {
2127
2130
  constructor(message: string, selector: string);
2128
2131
  }
@@ -2339,7 +2342,7 @@ declare class V3Context {
2339
2342
  private constructor();
2340
2343
  private readonly _piercerInstalled;
2341
2344
  private _lastPopupSignalAt;
2342
- private sessionKey;
2345
+ private readonly _targetSessionListeners;
2343
2346
  private readonly _sessionInit;
2344
2347
  private pagesByTarget;
2345
2348
  private mainFrameToTarget;
@@ -2351,6 +2354,7 @@ declare class V3Context {
2351
2354
  private _pageOrder;
2352
2355
  private pendingCreatedTargetUrl;
2353
2356
  private readonly initScripts;
2357
+ private installTargetSessionListeners;
2354
2358
  /**
2355
2359
  * Create a Context for a given CDP websocket URL and bootstrap target wiring.
2356
2360
  */
@@ -2401,7 +2405,6 @@ declare class V3Context {
2401
2405
  /**
2402
2406
  * Bootstrap target lifecycle:
2403
2407
  * - Attach to existing targets.
2404
- * - Attach on `Target.targetCreated` (fallback for OOPIFs).
2405
2408
  * - Handle auto-attach events.
2406
2409
  * - Clean up on detach/destroy.
2407
2410
  */
@@ -2722,6 +2725,7 @@ declare class Page {
2722
2725
  private installInitScriptOnSession;
2723
2726
  private applyInitScriptsToSession;
2724
2727
  registerInitScript(source: string): Promise<void>;
2728
+ seedInitScript(source: string): void;
2725
2729
  private cursorEnabled;
2726
2730
  private ensureCursorScript;
2727
2731
  enableCursorOverlay(): Promise<void>;
@@ -3348,7 +3352,7 @@ interface AgentStreamExecuteOptions extends AgentExecuteOptionsBase {
3348
3352
  callbacks?: AgentStreamCallbacks;
3349
3353
  }
3350
3354
  type AgentType = "openai" | "anthropic" | "google" | "microsoft";
3351
- declare const AVAILABLE_CUA_MODELS: readonly ["openai/computer-use-preview", "openai/computer-use-preview-2025-03-11", "anthropic/claude-3-7-sonnet-latest", "anthropic/claude-opus-4-5-20251101", "anthropic/claude-haiku-4-5-20251001", "anthropic/claude-sonnet-4-20250514", "anthropic/claude-sonnet-4-5-20250929", "google/gemini-2.5-computer-use-preview-10-2025", "microsoft/fara-7b"];
3355
+ declare const AVAILABLE_CUA_MODELS: readonly ["openai/computer-use-preview", "openai/computer-use-preview-2025-03-11", "anthropic/claude-3-7-sonnet-latest", "anthropic/claude-opus-4-5-20251101", "anthropic/claude-opus-4-6", "anthropic/claude-haiku-4-5-20251001", "anthropic/claude-sonnet-4-20250514", "anthropic/claude-sonnet-4-5-20250929", "google/gemini-2.5-computer-use-preview-10-2025", "google/gemini-3-flash-preview", "google/gemini-3-pro-preview", "microsoft/fara-7b"];
3352
3356
  type AvailableCuaModel = (typeof AVAILABLE_CUA_MODELS)[number];
3353
3357
  interface AgentExecutionOptions<TOptions extends AgentExecuteOptions = AgentExecuteOptions> {
3354
3358
  options: TOptions;
@@ -3601,10 +3605,12 @@ interface FillFormVisionToolResult {
3601
3605
  error?: string;
3602
3606
  screenshotBase64?: string;
3603
3607
  }
3604
- interface ScrollVisionToolResult {
3608
+ interface ScrollToolResult {
3605
3609
  success: boolean;
3606
3610
  message: string;
3607
3611
  scrolledPixels: number;
3612
+ }
3613
+ interface ScrollVisionToolResult extends ScrollToolResult {
3608
3614
  screenshotBase64?: string;
3609
3615
  }
3610
3616
  interface WaitToolResult {
@@ -4021,13 +4027,10 @@ declare const actTool: (v3: V3, executionModel?: string) => ai.Tool<{
4021
4027
  }, {
4022
4028
  success: boolean;
4023
4029
  action: string;
4024
- playwrightArguments: Action;
4025
- error?: undefined;
4030
+ playwrightArguments?: Action;
4026
4031
  } | {
4027
4032
  success: boolean;
4028
4033
  error: any;
4029
- action?: undefined;
4030
- playwrightArguments?: undefined;
4031
4034
  }>;
4032
4035
 
4033
4036
  declare const screenshotTool: (v3: V3) => ai.Tool<Record<string, never>, {
@@ -4069,11 +4072,7 @@ declare const fillFormTool: (v3: V3, executionModel?: string) => ai.Tool<{
4069
4072
  declare const scrollTool: (v3: V3) => ai.Tool<{
4070
4073
  direction: "up" | "down";
4071
4074
  percentage?: number;
4072
- }, {
4073
- success: boolean;
4074
- message: string;
4075
- scrolledPixels: number;
4076
- }>;
4075
+ }, ScrollToolResult>;
4077
4076
  /**
4078
4077
  * Scroll tool for hybrid mode (grounding models).
4079
4078
  * Supports optional coordinates for scrolling within nested scrollable elements.
@@ -4361,4 +4360,4 @@ interface ServerAgentCacheHandle {
4361
4360
  }
4362
4361
  declare function __internalCreateInMemoryAgentCacheHandle(stagehand: V3): ServerAgentCacheHandle;
4363
4362
 
4364
- export { type AISDKCustomProvider, type AISDKProvider, AISdkClient, AVAILABLE_CUA_MODELS, type ActOptions, type ActResult, ActTimeoutError, type Action, type ActionExecutionResult, AgentAbortError, type AgentAction, type AgentCallbacks, type AgentConfig, type AgentContext, type AgentExecuteCallbacks, type AgentExecuteOptions, type AgentExecuteOptionsBase, type AgentExecutionOptions, type AgentHandlerOptions, type AgentInstance, type AgentModelConfig, AgentProvider, type AgentProviderType, type AgentResult, AgentScreenshotProviderError, type AgentState, type AgentStreamCallbacks, type AgentStreamExecuteOptions, type AgentStreamResult, type AgentToolCall, type AgentToolMode, type AgentToolResult, type AgentToolTypesMap, type AgentTools, type AgentType, type AgentUITools, AnnotatedScreenshotText, type AnthropicClientOptions, type AnthropicContentBlock, type AnthropicJsonSchemaObject, type AnthropicMessage, type AnthropicTextBlock, type AnthropicToolResult, type AnyPage, api as Api, type AvailableCuaModel, type AvailableModel, BrowserbaseSessionNotFoundError, CaptchaTimeoutError, type ChatCompletionOptions, type ChatMessage, type ChatMessageContent, type ChatMessageImageContent, type ChatMessageTextContent, type ClickToolResult, type ClientOptions, type ComputerCallItem, ConnectionTimeoutError, type ConsoleListener, ConsoleMessage, ContentFrameNotFoundError, type CreateChatCompletionOptions, CreateChatCompletionResponseError, CuaModelRequiredError, CustomOpenAIClient, type DragAndDropToolResult, ElementNotVisibleError, ExperimentalApiConflictError, ExperimentalNotConfiguredError, type ExtractOptions, type ExtractResult, ExtractTimeoutError, type FillFormField, type FillFormVisionToolResult, type FunctionCallItem, type GoogleServiceAccountCredentials, type GoogleVertexProviderSettings, HandlerNotInitializedError, type HistoryEntry, type InferStagehandSchema, InvalidAISDKModelFormatError, type JsonSchema, type JsonSchemaDocument, type JsonSchemaProperty, LLMClient, type LLMParsedResponse, type LLMResponse, LLMResponseError, type LLMTool, type LLMUsage, LOG_LEVEL_NAMES, type LoadState, type LocalBrowserLaunchOptions, type LogLevel, type LogLine, type Logger, MCPConnectionError, MissingEnvironmentVariableError, MissingLLMConfigurationError, type ModelConfiguration, type ModelOutputContentItem, type ModelProvider, type NonStreamingAgentInstance, type ObserveOptions, ObserveTimeoutError, type OpenAIClientOptions, Page, PageNotFoundError, type PageSnapshotOptions, Response$1 as Response, ResponseBodyError, type ResponseInputItem, type ResponseItem, ResponseParseError, type SafetyCheck, type SafetyConfirmationHandler, type SafetyConfirmationResponse, type ScrollVisionToolResult, type ServerAgentCacheHandle, type SnapshotResult, V3 as Stagehand, StagehandAPIError, StagehandAPIUnauthorizedError, StagehandClickError, StagehandClosedError, StagehandDefaultError, StagehandDomProcessError, StagehandElementNotFoundError, StagehandEnvironmentError, StagehandError, StagehandEvalError, StagehandHttpError, StagehandIframeError, StagehandInitError, StagehandInvalidArgumentError, type StagehandMetrics, StagehandMissingArgumentError, StagehandNotInitializedError, StagehandResponseBodyError, StagehandResponseParseError, StagehandServerError, StagehandShadowRootMissingError, StagehandShadowSegmentEmptyError, StagehandShadowSegmentNotFoundError, StagehandSnapshotError, type StagehandZodObject, type StagehandZodSchema, type StreamingAgentInstance, StreamingCallbacksInNonStreamingModeError, TimeoutError, type ToolUseItem, type TypeToolResult, UnsupportedAISDKModelProviderError, UnsupportedModelError, UnsupportedModelProviderError, V3, type V3Env, V3Evaluator, V3FunctionName, type V3Options, type WaitToolResult, XPathResolutionError, ZodSchemaValidationError, __internalCreateInMemoryAgentCacheHandle, connectToMCPServer, defaultExtractSchema, getZodType, injectUrls, isRunningInBun, isZod3Schema, isZod4Schema, jsonSchemaToZod, loadApiKeyFromEnv, localBrowserLaunchOptionsSchema, modelToAgentProviderMap, pageTextSchema, providerEnvVarMap, toGeminiSchema, toJsonSchema, transformSchema, trimTrailingTextNode, validateZodSchema };
4363
+ export { type AISDKCustomProvider, type AISDKProvider, AISdkClient, AVAILABLE_CUA_MODELS, type ActOptions, type ActResult, ActTimeoutError, type Action, type ActionExecutionResult, AgentAbortError, type AgentAction, type AgentCallbacks, type AgentConfig, type AgentContext, type AgentExecuteCallbacks, type AgentExecuteOptions, type AgentExecuteOptionsBase, type AgentExecutionOptions, type AgentHandlerOptions, type AgentInstance, type AgentModelConfig, AgentProvider, type AgentProviderType, type AgentResult, AgentScreenshotProviderError, type AgentState, type AgentStreamCallbacks, type AgentStreamExecuteOptions, type AgentStreamResult, type AgentToolCall, type AgentToolMode, type AgentToolResult, type AgentToolTypesMap, type AgentTools, type AgentType, type AgentUITools, AnnotatedScreenshotText, type AnthropicClientOptions, type AnthropicContentBlock, type AnthropicJsonSchemaObject, type AnthropicMessage, type AnthropicTextBlock, type AnthropicToolResult, type AnyPage, api as Api, type AvailableCuaModel, type AvailableModel, BrowserbaseSessionNotFoundError, CaptchaTimeoutError, type ChatCompletionOptions, type ChatMessage, type ChatMessageContent, type ChatMessageImageContent, type ChatMessageTextContent, type ClickToolResult, type ClientOptions, type ComputerCallItem, ConnectionTimeoutError, type ConsoleListener, ConsoleMessage, ContentFrameNotFoundError, type CreateChatCompletionOptions, CreateChatCompletionResponseError, CuaModelRequiredError, CustomOpenAIClient, type DragAndDropToolResult, ElementNotVisibleError, ExperimentalApiConflictError, ExperimentalNotConfiguredError, type ExtractOptions, type ExtractResult, ExtractTimeoutError, type FillFormField, type FillFormVisionToolResult, type FunctionCallItem, type GoogleServiceAccountCredentials, type GoogleVertexProviderSettings, HandlerNotInitializedError, type HistoryEntry, type InferStagehandSchema, InvalidAISDKModelFormatError, type JsonSchema, type JsonSchemaDocument, type JsonSchemaProperty, LLMClient, type LLMParsedResponse, type LLMResponse, LLMResponseError, type LLMTool, type LLMUsage, LOG_LEVEL_NAMES, type LoadState, type LocalBrowserLaunchOptions, type LogLevel, type LogLine, type Logger, MCPConnectionError, MissingEnvironmentVariableError, MissingLLMConfigurationError, type ModelConfiguration, type ModelOutputContentItem, type ModelProvider, type NonStreamingAgentInstance, type ObserveOptions, ObserveTimeoutError, type OpenAIClientOptions, Page, PageNotFoundError, type PageSnapshotOptions, Response$1 as Response, ResponseBodyError, type ResponseInputItem, type ResponseItem, ResponseParseError, type SafetyCheck, type SafetyConfirmationHandler, type SafetyConfirmationResponse, type ScrollToolResult, type ScrollVisionToolResult, type ServerAgentCacheHandle, type SnapshotResult, V3 as Stagehand, StagehandAPIError, StagehandAPIUnauthorizedError, StagehandClickError, StagehandClosedError, StagehandDefaultError, StagehandDomProcessError, StagehandElementNotFoundError, StagehandEnvironmentError, StagehandError, StagehandEvalError, StagehandHttpError, StagehandIframeError, StagehandInitError, StagehandInvalidArgumentError, StagehandLocatorError, type StagehandMetrics, StagehandMissingArgumentError, StagehandNotInitializedError, StagehandResponseBodyError, StagehandResponseParseError, StagehandServerError, StagehandShadowRootMissingError, StagehandShadowSegmentEmptyError, StagehandShadowSegmentNotFoundError, StagehandSnapshotError, type StagehandZodObject, type StagehandZodSchema, type StreamingAgentInstance, StreamingCallbacksInNonStreamingModeError, TimeoutError, type ToolUseItem, type TypeToolResult, UnsupportedAISDKModelProviderError, UnsupportedModelError, UnsupportedModelProviderError, V3, type V3Env, V3Evaluator, V3FunctionName, type V3Options, type WaitToolResult, XPathResolutionError, ZodSchemaValidationError, __internalCreateInMemoryAgentCacheHandle, connectToMCPServer, defaultExtractSchema, getZodType, injectUrls, isRunningInBun, isZod3Schema, isZod4Schema, jsonSchemaToZod, loadApiKeyFromEnv, localBrowserLaunchOptionsSchema, modelToAgentProviderMap, pageTextSchema, providerEnvVarMap, toGeminiSchema, toJsonSchema, transformSchema, trimTrailingTextNode, validateZodSchema };
package/dist/index.js CHANGED
@@ -200,12 +200,12 @@ var init_zodCompat = __esm({
200
200
  var STAGEHAND_VERSION;
201
201
  var init_version = __esm({
202
202
  "lib/version.ts"() {
203
- STAGEHAND_VERSION = "3.0.9-alpha-2";
203
+ STAGEHAND_VERSION = "3.0.9-alpha-4";
204
204
  }
205
205
  });
206
206
 
207
207
  // lib/v3/types/public/sdkErrors.ts
208
- var StagehandError, StagehandDefaultError, StagehandEnvironmentError, MissingEnvironmentVariableError, UnsupportedModelError, UnsupportedModelProviderError, UnsupportedAISDKModelProviderError, InvalidAISDKModelFormatError, StagehandNotInitializedError, BrowserbaseSessionNotFoundError, CaptchaTimeoutError, MissingLLMConfigurationError, HandlerNotInitializedError, StagehandInvalidArgumentError, StagehandElementNotFoundError, AgentScreenshotProviderError, StagehandMissingArgumentError, CreateChatCompletionResponseError, StagehandEvalError, StagehandDomProcessError, StagehandClickError, LLMResponseError, StagehandIframeError, ContentFrameNotFoundError, XPathResolutionError, ExperimentalApiConflictError, ExperimentalNotConfiguredError, CuaModelRequiredError, ZodSchemaValidationError, StagehandInitError, MCPConnectionError, StagehandShadowRootMissingError, StagehandShadowSegmentEmptyError, StagehandShadowSegmentNotFoundError, ElementNotVisibleError, ResponseBodyError, ResponseParseError, TimeoutError, ActTimeoutError, ExtractTimeoutError, ObserveTimeoutError, PageNotFoundError, ConnectionTimeoutError, StreamingCallbacksInNonStreamingModeError, AgentAbortError, StagehandClosedError, StagehandSnapshotError;
208
+ var StagehandError, StagehandDefaultError, StagehandEnvironmentError, MissingEnvironmentVariableError, UnsupportedModelError, UnsupportedModelProviderError, UnsupportedAISDKModelProviderError, InvalidAISDKModelFormatError, StagehandNotInitializedError, BrowserbaseSessionNotFoundError, CaptchaTimeoutError, MissingLLMConfigurationError, HandlerNotInitializedError, StagehandInvalidArgumentError, StagehandElementNotFoundError, AgentScreenshotProviderError, StagehandMissingArgumentError, CreateChatCompletionResponseError, StagehandEvalError, StagehandDomProcessError, StagehandLocatorError, StagehandClickError, LLMResponseError, StagehandIframeError, ContentFrameNotFoundError, XPathResolutionError, ExperimentalApiConflictError, ExperimentalNotConfiguredError, CuaModelRequiredError, ZodSchemaValidationError, StagehandInitError, MCPConnectionError, StagehandShadowRootMissingError, StagehandShadowSegmentEmptyError, StagehandShadowSegmentNotFoundError, ElementNotVisibleError, ResponseBodyError, ResponseParseError, TimeoutError, ActTimeoutError, ExtractTimeoutError, ObserveTimeoutError, PageNotFoundError, ConnectionTimeoutError, StreamingCallbacksInNonStreamingModeError, AgentAbortError, StagehandClosedError, StagehandSnapshotError;
209
209
  var init_sdkErrors = __esm({
210
210
  "lib/v3/types/public/sdkErrors.ts"() {
211
211
  init_version();
@@ -343,6 +343,13 @@ For a complete list of supported models and providers, see: https://docs.stageha
343
343
  super(`Error Processing Dom: ${message}`);
344
344
  }
345
345
  };
346
+ StagehandLocatorError = class extends StagehandError {
347
+ constructor(action, selector, message) {
348
+ super(
349
+ `Error ${action} Element with selector: ${selector} Reason: ${message}`
350
+ );
351
+ }
352
+ };
346
353
  StagehandClickError = class extends StagehandError {
347
354
  constructor(message, selector) {
348
355
  super(
@@ -1345,31 +1352,31 @@ var init_executionContextRegistry = __esm({
1345
1352
  var locatorScriptBootstrap, locatorScriptSources, locatorScriptGlobalRefs;
1346
1353
  var init_locatorScripts_generated = __esm({
1347
1354
  "lib/v3/dom/build/locatorScripts.generated.ts"() {
1348
- locatorScriptBootstrap = 'if (!globalThis.__stagehandLocatorScripts) { var __stagehandLocatorScriptsFactory=(()=>{var N=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var W=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var r in e)N(t,r,{get:e[r],enumerable:!0})},I=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of F(e))!W.call(t,o)&&o!==r&&N(t,o,{get:()=>e[o],enumerable:!(n=_(e,o))||n.enumerable});return t};var O=t=>I(N({},"__esModule",{value:!0}),t);var ge={};P(ge,{assignFilePayloadsToInputElement:()=>V,countCssMatchesPierce:()=>se,countCssMatchesPrimary:()=>re,countTextMatches:()=>le,countXPathMatchesMainWorld:()=>ce,dispatchDomClick:()=>X,ensureFileInputElement:()=>q,fillElementValue:()=>Y,focusElement:()=>z,isElementChecked:()=>Q,isElementVisible:()=>K,prepareElementForTyping:()=>x,readElementInnerHTML:()=>G,readElementInnerText:()=>J,readElementInputValue:()=>j,readElementTextContent:()=>Z,resolveCssSelector:()=>ee,resolveCssSelectorPierce:()=>te,resolveTextSelector:()=>ne,resolveXPathMainWorld:()=>oe,scrollElementToPercent:()=>$,selectElementOptions:()=>U,waitForSelector:()=>pe});function q(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}function V(t){try{let e=this;if(!e||e.tagName?.toLowerCase()!=="input"||(e.type??"").toLowerCase()!=="file")return!1;let r=(()=>{try{return new DataTransfer}catch{return null}})();if(!r)return!1;let n=Array.isArray(t)?t:[];for(let o of n){if(!o)continue;let h=o.name||"upload.bin",l=o.mimeType||"application/octet-stream",i=typeof o.lastModified=="number"?o.lastModified:Date.now(),c=window.atob(o.base64??""),a=new Uint8Array(c.length);for(let s=0;s<c.length;s+=1)a[s]=c.charCodeAt(s);let f=new Blob([a],{type:l}),d=new File([f],h,{type:l,lastModified:i});r.items.add(d)}return e.files=r.files,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{return!1}}function X(t){let e=t??{};try{let r=new MouseEvent("click",{bubbles:!!e.bubbles,cancelable:!!e.cancelable,composed:!!e.composed,detail:typeof e.detail=="number"?e.detail:1,view:this?.ownerDocument?.defaultView??window});this.dispatchEvent(r)}catch{try{this.click()}catch{}}}function $(t){let e=r=>{if(typeof r=="number"&&Number.isFinite(r))return r;let n=String(r??"").trim();if(!n)return 0;let o=parseFloat(n.replace("%",""));return Number.isNaN(o)||!Number.isFinite(o)?0:o};try{let r=Math.max(0,Math.min(e(t),100)),n=this,o=n.tagName?.toLowerCase()??"";if(o==="html"||o==="body"){let d=(n.ownerDocument?.scrollingElement||n.ownerDocument?.documentElement||n.ownerDocument?.body||document.scrollingElement||document.documentElement||document.body)?.scrollHeight??document.body.scrollHeight??0,s=n.ownerDocument?.defaultView?.innerHeight??window.innerHeight,E=Math.max(0,d-s)*(r/100);return n.ownerDocument?.defaultView?.scrollTo({top:E,left:n.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let l=n.scrollHeight??0,i=n.clientHeight??0,a=Math.max(0,l-i)*(r/100);return n.scrollTo({top:a,left:n.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}var M=new Set(["color","date","datetime-local","month","range","time","week"]),B=new Set(["","email","number","password","search","tel","text","url"]);function x(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument||document,r=e.defaultView||window;try{typeof t.focus=="function"&&t.focus()}catch{}if(t instanceof r.HTMLInputElement||t instanceof r.HTMLTextAreaElement){try{if(typeof t.select=="function")return t.select(),!0}catch{}try{let n=(t.value??"").length;if(typeof t.setSelectionRange=="function")return t.setSelectionRange(0,n),!0}catch{}return!0}if(t.isContentEditable){let n=e.getSelection?.(),o=e.createRange?.();if(n&&o)try{o.selectNodeContents(t),n.removeAllRanges(),n.addRange(o)}catch{}return!0}return!1}catch{return!1}}function Y(t){let e=this;if(!e.isConnected)return{status:"error",reason:"notconnected"};let n=(e.ownerDocument||document).defaultView||window,o=t??"";try{let h=l=>{let i;if(typeof n.InputEvent=="function")try{i=new n.InputEvent("input",{bubbles:!0,composed:!0,data:l,inputType:"insertText"})}catch{i=new n.Event("input",{bubbles:!0,composed:!0})}else i=new n.Event("input",{bubbles:!0,composed:!0});e.dispatchEvent(i);let c=new n.Event("change",{bubbles:!0});e.dispatchEvent(c)};if(e instanceof n.HTMLInputElement){let l=(e.type||"").toLowerCase();if(!B.has(l)&&!M.has(l))return{status:"error",reason:`unsupported-input-type:${l}`};let i=t;if(l==="number"){let c=t.trim();if(c!==""&&Number.isNaN(Number(c)))return{status:"error",reason:"invalid-number-value"};i=c}if(o=i,M.has(l)){let c=t.trim();o=c,x.call(e);let a=n.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(a,"value")?.set;return typeof d=="function"?d.call(e,c):e.value=c,e._valueTracker?.setValue?.(c),e.value!==c?{status:"error",reason:"malformed-value"}:(h(c),{status:"done"})}return x.call(e),{status:"needsinput",value:i}}return e instanceof n.HTMLTextAreaElement?(x.call(e),o=t,{status:"needsinput",value:t}):e instanceof n.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:e.isContentEditable?(x.call(e),o=t,{status:"needsinput",value:t}):{status:"error",reason:"unsupported-element"}}catch(h){let l="exception";if(h&&typeof h=="object"){let i=h.message;typeof i=="string"&&i.trim().length>0&&(l=`exception:${i}`)}return{status:"needsinput",value:o,reason:l}}}function z(){try{typeof this.focus=="function"&&this.focus()}catch{}}function U(t){try{if(!(this instanceof HTMLSelectElement))return[];let e=Array.isArray(t)?t:[t],r=new Set(e.map(l=>String(l??"").trim())),n=l=>{let i=(l.label||l.textContent||"").trim(),c=String(l.value??"").trim();return r.has(i)||r.has(c)};if(this.multiple)for(let l of Array.from(this.options))l.selected=n(l);else{let l=!1;for(let i of Array.from(this.options))!l&&n(i)?(i.selected=!0,this.value=i.value,l=!0):i.selected=!1}let o=new Event("input",{bubbles:!0}),h=new Event("change",{bubbles:!0});return this.dispatchEvent(o),this.dispatchEvent(h),Array.from(this.selectedOptions).map(l=>l.value)}catch{return[]}}function K(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument?.defaultView?.getComputedStyle(t)??window.getComputedStyle(t);if(!e||e.display==="none"||e.visibility==="hidden")return!1;let r=parseFloat(e.opacity??"1");if(!Number.isFinite(r)||r===0)return!1;let n=t.getBoundingClientRect();return!(!n||Math.max(n.width,n.height)===0||t.getClientRects().length===0)}catch{return!1}}function Q(){try{let t=this;if((t.tagName||"").toLowerCase()==="input"){let n=t.type?.toLowerCase()??"";if(n==="checkbox"||n==="radio")return!!t.checked}let r=t.getAttribute?.("aria-checked");return r!=null?r==="true":!1}catch{return!1}}function j(){try{let t=this,e=(t.tagName||"").toLowerCase();return e==="input"||e==="textarea"||e==="select"?String(t.value??""):t.isContentEditable?String(t.textContent??""):""}catch{return""}}function Z(){try{return String(this.textContent??"")}catch{return""}}function G(){try{return String(this.innerHTML??"")}catch{return""}}function J(){try{let t=this,e=t.innerText;if(typeof e=="string"&&e.length>0)return e;let r=t.textContent;return typeof r=="string"?r:""}catch{return""}}var v=t=>{let e=Number(t??0);return!Number.isFinite(e)||e<0?0:Math.floor(e)},L=(t,e)=>{if(!t)return[];let r=new WeakSet,n=new Set,o=[],h=[document],l=i=>{if(!(!i||r.has(i)||o.length>=e)){r.add(i);try{let c=i.querySelectorAll(t);for(let a of c)if(!n.has(a)&&(n.add(a),o.push(a),o.length>=e))return}catch{}try{let a=(i instanceof Document?i:i.host?.ownerDocument??document).createTreeWalker(i,NodeFilter.SHOW_ELEMENT),f;for(;f=a.nextNode();){if(!(f instanceof Element))continue;let d=f.shadowRoot;d&&h.push(d)}}catch{}}};for(;h.length&&o.length<e;){let i=h.shift();i&&l(i)}return o};function ee(t,e){let r=String(t??"").trim();if(!r)return null;let n=v(e);return L(r,n+1)[n]??null}function te(t,e){let r=String(t??"").trim();if(!r)return null;let n=v(e),o=window.__stagehandV3__;if(!o||typeof o.getClosedRoot!="function")return L(r,n+1)[n]??null;let h=d=>{try{return o.getClosedRoot(d)??null}catch{return null}},l=new WeakSet,i=new Set,c=[],a=[document],f=d=>{if(!(!d||l.has(d)||c.length>=n+1)){l.add(d);try{let s=d.querySelectorAll(r);for(let m of s)if(!i.has(m)&&(i.add(m),c.push(m),c.length>=n+1))return}catch{}try{let m=(d instanceof Document?d:d.host?.ownerDocument??document).createTreeWalker(d,NodeFilter.SHOW_ELEMENT),E;for(;E=m.nextNode();){if(!(E instanceof Element))continue;let w=E.shadowRoot;w&&a.push(w);let y=h(E);y&&a.push(y)}}catch{}}};for(;a.length&&c.length<n+1;){let d=a.shift();d&&f(d)}return c[n]??null}function ne(t,e){let r=String(t??"");if(!r)return null;let n=r.toLowerCase(),o=v(e),h=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),l=u=>{if(!u)return!1;let g=u.tagName?.toUpperCase()??"";return h.has(g)},i=u=>{try{if(l(u))return"";let g=u.innerText;if(typeof g=="string"&&g.trim())return g.trim()}catch{}try{let g=u.textContent;if(typeof g=="string")return g.trim()}catch{}return""},c=u=>{let g=i(u);return!!g&&g.toLowerCase().includes(n)},a=window.__stagehandV3__,f=a&&typeof a.getClosedRoot=="function"?u=>{try{return a.getClosedRoot(u)??null}catch{return null}}:u=>null,d=new WeakSet,s=[],m=[],E=u=>{!u||d.has(u)||(d.add(u),s.push(u))},w=u=>{try{return(u instanceof Document?u:u?.ownerDocument??document).createTreeWalker(u,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(E(document);s.length;){let u=s.shift();if(!u)continue;u instanceof Element&&c(u)&&m.push({element:u,tag:u.tagName??"",id:u.id??"",className:u.className??"",text:i(u)});let g=w(u);if(!g)continue;let b;for(;b=g.nextNode();){if(!(b instanceof Element))continue;c(b)&&m.push({element:b,tag:b.tagName??"",id:b.id??"",className:b.className??"",text:i(b)});let S=b.shadowRoot;S&&E(S);let T=f(b);T&&E(T)}}let y=[];for(let u of m){let g=u.element,b=!1;for(let S of m)if(u!==S)try{if(g.contains(S.element)){b=!0;break}}catch{}b||y.push(u)}return y[o]?.element??null}function oe(t,e){let r=String(t??"").trim();if(!r)return null;let n=v(e),o=window.__stagehandV3__;if(n===0){try{if(o&&typeof o.resolveSimpleXPath=="function"){let s=o.resolveSimpleXPath(r);if(s)return s}}catch{}try{return document.evaluate(r,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{}}let l=(s=>{let m=String(s||"").trim();if(!m)return[];let E=m.replace(/^xpath=/i,""),w=[],y=0;for(;y<E.length;){let p="child";E.startsWith("//",y)?(p="desc",y+=2):E[y]==="/"&&(p="child",y+=1);let u=y;for(;y<E.length&&E[y]!=="/";)y+=1;let g=E.slice(u,y).trim();if(!g)continue;let b=g.match(/^(.*?)(\\[(\\d+)\\])?$/u),S=(b?.[1]??g).trim(),T=b?.[3]?Math.max(1,Number(b[3])):null,H=S===""?"*":S.toLowerCase();w.push({axis:p,tag:H,index:T})}return w})(r);if(!l.length)return null;let i=o&&typeof o.getClosedRoot=="function"?s=>{try{return o.getClosedRoot(s)??null}catch{return null}}:s=>null,c=s=>{let m=[];if(!s)return m;if(s instanceof Document)return s.documentElement&&m.push(s.documentElement),m;if(s instanceof ShadowRoot||s instanceof DocumentFragment)return m.push(...Array.from(s.children??[])),m;if(s instanceof Element){m.push(...Array.from(s.children??[]));let E=s.shadowRoot;E&&m.push(...Array.from(E.children??[]));let w=i(s);return w&&m.push(...Array.from(w.children??[])),m}return m},a=s=>{let m=[],E=new Set,w=[...c(s)];for(;w.length;){let y=w.shift();!y||E.has(y)||(E.add(y),m.push(y),w.push(...c(y)))}return m},f=[document];for(let s of l){let m=[],E=new Set;for(let w of f){if(!w)continue;let y=s.axis==="child"?c(w):a(w);if(!y.length)continue;let p=y.filter(u=>u instanceof Element?s.tag==="*"?!0:u.localName===s.tag:!1);if(s.index!=null){let u=s.index-1,g=u>=0&&u<p.length?p[u]:null;g&&!E.has(g)&&(E.add(g),m.push(g))}else for(let u of p)E.has(u)||(E.add(u),m.push(u))}if(!m.length)return null;f=m}return f[n]??null}function re(t){let e=String(t??"").trim();if(!e)return 0;let r=new WeakSet,n=o=>{if(!o||r.has(o))return 0;r.add(o);let h=0;try{let l=o;typeof l.querySelectorAll=="function"&&(h+=l.querySelectorAll(e).length)}catch{}try{let i=(o instanceof Document?o:o?.ownerDocument??document).createTreeWalker(o,NodeFilter.SHOW_ELEMENT),c;for(;c=i.nextNode();)c instanceof Element&&c.shadowRoot&&(h+=n(c.shadowRoot))}catch{}return h};try{return n(document)}catch{try{return document.querySelectorAll(e).length}catch{return 0}}}function se(t){let e=String(t??"").trim();if(!e)return 0;let r=window.__stagehandV3__;if(!r||typeof r.getClosedRoot!="function")try{return document.querySelectorAll(e).length}catch{return 0}let n=new WeakSet,o=[],h=c=>{!c||n.has(c)||(n.add(c),o.push(c))};h(document);let l=0,i=c=>{let a=c.shadowRoot;a&&h(a);try{let f=r.getClosedRoot(c);f&&h(f)}catch{}};for(;o.length;){let c=o.shift();if(c){try{let a=c;typeof a.querySelectorAll=="function"&&(l+=a.querySelectorAll(e).length)}catch{}try{let f=(c instanceof Document?c:c instanceof ShadowRoot?c.host?.ownerDocument??document:c.ownerDocument??document).createTreeWalker(c,NodeFilter.SHOW_ELEMENT),d;for(;d=f.nextNode();)d instanceof Element&&i(d)}catch{}}}return l}function le(t){let e=String(t??"");if(!e)return{count:0,sample:[],error:null};let r=e.toLowerCase(),n=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),o=p=>{if(!p)return!1;let u=p.tagName?.toUpperCase()??"";return n.has(u)},h=p=>{try{if(o(p))return"";let u=p.innerText;if(typeof u=="string"&&u.trim())return u.trim()}catch{}try{let u=p.textContent;if(typeof u=="string")return u.trim()}catch{}return""},l=p=>{let u=h(p);return!!u&&u.toLowerCase().includes(r)},i=window.__stagehandV3__,c=i&&typeof i.getClosedRoot=="function"?p=>{try{return i.getClosedRoot(p)??null}catch{return null}}:p=>null,a=new WeakSet,f=[],d=p=>{!p||a.has(p)||(a.add(p),f.push(p))},s=p=>{try{return(p instanceof Document?p:p?.ownerDocument??document).createTreeWalker(p,NodeFilter.SHOW_ELEMENT)}catch{return null}},m=[];for(d(document);f.length;){let p=f.shift();if(!p)continue;p instanceof Element&&l(p)&&m.push({element:p,tag:p.tagName??"",id:p.id??"",className:p.className??"",text:h(p)});let u=s(p);if(!u)continue;let g;for(;g=u.nextNode();){if(!(g instanceof Element))continue;l(g)&&m.push({element:g,tag:g.tagName??"",id:g.id??"",className:g.className??"",text:h(g)});let b=g.shadowRoot;b&&d(b);let S=c(g);S&&d(S)}}let E=[];for(let p of m){let u=p.element,g=!1;for(let b of m)if(p!==b)try{if(u.contains(b.element)){g=!0;break}}catch{}g||E.push(p)}let w=E.length,y=E.slice(0,5).map(p=>({tag:p.tag,id:p.id,class:p.className,text:p.text}));return{count:w,sample:y,error:null}}function ce(t){let e=String(t??"").trim();if(!e)return 0;let n=(a=>{let f=String(a||"").trim().replace(/^xpath=/i,"");if(!f)return[];let d=[],s=0;for(;s<f.length;){let m="child";f.startsWith("//",s)?(m="desc",s+=2):f[s]==="/"&&(m="child",s+=1);let E=s;for(;s<f.length&&f[s]!=="/";)s+=1;let w=f.slice(E,s).trim();if(!w)continue;let y=w.match(/^(.*?)(\\[(\\d+)\\])?$/u),p=(y?.[1]??w).trim(),u=y?.[3]?Math.max(1,Number(y[3])):null,g=p===""?"*":p.toLowerCase();d.push({axis:m,tag:g,index:u})}return d})(e);if(!n.length)return 0;let o=window.__stagehandV3__,h=o&&typeof o.getClosedRoot=="function"?a=>{try{return o.getClosedRoot(a)??null}catch{return null}}:a=>null,l=a=>{let f=[];if(!a)return f;if(a instanceof Document)return a.documentElement&&f.push(a.documentElement),f;if(a instanceof ShadowRoot||a instanceof DocumentFragment)return f.push(...Array.from(a.children??[])),f;if(a instanceof Element){f.push(...Array.from(a.children??[]));let d=a.shadowRoot;d&&f.push(...Array.from(d.children??[]));let s=h(a);return s&&f.push(...Array.from(s.children??[])),f}return f},i=a=>{let f=[],d=new Set,s=[...l(a)];for(;s.length;){let m=s.shift();!m||d.has(m)||(d.add(m),f.push(m),s.push(...l(m)))}return f},c=[document];for(let a of n){let f=[],d=new Set;for(let s of c){if(!s)continue;let m=a.axis==="child"?l(s):i(s);if(!m.length)continue;let E=m.filter(w=>w instanceof Element?a.tag==="*"?!0:w.localName===a.tag:!1);if(a.index!=null){let w=a.index-1,y=w>=0&&w<E.length?E[w]:null;y&&!d.has(y)&&(d.add(y),f.push(y))}else for(let w of E)d.has(w)||(d.add(w),f.push(w))}if(!f.length)return 0;c=f}return c.length}var ie=t=>t.startsWith("xpath=")||t.startsWith("/"),ae=t=>t.startsWith("xpath=")?t.slice(6).trim():t,k=t=>{try{let e=window.__stagehandV3__;if(e&&typeof e.getClosedRoot=="function")return e.getClosedRoot(t)??null}catch{}return null},A=t=>t.shadowRoot?t.shadowRoot:k(t),ue=(t,e,r)=>{try{let h=t.querySelector(e);if(h)return h}catch{}if(!r)return null;let n=new WeakSet,o=[t];for(;o.length>0;){let h=o.shift();if(!(!h||n.has(h))){n.add(h);try{let l=h.querySelector(e);if(l)return l}catch{}try{let i=(h instanceof Document?h:h.host?.ownerDocument??document).createTreeWalker(h,NodeFilter.SHOW_ELEMENT),c;for(;c=i.nextNode();){if(!(c instanceof Element))continue;let a=A(c);a&&!n.has(a)&&o.push(a)}}catch{}}}return null},de=t=>{let e=t.replace(/^xpath=/i,""),r=[],n=0;for(;n<e.length;){let o="child";e.startsWith("//",n)?(o="desc",n+=2):e[n]==="/"&&(o="child",n+=1);let h=n,l=0;for(;n<e.length;){if(e[n]==="[")l++;else if(e[n]==="]")l--;else if(e[n]==="/"&&l===0)break;n+=1}let i=e.slice(h,n).trim();if(!i)continue;let a=(i.match(/^([^[]+)/)?.[1]??"*").trim(),f=a===""?"*":a.toLowerCase(),d=i.match(/\\[(\\d+)\\]/),s=d?Math.max(1,Number(d[1])):null,m=i.match(/\\[@([a-zA-Z_][\\w-]*)\\s*=\\s*[\'"]([^\'"]*)[\'"]\\]/),E=m?m[1]:null,w=m?m[2]:null;r.push({axis:o,tag:f,index:s,attrName:E,attrValue:w})}return r},R=t=>{let e=[];if(!t)return e;if(t instanceof Document)return t.documentElement&&e.push(t.documentElement),e;if(t instanceof ShadowRoot||t instanceof DocumentFragment)return e.push(...Array.from(t.children??[])),e;if(t instanceof Element){e.push(...Array.from(t.children??[]));let r=t.shadowRoot;r&&e.push(...Array.from(r.children??[]));let n=k(t);return n&&e.push(...Array.from(n.children??[])),e}return e},me=t=>{let e=[],r=new Set,n=[...R(t)];for(;n.length;){let o=n.shift();!o||r.has(o)||(r.add(o),e.push(o),n.push(...R(o)))}return e},fe=(t,e)=>{let r=ae(t);if(!r)return null;let n=window.__stagehandV3__;if(e)try{if(n&&typeof n.resolveSimpleXPath=="function"){let l=n.resolveSimpleXPath(r);if(l)return l}}catch{}try{let l=document.evaluate(r,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;if(l)return l}catch{}if(!e)return null;let o=de(r);if(!o.length)return null;let h=[document];for(let l of o){let i=[],c=new Set;for(let a of h){if(!a)continue;let f=l.axis==="child"?R(a):me(a);if(!f.length)continue;let d=f.filter(s=>s instanceof Element?l.tag==="*"?!0:s.localName===l.tag:!1);if(l.attrName!=null&&l.attrValue!=null&&(d=d.filter(s=>s.getAttribute(l.attrName)===l.attrValue)),l.index!=null){let s=l.index-1,m=s>=0&&s<d.length?d[s]:null;m&&!c.has(m)&&(c.add(m),i.push(m))}else for(let s of d)c.has(s)||(c.add(s),i.push(s))}if(!i.length)return null;h=i}return h[0]??null},C=(t,e)=>ie(t)?fe(t,e):ue(document,t,e),D=(t,e)=>{if(e==="detached")return t===null;if(e==="attached")return t!==null;if(t===null)return!1;if(e==="hidden")try{let r=window.getComputedStyle(t),n=t.getBoundingClientRect();return r.display==="none"||r.visibility==="hidden"||r.opacity==="0"||n.width===0||n.height===0}catch{return!1}try{let r=window.getComputedStyle(t),n=t.getBoundingClientRect();return r.display!=="none"&&r.visibility!=="hidden"&&r.opacity!=="0"&&n.width>0&&n.height>0}catch{return!1}},he=(t,e)=>{let r=new WeakSet,n=h=>{let l=A(h);if(l&&!r.has(l)){r.add(l);let i=new MutationObserver(t);i.observe(l,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden","disabled"]}),e.push(i);for(let c of Array.from(l.children))n(c)}for(let i of Array.from(h.children))n(i)},o=document.documentElement||document.body;o&&n(o)};function pe(t,e,r,n){let o=String(t??"").trim(),h=String(e??"visible")||"visible",l=typeof r=="number"&&r>0?r:3e4,i=n!==!1;return new Promise((c,a)=>{let f=null,d=null,s=!1,m=()=>{f!==null&&(clearTimeout(f),f=null)},E=C(o,i);if(D(E,h)){s=!0,c(!0);return}let w=[],y=()=>{for(let b of w)b.disconnect();d&&(document.removeEventListener("DOMContentLoaded",d),d=null)},p=()=>{if(s)return;let b=C(o,i);D(b,h)&&(s=!0,m(),y(),c(!0))};if(!(document.body||document.documentElement)){d=()=>{document.removeEventListener("DOMContentLoaded",d),d=null,p(),g()},document.addEventListener("DOMContentLoaded",d),f=setTimeout(()=>{s||(s=!0,m(),y(),a(new Error(`waitForSelector: Timeout ${l}ms exceeded waiting for "${o}" to be ${h}`)))},l);return}let g=()=>{let b=document.body||document.documentElement;if(!b)return;let S=new MutationObserver(p);S.observe(b,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden","disabled"]}),w.push(S),i&&he(p,w)};g(),f=setTimeout(()=>{s||(s=!0,m(),y(),a(new Error(`waitForSelector: Timeout ${l}ms exceeded waiting for "${o}" to be ${h}`)))},l)})}return O(ge);})();\n globalThis.__stagehandLocatorScripts = __stagehandLocatorScriptsFactory;\n}';
1355
+ locatorScriptBootstrap = 'if (!globalThis.__stagehandLocatorScripts) { var __stagehandLocatorScriptsFactory=(()=>{var M=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var Q=Object.prototype.hasOwnProperty;var Z=(e,t)=>{for(var n in t)M(e,n,{get:t[n],enumerable:!0})},j=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of U(t))!Q.call(e,r)&&r!==n&&M(e,r,{get:()=>t[r],enumerable:!(o=K(t,r))||o.enumerable});return e};var J=e=>j(M({},"__esModule",{value:!0}),e);var Oe={};Z(Oe,{assignFilePayloadsToInputElement:()=>te,countCssMatchesPierce:()=>Me,countCssMatchesPrimary:()=>Ce,countTextMatches:()=>Le,countXPathMatchesMainWorld:()=>Pe,dispatchDomClick:()=>ne,ensureFileInputElement:()=>ee,fillElementValue:()=>se,focusElement:()=>le,isElementChecked:()=>ce,isElementVisible:()=>ae,prepareElementForTyping:()=>v,readElementInnerHTML:()=>me,readElementInnerText:()=>fe,readElementInputValue:()=>ue,readElementTextContent:()=>de,resolveCssSelector:()=>ve,resolveCssSelectorPierce:()=>Te,resolveTextSelector:()=>Re,resolveXPathMainWorld:()=>Ne,scrollElementToPercent:()=>oe,selectElementOptions:()=>ie,waitForSelector:()=>_e});function ee(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}function te(e){try{let t=this;if(!t||t.tagName?.toLowerCase()!=="input"||(t.type??"").toLowerCase()!=="file")return!1;let n=(()=>{try{return new DataTransfer}catch{return null}})();if(!n)return!1;let o=Array.isArray(e)?e:[];for(let r of o){if(!r)continue;let l=r.name||"upload.bin",s=r.mimeType||"application/octet-stream",i=typeof r.lastModified=="number"?r.lastModified:Date.now(),a=window.atob(r.base64??""),d=new Uint8Array(a.length);for(let p=0;p<a.length;p+=1)d[p]=a.charCodeAt(p);let f=new Blob([d],{type:s}),c=new File([f],l,{type:s,lastModified:i});n.items.add(c)}return t.files=n.files,t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{return!1}}function ne(e){let t=e??{};try{let n=new MouseEvent("click",{bubbles:!!t.bubbles,cancelable:!!t.cancelable,composed:!!t.composed,detail:typeof t.detail=="number"?t.detail:1,view:this?.ownerDocument?.defaultView??window});this.dispatchEvent(n)}catch{try{this.click()}catch{}}}function oe(e){let t=n=>{if(typeof n=="number"&&Number.isFinite(n))return n;let o=String(n??"").trim();if(!o)return 0;let r=parseFloat(o.replace("%",""));return Number.isNaN(r)||!Number.isFinite(r)?0:r};try{let n=Math.max(0,Math.min(t(e),100)),o=this,r=o.tagName?.toLowerCase()??"";if(r==="html"||r==="body"){let c=(o.ownerDocument?.scrollingElement||o.ownerDocument?.documentElement||o.ownerDocument?.body||document.scrollingElement||document.documentElement||document.body)?.scrollHeight??document.body.scrollHeight??0,p=o.ownerDocument?.defaultView?.innerHeight??window.innerHeight,w=Math.max(0,c-p)*(n/100);return o.ownerDocument?.defaultView?.scrollTo({top:w,left:o.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let s=o.scrollHeight??0,i=o.clientHeight??0,d=Math.max(0,s-i)*(n/100);return o.scrollTo({top:d,left:o.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}var H=new Set(["color","date","datetime-local","month","range","time","week"]),re=new Set(["","email","number","password","search","tel","text","url"]);function v(){try{let e=this;if(!e.isConnected)return!1;let t=e.ownerDocument||document,n=t.defaultView||window;try{typeof e.focus=="function"&&e.focus()}catch{}if(e instanceof n.HTMLInputElement||e instanceof n.HTMLTextAreaElement){try{if(typeof e.select=="function")return e.select(),!0}catch{}try{let o=(e.value??"").length;if(typeof e.setSelectionRange=="function")return e.setSelectionRange(0,o),!0}catch{}return!0}if(e.isContentEditable){let o=t.getSelection?.(),r=t.createRange?.();if(o&&r)try{r.selectNodeContents(e),o.removeAllRanges(),o.addRange(r)}catch{}return!0}return!1}catch{return!1}}function se(e){let t=this;if(!t.isConnected)return{status:"error",reason:"notconnected"};let o=(t.ownerDocument||document).defaultView||window,r=e??"";try{let l=s=>{let i;if(typeof o.InputEvent=="function")try{i=new o.InputEvent("input",{bubbles:!0,composed:!0,data:s,inputType:"insertText"})}catch{i=new o.Event("input",{bubbles:!0,composed:!0})}else i=new o.Event("input",{bubbles:!0,composed:!0});t.dispatchEvent(i);let a=new o.Event("change",{bubbles:!0});t.dispatchEvent(a)};if(t instanceof o.HTMLInputElement){let s=(t.type||"").toLowerCase();if(!re.has(s)&&!H.has(s))return{status:"error",reason:`unsupported-input-type:${s}`};let i=e;if(s==="number"){let a=e.trim();if(a!==""&&Number.isNaN(Number(a)))return{status:"error",reason:"invalid-number-value"};i=a}if(r=i,H.has(s)){let a=e.trim();r=a,v.call(t);let d=o.HTMLInputElement.prototype,c=Object.getOwnPropertyDescriptor(d,"value")?.set;return typeof c=="function"?c.call(t,a):t.value=a,t._valueTracker?.setValue?.(a),t.value!==a?{status:"error",reason:"malformed-value"}:(l(a),{status:"done"})}return v.call(t),{status:"needsinput",value:i}}return t instanceof o.HTMLTextAreaElement?(v.call(t),r=e,{status:"needsinput",value:e}):t instanceof o.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:t.isContentEditable?(v.call(t),r=e,{status:"needsinput",value:e}):{status:"error",reason:"unsupported-element"}}catch(l){let s="exception";if(l&&typeof l=="object"){let i=l.message;typeof i=="string"&&i.trim().length>0&&(s=`exception:${i}`)}return{status:"needsinput",value:r,reason:s}}}function le(){try{typeof this.focus=="function"&&this.focus()}catch{}}function ie(e){try{if(!(this instanceof HTMLSelectElement))return[];let t=Array.isArray(e)?e:[e],n=new Set(t.map(s=>String(s??"").trim())),o=s=>{let i=(s.label||s.textContent||"").trim(),a=String(s.value??"").trim();return n.has(i)||n.has(a)};if(this.multiple)for(let s of Array.from(this.options))s.selected=o(s);else{let s=!1;for(let i of Array.from(this.options))!s&&o(i)?(i.selected=!0,this.value=i.value,s=!0):i.selected=!1}let r=new Event("input",{bubbles:!0}),l=new Event("change",{bubbles:!0});return this.dispatchEvent(r),this.dispatchEvent(l),Array.from(this.selectedOptions).map(s=>s.value)}catch{return[]}}function ae(){try{let e=this;if(!e.isConnected)return!1;let t=e.ownerDocument?.defaultView?.getComputedStyle(e)??window.getComputedStyle(e);if(!t||t.display==="none"||t.visibility==="hidden")return!1;let n=parseFloat(t.opacity??"1");if(!Number.isFinite(n)||n===0)return!1;let o=e.getBoundingClientRect();return!(!o||Math.max(o.width,o.height)===0||e.getClientRects().length===0)}catch{return!1}}function ce(){try{let e=this;if((e.tagName||"").toLowerCase()==="input"){let o=e.type?.toLowerCase()??"";if(o==="checkbox"||o==="radio")return!!e.checked}let n=e.getAttribute?.("aria-checked");return n!=null?n==="true":!1}catch{return!1}}function ue(){try{let e=this,t=(e.tagName||"").toLowerCase();return t==="input"||t==="textarea"||t==="select"?String(e.value??""):e.isContentEditable?String(e.textContent??""):""}catch{return""}}function de(){try{return String(this.textContent??"")}catch{return""}}function me(){try{return String(this.innerHTML??"")}catch{return""}}function fe(){try{let e=this,t=e.innerText;if(typeof t=="string"&&t.length>0)return t;let n=e.textContent;return typeof n=="string"?n:""}catch{return""}}function O(e){let t=String(e||"").trim().replace(/^xpath=/i,"");if(!t)return[];let n=[],o=0;for(;o<t.length;){let r="child";t.startsWith("//",o)?(r="desc",o+=2):t[o]==="/"&&(r="child",o+=1);let l=o,s=0,i=null;for(;o<t.length;){let c=t[o];if(i)c===i&&(i=null);else if(c==="\'"||c===\'"\')i=c;else if(c==="[")s++;else if(c==="]")s--;else if(c==="/"&&s===0)break;o+=1}let a=t.slice(l,o).trim();if(!a)continue;let{tag:d,predicates:f}=pe(a);n.push({axis:r,tag:d,predicates:f})}return n}function he(e){let t=[],n=0;for(;n<e.length;){if(e[n]!=="["){n++;continue}n++;let o=n,r=null;for(;n<e.length;){let l=e[n];if(r)l===r&&(r=null);else if(l==="\'"||l===\'"\')r=l;else if(l==="]")break;n++}t.push(e.slice(o,n).trim()),n++}return t}function pe(e){let t=e.indexOf("[");if(t===-1)return{tag:e===""?"*":e.toLowerCase(),predicates:[]};let n=e.slice(0,t).trim(),o=n===""?"*":n.toLowerCase(),r=e.slice(t),l=[];for(let s of he(r)){let i=T(s);i&&l.push(i)}return{tag:o,predicates:l}}function T(e){let t=e.trim();if(!t)return null;let n=A(t,"or");if(n.length>1){let l=n.map(s=>T(s)).filter(Boolean);return l.length!==n.length?null:{type:"or",predicates:l}}let o=A(t,"and");if(o.length>1){let l=o.map(s=>T(s)).filter(Boolean);return l.length!==o.length?null:{type:"and",predicates:l}}let r=we(t,"not");if(r!=null){let l=T(r);return l?{type:"not",predicate:l}:null}return ge(t)}function ge(e){let t=/^(?:\'([^\']*)\'|"([^"]*)")$/,n="[a-zA-Z_][\\\\w.-]*",o=`(?:\'([^\']*)\'|"([^"]*)")`;if(/^\\d+$/.test(e))return{type:"index",index:Math.max(1,Number(e))};let r=e.match(new RegExp(`^normalize-space\\\\(\\\\s*@(${n})\\\\s*\\\\)\\\\s*=\\\\s*${o}$`));if(r)return{type:"attrEquals",name:r[1],value:r[2]??r[3]??"",normalize:!0};let l=e.match(new RegExp(`^normalize-space\\\\(\\\\s*(?:text\\\\(\\\\)|\\\\.)\\\\s*\\\\)\\\\s*=\\\\s*${o}$`));if(l)return{type:"textEquals",value:l[1]??l[2]??"",normalize:!0};let s=e.match(new RegExp(`^@(${n})\\\\s*=\\\\s*${o}$`));if(s)return{type:"attrEquals",name:s[1],value:s[2]??s[3]??""};let i=e.match(new RegExp(`^@(${n})$`));if(i)return{type:"attrExists",name:i[1]};let a=e.match(new RegExp(`^contains\\\\(\\\\s*@(${n})\\\\s*,\\\\s*${o}\\\\s*\\\\)$`));if(a)return{type:"attrContains",name:a[1],value:a[2]??a[3]??""};let d=e.match(new RegExp(`^starts-with\\\\(\\\\s*@(${n})\\\\s*,\\\\s*${o}\\\\s*\\\\)$`));if(d)return{type:"attrStartsWith",name:d[1],value:d[2]??d[3]??""};let f=e.match(new RegExp(`^(?:text\\\\(\\\\)|\\\\.)\\\\s*=\\\\s*${o}$`));if(f)return{type:"textEquals",value:f[1]??f[2]??""};let c=e.match(new RegExp(`^contains\\\\(\\\\s*(?:text\\\\(\\\\)|\\\\.)\\\\s*,\\\\s*${o}\\\\s*\\\\)$`));return c?{type:"textContains",value:c[1]??c[2]??""}:(t.test(e),null)}function A(e,t){let n=[],o=0,r=0,l=null,s=0;for(;s<e.length;){let i=e[s];if(l){i===l&&(l=null),s+=1;continue}if(i==="\'"||i===\'"\'){l=i,s+=1;continue}if(i==="("){r+=1,s+=1;continue}if(i===")"){r=Math.max(0,r-1),s+=1;continue}if(r===0&&Ee(e,s,t)){n.push(e.slice(o,s).trim()),s+=t.length,o=s;continue}s+=1}return n.push(e.slice(o).trim()),n.filter(i=>i.length>0)}function Ee(e,t,n){if(!e.startsWith(n,t))return!1;let o=t>0?e[t-1]:" ";if(o==="@")return!1;let r=t+n.length<e.length?e[t+n.length]:" ";return W(o)&&W(r)}function W(e){return!/[a-zA-Z0-9_.-]/.test(e)}function we(e,t){let n=`${t}(`;if(!e.startsWith(n)||!e.endsWith(")"))return null;let o=e.slice(n.length,-1);return ye(o)?o:null}function ye(e){let t=0,n=null;for(let o=0;o<e.length;o+=1){let r=e[o];if(n){r===n&&(n=null);continue}if(r==="\'"||r===\'"\'){n=r;continue}if(r==="("?t+=1:r===")"&&(t-=1),t<0)return!1}return t===0}var be=e=>e.replace(/\\s+/g," ").trim();function _(e){return String(e.textContent??"")}function S(e,t){return t?be(e):e}function R(e,t){switch(t.type){case"and":return t.predicates.every(n=>R(e,n));case"or":return t.predicates.some(n=>R(e,n));case"not":return!R(e,t.predicate);case"attrExists":return e.getAttribute(t.name)!==null;case"attrEquals":{let n=e.getAttribute(t.name);return n===null?!1:S(n,t.normalize)===S(t.value,t.normalize)}case"attrContains":{let n=e.getAttribute(t.name);return n===null?!1:S(n,t.normalize).includes(S(t.value,t.normalize))}case"attrStartsWith":{let n=e.getAttribute(t.name);return n===null?!1:S(n,t.normalize).startsWith(S(t.value,t.normalize))}case"textEquals":return S(_(e),t.normalize)===S(t.value,t.normalize);case"textContains":return S(_(e),t.normalize).includes(S(t.value,t.normalize));case"index":return!0;default:return!0}}function q(e,t){let n=e;for(let o of t){if(!n.length)return[];if(o.type==="index"){let r=o.index-1;n=r>=0&&r<n.length?[n[r]]:[];continue}n=n.filter(r=>R(r,o))}return n}var P=e=>{let t=String(e??"").trim();return t?t.replace(/^xpath=/i,"").trim():""};function I(e,t){return k(e,0,t)}function k(e,t,n){if(!Number.isFinite(t)||t<0)return null;let o=P(e);if(!o)return null;let r=Math.floor(t),l=n?.pierceShadow!==!1,s=l?z():null;if(!l)return X(o,r).value;if(!s?.hasShadow){let a=X(o,r);return a.error?N(o,s?.getClosedRoot)[r]??null:a.value}return N(o,s.getClosedRoot)[r]??null}function $(e,t){let n=P(e);if(!n)return 0;let o=t?.pierceShadow!==!1,r=o?z():null;if(!o)return F(n).count;if(!r?.hasShadow){let l=F(n);return l.error?N(n,r?.getClosedRoot).length:l.count}return N(n,r.getClosedRoot).length}function N(e,t){let n=P(e);if(!n)return[];let o=O(n);if(!o.length)return[];let r=t??null,l=[document];for(let s of o){let i=[],a=new Set;for(let d of l){if(!d)continue;let f=s.axis==="child"?L(d,r):Se(d,r);if(!f.length)continue;let c=f.filter(g=>xe(g,s)),p=q(c,s.predicates);for(let g of p)a.has(g)||(a.add(g),i.push(g))}if(!i.length)return[];l=i}return l}function xe(e,t){return t.tag==="*"?!0:e.localName===t.tag}function z(){let e=window.__stagehandV3__,t=e&&typeof e.getClosedRoot=="function"?o=>{try{return e.getClosedRoot(o)??null}catch{return null}}:null,n=!1;try{if(e&&typeof e.stats=="function"){let o=e.stats();n=(o?.open??0)>0||(o?.closed??0)>0}}catch{}if(!n)try{let o=document.createTreeWalker(document,NodeFilter.SHOW_ELEMENT);for(;o.nextNode();)if(o.currentNode.shadowRoot){n=!0;break}}catch{}return{getClosedRoot:t,hasShadow:n}}function L(e,t){let n=[];if(!e)return n;if(e instanceof Document)return e.documentElement&&n.push(e.documentElement),n;if(e instanceof ShadowRoot||e instanceof DocumentFragment)return n.push(...Array.from(e.children??[])),n;if(e instanceof Element){n.push(...Array.from(e.children??[]));let o=e.shadowRoot;if(o&&n.push(...Array.from(o.children??[])),t){let r=t(e);r&&n.push(...Array.from(r.children??[]))}return n}return n}function Se(e,t){let n=[],o=new Set,r=[...L(e,t)].reverse();for(;r.length;){let l=r.pop();if(!l||o.has(l))continue;o.add(l),n.push(l);let s=L(l,t);for(let i=s.length-1;i>=0;i-=1)r.push(s[i])}return n}function X(e,t){try{return{value:document.evaluate(e,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(t),error:!1}}catch{return{value:null,error:!0}}}function F(e){try{return{count:document.evaluate(e,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotLength,error:!1}}catch{return{count:0,error:!0}}}var C=e=>{let t=Number(e??0);return!Number.isFinite(t)||t<0?0:Math.floor(t)},V=(e,t)=>{if(!e)return[];let n=new WeakSet,o=new Set,r=[],l=[document],s=i=>{if(!(!i||n.has(i)||r.length>=t)){n.add(i);try{let a=i.querySelectorAll(e);for(let d of a)if(!o.has(d)&&(o.add(d),r.push(d),r.length>=t))return}catch{}try{let d=(i instanceof Document?i:i.host?.ownerDocument??document).createTreeWalker(i,NodeFilter.SHOW_ELEMENT),f;for(;f=d.nextNode();){if(!(f instanceof Element))continue;let c=f.shadowRoot;c&&l.push(c)}}catch{}}};for(;l.length&&r.length<t;){let i=l.shift();i&&s(i)}return r};function ve(e,t){let n=String(e??"").trim();if(!n)return null;let o=C(t);return V(n,o+1)[o]??null}function Te(e,t){let n=String(e??"").trim();if(!n)return null;let o=C(t),r=window.__stagehandV3__;if(!r||typeof r.getClosedRoot!="function")return V(n,o+1)[o]??null;let l=c=>{try{return r.getClosedRoot(c)??null}catch{return null}},s=new WeakSet,i=new Set,a=[],d=[document],f=c=>{if(!(!c||s.has(c)||a.length>=o+1)){s.add(c);try{let p=c.querySelectorAll(n);for(let g of p)if(!i.has(g)&&(i.add(g),a.push(g),a.length>=o+1))return}catch{}try{let g=(c instanceof Document?c:c.host?.ownerDocument??document).createTreeWalker(c,NodeFilter.SHOW_ELEMENT),w;for(;w=g.nextNode();){if(!(w instanceof Element))continue;let x=w.shadowRoot;x&&d.push(x);let y=l(w);y&&d.push(y)}}catch{}}};for(;d.length&&a.length<o+1;){let c=d.shift();c&&f(c)}return a[o]??null}function Re(e,t){let n=String(e??"");if(!n)return null;let o=n.toLowerCase(),r=C(t),l=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),s=u=>{if(!u)return!1;let h=u.tagName?.toUpperCase()??"";return l.has(h)},i=u=>{try{if(s(u))return"";let h=u.innerText;if(typeof h=="string"&&h.trim())return h.trim()}catch{}try{let h=u.textContent;if(typeof h=="string")return h.trim()}catch{}return""},a=u=>{let h=i(u);return!!h&&h.toLowerCase().includes(o)},d=window.__stagehandV3__,f=d&&typeof d.getClosedRoot=="function"?u=>{try{return d.getClosedRoot(u)??null}catch{return null}}:u=>null,c=new WeakSet,p=[],g=[],w=u=>{!u||c.has(u)||(c.add(u),p.push(u))},x=u=>{try{return(u instanceof Document?u:u?.ownerDocument??document).createTreeWalker(u,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(w(document);p.length;){let u=p.shift();if(!u)continue;u instanceof Element&&a(u)&&g.push({element:u,tag:u.tagName??"",id:u.id??"",className:u.className??"",text:i(u)});let h=x(u);if(!h)continue;let E;for(;E=h.nextNode();){if(!(E instanceof Element))continue;a(E)&&g.push({element:E,tag:E.tagName??"",id:E.id??"",className:E.className??"",text:i(E)});let b=E.shadowRoot;b&&w(b);let D=f(E);D&&w(D)}}let y=[];for(let u of g){let h=u.element,E=!1;for(let b of g)if(u!==b)try{if(h.contains(b.element)){E=!0;break}}catch{}E||y.push(u)}return y[r]?.element??null}function Ne(e,t){let n=C(t);return k(e,n,{pierceShadow:!0})}function Ce(e){let t=String(e??"").trim();if(!t)return 0;let n=new WeakSet,o=r=>{if(!r||n.has(r))return 0;n.add(r);let l=0;try{let s=r;typeof s.querySelectorAll=="function"&&(l+=s.querySelectorAll(t).length)}catch{}try{let i=(r instanceof Document?r:r?.ownerDocument??document).createTreeWalker(r,NodeFilter.SHOW_ELEMENT),a;for(;a=i.nextNode();)a instanceof Element&&a.shadowRoot&&(l+=o(a.shadowRoot))}catch{}return l};try{return o(document)}catch{try{return document.querySelectorAll(t).length}catch{return 0}}}function Me(e){let t=String(e??"").trim();if(!t)return 0;let n=window.__stagehandV3__;if(!n||typeof n.getClosedRoot!="function")try{return document.querySelectorAll(t).length}catch{return 0}let o=new WeakSet,r=[],l=a=>{!a||o.has(a)||(o.add(a),r.push(a))};l(document);let s=0,i=a=>{let d=a.shadowRoot;d&&l(d);try{let f=n.getClosedRoot(a);f&&l(f)}catch{}};for(;r.length;){let a=r.shift();if(a){try{let d=a;typeof d.querySelectorAll=="function"&&(s+=d.querySelectorAll(t).length)}catch{}try{let f=(a instanceof Document?a:a instanceof ShadowRoot?a.host?.ownerDocument??document:a.ownerDocument??document).createTreeWalker(a,NodeFilter.SHOW_ELEMENT),c;for(;c=f.nextNode();)c instanceof Element&&i(c)}catch{}}}return s}function Le(e){let t=String(e??"");if(!t)return{count:0,sample:[],error:null};let n=t.toLowerCase(),o=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),r=m=>{if(!m)return!1;let u=m.tagName?.toUpperCase()??"";return o.has(u)},l=m=>{try{if(r(m))return"";let u=m.innerText;if(typeof u=="string"&&u.trim())return u.trim()}catch{}try{let u=m.textContent;if(typeof u=="string")return u.trim()}catch{}return""},s=m=>{let u=l(m);return!!u&&u.toLowerCase().includes(n)},i=window.__stagehandV3__,a=i&&typeof i.getClosedRoot=="function"?m=>{try{return i.getClosedRoot(m)??null}catch{return null}}:m=>null,d=new WeakSet,f=[],c=m=>{!m||d.has(m)||(d.add(m),f.push(m))},p=m=>{try{return(m instanceof Document?m:m?.ownerDocument??document).createTreeWalker(m,NodeFilter.SHOW_ELEMENT)}catch{return null}},g=[];for(c(document);f.length;){let m=f.shift();if(!m)continue;m instanceof Element&&s(m)&&g.push({element:m,tag:m.tagName??"",id:m.id??"",className:m.className??"",text:l(m)});let u=p(m);if(!u)continue;let h;for(;h=u.nextNode();){if(!(h instanceof Element))continue;s(h)&&g.push({element:h,tag:h.tagName??"",id:h.id??"",className:h.className??"",text:l(h)});let E=h.shadowRoot;E&&c(E);let b=a(h);b&&c(b)}}let w=[];for(let m of g){let u=m.element,h=!1;for(let E of g)if(m!==E)try{if(u.contains(E.element)){h=!0;break}}catch{}h||w.push(m)}let x=w.length,y=w.slice(0,5).map(m=>({tag:m.tag,id:m.id,class:m.className,text:m.text}));return{count:x,sample:y,error:null}}function Pe(e){return $(e,{pierceShadow:!0})}var ke=e=>e.startsWith("xpath=")||e.startsWith("/"),De=e=>{try{let t=window.__stagehandV3__;if(t&&typeof t.getClosedRoot=="function")return t.getClosedRoot(e)??null}catch{}return null},Y=e=>e.shadowRoot?e.shadowRoot:De(e),He=(e,t,n)=>{try{let l=e.querySelector(t);if(l)return l}catch{}if(!n)return null;let o=new WeakSet,r=[e];for(;r.length>0;){let l=r.shift();if(!(!l||o.has(l))){o.add(l);try{let s=l.querySelector(t);if(s)return s}catch{}try{let i=(l instanceof Document?l:l.host?.ownerDocument??document).createTreeWalker(l,NodeFilter.SHOW_ELEMENT),a;for(;a=i.nextNode();){if(!(a instanceof Element))continue;let d=Y(a);d&&!o.has(d)&&r.push(d)}}catch{}}}return null},Ae=(e,t)=>I(e,{pierceShadow:t}),B=(e,t)=>ke(e)?Ae(e,t):He(document,e,t),G=(e,t)=>{if(t==="detached")return e===null;if(t==="attached")return e!==null;if(e===null)return!1;if(t==="hidden")try{let n=window.getComputedStyle(e),o=e.getBoundingClientRect();return n.display==="none"||n.visibility==="hidden"||n.opacity==="0"||o.width===0||o.height===0}catch{return!1}try{let n=window.getComputedStyle(e),o=e.getBoundingClientRect();return n.display!=="none"&&n.visibility!=="hidden"&&n.opacity!=="0"&&o.width>0&&o.height>0}catch{return!1}},We=(e,t)=>{let n=new WeakSet,o=l=>{let s=Y(l);if(s&&!n.has(s)){n.add(s);let i=new MutationObserver(e);i.observe(s,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden","disabled"]}),t.push(i);for(let a of Array.from(s.children))o(a)}for(let i of Array.from(l.children))o(i)},r=document.documentElement||document.body;r&&o(r)};function _e(e,t,n,o){let r=String(e??"").trim(),l=String(t??"visible")||"visible",s=typeof n=="number"&&n>0?n:3e4,i=o!==!1;return new Promise((a,d)=>{let f=null,c=null,p=!1,g=()=>{f!==null&&(clearTimeout(f),f=null)},w=B(r,i);if(G(w,l)){p=!0,a(!0);return}let x=[],y=()=>{for(let E of x)E.disconnect();c&&(document.removeEventListener("DOMContentLoaded",c),c=null)},m=()=>{if(p)return;let E=B(r,i);G(E,l)&&(p=!0,g(),y(),a(!0))};if(!(document.body||document.documentElement)){c=()=>{document.removeEventListener("DOMContentLoaded",c),c=null,m(),h()},document.addEventListener("DOMContentLoaded",c),f=setTimeout(()=>{p||(p=!0,g(),y(),d(new Error(`waitForSelector: Timeout ${s}ms exceeded waiting for "${r}" to be ${l}`)))},s);return}let h=()=>{let E=document.body||document.documentElement;if(!E)return;let b=new MutationObserver(m);b.observe(E,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden","disabled"]}),x.push(b),i&&We(m,x)};h(),f=setTimeout(()=>{p||(p=!0,g(),y(),d(new Error(`waitForSelector: Timeout ${s}ms exceeded waiting for "${r}" to be ${l}`)))},s)})}return J(Oe);})();\n globalThis.__stagehandLocatorScripts = __stagehandLocatorScriptsFactory;\n}';
1349
1356
  locatorScriptSources = {
1350
- "assignFilePayloadsToInputElement": 'function X(t){try{let e=this;if(!e||e.tagName?.toLowerCase()!=="input"||(e.type??"").toLowerCase()!=="file")return!1;let s=(()=>{try{return new DataTransfer}catch{return null}})();if(!s)return!1;let n=Array.isArray(t)?t:[];for(let r of n){if(!r)continue;let h=r.name||"upload.bin",l=r.mimeType||"application/octet-stream",i=typeof r.lastModified=="number"?r.lastModified:Date.now(),c=window.atob(r.base64??""),a=new Uint8Array(c.length);for(let o=0;o<c.length;o+=1)a[o]=c.charCodeAt(o);let f=new Blob([a],{type:l}),d=new File([f],h,{type:l,lastModified:i});s.items.add(d)}return e.files=s.files,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{return!1}}',
1351
- "countCssMatchesPierce": 'function ce(t){let e=String(t??"").trim();if(!e)return 0;let s=window.__stagehandV3__;if(!s||typeof s.getClosedRoot!="function")try{return document.querySelectorAll(e).length}catch{return 0}let n=new WeakSet,r=[],h=c=>{!c||n.has(c)||(n.add(c),r.push(c))};h(document);let l=0,i=c=>{let a=c.shadowRoot;a&&h(a);try{let f=s.getClosedRoot(c);f&&h(f)}catch{}};for(;r.length;){let c=r.shift();if(c){try{let a=c;typeof a.querySelectorAll=="function"&&(l+=a.querySelectorAll(e).length)}catch{}try{let f=(c instanceof Document?c:c instanceof ShadowRoot?c.host?.ownerDocument??document:c.ownerDocument??document).createTreeWalker(c,NodeFilter.SHOW_ELEMENT),d;for(;d=f.nextNode();)d instanceof Element&&i(d)}catch{}}}return l}',
1352
- "countCssMatchesPrimary": 'function le(t){let e=String(t??"").trim();if(!e)return 0;let s=new WeakSet,n=r=>{if(!r||s.has(r))return 0;s.add(r);let h=0;try{let l=r;typeof l.querySelectorAll=="function"&&(h+=l.querySelectorAll(e).length)}catch{}try{let i=(r instanceof Document?r:r?.ownerDocument??document).createTreeWalker(r,NodeFilter.SHOW_ELEMENT),c;for(;c=i.nextNode();)c instanceof Element&&c.shadowRoot&&(h+=n(c.shadowRoot))}catch{}return h};try{return n(document)}catch{try{return document.querySelectorAll(e).length}catch{return 0}}}',
1353
- "countTextMatches": 'function ie(t){let e=String(t??"");if(!e)return{count:0,sample:[],error:null};let s=e.toLowerCase(),n=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),r=p=>{if(!p)return!1;let u=p.tagName?.toUpperCase()??"";return n.has(u)},h=p=>{try{if(r(p))return"";let u=p.innerText;if(typeof u=="string"&&u.trim())return u.trim()}catch{}try{let u=p.textContent;if(typeof u=="string")return u.trim()}catch{}return""},l=p=>{let u=h(p);return!!u&&u.toLowerCase().includes(s)},i=window.__stagehandV3__,c=i&&typeof i.getClosedRoot=="function"?p=>{try{return i.getClosedRoot(p)??null}catch{return null}}:p=>null,a=new WeakSet,f=[],d=p=>{!p||a.has(p)||(a.add(p),f.push(p))},o=p=>{try{return(p instanceof Document?p:p?.ownerDocument??document).createTreeWalker(p,NodeFilter.SHOW_ELEMENT)}catch{return null}},m=[];for(d(document);f.length;){let p=f.shift();if(!p)continue;p instanceof Element&&l(p)&&m.push({element:p,tag:p.tagName??"",id:p.id??"",className:p.className??"",text:h(p)});let u=o(p);if(!u)continue;let g;for(;g=u.nextNode();){if(!(g instanceof Element))continue;l(g)&&m.push({element:g,tag:g.tagName??"",id:g.id??"",className:g.className??"",text:h(g)});let b=g.shadowRoot;b&&d(b);let S=c(g);S&&d(S)}}let E=[];for(let p of m){let u=p.element,g=!1;for(let b of m)if(p!==b)try{if(u.contains(b.element)){g=!0;break}}catch{}g||E.push(p)}let w=E.length,y=E.slice(0,5).map(p=>({tag:p.tag,id:p.id,class:p.className,text:p.text}));return{count:w,sample:y,error:null}}',
1354
- "countXPathMatchesMainWorld": 'function ae(t){let e=String(t??"").trim();if(!e)return 0;let n=(a=>{let f=String(a||"").trim().replace(/^xpath=/i,"");if(!f)return[];let d=[],o=0;for(;o<f.length;){let m="child";f.startsWith("//",o)?(m="desc",o+=2):f[o]==="/"&&(m="child",o+=1);let E=o;for(;o<f.length&&f[o]!=="/";)o+=1;let w=f.slice(E,o).trim();if(!w)continue;let y=w.match(/^(.*?)(\\[(\\d+)\\])?$/u),p=(y?.[1]??w).trim(),u=y?.[3]?Math.max(1,Number(y[3])):null,g=p===""?"*":p.toLowerCase();d.push({axis:m,tag:g,index:u})}return d})(e);if(!n.length)return 0;let r=window.__stagehandV3__,h=r&&typeof r.getClosedRoot=="function"?a=>{try{return r.getClosedRoot(a)??null}catch{return null}}:a=>null,l=a=>{let f=[];if(!a)return f;if(a instanceof Document)return a.documentElement&&f.push(a.documentElement),f;if(a instanceof ShadowRoot||a instanceof DocumentFragment)return f.push(...Array.from(a.children??[])),f;if(a instanceof Element){f.push(...Array.from(a.children??[]));let d=a.shadowRoot;d&&f.push(...Array.from(d.children??[]));let o=h(a);return o&&f.push(...Array.from(o.children??[])),f}return f},i=a=>{let f=[],d=new Set,o=[...l(a)];for(;o.length;){let m=o.shift();!m||d.has(m)||(d.add(m),f.push(m),o.push(...l(m)))}return f},c=[document];for(let a of n){let f=[],d=new Set;for(let o of c){if(!o)continue;let m=a.axis==="child"?l(o):i(o);if(!m.length)continue;let E=m.filter(w=>w instanceof Element?a.tag==="*"?!0:w.localName===a.tag:!1);if(a.index!=null){let w=a.index-1,y=w>=0&&w<E.length?E[w]:null;y&&!d.has(y)&&(d.add(y),f.push(y))}else for(let w of E)d.has(w)||(d.add(w),f.push(w))}if(!f.length)return 0;c=f}return c.length}',
1355
- "dispatchDomClick": 'function $(t){let e=t??{};try{let s=new MouseEvent("click",{bubbles:!!e.bubbles,cancelable:!!e.cancelable,composed:!!e.composed,detail:typeof e.detail=="number"?e.detail:1,view:this?.ownerDocument?.defaultView??window});this.dispatchEvent(s)}catch{try{this.click()}catch{}}}',
1356
- "ensureFileInputElement": 'function V(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}',
1357
- "fillElementValue": 'function Y(t){let e=this;if(!e.isConnected)return{status:"error",reason:"notconnected"};let n=(e.ownerDocument||document).defaultView||window,r=t??"";try{let h=l=>{let i;if(typeof n.InputEvent=="function")try{i=new n.InputEvent("input",{bubbles:!0,composed:!0,data:l,inputType:"insertText"})}catch{i=new n.Event("input",{bubbles:!0,composed:!0})}else i=new n.Event("input",{bubbles:!0,composed:!0});e.dispatchEvent(i);let c=new n.Event("change",{bubbles:!0});e.dispatchEvent(c)};if(e instanceof n.HTMLInputElement){let l=(e.type||"").toLowerCase();if(!H.has(l)&&!R.has(l))return{status:"error",reason:`unsupported-input-type:${l}`};let i=t;if(l==="number"){let c=t.trim();if(c!==""&&Number.isNaN(Number(c)))return{status:"error",reason:"invalid-number-value"};i=c}if(r=i,R.has(l)){let c=t.trim();r=c,T.call(e);let a=n.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(a,"value")?.set;return typeof d=="function"?d.call(e,c):e.value=c,e._valueTracker?.setValue?.(c),e.value!==c?{status:"error",reason:"malformed-value"}:(h(c),{status:"done"})}return T.call(e),{status:"needsinput",value:i}}return e instanceof n.HTMLTextAreaElement?(T.call(e),r=t,{status:"needsinput",value:t}):e instanceof n.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:e.isContentEditable?(T.call(e),r=t,{status:"needsinput",value:t}):{status:"error",reason:"unsupported-element"}}catch(h){let l="exception";if(h&&typeof h=="object"){let i=h.message;typeof i=="string"&&i.trim().length>0&&(l=`exception:${i}`)}return{status:"needsinput",value:r,reason:l}}}',
1358
- "focusElement": 'function z(){try{typeof this.focus=="function"&&this.focus()}catch{}}',
1359
- "isElementChecked": 'function Q(){try{let t=this;if((t.tagName||"").toLowerCase()==="input"){let n=t.type?.toLowerCase()??"";if(n==="checkbox"||n==="radio")return!!t.checked}let s=t.getAttribute?.("aria-checked");return s!=null?s==="true":!1}catch{return!1}}',
1360
- "isElementVisible": 'function K(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument?.defaultView?.getComputedStyle(t)??window.getComputedStyle(t);if(!e||e.display==="none"||e.visibility==="hidden")return!1;let s=parseFloat(e.opacity??"1");if(!Number.isFinite(s)||s===0)return!1;let n=t.getBoundingClientRect();return!(!n||Math.max(n.width,n.height)===0||t.getClientRects().length===0)}catch{return!1}}',
1361
- "prepareElementForTyping": 'function T(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument||document,s=e.defaultView||window;try{typeof t.focus=="function"&&t.focus()}catch{}if(t instanceof s.HTMLInputElement||t instanceof s.HTMLTextAreaElement){try{if(typeof t.select=="function")return t.select(),!0}catch{}try{let n=(t.value??"").length;if(typeof t.setSelectionRange=="function")return t.setSelectionRange(0,n),!0}catch{}return!0}if(t.isContentEditable){let n=e.getSelection?.(),r=e.createRange?.();if(n&&r)try{r.selectNodeContents(t),n.removeAllRanges(),n.addRange(r)}catch{}return!0}return!1}catch{return!1}}',
1362
- "readElementInnerHTML": 'function G(){try{return String(this.innerHTML??"")}catch{return""}}',
1363
- "readElementInnerText": 'function J(){try{let t=this,e=t.innerText;if(typeof e=="string"&&e.length>0)return e;let s=t.textContent;return typeof s=="string"?s:""}catch{return""}}',
1364
- "readElementInputValue": 'function j(){try{let t=this,e=(t.tagName||"").toLowerCase();return e==="input"||e==="textarea"||e==="select"?String(t.value??""):t.isContentEditable?String(t.textContent??""):""}catch{return""}}',
1365
- "readElementTextContent": 'function Z(){try{return String(this.textContent??"")}catch{return""}}',
1366
- "resolveCssSelector": 'function te(t,e){let s=String(t??"").trim();if(!s)return null;let n=v(e);return M(s,n+1)[n]??null}',
1367
- "resolveCssSelectorPierce": 'function ne(t,e){let s=String(t??"").trim();if(!s)return null;let n=v(e),r=window.__stagehandV3__;if(!r||typeof r.getClosedRoot!="function")return M(s,n+1)[n]??null;let h=d=>{try{return r.getClosedRoot(d)??null}catch{return null}},l=new WeakSet,i=new Set,c=[],a=[document],f=d=>{if(!(!d||l.has(d)||c.length>=n+1)){l.add(d);try{let o=d.querySelectorAll(s);for(let m of o)if(!i.has(m)&&(i.add(m),c.push(m),c.length>=n+1))return}catch{}try{let m=(d instanceof Document?d:d.host?.ownerDocument??document).createTreeWalker(d,NodeFilter.SHOW_ELEMENT),E;for(;E=m.nextNode();){if(!(E instanceof Element))continue;let w=E.shadowRoot;w&&a.push(w);let y=h(E);y&&a.push(y)}}catch{}}};for(;a.length&&c.length<n+1;){let d=a.shift();d&&f(d)}return c[n]??null}',
1368
- "resolveTextSelector": 'function oe(t,e){let s=String(t??"");if(!s)return null;let n=s.toLowerCase(),r=v(e),h=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),l=u=>{if(!u)return!1;let g=u.tagName?.toUpperCase()??"";return h.has(g)},i=u=>{try{if(l(u))return"";let g=u.innerText;if(typeof g=="string"&&g.trim())return g.trim()}catch{}try{let g=u.textContent;if(typeof g=="string")return g.trim()}catch{}return""},c=u=>{let g=i(u);return!!g&&g.toLowerCase().includes(n)},a=window.__stagehandV3__,f=a&&typeof a.getClosedRoot=="function"?u=>{try{return a.getClosedRoot(u)??null}catch{return null}}:u=>null,d=new WeakSet,o=[],m=[],E=u=>{!u||d.has(u)||(d.add(u),o.push(u))},w=u=>{try{return(u instanceof Document?u:u?.ownerDocument??document).createTreeWalker(u,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(E(document);o.length;){let u=o.shift();if(!u)continue;u instanceof Element&&c(u)&&m.push({element:u,tag:u.tagName??"",id:u.id??"",className:u.className??"",text:i(u)});let g=w(u);if(!g)continue;let b;for(;b=g.nextNode();){if(!(b instanceof Element))continue;c(b)&&m.push({element:b,tag:b.tagName??"",id:b.id??"",className:b.className??"",text:i(b)});let S=b.shadowRoot;S&&E(S);let x=f(b);x&&E(x)}}let y=[];for(let u of m){let g=u.element,b=!1;for(let S of m)if(u!==S)try{if(g.contains(S.element)){b=!0;break}}catch{}b||y.push(u)}return y[r]?.element??null}',
1369
- "resolveXPathMainWorld": 'function re(t,e){let s=String(t??"").trim();if(!s)return null;let n=v(e),r=window.__stagehandV3__;if(n===0){try{if(r&&typeof r.resolveSimpleXPath=="function"){let o=r.resolveSimpleXPath(s);if(o)return o}}catch{}try{return document.evaluate(s,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{}}let l=(o=>{let m=String(o||"").trim();if(!m)return[];let E=m.replace(/^xpath=/i,""),w=[],y=0;for(;y<E.length;){let p="child";E.startsWith("//",y)?(p="desc",y+=2):E[y]==="/"&&(p="child",y+=1);let u=y;for(;y<E.length&&E[y]!=="/";)y+=1;let g=E.slice(u,y).trim();if(!g)continue;let b=g.match(/^(.*?)(\\[(\\d+)\\])?$/u),S=(b?.[1]??g).trim(),x=b?.[3]?Math.max(1,Number(b[3])):null,A=S===""?"*":S.toLowerCase();w.push({axis:p,tag:A,index:x})}return w})(s);if(!l.length)return null;let i=r&&typeof r.getClosedRoot=="function"?o=>{try{return r.getClosedRoot(o)??null}catch{return null}}:o=>null,c=o=>{let m=[];if(!o)return m;if(o instanceof Document)return o.documentElement&&m.push(o.documentElement),m;if(o instanceof ShadowRoot||o instanceof DocumentFragment)return m.push(...Array.from(o.children??[])),m;if(o instanceof Element){m.push(...Array.from(o.children??[]));let E=o.shadowRoot;E&&m.push(...Array.from(E.children??[]));let w=i(o);return w&&m.push(...Array.from(w.children??[])),m}return m},a=o=>{let m=[],E=new Set,w=[...c(o)];for(;w.length;){let y=w.shift();!y||E.has(y)||(E.add(y),m.push(y),w.push(...c(y)))}return m},f=[document];for(let o of l){let m=[],E=new Set;for(let w of f){if(!w)continue;let y=o.axis==="child"?c(w):a(w);if(!y.length)continue;let p=y.filter(u=>u instanceof Element?o.tag==="*"?!0:u.localName===o.tag:!1);if(o.index!=null){let u=o.index-1,g=u>=0&&u<p.length?p[u]:null;g&&!E.has(g)&&(E.add(g),m.push(g))}else for(let u of p)E.has(u)||(E.add(u),m.push(u))}if(!m.length)return null;f=m}return f[n]??null}',
1370
- "scrollElementToPercent": 'function B(t){let e=s=>{if(typeof s=="number"&&Number.isFinite(s))return s;let n=String(s??"").trim();if(!n)return 0;let r=parseFloat(n.replace("%",""));return Number.isNaN(r)||!Number.isFinite(r)?0:r};try{let s=Math.max(0,Math.min(e(t),100)),n=this,r=n.tagName?.toLowerCase()??"";if(r==="html"||r==="body"){let d=(n.ownerDocument?.scrollingElement||n.ownerDocument?.documentElement||n.ownerDocument?.body||document.scrollingElement||document.documentElement||document.body)?.scrollHeight??document.body.scrollHeight??0,o=n.ownerDocument?.defaultView?.innerHeight??window.innerHeight,E=Math.max(0,d-o)*(s/100);return n.ownerDocument?.defaultView?.scrollTo({top:E,left:n.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let l=n.scrollHeight??0,i=n.clientHeight??0,a=Math.max(0,l-i)*(s/100);return n.scrollTo({top:a,left:n.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}',
1371
- "selectElementOptions": 'function U(t){try{if(!(this instanceof HTMLSelectElement))return[];let e=Array.isArray(t)?t:[t],s=new Set(e.map(l=>String(l??"").trim())),n=l=>{let i=(l.label||l.textContent||"").trim(),c=String(l.value??"").trim();return s.has(i)||s.has(c)};if(this.multiple)for(let l of Array.from(this.options))l.selected=n(l);else{let l=!1;for(let i of Array.from(this.options))!l&&n(i)?(i.selected=!0,this.value=i.value,l=!0):i.selected=!1}let r=new Event("input",{bubbles:!0}),h=new Event("change",{bubbles:!0});return this.dispatchEvent(r),this.dispatchEvent(h),Array.from(this.selectedOptions).map(l=>l.value)}catch{return[]}}',
1372
- "waitForSelector": 'function de(t,e,s,n){let r=String(t??"").trim(),h=String(e??"visible")||"visible",l=typeof s=="number"&&s>0?s:3e4,i=n!==!1;return new Promise((c,a)=>{let f=null,d=null,o=!1,m=()=>{f!==null&&(clearTimeout(f),f=null)},E=L(r,i);if(C(E,h)){o=!0,c(!0);return}let w=[],y=()=>{for(let b of w)b.disconnect();d&&(document.removeEventListener("DOMContentLoaded",d),d=null)},p=()=>{if(o)return;let b=L(r,i);C(b,h)&&(o=!0,m(),y(),c(!0))};if(!(document.body||document.documentElement)){d=()=>{document.removeEventListener("DOMContentLoaded",d),d=null,p(),g()},document.addEventListener("DOMContentLoaded",d),f=setTimeout(()=>{o||(o=!0,m(),y(),a(new Error(`waitForSelector: Timeout ${l}ms exceeded waiting for "${r}" to be ${h}`)))},l);return}let g=()=>{let b=document.body||document.documentElement;if(!b)return;let S=new MutationObserver(p);S.observe(b,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden","disabled"]}),w.push(S),i&&q(p,w)};g(),f=setTimeout(()=>{o||(o=!0,m(),y(),a(new Error(`waitForSelector: Timeout ${l}ms exceeded waiting for "${r}" to be ${h}`)))},l)})}'
1357
+ "assignFilePayloadsToInputElement": 'function ce(e){try{let t=this;if(!t||t.tagName?.toLowerCase()!=="input"||(t.type??"").toLowerCase()!=="file")return!1;let n=(()=>{try{return new DataTransfer}catch{return null}})();if(!n)return!1;let o=Array.isArray(e)?e:[];for(let r of o){if(!r)continue;let l=r.name||"upload.bin",s=r.mimeType||"application/octet-stream",i=typeof r.lastModified=="number"?r.lastModified:Date.now(),a=window.atob(r.base64??""),d=new Uint8Array(a.length);for(let p=0;p<a.length;p+=1)d[p]=a.charCodeAt(p);let f=new Blob([d],{type:s}),c=new File([f],l,{type:s,lastModified:i});n.items.add(c)}return t.files=n.files,t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{return!1}}',
1358
+ "countCssMatchesPierce": 'function He(e){let t=String(e??"").trim();if(!t)return 0;let n=window.__stagehandV3__;if(!n||typeof n.getClosedRoot!="function")try{return document.querySelectorAll(t).length}catch{return 0}let o=new WeakSet,r=[],l=a=>{!a||o.has(a)||(o.add(a),r.push(a))};l(document);let s=0,i=a=>{let d=a.shadowRoot;d&&l(d);try{let f=n.getClosedRoot(a);f&&l(f)}catch{}};for(;r.length;){let a=r.shift();if(a){try{let d=a;typeof d.querySelectorAll=="function"&&(s+=d.querySelectorAll(t).length)}catch{}try{let f=(a instanceof Document?a:a instanceof ShadowRoot?a.host?.ownerDocument??document:a.ownerDocument??document).createTreeWalker(a,NodeFilter.SHOW_ELEMENT),c;for(;c=f.nextNode();)c instanceof Element&&i(c)}catch{}}}return s}',
1359
+ "countCssMatchesPrimary": 'function De(e){let t=String(e??"").trim();if(!t)return 0;let n=new WeakSet,o=r=>{if(!r||n.has(r))return 0;n.add(r);let l=0;try{let s=r;typeof s.querySelectorAll=="function"&&(l+=s.querySelectorAll(t).length)}catch{}try{let i=(r instanceof Document?r:r?.ownerDocument??document).createTreeWalker(r,NodeFilter.SHOW_ELEMENT),a;for(;a=i.nextNode();)a instanceof Element&&a.shadowRoot&&(l+=o(a.shadowRoot))}catch{}return l};try{return o(document)}catch{try{return document.querySelectorAll(t).length}catch{return 0}}}',
1360
+ "countTextMatches": 'function Ae(e){let t=String(e??"");if(!t)return{count:0,sample:[],error:null};let n=t.toLowerCase(),o=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),r=m=>{if(!m)return!1;let u=m.tagName?.toUpperCase()??"";return o.has(u)},l=m=>{try{if(r(m))return"";let u=m.innerText;if(typeof u=="string"&&u.trim())return u.trim()}catch{}try{let u=m.textContent;if(typeof u=="string")return u.trim()}catch{}return""},s=m=>{let u=l(m);return!!u&&u.toLowerCase().includes(n)},i=window.__stagehandV3__,a=i&&typeof i.getClosedRoot=="function"?m=>{try{return i.getClosedRoot(m)??null}catch{return null}}:m=>null,d=new WeakSet,f=[],c=m=>{!m||d.has(m)||(d.add(m),f.push(m))},p=m=>{try{return(m instanceof Document?m:m?.ownerDocument??document).createTreeWalker(m,NodeFilter.SHOW_ELEMENT)}catch{return null}},g=[];for(c(document);f.length;){let m=f.shift();if(!m)continue;m instanceof Element&&s(m)&&g.push({element:m,tag:m.tagName??"",id:m.id??"",className:m.className??"",text:l(m)});let u=p(m);if(!u)continue;let h;for(;h=u.nextNode();){if(!(h instanceof Element))continue;s(h)&&g.push({element:h,tag:h.tagName??"",id:h.id??"",className:h.className??"",text:l(h)});let E=h.shadowRoot;E&&c(E);let b=a(h);b&&c(b)}}let w=[];for(let m of g){let u=m.element,h=!1;for(let E of g)if(m!==E)try{if(u.contains(E.element)){h=!0;break}}catch{}h||w.push(m)}let x=w.length,y=w.slice(0,5).map(m=>({tag:m.tag,id:m.id,class:m.className,text:m.text}));return{count:x,sample:y,error:null}}',
1361
+ "countXPathMatchesMainWorld": "function We(e){return I(e,{pierceShadow:!0})}",
1362
+ "dispatchDomClick": 'function ue(e){let t=e??{};try{let n=new MouseEvent("click",{bubbles:!!t.bubbles,cancelable:!!t.cancelable,composed:!!t.composed,detail:typeof t.detail=="number"?t.detail:1,view:this?.ownerDocument?.defaultView??window});this.dispatchEvent(n)}catch{try{this.click()}catch{}}}',
1363
+ "ensureFileInputElement": 'function ae(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}',
1364
+ "fillElementValue": 'function me(e){let t=this;if(!t.isConnected)return{status:"error",reason:"notconnected"};let o=(t.ownerDocument||document).defaultView||window,r=e??"";try{let l=s=>{let i;if(typeof o.InputEvent=="function")try{i=new o.InputEvent("input",{bubbles:!0,composed:!0,data:s,inputType:"insertText"})}catch{i=new o.Event("input",{bubbles:!0,composed:!0})}else i=new o.Event("input",{bubbles:!0,composed:!0});t.dispatchEvent(i);let a=new o.Event("change",{bubbles:!0});t.dispatchEvent(a)};if(t instanceof o.HTMLInputElement){let s=(t.type||"").toLowerCase();if(!Y.has(s)&&!D.has(s))return{status:"error",reason:`unsupported-input-type:${s}`};let i=e;if(s==="number"){let a=e.trim();if(a!==""&&Number.isNaN(Number(a)))return{status:"error",reason:"invalid-number-value"};i=a}if(r=i,D.has(s)){let a=e.trim();r=a,v.call(t);let d=o.HTMLInputElement.prototype,c=Object.getOwnPropertyDescriptor(d,"value")?.set;return typeof c=="function"?c.call(t,a):t.value=a,t._valueTracker?.setValue?.(a),t.value!==a?{status:"error",reason:"malformed-value"}:(l(a),{status:"done"})}return v.call(t),{status:"needsinput",value:i}}return t instanceof o.HTMLTextAreaElement?(v.call(t),r=e,{status:"needsinput",value:e}):t instanceof o.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:t.isContentEditable?(v.call(t),r=e,{status:"needsinput",value:e}):{status:"error",reason:"unsupported-element"}}catch(l){let s="exception";if(l&&typeof l=="object"){let i=l.message;typeof i=="string"&&i.trim().length>0&&(s=`exception:${i}`)}return{status:"needsinput",value:r,reason:s}}}',
1365
+ "focusElement": 'function fe(){try{typeof this.focus=="function"&&this.focus()}catch{}}',
1366
+ "isElementChecked": 'function ge(){try{let e=this;if((e.tagName||"").toLowerCase()==="input"){let o=e.type?.toLowerCase()??"";if(o==="checkbox"||o==="radio")return!!e.checked}let n=e.getAttribute?.("aria-checked");return n!=null?n==="true":!1}catch{return!1}}',
1367
+ "isElementVisible": 'function pe(){try{let e=this;if(!e.isConnected)return!1;let t=e.ownerDocument?.defaultView?.getComputedStyle(e)??window.getComputedStyle(e);if(!t||t.display==="none"||t.visibility==="hidden")return!1;let n=parseFloat(t.opacity??"1");if(!Number.isFinite(n)||n===0)return!1;let o=e.getBoundingClientRect();return!(!o||Math.max(o.width,o.height)===0||e.getClientRects().length===0)}catch{return!1}}',
1368
+ "prepareElementForTyping": 'function v(){try{let e=this;if(!e.isConnected)return!1;let t=e.ownerDocument||document,n=t.defaultView||window;try{typeof e.focus=="function"&&e.focus()}catch{}if(e instanceof n.HTMLInputElement||e instanceof n.HTMLTextAreaElement){try{if(typeof e.select=="function")return e.select(),!0}catch{}try{let o=(e.value??"").length;if(typeof e.setSelectionRange=="function")return e.setSelectionRange(0,o),!0}catch{}return!0}if(e.isContentEditable){let o=t.getSelection?.(),r=t.createRange?.();if(o&&r)try{r.selectNodeContents(e),o.removeAllRanges(),o.addRange(r)}catch{}return!0}return!1}catch{return!1}}',
1369
+ "readElementInnerHTML": 'function ye(){try{return String(this.innerHTML??"")}catch{return""}}',
1370
+ "readElementInnerText": 'function be(){try{let e=this,t=e.innerText;if(typeof t=="string"&&t.length>0)return t;let n=e.textContent;return typeof n=="string"?n:""}catch{return""}}',
1371
+ "readElementInputValue": 'function Ee(){try{let e=this,t=(e.tagName||"").toLowerCase();return t==="input"||t==="textarea"||t==="select"?String(e.value??""):e.isContentEditable?String(e.textContent??""):""}catch{return""}}',
1372
+ "readElementTextContent": 'function we(){try{return String(this.textContent??"")}catch{return""}}',
1373
+ "resolveCssSelector": 'function Ne(e,t){let n=String(e??"").trim();if(!n)return null;let o=C(t);return z(n,o+1)[o]??null}',
1374
+ "resolveCssSelectorPierce": 'function Ce(e,t){let n=String(e??"").trim();if(!n)return null;let o=C(t),r=window.__stagehandV3__;if(!r||typeof r.getClosedRoot!="function")return z(n,o+1)[o]??null;let l=c=>{try{return r.getClosedRoot(c)??null}catch{return null}},s=new WeakSet,i=new Set,a=[],d=[document],f=c=>{if(!(!c||s.has(c)||a.length>=o+1)){s.add(c);try{let p=c.querySelectorAll(n);for(let g of p)if(!i.has(g)&&(i.add(g),a.push(g),a.length>=o+1))return}catch{}try{let g=(c instanceof Document?c:c.host?.ownerDocument??document).createTreeWalker(c,NodeFilter.SHOW_ELEMENT),w;for(;w=g.nextNode();){if(!(w instanceof Element))continue;let x=w.shadowRoot;x&&d.push(x);let y=l(w);y&&d.push(y)}}catch{}}};for(;d.length&&a.length<o+1;){let c=d.shift();c&&f(c)}return a[o]??null}',
1375
+ "resolveTextSelector": 'function Me(e,t){let n=String(e??"");if(!n)return null;let o=n.toLowerCase(),r=C(t),l=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),s=u=>{if(!u)return!1;let h=u.tagName?.toUpperCase()??"";return l.has(h)},i=u=>{try{if(s(u))return"";let h=u.innerText;if(typeof h=="string"&&h.trim())return h.trim()}catch{}try{let h=u.textContent;if(typeof h=="string")return h.trim()}catch{}return""},a=u=>{let h=i(u);return!!h&&h.toLowerCase().includes(o)},d=window.__stagehandV3__,f=d&&typeof d.getClosedRoot=="function"?u=>{try{return d.getClosedRoot(u)??null}catch{return null}}:u=>null,c=new WeakSet,p=[],g=[],w=u=>{!u||c.has(u)||(c.add(u),p.push(u))},x=u=>{try{return(u instanceof Document?u:u?.ownerDocument??document).createTreeWalker(u,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(w(document);p.length;){let u=p.shift();if(!u)continue;u instanceof Element&&a(u)&&g.push({element:u,tag:u.tagName??"",id:u.id??"",className:u.className??"",text:i(u)});let h=x(u);if(!h)continue;let E;for(;E=h.nextNode();){if(!(E instanceof Element))continue;a(E)&&g.push({element:E,tag:E.tagName??"",id:E.id??"",className:E.className??"",text:i(E)});let b=E.shadowRoot;b&&w(b);let k=f(E);k&&w(k)}}let y=[];for(let u of g){let h=u.element,E=!1;for(let b of g)if(u!==b)try{if(h.contains(b.element)){E=!0;break}}catch{}E||y.push(u)}return y[r]?.element??null}',
1376
+ "resolveXPathMainWorld": "function Le(e,t){let n=C(t);return P(e,n,{pierceShadow:!0})}",
1377
+ "scrollElementToPercent": 'function de(e){let t=n=>{if(typeof n=="number"&&Number.isFinite(n))return n;let o=String(n??"").trim();if(!o)return 0;let r=parseFloat(o.replace("%",""));return Number.isNaN(r)||!Number.isFinite(r)?0:r};try{let n=Math.max(0,Math.min(t(e),100)),o=this,r=o.tagName?.toLowerCase()??"";if(r==="html"||r==="body"){let c=(o.ownerDocument?.scrollingElement||o.ownerDocument?.documentElement||o.ownerDocument?.body||document.scrollingElement||document.documentElement||document.body)?.scrollHeight??document.body.scrollHeight??0,p=o.ownerDocument?.defaultView?.innerHeight??window.innerHeight,w=Math.max(0,c-p)*(n/100);return o.ownerDocument?.defaultView?.scrollTo({top:w,left:o.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let s=o.scrollHeight??0,i=o.clientHeight??0,d=Math.max(0,s-i)*(n/100);return o.scrollTo({top:d,left:o.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}',
1378
+ "selectElementOptions": 'function he(e){try{if(!(this instanceof HTMLSelectElement))return[];let t=Array.isArray(e)?e:[e],n=new Set(t.map(s=>String(s??"").trim())),o=s=>{let i=(s.label||s.textContent||"").trim(),a=String(s.value??"").trim();return n.has(i)||n.has(a)};if(this.multiple)for(let s of Array.from(this.options))s.selected=o(s);else{let s=!1;for(let i of Array.from(this.options))!s&&o(i)?(i.selected=!0,this.value=i.value,s=!0):i.selected=!1}let r=new Event("input",{bubbles:!0}),l=new Event("change",{bubbles:!0});return this.dispatchEvent(r),this.dispatchEvent(l),Array.from(this.selectedOptions).map(s=>s.value)}catch{return[]}}',
1379
+ "waitForSelector": 'function qe(e,t,n,o){let r=String(e??"").trim(),l=String(t??"visible")||"visible",s=typeof n=="number"&&n>0?n:3e4,i=o!==!1;return new Promise((a,d)=>{let f=null,c=null,p=!1,g=()=>{f!==null&&(clearTimeout(f),f=null)},w=V(r,i);if(B(w,l)){p=!0,a(!0);return}let x=[],y=()=>{for(let E of x)E.disconnect();c&&(document.removeEventListener("DOMContentLoaded",c),c=null)},m=()=>{if(p)return;let E=V(r,i);B(E,l)&&(p=!0,g(),y(),a(!0))};if(!(document.body||document.documentElement)){c=()=>{document.removeEventListener("DOMContentLoaded",c),c=null,m(),h()},document.addEventListener("DOMContentLoaded",c),f=setTimeout(()=>{p||(p=!0,g(),y(),d(new Error(`waitForSelector: Timeout ${s}ms exceeded waiting for "${r}" to be ${l}`)))},s);return}let h=()=>{let E=document.body||document.documentElement;if(!E)return;let b=new MutationObserver(m);b.observe(E,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden","disabled"]}),x.push(b),i&&ie(m,x)};h(),f=setTimeout(()=>{p||(p=!0,g(),y(),d(new Error(`waitForSelector: Timeout ${s}ms exceeded waiting for "${r}" to be ${l}`)))},s)})}'
1373
1380
  };
1374
1381
  locatorScriptGlobalRefs = {
1375
1382
  "assignFilePayloadsToInputElement": "globalThis.__stagehandLocatorScripts.assignFilePayloadsToInputElement",
@@ -3761,7 +3768,9 @@ var init_locator = __esm({
3761
3768
  */
3762
3769
  fill(value) {
3763
3770
  return __async(this, null, function* () {
3771
+ var _a4, _b, _c;
3764
3772
  const session = this.frame.session;
3773
+ const fillDeclaration = `function(value) { ${locatorScriptBootstrap}; return ${locatorScriptGlobalRefs.fillElementValue}.call(this, value); }`;
3765
3774
  const { objectId } = yield this.resolveNode();
3766
3775
  let releaseNeeded = true;
3767
3776
  try {
@@ -3769,11 +3778,15 @@ var init_locator = __esm({
3769
3778
  "Runtime.callFunctionOn",
3770
3779
  {
3771
3780
  objectId,
3772
- functionDeclaration: locatorScriptSources.fillElementValue,
3781
+ functionDeclaration: fillDeclaration,
3773
3782
  arguments: [{ value }],
3774
3783
  returnByValue: true
3775
3784
  }
3776
3785
  );
3786
+ if (res.exceptionDetails) {
3787
+ const message = (_c = (_b = (_a4 = res.exceptionDetails.exception) == null ? void 0 : _a4.description) != null ? _b : res.exceptionDetails.text) != null ? _c : "Unknown exception during locator().fill()";
3788
+ throw new StagehandLocatorError("Filling", this.selector, message);
3789
+ }
3777
3790
  const result = res.result.value;
3778
3791
  const status = typeof result === "object" && result ? result.status : void 0;
3779
3792
  if (status === "done") {
@@ -24750,10 +24763,13 @@ var init_agent = __esm({
24750
24763
  "openai/computer-use-preview-2025-03-11",
24751
24764
  "anthropic/claude-3-7-sonnet-latest",
24752
24765
  "anthropic/claude-opus-4-5-20251101",
24766
+ "anthropic/claude-opus-4-6",
24753
24767
  "anthropic/claude-haiku-4-5-20251001",
24754
24768
  "anthropic/claude-sonnet-4-20250514",
24755
24769
  "anthropic/claude-sonnet-4-5-20250929",
24756
24770
  "google/gemini-2.5-computer-use-preview-10-2025",
24771
+ "google/gemini-3-flash-preview",
24772
+ "google/gemini-3-pro-preview",
24757
24773
  "microsoft/fara-7b"
24758
24774
  ];
24759
24775
  }
@@ -25962,10 +25978,10 @@ var init_page = __esm({
25962
25978
  });
25963
25979
 
25964
25980
  // examples/external_clients/aisdk.ts
25965
- var import_ai23, AISdkClient2;
25981
+ var import_ai24, AISdkClient2;
25966
25982
  var init_aisdk = __esm({
25967
25983
  "examples/external_clients/aisdk.ts"() {
25968
- import_ai23 = require("ai");
25984
+ import_ai24 = require("ai");
25969
25985
  init_LLMClient();
25970
25986
  AISdkClient2 = class extends LLMClient {
25971
25987
  constructor({ model }) {
@@ -26028,7 +26044,7 @@ var init_aisdk = __esm({
26028
26044
  }
26029
26045
  );
26030
26046
  if (options.response_model) {
26031
- const response2 = yield (0, import_ai23.generateObject)({
26047
+ const response2 = yield (0, import_ai24.generateObject)({
26032
26048
  model: this.model,
26033
26049
  messages: formattedMessages,
26034
26050
  schema: options.response_model.schema
@@ -26051,7 +26067,7 @@ var init_aisdk = __esm({
26051
26067
  inputSchema: rawTool.parameters
26052
26068
  };
26053
26069
  }
26054
- const response = yield (0, import_ai23.generateText)({
26070
+ const response = yield (0, import_ai24.generateText)({
26055
26071
  model: this.model,
26056
26072
  messages: formattedMessages,
26057
26073
  tools
@@ -28075,6 +28091,11 @@ var init_page2 = __esm({
28075
28091
  yield Promise.all(installs);
28076
28092
  });
28077
28093
  }
28094
+ // Seed an init script without re-installing it on the current sessions.
28095
+ seedInitScript(source) {
28096
+ if (this.initScripts.includes(source)) return;
28097
+ this.initScripts.push(source);
28098
+ }
28078
28099
  ensureCursorScript() {
28079
28100
  return __async(this, null, function* () {
28080
28101
  const script = `(() => {
@@ -28426,9 +28447,7 @@ var init_page2 = __esm({
28426
28447
  * );
28427
28448
  */
28428
28449
  sendCDP(method, params) {
28429
- return __async(this, null, function* () {
28430
- return this.mainSession.send(method, params);
28431
- });
28450
+ return this.mainSession.send(method, params);
28432
28451
  }
28433
28452
  /** Seed the cached URL before navigation events converge. */
28434
28453
  seedCurrentUrl(url) {
@@ -29759,6 +29778,7 @@ __export(v3_exports, {
29759
29778
  StagehandIframeError: () => StagehandIframeError,
29760
29779
  StagehandInitError: () => StagehandInitError,
29761
29780
  StagehandInvalidArgumentError: () => StagehandInvalidArgumentError,
29781
+ StagehandLocatorError: () => StagehandLocatorError,
29762
29782
  StagehandMissingArgumentError: () => StagehandMissingArgumentError,
29763
29783
  StagehandNotInitializedError: () => StagehandNotInitializedError,
29764
29784
  StagehandResponseBodyError: () => StagehandResponseBodyError,
@@ -29794,7 +29814,7 @@ __export(v3_exports, {
29794
29814
  providerEnvVarMap: () => providerEnvVarMap,
29795
29815
  toGeminiSchema: () => toGeminiSchema,
29796
29816
  toJsonSchema: () => toJsonSchema,
29797
- tool: () => import_ai24.tool,
29817
+ tool: () => import_ai25.tool,
29798
29818
  transformSchema: () => transformSchema,
29799
29819
  trimTrailingTextNode: () => trimTrailingTextNode,
29800
29820
  validateZodSchema: () => validateZodSchema
@@ -33278,11 +33298,14 @@ var actTool = (v3, executionModel) => (0, import_ai2.tool)({
33278
33298
  actionDescription: result.actionDescription,
33279
33299
  message: result.message
33280
33300
  });
33281
- return {
33301
+ const response = {
33282
33302
  success: (_b = result.success) != null ? _b : true,
33283
- action: (_c = result == null ? void 0 : result.actionDescription) != null ? _c : action,
33284
- playwrightArguments: actions.length > 0 ? actions[0] : void 0
33303
+ action: (_c = result == null ? void 0 : result.actionDescription) != null ? _c : action
33285
33304
  };
33305
+ if (actions.length > 0) {
33306
+ response.playwrightArguments = actions[0];
33307
+ }
33308
+ return response;
33286
33309
  } catch (error) {
33287
33310
  return { success: false, error: (_d2 = error == null ? void 0 : error.message) != null ? _d2 : String(error) };
33288
33311
  }
@@ -33528,7 +33551,10 @@ var scrollTool = (v3) => (0, import_ai8.tool)({
33528
33551
  direction: import_zod12.z.enum(["up", "down"]),
33529
33552
  percentage: import_zod12.z.number().min(1).max(200).optional()
33530
33553
  }),
33531
- execute: (_0) => __async(null, [_0], function* ({ direction, percentage = 80 }) {
33554
+ execute: (_0) => __async(null, [_0], function* ({
33555
+ direction,
33556
+ percentage = 80
33557
+ }) {
33532
33558
  v3.logger({
33533
33559
  category: "agent",
33534
33560
  message: `Agent calling tool: scroll`,
@@ -33558,7 +33584,17 @@ var scrollTool = (v3) => (0, import_ai8.tool)({
33558
33584
  message: `Scrolled ${percentage}% ${direction} (${scrollDistance}px)`,
33559
33585
  scrolledPixels: scrollDistance
33560
33586
  };
33561
- })
33587
+ }),
33588
+ toModelOutput: (result) => {
33589
+ return {
33590
+ type: "json",
33591
+ value: {
33592
+ success: result.success,
33593
+ message: result.message,
33594
+ scrolledPixels: result.scrolledPixels
33595
+ }
33596
+ };
33597
+ }
33562
33598
  });
33563
33599
  var scrollVisionTool = (v3, provider) => (0, import_ai8.tool)({
33564
33600
  description: `Scroll the page up or down. For general page scrolling, no coordinates needed. Only provide coordinates when scrolling inside a nested scrollable element (e.g., a dropdown menu, modal with overflow, or scrollable sidebar). Default is 80%, and what should be typically used for general page scrolling`,
@@ -34739,55 +34775,52 @@ function processMessages(messages) {
34739
34775
  }
34740
34776
  return compressedCount;
34741
34777
  }
34778
+ function isContentTypeOutput(output) {
34779
+ return output.type === "content";
34780
+ }
34742
34781
  function compressScreenshotMessage(message) {
34743
- var _a4;
34744
34782
  for (const part of message.content) {
34745
34783
  if (isScreenshotPart(part)) {
34746
34784
  const typedPart = part;
34747
- const placeholder = [{ type: "text", text: "screenshot taken" }];
34748
- if ((_a4 = typedPart.output) == null ? void 0 : _a4.value) {
34749
- typedPart.output.value = placeholder;
34750
- }
34751
- if (typedPart.result) {
34752
- typedPart.result = placeholder;
34785
+ if (typedPart.output && isContentTypeOutput(typedPart.output)) {
34786
+ typedPart.output = {
34787
+ type: "content",
34788
+ value: [{ type: "text", text: "screenshot taken" }]
34789
+ };
34753
34790
  }
34754
34791
  }
34755
34792
  }
34756
34793
  }
34757
34794
  function compressVisionActionMessage(message) {
34758
- var _a4;
34759
34795
  for (const part of message.content) {
34760
34796
  if (isVisionActionPart(part)) {
34761
34797
  const typedPart = part;
34762
- if (((_a4 = typedPart.output) == null ? void 0 : _a4.value) && Array.isArray(typedPart.output.value)) {
34763
- typedPart.output.value = typedPart.output.value.filter(
34764
- (item) => item && typeof item === "object" && item.type !== "media"
34765
- );
34766
- }
34767
- if (typedPart.result && Array.isArray(typedPart.result)) {
34768
- typedPart.result = typedPart.result.filter(
34798
+ if (typedPart.output && isContentTypeOutput(typedPart.output) && Array.isArray(typedPart.output.value)) {
34799
+ const filteredValue = typedPart.output.value.filter(
34769
34800
  (item) => item && typeof item === "object" && item.type !== "media"
34770
34801
  );
34802
+ typedPart.output = {
34803
+ type: "content",
34804
+ value: filteredValue
34805
+ };
34771
34806
  }
34772
34807
  }
34773
34808
  }
34774
34809
  }
34775
34810
  function compressAriaTreeMessage(message) {
34776
- var _a4;
34777
34811
  for (const part of message.content) {
34778
34812
  if (isAriaTreePart(part)) {
34779
34813
  const typedPart = part;
34780
- const placeholder = [
34781
- {
34782
- type: "text",
34783
- text: "ARIA tree extracted for context of page elements"
34784
- }
34785
- ];
34786
- if ((_a4 = typedPart.output) == null ? void 0 : _a4.value) {
34787
- typedPart.output.value = placeholder;
34788
- }
34789
- if (typedPart.result) {
34790
- typedPart.result = placeholder;
34814
+ if (typedPart.output && isContentTypeOutput(typedPart.output)) {
34815
+ typedPart.output = {
34816
+ type: "content",
34817
+ value: [
34818
+ {
34819
+ type: "text",
34820
+ text: "ARIA tree extracted for context of page elements"
34821
+ }
34822
+ ]
34823
+ };
34791
34824
  }
34792
34825
  }
34793
34826
  }
@@ -34984,6 +35017,20 @@ Call the "done" tool with:
34984
35017
  function getErrorMessage(error) {
34985
35018
  return error instanceof Error ? error.message : String(error);
34986
35019
  }
35020
+ function prependSystemMessage(systemPrompt, messages) {
35021
+ return [
35022
+ {
35023
+ role: "system",
35024
+ content: systemPrompt,
35025
+ providerOptions: {
35026
+ anthropic: {
35027
+ cacheControl: { type: "ephemeral" }
35028
+ }
35029
+ }
35030
+ },
35031
+ ...messages
35032
+ ];
35033
+ }
34987
35034
  var V3AgentHandler = class {
34988
35035
  constructor(v3, logger, llmClient, executionModel, systemInstructions, mcpTools, mode) {
34989
35036
  this.v3 = v3;
@@ -35163,8 +35210,7 @@ var V3AgentHandler = class {
35163
35210
  }
35164
35211
  const result = yield this.llmClient.generateText({
35165
35212
  model: wrappedModel,
35166
- system: systemPrompt,
35167
- messages,
35213
+ messages: prependSystemMessage(systemPrompt, messages),
35168
35214
  tools: allTools,
35169
35215
  stopWhen: (result2) => this.handleStop(result2, maxSteps),
35170
35216
  temperature: 1,
@@ -35264,8 +35310,7 @@ var V3AgentHandler = class {
35264
35310
  };
35265
35311
  const streamResult = this.llmClient.streamText({
35266
35312
  model: wrappedModel,
35267
- system: systemPrompt,
35268
- messages,
35313
+ messages: prependSystemMessage(systemPrompt, messages),
35269
35314
  tools: allTools,
35270
35315
  stopWhen: (result) => this.handleStop(result, maxSteps),
35271
35316
  temperature: 1,
@@ -38444,8 +38489,11 @@ var modelToAgentProviderMap = {
38444
38489
  "claude-sonnet-4-20250514": "anthropic",
38445
38490
  "claude-sonnet-4-5-20250929": "anthropic",
38446
38491
  "claude-opus-4-5-20251101": "anthropic",
38492
+ "claude-opus-4-6": "anthropic",
38447
38493
  "claude-haiku-4-5-20251001": "anthropic",
38448
38494
  "gemini-2.5-computer-use-preview-10-2025": "google",
38495
+ "gemini-3-flash-preview": "google",
38496
+ "gemini-3-pro-preview": "google",
38449
38497
  "fara-7b": "microsoft"
38450
38498
  };
38451
38499
  var AgentProvider = class _AgentProvider {
@@ -40289,7 +40337,11 @@ var AISdkClient = class extends LLMClient {
40289
40337
  );
40290
40338
  let objectResponse;
40291
40339
  const isGPT5 = this.model.modelId.includes("gpt-5");
40292
- const usesLowReasoningEffort = this.model.modelId.includes("gpt-5.1") || this.model.modelId.includes("gpt-5.2");
40340
+ const isCodex = this.model.modelId.includes("codex");
40341
+ const usesLowReasoningEffort = (this.model.modelId.includes("gpt-5.1") || this.model.modelId.includes("gpt-5.2")) && !isCodex;
40342
+ const isDeepSeek = this.model.modelId.includes("deepseek");
40343
+ const isKimi = this.model.modelId.includes("kimi");
40344
+ const temperature = isKimi ? 1 : options.temperature;
40293
40345
  if (options.response_model) {
40294
40346
  const llmRequestId2 = (0, import_uuid5.v7)();
40295
40347
  const promptPreview2 = formatLlmPromptPreview(options.messages, {
@@ -40301,8 +40353,7 @@ var AISdkClient = class extends LLMClient {
40301
40353
  operation: "generateObject",
40302
40354
  prompt: promptPreview2
40303
40355
  });
40304
- const isDeepSeek = this.model.modelId.includes("deepseek");
40305
- if (isDeepSeek) {
40356
+ if (isDeepSeek || isKimi) {
40306
40357
  const parsedSchema = JSON.stringify(
40307
40358
  toJsonSchema(options.response_model.schema)
40308
40359
  );
@@ -40319,12 +40370,12 @@ You must respond in JSON format. respond WITH JSON. Do not include any other tex
40319
40370
  model: this.model,
40320
40371
  messages: formattedMessages,
40321
40372
  schema: options.response_model.schema,
40322
- temperature: options.temperature,
40373
+ temperature,
40323
40374
  providerOptions: isGPT5 ? {
40324
40375
  openai: {
40325
- textVerbosity: "low",
40326
- // Making these the default for gpt-5 for now
40327
- reasoningEffort: usesLowReasoningEffort ? "low" : "minimal"
40376
+ textVerbosity: isCodex ? "medium" : "low",
40377
+ // codex models only support 'medium'
40378
+ reasoningEffort: isCodex ? "medium" : usesLowReasoningEffort ? "low" : "minimal"
40328
40379
  }
40329
40380
  } : void 0
40330
40381
  });
@@ -40438,7 +40489,7 @@ You must respond in JSON format. respond WITH JSON. Do not include any other tex
40438
40489
  messages: formattedMessages,
40439
40490
  tools: Object.keys(tools).length > 0 ? tools : void 0,
40440
40491
  toolChoice: Object.keys(tools).length > 0 ? options.tool_choice === "required" ? "required" : options.tool_choice === "none" ? "none" : "auto" : void 0,
40441
- temperature: options.temperature
40492
+ temperature
40442
40493
  });
40443
40494
  } catch (err) {
40444
40495
  SessionFileLogger.logLlmResponse({
@@ -72767,6 +72818,7 @@ function createOllama(options = {}) {
72767
72818
  var ollama = createOllama();
72768
72819
 
72769
72820
  // lib/v3/llm/LLMProvider.ts
72821
+ var import_ai23 = require("ai");
72770
72822
  var AISDKProviders = {
72771
72823
  openai,
72772
72824
  bedrock,
@@ -72781,7 +72833,8 @@ var AISDKProviders = {
72781
72833
  deepseek,
72782
72834
  perplexity,
72783
72835
  ollama,
72784
- vertex
72836
+ vertex,
72837
+ gateway: import_ai23.gateway
72785
72838
  };
72786
72839
  var AISDKProvidersWithAPIKey = {
72787
72840
  openai: createOpenAI,
@@ -72797,7 +72850,8 @@ var AISDKProvidersWithAPIKey = {
72797
72850
  mistral: createMistral,
72798
72851
  deepseek: createDeepSeek,
72799
72852
  perplexity: createPerplexity,
72800
- ollama: createOllama
72853
+ ollama: createOllama,
72854
+ gateway: import_ai23.createGateway
72801
72855
  };
72802
72856
  var modelToProviderMap = {
72803
72857
  "gpt-4.1": "openai",
@@ -73027,6 +73081,7 @@ init_logger();
73027
73081
 
73028
73082
  // lib/v3/understudy/cdp.ts
73029
73083
  var import_ws = __toESM(require("ws"));
73084
+ init_version();
73030
73085
  var CdpConnection = class _CdpConnection {
73031
73086
  constructor(ws) {
73032
73087
  this.nextId = 1;
@@ -73066,7 +73121,11 @@ var CdpConnection = class _CdpConnection {
73066
73121
  }
73067
73122
  static connect(wsUrl) {
73068
73123
  return __async(this, null, function* () {
73069
- const ws = new import_ws.default(wsUrl);
73124
+ const ws = new import_ws.default(wsUrl, {
73125
+ headers: {
73126
+ "User-Agent": `Stagehand/${STAGEHAND_VERSION}`
73127
+ }
73128
+ });
73070
73129
  yield new Promise((resolve4, reject) => {
73071
73130
  ws.once("open", () => resolve4());
73072
73131
  ws.once("error", (e2) => reject(e2));
@@ -73079,12 +73138,7 @@ var CdpConnection = class _CdpConnection {
73079
73138
  yield this.send("Target.setAutoAttach", {
73080
73139
  autoAttach: true,
73081
73140
  flatten: true,
73082
- waitForDebuggerOnStart: false,
73083
- filter: [
73084
- { type: "worker", exclude: true },
73085
- { type: "shared_worker", exclude: true },
73086
- { type: "service_worker", exclude: true }
73087
- ]
73141
+ waitForDebuggerOnStart: true
73088
73142
  });
73089
73143
  yield this.send("Target.setDiscoverTargets", { discover: true });
73090
73144
  });
@@ -73106,6 +73160,8 @@ var CdpConnection = class _CdpConnection {
73106
73160
  ts: Date.now()
73107
73161
  });
73108
73162
  });
73163
+ void p.catch(() => {
73164
+ });
73109
73165
  (_b = this.cdpLogger) == null ? void 0 : _b.call(this, { method, params, targetId: null });
73110
73166
  this.ws.send(JSON.stringify(payload));
73111
73167
  return p;
@@ -73221,6 +73277,8 @@ var CdpConnection = class _CdpConnection {
73221
73277
  ts: Date.now()
73222
73278
  });
73223
73279
  });
73280
+ void p.catch(() => {
73281
+ });
73224
73282
  const targetId = (_b = this.sessionToTarget.get(sessionId)) != null ? _b : null;
73225
73283
  (_c = this.cdpLogger) == null ? void 0 : _c.call(this, { method, params, targetId });
73226
73284
  this.ws.send(JSON.stringify(payload));
@@ -73277,7 +73335,7 @@ init_page2();
73277
73335
  init_logger();
73278
73336
 
73279
73337
  // lib/v3/dom/build/scriptV3Content.ts
73280
- var v3ScriptContent = '(()=>{function b(_={}){let S=n=>{let{hostToRoot:l}=n,m=t=>{let o=[];if(t instanceof Document)return t.documentElement&&o.push(t.documentElement),o;if(t instanceof ShadowRoot||t instanceof DocumentFragment)return o.push(...Array.from(t.children)),o;if(t instanceof Element){o.push(...Array.from(t.children));let a=t.shadowRoot;a&&o.push(...Array.from(a.children));let r=l.get(t);return r&&o.push(...Array.from(r.children)),o}return o},v=t=>{let o=[],a=[...m(t)];for(;a.length;){let r=a.shift();o.push(r),a.push(...m(r))}return o},y=t=>{let o=String(t||"").trim();if(!o)return null;let a=o.replace(/^xpath=/i,""),r=[];{let e=0;for(;e<a.length;){let d="child";a.startsWith("//",e)?(d="desc",e+=2):a[e]==="/"&&(d="child",e+=1);let h=e;for(;e<a.length&&a[e]!=="/";)e++;let u=a.slice(h,e).trim();if(!u)continue;let p=u.match(/^(.*?)(\\[(\\d+)\\])?$/u),i=(p?.[1]??u).trim(),c=p?.[3]?Math.max(1,Number(p[3])):null,R=i===""?"*":i.toLowerCase();r.push({axis:d,raw:u,tag:R,index:c})}}n.debug&&console.info("[v3-piercer][resolve] start",{url:location.href,steps:r.map(e=>({axis:e.axis,raw:e.raw,tag:e.tag,index:e.index}))});let g=[document];for(let e of r){let d=e.index,h=null;for(let u of g){let p=e.axis==="child"?m(u):v(u),i=[];for(let c of p)(e.tag==="*"||c.localName===e.tag)&&i.push(c);if(n.debug&&console.info("[v3-piercer][resolve] step",{axis:e.axis,tag:e.tag,index:d,poolCount:p.length,matchesCount:i.length}),!!i.length){if(d!=null){let c=d-1;h=c>=0&&c<i.length?i[c]:null}else h=i[0];if(h)break}}if(!h)return n.debug&&console.info("[v3-piercer][resolve] no-match",{step:e.raw}),null;g=[h]}let E=g.length?g[0]:null;return n.debug&&console.info("[v3-piercer][resolve] done",{found:!!E,tag:E?.localName??""}),E};window.__stagehandV3__={getClosedRoot:t=>l.get(t),stats:()=>({installed:!0,url:location.href,isTop:window.top===window,open:n.openCount,closed:n.closedCount}),resolveSimpleXPath:y}},f=Element.prototype.attachShadow;if(f.__v3Patched&&f.__v3State){f.__v3State.debug=!0,S(f.__v3State);return}let s={hostToRoot:new WeakMap,openCount:0,closedCount:0,debug:!0},x=f,w=function(n){let l=n?.mode??"open",m=x.call(this,n);try{s.hostToRoot.set(this,m),l==="closed"?s.closedCount++:s.openCount++,s.debug&&console.info("[v3-piercer] attachShadow",{tag:this.tagName?.toLowerCase()??"",mode:l,url:location.href})}catch{}return m};if(w.__v3Patched=!0,w.__v3State=s,Object.defineProperty(Element.prototype,"attachShadow",{configurable:!0,writable:!0,value:w}),_.tagExisting)try{let n=document.createTreeWalker(document,NodeFilter.SHOW_ELEMENT);for(;n.nextNode();){let l=n.currentNode;l.shadowRoot&&(s.hostToRoot.set(l,l.shadowRoot),s.openCount++)}}catch{}window.__stagehandV3Injected=!0,S(s),s.debug&&console.info("[v3-piercer] installed",{url:location.href,isTop:window.top===window,readyState:document.readyState})}b({debug:!0,tagExisting:!1});})();\n';
73338
+ var v3ScriptContent = '(()=>{function s(c={}){let r=e=>{let{hostToRoot:o}=e;window.__stagehandV3__={getClosedRoot:a=>o.get(a),stats:()=>({installed:!0,url:location.href,isTop:window.top===window,open:e.openCount,closed:e.closedCount})}},n=Element.prototype.attachShadow;if(n.__v3Patched&&n.__v3State){n.__v3State.debug=!0,r(n.__v3State);return}let t={hostToRoot:new WeakMap,openCount:0,closedCount:0,debug:!0},l=n,d=function(e){let o=e?.mode??"open",a=l.call(this,e);try{t.hostToRoot.set(this,a),o==="closed"?t.closedCount++:t.openCount++,t.debug&&console.info("[v3-piercer] attachShadow",{tag:this.tagName?.toLowerCase()??"",mode:o,url:location.href})}catch{}return a};if(d.__v3Patched=!0,d.__v3State=t,Object.defineProperty(Element.prototype,"attachShadow",{configurable:!0,writable:!0,value:d}),c.tagExisting)try{let e=document.createTreeWalker(document,NodeFilter.SHOW_ELEMENT);for(;e.nextNode();){let o=e.currentNode;o.shadowRoot&&(t.hostToRoot.set(o,o.shadowRoot),t.openCount++)}}catch{}window.__stagehandV3Injected=!0,r(t),t.debug&&console.info("[v3-piercer] installed",{url:location.href,isTop:window.top===window,readyState:document.readyState})}s({debug:!0,tagExisting:!1});})();\n';
73281
73339
 
73282
73340
  // lib/v3/dom/build/reRenderScriptContent.ts
73283
73341
  var reRenderScriptContent = '(()=>{function s(){try{let o=window.__stagehandV3__;if(!o||typeof o.getClosedRoot!="function")return;let t=[],r=document.createTreeWalker(document,NodeFilter.SHOW_ELEMENT);for(;r.nextNode();){let e=r.currentNode,n=e.tagName?.toLowerCase()??"";if(!n.includes("-")||typeof customElements?.get!="function"||!customElements.get(n))continue;let c=!!e.shadowRoot,i=!!o.getClosedRoot(e);c||i||t.push(e)}for(let e of t)try{let n=e.cloneNode(!0);e.replaceWith(n)}catch{}o.stats&&t.length&&console.info("[v3-piercer] rerender",{count:t.length})}catch(o){console.info("[v3-piercer] rerender error",{message:String(o??"")})}}s();})();\n';
@@ -73332,6 +73390,7 @@ var V3Context = class _V3Context {
73332
73390
  this._piercerInstalled = /* @__PURE__ */ new Set();
73333
73391
  // Timestamp for most recent popup/open signal
73334
73392
  this._lastPopupSignalAt = 0;
73393
+ this._targetSessionListeners = /* @__PURE__ */ new Set();
73335
73394
  this._sessionInit = /* @__PURE__ */ new Set();
73336
73395
  this.pagesByTarget = /* @__PURE__ */ new Map();
73337
73396
  this.mainFrameToTarget = /* @__PURE__ */ new Map();
@@ -73344,9 +73403,30 @@ var V3Context = class _V3Context {
73344
73403
  this.pendingCreatedTargetUrl = /* @__PURE__ */ new Map();
73345
73404
  this.initScripts = [];
73346
73405
  }
73347
- sessionKey(session) {
73348
- var _a4;
73349
- return (_a4 = session.id) != null ? _a4 : "root";
73406
+ installTargetSessionListeners(session) {
73407
+ const sessionId = session.id;
73408
+ if (!sessionId) return;
73409
+ if (this._targetSessionListeners.has(sessionId)) return;
73410
+ this._targetSessionListeners.add(sessionId);
73411
+ session.on(
73412
+ "Target.attachedToTarget",
73413
+ (evt) => {
73414
+ void this.onAttachedToTarget(evt.targetInfo, evt.sessionId);
73415
+ }
73416
+ );
73417
+ session.on(
73418
+ "Target.detachedFromTarget",
73419
+ (evt) => {
73420
+ var _a4;
73421
+ this.onDetachedFromTarget(evt.sessionId, (_a4 = evt.targetId) != null ? _a4 : null);
73422
+ }
73423
+ );
73424
+ session.on(
73425
+ "Target.targetDestroyed",
73426
+ (evt) => {
73427
+ this.cleanupByTarget(evt.targetId);
73428
+ }
73429
+ );
73350
73430
  }
73351
73431
  /**
73352
73432
  * Create a Context for a given CDP websocket URL and bootstrap target wiring.
@@ -73419,11 +73499,12 @@ var V3Context = class _V3Context {
73419
73499
  }
73420
73500
  ensurePiercer(session) {
73421
73501
  return __async(this, null, function* () {
73422
- const key = this.sessionKey(session);
73423
- if (this._piercerInstalled.has(key)) return true;
73502
+ var _a4;
73503
+ const id = (_a4 = session.id) != null ? _a4 : "";
73504
+ if (this._piercerInstalled.has(id)) return true;
73424
73505
  const installed = yield installV3PiercerIntoSession(session);
73425
73506
  if (installed) {
73426
- this._piercerInstalled.add(key);
73507
+ this._piercerInstalled.add(id);
73427
73508
  }
73428
73509
  return installed;
73429
73510
  });
@@ -73484,6 +73565,7 @@ var V3Context = class _V3Context {
73484
73565
  addInitScript(script, arg) {
73485
73566
  return __async(this, null, function* () {
73486
73567
  const source = yield normalizeInitScriptSource(script, arg);
73568
+ if (this.initScripts.includes(source)) return;
73487
73569
  this.initScripts.push(source);
73488
73570
  const pages = this.pages();
73489
73571
  yield Promise.all(pages.map((page) => page.registerInitScript(source)));
@@ -73503,8 +73585,14 @@ var V3Context = class _V3Context {
73503
73585
  rows.sort((a, b) => a.created - b.created);
73504
73586
  return rows.map((r2) => r2.page);
73505
73587
  }
73506
- applyInitScriptsToPage(page) {
73588
+ applyInitScriptsToPage(page, opts) {
73507
73589
  return __async(this, null, function* () {
73590
+ if (opts == null ? void 0 : opts.seedOnly) {
73591
+ for (const source of this.initScripts) {
73592
+ page.seedInitScript(source);
73593
+ }
73594
+ return;
73595
+ }
73508
73596
  for (const source of this.initScripts) {
73509
73597
  yield page.registerInitScript(source);
73510
73598
  }
@@ -73534,17 +73622,26 @@ var V3Context = class _V3Context {
73534
73622
  */
73535
73623
  newPage(url = "about:blank") {
73536
73624
  return __async(this, null, function* () {
73625
+ const targetUrl = String(url != null ? url : "about:blank");
73537
73626
  const { targetId } = yield this.conn.send(
73538
73627
  "Target.createTarget",
73539
- { url }
73628
+ // Create at about:blank so init scripts can install before first real navigation.
73629
+ { url: "about:blank" }
73540
73630
  );
73541
- this.pendingCreatedTargetUrl.set(targetId, url);
73631
+ this.pendingCreatedTargetUrl.set(targetId, "about:blank");
73542
73632
  yield this.conn.send("Target.activateTarget", { targetId }).catch(() => {
73543
73633
  });
73544
73634
  const deadline = Date.now() + 5e3;
73545
73635
  while (Date.now() < deadline) {
73546
73636
  const page = this.pagesByTarget.get(targetId);
73547
- if (page) return page;
73637
+ if (page) {
73638
+ if (targetUrl !== "about:blank") {
73639
+ page.seedCurrentUrl(targetUrl);
73640
+ void page.sendCDP("Page.navigate", { url: targetUrl }).catch(() => {
73641
+ });
73642
+ }
73643
+ return page;
73644
+ }
73548
73645
  yield new Promise((r2) => setTimeout(r2, 25));
73549
73646
  }
73550
73647
  throw new TimeoutError(`newPage: target not attached (${targetId})`, 5e3);
@@ -73569,7 +73666,6 @@ var V3Context = class _V3Context {
73569
73666
  /**
73570
73667
  * Bootstrap target lifecycle:
73571
73668
  * - Attach to existing targets.
73572
- * - Attach on `Target.targetCreated` (fallback for OOPIFs).
73573
73669
  * - Handle auto-attach events.
73574
73670
  * - Clean up on detach/destroy.
73575
73671
  */
@@ -73598,17 +73694,10 @@ var V3Context = class _V3Context {
73598
73694
  "Target.targetCreated",
73599
73695
  (evt) => __async(this, null, function* () {
73600
73696
  const info = evt.targetInfo;
73601
- if (info.type === "worker" || info.type === "service_worker" || info.type === "shared_worker") {
73602
- return;
73603
- }
73604
73697
  const ti = info;
73605
73698
  if (info.type === "page" && ((ti == null ? void 0 : ti.openerId) || (ti == null ? void 0 : ti.openerFrameId))) {
73606
73699
  this._notePopupSignal();
73607
73700
  }
73608
- try {
73609
- yield this.conn.attachToTarget(info.targetId);
73610
- } catch (e2) {
73611
- }
73612
73701
  })
73613
73702
  );
73614
73703
  yield this.conn.enableAutoAttach();
@@ -73635,74 +73724,142 @@ var V3Context = class _V3Context {
73635
73724
  onAttachedToTarget(info, sessionId) {
73636
73725
  return __async(this, null, function* () {
73637
73726
  var _a4;
73727
+ if (info.type === "worker" || info.type === "service_worker" || info.type === "shared_worker") {
73728
+ const session2 = this.conn.getSession(sessionId);
73729
+ if (session2) {
73730
+ yield session2.send("Runtime.runIfWaitingForDebugger").catch(() => {
73731
+ });
73732
+ }
73733
+ return;
73734
+ }
73638
73735
  const session = this.conn.getSession(sessionId);
73639
73736
  if (!session) return;
73640
73737
  if (this._sessionInit.has(sessionId)) return;
73641
73738
  this._sessionInit.add(sessionId);
73642
- yield session.send("Runtime.runIfWaitingForDebugger").catch(() => {
73643
- });
73739
+ this.installTargetSessionListeners(session);
73644
73740
  executionContexts.attachSession(session);
73645
- const piercerReady = yield this.ensurePiercer(session);
73646
- if (!piercerReady) return;
73647
- yield session.send("Page.setLifecycleEventsEnabled", { enabled: true }).catch(() => {
73741
+ let resumed = false;
73742
+ const resume = () => __async(this, null, function* () {
73743
+ if (resumed) return;
73744
+ resumed = true;
73745
+ yield session.send("Runtime.runIfWaitingForDebugger").catch(() => {
73746
+ });
73648
73747
  });
73649
- if (isTopLevelPage(info)) {
73650
- const page = yield Page.create(
73651
- this.conn,
73652
- session,
73653
- info.targetId,
73654
- this.apiClient,
73655
- this.localBrowserLaunchOptions,
73656
- this.env === "BROWSERBASE"
73657
- );
73658
- this.wireSessionToOwnerPage(sessionId, page);
73659
- this.pagesByTarget.set(info.targetId, page);
73660
- this.mainFrameToTarget.set(page.mainFrameId(), info.targetId);
73661
- this.sessionOwnerPage.set(sessionId, page);
73662
- this.frameOwnerPage.set(page.mainFrameId(), page);
73663
- this.typeByTarget.set(info.targetId, "page");
73664
- if (!this.createdAtByTarget.has(info.targetId)) {
73665
- this.createdAtByTarget.set(info.targetId, Date.now());
73666
- }
73667
- const pendingSeedUrl = this.pendingCreatedTargetUrl.get(info.targetId);
73668
- this.pendingCreatedTargetUrl.delete(info.targetId);
73669
- page.seedCurrentUrl((_a4 = pendingSeedUrl != null ? pendingSeedUrl : info.url) != null ? _a4 : "");
73670
- this._pushActive(info.targetId);
73671
- this.installFrameEventBridges(sessionId, page);
73672
- yield this.applyInitScriptsToPage(page);
73673
- return;
73674
- }
73748
+ let scriptsInstalled = true;
73749
+ let piercerPreRegistered = false;
73750
+ const installPromises = [];
73675
73751
  try {
73676
- const { frameTree } = yield session.send(
73677
- "Page.getFrameTree"
73752
+ const send = (method, params) => session.send(method, params).catch(() => {
73753
+ });
73754
+ installPromises.push(send("Page.enable"));
73755
+ installPromises.push(send("Runtime.enable"));
73756
+ installPromises.push(
73757
+ session.send("Target.setAutoAttach", {
73758
+ autoAttach: true,
73759
+ waitForDebuggerOnStart: true,
73760
+ flatten: true
73761
+ }).catch(() => {
73762
+ })
73678
73763
  );
73679
- const childMainId = frameTree.frame.id;
73680
- let owner = this.frameOwnerPage.get(childMainId);
73681
- if (!owner) {
73682
- for (const p of this.pagesByTarget.values()) {
73683
- const tree = p.asProtocolFrameTree(p.mainFrameId());
73684
- const has = (function find(n) {
73685
- var _a5;
73686
- if (n.frame.id === childMainId) return true;
73687
- for (const c of (_a5 = n.childFrames) != null ? _a5 : []) if (find(c)) return true;
73688
- return false;
73689
- })(tree);
73690
- if (has) {
73691
- owner = p;
73692
- break;
73693
- }
73764
+ if (this.initScripts.length) {
73765
+ for (const source of this.initScripts) {
73766
+ installPromises.push(
73767
+ session.send("Page.addScriptToEvaluateOnNewDocument", {
73768
+ source,
73769
+ runImmediately: true
73770
+ })
73771
+ );
73694
73772
  }
73695
73773
  }
73696
- if (owner) {
73697
- owner.adoptOopifSession(session, childMainId);
73698
- this.sessionOwnerPage.set(sessionId, owner);
73699
- this.installFrameEventBridges(sessionId, owner);
73700
- void executionContexts.waitForMainWorld(session, childMainId).catch(() => {
73774
+ installPromises.push(
73775
+ session.send("Page.addScriptToEvaluateOnNewDocument", {
73776
+ source: v3ScriptContent,
73777
+ runImmediately: true
73778
+ }).then(() => {
73779
+ piercerPreRegistered = true;
73780
+ }).catch(() => {
73781
+ })
73782
+ );
73783
+ installPromises.push(resume());
73784
+ } catch (e2) {
73785
+ scriptsInstalled = false;
73786
+ }
73787
+ if (installPromises.length) {
73788
+ const results = yield Promise.allSettled(installPromises);
73789
+ if (results.some((r2) => r2.status === "rejected")) {
73790
+ scriptsInstalled = false;
73791
+ }
73792
+ }
73793
+ if (piercerPreRegistered) {
73794
+ this._piercerInstalled.add(sessionId);
73795
+ }
73796
+ try {
73797
+ const piercerReady = yield this.ensurePiercer(session);
73798
+ if (!piercerReady) return;
73799
+ yield session.send("Page.setLifecycleEventsEnabled", { enabled: true }).catch(() => {
73800
+ });
73801
+ if (isTopLevelPage(info)) {
73802
+ const page = yield Page.create(
73803
+ this.conn,
73804
+ session,
73805
+ info.targetId,
73806
+ this.apiClient,
73807
+ this.localBrowserLaunchOptions,
73808
+ this.env === "BROWSERBASE"
73809
+ );
73810
+ this.wireSessionToOwnerPage(sessionId, page);
73811
+ this.pagesByTarget.set(info.targetId, page);
73812
+ this.mainFrameToTarget.set(page.mainFrameId(), info.targetId);
73813
+ this.sessionOwnerPage.set(sessionId, page);
73814
+ this.frameOwnerPage.set(page.mainFrameId(), page);
73815
+ this.typeByTarget.set(info.targetId, "page");
73816
+ if (!this.createdAtByTarget.has(info.targetId)) {
73817
+ this.createdAtByTarget.set(info.targetId, Date.now());
73818
+ }
73819
+ const pendingSeedUrl = this.pendingCreatedTargetUrl.get(info.targetId);
73820
+ this.pendingCreatedTargetUrl.delete(info.targetId);
73821
+ page.seedCurrentUrl((_a4 = pendingSeedUrl != null ? pendingSeedUrl : info.url) != null ? _a4 : "");
73822
+ this._pushActive(info.targetId);
73823
+ this.installFrameEventBridges(sessionId, page);
73824
+ yield this.applyInitScriptsToPage(page, {
73825
+ seedOnly: scriptsInstalled
73701
73826
  });
73702
- } else {
73703
- this.pendingOopifByMainFrame.set(childMainId, sessionId);
73827
+ return;
73704
73828
  }
73705
- } catch (e2) {
73829
+ try {
73830
+ const { frameTree } = yield session.send(
73831
+ "Page.getFrameTree"
73832
+ );
73833
+ const childMainId = frameTree.frame.id;
73834
+ let owner = this.frameOwnerPage.get(childMainId);
73835
+ if (!owner) {
73836
+ for (const p of this.pagesByTarget.values()) {
73837
+ const tree = p.asProtocolFrameTree(p.mainFrameId());
73838
+ const has = (function find(n) {
73839
+ var _a5;
73840
+ if (n.frame.id === childMainId) return true;
73841
+ for (const c of (_a5 = n.childFrames) != null ? _a5 : []) if (find(c)) return true;
73842
+ return false;
73843
+ })(tree);
73844
+ if (has) {
73845
+ owner = p;
73846
+ break;
73847
+ }
73848
+ }
73849
+ }
73850
+ if (owner) {
73851
+ owner.adoptOopifSession(session, childMainId);
73852
+ this.sessionOwnerPage.set(sessionId, owner);
73853
+ this.installFrameEventBridges(sessionId, owner);
73854
+ void executionContexts.waitForMainWorld(session, childMainId).catch(() => {
73855
+ });
73856
+ } else {
73857
+ this.pendingOopifByMainFrame.set(childMainId, sessionId);
73858
+ }
73859
+ } catch (e2) {
73860
+ }
73861
+ } finally {
73862
+ yield resume();
73706
73863
  }
73707
73864
  });
73708
73865
  }
@@ -73726,6 +73883,9 @@ var V3Context = class _V3Context {
73726
73883
  )) {
73727
73884
  if (sid === sessionId) this.pendingOopifByMainFrame.delete(fid);
73728
73885
  }
73886
+ this._targetSessionListeners.delete(sessionId);
73887
+ this._sessionInit.delete(sessionId);
73888
+ this._piercerInstalled.delete(sessionId);
73729
73889
  }
73730
73890
  /**
73731
73891
  * Cleanup a top-level Page by target id, removing its root and staged children.
@@ -74089,12 +74249,8 @@ var StagehandAPIClient = class {
74089
74249
  systemPrompt: agentConfig.systemPrompt,
74090
74250
  mode: (_b = agentConfig.mode) != null ? _b : agentConfig.cua === true ? "cua" : void 0,
74091
74251
  cua: agentConfig.mode === void 0 ? agentConfig.cua : void 0,
74092
- model: agentConfig.model ? this.prepareModelConfig(
74093
- agentConfig.model
74094
- ) : void 0,
74095
- executionModel: agentConfig.executionModel ? this.prepareModelConfig(
74096
- agentConfig.executionModel
74097
- ) : void 0
74252
+ model: agentConfig.model ? this.prepareModelConfig(agentConfig.model) : void 0,
74253
+ executionModel: agentConfig.executionModel ? this.prepareModelConfig(agentConfig.executionModel) : void 0
74098
74254
  };
74099
74255
  const requestBody = {
74100
74256
  agentConfig: wireAgentConfig,
@@ -76176,7 +76332,7 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
76176
76332
  };
76177
76333
 
76178
76334
  // lib/v3/index.ts
76179
- var import_ai24 = require("ai");
76335
+ var import_ai25 = require("ai");
76180
76336
 
76181
76337
  // lib/v3/cache/serverAgentCache.ts
76182
76338
  function getInternalField(instance, key) {
@@ -76275,6 +76431,7 @@ function __internalCreateInMemoryAgentCacheHandle(stagehand) {
76275
76431
  StagehandIframeError,
76276
76432
  StagehandInitError,
76277
76433
  StagehandInvalidArgumentError,
76434
+ StagehandLocatorError,
76278
76435
  StagehandMissingArgumentError,
76279
76436
  StagehandNotInitializedError,
76280
76437
  StagehandResponseBodyError,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@browserbasehq/orca",
3
- "version": "3.0.9-alpha-2",
3
+ "version": "3.0.9-alpha-4",
4
4
  "description": "An AI web browsing framework focused on simplicity and extensibility.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -47,9 +47,8 @@
47
47
  "@anthropic-ai/sdk": "0.39.0",
48
48
  "@browserbasehq/sdk": "^2.4.0",
49
49
  "@google/genai": "^1.22.0",
50
- "@langchain/openai": "^0.4.4",
51
50
  "@modelcontextprotocol/sdk": "^1.17.2",
52
- "ai": "^5.0.0",
51
+ "ai": "^5.0.133",
53
52
  "devtools-protocol": "^0.0.1464554",
54
53
  "fetch-cookie": "^3.1.0",
55
54
  "openai": "^4.87.1",
@@ -64,7 +63,7 @@
64
63
  "@ai-sdk/azure": "^2.0.54",
65
64
  "@ai-sdk/cerebras": "^1.0.25",
66
65
  "@ai-sdk/deepseek": "^1.0.23",
67
- "@ai-sdk/google": "^2.0.23",
66
+ "@ai-sdk/google": "^2.0.53",
68
67
  "@ai-sdk/google-vertex": "^3.0.70",
69
68
  "@ai-sdk/groq": "^2.0.24",
70
69
  "@ai-sdk/mistral": "^2.0.19",
@@ -72,7 +71,6 @@
72
71
  "@ai-sdk/perplexity": "^2.0.13",
73
72
  "@ai-sdk/togetherai": "^1.0.23",
74
73
  "@ai-sdk/xai": "^2.0.26",
75
- "@langchain/core": "^0.3.40",
76
74
  "bufferutil": "^4.0.9",
77
75
  "chrome-launcher": "^1.2.0",
78
76
  "ollama-ai-provider-v2": "^1.5.0",
@@ -90,6 +88,7 @@
90
88
  "chalk": "^5.4.1",
91
89
  "esbuild": "^0.21.4",
92
90
  "eslint": "^9.16.0",
91
+ "jsdom": "^24.0.0",
93
92
  "playwright": "^1.52.0",
94
93
  "playwright-core": "^1.54.1",
95
94
  "prettier": "^3.2.5",