@browserbasehq/stagehand 3.0.6-alpha-75f87f1920021a012fe0159123d01404969a94c8 → 3.0.6-alpha-943d2d79d0f289ac41c9164578f2f1dd876058f2

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.d.ts CHANGED
@@ -5,7 +5,8 @@ import { GoogleVertexProviderSettings as GoogleVertexProviderSettings$1 } from '
5
5
  import { LanguageModelV2 } from '@ai-sdk/provider';
6
6
  import { ClientOptions as ClientOptions$1 } from 'openai';
7
7
  import { Client, ClientOptions as ClientOptions$3 } from '@modelcontextprotocol/sdk/client/index.js';
8
- import { ToolSet, PrepareStepFunction, GenerateTextOnStepFinishCallback, StreamTextOnStepFinishCallback, StreamTextOnErrorCallback, StreamTextOnChunkCallback, StreamTextOnFinishCallback, StepResult, StreamTextResult, ModelMessage, wrapLanguageModel, generateObject, generateText, streamText, streamObject, experimental_generateImage, embed, embedMany, experimental_transcribe, experimental_generateSpeech } from 'ai';
8
+ import { ToolSet, ModelMessage, PrepareStepFunction, GenerateTextOnStepFinishCallback, StreamTextOnStepFinishCallback, StreamTextOnErrorCallback, StreamTextOnChunkCallback, StreamTextOnFinishCallback, StepResult, StreamTextResult, wrapLanguageModel, generateObject, generateText, streamText, streamObject, experimental_generateImage, embed, embedMany, experimental_transcribe, experimental_generateSpeech } from 'ai';
9
+ export { ModelMessage } from 'ai';
9
10
  import { Page as Page$1 } from 'playwright-core';
10
11
  export { Page as PlaywrightPage } from 'playwright-core';
11
12
  import { Page as Page$2 } from 'puppeteer-core';
@@ -811,6 +812,10 @@ declare class StreamingCallbacksInNonStreamingModeError extends StagehandError {
811
812
  readonly invalidCallbacks: string[];
812
813
  constructor(invalidCallbacks: string[]);
813
814
  }
815
+ declare class AgentAbortError extends StagehandError {
816
+ readonly reason: string;
817
+ constructor(reason?: string);
818
+ }
814
819
 
815
820
  declare class AISdkClient extends LLMClient {
816
821
  type: "aisdk";
@@ -1661,6 +1666,12 @@ interface AgentResult {
1661
1666
  cached_input_tokens?: number;
1662
1667
  inference_time_ms: number;
1663
1668
  };
1669
+ /**
1670
+ * The conversation messages from this execution.
1671
+ * Pass these to a subsequent execute() call via the `messages` option to continue the conversation.
1672
+ * @experimental
1673
+ */
1674
+ messages?: ModelMessage[];
1664
1675
  }
