@browserbasehq/orca 3.0.1 → 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.
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,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");
@@ -13126,9 +13296,11 @@ var GoogleCUAClient = class extends AgentClient {
13126
13296
  this.environment = "ENVIRONMENT_BROWSER";
13127
13297
  this.tools = tools;
13128
13298
  this.apiKey = (clientOptions == null ? void 0 : clientOptions.apiKey) || process.env.GEMINI_API_KEY || process.env.GOOGLE_GENERATIVE_AI_API_KEY || "";
13129
- this.client = new import_genai3.GoogleGenAI({
13299
+ this.baseURL = clientOptions == null ? void 0 : clientOptions.baseURL;
13300
+ const genAIOptions = __spreadValues({
13130
13301
  apiKey: this.apiKey
13131
- });
13302
+ }, this.baseURL ? { httpOptions: { baseUrl: this.baseURL } } : {});
13303
+ this.client = new import_genai3.GoogleGenAI(genAIOptions);
13132
13304
  if ((clientOptions == null ? void 0 : clientOptions.environment) && typeof clientOptions.environment === "string") {
13133
13305
  this.environment = clientOptions.environment;
13134
13306
  }
@@ -13148,9 +13320,9 @@ var GoogleCUAClient = class extends AgentClient {
13148
13320
  }
13149
13321
  ]
13150
13322
  };
13151
- this.clientOptions = {
13323
+ this.clientOptions = __spreadValues({
13152
13324
  apiKey: this.apiKey
13153
- };
13325
+ }, this.baseURL ? { baseURL: this.baseURL } : {});
13154
13326
  if (this.tools && Object.keys(this.tools).length > 0) {
13155
13327
  this.updateGenerateContentConfig();
13156
13328
  }
@@ -13314,7 +13486,7 @@ var GoogleCUAClient = class extends AgentClient {
13314
13486
  config: this.generateContentConfig
13315
13487
  });
13316
13488
  if (!response.candidates || response.candidates.length === 0) {
13317
- throw new Error("Response has no candidates!");
13489
+ throw new LLMResponseError("agent", "Response has no candidates!");
13318
13490
  }
13319
13491
  break;
