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

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 (171) hide show
  1. package/dist/cjs/lib/utils.d.ts +1 -0
  2. package/dist/cjs/lib/utils.js +4 -0
  3. package/dist/cjs/lib/utils.js.map +1 -1
  4. package/dist/cjs/lib/v3/agent/AnthropicCUAClient.js +5 -7
  5. package/dist/cjs/lib/v3/agent/AnthropicCUAClient.js.map +1 -1
  6. package/dist/cjs/lib/v3/agent/GoogleCUAClient.js +5 -7
  7. package/dist/cjs/lib/v3/agent/GoogleCUAClient.js.map +1 -1
  8. package/dist/cjs/lib/v3/agent/OpenAICUAClient.js +5 -7
  9. package/dist/cjs/lib/v3/agent/OpenAICUAClient.js.map +1 -1
  10. package/dist/cjs/lib/v3/agent/tools/act.js +1 -10
  11. package/dist/cjs/lib/v3/agent/tools/act.js.map +1 -1
  12. package/dist/cjs/lib/v3/agent/tools/ariaTree.js +1 -12
  13. package/dist/cjs/lib/v3/agent/tools/ariaTree.js.map +1 -1
  14. package/dist/cjs/lib/v3/agent/tools/braveSearch.js.map +1 -1
  15. package/dist/cjs/lib/v3/agent/tools/browserbaseSearch.js.map +1 -1
  16. package/dist/cjs/lib/v3/agent/tools/click.js.map +1 -1
  17. package/dist/cjs/lib/v3/agent/tools/clickAndHold.js.map +1 -1
  18. package/dist/cjs/lib/v3/agent/tools/dragAndDrop.js.map +1 -1
  19. package/dist/cjs/lib/v3/agent/tools/extract.js +1 -10
  20. package/dist/cjs/lib/v3/agent/tools/extract.js.map +1 -1
  21. package/dist/cjs/lib/v3/agent/tools/fillFormVision.js.map +1 -1
  22. package/dist/cjs/lib/v3/agent/tools/fillform.js +1 -10
  23. package/dist/cjs/lib/v3/agent/tools/fillform.js.map +1 -1
  24. package/dist/cjs/lib/v3/agent/tools/index.d.ts +2 -2
  25. package/dist/cjs/lib/v3/agent/tools/index.js +53 -5
  26. package/dist/cjs/lib/v3/agent/tools/index.js.map +1 -1
  27. package/dist/cjs/lib/v3/agent/tools/keys.d.ts +1 -1
  28. package/dist/cjs/lib/v3/agent/tools/keys.js.map +1 -1
  29. package/dist/cjs/lib/v3/agent/tools/type.js.map +1 -1
  30. package/dist/cjs/lib/v3/api.js +9 -2
  31. package/dist/cjs/lib/v3/api.js.map +1 -1
  32. package/dist/cjs/lib/v3/flowlogger/EventEmitter.d.ts +7 -0
  33. package/dist/cjs/lib/v3/flowlogger/EventEmitter.js +30 -0
  34. package/dist/cjs/lib/v3/flowlogger/EventEmitter.js.map +1 -0
  35. package/dist/cjs/lib/v3/flowlogger/EventSink.d.ts +44 -0
  36. package/dist/cjs/lib/v3/flowlogger/EventSink.js +217 -0
  37. package/dist/cjs/lib/v3/flowlogger/EventSink.js.map +1 -0
  38. package/dist/cjs/lib/v3/flowlogger/EventStore.d.ts +26 -0
  39. package/dist/cjs/lib/v3/flowlogger/EventStore.js +135 -0
  40. package/dist/cjs/lib/v3/flowlogger/EventStore.js.map +1 -0
  41. package/dist/cjs/lib/v3/flowlogger/FlowLogger.d.ts +99 -0
  42. package/dist/cjs/lib/v3/flowlogger/FlowLogger.js +591 -0
  43. package/dist/cjs/lib/v3/flowlogger/FlowLogger.js.map +1 -0
  44. package/dist/cjs/lib/v3/flowlogger/prettify.d.ts +6 -0
  45. package/dist/cjs/lib/v3/flowlogger/prettify.js +395 -0
  46. package/dist/cjs/lib/v3/flowlogger/prettify.js.map +1 -0
  47. package/dist/cjs/lib/v3/handlers/handlerUtils/actHandlerUtils.js +43 -57
  48. package/dist/cjs/lib/v3/handlers/handlerUtils/actHandlerUtils.js.map +1 -1
  49. package/dist/cjs/lib/v3/handlers/v3AgentHandler.d.ts +0 -4
  50. package/dist/cjs/lib/v3/handlers/v3AgentHandler.js +2 -32
  51. package/dist/cjs/lib/v3/handlers/v3AgentHandler.js.map +1 -1
  52. package/dist/cjs/lib/v3/handlers/v3CuaAgentHandler.js +9 -13
  53. package/dist/cjs/lib/v3/handlers/v3CuaAgentHandler.js.map +1 -1
  54. package/dist/cjs/lib/v3/llm/aisdk.js +11 -17
  55. package/dist/cjs/lib/v3/llm/aisdk.js.map +1 -1
  56. package/dist/cjs/lib/v3/types/public/options.d.ts +7 -0
  57. package/dist/cjs/lib/v3/types/public/options.js.map +1 -1
  58. package/dist/cjs/lib/v3/understudy/cdp.d.ts +3 -12
  59. package/dist/cjs/lib/v3/understudy/cdp.js +134 -21
  60. package/dist/cjs/lib/v3/understudy/cdp.js.map +1 -1
  61. package/dist/cjs/lib/v3/understudy/page.js +28 -18
  62. package/dist/cjs/lib/v3/understudy/page.js.map +1 -1
  63. package/dist/cjs/lib/v3/v3.d.ts +7 -2
  64. package/dist/cjs/lib/v3/v3.js +178 -159
  65. package/dist/cjs/lib/v3/v3.js.map +1 -1
  66. package/dist/cjs/tests/integration/flowLogger.spec.d.ts +1 -0
  67. package/dist/cjs/tests/integration/flowLogger.spec.js +714 -0
  68. package/dist/cjs/tests/integration/flowLogger.spec.js.map +1 -0
  69. package/dist/cjs/tests/integration/testUtils.d.ts +33 -0
  70. package/dist/cjs/tests/integration/testUtils.js +144 -0
  71. package/dist/cjs/tests/integration/testUtils.js.map +1 -1
  72. package/dist/cjs/tests/integration/timeouts.spec.js +112 -2
  73. package/dist/cjs/tests/integration/timeouts.spec.js.map +1 -1
  74. package/dist/cjs/tests/unit/flowlogger-capturing-cdp.test.d.ts +1 -0
  75. package/dist/cjs/tests/unit/flowlogger-capturing-cdp.test.js +95 -0
  76. package/dist/cjs/tests/unit/flowlogger-capturing-cdp.test.js.map +1 -0
  77. package/dist/cjs/tests/unit/flowlogger-capturing-llm.test.d.ts +1 -0
  78. package/dist/cjs/tests/unit/flowlogger-capturing-llm.test.js +43 -0
  79. package/dist/cjs/tests/unit/flowlogger-capturing-llm.test.js.map +1 -0
  80. package/dist/cjs/tests/unit/flowlogger-eventstore.test.d.ts +1 -0
  81. package/dist/cjs/tests/unit/flowlogger-eventstore.test.js +250 -0
  82. package/dist/cjs/tests/unit/flowlogger-eventstore.test.js.map +1 -0
  83. package/dist/esm/lib/utils.d.ts +1 -0
  84. package/dist/esm/lib/utils.js +3 -0
  85. package/dist/esm/lib/utils.js.map +1 -1
  86. package/dist/esm/lib/v3/agent/AnthropicCUAClient.js +5 -7
  87. package/dist/esm/lib/v3/agent/AnthropicCUAClient.js.map +1 -1
  88. package/dist/esm/lib/v3/agent/GoogleCUAClient.js +5 -7
  89. package/dist/esm/lib/v3/agent/GoogleCUAClient.js.map +1 -1
  90. package/dist/esm/lib/v3/agent/OpenAICUAClient.js +5 -7
  91. package/dist/esm/lib/v3/agent/OpenAICUAClient.js.map +1 -1
  92. package/dist/esm/lib/v3/agent/tools/act.js +1 -10
  93. package/dist/esm/lib/v3/agent/tools/act.js.map +1 -1
  94. package/dist/esm/lib/v3/agent/tools/ariaTree.js +1 -12
  95. package/dist/esm/lib/v3/agent/tools/ariaTree.js.map +1 -1
  96. package/dist/esm/lib/v3/agent/tools/braveSearch.js.map +1 -1
  97. package/dist/esm/lib/v3/agent/tools/browserbaseSearch.js.map +1 -1
  98. package/dist/esm/lib/v3/agent/tools/click.js.map +1 -1
  99. package/dist/esm/lib/v3/agent/tools/clickAndHold.js.map +1 -1
  100. package/dist/esm/lib/v3/agent/tools/dragAndDrop.js.map +1 -1
  101. package/dist/esm/lib/v3/agent/tools/extract.js +1 -10
  102. package/dist/esm/lib/v3/agent/tools/extract.js.map +1 -1
  103. package/dist/esm/lib/v3/agent/tools/fillFormVision.js.map +1 -1
  104. package/dist/esm/lib/v3/agent/tools/fillform.js +1 -10
  105. package/dist/esm/lib/v3/agent/tools/fillform.js.map +1 -1
  106. package/dist/esm/lib/v3/agent/tools/index.d.ts +2 -2
  107. package/dist/esm/lib/v3/agent/tools/index.js +53 -5
  108. package/dist/esm/lib/v3/agent/tools/index.js.map +1 -1
  109. package/dist/esm/lib/v3/agent/tools/keys.d.ts +1 -1
  110. package/dist/esm/lib/v3/agent/tools/keys.js.map +1 -1
  111. package/dist/esm/lib/v3/agent/tools/type.js.map +1 -1
  112. package/dist/esm/lib/v3/api.js +9 -2
  113. package/dist/esm/lib/v3/api.js.map +1 -1
  114. package/dist/esm/lib/v3/flowlogger/EventEmitter.d.ts +7 -0
  115. package/dist/esm/lib/v3/flowlogger/EventEmitter.js +26 -0
  116. package/dist/esm/lib/v3/flowlogger/EventEmitter.js.map +1 -0
  117. package/dist/esm/lib/v3/flowlogger/EventSink.d.ts +44 -0
  118. package/dist/esm/lib/v3/flowlogger/EventSink.js +206 -0
  119. package/dist/esm/lib/v3/flowlogger/EventSink.js.map +1 -0
  120. package/dist/esm/lib/v3/flowlogger/EventStore.d.ts +26 -0
  121. package/dist/esm/lib/v3/flowlogger/EventStore.js +127 -0
  122. package/dist/esm/lib/v3/flowlogger/EventStore.js.map +1 -0
  123. package/dist/esm/lib/v3/flowlogger/FlowLogger.d.ts +99 -0
  124. package/dist/esm/lib/v3/flowlogger/FlowLogger.js +583 -0
  125. package/dist/esm/lib/v3/flowlogger/FlowLogger.js.map +1 -0
  126. package/dist/esm/lib/v3/flowlogger/prettify.d.ts +6 -0
  127. package/dist/esm/lib/v3/flowlogger/prettify.js +389 -0
  128. package/dist/esm/lib/v3/flowlogger/prettify.js.map +1 -0
  129. package/dist/esm/lib/v3/handlers/handlerUtils/actHandlerUtils.js +43 -57
  130. package/dist/esm/lib/v3/handlers/handlerUtils/actHandlerUtils.js.map +1 -1
  131. package/dist/esm/lib/v3/handlers/v3AgentHandler.d.ts +0 -4
  132. package/dist/esm/lib/v3/handlers/v3AgentHandler.js +2 -32
  133. package/dist/esm/lib/v3/handlers/v3AgentHandler.js.map +1 -1
  134. package/dist/esm/lib/v3/handlers/v3CuaAgentHandler.js +9 -13
  135. package/dist/esm/lib/v3/handlers/v3CuaAgentHandler.js.map +1 -1
  136. package/dist/esm/lib/v3/llm/aisdk.js +11 -17
  137. package/dist/esm/lib/v3/llm/aisdk.js.map +1 -1
  138. package/dist/esm/lib/v3/types/public/options.d.ts +7 -0
  139. package/dist/esm/lib/v3/types/public/options.js.map +1 -1
  140. package/dist/esm/lib/v3/understudy/cdp.d.ts +3 -12
  141. package/dist/esm/lib/v3/understudy/cdp.js +134 -21
  142. package/dist/esm/lib/v3/understudy/cdp.js.map +1 -1
  143. package/dist/esm/lib/v3/understudy/page.js +28 -18
  144. package/dist/esm/lib/v3/understudy/page.js.map +1 -1
  145. package/dist/esm/lib/v3/v3.d.ts +7 -2
  146. package/dist/esm/lib/v3/v3.js +178 -159
  147. package/dist/esm/lib/v3/v3.js.map +1 -1
  148. package/dist/esm/tests/integration/flowLogger.spec.d.ts +1 -0
  149. package/dist/esm/tests/integration/flowLogger.spec.js +712 -0
  150. package/dist/esm/tests/integration/flowLogger.spec.js.map +1 -0
  151. package/dist/esm/tests/integration/testUtils.d.ts +33 -0
  152. package/dist/esm/tests/integration/testUtils.js +138 -0
  153. package/dist/esm/tests/integration/testUtils.js.map +1 -1
  154. package/dist/esm/tests/integration/timeouts.spec.js +112 -2
  155. package/dist/esm/tests/integration/timeouts.spec.js.map +1 -1
  156. package/dist/esm/tests/unit/flowlogger-capturing-cdp.test.d.ts +1 -0
  157. package/dist/esm/tests/unit/flowlogger-capturing-cdp.test.js +93 -0
  158. package/dist/esm/tests/unit/flowlogger-capturing-cdp.test.js.map +1 -0
  159. package/dist/esm/tests/unit/flowlogger-capturing-llm.test.d.ts +1 -0
  160. package/dist/esm/tests/unit/flowlogger-capturing-llm.test.js +41 -0
  161. package/dist/esm/tests/unit/flowlogger-capturing-llm.test.js.map +1 -0
  162. package/dist/esm/tests/unit/flowlogger-eventstore.test.d.ts +1 -0
  163. package/dist/esm/tests/unit/flowlogger-eventstore.test.js +248 -0
  164. package/dist/esm/tests/unit/flowlogger-eventstore.test.js.map +1 -0
  165. package/package.json +3 -1
  166. package/dist/cjs/lib/v3/flowLogger.d.ts +0 -139
  167. package/dist/cjs/lib/v3/flowLogger.js +0 -881
  168. package/dist/cjs/lib/v3/flowLogger.js.map +0 -1
  169. package/dist/esm/lib/v3/flowLogger.d.ts +0 -139
  170. package/dist/esm/lib/v3/flowLogger.js +0 -868
  171. package/dist/esm/lib/v3/flowLogger.js.map +0 -1
