@browserbasehq/orca 3.0.2-test-cua-base-url → 3.0.3-patch

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 (4) hide show
  1. package/dist/index.d.ts +80 -19
  2. package/dist/index.js +1053 -619
  3. package/package.json +18 -17
  4. package/LICENSE +0 -21
package/dist/index.js CHANGED
@@ -61,7 +61,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
61
61
  ));
62
62
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
63
63
  var __async = (__this, __arguments, generator) => {
64
- return new Promise((resolve3, reject) => {
64
+ return new Promise((resolve2, reject) => {
65
65
  var fulfilled = (value) => {
66
66
  try {
67
67
  step(generator.next(value));
@@ -76,11 +76,283 @@ var __async = (__this, __arguments, generator) => {
76
76
  reject(e);
77
77
  }
78
78
  };
79
- var step = (x) => x.done ? resolve3(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
79
+ var step = (x) => x.done ? resolve2(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
80
80
  step((generator = generator.apply(__this, __arguments)).next());
81
81
  });
82
82
  };
83
83
 
84
+ // lib/version.ts
85
+ var STAGEHAND_VERSION;
86
+ var init_version = __esm({
87
+ "lib/version.ts"() {
88
+ STAGEHAND_VERSION = "3.0.3-patch";
89
+ }
90
+ });
91
+
92
+ // lib/v3/types/public/sdkErrors.ts
93
+ 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, PageNotFoundError, ConnectionTimeoutError;
94
+ var init_sdkErrors = __esm({
95
+ "lib/v3/types/public/sdkErrors.ts"() {
96
+ init_version();
97
+ StagehandError = class extends Error {
98
+ constructor(message) {
99
+ super(message);
100
+ this.name = this.constructor.name;
101
+ }
102
+ };
103
+ StagehandDefaultError = class extends StagehandError {
104
+ constructor(error) {
105
+ if (error instanceof Error || error instanceof StagehandError) {
106
+ super(
107
+ `
108
+ Hey! We're sorry you ran into an error.
109
+ Stagehand version: ${STAGEHAND_VERSION}
110
+ If you need help, please open a Github issue or reach out to us on Slack: https://stagehand.dev/slack
111
+
112
+ Full error:
113
+ ${error.message}`
114
+ );
115
+ }
116
+ }
117
+ };
118
+ StagehandEnvironmentError = class extends StagehandError {
119
+ constructor(currentEnvironment, requiredEnvironment, feature) {
120
+ super(
121
+ `You seem to be setting the current environment to ${currentEnvironment}.Ensure the environment is set to ${requiredEnvironment} if you want to use ${feature}.`
122
+ );
123
+ }
124
+ };
125
+ MissingEnvironmentVariableError = class extends StagehandError {
126
+ constructor(missingEnvironmentVariable, feature) {
127
+ super(
128
+ `${missingEnvironmentVariable} is required to use ${feature}.Please set ${missingEnvironmentVariable} in your environment.`
129
+ );
130
+ }
131
+ };
132
+ UnsupportedModelError = class extends StagehandError {
133
+ constructor(supportedModels, feature) {
134
+ super(
135
+ feature ? `${feature} requires one of the following models: ${supportedModels}` : `please use one of the supported models: ${supportedModels}`
136
+ );
137
+ }
138
+ };
139
+ UnsupportedModelProviderError = class extends StagehandError {
140
+ constructor(supportedProviders, feature) {
141
+ super(
142
+ feature ? `${feature} requires one of the following model providers: ${supportedProviders}` : `please use one of the supported model providers: ${supportedProviders}`
143
+ );
144
+ }
145
+ };
146
+ UnsupportedAISDKModelProviderError = class extends StagehandError {
147
+ constructor(provider, supportedProviders) {
148
+ super(
149
+ `${provider} is not currently supported for aiSDK. please use one of the supported model providers: ${supportedProviders}`
150
+ );
151
+ }
152
+ };
153
+ InvalidAISDKModelFormatError = class extends StagehandError {
154
+ constructor(modelName) {
155
+ super(
156
+ `${modelName} does not follow correct format for specifying aiSDK models. Please define your model as 'provider/model-name'. For example: \`model: 'openai/gpt-4o-mini'\``
157
+ );
158
+ }
159
+ };
160
+ StagehandNotInitializedError = class extends StagehandError {
161
+ constructor(prop) {
162
+ super(
163
+ `You seem to be calling \`${prop}\` on a page in an uninitialized \`Stagehand\` object. Ensure you are running \`await stagehand.init()\` on the Stagehand object before referencing the \`page\` object.`
164
+ );
165
+ }
166
+ };
167
+ BrowserbaseSessionNotFoundError = class extends StagehandError {
168
+ constructor() {
169
+ super("No Browserbase session ID found");
170
+ }
171
+ };
172
+ CaptchaTimeoutError = class extends StagehandError {
173
+ constructor() {
174
+ super("Captcha timeout");
175
+ }
176
+ };
177
+ MissingLLMConfigurationError = class extends StagehandError {
178
+ constructor() {
179
+ super(
180
+ "No LLM API key or LLM Client configured. An LLM API key or a custom LLM Client is required to use act, extract, or observe."
181
+ );
182
+ }
183
+ };
184
+ HandlerNotInitializedError = class extends StagehandError {
185
+ constructor(handlerType) {
186
+ super(`${handlerType} handler not initialized`);
187
+ }
188
+ };
189
+ StagehandInvalidArgumentError = class extends StagehandError {
190
+ constructor(message) {
191
+ super(`InvalidArgumentError: ${message}`);
192
+ }
193
+ };
194
+ StagehandElementNotFoundError = class extends StagehandError {
195
+ constructor(xpaths) {
196
+ super(`Could not find an element for the given xPath(s): ${xpaths}`);
197
+ }
198
+ };
199
+ AgentScreenshotProviderError = class extends StagehandError {
200
+ constructor(message) {
201
+ super(`ScreenshotProviderError: ${message}`);
202
+ }
203
+ };
204
+ StagehandMissingArgumentError = class extends StagehandError {
205
+ constructor(message) {
206
+ super(`MissingArgumentError: ${message}`);
207
+ }
208
+ };
209
+ CreateChatCompletionResponseError = class extends StagehandError {
210
+ constructor(message) {
211
+ super(`CreateChatCompletionResponseError: ${message}`);
212
+ }
213
+ };
214
+ StagehandEvalError = class extends StagehandError {
215
+ constructor(message) {
216
+ super(`StagehandEvalError: ${message}`);
217
+ }
218
+ };
219
+ StagehandDomProcessError = class extends StagehandError {
220
+ constructor(message) {
221
+ super(`Error Processing Dom: ${message}`);
222
+ }
223
+ };
224
+ StagehandClickError = class extends StagehandError {
225
+ constructor(message, selector) {
226
+ super(
227
+ `Error Clicking Element with selector: ${selector} Reason: ${message}`
228
+ );
229
+ }
230
+ };
231
+ LLMResponseError = class extends StagehandError {
232
+ constructor(primitive, message) {
233
+ super(`${primitive} LLM response error: ${message}`);
234
+ }
235
+ };
236
+ StagehandIframeError = class extends StagehandError {
237
+ constructor(frameUrl, message) {
238
+ super(
239
+ `Unable to resolve frameId for iframe with URL: ${frameUrl} Full error: ${message}`
240
+ );
241
+ }
242
+ };
243
+ ContentFrameNotFoundError = class extends StagehandError {
244
+ constructor(selector) {
245
+ super(`Unable to obtain a content frame for selector: ${selector}`);
246
+ }
247
+ };
248
+ XPathResolutionError = class extends StagehandError {
249
+ constructor(xpath) {
250
+ super(`XPath "${xpath}" does not resolve in the current page or frames`);
251
+ }
252
+ };
253
+ ExperimentalApiConflictError = class extends StagehandError {
254
+ constructor() {
255
+ super(
256
+ "`experimental` mode cannot be used together with the Stagehand API. To use experimental features, set experimental: true, and useApi: false in the stagehand constructor. To use the Stagehand API, set experimental: false and useApi: true in the stagehand constructor. "
257
+ );
258
+ }
259
+ };
260
+ ExperimentalNotConfiguredError = class extends StagehandError {
261
+ constructor(featureName) {
262
+ super(`Feature "${featureName}" is an experimental feature, and cannot be configured when useAPI: true.
263
+ Please set experimental: true and useAPI: false in the stagehand constructor to use this feature.
264
+ If you wish to use the Stagehand API, please ensure ${featureName} is not defined in your function call,
265
+ and set experimental: false, useAPI: true in the Stagehand constructor. `);
266
+ }
267
+ };
268
+ CuaModelRequiredError = class extends StagehandError {
269
+ constructor(availableModels) {
270
+ super(
271
+ `To use the computer use agent (CUA), please provide a CUA model in the agent constructor or stagehand config. Try one of our supported CUA models: ${availableModels.join(", ")}`
272
+ );
273
+ }
274
+ };
275
+ ZodSchemaValidationError = class extends Error {
276
+ constructor(received, issues) {
277
+ super(`Zod schema validation failed
278
+
279
+ \u2014 Received \u2014
280
+ ${JSON.stringify(received, null, 2)}
281
+
282
+ \u2014 Issues \u2014
283
+ ${JSON.stringify(issues, null, 2)}`);
284
+ this.received = received;
285
+ this.issues = issues;
286
+ this.name = "ZodSchemaValidationError";
287
+ }
288
+ };
289
+ StagehandInitError = class extends StagehandError {
290
+ constructor(message) {
291
+ super(message);
292
+ }
293
+ };
294
+ MCPConnectionError = class extends StagehandError {
295
+ constructor(serverUrl, originalError) {
296
+ const errorMessage = originalError instanceof Error ? originalError.message : String(originalError);
297
+ super(
298
+ `Failed to connect to MCP server at "${serverUrl}". ${errorMessage}. Please verify the server URL is correct and the server is running.`
299
+ );
300
+ this.serverUrl = serverUrl;
301
+ this.originalError = originalError;
302
+ }
303
+ };
304
+ StagehandShadowRootMissingError = class extends StagehandError {
305
+ constructor(detail) {
306
+ super(
307
+ `No shadow root present on the resolved host` + (detail ? `: ${detail}` : "")
308
+ );
309
+ }
310
+ };
311
+ StagehandShadowSegmentEmptyError = class extends StagehandError {
312
+ constructor() {
313
+ super(`Empty selector segment after shadow-DOM hop ("//")`);
314
+ }
315
+ };
316
+ StagehandShadowSegmentNotFoundError = class extends StagehandError {
317
+ constructor(segment, hint) {
318
+ super(
319
+ `Shadow segment '${segment}' matched no element inside shadow root` + (hint ? ` ${hint}` : "")
320
+ );
321
+ }
322
+ };
323
+ ElementNotVisibleError = class extends StagehandError {
324
+ constructor(selector) {
325
+ super(`Element not visible (no box model): ${selector}`);
326
+ }
327
+ };
328
+ ResponseBodyError = class extends StagehandError {
329
+ constructor(message) {
330
+ super(`Failed to retrieve response body: ${message}`);
331
+ }
332
+ };
333
+ ResponseParseError = class extends StagehandError {
334
+ constructor(message) {
335
+ super(`Failed to parse response: ${message}`);
336
+ }
337
+ };
338
+ TimeoutError = class extends StagehandError {
339
+ constructor(operation, timeoutMs) {
340
+ super(`${operation} timed out after ${timeoutMs}ms`);
341
+ }
342
+ };
343
+ PageNotFoundError = class extends StagehandError {
344
+ constructor(identifier) {
345
+ super(`No Page found for ${identifier}`);
346
+ }
347
+ };
348
+ ConnectionTimeoutError = class extends StagehandError {
349
+ constructor(message) {
350
+ super(`Connection timeout: ${message}`);
351
+ }
352
+ };
353
+ }
354
+ });
355
+
84
356
  // lib/v3/logger.ts
85
357
  function bindInstanceLogger(instanceId, logger) {
86
358
  instanceLoggers.set(instanceId, logger);
@@ -189,7 +461,7 @@ var init_executionContextRegistry = __esm({
189
461
  });
190
462
  const after = this.getMainWorld(session, frameId);
191
463
  if (after) return after;
192
- return yield new Promise((resolve3, reject) => {
464
+ return yield new Promise((resolve2, reject) => {
193
465
  let done = false;
194
466
  const onCreated = (evt) => {
195
467
  var _a;
@@ -200,7 +472,7 @@ var init_executionContextRegistry = __esm({
200
472
  done = true;
201
473
  clearTimeout(timer);
202
474
  session.off("Runtime.executionContextCreated", onCreated);
203
- resolve3(evt.context.id);
475
+ resolve2(evt.context.id);
204
476
  }
205
477
  }
206
478
  };
@@ -906,8 +1178,8 @@ function normalizeXPath(x) {
906
1178
  if (s.length > 1 && s.endsWith("/")) s = s.slice(0, -1);
907
1179
  return s;
908
1180
  }
909
- function parseXPathToSteps(path6) {
910
- const s = path6.trim();
1181
+ function parseXPathToSteps(path7) {
1182
+ const s = path7.trim();
911
1183
  let i = 0;
912
1184
  const steps = [];
913
1185
  while (i < s.length) {
@@ -951,7 +1223,11 @@ function resolveFocusFrameAndTail(page, absoluteXPath, parentByFrame, rootId) {
951
1223
  selectorForIframe,
952
1224
  ctxFrameId
953
1225
  );
954
- if (!objectId) throw new Error("Failed to resolve iframe element by XPath");
1226
+ if (!objectId)
1227
+ throw new StagehandIframeError(
1228
+ selectorForIframe,
1229
+ "Failed to resolve iframe element by XPath"
1230
+ );
955
1231
  try {
956
1232
  yield parentSess.send("DOM.enable").catch(() => {
957
1233
  });
@@ -972,7 +1248,10 @@ function resolveFocusFrameAndTail(page, absoluteXPath, parentByFrame, rootId) {
972
1248
  }
973
1249
  }
974
1250
  if (!childFrameId)
975
- throw new Error("Could not map iframe to child frameId");
1251
+ throw new StagehandIframeError(
1252
+ selectorForIframe,
1253
+ "Could not map iframe to child frameId"
1254
+ );
976
1255
  absPrefix = prefixXPath(absPrefix || "/", selectorForIframe);
977
1256
  ctxFrameId = childFrameId;
978
1257
  } finally {
@@ -1004,7 +1283,11 @@ function resolveCssFocusFrameAndTail(page, rawSelector, parentByFrame, rootId) {
1004
1283
  parts[i],
1005
1284
  ctxFrameId
1006
1285
  );
1007
- if (!objectId) throw new Error("Failed to resolve iframe via CSS hop");
1286
+ if (!objectId)
1287
+ throw new StagehandIframeError(
1288
+ parts[i],
1289
+ "Failed to resolve iframe via CSS hop"
1290
+ );
1008
1291
  try {
1009
1292
  yield parentSess.send("DOM.enable").catch(() => {
1010
1293
  });
@@ -1025,7 +1308,10 @@ function resolveCssFocusFrameAndTail(page, rawSelector, parentByFrame, rootId) {
1025
1308
  }
1026
1309
  }
1027
1310
  if (!childFrameId)
1028
- throw new Error("Could not map CSS iframe hop to child frameId");
1311
+ throw new StagehandIframeError(
1312
+ parts[i],
1313
+ "Could not map CSS iframe hop to child frameId"
1314
+ );
1029
1315
  ctxFrameId = childFrameId;
1030
1316
  } finally {
1031
1317
  yield parentSess.send("Runtime.releaseObject", { objectId }).catch(() => {
@@ -1553,6 +1839,7 @@ var init_snapshot = __esm({
1553
1839
  "lib/v3/understudy/a11y/snapshot.ts"() {
1554
1840
  init_executionContextRegistry();
1555
1841
  init_logger();
1842
+ init_sdkErrors();
1556
1843
  IFRAME_STEP_RE = /^iframe(?:\[\d+])?$/i;
1557
1844
  }
1558
1845
  });
@@ -1561,31 +1848,33 @@ var init_snapshot = __esm({
1561
1848
  var locatorScriptBootstrap, locatorScriptSources, locatorScriptGlobalRefs;
1562
1849
  var init_locatorScripts_generated = __esm({
1563
1850
  "lib/v3/dom/build/locatorScripts.generated.ts"() {
1564
- locatorScriptBootstrap = 'if (!globalThis.__stagehandLocatorScripts) { var __stagehandLocatorScriptsFactory=(()=>{var L=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var D=(t,e)=>{for(var c in e)L(t,c,{get:e[c],enumerable:!0})},A=(t,e,c,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of k(e))!H.call(t,r)&&r!==c&&L(t,r,{get:()=>e[r],enumerable:!(n=C(e,r))||n.enumerable});return t};var _=t=>A(L({},"__esModule",{value:!0}),t);var ne={};D(ne,{countCssMatchesPierce:()=>Z,countCssMatchesPrimary:()=>Q,countTextMatches:()=>ee,countXPathMatchesMainWorld:()=>te,dispatchDomClick:()=>W,ensureFileInputElement:()=>I,fillElementValue:()=>O,focusElement:()=>P,isElementChecked:()=>Y,isElementVisible:()=>X,prepareElementForTyping:()=>b,readElementInnerHTML:()=>j,readElementInnerText:()=>K,readElementInputValue:()=>$,readElementTextContent:()=>B,resolveCssSelector:()=>U,resolveCssSelectorPierce:()=>z,resolveTextSelector:()=>G,resolveXPathMainWorld:()=>J,scrollElementToPercent:()=>q,selectElementOptions:()=>V});function I(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}function W(t){let e=t??{};try{let c=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(c)}catch{try{this.click()}catch{}}}function q(t){let e=c=>{if(typeof c=="number"&&Number.isFinite(c))return c;let n=String(c??"").trim();if(!n)return 0;let r=parseFloat(n.replace("%",""));return Number.isNaN(r)||!Number.isFinite(r)?0:r};try{let c=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,s=n.ownerDocument?.defaultView?.innerHeight??window.innerHeight,g=Math.max(0,d-s)*(c/100);return n.ownerDocument?.defaultView?.scrollTo({top:g,left:n.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let f=n.scrollHeight??0,u=n.clientHeight??0,i=Math.max(0,f-u)*(c/100);return n.scrollTo({top:i,left:n.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}var R=new Set(["color","date","datetime-local","month","range","time","week"]),F=new Set(["","email","number","password","search","tel","text","url"]);function b(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument||document,c=e.defaultView||window;try{typeof t.focus=="function"&&t.focus()}catch{}if(t instanceof c.HTMLInputElement||t instanceof c.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}}function O(t){let e=this;if(!e.isConnected)return{status:"error",reason:"notconnected"};let n=(e.ownerDocument||document).defaultView||window,r=t??"";try{let y=f=>{let u;if(typeof n.InputEvent=="function")try{u=new n.InputEvent("input",{bubbles:!0,composed:!0,data:f,inputType:"insertText"})}catch{u=new n.Event("input",{bubbles:!0,composed:!0})}else u=new n.Event("input",{bubbles:!0,composed:!0});e.dispatchEvent(u);let l=new n.Event("change",{bubbles:!0});e.dispatchEvent(l)};if(e instanceof n.HTMLInputElement){let f=(e.type||"").toLowerCase();if(!F.has(f)&&!R.has(f))return{status:"error",reason:`unsupported-input-type:${f}`};let u=t;if(f==="number"){let l=t.trim();if(l!==""&&Number.isNaN(Number(l)))return{status:"error",reason:"invalid-number-value"};u=l}if(r=u,R.has(f)){let l=t.trim();r=l,b.call(e);let i=n.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(i,"value")?.set;return typeof d=="function"?d.call(e,l):e.value=l,e._valueTracker?.setValue?.(l),e.value!==l?{status:"error",reason:"malformed-value"}:(y(l),{status:"done"})}return b.call(e),{status:"needsinput",value:u}}return e instanceof n.HTMLTextAreaElement?(b.call(e),r=t,{status:"needsinput",value:t}):e instanceof n.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:e.isContentEditable?(b.call(e),r=t,{status:"needsinput",value:t}):{status:"error",reason:"unsupported-element"}}catch(y){let f="exception";if(y&&typeof y=="object"){let u=y.message;typeof u=="string"&&u.trim().length>0&&(f=`exception:${u}`)}return{status:"needsinput",value:r,reason:f}}}function P(){try{typeof this.focus=="function"&&this.focus()}catch{}}function V(t){try{if(!(this instanceof HTMLSelectElement))return[];let e=Array.isArray(t)?t:[t],c=new Set(e.map(f=>String(f??"").trim())),n=f=>{let u=(f.label||f.textContent||"").trim(),l=String(f.value??"").trim();return c.has(u)||c.has(l)};if(this.multiple)for(let f of Array.from(this.options))f.selected=n(f);else{let f=!1;for(let u of Array.from(this.options))!f&&n(u)?(u.selected=!0,this.value=u.value,f=!0):u.selected=!1}let r=new Event("input",{bubbles:!0}),y=new Event("change",{bubbles:!0});return this.dispatchEvent(r),this.dispatchEvent(y),Array.from(this.selectedOptions).map(f=>f.value)}catch{return[]}}function X(){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 c=parseFloat(e.opacity??"1");if(!Number.isFinite(c)||c===0)return!1;let n=t.getBoundingClientRect();return!(!n||Math.max(n.width,n.height)===0||t.getClientRects().length===0)}catch{return!1}}function Y(){try{let t=this;if((t.tagName||"").toLowerCase()==="input"){let n=t.type?.toLowerCase()??"";if(n==="checkbox"||n==="radio")return!!t.checked}let c=t.getAttribute?.("aria-checked");return c!=null?c==="true":!1}catch{return!1}}function $(){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 B(){try{return String(this.textContent??"")}catch{return""}}function j(){try{return String(this.innerHTML??"")}catch{return""}}function K(){try{let t=this,e=t.innerText;if(typeof e=="string"&&e.length>0)return e;let c=t.textContent;return typeof c=="string"?c:""}catch{return""}}var N=t=>{let e=Number(t??0);return!Number.isFinite(e)||e<0?0:Math.floor(e)},v=(t,e)=>{if(!t)return[];let c=new WeakSet,n=new Set,r=[],y=[document],f=u=>{if(!(!u||c.has(u)||r.length>=e)){c.add(u);try{let l=u.querySelectorAll(t);for(let i of l)if(!n.has(i)&&(n.add(i),r.push(i),r.length>=e))return}catch{}try{let i=(u instanceof Document?u:u.host?.ownerDocument??document).createTreeWalker(u,NodeFilter.SHOW_ELEMENT),h;for(;h=i.nextNode();){if(!(h instanceof Element))continue;let d=h.shadowRoot;d&&y.push(d)}}catch{}}};for(;y.length&&r.length<e;){let u=y.shift();u&&f(u)}return r};function U(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e);return v(c,n+1)[n]??null}function z(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e),r=window.__stagehandV3__;if(!r||typeof r.getClosedRoot!="function")return v(c,n+1)[n]??null;let y=d=>{try{return r.getClosedRoot(d)??null}catch{return null}},f=new WeakSet,u=new Set,l=[],i=[document],h=d=>{if(!(!d||f.has(d)||l.length>=n+1)){f.add(d);try{let s=d.querySelectorAll(c);for(let m of s)if(!u.has(m)&&(u.add(m),l.push(m),l.length>=n+1))return}catch{}try{let m=(d instanceof Document?d:d.host?.ownerDocument??document).createTreeWalker(d,NodeFilter.SHOW_ELEMENT),g;for(;g=m.nextNode();){if(!(g instanceof Element))continue;let w=g.shadowRoot;w&&i.push(w);let E=y(g);E&&i.push(E)}}catch{}}};for(;i.length&&l.length<n+1;){let d=i.shift();d&&h(d)}return l[n]??null}function G(t,e){let c=String(t??"");if(!c)return null;let n=c.toLowerCase(),r=N(e),y=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),f=o=>{if(!o)return!1;let p=o.tagName?.toUpperCase()??"";return y.has(p)},u=o=>{try{if(f(o))return"";let p=o.innerText;if(typeof p=="string"&&p.trim())return p.trim()}catch{}try{let p=o.textContent;if(typeof p=="string")return p.trim()}catch{}return""},l=o=>{let p=u(o);return!!p&&p.toLowerCase().includes(n)},i=window.__stagehandV3__,h=i&&typeof i.getClosedRoot=="function"?o=>{try{return i.getClosedRoot(o)??null}catch{return null}}:o=>null,d=new WeakSet,s=[],m=[],g=o=>{!o||d.has(o)||(d.add(o),s.push(o))},w=o=>{try{return(o instanceof Document?o:o?.ownerDocument??document).createTreeWalker(o,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(g(document);s.length;){let o=s.shift();if(!o)continue;o instanceof Element&&l(o)&&m.push({element:o,tag:o.tagName??"",id:o.id??"",className:o.className??"",text:u(o)});let p=w(o);if(!p)continue;let x;for(;x=p.nextNode();){if(!(x instanceof Element))continue;l(x)&&m.push({element:x,tag:x.tagName??"",id:x.id??"",className:x.className??"",text:u(x)});let S=x.shadowRoot;S&&g(S);let T=h(x);T&&g(T)}}let E=[];for(let o of m){let p=o.element,x=!1;for(let S of m)if(o!==S)try{if(p.contains(S.element)){x=!0;break}}catch{}x||E.push(o)}return E[r]?.element??null}function J(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e),r=window.__stagehandV3__;if(n===0){try{if(r&&typeof r.resolveSimpleXPath=="function"){let s=r.resolveSimpleXPath(c);if(s)return s}}catch{}try{return document.evaluate(c,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{}}let f=(s=>{let m=String(s||"").trim();if(!m)return[];let g=m.replace(/^xpath=/i,""),w=[],E=0;for(;E<g.length;){let a="child";g.startsWith("//",E)?(a="desc",E+=2):g[E]==="/"&&(a="child",E+=1);let o=E;for(;E<g.length&&g[E]!=="/";)E+=1;let p=g.slice(o,E).trim();if(!p)continue;let x=p.match(/^(.*?)(\\[(\\d+)\\])?$/u),S=(x?.[1]??p).trim(),T=x?.[3]?Math.max(1,Number(x[3])):null,M=S===""?"*":S.toLowerCase();w.push({axis:a,tag:M,index:T})}return w})(c);if(!f.length)return null;let u=r&&typeof r.getClosedRoot=="function"?s=>{try{return r.getClosedRoot(s)??null}catch{return null}}:s=>null,l=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 g=s.shadowRoot;g&&m.push(...Array.from(g.children??[]));let w=u(s);return w&&m.push(...Array.from(w.children??[])),m}return m},i=s=>{let m=[],g=new Set,w=[...l(s)];for(;w.length;){let E=w.shift();!E||g.has(E)||(g.add(E),m.push(E),w.push(...l(E)))}return m},h=[document];for(let s of f){let m=[],g=new Set;for(let w of h){if(!w)continue;let E=s.axis==="child"?l(w):i(w);if(!E.length)continue;let a=E.filter(o=>o instanceof Element?s.tag==="*"?!0:o.localName===s.tag:!1);if(s.index!=null){let o=s.index-1,p=o>=0&&o<a.length?a[o]:null;p&&!g.has(p)&&(g.add(p),m.push(p))}else for(let o of a)g.has(o)||(g.add(o),m.push(o))}if(!m.length)return null;h=m}return h[n]??null}function Q(t){let e=String(t??"").trim();if(!e)return 0;let c=new WeakSet,n=r=>{if(!r||c.has(r))return 0;c.add(r);let y=0;try{let f=r;typeof f.querySelectorAll=="function"&&(y+=f.querySelectorAll(e).length)}catch{}try{let u=(r instanceof Document?r:r?.ownerDocument??document).createTreeWalker(r,NodeFilter.SHOW_ELEMENT),l;for(;l=u.nextNode();)l instanceof Element&&l.shadowRoot&&(y+=n(l.shadowRoot))}catch{}return y};try{return n(document)}catch{try{return document.querySelectorAll(e).length}catch{return 0}}}function Z(t){let e=String(t??"").trim();if(!e)return 0;let c=window.__stagehandV3__;if(!c||typeof c.getClosedRoot!="function")try{return document.querySelectorAll(e).length}catch{return 0}let n=new WeakSet,r=[],y=l=>{!l||n.has(l)||(n.add(l),r.push(l))};y(document);let f=0,u=l=>{let i=l.shadowRoot;i&&y(i);try{let h=c.getClosedRoot(l);h&&y(h)}catch{}};for(;r.length;){let l=r.shift();if(l){try{let i=l;typeof i.querySelectorAll=="function"&&(f+=i.querySelectorAll(e).length)}catch{}try{let h=(l instanceof Document?l:l instanceof ShadowRoot?l.host?.ownerDocument??document:l.ownerDocument??document).createTreeWalker(l,NodeFilter.SHOW_ELEMENT),d;for(;d=h.nextNode();)d instanceof Element&&u(d)}catch{}}}return f}function ee(t){let e=String(t??"");if(!e)return{count:0,sample:[],error:null};let c=e.toLowerCase(),n=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),r=a=>{if(!a)return!1;let o=a.tagName?.toUpperCase()??"";return n.has(o)},y=a=>{try{if(r(a))return"";let o=a.innerText;if(typeof o=="string"&&o.trim())return o.trim()}catch{}try{let o=a.textContent;if(typeof o=="string")return o.trim()}catch{}return""},f=a=>{let o=y(a);return!!o&&o.toLowerCase().includes(c)},u=window.__stagehandV3__,l=u&&typeof u.getClosedRoot=="function"?a=>{try{return u.getClosedRoot(a)??null}catch{return null}}:a=>null,i=new WeakSet,h=[],d=a=>{!a||i.has(a)||(i.add(a),h.push(a))},s=a=>{try{return(a instanceof Document?a:a?.ownerDocument??document).createTreeWalker(a,NodeFilter.SHOW_ELEMENT)}catch{return null}},m=[];for(d(document);h.length;){let a=h.shift();if(!a)continue;a instanceof Element&&f(a)&&m.push({element:a,tag:a.tagName??"",id:a.id??"",className:a.className??"",text:y(a)});let o=s(a);if(!o)continue;let p;for(;p=o.nextNode();){if(!(p instanceof Element))continue;f(p)&&m.push({element:p,tag:p.tagName??"",id:p.id??"",className:p.className??"",text:y(p)});let x=p.shadowRoot;x&&d(x);let S=l(p);S&&d(S)}}let g=[];for(let a of m){let o=a.element,p=!1;for(let x of m)if(a!==x)try{if(o.contains(x.element)){p=!0;break}}catch{}p||g.push(a)}let w=g.length,E=g.slice(0,5).map(a=>({tag:a.tag,id:a.id,class:a.className,text:a.text}));return{count:w,sample:E,error:null}}function te(t){let e=String(t??"").trim();if(!e)return 0;let n=(i=>{let h=String(i||"").trim().replace(/^xpath=/i,"");if(!h)return[];let d=[],s=0;for(;s<h.length;){let m="child";h.startsWith("//",s)?(m="desc",s+=2):h[s]==="/"&&(m="child",s+=1);let g=s;for(;s<h.length&&h[s]!=="/";)s+=1;let w=h.slice(g,s).trim();if(!w)continue;let E=w.match(/^(.*?)(\\[(\\d+)\\])?$/u),a=(E?.[1]??w).trim(),o=E?.[3]?Math.max(1,Number(E[3])):null,p=a===""?"*":a.toLowerCase();d.push({axis:m,tag:p,index:o})}return d})(e);if(!n.length)return 0;let r=window.__stagehandV3__,y=r&&typeof r.getClosedRoot=="function"?i=>{try{return r.getClosedRoot(i)??null}catch{return null}}:i=>null,f=i=>{let h=[];if(!i)return h;if(i instanceof Document)return i.documentElement&&h.push(i.documentElement),h;if(i instanceof ShadowRoot||i instanceof DocumentFragment)return h.push(...Array.from(i.children??[])),h;if(i instanceof Element){h.push(...Array.from(i.children??[]));let d=i.shadowRoot;d&&h.push(...Array.from(d.children??[]));let s=y(i);return s&&h.push(...Array.from(s.children??[])),h}return h},u=i=>{let h=[],d=new Set,s=[...f(i)];for(;s.length;){let m=s.shift();!m||d.has(m)||(d.add(m),h.push(m),s.push(...f(m)))}return h},l=[document];for(let i of n){let h=[],d=new Set;for(let s of l){if(!s)continue;let m=i.axis==="child"?f(s):u(s);if(!m.length)continue;let g=m.filter(w=>w instanceof Element?i.tag==="*"?!0:w.localName===i.tag:!1);if(i.index!=null){let w=i.index-1,E=w>=0&&w<g.length?g[w]:null;E&&!d.has(E)&&(d.add(E),h.push(E))}else for(let w of g)d.has(w)||(d.add(w),h.push(w))}if(!h.length)return 0;l=h}return l.length}return _(ne);})();\n globalThis.__stagehandLocatorScripts = __stagehandLocatorScriptsFactory;\n}';
1851
+ locatorScriptBootstrap = 'if (!globalThis.__stagehandLocatorScripts) { var __stagehandLocatorScriptsFactory=(()=>{var L=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var D=(t,e)=>{for(var c in e)L(t,c,{get:e[c],enumerable:!0})},A=(t,e,c,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of k(e))!H.call(t,o)&&o!==c&&L(t,o,{get:()=>e[o],enumerable:!(n=R(e,o))||n.enumerable});return t};var _=t=>A(L({},"__esModule",{value:!0}),t);var oe={};D(oe,{assignFilePayloadsToInputElement:()=>F,countCssMatchesPierce:()=>ee,countCssMatchesPrimary:()=>Z,countTextMatches:()=>te,countXPathMatchesMainWorld:()=>ne,dispatchDomClick:()=>W,ensureFileInputElement:()=>I,fillElementValue:()=>O,focusElement:()=>V,isElementChecked:()=>B,isElementVisible:()=>Y,prepareElementForTyping:()=>T,readElementInnerHTML:()=>U,readElementInnerText:()=>j,readElementInputValue:()=>$,readElementTextContent:()=>z,resolveCssSelector:()=>K,resolveCssSelectorPierce:()=>G,resolveTextSelector:()=>J,resolveXPathMainWorld:()=>Q,scrollElementToPercent:()=>q,selectElementOptions:()=>X});function I(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}function F(t){try{let e=this;if(!e||e.tagName?.toLowerCase()!=="input"||(e.type??"").toLowerCase()!=="file")return!1;let c=(()=>{try{return new DataTransfer}catch{return null}})();if(!c)return!1;let n=Array.isArray(t)?t:[];for(let o of n){if(!o)continue;let y=o.name||"upload.bin",u=o.mimeType||"application/octet-stream",a=typeof o.lastModified=="number"?o.lastModified:Date.now(),l=window.atob(o.base64??""),i=new Uint8Array(l.length);for(let s=0;s<l.length;s+=1)i[s]=l.charCodeAt(s);let f=new Blob([i],{type:u}),h=new File([f],y,{type:u,lastModified:a});c.items.add(h)}return e.files=c.files,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{return!1}}function W(t){let e=t??{};try{let c=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(c)}catch{try{this.click()}catch{}}}function q(t){let e=c=>{if(typeof c=="number"&&Number.isFinite(c))return c;let n=String(c??"").trim();if(!n)return 0;let o=parseFloat(n.replace("%",""));return Number.isNaN(o)||!Number.isFinite(o)?0:o};try{let c=Math.max(0,Math.min(e(t),100)),n=this,o=n.tagName?.toLowerCase()??"";if(o==="html"||o==="body"){let h=(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,g=Math.max(0,h-s)*(c/100);return n.ownerDocument?.defaultView?.scrollTo({top:g,left:n.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let u=n.scrollHeight??0,a=n.clientHeight??0,i=Math.max(0,u-a)*(c/100);return n.scrollTo({top:i,left:n.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}var v=new Set(["color","date","datetime-local","month","range","time","week"]),P=new Set(["","email","number","password","search","tel","text","url"]);function T(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument||document,c=e.defaultView||window;try{typeof t.focus=="function"&&t.focus()}catch{}if(t instanceof c.HTMLInputElement||t instanceof c.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 O(t){let e=this;if(!e.isConnected)return{status:"error",reason:"notconnected"};let n=(e.ownerDocument||document).defaultView||window,o=t??"";try{let y=u=>{let a;if(typeof n.InputEvent=="function")try{a=new n.InputEvent("input",{bubbles:!0,composed:!0,data:u,inputType:"insertText"})}catch{a=new n.Event("input",{bubbles:!0,composed:!0})}else a=new n.Event("input",{bubbles:!0,composed:!0});e.dispatchEvent(a);let l=new n.Event("change",{bubbles:!0});e.dispatchEvent(l)};if(e instanceof n.HTMLInputElement){let u=(e.type||"").toLowerCase();if(!P.has(u)&&!v.has(u))return{status:"error",reason:`unsupported-input-type:${u}`};let a=t;if(u==="number"){let l=t.trim();if(l!==""&&Number.isNaN(Number(l)))return{status:"error",reason:"invalid-number-value"};a=l}if(o=a,v.has(u)){let l=t.trim();o=l,T.call(e);let i=n.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(i,"value")?.set;return typeof h=="function"?h.call(e,l):e.value=l,e._valueTracker?.setValue?.(l),e.value!==l?{status:"error",reason:"malformed-value"}:(y(l),{status:"done"})}return T.call(e),{status:"needsinput",value:a}}return e instanceof n.HTMLTextAreaElement?(T.call(e),o=t,{status:"needsinput",value:t}):e instanceof n.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:e.isContentEditable?(T.call(e),o=t,{status:"needsinput",value:t}):{status:"error",reason:"unsupported-element"}}catch(y){let u="exception";if(y&&typeof y=="object"){let a=y.message;typeof a=="string"&&a.trim().length>0&&(u=`exception:${a}`)}return{status:"needsinput",value:o,reason:u}}}function V(){try{typeof this.focus=="function"&&this.focus()}catch{}}function X(t){try{if(!(this instanceof HTMLSelectElement))return[];let e=Array.isArray(t)?t:[t],c=new Set(e.map(u=>String(u??"").trim())),n=u=>{let a=(u.label||u.textContent||"").trim(),l=String(u.value??"").trim();return c.has(a)||c.has(l)};if(this.multiple)for(let u of Array.from(this.options))u.selected=n(u);else{let u=!1;for(let a of Array.from(this.options))!u&&n(a)?(a.selected=!0,this.value=a.value,u=!0):a.selected=!1}let o=new Event("input",{bubbles:!0}),y=new Event("change",{bubbles:!0});return this.dispatchEvent(o),this.dispatchEvent(y),Array.from(this.selectedOptions).map(u=>u.value)}catch{return[]}}function Y(){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 c=parseFloat(e.opacity??"1");if(!Number.isFinite(c)||c===0)return!1;let n=t.getBoundingClientRect();return!(!n||Math.max(n.width,n.height)===0||t.getClientRects().length===0)}catch{return!1}}function B(){try{let t=this;if((t.tagName||"").toLowerCase()==="input"){let n=t.type?.toLowerCase()??"";if(n==="checkbox"||n==="radio")return!!t.checked}let c=t.getAttribute?.("aria-checked");return c!=null?c==="true":!1}catch{return!1}}function $(){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 U(){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 c=t.textContent;return typeof c=="string"?c:""}catch{return""}}var N=t=>{let e=Number(t??0);return!Number.isFinite(e)||e<0?0:Math.floor(e)},M=(t,e)=>{if(!t)return[];let c=new WeakSet,n=new Set,o=[],y=[document],u=a=>{if(!(!a||c.has(a)||o.length>=e)){c.add(a);try{let l=a.querySelectorAll(t);for(let i of l)if(!n.has(i)&&(n.add(i),o.push(i),o.length>=e))return}catch{}try{let i=(a instanceof Document?a:a.host?.ownerDocument??document).createTreeWalker(a,NodeFilter.SHOW_ELEMENT),f;for(;f=i.nextNode();){if(!(f instanceof Element))continue;let h=f.shadowRoot;h&&y.push(h)}}catch{}}};for(;y.length&&o.length<e;){let a=y.shift();a&&u(a)}return o};function K(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e);return M(c,n+1)[n]??null}function G(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e),o=window.__stagehandV3__;if(!o||typeof o.getClosedRoot!="function")return M(c,n+1)[n]??null;let y=h=>{try{return o.getClosedRoot(h)??null}catch{return null}},u=new WeakSet,a=new Set,l=[],i=[document],f=h=>{if(!(!h||u.has(h)||l.length>=n+1)){u.add(h);try{let s=h.querySelectorAll(c);for(let d of s)if(!a.has(d)&&(a.add(d),l.push(d),l.length>=n+1))return}catch{}try{let d=(h instanceof Document?h:h.host?.ownerDocument??document).createTreeWalker(h,NodeFilter.SHOW_ELEMENT),g;for(;g=d.nextNode();){if(!(g instanceof Element))continue;let w=g.shadowRoot;w&&i.push(w);let E=y(g);E&&i.push(E)}}catch{}}};for(;i.length&&l.length<n+1;){let h=i.shift();h&&f(h)}return l[n]??null}function J(t,e){let c=String(t??"");if(!c)return null;let n=c.toLowerCase(),o=N(e),y=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),u=r=>{if(!r)return!1;let p=r.tagName?.toUpperCase()??"";return y.has(p)},a=r=>{try{if(u(r))return"";let p=r.innerText;if(typeof p=="string"&&p.trim())return p.trim()}catch{}try{let p=r.textContent;if(typeof p=="string")return p.trim()}catch{}return""},l=r=>{let p=a(r);return!!p&&p.toLowerCase().includes(n)},i=window.__stagehandV3__,f=i&&typeof i.getClosedRoot=="function"?r=>{try{return i.getClosedRoot(r)??null}catch{return null}}:r=>null,h=new WeakSet,s=[],d=[],g=r=>{!r||h.has(r)||(h.add(r),s.push(r))},w=r=>{try{return(r instanceof Document?r:r?.ownerDocument??document).createTreeWalker(r,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(g(document);s.length;){let r=s.shift();if(!r)continue;r instanceof Element&&l(r)&&d.push({element:r,tag:r.tagName??"",id:r.id??"",className:r.className??"",text:a(r)});let p=w(r);if(!p)continue;let x;for(;x=p.nextNode();){if(!(x instanceof Element))continue;l(x)&&d.push({element:x,tag:x.tagName??"",id:x.id??"",className:x.className??"",text:a(x)});let b=x.shadowRoot;b&&g(b);let S=f(x);S&&g(S)}}let E=[];for(let r of d){let p=r.element,x=!1;for(let b of d)if(r!==b)try{if(p.contains(b.element)){x=!0;break}}catch{}x||E.push(r)}return E[o]?.element??null}function Q(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e),o=window.__stagehandV3__;if(n===0){try{if(o&&typeof o.resolveSimpleXPath=="function"){let s=o.resolveSimpleXPath(c);if(s)return s}}catch{}try{return document.evaluate(c,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{}}let u=(s=>{let d=String(s||"").trim();if(!d)return[];let g=d.replace(/^xpath=/i,""),w=[],E=0;for(;E<g.length;){let m="child";g.startsWith("//",E)?(m="desc",E+=2):g[E]==="/"&&(m="child",E+=1);let r=E;for(;E<g.length&&g[E]!=="/";)E+=1;let p=g.slice(r,E).trim();if(!p)continue;let x=p.match(/^(.*?)(\\[(\\d+)\\])?$/u),b=(x?.[1]??p).trim(),S=x?.[3]?Math.max(1,Number(x[3])):null,C=b===""?"*":b.toLowerCase();w.push({axis:m,tag:C,index:S})}return w})(c);if(!u.length)return null;let a=o&&typeof o.getClosedRoot=="function"?s=>{try{return o.getClosedRoot(s)??null}catch{return null}}:s=>null,l=s=>{let d=[];if(!s)return d;if(s instanceof Document)return s.documentElement&&d.push(s.documentElement),d;if(s instanceof ShadowRoot||s instanceof DocumentFragment)return d.push(...Array.from(s.children??[])),d;if(s instanceof Element){d.push(...Array.from(s.children??[]));let g=s.shadowRoot;g&&d.push(...Array.from(g.children??[]));let w=a(s);return w&&d.push(...Array.from(w.children??[])),d}return d},i=s=>{let d=[],g=new Set,w=[...l(s)];for(;w.length;){let E=w.shift();!E||g.has(E)||(g.add(E),d.push(E),w.push(...l(E)))}return d},f=[document];for(let s of u){let d=[],g=new Set;for(let w of f){if(!w)continue;let E=s.axis==="child"?l(w):i(w);if(!E.length)continue;let m=E.filter(r=>r instanceof Element?s.tag==="*"?!0:r.localName===s.tag:!1);if(s.index!=null){let r=s.index-1,p=r>=0&&r<m.length?m[r]:null;p&&!g.has(p)&&(g.add(p),d.push(p))}else for(let r of m)g.has(r)||(g.add(r),d.push(r))}if(!d.length)return null;f=d}return f[n]??null}function Z(t){let e=String(t??"").trim();if(!e)return 0;let c=new WeakSet,n=o=>{if(!o||c.has(o))return 0;c.add(o);let y=0;try{let u=o;typeof u.querySelectorAll=="function"&&(y+=u.querySelectorAll(e).length)}catch{}try{let a=(o instanceof Document?o:o?.ownerDocument??document).createTreeWalker(o,NodeFilter.SHOW_ELEMENT),l;for(;l=a.nextNode();)l instanceof Element&&l.shadowRoot&&(y+=n(l.shadowRoot))}catch{}return y};try{return n(document)}catch{try{return document.querySelectorAll(e).length}catch{return 0}}}function ee(t){let e=String(t??"").trim();if(!e)return 0;let c=window.__stagehandV3__;if(!c||typeof c.getClosedRoot!="function")try{return document.querySelectorAll(e).length}catch{return 0}let n=new WeakSet,o=[],y=l=>{!l||n.has(l)||(n.add(l),o.push(l))};y(document);let u=0,a=l=>{let i=l.shadowRoot;i&&y(i);try{let f=c.getClosedRoot(l);f&&y(f)}catch{}};for(;o.length;){let l=o.shift();if(l){try{let i=l;typeof i.querySelectorAll=="function"&&(u+=i.querySelectorAll(e).length)}catch{}try{let f=(l instanceof Document?l:l instanceof ShadowRoot?l.host?.ownerDocument??document:l.ownerDocument??document).createTreeWalker(l,NodeFilter.SHOW_ELEMENT),h;for(;h=f.nextNode();)h instanceof Element&&a(h)}catch{}}}return u}function te(t){let e=String(t??"");if(!e)return{count:0,sample:[],error:null};let c=e.toLowerCase(),n=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),o=m=>{if(!m)return!1;let r=m.tagName?.toUpperCase()??"";return n.has(r)},y=m=>{try{if(o(m))return"";let r=m.innerText;if(typeof r=="string"&&r.trim())return r.trim()}catch{}try{let r=m.textContent;if(typeof r=="string")return r.trim()}catch{}return""},u=m=>{let r=y(m);return!!r&&r.toLowerCase().includes(c)},a=window.__stagehandV3__,l=a&&typeof a.getClosedRoot=="function"?m=>{try{return a.getClosedRoot(m)??null}catch{return null}}:m=>null,i=new WeakSet,f=[],h=m=>{!m||i.has(m)||(i.add(m),f.push(m))},s=m=>{try{return(m instanceof Document?m:m?.ownerDocument??document).createTreeWalker(m,NodeFilter.SHOW_ELEMENT)}catch{return null}},d=[];for(h(document);f.length;){let m=f.shift();if(!m)continue;m instanceof Element&&u(m)&&d.push({element:m,tag:m.tagName??"",id:m.id??"",className:m.className??"",text:y(m)});let r=s(m);if(!r)continue;let p;for(;p=r.nextNode();){if(!(p instanceof Element))continue;u(p)&&d.push({element:p,tag:p.tagName??"",id:p.id??"",className:p.className??"",text:y(p)});let x=p.shadowRoot;x&&h(x);let b=l(p);b&&h(b)}}let g=[];for(let m of d){let r=m.element,p=!1;for(let x of d)if(m!==x)try{if(r.contains(x.element)){p=!0;break}}catch{}p||g.push(m)}let w=g.length,E=g.slice(0,5).map(m=>({tag:m.tag,id:m.id,class:m.className,text:m.text}));return{count:w,sample:E,error:null}}function ne(t){let e=String(t??"").trim();if(!e)return 0;let n=(i=>{let f=String(i||"").trim().replace(/^xpath=/i,"");if(!f)return[];let h=[],s=0;for(;s<f.length;){let d="child";f.startsWith("//",s)?(d="desc",s+=2):f[s]==="/"&&(d="child",s+=1);let g=s;for(;s<f.length&&f[s]!=="/";)s+=1;let w=f.slice(g,s).trim();if(!w)continue;let E=w.match(/^(.*?)(\\[(\\d+)\\])?$/u),m=(E?.[1]??w).trim(),r=E?.[3]?Math.max(1,Number(E[3])):null,p=m===""?"*":m.toLowerCase();h.push({axis:d,tag:p,index:r})}return h})(e);if(!n.length)return 0;let o=window.__stagehandV3__,y=o&&typeof o.getClosedRoot=="function"?i=>{try{return o.getClosedRoot(i)??null}catch{return null}}:i=>null,u=i=>{let f=[];if(!i)return f;if(i instanceof Document)return i.documentElement&&f.push(i.documentElement),f;if(i instanceof ShadowRoot||i instanceof DocumentFragment)return f.push(...Array.from(i.children??[])),f;if(i instanceof Element){f.push(...Array.from(i.children??[]));let h=i.shadowRoot;h&&f.push(...Array.from(h.children??[]));let s=y(i);return s&&f.push(...Array.from(s.children??[])),f}return f},a=i=>{let f=[],h=new Set,s=[...u(i)];for(;s.length;){let d=s.shift();!d||h.has(d)||(h.add(d),f.push(d),s.push(...u(d)))}return f},l=[document];for(let i of n){let f=[],h=new Set;for(let s of l){if(!s)continue;let d=i.axis==="child"?u(s):a(s);if(!d.length)continue;let g=d.filter(w=>w instanceof Element?i.tag==="*"?!0:w.localName===i.tag:!1);if(i.index!=null){let w=i.index-1,E=w>=0&&w<g.length?g[w]:null;E&&!h.has(E)&&(h.add(E),f.push(E))}else for(let w of g)h.has(w)||(h.add(w),f.push(w))}if(!f.length)return 0;l=f}return l.length}return _(oe);})();\n globalThis.__stagehandLocatorScripts = __stagehandLocatorScriptsFactory;\n}';
1565
1852
  locatorScriptSources = {
1566
- "countCssMatchesPierce": 'function U(t){let e=String(t??"").trim();if(!e)return 0;let i=window.__stagehandV3__;if(!i||typeof i.getClosedRoot!="function")try{return document.querySelectorAll(e).length}catch{return 0}let n=new WeakSet,l=[],y=s=>{!s||n.has(s)||(n.add(s),l.push(s))};y(document);let f=0,u=s=>{let c=s.shadowRoot;c&&y(c);try{let h=i.getClosedRoot(s);h&&y(h)}catch{}};for(;l.length;){let s=l.shift();if(s){try{let c=s;typeof c.querySelectorAll=="function"&&(f+=c.querySelectorAll(e).length)}catch{}try{let h=(s instanceof Document?s:s instanceof ShadowRoot?s.host?.ownerDocument??document:s.ownerDocument??document).createTreeWalker(s,NodeFilter.SHOW_ELEMENT),d;for(;d=h.nextNode();)d instanceof Element&&u(d)}catch{}}}return f}',
1567
- "countCssMatchesPrimary": 'function K(t){let e=String(t??"").trim();if(!e)return 0;let i=new WeakSet,n=l=>{if(!l||i.has(l))return 0;i.add(l);let y=0;try{let f=l;typeof f.querySelectorAll=="function"&&(y+=f.querySelectorAll(e).length)}catch{}try{let u=(l instanceof Document?l:l?.ownerDocument??document).createTreeWalker(l,NodeFilter.SHOW_ELEMENT),s;for(;s=u.nextNode();)s instanceof Element&&s.shadowRoot&&(y+=n(s.shadowRoot))}catch{}return y};try{return n(document)}catch{try{return document.querySelectorAll(e).length}catch{return 0}}}',
1568
- "countTextMatches": 'function z(t){let e=String(t??"");if(!e)return{count:0,sample:[],error:null};let i=e.toLowerCase(),n=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),l=a=>{if(!a)return!1;let o=a.tagName?.toUpperCase()??"";return n.has(o)},y=a=>{try{if(l(a))return"";let o=a.innerText;if(typeof o=="string"&&o.trim())return o.trim()}catch{}try{let o=a.textContent;if(typeof o=="string")return o.trim()}catch{}return""},f=a=>{let o=y(a);return!!o&&o.toLowerCase().includes(i)},u=window.__stagehandV3__,s=u&&typeof u.getClosedRoot=="function"?a=>{try{return u.getClosedRoot(a)??null}catch{return null}}:a=>null,c=new WeakSet,h=[],d=a=>{!a||c.has(a)||(c.add(a),h.push(a))},r=a=>{try{return(a instanceof Document?a:a?.ownerDocument??document).createTreeWalker(a,NodeFilter.SHOW_ELEMENT)}catch{return null}},m=[];for(d(document);h.length;){let a=h.shift();if(!a)continue;a instanceof Element&&f(a)&&m.push({element:a,tag:a.tagName??"",id:a.id??"",className:a.className??"",text:y(a)});let o=r(a);if(!o)continue;let p;for(;p=o.nextNode();){if(!(p instanceof Element))continue;f(p)&&m.push({element:p,tag:p.tagName??"",id:p.id??"",className:p.className??"",text:y(p)});let x=p.shadowRoot;x&&d(x);let S=s(p);S&&d(S)}}let g=[];for(let a of m){let o=a.element,p=!1;for(let x of m)if(a!==x)try{if(o.contains(x.element)){p=!0;break}}catch{}p||g.push(a)}let w=g.length,E=g.slice(0,5).map(a=>({tag:a.tag,id:a.id,class:a.className,text:a.text}));return{count:w,sample:E,error:null}}',
1569
- "countXPathMatchesMainWorld": 'function G(t){let e=String(t??"").trim();if(!e)return 0;let n=(c=>{let h=String(c||"").trim().replace(/^xpath=/i,"");if(!h)return[];let d=[],r=0;for(;r<h.length;){let m="child";h.startsWith("//",r)?(m="desc",r+=2):h[r]==="/"&&(m="child",r+=1);let g=r;for(;r<h.length&&h[r]!=="/";)r+=1;let w=h.slice(g,r).trim();if(!w)continue;let E=w.match(/^(.*?)(\\[(\\d+)\\])?$/u),a=(E?.[1]??w).trim(),o=E?.[3]?Math.max(1,Number(E[3])):null,p=a===""?"*":a.toLowerCase();d.push({axis:m,tag:p,index:o})}return d})(e);if(!n.length)return 0;let l=window.__stagehandV3__,y=l&&typeof l.getClosedRoot=="function"?c=>{try{return l.getClosedRoot(c)??null}catch{return null}}:c=>null,f=c=>{let h=[];if(!c)return h;if(c instanceof Document)return c.documentElement&&h.push(c.documentElement),h;if(c instanceof ShadowRoot||c instanceof DocumentFragment)return h.push(...Array.from(c.children??[])),h;if(c instanceof Element){h.push(...Array.from(c.children??[]));let d=c.shadowRoot;d&&h.push(...Array.from(d.children??[]));let r=y(c);return r&&h.push(...Array.from(r.children??[])),h}return h},u=c=>{let h=[],d=new Set,r=[...f(c)];for(;r.length;){let m=r.shift();!m||d.has(m)||(d.add(m),h.push(m),r.push(...f(m)))}return h},s=[document];for(let c of n){let h=[],d=new Set;for(let r of s){if(!r)continue;let m=c.axis==="child"?f(r):u(r);if(!m.length)continue;let g=m.filter(w=>w instanceof Element?c.tag==="*"?!0:w.localName===c.tag:!1);if(c.index!=null){let w=c.index-1,E=w>=0&&w<g.length?g[w]:null;E&&!d.has(E)&&(d.add(E),h.push(E))}else for(let w of g)d.has(w)||(d.add(w),h.push(w))}if(!h.length)return 0;s=h}return s.length}',
1570
- "dispatchDomClick": 'function k(t){let e=t??{};try{let i=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(i)}catch{try{this.click()}catch{}}}',
1571
- "ensureFileInputElement": 'function C(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}',
1572
- "fillElementValue": 'function D(t){let e=this;if(!e.isConnected)return{status:"error",reason:"notconnected"};let n=(e.ownerDocument||document).defaultView||window,l=t??"";try{let y=f=>{let u;if(typeof n.InputEvent=="function")try{u=new n.InputEvent("input",{bubbles:!0,composed:!0,data:f,inputType:"insertText"})}catch{u=new n.Event("input",{bubbles:!0,composed:!0})}else u=new n.Event("input",{bubbles:!0,composed:!0});e.dispatchEvent(u);let s=new n.Event("change",{bubbles:!0});e.dispatchEvent(s)};if(e instanceof n.HTMLInputElement){let f=(e.type||"").toLowerCase();if(!M.has(f)&&!L.has(f))return{status:"error",reason:`unsupported-input-type:${f}`};let u=t;if(f==="number"){let s=t.trim();if(s!==""&&Number.isNaN(Number(s)))return{status:"error",reason:"invalid-number-value"};u=s}if(l=u,L.has(f)){let s=t.trim();l=s,T.call(e);let c=n.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value")?.set;return typeof d=="function"?d.call(e,s):e.value=s,e._valueTracker?.setValue?.(s),e.value!==s?{status:"error",reason:"malformed-value"}:(y(s),{status:"done"})}return T.call(e),{status:"needsinput",value:u}}return e instanceof n.HTMLTextAreaElement?(T.call(e),l=t,{status:"needsinput",value:t}):e instanceof n.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:e.isContentEditable?(T.call(e),l=t,{status:"needsinput",value:t}):{status:"error",reason:"unsupported-element"}}catch(y){let f="exception";if(y&&typeof y=="object"){let u=y.message;typeof u=="string"&&u.trim().length>0&&(f=`exception:${u}`)}return{status:"needsinput",value:l,reason:f}}}',
1573
- "focusElement": 'function A(){try{typeof this.focus=="function"&&this.focus()}catch{}}',
1853
+ "assignFilePayloadsToInputElement": 'function k(t){try{let e=this;if(!e||e.tagName?.toLowerCase()!=="input"||(e.type??"").toLowerCase()!=="file")return!1;let i=(()=>{try{return new DataTransfer}catch{return null}})();if(!i)return!1;let n=Array.isArray(t)?t:[];for(let s of n){if(!s)continue;let y=s.name||"upload.bin",u=s.mimeType||"application/octet-stream",a=typeof s.lastModified=="number"?s.lastModified:Date.now(),l=window.atob(s.base64??""),c=new Uint8Array(l.length);for(let r=0;r<l.length;r+=1)c[r]=l.charCodeAt(r);let f=new Blob([c],{type:u}),h=new File([f],y,{type:u,lastModified:a});i.items.add(h)}return e.files=i.files,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{return!1}}',
1854
+ "countCssMatchesPierce": 'function K(t){let e=String(t??"").trim();if(!e)return 0;let i=window.__stagehandV3__;if(!i||typeof i.getClosedRoot!="function")try{return document.querySelectorAll(e).length}catch{return 0}let n=new WeakSet,s=[],y=l=>{!l||n.has(l)||(n.add(l),s.push(l))};y(document);let u=0,a=l=>{let c=l.shadowRoot;c&&y(c);try{let f=i.getClosedRoot(l);f&&y(f)}catch{}};for(;s.length;){let l=s.shift();if(l){try{let c=l;typeof c.querySelectorAll=="function"&&(u+=c.querySelectorAll(e).length)}catch{}try{let f=(l instanceof Document?l:l instanceof ShadowRoot?l.host?.ownerDocument??document:l.ownerDocument??document).createTreeWalker(l,NodeFilter.SHOW_ELEMENT),h;for(;h=f.nextNode();)h instanceof Element&&a(h)}catch{}}}return u}',
1855
+ "countCssMatchesPrimary": 'function j(t){let e=String(t??"").trim();if(!e)return 0;let i=new WeakSet,n=s=>{if(!s||i.has(s))return 0;i.add(s);let y=0;try{let u=s;typeof u.querySelectorAll=="function"&&(y+=u.querySelectorAll(e).length)}catch{}try{let a=(s instanceof Document?s:s?.ownerDocument??document).createTreeWalker(s,NodeFilter.SHOW_ELEMENT),l;for(;l=a.nextNode();)l instanceof Element&&l.shadowRoot&&(y+=n(l.shadowRoot))}catch{}return y};try{return n(document)}catch{try{return document.querySelectorAll(e).length}catch{return 0}}}',
1856
+ "countTextMatches": 'function G(t){let e=String(t??"");if(!e)return{count:0,sample:[],error:null};let i=e.toLowerCase(),n=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),s=m=>{if(!m)return!1;let o=m.tagName?.toUpperCase()??"";return n.has(o)},y=m=>{try{if(s(m))return"";let o=m.innerText;if(typeof o=="string"&&o.trim())return o.trim()}catch{}try{let o=m.textContent;if(typeof o=="string")return o.trim()}catch{}return""},u=m=>{let o=y(m);return!!o&&o.toLowerCase().includes(i)},a=window.__stagehandV3__,l=a&&typeof a.getClosedRoot=="function"?m=>{try{return a.getClosedRoot(m)??null}catch{return null}}:m=>null,c=new WeakSet,f=[],h=m=>{!m||c.has(m)||(c.add(m),f.push(m))},r=m=>{try{return(m instanceof Document?m:m?.ownerDocument??document).createTreeWalker(m,NodeFilter.SHOW_ELEMENT)}catch{return null}},d=[];for(h(document);f.length;){let m=f.shift();if(!m)continue;m instanceof Element&&u(m)&&d.push({element:m,tag:m.tagName??"",id:m.id??"",className:m.className??"",text:y(m)});let o=r(m);if(!o)continue;let p;for(;p=o.nextNode();){if(!(p instanceof Element))continue;u(p)&&d.push({element:p,tag:p.tagName??"",id:p.id??"",className:p.className??"",text:y(p)});let x=p.shadowRoot;x&&h(x);let b=l(p);b&&h(b)}}let g=[];for(let m of d){let o=m.element,p=!1;for(let x of d)if(m!==x)try{if(o.contains(x.element)){p=!0;break}}catch{}p||g.push(m)}let w=g.length,E=g.slice(0,5).map(m=>({tag:m.tag,id:m.id,class:m.className,text:m.text}));return{count:w,sample:E,error:null}}',
1857
+ "countXPathMatchesMainWorld": 'function J(t){let e=String(t??"").trim();if(!e)return 0;let n=(c=>{let f=String(c||"").trim().replace(/^xpath=/i,"");if(!f)return[];let h=[],r=0;for(;r<f.length;){let d="child";f.startsWith("//",r)?(d="desc",r+=2):f[r]==="/"&&(d="child",r+=1);let g=r;for(;r<f.length&&f[r]!=="/";)r+=1;let w=f.slice(g,r).trim();if(!w)continue;let E=w.match(/^(.*?)(\\[(\\d+)\\])?$/u),m=(E?.[1]??w).trim(),o=E?.[3]?Math.max(1,Number(E[3])):null,p=m===""?"*":m.toLowerCase();h.push({axis:d,tag:p,index:o})}return h})(e);if(!n.length)return 0;let s=window.__stagehandV3__,y=s&&typeof s.getClosedRoot=="function"?c=>{try{return s.getClosedRoot(c)??null}catch{return null}}:c=>null,u=c=>{let f=[];if(!c)return f;if(c instanceof Document)return c.documentElement&&f.push(c.documentElement),f;if(c instanceof ShadowRoot||c instanceof DocumentFragment)return f.push(...Array.from(c.children??[])),f;if(c instanceof Element){f.push(...Array.from(c.children??[]));let h=c.shadowRoot;h&&f.push(...Array.from(h.children??[]));let r=y(c);return r&&f.push(...Array.from(r.children??[])),f}return f},a=c=>{let f=[],h=new Set,r=[...u(c)];for(;r.length;){let d=r.shift();!d||h.has(d)||(h.add(d),f.push(d),r.push(...u(d)))}return f},l=[document];for(let c of n){let f=[],h=new Set;for(let r of l){if(!r)continue;let d=c.axis==="child"?u(r):a(r);if(!d.length)continue;let g=d.filter(w=>w instanceof Element?c.tag==="*"?!0:w.localName===c.tag:!1);if(c.index!=null){let w=c.index-1,E=w>=0&&w<g.length?g[w]:null;E&&!h.has(E)&&(h.add(E),f.push(E))}else for(let w of g)h.has(w)||(h.add(w),f.push(w))}if(!f.length)return 0;l=f}return l.length}',
1858
+ "dispatchDomClick": 'function H(t){let e=t??{};try{let i=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(i)}catch{try{this.click()}catch{}}}',
1859
+ "ensureFileInputElement": 'function R(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}',
1860
+ "fillElementValue": 'function A(t){let e=this;if(!e.isConnected)return{status:"error",reason:"notconnected"};let n=(e.ownerDocument||document).defaultView||window,s=t??"";try{let y=u=>{let a;if(typeof n.InputEvent=="function")try{a=new n.InputEvent("input",{bubbles:!0,composed:!0,data:u,inputType:"insertText"})}catch{a=new n.Event("input",{bubbles:!0,composed:!0})}else a=new n.Event("input",{bubbles:!0,composed:!0});e.dispatchEvent(a);let l=new n.Event("change",{bubbles:!0});e.dispatchEvent(l)};if(e instanceof n.HTMLInputElement){let u=(e.type||"").toLowerCase();if(!C.has(u)&&!L.has(u))return{status:"error",reason:`unsupported-input-type:${u}`};let a=t;if(u==="number"){let l=t.trim();if(l!==""&&Number.isNaN(Number(l)))return{status:"error",reason:"invalid-number-value"};a=l}if(s=a,L.has(u)){let l=t.trim();s=l,S.call(e);let c=n.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(c,"value")?.set;return typeof h=="function"?h.call(e,l):e.value=l,e._valueTracker?.setValue?.(l),e.value!==l?{status:"error",reason:"malformed-value"}:(y(l),{status:"done"})}return S.call(e),{status:"needsinput",value:a}}return e instanceof n.HTMLTextAreaElement?(S.call(e),s=t,{status:"needsinput",value:t}):e instanceof n.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:e.isContentEditable?(S.call(e),s=t,{status:"needsinput",value:t}):{status:"error",reason:"unsupported-element"}}catch(y){let u="exception";if(y&&typeof y=="object"){let a=y.message;typeof a=="string"&&a.trim().length>0&&(u=`exception:${a}`)}return{status:"needsinput",value:s,reason:u}}}',
1861
+ "focusElement": 'function _(){try{typeof this.focus=="function"&&this.focus()}catch{}}',
1574
1862
  "isElementChecked": 'function W(){try{let t=this;if((t.tagName||"").toLowerCase()==="input"){let n=t.type?.toLowerCase()??"";if(n==="checkbox"||n==="radio")return!!t.checked}let i=t.getAttribute?.("aria-checked");return i!=null?i==="true":!1}catch{return!1}}',
1575
- "isElementVisible": 'function I(){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 i=parseFloat(e.opacity??"1");if(!Number.isFinite(i)||i===0)return!1;let n=t.getBoundingClientRect();return!(!n||Math.max(n.width,n.height)===0||t.getClientRects().length===0)}catch{return!1}}',
1576
- "prepareElementForTyping": 'function T(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument||document,i=e.defaultView||window;try{typeof t.focus=="function"&&t.focus()}catch{}if(t instanceof i.HTMLInputElement||t instanceof i.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?.(),l=e.createRange?.();if(n&&l)try{l.selectNodeContents(t),n.removeAllRanges(),n.addRange(l)}catch{}return!0}return!1}catch{return!1}}',
1863
+ "isElementVisible": 'function F(){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 i=parseFloat(e.opacity??"1");if(!Number.isFinite(i)||i===0)return!1;let n=t.getBoundingClientRect();return!(!n||Math.max(n.width,n.height)===0||t.getClientRects().length===0)}catch{return!1}}',
1864
+ "prepareElementForTyping": 'function S(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument||document,i=e.defaultView||window;try{typeof t.focus=="function"&&t.focus()}catch{}if(t instanceof i.HTMLInputElement||t instanceof i.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?.(),s=e.createRange?.();if(n&&s)try{s.selectNodeContents(t),n.removeAllRanges(),n.addRange(s)}catch{}return!0}return!1}catch{return!1}}',
1577
1865
  "readElementInnerHTML": 'function O(){try{return String(this.innerHTML??"")}catch{return""}}',
1578
- "readElementInnerText": 'function P(){try{let t=this,e=t.innerText;if(typeof e=="string"&&e.length>0)return e;let i=t.textContent;return typeof i=="string"?i:""}catch{return""}}',
1866
+ "readElementInnerText": 'function V(){try{let t=this,e=t.innerText;if(typeof e=="string"&&e.length>0)return e;let i=t.textContent;return typeof i=="string"?i:""}catch{return""}}',
1579
1867
  "readElementInputValue": 'function q(){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""}}',
1580
- "readElementTextContent": 'function F(){try{return String(this.textContent??"")}catch{return""}}',
1581
- "resolveCssSelector": 'function X(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e);return R(i,n+1)[n]??null}',
1582
- "resolveCssSelectorPierce": 'function Y(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e),l=window.__stagehandV3__;if(!l||typeof l.getClosedRoot!="function")return R(i,n+1)[n]??null;let y=d=>{try{return l.getClosedRoot(d)??null}catch{return null}},f=new WeakSet,u=new Set,s=[],c=[document],h=d=>{if(!(!d||f.has(d)||s.length>=n+1)){f.add(d);try{let r=d.querySelectorAll(i);for(let m of r)if(!u.has(m)&&(u.add(m),s.push(m),s.length>=n+1))return}catch{}try{let m=(d instanceof Document?d:d.host?.ownerDocument??document).createTreeWalker(d,NodeFilter.SHOW_ELEMENT),g;for(;g=m.nextNode();){if(!(g instanceof Element))continue;let w=g.shadowRoot;w&&c.push(w);let E=y(g);E&&c.push(E)}}catch{}}};for(;c.length&&s.length<n+1;){let d=c.shift();d&&h(d)}return s[n]??null}',
1583
- "resolveTextSelector": 'function $(t,e){let i=String(t??"");if(!i)return null;let n=i.toLowerCase(),l=N(e),y=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),f=o=>{if(!o)return!1;let p=o.tagName?.toUpperCase()??"";return y.has(p)},u=o=>{try{if(f(o))return"";let p=o.innerText;if(typeof p=="string"&&p.trim())return p.trim()}catch{}try{let p=o.textContent;if(typeof p=="string")return p.trim()}catch{}return""},s=o=>{let p=u(o);return!!p&&p.toLowerCase().includes(n)},c=window.__stagehandV3__,h=c&&typeof c.getClosedRoot=="function"?o=>{try{return c.getClosedRoot(o)??null}catch{return null}}:o=>null,d=new WeakSet,r=[],m=[],g=o=>{!o||d.has(o)||(d.add(o),r.push(o))},w=o=>{try{return(o instanceof Document?o:o?.ownerDocument??document).createTreeWalker(o,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(g(document);r.length;){let o=r.shift();if(!o)continue;o instanceof Element&&s(o)&&m.push({element:o,tag:o.tagName??"",id:o.id??"",className:o.className??"",text:u(o)});let p=w(o);if(!p)continue;let x;for(;x=p.nextNode();){if(!(x instanceof Element))continue;s(x)&&m.push({element:x,tag:x.tagName??"",id:x.id??"",className:x.className??"",text:u(x)});let S=x.shadowRoot;S&&g(S);let b=h(x);b&&g(b)}}let E=[];for(let o of m){let p=o.element,x=!1;for(let S of m)if(o!==S)try{if(p.contains(S.element)){x=!0;break}}catch{}x||E.push(o)}return E[l]?.element??null}',
1584
- "resolveXPathMainWorld": 'function B(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e),l=window.__stagehandV3__;if(n===0){try{if(l&&typeof l.resolveSimpleXPath=="function"){let r=l.resolveSimpleXPath(i);if(r)return r}}catch{}try{return document.evaluate(i,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{}}let f=(r=>{let m=String(r||"").trim();if(!m)return[];let g=m.replace(/^xpath=/i,""),w=[],E=0;for(;E<g.length;){let a="child";g.startsWith("//",E)?(a="desc",E+=2):g[E]==="/"&&(a="child",E+=1);let o=E;for(;E<g.length&&g[E]!=="/";)E+=1;let p=g.slice(o,E).trim();if(!p)continue;let x=p.match(/^(.*?)(\\[(\\d+)\\])?$/u),S=(x?.[1]??p).trim(),b=x?.[3]?Math.max(1,Number(x[3])):null,v=S===""?"*":S.toLowerCase();w.push({axis:a,tag:v,index:b})}return w})(i);if(!f.length)return null;let u=l&&typeof l.getClosedRoot=="function"?r=>{try{return l.getClosedRoot(r)??null}catch{return null}}:r=>null,s=r=>{let m=[];if(!r)return m;if(r instanceof Document)return r.documentElement&&m.push(r.documentElement),m;if(r instanceof ShadowRoot||r instanceof DocumentFragment)return m.push(...Array.from(r.children??[])),m;if(r instanceof Element){m.push(...Array.from(r.children??[]));let g=r.shadowRoot;g&&m.push(...Array.from(g.children??[]));let w=u(r);return w&&m.push(...Array.from(w.children??[])),m}return m},c=r=>{let m=[],g=new Set,w=[...s(r)];for(;w.length;){let E=w.shift();!E||g.has(E)||(g.add(E),m.push(E),w.push(...s(E)))}return m},h=[document];for(let r of f){let m=[],g=new Set;for(let w of h){if(!w)continue;let E=r.axis==="child"?s(w):c(w);if(!E.length)continue;let a=E.filter(o=>o instanceof Element?r.tag==="*"?!0:o.localName===r.tag:!1);if(r.index!=null){let o=r.index-1,p=o>=0&&o<a.length?a[o]:null;p&&!g.has(p)&&(g.add(p),m.push(p))}else for(let o of a)g.has(o)||(g.add(o),m.push(o))}if(!m.length)return null;h=m}return h[n]??null}',
1585
- "scrollElementToPercent": 'function H(t){let e=i=>{if(typeof i=="number"&&Number.isFinite(i))return i;let n=String(i??"").trim();if(!n)return 0;let l=parseFloat(n.replace("%",""));return Number.isNaN(l)||!Number.isFinite(l)?0:l};try{let i=Math.max(0,Math.min(e(t),100)),n=this,l=n.tagName?.toLowerCase()??"";if(l==="html"||l==="body"){let d=(n.ownerDocument?.scrollingElement||n.ownerDocument?.documentElement||n.ownerDocument?.body||document.scrollingElement||document.documentElement||document.body)?.scrollHeight??document.body.scrollHeight??0,r=n.ownerDocument?.defaultView?.innerHeight??window.innerHeight,g=Math.max(0,d-r)*(i/100);return n.ownerDocument?.defaultView?.scrollTo({top:g,left:n.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let f=n.scrollHeight??0,u=n.clientHeight??0,c=Math.max(0,f-u)*(i/100);return n.scrollTo({top:c,left:n.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}',
1586
- "selectElementOptions": 'function _(t){try{if(!(this instanceof HTMLSelectElement))return[];let e=Array.isArray(t)?t:[t],i=new Set(e.map(f=>String(f??"").trim())),n=f=>{let u=(f.label||f.textContent||"").trim(),s=String(f.value??"").trim();return i.has(u)||i.has(s)};if(this.multiple)for(let f of Array.from(this.options))f.selected=n(f);else{let f=!1;for(let u of Array.from(this.options))!f&&n(u)?(u.selected=!0,this.value=u.value,f=!0):u.selected=!1}let l=new Event("input",{bubbles:!0}),y=new Event("change",{bubbles:!0});return this.dispatchEvent(l),this.dispatchEvent(y),Array.from(this.selectedOptions).map(f=>f.value)}catch{return[]}}'
1868
+ "readElementTextContent": 'function P(){try{return String(this.textContent??"")}catch{return""}}',
1869
+ "resolveCssSelector": 'function Y(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e);return v(i,n+1)[n]??null}',
1870
+ "resolveCssSelectorPierce": 'function B(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e),s=window.__stagehandV3__;if(!s||typeof s.getClosedRoot!="function")return v(i,n+1)[n]??null;let y=h=>{try{return s.getClosedRoot(h)??null}catch{return null}},u=new WeakSet,a=new Set,l=[],c=[document],f=h=>{if(!(!h||u.has(h)||l.length>=n+1)){u.add(h);try{let r=h.querySelectorAll(i);for(let d of r)if(!a.has(d)&&(a.add(d),l.push(d),l.length>=n+1))return}catch{}try{let d=(h instanceof Document?h:h.host?.ownerDocument??document).createTreeWalker(h,NodeFilter.SHOW_ELEMENT),g;for(;g=d.nextNode();){if(!(g instanceof Element))continue;let w=g.shadowRoot;w&&c.push(w);let E=y(g);E&&c.push(E)}}catch{}}};for(;c.length&&l.length<n+1;){let h=c.shift();h&&f(h)}return l[n]??null}',
1871
+ "resolveTextSelector": 'function $(t,e){let i=String(t??"");if(!i)return null;let n=i.toLowerCase(),s=N(e),y=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),u=o=>{if(!o)return!1;let p=o.tagName?.toUpperCase()??"";return y.has(p)},a=o=>{try{if(u(o))return"";let p=o.innerText;if(typeof p=="string"&&p.trim())return p.trim()}catch{}try{let p=o.textContent;if(typeof p=="string")return p.trim()}catch{}return""},l=o=>{let p=a(o);return!!p&&p.toLowerCase().includes(n)},c=window.__stagehandV3__,f=c&&typeof c.getClosedRoot=="function"?o=>{try{return c.getClosedRoot(o)??null}catch{return null}}:o=>null,h=new WeakSet,r=[],d=[],g=o=>{!o||h.has(o)||(h.add(o),r.push(o))},w=o=>{try{return(o instanceof Document?o:o?.ownerDocument??document).createTreeWalker(o,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(g(document);r.length;){let o=r.shift();if(!o)continue;o instanceof Element&&l(o)&&d.push({element:o,tag:o.tagName??"",id:o.id??"",className:o.className??"",text:a(o)});let p=w(o);if(!p)continue;let x;for(;x=p.nextNode();){if(!(x instanceof Element))continue;l(x)&&d.push({element:x,tag:x.tagName??"",id:x.id??"",className:x.className??"",text:a(x)});let b=x.shadowRoot;b&&g(b);let T=f(x);T&&g(T)}}let E=[];for(let o of d){let p=o.element,x=!1;for(let b of d)if(o!==b)try{if(p.contains(b.element)){x=!0;break}}catch{}x||E.push(o)}return E[s]?.element??null}',
1872
+ "resolveXPathMainWorld": 'function z(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e),s=window.__stagehandV3__;if(n===0){try{if(s&&typeof s.resolveSimpleXPath=="function"){let r=s.resolveSimpleXPath(i);if(r)return r}}catch{}try{return document.evaluate(i,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{}}let u=(r=>{let d=String(r||"").trim();if(!d)return[];let g=d.replace(/^xpath=/i,""),w=[],E=0;for(;E<g.length;){let m="child";g.startsWith("//",E)?(m="desc",E+=2):g[E]==="/"&&(m="child",E+=1);let o=E;for(;E<g.length&&g[E]!=="/";)E+=1;let p=g.slice(o,E).trim();if(!p)continue;let x=p.match(/^(.*?)(\\[(\\d+)\\])?$/u),b=(x?.[1]??p).trim(),T=x?.[3]?Math.max(1,Number(x[3])):null,M=b===""?"*":b.toLowerCase();w.push({axis:m,tag:M,index:T})}return w})(i);if(!u.length)return null;let a=s&&typeof s.getClosedRoot=="function"?r=>{try{return s.getClosedRoot(r)??null}catch{return null}}:r=>null,l=r=>{let d=[];if(!r)return d;if(r instanceof Document)return r.documentElement&&d.push(r.documentElement),d;if(r instanceof ShadowRoot||r instanceof DocumentFragment)return d.push(...Array.from(r.children??[])),d;if(r instanceof Element){d.push(...Array.from(r.children??[]));let g=r.shadowRoot;g&&d.push(...Array.from(g.children??[]));let w=a(r);return w&&d.push(...Array.from(w.children??[])),d}return d},c=r=>{let d=[],g=new Set,w=[...l(r)];for(;w.length;){let E=w.shift();!E||g.has(E)||(g.add(E),d.push(E),w.push(...l(E)))}return d},f=[document];for(let r of u){let d=[],g=new Set;for(let w of f){if(!w)continue;let E=r.axis==="child"?l(w):c(w);if(!E.length)continue;let m=E.filter(o=>o instanceof Element?r.tag==="*"?!0:o.localName===r.tag:!1);if(r.index!=null){let o=r.index-1,p=o>=0&&o<m.length?m[o]:null;p&&!g.has(p)&&(g.add(p),d.push(p))}else for(let o of m)g.has(o)||(g.add(o),d.push(o))}if(!d.length)return null;f=d}return f[n]??null}',
1873
+ "scrollElementToPercent": 'function D(t){let e=i=>{if(typeof i=="number"&&Number.isFinite(i))return i;let n=String(i??"").trim();if(!n)return 0;let s=parseFloat(n.replace("%",""));return Number.isNaN(s)||!Number.isFinite(s)?0:s};try{let i=Math.max(0,Math.min(e(t),100)),n=this,s=n.tagName?.toLowerCase()??"";if(s==="html"||s==="body"){let h=(n.ownerDocument?.scrollingElement||n.ownerDocument?.documentElement||n.ownerDocument?.body||document.scrollingElement||document.documentElement||document.body)?.scrollHeight??document.body.scrollHeight??0,r=n.ownerDocument?.defaultView?.innerHeight??window.innerHeight,g=Math.max(0,h-r)*(i/100);return n.ownerDocument?.defaultView?.scrollTo({top:g,left:n.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let u=n.scrollHeight??0,a=n.clientHeight??0,c=Math.max(0,u-a)*(i/100);return n.scrollTo({top:c,left:n.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}',
1874
+ "selectElementOptions": 'function I(t){try{if(!(this instanceof HTMLSelectElement))return[];let e=Array.isArray(t)?t:[t],i=new Set(e.map(u=>String(u??"").trim())),n=u=>{let a=(u.label||u.textContent||"").trim(),l=String(u.value??"").trim();return i.has(a)||i.has(l)};if(this.multiple)for(let u of Array.from(this.options))u.selected=n(u);else{let u=!1;for(let a of Array.from(this.options))!u&&n(a)?(a.selected=!0,this.value=a.value,u=!0):a.selected=!1}let s=new Event("input",{bubbles:!0}),y=new Event("change",{bubbles:!0});return this.dispatchEvent(s),this.dispatchEvent(y),Array.from(this.selectedOptions).map(u=>u.value)}catch{return[]}}'
1587
1875
  };
1588
1876
  locatorScriptGlobalRefs = {
1877
+ "assignFilePayloadsToInputElement": "globalThis.__stagehandLocatorScripts.assignFilePayloadsToInputElement",
1589
1878
  "countCssMatchesPierce": "globalThis.__stagehandLocatorScripts.countCssMatchesPierce",
1590
1879
  "countCssMatchesPrimary": "globalThis.__stagehandLocatorScripts.countCssMatchesPrimary",
1591
1880
  "countTextMatches": "globalThis.__stagehandLocatorScripts.countTextMatches",
@@ -1971,16 +2260,99 @@ var init_selectorResolver = __esm({
1971
2260
  }
1972
2261
  });
1973
2262
 
2263
+ // lib/v3/understudy/fileUploadUtils.ts
2264
+ function normalizeInputFiles(_0) {
2265
+ return __async(this, arguments, function* (files, opts = {}) {
2266
+ var _a;
2267
+ if (files === null || files === void 0) return [];
2268
+ const flattened = Array.isArray(files) ? files : [files];
2269
+ if (!flattened.length) return [];
2270
+ const baseDir = (_a = opts.baseDir) != null ? _a : process.cwd();
2271
+ const normalized = [];
2272
+ for (const entry of flattened) {
2273
+ if (typeof entry === "string") {
2274
+ const absolutePath = import_path3.default.isAbsolute(entry) ? entry : import_path3.default.resolve(baseDir, entry);
2275
+ const stat = yield statFile(absolutePath);
2276
+ if (!stat.isFile()) {
2277
+ throw new StagehandInvalidArgumentError(
2278
+ `setInputFiles(): expected a file but received directory or special entry at ${absolutePath}`
2279
+ );
2280
+ }
2281
+ const buffer = yield import_fs3.promises.readFile(absolutePath);
2282
+ normalized.push({
2283
+ name: import_path3.default.basename(absolutePath) || "upload.bin",
2284
+ mimeType: DEFAULT_MIME_TYPE,
2285
+ buffer,
2286
+ lastModified: stat.mtimeMs || Date.now(),
2287
+ absolutePath
2288
+ });
2289
+ continue;
2290
+ }
2291
+ if (entry && typeof entry === "object" && "buffer" in entry) {
2292
+ const payload = entry;
2293
+ const buffer = toBuffer(payload.buffer);
2294
+ normalized.push({
2295
+ name: payload.name || "upload.bin",
2296
+ mimeType: payload.mimeType || DEFAULT_MIME_TYPE,
2297
+ buffer,
2298
+ lastModified: typeof payload.lastModified === "number" ? payload.lastModified : Date.now()
2299
+ });
2300
+ continue;
2301
+ }
2302
+ throw new StagehandInvalidArgumentError(
2303
+ "setInputFiles(): expected file path(s) or payload object(s)"
2304
+ );
2305
+ }
2306
+ return normalized;
2307
+ });
2308
+ }
2309
+ function statFile(absolutePath) {
2310
+ return __async(this, null, function* () {
2311
+ try {
2312
+ return yield import_fs3.promises.stat(absolutePath);
2313
+ } catch (error) {
2314
+ const code = error == null ? void 0 : error.code;
2315
+ if (code === "ENOENT") {
2316
+ throw new StagehandInvalidArgumentError(
2317
+ `setInputFiles(): file not found at ${absolutePath}`
2318
+ );
2319
+ }
2320
+ throw error;
2321
+ }
2322
+ });
2323
+ }
2324
+ function toBuffer(data) {
2325
+ if (import_buffer.Buffer.isBuffer(data)) return data;
2326
+ if (data instanceof Uint8Array) return import_buffer.Buffer.from(data);
2327
+ if (typeof data === "string") return import_buffer.Buffer.from(data);
2328
+ if (data instanceof ArrayBuffer) return import_buffer.Buffer.from(new Uint8Array(data));
2329
+ throw new StagehandInvalidArgumentError(
2330
+ "Unsupported file payload buffer type"
2331
+ );
2332
+ }
2333
+ var import_fs3, import_path3, import_buffer, DEFAULT_MIME_TYPE;
2334
+ var init_fileUploadUtils = __esm({
2335
+ "lib/v3/understudy/fileUploadUtils.ts"() {
2336
+ import_fs3 = require("fs");
2337
+ import_path3 = __toESM(require("path"));
2338
+ import_buffer = require("buffer");
2339
+ init_sdkErrors();
2340
+ DEFAULT_MIME_TYPE = "application/octet-stream";
2341
+ }
2342
+ });
2343
+
1974
2344
  // lib/v3/understudy/locator.ts
1975
- var fs3, os, path3, import_buffer, Locator;
2345
+ var fs4, os, path4, MAX_REMOTE_UPLOAD_BYTES, Locator;
1976
2346
  var init_locator = __esm({
1977
2347
  "lib/v3/understudy/locator.ts"() {
1978
- fs3 = __toESM(require("fs"));
2348
+ fs4 = __toESM(require("fs"));
1979
2349
  os = __toESM(require("os"));
1980
- path3 = __toESM(require("path"));
1981
- import_buffer = require("buffer");
2350
+ path4 = __toESM(require("path"));
1982
2351
  init_locatorScripts_generated();
1983
2352
  init_selectorResolver();
2353
+ init_sdkErrors();
2354
+ init_fileUploadUtils();
2355
+ MAX_REMOTE_UPLOAD_BYTES = 50 * 1024 * 1024;
1984
2356
  Locator = class _Locator {
1985
2357
  constructor(frame, selector, options, nthIndex = 0) {
1986
2358
  this.frame = frame;
@@ -2010,16 +2382,7 @@ var init_locator = __esm({
2010
2382
  return __async(this, null, function* () {
2011
2383
  const session = this.frame.session;
2012
2384
  const { objectId } = yield this.resolveNode();
2013
- const items = Array.isArray(files) ? files : [files];
2014
2385
  const tempFiles = [];
2015
- const filePaths = [];
2016
- const toBuffer = (data) => {
2017
- if (import_buffer.Buffer.isBuffer(data)) return data;
2018
- if (data instanceof Uint8Array) return import_buffer.Buffer.from(data);
2019
- if (typeof data === "string") return import_buffer.Buffer.from(data);
2020
- if (data instanceof ArrayBuffer) return import_buffer.Buffer.from(new Uint8Array(data));
2021
- throw new Error("Unsupported file payload buffer type");
2022
- };
2023
2386
  try {
2024
2387
  try {
2025
2388
  const res = yield session.send(
@@ -2032,34 +2395,40 @@ var init_locator = __esm({
2032
2395
  );
2033
2396
  const ok = Boolean(res.result.value);
2034
2397
  if (!ok)
2035
- throw new Error('Target is not an <input type="file"> element');
2398
+ throw new StagehandInvalidArgumentError(
2399
+ 'Target is not an <input type="file"> element'
2400
+ );
2036
2401
  } catch (e) {
2037
- throw new Error(
2402
+ throw new StagehandInvalidArgumentError(
2038
2403
  e instanceof Error ? e.message : "Unable to verify file input element"
2039
2404
  );
2040
2405
  }
2041
- for (const it of items) {
2042
- if (typeof it === "string") {
2043
- filePaths.push(path3.resolve(it));
2044
- continue;
2045
- }
2046
- if (it && typeof it === "object" && "name" in it && "mimeType" in it && "buffer" in it) {
2047
- const payload = it;
2048
- const base = payload.name || "upload.bin";
2049
- const ext = path3.extname(base);
2050
- const tmp = path3.join(
2051
- os.tmpdir(),
2052
- `stagehand-upload-${Date.now()}-${Math.random().toString(36).slice(2)}${ext}`
2053
- );
2054
- const buf = toBuffer(payload.buffer);
2055
- yield fs3.promises.writeFile(tmp, buf);
2056
- tempFiles.push(tmp);
2057
- filePaths.push(tmp);
2406
+ const normalized = yield normalizeInputFiles(files);
2407
+ if (!normalized.length) {
2408
+ yield session.send("DOM.setFileInputFiles", {
2409
+ objectId,
2410
+ files: []
2411
+ });
2412
+ return;
2413
+ }
2414
+ if (this.frame.isBrowserRemote()) {
2415
+ yield this.assignFilesViaPayloadInjection(objectId, normalized);
2416
+ return;
2417
+ }
2418
+ const filePaths = [];
2419
+ for (const payload of normalized) {
2420
+ if (payload.absolutePath) {
2421
+ filePaths.push(payload.absolutePath);
2058
2422
  continue;
2059
2423
  }
2060
- throw new Error(
2061
- "Unsupported setInputFiles item \u2013 expected path or payload"
2424
+ const ext = path4.extname(payload.name);
2425
+ const tmp = path4.join(
2426
+ os.tmpdir(),
2427
+ `stagehand-upload-${Date.now()}-${Math.random().toString(36).slice(2)}${ext}`
2062
2428
  );
2429
+ yield fs4.promises.writeFile(tmp, payload.buffer);
2430
+ tempFiles.push(tmp);
2431
+ filePaths.push(tmp);
2063
2432
  }
2064
2433
  yield session.send("DOM.setFileInputFiles", {
2065
2434
  objectId,
@@ -2070,13 +2439,59 @@ var init_locator = __esm({
2070
2439
  });
2071
2440
  for (const p of tempFiles) {
2072
2441
  try {
2073
- yield fs3.promises.unlink(p);
2442
+ yield fs4.promises.unlink(p);
2074
2443
  } catch (e) {
2075
2444
  }
2076
2445
  }
2077
2446
  }
2078
2447
  });
2079
2448
  }
2449
+ /**
2450
+ * Remote browser fallback: build File objects inside the page and attach them via JS.
2451
+ *
2452
+ * When Stagehand is driving a browser that cannot see the local filesystem (Browserbase,
2453
+ * remote CDP, etc.), CDP's DOM.setFileInputFiles would fail because Chrome can't reach
2454
+ * our temp files. Instead we base64-encode the payloads, send them into the page, and
2455
+ * let a DOM helper create File objects + dispatch change/input events.
2456
+ */
2457
+ assignFilesViaPayloadInjection(objectId, files) {
2458
+ return __async(this, null, function* () {
2459
+ var _a;
2460
+ const session = this.frame.session;
2461
+ for (const payload of files) {
2462
+ if (payload.buffer.length > MAX_REMOTE_UPLOAD_BYTES) {
2463
+ throw new StagehandInvalidArgumentError(
2464
+ `setInputFiles(): file "${payload.name}" is larger than the 50MB limit for remote uploads`
2465
+ );
2466
+ }
2467
+ }
2468
+ const serialized = files.map((payload) => ({
2469
+ name: payload.name,
2470
+ mimeType: payload.mimeType,
2471
+ lastModified: payload.lastModified,
2472
+ base64: payload.buffer.toString("base64")
2473
+ }));
2474
+ const res = yield session.send(
2475
+ "Runtime.callFunctionOn",
2476
+ {
2477
+ objectId,
2478
+ functionDeclaration: locatorScriptSources.assignFilePayloadsToInputElement,
2479
+ arguments: [
2480
+ {
2481
+ value: serialized
2482
+ }
2483
+ ],
2484
+ returnByValue: true
2485
+ }
2486
+ );
2487
+ const ok = Boolean((_a = res.result) == null ? void 0 : _a.value);
2488
+ if (!ok) {
2489
+ throw new StagehandInvalidArgumentError(
2490
+ "Unable to assign file payloads to remote input element"
2491
+ );
2492
+ }
2493
+ });
2494
+ }
2080
2495
  /**
2081
2496
  * Return the DOM backendNodeId for this locator's target element.
2082
2497
  * Useful for identity comparisons without needing element handles.
@@ -2123,7 +2538,7 @@ var init_locator = __esm({
2123
2538
  "DOM.getBoxModel",
2124
2539
  { objectId }
2125
2540
  );
2126
- if (!box.model) throw new Error("Element not visible (no box model)");
2541
+ if (!box.model) throw new ElementNotVisibleError(this.selector);
2127
2542
  const { cx, cy } = this.centerFromBoxContent(box.model.content);
2128
2543
  return { x: Math.round(cx), y: Math.round(cy) };
2129
2544
  } finally {
@@ -2210,7 +2625,7 @@ var init_locator = __esm({
2210
2625
  "DOM.getBoxModel",
2211
2626
  { objectId }
2212
2627
  );
2213
- if (!box.model) throw new Error("Element not visible (no box model)");
2628
+ if (!box.model) throw new ElementNotVisibleError(this.selector);
2214
2629
  const { cx, cy } = this.centerFromBoxContent(box.model.content);
2215
2630
  yield session.send("Input.dispatchMouseEvent", {
2216
2631
  type: "mouseMoved",
@@ -2245,7 +2660,7 @@ var init_locator = __esm({
2245
2660
  "DOM.getBoxModel",
2246
2661
  { objectId }
2247
2662
  );
2248
- if (!box.model) throw new Error("Element not visible (no box model)");
2663
+ if (!box.model) throw new ElementNotVisibleError(this.selector);
2249
2664
  const { cx, cy } = this.centerFromBoxContent(box.model.content);
2250
2665
  yield session.send("Input.dispatchMouseEvent", {
2251
2666
  type: "mouseMoved",
@@ -2412,7 +2827,9 @@ var init_locator = __esm({
2412
2827
  }
2413
2828
  if (status === "error") {
2414
2829
  const reason = typeof (result == null ? void 0 : result.reason) === "string" && result.reason.length > 0 ? result.reason : "Failed to fill element";
2415
- throw new Error(`Failed to fill element (${reason})`);
2830
+ throw new StagehandInvalidArgumentError(
2831
+ `Failed to fill element (${reason})`
2832
+ );
2416
2833
  }
2417
2834
  if (!status) {
2418
2835
  yield this.type(value);
@@ -2639,7 +3056,9 @@ var init_locator = __esm({
2639
3056
  nth(index) {
2640
3057
  const value = Number(index);
2641
3058
  if (!Number.isFinite(value) || value < 0) {
2642
- throw new Error("locator().nth() expects a non-negative index");
3059
+ throw new StagehandInvalidArgumentError(
3060
+ "locator().nth() expects a non-negative index"
3061
+ );
2643
3062
  }
2644
3063
  const nextIndex = Math.floor(value);
2645
3064
  if (nextIndex === this.nthIndex) {
@@ -2662,7 +3081,7 @@ var init_locator = __esm({
2662
3081
  this.nthIndex
2663
3082
  );
2664
3083
  if (!resolved) {
2665
- throw new Error(`Element not found for selector: ${this.selector}`);
3084
+ throw new StagehandElementNotFoundError([this.selector]);
2666
3085
  }
2667
3086
  return resolved;
2668
3087
  });
@@ -2670,7 +3089,7 @@ var init_locator = __esm({
2670
3089
  /** Compute a center point from a BoxModel content quad */
2671
3090
  centerFromBoxContent(content) {
2672
3091
  if (!content || content.length < 8) {
2673
- throw new Error("Invalid box model content quad");
3092
+ throw new StagehandInvalidArgumentError("Invalid box model content quad");
2674
3093
  }
2675
3094
  const xs = [content[0], content[2], content[4], content[6]];
2676
3095
  const ys = [content[1], content[3], content[5], content[7]];
@@ -2735,13 +3154,13 @@ function ensureChildFrameReady(page, parentFrame, childFrameId, budgetMs) {
2735
3154
  });
2736
3155
  yield parentSession2.send("Runtime.enable").catch(() => {
2737
3156
  });
2738
- yield new Promise((resolve3) => {
3157
+ yield new Promise((resolve2) => {
2739
3158
  let done = false;
2740
3159
  const finish = () => {
2741
3160
  if (done) return;
2742
3161
  done = true;
2743
3162
  parentSession2.off("Page.lifecycleEvent", onLifecycle);
2744
- resolve3();
3163
+ resolve2();
2745
3164
  };
2746
3165
  const onLifecycle = (evt) => {
2747
3166
  if (evt.frameId !== childFrameId || evt.name !== "DOMContentLoaded" && evt.name !== "load" && evt.name !== "networkIdle" && evt.name !== "networkidle") {
@@ -2781,6 +3200,7 @@ var FrameLocator, LocatorDelegate;
2781
3200
  var init_frameLocator = __esm({
2782
3201
  "lib/v3/understudy/frameLocator.ts"() {
2783
3202
  init_executionContextRegistry();
3203
+ init_sdkErrors();
2784
3204
  FrameLocator = class _FrameLocator {
2785
3205
  constructor(page, selector, parent, root) {
2786
3206
  this.page = page;
@@ -2823,9 +3243,7 @@ var init_frameLocator = __esm({
2823
3243
  } catch (e) {
2824
3244
  }
2825
3245
  }
2826
- throw new Error(
2827
- `frameLocator: could not resolve child frame for selector: ${this.selector}`
2828
- );
3246
+ throw new ContentFrameNotFoundError(this.selector);
2829
3247
  } finally {
2830
3248
  yield parentSession2.send("Runtime.releaseObject", { objectId }).catch(() => {
2831
3249
  });
@@ -2922,8 +3340,8 @@ var init_frameLocator = __esm({
2922
3340
  });
2923
3341
 
2924
3342
  // lib/v3/understudy/deepLocator.ts
2925
- function parseXPath(path6) {
2926
- const s = path6.trim();
3343
+ function parseXPath(path7) {
3344
+ const s = path7.trim();
2927
3345
  let i = 0;
2928
3346
  const steps = [];
2929
3347
  while (i < s.length) {
@@ -2954,10 +3372,10 @@ function buildXPathFromSteps2(steps) {
2954
3372
  }
2955
3373
  function deepLocatorThroughIframes(page, root, xpathOrSelector) {
2956
3374
  return __async(this, null, function* () {
2957
- let path6 = xpathOrSelector.trim();
2958
- if (path6.startsWith("xpath=")) path6 = path6.slice("xpath=".length).trim();
2959
- if (!path6.startsWith("/")) path6 = "/" + path6;
2960
- const steps = parseXPath(path6);
3375
+ let path7 = xpathOrSelector.trim();
3376
+ if (path7.startsWith("xpath=")) path7 = path7.slice("xpath=".length).trim();
3377
+ if (!path7.startsWith("/")) path7 = "/" + path7;
3378
+ const steps = parseXPath(path7);
2961
3379
  let fl;
2962
3380
  let buf = [];
2963
3381
  const flushIntoFrameLocator = () => {
@@ -3019,6 +3437,7 @@ var init_deepLocator = __esm({
3019
3437
  init_locator();
3020
3438
  init_logger();
3021
3439
  init_frameLocator();
3440
+ init_sdkErrors();
3022
3441
  IFRAME_STEP_RE2 = /^iframe(?:\[\d+])?$/i;
3023
3442
  DeepLocatorDelegate = class _DeepLocatorDelegate {
3024
3443
  constructor(page, root, selector, nthIndex = 0) {
@@ -3134,7 +3553,9 @@ var init_deepLocator = __esm({
3134
3553
  nth(index) {
3135
3554
  const value = Number(index);
3136
3555
  if (!Number.isFinite(value) || value < 0) {
3137
- throw new Error("deepLocator().nth() expects a non-negative index");
3556
+ throw new StagehandInvalidArgumentError(
3557
+ "deepLocator().nth() expects a non-negative index"
3558
+ );
3138
3559
  }
3139
3560
  const nextIndex = Math.floor(value);
3140
3561
  if (nextIndex === this.nthIndex) return this;
@@ -3929,11 +4350,11 @@ var require_src = __commonJS({
3929
4350
  var require_is_docker = __commonJS({
3930
4351
  "../../node_modules/.pnpm/is-docker@2.2.1/node_modules/is-docker/index.js"(exports2, module2) {
3931
4352
  "use strict";
3932
- var fs8 = require("fs");
4353
+ var fs9 = require("fs");
3933
4354
  var isDocker;
3934
4355
  function hasDockerEnv() {
3935
4356
  try {
3936
- fs8.statSync("/.dockerenv");
4357
+ fs9.statSync("/.dockerenv");
3937
4358
  return true;
3938
4359
  } catch (_) {
3939
4360
  return false;
@@ -3941,7 +4362,7 @@ var require_is_docker = __commonJS({
3941
4362
  }
3942
4363
  function hasDockerCGroup() {
3943
4364
  try {
3944
- return fs8.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
4365
+ return fs9.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
3945
4366
  } catch (_) {
3946
4367
  return false;
3947
4368
  }
@@ -3960,7 +4381,7 @@ var require_is_wsl = __commonJS({
3960
4381
  "../../node_modules/.pnpm/is-wsl@2.2.0/node_modules/is-wsl/index.js"(exports2, module2) {
3961
4382
  "use strict";
3962
4383
  var os3 = require("os");
3963
- var fs8 = require("fs");
4384
+ var fs9 = require("fs");
3964
4385
  var isDocker = require_is_docker();
3965
4386
  var isWsl3 = () => {
3966
4387
  if (process.platform !== "linux") {
@@ -3973,7 +4394,7 @@ var require_is_wsl = __commonJS({
3973
4394
  return true;
3974
4395
  }
3975
4396
  try {
3976
- return fs8.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false;
4397
+ return fs9.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false;
3977
4398
  } catch (_) {
3978
4399
  return false;
3979
4400
  }
@@ -4049,14 +4470,23 @@ var init_consoleMessage = __esm({
4049
4470
  });
4050
4471
 
4051
4472
  // lib/v3/understudy/response.ts
4473
+ function isSerializableResponse(value) {
4474
+ if (!value || typeof value !== "object") return false;
4475
+ const candidate = value;
4476
+ if (typeof candidate.requestId !== "string") return false;
4477
+ if (!candidate.response || typeof candidate.response !== "object") {
4478
+ return false;
4479
+ }
4480
+ return true;
4481
+ }
4052
4482
  function createDeferred() {
4053
- let resolve3;
4483
+ let resolve2;
4054
4484
  let reject;
4055
4485
  const promise = new Promise((res, rej) => {
4056
- resolve3 = res;
4486
+ resolve2 = res;
4057
4487
  reject = rej;
4058
4488
  });
4059
- return { promise, resolve: resolve3, reject };
4489
+ return { promise, resolve: resolve2, reject };
4060
4490
  }
4061
4491
  function normaliseHeaderName(name) {
4062
4492
  return name.toLowerCase();
@@ -4081,7 +4511,8 @@ function parseHeadersText(headersText) {
4081
4511
  var Response;
4082
4512
  var init_response = __esm({
4083
4513
  "lib/v3/understudy/response.ts"() {
4084
- Response = class {
4514
+ init_sdkErrors();
4515
+ Response = class _Response {
4085
4516
  /**
4086
4517
  * Build a response wrapper from the CDP notification associated with a
4087
4518
  * navigation. The constructor captures the owning page/session so follow-up
@@ -4251,7 +4682,7 @@ var init_response = __esm({
4251
4682
  "Network.getResponseBody",
4252
4683
  { requestId: this.requestId }
4253
4684
  ).catch((error) => {
4254
- throw new Error(`Failed to retrieve response body: ${String(error)}`);
4685
+ throw new ResponseBodyError(String(error));
4255
4686
  });
4256
4687
  if (result.base64Encoded) {
4257
4688
  return Buffer.from(result.body, "base64");
@@ -4273,7 +4704,7 @@ var init_response = __esm({
4273
4704
  try {
4274
4705
  return JSON.parse(text);
4275
4706
  } catch (error) {
4276
- throw new Error(`Failed to parse JSON response: ${String(error)}`);
4707
+ throw new ResponseParseError(String(error));
4277
4708
  }
4278
4709
  });
4279
4710
  }
@@ -4308,6 +4739,33 @@ var init_response = __esm({
4308
4739
  this.headersObject[lower] = segments.join(", ");
4309
4740
  }
4310
4741
  }
4742
+ /**
4743
+ * Internal helper for creating a Response object from a Serializable
4744
+ * goto response from the Stagehand API
4745
+ */
4746
+ static fromSerializable(serialized, context) {
4747
+ var _a;
4748
+ const reconstructed = new _Response({
4749
+ page: context.page,
4750
+ session: context.session,
4751
+ requestId: serialized.requestId,
4752
+ frameId: serialized.frameId,
4753
+ loaderId: serialized.loaderId,
4754
+ response: serialized.response,
4755
+ fromServiceWorker: (_a = serialized.fromServiceWorkerFlag) != null ? _a : false
4756
+ });
4757
+ if (serialized.extraInfoHeaders) {
4758
+ reconstructed.applyExtraInfo({
4759
+ requestId: serialized.requestId,
4760
+ headers: serialized.extraInfoHeaders,
4761
+ headersText: serialized.extraInfoHeadersText
4762
+ });
4763
+ }
4764
+ if (serialized.finishedSettled) {
4765
+ reconstructed.markFinished(null);
4766
+ }
4767
+ return reconstructed;
4768
+ }
4311
4769
  /** Marks the response as finished and resolves the `finished()` promise. */
4312
4770
  markFinished(error) {
4313
4771
  if (this.finishedSettled) return;
@@ -4327,14 +4785,20 @@ var Frame;
4327
4785
  var init_frame = __esm({
4328
4786
  "lib/v3/understudy/frame.ts"() {
4329
4787
  init_locator();
4788
+ init_sdkErrors();
4330
4789
  Frame = class _Frame {
4331
- constructor(session, frameId, pageId) {
4790
+ constructor(session, frameId, pageId, remoteBrowser) {
4332
4791
  this.session = session;
4333
4792
  this.frameId = frameId;
4334
4793
  this.pageId = pageId;
4794
+ this.remoteBrowser = remoteBrowser;
4335
4795
  var _a;
4336
4796
  this.sessionId = (_a = this.session.id) != null ? _a : null;
4337
4797
  }
4798
+ /** True when the controlled browser runs on a different machine. */
4799
+ isBrowserRemote() {
4800
+ return this.remoteBrowser;
4801
+ }
4338
4802
  /** DOM.getNodeForLocation → DOM.describeNode */
4339
4803
  getNodeAtLocation(x, y) {
4340
4804
  return __async(this, null, function* () {
@@ -4433,7 +4897,9 @@ var init_frame = __esm({
4433
4897
  }
4434
4898
  );
4435
4899
  if (res.exceptionDetails) {
4436
- throw new Error((_a = res.exceptionDetails.text) != null ? _a : "Evaluation failed");
4900
+ throw new StagehandEvalError(
4901
+ (_a = res.exceptionDetails.text) != null ? _a : "Evaluation failed"
4902
+ );
4437
4903
  }
4438
4904
  return res.result.value;
4439
4905
  });
@@ -4482,7 +4948,14 @@ var init_frame = __esm({
4482
4948
  const collect = (tree) => {
4483
4949
  var _a;
4484
4950
  if (tree.frame.parentId === this.frameId) {
4485
- frames.push(new _Frame(this.session, tree.frame.id, this.pageId));
4951
+ frames.push(
4952
+ new _Frame(
4953
+ this.session,
4954
+ tree.frame.id,
4955
+ this.pageId,
4956
+ this.remoteBrowser
4957
+ )
4958
+ );
4486
4959
  }
4487
4960
  (_a = tree.childFrames) == null ? void 0 : _a.forEach(collect);
4488
4961
  };
@@ -4494,11 +4967,11 @@ var init_frame = __esm({
4494
4967
  waitForLoadState(state = "load") {
4495
4968
  return __async(this, null, function* () {
4496
4969
  yield this.session.send("Page.enable");
4497
- yield new Promise((resolve3) => {
4970
+ yield new Promise((resolve2) => {
4498
4971
  const handler = (evt) => {
4499
4972
  if (evt.frameId === this.frameId && evt.name === state) {
4500
4973
  this.session.off("Page.lifecycleEvent", handler);
4501
- resolve3();
4974
+ resolve2();
4502
4975
  }
4503
4976
  };
4504
4977
  this.session.on("Page.lifecycleEvent", handler);
@@ -5019,8 +5492,8 @@ var init_networkManager = __esm({
5019
5492
  }
5020
5493
  };
5021
5494
  const removeObserver = this.addObserver(observer);
5022
- const promise = new Promise((resolve3, reject) => {
5023
- resolveFn = resolve3;
5495
+ const promise = new Promise((resolve2, reject) => {
5496
+ resolveFn = resolve2;
5024
5497
  rejectFn = reject;
5025
5498
  });
5026
5499
  maybeIdle();
@@ -5086,6 +5559,7 @@ var init_networkManager = __esm({
5086
5559
  var LifecycleWatcher;
5087
5560
  var init_lifecycleWatcher = __esm({
5088
5561
  "lib/v3/understudy/lifecycleWatcher.ts"() {
5562
+ init_sdkErrors();
5089
5563
  init_network();
5090
5564
  LifecycleWatcher = class {
5091
5565
  /**
@@ -5223,7 +5697,7 @@ var init_lifecycleWatcher = __esm({
5223
5697
  timeRemaining(deadline) {
5224
5698
  const remaining = deadline - Date.now();
5225
5699
  if (remaining <= 0) {
5226
- throw new Error(`Lifecycle wait timed out after ${this.timeoutMs}ms`);
5700
+ throw new TimeoutError("Lifecycle wait", this.timeoutMs);
5227
5701
  }
5228
5702
  return remaining;
5229
5703
  }
@@ -5324,11 +5798,11 @@ var init_navigationResponseTracker = __esm({
5324
5798
  this.page = params.page;
5325
5799
  this.session = params.session;
5326
5800
  this.navigationCommandId = params.navigationCommandId;
5327
- this.responsePromise = new Promise((resolve3) => {
5801
+ this.responsePromise = new Promise((resolve2) => {
5328
5802
  this.resolveResponse = (value) => {
5329
5803
  if (this.responseResolved) return;
5330
5804
  this.responseResolved = true;
5331
- resolve3(value);
5805
+ resolve2(value);
5332
5806
  };
5333
5807
  });
5334
5808
  this.installListeners();
@@ -5520,11 +5994,15 @@ function normalizeScreenshotClip(clip) {
5520
5994
  const height = Number(clip.height);
5521
5995
  for (const [key, value] of Object.entries({ x, y, width, height })) {
5522
5996
  if (!Number.isFinite(value)) {
5523
- throw new Error(`screenshot: clip.${key} must be a finite number`);
5997
+ throw new StagehandInvalidArgumentError(
5998
+ `screenshot: clip.${key} must be a finite number`
5999
+ );
5524
6000
  }
5525
6001
  }
5526
6002
  if (width <= 0 || height <= 0) {
5527
- throw new Error("screenshot: clip width/height must be positive");
6003
+ throw new StagehandInvalidArgumentError(
6004
+ "screenshot: clip width/height must be positive"
6005
+ );
5528
6006
  }
5529
6007
  return { x, y, width, height };
5530
6008
  }
@@ -5813,6 +6291,7 @@ function withScreenshotTimeout(timeoutMs, task) {
5813
6291
  }
5814
6292
  var init_screenshotUtils = __esm({
5815
6293
  "lib/v3/understudy/screenshotUtils.ts"() {
6294
+ init_sdkErrors();
5816
6295
  }
5817
6296
  });
5818
6297
 
@@ -5821,10 +6300,10 @@ var page_exports = {};
5821
6300
  __export(page_exports, {
5822
6301
  Page: () => Page
5823
6302
  });
5824
- var import_fs5, LIFECYCLE_NAME, Page;
6303
+ var import_fs6, LIFECYCLE_NAME, Page;
5825
6304
  var init_page = __esm({
5826
6305
  "lib/v3/understudy/page.ts"() {
5827
- import_fs5 = require("fs");
6306
+ import_fs6 = require("fs");
5828
6307
  init_logger();
5829
6308
  init_frame();
5830
6309
  init_frameLocator();
@@ -5834,7 +6313,9 @@ var init_page = __esm({
5834
6313
  init_networkManager();
5835
6314
  init_lifecycleWatcher();
5836
6315
  init_navigationResponseTracker();
6316
+ init_response();
5837
6317
  init_consoleMessage();
6318
+ init_sdkErrors();
5838
6319
  init_screenshotUtils();
5839
6320
  LIFECYCLE_NAME = {
5840
6321
  load: "load",
@@ -5842,7 +6323,7 @@ var init_page = __esm({
5842
6323
  networkidle: "networkIdle"
5843
6324
  };
5844
6325
  Page = class _Page {
5845
- constructor(conn, mainSession, _targetId, mainFrameId, apiClient) {
6326
+ constructor(conn, mainSession, _targetId, mainFrameId, apiClient, browserIsRemote = false) {
5846
6327
  this.conn = conn;
5847
6328
  this.mainSession = mainSession;
5848
6329
  this._targetId = _targetId;
@@ -5867,12 +6348,14 @@ var init_page = __esm({
5867
6348
  this._pressedModifiers = /* @__PURE__ */ new Set();
5868
6349
  this.pageId = _targetId;
5869
6350
  this.apiClient = apiClient != null ? apiClient : null;
6351
+ this.browserIsRemote = browserIsRemote;
5870
6352
  if (mainSession.id) this.sessions.set(mainSession.id, mainSession);
5871
6353
  this.registry = new FrameRegistry(_targetId, mainFrameId);
5872
6354
  this.mainFrameWrapper = new Frame(
5873
6355
  this.mainSession,
5874
6356
  mainFrameId,
5875
- this.pageId
6357
+ this.pageId,
6358
+ this.browserIsRemote
5876
6359
  );
5877
6360
  this.networkManager = new NetworkManager();
5878
6361
  this.networkManager.trackSession(this.mainSession);
@@ -5972,7 +6455,7 @@ var init_page = __esm({
5972
6455
  * Factory: create Page and seed registry with the shallow tree from Page.getFrameTree.
5973
6456
  * Assumes Page domain is already enabled on the session passed in.
5974
6457
  */
5975
- static create(conn, session, targetId, apiClient, localBrowserLaunchOptions) {
6458
+ static create(conn, session, targetId, apiClient, localBrowserLaunchOptions, browserIsRemote = false) {
5976
6459
  return __async(this, null, function* () {
5977
6460
  var _a, _b, _c, _d;
5978
6461
  yield session.send("Page.enable").catch(() => {
@@ -5981,7 +6464,14 @@ var init_page = __esm({
5981
6464
  });
5982
6465
  const { frameTree } = yield session.send("Page.getFrameTree");
5983
6466
  const mainFrameId = frameTree.frame.id;
5984
- const page = new _Page(conn, session, targetId, mainFrameId, apiClient);
6467
+ const page = new _Page(
6468
+ conn,
6469
+ session,
6470
+ targetId,
6471
+ mainFrameId,
6472
+ apiClient,
6473
+ browserIsRemote
6474
+ );
5985
6475
  try {
5986
6476
  page._currentUrl = String((_b = (_a = frameTree == null ? void 0 : frameTree.frame) == null ? void 0 : _a.url) != null ? _b : page._currentUrl);
5987
6477
  if (localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.viewport) {
@@ -6029,7 +6519,12 @@ var init_page = __esm({
6029
6519
  if (newRoot !== prevRoot) {
6030
6520
  const oldOrd = (_b = this.frameOrdinals.get(prevRoot)) != null ? _b : 0;
6031
6521
  this.frameOrdinals.set(newRoot, oldOrd);
6032
- this.mainFrameWrapper = new Frame(this.mainSession, newRoot, this.pageId);
6522
+ this.mainFrameWrapper = new Frame(
6523
+ this.mainSession,
6524
+ newRoot,
6525
+ this.pageId,
6526
+ this.browserIsRemote
6527
+ );
6033
6528
  }
6034
6529
  if (frame.id === this.mainFrameId()) {
6035
6530
  try {
@@ -6135,7 +6630,7 @@ var init_page = __esm({
6135
6630
  const hit = this.frameCache.get(frameId);
6136
6631
  if (hit) return hit;
6137
6632
  const sess = this.getSessionForFrame(frameId);
6138
- const f = new Frame(sess, frameId, this.pageId);
6633
+ const f = new Frame(sess, frameId, this.pageId, this.browserIsRemote);
6139
6634
  this.frameCache.set(frameId, f);
6140
6635
  return f;
6141
6636
  }
@@ -6151,7 +6646,7 @@ var init_page = __esm({
6151
6646
  }
6152
6647
  on(event, listener) {
6153
6648
  if (event !== "console") {
6154
- throw new Error(`Unsupported event: ${event}`);
6649
+ throw new StagehandInvalidArgumentError(`Unsupported event: ${event}`);
6155
6650
  }
6156
6651
  const firstListener = this.consoleListeners.size === 0;
6157
6652
  this.consoleListeners.add(listener);
@@ -6162,7 +6657,7 @@ var init_page = __esm({
6162
6657
  }
6163
6658
  once(event, listener) {
6164
6659
  if (event !== "console") {
6165
- throw new Error(`Unsupported event: ${event}`);
6660
+ throw new StagehandInvalidArgumentError(`Unsupported event: ${event}`);
6166
6661
  }
6167
6662
  const wrapper = (message) => {
6168
6663
  this.off("console", wrapper);
@@ -6172,7 +6667,7 @@ var init_page = __esm({
6172
6667
  }
6173
6668
  off(event, listener) {
6174
6669
  if (event !== "console") {
6175
- throw new Error(`Unsupported event: ${event}`);
6670
+ throw new StagehandInvalidArgumentError(`Unsupported event: ${event}`);
6176
6671
  }
6177
6672
  this.consoleListeners.delete(listener);
6178
6673
  if (this.consoleListeners.size === 0) {
@@ -6361,13 +6856,19 @@ var init_page = __esm({
6361
6856
  });
6362
6857
  try {
6363
6858
  if (this.apiClient) {
6364
- yield this.apiClient.goto(
6859
+ const result = yield this.apiClient.goto(
6365
6860
  url,
6366
6861
  { waitUntil: options == null ? void 0 : options.waitUntil },
6367
6862
  this.mainFrameId()
6368
6863
  );
6369
6864
  this._currentUrl = url;
6370
- return null;
6865
+ if (isSerializableResponse(result)) {
6866
+ return Response.fromSerializable(result, {
6867
+ page: this,
6868
+ session: this.mainSession
6869
+ });
6870
+ }
6871
+ return result;
6371
6872
  }
6372
6873
  const response = yield this.mainSession.send(
6373
6874
  "Page.navigate",
@@ -6592,13 +7093,17 @@ var init_page = __esm({
6592
7093
  const opts = options != null ? options : {};
6593
7094
  const type = (_a = opts.type) != null ? _a : "png";
6594
7095
  if (type !== "png" && type !== "jpeg") {
6595
- throw new Error(`screenshot: unsupported image type "${type}"`);
7096
+ throw new StagehandInvalidArgumentError(
7097
+ `screenshot: unsupported image type "${type}"`
7098
+ );
6596
7099
  }
6597
7100
  if (opts.fullPage && opts.clip) {
6598
- throw new Error("screenshot: clip and fullPage cannot be used together");
7101
+ throw new StagehandInvalidArgumentError(
7102
+ "screenshot: clip and fullPage cannot be used together"
7103
+ );
6599
7104
  }
6600
7105
  if (type === "png" && typeof opts.quality === "number") {
6601
- throw new Error(
7106
+ throw new StagehandInvalidArgumentError(
6602
7107
  'screenshot: quality option is only valid for type="jpeg"'
6603
7108
  );
6604
7109
  }
@@ -6642,7 +7147,7 @@ var init_page = __esm({
6642
7147
  scale: captureScale
6643
7148
  });
6644
7149
  if (opts.path) {
6645
- yield import_fs5.promises.writeFile(opts.path, buffer);
7150
+ yield import_fs6.promises.writeFile(opts.path, buffer);
6646
7151
  }
6647
7152
  return buffer;
6648
7153
  } finally {
@@ -6735,7 +7240,7 @@ var init_page = __esm({
6735
7240
  );
6736
7241
  if (exceptionDetails) {
6737
7242
  const msg = exceptionDetails.text || ((_a = exceptionDetails.exception) == null ? void 0 : _a.description) || "Evaluation failed";
6738
- throw new Error(msg);
7243
+ throw new StagehandEvalError(msg);
6739
7244
  }
6740
7245
  return result == null ? void 0 : result.value;
6741
7246
  });
@@ -7316,7 +7821,7 @@ var init_page = __esm({
7316
7821
  } catch (e) {
7317
7822
  }
7318
7823
  const wanted = LIFECYCLE_NAME[state];
7319
- return new Promise((resolve3, reject) => {
7824
+ return new Promise((resolve2, reject) => {
7320
7825
  let done = false;
7321
7826
  let timer = null;
7322
7827
  const off = () => {
@@ -7332,7 +7837,7 @@ var init_page = __esm({
7332
7837
  timer = null;
7333
7838
  }
7334
7839
  off();
7335
- resolve3();
7840
+ resolve2();
7336
7841
  };
7337
7842
  const onLifecycle = (evt) => {
7338
7843
  if (evt.name !== wanted) return;
@@ -7374,9 +7879,12 @@ __export(v3_exports, {
7374
7879
  AnnotatedScreenshotText: () => AnnotatedScreenshotText,
7375
7880
  BrowserbaseSessionNotFoundError: () => BrowserbaseSessionNotFoundError,
7376
7881
  CaptchaTimeoutError: () => CaptchaTimeoutError,
7882
+ ConnectionTimeoutError: () => ConnectionTimeoutError,
7377
7883
  ConsoleMessage: () => ConsoleMessage,
7378
7884
  ContentFrameNotFoundError: () => ContentFrameNotFoundError,
7379
7885
  CreateChatCompletionResponseError: () => CreateChatCompletionResponseError,
7886
+ CuaModelRequiredError: () => CuaModelRequiredError,
7887
+ ElementNotVisibleError: () => ElementNotVisibleError,
7380
7888
  ExperimentalApiConflictError: () => ExperimentalApiConflictError,
7381
7889
  ExperimentalNotConfiguredError: () => ExperimentalNotConfiguredError,
7382
7890
  HandlerNotInitializedError: () => HandlerNotInitializedError,
@@ -7387,7 +7895,10 @@ __export(v3_exports, {
7387
7895
  MCPConnectionError: () => MCPConnectionError,
7388
7896
  MissingEnvironmentVariableError: () => MissingEnvironmentVariableError,
7389
7897
  MissingLLMConfigurationError: () => MissingLLMConfigurationError,
7898
+ PageNotFoundError: () => PageNotFoundError,
7390
7899
  Response: () => Response,
7900
+ ResponseBodyError: () => ResponseBodyError,
7901
+ ResponseParseError: () => ResponseParseError,
7391
7902
  Stagehand: () => V3,
7392
7903
  StagehandAPIError: () => StagehandAPIError,
7393
7904
  StagehandAPIUnauthorizedError: () => StagehandAPIUnauthorizedError,
@@ -7410,6 +7921,7 @@ __export(v3_exports, {
7410
7921
  StagehandShadowRootMissingError: () => StagehandShadowRootMissingError,
7411
7922
  StagehandShadowSegmentEmptyError: () => StagehandShadowSegmentEmptyError,
7412
7923
  StagehandShadowSegmentNotFoundError: () => StagehandShadowSegmentNotFoundError,
7924
+ TimeoutError: () => TimeoutError,
7413
7925
  UnsupportedAISDKModelProviderError: () => UnsupportedAISDKModelProviderError,
7414
7926
  UnsupportedModelError: () => UnsupportedModelError,
7415
7927
  UnsupportedModelProviderError: () => UnsupportedModelProviderError,
@@ -7437,236 +7949,13 @@ module.exports = __toCommonJS(v3_exports);
7437
7949
 
7438
7950
  // lib/v3/v3.ts
7439
7951
  var import_dotenv = __toESM(require("dotenv"));
7440
- var import_fs6 = __toESM(require("fs"));
7952
+ var import_fs7 = __toESM(require("fs"));
7441
7953
  var import_os2 = __toESM(require("os"));
7442
- var import_path5 = __toESM(require("path"));
7954
+ var import_path6 = __toESM(require("path"));
7443
7955
  var import_process2 = __toESM(require("process"));
7444
7956
 
7445
- // lib/version.ts
7446
- var STAGEHAND_VERSION = "3.0.2-test-cua-base-url";
7447
-
7448
- // lib/v3/types/public/sdkErrors.ts
7449
- var StagehandError = class extends Error {
7450
- constructor(message) {
7451
- super(message);
7452
- this.name = this.constructor.name;
7453
- }
7454
- };
7455
- var StagehandDefaultError = class extends StagehandError {
7456
- constructor(error) {
7457
- if (error instanceof Error || error instanceof StagehandError) {
7458
- super(
7459
- `
7460
- Hey! We're sorry you ran into an error.
7461
- Stagehand version: ${STAGEHAND_VERSION}
7462
- If you need help, please open a Github issue or reach out to us on Slack: https://stagehand.dev/slack
7463
-
7464
- Full error:
7465
- ${error.message}`
7466
- );
7467
- }
7468
- }
7469
- };
7470
- var StagehandEnvironmentError = class extends StagehandError {
7471
- constructor(currentEnvironment, requiredEnvironment, feature) {
7472
- super(
7473
- `You seem to be setting the current environment to ${currentEnvironment}.Ensure the environment is set to ${requiredEnvironment} if you want to use ${feature}.`
7474
- );
7475
- }
7476
- };
7477
- var MissingEnvironmentVariableError = class extends StagehandError {
7478
- constructor(missingEnvironmentVariable, feature) {
7479
- super(
7480
- `${missingEnvironmentVariable} is required to use ${feature}.Please set ${missingEnvironmentVariable} in your environment.`
7481
- );
7482
- }
7483
- };
7484
- var UnsupportedModelError = class extends StagehandError {
7485
- constructor(supportedModels, feature) {
7486
- super(
7487
- feature ? `${feature} requires one of the following models: ${supportedModels}` : `please use one of the supported models: ${supportedModels}`
7488
- );
7489
- }
7490
- };
7491
- var UnsupportedModelProviderError = class extends StagehandError {
7492
- constructor(supportedProviders, feature) {
7493
- super(
7494
- feature ? `${feature} requires one of the following model providers: ${supportedProviders}` : `please use one of the supported model providers: ${supportedProviders}`
7495
- );
7496
- }
7497
- };
7498
- var UnsupportedAISDKModelProviderError = class extends StagehandError {
7499
- constructor(provider, supportedProviders) {
7500
- super(
7501
- `${provider} is not currently supported for aiSDK. please use one of the supported model providers: ${supportedProviders}`
7502
- );
7503
- }
7504
- };
7505
- var InvalidAISDKModelFormatError = class extends StagehandError {
7506
- constructor(modelName) {
7507
- super(
7508
- `${modelName} does not follow correct format for specifying aiSDK models. Please define your model as 'provider/model-name'. For example: \`model: 'openai/gpt-4o-mini'\``
7509
- );
7510
- }
7511
- };
7512
- var StagehandNotInitializedError = class extends StagehandError {
7513
- constructor(prop) {
7514
- super(
7515
- `You seem to be calling \`${prop}\` on a page in an uninitialized \`Stagehand\` object. Ensure you are running \`await stagehand.init()\` on the Stagehand object before referencing the \`page\` object.`
7516
- );
7517
- }
7518
- };
7519
- var BrowserbaseSessionNotFoundError = class extends StagehandError {
7520
- constructor() {
7521
- super("No Browserbase session ID found");
7522
- }
7523
- };
7524
- var CaptchaTimeoutError = class extends StagehandError {
7525
- constructor() {
7526
- super("Captcha timeout");
7527
- }
7528
- };
7529
- var MissingLLMConfigurationError = class extends StagehandError {
7530
- constructor() {
7531
- super(
7532
- "No LLM API key or LLM Client configured. An LLM API key or a custom LLM Client is required to use act, extract, or observe."
7533
- );
7534
- }
7535
- };
7536
- var HandlerNotInitializedError = class extends StagehandError {
7537
- constructor(handlerType) {
7538
- super(`${handlerType} handler not initialized`);
7539
- }
7540
- };
7541
- var StagehandInvalidArgumentError = class extends StagehandError {
7542
- constructor(message) {
7543
- super(`InvalidArgumentError: ${message}`);
7544
- }
7545
- };
7546
- var StagehandElementNotFoundError = class extends StagehandError {
7547
- constructor(xpaths) {
7548
- super(`Could not find an element for the given xPath(s): ${xpaths}`);
7549
- }
7550
- };
7551
- var AgentScreenshotProviderError = class extends StagehandError {
7552
- constructor(message) {
7553
- super(`ScreenshotProviderError: ${message}`);
7554
- }
7555
- };
7556
- var StagehandMissingArgumentError = class extends StagehandError {
7557
- constructor(message) {
7558
- super(`MissingArgumentError: ${message}`);
7559
- }
7560
- };
7561
- var CreateChatCompletionResponseError = class extends StagehandError {
7562
- constructor(message) {
7563
- super(`CreateChatCompletionResponseError: ${message}`);
7564
- }
7565
- };
7566
- var StagehandEvalError = class extends StagehandError {
7567
- constructor(message) {
7568
- super(`StagehandEvalError: ${message}`);
7569
- }
7570
- };
7571
- var StagehandDomProcessError = class extends StagehandError {
7572
- constructor(message) {
7573
- super(`Error Processing Dom: ${message}`);
7574
- }
7575
- };
7576
- var StagehandClickError = class extends StagehandError {
7577
- constructor(message, selector) {
7578
- super(
7579
- `Error Clicking Element with selector: ${selector} Reason: ${message}`
7580
- );
7581
- }
7582
- };
7583
- var LLMResponseError = class extends StagehandError {
7584
- constructor(primitive, message) {
7585
- super(`${primitive} LLM response error: ${message}`);
7586
- }
7587
- };
7588
- var StagehandIframeError = class extends StagehandError {
7589
- constructor(frameUrl, message) {
7590
- super(
7591
- `Unable to resolve frameId for iframe with URL: ${frameUrl} Full error: ${message}`
7592
- );
7593
- }
7594
- };
7595
- var ContentFrameNotFoundError = class extends StagehandError {
7596
- constructor(selector) {
7597
- super(`Unable to obtain a content frame for selector: ${selector}`);
7598
- }
7599
- };
7600
- var XPathResolutionError = class extends StagehandError {
7601
- constructor(xpath) {
7602
- super(`XPath "${xpath}" does not resolve in the current page or frames`);
7603
- }
7604
- };
7605
- var ExperimentalApiConflictError = class extends StagehandError {
7606
- constructor() {
7607
- super(
7608
- "`experimental` mode cannot be used together with the Stagehand API. To use experimental features, set experimental: true, and useApi: false in the stagehand constructor. To use the Stagehand API, set experimental: false and useApi: true in the stagehand constructor. "
7609
- );
7610
- }
7611
- };
7612
- var ExperimentalNotConfiguredError = class extends StagehandError {
7613
- constructor(featureName) {
7614
- super(`Feature "${featureName}" is an experimental feature, and cannot be configured when useAPI: true.
7615
- Please set experimental: true and useAPI: false in the stagehand constructor to use this feature.
7616
- If you wish to use the Stagehand API, please ensure ${featureName} is not defined in your function call,
7617
- and set experimental: false, useAPI: true in the Stagehand constructor. `);
7618
- }
7619
- };
7620
- var ZodSchemaValidationError = class extends Error {
7621
- constructor(received, issues) {
7622
- super(`Zod schema validation failed
7623
-
7624
- \u2014 Received \u2014
7625
- ${JSON.stringify(received, null, 2)}
7626
-
7627
- \u2014 Issues \u2014
7628
- ${JSON.stringify(issues, null, 2)}`);
7629
- this.received = received;
7630
- this.issues = issues;
7631
- this.name = "ZodSchemaValidationError";
7632
- }
7633
- };
7634
- var StagehandInitError = class extends StagehandError {
7635
- constructor(message) {
7636
- super(message);
7637
- }
7638
- };
7639
- var MCPConnectionError = class extends StagehandError {
7640
- constructor(serverUrl, originalError) {
7641
- const errorMessage = originalError instanceof Error ? originalError.message : String(originalError);
7642
- super(
7643
- `Failed to connect to MCP server at "${serverUrl}". ${errorMessage}. Please verify the server URL is correct and the server is running.`
7644
- );
7645
- this.serverUrl = serverUrl;
7646
- this.originalError = originalError;
7647
- }
7648
- };
7649
- var StagehandShadowRootMissingError = class extends StagehandError {
7650
- constructor(detail) {
7651
- super(
7652
- `No shadow root present on the resolved host` + (detail ? `: ${detail}` : "")
7653
- );
7654
- }
7655
- };
7656
- var StagehandShadowSegmentEmptyError = class extends StagehandError {
7657
- constructor() {
7658
- super(`Empty selector segment after shadow-DOM hop ("//")`);
7659
- }
7660
- };
7661
- var StagehandShadowSegmentNotFoundError = class extends StagehandError {
7662
- constructor(segment, hint) {
7663
- super(
7664
- `Shadow segment '${segment}' matched no element inside shadow root` + (hint ? ` ${hint}` : "")
7665
- );
7666
- }
7667
- };
7668
-
7669
7957
  // lib/utils.ts
7958
+ init_sdkErrors();
7670
7959
  var import_genai = require("@google/genai");
7671
7960
  var import_v3 = require("zod/v3");
7672
7961
  var ID_PATTERN = /^\d+-\d+$/;
@@ -7905,9 +8194,9 @@ function transformSchema(schema, currentPath) {
7905
8194
  }
7906
8195
  return [schema, []];
7907
8196
  }
7908
- function injectUrls(obj, path6, idToUrlMapping) {
8197
+ function injectUrls(obj, path7, idToUrlMapping) {
7909
8198
  var _a, _b;
7910
- if (path6.length === 0) return;
8199
+ if (path7.length === 0) return;
7911
8200
  const toId = (value) => {
7912
8201
  if (typeof value === "number") {
7913
8202
  return String(value);
@@ -7917,7 +8206,7 @@ function injectUrls(obj, path6, idToUrlMapping) {
7917
8206
  }
7918
8207
  return void 0;
7919
8208
  };
7920
- const [key, ...rest] = path6;
8209
+ const [key, ...rest] = path7;
7921
8210
  if (key === "*") {
7922
8211
  if (Array.isArray(obj)) {
7923
8212
  if (rest.length === 0) {
@@ -7935,7 +8224,7 @@ function injectUrls(obj, path6, idToUrlMapping) {
7935
8224
  }
7936
8225
  if (obj && typeof obj === "object") {
7937
8226
  const record = obj;
7938
- if (path6.length === 1) {
8227
+ if (path7.length === 1) {
7939
8228
  const fieldValue = record[key];
7940
8229
  const id = toId(fieldValue);
7941
8230
  if (id !== void 0) {
@@ -7992,8 +8281,8 @@ function loadApiKeyFromEnv(provider, logger) {
7992
8281
  }
7993
8282
  return void 0;
7994
8283
  }
7995
- function trimTrailingTextNode(path6) {
7996
- return path6 == null ? void 0 : path6.replace(/\/text\(\)(\[\d+\])?$/iu, "");
8284
+ function trimTrailingTextNode(path7) {
8285
+ return path7 == null ? void 0 : path7.replace(/\/text\(\)(\[\d+\])?$/iu, "");
7997
8286
  }
7998
8287
  function jsonSchemaToZod(schema) {
7999
8288
  switch (schema.type) {
@@ -8326,6 +8615,7 @@ function safeGetPageUrl(page) {
8326
8615
  }
8327
8616
 
8328
8617
  // lib/v3/cache/ActCache.ts
8618
+ init_sdkErrors();
8329
8619
  var ActCache = class {
8330
8620
  constructor({
8331
8621
  storage,
@@ -8369,12 +8659,12 @@ var ActCache = class {
8369
8659
  const {
8370
8660
  value: entry,
8371
8661
  error,
8372
- path: path6
8662
+ path: path7
8373
8663
  } = yield this.storage.readJson(`${context.cacheKey}.json`);
8374
- if (error && path6) {
8664
+ if (error && path7) {
8375
8665
  this.logger({
8376
8666
  category: "cache",
8377
- message: `failed to read act cache entry: ${path6}`,
8667
+ message: `failed to read act cache entry: ${path7}`,
8378
8668
  level: 2,
8379
8669
  auxiliary: {
8380
8670
  error: { value: String(error), type: "string" }
@@ -8415,11 +8705,11 @@ var ActCache = class {
8415
8705
  actionDescription: result.actionDescription,
8416
8706
  message: result.message
8417
8707
  };
8418
- const { error, path: path6 } = yield this.storage.writeJson(
8708
+ const { error, path: path7 } = yield this.storage.writeJson(
8419
8709
  `${context.cacheKey}.json`,
8420
8710
  entry
8421
8711
  );
8422
- if (error && path6) {
8712
+ if (error && path7) {
8423
8713
  this.logger({
8424
8714
  category: "cache",
8425
8715
  message: "failed to write act cache entry",
@@ -8453,7 +8743,7 @@ var ActCache = class {
8453
8743
  return __async(this, null, function* () {
8454
8744
  const handler = this.getActHandler();
8455
8745
  if (!handler) {
8456
- throw new Error("V3 not initialized. Call init() before act().");
8746
+ throw new StagehandNotInitializedError("act()");
8457
8747
  }
8458
8748
  const execute = () => __async(this, null, function* () {
8459
8749
  var _a, _b, _c;
@@ -8537,11 +8827,11 @@ var ActCache = class {
8537
8827
  }
8538
8828
  refreshCacheEntry(context, entry) {
8539
8829
  return __async(this, null, function* () {
8540
- const { error, path: path6 } = yield this.storage.writeJson(
8830
+ const { error, path: path7 } = yield this.storage.writeJson(
8541
8831
  `${context.cacheKey}.json`,
8542
8832
  entry
8543
8833
  );
8544
- if (error && path6) {
8834
+ if (error && path7) {
8545
8835
  this.logger({
8546
8836
  category: "cache",
8547
8837
  message: "failed to update act cache entry after self-heal",
@@ -8568,14 +8858,14 @@ var ActCache = class {
8568
8858
  if (!timeout) {
8569
8859
  return yield run();
8570
8860
  }
8571
- return yield new Promise((resolve3, reject) => {
8861
+ return yield new Promise((resolve2, reject) => {
8572
8862
  const timer = setTimeout(() => {
8573
8863
  reject(new Error(`act() timed out after ${timeout}ms`));
8574
8864
  }, timeout);
8575
8865
  void run().then(
8576
8866
  (value) => {
8577
8867
  clearTimeout(timer);
8578
- resolve3(value);
8868
+ resolve2(value);
8579
8869
  },
8580
8870
  (err) => {
8581
8871
  clearTimeout(timer);
@@ -8683,14 +8973,14 @@ var AgentCache = class {
8683
8973
  const {
8684
8974
  value: entry,
8685
8975
  error,
8686
- path: path6
8976
+ path: path7
8687
8977
  } = yield this.storage.readJson(
8688
8978
  `agent-${context.cacheKey}.json`
8689
8979
  );
8690
- if (error && path6) {
8980
+ if (error && path7) {
8691
8981
  this.logger({
8692
8982
  category: "cache",
8693
- message: `failed to read agent cache entry: ${path6}`,
8983
+ message: `failed to read agent cache entry: ${path7}`,
8694
8984
  level: 1,
8695
8985
  auxiliary: {
8696
8986
  error: { value: String(error), type: "string" }
@@ -8726,11 +9016,11 @@ var AgentCache = class {
8726
9016
  result: cloneForCache(result),
8727
9017
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
8728
9018
  };
8729
- const { error, path: path6 } = yield this.storage.writeJson(
9019
+ const { error, path: path7 } = yield this.storage.writeJson(
8730
9020
  `agent-${context.cacheKey}.json`,
8731
9021
  entry
8732
9022
  );
8733
- if (error && path6) {
9023
+ if (error && path7) {
8734
9024
  this.logger({
8735
9025
  category: "cache",
8736
9026
  message: "failed to write agent cache entry",
@@ -8842,6 +9132,8 @@ var AgentCache = class {
8842
9132
  result.usage = {
8843
9133
  input_tokens: 0,
8844
9134
  output_tokens: 0,
9135
+ reasoning_tokens: 0,
9136
+ cached_input_tokens: 0,
8845
9137
  inference_time_ms: 0
8846
9138
  };
8847
9139
  result.metadata = __spreadProps(__spreadValues({}, (_b = result.metadata) != null ? _b : {}), {
@@ -8966,7 +9258,7 @@ var AgentCache = class {
8966
9258
  replayAgentWaitStep(step) {
8967
9259
  return __async(this, null, function* () {
8968
9260
  if (!step.timeMs || step.timeMs <= 0) return;
8969
- yield new Promise((resolve3) => setTimeout(resolve3, step.timeMs));
9261
+ yield new Promise((resolve2) => setTimeout(resolve2, step.timeMs));
8970
9262
  });
8971
9263
  }
8972
9264
  replayAgentNavBackStep(step, ctx) {
@@ -9316,7 +9608,7 @@ function extract(_0) {
9316
9608
  userProvidedInstructions,
9317
9609
  logInferenceToFile = false
9318
9610
  }) {
9319
- var _a, _b, _c, _d, _e, _f, _g, _h;
9611
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
9320
9612
  const metadataSchema = import_v32.z.object({
9321
9613
  progress: import_v32.z.string().describe(
9322
9614
  "progress of what has been extracted so far, as concise as possible"
@@ -9380,6 +9672,8 @@ function extract(_0) {
9380
9672
  LLM_output_file: extractResponseFile,
9381
9673
  prompt_tokens: (_a = extractUsage == null ? void 0 : extractUsage.prompt_tokens) != null ? _a : 0,
9382
9674
  completion_tokens: (_b = extractUsage == null ? void 0 : extractUsage.completion_tokens) != null ? _b : 0,
9675
+ reasoning_tokens: (_c = extractUsage == null ? void 0 : extractUsage.reasoning_tokens) != null ? _c : 0,
9676
+ cached_input_tokens: (_d = extractUsage == null ? void 0 : extractUsage.cached_input_tokens) != null ? _d : 0,
9383
9677
  inference_time_ms: extractEndTime - extractStartTime
9384
9678
  });
9385
9679
  }
@@ -9441,14 +9735,18 @@ function extract(_0) {
9441
9735
  timestamp: metadataCallTimestamp,
9442
9736
  LLM_input_file: metadataCallFile,
9443
9737
  LLM_output_file: metadataResponseFile,
9444
- prompt_tokens: (_c = metadataResponseUsage == null ? void 0 : metadataResponseUsage.prompt_tokens) != null ? _c : 0,
9445
- completion_tokens: (_d = metadataResponseUsage == null ? void 0 : metadataResponseUsage.completion_tokens) != null ? _d : 0,
9738
+ prompt_tokens: (_e = metadataResponseUsage == null ? void 0 : metadataResponseUsage.prompt_tokens) != null ? _e : 0,
9739
+ completion_tokens: (_f = metadataResponseUsage == null ? void 0 : metadataResponseUsage.completion_tokens) != null ? _f : 0,
9740
+ reasoning_tokens: (_g = metadataResponseUsage == null ? void 0 : metadataResponseUsage.reasoning_tokens) != null ? _g : 0,
9741
+ cached_input_tokens: (_h = metadataResponseUsage == null ? void 0 : metadataResponseUsage.cached_input_tokens) != null ? _h : 0,
9446
9742
  inference_time_ms: metadataEndTime - metadataStartTime
9447
9743
  });
9448
9744
  }
9449
- const totalPromptTokens = ((_e = extractUsage == null ? void 0 : extractUsage.prompt_tokens) != null ? _e : 0) + ((_f = metadataResponseUsage == null ? void 0 : metadataResponseUsage.prompt_tokens) != null ? _f : 0);
9450
- const totalCompletionTokens = ((_g = extractUsage == null ? void 0 : extractUsage.completion_tokens) != null ? _g : 0) + ((_h = metadataResponseUsage == null ? void 0 : metadataResponseUsage.completion_tokens) != null ? _h : 0);
9745
+ const totalPromptTokens = ((_i = extractUsage == null ? void 0 : extractUsage.prompt_tokens) != null ? _i : 0) + ((_j = metadataResponseUsage == null ? void 0 : metadataResponseUsage.prompt_tokens) != null ? _j : 0);
9746
+ const totalCompletionTokens = ((_k = extractUsage == null ? void 0 : extractUsage.completion_tokens) != null ? _k : 0) + ((_l = metadataResponseUsage == null ? void 0 : metadataResponseUsage.completion_tokens) != null ? _l : 0);
9451
9747
  const totalInferenceTimeMs = extractEndTime - extractStartTime + (metadataEndTime - metadataStartTime);
9748
+ const totalReasoningTokens = ((_m = extractUsage == null ? void 0 : extractUsage.reasoning_tokens) != null ? _m : 0) + ((_n = metadataResponseUsage == null ? void 0 : metadataResponseUsage.reasoning_tokens) != null ? _n : 0);
9749
+ const totalCachedInputTokens = ((_o = extractUsage == null ? void 0 : extractUsage.cached_input_tokens) != null ? _o : 0) + ((_p = metadataResponseUsage == null ? void 0 : metadataResponseUsage.cached_input_tokens) != null ? _p : 0);
9452
9750
  return __spreadProps(__spreadValues({}, extractedData), {
9453
9751
  metadata: {
9454
9752
  completed: metadataResponseCompleted,
@@ -9456,6 +9754,8 @@ function extract(_0) {
9456
9754
  },
9457
9755
  prompt_tokens: totalPromptTokens,
9458
9756
  completion_tokens: totalCompletionTokens,
9757
+ reasoning_tokens: totalReasoningTokens,
9758
+ cached_input_tokens: totalCachedInputTokens,
9459
9759
  inference_time_ms: totalInferenceTimeMs
9460
9760
  });
9461
9761
  });
@@ -9469,7 +9769,7 @@ function observe(_0) {
9469
9769
  logger,
9470
9770
  logInferenceToFile = false
9471
9771
  }) {
9472
- var _a, _b, _c, _d;
9772
+ var _a, _b, _c, _d, _e, _f;
9473
9773
  const isGPT5 = llmClient.modelName.includes("gpt-5");
9474
9774
  const observeSchema = import_v32.z.object({
9475
9775
  elements: import_v32.z.array(
@@ -9529,6 +9829,8 @@ function observe(_0) {
9529
9829
  const { data: observeData, usage: observeUsage } = rawResponse;
9530
9830
  const promptTokens = (_a = observeUsage == null ? void 0 : observeUsage.prompt_tokens) != null ? _a : 0;
9531
9831
  const completionTokens = (_b = observeUsage == null ? void 0 : observeUsage.completion_tokens) != null ? _b : 0;
9832
+ const reasoningTokens = (_c = observeUsage == null ? void 0 : observeUsage.reasoning_tokens) != null ? _c : 0;
9833
+ const cachedInputTokens = (_d = observeUsage == null ? void 0 : observeUsage.cached_input_tokens) != null ? _d : 0;
9532
9834
  let responseFile = "";
9533
9835
  if (logInferenceToFile) {
9534
9836
  const { fileName: responseFileName } = writeTimestampedTxtFile(
@@ -9547,10 +9849,12 @@ function observe(_0) {
9547
9849
  LLM_output_file: responseFile,
9548
9850
  prompt_tokens: promptTokens,
9549
9851
  completion_tokens: completionTokens,
9852
+ reasoning_tokens: reasoningTokens,
9853
+ cached_input_tokens: cachedInputTokens,
9550
9854
  inference_time_ms: usageTimeMs
9551
9855
  });
9552
9856
  }
9553
- const parsedElements = (_d = (_c = observeData.elements) == null ? void 0 : _c.map((el) => {
9857
+ const parsedElements = (_f = (_e = observeData.elements) == null ? void 0 : _e.map((el) => {
9554
9858
  const base = {
9555
9859
  elementId: el.elementId,
9556
9860
  description: String(el.description),
@@ -9558,11 +9862,13 @@ function observe(_0) {
9558
9862
  arguments: el.arguments
9559
9863
  };
9560
9864
  return base;
9561
- })) != null ? _d : [];
9865
+ })) != null ? _f : [];
9562
9866
  return {
9563
9867
  elements: parsedElements,
9564
9868
  prompt_tokens: promptTokens,
9565
9869
  completion_tokens: completionTokens,
9870
+ reasoning_tokens: reasoningTokens,
9871
+ cached_input_tokens: cachedInputTokens,
9566
9872
  inference_time_ms: usageTimeMs
9567
9873
  };
9568
9874
  });
@@ -9576,7 +9882,7 @@ function act(_0) {
9576
9882
  logger,
9577
9883
  logInferenceToFile = false
9578
9884
  }) {
9579
- var _a, _b;
9885
+ var _a, _b, _c, _d;
9580
9886
  const isGPT5 = llmClient.modelName.includes("gpt-5");
9581
9887
  const actSchema = import_v32.z.object({
9582
9888
  elementId: import_v32.z.string().describe(
@@ -9631,6 +9937,8 @@ function act(_0) {
9631
9937
  const { data: actData, usage: actUsage } = rawResponse;
9632
9938
  const promptTokens = (_a = actUsage == null ? void 0 : actUsage.prompt_tokens) != null ? _a : 0;
9633
9939
  const completionTokens = (_b = actUsage == null ? void 0 : actUsage.completion_tokens) != null ? _b : 0;
9940
+ const reasoningTokens = (_c = actUsage == null ? void 0 : actUsage.reasoning_tokens) != null ? _c : 0;
9941
+ const cachedInputTokens = (_d = actUsage == null ? void 0 : actUsage.cached_input_tokens) != null ? _d : 0;
9634
9942
  let responseFile = "";
9635
9943
  if (logInferenceToFile) {
9636
9944
  const { fileName: responseFileName } = writeTimestampedTxtFile(
@@ -9649,6 +9957,8 @@ function act(_0) {
9649
9957
  LLM_output_file: responseFile,
9650
9958
  prompt_tokens: promptTokens,
9651
9959
  completion_tokens: completionTokens,
9960
+ reasoning_tokens: reasoningTokens,
9961
+ cached_input_tokens: cachedInputTokens,
9652
9962
  inference_time_ms: usageTimeMs
9653
9963
  });
9654
9964
  }
@@ -9662,6 +9972,8 @@ function act(_0) {
9662
9972
  element: parsedElement,
9663
9973
  prompt_tokens: promptTokens,
9664
9974
  completion_tokens: completionTokens,
9975
+ reasoning_tokens: reasoningTokens,
9976
+ cached_input_tokens: cachedInputTokens,
9665
9977
  inference_time_ms: usageTimeMs,
9666
9978
  twoStep: actData.twoStep
9667
9979
  };
@@ -9707,6 +10019,7 @@ var SupportedPlaywrightAction = /* @__PURE__ */ ((SupportedPlaywrightAction2) =>
9707
10019
  // lib/v3/handlers/handlerUtils/actHandlerUtils.ts
9708
10020
  init_deepLocator();
9709
10021
  init_logger();
10022
+ init_sdkErrors();
9710
10023
  var UnderstudyCommandException = class extends Error {
9711
10024
  constructor(message) {
9712
10025
  super(message);
@@ -10210,7 +10523,7 @@ function waitForDomNetworkQuiet(frame, timeoutMs) {
10210
10523
  ]
10211
10524
  }).catch(() => {
10212
10525
  });
10213
- return new Promise((resolve3) => {
10526
+ return new Promise((resolve2) => {
10214
10527
  const inflight = /* @__PURE__ */ new Set();
10215
10528
  const meta = /* @__PURE__ */ new Map();
10216
10529
  const docByFrame = /* @__PURE__ */ new Map();
@@ -10301,7 +10614,7 @@ function waitForDomNetworkQuiet(frame, timeoutMs) {
10301
10614
  if (quietTimer) clearTimeout(quietTimer);
10302
10615
  if (stalledRequestSweepTimer) clearInterval(stalledRequestSweepTimer);
10303
10616
  clearTimeout(guard);
10304
- resolve3();
10617
+ resolve2();
10305
10618
  };
10306
10619
  });
10307
10620
  });
@@ -10351,7 +10664,7 @@ var ActHandler = class {
10351
10664
  const { instruction, page, variables, timeout, model } = params;
10352
10665
  const llmClient = this.resolveLlmClient(model);
10353
10666
  const doObserveAndAct = () => __async(this, null, function* () {
10354
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
10667
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
10355
10668
  yield waitForDomNetworkQuiet(
10356
10669
  page.mainFrame(),
10357
10670
  this.defaultDomSettleTimeoutMs
@@ -10376,12 +10689,16 @@ var ActHandler = class {
10376
10689
  });
10377
10690
  const actPromptTokens = (_b = actInferenceResponse.prompt_tokens) != null ? _b : 0;
10378
10691
  const actCompletionTokens = (_c = actInferenceResponse.completion_tokens) != null ? _c : 0;
10379
- const actInferenceTimeMs = (_d = actInferenceResponse.inference_time_ms) != null ? _d : 0;
10380
- (_e = this.onMetrics) == null ? void 0 : _e.call(
10692
+ const actReasoningTokens = (_d = actInferenceResponse.reasoning_tokens) != null ? _d : 0;
10693
+ const actCachedInputTokens = (_e = actInferenceResponse.cached_input_tokens) != null ? _e : 0;
10694
+ const actInferenceTimeMs = (_f = actInferenceResponse.inference_time_ms) != null ? _f : 0;
10695
+ (_g = this.onMetrics) == null ? void 0 : _g.call(
10381
10696
  this,
10382
10697
  "ACT" /* ACT */,
10383
10698
  actPromptTokens,
10384
10699
  actCompletionTokens,
10700
+ actReasoningTokens,
10701
+ actCachedInputTokens,
10385
10702
  actInferenceTimeMs
10386
10703
  );
10387
10704
  const raw = actInferenceResponse.element;
@@ -10446,7 +10763,7 @@ var ActHandler = class {
10446
10763
  if (!diffedTree.trim()) {
10447
10764
  diffedTree = combinedTree2;
10448
10765
  }
10449
- const combinedXpathMap2 = (_f = secondSnapshot.combinedXpathMap) != null ? _f : {};
10766
+ const combinedXpathMap2 = (_h = secondSnapshot.combinedXpathMap) != null ? _h : {};
10450
10767
  const previousAction = `method: ${chosen.method}, description: ${chosen.description}, arguments: ${chosen.arguments}`;
10451
10768
  const stepTwoInstructions = buildStepTwoPrompt(
10452
10769
  instruction,
@@ -10464,12 +10781,14 @@ var ActHandler = class {
10464
10781
  logger: v3Logger,
10465
10782
  logInferenceToFile: this.logInferenceToFile
10466
10783
  });
10467
- (_j = this.onMetrics) == null ? void 0 : _j.call(
10784
+ (_n = this.onMetrics) == null ? void 0 : _n.call(
10468
10785
  this,
10469
10786
  "ACT" /* ACT */,
10470
- (_g = action2.prompt_tokens) != null ? _g : 0,
10471
- (_h = action2.completion_tokens) != null ? _h : 0,
10472
- (_i = action2.inference_time_ms) != null ? _i : 0
10787
+ (_i = action2.prompt_tokens) != null ? _i : 0,
10788
+ (_j = action2.completion_tokens) != null ? _j : 0,
10789
+ (_k = action2.reasoning_tokens) != null ? _k : 0,
10790
+ (_l = action2.cached_input_tokens) != null ? _l : 0,
10791
+ (_m = action2.inference_time_ms) != null ? _m : 0
10473
10792
  );
10474
10793
  const raw2 = action2.element;
10475
10794
  const result2 = (() => {
@@ -10537,7 +10856,7 @@ var ActHandler = class {
10537
10856
  }
10538
10857
  actFromObserveResult(action, page, domSettleTimeoutMs, llmClientOverride) {
10539
10858
  return __async(this, null, function* () {
10540
- var _a, _b, _c, _d, _e, _f;
10859
+ var _a, _b, _c, _d, _e, _f, _g, _h;
10541
10860
  const settleTimeout = domSettleTimeoutMs != null ? domSettleTimeoutMs : this.defaultDomSettleTimeoutMs;
10542
10861
  const effectiveClient = llmClientOverride != null ? llmClientOverride : this.llmClient;
10543
10862
  const method = (_a = action.method) == null ? void 0 : _a.trim();
@@ -10614,12 +10933,14 @@ var ActHandler = class {
10614
10933
  logger: v3Logger,
10615
10934
  logInferenceToFile: this.logInferenceToFile
10616
10935
  });
10617
- (_e = this.onMetrics) == null ? void 0 : _e.call(
10936
+ (_g = this.onMetrics) == null ? void 0 : _g.call(
10618
10937
  this,
10619
10938
  "ACT" /* ACT */,
10620
10939
  (_b = actInferenceResponse.prompt_tokens) != null ? _b : 0,
10621
10940
  (_c = actInferenceResponse.completion_tokens) != null ? _c : 0,
10622
- (_d = actInferenceResponse.inference_time_ms) != null ? _d : 0
10941
+ (_d = actInferenceResponse.reasoning_tokens) != null ? _d : 0,
10942
+ (_e = actInferenceResponse.cached_input_tokens) != null ? _e : 0,
10943
+ (_f = actInferenceResponse.inference_time_ms) != null ? _f : 0
10623
10944
  );
10624
10945
  const fallback = actInferenceResponse.element;
10625
10946
  if (!fallback) {
@@ -10633,7 +10954,7 @@ var ActHandler = class {
10633
10954
  let newSelector = action.selector;
10634
10955
  if (typeof fallback.elementId === "string") {
10635
10956
  const enc = fallback.elementId;
10636
- const rawXp = ((_f = snapshot.combinedXpathMap) != null ? _f : {})[enc];
10957
+ const rawXp = ((_h = snapshot.combinedXpathMap) != null ? _h : {})[enc];
10637
10958
  const trimmed = trimTrailingTextNode(rawXp);
10638
10959
  if (trimmed) newSelector = `xpath=${trimmed}`;
10639
10960
  }
@@ -10683,6 +11004,7 @@ var ActHandler = class {
10683
11004
  init_logger();
10684
11005
  init_snapshot();
10685
11006
  var import_v34 = require("zod/v3");
11007
+ init_sdkErrors();
10686
11008
  function transformUrlStringsToNumericIds(schema) {
10687
11009
  const [finalSchema, urlPaths] = transformSchema(schema, []);
10688
11010
  return [finalSchema, urlPaths];
@@ -10715,7 +11037,7 @@ var ExtractHandler = class {
10715
11037
  return pageTextSchema.parse(result);
10716
11038
  }
10717
11039
  if (!instruction && schema) {
10718
- throw new Error(
11040
+ throw new StagehandInvalidArgumentError(
10719
11041
  "extract() requires an instruction when a schema is provided."
10720
11042
  );
10721
11043
  }
@@ -10751,11 +11073,15 @@ var ExtractHandler = class {
10751
11073
  metadata: { completed },
10752
11074
  prompt_tokens,
10753
11075
  completion_tokens,
11076
+ reasoning_tokens = 0,
11077
+ cached_input_tokens = 0,
10754
11078
  inference_time_ms
10755
11079
  } = _d, rest = __objRest(_d, [
10756
11080
  "metadata",
10757
11081
  "prompt_tokens",
10758
11082
  "completion_tokens",
11083
+ "reasoning_tokens",
11084
+ "cached_input_tokens",
10759
11085
  "inference_time_ms"
10760
11086
  ]);
10761
11087
  let output = rest;
@@ -10780,6 +11106,8 @@ var ExtractHandler = class {
10780
11106
  "EXTRACT" /* EXTRACT */,
10781
11107
  prompt_tokens,
10782
11108
  completion_tokens,
11109
+ reasoning_tokens,
11110
+ cached_input_tokens,
10783
11111
  inference_time_ms
10784
11112
  );
10785
11113
  const idToUrl = combinedUrlMap != null ? combinedUrlMap : {};
@@ -10864,6 +11192,8 @@ var ObserveHandler = class {
10864
11192
  const {
10865
11193
  prompt_tokens = 0,
10866
11194
  completion_tokens = 0,
11195
+ reasoning_tokens = 0,
11196
+ cached_input_tokens = 0,
10867
11197
  inference_time_ms = 0
10868
11198
  } = observationResponse;
10869
11199
  (_c = this.onMetrics) == null ? void 0 : _c.call(
@@ -10871,6 +11201,8 @@ var ObserveHandler = class {
10871
11201
  "OBSERVE" /* OBSERVE */,
10872
11202
  prompt_tokens,
10873
11203
  completion_tokens,
11204
+ reasoning_tokens,
11205
+ cached_input_tokens,
10874
11206
  inference_time_ms
10875
11207
  );
10876
11208
  const elementsWithSelectors = (yield Promise.all(
@@ -11045,7 +11377,7 @@ var createWaitTool = (v3) => (0, import_ai4.tool)({
11045
11377
  }
11046
11378
  }
11047
11379
  });
11048
- yield new Promise((resolve3) => setTimeout(resolve3, timeMs));
11380
+ yield new Promise((resolve2) => setTimeout(resolve2, timeMs));
11049
11381
  if (timeMs > 0) {
11050
11382
  v3.recordAgentReplayStep({ type: "wait", timeMs });
11051
11383
  }
@@ -11474,6 +11806,7 @@ function createStandardAction(toolCallName, toolResult, args, reasoning) {
11474
11806
  }
11475
11807
 
11476
11808
  // lib/v3/handlers/v3AgentHandler.ts
11809
+ init_sdkErrors();
11477
11810
  var V3AgentHandler = class {
11478
11811
  constructor(v3, logger, llmClient, executionModel, systemInstructions, mcpTools) {
11479
11812
  this.v3 = v3;
@@ -11505,9 +11838,7 @@ var V3AgentHandler = class {
11505
11838
  { role: "user", content: options.instruction }
11506
11839
  ];
11507
11840
  if (!((_a = this.llmClient) == null ? void 0 : _a.getLanguageModel)) {
11508
- throw new Error(
11509
- "V3AgentHandler requires an AISDK-backed LLM client. Ensure your model is configured like 'openai/gpt-4.1-mini'."
11510
- );
11841
+ throw new MissingLLMConfigurationError();
11511
11842
  }
11512
11843
  const baseModel = this.llmClient.getLanguageModel();
11513
11844
  const wrappedModel = (0, import_ai11.wrapLanguageModel)({
@@ -11582,6 +11913,8 @@ var V3AgentHandler = class {
11582
11913
  "AGENT" /* AGENT */,
11583
11914
  result.usage.inputTokens || 0,
11584
11915
  result.usage.outputTokens || 0,
11916
+ result.usage.reasoningTokens || 0,
11917
+ result.usage.cachedInputTokens || 0,
11585
11918
  inferenceTimeMs
11586
11919
  );
11587
11920
  }
@@ -11593,6 +11926,8 @@ var V3AgentHandler = class {
11593
11926
  usage: result.usage ? {
11594
11927
  input_tokens: result.usage.inputTokens || 0,
11595
11928
  output_tokens: result.usage.outputTokens || 0,
11929
+ reasoning_tokens: result.usage.reasoningTokens || 0,
11930
+ cached_input_tokens: result.usage.cachedInputTokens || 0,
11596
11931
  inference_time_ms: inferenceTimeMs
11597
11932
  } : void 0
11598
11933
  };
@@ -11654,7 +11989,11 @@ STRATEGY:
11654
11989
  // lib/v3/handlers/v3CuaAgentHandler.ts
11655
11990
  init_snapshot();
11656
11991
 
11992
+ // lib/v3/agent/AgentProvider.ts
11993
+ init_sdkErrors();
11994
+
11657
11995
  // lib/v3/agent/AnthropicCUAClient.ts
11996
+ init_sdkErrors();
11658
11997
  var import_sdk = __toESM(require("@anthropic-ai/sdk"));
11659
11998
  var import_zod_to_json_schema = require("zod-to-json-schema");
11660
11999
 
@@ -12469,7 +12808,7 @@ var AnthropicCUAClient = class extends AgentClient {
12469
12808
  y
12470
12809
  }, input);
12471
12810
  } else if (action === "drag" || action === "left_click_drag") {
12472
- const path6 = input.path || (input.coordinate ? [
12811
+ const path7 = input.path || (input.coordinate ? [
12473
12812
  {
12474
12813
  x: input.start_coordinate[0],
12475
12814
  y: input.start_coordinate[1]
@@ -12481,7 +12820,7 @@ var AnthropicCUAClient = class extends AgentClient {
12481
12820
  ] : []);
12482
12821
  return __spreadValues({
12483
12822
  type: "drag",
12484
- path: path6
12823
+ path: path7
12485
12824
  }, input);
12486
12825
  } else if (action === "wait") {
12487
12826
  return __spreadValues({
@@ -12547,6 +12886,7 @@ var AnthropicCUAClient = class extends AgentClient {
12547
12886
 
12548
12887
  // lib/v3/agent/OpenAICUAClient.ts
12549
12888
  var import_openai = __toESM(require("openai"));
12889
+ init_sdkErrors();
12550
12890
  var OpenAICUAClient = class extends AgentClient {
12551
12891
  constructor(type, modelName, userProvidedInstructions, clientOptions, tools) {
12552
12892
  super(type, modelName, userProvidedInstructions);
@@ -13020,6 +13360,7 @@ var OpenAICUAClient = class extends AgentClient {
13020
13360
 
13021
13361
  // lib/v3/agent/GoogleCUAClient.ts
13022
13362
  var import_genai3 = require("@google/genai");
13363
+ init_sdkErrors();
13023
13364
 
13024
13365
  // lib/v3/agent/utils/googleCustomToolHandler.ts
13025
13366
  var import_genai2 = require("@google/genai");
@@ -13330,7 +13671,7 @@ var GoogleCUAClient = class extends AgentClient {
13330
13671
  message: `Generating content failed on attempt ${attempt + 1}. Retrying in ${delay2 / 1e3} seconds...`,
13331
13672
  level: 2
13332
13673
  });
13333
- yield new Promise((resolve3) => setTimeout(resolve3, delay2));
13674
+ yield new Promise((resolve2) => setTimeout(resolve2, delay2));
13334
13675
  }
13335
13676
  response = yield this.client.models.generateContent({
13336
13677
  model: this.modelName,
@@ -13338,7 +13679,7 @@ var GoogleCUAClient = class extends AgentClient {
13338
13679
  config: this.generateContentConfig
13339
13680
  });
13340
13681
  if (!response.candidates || response.candidates.length === 0) {
13341
- throw new Error("Response has no candidates!");
13682
+ throw new LLMResponseError("agent", "Response has no candidates!");
13342
13683
  }
13343
13684
  break;
13344
13685
  } catch (error) {
@@ -13428,7 +13769,7 @@ var GoogleCUAClient = class extends AgentClient {
13428
13769
  const nextAction = result.actions[i + 1];
13429
13770
  const isTypingAction = action.type === "type" || nextAction.type === "type";
13430
13771
  const delay2 = isTypingAction ? 500 : 200;
13431
- yield new Promise((resolve3) => setTimeout(resolve3, delay2));
13772
+ yield new Promise((resolve2) => setTimeout(resolve2, delay2));
13432
13773
  }
13433
13774
  } catch (actionError) {
13434
13775
  logger({
@@ -13943,6 +14284,7 @@ var V3CuaAgentHandler = class {
13943
14284
  }
13944
14285
  execute(optionsOrInstruction) {
13945
14286
  return __async(this, null, function* () {
14287
+ var _a, _b;
13946
14288
  const options = typeof optionsOrInstruction === "string" ? { instruction: optionsOrInstruction } : optionsOrInstruction;
13947
14289
  this.highlightCursor = options.highlightCursor !== false;
13948
14290
  const page = yield this.v3.context.awaitActivePage();
@@ -13975,6 +14317,8 @@ var V3CuaAgentHandler = class {
13975
14317
  "AGENT" /* AGENT */,
13976
14318
  result.usage.input_tokens,
13977
14319
  result.usage.output_tokens,
14320
+ (_a = result.usage.reasoning_tokens) != null ? _a : 0,
14321
+ (_b = result.usage.cached_input_tokens) != null ? _b : 0,
13978
14322
  inferenceTimeMs
13979
14323
  );
13980
14324
  }
@@ -14141,13 +14485,13 @@ var V3CuaAgentHandler = class {
14141
14485
  return { success: true };
14142
14486
  }
14143
14487
  case "drag": {
14144
- const { path: path6 } = action;
14145
- if (Array.isArray(path6) && path6.length >= 2) {
14146
- const start = path6[0];
14147
- const end = path6[path6.length - 1];
14488
+ const { path: path7 } = action;
14489
+ if (Array.isArray(path7) && path7.length >= 2) {
14490
+ const start = path7[0];
14491
+ const end = path7[path7.length - 1];
14148
14492
  if (recording) {
14149
14493
  const xps = yield page.dragAndDrop(start.x, start.y, end.x, end.y, {
14150
- steps: Math.min(20, Math.max(5, path6.length)),
14494
+ steps: Math.min(20, Math.max(5, path7.length)),
14151
14495
  delay: 10,
14152
14496
  returnXpath: true
14153
14497
  });
@@ -14169,7 +14513,7 @@ var V3CuaAgentHandler = class {
14169
14513
  }
14170
14514
  } else {
14171
14515
  yield page.dragAndDrop(start.x, start.y, end.x, end.y, {
14172
- steps: Math.min(20, Math.max(5, path6.length)),
14516
+ steps: Math.min(20, Math.max(5, path7.length)),
14173
14517
  delay: 10
14174
14518
  });
14175
14519
  }
@@ -14338,6 +14682,7 @@ var V3CuaAgentHandler = class {
14338
14682
 
14339
14683
  // lib/v3/launch/browserbase.ts
14340
14684
  var import_sdk2 = __toESM(require("@browserbasehq/sdk"));
14685
+ init_sdkErrors();
14341
14686
  function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14342
14687
  return __async(this, null, function* () {
14343
14688
  var _b;
@@ -14347,11 +14692,11 @@ function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14347
14692
  resumeSessionId
14348
14693
  );
14349
14694
  if (!(existing == null ? void 0 : existing.id)) {
14350
- throw new Error(`Browserbase session not found: ${resumeSessionId}`);
14695
+ throw new BrowserbaseSessionNotFoundError();
14351
14696
  }
14352
14697
  const ws = existing.connectUrl;
14353
14698
  if (!ws) {
14354
- throw new Error(
14699
+ throw new StagehandInitError(
14355
14700
  `Browserbase session resume missing connectUrl for ${resumeSessionId}`
14356
14701
  );
14357
14702
  }
@@ -14378,7 +14723,7 @@ function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14378
14723
  });
14379
14724
  const created = yield bb.sessions.create(createPayload);
14380
14725
  if (!(created == null ? void 0 : created.connectUrl) || !(created == null ? void 0 : created.id)) {
14381
- throw new Error(
14726
+ throw new StagehandInitError(
14382
14727
  "Browserbase session creation returned an unexpected shape."
14383
14728
  );
14384
14729
  }
@@ -14387,7 +14732,7 @@ function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14387
14732
  }
14388
14733
 
14389
14734
  // ../../node_modules/.pnpm/chrome-launcher@1.2.0/node_modules/chrome-launcher/dist/chrome-launcher.js
14390
- var fs5 = __toESM(require("fs"), 1);
14735
+ var fs6 = __toESM(require("fs"), 1);
14391
14736
  var net = __toESM(require("net"), 1);
14392
14737
 
14393
14738
  // ../../node_modules/.pnpm/chrome-launcher@1.2.0/node_modules/chrome-launcher/dist/chrome-finder.js
@@ -14399,8 +14744,8 @@ __export(chrome_finder_exports, {
14399
14744
  win32: () => win32,
14400
14745
  wsl: () => wsl
14401
14746
  });
14402
- var import_fs4 = __toESM(require("fs"), 1);
14403
- var import_path4 = __toESM(require("path"), 1);
14747
+ var import_fs5 = __toESM(require("fs"), 1);
14748
+ var import_path5 = __toESM(require("path"), 1);
14404
14749
  var import_os = require("os");
14405
14750
  var import_child_process2 = require("child_process");
14406
14751
  var import_escape_string_regexp = __toESM(require_escape_string_regexp(), 1);
@@ -14744,16 +15089,16 @@ Log.getTimeEntries = () => getEntries();
14744
15089
  var lighthouse_logger_default = Log;
14745
15090
 
14746
15091
  // ../../node_modules/.pnpm/chrome-launcher@1.2.0/node_modules/chrome-launcher/dist/utils.js
14747
- var import_path3 = require("path");
15092
+ var import_path4 = require("path");
14748
15093
  var import_child_process = __toESM(require("child_process"), 1);
14749
- var import_fs3 = require("fs");
15094
+ var import_fs4 = require("fs");
14750
15095
  var import_is_wsl = __toESM(require_is_wsl(), 1);
14751
15096
  function defaults(val, def) {
14752
15097
  return typeof val === "undefined" ? def : val;
14753
15098
  }
14754
15099
  function delay(time) {
14755
15100
  return __async(this, null, function* () {
14756
- return new Promise((resolve3) => setTimeout(resolve3, time));
15101
+ return new Promise((resolve2) => setTimeout(resolve2, time));
14757
15102
  });
14758
15103
  }
14759
15104
  var LauncherError = class extends Error {
@@ -14834,15 +15179,15 @@ function toWSLPath(dir, fallback) {
14834
15179
  return fallback;
14835
15180
  }
14836
15181
  }
14837
- function getLocalAppDataPath(path6) {
15182
+ function getLocalAppDataPath(path7) {
14838
15183
  const userRegExp = /\/mnt\/([a-z])\/Users\/([^\/:]+)\/AppData\//;
14839
- const results = userRegExp.exec(path6) || [];
15184
+ const results = userRegExp.exec(path7) || [];
14840
15185
  return `/mnt/${results[1]}/Users/${results[2]}/AppData/Local`;
14841
15186
  }
14842
- function getWSLLocalAppDataPath(path6) {
15187
+ function getWSLLocalAppDataPath(path7) {
14843
15188
  const userRegExp = /\/([a-z])\/Users\/([^\/:]+)\/AppData\//;
14844
- const results = userRegExp.exec(path6) || [];
14845
- return toWSLPath(`${results[1]}:\\Users\\${results[2]}\\AppData\\Local`, getLocalAppDataPath(path6));
15189
+ const results = userRegExp.exec(path7) || [];
15190
+ return toWSLPath(`${results[1]}:\\Users\\${results[2]}\\AppData\\Local`, getLocalAppDataPath(path7));
14846
15191
  }
14847
15192
  function makeUnixTmpDir() {
14848
15193
  return import_child_process.default.execSync("mktemp -d -t lighthouse.XXXXXXX").toString().trim();
@@ -14850,8 +15195,8 @@ function makeUnixTmpDir() {
14850
15195
  function makeWin32TmpDir() {
14851
15196
  const winTmpPath = process.env.TEMP || process.env.TMP || (process.env.SystemRoot || process.env.windir) + "\\temp";
14852
15197
  const randomNumber = Math.floor(Math.random() * 9e7 + 1e7);
14853
- const tmpdir2 = (0, import_path3.join)(winTmpPath, "lighthouse." + randomNumber);
14854
- (0, import_fs3.mkdirSync)(tmpdir2, { recursive: true });
15198
+ const tmpdir2 = (0, import_path4.join)(winTmpPath, "lighthouse." + randomNumber);
15199
+ (0, import_fs4.mkdirSync)(tmpdir2, { recursive: true });
14855
15200
  return tmpdir2;
14856
15201
  }
14857
15202
 
@@ -14880,7 +15225,7 @@ function darwin() {
14880
15225
  }
14881
15226
  (0, import_child_process2.execSync)(`${LSREGISTER} -dump | grep -i 'google chrome\\( canary\\)\\?\\.app' | awk '{$1=""; print $0}'`).toString().split(newLineRegex).forEach((inst) => {
14882
15227
  suffixes.forEach((suffix) => {
14883
- const execPath = import_path4.default.join(inst.substring(0, inst.indexOf(".app") + 4).trim(), suffix);
15228
+ const execPath = import_path5.default.join(inst.substring(0, inst.indexOf(".app") + 4).trim(), suffix);
14884
15229
  if (canAccess(execPath) && installations.indexOf(execPath) === -1) {
14885
15230
  installations.push(execPath);
14886
15231
  }
@@ -14920,7 +15265,7 @@ function linux() {
14920
15265
  installations.push(customChromePath);
14921
15266
  }
14922
15267
  const desktopInstallationFolders = [
14923
- import_path4.default.join((0, import_os.homedir)(), ".local/share/applications/"),
15268
+ import_path5.default.join((0, import_os.homedir)(), ".local/share/applications/"),
14924
15269
  "/usr/share/applications/"
14925
15270
  ];
14926
15271
  desktopInstallationFolders.forEach((folder) => {
@@ -14968,8 +15313,8 @@ function wsl() {
14968
15313
  function win32() {
14969
15314
  const installations = [];
14970
15315
  const suffixes = [
14971
- `${import_path4.default.sep}Google${import_path4.default.sep}Chrome SxS${import_path4.default.sep}Application${import_path4.default.sep}chrome.exe`,
14972
- `${import_path4.default.sep}Google${import_path4.default.sep}Chrome${import_path4.default.sep}Application${import_path4.default.sep}chrome.exe`
15316
+ `${import_path5.default.sep}Google${import_path5.default.sep}Chrome SxS${import_path5.default.sep}Application${import_path5.default.sep}chrome.exe`,
15317
+ `${import_path5.default.sep}Google${import_path5.default.sep}Chrome${import_path5.default.sep}Application${import_path5.default.sep}chrome.exe`
14973
15318
  ];
14974
15319
  const prefixes = [
14975
15320
  process.env.LOCALAPPDATA,
@@ -14981,7 +15326,7 @@ function win32() {
14981
15326
  installations.push(customChromePath);
14982
15327
  }
14983
15328
  prefixes.forEach((prefix) => suffixes.forEach((suffix) => {
14984
- const chromePath = import_path4.default.join(prefix, suffix);
15329
+ const chromePath = import_path5.default.join(prefix, suffix);
14985
15330
  if (canAccess(chromePath)) {
14986
15331
  installations.push(chromePath);
14987
15332
  }
@@ -15004,7 +15349,7 @@ function canAccess(file) {
15004
15349
  return false;
15005
15350
  }
15006
15351
  try {
15007
- import_fs4.default.accessSync(file);
15352
+ import_fs5.default.accessSync(file);
15008
15353
  return true;
15009
15354
  } catch (e) {
15010
15355
  return false;
@@ -15033,12 +15378,12 @@ function findChromeExecutables(folder) {
15033
15378
  // ../../node_modules/.pnpm/chrome-launcher@1.2.0/node_modules/chrome-launcher/dist/random-port.js
15034
15379
  var import_http = require("http");
15035
15380
  function getRandomPort() {
15036
- return new Promise((resolve3, reject) => {
15381
+ return new Promise((resolve2, reject) => {
15037
15382
  const server = (0, import_http.createServer)();
15038
15383
  server.listen(0);
15039
15384
  server.once("listening", () => {
15040
15385
  const { port } = server.address();
15041
- server.close(() => resolve3(port));
15386
+ server.close(() => resolve2(port));
15042
15387
  });
15043
15388
  server.once("error", reject);
15044
15389
  });
@@ -15167,7 +15512,7 @@ var Launcher = class _Launcher {
15167
15512
  this.opts = opts;
15168
15513
  this.tmpDirandPidFileReady = false;
15169
15514
  this.remoteDebuggingPipes = null;
15170
- this.fs = moduleOverrides.fs || fs5;
15515
+ this.fs = moduleOverrides.fs || fs6;
15171
15516
  this.spawn = moduleOverrides.spawn || import_child_process3.spawn;
15172
15517
  lighthouse_logger_default.setLevel(defaults(this.opts.logLevel, "silent"));
15173
15518
  this.startingUrl = defaults(this.opts.startingUrl, "about:blank");
@@ -15343,7 +15688,7 @@ var Launcher = class _Launcher {
15343
15688
  }
15344
15689
  // resolves if ready, rejects otherwise
15345
15690
  isDebuggerReady() {
15346
- return new Promise((resolve3, reject) => {
15691
+ return new Promise((resolve2, reject) => {
15347
15692
  const client = net.createConnection(this.port, "127.0.0.1");
15348
15693
  client.once("error", (err) => {
15349
15694
  this.cleanup(client);
@@ -15351,14 +15696,14 @@ var Launcher = class _Launcher {
15351
15696
  });
15352
15697
  client.once("connect", () => {
15353
15698
  this.cleanup(client);
15354
- resolve3();
15699
+ resolve2();
15355
15700
  });
15356
15701
  });
15357
15702
  }
15358
15703
  // resolves when debugger is ready, rejects after 10 polls
15359
15704
  waitUntilReady() {
15360
15705
  const launcher = this;
15361
- return new Promise((resolve3, reject) => {
15706
+ return new Promise((resolve2, reject) => {
15362
15707
  let retries = 0;
15363
15708
  let waitStatus = "Waiting for browser.";
15364
15709
  const poll = () => {
@@ -15370,7 +15715,7 @@ var Launcher = class _Launcher {
15370
15715
  lighthouse_logger_default.log("ChromeLauncher", waitStatus);
15371
15716
  launcher.isDebuggerReady().then(() => {
15372
15717
  lighthouse_logger_default.log("ChromeLauncher", waitStatus + `${lighthouse_logger_default.greenify(lighthouse_logger_default.tick)}`);
15373
- resolve3();
15718
+ resolve2();
15374
15719
  }).catch((err) => {
15375
15720
  if (retries > launcher.maxConnectionRetries) {
15376
15721
  lighthouse_logger_default.error("ChromeLauncher", err.message);
@@ -15429,6 +15774,7 @@ var Launcher = class _Launcher {
15429
15774
  };
15430
15775
 
15431
15776
  // lib/v3/launch/local.ts
15777
+ init_sdkErrors();
15432
15778
  function launchLocalChrome(opts) {
15433
15779
  return __async(this, null, function* () {
15434
15780
  var _a, _b, _c;
@@ -15473,12 +15819,15 @@ function waitForWebSocketDebuggerUrl(port, timeoutMs) {
15473
15819
  }
15474
15820
  yield new Promise((r) => setTimeout(r, 250));
15475
15821
  }
15476
- throw new Error(
15822
+ throw new ConnectionTimeoutError(
15477
15823
  `Timed out waiting for /json/version on port ${port}${lastErrMsg ? ` (last error: ${lastErrMsg})` : ""}`
15478
15824
  );
15479
15825
  });
15480
15826
  }
15481
15827
 
15828
+ // lib/v3/llm/LLMProvider.ts
15829
+ init_sdkErrors();
15830
+
15482
15831
  // lib/v3/llm/aisdk.ts
15483
15832
  var import_ai13 = require("ai");
15484
15833
 
@@ -15519,7 +15868,7 @@ var AISdkClient = class extends LLMClient {
15519
15868
  return __async(this, arguments, function* ({
15520
15869
  options
15521
15870
  }) {
15522
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
15871
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
15523
15872
  (_a = this.logger) == null ? void 0 : _a.call(this, {
15524
15873
  category: "aisdk",
15525
15874
  message: "creating chat completion",
@@ -15650,10 +15999,12 @@ var AISdkClient = class extends LLMClient {
15650
15999
  usage: {
15651
16000
  prompt_tokens: (_h = objectResponse.usage.inputTokens) != null ? _h : 0,
15652
16001
  completion_tokens: (_i = objectResponse.usage.outputTokens) != null ? _i : 0,
15653
- total_tokens: (_j = objectResponse.usage.totalTokens) != null ? _j : 0
16002
+ reasoning_tokens: (_j = objectResponse.usage.reasoningTokens) != null ? _j : 0,
16003
+ cached_input_tokens: (_k = objectResponse.usage.cachedInputTokens) != null ? _k : 0,
16004
+ total_tokens: (_l = objectResponse.usage.totalTokens) != null ? _l : 0
15654
16005
  }
15655
16006
  };
15656
- (_k = this.logger) == null ? void 0 : _k.call(this, {
16007
+ (_m = this.logger) == null ? void 0 : _m.call(this, {
15657
16008
  category: "aisdk",
15658
16009
  message: "response",
15659
16010
  level: 1,
@@ -15718,12 +16069,14 @@ var AISdkClient = class extends LLMClient {
15718
16069
  }
15719
16070
  ],
15720
16071
  usage: {
15721
- prompt_tokens: (_l = textResponse.usage.inputTokens) != null ? _l : 0,
15722
- completion_tokens: (_m = textResponse.usage.outputTokens) != null ? _m : 0,
15723
- total_tokens: (_n = textResponse.usage.totalTokens) != null ? _n : 0
16072
+ prompt_tokens: (_n = textResponse.usage.inputTokens) != null ? _n : 0,
16073
+ completion_tokens: (_o = textResponse.usage.outputTokens) != null ? _o : 0,
16074
+ reasoning_tokens: (_p = textResponse.usage.reasoningTokens) != null ? _p : 0,
16075
+ cached_input_tokens: (_q = textResponse.usage.cachedInputTokens) != null ? _q : 0,
16076
+ total_tokens: (_r = textResponse.usage.totalTokens) != null ? _r : 0
15724
16077
  }
15725
16078
  };
15726
- (_o = this.logger) == null ? void 0 : _o.call(this, {
16079
+ (_s = this.logger) == null ? void 0 : _s.call(this, {
15727
16080
  category: "aisdk",
15728
16081
  message: "response",
15729
16082
  level: 2,
@@ -15751,6 +16104,7 @@ var AISdkClient = class extends LLMClient {
15751
16104
  // lib/v3/llm/AnthropicClient.ts
15752
16105
  var import_sdk3 = __toESM(require("@anthropic-ai/sdk"));
15753
16106
  var import_zod_to_json_schema3 = require("zod-to-json-schema");
16107
+ init_sdkErrors();
15754
16108
  var AnthropicClient = class extends LLMClient {
15755
16109
  constructor({
15756
16110
  modelName,
@@ -15993,6 +16347,7 @@ var extractSchemaProperties = (jsonSchema2) => {
15993
16347
  // lib/v3/llm/CerebrasClient.ts
15994
16348
  var import_openai2 = __toESM(require("openai"));
15995
16349
  var import_zod_to_json_schema4 = require("zod-to-json-schema");
16350
+ init_sdkErrors();
15996
16351
  var CerebrasClient = class extends LLMClient {
15997
16352
  constructor({
15998
16353
  modelName,
@@ -16212,6 +16567,7 @@ var CerebrasClient = class extends LLMClient {
16212
16567
 
16213
16568
  // lib/v3/llm/GoogleClient.ts
16214
16569
  var import_genai4 = require("@google/genai");
16570
+ init_sdkErrors();
16215
16571
  var roleMap = {
16216
16572
  user: "user",
16217
16573
  assistant: "model",
@@ -16558,7 +16914,7 @@ ${firstPartText.text}`;
16558
16914
  level: 1
16559
16915
  });
16560
16916
  yield new Promise(
16561
- (resolve3) => setTimeout(resolve3, 1e3 * (4 - retries))
16917
+ (resolve2) => setTimeout(resolve2, 1e3 * (4 - retries))
16562
16918
  );
16563
16919
  return this.createChatCompletion({
16564
16920
  options,
@@ -16580,6 +16936,7 @@ ${firstPartText.text}`;
16580
16936
  // lib/v3/llm/GroqClient.ts
16581
16937
  var import_openai3 = __toESM(require("openai"));
16582
16938
  var import_zod_to_json_schema5 = require("zod-to-json-schema");
16939
+ init_sdkErrors();
16583
16940
  var GroqClient = class extends LLMClient {
16584
16941
  constructor({
16585
16942
  modelName,
@@ -16801,6 +17158,7 @@ var GroqClient = class extends LLMClient {
16801
17158
  var import_openai4 = __toESM(require("openai"));
16802
17159
  var import_zod = require("openai/helpers/zod");
16803
17160
  var import_zod_to_json_schema6 = __toESM(require("zod-to-json-schema"));
17161
+ init_sdkErrors();
16804
17162
  var OpenAIClient = class extends LLMClient {
16805
17163
  constructor({
16806
17164
  modelName,
@@ -17882,7 +18240,7 @@ function createProviderDefinedToolFactoryWithOutputSchema({
17882
18240
  });
17883
18241
  };
17884
18242
  }
17885
- function resolve2(value) {
18243
+ function resolve(value) {
17886
18244
  return __async(this, null, function* () {
17887
18245
  if (typeof value === "function") {
17888
18246
  value = value();
@@ -23516,37 +23874,37 @@ function createOpenAI(options = {}) {
23516
23874
  );
23517
23875
  const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, {
23518
23876
  provider: `${providerName}.chat`,
23519
- url: ({ path: path6 }) => `${baseURL}${path6}`,
23877
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23520
23878
  headers: getHeaders,
23521
23879
  fetch: options.fetch
23522
23880
  });
23523
23881
  const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
23524
23882
  provider: `${providerName}.completion`,
23525
- url: ({ path: path6 }) => `${baseURL}${path6}`,
23883
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23526
23884
  headers: getHeaders,
23527
23885
  fetch: options.fetch
23528
23886
  });
23529
23887
  const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
23530
23888
  provider: `${providerName}.embedding`,
23531
- url: ({ path: path6 }) => `${baseURL}${path6}`,
23889
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23532
23890
  headers: getHeaders,
23533
23891
  fetch: options.fetch
23534
23892
  });
23535
23893
  const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
23536
23894
  provider: `${providerName}.image`,
23537
- url: ({ path: path6 }) => `${baseURL}${path6}`,
23895
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23538
23896
  headers: getHeaders,
23539
23897
  fetch: options.fetch
23540
23898
  });
23541
23899
  const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
23542
23900
  provider: `${providerName}.transcription`,
23543
- url: ({ path: path6 }) => `${baseURL}${path6}`,
23901
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23544
23902
  headers: getHeaders,
23545
23903
  fetch: options.fetch
23546
23904
  });
23547
23905
  const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
23548
23906
  provider: `${providerName}.speech`,
23549
- url: ({ path: path6 }) => `${baseURL}${path6}`,
23907
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23550
23908
  headers: getHeaders,
23551
23909
  fetch: options.fetch
23552
23910
  });
@@ -23561,7 +23919,7 @@ function createOpenAI(options = {}) {
23561
23919
  const createResponsesModel = (modelId) => {
23562
23920
  return new OpenAIResponsesLanguageModel(modelId, {
23563
23921
  provider: `${providerName}.responses`,
23564
- url: ({ path: path6 }) => `${baseURL}${path6}`,
23922
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23565
23923
  headers: getHeaders,
23566
23924
  fetch: options.fetch,
23567
23925
  fileIdPrefixes: ["file-"]
@@ -25469,7 +25827,7 @@ var AnthropicMessagesLanguageModel = class {
25469
25827
  headers
25470
25828
  }) {
25471
25829
  return combineHeaders(
25472
- yield resolve2(this.config.headers),
25830
+ yield resolve(this.config.headers),
25473
25831
  betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {},
25474
25832
  headers
25475
25833
  );
@@ -26721,7 +27079,7 @@ var GoogleGenerativeAIEmbeddingModel = class {
26721
27079
  });
26722
27080
  }
26723
27081
  const mergedHeaders = combineHeaders(
26724
- yield resolve2(this.config.headers),
27082
+ yield resolve(this.config.headers),
26725
27083
  headers
26726
27084
  );
26727
27085
  if (values.length === 1) {
@@ -27428,7 +27786,7 @@ var GoogleGenerativeAILanguageModel = class {
27428
27786
  const { args, warnings } = yield this.getArgs(options);
27429
27787
  const body = JSON.stringify(args);
27430
27788
  const mergedHeaders = combineHeaders(
27431
- yield resolve2(this.config.headers),
27789
+ yield resolve(this.config.headers),
27432
27790
  options.headers
27433
27791
  );
27434
27792
  const {
@@ -27541,7 +27899,7 @@ var GoogleGenerativeAILanguageModel = class {
27541
27899
  const { args, warnings } = yield this.getArgs(options);
27542
27900
  const body = JSON.stringify(args);
27543
27901
  const headers = combineHeaders(
27544
- yield resolve2(this.config.headers),
27902
+ yield resolve(this.config.headers),
27545
27903
  options.headers
27546
27904
  );
27547
27905
  const { responseHeaders, value: response } = yield postJsonToApi({
@@ -28066,7 +28424,7 @@ var GoogleGenerativeAIImageModel = class {
28066
28424
  };
28067
28425
  const { responseHeaders, value: response } = yield postJsonToApi({
28068
28426
  url: `${this.config.baseURL}/models/${this.modelId}:predict`,
28069
- headers: combineHeaders(yield resolve2(this.config.headers), headers),
28427
+ headers: combineHeaders(yield resolve(this.config.headers), headers),
28070
28428
  body,
28071
28429
  failedResponseHandler: googleFailedResponseHandler,
28072
28430
  successfulResponseHandler: createJsonResponseHandler(
@@ -30233,7 +30591,7 @@ function createXai(options = {}) {
30233
30591
  const createImageModel = (modelId) => {
30234
30592
  return new OpenAICompatibleImageModel(modelId, {
30235
30593
  provider: "xai.image",
30236
- url: ({ path: path6 }) => `${baseURL}${path6}`,
30594
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
30237
30595
  headers: getHeaders,
30238
30596
  fetch: options.fetch,
30239
30597
  errorStructure: xaiErrorStructure
@@ -34500,14 +34858,14 @@ function createAzure(options = {}) {
34500
34858
  description: "Azure OpenAI resource name"
34501
34859
  });
34502
34860
  const apiVersion = (_a = options.apiVersion) != null ? _a : "v1";
34503
- const url = ({ path: path6, modelId }) => {
34861
+ const url = ({ path: path7, modelId }) => {
34504
34862
  var _a2;
34505
34863
  const baseUrlPrefix = (_a2 = options.baseURL) != null ? _a2 : `https://${getResourceName()}.openai.azure.com/openai`;
34506
34864
  let fullUrl;
34507
34865
  if (options.useDeploymentBasedUrls) {
34508
- fullUrl = new URL(`${baseUrlPrefix}/deployments/${modelId}${path6}`);
34866
+ fullUrl = new URL(`${baseUrlPrefix}/deployments/${modelId}${path7}`);
34509
34867
  } else {
34510
- fullUrl = new URL(`${baseUrlPrefix}/v1${path6}`);
34868
+ fullUrl = new URL(`${baseUrlPrefix}/v1${path7}`);
34511
34869
  }
34512
34870
  fullUrl.searchParams.set("api-version", apiVersion);
34513
34871
  return fullUrl.toString();
@@ -35423,7 +35781,7 @@ function createGroq(options = {}) {
35423
35781
  );
35424
35782
  const createChatModel = (modelId) => new GroqChatLanguageModel(modelId, {
35425
35783
  provider: "groq.chat",
35426
- url: ({ path: path6 }) => `${baseURL}${path6}`,
35784
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
35427
35785
  headers: getHeaders,
35428
35786
  fetch: options.fetch
35429
35787
  });
@@ -35438,7 +35796,7 @@ function createGroq(options = {}) {
35438
35796
  const createTranscriptionModel = (modelId) => {
35439
35797
  return new GroqTranscriptionModel(modelId, {
35440
35798
  provider: "groq.transcription",
35441
- url: ({ path: path6 }) => `${baseURL}${path6}`,
35799
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
35442
35800
  headers: getHeaders,
35443
35801
  fetch: options.fetch
35444
35802
  });
@@ -35493,7 +35851,7 @@ function createCerebras(options = {}) {
35493
35851
  const createLanguageModel = (modelId) => {
35494
35852
  return new OpenAICompatibleChatLanguageModel(modelId, {
35495
35853
  provider: `cerebras.chat`,
35496
- url: ({ path: path6 }) => `${baseURL}${path6}`,
35854
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
35497
35855
  headers: getHeaders,
35498
35856
  fetch: options.fetch,
35499
35857
  errorStructure: cerebrasErrorStructure,
@@ -35612,7 +35970,7 @@ function createTogetherAI(options = {}) {
35612
35970
  );
35613
35971
  const getCommonModelConfig = (modelType) => ({
35614
35972
  provider: `togetherai.${modelType}`,
35615
- url: ({ path: path6 }) => `${baseURL}${path6}`,
35973
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
35616
35974
  headers: getHeaders,
35617
35975
  fetch: options.fetch
35618
35976
  });
@@ -36498,7 +36856,7 @@ function createDeepSeek(options = {}) {
36498
36856
  const createLanguageModel = (modelId) => {
36499
36857
  return new OpenAICompatibleChatLanguageModel(modelId, {
36500
36858
  provider: `deepseek.chat`,
36501
- url: ({ path: path6 }) => `${baseURL}${path6}`,
36859
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
36502
36860
  headers: getHeaders,
36503
36861
  fetch: options.fetch,
36504
36862
  metadataExtractor: deepSeekMetadataExtractor
@@ -38208,13 +38566,13 @@ function createOllama(options = {}) {
38208
38566
  }, options.headers);
38209
38567
  const createCompletionModel = (modelId, settings = {}) => new OllamaCompletionLanguageModel(modelId, settings, {
38210
38568
  provider: `${providerName}.completion`,
38211
- url: ({ path: path6 }) => `${baseURL}${path6}`,
38569
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
38212
38570
  headers: getHeaders,
38213
38571
  fetch: options.fetch
38214
38572
  });
38215
38573
  const createEmbeddingModel = (modelId, settings = {}) => new OllamaEmbeddingModel(modelId, settings, {
38216
38574
  provider: `${providerName}.embedding`,
38217
- url: ({ path: path6 }) => `${baseURL}${path6}`,
38575
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
38218
38576
  headers: getHeaders,
38219
38577
  fetch: options.fetch
38220
38578
  });
@@ -38229,7 +38587,7 @@ function createOllama(options = {}) {
38229
38587
  const createResponsesModel = (modelId) => {
38230
38588
  return new OllamaResponsesLanguageModel(modelId, {
38231
38589
  provider: `${providerName}.responses`,
38232
- url: ({ path: path6 }) => `${baseURL}${path6}`,
38590
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
38233
38591
  headers: getHeaders,
38234
38592
  fetch: options.fetch
38235
38593
  });
@@ -38424,6 +38782,7 @@ init_logger();
38424
38782
  var import_client = require("@modelcontextprotocol/sdk/client/index.js");
38425
38783
  var import_streamableHttp = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
38426
38784
  var import_stdio = require("@modelcontextprotocol/sdk/client/stdio.js");
38785
+ init_sdkErrors();
38427
38786
  var connectToMCPServer = (serverConfig) => __async(null, null, function* () {
38428
38787
  try {
38429
38788
  let transport;
@@ -38549,6 +38908,9 @@ var LOG_LEVEL_NAMES = {
38549
38908
  init_consoleMessage();
38550
38909
  init_response();
38551
38910
 
38911
+ // lib/v3/types/public/index.ts
38912
+ init_sdkErrors();
38913
+
38552
38914
  // examples/external_clients/aisdk.ts
38553
38915
  var import_ai14 = require("ai");
38554
38916
  var AISdkClient2 = class extends LLMClient {
@@ -38561,7 +38923,7 @@ var AISdkClient2 = class extends LLMClient {
38561
38923
  return __async(this, arguments, function* ({
38562
38924
  options
38563
38925
  }) {
38564
- var _a, _b, _c, _d, _e, _f;
38926
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
38565
38927
  const formattedMessages = options.messages.map(
38566
38928
  (message) => {
38567
38929
  if (Array.isArray(message.content)) {
@@ -38622,7 +38984,9 @@ var AISdkClient2 = class extends LLMClient {
38622
38984
  usage: {
38623
38985
  prompt_tokens: (_a = response2.usage.inputTokens) != null ? _a : 0,
38624
38986
  completion_tokens: (_b = response2.usage.outputTokens) != null ? _b : 0,
38625
- total_tokens: (_c = response2.usage.totalTokens) != null ? _c : 0
38987
+ reasoning_tokens: (_c = response2.usage.reasoningTokens) != null ? _c : 0,
38988
+ cached_input_tokens: (_d = response2.usage.cachedInputTokens) != null ? _d : 0,
38989
+ total_tokens: (_e = response2.usage.totalTokens) != null ? _e : 0
38626
38990
  }
38627
38991
  };
38628
38992
  }
@@ -38641,9 +39005,11 @@ var AISdkClient2 = class extends LLMClient {
38641
39005
  return {
38642
39006
  data: response.text,
38643
39007
  usage: {
38644
- prompt_tokens: (_d = response.usage.inputTokens) != null ? _d : 0,
38645
- completion_tokens: (_e = response.usage.outputTokens) != null ? _e : 0,
38646
- total_tokens: (_f = response.usage.totalTokens) != null ? _f : 0
39008
+ prompt_tokens: (_f = response.usage.inputTokens) != null ? _f : 0,
39009
+ completion_tokens: (_g = response.usage.outputTokens) != null ? _g : 0,
39010
+ reasoning_tokens: (_h = response.usage.reasoningTokens) != null ? _h : 0,
39011
+ cached_input_tokens: (_i = response.usage.cachedInputTokens) != null ? _i : 0,
39012
+ total_tokens: (_j = response.usage.totalTokens) != null ? _j : 0
38647
39013
  }
38648
39014
  };
38649
39015
  });
@@ -38693,8 +39059,8 @@ var CdpConnection = class _CdpConnection {
38693
39059
  static connect(wsUrl) {
38694
39060
  return __async(this, null, function* () {
38695
39061
  const ws = new import_ws.default(wsUrl);
38696
- yield new Promise((resolve3, reject) => {
38697
- ws.once("open", () => resolve3());
39062
+ yield new Promise((resolve2, reject) => {
39063
+ ws.once("open", () => resolve2());
38698
39064
  ws.once("error", (e) => reject(e));
38699
39065
  });
38700
39066
  return new _CdpConnection(ws);
@@ -38705,7 +39071,7 @@ var CdpConnection = class _CdpConnection {
38705
39071
  yield this.send("Target.setAutoAttach", {
38706
39072
  autoAttach: true,
38707
39073
  flatten: true,
38708
- waitForDebuggerOnStart: true,
39074
+ waitForDebuggerOnStart: false,
38709
39075
  filter: [
38710
39076
  { type: "worker", exclude: true },
38711
39077
  { type: "shared_worker", exclude: true },
@@ -38721,9 +39087,9 @@ var CdpConnection = class _CdpConnection {
38721
39087
  const id = this.nextId++;
38722
39088
  const payload = { id, method, params };
38723
39089
  const stack = (_a = new Error().stack) == null ? void 0 : _a.split("\n").slice(1, 4).join("\n");
38724
- const p = new Promise((resolve3, reject) => {
39090
+ const p = new Promise((resolve2, reject) => {
38725
39091
  this.inflight.set(id, {
38726
- resolve: resolve3,
39092
+ resolve: resolve2,
38727
39093
  reject,
38728
39094
  sessionId: null,
38729
39095
  method,
@@ -38748,8 +39114,8 @@ var CdpConnection = class _CdpConnection {
38748
39114
  }
38749
39115
  close() {
38750
39116
  return __async(this, null, function* () {
38751
- yield new Promise((resolve3) => {
38752
- this.ws.once("close", () => resolve3());
39117
+ yield new Promise((resolve2) => {
39118
+ this.ws.once("close", () => resolve2());
38753
39119
  this.ws.close();
38754
39120
  });
38755
39121
  });
@@ -38821,9 +39187,9 @@ var CdpConnection = class _CdpConnection {
38821
39187
  const id = this.nextId++;
38822
39188
  const payload = { id, method, params, sessionId };
38823
39189
  const stack = (_a = new Error().stack) == null ? void 0 : _a.split("\n").slice(1, 4).join("\n");
38824
- const p = new Promise((resolve3, reject) => {
39190
+ const p = new Promise((resolve2, reject) => {
38825
39191
  this.inflight.set(id, {
38826
- resolve: resolve3,
39192
+ resolve: resolve2,
38827
39193
  reject,
38828
39194
  sessionId,
38829
39195
  method,
@@ -38888,12 +39254,15 @@ init_logger();
38888
39254
  // lib/v3/dom/build/scriptV3Content.ts
38889
39255
  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';
38890
39256
 
39257
+ // lib/v3/dom/build/reRenderScriptContent.ts
39258
+ 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';
39259
+
38891
39260
  // lib/v3/understudy/piercer.ts
38892
39261
  function installV3PiercerIntoSession(session) {
38893
39262
  return __async(this, null, function* () {
38894
39263
  var _a, _b;
38895
- yield session.send("Page.enable").catch(() => {
38896
- });
39264
+ const pageEnabled = yield session.send("Page.enable").then(() => true).catch(() => false);
39265
+ if (!pageEnabled) return false;
38897
39266
  yield session.send("Runtime.enable").catch(() => {
38898
39267
  });
38899
39268
  try {
@@ -38903,7 +39272,7 @@ function installV3PiercerIntoSession(session) {
38903
39272
  );
38904
39273
  } catch (e) {
38905
39274
  const msg = String((_b = (_a = e == null ? void 0 : e.message) != null ? _a : e) != null ? _b : "");
38906
- if (msg.includes("Session with given id not found")) return;
39275
+ if (msg.includes("Session with given id not found")) return false;
38907
39276
  }
38908
39277
  yield session.send("Runtime.evaluate", {
38909
39278
  expression: v3ScriptContent,
@@ -38911,11 +39280,19 @@ function installV3PiercerIntoSession(session) {
38911
39280
  awaitPromise: true
38912
39281
  }).catch(() => {
38913
39282
  });
39283
+ yield session.send("Runtime.evaluate", {
39284
+ expression: reRenderScriptContent,
39285
+ returnByValue: true,
39286
+ awaitPromise: false
39287
+ }).catch(() => {
39288
+ });
39289
+ return true;
38914
39290
  });
38915
39291
  }
38916
39292
 
38917
39293
  // lib/v3/understudy/context.ts
38918
39294
  init_executionContextRegistry();
39295
+ init_sdkErrors();
38919
39296
  function isTopLevelPage(info) {
38920
39297
  const ti = info;
38921
39298
  return info.type === "page" && ti.subtype !== "iframe";
@@ -38951,7 +39328,6 @@ var V3Context = class _V3Context {
38951
39328
  return __async(this, null, function* () {
38952
39329
  var _a, _b, _c;
38953
39330
  const conn = yield CdpConnection.connect(wsUrl);
38954
- yield conn.enableAutoAttach();
38955
39331
  const ctx = new _V3Context(
38956
39332
  conn,
38957
39333
  (_a = opts == null ? void 0 : opts.env) != null ? _a : "LOCAL",
@@ -38979,17 +39355,50 @@ var V3Context = class _V3Context {
38979
39355
  }
38980
39356
  yield new Promise((r) => setTimeout(r, 25));
38981
39357
  }
38982
- throw new Error(
38983
- `waitForFirstTopLevelPage timed out after ${timeoutMs}ms (no top-level Page)`
39358
+ throw new TimeoutError(
39359
+ "waitForFirstTopLevelPage (no top-level Page)",
39360
+ timeoutMs
38984
39361
  );
38985
39362
  });
38986
39363
  }
39364
+ waitForInitialTopLevelTargets(targetIds, timeoutMs = 3e3) {
39365
+ return __async(this, null, function* () {
39366
+ if (!targetIds.length) return;
39367
+ const pending = new Set(targetIds);
39368
+ const deadline = Date.now() + timeoutMs;
39369
+ while (pending.size && Date.now() < deadline) {
39370
+ for (const tid of Array.from(pending)) {
39371
+ if (this.pagesByTarget.has(tid)) {
39372
+ pending.delete(tid);
39373
+ }
39374
+ }
39375
+ if (!pending.size) return;
39376
+ yield new Promise((r) => setTimeout(r, 25));
39377
+ }
39378
+ if (pending.size) {
39379
+ v3Logger({
39380
+ category: "ctx",
39381
+ message: "Timed out waiting for existing top-level targets to attach",
39382
+ level: 2,
39383
+ auxiliary: {
39384
+ remainingTargets: {
39385
+ value: JSON.stringify(Array.from(pending)),
39386
+ type: "object"
39387
+ }
39388
+ }
39389
+ });
39390
+ }
39391
+ });
39392
+ }
38987
39393
  ensurePiercer(session) {
38988
39394
  return __async(this, null, function* () {
38989
39395
  const key = this.sessionKey(session);
38990
- if (this._piercerInstalled.has(key)) return;
38991
- yield installV3PiercerIntoSession(session);
38992
- this._piercerInstalled.add(key);
39396
+ if (this._piercerInstalled.has(key)) return true;
39397
+ const installed = yield installV3PiercerIntoSession(session);
39398
+ if (installed) {
39399
+ this._piercerInstalled.add(key);
39400
+ }
39401
+ return installed;
38993
39402
  });
38994
39403
  }
38995
39404
  /** Mark a page target as the most-recent one (active). */
@@ -39073,8 +39482,7 @@ var V3Context = class _V3Context {
39073
39482
  getFullFrameTreeByMainFrameId(rootMainFrameId) {
39074
39483
  return __async(this, null, function* () {
39075
39484
  const owner = this.resolvePageByMainFrameId(rootMainFrameId);
39076
- if (!owner)
39077
- throw new Error(`No Page found for mainFrameId=${rootMainFrameId}`);
39485
+ if (!owner) throw new PageNotFoundError(`mainFrameId=${rootMainFrameId}`);
39078
39486
  return owner.asProtocolFrameTree(rootMainFrameId);
39079
39487
  });
39080
39488
  }
@@ -39097,7 +39505,7 @@ var V3Context = class _V3Context {
39097
39505
  if (page) return page;
39098
39506
  yield new Promise((r) => setTimeout(r, 25));
39099
39507
  }
39100
- throw new Error(`newPage timeout: target not attached (${targetId})`);
39508
+ throw new TimeoutError(`newPage: target not attached (${targetId})`, 5e3);
39101
39509
  });
39102
39510
  }
39103
39511
  /**
@@ -39128,11 +39536,7 @@ var V3Context = class _V3Context {
39128
39536
  this.conn.on(
39129
39537
  "Target.attachedToTarget",
39130
39538
  (evt) => __async(this, null, function* () {
39131
- yield this.onAttachedToTarget(
39132
- evt.targetInfo,
39133
- evt.sessionId,
39134
- evt.waitingForDebugger === true
39135
- );
39539
+ yield this.onAttachedToTarget(evt.targetInfo, evt.sessionId);
39136
39540
  })
39137
39541
  );
39138
39542
  this.conn.on(
@@ -39165,6 +39569,7 @@ var V3Context = class _V3Context {
39165
39569
  }
39166
39570
  })
39167
39571
  );
39572
+ yield this.conn.enableAutoAttach();
39168
39573
  const targets = yield this.conn.getTargets();
39169
39574
  for (const t of targets) {
39170
39575
  try {
@@ -39172,6 +39577,8 @@ var V3Context = class _V3Context {
39172
39577
  } catch (e) {
39173
39578
  }
39174
39579
  }
39580
+ const topLevelTargetIds = targets.filter((t) => isTopLevelPage(t)).map((t) => t.targetId);
39581
+ yield this.waitForInitialTopLevelTargets(topLevelTargetIds);
39175
39582
  });
39176
39583
  }
39177
39584
  /**
@@ -39182,36 +39589,28 @@ var V3Context = class _V3Context {
39182
39589
  * if the parent is known; otherwise stage until parent `frameAttached`.
39183
39590
  * - Resume the target only after listeners are wired.
39184
39591
  */
39185
- onAttachedToTarget(info, sessionId, waitingForDebugger) {
39592
+ onAttachedToTarget(info, sessionId) {
39186
39593
  return __async(this, null, function* () {
39187
39594
  var _a;
39188
39595
  const session = this.conn.getSession(sessionId);
39189
39596
  if (!session) return;
39190
39597
  if (this._sessionInit.has(sessionId)) return;
39191
39598
  this._sessionInit.add(sessionId);
39192
- const pageEnabled = yield session.send("Page.enable").then(() => true).catch(() => false);
39193
- if (!pageEnabled) {
39194
- if (waitingForDebugger) {
39195
- yield session.send("Runtime.runIfWaitingForDebugger").catch(() => {
39196
- });
39197
- }
39198
- return;
39199
- }
39200
- yield session.send("Page.setLifecycleEventsEnabled", { enabled: true }).catch(() => {
39201
- });
39202
39599
  yield session.send("Runtime.runIfWaitingForDebugger").catch(() => {
39203
39600
  });
39204
39601
  executionContexts.attachSession(session);
39205
- yield session.send("Runtime.enable").catch(() => {
39602
+ const piercerReady = yield this.ensurePiercer(session);
39603
+ if (!piercerReady) return;
39604
+ yield session.send("Page.setLifecycleEventsEnabled", { enabled: true }).catch(() => {
39206
39605
  });
39207
- yield this.ensurePiercer(session);
39208
39606
  if (isTopLevelPage(info)) {
39209
39607
  const page = yield Page.create(
39210
39608
  this.conn,
39211
39609
  session,
39212
39610
  info.targetId,
39213
39611
  this.apiClient,
39214
- this.localBrowserLaunchOptions
39612
+ this.localBrowserLaunchOptions,
39613
+ this.env === "BROWSERBASE"
39215
39614
  );
39216
39615
  this.wireSessionToOwnerPage(sessionId, page);
39217
39616
  this.pagesByTarget.set(info.targetId, page);
@@ -39227,10 +39626,6 @@ var V3Context = class _V3Context {
39227
39626
  page.seedCurrentUrl((_a = pendingSeedUrl != null ? pendingSeedUrl : info.url) != null ? _a : "");
39228
39627
  this._pushActive(info.targetId);
39229
39628
  this.installFrameEventBridges(sessionId, page);
39230
- if (waitingForDebugger) {
39231
- yield session.send("Runtime.runIfWaitingForDebugger").catch(() => {
39232
- });
39233
- }
39234
39629
  return;
39235
39630
  }
39236
39631
  try {
@@ -39258,51 +39653,13 @@ var V3Context = class _V3Context {
39258
39653
  owner.adoptOopifSession(session, childMainId);
39259
39654
  this.sessionOwnerPage.set(sessionId, owner);
39260
39655
  this.installFrameEventBridges(sessionId, owner);
39656
+ void executionContexts.waitForMainWorld(session, childMainId).catch(() => {
39657
+ });
39261
39658
  } else {
39262
39659
  this.pendingOopifByMainFrame.set(childMainId, sessionId);
39263
39660
  }
39264
39661
  } catch (e) {
39265
39662
  }
39266
- if (info.type === "iframe" && !waitingForDebugger) {
39267
- try {
39268
- yield session.send("Page.setLifecycleEventsEnabled", { enabled: true }).catch(() => {
39269
- });
39270
- const loadWait = new Promise((resolve3) => {
39271
- const handler = (evt) => {
39272
- if (evt.name === "load") {
39273
- session.off("Page.lifecycleEvent", handler);
39274
- resolve3();
39275
- }
39276
- };
39277
- session.on("Page.lifecycleEvent", handler);
39278
- });
39279
- yield session.send("Runtime.evaluate", {
39280
- expression: "location.reload()",
39281
- returnByValue: true,
39282
- awaitPromise: false
39283
- }).catch(() => {
39284
- });
39285
- yield Promise.race([
39286
- loadWait,
39287
- new Promise((r) => setTimeout(r, 3e3))
39288
- ]);
39289
- yield this.ensurePiercer(session);
39290
- } catch (e) {
39291
- v3Logger({
39292
- category: "ctx",
39293
- message: "child reload attempt failed (continuing)",
39294
- level: 2,
39295
- auxiliary: {
39296
- sessionId: { value: String(sessionId), type: "string" },
39297
- err: { value: String(e), type: "string" }
39298
- }
39299
- });
39300
- }
39301
- }
39302
- if (waitingForDebugger) {
39303
- yield session.send("Runtime.runIfWaitingForDebugger").catch(() => {
39304
- });
39305
- }
39306
39663
  });
39307
39664
  }
39308
39665
  /**
@@ -39457,7 +39814,7 @@ var V3Context = class _V3Context {
39457
39814
  yield new Promise((r) => setTimeout(r, 25));
39458
39815
  }
39459
39816
  if (immediate) return immediate;
39460
- throw new Error("awaitActivePage: no page available");
39817
+ throw new PageNotFoundError("awaitActivePage: no page available");
39461
39818
  });
39462
39819
  }
39463
39820
  };
@@ -39488,6 +39845,7 @@ function resolveModel(model) {
39488
39845
  // lib/v3/api.ts
39489
39846
  var import_fetch_cookie = __toESM(require("fetch-cookie"));
39490
39847
  var import_zod_to_json_schema7 = __toESM(require("zod-to-json-schema"));
39848
+ init_version();
39491
39849
  var StagehandAPIClient = class {
39492
39850
  constructor({ apiKey, projectId, logger }) {
39493
39851
  this.apiKey = apiKey;
@@ -39632,9 +39990,7 @@ var StagehandAPIClient = class {
39632
39990
  agentExecute(agentConfig, executeOptions, frameId) {
39633
39991
  return __async(this, null, function* () {
39634
39992
  if (agentConfig.integrations && agentConfig.integrations.length > 0) {
39635
- throw new StagehandAPIError(
39636
- "MCP integrations are not supported in API mode. Set experimental: true to use MCP integrations."
39637
- );
39993
+ throw new ExperimentalNotConfiguredError("MCP integrations");
39638
39994
  }
39639
39995
  if (typeof executeOptions === "object") {
39640
39996
  if (executeOptions.page) {
@@ -39686,18 +40042,28 @@ var StagehandAPIClient = class {
39686
40042
  const metrics = {
39687
40043
  actPromptTokens: 0,
39688
40044
  actCompletionTokens: 0,
40045
+ actReasoningTokens: 0,
40046
+ actCachedInputTokens: 0,
39689
40047
  actInferenceTimeMs: 0,
39690
40048
  extractPromptTokens: 0,
39691
40049
  extractCompletionTokens: 0,
40050
+ extractReasoningTokens: 0,
40051
+ extractCachedInputTokens: 0,
39692
40052
  extractInferenceTimeMs: 0,
39693
40053
  observePromptTokens: 0,
39694
40054
  observeCompletionTokens: 0,
40055
+ observeReasoningTokens: 0,
40056
+ observeCachedInputTokens: 0,
39695
40057
  observeInferenceTimeMs: 0,
39696
40058
  agentPromptTokens: 0,
39697
40059
  agentCompletionTokens: 0,
40060
+ agentReasoningTokens: 0,
40061
+ agentCachedInputTokens: 0,
39698
40062
  agentInferenceTimeMs: 0,
39699
40063
  totalPromptTokens: 0,
39700
40064
  totalCompletionTokens: 0,
40065
+ totalReasoningTokens: 0,
40066
+ totalCachedInputTokens: 0,
39701
40067
  totalInferenceTimeMs: 0
39702
40068
  };
39703
40069
  const pages = apiData.pages || [];
@@ -39709,26 +40075,38 @@ var StagehandAPIClient = class {
39709
40075
  if (tokenUsage) {
39710
40076
  const inputTokens = tokenUsage.inputTokens || 0;
39711
40077
  const outputTokens = tokenUsage.outputTokens || 0;
40078
+ const reasoningTokens = tokenUsage.reasoningTokens || 0;
40079
+ const cachedInputTokens = tokenUsage.cachedInputTokens || 0;
39712
40080
  const timeMs = tokenUsage.timeMs || 0;
39713
40081
  if (method === "act") {
39714
40082
  metrics.actPromptTokens += inputTokens;
39715
40083
  metrics.actCompletionTokens += outputTokens;
40084
+ metrics.actReasoningTokens += reasoningTokens;
40085
+ metrics.actCachedInputTokens += cachedInputTokens;
39716
40086
  metrics.actInferenceTimeMs += timeMs;
39717
40087
  } else if (method === "extract") {
39718
40088
  metrics.extractPromptTokens += inputTokens;
39719
40089
  metrics.extractCompletionTokens += outputTokens;
40090
+ metrics.extractReasoningTokens += reasoningTokens;
40091
+ metrics.extractCachedInputTokens += cachedInputTokens;
39720
40092
  metrics.extractInferenceTimeMs += timeMs;
39721
40093
  } else if (method === "observe") {
39722
40094
  metrics.observePromptTokens += inputTokens;
39723
40095
  metrics.observeCompletionTokens += outputTokens;
40096
+ metrics.observeReasoningTokens += reasoningTokens;
40097
+ metrics.observeCachedInputTokens += cachedInputTokens;
39724
40098
  metrics.observeInferenceTimeMs += timeMs;
39725
40099
  } else if (method === "agent") {
39726
40100
  metrics.agentPromptTokens += inputTokens;
39727
40101
  metrics.agentCompletionTokens += outputTokens;
40102
+ metrics.agentReasoningTokens += reasoningTokens;
40103
+ metrics.agentCachedInputTokens += cachedInputTokens;
39728
40104
  metrics.agentInferenceTimeMs += timeMs;
39729
40105
  }
39730
40106
  metrics.totalPromptTokens += inputTokens;
39731
40107
  metrics.totalCompletionTokens += outputTokens;
40108
+ metrics.totalReasoningTokens += reasoningTokens;
40109
+ metrics.totalCachedInputTokens += cachedInputTokens;
39732
40110
  metrics.totalInferenceTimeMs += timeMs;
39733
40111
  }
39734
40112
  }
@@ -39822,7 +40200,7 @@ var StagehandAPIClient = class {
39822
40200
  }
39823
40201
  });
39824
40202
  }
39825
- request(path6, options) {
40203
+ request(path7, options) {
39826
40204
  return __async(this, null, function* () {
39827
40205
  var _a;
39828
40206
  const defaultHeaders = {
@@ -39840,7 +40218,7 @@ var StagehandAPIClient = class {
39840
40218
  defaultHeaders["Content-Type"] = "application/json";
39841
40219
  }
39842
40220
  const response = yield this.fetchWithCookies(
39843
- `${(_a = process.env.STAGEHAND_API_URL) != null ? _a : "https://api.stagehand.browserbase.com/v1"}${path6}`,
40221
+ `${(_a = process.env.STAGEHAND_API_URL) != null ? _a : "https://api.stagehand.browserbase.com/v1"}${path7}`,
39844
40222
  __spreadProps(__spreadValues({}, options), {
39845
40223
  headers: __spreadValues(__spreadValues({}, defaultHeaders), options.headers)
39846
40224
  })
@@ -39863,7 +40241,7 @@ function resolveModelConfiguration(model) {
39863
40241
  if (model && typeof model === "object") {
39864
40242
  const _a = model, { modelName } = _a, clientOptions = __objRest(_a, ["modelName"]);
39865
40243
  if (!modelName) {
39866
- throw new Error(
40244
+ throw new StagehandInvalidArgumentError(
39867
40245
  "model.modelName is required when providing client options."
39868
40246
  );
39869
40247
  }
@@ -39897,18 +40275,28 @@ var _V3 = class _V3 {
39897
40275
  this.stagehandMetrics = {
39898
40276
  actPromptTokens: 0,
39899
40277
  actCompletionTokens: 0,
40278
+ actReasoningTokens: 0,
40279
+ actCachedInputTokens: 0,
39900
40280
  actInferenceTimeMs: 0,
39901
40281
  extractPromptTokens: 0,
39902
40282
  extractCompletionTokens: 0,
40283
+ extractReasoningTokens: 0,
40284
+ extractCachedInputTokens: 0,
39903
40285
  extractInferenceTimeMs: 0,
39904
40286
  observePromptTokens: 0,
39905
40287
  observeCompletionTokens: 0,
40288
+ observeReasoningTokens: 0,
40289
+ observeCachedInputTokens: 0,
39906
40290
  observeInferenceTimeMs: 0,
39907
40291
  agentPromptTokens: 0,
39908
40292
  agentCompletionTokens: 0,
40293
+ agentReasoningTokens: 0,
40294
+ agentCachedInputTokens: 0,
39909
40295
  agentInferenceTimeMs: 0,
39910
40296
  totalPromptTokens: 0,
39911
40297
  totalCompletionTokens: 0,
40298
+ totalReasoningTokens: 0,
40299
+ totalCachedInputTokens: 0,
39912
40300
  totalInferenceTimeMs: 0
39913
40301
  };
39914
40302
  var _a, _b, _c, _d, _e, _f, _g;
@@ -40092,34 +40480,50 @@ var _V3 = class _V3 {
40092
40480
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
40093
40481
  });
40094
40482
  }
40095
- updateMetrics(functionName, promptTokens, completionTokens, inferenceTimeMs) {
40483
+ updateMetrics(functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) {
40096
40484
  switch (functionName) {
40097
40485
  case "ACT" /* ACT */:
40098
40486
  this.stagehandMetrics.actPromptTokens += promptTokens;
40099
40487
  this.stagehandMetrics.actCompletionTokens += completionTokens;
40488
+ this.stagehandMetrics.actReasoningTokens += reasoningTokens;
40489
+ this.stagehandMetrics.actCachedInputTokens += cachedInputTokens;
40100
40490
  this.stagehandMetrics.actInferenceTimeMs += inferenceTimeMs;
40101
40491
  break;
40102
40492
  case "EXTRACT" /* EXTRACT */:
40103
40493
  this.stagehandMetrics.extractPromptTokens += promptTokens;
40104
40494
  this.stagehandMetrics.extractCompletionTokens += completionTokens;
40495
+ this.stagehandMetrics.extractReasoningTokens += reasoningTokens;
40496
+ this.stagehandMetrics.extractCachedInputTokens += cachedInputTokens;
40105
40497
  this.stagehandMetrics.extractInferenceTimeMs += inferenceTimeMs;
40106
40498
  break;
40107
40499
  case "OBSERVE" /* OBSERVE */:
40108
40500
  this.stagehandMetrics.observePromptTokens += promptTokens;
40109
40501
  this.stagehandMetrics.observeCompletionTokens += completionTokens;
40502
+ this.stagehandMetrics.observeReasoningTokens += reasoningTokens;
40503
+ this.stagehandMetrics.observeCachedInputTokens += cachedInputTokens;
40110
40504
  this.stagehandMetrics.observeInferenceTimeMs += inferenceTimeMs;
40111
40505
  break;
40112
40506
  case "AGENT" /* AGENT */:
40113
40507
  this.stagehandMetrics.agentPromptTokens += promptTokens;
40114
40508
  this.stagehandMetrics.agentCompletionTokens += completionTokens;
40509
+ this.stagehandMetrics.agentReasoningTokens += reasoningTokens;
40510
+ this.stagehandMetrics.agentCachedInputTokens += cachedInputTokens;
40115
40511
  this.stagehandMetrics.agentInferenceTimeMs += inferenceTimeMs;
40116
40512
  break;
40117
40513
  }
40118
- this.updateTotalMetrics(promptTokens, completionTokens, inferenceTimeMs);
40514
+ this.updateTotalMetrics(
40515
+ promptTokens,
40516
+ completionTokens,
40517
+ reasoningTokens,
40518
+ cachedInputTokens,
40519
+ inferenceTimeMs
40520
+ );
40119
40521
  }
40120
- updateTotalMetrics(promptTokens, completionTokens, inferenceTimeMs) {
40522
+ updateTotalMetrics(promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) {
40121
40523
  this.stagehandMetrics.totalPromptTokens += promptTokens;
40122
40524
  this.stagehandMetrics.totalCompletionTokens += completionTokens;
40525
+ this.stagehandMetrics.totalReasoningTokens += reasoningTokens;
40526
+ this.stagehandMetrics.totalCachedInputTokens += cachedInputTokens;
40123
40527
  this.stagehandMetrics.totalInferenceTimeMs += inferenceTimeMs;
40124
40528
  }
40125
40529
  _immediateShutdown(reason) {
@@ -40212,10 +40616,12 @@ var _V3 = class _V3 {
40212
40616
  (_a = this.opts.systemPrompt) != null ? _a : "",
40213
40617
  this.logInferenceToFile,
40214
40618
  (_b = this.opts.selfHeal) != null ? _b : true,
40215
- (functionName, promptTokens, completionTokens, inferenceTimeMs) => this.updateMetrics(
40619
+ (functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) => this.updateMetrics(
40216
40620
  functionName,
40217
40621
  promptTokens,
40218
40622
  completionTokens,
40623
+ reasoningTokens,
40624
+ cachedInputTokens,
40219
40625
  inferenceTimeMs
40220
40626
  ),
40221
40627
  this.domSettleTimeoutMs
@@ -40228,10 +40634,12 @@ var _V3 = class _V3 {
40228
40634
  (_c = this.opts.systemPrompt) != null ? _c : "",
40229
40635
  this.logInferenceToFile,
40230
40636
  this.experimental,
40231
- (functionName, promptTokens, completionTokens, inferenceTimeMs) => this.updateMetrics(
40637
+ (functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) => this.updateMetrics(
40232
40638
  functionName,
40233
40639
  promptTokens,
40234
40640
  completionTokens,
40641
+ reasoningTokens,
40642
+ cachedInputTokens,
40235
40643
  inferenceTimeMs
40236
40644
  )
40237
40645
  );
@@ -40243,10 +40651,12 @@ var _V3 = class _V3 {
40243
40651
  (_d = this.opts.systemPrompt) != null ? _d : "",
40244
40652
  this.logInferenceToFile,
40245
40653
  this.experimental,
40246
- (functionName, promptTokens, completionTokens, inferenceTimeMs) => this.updateMetrics(
40654
+ (functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) => this.updateMetrics(
40247
40655
  functionName,
40248
40656
  promptTokens,
40249
40657
  completionTokens,
40658
+ reasoningTokens,
40659
+ cachedInputTokens,
40250
40660
  inferenceTimeMs
40251
40661
  )
40252
40662
  );
@@ -40289,9 +40699,9 @@ var _V3 = class _V3 {
40289
40699
  let userDataDir = lbo.userDataDir;
40290
40700
  let createdTemp = false;
40291
40701
  if (!userDataDir) {
40292
- const base = import_path5.default.join(import_os2.default.tmpdir(), "stagehand-v3");
40293
- import_fs6.default.mkdirSync(base, { recursive: true });
40294
- userDataDir = import_fs6.default.mkdtempSync(import_path5.default.join(base, "profile-"));
40702
+ const base = import_path6.default.join(import_os2.default.tmpdir(), "stagehand-v3");
40703
+ import_fs7.default.mkdirSync(base, { recursive: true });
40704
+ userDataDir = import_fs7.default.mkdtempSync(import_path6.default.join(base, "profile-"));
40295
40705
  createdTemp = true;
40296
40706
  }
40297
40707
  const defaults2 = [
@@ -40363,8 +40773,9 @@ var _V3 = class _V3 {
40363
40773
  if (this.opts.env === "BROWSERBASE") {
40364
40774
  const { apiKey, projectId } = this.requireBrowserbaseCreds();
40365
40775
  if (!apiKey || !projectId) {
40366
- throw new Error(
40367
- "BROWSERBASE credentials missing. Provide in your v3 constructor, or set BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID in your .env"
40776
+ throw new MissingEnvironmentVariableError(
40777
+ "BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID",
40778
+ "Browserbase environment"
40368
40779
  );
40369
40780
  }
40370
40781
  this.logger({
@@ -40443,7 +40854,7 @@ var _V3 = class _V3 {
40443
40854
  return;
40444
40855
  }
40445
40856
  const neverEnv = this.opts.env;
40446
- throw new Error(`Unsupported env: ${neverEnv}`);
40857
+ throw new StagehandInitError(`Unsupported env: ${neverEnv}`);
40447
40858
  }));
40448
40859
  } catch (error) {
40449
40860
  if (this.externalLogger) {
@@ -40492,8 +40903,7 @@ var _V3 = class _V3 {
40492
40903
  act(input, options) {
40493
40904
  return __async(this, null, function* () {
40494
40905
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40495
- if (!this.actHandler)
40496
- throw new Error("V3 not initialized. Call init() before act().");
40906
+ if (!this.actHandler) throw new StagehandNotInitializedError("act()");
40497
40907
  let actResult;
40498
40908
  if (isObserveResult(input)) {
40499
40909
  const v3Page = yield this.resolvePage(options == null ? void 0 : options.page);
@@ -40524,7 +40934,7 @@ var _V3 = class _V3 {
40524
40934
  return actResult;
40525
40935
  }
40526
40936
  if (typeof input !== "string" || !input.trim()) {
40527
- throw new Error(
40937
+ throw new StagehandInvalidArgumentError(
40528
40938
  "act(): instruction string is required unless passing an Action"
40529
40939
  );
40530
40940
  }
@@ -40591,7 +41001,7 @@ var _V3 = class _V3 {
40591
41001
  return __async(this, null, function* () {
40592
41002
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40593
41003
  if (!this.extractHandler) {
40594
- throw new Error("V3 not initialized. Call init() before extract().");
41004
+ throw new StagehandNotInitializedError("extract()");
40595
41005
  }
40596
41006
  let instruction;
40597
41007
  let schema;
@@ -40609,7 +41019,9 @@ var _V3 = class _V3 {
40609
41019
  options = a || void 0;
40610
41020
  }
40611
41021
  if (!instruction && schema) {
40612
- throw new Error("extract(): schema provided without instruction");
41022
+ throw new StagehandInvalidArgumentError(
41023
+ "extract(): schema provided without instruction"
41024
+ );
40613
41025
  }
40614
41026
  const effectiveSchema = instruction && !schema ? defaultExtractSchema : schema;
40615
41027
  const page = yield this.resolvePage(options == null ? void 0 : options.page);
@@ -40641,7 +41053,7 @@ var _V3 = class _V3 {
40641
41053
  return __async(this, null, function* () {
40642
41054
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40643
41055
  if (!this.observeHandler) {
40644
- throw new Error("V3 not initialized. Call init() before observe().");
41056
+ throw new StagehandNotInitializedError("observe()");
40645
41057
  }
40646
41058
  let instruction;
40647
41059
  let options;
@@ -40685,7 +41097,7 @@ var _V3 = class _V3 {
40685
41097
  /** Return the browser-level CDP WebSocket endpoint. */
40686
41098
  connectURL() {
40687
41099
  if (this.state.kind === "UNINITIALIZED") {
40688
- throw new Error("V3 not initialized. Call await v3.init() first.");
41100
+ throw new StagehandNotInitializedError("connectURL()");
40689
41101
  }
40690
41102
  return this.state.ws;
40691
41103
  }
@@ -40720,7 +41132,7 @@ var _V3 = class _V3 {
40720
41132
  }
40721
41133
  try {
40722
41134
  if (this.state.createdTempProfile && !this.state.preserveUserDataDir && this.state.userDataDir) {
40723
- import_fs6.default.rmSync(this.state.userDataDir, { recursive: true, force: true });
41135
+ import_fs7.default.rmSync(this.state.userDataDir, { recursive: true, force: true });
40724
41136
  }
40725
41137
  } catch (e) {
40726
41138
  }
@@ -40750,10 +41162,9 @@ var _V3 = class _V3 {
40750
41162
  const missing = [];
40751
41163
  if (!apiKey) missing.push("BROWSERBASE_API_KEY");
40752
41164
  if (!projectId) missing.push("BROWSERBASE_PROJECT_ID");
40753
- throw new Error(
40754
- `BROWSERBASE credentials missing. Provide in your v3 constructor, or set ${missing.join(
40755
- ", "
40756
- )} in your .env`
41165
+ throw new MissingEnvironmentVariableError(
41166
+ missing.join(", "),
41167
+ "Browserbase"
40757
41168
  );
40758
41169
  }
40759
41170
  this.opts.apiKey = apiKey;
@@ -40799,7 +41210,9 @@ var _V3 = class _V3 {
40799
41210
  });
40800
41211
  return frameTree.frame.id;
40801
41212
  }
40802
- throw new Error("Unsupported page object passed to V3.act()");
41213
+ throw new StagehandInvalidArgumentError(
41214
+ "Unsupported page object passed to V3.act()"
41215
+ );
40803
41216
  });
40804
41217
  }
40805
41218
  isPlaywrightPage(p) {
@@ -40819,9 +41232,7 @@ var _V3 = class _V3 {
40819
41232
  }
40820
41233
  const ctx = this.ctx;
40821
41234
  if (!ctx) {
40822
- throw new Error(
40823
- "V3 context not initialized. Call init() before resolving pages."
40824
- );
41235
+ throw new StagehandNotInitializedError("resolvePage()");
40825
41236
  }
40826
41237
  return yield ctx.awaitActivePage();
40827
41238
  });
@@ -40835,24 +41246,30 @@ var _V3 = class _V3 {
40835
41246
  const frameId = yield this.resolveTopFrameId(input);
40836
41247
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40837
41248
  if (!page)
40838
- throw new Error("Failed to resolve V3 Page from Playwright page.");
41249
+ throw new StagehandInitError(
41250
+ "Failed to resolve V3 Page from Playwright page."
41251
+ );
40839
41252
  return page;
40840
41253
  }
40841
41254
  if (this.isPatchrightPage(input)) {
40842
41255
  const frameId = yield this.resolveTopFrameId(input);
40843
41256
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40844
41257
  if (!page)
40845
- throw new Error("Failed to resolve V3 Page from Playwright page.");
41258
+ throw new StagehandInitError(
41259
+ "Failed to resolve V3 Page from Patchright page."
41260
+ );
40846
41261
  return page;
40847
41262
  }
40848
41263
  if (this.isPuppeteerPage(input)) {
40849
41264
  const frameId = yield this.resolveTopFrameId(input);
40850
41265
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40851
41266
  if (!page)
40852
- throw new Error("Failed to resolve V3 Page from Puppeteer page.");
41267
+ throw new StagehandInitError(
41268
+ "Failed to resolve V3 Page from Puppeteer page."
41269
+ );
40853
41270
  return page;
40854
41271
  }
40855
- throw new Error("Unsupported page object.");
41272
+ throw new StagehandInvalidArgumentError("Unsupported page object.");
40856
41273
  });
40857
41274
  }
40858
41275
  /**
@@ -40879,8 +41296,8 @@ var _V3 = class _V3 {
40879
41296
  });
40880
41297
  if (options == null ? void 0 : options.cua) {
40881
41298
  if (((options == null ? void 0 : options.integrations) || (options == null ? void 0 : options.tools)) && !this.experimental) {
40882
- throw new Error(
40883
- "MCP integrations and custom tools are experimental. Enable experimental: true in V3 options."
41299
+ throw new ExperimentalNotConfiguredError(
41300
+ "MCP integrations and custom tools"
40884
41301
  );
40885
41302
  }
40886
41303
  const modelToUse = (options == null ? void 0 : options.model) || __spreadValues({
@@ -40888,9 +41305,7 @@ var _V3 = class _V3 {
40888
41305
  }, this.modelClientOptions);
40889
41306
  const { modelName, isCua, clientOptions } = resolveModel(modelToUse);
40890
41307
  if (!isCua) {
40891
- throw new Error(
40892
- "To use the computer use agent, please provide a CUA model in the agent constructor or stagehand config. Try one of our supported CUA models: " + AVAILABLE_CUA_MODELS.join(", ")
40893
- );
41308
+ throw new CuaModelRequiredError(AVAILABLE_CUA_MODELS);
40894
41309
  }
40895
41310
  const agentConfigSignature2 = this.agentCache.buildConfigSignature(options);
40896
41311
  return {
@@ -40898,9 +41313,7 @@ var _V3 = class _V3 {
40898
41313
  return withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40899
41314
  var _a2, _b2;
40900
41315
  if ((options == null ? void 0 : options.integrations) && !this.experimental) {
40901
- throw new Error(
40902
- "MCP integrations are experimental. Enable experimental: true in V3 options."
40903
- );
41316
+ throw new ExperimentalNotConfiguredError("MCP integrations");
40904
41317
  }
40905
41318
  const tools = (options == null ? void 0 : options.integrations) ? yield resolveTools(options.integrations, options.tools) : (_a2 = options == null ? void 0 : options.tools) != null ? _a2 : {};
40906
41319
  const handler = new V3CuaAgentHandler(
@@ -40981,8 +41394,8 @@ Do not ask follow up questions, the user will trust your judgement.`
40981
41394
  return withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40982
41395
  var _a2, _b2;
40983
41396
  if (((options == null ? void 0 : options.integrations) || (options == null ? void 0 : options.tools)) && !this.experimental) {
40984
- throw new Error(
40985
- "MCP integrations and custom tools are experimental. Enable experimental: true in V3 options."
41397
+ throw new ExperimentalNotConfiguredError(
41398
+ "MCP integrations and custom tools"
40986
41399
  );
40987
41400
  }
40988
41401
  const tools = (options == null ? void 0 : options.integrations) ? yield resolveTools(options.integrations, options.tools) : (_a2 = options == null ? void 0 : options.tools) != null ? _a2 : {};
@@ -41067,6 +41480,7 @@ function isObserveResult(v) {
41067
41480
  // lib/v3Evaluator.ts
41068
41481
  var import_dotenv2 = __toESM(require("dotenv"));
41069
41482
  var import_v318 = require("zod/v3");
41483
+ init_sdkErrors();
41070
41484
  import_dotenv2.default.config();
41071
41485
  var EvaluationSchema = import_v318.z.object({
41072
41486
  evaluation: import_v318.z.enum(["YES", "NO"]),
@@ -41097,9 +41511,14 @@ var V3Evaluator = class {
41097
41511
  screenshotDelayMs = 250,
41098
41512
  agentReasoning
41099
41513
  } = options;
41100
- if (!question) throw new Error("Question cannot be an empty string");
41514
+ if (!question)
41515
+ throw new StagehandInvalidArgumentError(
41516
+ "Question cannot be an empty string"
41517
+ );
41101
41518
  if (!answer && !screenshot)
41102
- throw new Error("Either answer (text) or screenshot must be provided");
41519
+ throw new StagehandInvalidArgumentError(
41520
+ "Either answer (text) or screenshot must be provided"
41521
+ );
41103
41522
  if (Array.isArray(screenshot)) {
41104
41523
  return this._evaluateWithMultipleScreenshots({
41105
41524
  question,
@@ -41167,7 +41586,10 @@ ${agentReasoning}` : question
41167
41586
  systemPrompt = "You are an expert evaluator that returns YES or NO with a concise reasoning.",
41168
41587
  screenshotDelayMs = 250
41169
41588
  } = options;
41170
- if (!(questions == null ? void 0 : questions.length)) throw new Error("Questions array cannot be empty");
41589
+ if (!(questions == null ? void 0 : questions.length))
41590
+ throw new StagehandInvalidArgumentError(
41591
+ "Questions array cannot be empty"
41592
+ );
41171
41593
  yield new Promise((r) => setTimeout(r, screenshotDelayMs));
41172
41594
  let imageBuffer;
41173
41595
  if (screenshot) {
@@ -41238,9 +41660,14 @@ You will be given multiple questions${screenshot ? " with a screenshot" : ""}. $
41238
41660
  ${agentReasoning ? "The agent's reasoning provides crucial context about what actions were attempted, what was observed, and the decision-making process. Use this alongside the visual evidence to make a comprehensive evaluation." : ""}
41239
41661
  Today's date is ${(/* @__PURE__ */ new Date()).toLocaleDateString()}`
41240
41662
  } = options;
41241
- if (!question) throw new Error("Question cannot be an empty string");
41663
+ if (!question)
41664
+ throw new StagehandInvalidArgumentError(
41665
+ "Question cannot be an empty string"
41666
+ );
41242
41667
  if (!screenshots || screenshots.length === 0)
41243
- throw new Error("At least one screenshot must be provided");
41668
+ throw new StagehandInvalidArgumentError(
41669
+ "At least one screenshot must be provided"
41670
+ );
41244
41671
  const llmClient = this.getClient();
41245
41672
  const imageContents = screenshots.map((s) => ({
41246
41673
  type: "image_url",
@@ -41294,9 +41721,12 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41294
41721
  AnnotatedScreenshotText,
41295
41722
  BrowserbaseSessionNotFoundError,
41296
41723
  CaptchaTimeoutError,
41724
+ ConnectionTimeoutError,
41297
41725
  ConsoleMessage,
41298
41726
  ContentFrameNotFoundError,
41299
41727
  CreateChatCompletionResponseError,
41728
+ CuaModelRequiredError,
41729
+ ElementNotVisibleError,
41300
41730
  ExperimentalApiConflictError,
41301
41731
  ExperimentalNotConfiguredError,
41302
41732
  HandlerNotInitializedError,
@@ -41307,7 +41737,10 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41307
41737
  MCPConnectionError,
41308
41738
  MissingEnvironmentVariableError,
41309
41739
  MissingLLMConfigurationError,
41740
+ PageNotFoundError,
41310
41741
  Response,
41742
+ ResponseBodyError,
41743
+ ResponseParseError,
41311
41744
  Stagehand,
41312
41745
  StagehandAPIError,
41313
41746
  StagehandAPIUnauthorizedError,
@@ -41330,6 +41763,7 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41330
41763
  StagehandShadowRootMissingError,
41331
41764
  StagehandShadowSegmentEmptyError,
41332
41765
  StagehandShadowSegmentNotFoundError,
41766
+ TimeoutError,
41333
41767
  UnsupportedAISDKModelProviderError,
41334
41768
  UnsupportedModelError,
41335
41769
  UnsupportedModelProviderError,