13320
13492
  } catch (error) {
@@ -14314,6 +14486,7 @@ var V3CuaAgentHandler = class {
14314
14486
 
14315
14487
  // lib/v3/launch/browserbase.ts
14316
14488
  var import_sdk2 = __toESM(require("@browserbasehq/sdk"));
14489
+ init_sdkErrors();
14317
14490
  function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14318
14491
  return __async(this, null, function* () {
14319
14492
  var _b;
@@ -14323,11 +14496,11 @@ function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14323
14496
  resumeSessionId
14324
14497
  );
14325
14498
  if (!(existing == null ? void 0 : existing.id)) {
14326
- throw new Error(`Browserbase session not found: ${resumeSessionId}`);
14499
+ throw new BrowserbaseSessionNotFoundError();
14327
14500
  }
14328
14501
  const ws = existing.connectUrl;
14329
14502
  if (!ws) {
14330
- throw new Error(
14503
+ throw new StagehandInitError(
14331
14504
  `Browserbase session resume missing connectUrl for ${resumeSessionId}`
14332
14505
  );
14333
14506
  }
@@ -14354,7 +14527,7 @@ function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14354
14527
  });
14355
14528
  const created = yield bb.sessions.create(createPayload);
14356
14529
  if (!(created == null ? void 0 : created.connectUrl) || !(created == null ? void 0 : created.id)) {
14357
- throw new Error(
14530
+ throw new StagehandInitError(
14358
14531
  "Browserbase session creation returned an unexpected shape."
14359
14532
  );
14360
14533
  }
@@ -15405,6 +15578,7 @@ var Launcher = class _Launcher {
15405
15578
  };
15406
15579
 
15407
15580
  // lib/v3/launch/local.ts
15581
+ init_sdkErrors();
15408
15582
  function launchLocalChrome(opts) {
15409
15583
  return __async(this, null, function* () {
15410
15584
  var _a, _b, _c;
@@ -15449,12 +15623,15 @@ function waitForWebSocketDebuggerUrl(port, timeoutMs) {
15449
15623
  }
15450
15624
  yield new Promise((r) => setTimeout(r, 250));
15451
15625
  }
15452
- throw new Error(
15626
+ throw new ConnectionTimeoutError(
15453
15627
  `Timed out waiting for /json/version on port ${port}${lastErrMsg ? ` (last error: ${lastErrMsg})` : ""}`
15454
15628
  );
15455
15629
  });
15456
15630
  }
15457
15631
 
15632
+ // lib/v3/llm/LLMProvider.ts
15633
+ init_sdkErrors();
15634
+
15458
15635
  // lib/v3/llm/aisdk.ts
15459
15636
  var import_ai13 = require("ai");
15460
15637
 
@@ -15727,6 +15904,7 @@ var AISdkClient = class extends LLMClient {
15727
15904
  // lib/v3/llm/AnthropicClient.ts
15728
15905
  var import_sdk3 = __toESM(require("@anthropic-ai/sdk"));
15729
15906
  var import_zod_to_json_schema3 = require("zod-to-json-schema");
15907
+ init_sdkErrors();
15730
15908
  var AnthropicClient = class extends LLMClient {
15731
15909
  constructor({
15732
15910
  modelName,
@@ -15969,6 +16147,7 @@ var extractSchemaProperties = (jsonSchema2) => {
15969
16147
  // lib/v3/llm/CerebrasClient.ts
15970
16148
  var import_openai2 = __toESM(require("openai"));
15971
16149
  var import_zod_to_json_schema4 = require("zod-to-json-schema");
16150
+ init_sdkErrors();
15972
16151
  var CerebrasClient = class extends LLMClient {
15973
16152
  constructor({
15974
16153
  modelName,
@@ -16188,6 +16367,7 @@ var CerebrasClient = class extends LLMClient {
16188
16367
 
16189
16368
  // lib/v3/llm/GoogleClient.ts
16190
16369
  var import_genai4 = require("@google/genai");
16370
+ init_sdkErrors();
16191
16371
  var roleMap = {
16192
16372
  user: "user",
16193
16373
  assistant: "model",
@@ -16556,6 +16736,7 @@ ${firstPartText.text}`;
16556
16736
  // lib/v3/llm/GroqClient.ts
16557
16737
  var import_openai3 = __toESM(require("openai"));
16558
16738
  var import_zod_to_json_schema5 = require("zod-to-json-schema");
16739
+ init_sdkErrors();
16559
16740
  var GroqClient = class extends LLMClient {
16560
16741
  constructor({
16561
16742
  modelName,
@@ -16777,6 +16958,7 @@ var GroqClient = class extends LLMClient {
16777
16958
  var import_openai4 = __toESM(require("openai"));
16778
16959
  var import_zod = require("openai/helpers/zod");
16779
16960
  var import_zod_to_json_schema6 = __toESM(require("zod-to-json-schema"));
16961
+ init_sdkErrors();
16780
16962
  var OpenAIClient = class extends LLMClient {
16781
16963
  constructor({
16782
16964
  modelName,
@@ -38400,6 +38582,7 @@ init_logger();
38400
38582
  var import_client = require("@modelcontextprotocol/sdk/client/index.js");
38401
38583
  var import_streamableHttp = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
38402
38584
  var import_stdio = require("@modelcontextprotocol/sdk/client/stdio.js");
38585
+ init_sdkErrors();
38403
38586
  var connectToMCPServer = (serverConfig) => __async(null, null, function* () {
38404
38587
  try {
38405
38588
  let transport;
@@ -38525,6 +38708,9 @@ var LOG_LEVEL_NAMES = {
38525
38708
  init_consoleMessage();
38526
38709
  init_response();
38527
38710
 
38711
+ // lib/v3/types/public/index.ts
38712
+ init_sdkErrors();
38713
+
38528
38714
  // examples/external_clients/aisdk.ts
38529
38715
  var import_ai14 = require("ai");
38530
38716
  var AISdkClient2 = class extends LLMClient {
@@ -38892,6 +39078,7 @@ function installV3PiercerIntoSession(session) {
38892
39078
 
38893
39079
  // lib/v3/understudy/context.ts
38894
39080
  init_executionContextRegistry();
39081
+ init_sdkErrors();
38895
39082
  function isTopLevelPage(info) {
38896
39083
  const ti = info;
38897
39084
  return info.type === "page" && ti.subtype !== "iframe";
@@ -38927,7 +39114,6 @@ var V3Context = class _V3Context {
38927
39114
  return __async(this, null, function* () {
38928
39115
  var _a, _b, _c;
38929
39116
  const conn = yield CdpConnection.connect(wsUrl);
38930
- yield conn.enableAutoAttach();
38931
39117
  const ctx = new _V3Context(
38932
39118
  conn,
38933
39119
  (_a = opts == null ? void 0 : opts.env) != null ? _a : "LOCAL",
@@ -38955,11 +39141,41 @@ var V3Context = class _V3Context {
38955
39141
  }
38956
39142
  yield new Promise((r) => setTimeout(r, 25));
38957
39143
  }
38958
- throw new Error(
38959
- `waitForFirstTopLevelPage timed out after ${timeoutMs}ms (no top-level Page)`
39144
+ throw new TimeoutError(
39145
+ "waitForFirstTopLevelPage (no top-level Page)",
39146
+ timeoutMs
38960
39147
  );
38961
39148
  });
38962
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
+ }
38963
39179
  ensurePiercer(session) {
38964
39180
  return __async(this, null, function* () {
38965
39181
  const key = this.sessionKey(session);
@@ -39049,8 +39265,7 @@ var V3Context = class _V3Context {
39049
39265
  getFullFrameTreeByMainFrameId(rootMainFrameId) {
39050
39266
  return __async(this, null, function* () {
39051
39267
  const owner = this.resolvePageByMainFrameId(rootMainFrameId);
39052
- if (!owner)
39053
- throw new Error(`No Page found for mainFrameId=${rootMainFrameId}`);
39268
+ if (!owner) throw new PageNotFoundError(`mainFrameId=${rootMainFrameId}`);
39054
39269
  return owner.asProtocolFrameTree(rootMainFrameId);
39055
39270
  });
39056
39271
  }
@@ -39073,7 +39288,7 @@ var V3Context = class _V3Context {
39073
39288
  if (page) return page;
39074
39289
  yield new Promise((r) => setTimeout(r, 25));
39075
39290
  }
39076
- throw new Error(`newPage timeout: target not attached (${targetId})`);
39291
+ throw new TimeoutError(`newPage: target not attached (${targetId})`, 5e3);
39077
39292
  });
39078
39293
  }
39079
39294
  /**
@@ -39141,6 +39356,7 @@ var V3Context = class _V3Context {
39141
39356
  }
39142
39357
  })
39143
39358
  );
39359
+ yield this.conn.enableAutoAttach();
39144
39360
  const targets = yield this.conn.getTargets();
39145
39361
  for (const t of targets) {
39146
39362
  try {
@@ -39148,6 +39364,8 @@ var V3Context = class _V3Context {
39148
39364
  } catch (e) {
39149
39365
  }
39150
39366
  }
39367
+ const topLevelTargetIds = targets.filter((t) => isTopLevelPage(t)).map((t) => t.targetId);
39368
+ yield this.waitForInitialTopLevelTargets(topLevelTargetIds);
39151
39369
  });
39152
39370
  }
39153
39371
  /**
@@ -39433,7 +39651,7 @@ var V3Context = class _V3Context {
39433
39651
  yield new Promise((r) => setTimeout(r, 25));
39434
39652
  }
39435
39653
  if (immediate) return immediate;
39436
- throw new Error("awaitActivePage: no page available");
39654
+ throw new PageNotFoundError("awaitActivePage: no page available");
39437
39655
  });
39438
39656
  }
39439
39657
  };
@@ -39464,6 +39682,7 @@ function resolveModel(model) {
39464
39682
  // lib/v3/api.ts
39465
39683
  var import_fetch_cookie = __toESM(require("fetch-cookie"));
39466
39684
  var import_zod_to_json_schema7 = __toESM(require("zod-to-json-schema"));
39685
+ init_version();
39467
39686
  var StagehandAPIClient = class {
39468
39687
  constructor({ apiKey, projectId, logger }) {
39469
39688
  this.apiKey = apiKey;
@@ -39608,9 +39827,7 @@ var StagehandAPIClient = class {
39608
39827
  agentExecute(agentConfig, executeOptions, frameId) {
39609
39828
  return __async(this, null, function* () {
39610
39829
  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
- );
39830
+ throw new ExperimentalNotConfiguredError("MCP integrations");
39614
39831
  }
39615
39832
  if (typeof executeOptions === "object") {
39616
39833
  if (executeOptions.page) {
@@ -39839,7 +40056,7 @@ function resolveModelConfiguration(model) {
39839
40056
  if (model && typeof model === "object") {
39840
40057
  const _a = model, { modelName } = _a, clientOptions = __objRest(_a, ["modelName"]);
39841
40058
  if (!modelName) {
39842
- throw new Error(
40059
+ throw new StagehandInvalidArgumentError(
39843
40060
  "model.modelName is required when providing client options."
39844
40061
  );
39845
40062
  }
@@ -40339,8 +40556,9 @@ var _V3 = class _V3 {
40339
40556
  if (this.opts.env === "BROWSERBASE") {
40340
40557
  const { apiKey, projectId } = this.requireBrowserbaseCreds();
40341
40558
  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"
40559
+ throw new MissingEnvironmentVariableError(
40560
+ "BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID",
40561
+ "Browserbase environment"
40344
40562
  );
40345
40563
  }
40346
40564
  this.logger({
@@ -40419,7 +40637,7 @@ var _V3 = class _V3 {
40419
40637
  return;
40420
40638
  }
40421
40639
  const neverEnv = this.opts.env;
40422
- throw new Error(`Unsupported env: ${neverEnv}`);
40640
+ throw new StagehandInitError(`Unsupported env: ${neverEnv}`);
40423
40641
  }));
40424
40642
  } catch (error) {
40425
40643
  if (this.externalLogger) {
@@ -40468,8 +40686,7 @@ var _V3 = class _V3 {
40468
40686
  act(input, options) {
40469
40687
  return __async(this, null, function* () {
40470
40688
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40471
- if (!this.actHandler)
40472
- throw new Error("V3 not initialized. Call init() before act().");
40689
+ if (!this.actHandler) throw new StagehandNotInitializedError("act()");
40473
40690
  let actResult;
40474
40691
  if (isObserveResult(input)) {
40475
40692
  const v3Page = yield this.resolvePage(options == null ? void 0 : options.page);
@@ -40500,7 +40717,7 @@ var _V3 = class _V3 {
40500
40717
  return actResult;
40501
40718
  }
40502
40719
  if (typeof input !== "string" || !input.trim()) {
40503
- throw new Error(
40720
+ throw new StagehandInvalidArgumentError(
40504
40721
  "act(): instruction string is required unless passing an Action"
40505
40722
  );
40506
40723
  }
@@ -40567,7 +40784,7 @@ var _V3 = class _V3 {
40567
40784
  return __async(this, null, function* () {
40568
40785
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40569
40786
  if (!this.extractHandler) {
40570
- throw new Error("V3 not initialized. Call init() before extract().");
40787
+ throw new StagehandNotInitializedError("extract()");
40571
40788
  }
40572
40789
  let instruction;
40573
40790
  let schema;
@@ -40585,7 +40802,9 @@ var _V3 = class _V3 {
40585
40802
  options = a || void 0;
40586
40803
  }
40587
40804
  if (!instruction && schema) {
40588
- throw new Error("extract(): schema provided without instruction");
40805
+ throw new StagehandInvalidArgumentError(
40806
+ "extract(): schema provided without instruction"
40807
+ );
40589
40808
  }
40590
40809
  const effectiveSchema = instruction && !schema ? defaultExtractSchema : schema;
40591
40810
  const page = yield this.resolvePage(options == null ? void 0 : options.page);
@@ -40617,7 +40836,7 @@ var _V3 = class _V3 {
40617
40836
  return __async(this, null, function* () {
40618
40837
  return yield withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40619
40838
  if (!this.observeHandler) {
40620
- throw new Error("V3 not initialized. Call init() before observe().");
40839
+ throw new StagehandNotInitializedError("observe()");
40621
40840
  }
40622
40841
  let instruction;
40623
40842
  let options;
@@ -40661,7 +40880,7 @@ var _V3 = class _V3 {
40661
40880
  /** Return the browser-level CDP WebSocket endpoint. */
40662
40881
  connectURL() {
40663
40882
  if (this.state.kind === "UNINITIALIZED") {
40664
- throw new Error("V3 not initialized. Call await v3.init() first.");
40883
+ throw new StagehandNotInitializedError("connectURL()");
40665
40884
  }
40666
40885
  return this.state.ws;
40667
40886
  }
@@ -40726,10 +40945,9 @@ var _V3 = class _V3 {
40726
40945
  const missing = [];
40727
40946
  if (!apiKey) missing.push("BROWSERBASE_API_KEY");
40728
40947
  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`
40948
+ throw new MissingEnvironmentVariableError(
40949
+ missing.join(", "),
40950
+ "Browserbase"
40733
40951
  );
40734
40952
  }
40735
40953
  this.opts.apiKey = apiKey;
@@ -40775,7 +40993,9 @@ var _V3 = class _V3 {
40775
40993
  });
40776
40994
  return frameTree.frame.id;
40777
40995
  }
40778
- throw new Error("Unsupported page object passed to V3.act()");
40996
+ throw new StagehandInvalidArgumentError(
40997
+ "Unsupported page object passed to V3.act()"
40998
+ );
40779
40999
  });
40780
41000
  }
40781
41001
  isPlaywrightPage(p) {
@@ -40795,9 +41015,7 @@ var _V3 = class _V3 {
40795
41015
  }
40796
41016
  const ctx = this.ctx;
40797
41017
  if (!ctx) {
40798
- throw new Error(
40799
- "V3 context not initialized. Call init() before resolving pages."
40800
- );
41018
+ throw new StagehandNotInitializedError("resolvePage()");
40801
41019
  }
40802
41020
  return yield ctx.awaitActivePage();
40803
41021
  });
@@ -40811,24 +41029,30 @@ var _V3 = class _V3 {
40811
41029
  const frameId = yield this.resolveTopFrameId(input);
40812
41030
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40813
41031
  if (!page)
40814
- 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
+ );
40815
41035
  return page;
40816
41036
  }
40817
41037
  if (this.isPatchrightPage(input)) {
40818
41038
  const frameId = yield this.resolveTopFrameId(input);
40819
41039
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40820
41040
  if (!page)
40821
- 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
+ );
40822
41044
  return page;
40823
41045
  }
40824
41046
  if (this.isPuppeteerPage(input)) {
40825
41047
  const frameId = yield this.resolveTopFrameId(input);
40826
41048
  const page = this.ctx.resolvePageByMainFrameId(frameId);
40827
41049
  if (!page)
40828
- 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
+ );
40829
41053
  return page;
40830
41054
  }
40831
- throw new Error("Unsupported page object.");
41055
+ throw new StagehandInvalidArgumentError("Unsupported page object.");
40832
41056
  });
40833
41057
  }