@@ -1,10 +1,12 @@
1
- import { EventEmitter } from "events";
2
1
  import { z } from "zod";
3
2
  import { InferStagehandSchema, StagehandZodSchema } from "./zodCompat.js";
4
3
  import { LLMClient } from "./llm/LLMClient.js";
5
4
  import { AgentReplayStep } from "./types/private/index.js";
6
5
  import { AgentConfig, AgentExecuteOptions, AgentStreamExecuteOptions, AgentResult, LogLine, StagehandMetrics, Action, ActOptions, ActResult, defaultExtractSchema, ExtractOptions, HistoryEntry, ObserveOptions, pageTextSchema, V3FunctionName, V3Options, AgentStreamResult } from "./types/public/index.js";
7
6
  import { V3Context } from "./understudy/context.js";
7
+ import { type FlowLoggerContext } from "./flowlogger/FlowLogger.js";
8
+ import { EventEmitterWithWildcardSupport } from "./flowlogger/EventEmitter.js";
9
+ import { EventStore } from "./flowlogger/EventStore.js";
8
10
  /**
9
11
  * V3
10
12
  *
@@ -32,7 +34,7 @@ export declare class V3 {
32
34
  * Event bus for internal communication.
33
35
  * Emits events like 'screenshot' when screenshots are captured during agent execution.
34
36
  */
