@browserbasehq/orca 3.2.0-preview.2 → 3.2.0-preview.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/cjs/lib/utils.d.ts +0 -1
  2. package/dist/cjs/lib/utils.js +0 -4
  3. package/dist/cjs/lib/utils.js.map +1 -1
  4. package/dist/cjs/lib/v3/agent/AnthropicCUAClient.js +6 -4
  5. package/dist/cjs/lib/v3/agent/AnthropicCUAClient.js.map +1 -1
  6. package/dist/cjs/lib/v3/agent/GoogleCUAClient.js +6 -4
  7. package/dist/cjs/lib/v3/agent/GoogleCUAClient.js.map +1 -1
  8. package/dist/cjs/lib/v3/agent/OpenAICUAClient.js +6 -4
  9. package/dist/cjs/lib/v3/agent/OpenAICUAClient.js.map +1 -1
  10. package/dist/cjs/lib/v3/flowLogger.d.ts +103 -62
  11. package/dist/cjs/lib/v3/flowLogger.js +773 -362
  12. package/dist/cjs/lib/v3/flowLogger.js.map +1 -1
  13. package/dist/cjs/lib/v3/handlers/handlerUtils/actHandlerUtils.js +33 -21
  14. package/dist/cjs/lib/v3/handlers/handlerUtils/actHandlerUtils.js.map +1 -1
  15. package/dist/cjs/lib/v3/handlers/v3AgentHandler.d.ts +4 -0
  16. package/dist/cjs/lib/v3/handlers/v3AgentHandler.js +31 -1
  17. package/dist/cjs/lib/v3/handlers/v3AgentHandler.js.map +1 -1
  18. package/dist/cjs/lib/v3/handlers/v3CuaAgentHandler.js +12 -10
  19. package/dist/cjs/lib/v3/handlers/v3CuaAgentHandler.js.map +1 -1
  20. package/dist/cjs/lib/v3/llm/aisdk.js +16 -10
  21. package/dist/cjs/lib/v3/llm/aisdk.js.map +1 -1
  22. package/dist/cjs/lib/v3/types/public/options.d.ts +0 -5
  23. package/dist/cjs/lib/v3/types/public/options.js.map +1 -1
  24. package/dist/cjs/lib/v3/understudy/cdp.d.ts +12 -3
  25. package/dist/cjs/lib/v3/understudy/cdp.js +10 -83
  26. package/dist/cjs/lib/v3/understudy/cdp.js.map +1 -1
  27. package/dist/cjs/lib/v3/understudy/page.js +17 -32
  28. package/dist/cjs/lib/v3/understudy/page.js.map +1 -1
  29. package/dist/cjs/lib/v3/v3.d.ts +0 -5
  30. package/dist/cjs/lib/v3/v3.js +157 -174
  31. package/dist/cjs/lib/v3/v3.js.map +1 -1
  32. package/dist/esm/lib/utils.d.ts +0 -1
  33. package/dist/esm/lib/utils.js +0 -3
  34. package/dist/esm/lib/utils.js.map +1 -1
  35. package/dist/esm/lib/v3/agent/AnthropicCUAClient.js +7 -5
  36. package/dist/esm/lib/v3/agent/AnthropicCUAClient.js.map +1 -1
  37. package/dist/esm/lib/v3/agent/GoogleCUAClient.js +7 -5
  38. package/dist/esm/lib/v3/agent/GoogleCUAClient.js.map +1 -1
  39. package/dist/esm/lib/v3/agent/OpenAICUAClient.js +7 -5
  40. package/dist/esm/lib/v3/agent/OpenAICUAClient.js.map +1 -1
  41. package/dist/esm/lib/v3/flowLogger.d.ts +103 -62
  42. package/dist/esm/lib/v3/flowLogger.js +762 -356
  43. package/dist/esm/lib/v3/flowLogger.js.map +1 -1
  44. package/dist/esm/lib/v3/handlers/handlerUtils/actHandlerUtils.js +34 -22
  45. package/dist/esm/lib/v3/handlers/handlerUtils/actHandlerUtils.js.map +1 -1
  46. package/dist/esm/lib/v3/handlers/v3AgentHandler.d.ts +4 -0
  47. package/dist/esm/lib/v3/handlers/v3AgentHandler.js +32 -2
  48. package/dist/esm/lib/v3/handlers/v3AgentHandler.js.map +1 -1
  49. package/dist/esm/lib/v3/handlers/v3CuaAgentHandler.js +13 -11
  50. package/dist/esm/lib/v3/handlers/v3CuaAgentHandler.js.map +1 -1
  51. package/dist/esm/lib/v3/llm/aisdk.js +17 -11
  52. package/dist/esm/lib/v3/llm/aisdk.js.map +1 -1
  53. package/dist/esm/lib/v3/types/public/options.d.ts +0 -5
  54. package/dist/esm/lib/v3/types/public/options.js.map +1 -1
  55. package/dist/esm/lib/v3/understudy/cdp.d.ts +12 -3
  56. package/dist/esm/lib/v3/understudy/cdp.js +10 -83
  57. package/dist/esm/lib/v3/understudy/cdp.js.map +1 -1
  58. package/dist/esm/lib/v3/understudy/page.js +18 -33
  59. package/dist/esm/lib/v3/understudy/page.js.map +1 -1
  60. package/dist/esm/lib/v3/v3.d.ts +0 -5
  61. package/dist/esm/lib/v3/v3.js +158 -175
  62. package/dist/esm/lib/v3/v3.js.map +1 -1
  63. package/package.json +1 -1
  64. package/dist/cjs/lib/v3/eventStore.d.ts +0 -41
  65. package/dist/cjs/lib/v3/eventStore.js +0 -375
  66. package/dist/cjs/lib/v3/eventStore.js.map +0 -1
  67. package/dist/esm/lib/v3/eventStore.d.ts +0 -41
  68. package/dist/esm/lib/v3/eventStore.js +0 -363
  69. package/dist/esm/lib/v3/eventStore.js.map +0 -1