1665
1676
  type AgentStreamResult = StreamTextResult<ToolSet, never> & {
1666
1677
  result: Promise<AgentResult>;
@@ -1792,6 +1803,29 @@ interface AgentExecuteOptionsBase {
1792
1803
  maxSteps?: number;
1793
1804
  page?: Page$1 | Page$2 | Page$3 | Page;
1794
1805
  highlightCursor?: boolean;
1806
+ /**
1807
+ * Previous conversation messages to continue from.
1808
+ * Pass the `messages` from a previous AgentResult to continue that conversation.
1809
+ * @experimental
1810
+ */
1811
+ messages?: ModelMessage[];
1812
+ /**
1813
+ * An AbortSignal that can be used to cancel the agent execution.
1814
+ * When aborted, the agent will stop and return a partial result.
1815
+ * @experimental
1816
+ *
1817
+ * @example
1818
+ * ```typescript
1819
+ * const controller = new AbortController();
1820
+ * setTimeout(() => controller.abort(), 30000); // 30 second timeout
1821
+ *
1822
+ * const result = await agent.execute({
1823
+ * instruction: "...",
1824
+ * signal: controller.signal
1825
+ * });
1826
+ * ```
1827
+ */
1828
+ signal?: AbortSignal;
1795
1829
  }
1796
1830
  /**
1797
1831
  * Options for non-streaming agent execution.
@@ -2423,4 +2457,4 @@ declare class V3Evaluator {
2423
2457
  private _evaluateWithMultipleScreenshots;
2424
2458
  }
2425
2459
 
2426
- export { type AISDKCustomProvider, type AISDKProvider, AISdkClient, AVAILABLE_CUA_MODELS, type ActOptions, type ActResult, ActTimeoutError, type Action, type ActionExecutionResult, type AgentAction, type AgentCallbacks, type AgentConfig, type AgentContext, type AgentExecuteCallbacks, type AgentExecuteOptions, type AgentExecuteOptionsBase, type AgentExecutionOptions, type AgentHandlerOptions, type AgentInstance, type AgentModelConfig, AgentProvider, type AgentProviderType, type AgentResult, AgentScreenshotProviderError, type AgentState, type AgentStreamCallbacks, type AgentStreamExecuteOptions, type AgentStreamResult, type AgentType, AnnotatedScreenshotText, type AnthropicClientOptions, type AnthropicContentBlock, type AnthropicJsonSchemaObject, type AnthropicMessage, type AnthropicTextBlock, type AnthropicToolResult, type AnyPage, type AvailableCuaModel, type AvailableModel, BrowserbaseSessionNotFoundError, CaptchaTimeoutError, type ChatCompletionOptions, type ChatMessage, type ChatMessageContent, type ChatMessageImageContent, type ChatMessageTextContent, type ClientOptions, type ComputerCallItem, ConnectionTimeoutError, type ConsoleListener, ConsoleMessage, ContentFrameNotFoundError, type CreateChatCompletionOptions, CreateChatCompletionResponseError, CuaModelRequiredError, ElementNotVisibleError, ExperimentalApiConflictError, ExperimentalNotConfiguredError, type ExtractOptions, type ExtractResult, ExtractTimeoutError, type FunctionCallItem, type GoogleServiceAccountCredentials, type GoogleVertexProviderSettings, HandlerNotInitializedError, type HistoryEntry, type InferStagehandSchema, InvalidAISDKModelFormatError, type JsonSchema, type JsonSchemaDocument, type JsonSchemaProperty, LLMClient, type LLMParsedResponse, type LLMResponse, LLMResponseError, type LLMTool, type LLMUsage, LOG_LEVEL_NAMES, type LoadState, type LocalBrowserLaunchOptions, type LogLevel, type LogLine, type Logger, MCPConnectionError, MissingEnvironmentVariableError, MissingLLMConfigurationError, type ModelConfiguration, type ModelProvider, type NonStreamingAgentInstance, type ObserveOptions, ObserveTimeoutError, type OpenAIClientOptions, Page, PageNotFoundError, Response$1 as Response, ResponseBodyError, type ResponseInputItem, type ResponseItem, ResponseParseError, V3 as Stagehand, StagehandAPIError, StagehandAPIUnauthorizedError, StagehandClickError, StagehandDefaultError, StagehandDomProcessError, StagehandElementNotFoundError, StagehandEnvironmentError, StagehandError, StagehandEvalError, StagehandHttpError, StagehandIframeError, StagehandInitError, StagehandInvalidArgumentError, type StagehandMetrics, StagehandMissingArgumentError, StagehandNotInitializedError, StagehandResponseBodyError, StagehandResponseParseError, StagehandServerError, StagehandShadowRootMissingError, StagehandShadowSegmentEmptyError, StagehandShadowSegmentNotFoundError, type StagehandZodObject, type StagehandZodSchema, type StreamingAgentInstance, StreamingCallbacksInNonStreamingModeError, TimeoutError, type ToolUseItem, UnsupportedAISDKModelProviderError, UnsupportedModelError, UnsupportedModelProviderError, V3, type V3Env, V3Evaluator, V3FunctionName, type V3Options, XPathResolutionError, ZodSchemaValidationError, connectToMCPServer, defaultExtractSchema, getZodType, injectUrls, isRunningInBun, isZod3Schema, isZod4Schema, jsonSchemaToZod, loadApiKeyFromEnv, modelToAgentProviderMap, pageTextSchema, providerEnvVarMap, toGeminiSchema, toJsonSchema, transformSchema, trimTrailingTextNode, validateZodSchema };
2460
+ export { type AISDKCustomProvider, type AISDKProvider, AISdkClient, AVAILABLE_CUA_MODELS, type ActOptions, type ActResult, ActTimeoutError, type Action, type ActionExecutionResult, AgentAbortError, type AgentAction, type AgentCallbacks, type AgentConfig, type AgentContext, type AgentExecuteCallbacks, type AgentExecuteOptions, type AgentExecuteOptionsBase, type AgentExecutionOptions, type AgentHandlerOptions, type AgentInstance, type AgentModelConfig, AgentProvider, type AgentProviderType, type AgentResult, AgentScreenshotProviderError, type AgentState, type AgentStreamCallbacks, type AgentStreamExecuteOptions, type AgentStreamResult, type AgentType, AnnotatedScreenshotText, type AnthropicClientOptions, type AnthropicContentBlock, type AnthropicJsonSchemaObject, type AnthropicMessage, type AnthropicTextBlock, type AnthropicToolResult, type AnyPage, type AvailableCuaModel, type AvailableModel, BrowserbaseSessionNotFoundError, CaptchaTimeoutError, type ChatCompletionOptions, type ChatMessage, type ChatMessageContent, type ChatMessageImageContent, type ChatMessageTextContent, type ClientOptions, type ComputerCallItem, ConnectionTimeoutError, type ConsoleListener, ConsoleMessage, ContentFrameNotFoundError, type CreateChatCompletionOptions, CreateChatCompletionResponseError, CuaModelRequiredError, ElementNotVisibleError, ExperimentalApiConflictError, ExperimentalNotConfiguredError, type ExtractOptions, type ExtractResult, ExtractTimeoutError, type FunctionCallItem, type GoogleServiceAccountCredentials, type GoogleVertexProviderSettings, HandlerNotInitializedError, type HistoryEntry, type InferStagehandSchema, InvalidAISDKModelFormatError, type JsonSchema, type JsonSchemaDocument, type JsonSchemaProperty, LLMClient, type LLMParsedResponse, type LLMResponse, LLMResponseError, type LLMTool, type LLMUsage, LOG_LEVEL_NAMES, type LoadState, type LocalBrowserLaunchOptions, type LogLevel, type LogLine, type Logger, MCPConnectionError, MissingEnvironmentVariableError, MissingLLMConfigurationError, type ModelConfiguration, type ModelProvider, type NonStreamingAgentInstance, type ObserveOptions, ObserveTimeoutError, type OpenAIClientOptions, Page, PageNotFoundError, Response$1 as Response, ResponseBodyError, type ResponseInputItem, type ResponseItem, ResponseParseError, V3 as Stagehand, StagehandAPIError, StagehandAPIUnauthorizedError, StagehandClickError, StagehandDefaultError, StagehandDomProcessError, StagehandElementNotFoundError, StagehandEnvironmentError, StagehandError, StagehandEvalError, StagehandHttpError, StagehandIframeError, StagehandInitError, StagehandInvalidArgumentError, type StagehandMetrics, StagehandMissingArgumentError, StagehandNotInitializedError, StagehandResponseBodyError, StagehandResponseParseError, StagehandServerError, StagehandShadowRootMissingError, StagehandShadowSegmentEmptyError, StagehandShadowSegmentNotFoundError, type StagehandZodObject, type StagehandZodSchema, type StreamingAgentInstance, StreamingCallbacksInNonStreamingModeError, TimeoutError, type ToolUseItem, UnsupportedAISDKModelProviderError, UnsupportedModelError, UnsupportedModelProviderError, V3, type V3Env, V3Evaluator, V3FunctionName, type V3Options, XPathResolutionError, ZodSchemaValidationError, connectToMCPServer, defaultExtractSchema, getZodType, injectUrls, isRunningInBun, isZod3Schema, isZod4Schema, jsonSchemaToZod, loadApiKeyFromEnv, modelToAgentProviderMap, pageTextSchema, providerEnvVarMap, toGeminiSchema, toJsonSchema, transformSchema, trimTrailingTextNode, validateZodSchema };
package/dist/index.js CHANGED
@@ -179,12 +179,12 @@ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")])
179
179
  var STAGEHAND_VERSION;
180
180
  var init_version = __esm({
181
181
  "lib/version.ts"() {
182
- STAGEHAND_VERSION = "3.0.6-alpha-75f87f1920021a012fe0159123d01404969a94c8";
182
+ STAGEHAND_VERSION = "3.0.6-alpha-943d2d79d0f289ac41c9164578f2f1dd876058f2";
183
183
  }
184
184
  });
185
185
 
186
186
  // lib/v3/types/public/sdkErrors.ts
187
- var StagehandError, StagehandDefaultError, StagehandEnvironmentError, MissingEnvironmentVariableError, UnsupportedModelError, UnsupportedModelProviderError, UnsupportedAISDKModelProviderError, InvalidAISDKModelFormatError, StagehandNotInitializedError, BrowserbaseSessionNotFoundError, CaptchaTimeoutError, MissingLLMConfigurationError, HandlerNotInitializedError, StagehandInvalidArgumentError, StagehandElementNotFoundError, AgentScreenshotProviderError, StagehandMissingArgumentError, CreateChatCompletionResponseError, StagehandEvalError, StagehandDomProcessError, StagehandClickError, LLMResponseError, StagehandIframeError, ContentFrameNotFoundError, XPathResolutionError, ExperimentalApiConflictError, ExperimentalNotConfiguredError, CuaModelRequiredError, ZodSchemaValidationError, StagehandInitError, MCPConnectionError, StagehandShadowRootMissingError, StagehandShadowSegmentEmptyError, StagehandShadowSegmentNotFoundError, ElementNotVisibleError, ResponseBodyError, ResponseParseError, TimeoutError, ActTimeoutError, ExtractTimeoutError, ObserveTimeoutError, PageNotFoundError, ConnectionTimeoutError, StreamingCallbacksInNonStreamingModeError;
187
+ var StagehandError, StagehandDefaultError, StagehandEnvironmentError, MissingEnvironmentVariableError, UnsupportedModelError, UnsupportedModelProviderError, UnsupportedAISDKModelProviderError, InvalidAISDKModelFormatError, StagehandNotInitializedError, BrowserbaseSessionNotFoundError, CaptchaTimeoutError, MissingLLMConfigurationError, HandlerNotInitializedError, StagehandInvalidArgumentError, StagehandElementNotFoundError, AgentScreenshotProviderError, StagehandMissingArgumentError, CreateChatCompletionResponseError, StagehandEvalError, StagehandDomProcessError, StagehandClickError, LLMResponseError, StagehandIframeError, ContentFrameNotFoundError, XPathResolutionError, ExperimentalApiConflictError, ExperimentalNotConfiguredError, CuaModelRequiredError, ZodSchemaValidationError, StagehandInitError, MCPConnectionError, StagehandShadowRootMissingError, StagehandShadowSegmentEmptyError, StagehandShadowSegmentNotFoundError, ElementNotVisibleError, ResponseBodyError, ResponseParseError, TimeoutError, ActTimeoutError, ExtractTimeoutError, ObserveTimeoutError, PageNotFoundError, ConnectionTimeoutError, StreamingCallbacksInNonStreamingModeError, AgentAbortError;
188
188
  var init_sdkErrors = __esm({
189
189
  "lib/v3/types/public/sdkErrors.ts"() {
190
190
  init_version();
@@ -470,6 +470,13 @@ ${JSON.stringify(issues, null, 2)}`);
470
470
  this.invalidCallbacks = invalidCallbacks;
471
471
  }
472
472
  };
473
+ AgentAbortError = class extends StagehandError {
474
+ constructor(reason) {
475
+ const message = reason ? `Agent execution was aborted: ${reason}` : "Agent execution was aborted";
476
+ super(message);
477
+ this.reason = reason || "aborted";
478
+ }
479
+ };
473
480
  }
474
481
  });
475
482
 
@@ -26780,6 +26787,7 @@ __export(v3_exports, {
26780
26787
  AISdkClient: () => AISdkClient2,
26781
26788
  AVAILABLE_CUA_MODELS: () => AVAILABLE_CUA_MODELS,
26782
26789
  ActTimeoutError: () => ActTimeoutError,
26790
+ AgentAbortError: () => AgentAbortError,
26783
26791
  AgentProvider: () => AgentProvider,
26784
26792
  AgentScreenshotProviderError: () => AgentScreenshotProviderError,
26785
26793
  AnnotatedScreenshotText: () => AnnotatedScreenshotText,
@@ -31105,6 +31113,9 @@ function createStandardAction(toolCallName, toolResult, args, reasoning) {
31105
31113
 
31106
31114
  // lib/v3/handlers/v3AgentHandler.ts
31107
31115
  init_sdkErrors();
31116
+ function getErrorMessage(error) {
31117
+ return error instanceof Error ? error.message : String(error);
31118
+ }
31108
31119
  var V3AgentHandler = class {
31109
31120
  constructor(v3, logger, llmClient, executionModel, systemInstructions, mcpTools) {
31110
31121
  this.v3 = v3;
@@ -31116,7 +31127,7 @@ var V3AgentHandler = class {
31116
31127
  }
31117
31128
  prepareAgent(instructionOrOptions) {
31118
31129
  return __async(this, null, function* () {
31119
- var _a4;
31130
+ var _a4, _b;
31120
31131
  try {
31121
31132
  const options = typeof instructionOrOptions === "string" ? { instruction: instructionOrOptions } : instructionOrOptions;
31122
31133
  const maxSteps = options.maxSteps || 20;
@@ -31126,10 +31137,8 @@ var V3AgentHandler = class {
31126
31137
  );
31127
31138
  const tools = this.createTools();
31128
31139
  const allTools = __spreadValues(__spreadValues({}, tools), this.mcpTools);
31129
- const messages = [
31130
- { role: "user", content: options.instruction }
31131
- ];
31132
- if (!((_a4 = this.llmClient) == null ? void 0 : _a4.getLanguageModel)) {
31140
+ const messages = ((_a4 = options.messages) == null ? void 0 : _a4.length) ? [...options.messages, { role: "user", content: options.instruction }] : [{ role: "user", content: options.instruction }];
31141
+ if (!((_b = this.llmClient) == null ? void 0 : _b.getLanguageModel)) {
31133
31142
  throw new MissingLLMConfigurationError();
31134
31143
  }
31135
31144
  const baseModel = this.llmClient.getLanguageModel();
@@ -31212,39 +31221,43 @@ var V3AgentHandler = class {
31212
31221
  }
31213
31222
  execute(instructionOrOptions) {
31214
31223
  return __async(this, null, function* () {
31215
- var _a4;
31216
31224
  const startTime = Date.now();
31217
- const {
31218
- maxSteps,
31219
- systemPrompt,
31220
- allTools,
31221
- messages,
31222
- wrappedModel,
31223
- initialPageUrl
31224
- } = yield this.prepareAgent(instructionOrOptions);
31225
- const callbacks = instructionOrOptions.callbacks;
31226
- if (callbacks) {
31227
- const streamingOnlyCallbacks = [
31228
- "onChunk",
31229
- "onFinish",
31230
- "onError",
31231
- "onAbort"
31232
- ];
31233
- const invalidCallbacks = streamingOnlyCallbacks.filter(
31234
- (name) => callbacks[name] != null
31235
- );
31236
- if (invalidCallbacks.length > 0) {
31237
- throw new StreamingCallbacksInNonStreamingModeError(invalidCallbacks);
31238
- }
31239
- }
31225
+ const signal = typeof instructionOrOptions === "object" ? instructionOrOptions.signal : void 0;
31240
31226
  const state = {
31241
31227
  collectedReasoning: [],
31242
31228
  actions: [],
31243
31229
  finalMessage: "",
31244
31230
  completed: false,
31245
- currentPageUrl: initialPageUrl
31231
+ currentPageUrl: ""
31246
31232
  };
31233
+ let messages = [];
31247
31234
  try {
31235
+ const {
31236
+ options,
31237
+ maxSteps,
31238
+ systemPrompt,
31239
+ allTools,
31240
+ messages: preparedMessages,
31241
+ wrappedModel,
31242
+ initialPageUrl
31243
+ } = yield this.prepareAgent(instructionOrOptions);
31244
+ messages = preparedMessages;
31245
+ state.currentPageUrl = initialPageUrl;
31246
+ const callbacks = instructionOrOptions.callbacks;
31247
+ if (callbacks) {
31248
+ const streamingOnlyCallbacks = [
31249
+ "onChunk",
31250
+ "onFinish",
31251
+ "onError",
31252
+ "onAbort"
31253
+ ];
31254
+ const invalidCallbacks = streamingOnlyCallbacks.filter(
31255
+ (name) => callbacks[name] != null
31256
+ );
31257
+ if (invalidCallbacks.length > 0) {
31258
+ throw new StreamingCallbacksInNonStreamingModeError(invalidCallbacks);
31259
+ }
31260
+ }
31248
31261
  const result = yield this.llmClient.generateText({
31249
31262
  model: wrappedModel,
31250
31263
  system: systemPrompt,
@@ -31254,11 +31267,24 @@ var V3AgentHandler = class {
31254
31267
  temperature: 1,
31255
31268
  toolChoice: "auto",
31256
31269
  prepareStep: callbacks == null ? void 0 : callbacks.prepareStep,
31257
- onStepFinish: this.createStepHandler(state, callbacks == null ? void 0 : callbacks.onStepFinish)
31270
+ onStepFinish: this.createStepHandler(state, callbacks == null ? void 0 : callbacks.onStepFinish),
31271
+ abortSignal: options.signal
31258
31272
  });
31259
- return this.consolidateMetricsAndResult(startTime, state, result);
31273
+ return this.consolidateMetricsAndResult(
31274
+ startTime,
31275
+ state,
31276
+ messages,
31277
+ result
31278
+ );
31260
31279
  } catch (error) {
31261
- const errorMessage = (_a4 = error == null ? void 0 : error.message) != null ? _a4 : String(error);
31280
+ if (error instanceof StreamingCallbacksInNonStreamingModeError) {
31281
+ throw error;
31282
+ }
31283
+ if (signal == null ? void 0 : signal.aborted) {
31284
+ const reason = signal.reason ? String(signal.reason) : "aborted";
31285
+ throw new AgentAbortError(reason);
31286
+ }
31287
+ const errorMessage = getErrorMessage(error);
31262
31288
  this.logger({
31263
31289
  category: "agent",
31264
31290
  message: `Error executing agent task: ${errorMessage}`,
@@ -31268,7 +31294,8 @@ var V3AgentHandler = class {
31268
31294
  success: false,
31269
31295
  actions: state.actions,
31270
31296
  message: `Failed to execute task: ${errorMessage}`,
31271
- completed: false
31297
+ completed: false,
31298
+ messages
31272
31299
  };
31273
31300
  }
31274
31301
  });
@@ -31276,6 +31303,7 @@ var V3AgentHandler = class {
31276
31303
  stream(instructionOrOptions) {
31277
31304
  return __async(this, null, function* () {
31278
31305
  const {
31306
+ options,
31279
31307
  maxSteps,
31280
31308
  systemPrompt,
31281
31309
  allTools,
@@ -31328,24 +31356,31 @@ var V3AgentHandler = class {
31328
31356
  if (callbacks == null ? void 0 : callbacks.onFinish) {
31329
31357
  callbacks.onFinish(event);
31330
31358
  }
31331
- try {
31332
- const result = this.consolidateMetricsAndResult(
31333
- startTime,
31334
- state,
31335
- event
31336
- );
31337
- resolveResult(result);
31338
- } catch (error) {
31339
- handleError(error);
31359
+ const result = this.consolidateMetricsAndResult(
31360
+ startTime,
31361
+ state,
31362
+ messages,
31363
+ event
31364
+ );
31365
+ resolveResult(result);
31366
+ },
31367
+ onAbort: (event) => {
31368
+ var _a4;
31369
+ if (callbacks == null ? void 0 : callbacks.onAbort) {
31370
+ callbacks.onAbort(event);
31340
31371
  }
31341
- }
31372
+ const reason = ((_a4 = options.signal) == null ? void 0 : _a4.reason) ? String(options.signal.reason) : "Stream was aborted";
31373
+ rejectResult(new AgentAbortError(reason));
31374
+ },
31375
+ abortSignal: options.signal
31342
31376
  });
31343
31377
  const agentStreamResult = streamResult;
31344
31378
  agentStreamResult.result = resultPromise;
31345
31379
  return agentStreamResult;
31346
31380
  });
31347
31381
  }
31348
- consolidateMetricsAndResult(startTime, state, result) {
31382
+ consolidateMetricsAndResult(startTime, state, inputMessages, result) {
31383
+ var _a4;
31349
31384
  if (!state.finalMessage) {
31350
31385
  const allReasoning = state.collectedReasoning.join(" ").trim();
31351
31386
  state.finalMessage = allReasoning || result.text || "";
@@ -31362,6 +31397,11 @@ var V3AgentHandler = class {
31362
31397
  inferenceTimeMs
31363
31398
  );
31364
31399
  }
31400
+ const responseMessages = ((_a4 = result.response) == null ? void 0 : _a4.messages) || [];
31401
+ const fullMessages = [
31402
+ ...inputMessages,
31403
+ ...responseMessages
31404
+ ];
31365
31405
  return {
31366
31406
  success: state.completed,
31367
31407
  message: state.finalMessage || "Task execution completed",
@@ -31373,7 +31413,8 @@ var V3AgentHandler = class {
31373
31413
  reasoning_tokens: result.usage.reasoningTokens || 0,
31374
31414
  cached_input_tokens: result.usage.cachedInputTokens || 0,
31375
31415
  inference_time_ms: inferenceTimeMs
31376
- } : void 0
31416
+ } : void 0,
31417
+ messages: fullMessages
31377
31418
  };
31378
31419
  }
31379
31420
  buildSystemPrompt(executionInstruction, systemInstructions) {
@@ -64036,6 +64077,53 @@ var StagehandAPIClient = class {
64036
64077
  }
64037
64078
  };
64038
64079
 
64080
+ // lib/v3/agent/utils/validateExperimentalFeatures.ts
64081
+ init_sdkErrors();
64082
+ function validateExperimentalFeatures(options) {
64083
+ const { isExperimental, agentConfig, executeOptions, isStreaming } = options;
64084
+ if (agentConfig == null ? void 0 : agentConfig.cua) {
64085
+ const unsupportedFeatures = [];
64086
+ if (agentConfig == null ? void 0 : agentConfig.stream) {
64087
+ unsupportedFeatures.push("streaming");
64088
+ }
64089
+ if (executeOptions == null ? void 0 : executeOptions.signal) {
64090
+ unsupportedFeatures.push("abort signal");
64091
+ }
64092
+ if (executeOptions == null ? void 0 : executeOptions.messages) {
64093
+ unsupportedFeatures.push("message continuation");
64094
+ }
64095
+ if (unsupportedFeatures.length > 0) {
64096
+ throw new StagehandInvalidArgumentError(
64097
+ `${unsupportedFeatures.join(", ")} ${unsupportedFeatures.length === 1 ? "is" : "are"} not supported with CUA (Computer Use Agent) mode.`
64098
+ );
64099
+ }
64100
+ }
64101
+ if (isExperimental) return;
64102
+ const features = [];
64103
+ const hasIntegrations = (agentConfig == null ? void 0 : agentConfig.integrations) && agentConfig.integrations.length > 0;
64104
+ const hasTools = (agentConfig == null ? void 0 : agentConfig.tools) && Object.keys(agentConfig.tools).length > 0;
64105
+ if (hasIntegrations || hasTools) {
64106
+ features.push("MCP integrations and custom tools");
64107
+ }
64108
+ if (!(agentConfig == null ? void 0 : agentConfig.cua) && (isStreaming || (agentConfig == null ? void 0 : agentConfig.stream))) {
64109
+ features.push("streaming");
64110
+ }
64111
+ if (executeOptions && !(agentConfig == null ? void 0 : agentConfig.cua)) {
64112
+ if (executeOptions.callbacks) {
64113
+ features.push("callbacks");
64114
+ }
64115
+ if (executeOptions.signal) {
64116
+ features.push("abort signal");
64117
+ }
64118
+ if (executeOptions.messages) {
64119
+ features.push("message continuation");
64120
+ }
64121
+ }
64122
+ if (features.length > 0) {
64123
+ throw new ExperimentalNotConfiguredError(`Agent ${features.join(", ")}`);
64124
+ }
64125
+ }
64126
+
64039
64127
  // lib/v3/v3.ts
64040
64128
  init_flowLogger();
64041
64129
  init_sdkErrors();
@@ -65166,11 +65254,6 @@ var _V3 = class _V3 {
65166
65254
  prepareAgentExecution(options, instructionOrOptions, agentConfigSignature) {
65167
65255
  return __async(this, null, function* () {
65168
65256
  var _a4, _b;
65169
- if (((options == null ? void 0 : options.integrations) || (options == null ? void 0 : options.tools)) && !this.experimental) {
65170
- throw new ExperimentalNotConfiguredError(
65171
- "MCP integrations and custom tools"
65172
- );
65173
- }
65174
65257
  const tools = (options == null ? void 0 : options.integrations) ? yield resolveTools(options.integrations, options.tools) : (_a4 = options == null ? void 0 : options.tools) != null ? _a4 : {};
65175
65258
  const agentLlmClient = (options == null ? void 0 : options.model) ? this.resolveLlmClient(options.model) : this.llmClient;
65176
65259
  const handler = new V3AgentHandler(
@@ -65216,16 +65299,10 @@ var _V3 = class _V3 {
65216
65299
  })
65217
65300
  });
65218
65301
  if (options == null ? void 0 : options.cua) {
65219
- if (options == null ? void 0 : options.stream) {
65220
- throw new StagehandInvalidArgumentError(
65221
- "Streaming is not supported with CUA (Computer Use Agent) mode. Remove either 'stream: true' or 'cua: true' from your agent config."
65222
- );
65223
- }
65224
- if (((options == null ? void 0 : options.integrations) || (options == null ? void 0 : options.tools)) && !this.experimental) {
65225
- throw new ExperimentalNotConfiguredError(
65226
- "MCP integrations and custom tools"
65227
- );
65228
- }
65302
+ validateExperimentalFeatures({
65303
+ isExperimental: this.experimental,
65304
+ agentConfig: options
65305
+ });
65229
65306
  const modelToUse = (options == null ? void 0 : options.model) || __spreadValues({
65230
65307
  modelName: this.modelName
65231
65308
  }, this.modelClientOptions);
@@ -65238,13 +65315,15 @@ var _V3 = class _V3 {
65238
65315
  execute: (instructionOrOptions) => __async(this, null, function* () {
65239
65316
  return withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
65240
65317
  var _a5, _b2;
65318
+ validateExperimentalFeatures({
65319
+ isExperimental: this.experimental,
65320
+ agentConfig: options,
65321
+ executeOptions: typeof instructionOrOptions === "object" ? instructionOrOptions : null
65322
+ });
65241
65323
  SessionFileLogger.logAgentTaskStarted({
65242
65324
  invocation: "Agent.execute",
65243
65325
  args: [instructionOrOptions]
65244
65326
  });
65245
- if ((options == null ? void 0 : options.integrations) && !this.experimental) {
65246
- throw new ExperimentalNotConfiguredError("MCP integrations");
65247
- }
65248
65327
  const tools = (options == null ? void 0 : options.integrations) ? yield resolveTools(options.integrations, options.tools) : (_a5 = options == null ? void 0 : options.tools) != null ? _a5 : {};
65249
65328
  const handler = new V3CuaAgentHandler(
65250
65329
  this,
@@ -65325,18 +65404,18 @@ Do not ask follow up questions, the user will trust your judgement.`
65325
65404
  return {
65326
65405
  execute: (instructionOrOptions) => __async(this, null, function* () {
65327
65406
  return withInstanceLogContext(this.instanceId, () => __async(this, null, function* () {
65407
+ validateExperimentalFeatures({
65408
+ isExperimental: this.experimental,
65409
+ agentConfig: options,
65410
+ executeOptions: typeof instructionOrOptions === "object" ? instructionOrOptions : null,
65411
+ isStreaming
65412
+ });
65328
65413
  SessionFileLogger.logAgentTaskStarted({
65329
65414
  invocation: "Agent.execute",
65330
65415
  args: [instructionOrOptions]
65331
65416
  });
65332
- if (typeof instructionOrOptions === "object" && instructionOrOptions.callbacks && !this.experimental) {
65333
- throw new ExperimentalNotConfiguredError("Agent callbacks");
65334
- }
65335
65417
  if (isStreaming) {
65336
- if (!this.experimental) {
65337
- throw new ExperimentalNotConfiguredError("Agent streaming");
65338
- }
65339
- const { handler: handler2, cacheContext: cacheContext2 } = yield this.prepareAgentExecution(
65418
+ const { handler: handler2, resolvedOptions: resolvedOptions2, cacheContext: cacheContext2 } = yield this.prepareAgentExecution(
65340
65419
  options,
65341
65420
  instructionOrOptions,
65342
65421
  agentConfigSignature
@@ -65349,7 +65428,7 @@ Do not ask follow up questions, the user will trust your judgement.`
65349
65428
  }
65350
65429
  }
65351
65430
  const streamResult = yield handler2.stream(
65352
- instructionOrOptions
65431
+ resolvedOptions2
65353
65432
  );
65354
65433
  if (cacheContext2) {
65355
65434
  const wrappedStream = this.agentCache.wrapStreamForCaching(
@@ -65393,7 +65472,7 @@ Do not ask follow up questions, the user will trust your judgement.`
65393
65472
  );
65394
65473
  } else {
65395
65474
  result = yield handler.execute(
65396
- instructionOrOptions
65475
+ resolvedOptions
65397
65476
  );
65398
65477
  }
65399
65478
  if (recording) {
@@ -65669,6 +65748,7 @@ I'm providing ${screenshots.length} screenshots showing the progression of the t
65669
65748
  AISdkClient,
65670
65749
  AVAILABLE_CUA_MODELS,
65671
65750
  ActTimeoutError,
65751
+ AgentAbortError,
65672
65752
  AgentProvider,
65673
65753
  AgentScreenshotProviderError,
65674
65754
  AnnotatedScreenshotText,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@browserbasehq/stagehand",
3
- "version": "3.0.6-alpha-75f87f1920021a012fe0159123d01404969a94c8",
3
+ "version": "3.0.6-alpha-943d2d79d0f289ac41c9164578f2f1dd876058f2",
4
4
  "description": "An AI web browsing framework focused on simplicity and extensibility.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",