35
- readonly bus: EventEmitter;
37
+ readonly bus: EventEmitterWithWildcardSupport;
36
38
  private modelName;
37
39
  private modelClientOptions;
38
40
  private llmProvider;
@@ -70,6 +72,9 @@ export declare class V3 {
70
72
  private stagehandLogger;
71
73
  private _history;
72
74
  private readonly instanceId;
75
+ private readonly sessionId;
76
+ readonly eventStore: EventStore;
77
+ readonly flowLoggerContext: FlowLoggerContext;
73
78
  private static _processGuardsInstalled;
74
79
  private static _instances;
75
80
  private cacheStorage;
@@ -32,7 +32,6 @@ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn,
32
32
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
33
  done = true;
34
34
  };
35
- import { EventEmitter } from "events";
36
35
  import fs from "fs";
37
36
  import os from "os";
38
37
  import path from "path";
@@ -63,7 +62,9 @@ import { resolveModel } from "../modelUtils.js";
63
62
  import { StagehandAPIClient } from "./api.js";
64
63
  import { validateExperimentalFeatures } from "./agent/utils/validateExperimentalFeatures.js";
65
64
  import { flattenVariables } from "./agent/utils/variables.js";
66
- import { SessionFileLogger, logStagehandStep } from "./flowLogger.js";
65
+ import { FlowLogger } from "./flowlogger/FlowLogger.js";
66
+ import { EventEmitterWithWildcardSupport } from "./flowlogger/EventEmitter.js";
67
+ import { EventStore } from "./flowlogger/EventStore.js";
67
68
  import { createTimeoutGuard } from "./handlers/handlerUtils/timeoutGuard.js";
