@browserbasehq/orca 3.0.1-zod4 → 3.0.2-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 +71 -41
  2. package/dist/index.js +777 -602
  3. package/package.json +21 -19
  4. package/LICENSE +0 -21
package/dist/index.js CHANGED
@@ -81,6 +81,278 @@ var __async = (__this, __arguments, generator) => {
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.2-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);
@@ -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
  });
@@ -1981,6 +2268,7 @@ var init_locator = __esm({
1981
2268
  import_buffer = require("buffer");
1982
2269
  init_locatorScripts_generated();
1983
2270
  init_selectorResolver();
2271
+ init_sdkErrors();
1984
2272
  Locator = class _Locator {
1985
2273
  constructor(frame, selector, options, nthIndex = 0) {
1986
2274
  this.frame = frame;
@@ -2018,7 +2306,9 @@ var init_locator = __esm({
2018
2306
  if (data instanceof Uint8Array) return import_buffer.Buffer.from(data);
2019
2307
  if (typeof data === "string") return import_buffer.Buffer.from(data);
2020
2308
  if (data instanceof ArrayBuffer) return import_buffer.Buffer.from(new Uint8Array(data));
2021
- throw new Error("Unsupported file payload buffer type");
2309
+ throw new StagehandInvalidArgumentError(
2310
+ "Unsupported file payload buffer type"
2311
+ );
2022
2312
  };
2023
2313
  try {
2024
2314
  try {
@@ -2032,9 +2322,11 @@ var init_locator = __esm({
2032
2322
  );
2033
2323
  const ok = Boolean(res.result.value);
2034
2324
  if (!ok)
2035
- throw new Error('Target is not an <input type="file"> element');
2325
+ throw new StagehandInvalidArgumentError(
2326
+ 'Target is not an <input type="file"> element'
2327
+ );
2036
2328
  } catch (e) {
2037
- throw new Error(
2329
+ throw new StagehandInvalidArgumentError(
2038
2330
  e instanceof Error ? e.message : "Unable to verify file input element"
2039
2331
  );
2040
2332
  }
@@ -2057,7 +2349,7 @@ var init_locator = __esm({
2057
2349
  filePaths.push(tmp);
2058
2350
  continue;
2059
2351
  }
2060
- throw new Error(
2352
+ throw new StagehandInvalidArgumentError(
2061
2353
  "Unsupported setInputFiles item \u2013 expected path or payload"
2062
2354
  );
2063
2355
  }
@@ -2123,7 +2415,7 @@ var init_locator = __esm({
2123
2415
  "DOM.getBoxModel",
2124
2416
  { objectId }
2125
2417
  );
2126
- if (!box.model) throw new Error("Element not visible (no box model)");
2418
+ if (!box.model) throw new ElementNotVisibleError(this.selector);
2127
2419
  const { cx, cy } = this.centerFromBoxContent(box.model.content);
2128
2420
  return { x: Math.round(cx), y: Math.round(cy) };
2129
2421
  } finally {
@@ -2210,7 +2502,7 @@ var init_locator = __esm({
2210
2502
  "DOM.getBoxModel",
2211
2503
  { objectId }
2212
2504
  );
2213
- if (!box.model) throw new Error("Element not visible (no box model)");
2505
+ if (!box.model) throw new ElementNotVisibleError(this.selector);
2214
2506
  const { cx, cy } = this.centerFromBoxContent(box.model.content);
2215
2507
  yield session.send("Input.dispatchMouseEvent", {
2216
2508
  type: "mouseMoved",
@@ -2245,7 +2537,7 @@ var init_locator = __esm({
2245
2537
  "DOM.getBoxModel",
2246
2538
  { objectId }
2247
2539
  );
2248
- if (!box.model) throw new Error("Element not visible (no box model)");
2540
+ if (!box.model) throw new ElementNotVisibleError(this.selector);
2249
2541
  const { cx, cy } = this.centerFromBoxContent(box.model.content);
2250
2542
  yield session.send("Input.dispatchMouseEvent", {
2251
2543
  type: "mouseMoved",
@@ -2412,7 +2704,9 @@ var init_locator = __esm({
2412
2704
  }
2413
2705
  if (status === "error") {
2414
2706
  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})`);
2707
+ throw new StagehandInvalidArgumentError(
2708
+ `Failed to fill element (${reason})`
2709
+ );
2416
2710
  }
2417
2711
  if (!status) {
2418
2712
  yield this.type(value);
@@ -2639,7 +2933,9 @@ var init_locator = __esm({
2639
2933
  nth(index) {
2640
2934
  const value = Number(index);
2641
2935
  if (!Number.isFinite(value) || value < 0) {
2642
- throw new Error("locator().nth() expects a non-negative index");
2936
+ throw new StagehandInvalidArgumentError(
2937
+ "locator().nth() expects a non-negative index"
2938
+ );
2643
2939
  }
2644
2940
  const nextIndex = Math.floor(value);
2645
2941
  if (nextIndex === this.nthIndex) {
@@ -2662,7 +2958,7 @@ var init_locator = __esm({
2662
2958
  this.nthIndex
2663
2959
  );
2664
2960
  if (!resolved) {
2665
- throw new Error(`Element not found for selector: ${this.selector}`);
2961
+ throw new StagehandElementNotFoundError([this.selector]);
2666
2962
  }
2667
2963
  return resolved;
2668
2964
  });
@@ -2670,7 +2966,7 @@ var init_locator = __esm({
2670
2966
  /** Compute a center point from a BoxModel content quad */
2671
2967
  centerFromBoxContent(content) {
2672
2968
  if (!content || content.length < 8) {
2673
- throw new Error("Invalid box model content quad");
2969
+ throw new StagehandInvalidArgumentError("Invalid box model content quad");
2674
2970
  }
2675
2971
  const xs = [content[0], content[2], content[4], content[6]];
2676
2972
  const ys = [content[1], content[3], content[5], content[7]];
@@ -2781,6 +3077,7 @@ var FrameLocator, LocatorDelegate;
2781
3077
  var init_frameLocator = __esm({
2782
3078
  "lib/v3/understudy/frameLocator.ts"() {
2783
3079
  init_executionContextRegistry();
3080
+ init_sdkErrors();
2784
3081
  FrameLocator = class _FrameLocator {
2785
3082
  constructor(page, selector, parent, root) {
2786
3083
  this.page = page;
@@ -2823,9 +3120,7 @@ var init_frameLocator = __esm({
2823
3120
  } catch (e) {
2824
3121
  }
2825
3122
  }
2826
- throw new Error(
2827
- `frameLocator: could not resolve child frame for selector: ${this.selector}`
2828
- );
3123
+ throw new ContentFrameNotFoundError(this.selector);
2829
3124
  } finally {
2830
3125
  yield parentSession2.send("Runtime.releaseObject", { objectId }).catch(() => {
2831
3126
  });
@@ -3019,6 +3314,7 @@ var init_deepLocator = __esm({
3019
3314
  init_locator();
3020
3315
  init_logger();
3021
3316
  init_frameLocator();
3317
+ init_sdkErrors();
3022
3318
  IFRAME_STEP_RE2 = /^iframe(?:\[\d+])?$/i;
3023
3319
  DeepLocatorDelegate = class _DeepLocatorDelegate {
3024
3320
  constructor(page, root, selector, nthIndex = 0) {
@@ -3134,7 +3430,9 @@ var init_deepLocator = __esm({
3134
3430
  nth(index) {
3135
3431
  const value = Number(index);
3136
3432
  if (!Number.isFinite(value) || value < 0) {
3137
- throw new Error("deepLocator().nth() expects a non-negative index");
3433
+ throw new StagehandInvalidArgumentError(
3434
+ "deepLocator().nth() expects a non-negative index"
3435
+ );
3138
3436
  }
3139
3437
  const nextIndex = Math.floor(value);
3140
3438
  if (nextIndex === this.nthIndex) return this;
@@ -4049,6 +4347,15 @@ var init_consoleMessage = __esm({
4049
4347
  });
4050
4348
 
4051
4349
  // lib/v3/understudy/response.ts
4350
+ function isSerializableResponse(value) {
4351
+ if (!value || typeof value !== "object") return false;
4352
+ const candidate = value;
4353
+ if (typeof candidate.requestId !== "string") return false;
4354
+ if (!candidate.response || typeof candidate.response !== "object") {
4355
+ return false;
4356
+ }
4357
+ return true;
4358
+ }
4052
4359
  function createDeferred() {
4053
4360
  let resolve3;
4054
4361
  let reject;
@@ -4081,7 +4388,8 @@ function parseHeadersText(headersText) {
4081
4388
  var Response;
4082
4389
  var init_response = __esm({
4083
4390
  "lib/v3/understudy/response.ts"() {
4084
- Response = class {
4391
+ init_sdkErrors();
4392
+ Response = class _Response {
4085
4393
  /**
4086
4394
  * Build a response wrapper from the CDP notification associated with a
4087
4395
  * navigation. The constructor captures the owning page/session so follow-up
@@ -4251,7 +4559,7 @@ var init_response = __esm({
4251
4559
  "Network.getResponseBody",
4252
4560
  { requestId: this.requestId }
4253
4561
  ).catch((error) => {
4254
- throw new Error(`Failed to retrieve response body: ${String(error)}`);
4562
+ throw new ResponseBodyError(String(error));
4255
4563
  });
4256
4564
  if (result.base64Encoded) {
4257
4565
  return Buffer.from(result.body, "base64");
@@ -4273,7 +4581,7 @@ var init_response = __esm({
4273
4581
  try {
4274
4582
  return JSON.parse(text);
4275
4583
  } catch (error) {
4276
- throw new Error(`Failed to parse JSON response: ${String(error)}`);
4584
+ throw new ResponseParseError(String(error));
4277
4585
  }
4278
4586
  });
4279
4587
  }
@@ -4308,6 +4616,33 @@ var init_response = __esm({
4308
4616
  this.headersObject[lower] = segments.join(", ");
4309
4617
  }
4310
4618
  }
4619
+ /**
4620
+ * Internal helper for creating a Response object from a Serializable
4621
+ * goto response from the Stagehand API
4622
+ */
4623
+ static fromSerializable(serialized, context) {
4624
+ var _a;
4625
+ const reconstructed = new _Response({
4626
+ page: context.page,
4627
+ session: context.session,
4628
+ requestId: serialized.requestId,
4629
+ frameId: serialized.frameId,
4630
+ loaderId: serialized.loaderId,
4631
+ response: serialized.response,
4632
+ fromServiceWorker: (_a = serialized.fromServiceWorkerFlag) != null ? _a : false
4633
+ });
4634
+ if (serialized.extraInfoHeaders) {
4635
+ reconstructed.applyExtraInfo({
4636
+ requestId: serialized.requestId,
4637
+ headers: serialized.extraInfoHeaders,
4638
+ headersText: serialized.extraInfoHeadersText
4639
+ });
4640
+ }
4641
+ if (serialized.finishedSettled) {
4642
+ reconstructed.markFinished(null);
4643
+ }
4644
+ return reconstructed;
4645
+ }
4311
4646
  /** Marks the response as finished and resolves the `finished()` promise. */
4312
4647
  markFinished(error) {
4313
4648
  if (this.finishedSettled) return;
@@ -4327,6 +4662,7 @@ var Frame;
4327
4662
  var init_frame = __esm({
4328
4663
  "lib/v3/understudy/frame.ts"() {
4329
4664
  init_locator();
4665
+ init_sdkErrors();
4330
4666
  Frame = class _Frame {
4331
4667
  constructor(session, frameId, pageId) {
4332
4668
  this.session = session;
@@ -4433,7 +4769,9 @@ var init_frame = __esm({
4433
4769
  }
4434
4770
  );
4435
4771
  if (res.exceptionDetails) {
4436
- throw new Error((_a = res.exceptionDetails.text) != null ? _a : "Evaluation failed");
4772
+ throw new StagehandEvalError(
4773
+ (_a = res.exceptionDetails.text) != null ? _a : "Evaluation failed"
4774
+ );
4437
4775
  }
4438
4776
  return res.result.value;
4439
4777
  });
@@ -5086,6 +5424,7 @@ var init_networkManager = __esm({
5086
5424
  var LifecycleWatcher;
5087
5425
  var init_lifecycleWatcher = __esm({
5088
5426
  "lib/v3/understudy/lifecycleWatcher.ts"() {
5427
+ init_sdkErrors();
5089
5428
  init_network();
5090
5429
  LifecycleWatcher = class {
5091
5430
  /**
@@ -5223,7 +5562,7 @@ var init_lifecycleWatcher = __esm({
5223
5562
  timeRemaining(deadline) {
5224
5563
  const remaining = deadline - Date.now();
5225
5564
  if (remaining <= 0) {
5226
- throw new Error(`Lifecycle wait timed out after ${this.timeoutMs}ms`);
5565
+ throw new TimeoutError("Lifecycle wait", this.timeoutMs);
5227
5566
  }
5228
5567
  return remaining;
5229
5568
  }
@@ -5520,11 +5859,15 @@ function normalizeScreenshotClip(clip) {
5520
5859
  const height = Number(clip.height);
5521
5860
  for (const [key, value] of Object.entries({ x, y, width, height })) {
5522
5861
  if (!Number.isFinite(value)) {
5523
- throw new Error(`screenshot: clip.${key} must be a finite number`);
5862
+ throw new StagehandInvalidArgumentError(
5863
+ `screenshot: clip.${key} must be a finite number`
5864
+ );
5524
5865
  }
5525
5866
  }
5526
5867
  if (width <= 0 || height <= 0) {
5527
- throw new Error("screenshot: clip width/height must be positive");
5868
+ throw new StagehandInvalidArgumentError(
5869
+ "screenshot: clip width/height must be positive"
5870
+ );
5528
5871
  }
5529
5872
  return { x, y, width, height };
5530
5873
  }
@@ -5813,6 +6156,7 @@ function withScreenshotTimeout(timeoutMs, task) {
5813
6156
  }
5814
6157
  var init_screenshotUtils = __esm({
5815
6158
  "lib/v3/understudy/screenshotUtils.ts"() {
6159
+ init_sdkErrors();
5816
6160
  }
5817
6161
  });
5818
6162
 
@@ -5834,7 +6178,9 @@ var init_page = __esm({
5834
6178
  init_networkManager();
5835
6179
  init_lifecycleWatcher();
5836
6180
  init_navigationResponseTracker();
6181
+ init_response();
5837
6182
  init_consoleMessage();
6183
+ init_sdkErrors();
5838
6184
  init_screenshotUtils();
5839
6185
  LIFECYCLE_NAME = {
5840
6186
  load: "load",
@@ -6151,7 +6497,7 @@ var init_page = __esm({
6151
6497
  }
6152
6498
  on(event, listener) {
6153
6499
  if (event !== "console") {
6154
- throw new Error(`Unsupported event: ${event}`);
6500
+ throw new StagehandInvalidArgumentError(`Unsupported event: ${event}`);
6155
6501
  }
6156
6502
  const firstListener = this.consoleListeners.size === 0;
6157
6503
  this.consoleListeners.add(listener);
@@ -6162,7 +6508,7 @@ var init_page = __esm({
6162
6508
  }
6163
6509
  once(event, listener) {
6164
6510
  if (event !== "console") {
6165
- throw new Error(`Unsupported event: ${event}`);
6511
+ throw new StagehandInvalidArgumentError(`Unsupported event: ${event}`);
6166
6512
  }
6167
6513
  const wrapper = (message) => {
6168
6514
  this.off("console", wrapper);
@@ -6172,7 +6518,7 @@ var init_page = __esm({
6172
6518
  }
6173
6519
  off(event, listener) {
6174
6520
  if (event !== "console") {
6175
- throw new Error(`Unsupported event: ${event}`);
6521
+ throw new StagehandInvalidArgumentError(`Unsupported event: ${event}`);
6176
6522
  }
6177
6523
  this.consoleListeners.delete(listener);
6178
6524
  if (this.consoleListeners.size === 0) {
@@ -6361,13 +6707,19 @@ var init_page = __esm({
6361
6707
  });
6362
6708
  try {
6363
6709
  if (this.apiClient) {
6364
- yield this.apiClient.goto(
6710
+ const result = yield this.apiClient.goto(
6365
6711
  url,
6366
6712
  { waitUntil: options == null ? void 0 : options.waitUntil },
6367
6713
  this.mainFrameId()
6368
6714
  );
6369
6715
  this._currentUrl = url;
6370
- return null;
6716
+ if (isSerializableResponse(result)) {
6717
+ return Response.fromSerializable(result, {
6718
+ page: this,
6719
+ session: this.mainSession
6720
+ });
6721
+ }
6722
+ return result;
6371
6723
  }
6372
6724
  const response = yield this.mainSession.send(
6373
6725
  "Page.navigate",
@@ -6592,13 +6944,17 @@ var init_page = __esm({
6592
6944
  const opts = options != null ? options : {};
6593
6945
  const type = (_a = opts.type) != null ? _a : "png";
6594
6946
  if (type !== "png" && type !== "jpeg") {
6595
- throw new Error(`screenshot: unsupported image type "${type}"`);
6947
+ throw new StagehandInvalidArgumentError(
6948
+ `screenshot: unsupported image type "${type}"`
6949
+ );
6596
6950
  }
6597
6951
  if (opts.fullPage && opts.clip) {
6598
- throw new Error("screenshot: clip and fullPage cannot be used together");
6952
+ throw new StagehandInvalidArgumentError(
6953
+ "screenshot: clip and fullPage cannot be used together"
6954
+ );
6599
6955
  }
6600
6956
  if (type === "png" && typeof opts.quality === "number") {
6601
- throw new Error(
6957
+ throw new StagehandInvalidArgumentError(
6602
6958
  'screenshot: quality option is only valid for type="jpeg"'
6603
6959
  );
6604
6960
  }
@@ -6735,7 +7091,7 @@ var init_page = __esm({
6735
7091
  );
6736
7092
  if (exceptionDetails) {
6737
7093
  const msg = exceptionDetails.text || ((_a = exceptionDetails.exception) == null ? void 0 : _a.description) || "Evaluation failed";
6738
- throw new Error(msg);
7094
+ throw new StagehandEvalError(msg);
6739
7095
  }
6740
7096
  return result == null ? void 0 : result.value;
6741
7097
  });
@@ -7374,9 +7730,12 @@ __export(v3_exports, {
7374
7730
  AnnotatedScreenshotText: () => AnnotatedScreenshotText,
7375
7731
  BrowserbaseSessionNotFoundError: () => BrowserbaseSessionNotFoundError,
7376
7732
  CaptchaTimeoutError: () => CaptchaTimeoutError,
7733
+ ConnectionTimeoutError: () => ConnectionTimeoutError,
7377
7734
  ConsoleMessage: () => ConsoleMessage,
7378
7735
  ContentFrameNotFoundError: () => ContentFrameNotFoundError,
7379
7736
  CreateChatCompletionResponseError: () => CreateChatCompletionResponseError,
7737
+ CuaModelRequiredError: () => CuaModelRequiredError,
7738
+ ElementNotVisibleError: () => ElementNotVisibleError,
7380
7739
  ExperimentalApiConflictError: () => ExperimentalApiConflictError,
7381
7740
  ExperimentalNotConfiguredError: () => ExperimentalNotConfiguredError,
7382
7741
  HandlerNotInitializedError: () => HandlerNotInitializedError,
@@ -7387,7 +7746,10 @@ __export(v3_exports, {
7387
7746
  MCPConnectionError: () => MCPConnectionError,
7388
7747
  MissingEnvironmentVariableError: () => MissingEnvironmentVariableError,
7389
7748
  MissingLLMConfigurationError: () => MissingLLMConfigurationError,
7749
+ PageNotFoundError: () => PageNotFoundError,
7390
7750
  Response: () => Response,
7751
+ ResponseBodyError: () => ResponseBodyError,
7752
+ ResponseParseError: () => ResponseParseError,
7391
7753
  Stagehand: () => V3,
7392
7754
  StagehandAPIError: () => StagehandAPIError,
7393
7755
  StagehandAPIUnauthorizedError: () => StagehandAPIUnauthorizedError,
@@ -7410,6 +7772,7 @@ __export(v3_exports, {
7410
7772
  StagehandShadowRootMissingError: () => StagehandShadowRootMissingError,
7411
7773
  StagehandShadowSegmentEmptyError: () => StagehandShadowSegmentEmptyError,
7412
7774
  StagehandShadowSegmentNotFoundError: () => StagehandShadowSegmentNotFoundError,
7775
+ TimeoutError: () => TimeoutError,
7413
7776
  UnsupportedAISDKModelProviderError: () => UnsupportedAISDKModelProviderError,
7414
7777
  UnsupportedModelError: () => UnsupportedModelError,
7415
7778
  UnsupportedModelProviderError: () => UnsupportedModelProviderError,
@@ -7442,233 +7805,10 @@ var import_os2 = __toESM(require("os"));
7442
7805
  var import_path5 = __toESM(require("path"));
7443
7806
  var import_process2 = __toESM(require("process"));
7444
7807
 
7445
- // lib/version.ts
7446
- var STAGEHAND_VERSION = "3.0.1-zod4";
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
7808
  // lib/utils.ts
7809
+ init_sdkErrors();
7670
7810
  var import_genai = require("@google/genai");
7671
- var import_zod = require("zod");
7811
+ var import_v3 = require("zod/v3");
7672
7812
  var ID_PATTERN = /^\d+-\d+$/;
7673
7813
  function validateZodSchema(schema, data) {
7674
7814
  const result = schema.safeParse(data);
@@ -7692,28 +7832,28 @@ function decorateGeminiSchema(geminiSchema, zodSchema2) {
7692
7832
  function toGeminiSchema(zodSchema2) {
7693
7833
  const zodType = getZodType(zodSchema2);
7694
7834
  switch (zodType) {
7695
- case "array": {
7696
- const arraySchema = zodSchema2;
7697
- const element = arraySchema._zod.def.element;
7835
+ case "ZodArray": {
7698
7836
  return decorateGeminiSchema(
7699
7837
  {
7700
7838
  type: import_genai.Type.ARRAY,
7701
- items: toGeminiSchema(element != null ? element : import_zod.z.any())
7839
+ items: toGeminiSchema(
7840
+ zodSchema2.element
7841
+ )
7702
7842
  },
7703
7843
  zodSchema2
7704
7844
  );
7705
7845
  }
7706
- case "object": {
7846
+ case "ZodObject": {
7707
7847
  const properties = {};
7708
7848
  const required = [];
7709
- const objectSchema = zodSchema2;
7710
- const shape = objectSchema._zod.def.shape;
7711
- Object.entries(shape).forEach(([key, value]) => {
7712
- properties[key] = toGeminiSchema(value);
7713
- if (getZodType(value) !== "optional") {
7714
- required.push(key);
7849
+ Object.entries(zodSchema2.shape).forEach(
7850
+ ([key, value]) => {
7851
+ properties[key] = toGeminiSchema(value);
7852
+ if (getZodType(value) !== "ZodOptional") {
7853
+ required.push(key);
7854
+ }
7715
7855
  }
7716
- });
7856
+ );
7717
7857
  return decorateGeminiSchema(
7718
7858
  {
7719
7859
  type: import_genai.Type.OBJECT,
@@ -7723,45 +7863,39 @@ function toGeminiSchema(zodSchema2) {
7723
7863
  zodSchema2
7724
7864
  );
7725
7865
  }
7726
- case "string":
7727
- case "url":
7866
+ case "ZodString":
7728
7867
  return decorateGeminiSchema(
7729
7868
  {
7730
7869
  type: import_genai.Type.STRING
7731
7870
  },
7732
7871
  zodSchema2
7733
7872
  );
7734
- case "number":
7873
+ case "ZodNumber":
7735
7874
  return decorateGeminiSchema(
7736
7875
  {
7737
7876
  type: import_genai.Type.NUMBER
7738
7877
  },
7739
7878
  zodSchema2
7740
7879
  );
7741
- case "boolean":
7880
+ case "ZodBoolean":
7742
7881
  return decorateGeminiSchema(
7743
7882
  {
7744
7883
  type: import_genai.Type.BOOLEAN
7745
7884
  },
7746
7885
  zodSchema2
7747
7886
  );
7748
- case "enum": {
7749
- const enumSchema = zodSchema2;
7750
- const values = Object.values(enumSchema._zod.def.entries);
7887
+ case "ZodEnum":
7751
7888
  return decorateGeminiSchema(
7752
7889
  {
7753
7890
  type: import_genai.Type.STRING,
7754
- enum: values
7891
+ enum: zodSchema2._def.values
7755
7892
  },
7756
7893
  zodSchema2
7757
7894
  );
7758
- }
7759
- case "default":
7760
- case "nullable":
7761
- case "optional": {
7762
- const wrapperSchema = zodSchema2;
7763
- const innerType = wrapperSchema._zod.def.innerType;
7764
- const innerSchema = toGeminiSchema(innerType);
7895
+ case "ZodDefault":
7896
+ case "ZodNullable":
7897
+ case "ZodOptional": {
7898
+ const innerSchema = toGeminiSchema(zodSchema2._def.innerType);
7765
7899
  return decorateGeminiSchema(
7766
7900
  __spreadProps(__spreadValues({}, innerSchema), {
7767
7901
  nullable: true
@@ -7769,23 +7903,14 @@ function toGeminiSchema(zodSchema2) {
7769
7903
  zodSchema2
7770
7904
  );
7771
7905
  }
7772
- case "literal": {
7773
- const literalSchema = zodSchema2;
7774
- const values = literalSchema._zod.def.values;
7906
+ case "ZodLiteral":
7775
7907
  return decorateGeminiSchema(
7776
7908
  {
7777
7909
  type: import_genai.Type.STRING,
7778
- enum: values
7910
+ enum: [zodSchema2._def.value]
7779
7911
  },
7780
7912
  zodSchema2
7781
7913
  );
7782
- }
7783
- case "pipe": {
7784
- const pipeSchema = zodSchema2;
7785
- const inSchema = pipeSchema._zod.def.in;
7786
- return toGeminiSchema(inSchema);
7787
- }
7788
- // Standalone transforms and any unknown types fall through to default
7789
7914
  default:
7790
7915
  return decorateGeminiSchema(
7791
7916
  {
@@ -7797,40 +7922,21 @@ function toGeminiSchema(zodSchema2) {
7797
7922
  }
7798
7923
  }
7799
7924
  function getZodType(schema) {
7800
- var _a, _b;
7801
- const schemaWithDef = schema;
7802
- if ((_b = (_a = schemaWithDef._zod) == null ? void 0 : _a.def) == null ? void 0 : _b.type) {
7803
- return schemaWithDef._zod.def.type;
7804
- }
7805
- throw new Error(
7806
- `Unable to determine Zod schema type. Schema: ${JSON.stringify(schema)}`
7807
- );
7925
+ return schema._def.typeName;
7808
7926
  }
7809
7927
  function transformSchema(schema, currentPath) {
7810
7928
  var _a, _b;
7811
- if (isKind(schema, "url")) {
7812
- const transformed = makeIdStringSchema(schema);
7813
- return [transformed, [{ segments: [] }]];
7814
- }
7815
- if (isKind(schema, "string")) {
7816
- const stringSchema = schema;
7817
- const checks = stringSchema._zod.def.checks;
7818
- const format = (_a = stringSchema._zod.bag) == null ? void 0 : _a.format;
7819
- const hasUrlCheck = ((_b = checks == null ? void 0 : checks.some((check) => {
7820
- var _a2, _b2;
7821
- return ((_b2 = (_a2 = check._zod) == null ? void 0 : _a2.def) == null ? void 0 : _b2.check) === "url";
7822
- })) != null ? _b : false) || format === "url";
7929
+ if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodString)) {
7930
+ const hasUrlCheck = (_b = (_a = schema._def.checks) == null ? void 0 : _a.some(
7931
+ (check) => check.kind === "url"
7932
+ )) != null ? _b : false;
7823
7933
  if (hasUrlCheck) {
7824
7934
  return [makeIdStringSchema(schema), [{ segments: [] }]];
7825
7935
  }
7826
7936
  return [schema, []];
7827
7937
  }
7828
- if (isKind(schema, "object")) {
7829
- const objectSchema = schema;
7830
- const shape = objectSchema._zod.def.shape;
7831
- if (!shape) {
7832
- return [schema, []];
7833
- }
7938
+ if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodObject)) {
7939
+ const shape = schema._def.shape();
7834
7940
  const newShape = {};
7835
7941
  const urlPaths = [];
7836
7942
  let changed = false;
@@ -7852,17 +7958,12 @@ function transformSchema(schema, currentPath) {
7852
7958
  }
7853
7959
  }
7854
7960
  if (changed) {
7855
- const newSchema = import_zod.z.object(newShape);
7856
- return [newSchema, urlPaths];
7961
+ return [import_v3.z.object(newShape), urlPaths];
7857
7962
  }
7858
7963
  return [schema, urlPaths];
7859
7964
  }
7860
- if (isKind(schema, "array")) {
7861
- const arraySchema = schema;
7862
- const itemType = arraySchema._zod.def.element;
7863
- if (!itemType) {
7864
- return [schema, []];
7865
- }
7965
+ if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodArray)) {
7966
+ const itemType = schema._def.type;
7866
7967
  const [transformedItem, childPaths] = transformSchema(itemType, [
7867
7968
  ...currentPath,
7868
7969
  "*"
@@ -7872,17 +7973,12 @@ function transformSchema(schema, currentPath) {
7872
7973
  segments: ["*", ...cp.segments]
7873
7974
  }));
7874
7975
  if (changed) {
7875
- const newSchema = import_zod.z.array(transformedItem);
7876
- return [newSchema, arrayPaths];
7976
+ return [import_v3.z.array(transformedItem), arrayPaths];
7877
7977
  }
7878
7978
  return [schema, arrayPaths];
7879
7979
  }
7880
- if (isKind(schema, "union")) {
7881
- const unionSchema = schema;
7882
- const unionOptions = unionSchema._zod.def.options;
7883
- if (!unionOptions || unionOptions.length === 0) {
7884
- return [schema, []];
7885
- }
7980
+ if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodUnion)) {
7981
+ const unionOptions = schema._def.options;
7886
7982
  const newOptions = [];
7887
7983
  let changed = false;
7888
7984
  let allPaths = [];
@@ -7899,19 +7995,15 @@ function transformSchema(schema, currentPath) {
7899
7995
  });
7900
7996
  if (changed) {
7901
7997
  return [
7902
- import_zod.z.union(newOptions),
7998
+ import_v3.z.union(newOptions),
7903
7999
  allPaths
7904
8000
  ];
7905
8001
  }
7906
8002
  return [schema, allPaths];
7907
8003
  }
7908
- if (isKind(schema, "intersection")) {
7909
- const intersectionSchema = schema;
7910
- const leftType = intersectionSchema._zod.def.left;
7911
- const rightType = intersectionSchema._zod.def.right;
7912
- if (!leftType || !rightType) {
7913
- return [schema, []];
7914
- }
8004
+ if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodIntersection)) {
8005
+ const leftType = schema._def.left;
8006
+ const rightType = schema._def.right;
7915
8007
  const [left, leftPaths] = transformSchema(leftType, [
7916
8008
  ...currentPath,
7917
8009
  "intersection_left"
@@ -7923,50 +8015,33 @@ function transformSchema(schema, currentPath) {
7923
8015
  const changed = left !== leftType || right !== rightType;
7924
8016
  const allPaths = [...leftPaths, ...rightPaths];
7925
8017
  if (changed) {
7926
- return [import_zod.z.intersection(left, right), allPaths];
8018
+ return [import_v3.z.intersection(left, right), allPaths];
7927
8019
  }
7928
8020
  return [schema, allPaths];
7929
8021
  }
7930
- if (isKind(schema, "optional")) {
7931
- const optionalSchema = schema;
7932
- const innerType = optionalSchema._zod.def.innerType;
7933
- if (!innerType) {
7934
- return [schema, []];
7935
- }
8022
+ if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodOptional)) {
8023
+ const innerType = schema._def.innerType;
7936
8024
  const [inner, innerPaths] = transformSchema(innerType, currentPath);
7937
8025
  if (inner !== innerType) {
7938
- return [import_zod.z.optional(inner), innerPaths];
8026
+ return [import_v3.z.optional(inner), innerPaths];
7939
8027
  }
7940
8028
  return [schema, innerPaths];
7941
8029
  }
7942
- if (isKind(schema, "nullable")) {
7943
- const nullableSchema = schema;
7944
- const innerType = nullableSchema._zod.def.innerType;
7945
- if (!innerType) {
7946
- return [schema, []];
7947
- }
8030
+ if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodNullable)) {
8031
+ const innerType = schema._def.innerType;
7948
8032
  const [inner, innerPaths] = transformSchema(innerType, currentPath);
7949
8033
  if (inner !== innerType) {
7950
- return [import_zod.z.nullable(inner), innerPaths];
8034
+ return [import_v3.z.nullable(inner), innerPaths];
7951
8035
  }
7952
8036
  return [schema, innerPaths];
7953
8037
  }
7954
- if (isKind(schema, "pipe")) {
7955
- const pipeSchema = schema;
7956
- const inSchema = pipeSchema._zod.def.in;
7957
- const outSchema = pipeSchema._zod.def.out;
7958
- if (!inSchema || !outSchema) {
7959
- return [schema, []];
7960
- }
7961
- const [newIn, inPaths] = transformSchema(inSchema, currentPath);
7962
- const [newOut, outPaths] = transformSchema(outSchema, currentPath);
7963
- const allPaths = [...inPaths, ...outPaths];
7964
- const changed = newIn !== inSchema || newOut !== outSchema;
7965
- if (changed) {
7966
- const result = import_zod.z.pipe(newIn, newOut);
7967
- return [result, allPaths];
8038
+ if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodEffects)) {
8039
+ const baseSchema = schema._def.schema;
8040
+ const [newBaseSchema, basePaths] = transformSchema(baseSchema, currentPath);
8041
+ if (newBaseSchema !== baseSchema) {
8042
+ return [import_v3.z.effect(newBaseSchema, schema._def.effect), basePaths];
7968
8043
  }
7969
- return [schema, allPaths];
8044
+ return [schema, basePaths];
7970
8045
  }
7971
8046
  return [schema, []];
7972
8047
  }
@@ -8012,18 +8087,17 @@ function injectUrls(obj, path6, idToUrlMapping) {
8012
8087
  }
8013
8088
  }
8014
8089
  function isKind(s, kind) {
8015
- try {
8016
- return getZodType(s) === kind;
8017
- } catch (e) {
8018
- return false;
8019
- }
8090
+ return s._def.typeName === kind;
8020
8091
  }
8021
8092
  function makeIdStringSchema(orig) {
8022
- var _a;
8023
- const userDesc = (_a = orig.description) != null ? _a : "";
8093
+ var _a, _b, _c;
8094
+ const userDesc = (
8095
+ // Zod ≥3.23 exposes .description directly; fall back to _def for older minor versions
8096
+ (_c = (_b = orig.description) != null ? _b : (_a = orig._def) == null ? void 0 : _a.description) != null ? _c : ""
8097
+ );
8024
8098
  const base = `This field must be the element-ID in the form 'frameId-backendId' (e.g. "0-432").`;
8025
8099
  const composed = userDesc.trim().length > 0 ? `${base} that follows this user-defined description: ${userDesc}` : base;
8026
- return import_zod.z.string().regex(ID_PATTERN).describe(composed);
8100
+ return import_v3.z.string().regex(ID_PATTERN).describe(composed);
8027
8101
  }
8028
8102
  var providerEnvVarMap = {
8029
8103
  openai: "OPENAI_API_KEY",
@@ -8069,7 +8143,7 @@ function jsonSchemaToZod(schema) {
8069
8143
  for (const key in schema.properties) {
8070
8144
  shape[key] = jsonSchemaToZod(schema.properties[key]);
8071
8145
  }
8072
- let zodObject = import_zod.z.object(shape);
8146
+ let zodObject = import_v3.z.object(shape);
8073
8147
  if (schema.required && Array.isArray(schema.required)) {
8074
8148
  const requiredFields = schema.required.reduce(
8075
8149
  (acc, field) => __spreadProps(__spreadValues({}, acc), { [field]: true }),
@@ -8082,30 +8156,30 @@ function jsonSchemaToZod(schema) {
8082
8156
  }
8083
8157
  return zodObject;
8084
8158
  } else {
8085
- return import_zod.z.object({});
8159
+ return import_v3.z.object({});
8086
8160
  }
8087
8161
  case "array":
8088
8162
  if (schema.items) {
8089
- let zodArray = import_zod.z.array(jsonSchemaToZod(schema.items));
8163
+ let zodArray = import_v3.z.array(jsonSchemaToZod(schema.items));
8090
8164
  if (schema.description) {
8091
8165
  zodArray = zodArray.describe(schema.description);
8092
8166
  }
8093
8167
  return zodArray;
8094
8168
  } else {
8095
- return import_zod.z.array(import_zod.z.any());
8169
+ return import_v3.z.array(import_v3.z.any());
8096
8170
  }
8097
8171
  case "string": {
8098
8172
  if (schema.enum) {
8099
- return import_zod.z.string().refine((val) => schema.enum.includes(val));
8173
+ return import_v3.z.string().refine((val) => schema.enum.includes(val));
8100
8174
  }
8101
- let zodString = import_zod.z.string();
8175
+ let zodString = import_v3.z.string();
8102
8176
  if (schema.description) {
8103
8177
  zodString = zodString.describe(schema.description);
8104
8178
  }
8105
8179
  return zodString;
8106
8180
  }
8107
8181
  case "number": {
8108
- let zodNumber = import_zod.z.number();
8182
+ let zodNumber = import_v3.z.number();
8109
8183
  if (schema.minimum !== void 0) {
8110
8184
  zodNumber = zodNumber.min(schema.minimum);
8111
8185
  }
@@ -8118,14 +8192,14 @@ function jsonSchemaToZod(schema) {
8118
8192
  return zodNumber;
8119
8193
  }
8120
8194
  case "boolean": {
8121
- let zodBoolean = import_zod.z.boolean();
8195
+ let zodBoolean = import_v3.z.boolean();
8122
8196
  if (schema.description) {
8123
8197
  zodBoolean = zodBoolean.describe(schema.description);
8124
8198
  }
8125
8199
  return zodBoolean;
8126
8200
  }
8127
8201
  default:
8128
- return import_zod.z.any();
8202
+ return import_v3.z.any();
8129
8203
  }
8130
8204
  }
8131
8205
 
@@ -8392,6 +8466,7 @@ function safeGetPageUrl(page) {
8392
8466
  }
8393
8467
 
8394
8468
  // lib/v3/cache/ActCache.ts
8469
+ init_sdkErrors();
8395
8470
  var ActCache = class {
8396
8471
  constructor({
8397
8472
  storage,
@@ -8519,7 +8594,7 @@ var ActCache = class {
8519
8594
  return __async(this, null, function* () {
8520
8595
  const handler = this.getActHandler();
8521
8596
  if (!handler) {
8522
- throw new Error("V3 not initialized. Call init() before act().");
8597
+ throw new StagehandNotInitializedError("act()");
8523
8598
  }
8524
8599
  const execute = () => __async(this, null, function* () {
8525
8600
  var _a, _b, _c;
@@ -9124,7 +9199,7 @@ var CacheStorage = class _CacheStorage {
9124
9199
  };
9125
9200
 
9126
9201
  // lib/inference.ts
9127
- var import_zod2 = require("zod");
9202
+ var import_v32 = require("zod/v3");
9128
9203
 
9129
9204
  // lib/prompt.ts
9130
9205
  function buildUserInstructionsString(userProvidedInstructions) {
@@ -9383,11 +9458,11 @@ function extract(_0) {
9383
9458
  logInferenceToFile = false
9384
9459
  }) {
9385
9460
  var _a, _b, _c, _d, _e, _f, _g, _h;
9386
- const metadataSchema = import_zod2.z.object({
9387
- progress: import_zod2.z.string().describe(
9461
+ const metadataSchema = import_v32.z.object({
9462
+ progress: import_v32.z.string().describe(
9388
9463
  "progress of what has been extracted so far, as concise as possible"
9389
9464
  ),
9390
- completed: import_zod2.z.boolean().describe(
9465
+ completed: import_v32.z.boolean().describe(
9391
9466
  "true if the goal is now accomplished. Use this conservatively, only when sure that the goal has been completed."
9392
9467
  )
9393
9468
  });
@@ -9537,20 +9612,20 @@ function observe(_0) {
9537
9612
  }) {
9538
9613
  var _a, _b, _c, _d;
9539
9614
  const isGPT5 = llmClient.modelName.includes("gpt-5");
9540
- const observeSchema = import_zod2.z.object({
9541
- elements: import_zod2.z.array(
9542
- import_zod2.z.object({
9543
- elementId: import_zod2.z.string().describe(
9615
+ const observeSchema = import_v32.z.object({
9616
+ elements: import_v32.z.array(
9617
+ import_v32.z.object({
9618
+ elementId: import_v32.z.string().describe(
9544
9619
  "the ID string associated with the element. Never include surrounding square brackets. This field must follow the format of 'number-number'."
9545
9620
  ),
9546
- description: import_zod2.z.string().describe(
9621
+ description: import_v32.z.string().describe(
9547
9622
  "a description of the accessible element and its purpose"
9548
9623
  ),
9549
- method: import_zod2.z.string().describe(
9624
+ method: import_v32.z.string().describe(
9550
9625
  "the candidate method/action to interact with the element. Select one of the available Playwright interaction methods."
9551
9626
  ),
9552
- arguments: import_zod2.z.array(
9553
- import_zod2.z.string().describe(
9627
+ arguments: import_v32.z.array(
9628
+ import_v32.z.string().describe(
9554
9629
  "the arguments to pass to the method. For example, for a click, the arguments are empty, but for a fill, the arguments are the value to fill in."
9555
9630
  )
9556
9631
  )
@@ -9644,20 +9719,20 @@ function act(_0) {
9644
9719
  }) {
9645
9720
  var _a, _b;
9646
9721
  const isGPT5 = llmClient.modelName.includes("gpt-5");
9647
- const actSchema = import_zod2.z.object({
9648
- elementId: import_zod2.z.string().describe(
9722
+ const actSchema = import_v32.z.object({
9723
+ elementId: import_v32.z.string().describe(
9649
9724
  "the ID string associated with the element. Never include surrounding square brackets. This field must follow the format of 'number-number'."
9650
9725
  ),
9651
- description: import_zod2.z.string().describe("a description of the accessible element and its purpose"),
9652
- method: import_zod2.z.string().describe(
9726
+ description: import_v32.z.string().describe("a description of the accessible element and its purpose"),
9727
+ method: import_v32.z.string().describe(
9653
9728
  "the candidate method/action to interact with the element. Select one of the available Playwright interaction methods."
9654
9729
  ),
9655
- arguments: import_zod2.z.array(
9656
- import_zod2.z.string().describe(
9730
+ arguments: import_v32.z.array(
9731
+ import_v32.z.string().describe(
9657
9732
  "the arguments to pass to the method. For example, for a click, the arguments are empty, but for a fill, the arguments are the value to fill in."
9658
9733
  )
9659
9734
  ),
9660
- twoStep: import_zod2.z.boolean()
9735
+ twoStep: import_v32.z.boolean()
9661
9736
  });
9662
9737
  const messages = [
9663
9738
  buildActSystemPrompt(userProvidedInstructions),
@@ -9738,12 +9813,12 @@ function act(_0) {
9738
9813
  init_logger();
9739
9814
 
9740
9815
  // lib/v3/types/public/methods.ts
9741
- var import_zod3 = require("zod");
9742
- var defaultExtractSchema = import_zod3.z.object({
9743
- extraction: import_zod3.z.string()
9816
+ var import_v33 = require("zod/v3");
9817
+ var defaultExtractSchema = import_v33.z.object({
9818
+ extraction: import_v33.z.string()
9744
9819
  });
9745
- var pageTextSchema = import_zod3.z.object({
9746
- pageText: import_zod3.z.string()
9820
+ var pageTextSchema = import_v33.z.object({
9821
+ pageText: import_v33.z.string()
9747
9822
  });
9748
9823
  var V3FunctionName = /* @__PURE__ */ ((V3FunctionName2) => {
9749
9824
  V3FunctionName2["ACT"] = "ACT";
@@ -9766,12 +9841,14 @@ var SupportedPlaywrightAction = /* @__PURE__ */ ((SupportedPlaywrightAction2) =>
9766
9841
  SupportedPlaywrightAction2["NEXT_CHUNK"] = "nextChunk";
9767
9842
  SupportedPlaywrightAction2["PREV_CHUNK"] = "prevChunk";
9768
9843
  SupportedPlaywrightAction2["SELECT_OPTION_FROM_DROPDOWN"] = "selectOptionFromDropdown";
9844
+ SupportedPlaywrightAction2["HOVER"] = "hover";
9769
9845
  return SupportedPlaywrightAction2;
9770
9846
  })(SupportedPlaywrightAction || {});
9771
9847
 
9772
9848
  // lib/v3/handlers/handlerUtils/actHandlerUtils.ts
9773
9849
  init_deepLocator();
9774
9850
  init_logger();
9851
+ init_sdkErrors();
9775
9852
  var UnderstudyCommandException = class extends Error {
9776
9853
  constructor(message) {
9777
9854
  super(message);
@@ -9876,7 +9953,8 @@ var METHOD_HANDLER_MAP = {
9876
9953
  nextChunk: scrollToNextChunk,
9877
9954
  prevChunk: scrollToPreviousChunk,
9878
9955
  selectOptionFromDropdown: selectOption,
9879
- selectOption
9956
+ selectOption,
9957
+ hover
9880
9958
  };
9881
9959
  function selectOption(ctx) {
9882
9960
  return __async(this, null, function* () {
@@ -10219,6 +10297,26 @@ function scrollByElementHeight(ctx, direction) {
10219
10297
  }
10220
10298
  });
10221
10299
  }
10300
+ function hover(ctx) {
10301
+ return __async(this, null, function* () {
10302
+ const { locator, xpath } = ctx;
10303
+ try {
10304
+ yield locator.hover();
10305
+ } catch (e) {
10306
+ v3Logger({
10307
+ category: "action",
10308
+ message: "error attempting to hover",
10309
+ level: 0,
10310
+ auxiliary: {
10311
+ error: { value: e.message, type: "string" },
10312
+ trace: { value: e.stack, type: "string" },
10313
+ xpath: { value: xpath, type: "string" }
10314
+ }
10315
+ });
10316
+ throw new UnderstudyCommandException(e.message);
10317
+ }
10318
+ });
10319
+ }
10222
10320
  function getFrameUrl(frame) {
10223
10321
  return __async(this, null, function* () {
10224
10322
  const url = yield frame.evaluate("location.href");
@@ -10726,7 +10824,8 @@ var ActHandler = class {
10726
10824
  // lib/v3/handlers/extractHandler.ts
10727
10825
  init_logger();
10728
10826
  init_snapshot();
10729
- var import_zod4 = require("zod");
10827
+ var import_v34 = require("zod/v3");
10828
+ init_sdkErrors();
10730
10829
  function transformUrlStringsToNumericIds(schema) {
10731
10830
  const [finalSchema, urlPaths] = transformSchema(schema, []);
10732
10831
  return [finalSchema, urlPaths];
@@ -10759,7 +10858,7 @@ var ExtractHandler = class {
10759
10858
  return pageTextSchema.parse(result);
10760
10859
  }
10761
10860
  if (!instruction && schema) {
10762
- throw new Error(
10861
+ throw new StagehandInvalidArgumentError(
10763
10862
  "extract() requires an instruction when a schema is provided."
10764
10863
  );
10765
10864
  }
@@ -10780,7 +10879,7 @@ var ExtractHandler = class {
10780
10879
  const baseSchema = schema != null ? schema : defaultExtractSchema;
10781
10880
  const isObjectSchema = !!((_c = baseSchema._def) == null ? void 0 : _c.shape);
10782
10881
  const WRAP_KEY = "value";
10783
- const objectSchema = isObjectSchema ? baseSchema : import_zod4.z.object({ [WRAP_KEY]: baseSchema });
10882
+ const objectSchema = isObjectSchema ? baseSchema : import_v34.z.object({ [WRAP_KEY]: baseSchema });
10784
10883
  const [transformedSchema, urlFieldPaths] = transformUrlStringsToNumericIds(objectSchema);
10785
10884
  const extractionResponse = yield extract({
10786
10885
  instruction,
@@ -10967,11 +11066,11 @@ var ObserveHandler = class {
10967
11066
 
10968
11067
  // lib/v3/agent/tools/v3-goto.ts
10969
11068
  var import_ai = require("ai");
10970
- var import_zod5 = require("zod");
11069
+ var import_v35 = require("zod/v3");
10971
11070
  var createGotoTool = (v3) => (0, import_ai.tool)({
10972
11071
  description: "Navigate to a specific URL",
10973
- inputSchema: import_zod5.z.object({
10974
- url: import_zod5.z.string().describe("The URL to navigate to")
11072
+ inputSchema: import_v35.z.object({
11073
+ url: import_v35.z.string().describe("The URL to navigate to")
10975
11074
  }),
10976
11075
  execute: (_0) => __async(null, [_0], function* ({ url }) {
10977
11076
  var _a;
@@ -10999,11 +11098,11 @@ var createGotoTool = (v3) => (0, import_ai.tool)({
10999
11098
 
11000
11099
  // lib/v3/agent/tools/v3-act.ts
11001
11100
  var import_ai2 = require("ai");
11002
- var import_zod6 = require("zod");
11101
+ var import_v36 = require("zod/v3");
11003
11102
  var createActTool = (v3, executionModel) => (0, import_ai2.tool)({
11004
11103
  description: "Perform an action on the page (click, type). Provide a short, specific phrase that mentions the element type.",
11005
- inputSchema: import_zod6.z.object({
11006
- action: import_zod6.z.string().describe(
11104
+ inputSchema: import_v36.z.object({
11105
+ action: import_v36.z.string().describe(
11007
11106
  'Describe what to click or type, e.g. "click the Login button" or "type "John" into the first name input"'
11008
11107
  )
11009
11108
  }),
@@ -11044,10 +11143,10 @@ var createActTool = (v3, executionModel) => (0, import_ai2.tool)({
11044
11143
 
11045
11144
  // lib/v3/agent/tools/v3-screenshot.ts
11046
11145
  var import_ai3 = require("ai");
11047
- var import_zod7 = require("zod");
11146
+ var import_v37 = require("zod/v3");
11048
11147
  var createScreenshotTool = (v3) => (0, import_ai3.tool)({
11049
11148
  description: "Takes a screenshot (PNG) of the current page. Use this to quickly verify page state.",
11050
- inputSchema: import_zod7.z.object({}),
11149
+ inputSchema: import_v37.z.object({}),
11051
11150
  execute: () => __async(null, null, function* () {
11052
11151
  v3.logger({
11053
11152
  category: "agent",
@@ -11071,11 +11170,11 @@ var createScreenshotTool = (v3) => (0, import_ai3.tool)({
11071
11170
 
11072
11171
  // lib/v3/agent/tools/v3-wait.ts
11073
11172
  var import_ai4 = require("ai");
11074
- var import_zod8 = require("zod");
11173
+ var import_v38 = require("zod/v3");
11075
11174
  var createWaitTool = (v3) => (0, import_ai4.tool)({
11076
11175
  description: "Wait for a specified time",
11077
- inputSchema: import_zod8.z.object({
11078
- timeMs: import_zod8.z.number().describe("Time in milliseconds")
11176
+ inputSchema: import_v38.z.object({
11177
+ timeMs: import_v38.z.number().describe("Time in milliseconds")
11079
11178
  }),
11080
11179
  execute: (_0) => __async(null, [_0], function* ({ timeMs }) {
11081
11180
  v3.logger({
@@ -11099,11 +11198,11 @@ var createWaitTool = (v3) => (0, import_ai4.tool)({
11099
11198
 
11100
11199
  // lib/v3/agent/tools/v3-navback.ts
11101
11200
  var import_ai5 = require("ai");
11102
- var import_zod9 = require("zod");
11201
+ var import_v39 = require("zod/v3");
11103
11202
  var createNavBackTool = (v3) => (0, import_ai5.tool)({
11104
11203
  description: "Navigate back to the previous page",
11105
- inputSchema: import_zod9.z.object({
11106
- reasoningText: import_zod9.z.string().describe("Why you're going back")
11204
+ inputSchema: import_v39.z.object({
11205
+ reasoningText: import_v39.z.string().describe("Why you're going back")
11107
11206
  }),
11108
11207
  execute: () => __async(null, null, function* () {
11109
11208
  v3.logger({
@@ -11123,12 +11222,12 @@ var createNavBackTool = (v3) => (0, import_ai5.tool)({
11123
11222
 
11124
11223
  // lib/v3/agent/tools/v3-close.ts
11125
11224
  var import_ai6 = require("ai");
11126
- var import_zod10 = require("zod");
11225
+ var import_v310 = require("zod/v3");
11127
11226
  var createCloseTool = () => (0, import_ai6.tool)({
11128
11227
  description: "Complete the task and close",
11129
- inputSchema: import_zod10.z.object({
11130
- reasoning: import_zod10.z.string().describe("Summary of what was accomplished"),
11131
- taskComplete: import_zod10.z.boolean().describe("Whether the task was completed successfully")
11228
+ inputSchema: import_v310.z.object({
11229
+ reasoning: import_v310.z.string().describe("Summary of what was accomplished"),
11230
+ taskComplete: import_v310.z.boolean().describe("Whether the task was completed successfully")
11132
11231
  }),
11133
11232
  execute: (_0) => __async(null, [_0], function* ({ reasoning, taskComplete }) {
11134
11233
  return { success: true, reasoning, taskComplete };
@@ -11137,10 +11236,10 @@ var createCloseTool = () => (0, import_ai6.tool)({
11137
11236
 
11138
11237
  // lib/v3/agent/tools/v3-ariaTree.ts
11139
11238
  var import_ai7 = require("ai");
11140
- var import_zod11 = require("zod");
11239
+ var import_v311 = require("zod/v3");
11141
11240
  var createAriaTreeTool = (v3) => (0, import_ai7.tool)({
11142
11241
  description: "gets the accessibility (ARIA) hybrid tree text for the current page. use this to understand structure and content.",
11143
- inputSchema: import_zod11.z.object({}),
11242
+ inputSchema: import_v311.z.object({}),
11144
11243
  execute: () => __async(null, null, function* () {
11145
11244
  v3.logger({
11146
11245
  category: "agent",
@@ -11168,17 +11267,17 @@ ${result.content}` }]
11168
11267
 
11169
11268
  // lib/v3/agent/tools/v3-fillform.ts
11170
11269
  var import_ai8 = require("ai");
11171
- var import_zod12 = require("zod");
11270
+ var import_v312 = require("zod/v3");
11172
11271
  var createFillFormTool = (v3, executionModel) => (0, import_ai8.tool)({
11173
11272
  description: `\u{1F4DD} FORM FILL - MULTI-FIELD INPUT TOOL
11174
11273
  For any form with 2+ inputs/textareas. Faster than individual typing.`,
11175
- inputSchema: import_zod12.z.object({
11176
- fields: import_zod12.z.array(
11177
- import_zod12.z.object({
11178
- action: import_zod12.z.string().describe(
11274
+ inputSchema: import_v312.z.object({
11275
+ fields: import_v312.z.array(
11276
+ import_v312.z.object({
11277
+ action: import_v312.z.string().describe(
11179
11278
  'Description of typing action, e.g. "type foo into the email field"'
11180
11279
  ),
11181
- value: import_zod12.z.string().describe("Text to type into the target")
11280
+ value: import_v312.z.string().describe("Text to type into the target")
11182
11281
  })
11183
11282
  ).min(1, "Provide at least one field to fill")
11184
11283
  }),
@@ -11222,12 +11321,12 @@ For any form with 2+ inputs/textareas. Faster than individual typing.`,
11222
11321
 
11223
11322
  // lib/v3/agent/tools/v3-scroll.ts
11224
11323
  var import_ai9 = require("ai");
11225
- var import_zod13 = require("zod");
11324
+ var import_v313 = require("zod/v3");
11226
11325
  var createScrollTool = (v3) => (0, import_ai9.tool)({
11227
11326
  description: "Scroll the page",
11228
- inputSchema: import_zod13.z.object({
11229
- pixels: import_zod13.z.number().describe("Number of pixels to scroll up or down"),
11230
- direction: import_zod13.z.enum(["up", "down"]).describe("Direction to scroll")
11327
+ inputSchema: import_v313.z.object({
11328
+ pixels: import_v313.z.number().describe("Number of pixels to scroll up or down"),
11329
+ direction: import_v313.z.enum(["up", "down"]).describe("Direction to scroll")
11231
11330
  }),
11232
11331
  execute: (_0) => __async(null, [_0], function* ({ pixels, direction }) {
11233
11332
  v3.logger({
@@ -11259,19 +11358,19 @@ var createScrollTool = (v3) => (0, import_ai9.tool)({
11259
11358
 
11260
11359
  // lib/v3/agent/tools/v3-extract.ts
11261
11360
  var import_ai10 = require("ai");
11262
- var import_zod14 = require("zod");
11361
+ var import_v314 = require("zod/v3");
11263
11362
  function evaluateZodSchema(schemaStr, logger) {
11264
11363
  var _a;
11265
11364
  try {
11266
11365
  const fn = new Function("z", `return ${schemaStr}`);
11267
- return fn(import_zod14.z);
11366
+ return fn(import_v314.z);
11268
11367
  } catch (e) {
11269
11368
  logger == null ? void 0 : logger({
11270
11369
  category: "agent",
11271
11370
  message: `Failed to evaluate schema: ${(_a = e == null ? void 0 : e.message) != null ? _a : String(e)}`,
11272
11371
  level: 0
11273
11372
  });
11274
- return import_zod14.z.any();
11373
+ return import_v314.z.any();
11275
11374
  }
11276
11375
  }
11277
11376
  var createExtractTool = (v3, executionModel, logger) => (0, import_ai10.tool)({
@@ -11293,9 +11392,9 @@ var createExtractTool = (v3, executionModel, logger) => (0, import_ai10.tool)({
11293
11392
  3. Extract arrays:
11294
11393
  instruction: "extract all product names and prices"
11295
11394
  schema: "z.object({ products: z.array(z.object({ name: z.string(), price: z.number() })) })"`,
11296
- inputSchema: import_zod14.z.object({
11297
- instruction: import_zod14.z.string(),
11298
- schema: import_zod14.z.string().optional().describe("Zod schema as code, e.g. z.object({ title: z.string() })")
11395
+ inputSchema: import_v314.z.object({
11396
+ instruction: import_v314.z.string(),
11397
+ schema: import_v314.z.string().optional().describe("Zod schema as code, e.g. z.object({ title: z.string() })")
11299
11398
  }),
11300
11399
  execute: (_0) => __async(null, [_0], function* ({ instruction, schema }) {
11301
11400
  var _a;
@@ -11518,6 +11617,7 @@ function createStandardAction(toolCallName, toolResult, args, reasoning) {
11518
11617
  }
11519
11618
 
11520
11619
  // lib/v3/handlers/v3AgentHandler.ts
11620
+ init_sdkErrors();
11521
11621
  var V3AgentHandler = class {
11522
11622
  constructor(v3, logger, llmClient, executionModel, systemInstructions, mcpTools) {
11523
11623
  this.v3 = v3;
@@ -11549,9 +11649,7 @@ var V3AgentHandler = class {
11549
11649
  { role: "user", content: options.instruction }
11550
11650
  ];
11551
11651
  if (!((_a = this.llmClient) == null ? void 0 : _a.getLanguageModel)) {
11552
- throw new Error(
11553
- "V3AgentHandler requires an AISDK-backed LLM client. Ensure your model is configured like 'openai/gpt-4.1-mini'."
11554
- );
11652
+ throw new MissingLLMConfigurationError();
11555
11653
  }
11556
11654
  const baseModel = this.llmClient.getLanguageModel();
11557
11655
  const wrappedModel = (0, import_ai11.wrapLanguageModel)({
@@ -11698,9 +11796,13 @@ STRATEGY:
11698
11796
  // lib/v3/handlers/v3CuaAgentHandler.ts
11699
11797
  init_snapshot();
11700
11798
 
11799
+ // lib/v3/agent/AgentProvider.ts
11800
+ init_sdkErrors();
11801
+
11701
11802
  // lib/v3/agent/AnthropicCUAClient.ts
11803
+ init_sdkErrors();
11702
11804
  var import_sdk = __toESM(require("@anthropic-ai/sdk"));
11703
- var import_zod15 = require("zod");
11805
+ var import_zod_to_json_schema = require("zod-to-json-schema");
11704
11806
 
11705
11807
  // lib/v3/agent/AgentClient.ts
11706
11808
  var AgentClient = class {
@@ -12203,7 +12305,7 @@ var AnthropicCUAClient = class extends AgentClient {
12203
12305
  };
12204
12306
  if (this.tools && Object.keys(this.tools).length > 0) {
12205
12307
  const customTools = Object.entries(this.tools).map(([name, tool12]) => {
12206
- const jsonSchema2 = import_zod15.z.toJSONSchema(tool12.inputSchema);
12308
+ const jsonSchema2 = (0, import_zod_to_json_schema.zodToJsonSchema)(tool12.inputSchema);
12207
12309
  const inputSchema = {
12208
12310
  type: "object",
12209
12311
  properties: jsonSchema2.properties || {},
@@ -12591,6 +12693,7 @@ var AnthropicCUAClient = class extends AgentClient {
12591
12693
 
12592
12694
  // lib/v3/agent/OpenAICUAClient.ts
12593
12695
  var import_openai = __toESM(require("openai"));
12696
+ init_sdkErrors();
12594
12697
  var OpenAICUAClient = class extends AgentClient {
12595
12698
  constructor(type, modelName, userProvidedInstructions, clientOptions, tools) {
12596
12699
  super(type, modelName, userProvidedInstructions);
@@ -13064,10 +13167,11 @@ var OpenAICUAClient = class extends AgentClient {
13064
13167
 
13065
13168
  // lib/v3/agent/GoogleCUAClient.ts
13066
13169
  var import_genai3 = require("@google/genai");
13170
+ init_sdkErrors();
13067
13171
 
13068
13172
  // lib/v3/agent/utils/googleCustomToolHandler.ts
13069
13173
  var import_genai2 = require("@google/genai");
13070
- var import_zod16 = require("zod");
13174
+ var import_zod_to_json_schema2 = require("zod-to-json-schema");
13071
13175
  function executeGoogleCustomTool(toolName, toolArgs, tools, functionCall, logger) {
13072
13176
  return __async(this, null, function* () {
13073
13177
  try {
@@ -13135,7 +13239,7 @@ function convertToolSetToFunctionDeclarations(tools) {
13135
13239
  }
13136
13240
  function convertToolToFunctionDeclaration(name, tool12) {
13137
13241
  try {
13138
- const jsonSchema2 = import_zod16.z.toJSONSchema(tool12.inputSchema);
13242
+ const jsonSchema2 = (0, import_zod_to_json_schema2.zodToJsonSchema)(tool12.inputSchema);
13139
13243
  const parameters = convertJsonSchemaToGoogleParameters(jsonSchema2);
13140
13244
  return {
13141
13245
  name,
@@ -13192,9 +13296,11 @@ var GoogleCUAClient = class extends AgentClient {
13192
13296
  this.environment = "ENVIRONMENT_BROWSER";
13193
13297
  this.tools = tools;
13194
13298
  this.apiKey = (clientOptions == null ? void 0 : clientOptions.apiKey) || process.env.GEMINI_API_KEY || process.env.GOOGLE_GENERATIVE_AI_API_KEY || "";
13195
- this.client = new import_genai3.GoogleGenAI({
13299
+ this.baseURL = clientOptions == null ? void 0 : clientOptions.baseURL;
13300
+ const genAIOptions = __spreadValues({
13196
13301
  apiKey: this.apiKey
13197
- });
13302
+ }, this.baseURL ? { httpOptions: { baseUrl: this.baseURL } } : {});
13303
+ this.client = new import_genai3.GoogleGenAI(genAIOptions);
13198
13304
  if ((clientOptions == null ? void 0 : clientOptions.environment) && typeof clientOptions.environment === "string") {
13199
13305
  this.environment = clientOptions.environment;
13200
13306
  }
@@ -13214,9 +13320,9 @@ var GoogleCUAClient = class extends AgentClient {
13214
13320
  }
13215
13321
  ]
13216
13322
  };
13217
- this.clientOptions = {
13323
+ this.clientOptions = __spreadValues({
13218
13324
  apiKey: this.apiKey
13219
- };
13325
+ }, this.baseURL ? { baseURL: this.baseURL } : {});
13220
13326
  if (this.tools && Object.keys(this.tools).length > 0) {
13221
13327
  this.updateGenerateContentConfig();
13222
13328
  }
@@ -13380,7 +13486,7 @@ var GoogleCUAClient = class extends AgentClient {
13380
13486
  config: this.generateContentConfig
13381
13487
  });
13382
13488
  if (!response.candidates || response.candidates.length === 0) {
13383
- throw new Error("Response has no candidates!");
13489
+ throw new LLMResponseError("agent", "Response has no candidates!");
13384
13490
  }
13385
13491
  break;
13386
13492
  } catch (error) {
@@ -14380,6 +14486,7 @@ var V3CuaAgentHandler = class {
14380
14486
 
14381
14487
  // lib/v3/launch/browserbase.ts
14382
14488
  var import_sdk2 = __toESM(require("@browserbasehq/sdk"));
14489
+ init_sdkErrors();
14383
14490
  function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14384
14491
  return __async(this, null, function* () {
14385
14492
  var _b;
@@ -14389,11 +14496,11 @@ function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14389
14496
  resumeSessionId
14390
14497
  );
14391
14498
  if (!(existing == null ? void 0 : existing.id)) {
14392
- throw new Error(`Browserbase session not found: ${resumeSessionId}`);
14499
+ throw new BrowserbaseSessionNotFoundError();
14393
14500
  }
14394
14501
  const ws = existing.connectUrl;
14395
14502
  if (!ws) {
14396
- throw new Error(
14503
+ throw new StagehandInitError(
14397
14504
  `Browserbase session resume missing connectUrl for ${resumeSessionId}`
14398
14505
  );
14399
14506
  }
@@ -14420,7 +14527,7 @@ function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14420
14527
  });
14421
14528
  const created = yield bb.sessions.create(createPayload);
14422
14529
  if (!(created == null ? void 0 : created.connectUrl) || !(created == null ? void 0 : created.id)) {
14423
- throw new Error(
14530
+ throw new StagehandInitError(
14424
14531
  "Browserbase session creation returned an unexpected shape."
14425
14532
  );
14426
14533
  }
@@ -15471,6 +15578,7 @@ var Launcher = class _Launcher {
15471
15578
  };
15472
15579
 
15473
15580
  // lib/v3/launch/local.ts
15581
+ init_sdkErrors();
15474
15582
  function launchLocalChrome(opts) {
15475
15583
  return __async(this, null, function* () {
15476
15584
  var _a, _b, _c;
@@ -15515,12 +15623,15 @@ function waitForWebSocketDebuggerUrl(port, timeoutMs) {
15515
15623
  }
15516
15624
  yield new Promise((r) => setTimeout(r, 250));
15517
15625
  }
15518
- throw new Error(
15626
+ throw new ConnectionTimeoutError(
15519
15627
  `Timed out waiting for /json/version on port ${port}${lastErrMsg ? ` (last error: ${lastErrMsg})` : ""}`
15520
15628
  );
15521
15629
  });
15522
15630
  }
15523
15631
 
15632
+ // lib/v3/llm/LLMProvider.ts
15633
+ init_sdkErrors();
15634
+
15524
15635
  // lib/v3/llm/aisdk.ts
15525
15636
  var import_ai13 = require("ai");
15526
15637
 
@@ -15792,7 +15903,8 @@ var AISdkClient = class extends LLMClient {
15792
15903
 
15793
15904
  // lib/v3/llm/AnthropicClient.ts
15794
15905
  var import_sdk3 = __toESM(require("@anthropic-ai/sdk"));
15795
- var import_zod17 = require("zod");
15906
+ var import_zod_to_json_schema3 = require("zod-to-json-schema");
15907
+ init_sdkErrors();
15796
15908
  var AnthropicClient = class extends LLMClient {
15797
15909
  constructor({
15798
15910
  modelName,
@@ -15902,7 +16014,7 @@ var AnthropicClient = class extends LLMClient {
15902
16014
  });
15903
16015
  let toolDefinition;
15904
16016
  if (options.response_model) {
15905
- const jsonSchema2 = import_zod17.z.toJSONSchema(options.response_model.schema);
16017
+ const jsonSchema2 = (0, import_zod_to_json_schema3.zodToJsonSchema)(options.response_model.schema);
15906
16018
  const { properties: schemaProperties, required: schemaRequired } = extractSchemaProperties(jsonSchema2);
15907
16019
  toolDefinition = {
15908
16020
  name: "print_extracted_data",
@@ -16034,7 +16146,8 @@ var extractSchemaProperties = (jsonSchema2) => {
16034
16146
 
16035
16147
  // lib/v3/llm/CerebrasClient.ts
16036
16148
  var import_openai2 = __toESM(require("openai"));
16037
- var import_zod18 = require("zod");
16149
+ var import_zod_to_json_schema4 = require("zod-to-json-schema");
16150
+ init_sdkErrors();
16038
16151
  var CerebrasClient = class extends LLMClient {
16039
16152
  constructor({
16040
16153
  modelName,
@@ -16096,7 +16209,7 @@ var CerebrasClient = class extends LLMClient {
16096
16209
  }
16097
16210
  }));
16098
16211
  if (options.response_model) {
16099
- const jsonSchema2 = import_zod18.z.toJSONSchema(options.response_model.schema);
16212
+ const jsonSchema2 = (0, import_zod_to_json_schema4.zodToJsonSchema)(options.response_model.schema);
16100
16213
  const schemaProperties = jsonSchema2.properties || {};
16101
16214
  const schemaRequired = jsonSchema2.required || [];
16102
16215
  const responseTool = {
@@ -16254,6 +16367,7 @@ var CerebrasClient = class extends LLMClient {
16254
16367
 
16255
16368
  // lib/v3/llm/GoogleClient.ts
16256
16369
  var import_genai4 = require("@google/genai");
16370
+ init_sdkErrors();
16257
16371
  var roleMap = {
16258
16372
  user: "user",
16259
16373
  assistant: "model",
@@ -16621,7 +16735,8 @@ ${firstPartText.text}`;
16621
16735
 
16622
16736
  // lib/v3/llm/GroqClient.ts
16623
16737
  var import_openai3 = __toESM(require("openai"));
16624
- var import_zod19 = require("zod");
16738
+ var import_zod_to_json_schema5 = require("zod-to-json-schema");
16739
+ init_sdkErrors();
16625
16740
  var GroqClient = class extends LLMClient {
16626
16741
  constructor({
16627
16742
  modelName,
@@ -16683,7 +16798,7 @@ var GroqClient = class extends LLMClient {
16683
16798
  }
16684
16799
  }));
16685
16800
  if (options.response_model) {
16686
- const jsonSchema2 = import_zod19.z.toJSONSchema(options.response_model.schema);
16801
+ const jsonSchema2 = (0, import_zod_to_json_schema5.zodToJsonSchema)(options.response_model.schema);
16687
16802
  const schemaProperties = jsonSchema2.properties || {};
16688
16803
  const schemaRequired = jsonSchema2.required || [];
16689
16804
  const responseTool = {
@@ -16841,8 +16956,9 @@ var GroqClient = class extends LLMClient {
16841
16956
 
16842
16957
  // lib/v3/llm/OpenAIClient.ts
16843
16958
  var import_openai4 = __toESM(require("openai"));
16844
- var import_zod20 = require("openai/helpers/zod");
16845
- var import_zod21 = require("zod");
16959
+ var import_zod = require("openai/helpers/zod");
16960
+ var import_zod_to_json_schema6 = __toESM(require("zod-to-json-schema"));
16961
+ init_sdkErrors();
16846
16962
  var OpenAIClient = class extends LLMClient {
16847
16963
  constructor({
16848
16964
  modelName,
@@ -16953,7 +17069,7 @@ ${JSON.stringify(
16953
17069
  if (this.modelName.startsWith("o1") || this.modelName.startsWith("o3")) {
16954
17070
  try {
16955
17071
  const parsedSchema = JSON.stringify(
16956
- import_zod21.z.toJSONSchema(options.response_model.schema)
17072
+ (0, import_zod_to_json_schema6.default)(options.response_model.schema)
16957
17073
  );
16958
17074
  options.messages.push({
16959
17075
  role: "user",
@@ -16979,7 +17095,7 @@ ${parsedSchema}
16979
17095
  throw error;
16980
17096
  }
16981
17097
  } else {
16982
- responseFormat = (0, import_zod20.zodResponseFormat)(
17098
+ responseFormat = (0, import_zod.zodResponseFormat)(
16983
17099
  options.response_model.schema,
16984
17100
  options.response_model.name
16985
17101
  );
@@ -17163,7 +17279,7 @@ ${parsedSchema}
17163
17279
  }
17164
17280
  };
17165
17281
 
17166
- // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.12_zod@4.1.12/node_modules/@ai-sdk/provider-utils/dist/index.mjs
17282
+ // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.12_zod@3.25.67/node_modules/@ai-sdk/provider-utils/dist/index.mjs
17167
17283
  var import_provider = require("@ai-sdk/provider");
17168
17284
  var import_provider2 = require("@ai-sdk/provider");
17169
17285
  var import_provider3 = require("@ai-sdk/provider");
@@ -17300,14 +17416,14 @@ var EventSourceParserStream = class extends TransformStream {
17300
17416
  }
17301
17417
  };
17302
17418
 
17303
- // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.12_zod@4.1.12/node_modules/@ai-sdk/provider-utils/dist/index.mjs
17419
+ // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.12_zod@3.25.67/node_modules/@ai-sdk/provider-utils/dist/index.mjs
17304
17420
  var import_provider9 = require("@ai-sdk/provider");
17305
17421
  var import_provider10 = require("@ai-sdk/provider");
17306
17422
  var import_provider11 = require("@ai-sdk/provider");
17307
17423
  var z42 = __toESM(require("zod/v4"), 1);
17308
- var import_v3 = require("zod/v3");
17309
- var import_v32 = require("zod/v3");
17310
- var import_v33 = require("zod/v3");
17424
+ var import_v315 = require("zod/v3");
17425
+ var import_v316 = require("zod/v3");
17426
+ var import_v317 = require("zod/v3");
17311
17427
  function combineHeaders(...headers) {
17312
17428
  return headers.reduce(
17313
17429
  (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
@@ -18124,7 +18240,7 @@ function parseArrayDef(def, refs) {
18124
18240
  const res = {
18125
18241
  type: "array"
18126
18242
  };
18127
- if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== import_v32.ZodFirstPartyTypeKind.ZodAny) {
18243
+ if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== import_v316.ZodFirstPartyTypeKind.ZodAny) {
18128
18244
  res.items = parseDef(def.type._def, __spreadProps(__spreadValues({}, refs), {
18129
18245
  currentPath: [...refs.currentPath, "items"]
18130
18246
  }));
@@ -18613,18 +18729,18 @@ function parseRecordDef(def, refs) {
18613
18729
  currentPath: [...refs.currentPath, "additionalProperties"]
18614
18730
  }))) != null ? _a : refs.allowedAdditionalProperties
18615
18731
  };
18616
- if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === import_v33.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
18732
+ if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === import_v317.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
18617
18733
  const _a2 = parseStringDef(def.keyType._def, refs), { type } = _a2, keyType = __objRest(_a2, ["type"]);
18618
18734
  return __spreadProps(__spreadValues({}, schema), {
18619
18735
  propertyNames: keyType
18620
18736
  });
18621
- } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === import_v33.ZodFirstPartyTypeKind.ZodEnum) {
18737
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === import_v317.ZodFirstPartyTypeKind.ZodEnum) {
18622
18738
  return __spreadProps(__spreadValues({}, schema), {
18623
18739
  propertyNames: {
18624
18740
  enum: def.keyType._def.values
18625
18741
  }
18626
18742
  });
18627
- } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === import_v33.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === import_v33.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
18743
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === import_v317.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === import_v317.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
18628
18744
  const _b2 = parseBrandedDef(
18629
18745
  def.keyType._def,
18630
18746
  refs
@@ -18950,73 +19066,73 @@ var parseReadonlyDef = (def, refs) => {
18950
19066
  };
18951
19067
  var selectParser = (def, typeName, refs) => {
18952
19068
  switch (typeName) {
18953
- case import_v3.ZodFirstPartyTypeKind.ZodString:
19069
+ case import_v315.ZodFirstPartyTypeKind.ZodString:
18954
19070
  return parseStringDef(def, refs);
18955
- case import_v3.ZodFirstPartyTypeKind.ZodNumber:
19071
+ case import_v315.ZodFirstPartyTypeKind.ZodNumber:
18956
19072
  return parseNumberDef(def);
18957
- case import_v3.ZodFirstPartyTypeKind.ZodObject:
19073
+ case import_v315.ZodFirstPartyTypeKind.ZodObject:
18958
19074
  return parseObjectDef(def, refs);
18959
- case import_v3.ZodFirstPartyTypeKind.ZodBigInt:
19075
+ case import_v315.ZodFirstPartyTypeKind.ZodBigInt:
18960
19076
  return parseBigintDef(def);
18961
- case import_v3.ZodFirstPartyTypeKind.ZodBoolean:
19077
+ case import_v315.ZodFirstPartyTypeKind.ZodBoolean:
18962
19078
  return parseBooleanDef();
18963
- case import_v3.ZodFirstPartyTypeKind.ZodDate:
19079
+ case import_v315.ZodFirstPartyTypeKind.ZodDate:
18964
19080
  return parseDateDef(def, refs);
18965
- case import_v3.ZodFirstPartyTypeKind.ZodUndefined:
19081
+ case import_v315.ZodFirstPartyTypeKind.ZodUndefined:
18966
19082
  return parseUndefinedDef();
18967
- case import_v3.ZodFirstPartyTypeKind.ZodNull:
19083
+ case import_v315.ZodFirstPartyTypeKind.ZodNull:
18968
19084
  return parseNullDef();
18969
- case import_v3.ZodFirstPartyTypeKind.ZodArray:
19085
+ case import_v315.ZodFirstPartyTypeKind.ZodArray:
18970
19086
  return parseArrayDef(def, refs);
18971
- case import_v3.ZodFirstPartyTypeKind.ZodUnion:
18972
- case import_v3.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
19087
+ case import_v315.ZodFirstPartyTypeKind.ZodUnion:
19088
+ case import_v315.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
18973
19089
  return parseUnionDef(def, refs);
18974
- case import_v3.ZodFirstPartyTypeKind.ZodIntersection:
19090
+ case import_v315.ZodFirstPartyTypeKind.ZodIntersection:
18975
19091
  return parseIntersectionDef(def, refs);
18976
- case import_v3.ZodFirstPartyTypeKind.ZodTuple:
19092
+ case import_v315.ZodFirstPartyTypeKind.ZodTuple:
18977
19093
  return parseTupleDef(def, refs);
18978
- case import_v3.ZodFirstPartyTypeKind.ZodRecord:
19094
+ case import_v315.ZodFirstPartyTypeKind.ZodRecord:
18979
19095
  return parseRecordDef(def, refs);
18980
- case import_v3.ZodFirstPartyTypeKind.ZodLiteral:
19096
+ case import_v315.ZodFirstPartyTypeKind.ZodLiteral:
18981
19097
  return parseLiteralDef(def);
18982
- case import_v3.ZodFirstPartyTypeKind.ZodEnum:
19098
+ case import_v315.ZodFirstPartyTypeKind.ZodEnum:
18983
19099
  return parseEnumDef(def);
18984
- case import_v3.ZodFirstPartyTypeKind.ZodNativeEnum:
19100
+ case import_v315.ZodFirstPartyTypeKind.ZodNativeEnum:
18985
19101
  return parseNativeEnumDef(def);
18986
- case import_v3.ZodFirstPartyTypeKind.ZodNullable:
19102
+ case import_v315.ZodFirstPartyTypeKind.ZodNullable:
18987
19103
  return parseNullableDef(def, refs);
18988
- case import_v3.ZodFirstPartyTypeKind.ZodOptional:
19104
+ case import_v315.ZodFirstPartyTypeKind.ZodOptional:
18989
19105
  return parseOptionalDef(def, refs);
18990
- case import_v3.ZodFirstPartyTypeKind.ZodMap:
19106
+ case import_v315.ZodFirstPartyTypeKind.ZodMap:
18991
19107
  return parseMapDef(def, refs);
18992
- case import_v3.ZodFirstPartyTypeKind.ZodSet:
19108
+ case import_v315.ZodFirstPartyTypeKind.ZodSet:
18993
19109
  return parseSetDef(def, refs);
18994
- case import_v3.ZodFirstPartyTypeKind.ZodLazy:
19110
+ case import_v315.ZodFirstPartyTypeKind.ZodLazy:
18995
19111
  return () => def.getter()._def;
18996
- case import_v3.ZodFirstPartyTypeKind.ZodPromise:
19112
+ case import_v315.ZodFirstPartyTypeKind.ZodPromise:
18997
19113
  return parsePromiseDef(def, refs);
18998
- case import_v3.ZodFirstPartyTypeKind.ZodNaN:
18999
- case import_v3.ZodFirstPartyTypeKind.ZodNever:
19114
+ case import_v315.ZodFirstPartyTypeKind.ZodNaN:
19115
+ case import_v315.ZodFirstPartyTypeKind.ZodNever:
19000
19116
  return parseNeverDef();
19001
- case import_v3.ZodFirstPartyTypeKind.ZodEffects:
19117
+ case import_v315.ZodFirstPartyTypeKind.ZodEffects:
19002
19118
  return parseEffectsDef(def, refs);
19003
- case import_v3.ZodFirstPartyTypeKind.ZodAny:
19119
+ case import_v315.ZodFirstPartyTypeKind.ZodAny:
19004
19120
  return parseAnyDef();
19005
- case import_v3.ZodFirstPartyTypeKind.ZodUnknown:
19121
+ case import_v315.ZodFirstPartyTypeKind.ZodUnknown:
19006
19122
  return parseUnknownDef();
19007
- case import_v3.ZodFirstPartyTypeKind.ZodDefault:
19123
+ case import_v315.ZodFirstPartyTypeKind.ZodDefault:
19008
19124
  return parseDefaultDef(def, refs);
19009
- case import_v3.ZodFirstPartyTypeKind.ZodBranded:
19125
+ case import_v315.ZodFirstPartyTypeKind.ZodBranded:
19010
19126
  return parseBrandedDef(def, refs);
19011
- case import_v3.ZodFirstPartyTypeKind.ZodReadonly:
19127
+ case import_v315.ZodFirstPartyTypeKind.ZodReadonly:
19012
19128
  return parseReadonlyDef(def, refs);
19013
- case import_v3.ZodFirstPartyTypeKind.ZodCatch:
19129
+ case import_v315.ZodFirstPartyTypeKind.ZodCatch:
19014
19130
  return parseCatchDef(def, refs);
19015
- case import_v3.ZodFirstPartyTypeKind.ZodPipeline:
19131
+ case import_v315.ZodFirstPartyTypeKind.ZodPipeline:
19016
19132
  return parsePipelineDef(def, refs);
19017
- case import_v3.ZodFirstPartyTypeKind.ZodFunction:
19018
- case import_v3.ZodFirstPartyTypeKind.ZodVoid:
19019
- case import_v3.ZodFirstPartyTypeKind.ZodSymbol:
19133
+ case import_v315.ZodFirstPartyTypeKind.ZodFunction:
19134
+ case import_v315.ZodFirstPartyTypeKind.ZodVoid:
19135
+ case import_v315.ZodFirstPartyTypeKind.ZodSymbol:
19020
19136
  return void 0;
19021
19137
  default:
19022
19138
  return /* @__PURE__ */ ((_) => void 0)(typeName);
@@ -19103,7 +19219,7 @@ var getRefs = (options) => {
19103
19219
  )
19104
19220
  });
19105
19221
  };
19106
- var zodToJsonSchema = (schema, options) => {
19222
+ var zodToJsonSchema7 = (schema, options) => {
19107
19223
  var _a;
19108
19224
  const refs = getRefs(options);
19109
19225
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
@@ -19148,7 +19264,7 @@ var zodToJsonSchema = (schema, options) => {
19148
19264
  combined.$schema = "http://json-schema.org/draft-07/schema#";
19149
19265
  return combined;
19150
19266
  };
19151
- var zod_to_json_schema_default = zodToJsonSchema;
19267
+ var zod_to_json_schema_default = zodToJsonSchema7;
19152
19268
  function zod3Schema(zodSchema2, options) {
19153
19269
  var _a;
19154
19270
  const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
@@ -19240,7 +19356,7 @@ function withoutTrailingSlash(url) {
19240
19356
  return url == null ? void 0 : url.replace(/\/$/, "");
19241
19357
  }
19242
19358
 
19243
- // ../../node_modules/.pnpm/@ai-sdk+openai@2.0.53_zod@4.1.12/node_modules/@ai-sdk/openai/dist/index.mjs
19359
+ // ../../node_modules/.pnpm/@ai-sdk+openai@2.0.53_zod@3.25.67/node_modules/@ai-sdk/openai/dist/index.mjs
19244
19360
  var import_provider12 = require("@ai-sdk/provider");
19245
19361
  var import_v4 = require("zod/v4");
19246
19362
  var import_provider13 = require("@ai-sdk/provider");
@@ -23630,7 +23746,7 @@ function createOpenAI(options = {}) {
23630
23746
  }
23631
23747
  var openai = createOpenAI();
23632
23748
 
23633
- // ../../node_modules/.pnpm/@ai-sdk+anthropic@2.0.34_zod@4.1.12/node_modules/@ai-sdk/anthropic/dist/index.mjs
23749
+ // ../../node_modules/.pnpm/@ai-sdk+anthropic@2.0.34_zod@3.25.67/node_modules/@ai-sdk/anthropic/dist/index.mjs
23634
23750
  var import_provider20 = require("@ai-sdk/provider");
23635
23751
  var import_provider21 = require("@ai-sdk/provider");
23636
23752
  var import_v421 = require("zod/v4");
@@ -26669,7 +26785,7 @@ function createAnthropic(options = {}) {
26669
26785
  }
26670
26786
  var anthropic = createAnthropic();
26671
26787
 
26672
- // ../../node_modules/.pnpm/@ai-sdk+google@2.0.23_zod@4.1.12/node_modules/@ai-sdk/google/dist/index.mjs
26788
+ // ../../node_modules/.pnpm/@ai-sdk+google@2.0.23_zod@3.25.67/node_modules/@ai-sdk/google/dist/index.mjs
26673
26789
  var import_provider24 = require("@ai-sdk/provider");
26674
26790
  var import_v437 = require("zod/v4");
26675
26791
  var import_v438 = require("zod/v4");
@@ -28221,7 +28337,7 @@ function createGoogleGenerativeAI(options = {}) {
28221
28337
  }
28222
28338
  var google = createGoogleGenerativeAI();
28223
28339
 
28224
- // ../../node_modules/.pnpm/@ai-sdk+openai-compatible@1.0.22_zod@4.1.12/node_modules/@ai-sdk/openai-compatible/dist/index.mjs
28340
+ // ../../node_modules/.pnpm/@ai-sdk+openai-compatible@1.0.22_zod@3.25.67/node_modules/@ai-sdk/openai-compatible/dist/index.mjs
28225
28341
  var import_provider27 = require("@ai-sdk/provider");
28226
28342
  var import_v446 = require("zod/v4");
28227
28343
  var import_provider28 = require("@ai-sdk/provider");
@@ -29541,7 +29657,7 @@ var openaiCompatibleImageResponseSchema = import_v453.z.object({
29541
29657
  data: import_v453.z.array(import_v453.z.object({ b64_json: import_v453.z.string() }))
29542
29658
  });
29543
29659
 
29544
- // ../../node_modules/.pnpm/@ai-sdk+xai@2.0.26_zod@4.1.12/node_modules/@ai-sdk/xai/dist/index.mjs
29660
+ // ../../node_modules/.pnpm/@ai-sdk+xai@2.0.26_zod@3.25.67/node_modules/@ai-sdk/xai/dist/index.mjs
29545
29661
  var import_provider32 = require("@ai-sdk/provider");
29546
29662
  var import_v454 = require("zod/v4");
29547
29663
  var import_provider33 = require("@ai-sdk/provider");
@@ -30293,7 +30409,7 @@ function createXai(options = {}) {
30293
30409
  }
30294
30410
  var xai = createXai();
30295
30411
 
30296
- // ../../node_modules/.pnpm/@ai-sdk+openai@2.0.53_zod@4.1.12/node_modules/@ai-sdk/openai/dist/internal/index.mjs
30412
+ // ../../node_modules/.pnpm/@ai-sdk+openai@2.0.53_zod@3.25.67/node_modules/@ai-sdk/openai/dist/internal/index.mjs
30297
30413
  var import_provider35 = require("@ai-sdk/provider");
30298
30414
  var import_v457 = require("zod/v4");
30299
30415
  var import_provider36 = require("@ai-sdk/provider");
@@ -34516,7 +34632,7 @@ function mapWebSearchOutput2(action) {
34516
34632
  }
34517
34633
  }
34518
34634
 
34519
- // ../../node_modules/.pnpm/@ai-sdk+azure@2.0.54_zod@4.1.12/node_modules/@ai-sdk/azure/dist/index.mjs
34635
+ // ../../node_modules/.pnpm/@ai-sdk+azure@2.0.54_zod@3.25.67/node_modules/@ai-sdk/azure/dist/index.mjs
34520
34636
  var azureOpenaiTools = {
34521
34637
  codeInterpreter: codeInterpreter2,
34522
34638
  fileSearch: fileSearch2,
@@ -34621,7 +34737,7 @@ function createAzure(options = {}) {
34621
34737
  }
34622
34738
  var azure = createAzure();
34623
34739
 
34624
- // ../../node_modules/.pnpm/@ai-sdk+groq@2.0.24_zod@4.1.12/node_modules/@ai-sdk/groq/dist/index.mjs
34740
+ // ../../node_modules/.pnpm/@ai-sdk+groq@2.0.24_zod@3.25.67/node_modules/@ai-sdk/groq/dist/index.mjs
34625
34741
  var import_provider43 = require("@ai-sdk/provider");
34626
34742
  var import_provider44 = require("@ai-sdk/provider");
34627
34743
  var import_v477 = require("zod/v4");
@@ -35503,7 +35619,7 @@ function createGroq(options = {}) {
35503
35619
  }
35504
35620
  var groq = createGroq();
35505
35621
 
35506
- // ../../node_modules/.pnpm/@ai-sdk+cerebras@1.0.25_zod@4.1.12/node_modules/@ai-sdk/cerebras/dist/index.mjs
35622
+ // ../../node_modules/.pnpm/@ai-sdk+cerebras@1.0.25_zod@3.25.67/node_modules/@ai-sdk/cerebras/dist/index.mjs
35507
35623
  var import_provider47 = require("@ai-sdk/provider");
35508
35624
  var import_v482 = require("zod/v4");
35509
35625
  var VERSION8 = true ? "1.0.25" : "0.0.0-test";
@@ -35555,7 +35671,7 @@ function createCerebras(options = {}) {
35555
35671
  }
35556
35672
  var cerebras = createCerebras();
35557
35673
 
35558
- // ../../node_modules/.pnpm/@ai-sdk+togetherai@1.0.23_zod@4.1.12/node_modules/@ai-sdk/togetherai/dist/index.mjs
35674
+ // ../../node_modules/.pnpm/@ai-sdk+togetherai@1.0.23_zod@3.25.67/node_modules/@ai-sdk/togetherai/dist/index.mjs
35559
35675
  var import_v483 = require("zod/v4");
35560
35676
  var TogetherAIImageModel = class {
35561
35677
  constructor(modelId, config) {
@@ -35686,7 +35802,7 @@ function createTogetherAI(options = {}) {
35686
35802
  }
35687
35803
  var togetherai = createTogetherAI();
35688
35804
 
35689
- // ../../node_modules/.pnpm/@ai-sdk+mistral@2.0.19_zod@4.1.12/node_modules/@ai-sdk/mistral/dist/index.mjs
35805
+ // ../../node_modules/.pnpm/@ai-sdk+mistral@2.0.19_zod@3.25.67/node_modules/@ai-sdk/mistral/dist/index.mjs
35690
35806
  var import_provider48 = require("@ai-sdk/provider");
35691
35807
  var import_v484 = require("zod/v4");
35692
35808
  var import_provider49 = require("@ai-sdk/provider");
@@ -36469,7 +36585,7 @@ function createMistral(options = {}) {
36469
36585
  }
36470
36586
  var mistral = createMistral();
36471
36587
 
36472
- // ../../node_modules/.pnpm/@ai-sdk+deepseek@1.0.23_zod@4.1.12/node_modules/@ai-sdk/deepseek/dist/index.mjs
36588
+ // ../../node_modules/.pnpm/@ai-sdk+deepseek@1.0.23_zod@3.25.67/node_modules/@ai-sdk/deepseek/dist/index.mjs
36473
36589
  var import_provider52 = require("@ai-sdk/provider");
36474
36590
  var import_v488 = require("zod/v4");
36475
36591
  var buildDeepseekMetadata = (usage) => {
@@ -36559,7 +36675,7 @@ function createDeepSeek(options = {}) {
36559
36675
  }
36560
36676
  var deepseek = createDeepSeek();
36561
36677
 
36562
- // ../../node_modules/.pnpm/@ai-sdk+perplexity@2.0.13_zod@4.1.12/node_modules/@ai-sdk/perplexity/dist/index.mjs
36678
+ // ../../node_modules/.pnpm/@ai-sdk+perplexity@2.0.13_zod@3.25.67/node_modules/@ai-sdk/perplexity/dist/index.mjs
36563
36679
  var import_provider53 = require("@ai-sdk/provider");
36564
36680
  var import_v489 = require("zod/v4");
36565
36681
  var import_provider54 = require("@ai-sdk/provider");
@@ -36989,7 +37105,7 @@ function createPerplexity(options = {}) {
36989
37105
  }
36990
37106
  var perplexity = createPerplexity();
36991
37107
 
36992
- // ../../node_modules/.pnpm/ollama-ai-provider-v2@1.5.0_zod@4.1.12/node_modules/ollama-ai-provider-v2/dist/index.mjs
37108
+ // ../../node_modules/.pnpm/ollama-ai-provider-v2@1.5.0_zod@3.25.67/node_modules/ollama-ai-provider-v2/dist/index.mjs
36993
37109
  var import_provider55 = require("@ai-sdk/provider");
36994
37110
  var import_v490 = require("zod/v4");
36995
37111
  var import_v491 = require("zod/v4");
@@ -38466,6 +38582,7 @@ init_logger();
38466
38582
  var import_client = require("@modelcontextprotocol/sdk/client/index.js");
38467
38583
  var import_streamableHttp = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
38468
38584
  var import_stdio = require("@modelcontextprotocol/sdk/client/stdio.js");
38585
+ init_sdkErrors();
38469
38586
  var connectToMCPServer = (serverConfig) => __async(null, null, function* () {
38470
38587
  try {
38471
38588
  let transport;
@@ -38591,6 +38708,9 @@ var LOG_LEVEL_NAMES = {
38591
38708
  init_consoleMessage();
38592
38709
  init_response();
38593
38710
 
38711
+ // lib/v3/types/public/index.ts
38712
+ init_sdkErrors();
38713
+
38594
38714
  // examples/external_clients/aisdk.ts
38595
38715
  var import_ai14 = require("ai");
38596
38716
  var AISdkClient2 = class extends LLMClient {
@@ -38958,6 +39078,7 @@ function installV3PiercerIntoSession(session) {
38958
39078
 
38959
39079
  // lib/v3/understudy/context.ts
38960
39080
  init_executionContextRegistry();
39081
+ init_sdkErrors();
38961
39082
  function isTopLevelPage(info) {
38962
39083
  const ti = info;
38963
39084
  return info.type === "page" && ti.subtype !== "iframe";
@@ -38993,7 +39114,6 @@ var V3Context = class _V3Context {
38993
39114
  return __async(this, null, function* () {
38994
39115
  var _a, _b, _c;
38995
39116
  const conn = yield CdpConnection.connect(wsUrl);
38996
- yield conn.enableAutoAttach();
38997
39117
  const ctx = new _V3Context(
38998
39118
  conn,
38999
39119
  (_a = opts == null ? void 0 : opts.env) != null ? _a : "LOCAL",
@@ -39021,11 +39141,41 @@ var V3Context = class _V3Context {
39021
39141
  }
39022
39142
  yield new Promise((r) => setTimeout(r, 25));
39023
39143
  }
39024
- throw new Error(
39025
- `waitForFirstTopLevelPage timed out after ${timeoutMs}ms (no top-level Page)`
39144
+ throw new TimeoutError(
39145
+ "waitForFirstTopLevelPage (no top-level Page)",
39146
+ timeoutMs
39026
39147
  );
39027
39148
  });
39028
39149
  }
39150
+ waitForInitialTopLevelTargets(targetIds, timeoutMs = 3e3) {
39151
+ return __async(this, null, function* () {
39152
+ if (!targetIds.length) return;
39153
+ const pending = new Set(targetIds);
39154
+ const deadline = Date.now() + timeoutMs;
39155
+ while (pending.size && Date.now() < deadline) {
39156
+ for (const tid of Array.from(pending)) {
39157
+ if (this.pagesByTarget.has(tid)) {
39158
+ pending.delete(tid);
39159
+ }
39160
+ }
39161
+ if (!pending.size) return;
39162
+ yield new Promise((r) => setTimeout(r, 25));
39163
+ }
39164
+ if (pending.size) {
39165
+ v3Logger({
39166
+ category: "ctx",
39167
+ message: "Timed out waiting for existing top-level targets to attach",
39168
+ level: 2,
39169
+ auxiliary: {
39170
+ remainingTargets: {
39171
+ value: JSON.stringify(Array.from(pending)),
39172
+ type: "object"
39173
+ }
39174
+ }
39175
+ });
39176
+ }
39177
+ });
39178
+ }
39029
39179
  ensurePiercer(session) {
39030
39180
  return __async(this, null, function* () {
39031
39181
  const key = this.sessionKey(session);
@@ -39115,8 +39265,7 @@ var V3Context = class _V3Context {
39115
39265
  getFullFrameTreeByMainFrameId(rootMainFrameId) {
39116
39266
  return __async(this, null, function* () {
39117
39267
  const owner = this.resolvePageByMainFrameId(rootMainFrameId);
39118
- if (!owner)
39119
- throw new Error(`No Page found for mainFrameId=${rootMainFrameId}`);
39268
+ if (!owner) throw new PageNotFoundError(`mainFrameId=${rootMainFrameId}`);
39120
39269
  return owner.asProtocolFrameTree(rootMainFrameId);
39121
39270
  });
39122
39271
  }
@@ -39139,7 +39288,7 @@ var V3Context = class _V3Context {
39139
39288
  if (page) return page;
39140
39289
  yield new Promise((r) => setTimeout(r, 25));
39141
39290
  }
39142
- throw new Error(`newPage timeout: target not attached (${targetId})`);
39291
+ throw new TimeoutError(`newPage: target not attached (${targetId})`, 5e3);
39143
39292
  });
39144
39293
  }
39145
39294
  /**
@@ -39207,6 +39356,7 @@ var V3Context = class _V3Context {
39207
39356
  }
39208
39357
  })
39209
39358
  );
39359
+ yield this.conn.enableAutoAttach();
39210
39360
  const targets = yield this.conn.getTargets();
39211
39361
  for (const t of targets) {
39212
39362
  try {
@@ -39214,6 +39364,8 @@ var V3Context = class _V3Context {
39214
39364
  } catch (e) {
39215
39365
  }
39216
39366
  }
39367
+ const topLevelTargetIds = targets.filter((t) => isTopLevelPage(t)).map((t) => t.targetId);
39368
+ yield this.waitForInitialTopLevelTargets(topLevelTargetIds);
39217
39369
  });
39218
39370
  }
39219
39371
  /**
@@ -39499,7 +39651,7 @@ var V3Context = class _V3Context {
39499
39651
  yield new Promise((r) => setTimeout(r, 25));
39500
39652
  }
39501
39653
  if (immediate) return immediate;
39502
- throw new Error("awaitActivePage: no page available");
39654
+ throw new PageNotFoundError("awaitActivePage: no page available");
39503
39655
  });
39504
39656
  }
39505
39657
  };
@@ -39529,7 +39681,8 @@ function resolveModel(model) {
39529
39681
 
39530
39682
  // lib/v3/api.ts
39531
39683
  var import_fetch_cookie = __toESM(require("fetch-cookie"));
39532
- var import_zod22 = require("zod");
39684
+ var import_zod_to_json_schema7 = __toESM(require("zod-to-json-schema"));
39685
+ init_version();
39533
39686
  var StagehandAPIClient = class {
39534
39687
  constructor({ apiKey, projectId, logger }) {
39535
39688
  this.apiKey = apiKey;
@@ -39623,7 +39776,7 @@ var StagehandAPIClient = class {
39623
39776
  options,
39624
39777
  frameId
39625
39778
  }) {
39626
- const jsonSchema2 = zodSchema2 ? import_zod22.z.toJSONSchema(zodSchema2) : void 0;
39779
+ const jsonSchema2 = zodSchema2 ? (0, import_zod_to_json_schema7.default)(zodSchema2) : void 0;
39627
39780
  const args = {
39628
39781
  schema: jsonSchema2,
39629
39782
  instruction,
@@ -39674,9 +39827,7 @@ var StagehandAPIClient = class {
39674
39827
  agentExecute(agentConfig, executeOptions, frameId) {
39675
39828
  return __async(this, null, function* () {
39676
39829
  if (agentConfig.integrations && agentConfig.integrations.length > 0) {
39677
- throw new StagehandAPIError(
39678
- "MCP integrations are not supported in API mode. Set experimental: true to use MCP integrations."
39679
- );
39830
+ throw new ExperimentalNotConfiguredError("MCP integrations");
39680
39831
  }
39681
39832
  if (typeof executeOptions === "object") {
39682
39833
  if (executeOptions.page) {
@@ -39905,7 +40056,7 @@ function resolveModelConfiguration(model) {
39905
40056
  if (model && typeof model === "object") {
39906
40057
  const _a = model, { modelName } = _a, clientOptions = __objRest(_a, ["modelName"]);
39907
40058
  if (!modelName) {
39908
- throw new Error(
40059
+ throw new StagehandInvalidArgumentError(
39909
40060
  "model.modelName is required when providing client options."
39910
40061
  );
39911
40062
  }
@@ -40405,8 +40556,9 @@ var _V3 = class _V3 {
40405
40556
  if (this.opts.env === "BROWSERBASE") {
40406
40557
  const { apiKey, projectId } = this.requireBrowserbaseCreds();
40407
40558
  if (!apiKey || !projectId) {
40408
- throw new Error(
40409
- "BROWSERBASE credentials missing. Provide in your v3 constructor, or set BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID in your .env"
40559
+ throw new MissingEnvironmentVariableError(
40560
+ "BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID",
40561
+ "Browserbase environment"
40410
40562
  );
40411
40563
  }
40412
40564
  this.logger({
@@ -40485,7 +40637,7 @@ var _V3 = class _V3 {
40485
40637
  return;
40486
40638
  }
40487
40639
  const neverEnv = this.opts.env;
40488
- throw new Error(`Unsupported env: ${neverEnv}`);
40640
+ throw new StagehandInitError(`Unsupported env: ${neverEnv}`);
40489
40641
  }));
40490
40642
  } catch (error) {
40491
40643
  if (this.externalLogger) {
@@ -40534,8 +40686,7 @@ var _V3 = class _V3 {
40534
40686
  act(input, options) {
40535
40687
  return __async(this, null, function* () {
40536
40688
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40537
- if (!this.actHandler)
40538
- throw new Error("V3 not initialized. Call init() before act().");
40689
+ if (!this.actHandler) throw new StagehandNotInitializedError("act()");
40539
40690
  let actResult;
40540
40691
  if (isObserveResult(input)) {
40541
40692
  const v3Page = yield this.resolvePage(options == null ? void 0 : options.page);
@@ -40566,7 +40717,7 @@ var _V3 = class _V3 {
40566
40717
  return actResult;
40567
40718
  }
40568
40719
  if (typeof input !== "string" || !input.trim()) {
40569
- throw new Error(
40720
+ throw new StagehandInvalidArgumentError(
40570
40721
  "act(): instruction string is required unless passing an Action"
40571
40722
  );
40572
40723
  }
@@ -40633,7 +40784,7 @@ var _V3 = class _V3 {
40633
40784
  return __async(this, null, function* () {
40634
40785
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40635
40786
  if (!this.extractHandler) {
40636
- throw new Error("V3 not initialized. Call init() before extract().");
40787
+ throw new StagehandNotInitializedError("extract()");
40637
40788
  }
40638
40789
  let instruction;
40639
40790
  let schema;
@@ -40651,7 +40802,9 @@ var _V3 = class _V3 {
40651
40802
  options = a || void 0;
40652
40803
  }
40653
40804
  if (!instruction && schema) {
40654
- throw new Error("extract(): schema provided without instruction");
40805
+ throw new StagehandInvalidArgumentError(
40806
+ "extract(): schema provided without instruction"
40807
+ );
40655
40808
  }
40656
40809
  const effectiveSchema = instruction && !schema ? defaultExtractSchema : schema;
40657
40810
  const page = yield this.resolvePage(options == null ? void 0 : options.page);
@@ -40683,7 +40836,7 @@ var _V3 = class _V3 {
40683
40836
  return __async(this, null, function* () {
40684
40837
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40685
40838
  if (!this.observeHandler) {
40686
- throw new Error("V3 not initialized. Call init() before observe().");
40839
+ throw new StagehandNotInitializedError("observe()");
40687
40840
  }
40688
40841
  let instruction;
40689
40842
  let options;
@@ -40727,7 +40880,7 @@ var _V3 = class _V3 {
40727
40880
  /** Return the browser-level CDP WebSocket endpoint. */
40728
40881
  connectURL() {
40729
40882
  if (this.state.kind === "UNINITIALIZED") {
40730
- throw new Error("V3 not initialized. Call await v3.init() first.");
40883
+ throw new StagehandNotInitializedError("connectURL()");
40731
40884
  }
40732
40885
  return this.state.ws;
40733
40886
  }
@@ -40792,10 +40945,9 @@ var _V3 = class _V3 {
40792
40945
  const missing = [];
40793
40946
  if (!apiKey) missing.push("BROWSERBASE_API_KEY");
40794
40947
  if (!projectId) missing.push("BROWSERBASE_PROJECT_ID");
40795
- throw new Error(
40796
- `BROWSERBASE credentials missing. Provide in your v3 constructor, or set ${missing.join(
40797
- ", "
40798
- )} in your .env`
40948
+ throw new MissingEnvironmentVariableError(
40949
+ missing.join(", "),
40950
+ "Browserbase"
40799
40951
  );
40800
40952
  }
40801
40953
  this.opts.apiKey = apiKey;
@@ -40841,7 +40993,9 @@ var _V3 = class _V3 {
40841
40993
  });
40842
40994
  return frameTree.frame.id;
40843
40995
  }
40844
- throw new Error("Unsupported page object passed to V3.act()");
40996
+ throw new StagehandInvalidArgumentError(
40997
+ "Unsupported page object passed to V3.act()"
40998
+ );
40845
40999
  });
40846
41000
  }
40847
41001
  isPlaywrightPage(p) {
@@ -40861,9 +41015,7 @@ var _V3 = class _V3 {
40861
41015
  }
40862
41016
  const ctx = this.ctx;
40863
41017
  if (!ctx) {
40864
- throw new Error(
40865
- "V3 context not initialized. Call init() before resolving pages."
40866
- );
41018
+ throw new StagehandNotInitializedError("resolvePage()");
40867
41019
  }
40868
41020
  return yield ctx.awaitActivePage();
40869
41021
  });
@@ -40877,24 +41029,30 @@ var _V3 = class _V3 {
40877
41029
  const frameId = yield this.resolveTopFrameId(input);
40878
41030
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40879
41031
  if (!page)
40880
- throw new Error("Failed to resolve V3 Page from Playwright page.");
41032
+ throw new StagehandInitError(
41033
+ "Failed to resolve V3 Page from Playwright page."
41034
+ );
40881
41035
  return page;
40882
41036
  }
40883
41037
  if (this.isPatchrightPage(input)) {
40884
41038
  const frameId = yield this.resolveTopFrameId(input);
40885
41039
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40886
41040
  if (!page)
40887
- throw new Error("Failed to resolve V3 Page from Playwright page.");
41041
+ throw new StagehandInitError(
41042
+ "Failed to resolve V3 Page from Patchright page."
41043
+ );
40888
41044
  return page;
40889
41045
  }
40890
41046
  if (this.isPuppeteerPage(input)) {
40891
41047
  const frameId = yield this.resolveTopFrameId(input);
40892
41048
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40893
41049
  if (!page)
40894
- throw new Error("Failed to resolve V3 Page from Puppeteer page.");
41050
+ throw new StagehandInitError(
41051
+ "Failed to resolve V3 Page from Puppeteer page."
41052
+ );
40895
41053
  return page;
40896
41054
  }
40897
- throw new Error("Unsupported page object.");
41055
+ throw new StagehandInvalidArgumentError("Unsupported page object.");
40898
41056
  });
40899
41057
  }
40900
41058
  /**
@@ -40921,8 +41079,8 @@ var _V3 = class _V3 {
40921
41079
  });
40922
41080
  if (options == null ? void 0 : options.cua) {
40923
41081
  if (((options == null ? void 0 : options.integrations) || (options == null ? void 0 : options.tools)) && !this.experimental) {
40924
- throw new Error(
40925
- "MCP integrations and custom tools are experimental. Enable experimental: true in V3 options."
41082
+ throw new ExperimentalNotConfiguredError(
41083
+ "MCP integrations and custom tools"
40926
41084
  );
40927
41085
  }
40928
41086
  const modelToUse = (options == null ? void 0 : options.model) || __spreadValues({
@@ -40930,9 +41088,7 @@ var _V3 = class _V3 {
40930
41088
  }, this.modelClientOptions);
40931
41089
  const { modelName, isCua, clientOptions } = resolveModel(modelToUse);
40932
41090
  if (!isCua) {
40933
- throw new Error(
40934
- "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(", ")
40935
- );
41091
+ throw new CuaModelRequiredError(AVAILABLE_CUA_MODELS);
40936
41092
  }
40937
41093
  const agentConfigSignature2 = this.agentCache.buildConfigSignature(options);
40938
41094
  return {
@@ -40940,9 +41096,7 @@ var _V3 = class _V3 {
40940
41096
  return withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40941
41097
  var _a2, _b2;
40942
41098
  if ((options == null ? void 0 : options.integrations) && !this.experimental) {
40943
- throw new Error(
40944
- "MCP integrations are experimental. Enable experimental: true in V3 options."
40945
- );
41099
+ throw new ExperimentalNotConfiguredError("MCP integrations");
40946
41100
  }
40947
41101
  const tools = (options == null ? void 0 : options.integrations) ? yield resolveTools(options.integrations, options.tools) : (_a2 = options == null ? void 0 : options.tools) != null ? _a2 : {};
40948
41102
  const handler = new V3CuaAgentHandler(
@@ -41023,8 +41177,8 @@ Do not ask follow up questions, the user will trust your judgement.`
41023
41177
  return withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
41024
41178
  var _a2, _b2;
41025
41179
  if (((options == null ? void 0 : options.integrations) || (options == null ? void 0 : options.tools)) && !this.experimental) {
41026
- throw new Error(
41027
- "MCP integrations and custom tools are experimental. Enable experimental: true in V3 options."
41180
+ throw new ExperimentalNotConfiguredError(
41181
+ "MCP integrations and custom tools"
41028
41182
  );
41029
41183
  }
41030
41184
  const tools = (options == null ? void 0 : options.integrations) ? yield resolveTools(options.integrations, options.tools) : (_a2 = options == null ? void 0 : options.tools) != null ? _a2 : {};
@@ -41108,13 +41262,14 @@ function isObserveResult(v) {
41108
41262
 
41109
41263
  // lib/v3Evaluator.ts
41110
41264
  var import_dotenv2 = __toESM(require("dotenv"));
41111
- var import_zod23 = require("zod");
41265
+ var import_v318 = require("zod/v3");
41266
+ init_sdkErrors();
41112
41267
  import_dotenv2.default.config();
41113
- var EvaluationSchema = import_zod23.z.object({
41114
- evaluation: import_zod23.z.enum(["YES", "NO"]),
41115
- reasoning: import_zod23.z.string()
41268
+ var EvaluationSchema = import_v318.z.object({
41269
+ evaluation: import_v318.z.enum(["YES", "NO"]),
41270
+ reasoning: import_v318.z.string()
41116
41271
  });
41117
- var BatchEvaluationSchema = import_zod23.z.array(EvaluationSchema);
41272
+ var BatchEvaluationSchema = import_v318.z.array(EvaluationSchema);
41118
41273
  var V3Evaluator = class {
41119
41274
  constructor(v3, modelName, modelClientOptions) {
41120
41275
  this.silentLogger = () => {
@@ -41139,9 +41294,14 @@ var V3Evaluator = class {
41139
41294
  screenshotDelayMs = 250,
41140
41295
  agentReasoning
41141
41296
  } = options;
41142
- if (!question) throw new Error("Question cannot be an empty string");
41297
+ if (!question)
41298
+ throw new StagehandInvalidArgumentError(
41299
+ "Question cannot be an empty string"
41300
+ );
41143
41301
  if (!answer && !screenshot)
41144
- throw new Error("Either answer (text) or screenshot must be provided");
41302
+ throw new StagehandInvalidArgumentError(
41303
+ "Either answer (text) or screenshot must be provided"
41304
+ );
41145
41305
  if (Array.isArray(screenshot)) {
41146
41306
  return this._evaluateWithMultipleScreenshots({
41147
41307
  question,
@@ -41209,7 +41369,10 @@ ${agentReasoning}` : question
41209
41369
  systemPrompt = "You are an expert evaluator that returns YES or NO with a concise reasoning.",
41210
41370
  screenshotDelayMs = 250
41211
41371
  } = options;
41212
- if (!(questions == null ? void 0 : questions.length)) throw new Error("Questions array cannot be empty");
41372
+ if (!(questions == null ? void 0 : questions.length))
41373
+ throw new StagehandInvalidArgumentError(
41374
+ "Questions array cannot be empty"
41375
+ );
41213
41376
  yield new Promise((r) => setTimeout(r, screenshotDelayMs));
41214
41377
  let imageBuffer;
41215
41378
  if (screenshot) {
@@ -41280,9 +41443,14 @@ You will be given multiple questions${screenshot ? " with a screenshot" : ""}. $
41280
41443
  ${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." : ""}
41281
41444
  Today's date is ${(/* @__PURE__ */ new Date()).toLocaleDateString()}`
41282
41445
  } = options;
41283
- if (!question) throw new Error("Question cannot be an empty string");
41446
+ if (!question)
41447
+ throw new StagehandInvalidArgumentError(
41448
+ "Question cannot be an empty string"
41449
+ );
41284
41450
  if (!screenshots || screenshots.length === 0)
41285
- throw new Error("At least one screenshot must be provided");
41451
+ throw new StagehandInvalidArgumentError(
41452
+ "At least one screenshot must be provided"
41453
+ );
41286
41454
  const llmClient = this.getClient();
41287
41455
  const imageContents = screenshots.map((s) => ({
41288
41456
  type: "image_url",
@@ -41336,9 +41504,12 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41336
41504
  AnnotatedScreenshotText,
41337
41505
  BrowserbaseSessionNotFoundError,
41338
41506
  CaptchaTimeoutError,
41507
+ ConnectionTimeoutError,
41339
41508
  ConsoleMessage,
41340
41509
  ContentFrameNotFoundError,
41341
41510
  CreateChatCompletionResponseError,
41511
+ CuaModelRequiredError,
41512
+ ElementNotVisibleError,
41342
41513
  ExperimentalApiConflictError,
41343
41514
  ExperimentalNotConfiguredError,
41344
41515
  HandlerNotInitializedError,
@@ -41349,7 +41520,10 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41349
41520
  MCPConnectionError,
41350
41521
  MissingEnvironmentVariableError,
41351
41522
  MissingLLMConfigurationError,
41523
+ PageNotFoundError,
41352
41524
  Response,
41525
+ ResponseBodyError,
41526
+ ResponseParseError,
41353
41527
  Stagehand,
41354
41528
  StagehandAPIError,
41355
41529
  StagehandAPIUnauthorizedError,
@@ -41372,6 +41546,7 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41372
41546
  StagehandShadowRootMissingError,
41373
41547
  StagehandShadowSegmentEmptyError,
41374
41548
  StagehandShadowSegmentNotFoundError,
41549
+ TimeoutError,
41375
41550
  UnsupportedAISDKModelProviderError,
41376
41551
  UnsupportedModelError,
41377
41552
  UnsupportedModelProviderError,