@@ -5,7 +5,6 @@ import { LLMClient } from "./llm/LLMClient.js";
5
5
  import { AgentReplayStep } from "./types/private/index.js";
6
6
  import { AgentConfig, AgentExecuteOptions, AgentStreamExecuteOptions, AgentResult, LogLine, StagehandMetrics, Action, ActOptions, ActResult, defaultExtractSchema, ExtractOptions, HistoryEntry, ObserveOptions, pageTextSchema, V3FunctionName, V3Options, AgentStreamResult } from "./types/public/index.js";
7
7
  import { V3Context } from "./understudy/context.js";
8
- import { type FlowLoggerContext } from "./flowLogger.js";
9
8
  /**
10
9
  * V3
11
10
  *
@@ -71,8 +70,6 @@ export declare class V3 {
71
70
  private stagehandLogger;
72
71
  private _history;
73
72
  private readonly instanceId;
74
- private readonly sessionId;
75
- readonly flowLoggerContext: FlowLoggerContext;
76
73
  private static _processGuardsInstalled;
77
74
  private static _instances;
78
75
  private cacheStorage;
@@ -81,8 +78,6 @@ export declare class V3 {
81
78
  private apiClient;
82
79
  private keepAlive?;
83
80
  private shutdownSupervisor;
84
- private detachEventStoreListener;
85
- private withLoggingContext;
86
81
  stagehandMetrics: StagehandMetrics;
87
82
  constructor(opts: V3Options);
88
83
  /**
@@ -103,7 +103,6 @@ const api_js_1 = require("./api.js");
103
103
  const validateExperimentalFeatures_js_1 = require("./agent/utils/validateExperimentalFeatures.js");
104
104
  const variables_js_1 = require("./agent/utils/variables.js");
105
105
  const flowLogger_js_1 = require("./flowLogger.js");
106
- const eventStore_js_1 = require("./eventStore.js");
107
106
  const timeoutGuard_js_1 = require("./handlers/handlerUtils/timeoutGuard.js");
108
107
  const sdkErrors_js_1 = require("./types/public/sdkErrors.js");
109
108
  const DEFAULT_MODEL_NAME = "openai/gpt-4.1-mini";
@@ -151,18 +150,9 @@ let V3 = (() => {
151
150
  return class V3 {
152
151
  static {
153
152
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
154
- _act_decorators = [flowLogger_js_1.FlowLogger.wrapWithLogging({
155
- eventType: "StagehandAct",
156
- eventIdSuffix: "4",
157
- })];
158
- _extract_decorators = [flowLogger_js_1.FlowLogger.wrapWithLogging({
159
- eventType: "StagehandExtract",
160
- eventIdSuffix: "4",
161
- })];
162
- _observe_decorators = [flowLogger_js_1.FlowLogger.wrapWithLogging({
163
- eventType: "StagehandObserve",
164
- eventIdSuffix: "4",
165
- })];
153
+ _act_decorators = [(0, flowLogger_js_1.logStagehandStep)("Stagehand.act", "ACT")];
154
+ _extract_decorators = [(0, flowLogger_js_1.logStagehandStep)("Stagehand.extract", "EXTRACT")];
155
+ _observe_decorators = [(0, flowLogger_js_1.logStagehandStep)("Stagehand.observe", "OBSERVE")];
166
156
  __esDecorate(this, null, _act_decorators, { kind: "method", name: "act", static: false, private: false, access: { has: obj => "act" in obj, get: obj => obj.act }, metadata: _metadata }, null, _instanceExtraInitializers);
167
157
  __esDecorate(this, null, _extract_decorators, { kind: "method", name: "extract", static: false, private: false, access: { has: obj => "extract" in obj, get: obj => obj.extract }, metadata: _metadata }, null, _instanceExtraInitializers);
168
158
  __esDecorate(this, null, _observe_decorators, { kind: "method", name: "observe", static: false, private: false, access: { has: obj => "observe" in obj, get: obj => obj.observe }, metadata: _metadata }, null, _instanceExtraInitializers);
@@ -247,8 +237,6 @@ let V3 = (() => {
247
237
  stagehandLogger;
248
238
  _history = [];
249
239
  instanceId;
250
- sessionId;
251
- flowLoggerContext;
252
240
  static _processGuardsInstalled = false;
253
241
  static _instances = new Set();
254
242
  cacheStorage;
@@ -257,10 +245,6 @@ let V3 = (() => {
257
245
  apiClient = null;
258
246
  keepAlive;
259
247
  shutdownSupervisor = null;
260
- detachEventStoreListener = null;
261
- withLoggingContext(fn) {
262
- return (0, logger_js_2.withInstanceLogContext)(this.instanceId, fn);
263
- }
264
248
  stagehandMetrics = {
265
249
  actPromptTokens: 0,
266
250
  actCompletionTokens: 0,
@@ -292,7 +276,6 @@ let V3 = (() => {
292
276
  this.externalLogger = opts.logger;
293
277
  this.verbose = opts.verbose ?? 1;
294
278
  this.instanceId = (0, uuid_1.v7)();
295
- this.sessionId = opts.sessionId ?? this.instanceId;
296
279
  this.keepAlive =
297
280
  opts.keepAlive ?? opts.browserbaseSessionCreateParams?.keepAlive;
298
281
  // Create per-instance StagehandLogger (handles usePino, verbose, externalLogger)
@@ -385,9 +368,8 @@ let V3 = (() => {
385
368
  act: this.act.bind(this),
386
369
  });
387
370
  this.opts = opts;
388
- void (0, eventStore_js_1.getEventStore)().initializeSession(this.sessionId, opts);
389
- this.flowLoggerContext = flowLogger_js_1.FlowLogger.init(this.sessionId, this.bus);
390
- this.detachEventStoreListener = (0, eventStore_js_1.getEventStore)().attachBus(this.sessionId, this.bus);
371
+ // Initialize session file logger
372
+ flowLogger_js_1.SessionFileLogger.init(this.instanceId, opts);
391
373
  // Track instance for global process guard handling
392
374
  V3._instances.add(this);
393
375
  }
@@ -594,7 +576,7 @@ let V3 = (() => {
594
576
  */