68
69
  import { ActTimeoutError } from "./types/public/sdkErrors.js";
69
70
  const DEFAULT_MODEL_NAME = "openai/gpt-4.1-mini";
@@ -111,9 +112,15 @@ let V3 = (() => {
111
112
  return class V3 {
112
113
  static {
113
114
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
114
- _act_decorators = [logStagehandStep("Stagehand.act", "ACT")];
115
- _extract_decorators = [logStagehandStep("Stagehand.extract", "EXTRACT")];
116
- _observe_decorators = [logStagehandStep("Stagehand.observe", "OBSERVE")];
115
+ _act_decorators = [FlowLogger.wrapWithLogging({
116
+ eventType: "StagehandAct",
117
+ })];
118
+ _extract_decorators = [FlowLogger.wrapWithLogging({
119
+ eventType: "StagehandExtract",
120
+ })];
121
+ _observe_decorators = [FlowLogger.wrapWithLogging({
122
+ eventType: "StagehandObserve",
123
+ })];
117
124
  __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);
118
125
  __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);
119
126
  __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);
@@ -130,7 +137,7 @@ let V3 = (() => {
130
137
  * Event bus for internal communication.
131
138
  * Emits events like 'screenshot' when screenshots are captured during agent execution.
132
139
  */
133
- bus = new EventEmitter();
140
+ bus = new EventEmitterWithWildcardSupport();
134
141
  modelName;
135
142
  modelClientOptions;
136
143
  llmProvider;
@@ -198,6 +205,9 @@ let V3 = (() => {
198
205
  stagehandLogger;
199
206
  _history = [];
200
207
  instanceId;
208
+ sessionId;
209
+ eventStore;
210
+ flowLoggerContext;
201
211
  static _processGuardsInstalled = false;
202
212
  static _instances = new Set();
203
213
  cacheStorage;
@@ -237,6 +247,7 @@ let V3 = (() => {
237
247
  this.externalLogger = opts.logger;
238
248
  this.verbose = opts.verbose ?? 1;
239
249
  this.instanceId = uuidv7();
250
+ this.sessionId = opts.sessionId ?? this.instanceId;
240
251
  this.keepAlive =
241
252
  opts.keepAlive ?? opts.browserbaseSessionCreateParams?.keepAlive;
242
253
  // Create per-instance StagehandLogger (handles usePino, verbose, externalLogger)
@@ -329,8 +340,21 @@ let V3 = (() => {
329
340
  act: this.act.bind(this),
330
341
  });
331
342
  this.opts = opts;
332
- // Initialize session file logger
333
- SessionFileLogger.init(this.instanceId, opts);
343
+ // FlowLogger always gets a per-instance session context and shared event
344
+ // bus. The attached EventStore decides which sinks are active:
345
+ // `verbose: 2` or `BROWSERBASE_FLOW_LOGS=1` enables pretty stderr output,
346
+ // and `BROWSERBASE_CONFIG_DIR` enables the pretty/jsonl file sinks for this session.
347
+ this.eventStore = new EventStore(this.sessionId, opts);
348
+ this.flowLoggerContext = FlowLogger.init(this.sessionId, this.bus);
349
+ // Flow event pipeline:
350
+ // FlowLogger -> this.bus -> this.eventStore -> configured sinks/query history.
351
+ // V3 owns the bus for this session. EventStore is not another bus; it just
352
+ // receives already-emitted FlowEvents here, then fans them out to sinks and
353
+ // keeps the queryable per-session history used by /v4/log, parent/ancestor lookups, and tests.
354
+ // `on()` stores a strong reference to the handler, so the EventStore
355
+ // stays alive until this bus is garbage-collected with the rest of the V3
356
+ // object graph.
357
+ this.bus.on("*", this.eventStore.emit);
334
358
  // Track instance for global process guard handling
335
359
  V3._instances.add(this);
336
360
  }
@@ -571,9 +595,7 @@ let V3 = (() => {
571
595
  env: "LOCAL",
572
596
  cdpHeaders: lbo.cdpHeaders,
573
597
  });
574
- const logCtx = SessionFileLogger.getContext();
575
- this.ctx.conn.cdpLogger = (info) => SessionFileLogger.logCdpCallEvent(info, logCtx);
576
- this.ctx.conn.cdpEventLogger = (info) => SessionFileLogger.logCdpMessageEvent(info, logCtx);
598
+ this.ctx.conn.flowLoggerContext = this.flowLoggerContext;
577
599
  this.ctx.conn.onTransportClosed(this._onCdpClosed);
578
600
  this.state = {
579
601
  kind: "LOCAL",
@@ -669,9 +691,7 @@ let V3 = (() => {
669
691
  env: "LOCAL",
670
692
  localBrowserLaunchOptions: lbo,
671
693
  });
672
- const logCtx = SessionFileLogger.getContext();
673
- this.ctx.conn.cdpLogger = (info) => SessionFileLogger.logCdpCallEvent(info, logCtx);
674
- this.ctx.conn.cdpEventLogger = (info) => SessionFileLogger.logCdpMessageEvent(info, logCtx);
694
+ this.ctx.conn.flowLoggerContext = this.flowLoggerContext;
675
695
  this.ctx.conn.onTransportClosed(this._onCdpClosed);
676
696
  this.state = {
677
697
  kind: "LOCAL",
@@ -706,9 +726,13 @@ let V3 = (() => {
706
726
  const baseSessionParams = this.opts.browserbaseSessionCreateParams ?? {};
707
727
  const resolvedKeepAlive = this.keepAlive;
708
728
  const keepAlive = this.keepAlive === true;
709
- const effectiveSessionParams = resolvedKeepAlive !== undefined
710
- ? { ...baseSessionParams, keepAlive: resolvedKeepAlive }
711
- : baseSessionParams;
729
+ let effectiveSessionParams = baseSessionParams;
730
+ if (resolvedKeepAlive !== undefined) {
731
+ effectiveSessionParams = {
732
+ ...baseSessionParams,
733
+ keepAlive: resolvedKeepAlive,
734
+ };
735
+ }
712
736
  if (!this.disableAPI && !this.experimental) {
713
737
  this.apiClient = new StagehandAPIClient({
714
738
  apiKey,
@@ -753,9 +777,7 @@ let V3 = (() => {
753
777
  env: "BROWSERBASE",
754
778
  apiClient: this.apiClient,
755
779
  });
756
- const logCtx = SessionFileLogger.getContext();
757
- this.ctx.conn.cdpLogger = (info) => SessionFileLogger.logCdpCallEvent(info, logCtx);
758
- this.ctx.conn.cdpEventLogger = (info) => SessionFileLogger.logCdpMessageEvent(info, logCtx);
780
+ this.ctx.conn.flowLoggerContext = this.flowLoggerContext;
759
781
  this.ctx.conn.onTransportClosed(this._onCdpClosed);
760
782
  this.state = { kind: "BROWSERBASE", sessionId, ws, bb };
761
783
  this.browserbaseSessionId = sessionId;
@@ -1098,7 +1120,7 @@ let V3 = (() => {
1098
1120
  try {
1099
1121
  // Close session file logger
1100
1122
  try {
1101
- await SessionFileLogger.close();
1123
+ await FlowLogger.close(this.flowLoggerContext);
1102
1124
  }
1103
1125
  catch {
1104
1126
  // ignore
@@ -1134,6 +1156,12 @@ let V3 = (() => {
1134
1156
  catch {
1135
1157
  // ignore
1136
1158
  }
1159
+ try {
1160
+ await this.eventStore.destroy();
1161
+ }
1162
+ catch {
1163
+ // ignore
1164
+ }
1137
1165
  try {
1138
1166
  this.bus.removeAllListeners();
1139
1167
  }
@@ -1400,152 +1428,56 @@ let V3 = (() => {
1400
1428
  throw new CuaModelRequiredError(AVAILABLE_CUA_MODELS);
1401
1429
  }
1402
1430
  const agentConfigSignature = this.agentCache.buildConfigSignature(options);
1403
- return {
1404
- execute: async (instructionOrOptions) => withInstanceLogContext(this.instanceId, async () => {
1405
- validateExperimentalFeatures({
1406
- isExperimental: this.experimental,
1407
- agentConfig: options,
1408
- executeOptions: typeof instructionOrOptions === "object"
1409
- ? instructionOrOptions
1410
- : null,
1411
- });
1412
- SessionFileLogger.logAgentTaskStarted({
1413
- invocation: "Agent.execute",
1414
- args: [instructionOrOptions],
1415
- });
1416
- const tools = options?.integrations
1417
- ? await resolveTools(options.integrations, options.tools)
1418
- : (options?.tools ?? {});
1419
- const handler = new V3CuaAgentHandler(this, this.logger, {
1420
- modelName,
1421
- clientOptions,
1422
- userProvidedInstructions: options.systemPrompt ??
1423
- `You are a helpful assistant that can use a web browser.\nDo not ask follow up questions, the user will trust your judgement.`,
1424
- }, tools);
1425
- const resolvedOptions = typeof instructionOrOptions === "string"
1426
- ? {
1427
- instruction: instructionOrOptions,
1428
- toolTimeout: DEFAULT_AGENT_TOOL_TIMEOUT_MS,
1429
- }
1430
- : {
1431
- ...instructionOrOptions,
1432
- toolTimeout: instructionOrOptions.toolTimeout ??
1433
- DEFAULT_AGENT_TOOL_TIMEOUT_MS,
1434
- };
1435
- if (resolvedOptions.page) {
1436
- const normalizedPage = await this.normalizeToV3Page(resolvedOptions.page);
1437
- this.ctx.setActivePage(normalizedPage);
1438
- }
1439
- const instruction = resolvedOptions.instruction.trim();
1440
- const sanitizedOptions = this.agentCache.sanitizeExecuteOptions(resolvedOptions);
1441
- const cacheVariables = flattenVariables(resolvedOptions.variables);
1442
- let cacheContext = null;
1443
- if (this.agentCache.shouldAttemptCache(instruction)) {
1444
- const startPage = await this.ctx.awaitActivePage();
1445
- cacheContext = await this.agentCache.prepareContext({
1446
- instruction,
1447
- options: sanitizedOptions,
1448
- configSignature: agentConfigSignature,
1449
- page: startPage,
1450
- variables: cacheVariables,
1451
- });
1452
- if (cacheContext) {
1453
- const replayed = await this.agentCache.tryReplay(cacheContext);
1454
- if (replayed) {
1455
- SessionFileLogger.logAgentTaskCompleted({ cacheHit: true });
1456
- return replayed;
1457
- }
1458
- }
1459
- }
1460
- let agentSteps = [];
1461
- const shouldRecordLocally = !!cacheContext && (!this.apiClient || this.experimental);
1462
- if (shouldRecordLocally) {
1463
- this.beginAgentReplayRecording();
1464
- }
1465
- let result;
1466
- try {
1467
- if (this.apiClient && !this.experimental) {
1468
- const page = await this.ctx.awaitActivePage();
1469
- result = await this.apiClient.agentExecute(options, resolvedOptions, page.mainFrameId(), !!cacheContext);
1470
- if (cacheContext) {
1471
- const transferredEntry = this.apiClient.consumeLatestAgentCacheEntry();
1472
- await this.agentCache.storeTransferredEntry(transferredEntry);
1473
- }
1474
- }
1475
- else {
1476
- result = await handler.execute(instructionOrOptions);
1477
- }
1478
- if (shouldRecordLocally) {
1479
- agentSteps = this.endAgentReplayRecording();
1480
- }
1481
- if (shouldRecordLocally &&
1482
- cacheContext &&
1483
- result.success &&
1484
- agentSteps.length > 0) {
1485
- await this.agentCache.store(cacheContext, agentSteps, result);
1486
- }
1487
- return result;
1488
- }
1489
- catch (err) {
1490
- if (shouldRecordLocally)
1491
- this.discardAgentReplayRecording();
1492
- throw err;
1493
- }
1494
- finally {
1495
- if (shouldRecordLocally) {
1496
- this.discardAgentReplayRecording();
1497
- }
1498
- SessionFileLogger.logAgentTaskCompleted();
1499
- }
1500
- }),
1501
- };
1502
- }
1503
- // Default: AISDK tools-based agent
1504
- const agentConfigSignature = this.agentCache.buildConfigSignature(options);
1505
- const isStreaming = options?.stream ?? false;
1506
- return {
1507
- execute: async (instructionOrOptions) => withInstanceLogContext(this.instanceId, async () => {
1431
+ const execute = async (instructionOrOptions) => withInstanceLogContext(this.instanceId, async () => {
1508
1432
  validateExperimentalFeatures({
1509
1433
  isExperimental: this.experimental,
1510
1434
  agentConfig: options,
1511
1435
  executeOptions: typeof instructionOrOptions === "object"
1512
1436
  ? instructionOrOptions
1513
1437
  : null,
1514
- isStreaming,
1515
- });
1516
- SessionFileLogger.logAgentTaskStarted({
1517
- invocation: "Agent.execute",
1518
- args: [instructionOrOptions],
1519
1438
  });
1520
- // Streaming mode
1521
- if (isStreaming) {
1522
- const { handler, resolvedOptions, cacheContext, llmClient } = await this.prepareAgentExecution(options, instructionOrOptions, agentConfigSignature);
1439
+ const tools = options?.integrations
1440
+ ? await resolveTools(options.integrations, options.tools)
1441
+ : (options?.tools ?? {});
1442
+ const handler = new V3CuaAgentHandler(this, this.logger, {
1443
+ modelName,
1444
+ clientOptions,
1445
+ userProvidedInstructions: options.systemPrompt ??
1446
+ `You are a helpful assistant that can use a web browser.\nDo not ask follow up questions, the user will trust your judgement.`,
1447
+ }, tools);
1448
+ const resolvedOptions = typeof instructionOrOptions === "string"
1449
+ ? {
1450
+ instruction: instructionOrOptions,
1451
+ toolTimeout: DEFAULT_AGENT_TOOL_TIMEOUT_MS,
1452
+ }
1453
+ : {
1454
+ ...instructionOrOptions,
1455
+ toolTimeout: instructionOrOptions.toolTimeout ??
1456
+ DEFAULT_AGENT_TOOL_TIMEOUT_MS,
1457
+ };
1458
+ if (resolvedOptions.page) {
1459
+ const normalizedPage = await this.normalizeToV3Page(resolvedOptions.page);
1460
+ this.ctx.setActivePage(normalizedPage);
1461
+ }
1462
+ const instruction = resolvedOptions.instruction.trim();
1463
+ const sanitizedOptions = this.agentCache.sanitizeExecuteOptions(resolvedOptions);
1464
+ const cacheVariables = flattenVariables(resolvedOptions.variables);
1465
+ let cacheContext = null;
1466
+ if (this.agentCache.shouldAttemptCache(instruction)) {
1467
+ const startPage = await this.ctx.awaitActivePage();
1468
+ cacheContext = await this.agentCache.prepareContext({
1469
+ instruction,
1470
+ options: sanitizedOptions,
1471
+ configSignature: agentConfigSignature,
1472
+ page: startPage,
1473
+ variables: cacheVariables,
1474
+ });
1523
1475
  if (cacheContext) {
1524
- const replayed = await this.agentCache.tryReplayAsStream(cacheContext, llmClient);
1476
+ const replayed = await this.agentCache.tryReplay(cacheContext);
1525
1477
  if (replayed) {
1526
- SessionFileLogger.logAgentTaskCompleted({ cacheHit: true });
1527
1478
  return replayed;
1528
1479
  }
1529
1480
  }
1530
- const streamResult = await handler.stream(resolvedOptions);
1531
- if (cacheContext) {
1532
- const wrappedStream = this.agentCache.wrapStreamForCaching(cacheContext, streamResult, () => this.beginAgentReplayRecording(), () => this.endAgentReplayRecording(), () => this.discardAgentReplayRecording());
1533
- // Log completion when stream is returned (stream completes asynchronously)
1534
- SessionFileLogger.logAgentTaskCompleted();
1535
- return wrappedStream;
1536
- }
1537
- // Log completion when stream is returned (stream completes asynchronously)
1538
- SessionFileLogger.logAgentTaskCompleted();
1539
- return streamResult;
1540
- }
1541
- // Non-streaming mode (default)
1542
- const { handler, resolvedOptions, cacheContext, llmClient } = await this.prepareAgentExecution(options, instructionOrOptions, agentConfigSignature);
1543
- if (cacheContext) {
1544
- const replayed = await this.agentCache.tryReplay(cacheContext, llmClient);
1545
- if (replayed) {
1546
- SessionFileLogger.logAgentTaskCompleted({ cacheHit: true });
1547
- return replayed;
1548
- }
1549
1481
  }
1550
1482
  let agentSteps = [];
1551
1483
  const shouldRecordLocally = !!cacheContext && (!this.apiClient || this.experimental);
@@ -1556,14 +1488,14 @@ let V3 = (() => {
1556
1488
  try {
1557
1489
  if (this.apiClient && !this.experimental) {
1558
1490
  const page = await this.ctx.awaitActivePage();
1559
- result = await this.apiClient.agentExecute(options ?? {}, resolvedOptions, page.mainFrameId(), !!cacheContext);
1491
+ result = await this.apiClient.agentExecute(options, resolvedOptions, page.mainFrameId(), !!cacheContext);
1560
1492
  if (cacheContext) {
1561
1493
  const transferredEntry = this.apiClient.consumeLatestAgentCacheEntry();
1562
1494
  await this.agentCache.storeTransferredEntry(transferredEntry);
1563
1495
  }
1564
1496
  }
1565
1497
  else {
1566
- result = await handler.execute(resolvedOptions);
1498
+ result = await handler.execute(instructionOrOptions);
1567
1499
  }
1568
1500
  if (shouldRecordLocally) {
1569
1501
  agentSteps = this.endAgentReplayRecording();
@@ -1585,9 +1517,96 @@ let V3 = (() => {
1585
1517
  if (shouldRecordLocally) {
1586
1518
  this.discardAgentReplayRecording();
1587
1519
  }
1588
- SessionFileLogger.logAgentTaskCompleted();
1589
1520
  }
1590
- }),
1521
+ });
1522
+ return {
1523
+ execute: FlowLogger.wrapWithLogging({
1524
+ eventType: "AgentExecute",
1525
+ context: this.flowLoggerContext,
1526
+ })(execute),
1527
+ };
1528
+ }
1529
+ // Default: AISDK tools-based agent
1530
+ const agentConfigSignature = this.agentCache.buildConfigSignature(options);
1531
+ const isStreaming = options?.stream ?? false;
1532
+ const execute = async (instructionOrOptions) => withInstanceLogContext(this.instanceId, async () => {
1533
+ validateExperimentalFeatures({
1534
+ isExperimental: this.experimental,
1535
+ agentConfig: options,
1536
+ executeOptions: typeof instructionOrOptions === "object"
1537
+ ? instructionOrOptions
1538
+ : null,
1539
+ isStreaming,
1540
+ });
1541
+ // Streaming mode
1542
+ if (isStreaming) {
1543
+ const { handler, resolvedOptions, cacheContext, llmClient } = await this.prepareAgentExecution(options, instructionOrOptions, agentConfigSignature);
1544
+ if (cacheContext) {
1545
+ const replayed = await this.agentCache.tryReplayAsStream(cacheContext, llmClient);
1546
+ if (replayed) {
1547
+ return replayed;
1548
+ }
1549
+ }
1550
+ const streamResult = await handler.stream(resolvedOptions);
1551
+ if (cacheContext) {
1552
+ const wrappedStream = this.agentCache.wrapStreamForCaching(cacheContext, streamResult, () => this.beginAgentReplayRecording(), () => this.endAgentReplayRecording(), () => this.discardAgentReplayRecording());
1553
+ return wrappedStream;
1554
+ }
1555
+ return streamResult;
1556
+ }
1557
+ // Non-streaming mode (default)
1558
+ const { handler, resolvedOptions, cacheContext, llmClient } = await this.prepareAgentExecution(options, instructionOrOptions, agentConfigSignature);
1559
+ if (cacheContext) {
1560
+ const replayed = await this.agentCache.tryReplay(cacheContext, llmClient);
1561
+ if (replayed) {
1562
+ return replayed;
1563
+ }
1564
+ }
1565
+ let agentSteps = [];
1566
+ const shouldRecordLocally = !!cacheContext && (!this.apiClient || this.experimental);
1567
+ if (shouldRecordLocally) {
1568
+ this.beginAgentReplayRecording();
1569
+ }
1570
+ let result;
1571
+ try {
1572
+ if (this.apiClient && !this.experimental) {
1573
+ const page = await this.ctx.awaitActivePage();
1574
+ result = await this.apiClient.agentExecute(options ?? {}, resolvedOptions, page.mainFrameId(), !!cacheContext);
1575
+ if (cacheContext) {
1576
+ const transferredEntry = this.apiClient.consumeLatestAgentCacheEntry();
1577
+ await this.agentCache.storeTransferredEntry(transferredEntry);
1578
+ }
1579
+ }
1580
+ else {
1581
+ result = await handler.execute(resolvedOptions);
1582
+ }
1583
+ if (shouldRecordLocally) {
1584
+ agentSteps = this.endAgentReplayRecording();
1585
+ }
1586
+ if (shouldRecordLocally &&
1587
+ cacheContext &&
1588
+ result.success &&
1589
+ agentSteps.length > 0) {
1590
+ await this.agentCache.store(cacheContext, agentSteps, result);
1591
+ }
1592
+ return result;
1593
+ }
1594
+ catch (err) {
1595
+ if (shouldRecordLocally)
1596
+ this.discardAgentReplayRecording();
1597
+ throw err;
1598
+ }
1599
+ finally {
1600
+ if (shouldRecordLocally) {
1601
+ this.discardAgentReplayRecording();
1602
+ }
1603
+ }
1604
+ });
1605
+ return {
1606
+ execute: FlowLogger.wrapWithLogging({
1607
+ eventType: "AgentExecute",
1608
+ context: this.flowLoggerContext,
1609
+ })(execute),
1591
1610
  };
1592
1611
  }
1593
1612
  };