@browserbasehq/orca 3.0.1 → 3.0.2

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.
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";
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,231 +7805,8 @@ 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";
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
7811
  var import_v3 = require("zod/v3");
7672
7812
  var ID_PATTERN = /^\d+-\d+$/;
@@ -8326,6 +8466,7 @@ function safeGetPageUrl(page) {
8326
8466
  }
8327
8467
 
8328
8468
  // lib/v3/cache/ActCache.ts
8469
+ init_sdkErrors();
8329
8470
  var ActCache = class {
8330
8471
  constructor({
8331
8472
  storage,
@@ -8453,7 +8594,7 @@ var ActCache = class {
8453
8594
  return __async(this, null, function* () {
8454
8595
  const handler = this.getActHandler();
8455
8596
  if (!handler) {
8456
- throw new Error("V3 not initialized. Call init() before act().");
8597
+ throw new StagehandNotInitializedError("act()");
8457
8598
  }
8458
8599
  const execute = () => __async(this, null, function* () {
8459
8600
  var _a, _b, _c;
@@ -9700,12 +9841,14 @@ var SupportedPlaywrightAction = /* @__PURE__ */ ((SupportedPlaywrightAction2) =>
9700
9841
  SupportedPlaywrightAction2["NEXT_CHUNK"] = "nextChunk";
9701
9842
  SupportedPlaywrightAction2["PREV_CHUNK"] = "prevChunk";
9702
9843
  SupportedPlaywrightAction2["SELECT_OPTION_FROM_DROPDOWN"] = "selectOptionFromDropdown";
9844
+ SupportedPlaywrightAction2["HOVER"] = "hover";
9703
9845
  return SupportedPlaywrightAction2;
9704
9846
  })(SupportedPlaywrightAction || {});
9705
9847
 
9706
9848
  // lib/v3/handlers/handlerUtils/actHandlerUtils.ts
9707
9849
  init_deepLocator();
9708
9850
  init_logger();
9851
+ init_sdkErrors();
9709
9852
  var UnderstudyCommandException = class extends Error {
9710
9853
  constructor(message) {
9711
9854
  super(message);
@@ -9810,7 +9953,8 @@ var METHOD_HANDLER_MAP = {
9810
9953
  nextChunk: scrollToNextChunk,
9811
9954
  prevChunk: scrollToPreviousChunk,
9812
9955
  selectOptionFromDropdown: selectOption,
9813
- selectOption
9956
+ selectOption,
9957
+ hover
9814
9958
  };
9815
9959
  function selectOption(ctx) {
9816
9960
  return __async(this, null, function* () {
@@ -10153,6 +10297,26 @@ function scrollByElementHeight(ctx, direction) {
10153
10297
  }
10154
10298
  });
10155
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
+ }
10156
10320
  function getFrameUrl(frame) {
10157
10321
  return __async(this, null, function* () {
10158
10322
  const url = yield frame.evaluate("location.href");
@@ -10661,6 +10825,7 @@ var ActHandler = class {
10661
10825
  init_logger();
10662
10826
  init_snapshot();
10663
10827
  var import_v34 = require("zod/v3");
10828
+ init_sdkErrors();
10664
10829
  function transformUrlStringsToNumericIds(schema) {
10665
10830
  const [finalSchema, urlPaths] = transformSchema(schema, []);
10666
10831
  return [finalSchema, urlPaths];
@@ -10693,7 +10858,7 @@ var ExtractHandler = class {
10693
10858
  return pageTextSchema.parse(result);
10694
10859
  }
10695
10860
  if (!instruction && schema) {
10696
- throw new Error(
10861
+ throw new StagehandInvalidArgumentError(
10697
10862
  "extract() requires an instruction when a schema is provided."
10698
10863
  );
10699
10864
  }
@@ -11452,6 +11617,7 @@ function createStandardAction(toolCallName, toolResult, args, reasoning) {
11452
11617
  }
11453
11618
 
11454
11619
  // lib/v3/handlers/v3AgentHandler.ts
11620
+ init_sdkErrors();
11455
11621
  var V3AgentHandler = class {
11456
11622
  constructor(v3, logger, llmClient, executionModel, systemInstructions, mcpTools) {
11457
11623
  this.v3 = v3;
@@ -11483,9 +11649,7 @@ var V3AgentHandler = class {
11483
11649
  { role: "user", content: options.instruction }
11484
11650
  ];
11485
11651
  if (!((_a = this.llmClient) == null ? void 0 : _a.getLanguageModel)) {
11486
- throw new Error(
11487
- "V3AgentHandler requires an AISDK-backed LLM client. Ensure your model is configured like 'openai/gpt-4.1-mini'."
11488
- );
11652
+ throw new MissingLLMConfigurationError();
11489
11653
  }
11490
11654
  const baseModel = this.llmClient.getLanguageModel();
11491
11655
  const wrappedModel = (0, import_ai11.wrapLanguageModel)({
@@ -11632,7 +11796,11 @@ STRATEGY:
11632
11796
  // lib/v3/handlers/v3CuaAgentHandler.ts
11633
11797
  init_snapshot();
11634
11798
 
11799
+ // lib/v3/agent/AgentProvider.ts
11800
+ init_sdkErrors();
11801
+
11635
11802
  // lib/v3/agent/AnthropicCUAClient.ts
11803
+ init_sdkErrors();
11636
11804
  var import_sdk = __toESM(require("@anthropic-ai/sdk"));
11637
11805
  var import_zod_to_json_schema = require("zod-to-json-schema");
11638
11806
 
@@ -12525,6 +12693,7 @@ var AnthropicCUAClient = class extends AgentClient {
12525
12693
 
12526
12694
  // lib/v3/agent/OpenAICUAClient.ts
12527
12695
  var import_openai = __toESM(require("openai"));
12696
+ init_sdkErrors();
12528
12697
  var OpenAICUAClient = class extends AgentClient {
12529
12698
  constructor(type, modelName, userProvidedInstructions, clientOptions, tools) {
12530
12699
  super(type, modelName, userProvidedInstructions);
@@ -12998,6 +13167,7 @@ var OpenAICUAClient = class extends AgentClient {
12998
13167
 
12999
13168
  // lib/v3/agent/GoogleCUAClient.ts
13000
13169
  var import_genai3 = require("@google/genai");
13170
+ init_sdkErrors();
13001
13171
 
13002
13172
  // lib/v3/agent/utils/googleCustomToolHandler.ts
13003
13173
  var import_genai2 = require("@google/genai");
@@ -13314,7 +13484,7 @@ var GoogleCUAClient = class extends AgentClient {
13314
13484
  config: this.generateContentConfig
13315
13485
  });
13316
13486
  if (!response.candidates || response.candidates.length === 0) {
13317
- throw new Error("Response has no candidates!");
13487
+ throw new LLMResponseError("agent", "Response has no candidates!");
13318
13488
  }
13319
13489
  break;
13320
13490
  } catch (error) {
@@ -14314,6 +14484,7 @@ var V3CuaAgentHandler = class {
14314
14484
 
14315
14485
  // lib/v3/launch/browserbase.ts
14316
14486
  var import_sdk2 = __toESM(require("@browserbasehq/sdk"));
14487
+ init_sdkErrors();
14317
14488
  function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14318
14489
  return __async(this, null, function* () {
14319
14490
  var _b;
@@ -14323,11 +14494,11 @@ function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14323
14494
  resumeSessionId
14324
14495
  );
14325
14496
  if (!(existing == null ? void 0 : existing.id)) {
14326
- throw new Error(`Browserbase session not found: ${resumeSessionId}`);
14497
+ throw new BrowserbaseSessionNotFoundError();
14327
14498
  }
14328
14499
  const ws = existing.connectUrl;
14329
14500
  if (!ws) {
14330
- throw new Error(
14501
+ throw new StagehandInitError(
14331
14502
  `Browserbase session resume missing connectUrl for ${resumeSessionId}`
14332
14503
  );
14333
14504
  }
@@ -14354,7 +14525,7 @@ function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14354
14525
  });
14355
14526
  const created = yield bb.sessions.create(createPayload);
14356
14527
  if (!(created == null ? void 0 : created.connectUrl) || !(created == null ? void 0 : created.id)) {
14357
- throw new Error(
14528
+ throw new StagehandInitError(
14358
14529
  "Browserbase session creation returned an unexpected shape."
14359
14530
  );
14360
14531
  }
@@ -15405,6 +15576,7 @@ var Launcher = class _Launcher {
15405
15576
  };
15406
15577
 
15407
15578
  // lib/v3/launch/local.ts
15579
+ init_sdkErrors();
15408
15580
  function launchLocalChrome(opts) {
15409
15581
  return __async(this, null, function* () {
15410
15582
  var _a, _b, _c;
@@ -15449,12 +15621,15 @@ function waitForWebSocketDebuggerUrl(port, timeoutMs) {
15449
15621
  }
15450
15622
  yield new Promise((r) => setTimeout(r, 250));
15451
15623
  }
15452
- throw new Error(
15624
+ throw new ConnectionTimeoutError(
15453
15625
  `Timed out waiting for /json/version on port ${port}${lastErrMsg ? ` (last error: ${lastErrMsg})` : ""}`
15454
15626
  );
15455
15627
  });
15456
15628
  }
15457
15629
 
15630
+ // lib/v3/llm/LLMProvider.ts
15631
+ init_sdkErrors();
15632
+
15458
15633
  // lib/v3/llm/aisdk.ts
15459
15634
  var import_ai13 = require("ai");
15460
15635
 
@@ -15727,6 +15902,7 @@ var AISdkClient = class extends LLMClient {
15727
15902
  // lib/v3/llm/AnthropicClient.ts
15728
15903
  var import_sdk3 = __toESM(require("@anthropic-ai/sdk"));
15729
15904
  var import_zod_to_json_schema3 = require("zod-to-json-schema");
15905
+ init_sdkErrors();
15730
15906
  var AnthropicClient = class extends LLMClient {
15731
15907
  constructor({
15732
15908
  modelName,
@@ -15969,6 +16145,7 @@ var extractSchemaProperties = (jsonSchema2) => {
15969
16145
  // lib/v3/llm/CerebrasClient.ts
15970
16146
  var import_openai2 = __toESM(require("openai"));
15971
16147
  var import_zod_to_json_schema4 = require("zod-to-json-schema");
16148
+ init_sdkErrors();
15972
16149
  var CerebrasClient = class extends LLMClient {
15973
16150
  constructor({
15974
16151
  modelName,
@@ -16188,6 +16365,7 @@ var CerebrasClient = class extends LLMClient {
16188
16365
 
16189
16366
  // lib/v3/llm/GoogleClient.ts
16190
16367
  var import_genai4 = require("@google/genai");
16368
+ init_sdkErrors();
16191
16369
  var roleMap = {
16192
16370
  user: "user",
16193
16371
  assistant: "model",
@@ -16556,6 +16734,7 @@ ${firstPartText.text}`;
16556
16734
  // lib/v3/llm/GroqClient.ts
16557
16735
  var import_openai3 = __toESM(require("openai"));
16558
16736
  var import_zod_to_json_schema5 = require("zod-to-json-schema");
16737
+ init_sdkErrors();
16559
16738
  var GroqClient = class extends LLMClient {
16560
16739
  constructor({
16561
16740
  modelName,
@@ -16777,6 +16956,7 @@ var GroqClient = class extends LLMClient {
16777
16956
  var import_openai4 = __toESM(require("openai"));
16778
16957
  var import_zod = require("openai/helpers/zod");
16779
16958
  var import_zod_to_json_schema6 = __toESM(require("zod-to-json-schema"));
16959
+ init_sdkErrors();
16780
16960
  var OpenAIClient = class extends LLMClient {
16781
16961
  constructor({
16782
16962
  modelName,
@@ -38400,6 +38580,7 @@ init_logger();
38400
38580
  var import_client = require("@modelcontextprotocol/sdk/client/index.js");
38401
38581
  var import_streamableHttp = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
38402
38582
  var import_stdio = require("@modelcontextprotocol/sdk/client/stdio.js");
38583
+ init_sdkErrors();
38403
38584
  var connectToMCPServer = (serverConfig) => __async(null, null, function* () {
38404
38585
  try {
38405
38586
  let transport;
@@ -38525,6 +38706,9 @@ var LOG_LEVEL_NAMES = {
38525
38706
  init_consoleMessage();
38526
38707
  init_response();
38527
38708
 
38709
+ // lib/v3/types/public/index.ts
38710
+ init_sdkErrors();
38711
+
38528
38712
  // examples/external_clients/aisdk.ts
38529
38713
  var import_ai14 = require("ai");
38530
38714
  var AISdkClient2 = class extends LLMClient {
@@ -38892,6 +39076,7 @@ function installV3PiercerIntoSession(session) {
38892
39076
 
38893
39077
  // lib/v3/understudy/context.ts
38894
39078
  init_executionContextRegistry();
39079
+ init_sdkErrors();
38895
39080
  function isTopLevelPage(info) {
38896
39081
  const ti = info;
38897
39082
  return info.type === "page" && ti.subtype !== "iframe";
@@ -38927,7 +39112,6 @@ var V3Context = class _V3Context {
38927
39112
  return __async(this, null, function* () {
38928
39113
  var _a, _b, _c;
38929
39114
  const conn = yield CdpConnection.connect(wsUrl);
38930
- yield conn.enableAutoAttach();
38931
39115
  const ctx = new _V3Context(
38932
39116
  conn,
38933
39117
  (_a = opts == null ? void 0 : opts.env) != null ? _a : "LOCAL",
@@ -38955,11 +39139,41 @@ var V3Context = class _V3Context {
38955
39139
  }
38956
39140
  yield new Promise((r) => setTimeout(r, 25));
38957
39141
  }
38958
- throw new Error(
38959
- `waitForFirstTopLevelPage timed out after ${timeoutMs}ms (no top-level Page)`
39142
+ throw new TimeoutError(
39143
+ "waitForFirstTopLevelPage (no top-level Page)",
39144
+ timeoutMs
38960
39145
  );
38961
39146
  });
38962
39147
  }
39148
+ waitForInitialTopLevelTargets(targetIds, timeoutMs = 3e3) {
39149
+ return __async(this, null, function* () {
39150
+ if (!targetIds.length) return;
39151
+ const pending = new Set(targetIds);
39152
+ const deadline = Date.now() + timeoutMs;
39153
+ while (pending.size && Date.now() < deadline) {
39154
+ for (const tid of Array.from(pending)) {
39155
+ if (this.pagesByTarget.has(tid)) {
39156
+ pending.delete(tid);
39157
+ }
39158
+ }
39159
+ if (!pending.size) return;
39160
+ yield new Promise((r) => setTimeout(r, 25));
39161
+ }
39162
+ if (pending.size) {
39163
+ v3Logger({
39164
+ category: "ctx",
39165
+ message: "Timed out waiting for existing top-level targets to attach",
39166
+ level: 2,
39167
+ auxiliary: {
39168
+ remainingTargets: {
39169
+ value: JSON.stringify(Array.from(pending)),
39170
+ type: "object"
39171
+ }
39172
+ }
39173
+ });
39174
+ }
39175
+ });
39176
+ }
38963
39177
  ensurePiercer(session) {
38964
39178
  return __async(this, null, function* () {
38965
39179
  const key = this.sessionKey(session);
@@ -39049,8 +39263,7 @@ var V3Context = class _V3Context {
39049
39263
  getFullFrameTreeByMainFrameId(rootMainFrameId) {
39050
39264
  return __async(this, null, function* () {
39051
39265
  const owner = this.resolvePageByMainFrameId(rootMainFrameId);
39052
- if (!owner)
39053
- throw new Error(`No Page found for mainFrameId=${rootMainFrameId}`);
39266
+ if (!owner) throw new PageNotFoundError(`mainFrameId=${rootMainFrameId}`);
39054
39267
  return owner.asProtocolFrameTree(rootMainFrameId);
39055
39268
  });
39056
39269
  }
@@ -39073,7 +39286,7 @@ var V3Context = class _V3Context {
39073
39286
  if (page) return page;
39074
39287
  yield new Promise((r) => setTimeout(r, 25));
39075
39288
  }
39076
- throw new Error(`newPage timeout: target not attached (${targetId})`);
39289
+ throw new TimeoutError(`newPage: target not attached (${targetId})`, 5e3);
39077
39290
  });
39078
39291
  }
39079
39292
  /**
@@ -39141,6 +39354,7 @@ var V3Context = class _V3Context {
39141
39354
  }
39142
39355
  })
39143
39356
  );
39357
+ yield this.conn.enableAutoAttach();
39144
39358
  const targets = yield this.conn.getTargets();
39145
39359
  for (const t of targets) {
39146
39360
  try {
@@ -39148,6 +39362,8 @@ var V3Context = class _V3Context {
39148
39362
  } catch (e) {
39149
39363
  }
39150
39364
  }
39365
+ const topLevelTargetIds = targets.filter((t) => isTopLevelPage(t)).map((t) => t.targetId);
39366
+ yield this.waitForInitialTopLevelTargets(topLevelTargetIds);
39151
39367
  });
39152
39368
  }
39153
39369
  /**
@@ -39433,7 +39649,7 @@ var V3Context = class _V3Context {
39433
39649
  yield new Promise((r) => setTimeout(r, 25));
39434
39650
  }
39435
39651
  if (immediate) return immediate;
39436
- throw new Error("awaitActivePage: no page available");
39652
+ throw new PageNotFoundError("awaitActivePage: no page available");
39437
39653
  });
39438
39654
  }
39439
39655
  };
@@ -39464,6 +39680,7 @@ function resolveModel(model) {
39464
39680
  // lib/v3/api.ts
39465
39681
  var import_fetch_cookie = __toESM(require("fetch-cookie"));
39466
39682
  var import_zod_to_json_schema7 = __toESM(require("zod-to-json-schema"));
39683
+ init_version();
39467
39684
  var StagehandAPIClient = class {
39468
39685
  constructor({ apiKey, projectId, logger }) {
39469
39686
  this.apiKey = apiKey;
@@ -39608,9 +39825,7 @@ var StagehandAPIClient = class {
39608
39825
  agentExecute(agentConfig, executeOptions, frameId) {
39609
39826
  return __async(this, null, function* () {
39610
39827
  if (agentConfig.integrations && agentConfig.integrations.length > 0) {
39611
- throw new StagehandAPIError(
39612
- "MCP integrations are not supported in API mode. Set experimental: true to use MCP integrations."
39613
- );
39828
+ throw new ExperimentalNotConfiguredError("MCP integrations");
39614
39829
  }
39615
39830
  if (typeof executeOptions === "object") {
39616
39831
  if (executeOptions.page) {
@@ -39839,7 +40054,7 @@ function resolveModelConfiguration(model) {
39839
40054
  if (model && typeof model === "object") {
39840
40055
  const _a = model, { modelName } = _a, clientOptions = __objRest(_a, ["modelName"]);
39841
40056
  if (!modelName) {
39842
- throw new Error(
40057
+ throw new StagehandInvalidArgumentError(
39843
40058
  "model.modelName is required when providing client options."
39844
40059
  );
39845
40060
  }
@@ -39919,6 +40134,9 @@ var _V3 = class _V3 {
39919
40134
  this.llmProvider = new LLMProvider(this.logger);
39920
40135
  this.domSettleTimeoutMs = opts.domSettleTimeout;
39921
40136
  this.disableAPI = (_g = opts.disableAPI) != null ? _g : false;
40137
+ if (this.experimental && !this.disableAPI) {
40138
+ throw new ExperimentalApiConflictError();
40139
+ }
39922
40140
  const baseClientOptions = clientOptions ? __spreadValues({}, clientOptions) : {};
39923
40141
  if (opts.llmClient) {
39924
40142
  this.llmClient = opts.llmClient;
@@ -40339,8 +40557,9 @@ var _V3 = class _V3 {
40339
40557
  if (this.opts.env === "BROWSERBASE") {
40340
40558
  const { apiKey, projectId } = this.requireBrowserbaseCreds();
40341
40559
  if (!apiKey || !projectId) {
40342
- throw new Error(
40343
- "BROWSERBASE credentials missing. Provide in your v3 constructor, or set BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID in your .env"
40560
+ throw new MissingEnvironmentVariableError(
40561
+ "BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID",
40562
+ "Browserbase environment"
40344
40563
  );
40345
40564
  }
40346
40565
  this.logger({
@@ -40419,7 +40638,7 @@ var _V3 = class _V3 {
40419
40638
  return;
40420
40639
  }
40421
40640
  const neverEnv = this.opts.env;
40422
- throw new Error(`Unsupported env: ${neverEnv}`);
40641
+ throw new StagehandInitError(`Unsupported env: ${neverEnv}`);
40423
40642
  }));
40424
40643
  } catch (error) {
40425
40644
  if (this.externalLogger) {
@@ -40468,8 +40687,7 @@ var _V3 = class _V3 {
40468
40687
  act(input, options) {
40469
40688
  return __async(this, null, function* () {
40470
40689
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40471
- if (!this.actHandler)
40472
- throw new Error("V3 not initialized. Call init() before act().");
40690
+ if (!this.actHandler) throw new StagehandNotInitializedError("act()");
40473
40691
  let actResult;
40474
40692
  if (isObserveResult(input)) {
40475
40693
  const v3Page = yield this.resolvePage(options == null ? void 0 : options.page);
@@ -40500,7 +40718,7 @@ var _V3 = class _V3 {
40500
40718
  return actResult;
40501
40719
  }
40502
40720
  if (typeof input !== "string" || !input.trim()) {
40503
- throw new Error(
40721
+ throw new StagehandInvalidArgumentError(
40504
40722
  "act(): instruction string is required unless passing an Action"
40505
40723
  );
40506
40724
  }
@@ -40567,7 +40785,7 @@ var _V3 = class _V3 {
40567
40785
  return __async(this, null, function* () {
40568
40786
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40569
40787
  if (!this.extractHandler) {
40570
- throw new Error("V3 not initialized. Call init() before extract().");
40788
+ throw new StagehandNotInitializedError("extract()");
40571
40789
  }
40572
40790
  let instruction;
40573
40791
  let schema;
@@ -40585,7 +40803,9 @@ var _V3 = class _V3 {
40585
40803
  options = a || void 0;
40586
40804
  }
40587
40805
  if (!instruction && schema) {
40588
- throw new Error("extract(): schema provided without instruction");
40806
+ throw new StagehandInvalidArgumentError(
40807
+ "extract(): schema provided without instruction"
40808
+ );
40589
40809
  }
40590
40810
  const effectiveSchema = instruction && !schema ? defaultExtractSchema : schema;
40591
40811
  const page = yield this.resolvePage(options == null ? void 0 : options.page);
@@ -40617,7 +40837,7 @@ var _V3 = class _V3 {
40617
40837
  return __async(this, null, function* () {
40618
40838
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40619
40839
  if (!this.observeHandler) {
40620
- throw new Error("V3 not initialized. Call init() before observe().");
40840
+ throw new StagehandNotInitializedError("observe()");
40621
40841
  }
40622
40842
  let instruction;
40623
40843
  let options;
@@ -40661,7 +40881,7 @@ var _V3 = class _V3 {
40661
40881
  /** Return the browser-level CDP WebSocket endpoint. */
40662
40882
  connectURL() {
40663
40883
  if (this.state.kind === "UNINITIALIZED") {
40664
- throw new Error("V3 not initialized. Call await v3.init() first.");
40884
+ throw new StagehandNotInitializedError("connectURL()");
40665
40885
  }
40666
40886
  return this.state.ws;
40667
40887
  }
@@ -40726,10 +40946,9 @@ var _V3 = class _V3 {
40726
40946
  const missing = [];
40727
40947
  if (!apiKey) missing.push("BROWSERBASE_API_KEY");
40728
40948
  if (!projectId) missing.push("BROWSERBASE_PROJECT_ID");
40729
- throw new Error(
40730
- `BROWSERBASE credentials missing. Provide in your v3 constructor, or set ${missing.join(
40731
- ", "
40732
- )} in your .env`
40949
+ throw new MissingEnvironmentVariableError(
40950
+ missing.join(", "),
40951
+ "Browserbase"
40733
40952
  );
40734
40953
  }
40735
40954
  this.opts.apiKey = apiKey;
@@ -40775,7 +40994,9 @@ var _V3 = class _V3 {
40775
40994
  });
40776
40995
  return frameTree.frame.id;
40777
40996
  }
40778
- throw new Error("Unsupported page object passed to V3.act()");
40997
+ throw new StagehandInvalidArgumentError(
40998
+ "Unsupported page object passed to V3.act()"
40999
+ );
40779
41000
  });
40780
41001
  }
40781
41002
  isPlaywrightPage(p) {
@@ -40795,9 +41016,7 @@ var _V3 = class _V3 {
40795
41016
  }
40796
41017
  const ctx = this.ctx;
40797
41018
  if (!ctx) {
40798
- throw new Error(
40799
- "V3 context not initialized. Call init() before resolving pages."
40800
- );
41019
+ throw new StagehandNotInitializedError("resolvePage()");
40801
41020
  }
40802
41021
  return yield ctx.awaitActivePage();
40803
41022
  });
@@ -40811,24 +41030,30 @@ var _V3 = class _V3 {
40811
41030
  const frameId = yield this.resolveTopFrameId(input);
40812
41031
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40813
41032
  if (!page)
40814
- throw new Error("Failed to resolve V3 Page from Playwright page.");
41033
+ throw new StagehandInitError(
41034
+ "Failed to resolve V3 Page from Playwright page."
41035
+ );
40815
41036
  return page;
40816
41037
  }
40817
41038
  if (this.isPatchrightPage(input)) {
40818
41039
  const frameId = yield this.resolveTopFrameId(input);
40819
41040
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40820
41041
  if (!page)
40821
- throw new Error("Failed to resolve V3 Page from Playwright page.");
41042
+ throw new StagehandInitError(
41043
+ "Failed to resolve V3 Page from Patchright page."
41044
+ );
40822
41045
  return page;
40823
41046
  }
40824
41047
  if (this.isPuppeteerPage(input)) {
40825
41048
  const frameId = yield this.resolveTopFrameId(input);
40826
41049
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40827
41050
  if (!page)
40828
- throw new Error("Failed to resolve V3 Page from Puppeteer page.");
41051
+ throw new StagehandInitError(
41052
+ "Failed to resolve V3 Page from Puppeteer page."
41053
+ );
40829
41054
  return page;
40830
41055
  }
40831
- throw new Error("Unsupported page object.");
41056
+ throw new StagehandInvalidArgumentError("Unsupported page object.");
40832
41057
  });
40833
41058
  }
40834
41059
  /**
@@ -40855,8 +41080,8 @@ var _V3 = class _V3 {
40855
41080
  });
40856
41081
  if (options == null ? void 0 : options.cua) {
40857
41082
  if (((options == null ? void 0 : options.integrations) || (options == null ? void 0 : options.tools)) && !this.experimental) {
40858
- throw new Error(
40859
- "MCP integrations and custom tools are experimental. Enable experimental: true in V3 options."
41083
+ throw new ExperimentalNotConfiguredError(
41084
+ "MCP integrations and custom tools"
40860
41085
  );
40861
41086
  }
40862
41087
  const modelToUse = (options == null ? void 0 : options.model) || __spreadValues({
@@ -40864,9 +41089,7 @@ var _V3 = class _V3 {
40864
41089
  }, this.modelClientOptions);
40865
41090
  const { modelName, isCua, clientOptions } = resolveModel(modelToUse);
40866
41091
  if (!isCua) {
40867
- throw new Error(
40868
- "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(", ")
40869
- );
41092
+ throw new CuaModelRequiredError(AVAILABLE_CUA_MODELS);
40870
41093
  }
40871
41094
  const agentConfigSignature2 = this.agentCache.buildConfigSignature(options);
40872
41095
  return {
@@ -40874,9 +41097,7 @@ var _V3 = class _V3 {
40874
41097
  return withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40875
41098
  var _a2, _b2;
40876
41099
  if ((options == null ? void 0 : options.integrations) && !this.experimental) {
40877
- throw new Error(
40878
- "MCP integrations are experimental. Enable experimental: true in V3 options."
40879
- );
41100
+ throw new ExperimentalNotConfiguredError("MCP integrations");
40880
41101
  }
40881
41102
  const tools = (options == null ? void 0 : options.integrations) ? yield resolveTools(options.integrations, options.tools) : (_a2 = options == null ? void 0 : options.tools) != null ? _a2 : {};
40882
41103
  const handler = new V3CuaAgentHandler(
@@ -40957,8 +41178,8 @@ Do not ask follow up questions, the user will trust your judgement.`
40957
41178
  return withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40958
41179
  var _a2, _b2;
40959
41180
  if (((options == null ? void 0 : options.integrations) || (options == null ? void 0 : options.tools)) && !this.experimental) {
40960
- throw new Error(
40961
- "MCP integrations and custom tools are experimental. Enable experimental: true in V3 options."
41181
+ throw new ExperimentalNotConfiguredError(
41182
+ "MCP integrations and custom tools"
40962
41183
  );
40963
41184
  }
40964
41185
  const tools = (options == null ? void 0 : options.integrations) ? yield resolveTools(options.integrations, options.tools) : (_a2 = options == null ? void 0 : options.tools) != null ? _a2 : {};
@@ -41043,6 +41264,7 @@ function isObserveResult(v) {
41043
41264
  // lib/v3Evaluator.ts
41044
41265
  var import_dotenv2 = __toESM(require("dotenv"));
41045
41266
  var import_v318 = require("zod/v3");
41267
+ init_sdkErrors();
41046
41268
  import_dotenv2.default.config();
41047
41269
  var EvaluationSchema = import_v318.z.object({
41048
41270
  evaluation: import_v318.z.enum(["YES", "NO"]),
@@ -41073,9 +41295,14 @@ var V3Evaluator = class {
41073
41295
  screenshotDelayMs = 250,
41074
41296
  agentReasoning
41075
41297
  } = options;
41076
- if (!question) throw new Error("Question cannot be an empty string");
41298
+ if (!question)
41299
+ throw new StagehandInvalidArgumentError(
41300
+ "Question cannot be an empty string"
41301
+ );
41077
41302
  if (!answer && !screenshot)
41078
- throw new Error("Either answer (text) or screenshot must be provided");
41303
+ throw new StagehandInvalidArgumentError(
41304
+ "Either answer (text) or screenshot must be provided"
41305
+ );
41079
41306
  if (Array.isArray(screenshot)) {
41080
41307
  return this._evaluateWithMultipleScreenshots({
41081
41308
  question,
@@ -41143,7 +41370,10 @@ ${agentReasoning}` : question
41143
41370
  systemPrompt = "You are an expert evaluator that returns YES or NO with a concise reasoning.",
41144
41371
  screenshotDelayMs = 250
41145
41372
  } = options;
41146
- if (!(questions == null ? void 0 : questions.length)) throw new Error("Questions array cannot be empty");
41373
+ if (!(questions == null ? void 0 : questions.length))
41374
+ throw new StagehandInvalidArgumentError(
41375
+ "Questions array cannot be empty"
41376
+ );
41147
41377
  yield new Promise((r) => setTimeout(r, screenshotDelayMs));
41148
41378
  let imageBuffer;
41149
41379
  if (screenshot) {
@@ -41214,9 +41444,14 @@ You will be given multiple questions${screenshot ? " with a screenshot" : ""}. $
41214
41444
  ${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." : ""}
41215
41445
  Today's date is ${(/* @__PURE__ */ new Date()).toLocaleDateString()}`
41216
41446
  } = options;
41217
- if (!question) throw new Error("Question cannot be an empty string");
41447
+ if (!question)
41448
+ throw new StagehandInvalidArgumentError(
41449
+ "Question cannot be an empty string"
41450
+ );
41218
41451
  if (!screenshots || screenshots.length === 0)
41219
- throw new Error("At least one screenshot must be provided");
41452
+ throw new StagehandInvalidArgumentError(
41453
+ "At least one screenshot must be provided"
41454
+ );
41220
41455
  const llmClient = this.getClient();
41221
41456
  const imageContents = screenshots.map((s) => ({
41222
41457
  type: "image_url",
@@ -41270,9 +41505,12 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41270
41505
  AnnotatedScreenshotText,
41271
41506
  BrowserbaseSessionNotFoundError,
41272
41507
  CaptchaTimeoutError,
41508
+ ConnectionTimeoutError,
41273
41509
  ConsoleMessage,
41274
41510
  ContentFrameNotFoundError,
41275
41511
  CreateChatCompletionResponseError,
41512
+ CuaModelRequiredError,
41513
+ ElementNotVisibleError,
41276
41514
  ExperimentalApiConflictError,
41277
41515
  ExperimentalNotConfiguredError,
41278
41516
  HandlerNotInitializedError,
@@ -41283,7 +41521,10 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41283
41521
  MCPConnectionError,
41284
41522
  MissingEnvironmentVariableError,
41285
41523
  MissingLLMConfigurationError,
41524
+ PageNotFoundError,
41286
41525
  Response,
41526
+ ResponseBodyError,
41527
+ ResponseParseError,
41287
41528
  Stagehand,
41288
41529
  StagehandAPIError,
41289
41530
  StagehandAPIUnauthorizedError,
@@ -41306,6 +41547,7 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41306
41547
  StagehandShadowRootMissingError,
41307
41548
  StagehandShadowSegmentEmptyError,
41308
41549
  StagehandShadowSegmentNotFoundError,
41550
+ TimeoutError,
41309
41551
  UnsupportedAISDKModelProviderError,
41310
41552
  UnsupportedModelError,
41311
41553
  UnsupportedModelProviderError,