595
577
  async init() {
596
578
  try {
597
- return await this.withLoggingContext(async () => {
579
+ return await (0, logger_js_2.withInstanceLogContext)(this.instanceId, async () => {
598
580
  this.actHandler = new actHandler_js_1.ActHandler(this.llmClient, this.modelName, this.modelClientOptions, (model) => this.resolveLlmClient(model), this.opts.systemPrompt ?? "", this.logInferenceToFile, this.opts.selfHeal ?? true, (functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) => this.updateMetrics(functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs), this.domSettleTimeoutMs);
599
581
  this.extractHandler = new extractHandler_js_1.ExtractHandler(this.llmClient, this.modelName, this.modelClientOptions, (model) => this.resolveLlmClient(model), this.opts.systemPrompt ?? "", this.logInferenceToFile, this.experimental, (functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) => this.updateMetrics(functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs));
600
582
  this.observeHandler = new observeHandler_js_1.ObserveHandler(this.llmClient, this.modelName, this.modelClientOptions, (model) => this.resolveLlmClient(model), this.opts.systemPrompt ?? "", this.logInferenceToFile, this.experimental, (functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) => this.updateMetrics(functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs));
@@ -628,7 +610,9 @@ let V3 = (() => {
628
610
  env: "LOCAL",
629
611
  cdpHeaders: lbo.cdpHeaders,
630
612
  });
631
- this.ctx.conn.flowLoggerContext = this.flowLoggerContext;
613
+ const logCtx = flowLogger_js_1.SessionFileLogger.getContext();
614
+ this.ctx.conn.cdpLogger = (info) => flowLogger_js_1.SessionFileLogger.logCdpCallEvent(info, logCtx);
615
+ this.ctx.conn.cdpEventLogger = (info) => flowLogger_js_1.SessionFileLogger.logCdpMessageEvent(info, logCtx);
632
616
  this.ctx.conn.onTransportClosed(this._onCdpClosed);
633
617
  this.state = {
634
618
  kind: "LOCAL",
@@ -724,7 +708,9 @@ let V3 = (() => {
724
708
  env: "LOCAL",
725
709
  localBrowserLaunchOptions: lbo,
726
710
  });
727
- this.ctx.conn.flowLoggerContext = this.flowLoggerContext;
711
+ const logCtx = flowLogger_js_1.SessionFileLogger.getContext();
712
+ this.ctx.conn.cdpLogger = (info) => flowLogger_js_1.SessionFileLogger.logCdpCallEvent(info, logCtx);
713
+ this.ctx.conn.cdpEventLogger = (info) => flowLogger_js_1.SessionFileLogger.logCdpMessageEvent(info, logCtx);
728
714
  this.ctx.conn.onTransportClosed(this._onCdpClosed);
729
715
  this.state = {
730
716
  kind: "LOCAL",
@@ -806,7 +792,9 @@ let V3 = (() => {
806
792
  env: "BROWSERBASE",
807
793
  apiClient: this.apiClient,
808
794
  });
809
- this.ctx.conn.flowLoggerContext = this.flowLoggerContext;
795
+ const logCtx = flowLogger_js_1.SessionFileLogger.getContext();
796
+ this.ctx.conn.cdpLogger = (info) => flowLogger_js_1.SessionFileLogger.logCdpCallEvent(info, logCtx);
797
+ this.ctx.conn.cdpEventLogger = (info) => flowLogger_js_1.SessionFileLogger.logCdpMessageEvent(info, logCtx);
810
798
  this.ctx.conn.onTransportClosed(this._onCdpClosed);
811
799
  this.state = { kind: "BROWSERBASE", sessionId, ws, bb };
812
800
  this.browserbaseSessionId = sessionId;
@@ -868,13 +856,6 @@ let V3 = (() => {
868
856
  // ignore cleanup errors
869
857
  }
870
858
  }
871
- try {
872
- this.detachEventStoreListener?.();
873
- this.detachEventStoreListener = null;
874
- }
875
- catch {
876
- // ignore cleanup errors
877
- }
878
859
  throw error;
879
860
  }
880
861
  }
@@ -918,7 +899,7 @@ let V3 = (() => {
918
899
  this.browserbaseDebugUrl = undefined;
919
900
  }
920
901
  async act(input, options) {
921
- return await this.withLoggingContext(async () => {
902
+ return await (0, logger_js_2.withInstanceLogContext)(this.instanceId, async () => {
922
903
  if (!this.actHandler)
923
904
  throw new index_js_1.StagehandNotInitializedError("act()");
924
905
  let actResult;
@@ -1002,7 +983,7 @@ let V3 = (() => {
1002
983
  });
1003
984
  }
1004
985
  async extract(a, b, c) {
1005
- return await this.withLoggingContext(async () => {
986
+ return await (0, logger_js_2.withInstanceLogContext)(this.instanceId, async () => {
1006
987
  if (!this.extractHandler) {
1007
988
  throw new index_js_1.StagehandNotInitializedError("extract()");
1008
989
  }
@@ -1070,7 +1051,7 @@ let V3 = (() => {
1070
1051
  });
1071
1052
  }
1072
1053
  async observe(a, b) {
1073
- return await this.withLoggingContext(async () => {
1054
+ return await (0, logger_js_2.withInstanceLogContext)(this.instanceId, async () => {
1074
1055
  if (!this.observeHandler) {
1075
1056
  throw new index_js_1.StagehandNotInitializedError("observe()");
1076
1057
  }
@@ -1156,7 +1137,7 @@ let V3 = (() => {
1156
1137
  try {
1157
1138
  // Close session file logger
1158
1139
  try {
1159
- await flowLogger_js_1.FlowLogger.close(this.flowLoggerContext);
1140
+ await flowLogger_js_1.SessionFileLogger.close();
1160
1141
  }
1161
1142
  catch {
1162
1143
  // ignore
@@ -1192,13 +1173,6 @@ let V3 = (() => {
1192
1173
  catch {
1193
1174
  // ignore
1194
1175
  }
1195
- try {
1196
- this.detachEventStoreListener?.();
1197
- this.detachEventStoreListener = null;
1198
- }
1199
- catch {
1200
- // ignore
1201
- }
1202
1176
  try {
1203
1177
  this.bus.removeAllListeners();
1204
1178
  }
@@ -1465,59 +1439,152 @@ let V3 = (() => {
1465
1439
  throw new index_js_1.CuaModelRequiredError(index_js_1.AVAILABLE_CUA_MODELS);
1466
1440
  }
1467
1441
  const agentConfigSignature = this.agentCache.buildConfigSignature(options);
1468
- const execute = flowLogger_js_1.FlowLogger.wrapWithLogging({
1469
- eventType: "AgentExecute",
1470
- eventIdSuffix: "3",
1471
- })(async (instructionOrOptions) => this.withLoggingContext(async () => {
1442
+ return {
1443
+ execute: async (instructionOrOptions) => (0, logger_js_2.withInstanceLogContext)(this.instanceId, async () => {
1444
+ (0, validateExperimentalFeatures_js_1.validateExperimentalFeatures)({
1445
+ isExperimental: this.experimental,
1446
+ agentConfig: options,
1447
+ executeOptions: typeof instructionOrOptions === "object"
1448
+ ? instructionOrOptions
1449
+ : null,
1450
+ });
1451
+ flowLogger_js_1.SessionFileLogger.logAgentTaskStarted({
1452
+ invocation: "Agent.execute",
1453
+ args: [instructionOrOptions],
1454
+ });
1455
+ const tools = options?.integrations
1456
+ ? await (0, utils_js_2.resolveTools)(options.integrations, options.tools)
1457
+ : (options?.tools ?? {});
1458
+ const handler = new v3CuaAgentHandler_js_1.V3CuaAgentHandler(this, this.logger, {
1459
+ modelName,
1460
+ clientOptions,
1461
+ userProvidedInstructions: options.systemPrompt ??
1462
+ `You are a helpful assistant that can use a web browser.\nDo not ask follow up questions, the user will trust your judgement.`,
1463
+ }, tools);
1464
+ const resolvedOptions = typeof instructionOrOptions === "string"
1465
+ ? {
1466
+ instruction: instructionOrOptions,
1467
+ toolTimeout: DEFAULT_AGENT_TOOL_TIMEOUT_MS,
1468
+ }
1469
+ : {
1470
+ ...instructionOrOptions,
1471
+ toolTimeout: instructionOrOptions.toolTimeout ??
1472
+ DEFAULT_AGENT_TOOL_TIMEOUT_MS,
1473
+ };
1474
+ if (resolvedOptions.page) {
1475
+ const normalizedPage = await this.normalizeToV3Page(resolvedOptions.page);
1476
+ this.ctx.setActivePage(normalizedPage);
1477
+ }
1478
+ const instruction = resolvedOptions.instruction.trim();
1479
+ const sanitizedOptions = this.agentCache.sanitizeExecuteOptions(resolvedOptions);
1480
+ const cacheVariables = (0, variables_js_1.flattenVariables)(resolvedOptions.variables);
1481
+ let cacheContext = null;
1482
+ if (this.agentCache.shouldAttemptCache(instruction)) {
1483
+ const startPage = await this.ctx.awaitActivePage();
1484
+ cacheContext = await this.agentCache.prepareContext({
1485
+ instruction,
1486
+ options: sanitizedOptions,
1487
+ configSignature: agentConfigSignature,
1488
+ page: startPage,
1489
+ variables: cacheVariables,
1490
+ });
1491
+ if (cacheContext) {
1492
+ const replayed = await this.agentCache.tryReplay(cacheContext);
1493
+ if (replayed) {
1494
+ flowLogger_js_1.SessionFileLogger.logAgentTaskCompleted({ cacheHit: true });
1495
+ return replayed;
1496
+ }
1497
+ }
1498
+ }
1499
+ let agentSteps = [];
1500
+ const shouldRecordLocally = !!cacheContext && (!this.apiClient || this.experimental);
1501
+ if (shouldRecordLocally) {
1502
+ this.beginAgentReplayRecording();
1503
+ }
1504
+ let result;
1505
+ try {
1506
+ if (this.apiClient && !this.experimental) {
1507
+ const page = await this.ctx.awaitActivePage();
1508
+ result = await this.apiClient.agentExecute(options, resolvedOptions, page.mainFrameId(), !!cacheContext);
1509
+ if (cacheContext) {
1510
+ const transferredEntry = this.apiClient.consumeLatestAgentCacheEntry();
1511
+ await this.agentCache.storeTransferredEntry(transferredEntry);
1512
+ }
1513
+ }
1514
+ else {
1515
+ result = await handler.execute(instructionOrOptions);
1516
+ }
1517
+ if (shouldRecordLocally) {
1518
+ agentSteps = this.endAgentReplayRecording();
1519
+ }
1520
+ if (shouldRecordLocally &&
1521
+ cacheContext &&
1522
+ result.success &&
1523
+ agentSteps.length > 0) {
1524
+ await this.agentCache.store(cacheContext, agentSteps, result);
1525
+ }
1526
+ return result;
1527
+ }
1528
+ catch (err) {
1529
+ if (shouldRecordLocally)
1530
+ this.discardAgentReplayRecording();
1531
+ throw err;
1532
+ }
1533
+ finally {
1534
+ if (shouldRecordLocally) {
1535
+ this.discardAgentReplayRecording();
1536
+ }
1537
+ flowLogger_js_1.SessionFileLogger.logAgentTaskCompleted();
1538
+ }
1539
+ }),
1540
+ };
1541
+ }
1542
+ // Default: AISDK tools-based agent
1543
+ const agentConfigSignature = this.agentCache.buildConfigSignature(options);
1544
+ const isStreaming = options?.stream ?? false;
1545
+ return {
1546
+ execute: async (instructionOrOptions) => (0, logger_js_2.withInstanceLogContext)(this.instanceId, async () => {
1472
1547
  (0, validateExperimentalFeatures_js_1.validateExperimentalFeatures)({
1473
1548
  isExperimental: this.experimental,
1474
1549
  agentConfig: options,
1475
1550
  executeOptions: typeof instructionOrOptions === "object"
1476
1551
  ? instructionOrOptions
1477
1552
  : null,
1553
+ isStreaming,
1478
1554
  });
1479
- const tools = options?.integrations
1480
- ? await (0, utils_js_2.resolveTools)(options.integrations, options.tools)
1481
- : (options?.tools ?? {});
1482
- const handler = new v3CuaAgentHandler_js_1.V3CuaAgentHandler(this, this.logger, {
1483
- modelName,
1484
- clientOptions,
1485
- userProvidedInstructions: options.systemPrompt ??
1486
- `You are a helpful assistant that can use a web browser.\nDo not ask follow up questions, the user will trust your judgement.`,
1487
- }, tools);
1488
- const resolvedOptions = typeof instructionOrOptions === "string"
1489
- ? {
1490
- instruction: instructionOrOptions,
1491
- toolTimeout: DEFAULT_AGENT_TOOL_TIMEOUT_MS,
1492
- }
1493
- : {
1494
- ...instructionOrOptions,
1495
- toolTimeout: instructionOrOptions.toolTimeout ??
1496
- DEFAULT_AGENT_TOOL_TIMEOUT_MS,
1497
- };
1498
- if (resolvedOptions.page) {
1499
- const normalizedPage = await this.normalizeToV3Page(resolvedOptions.page);
1500
- this.ctx.setActivePage(normalizedPage);
1501
- }
1502
- const instruction = resolvedOptions.instruction.trim();
1503
- const sanitizedOptions = this.agentCache.sanitizeExecuteOptions(resolvedOptions);
1504
- const cacheVariables = (0, variables_js_1.flattenVariables)(resolvedOptions.variables);
1505
- let cacheContext = null;
1506
- if (this.agentCache.shouldAttemptCache(instruction)) {
1507
- const startPage = await this.ctx.awaitActivePage();
1508
- cacheContext = await this.agentCache.prepareContext({
1509
- instruction,
1510
- options: sanitizedOptions,
1511
- configSignature: agentConfigSignature,
1512
- page: startPage,
1513
- variables: cacheVariables,
1514
- });
1555
+ flowLogger_js_1.SessionFileLogger.logAgentTaskStarted({
1556
+ invocation: "Agent.execute",
1557
+ args: [instructionOrOptions],
1558
+ });
1559
+ // Streaming mode
1560
+ if (isStreaming) {
1561
+ const { handler, resolvedOptions, cacheContext, llmClient } = await this.prepareAgentExecution(options, instructionOrOptions, agentConfigSignature);
1515
1562
  if (cacheContext) {
1516
- const replayed = await this.agentCache.tryReplay(cacheContext);
1563
+ const replayed = await this.agentCache.tryReplayAsStream(cacheContext, llmClient);
1517
1564
  if (replayed) {
1565
+ flowLogger_js_1.SessionFileLogger.logAgentTaskCompleted({ cacheHit: true });
1518
1566
  return replayed;
1519
1567
  }
1520
1568
  }
1569
+ const streamResult = await handler.stream(resolvedOptions);
1570
+ if (cacheContext) {
1571
+ const wrappedStream = this.agentCache.wrapStreamForCaching(cacheContext, streamResult, () => this.beginAgentReplayRecording(), () => this.endAgentReplayRecording(), () => this.discardAgentReplayRecording());
1572
+ // Log completion when stream is returned (stream completes asynchronously)
1573
+ flowLogger_js_1.SessionFileLogger.logAgentTaskCompleted();
1574
+ return wrappedStream;
1575
+ }
1576
+ // Log completion when stream is returned (stream completes asynchronously)
1577
+ flowLogger_js_1.SessionFileLogger.logAgentTaskCompleted();
1578
+ return streamResult;
1579
+ }
1580
+ // Non-streaming mode (default)
1581
+ const { handler, resolvedOptions, cacheContext, llmClient } = await this.prepareAgentExecution(options, instructionOrOptions, agentConfigSignature);
1582
+ if (cacheContext) {
1583
+ const replayed = await this.agentCache.tryReplay(cacheContext, llmClient);
1584
+ if (replayed) {
1585
+ flowLogger_js_1.SessionFileLogger.logAgentTaskCompleted({ cacheHit: true });
1586
+ return replayed;
1587
+ }
1521
1588
  }
1522
1589
  let agentSteps = [];
1523
1590
  const shouldRecordLocally = !!cacheContext && (!this.apiClient || this.experimental);
@@ -1528,14 +1595,14 @@ let V3 = (() => {
1528
1595
  try {
1529
1596
  if (this.apiClient && !this.experimental) {
1530
1597
  const page = await this.ctx.awaitActivePage();
1531
- result = await this.apiClient.agentExecute(options, resolvedOptions, page.mainFrameId(), !!cacheContext);
1598
+ result = await this.apiClient.agentExecute(options ?? {}, resolvedOptions, page.mainFrameId(), !!cacheContext);
1532
1599
  if (cacheContext) {
1533
1600
  const transferredEntry = this.apiClient.consumeLatestAgentCacheEntry();
1534
1601
  await this.agentCache.storeTransferredEntry(transferredEntry);
1535
1602
  }
1536
1603
  }
1537
1604
  else {
1538
- result = await handler.execute(instructionOrOptions);
1605
+ result = await handler.execute(resolvedOptions);
1539
1606
  }
1540
1607
  if (shouldRecordLocally) {
1541
1608
  agentSteps = this.endAgentReplayRecording();
@@ -1557,93 +1624,9 @@ let V3 = (() => {
1557
1624
  if (shouldRecordLocally) {
1558
1625
  this.discardAgentReplayRecording();
1559
1626
  }
1627
+ flowLogger_js_1.SessionFileLogger.logAgentTaskCompleted();
1560
1628
  }
1561
- }));
1562
- return {
1563
- execute,
1564
- };
1565
- }
1566
- // Default: AISDK tools-based agent
1567
- const agentConfigSignature = this.agentCache.buildConfigSignature(options);
1568
- const isStreaming = options?.stream ?? false;
1569
- const execute = flowLogger_js_1.FlowLogger.wrapWithLogging({
1570
- eventType: "AgentExecute",
1571
- eventIdSuffix: "3",
1572
- })(async (instructionOrOptions) => this.withLoggingContext(async () => {
1573
- (0, validateExperimentalFeatures_js_1.validateExperimentalFeatures)({
1574
- isExperimental: this.experimental,
1575
- agentConfig: options,
1576
- executeOptions: typeof instructionOrOptions === "object"
1577
- ? instructionOrOptions
1578
- : null,
1579
- isStreaming,
1580
- });
1581
- // Streaming mode
1582
- if (isStreaming) {
1583
- const { handler, resolvedOptions, cacheContext, llmClient } = await this.prepareAgentExecution(options, instructionOrOptions, agentConfigSignature);
1584
- if (cacheContext) {
1585
- const replayed = await this.agentCache.tryReplayAsStream(cacheContext, llmClient);
1586
- if (replayed) {
1587
- return replayed;
1588
- }
1589
- }
1590
- const streamResult = await handler.stream(resolvedOptions);
1591
- if (cacheContext) {
1592
- const wrappedStream = this.agentCache.wrapStreamForCaching(cacheContext, streamResult, () => this.beginAgentReplayRecording(), () => this.endAgentReplayRecording(), () => this.discardAgentReplayRecording());
1593
- return wrappedStream;
1594
- }
1595
- return streamResult;
1596
- }
1597
- // Non-streaming mode (default)
1598
- const { handler, resolvedOptions, cacheContext, llmClient } = await this.prepareAgentExecution(options, instructionOrOptions, agentConfigSignature);
1599
- if (cacheContext) {
1600
- const replayed = await this.agentCache.tryReplay(cacheContext, llmClient);
1601
- if (replayed) {
1602
- return replayed;
1603
- }
1604
- }
1605
- let agentSteps = [];
1606
- const shouldRecordLocally = !!cacheContext && (!this.apiClient || this.experimental);
1607
- if (shouldRecordLocally) {
1608
- this.beginAgentReplayRecording();
1609
- }
1610
- let result;
1611
- try {
1612
- if (this.apiClient && !this.experimental) {
1613
- const page = await this.ctx.awaitActivePage();
1614
- result = await this.apiClient.agentExecute(options ?? {}, resolvedOptions, page.mainFrameId(), !!cacheContext);
1615
- if (cacheContext) {
1616
- const transferredEntry = this.apiClient.consumeLatestAgentCacheEntry();
1617
- await this.agentCache.storeTransferredEntry(transferredEntry);
1618
- }
1619
- }
1620
- else {
1621
- result = await handler.execute(resolvedOptions);
1622
- }
1623
- if (shouldRecordLocally) {
1624
- agentSteps = this.endAgentReplayRecording();
1625
- }
1626
- if (shouldRecordLocally &&
1627
- cacheContext &&
1628
- result.success &&
1629
- agentSteps.length > 0) {
1630
- await this.agentCache.store(cacheContext, agentSteps, result);
1631
- }
1632
- return result;
1633
- }
1634
- catch (err) {
1635
- if (shouldRecordLocally)
1636
- this.discardAgentReplayRecording();
1637
- throw err;
1638
- }
1639
- finally {
1640
- if (shouldRecordLocally) {
1641
- this.discardAgentReplayRecording();
1642
- }
1643
- }
1644
- }));
1645
- return {
1646
- execute,
1629
+ }),
1647
1630
  };
1648
1631
  }
1649
1632
  };