40834
41058
  /**
@@ -40855,8 +41079,8 @@ var _V3 = class _V3 {
40855
41079
  });
40856
41080
  if (options == null ? void 0 : options.cua) {
40857
41081
  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."
41082
+ throw new ExperimentalNotConfiguredError(
41083
+ "MCP integrations and custom tools"
40860
41084
  );
40861
41085
  }
40862
41086
  const modelToUse = (options == null ? void 0 : options.model) || __spreadValues({
@@ -40864,9 +41088,7 @@ var _V3 = class _V3 {
40864
41088
  }, this.modelClientOptions);
40865
41089
  const { modelName, isCua, clientOptions } = resolveModel(modelToUse);
40866
41090
  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
- );
41091
+ throw new CuaModelRequiredError(AVAILABLE_CUA_MODELS);
40870
41092
  }
40871
41093
  const agentConfigSignature2 = this.agentCache.buildConfigSignature(options);
40872
41094
  return {
@@ -40874,9 +41096,7 @@ var _V3 = class _V3 {
40874
41096
  return withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40875
41097
  var _a2, _b2;
40876
41098
  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
- );
41099
+ throw new ExperimentalNotConfiguredError("MCP integrations");
40880
41100
  }
40881
41101
  const tools = (options == null ? void 0 : options.integrations) ? yield resolveTools(options.integrations, options.tools) : (_a2 = options == null ? void 0 : options.tools) != null ? _a2 : {};
40882
41102
  const handler = new V3CuaAgentHandler(
@@ -40957,8 +41177,8 @@ Do not ask follow up questions, the user will trust your judgement.`
40957
41177
  return withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
40958
41178
  var _a2, _b2;
40959
41179
  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."
41180
+ throw new ExperimentalNotConfiguredError(
41181
+ "MCP integrations and custom tools"
40962
41182
  );
40963
41183
  }
40964
41184
  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 +41263,7 @@ function isObserveResult(v) {
41043
41263
  // lib/v3Evaluator.ts
41044
41264
  var import_dotenv2 = __toESM(require("dotenv"));
41045
41265
  var import_v318 = require("zod/v3");
41266
+ init_sdkErrors();
41046
41267
  import_dotenv2.default.config();
41047
41268
  var EvaluationSchema = import_v318.z.object({
41048
41269
  evaluation: import_v318.z.enum(["YES", "NO"]),
@@ -41073,9 +41294,14 @@ var V3Evaluator = class {
41073
41294
  screenshotDelayMs = 250,
41074
41295
  agentReasoning
41075
41296
  } = options;
41076
- 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
+ );
41077
41301
  if (!answer && !screenshot)
41078
- 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
+ );
41079
41305
  if (Array.isArray(screenshot)) {
41080
41306
  return this._evaluateWithMultipleScreenshots({
41081
41307
  question,
@@ -41143,7 +41369,10 @@ ${agentReasoning}` : question
41143
41369
  systemPrompt = "You are an expert evaluator that returns YES or NO with a concise reasoning.",
41144
41370
  screenshotDelayMs = 250
41145
41371
  } = options;
41146
- 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
+ );
41147
41376
  yield new Promise((r) => setTimeout(r, screenshotDelayMs));
41148
41377
  let imageBuffer;
41149
41378
  if (screenshot) {
@@ -41214,9 +41443,14 @@ You will be given multiple questions${screenshot ? " with a screenshot" : ""}. $
41214
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." : ""}
41215
41444
  Today's date is ${(/* @__PURE__ */ new Date()).toLocaleDateString()}`
41216
41445
  } = options;
41217
- 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
+ );
41218
41450
  if (!screenshots || screenshots.length === 0)
41219
- throw new Error("At least one screenshot must be provided");
41451
+ throw new StagehandInvalidArgumentError(
41452
+ "At least one screenshot must be provided"
41453
+ );
41220
41454
  const llmClient = this.getClient();
41221
41455
  const imageContents = screenshots.map((s) => ({
41222
41456
  type: "image_url",
@@ -41270,9 +41504,12 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41270
41504
  AnnotatedScreenshotText,
41271
41505
  BrowserbaseSessionNotFoundError,
41272
41506
  CaptchaTimeoutError,
41507
+ ConnectionTimeoutError,
41273
41508
  ConsoleMessage,
41274
41509
  ContentFrameNotFoundError,
41275
41510
  CreateChatCompletionResponseError,
41511
+ CuaModelRequiredError,
41512
+ ElementNotVisibleError,
41276
41513
  ExperimentalApiConflictError,
41277
41514
  ExperimentalNotConfiguredError,
41278
41515
  HandlerNotInitializedError,
@@ -41283,7 +41520,10 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41283
41520
  MCPConnectionError,
41284
41521
  MissingEnvironmentVariableError,
41285
41522
  MissingLLMConfigurationError,
41523
+ PageNotFoundError,
41286
41524
  Response,
41525
+ ResponseBodyError,
41526
+ ResponseParseError,
41287
41527
  Stagehand,
41288
41528
  StagehandAPIError,
41289
41529
  StagehandAPIUnauthorizedError,
@@ -41306,6 +41546,7 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
41306
41546
  StagehandShadowRootMissingError,
41307
41547
  StagehandShadowSegmentEmptyError,
41308
41548
  StagehandShadowSegmentNotFoundError,
41549
+ TimeoutError,
41309
41550
  UnsupportedAISDKModelProviderError,
41310
41551
  UnsupportedModelError,
41311
41552
  UnsupportedModelProviderError,