@effect-agent/platform-cloudflare 0.1.0-beta.13 → 0.1.0-beta.130

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 (105) hide show
  1. package/dist/Alarm.d.mts +244 -0
  2. package/dist/Alarm.mjs +947 -0
  3. package/dist/Alarm.mjs.map +1 -0
  4. package/dist/BrowserCredentials.d.mts +91 -0
  5. package/dist/BrowserCredentials.mjs +120 -0
  6. package/dist/BrowserCredentials.mjs.map +1 -0
  7. package/dist/BrowserRestCapture.d.mts +34 -0
  8. package/dist/BrowserRestCapture.mjs +238 -0
  9. package/dist/BrowserRestCapture.mjs.map +1 -0
  10. package/dist/BrowserRestCrawl.d.mts +16 -0
  11. package/dist/BrowserRestCrawl.mjs +244 -0
  12. package/dist/BrowserRestCrawl.mjs.map +1 -0
  13. package/dist/BrowserSession-BplIoNfi.mjs +442 -0
  14. package/dist/BrowserSession-BplIoNfi.mjs.map +1 -0
  15. package/dist/BrowserSession-DxCN-5F9.d.mts +109 -0
  16. package/dist/BrowserSession.d.mts +3 -0
  17. package/dist/BrowserSession.mjs +4 -0
  18. package/dist/CloudflareAiGateway.d.mts +64 -0
  19. package/dist/CloudflareAiGateway.mjs +70 -0
  20. package/dist/CloudflareAiGateway.mjs.map +1 -0
  21. package/dist/CloudflareBindings.d.mts +115 -0
  22. package/dist/CloudflareBindings.mjs +113 -0
  23. package/dist/CloudflareBindings.mjs.map +1 -0
  24. package/dist/CloudflareBrowser-DV6kya1H.mjs +495 -0
  25. package/dist/CloudflareBrowser-DV6kya1H.mjs.map +1 -0
  26. package/dist/CloudflareBrowser-Doe1M7R5.d.mts +80 -0
  27. package/dist/CloudflareBrowser.d.mts +2 -0
  28. package/dist/CloudflareBrowser.mjs +2 -0
  29. package/dist/CloudflareCodeMode.d.mts +44 -0
  30. package/dist/CloudflareCodeMode.mjs +616 -0
  31. package/dist/CloudflareCodeMode.mjs.map +1 -0
  32. package/dist/CloudflareConfig-DKXGo8L3.d.mts +106 -0
  33. package/dist/CloudflareConfig.d.mts +2 -0
  34. package/dist/CloudflareConfig.mjs +128 -0
  35. package/dist/CloudflareConfig.mjs.map +1 -0
  36. package/dist/CloudflareMemory.d.mts +142 -0
  37. package/dist/CloudflareMemory.mjs +202 -0
  38. package/dist/CloudflareMemory.mjs.map +1 -0
  39. package/dist/CloudflareScheduling.d.mts +52 -0
  40. package/dist/CloudflareScheduling.mjs +396 -0
  41. package/dist/CloudflareScheduling.mjs.map +1 -0
  42. package/dist/CloudflareSubscriptions.d.mts +87 -0
  43. package/dist/CloudflareSubscriptions.mjs +530 -0
  44. package/dist/CloudflareSubscriptions.mjs.map +1 -0
  45. package/dist/CloudflareThreadClient.d.mts +1752 -0
  46. package/dist/CloudflareThreadClient.mjs +382 -0
  47. package/dist/CloudflareThreadClient.mjs.map +1 -0
  48. package/dist/InteractiveBrowser-BnqY_Y-F.d.mts +228 -0
  49. package/dist/InteractiveBrowser-D-xxDv_f.mjs +1923 -0
  50. package/dist/InteractiveBrowser-D-xxDv_f.mjs.map +1 -0
  51. package/dist/InteractiveBrowser.d.mts +2 -0
  52. package/dist/InteractiveBrowser.mjs +2 -0
  53. package/dist/ThreadObject-CVhZC-7l.mjs +849 -0
  54. package/dist/ThreadObject-CVhZC-7l.mjs.map +1 -0
  55. package/dist/ThreadObject-CcS4Q2iT.d.mts +839 -0
  56. package/dist/ThreadObject.d.mts +2 -0
  57. package/dist/ThreadObject.mjs +3 -0
  58. package/dist/WakeScheduler.d.mts +23 -0
  59. package/dist/WakeScheduler.mjs +57 -0
  60. package/dist/WakeScheduler.mjs.map +1 -0
  61. package/dist/boundary-BguazVkh.mjs +42 -0
  62. package/dist/boundary-BguazVkh.mjs.map +1 -0
  63. package/dist/index.d.mts +15 -1550
  64. package/dist/index.mjs +15 -1716
  65. package/dist/prepared-admission-DU0_T-ev.mjs +73 -0
  66. package/dist/prepared-admission-DU0_T-ev.mjs.map +1 -0
  67. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  68. package/package.json +1 -56
  69. package/src/Alarm.ts +1979 -0
  70. package/src/BrowserCredentials.ts +146 -0
  71. package/src/BrowserRestCapture.ts +477 -0
  72. package/src/BrowserRestCrawl.ts +540 -0
  73. package/src/BrowserSession.ts +591 -0
  74. package/src/CloudflareAiGateway.ts +170 -0
  75. package/src/CloudflareBindings.ts +199 -0
  76. package/src/CloudflareBrowser.ts +15 -0
  77. package/src/{code-mode-executor.ts → CloudflareCodeMode.ts} +308 -283
  78. package/src/{config.ts → CloudflareConfig.ts} +19 -12
  79. package/src/CloudflareMemory.ts +420 -0
  80. package/src/CloudflareScheduling.ts +747 -0
  81. package/src/CloudflareSubscriptions.ts +1041 -0
  82. package/src/CloudflareThreadClient.ts +809 -0
  83. package/src/InteractiveBrowser.ts +3246 -0
  84. package/src/ThreadObject.ts +1190 -0
  85. package/src/{wake-scheduler.ts → WakeScheduler.ts} +32 -26
  86. package/src/index.ts +14 -23
  87. package/src/internal/boundary.ts +55 -0
  88. package/src/internal/browser-binding.ts +322 -0
  89. package/src/internal/browser-credentials.ts +362 -0
  90. package/src/internal/browser-failure.ts +92 -0
  91. package/src/internal/browser-file-selection.ts +126 -0
  92. package/src/internal/browser-quick-action.ts +857 -0
  93. package/src/internal/browser-session-lifecycle.ts +193 -0
  94. package/src/internal/layers.ts +773 -0
  95. package/src/internal/message-delivery.ts +131 -0
  96. package/src/internal/prepared-admission.ts +116 -0
  97. package/src/internal/progress-wait.ts +121 -0
  98. package/src/internal/transport.ts +44 -0
  99. package/dist/index.mjs.map +0 -1
  100. package/src/alarm.ts +0 -334
  101. package/src/bindings.ts +0 -145
  102. package/src/client.ts +0 -646
  103. package/src/conversation-object.ts +0 -768
  104. package/src/layers.ts +0 -376
  105. package/src/transport.ts +0 -38
@@ -0,0 +1,3246 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+
3
+ import {
4
+ Cause,
5
+ Context,
6
+ Clock,
7
+ Duration,
8
+ Effect,
9
+ Layer,
10
+ Redacted,
11
+ Schema,
12
+ Semaphore,
13
+ Scope,
14
+ } from "effect";
15
+ import {
16
+ BrowserActionResult,
17
+ BrowserExpectedTargetState,
18
+ BrowserSelectFileRequest,
19
+ BrowserFileSelectionResult,
20
+ BrowserScreenshotRequest,
21
+ BrowserScrollRequest,
22
+ BrowserNavigationResult,
23
+ BrowserTextResult,
24
+ InteractiveBrowser,
25
+ InteractiveBrowserActionError,
26
+ InteractiveBrowserBusyError,
27
+ InteractiveBrowserCapacityError,
28
+ InteractiveBrowserExpiredError,
29
+ InteractiveBrowserLimitError,
30
+ InteractiveBrowserPolicy,
31
+ InteractiveBrowserPolicyDeniedError,
32
+ InteractiveBrowserProtocolError,
33
+ InteractiveBrowserTargetUrl,
34
+ InteractiveBrowserUnsupportedError,
35
+ type BrowserHandle,
36
+ type BrowserExpectedTarget,
37
+ type InteractiveBrowserError,
38
+ type InteractiveBrowserFailureEvidence,
39
+ type InteractiveBrowserNetworkPolicy,
40
+ } from "effect-agent/interactive-browser";
41
+ import { PageScreenshotResult } from "effect-agent/page-screenshot";
42
+ import { SandboxImplementation } from "effect-agent/sandbox";
43
+ import {
44
+ type Browser,
45
+ type BrowserContext,
46
+ type CDPSession,
47
+ type HTTPRequest,
48
+ type Page,
49
+ } from "puppeteer-core/lib/esm/puppeteer/puppeteer-core-browser.js";
50
+
51
+ import { BrowserRunBinding } from "./internal/browser-binding.ts";
52
+ import {
53
+ BrowserRunFailure,
54
+ reportBrowserCause,
55
+ reportedBrowserError,
56
+ } from "./internal/browser-failure.ts";
57
+ import { makeFileSelection } from "./internal/browser-file-selection.ts";
58
+ import {
59
+ BrowserRunSessionLifecycle,
60
+ type BrowserRunLifecycleOptions,
61
+ } from "./internal/browser-session-lifecycle.ts";
62
+
63
+ export {
64
+ BrowserRunCleanupError,
65
+ BrowserRunSessionLifecycle,
66
+ } from "./internal/browser-session-lifecycle.ts";
67
+
68
+ export const browserRunInteractiveImplementation = SandboxImplementation.make({
69
+ isolation: "isolated",
70
+ identity: "cloudflare-browser-run-interactive",
71
+ });
72
+
73
+ const MIN_KEEP_ALIVE_MILLIS = 10_000;
74
+ const MAX_KEEP_ALIVE_MILLIS = 600_000;
75
+ const MAX_TEXT_LENGTH = 8 * 1024 * 1024;
76
+ const MAX_SCREENSHOT_BYTES = 8 * 1024 * 1024;
77
+ const MIN_LIVE_VIEW_EXPIRY_MILLIS = 60_000;
78
+ const MAX_LIVE_VIEW_EXPIRY_MILLIS = 60 * 60_000;
79
+ const MAX_HANDOFF_TIMEOUT_MILLIS = 30 * 60_000;
80
+ const MAX_HOST_TEXT_LENGTH = 8 * 1024;
81
+ const CLEANUP_STEP_TIMEOUT_MILLIS = 10_000;
82
+ const ACTION_NETWORK_QUIET_MILLIS = 200;
83
+ const ACTION_NETWORK_SETTLE_MILLIS = 2_000;
84
+ const ACTION_POST_STATE_MILLIS = 250;
85
+ const MAX_OBSERVED_CONTROLS = 64;
86
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));
87
+
88
+ const BoundedHostText = Schema.String.check(
89
+ Schema.isMinLength(1),
90
+ Schema.isMaxLength(MAX_HOST_TEXT_LENGTH),
91
+ );
92
+
93
+ const BoundedRemoteText = Schema.String.check(Schema.isMaxLength(MAX_TEXT_LENGTH));
94
+
95
+ const TextObservation = Schema.Union([
96
+ Schema.Struct({ _tag: Schema.Literal("Text"), text: BoundedRemoteText }),
97
+ Schema.Struct({ _tag: Schema.Literal("MissingElement") }),
98
+ Schema.Struct({ _tag: Schema.Literal("OverLimit"), observed: Schema.Natural }),
99
+ ]);
100
+
101
+ const ActionTargetState = Schema.Struct({
102
+ matchCount: Schema.Natural,
103
+ invalidSelector: Schema.optionalKey(Schema.Boolean),
104
+ kind: Schema.optionalKey(
105
+ Schema.Literals(["button", "checkbox", "radio", "select", "text", "link", "other"]),
106
+ ),
107
+ checked: Schema.optionalKey(Schema.Boolean),
108
+ selected: Schema.optionalKey(Schema.Boolean),
109
+ disabled: Schema.optionalKey(Schema.Boolean),
110
+ required: Schema.optionalKey(Schema.Boolean),
111
+ valid: Schema.optionalKey(Schema.Boolean),
112
+ formValid: Schema.optionalKey(Schema.Boolean),
113
+ });
114
+
115
+ const ActionNetworkState = Schema.Struct({
116
+ total: Schema.Natural,
117
+ status2xx: Schema.Natural,
118
+ status3xx: Schema.Natural,
119
+ status4xx: Schema.Natural,
120
+ status5xx: Schema.Natural,
121
+ failed: Schema.Natural,
122
+ pending: Schema.Natural,
123
+ settleTimedOut: Schema.Boolean,
124
+ });
125
+
126
+ const ActionObservation = Schema.Struct({
127
+ before: ActionTargetState,
128
+ after: Schema.optionalKey(ActionTargetState),
129
+ afterUnavailable: Schema.Boolean,
130
+ network: ActionNetworkState,
131
+ inputMillis: Schema.optionalKey(Schema.Finite),
132
+ observationMillis: Schema.optionalKey(Schema.Finite),
133
+ });
134
+
135
+ export const BrowserRunPageObservation = Schema.fromJsonString(
136
+ Schema.Struct({
137
+ documentId: Schema.NonEmptyString,
138
+ pageText: BoundedRemoteText,
139
+ selectorMatchCount: Schema.Natural,
140
+ controlsTruncated: Schema.Boolean,
141
+ controls: Schema.Array(
142
+ Schema.Struct({
143
+ nodeId: Schema.NonEmptyString,
144
+ selector: BoundedRemoteText,
145
+ ...BrowserExpectedTargetState.fields,
146
+ }),
147
+ ).check(Schema.isMaxLength(MAX_OBSERVED_CONTROLS)),
148
+ }),
149
+ );
150
+
151
+ const PngBytes = Schema.Uint8Array.check(
152
+ Schema.isMaxLength(MAX_SCREENSHOT_BYTES),
153
+ Schema.makeFilter(
154
+ (bytes) =>
155
+ bytes.length >= 8 &&
156
+ bytes[0] === 0x89 &&
157
+ bytes[1] === 0x50 &&
158
+ bytes[2] === 0x4e &&
159
+ bytes[3] === 0x47 &&
160
+ bytes[4] === 0x0d &&
161
+ bytes[5] === 0x0a &&
162
+ bytes[6] === 0x1a &&
163
+ bytes[7] === 0x0a,
164
+ { title: "PNG bytes" },
165
+ ),
166
+ );
167
+
168
+ const BrowserRunSessionId = Schema.String.check(
169
+ Schema.isMinLength(1),
170
+ Schema.isMaxLength(256),
171
+ Schema.makeFilter((value) => /^[A-Za-z0-9_-]+$/.test(value), {
172
+ title: "a Browser Run session identifier",
173
+ }),
174
+ );
175
+
176
+ const LiveViewUrl = Schema.String.check(
177
+ Schema.isMaxLength(MAX_HOST_TEXT_LENGTH),
178
+ Schema.makeFilter(
179
+ (value) => {
180
+ try {
181
+ const url = new URL(value);
182
+
183
+ return (
184
+ url.protocol === "https:" &&
185
+ url.host === "live.browser.run" &&
186
+ url.username === "" &&
187
+ url.password === "" &&
188
+ url.pathname === "/ui/view" &&
189
+ url.searchParams.get("mode") === "tab" &&
190
+ (url.searchParams.get("wss") ?? "").startsWith("live.browser.run/api/devtools/browser/")
191
+ );
192
+ } catch {
193
+ return false;
194
+ }
195
+ },
196
+ { title: "a Cloudflare Live View HTTPS URL" },
197
+ ),
198
+ );
199
+
200
+ const LiveViewObservation = Schema.Struct({ devtoolsFrontendUrl: LiveViewUrl });
201
+ const HandoffObservation = Schema.Struct({ handoffId: BoundedHostText });
202
+
203
+ const HandoffDuration = Schema.Natural.check(
204
+ Schema.isLessThanOrEqualTo(MAX_HANDOFF_TIMEOUT_MILLIS),
205
+ );
206
+
207
+ const HandoffStateObservation = Schema.Union([
208
+ Schema.Struct({
209
+ active: Schema.Literal(true),
210
+ handoffId: BoundedHostText,
211
+ durationMs: HandoffDuration,
212
+ }),
213
+ Schema.Struct({
214
+ active: Schema.Literal(false),
215
+ handoffId: Schema.optionalKey(BoundedHostText),
216
+ durationMs: Schema.optionalKey(HandoffDuration),
217
+ }),
218
+ ]);
219
+
220
+ /**
221
+ * Host presentation state in CSS pixels. Dimensions are integers in 1..2048,
222
+ * density is finite in 1..2 (default 1), and neither scaled dimension may exceed
223
+ * 2048 pixels. Mobile, touch, and orientation emulation are not supported.
224
+ */
225
+ export class BrowserRunViewport extends Schema.Class<BrowserRunViewport>("BrowserRunViewport")(
226
+ Schema.Struct({
227
+ width: PositiveInt.check(Schema.isLessThanOrEqualTo(2_048)),
228
+ height: PositiveInt.check(Schema.isLessThanOrEqualTo(2_048)),
229
+ deviceScaleFactor: Schema.optionalKey(
230
+ Schema.Finite.check(Schema.isBetween({ minimum: 1, maximum: 2 })),
231
+ ),
232
+ }).check(
233
+ Schema.makeFilter(
234
+ (viewport) =>
235
+ Math.max(viewport.width, viewport.height) * (viewport.deviceScaleFactor ?? 1) <= 2_048,
236
+ { title: "a viewport with scaled dimensions no larger than 2048 pixels" },
237
+ ),
238
+ ),
239
+ ) {}
240
+
241
+ const decodeViewport = (input: BrowserRunViewport) =>
242
+ Schema.decodeEffect(BrowserRunViewport)(input, { onExcessProperty: "error" }).pipe(
243
+ Effect.mapError(() => policyError("The browser viewport is malformed")),
244
+ // Copy only presentation fields, including for Schema class instances.
245
+ Effect.map((viewport) => ({
246
+ width: viewport.width,
247
+ height: viewport.height,
248
+ deviceScaleFactor: viewport.deviceScaleFactor ?? 1,
249
+ })),
250
+ );
251
+
252
+ /** Host-only request for a redacted Cloudflare Live View URL. */
253
+ export class BrowserRunLiveViewRequest extends Schema.Class<BrowserRunLiveViewRequest>(
254
+ "BrowserRunLiveViewRequest",
255
+ )({
256
+ mode: Schema.Literal("tab"),
257
+ expiresInMs: PositiveInt.check(
258
+ Schema.isBetween({
259
+ minimum: MIN_LIVE_VIEW_EXPIRY_MILLIS,
260
+ maximum: MAX_LIVE_VIEW_EXPIRY_MILLIS,
261
+ }),
262
+ ),
263
+ }) {}
264
+
265
+ export class BrowserRunLiveViewResult extends Schema.Class<BrowserRunLiveViewResult>(
266
+ "BrowserRunLiveViewResult",
267
+ )({ devtoolsFrontendUrl: Schema.Redacted(LiveViewUrl) }) {}
268
+
269
+ /** Start one bounded handoff; controller ownership remains a consumer concern. */
270
+ export class BrowserRunHandoffRequest extends Schema.Class<BrowserRunHandoffRequest>(
271
+ "BrowserRunHandoffRequest",
272
+ )({
273
+ instructions: BoundedHostText.check(Schema.isMaxLength(1_024)),
274
+ timeout: PositiveInt.check(Schema.isLessThanOrEqualTo(MAX_HANDOFF_TIMEOUT_MILLIS)),
275
+ }) {}
276
+
277
+ export class BrowserRunHandoffResult extends Schema.Class<BrowserRunHandoffResult>(
278
+ "BrowserRunHandoffResult",
279
+ )({ handoffId: Schema.Redacted(BoundedHostText) }) {}
280
+
281
+ export class BrowserRunHandoffState extends Schema.Class<BrowserRunHandoffState>(
282
+ "BrowserRunHandoffState",
283
+ )({
284
+ active: Schema.Boolean,
285
+ handoffId: Schema.optionalKey(Schema.Redacted(BoundedHostText)),
286
+ durationMs: Schema.optionalKey(HandoffDuration),
287
+ }) {}
288
+
289
+ type BrowserFailure = typeof InteractiveBrowserError.Type;
290
+ type BrowserOperation = InteractiveBrowserActionError["operation"];
291
+
292
+ interface InteractiveBrowserPolicySnapshot {
293
+ readonly network: Exclude<InteractiveBrowserNetworkPolicy, { readonly _tag: "PublicWeb" }>;
294
+ readonly maxActions: number;
295
+ readonly maxElapsedMillis: number;
296
+ readonly maxReturnedBytes: number;
297
+ }
298
+
299
+ /** One intercepted Puppeteer request, narrowed to the policy-relevant surface. */
300
+ export interface BrowserRunInteractiveRequest {
301
+ readonly url: () => string;
302
+ readonly abort: () => Promise<void>;
303
+ readonly continue: () => Promise<void>;
304
+ }
305
+
306
+ export type BrowserRunInteractiveRequestListener = (request: BrowserRunInteractiveRequest) => void;
307
+
308
+ export type BrowserRunCloudflareCommand =
309
+ | "Cloudflare.getLiveView"
310
+ | "Cloudflare.handoff"
311
+ | "Cloudflare.getHandoffState";
312
+
313
+ /** Narrow CDP boundary for Cloudflare commands absent from the pinned protocol types. */
314
+ export interface BrowserRunInteractiveCdpSession {
315
+ readonly send: (command: BrowserRunCloudflareCommand, parameters: unknown) => Promise<unknown>;
316
+ readonly detach: () => Promise<void>;
317
+ }
318
+
319
+ /** Narrow page boundary used by deterministic tests; SDK values remain in this package. */
320
+ export interface BrowserRunInteractivePage {
321
+ readonly identity?: () => Promise<BrowserRunPageIdentity>;
322
+ readonly close: () => Promise<void>;
323
+ readonly setBypassServiceWorker: (enabled: boolean) => Promise<void>;
324
+ readonly setRequestInterception: (enabled: boolean) => Promise<void>;
325
+ readonly onRequest: (listener: BrowserRunInteractiveRequestListener) => void;
326
+ readonly offRequest: (listener: BrowserRunInteractiveRequestListener) => void;
327
+ readonly goto: (url: string) => Promise<void>;
328
+ readonly url: () => unknown;
329
+ readonly readText: (selector: string | undefined, maximumBytes: number) => Promise<unknown>;
330
+ readonly fill: (
331
+ selector: string,
332
+ value: string,
333
+ signal: AbortSignal,
334
+ onDispatch: () => void,
335
+ onComplete?: () => void,
336
+ expectedTarget?: BrowserExpectedTarget,
337
+ ) => Promise<unknown>;
338
+ readonly click: (
339
+ selector: string,
340
+ signal: AbortSignal,
341
+ onDispatch: () => void,
342
+ onComplete?: () => void,
343
+ expectedTarget?: BrowserExpectedTarget,
344
+ ) => Promise<unknown>;
345
+ readonly selectFile: (
346
+ request: BrowserSelectFileRequest,
347
+ signal: AbortSignal,
348
+ onDispatch: () => void,
349
+ onComplete?: () => void,
350
+ ) => Promise<unknown>;
351
+ readonly screenshot: (fullPage: boolean) => Promise<unknown>;
352
+ readonly scroll: (deltaX: number, deltaY: number) => Promise<void>;
353
+ readonly setViewport: (viewport: BrowserRunViewport) => Promise<void>;
354
+ readonly createCdpSession: () => Promise<BrowserRunInteractiveCdpSession>;
355
+ }
356
+
357
+ export interface BrowserRunInteractiveContext {
358
+ readonly newPage: () => Promise<BrowserRunInteractivePage>;
359
+ readonly close: () => Promise<void>;
360
+ }
361
+
362
+ export interface BrowserRunInteractiveBrowser {
363
+ readonly detach?: () => Promise<void>;
364
+ readonly reattach?: (
365
+ identity: BrowserRunPageIdentity,
366
+ ) => Promise<
367
+ | { readonly context: BrowserRunInteractiveContext; readonly page: BrowserRunInteractivePage }
368
+ | undefined
369
+ >;
370
+ readonly createContext: () => Promise<BrowserRunInteractiveContext>;
371
+ readonly close: () => Promise<void>;
372
+ readonly sessionId: () => unknown;
373
+ readonly isConnected: () => boolean;
374
+ readonly onDisconnected: (listener: () => void) => void;
375
+ readonly offDisconnected: (listener: () => void) => void;
376
+ }
377
+
378
+ /** Host-supplied Browser Run allocation and connection transport. */
379
+ export class BrowserRunInteractiveBinding extends Context.Service<
380
+ BrowserRunInteractiveBinding,
381
+ {
382
+ readonly acquire: (keepAliveMillis: number) => Promise<unknown>;
383
+ readonly connect: (
384
+ sessionId: string,
385
+ signal?: AbortSignal,
386
+ ) => Promise<BrowserRunInteractiveBrowser>;
387
+ /** Success proves whole-browser termination or exact-session absence. */
388
+ readonly closeSession: (
389
+ sessionId: Redacted.Redacted<string>,
390
+ ) => Effect.Effect<void, InteractiveBrowserError>;
391
+ }
392
+ >()("@effect-agent/platform-cloudflare/BrowserRunInteractiveBinding") {
393
+ static layer(options: {
394
+ readonly browser: BrowserRun;
395
+ readonly viewport?: BrowserRunViewport;
396
+ }): Layer.Layer<
397
+ BrowserRunInteractiveBinding,
398
+ InteractiveBrowserPolicyDeniedError,
399
+ BrowserRunSessionLifecycle
400
+ > {
401
+ return Layer.effect(BrowserRunInteractiveBinding)(
402
+ Effect.gen(function* () {
403
+ const lifecycle = yield* BrowserRunSessionLifecycle;
404
+ const binding = yield* BrowserRunBinding;
405
+
406
+ const viewport =
407
+ options.viewport === undefined ? undefined : yield* decodeViewport(options.viewport);
408
+
409
+ return {
410
+ acquire: async (keepAliveMillis: number) =>
411
+ binding.acquire(keepAliveMillis, "interactive.acquire"),
412
+ connect: async (sessionId: string, signal?: AbortSignal) =>
413
+ makeProductionBrowser(
414
+ await binding.connect(sessionId, "interactive.connect", signal).browser,
415
+ sessionId,
416
+ viewport,
417
+ ),
418
+ closeSession: (sessionId: Redacted.Redacted<string>) =>
419
+ lifecycle
420
+ .close(sessionId)
421
+ .pipe(Effect.mapError((cause) => actionError("close", cause))),
422
+ };
423
+ }),
424
+ ).pipe(Layer.provide(BrowserRunBinding.layer(options.browser)));
425
+ }
426
+ }
427
+
428
+ /** Private target identity; never include this checkpoint in model-visible records. */
429
+ export class BrowserRunPageIdentity extends Schema.Class<BrowserRunPageIdentity>(
430
+ "BrowserRunPageIdentity",
431
+ )({
432
+ contextId: BrowserRunSessionId,
433
+ targetId: BrowserRunSessionId,
434
+ }) {}
435
+
436
+ /** Host-owned recovery data. Persist with the application's input receipts and ownership fence. */
437
+ export class BrowserRunInteractiveCheckpoint extends Schema.Class<BrowserRunInteractiveCheckpoint>(
438
+ "BrowserRunInteractiveCheckpoint",
439
+ )({
440
+ sessionId: Schema.RedactedFromValue(BrowserRunSessionId),
441
+ page: BrowserRunPageIdentity,
442
+ policy: InteractiveBrowserPolicy,
443
+ startedAt: Schema.Natural,
444
+ consumedActions: Schema.Natural.check(Schema.isLessThanOrEqualTo(1_000)),
445
+ inputState: Schema.Literals(["idle", "running", "unknown"]),
446
+ }) {}
447
+
448
+ export type BrowserRunInputState = "idle" | "running" | "unknown";
449
+
450
+ export interface BrowserRunInteractiveSession {
451
+ readonly handle: BrowserHandle;
452
+ readonly checkpoint: Effect.Effect<BrowserRunInteractiveCheckpoint, InteractiveBrowserError>;
453
+ /** Invalidate this owner and disconnect locally, retaining the exact remote page until its deadline.
454
+ * Checkpoint and durable input receipts must be persisted first. Never grants another owner authority.
455
+ */
456
+ readonly detach: Effect.Effect<void, InteractiveBrowserError>;
457
+ readonly inputState: Effect.Effect<BrowserRunInputState>;
458
+ /** Wait at most 500 ms for local SDK input. A restart/transport-unknown fence cannot be drained. */
459
+ readonly drainInput: Effect.Effect<BrowserRunInputState>;
460
+ readonly sessionId: Redacted.Redacted<string>;
461
+ /**
462
+ * Resize without charging an agent action or changing emulation modes. Shares
463
+ * the handle's fail-fast lock, page-policy preflight, and elapsed deadline.
464
+ * An interrupted resize fences further input until the SDK settles; no resize is retried.
465
+ * The host must authorize callers. No viewer ownership or durable state is added.
466
+ */
467
+ readonly resizeViewport: (
468
+ viewport: BrowserRunViewport,
469
+ ) => Effect.Effect<void, InteractiveBrowserError>;
470
+ readonly getLiveView: (
471
+ request: BrowserRunLiveViewRequest,
472
+ ) => Effect.Effect<BrowserRunLiveViewResult, InteractiveBrowserError>;
473
+ readonly handoff: (
474
+ request: BrowserRunHandoffRequest,
475
+ ) => Effect.Effect<BrowserRunHandoffResult, InteractiveBrowserError>;
476
+ readonly getHandoffState: Effect.Effect<BrowserRunHandoffState, InteractiveBrowserError>;
477
+ readonly close: Effect.Effect<void, InteractiveBrowserError>;
478
+ }
479
+
480
+ /** Persist the private cleanup identity before connecting or creating a page. */
481
+ export interface BrowserRunInteractiveAcquisition {
482
+ readonly sessionId: Redacted.Redacted<string>;
483
+ /** Connect at most once, within the acquisition's original scope and elapsed deadline. */
484
+ readonly connect: Effect.Effect<BrowserRunInteractiveSession, InteractiveBrowserError>;
485
+ }
486
+
487
+ /** Cloudflare host authority kept separate from the provider-neutral browser handle. */
488
+ export class BrowserRunInteractiveHost extends Context.Service<
489
+ BrowserRunInteractiveHost,
490
+ {
491
+ readonly cleanupSemantics?: "confirmed-terminal";
492
+ readonly acquire: (
493
+ policy: InteractiveBrowserPolicy,
494
+ ) => Effect.Effect<BrowserRunInteractiveAcquisition, InteractiveBrowserError, Scope.Scope>;
495
+ readonly open: (
496
+ policy: InteractiveBrowserPolicy,
497
+ ) => Effect.Effect<BrowserRunInteractiveSession, InteractiveBrowserError, Scope.Scope>;
498
+ /** Requires exclusive host ownership. Never allocates a replacement page or replays an action.
499
+ * pendingInput must include durable receipts written after the checkpoint. Unknown input keeps
500
+ * mutations and human control fenced; reads remain available. Only confirmed close ends that fence.
501
+ */
502
+ readonly resume: (
503
+ checkpoint: BrowserRunInteractiveCheckpoint,
504
+ options: { readonly pendingInput: boolean },
505
+ ) => Effect.Effect<BrowserRunInteractiveSession, InteractiveBrowserError, Scope.Scope>;
506
+ readonly closeSession: (
507
+ sessionId: Redacted.Redacted<string>,
508
+ ) => Effect.Effect<void, InteractiveBrowserError>;
509
+ }
510
+ >()("@effect-agent/platform-cloudflare/BrowserRunInteractiveHost") {}
511
+
512
+ const makeProductionRequest = (request: HTTPRequest): BrowserRunInteractiveRequest => ({
513
+ url: () => request.url(),
514
+ abort: () => request.abort("blockedbyclient"),
515
+ continue: () => request.continue(),
516
+ });
517
+
518
+ const makeProductionCdpSession = (session: CDPSession): BrowserRunInteractiveCdpSession => ({
519
+ send: async (command, parameters) => {
520
+ const send = Reflect.get(session, "send");
521
+
522
+ return await Reflect.apply(send, session, [command, parameters]);
523
+ },
524
+ detach: () => session.detach(),
525
+ });
526
+
527
+ class BrowserRunActionUndispatched extends Error {
528
+ readonly matchCount: number;
529
+
530
+ constructor(matchCount: number) {
531
+ super("The browser action selector did not resolve to exactly one element");
532
+ this.matchCount = matchCount;
533
+ }
534
+ }
535
+
536
+ const readActionTarget = (page: Page, selector: string): Promise<unknown> =>
537
+ page.evaluate((requestedSelector) => {
538
+ const pageDocument = Reflect.get(globalThis, "document");
539
+ let matches;
540
+
541
+ try {
542
+ matches = Reflect.apply(Reflect.get(pageDocument, "querySelectorAll"), pageDocument, [
543
+ requestedSelector,
544
+ ]);
545
+ } catch (cause) {
546
+ if (cause instanceof Error && cause.name === "SyntaxError") {
547
+ return { matchCount: 0, invalidSelector: true };
548
+ }
549
+ throw cause;
550
+ }
551
+ if (typeof matches !== "object" || matches === null) throw new Error("Invalid query result");
552
+ const matchCount = Math.min(10_000, Reflect.get(matches, "length"));
553
+ const element = Reflect.get(matches, 0);
554
+
555
+ if (element === undefined) return { matchCount };
556
+
557
+ const associated = Reflect.get(element, "control") ?? element;
558
+ const tagName = String(Reflect.get(associated, "tagName") ?? "").toLowerCase();
559
+ const inputType = String(Reflect.get(associated, "type") ?? "").toLowerCase();
560
+
561
+ const role = String(
562
+ Reflect.apply(Reflect.get(element, "getAttribute"), element, ["role"]) ?? "",
563
+ ).toLowerCase();
564
+
565
+ const kind =
566
+ tagName === "button" || role === "button"
567
+ ? "button"
568
+ : inputType === "checkbox" || role === "checkbox" || role === "switch"
569
+ ? "checkbox"
570
+ : inputType === "radio" || role === "radio"
571
+ ? "radio"
572
+ : tagName === "select"
573
+ ? "select"
574
+ : tagName === "input" || tagName === "textarea"
575
+ ? "text"
576
+ : tagName === "a"
577
+ ? "link"
578
+ : "other";
579
+
580
+ const checked = Reflect.get(associated, "checked");
581
+
582
+ const selected =
583
+ tagName === "select"
584
+ ? Reflect.get(associated, "selectedIndex") >= 0
585
+ : Reflect.get(associated, "selected");
586
+
587
+ const disabled = Reflect.get(associated, "disabled");
588
+ const required = Reflect.get(associated, "required");
589
+ const validity = Reflect.get(associated, "validity");
590
+ const form = Reflect.get(associated, "form");
591
+
592
+ const formMatches =
593
+ form === null || form === undefined ? undefined : Reflect.get(form, "matches");
594
+
595
+ const ariaChecked = Reflect.apply(Reflect.get(element, "getAttribute"), element, [
596
+ "aria-checked",
597
+ ]);
598
+
599
+ const ariaDisabled = Reflect.apply(Reflect.get(element, "getAttribute"), element, [
600
+ "aria-disabled",
601
+ ]);
602
+
603
+ const ariaSelected = Reflect.apply(Reflect.get(element, "getAttribute"), element, [
604
+ "aria-selected",
605
+ ]);
606
+
607
+ return {
608
+ matchCount,
609
+ kind,
610
+ ...(typeof checked === "boolean"
611
+ ? { checked }
612
+ : ariaChecked === "true" || ariaChecked === "false"
613
+ ? { checked: ariaChecked === "true" }
614
+ : {}),
615
+ ...(typeof selected === "boolean"
616
+ ? { selected }
617
+ : ariaSelected === "true" || ariaSelected === "false"
618
+ ? { selected: ariaSelected === "true" }
619
+ : {}),
620
+ disabled: typeof disabled === "boolean" ? disabled : ariaDisabled === "true",
621
+ ...(typeof required === "boolean" ? { required } : {}),
622
+ ...(validity !== undefined && typeof Reflect.get(validity, "valid") === "boolean"
623
+ ? { valid: Reflect.get(validity, "valid") }
624
+ : {}),
625
+ ...(typeof formMatches === "function"
626
+ ? { formValid: Reflect.apply(formMatches, form, [":valid"]) }
627
+ : {}),
628
+ };
629
+ }, selector);
630
+
631
+ // SDK promises cannot be cancelled. Clear our timer and observe late rejections;
632
+ // the owning browser Scope is responsible for terminating the remote session.
633
+ const boundedBestEffort = async <A>(
634
+ promise: Promise<A>,
635
+ millis: number,
636
+ ): Promise<A | undefined> => {
637
+ let timer: ReturnType<typeof setTimeout> | number | undefined;
638
+
639
+ try {
640
+ return await Promise.race([
641
+ promise.catch(() => undefined),
642
+ new Promise<undefined>((resolve) => {
643
+ timer = setTimeout(resolve, millis);
644
+ }),
645
+ ]);
646
+ } finally {
647
+ clearTimeout(timer);
648
+ }
649
+ };
650
+
651
+ const readActionTargetAfter = (page: Page, selector: string) =>
652
+ boundedBestEffort(
653
+ readActionTarget(page, selector).then(Schema.decodeUnknownSync(ActionTargetState)),
654
+ ACTION_POST_STATE_MILLIS,
655
+ );
656
+
657
+ const makeActionRequestTracker = (page: Page, signal: AbortSignal) => {
658
+ const pending = new Set<HTTPRequest>();
659
+ let total = 0;
660
+ let status2xx = 0;
661
+ let status3xx = 0;
662
+ let status4xx = 0;
663
+ let status5xx = 0;
664
+ let failed = 0;
665
+ let lastChange = performance.now();
666
+ let closed = false;
667
+ let wake: (() => void) | undefined;
668
+ let timer: ReturnType<typeof setTimeout> | number | undefined;
669
+
670
+ const relevant = (request: HTTPRequest) => {
671
+ const resourceType = request.resourceType();
672
+
673
+ return resourceType === "fetch" || resourceType === "xhr";
674
+ };
675
+
676
+ const onRequest = (request: HTTPRequest) => {
677
+ if (!relevant(request)) return;
678
+ pending.add(request);
679
+ total++;
680
+ lastChange = performance.now();
681
+ };
682
+
683
+ const onFinished = (request: HTTPRequest) => {
684
+ if (!pending.delete(request)) return;
685
+ let status: number | undefined;
686
+
687
+ try {
688
+ status = request.response()?.status();
689
+ } catch {
690
+ // Provider response details remain intentionally unavailable to diagnostics.
691
+ }
692
+ if (status !== undefined) {
693
+ if (status >= 200 && status < 300) status2xx++;
694
+ else if (status >= 300 && status < 400) status3xx++;
695
+ else if (status >= 400 && status < 500) status4xx++;
696
+ else if (status >= 500 && status < 600) status5xx++;
697
+ }
698
+ lastChange = performance.now();
699
+ };
700
+
701
+ const onFailed = (request: HTTPRequest) => {
702
+ if (!pending.delete(request)) return;
703
+ failed++;
704
+ lastChange = performance.now();
705
+ };
706
+
707
+ const close = () => {
708
+ if (closed) return;
709
+ closed = true;
710
+ page.off("request", onRequest);
711
+ page.off("requestfinished", onFinished);
712
+ page.off("requestfailed", onFailed);
713
+ signal.removeEventListener("abort", close);
714
+ clearTimeout(timer);
715
+ wake?.();
716
+ };
717
+
718
+ try {
719
+ page.on("request", onRequest);
720
+ page.on("requestfinished", onFinished);
721
+ page.on("requestfailed", onFailed);
722
+ signal.addEventListener("abort", close, { once: true });
723
+ if (signal.aborted) close();
724
+ } catch (cause) {
725
+ close();
726
+ throw cause;
727
+ }
728
+
729
+ const wait = async () => {
730
+ const startedAt = performance.now();
731
+ let settleTimedOut = false;
732
+
733
+ while (!closed) {
734
+ const now = performance.now();
735
+
736
+ if (pending.size === 0 && now - lastChange >= ACTION_NETWORK_QUIET_MILLIS) break;
737
+ if (now - startedAt >= ACTION_NETWORK_SETTLE_MILLIS) {
738
+ settleTimedOut = true;
739
+ break;
740
+ }
741
+ await new Promise<void>((resolve) => {
742
+ wake = resolve;
743
+ timer = setTimeout(() => resolve(), 50);
744
+ });
745
+ wake = undefined;
746
+ }
747
+
748
+ return {
749
+ total,
750
+ status2xx,
751
+ status3xx,
752
+ status4xx,
753
+ status5xx,
754
+ failed,
755
+ pending: pending.size,
756
+ settleTimedOut,
757
+ };
758
+ };
759
+
760
+ return {
761
+ wait,
762
+ close,
763
+ markActionSettled: () => {
764
+ lastChange = performance.now();
765
+ },
766
+ };
767
+ };
768
+
769
+ const disposeActionHandles = async (handles: ReadonlyArray<{ dispose: () => Promise<void> }>) => {
770
+ await boundedBestEffort(
771
+ Promise.allSettled(handles.map(async (handle) => handle.dispose())),
772
+ ACTION_POST_STATE_MILLIS,
773
+ );
774
+ };
775
+
776
+ /** Runs entirely in the page realm for both observations and the last bound-element guard. */
777
+ const observePage = (
778
+ target: object | undefined,
779
+ requestedSelector: string | undefined,
780
+ maximum: number,
781
+ maximumControls: number,
782
+ input?: {
783
+ readonly mode: "click" | "fill";
784
+ readonly expectedTarget: BrowserExpectedTarget;
785
+ readonly value?: string;
786
+ },
787
+ ) => {
788
+ const pageDocument = Reflect.get(globalThis, "document");
789
+
790
+ const matches =
791
+ requestedSelector === undefined
792
+ ? undefined
793
+ : Reflect.apply(Reflect.get(pageDocument, "querySelectorAll"), pageDocument, [
794
+ requestedSelector,
795
+ ]);
796
+
797
+ const selectorMatchCount =
798
+ matches === undefined || matches === null
799
+ ? 1
800
+ : Math.min(10_000, Reflect.get(matches, "length"));
801
+
802
+ const element =
803
+ target ??
804
+ (matches === undefined || matches === null
805
+ ? Reflect.get(pageDocument, "body")
806
+ : Reflect.get(matches, 0));
807
+
808
+ if (target !== undefined && Reflect.get(target, "isConnected") !== true)
809
+ return { _tag: "MissingElement" };
810
+
811
+ if (element === null) return { _tag: "MissingElement" };
812
+ if (element === undefined) return { _tag: "MissingElement" };
813
+ const innerText = Reflect.get(element, "innerText");
814
+ const textContent = Reflect.get(element, "textContent");
815
+
816
+ const pageText =
817
+ typeof innerText === "string" ? innerText : typeof textContent === "string" ? textContent : "";
818
+
819
+ const primaryControlSelector =
820
+ 'input,select,textarea,label,button,[role="checkbox"],[role="radio"],[role="option"],[role="switch"],[role="tab"],[role="button"]';
821
+
822
+ const optionSelector = "select option";
823
+ const secondaryControlSelector = "a[href]";
824
+ const controlSelector = `${primaryControlSelector},${optionSelector},${secondaryControlSelector}`;
825
+
826
+ const selectorFor = (candidate: object) => {
827
+ const parts: Array<string> = [];
828
+ let current: object | null = candidate;
829
+
830
+ while (current !== null && current !== undefined) {
831
+ const tagName = String(Reflect.get(current, "tagName") ?? "").toLowerCase();
832
+
833
+ if (tagName === "") break;
834
+ const parent: object | null = Reflect.get(current, "parentElement");
835
+
836
+ if (parent === null) {
837
+ parts.push(tagName);
838
+ break;
839
+ }
840
+ let sibling = Reflect.get(current, "previousElementSibling");
841
+ let index = 1;
842
+
843
+ while (sibling !== null && sibling !== undefined) {
844
+ if (String(Reflect.get(sibling, "tagName") ?? "").toLowerCase() === tagName) index++;
845
+ sibling = Reflect.get(sibling, "previousElementSibling");
846
+ }
847
+ parts.push(`${tagName}:nth-of-type(${index})`);
848
+ current = parent;
849
+ }
850
+
851
+ return parts.reverse().join(" > ");
852
+ };
853
+
854
+ const visible = (candidate: object) => {
855
+ const hidden = Reflect.get(candidate, "hidden");
856
+
857
+ const ariaHidden = Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, [
858
+ "aria-hidden",
859
+ ]);
860
+
861
+ const rects = Reflect.apply(Reflect.get(candidate, "getClientRects"), candidate, []);
862
+
863
+ return (
864
+ hidden !== true &&
865
+ ariaHidden !== "true" &&
866
+ typeof rects === "object" &&
867
+ rects !== null &&
868
+ Reflect.get(rects, "length") > 0
869
+ );
870
+ };
871
+
872
+ const candidates: Array<object> = [];
873
+ let controlsTruncated = false;
874
+
875
+ const consider = (candidate: object) => {
876
+ const tagName = String(Reflect.get(candidate, "tagName") ?? "").toLowerCase();
877
+
878
+ // Collapsed native options have no client rects. Their owning
879
+ // select determines visibility; observe text/selection, never value.
880
+ const visibilityTarget =
881
+ tagName === "option"
882
+ ? Reflect.apply(Reflect.get(candidate, "closest"), candidate, ["select"])
883
+ : candidate;
884
+
885
+ const actionable = tagName !== "label" || Reflect.get(candidate, "control") !== null;
886
+
887
+ if (
888
+ !actionable ||
889
+ typeof visibilityTarget !== "object" ||
890
+ visibilityTarget === null ||
891
+ !visible(visibilityTarget)
892
+ )
893
+ return;
894
+ candidates.push(candidate);
895
+ if (candidates.length > maximumControls) controlsTruncated = true;
896
+ };
897
+
898
+ const elementMatches = Reflect.get(element, "matches");
899
+
900
+ if (
901
+ typeof elementMatches === "function" &&
902
+ Reflect.apply(elementMatches, element, [controlSelector])
903
+ ) {
904
+ consider(element);
905
+ }
906
+
907
+ const considerSelector = (candidateSelector: string) => {
908
+ const descendants = Reflect.apply(Reflect.get(element, "querySelectorAll"), element, [
909
+ candidateSelector,
910
+ ]);
911
+
912
+ if (typeof descendants !== "object" || descendants === null) return;
913
+ const descendantCount = Reflect.get(descendants, "length");
914
+
915
+ for (let index = 0; index < descendantCount && !controlsTruncated; index++) {
916
+ consider(Reflect.get(descendants, index));
917
+ }
918
+ };
919
+
920
+ considerSelector(primaryControlSelector);
921
+ if (!controlsTruncated) considerSelector(optionSelector);
922
+ if (!controlsTruncated) considerSelector(secondaryControlSelector);
923
+
924
+ const identityKey = Symbol.for("@effect-agent/browser-observation");
925
+ let identity = Reflect.get(globalThis, identityKey);
926
+
927
+ if (identity === undefined || identity.document !== pageDocument) {
928
+ identity = {
929
+ document: pageDocument,
930
+ documentId: crypto.getRandomValues(new Uint32Array(4)).join("-"),
931
+ nodes: new WeakMap<object, string>(),
932
+ };
933
+ Reflect.set(globalThis, identityKey, identity);
934
+ }
935
+
936
+ const controls = candidates.slice(0, maximumControls).map((candidate) => {
937
+ let nodeId = identity.nodes.get(candidate);
938
+
939
+ if (nodeId === undefined) {
940
+ nodeId = crypto.getRandomValues(new Uint32Array(4)).join("-");
941
+ identity.nodes.set(candidate, nodeId);
942
+ }
943
+ const associated = Reflect.get(candidate, "control") ?? candidate;
944
+ const tagName = String(Reflect.get(candidate, "tagName") ?? "").toLowerCase();
945
+ const inputType = String(Reflect.get(associated, "type") ?? "").toLowerCase();
946
+
947
+ const role = String(
948
+ Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, ["role"]) ?? "",
949
+ ).toLowerCase();
950
+
951
+ const ariaLabel = Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, [
952
+ "aria-label",
953
+ ]);
954
+
955
+ const candidateText =
956
+ tagName === "textarea" || tagName === "input" || tagName === "select"
957
+ ? undefined
958
+ : Reflect.get(candidate, tagName === "option" ? "label" : "innerText");
959
+
960
+ const associatedLabels = Reflect.get(associated, "labels");
961
+
962
+ const associatedLabel =
963
+ associatedLabels !== undefined &&
964
+ associatedLabels !== null &&
965
+ Reflect.get(associatedLabels, "length") > 0
966
+ ? Reflect.get(Reflect.get(associatedLabels, 0), "innerText")
967
+ : undefined;
968
+
969
+ const label = String(
970
+ typeof ariaLabel === "string" && ariaLabel !== ""
971
+ ? ariaLabel
972
+ : typeof candidateText === "string" && candidateText !== ""
973
+ ? candidateText
974
+ : (associatedLabel ?? ""),
975
+ )
976
+ .replace(/\s+/g, " ")
977
+ .trim()
978
+ .slice(0, 200);
979
+
980
+ const checked = Reflect.get(associated, "checked");
981
+
982
+ const selected =
983
+ tagName === "select"
984
+ ? Reflect.get(associated, "selectedIndex") >= 0
985
+ : Reflect.get(associated, "selected");
986
+
987
+ const disabled = Reflect.get(associated, "disabled");
988
+ const required = Reflect.get(associated, "required");
989
+ const validity = Reflect.get(associated, "validity");
990
+ const form = Reflect.get(associated, "form");
991
+
992
+ const formMatches =
993
+ form === null || form === undefined ? undefined : Reflect.get(form, "matches");
994
+
995
+ const ariaChecked = Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, [
996
+ "aria-checked",
997
+ ]);
998
+
999
+ const ariaSelected = Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, [
1000
+ "aria-selected",
1001
+ ]);
1002
+
1003
+ const ariaDisabled = Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, [
1004
+ "aria-disabled",
1005
+ ]);
1006
+
1007
+ return {
1008
+ nodeId,
1009
+ ...(inputType === "" ? {} : { inputType: inputType.slice(0, 64) }),
1010
+ selector: selectorFor(candidate),
1011
+ kind: (tagName === "label"
1012
+ ? `label:${inputType || "control"}`
1013
+ : tagName === "input"
1014
+ ? `input:${inputType || "text"}`
1015
+ : role !== ""
1016
+ ? `role:${role}`
1017
+ : tagName
1018
+ ).slice(0, 128),
1019
+ ...(label === "" ? {} : { label }),
1020
+ ...(typeof checked === "boolean"
1021
+ ? { checked }
1022
+ : ariaChecked === "true" || ariaChecked === "false"
1023
+ ? { checked: ariaChecked === "true" }
1024
+ : {}),
1025
+ ...(typeof selected === "boolean"
1026
+ ? { selected }
1027
+ : ariaSelected === "true" || ariaSelected === "false"
1028
+ ? { selected: ariaSelected === "true" }
1029
+ : {}),
1030
+ ...(typeof disabled === "boolean"
1031
+ ? { disabled }
1032
+ : ariaDisabled === "true" || ariaDisabled === "false"
1033
+ ? { disabled: ariaDisabled === "true" }
1034
+ : {}),
1035
+ ...(typeof required === "boolean" ? { required } : {}),
1036
+ ...(validity !== undefined && typeof Reflect.get(validity, "valid") === "boolean"
1037
+ ? { valid: Reflect.get(validity, "valid") }
1038
+ : {}),
1039
+ ...(typeof formMatches === "function"
1040
+ ? { formValid: Reflect.apply(formMatches, form, [":valid"]) }
1041
+ : {}),
1042
+ };
1043
+ });
1044
+
1045
+ if (input !== undefined) {
1046
+ const expected = input.expectedTarget;
1047
+ const control = controls.find((candidate) => candidate.nodeId === expected.nodeId);
1048
+
1049
+ const fields = [
1050
+ "kind",
1051
+ "inputType",
1052
+ "label",
1053
+ "checked",
1054
+ "selected",
1055
+ "disabled",
1056
+ "required",
1057
+ "valid",
1058
+ "formValid",
1059
+ ] as const;
1060
+
1061
+ if (
1062
+ target === undefined ||
1063
+ identity.documentId !== expected.documentId ||
1064
+ identity.nodes.get(target) !== expected.nodeId ||
1065
+ control === undefined ||
1066
+ (expected.state !== undefined &&
1067
+ fields.some((field) => control[field] !== expected.state?.[field])) ||
1068
+ Reflect.get(target, "isConnected") !== true
1069
+ )
1070
+ return { _tag: "MissingElement" };
1071
+ if (expected.scopeSelector !== undefined) {
1072
+ let roots;
1073
+
1074
+ try {
1075
+ roots = Reflect.apply(Reflect.get(pageDocument, "querySelectorAll"), pageDocument, [
1076
+ expected.scopeSelector,
1077
+ ]);
1078
+ } catch {
1079
+ return { _tag: "MissingElement" };
1080
+ }
1081
+ if (typeof roots !== "object" || roots === null) return { _tag: "MissingElement" };
1082
+ const root = Reflect.get(roots, 0);
1083
+
1084
+ if (
1085
+ Reflect.get(roots, "length") !== 1 ||
1086
+ root === undefined ||
1087
+ !Reflect.apply(Reflect.get(root, "contains"), root, [target])
1088
+ )
1089
+ return { _tag: "MissingElement" };
1090
+ }
1091
+ // Validation and dispatch share one page JS task. No coordinate lookup, selector
1092
+ // re-resolution, or asynchronous boundary can select a replacement node.
1093
+ if (input.mode === "click") {
1094
+ const prototype = Reflect.get(Reflect.get(globalThis, "HTMLElement"), "prototype");
1095
+
1096
+ Reflect.apply(Reflect.get(prototype, "click"), target, []);
1097
+ } else {
1098
+ let prototype = Reflect.getPrototypeOf(target);
1099
+ let setValue: ((value: string) => void) | undefined;
1100
+
1101
+ while (prototype !== null) {
1102
+ const setter = Reflect.getOwnPropertyDescriptor(prototype, "value")?.set;
1103
+
1104
+ if (typeof setter === "function") {
1105
+ setValue = setter;
1106
+ break;
1107
+ }
1108
+ prototype = Reflect.getPrototypeOf(prototype);
1109
+ }
1110
+ if (setValue === undefined || input.value === undefined) return { _tag: "MissingElement" };
1111
+ Reflect.apply(setValue, target, [input.value]);
1112
+ const dispatchEvent = Reflect.get(target, "dispatchEvent");
1113
+
1114
+ Reflect.apply(dispatchEvent, target, [new Event("input", { bubbles: true })]);
1115
+ Reflect.apply(dispatchEvent, target, [new Event("change", { bubbles: true })]);
1116
+ }
1117
+
1118
+ return { _tag: "Text", text: "" };
1119
+ }
1120
+
1121
+ // JSON is the bounded wire representation of this existing text result.
1122
+ // eslint-disable-next-line no-restricted-properties
1123
+ const text = JSON.stringify({
1124
+ documentId: identity.documentId,
1125
+ pageText,
1126
+ selectorMatchCount,
1127
+ controls,
1128
+ controlsTruncated,
1129
+ });
1130
+
1131
+ const observed = new TextEncoder().encode(text).byteLength;
1132
+
1133
+ return observed > maximum ? { _tag: "OverLimit", observed } : { _tag: "Text", text };
1134
+ };
1135
+
1136
+ const runObservedPageAction = async (
1137
+ page: Page,
1138
+ selector: string,
1139
+ signal: AbortSignal,
1140
+ onDispatch: () => void,
1141
+ action: (element: NonNullable<Awaited<ReturnType<Page["$"]>>>) => Promise<void>,
1142
+ validate?: (element: NonNullable<Awaited<ReturnType<Page["$"]>>>) => Promise<boolean>,
1143
+ onComplete?: () => void,
1144
+ ): Promise<unknown> => {
1145
+ if (signal.aborted) throw new BrowserRunActionUndispatched(0);
1146
+
1147
+ const before = Schema.decodeUnknownSync(ActionTargetState)(
1148
+ await readActionTarget(page, selector),
1149
+ );
1150
+
1151
+ if (before.matchCount !== 1 || before.invalidSelector === true) {
1152
+ throw new BrowserRunActionUndispatched(before.matchCount);
1153
+ }
1154
+ const matches = await page.$$(selector);
1155
+
1156
+ if (matches.length !== 1 || matches[0] === undefined) {
1157
+ await disposeActionHandles(matches);
1158
+ throw new BrowserRunActionUndispatched(Math.min(10_000, matches.length));
1159
+ }
1160
+ if (signal.aborted) {
1161
+ await disposeActionHandles(matches);
1162
+ throw new BrowserRunActionUndispatched(1);
1163
+ }
1164
+
1165
+ let tracker: ReturnType<typeof makeActionRequestTracker> | undefined;
1166
+ let disposing: Promise<void> | undefined;
1167
+ const dispose = () => (disposing ??= disposeActionHandles(matches));
1168
+
1169
+ const onAbort = () => {
1170
+ void dispose();
1171
+ };
1172
+
1173
+ signal.addEventListener("abort", onAbort, { once: true });
1174
+ try {
1175
+ if (validate !== undefined && !(await validate(matches[0])))
1176
+ throw new BrowserRunActionUndispatched(1);
1177
+ tracker = makeActionRequestTracker(page, signal);
1178
+ // No await between the final cancellation fence and SDK dispatch. Once
1179
+ // dispatched, interruption is uncertain, even if the SDK later resolves.
1180
+ if (signal.aborted) throw new BrowserRunActionUndispatched(1);
1181
+ onDispatch();
1182
+ const inputStarted = performance.now();
1183
+
1184
+ await action(matches[0]);
1185
+ const inputFinished = performance.now();
1186
+
1187
+ onComplete?.();
1188
+ tracker.markActionSettled();
1189
+ const network = await tracker.wait();
1190
+ const after = signal.aborted ? undefined : await readActionTargetAfter(page, selector);
1191
+
1192
+ return {
1193
+ before,
1194
+ inputMillis: Math.max(0, inputFinished - inputStarted),
1195
+ observationMillis: Math.max(0, performance.now() - inputFinished),
1196
+ ...(after === undefined ? {} : { after }),
1197
+ afterUnavailable: after === undefined,
1198
+ network,
1199
+ };
1200
+ } finally {
1201
+ tracker?.close();
1202
+ signal.removeEventListener("abort", onAbort);
1203
+ await dispose();
1204
+ }
1205
+ };
1206
+
1207
+ const guardedPageInput = async (
1208
+ element: NonNullable<Awaited<ReturnType<Page["$"]>>>,
1209
+ expectedTarget: BrowserExpectedTarget,
1210
+ mode: "click" | "fill",
1211
+ value?: string,
1212
+ ): Promise<void> => {
1213
+ const observed = Schema.decodeUnknownSync(TextObservation)(
1214
+ await element.evaluate(observePage, undefined, 256 * 1024, 1, {
1215
+ mode,
1216
+ expectedTarget,
1217
+ ...(value === undefined ? {} : { value }),
1218
+ }),
1219
+ );
1220
+
1221
+ if (observed._tag !== "Text") throw new BrowserRunActionUndispatched(1);
1222
+ };
1223
+
1224
+ const makeProductionPage = (page: Page): BrowserRunInteractivePage => {
1225
+ const prepareFileSelection = makeFileSelection(page);
1226
+ const listeners = new Map<BrowserRunInteractiveRequestListener, (request: HTTPRequest) => void>();
1227
+
1228
+ return {
1229
+ identity: async () => {
1230
+ const cdp = await page.createCDPSession();
1231
+
1232
+ try {
1233
+ const { targetInfo } = await cdp.send("Target.getTargetInfo");
1234
+
1235
+ return Schema.decodeUnknownSync(BrowserRunPageIdentity)({
1236
+ contextId: targetInfo.browserContextId,
1237
+ targetId: targetInfo.targetId,
1238
+ });
1239
+ } finally {
1240
+ await cdp.detach();
1241
+ }
1242
+ },
1243
+ close: async () => {
1244
+ if (!page.browser().isConnected()) return;
1245
+ try {
1246
+ await page.close();
1247
+ } catch (cause) {
1248
+ if (!isRemoteClosure(cause)) throw cause;
1249
+ }
1250
+ },
1251
+ setBypassServiceWorker: (enabled) => page.setBypassServiceWorker(enabled),
1252
+ setRequestInterception: (enabled) => page.setRequestInterception(enabled),
1253
+ onRequest: (listener) => {
1254
+ const sdkListener = (request: HTTPRequest) => listener(makeProductionRequest(request));
1255
+
1256
+ listeners.set(listener, sdkListener);
1257
+ page.on("request", sdkListener);
1258
+ },
1259
+ offRequest: (listener) => {
1260
+ const sdkListener = listeners.get(listener);
1261
+
1262
+ if (sdkListener !== undefined) {
1263
+ page.off("request", sdkListener);
1264
+ listeners.delete(listener);
1265
+ }
1266
+ },
1267
+ goto: async (url) => {
1268
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30_000 });
1269
+ },
1270
+ url: () => page.url(),
1271
+ readText: async (selector, maximumBytes) => {
1272
+ const observation = Schema.decodeUnknownSync(TextObservation)(
1273
+ await page.evaluate(observePage, undefined, selector, maximumBytes, MAX_OBSERVED_CONTROLS),
1274
+ );
1275
+
1276
+ if (observation._tag === "Text")
1277
+ Schema.decodeSync(BrowserRunPageObservation)(observation.text);
1278
+
1279
+ return observation;
1280
+ },
1281
+ fill: (selector, value, signal, onDispatch, onComplete, expectedTarget) =>
1282
+ runObservedPageAction(
1283
+ page,
1284
+ selector,
1285
+ signal,
1286
+ onDispatch,
1287
+ (element) =>
1288
+ expectedTarget !== undefined
1289
+ ? guardedPageInput(element, expectedTarget, "fill", value)
1290
+ : element.evaluate((element, nextValue) => {
1291
+ // Bypass instance setters so React can detect the change when events fire.
1292
+ let prototype = Reflect.getPrototypeOf(element);
1293
+ let setValue: ((value: string) => void) | undefined;
1294
+
1295
+ while (prototype !== null) {
1296
+ const setter = Reflect.getOwnPropertyDescriptor(prototype, "value")?.set;
1297
+
1298
+ if (typeof setter === "function") {
1299
+ setValue = setter;
1300
+ break;
1301
+ }
1302
+ prototype = Reflect.getPrototypeOf(prototype);
1303
+ }
1304
+ if (setValue === undefined) {
1305
+ throw new Error("The selector did not resolve to a fillable field");
1306
+ }
1307
+ const focus = Reflect.get(element, "focus");
1308
+
1309
+ if (typeof focus === "function") Reflect.apply(focus, element, []);
1310
+ Reflect.apply(setValue, element, [nextValue]);
1311
+ const dispatchEvent = Reflect.get(element, "dispatchEvent");
1312
+
1313
+ if (typeof dispatchEvent === "function") {
1314
+ Reflect.apply(dispatchEvent, element, [new Event("input", { bubbles: true })]);
1315
+ Reflect.apply(dispatchEvent, element, [new Event("change", { bubbles: true })]);
1316
+ }
1317
+ }, value),
1318
+ undefined,
1319
+ onComplete,
1320
+ ),
1321
+ click: (selector, signal, onDispatch, onComplete, expectedTarget) =>
1322
+ runObservedPageAction(
1323
+ page,
1324
+ selector,
1325
+ signal,
1326
+ onDispatch,
1327
+ (element) =>
1328
+ expectedTarget === undefined
1329
+ ? element.click()
1330
+ : guardedPageInput(element, expectedTarget, "click"),
1331
+ undefined,
1332
+ onComplete,
1333
+ ),
1334
+ selectFile: async (request, signal, onDispatch, onComplete) => {
1335
+ const selection = await prepareFileSelection(request, signal);
1336
+
1337
+ try {
1338
+ return await runObservedPageAction(
1339
+ page,
1340
+ request.selector,
1341
+ signal,
1342
+ onDispatch,
1343
+ selection.select,
1344
+ selection.validate,
1345
+ onComplete,
1346
+ );
1347
+ } finally {
1348
+ await selection.close();
1349
+ }
1350
+ },
1351
+ // Puppeteer materializes the complete image before returning. The adapter
1352
+ // validates the 8 MiB Schema ceiling and pass limit immediately afterward.
1353
+ screenshot: (fullPage) => page.screenshot({ type: "png", fullPage }),
1354
+ scroll: (deltaX, deltaY) =>
1355
+ page.evaluate(
1356
+ (x, y) => {
1357
+ const scrollBy = Reflect.get(globalThis, "scrollBy");
1358
+
1359
+ Reflect.apply(scrollBy, globalThis, [{ left: x, top: y, behavior: "instant" }]);
1360
+ },
1361
+ deltaX,
1362
+ deltaY,
1363
+ ),
1364
+ createCdpSession: async () => makeProductionCdpSession(await page.createCDPSession()),
1365
+ setViewport: (viewport) => page.setViewport(viewport),
1366
+ };
1367
+ };
1368
+
1369
+ const makeProductionContext = (
1370
+ context: BrowserContext,
1371
+ viewport?: BrowserRunViewport,
1372
+ ): BrowserRunInteractiveContext => ({
1373
+ newPage: async () => {
1374
+ const page = await context.newPage();
1375
+
1376
+ if (viewport !== undefined) await page.setViewport(viewport);
1377
+
1378
+ return makeProductionPage(page);
1379
+ },
1380
+ close: async () => {
1381
+ if (!context.browser().isConnected()) return;
1382
+ try {
1383
+ await context.close();
1384
+ } catch (cause) {
1385
+ if (!isRemoteClosure(cause)) throw cause;
1386
+ }
1387
+ },
1388
+ });
1389
+
1390
+ const makeProductionBrowser = (
1391
+ browser: Browser,
1392
+ sessionId: string,
1393
+ viewport?: BrowserRunViewport,
1394
+ ): BrowserRunInteractiveBrowser => ({
1395
+ detach: () => browser.disconnect(),
1396
+ reattach: async (identity) => {
1397
+ const context = browser
1398
+ .browserContexts()
1399
+ .find((candidate) => candidate.id === identity.contextId);
1400
+
1401
+ if (context === undefined) return undefined;
1402
+ const pages = await context.pages();
1403
+
1404
+ if (pages.length > 64) throw new Error("The browser target inventory exceeds its bound");
1405
+ for (const candidate of pages) {
1406
+ const page = makeProductionPage(candidate);
1407
+ const current = await page.identity?.();
1408
+
1409
+ if (current?.targetId === identity.targetId)
1410
+ return { context: makeProductionContext(context), page };
1411
+ }
1412
+
1413
+ return undefined;
1414
+ },
1415
+ createContext: async () => makeProductionContext(await browser.createBrowserContext(), viewport),
1416
+ // Exact-session termination may already have closed the provider transport.
1417
+ close: async () => {
1418
+ if (!browser.isConnected()) return;
1419
+ try {
1420
+ await browser.close();
1421
+ } catch (cause) {
1422
+ if (!isRemoteClosure(cause)) throw cause;
1423
+ }
1424
+ },
1425
+ sessionId: () => sessionId,
1426
+ isConnected: () => browser.isConnected(),
1427
+ onDisconnected: (listener) => {
1428
+ browser.on("disconnected", listener);
1429
+ },
1430
+ offDisconnected: (listener) => {
1431
+ browser.off("disconnected", listener);
1432
+ },
1433
+ });
1434
+
1435
+ const protocolError = (message: string, cause?: unknown): InteractiveBrowserProtocolError =>
1436
+ InteractiveBrowserProtocolError.make({
1437
+ implementation: browserRunInteractiveImplementation,
1438
+ message,
1439
+ ...(cause === undefined ? {} : { cause }),
1440
+ });
1441
+
1442
+ const failReportedProtocol = (
1443
+ operation: string,
1444
+ error: InteractiveBrowserProtocolError,
1445
+ evidence = error.evidence,
1446
+ ) =>
1447
+ reportBrowserCause(operation, Cause.fail(error)).pipe(
1448
+ Effect.andThen(
1449
+ Effect.fail(
1450
+ reportedBrowserError(
1451
+ InteractiveBrowserProtocolError.make({
1452
+ implementation: browserRunInteractiveImplementation,
1453
+ message: error.message,
1454
+ ...(evidence === undefined ? {} : { evidence }),
1455
+ }),
1456
+ ),
1457
+ ),
1458
+ ),
1459
+ );
1460
+
1461
+ const actionError = (
1462
+ operation: BrowserOperation,
1463
+ cause?: unknown,
1464
+ evidence?: InteractiveBrowserFailureEvidence,
1465
+ ): InteractiveBrowserActionError =>
1466
+ InteractiveBrowserActionError.make({
1467
+ implementation: browserRunInteractiveImplementation,
1468
+ operation,
1469
+ ...(evidence === undefined ? {} : { evidence }),
1470
+ message: `The interactive browser ${operation} operation failed`,
1471
+ ...(cause === undefined ? {} : { cause }),
1472
+ });
1473
+
1474
+ const undispatchedActionError = (operation: BrowserOperation): InteractiveBrowserActionError =>
1475
+ InteractiveBrowserActionError.make({
1476
+ implementation: browserRunInteractiveImplementation,
1477
+ operation,
1478
+ message: `The interactive browser ${operation} operation was not dispatched`,
1479
+ evidence: { stage: "preparation", dispatch: "not-dispatched", session: "attached" },
1480
+ });
1481
+
1482
+ /** Recognizes a local pre-dispatch refusal without exposing selector or page content. */
1483
+ export const isBrowserRunUndispatchedActionError = (error: unknown): boolean =>
1484
+ Schema.is(InteractiveBrowserActionError)(error) &&
1485
+ error.implementation.identity === browserRunInteractiveImplementation.identity &&
1486
+ error.evidence?.dispatch === "not-dispatched";
1487
+
1488
+ const policyError = (message: string): InteractiveBrowserPolicyDeniedError =>
1489
+ InteractiveBrowserPolicyDeniedError.make({
1490
+ implementation: browserRunInteractiveImplementation,
1491
+ message,
1492
+ });
1493
+
1494
+ const expiredError = (session: "lost" | "disconnected" = "lost"): InteractiveBrowserExpiredError =>
1495
+ InteractiveBrowserExpiredError.make({
1496
+ implementation: browserRunInteractiveImplementation,
1497
+ message: "The remote browser is no longer usable",
1498
+ evidence: { stage: "preparation", dispatch: "not-dispatched", session },
1499
+ });
1500
+
1501
+ const causeText = (cause: unknown): string => {
1502
+ if (cause instanceof Error) return cause.message.slice(0, 8_000);
1503
+
1504
+ return String(cause).slice(0, 8_000);
1505
+ };
1506
+
1507
+ const isCapacityRefusal = (cause: unknown): boolean =>
1508
+ cause instanceof BrowserRunFailure && cause.status === 429;
1509
+
1510
+ const isRemoteClosure = (cause: unknown): boolean =>
1511
+ /target closed|browser.*closed|session.*closed|connection.*closed|not connected|websocket.*closed/i.test(
1512
+ causeText(cause),
1513
+ );
1514
+
1515
+ const inputMayStillRun = (cause: unknown): boolean =>
1516
+ isRemoteClosure(cause) ||
1517
+ (cause instanceof Error && cause.name === "TimeoutError") ||
1518
+ (cause instanceof BrowserRunFailure && cause.reason === "timeout");
1519
+
1520
+ const snapshotPolicy = Effect.fn("BrowserRunInteractive.snapshotPolicy")(function* (
1521
+ input: InteractiveBrowserPolicy,
1522
+ ): Effect.fn.Return<
1523
+ InteractiveBrowserPolicySnapshot,
1524
+ InteractiveBrowserPolicyDeniedError | InteractiveBrowserUnsupportedError
1525
+ > {
1526
+ const decoded = yield* Schema.decodeEffect(InteractiveBrowserPolicy, {
1527
+ onExcessProperty: "error",
1528
+ })(input).pipe(Effect.mapError(() => policyError("The interactive browser policy is malformed")));
1529
+
1530
+ if (decoded.network._tag === "PublicWeb") {
1531
+ return yield* InteractiveBrowserUnsupportedError.make({
1532
+ implementation: browserRunInteractiveImplementation,
1533
+ feature: "policy",
1534
+ message:
1535
+ "Cloudflare Browser Run cannot enforce the PublicWeb network policy for all session traffic",
1536
+ });
1537
+ }
1538
+
1539
+ return Object.freeze({
1540
+ network:
1541
+ decoded.network._tag === "ExactHosts"
1542
+ ? Object.freeze({
1543
+ _tag: decoded.network._tag,
1544
+ allowedHosts: Object.freeze([...decoded.network.allowedHosts]),
1545
+ })
1546
+ : Object.freeze({ _tag: decoded.network._tag }),
1547
+ maxActions: decoded.maxActions,
1548
+ maxElapsedMillis: decoded.maxElapsedMillis,
1549
+ maxReturnedBytes: decoded.maxReturnedBytes,
1550
+ });
1551
+ });
1552
+
1553
+ const hostAllowed = (policy: InteractiveBrowserPolicySnapshot, value: string): boolean => {
1554
+ if (policy.network._tag === "Unrestricted") return true;
1555
+ try {
1556
+ const url = new URL(value);
1557
+
1558
+ return (
1559
+ url.protocol === "https:" &&
1560
+ url.username === "" &&
1561
+ url.password === "" &&
1562
+ policy.network.allowedHosts.some((host) => host === url.host)
1563
+ );
1564
+ } catch {
1565
+ return false;
1566
+ }
1567
+ };
1568
+
1569
+ const keepAliveMillis = (policy: InteractiveBrowserPolicySnapshot): number =>
1570
+ Math.max(MIN_KEEP_ALIVE_MILLIS, Math.min(MAX_KEEP_ALIVE_MILLIS, policy.maxElapsedMillis));
1571
+
1572
+ class LateBrowserAcquisition extends Error {}
1573
+
1574
+ const closeLateAcquisition = async <A>(
1575
+ signal: AbortSignal,
1576
+ acquire: () => Promise<A>,
1577
+ close: (acquired: A) => Promise<void>,
1578
+ ): Promise<A> => {
1579
+ const acquired = await acquire();
1580
+
1581
+ if (!signal.aborted) return acquired;
1582
+
1583
+ // The SDK does not accept AbortSignal. If an acquisition settles after Effect
1584
+ // has interrupted it, ownership never reaches Scope, so close it here instead.
1585
+ try {
1586
+ await close(acquired);
1587
+ } catch {
1588
+ // The captured runtime reports cleanup failures before this callback absorbs rejection.
1589
+ }
1590
+ throw new LateBrowserAcquisition("The interrupted browser acquisition completed late");
1591
+ };
1592
+
1593
+ const closeWithWarning = (close: () => Promise<void>, warning: string): Effect.Effect<void> =>
1594
+ Effect.tryPromise({
1595
+ try: close,
1596
+ catch: (cause) => protocolError(warning, cause),
1597
+ }).pipe(
1598
+ Effect.timeoutOrElse({
1599
+ duration: Duration.millis(CLEANUP_STEP_TIMEOUT_MILLIS),
1600
+ orElse: () => Effect.fail(protocolError(warning)),
1601
+ }),
1602
+ Effect.catchCause((cause) =>
1603
+ reportBrowserCause("interactive.cleanup", cause).pipe(
1604
+ Effect.andThen(Effect.logWarning(warning)),
1605
+ ),
1606
+ ),
1607
+ );
1608
+
1609
+ const deadlineError = Effect.fn("BrowserRunInteractive.deadlineError")(function* (
1610
+ policy: InteractiveBrowserPolicySnapshot,
1611
+ startedAt: number,
1612
+ ) {
1613
+ const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
1614
+
1615
+ return yield* InteractiveBrowserLimitError.make({
1616
+ implementation: browserRunInteractiveImplementation,
1617
+ limit: "elapsed",
1618
+ maximum: policy.maxElapsedMillis,
1619
+ observed: Math.max(policy.maxElapsedMillis, now - startedAt),
1620
+ message: "The browser elapsed-time limit was reached",
1621
+ });
1622
+ });
1623
+
1624
+ const withinDeadline = Effect.fn("BrowserRunInteractive.withinDeadline")(function* <A, E, R>(
1625
+ effect: Effect.Effect<A, E, R>,
1626
+ policy: InteractiveBrowserPolicySnapshot,
1627
+ startedAt: number,
1628
+ onTimeout?: () => void,
1629
+ ): Effect.fn.Return<A, E | InteractiveBrowserLimitError, R> {
1630
+ const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
1631
+ const elapsed = Math.max(0, now - startedAt);
1632
+ const remaining = policy.maxElapsedMillis - elapsed;
1633
+
1634
+ if (remaining <= 0) return yield* deadlineError(policy, startedAt);
1635
+
1636
+ return yield* effect.pipe(
1637
+ Effect.timeoutOrElse({
1638
+ duration: Duration.millis(remaining),
1639
+ orElse: () =>
1640
+ Effect.sync(() => onTimeout?.()).pipe(Effect.andThen(deadlineError(policy, startedAt))),
1641
+ }),
1642
+ );
1643
+ });
1644
+
1645
+ interface HandleState {
1646
+ readonly closed: { value: boolean };
1647
+ readonly disconnected: { value: boolean };
1648
+ readonly uncertain: { value: boolean };
1649
+ readonly pendingInputs: Set<Promise<unknown>>;
1650
+ readonly actions: { value: number };
1651
+ readonly violation: { value: BrowserFailure | undefined };
1652
+ readonly pendingRequests: Set<Promise<void>>;
1653
+ }
1654
+
1655
+ const trackPendingInput = <A>(state: HandleState, pending: Promise<A>): Promise<A> => {
1656
+ state.pendingInputs.add(pending);
1657
+ void pending.then(
1658
+ () => state.pendingInputs.delete(pending),
1659
+ (cause) => {
1660
+ state.pendingInputs.delete(pending);
1661
+ if (state.disconnected.value || inputMayStillRun(cause)) state.uncertain.value = true;
1662
+ if (isRemoteClosure(cause)) state.disconnected.value = true;
1663
+ },
1664
+ );
1665
+
1666
+ return pending;
1667
+ };
1668
+
1669
+ const makeHostInputObserver = Effect.fnUntraced(function* (state: HandleState, operation: string) {
1670
+ const reporterContext = yield* Effect.context<never>();
1671
+
1672
+ return <A>(pending: Promise<A>, signal: AbortSignal): Promise<A> => {
1673
+ void pending.then(undefined, (cause) => {
1674
+ if (signal.aborted)
1675
+ return Effect.runPromiseWith(reporterContext)(
1676
+ reportBrowserCause(operation, Cause.fail(cause)),
1677
+ );
1678
+ });
1679
+
1680
+ return trackPendingInput(state, pending);
1681
+ };
1682
+ });
1683
+
1684
+ const stateFailure = (state: HandleState): BrowserFailure | undefined => {
1685
+ if (state.violation.value !== undefined) return state.violation.value;
1686
+ if (state.closed.value) return expiredError();
1687
+ if (state.disconnected.value) return expiredError("disconnected");
1688
+
1689
+ return undefined;
1690
+ };
1691
+
1692
+ interface CloseFailure {
1693
+ readonly error: InteractiveBrowserActionError;
1694
+ readonly warning: string;
1695
+ }
1696
+
1697
+ interface CloseEntry {
1698
+ readonly close: Effect.Effect<void, InteractiveBrowserActionError>;
1699
+ readonly warning: string;
1700
+ }
1701
+
1702
+ interface HandleRuntime {
1703
+ readonly handle: BrowserHandle;
1704
+ readonly run: <A>(
1705
+ effect: Effect.Effect<A, BrowserFailure>,
1706
+ preflight?: Effect.Effect<void, BrowserFailure>,
1707
+ consumeAction?: boolean,
1708
+ mutating?: boolean,
1709
+ ) => Effect.Effect<A, BrowserFailure>;
1710
+ }
1711
+
1712
+ class BrowserRunRemoteFailure {
1713
+ readonly cause: unknown;
1714
+
1715
+ constructor(cause: unknown) {
1716
+ this.cause = cause;
1717
+ }
1718
+ }
1719
+
1720
+ const awaitPendingRequests = (state: HandleState): Effect.Effect<void> =>
1721
+ Effect.suspend(() => {
1722
+ const pending = [...state.pendingRequests];
1723
+
1724
+ return pending.length === 0
1725
+ ? Effect.void
1726
+ : Effect.promise(() => Promise.all(pending)).pipe(
1727
+ Effect.asVoid,
1728
+ Effect.andThen(awaitPendingRequests(state)),
1729
+ );
1730
+ });
1731
+
1732
+ const decodeNavigationResult = Effect.fn("BrowserRunInteractive.decodeNavigationResult")(function* (
1733
+ page: BrowserRunInteractivePage,
1734
+ policy: InteractiveBrowserPolicySnapshot,
1735
+ ) {
1736
+ const url = yield* Effect.try({
1737
+ try: page.url,
1738
+ catch: (cause) => protocolError("Reading the browser navigation URL failed", cause),
1739
+ });
1740
+
1741
+ const result = yield* Schema.decodeUnknownEffect(BrowserNavigationResult)({
1742
+ url,
1743
+ }).pipe(
1744
+ Effect.mapError((cause) =>
1745
+ protocolError("The browser returned a malformed navigation URL", cause),
1746
+ ),
1747
+ );
1748
+
1749
+ if (!hostAllowed(policy, result.url)) {
1750
+ return yield* policyError("The browser returned an off-policy page URL");
1751
+ }
1752
+
1753
+ return result;
1754
+ });
1755
+
1756
+ const decodeActionResult = Effect.fn("BrowserRunInteractive.decodeActionResult")(function* (
1757
+ page: BrowserRunInteractivePage,
1758
+ policy: InteractiveBrowserPolicySnapshot,
1759
+ ) {
1760
+ const url = yield* Effect.try({
1761
+ try: page.url,
1762
+ catch: (cause) => protocolError("Reading the browser page URL failed", cause),
1763
+ });
1764
+
1765
+ const result = yield* Schema.decodeUnknownEffect(BrowserActionResult)({ url }).pipe(
1766
+ Effect.mapError((cause) => protocolError("The browser returned a malformed page URL", cause)),
1767
+ );
1768
+
1769
+ if (!hostAllowed(policy, result.url)) {
1770
+ return yield* policyError("The browser returned an off-policy page URL");
1771
+ }
1772
+
1773
+ return result;
1774
+ });
1775
+
1776
+ const makeRequestListener =
1777
+ (
1778
+ policy: InteractiveBrowserPolicySnapshot,
1779
+ state: HandleState,
1780
+ ): BrowserRunInteractiveRequestListener =>
1781
+ (request) => {
1782
+ let allowed = false;
1783
+
1784
+ try {
1785
+ allowed = hostAllowed(policy, request.url());
1786
+ } catch {
1787
+ allowed = false;
1788
+ }
1789
+ if (!allowed) {
1790
+ state.violation.value = policyError("The browser requested an off-policy URL");
1791
+ }
1792
+
1793
+ let settlement: Promise<void>;
1794
+
1795
+ try {
1796
+ settlement = allowed ? request.continue() : request.abort();
1797
+ } catch (cause) {
1798
+ state.violation.value = protocolError(
1799
+ "Resolving an intercepted browser request failed",
1800
+ cause,
1801
+ );
1802
+
1803
+ return;
1804
+ }
1805
+
1806
+ const observed = settlement
1807
+ .catch((cause) => {
1808
+ state.violation.value = protocolError(
1809
+ "Resolving an intercepted browser request failed",
1810
+ cause,
1811
+ );
1812
+ })
1813
+ .finally(() => {
1814
+ state.pendingRequests.delete(observed);
1815
+ });
1816
+
1817
+ state.pendingRequests.add(observed);
1818
+ };
1819
+
1820
+ const makeHandle = Effect.fn("BrowserRunInteractive.makeHandle")(function* (
1821
+ page: BrowserRunInteractivePage,
1822
+ policy: InteractiveBrowserPolicySnapshot,
1823
+ startedAt: number,
1824
+ state: HandleState,
1825
+ close: Effect.Effect<void, InteractiveBrowserError>,
1826
+ ): Effect.fn.Return<HandleRuntime> {
1827
+ const permits = yield* Semaphore.make(1);
1828
+ let currentOperation: BrowserOperation | undefined;
1829
+ let generation = 0;
1830
+
1831
+ let evidence: InteractiveBrowserFailureEvidence = {
1832
+ stage: "preparation",
1833
+ dispatch: "not-dispatched",
1834
+ session: "attached",
1835
+ };
1836
+
1837
+ const reporterContext = yield* Effect.context<never>();
1838
+
1839
+ const remote = <A>(
1840
+ operation: BrowserOperation,
1841
+ evaluate: (signal: AbortSignal) => Promise<A>,
1842
+ observed = false,
1843
+ ) =>
1844
+ Effect.suspend(() => {
1845
+ currentOperation = operation;
1846
+ const mutating = operation !== "read-text" && operation !== "screenshot";
1847
+ const currentGeneration = ++generation;
1848
+
1849
+ evidence = {
1850
+ stage: observed ? "preparation" : mutating ? "input" : "observation",
1851
+ dispatch: observed || !mutating ? "not-dispatched" : "running",
1852
+ session: "attached",
1853
+ };
1854
+
1855
+ return Effect.tryPromise({
1856
+ try: (signal) => {
1857
+ const pending = evaluate(signal);
1858
+
1859
+ if (mutating) trackPendingInput(state, pending);
1860
+ void pending.then(
1861
+ () => {
1862
+ if (mutating && generation === currentGeneration)
1863
+ evidence = { ...evidence, stage: "observation", dispatch: "completed" };
1864
+ },
1865
+ (cause) => {
1866
+ if (state.disconnected.value || isRemoteClosure(cause)) {
1867
+ state.disconnected.value = true;
1868
+ if (mutating) state.uncertain.value = true;
1869
+ }
1870
+ if (generation === currentGeneration && evidence.dispatch === "running")
1871
+ evidence = { ...evidence, dispatch: "unknown" };
1872
+ if (signal.aborted && !(cause instanceof BrowserRunActionUndispatched))
1873
+ void Effect.runPromiseWith(reporterContext)(
1874
+ reportBrowserCause("interactive.input.late", Cause.fail(cause)),
1875
+ );
1876
+ },
1877
+ );
1878
+
1879
+ return pending;
1880
+ },
1881
+ catch: (cause) => new BrowserRunRemoteFailure(cause),
1882
+ }).pipe(
1883
+ Effect.catch((failure) => {
1884
+ if (failure.cause instanceof BrowserRunActionUndispatched)
1885
+ return Effect.logInfo("Browser interactive action was not dispatched").pipe(
1886
+ Effect.annotateLogs({
1887
+ "browser.action": operation,
1888
+ "browser.selector_match_count": failure.cause.matchCount,
1889
+ }),
1890
+ Effect.andThen(Effect.fail(undispatchedActionError(operation))),
1891
+ );
1892
+ if (mutating && inputMayStillRun(failure.cause)) state.uncertain.value = true;
1893
+ if (isRemoteClosure(failure.cause)) {
1894
+ state.disconnected.value = true;
1895
+ if (mutating) state.uncertain.value = true;
1896
+ }
1897
+ evidence = {
1898
+ ...evidence,
1899
+ dispatch: evidence.dispatch === "running" ? "unknown" : evidence.dispatch,
1900
+ session: state.disconnected.value ? "disconnected" : "attached",
1901
+ };
1902
+
1903
+ return reportBrowserCause(
1904
+ `interactive.${operation}.${evidence.stage}.${evidence.dispatch}`,
1905
+ Cause.fail(failure.cause),
1906
+ ).pipe(
1907
+ Effect.andThen(
1908
+ Effect.fail(reportedBrowserError(actionError(operation, undefined, evidence))),
1909
+ ),
1910
+ );
1911
+ }),
1912
+ );
1913
+ });
1914
+
1915
+ const observedAction = (
1916
+ operation: "fill" | "click" | "select-file",
1917
+ evaluate: (
1918
+ signal: AbortSignal,
1919
+ onDispatch: () => void,
1920
+ onComplete: () => void,
1921
+ ) => Promise<unknown>,
1922
+ ) =>
1923
+ remote(
1924
+ operation,
1925
+ (signal) => {
1926
+ const observedGeneration = generation;
1927
+
1928
+ return evaluate(
1929
+ signal,
1930
+ () => {
1931
+ if (generation === observedGeneration)
1932
+ evidence = { ...evidence, stage: "input", dispatch: "running" };
1933
+ },
1934
+ () => {
1935
+ if (generation === observedGeneration)
1936
+ evidence = { ...evidence, stage: "observation", dispatch: "completed" };
1937
+ },
1938
+ );
1939
+ },
1940
+ true,
1941
+ ).pipe(
1942
+ Effect.onInterrupt(() =>
1943
+ Effect.logWarning("Browser interactive action interrupted").pipe(
1944
+ Effect.annotateLogs({
1945
+ "browser.action": operation,
1946
+ "browser.action_dispatched": evidence.dispatch !== "not-dispatched",
1947
+ "browser.action_outcome_unknown":
1948
+ evidence.dispatch === "running" || evidence.dispatch === "unknown",
1949
+ }),
1950
+ ),
1951
+ ),
1952
+ );
1953
+
1954
+ const decodeActionObservation = Effect.fn("BrowserRunInteractive.decodeActionObservation")(
1955
+ function* (raw: unknown) {
1956
+ return yield* Schema.decodeUnknownEffect(ActionObservation)(raw).pipe(
1957
+ Effect.mapError((cause) =>
1958
+ protocolError("The browser returned a malformed action observation", cause),
1959
+ ),
1960
+ );
1961
+ },
1962
+ );
1963
+
1964
+ const logActionObservation = (
1965
+ operation: "fill" | "click" | "select-file",
1966
+ observation: typeof ActionObservation.Type,
1967
+ ) =>
1968
+ Effect.logInfo("Browser interactive action observed").pipe(
1969
+ Effect.annotateLogs({
1970
+ "browser.action": operation,
1971
+ "browser.input_millis": observation.inputMillis,
1972
+ "browser.observation_millis": observation.observationMillis,
1973
+ "browser.selector_match_count": observation.before.matchCount,
1974
+ ...(observation.before.kind === undefined
1975
+ ? {}
1976
+ : { "browser.target_kind": observation.before.kind }),
1977
+ ...(observation.before.checked === undefined
1978
+ ? {}
1979
+ : { "browser.target_checked_before": observation.before.checked }),
1980
+ ...(observation.after?.checked === undefined
1981
+ ? {}
1982
+ : { "browser.target_checked_after": observation.after.checked }),
1983
+ ...(observation.before.selected === undefined
1984
+ ? {}
1985
+ : { "browser.target_selected_before": observation.before.selected }),
1986
+ ...(observation.after?.selected === undefined
1987
+ ? {}
1988
+ : { "browser.target_selected_after": observation.after.selected }),
1989
+ ...(observation.before.disabled === undefined
1990
+ ? {}
1991
+ : { "browser.target_disabled_before": observation.before.disabled }),
1992
+ ...(observation.after?.disabled === undefined
1993
+ ? {}
1994
+ : { "browser.target_disabled_after": observation.after.disabled }),
1995
+ ...(observation.before.required === undefined
1996
+ ? {}
1997
+ : { "browser.target_required_before": observation.before.required }),
1998
+ ...(observation.after?.required === undefined
1999
+ ? {}
2000
+ : { "browser.target_required_after": observation.after.required }),
2001
+ ...(observation.before.valid === undefined
2002
+ ? {}
2003
+ : { "browser.target_valid_before": observation.before.valid }),
2004
+ ...(observation.after?.valid === undefined
2005
+ ? {}
2006
+ : { "browser.target_valid_after": observation.after.valid }),
2007
+ ...(observation.before.formValid === undefined
2008
+ ? {}
2009
+ : { "browser.form_valid_before": observation.before.formValid }),
2010
+ ...(observation.after?.formValid === undefined
2011
+ ? {}
2012
+ : { "browser.form_valid_after": observation.after.formValid }),
2013
+ "browser.target_after_unavailable": observation.afterUnavailable,
2014
+ "browser.fetch_xhr_total": observation.network.total,
2015
+ "browser.fetch_xhr_2xx": observation.network.status2xx,
2016
+ "browser.fetch_xhr_3xx": observation.network.status3xx,
2017
+ "browser.fetch_xhr_4xx": observation.network.status4xx,
2018
+ "browser.fetch_xhr_5xx": observation.network.status5xx,
2019
+ "browser.fetch_xhr_failed": observation.network.failed,
2020
+ "browser.fetch_xhr_pending": observation.network.pending,
2021
+ "browser.network_settle_timed_out": observation.network.settleTimedOut,
2022
+ }),
2023
+ );
2024
+
2025
+ const run = <A>(
2026
+ effect: Effect.Effect<A, BrowserFailure>,
2027
+ preflight: Effect.Effect<void, BrowserFailure> = Effect.void,
2028
+ consumeAction = true,
2029
+ mutating = true,
2030
+ ) =>
2031
+ permits
2032
+ .withPermitsIfAvailable(1)(
2033
+ Effect.gen(function* () {
2034
+ const unavailable = stateFailure(state);
2035
+
2036
+ if (unavailable !== undefined) {
2037
+ if (unavailable._tag === "InteractiveBrowserProtocolError") {
2038
+ yield* reportBrowserCause("interactive.policy", Cause.fail(unavailable));
2039
+
2040
+ const safe = reportedBrowserError(
2041
+ InteractiveBrowserProtocolError.make({
2042
+ implementation: browserRunInteractiveImplementation,
2043
+ message: unavailable.message,
2044
+ evidence: unavailable.evidence ?? {
2045
+ stage: "preparation",
2046
+ dispatch: "not-dispatched",
2047
+ session: "attached",
2048
+ },
2049
+ }),
2050
+ );
2051
+
2052
+ if (state.violation.value === unavailable) state.violation.value = safe;
2053
+
2054
+ return yield* safe;
2055
+ }
2056
+
2057
+ return yield* unavailable;
2058
+ }
2059
+ if (mutating && (state.uncertain.value || state.pendingInputs.size > 0))
2060
+ return yield* InteractiveBrowserBusyError.make({
2061
+ implementation: browserRunInteractiveImplementation,
2062
+ message: "Earlier browser input has not been proven stopped",
2063
+ });
2064
+ currentOperation = undefined;
2065
+ generation++;
2066
+ yield* preflight;
2067
+
2068
+ if (consumeAction) {
2069
+ const admitted = {
2070
+ allowed: state.actions.value < policy.maxActions,
2071
+ observed: state.actions.value + 1,
2072
+ };
2073
+
2074
+ if (admitted.allowed) state.actions.value++;
2075
+
2076
+ if (!admitted.allowed) {
2077
+ return yield* InteractiveBrowserLimitError.make({
2078
+ implementation: browserRunInteractiveImplementation,
2079
+ limit: "actions",
2080
+ maximum: policy.maxActions,
2081
+ observed: admitted.observed,
2082
+ message: "The browser action limit was reached",
2083
+ });
2084
+ }
2085
+ }
2086
+
2087
+ const completed = effect.pipe(
2088
+ Effect.flatMap((result) =>
2089
+ awaitPendingRequests(state).pipe(
2090
+ Effect.andThen(
2091
+ Effect.suspend(() => {
2092
+ const failure = stateFailure(state);
2093
+
2094
+ return failure === undefined ? Effect.succeed(result) : Effect.fail(failure);
2095
+ }),
2096
+ ),
2097
+ ),
2098
+ ),
2099
+ );
2100
+
2101
+ return yield* withinDeadline(completed, policy, startedAt).pipe(
2102
+ Effect.mapError((error) =>
2103
+ currentOperation === undefined
2104
+ ? error
2105
+ : error._tag === "InteractiveBrowserLimitError"
2106
+ ? InteractiveBrowserLimitError.make({
2107
+ implementation: error.implementation,
2108
+ limit: error.limit,
2109
+ maximum: error.maximum,
2110
+ observed: error.observed,
2111
+ message: error.message,
2112
+ evidence,
2113
+ })
2114
+ : error._tag === "InteractiveBrowserPolicyDeniedError"
2115
+ ? InteractiveBrowserPolicyDeniedError.make({
2116
+ implementation: error.implementation,
2117
+ message: error.message,
2118
+ evidence,
2119
+ })
2120
+ : error,
2121
+ ),
2122
+ Effect.catchIf(
2123
+ (error) =>
2124
+ currentOperation !== undefined &&
2125
+ error._tag !== "InteractiveBrowserActionError" &&
2126
+ error._tag !== "InteractiveBrowserLimitError" &&
2127
+ error._tag !== "InteractiveBrowserPolicyDeniedError" &&
2128
+ error._tag !== "InteractiveBrowserExpiredError",
2129
+ (error) => {
2130
+ const safe = reportedBrowserError(
2131
+ error._tag === "InteractiveBrowserProtocolError"
2132
+ ? InteractiveBrowserProtocolError.make({
2133
+ implementation: browserRunInteractiveImplementation,
2134
+ message: error.message,
2135
+ evidence,
2136
+ })
2137
+ : actionError(currentOperation ?? "read-text", undefined, evidence),
2138
+ );
2139
+
2140
+ if (state.violation.value === error) state.violation.value = safe;
2141
+
2142
+ return reportBrowserCause(
2143
+ `interactive.${currentOperation}.observation`,
2144
+ Cause.fail(error),
2145
+ ).pipe(Effect.andThen(Effect.fail(safe)));
2146
+ },
2147
+ ),
2148
+ );
2149
+ }),
2150
+ )
2151
+ .pipe(
2152
+ Effect.flatMap(
2153
+ Effect.fromOption(() =>
2154
+ InteractiveBrowserBusyError.make({
2155
+ implementation: browserRunInteractiveImplementation,
2156
+ message: "The browser handle already has an operation in flight",
2157
+ }),
2158
+ ),
2159
+ ),
2160
+ );
2161
+
2162
+ const handle: BrowserHandle = {
2163
+ navigate: (request) =>
2164
+ run(
2165
+ Effect.gen(function* () {
2166
+ yield* remote("navigate", () => page.goto(request.url));
2167
+
2168
+ return yield* decodeNavigationResult(page, policy);
2169
+ }),
2170
+ Effect.suspend(() =>
2171
+ Schema.is(InteractiveBrowserTargetUrl)(request.url) && hostAllowed(policy, request.url)
2172
+ ? Effect.void
2173
+ : Effect.fail(policyError("The navigation URL is outside the browser policy")),
2174
+ ),
2175
+ ),
2176
+ readText: (request) =>
2177
+ run(
2178
+ Effect.gen(function* () {
2179
+ const raw = yield* remote("read-text", () =>
2180
+ page.readText(request.selector, policy.maxReturnedBytes),
2181
+ );
2182
+
2183
+ const observation = yield* Schema.decodeUnknownEffect(TextObservation)(raw).pipe(
2184
+ Effect.mapError((cause) =>
2185
+ protocolError("The browser returned a malformed text observation", cause),
2186
+ ),
2187
+ );
2188
+
2189
+ if (observation._tag === "MissingElement") {
2190
+ return yield* actionError("read-text", undefined, evidence);
2191
+ }
2192
+ if (observation._tag === "OverLimit") {
2193
+ return yield* InteractiveBrowserLimitError.make({
2194
+ implementation: browserRunInteractiveImplementation,
2195
+ limit: "returned-bytes",
2196
+ maximum: policy.maxReturnedBytes,
2197
+ observed: observation.observed,
2198
+ message: "The browser returned-text limit was reached",
2199
+ });
2200
+ }
2201
+ const observed = new TextEncoder().encode(observation.text).byteLength;
2202
+
2203
+ if (observed > policy.maxReturnedBytes) {
2204
+ return yield* InteractiveBrowserLimitError.make({
2205
+ implementation: browserRunInteractiveImplementation,
2206
+ limit: "returned-bytes",
2207
+ maximum: policy.maxReturnedBytes,
2208
+ observed,
2209
+ message: "The browser returned-text limit was reached",
2210
+ });
2211
+ }
2212
+
2213
+ return yield* Schema.decodeEffect(BrowserTextResult)({
2214
+ text: observation.text,
2215
+ }).pipe(
2216
+ Effect.mapError((cause) =>
2217
+ protocolError("The browser returned malformed page text", cause),
2218
+ ),
2219
+ );
2220
+ }),
2221
+ Effect.void,
2222
+ true,
2223
+ false,
2224
+ ),
2225
+ fill: (request) =>
2226
+ run(
2227
+ Effect.gen(function* () {
2228
+ const observation = yield* observedAction("fill", (signal, onDispatch, onComplete) =>
2229
+ page.fill(
2230
+ request.selector,
2231
+ request.value,
2232
+ signal,
2233
+ onDispatch,
2234
+ onComplete,
2235
+ request.expectedTarget,
2236
+ ),
2237
+ ).pipe(Effect.flatMap(decodeActionObservation));
2238
+
2239
+ yield* logActionObservation("fill", observation);
2240
+
2241
+ return yield* decodeActionResult(page, policy);
2242
+ }),
2243
+ ),
2244
+ click: (request) =>
2245
+ run(
2246
+ Effect.gen(function* () {
2247
+ const observation = yield* observedAction("click", (signal, onDispatch, onComplete) =>
2248
+ page.click(request.selector, signal, onDispatch, onComplete, request.expectedTarget),
2249
+ ).pipe(Effect.flatMap(decodeActionObservation));
2250
+
2251
+ yield* logActionObservation("click", observation);
2252
+
2253
+ return yield* decodeActionResult(page, policy);
2254
+ }),
2255
+ ),
2256
+ selectFile: (request) =>
2257
+ Schema.decodeEffect(BrowserSelectFileRequest)(request).pipe(
2258
+ Effect.mapError(() => policyError("The browser file selection request is malformed")),
2259
+ Effect.flatMap((decoded) =>
2260
+ run(
2261
+ Effect.gen(function* () {
2262
+ const observation = yield* observedAction(
2263
+ "select-file",
2264
+ (signal, onDispatch, onComplete) =>
2265
+ page.selectFile(decoded, signal, onDispatch, onComplete),
2266
+ ).pipe(Effect.flatMap(decodeActionObservation));
2267
+
2268
+ yield* logActionObservation("select-file", observation);
2269
+ const result = yield* decodeActionResult(page, policy);
2270
+
2271
+ return BrowserFileSelectionResult.make({
2272
+ url: result.url,
2273
+ fileName: decoded.fileName,
2274
+ mediaType: decoded.mediaType,
2275
+ size: decoded.bytes.length,
2276
+ });
2277
+ }),
2278
+ ),
2279
+ ),
2280
+ ),
2281
+ screenshot: (request) =>
2282
+ Schema.decodeEffect(BrowserScreenshotRequest)(request).pipe(
2283
+ Effect.mapError(() => policyError("The browser screenshot request is malformed")),
2284
+ Effect.flatMap((decoded) =>
2285
+ run(
2286
+ Effect.gen(function* () {
2287
+ const raw = yield* remote("screenshot", () => page.screenshot(decoded.fullPage));
2288
+
2289
+ const bytes = yield* Schema.decodeUnknownEffect(PngBytes)(raw).pipe(
2290
+ Effect.mapError(() =>
2291
+ protocolError("The browser returned a malformed PNG screenshot"),
2292
+ ),
2293
+ );
2294
+
2295
+ if (bytes.length > policy.maxReturnedBytes) {
2296
+ return yield* InteractiveBrowserLimitError.make({
2297
+ implementation: browserRunInteractiveImplementation,
2298
+ limit: "returned-bytes",
2299
+ maximum: policy.maxReturnedBytes,
2300
+ observed: bytes.length,
2301
+ message: "The browser screenshot byte limit was reached",
2302
+ });
2303
+ }
2304
+
2305
+ return yield* Schema.decodeEffect(PageScreenshotResult)({
2306
+ implementation: browserRunInteractiveImplementation,
2307
+ mediaType: "image/png",
2308
+ bytes: new Uint8Array(bytes),
2309
+ }).pipe(
2310
+ Effect.mapError(() =>
2311
+ protocolError("The browser returned a malformed PNG screenshot"),
2312
+ ),
2313
+ );
2314
+ }),
2315
+ decodeActionResult(page, policy).pipe(Effect.asVoid),
2316
+ true,
2317
+ false,
2318
+ ),
2319
+ ),
2320
+ ),
2321
+ scroll: (request) =>
2322
+ Schema.decodeEffect(BrowserScrollRequest)(request).pipe(
2323
+ Effect.mapError(() => policyError("The browser scroll request is malformed")),
2324
+ Effect.flatMap((decoded) =>
2325
+ run(
2326
+ remote("scroll", () => page.scroll(decoded.deltaX, decoded.deltaY)).pipe(
2327
+ Effect.andThen(decodeActionResult(page, policy)),
2328
+ ),
2329
+ decodeActionResult(page, policy).pipe(Effect.asVoid),
2330
+ ),
2331
+ ),
2332
+ ),
2333
+ close,
2334
+ };
2335
+
2336
+ return { handle, run };
2337
+ });
2338
+
2339
+ const remainingMillis = Effect.fn("BrowserRunInteractive.remainingMillis")(function* (
2340
+ policy: InteractiveBrowserPolicySnapshot,
2341
+ startedAt: number,
2342
+ ) {
2343
+ const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
2344
+
2345
+ return Math.max(0, policy.maxElapsedMillis - Math.max(0, now - startedAt));
2346
+ });
2347
+
2348
+ const closeEntry = (close: () => Promise<void>, warning: string): CloseEntry => ({
2349
+ close: Effect.tryPromise({
2350
+ try: close,
2351
+ catch: (cause) => actionError("close", cause),
2352
+ }).pipe(
2353
+ Effect.timeoutOrElse({
2354
+ duration: Duration.millis(CLEANUP_STEP_TIMEOUT_MILLIS),
2355
+ orElse: () => Effect.fail(actionError("close")),
2356
+ }),
2357
+ ),
2358
+ warning,
2359
+ });
2360
+
2361
+ const syncCloseEntry = (close: () => void, warning: string): CloseEntry => ({
2362
+ close: Effect.try({
2363
+ try: close,
2364
+ catch: (cause) => actionError("close", cause),
2365
+ }),
2366
+ warning,
2367
+ });
2368
+
2369
+ const runTeardown = (
2370
+ entries: ReadonlyArray<CloseEntry>,
2371
+ ): Effect.Effect<ReadonlyArray<CloseFailure>> =>
2372
+ Effect.forEach([...entries].reverse(), (entry) =>
2373
+ entry.close.pipe(
2374
+ Effect.match({
2375
+ onFailure: (error): CloseFailure | undefined => ({ error, warning: entry.warning }),
2376
+ onSuccess: (): CloseFailure | undefined => undefined,
2377
+ }),
2378
+ ),
2379
+ ).pipe(Effect.map((failures) => failures.filter((failure) => failure !== undefined)));
2380
+
2381
+ const cdpCommand = <A>(
2382
+ page: BrowserRunInteractivePage,
2383
+ state: HandleState,
2384
+ command: BrowserRunCloudflareCommand,
2385
+ parameters: unknown,
2386
+ output: Schema.Codec<A>,
2387
+ malformedMessage: string,
2388
+ ): Effect.Effect<A, InteractiveBrowserError> =>
2389
+ Effect.scoped(
2390
+ Effect.gen(function* () {
2391
+ const cleanupContext = yield* Effect.context<never>();
2392
+ const observeInput = yield* makeHostInputObserver(state, "interactive.control.late");
2393
+
2394
+ const cdp = yield* Effect.acquireRelease(
2395
+ Effect.tryPromise({
2396
+ try: (signal) => {
2397
+ const pending = closeLateAcquisition(signal, page.createCdpSession, (acquired) =>
2398
+ Effect.runPromiseWith(cleanupContext)(
2399
+ Effect.tryPromise({
2400
+ try: () => acquired.detach(),
2401
+ catch: (cause) => actionError("close", cause),
2402
+ }).pipe(
2403
+ Effect.tapCause((cause) => reportBrowserCause("interactive.lateDetach", cause)),
2404
+ ),
2405
+ ),
2406
+ );
2407
+
2408
+ void pending.then(undefined, (cause) => {
2409
+ if (signal.aborted && !(cause instanceof LateBrowserAcquisition))
2410
+ return Effect.runPromiseWith(cleanupContext)(
2411
+ reportBrowserCause("interactive.connect", Cause.fail(cause)),
2412
+ );
2413
+ });
2414
+
2415
+ return pending;
2416
+ },
2417
+ catch: (cause) =>
2418
+ state.disconnected.value || isRemoteClosure(cause)
2419
+ ? expiredError()
2420
+ : protocolError("Creating the Cloudflare browser control session failed", cause),
2421
+ }),
2422
+ (acquired) =>
2423
+ closeWithWarning(
2424
+ acquired.detach,
2425
+ "Detaching the Cloudflare browser control session failed",
2426
+ ),
2427
+ { interruptible: true },
2428
+ );
2429
+
2430
+ const raw = yield* Effect.tryPromise({
2431
+ try: (signal) => {
2432
+ const pending = cdp.send(command, parameters);
2433
+
2434
+ return command === "Cloudflare.getHandoffState" ? pending : observeInput(pending, signal);
2435
+ },
2436
+ catch: (cause) =>
2437
+ state.disconnected.value || isRemoteClosure(cause)
2438
+ ? expiredError()
2439
+ : protocolError("The Cloudflare browser control command failed", cause),
2440
+ });
2441
+
2442
+ return yield* Schema.decodeUnknownEffect(output)(raw).pipe(
2443
+ Effect.catch((error) =>
2444
+ reportBrowserCause("interactive.command.decode", Cause.fail(error)).pipe(
2445
+ Effect.andThen(Effect.fail(reportedBrowserError(protocolError(malformedMessage)))),
2446
+ ),
2447
+ ),
2448
+ );
2449
+ }),
2450
+ ).pipe(
2451
+ Effect.catchTag("InteractiveBrowserProtocolError", (error) =>
2452
+ failReportedProtocol("interactive.control", error),
2453
+ ),
2454
+ );
2455
+
2456
+ const makeHostService = (
2457
+ binding: BrowserRunInteractiveBinding["Service"],
2458
+ ): BrowserRunInteractiveHost["Service"] => {
2459
+ const owners = new Map<string, symbol>();
2460
+
2461
+ const closeSession: BrowserRunInteractiveHost["Service"]["closeSession"] = (sessionId) =>
2462
+ binding.closeSession(sessionId).pipe(
2463
+ Effect.tap(() =>
2464
+ Effect.sync(() => {
2465
+ owners.delete(Redacted.value(sessionId));
2466
+ }),
2467
+ ),
2468
+ );
2469
+
2470
+ const terminate = Effect.fn("BrowserRunInteractiveHost.terminate")(function* (
2471
+ sessionId: Redacted.Redacted<string>,
2472
+ entries: ReadonlyArray<CloseEntry>,
2473
+ ) {
2474
+ const deadline = (yield* Clock.currentTimeMillis) + 10_000;
2475
+
2476
+ yield* closeSession(sessionId).pipe(
2477
+ Effect.interruptible,
2478
+ Effect.timeoutOrElse({
2479
+ duration: "10 seconds",
2480
+ orElse: () => Effect.fail(actionError("close")),
2481
+ }),
2482
+ );
2483
+ const remaining = deadline - (yield* Clock.currentTimeMillis);
2484
+
2485
+ if (remaining <= 0)
2486
+ return yield* Effect.logWarning(
2487
+ "Local browser teardown skipped after confirmed termination deadline",
2488
+ );
2489
+ // Remote termination is authoritative. Local cleanup must not veto it or extend the deadline.
2490
+ yield* runTeardown(entries).pipe(
2491
+ Effect.flatMap((failures) =>
2492
+ Effect.forEach(
2493
+ failures,
2494
+ (failure) =>
2495
+ reportBrowserCause("interactive.cleanup", Cause.fail(failure.error)).pipe(
2496
+ Effect.andThen(Effect.logWarning(failure.warning)),
2497
+ ),
2498
+ {
2499
+ discard: true,
2500
+ },
2501
+ ),
2502
+ ),
2503
+ Effect.interruptible,
2504
+ Effect.timeout(`${remaining} millis`),
2505
+ Effect.catchCause((cause) =>
2506
+ reportBrowserCause("interactive.cleanup", cause).pipe(
2507
+ Effect.andThen(
2508
+ Effect.logWarning("Local browser teardown incomplete after confirmed termination"),
2509
+ ),
2510
+ ),
2511
+ ),
2512
+ );
2513
+ });
2514
+
2515
+ const closeAcquired = Effect.fn("BrowserRunInteractiveHost.closeAcquired")(function* (
2516
+ browser: BrowserRunInteractiveBrowser,
2517
+ ) {
2518
+ const sessionId = yield* Effect.try({
2519
+ try: browser.sessionId,
2520
+ catch: (cause) => actionError("close", cause),
2521
+ }).pipe(
2522
+ Effect.flatMap(Schema.decodeUnknownEffect(BrowserRunSessionId)),
2523
+ Effect.mapError((cause) => actionError("close", cause)),
2524
+ Effect.onError(() =>
2525
+ closeWithWarning(browser.close, "Closing an unidentified browser failed"),
2526
+ ),
2527
+ );
2528
+
2529
+ yield* terminate(Redacted.make(sessionId), [
2530
+ closeEntry(browser.close, "Closing the local browser connection failed"),
2531
+ ]);
2532
+ });
2533
+
2534
+ const acquire = Effect.fn("BrowserRunInteractiveHost.acquire")(function* (
2535
+ policy: InteractiveBrowserPolicy,
2536
+ resume?: BrowserRunInteractiveCheckpoint,
2537
+ pendingInput = false,
2538
+ ): Effect.fn.Return<BrowserRunInteractiveAcquisition, InteractiveBrowserError, Scope.Scope> {
2539
+ const scope = yield* Scope.Scope;
2540
+ const fixedPolicy = yield* snapshotPolicy(policy);
2541
+ const startedAt = resume?.startedAt ?? (yield* Clock.currentTimeMillis);
2542
+
2543
+ // Late SDK replies retain this pass's clock and private reporting scope.
2544
+ const runCleanup = <A, E>(effect: Effect.Effect<A, E>) =>
2545
+ Effect.runPromiseWith(cleanupContext)(
2546
+ effect.pipe(
2547
+ Effect.tapCause((cause) => reportBrowserCause("interactive.lateCleanup", cause)),
2548
+ ),
2549
+ );
2550
+
2551
+ const cleanupContext = yield* Effect.context<never>();
2552
+
2553
+ const observeLate = <A>(signal: AbortSignal, pending: Promise<A>): Promise<A> => {
2554
+ // Observe the original Promise without creating another rejected continuation.
2555
+ void pending.then(undefined, (cause) => {
2556
+ if (signal.aborted && !(cause instanceof LateBrowserAcquisition))
2557
+ return runCleanup(reportBrowserCause("interactive.acquire", Cause.fail(cause)));
2558
+ });
2559
+
2560
+ return pending;
2561
+ };
2562
+
2563
+ const state: HandleState = {
2564
+ closed: { value: false },
2565
+ disconnected: { value: false },
2566
+ uncertain: { value: pendingInput || (resume !== undefined && resume.inputState !== "idle") },
2567
+ pendingInputs: new Set(),
2568
+ actions: { value: resume?.consumedActions ?? 0 },
2569
+ violation: { value: undefined },
2570
+ pendingRequests: new Set(),
2571
+ };
2572
+
2573
+ const lifecycle = {
2574
+ managedTeardownInstalled: false,
2575
+ retained: resume !== undefined,
2576
+ };
2577
+
2578
+ const closers: Array<CloseEntry> = [];
2579
+
2580
+ const releaseBeforeManaged = (entry: CloseEntry): Effect.Effect<void> =>
2581
+ Effect.suspend(() =>
2582
+ lifecycle.managedTeardownInstalled || lifecycle.retained
2583
+ ? Effect.void
2584
+ : entry.close.pipe(
2585
+ Effect.catchCause((cause) =>
2586
+ reportBrowserCause("interactive.cleanup", cause).pipe(
2587
+ Effect.andThen(Effect.logWarning(entry.warning)),
2588
+ ),
2589
+ ),
2590
+ ),
2591
+ );
2592
+
2593
+ const sessionIdValue = yield* Effect.acquireRelease(
2594
+ withinDeadline(
2595
+ resume === undefined
2596
+ ? Effect.tryPromise({
2597
+ try: (signal) =>
2598
+ observeLate(
2599
+ signal,
2600
+ closeLateAcquisition(
2601
+ signal,
2602
+ () => binding.acquire(keepAliveMillis(fixedPolicy)),
2603
+ (id) =>
2604
+ runCleanup(
2605
+ Schema.decodeUnknownEffect(BrowserRunSessionId)(id).pipe(
2606
+ Effect.flatMap((value) => terminate(Redacted.make(value), [])),
2607
+ ),
2608
+ ),
2609
+ ),
2610
+ ),
2611
+ catch: (cause) =>
2612
+ isCapacityRefusal(cause)
2613
+ ? InteractiveBrowserCapacityError.make({
2614
+ implementation: browserRunInteractiveImplementation,
2615
+ message: "Browser Run has no capacity for a new browser session",
2616
+ })
2617
+ : protocolError("Acquiring the Browser Run session failed", cause),
2618
+ }).pipe(
2619
+ Effect.flatMap(Schema.decodeUnknownEffect(BrowserRunSessionId)),
2620
+ Effect.catchTag("SchemaError", () =>
2621
+ protocolError("The Browser Run session identity was malformed"),
2622
+ ),
2623
+ )
2624
+ : Effect.succeed(Redacted.value(resume.sessionId)),
2625
+ fixedPolicy,
2626
+ startedAt,
2627
+ ),
2628
+ (id) =>
2629
+ Effect.suspend(() => {
2630
+ state.closed.value = true;
2631
+ state.disconnected.value = true;
2632
+
2633
+ return lifecycle.managedTeardownInstalled || lifecycle.retained
2634
+ ? Effect.void
2635
+ : terminate(Redacted.make(id), []).pipe(
2636
+ Effect.catchCause((cause) =>
2637
+ reportBrowserCause("interactive.close", cause).pipe(
2638
+ Effect.andThen(Effect.logWarning("Whole-browser cleanup remains unconfirmed")),
2639
+ ),
2640
+ ),
2641
+ );
2642
+ }),
2643
+ { interruptible: true },
2644
+ );
2645
+
2646
+ const owner = Symbol();
2647
+
2648
+ const releaseOwner = () => {
2649
+ if (owners.get(sessionIdValue) === owner) owners.delete(sessionIdValue);
2650
+ };
2651
+
2652
+ const connect = yield* Effect.cached(
2653
+ Effect.gen(function* (): Effect.fn.Return<
2654
+ BrowserRunInteractiveSession,
2655
+ InteractiveBrowserError,
2656
+ Scope.Scope
2657
+ > {
2658
+ if (owners.has(sessionIdValue))
2659
+ return yield* InteractiveBrowserBusyError.make({
2660
+ implementation: browserRunInteractiveImplementation,
2661
+ message: "The previous local browser owner must detach before resuming",
2662
+ });
2663
+ yield* Effect.acquireRelease(
2664
+ Effect.sync(() => {
2665
+ owners.set(sessionIdValue, owner);
2666
+ }),
2667
+ () =>
2668
+ Effect.sync(() => {
2669
+ if (!lifecycle.managedTeardownInstalled) releaseOwner();
2670
+ }),
2671
+ );
2672
+
2673
+ const browser = yield* Effect.acquireRelease(
2674
+ withinDeadline(
2675
+ Effect.tryPromise({
2676
+ try: (signal) =>
2677
+ observeLate(
2678
+ signal,
2679
+ closeLateAcquisition(
2680
+ signal,
2681
+ () => binding.connect(sessionIdValue, signal),
2682
+ (acquired) =>
2683
+ runCleanup(
2684
+ resume === undefined
2685
+ ? closeAcquired(acquired)
2686
+ : closeEntry(
2687
+ acquired.detach ?? (async () => {}),
2688
+ "Detaching the browser failed",
2689
+ ).close,
2690
+ ),
2691
+ ),
2692
+ ),
2693
+ catch: (cause) =>
2694
+ resume !== undefined &&
2695
+ cause instanceof BrowserRunFailure &&
2696
+ (cause.status === 404 || cause.status === 410)
2697
+ ? expiredError()
2698
+ : protocolError("Connecting to the Browser Run session failed", cause),
2699
+ }).pipe(
2700
+ Effect.timeoutOrElse({
2701
+ duration: "10 seconds",
2702
+ orElse: () =>
2703
+ Effect.fail(protocolError("Connecting to the Browser Run session timed out")),
2704
+ }),
2705
+ ),
2706
+ fixedPolicy,
2707
+ startedAt,
2708
+ ),
2709
+ (acquired) =>
2710
+ lifecycle.managedTeardownInstalled
2711
+ ? Effect.void
2712
+ : lifecycle.retained
2713
+ ? closeEntry(
2714
+ acquired.detach ?? (async () => {}),
2715
+ "Detaching the browser failed",
2716
+ ).close.pipe(
2717
+ Effect.tap(() => Effect.sync(releaseOwner)),
2718
+ Effect.catchCause((cause) => reportBrowserCause("interactive.detach", cause)),
2719
+ )
2720
+ : releaseBeforeManaged(
2721
+ closeEntry(acquired.close, "Closing the local browser connection failed"),
2722
+ ),
2723
+ { interruptible: true },
2724
+ );
2725
+
2726
+ if (resume !== undefined) {
2727
+ const actualSession = yield* Effect.try({
2728
+ try: browser.sessionId,
2729
+ catch: (cause) =>
2730
+ protocolError("Reading the reattached browser identity failed", cause),
2731
+ });
2732
+
2733
+ if (actualSession !== sessionIdValue)
2734
+ return yield* protocolError("The reattached browser session identity did not match");
2735
+ }
2736
+ closers.push(closeEntry(browser.close, "Closing the interactive browser failed"));
2737
+
2738
+ const disconnected = () => {
2739
+ state.disconnected.value = true;
2740
+ };
2741
+
2742
+ yield* Effect.acquireRelease(
2743
+ Effect.try({
2744
+ try: () => browser.onDisconnected(disconnected),
2745
+ catch: (cause) =>
2746
+ protocolError("Installing the browser disconnect listener failed", cause),
2747
+ }),
2748
+ () =>
2749
+ releaseBeforeManaged(
2750
+ syncCloseEntry(
2751
+ () => browser.offDisconnected(disconnected),
2752
+ "Removing the browser disconnect listener failed",
2753
+ ),
2754
+ ),
2755
+ );
2756
+ closers.push(
2757
+ syncCloseEntry(
2758
+ () => browser.offDisconnected(disconnected),
2759
+ "Removing the browser disconnect listener failed",
2760
+ ),
2761
+ );
2762
+
2763
+ const connected = yield* Effect.try({
2764
+ try: browser.isConnected,
2765
+ catch: (cause) => protocolError("Reading the Browser Run connection state failed", cause),
2766
+ });
2767
+
2768
+ if (!connected) {
2769
+ state.disconnected.value = true;
2770
+
2771
+ return yield* expiredError();
2772
+ }
2773
+
2774
+ const reattached =
2775
+ resume === undefined
2776
+ ? undefined
2777
+ : yield* withinDeadline(
2778
+ Effect.tryPromise({
2779
+ try: async () => {
2780
+ if (browser.reattach === undefined || browser.detach === undefined)
2781
+ throw new Error("The browser binding does not support exact reattachment");
2782
+
2783
+ return await browser.reattach(resume.page);
2784
+ },
2785
+ catch: (cause) =>
2786
+ protocolError("Reattaching the exact browser page failed", cause),
2787
+ }).pipe(
2788
+ Effect.timeoutOrElse({
2789
+ duration: "10 seconds",
2790
+ orElse: () =>
2791
+ Effect.fail(protocolError("Reattaching the exact browser page timed out")),
2792
+ }),
2793
+ ),
2794
+ fixedPolicy,
2795
+ startedAt,
2796
+ );
2797
+
2798
+ if (resume !== undefined && reattached === undefined) return yield* expiredError();
2799
+
2800
+ const context =
2801
+ reattached?.context ??
2802
+ (yield* Effect.acquireRelease(
2803
+ withinDeadline(
2804
+ Effect.tryPromise({
2805
+ try: (signal) =>
2806
+ observeLate(
2807
+ signal,
2808
+ closeLateAcquisition(signal, browser.createContext, (acquired) =>
2809
+ runCleanup(
2810
+ Effect.tryPromise({
2811
+ try: () => acquired.close(),
2812
+ catch: (cause) => actionError("close", cause),
2813
+ }),
2814
+ ),
2815
+ ),
2816
+ ),
2817
+ catch: (cause) =>
2818
+ state.disconnected.value || isRemoteClosure(cause)
2819
+ ? expiredError()
2820
+ : protocolError("Creating the browser context failed", cause),
2821
+ }),
2822
+ fixedPolicy,
2823
+ startedAt,
2824
+ ),
2825
+ (acquired) =>
2826
+ releaseBeforeManaged(
2827
+ closeEntry(acquired.close, "Closing the interactive browser context failed"),
2828
+ ),
2829
+ { interruptible: true },
2830
+ ));
2831
+
2832
+ closers.push(closeEntry(context.close, "Closing the interactive browser context failed"));
2833
+
2834
+ const page =
2835
+ reattached?.page ??
2836
+ (yield* Effect.acquireRelease(
2837
+ withinDeadline(
2838
+ Effect.tryPromise({
2839
+ try: (signal) =>
2840
+ observeLate(
2841
+ signal,
2842
+ closeLateAcquisition(signal, context.newPage, (acquired) =>
2843
+ runCleanup(
2844
+ Effect.tryPromise({
2845
+ try: () => acquired.close(),
2846
+ catch: (cause) => actionError("close", cause),
2847
+ }),
2848
+ ),
2849
+ ),
2850
+ ),
2851
+ catch: (cause) =>
2852
+ state.disconnected.value || isRemoteClosure(cause)
2853
+ ? expiredError()
2854
+ : protocolError("Creating the browser page failed", cause),
2855
+ }),
2856
+ fixedPolicy,
2857
+ startedAt,
2858
+ ),
2859
+ (acquired) =>
2860
+ releaseBeforeManaged(
2861
+ closeEntry(acquired.close, "Closing the interactive browser page failed"),
2862
+ ),
2863
+ { interruptible: true },
2864
+ ));
2865
+
2866
+ closers.push(closeEntry(page.close, "Closing the interactive browser page failed"));
2867
+
2868
+ yield* withinDeadline(
2869
+ Effect.tryPromise({
2870
+ try: () => page.setBypassServiceWorker(true),
2871
+ catch: (cause) => protocolError("Bypassing browser service workers failed", cause),
2872
+ }),
2873
+ fixedPolicy,
2874
+ startedAt,
2875
+ );
2876
+
2877
+ const requestListener = makeRequestListener(fixedPolicy, state);
2878
+
2879
+ yield* Effect.acquireRelease(
2880
+ Effect.try({
2881
+ try: () => page.onRequest(requestListener),
2882
+ catch: (cause) =>
2883
+ protocolError("Installing the browser request listener failed", cause),
2884
+ }),
2885
+ () =>
2886
+ releaseBeforeManaged(
2887
+ syncCloseEntry(
2888
+ () => page.offRequest(requestListener),
2889
+ "Removing the browser request policy failed",
2890
+ ),
2891
+ ),
2892
+ );
2893
+ closers.push(
2894
+ syncCloseEntry(
2895
+ () => page.offRequest(requestListener),
2896
+ "Removing the browser request policy failed",
2897
+ ),
2898
+ );
2899
+
2900
+ yield* withinDeadline(
2901
+ Effect.tryPromise({
2902
+ try: () => page.setRequestInterception(true),
2903
+ catch: (cause) => protocolError("Installing the browser request policy failed", cause),
2904
+ }),
2905
+ fixedPolicy,
2906
+ startedAt,
2907
+ );
2908
+
2909
+ yield* withinDeadline(awaitPendingRequests(state), fixedPolicy, startedAt);
2910
+ const setupFailure = stateFailure(state);
2911
+
2912
+ if (setupFailure !== undefined) return yield* setupFailure;
2913
+
2914
+ const detach = yield* Effect.cached(
2915
+ Effect.uninterruptible(
2916
+ Effect.gen(function* () {
2917
+ if (browser.detach === undefined)
2918
+ return yield* protocolError("The browser binding does not support detachment");
2919
+ lifecycle.retained = true;
2920
+ state.closed.value = true;
2921
+ state.disconnected.value = true;
2922
+ if (state.pendingInputs.size > 0) state.uncertain.value = true;
2923
+ yield* closeEntry(async () => {
2924
+ page.offRequest(requestListener);
2925
+ browser.offDisconnected(disconnected);
2926
+ await browser.detach?.();
2927
+ }, "Detaching the browser transport failed").close;
2928
+ releaseOwner();
2929
+ }).pipe(
2930
+ Effect.catchTag("InteractiveBrowserActionError", (error) =>
2931
+ reportBrowserCause("interactive.detach", Cause.fail(error)).pipe(
2932
+ Effect.andThen(Effect.fail(reportedBrowserError(actionError("close")))),
2933
+ ),
2934
+ ),
2935
+ Effect.catchTag("InteractiveBrowserProtocolError", (error) =>
2936
+ failReportedProtocol("interactive.detach", error),
2937
+ ),
2938
+ ),
2939
+ ),
2940
+ );
2941
+
2942
+ const teardown = yield* Effect.uninterruptible(
2943
+ Effect.gen(function* () {
2944
+ const cached = yield* Effect.cached(
2945
+ terminate(Redacted.make(sessionIdValue), closers).pipe(
2946
+ Effect.tapCause((cause) => reportBrowserCause("interactive.close", cause)),
2947
+ Effect.mapError(reportedBrowserError),
2948
+ ),
2949
+ );
2950
+
2951
+ lifecycle.managedTeardownInstalled = true;
2952
+ lifecycle.retained = false;
2953
+ yield* Effect.addFinalizer(() =>
2954
+ Effect.uninterruptible(
2955
+ Effect.sync(() => {
2956
+ state.closed.value = true;
2957
+ state.disconnected.value = true;
2958
+ }).pipe(
2959
+ Effect.andThen(Effect.suspend(() => (lifecycle.retained ? detach : cached))),
2960
+ Effect.catchCause((cause) =>
2961
+ reportBrowserCause("interactive.close", cause).pipe(
2962
+ Effect.andThen(
2963
+ Effect.logWarning("Whole-browser cleanup remains unconfirmed"),
2964
+ ),
2965
+ ),
2966
+ ),
2967
+ ),
2968
+ ),
2969
+ );
2970
+
2971
+ return cached;
2972
+ }),
2973
+ );
2974
+
2975
+ const close: Effect.Effect<void, InteractiveBrowserError> = Effect.uninterruptible(
2976
+ Effect.suspend(() => {
2977
+ if (lifecycle.retained || owners.get(sessionIdValue) !== owner) return Effect.void;
2978
+ state.closed.value = true;
2979
+ state.disconnected.value = true;
2980
+
2981
+ return teardown;
2982
+ }),
2983
+ );
2984
+
2985
+ const runtime = yield* makeHandle(page, fixedPolicy, startedAt, state, close);
2986
+ const currentPagePreflight = decodeActionResult(page, fixedPolicy).pipe(Effect.asVoid);
2987
+
2988
+ const requestFitsSession = (requestedMillis: number): Effect.Effect<void, BrowserFailure> =>
2989
+ remainingMillis(fixedPolicy, startedAt).pipe(
2990
+ Effect.flatMap((remaining) =>
2991
+ remaining > 0 && requestedMillis <= remaining
2992
+ ? Effect.void
2993
+ : Effect.fail(
2994
+ policyError("The host browser request exceeds the remaining session time"),
2995
+ ),
2996
+ ),
2997
+ );
2998
+
2999
+ const inputState = Effect.sync((): BrowserRunInputState =>
3000
+ state.uncertain.value ? "unknown" : state.pendingInputs.size > 0 ? "running" : "idle",
3001
+ );
3002
+
3003
+ const pageIdentity = yield* Effect.cached(
3004
+ Effect.tryPromise({
3005
+ try: async () => {
3006
+ if (page.identity === undefined)
3007
+ throw new Error("The browser binding does not expose page identity");
3008
+
3009
+ return await page.identity();
3010
+ },
3011
+ catch: (cause) =>
3012
+ protocolError("Reading the exact browser page identity failed", cause),
3013
+ }).pipe(
3014
+ Effect.catchTag("InteractiveBrowserProtocolError", (error) =>
3015
+ failReportedProtocol("interactive.checkpoint", error),
3016
+ ),
3017
+ ),
3018
+ );
3019
+
3020
+ const observeResize = yield* makeHostInputObserver(state, "interactive.resize.late");
3021
+
3022
+ return {
3023
+ handle: runtime.handle,
3024
+ checkpoint: withinDeadline(
3025
+ Effect.gen(function* () {
3026
+ const identity = resume?.page ?? (yield* pageIdentity);
3027
+
3028
+ return BrowserRunInteractiveCheckpoint.make({
3029
+ sessionId: Redacted.make(sessionIdValue),
3030
+ page: identity,
3031
+ policy: InteractiveBrowserPolicy.make(fixedPolicy),
3032
+ startedAt,
3033
+ consumedActions: state.actions.value,
3034
+ inputState: yield* inputState,
3035
+ });
3036
+ }),
3037
+ fixedPolicy,
3038
+ startedAt,
3039
+ ),
3040
+ detach,
3041
+ inputState,
3042
+ drainInput: Effect.suspend(() =>
3043
+ Effect.promise(() =>
3044
+ boundedBestEffort(Promise.allSettled(state.pendingInputs), 500),
3045
+ ).pipe(Effect.andThen(inputState)),
3046
+ ),
3047
+ sessionId: Redacted.make(sessionIdValue),
3048
+ resizeViewport: (viewport) =>
3049
+ decodeViewport(viewport).pipe(
3050
+ Effect.flatMap((decoded) =>
3051
+ runtime.run(
3052
+ Effect.tryPromise({
3053
+ try: (signal) => observeResize(page.setViewport(decoded), signal),
3054
+ catch: (cause) => {
3055
+ if (state.disconnected.value || isRemoteClosure(cause)) {
3056
+ state.disconnected.value = true;
3057
+
3058
+ return expiredError();
3059
+ }
3060
+
3061
+ return protocolError("Resizing the browser viewport failed", cause);
3062
+ },
3063
+ }).pipe(
3064
+ Effect.catchTag("InteractiveBrowserProtocolError", (error) =>
3065
+ failReportedProtocol("interactive.resize", error),
3066
+ ),
3067
+ ),
3068
+ currentPagePreflight,
3069
+ false,
3070
+ ),
3071
+ ),
3072
+ ),
3073
+ getLiveView: (request) =>
3074
+ Schema.decodeEffect(BrowserRunLiveViewRequest)(request).pipe(
3075
+ Effect.mapError(() => policyError("The Live View request is malformed")),
3076
+ Effect.flatMap((decoded) =>
3077
+ runtime.run(
3078
+ cdpCommand(
3079
+ page,
3080
+ state,
3081
+ "Cloudflare.getLiveView",
3082
+ { mode: decoded.mode, expiresInMs: decoded.expiresInMs },
3083
+ LiveViewObservation,
3084
+ "Cloudflare returned a malformed Live View response",
3085
+ ).pipe(
3086
+ Effect.flatMap((observation) =>
3087
+ Schema.decodeEffect(BrowserRunLiveViewResult)({
3088
+ devtoolsFrontendUrl: Redacted.make(observation.devtoolsFrontendUrl),
3089
+ }).pipe(
3090
+ Effect.mapError(() =>
3091
+ protocolError("Cloudflare returned a malformed Live View response"),
3092
+ ),
3093
+ ),
3094
+ ),
3095
+ ),
3096
+ currentPagePreflight.pipe(
3097
+ Effect.andThen(requestFitsSession(decoded.expiresInMs)),
3098
+ ),
3099
+ true,
3100
+ true,
3101
+ ),
3102
+ ),
3103
+ ),
3104
+ handoff: (request) =>
3105
+ Schema.decodeEffect(BrowserRunHandoffRequest)(request).pipe(
3106
+ Effect.mapError(() => policyError("The browser handoff request is malformed")),
3107
+ Effect.flatMap((decoded) =>
3108
+ runtime.run(
3109
+ cdpCommand(
3110
+ page,
3111
+ state,
3112
+ "Cloudflare.handoff",
3113
+ { instructions: decoded.instructions, timeout: decoded.timeout },
3114
+ HandoffObservation,
3115
+ "Cloudflare returned a malformed browser handoff response",
3116
+ ).pipe(
3117
+ Effect.flatMap((observation) =>
3118
+ Schema.decodeEffect(BrowserRunHandoffResult)({
3119
+ handoffId: Redacted.make(observation.handoffId),
3120
+ }).pipe(
3121
+ Effect.mapError(() =>
3122
+ protocolError("Cloudflare returned a malformed browser handoff response"),
3123
+ ),
3124
+ ),
3125
+ ),
3126
+ ),
3127
+ currentPagePreflight.pipe(Effect.andThen(requestFitsSession(decoded.timeout))),
3128
+ ),
3129
+ ),
3130
+ ),
3131
+ getHandoffState: runtime.run(
3132
+ cdpCommand(
3133
+ page,
3134
+ state,
3135
+ "Cloudflare.getHandoffState",
3136
+ {},
3137
+ HandoffStateObservation,
3138
+ "Cloudflare returned a malformed browser handoff state",
3139
+ ).pipe(
3140
+ Effect.flatMap((observation) =>
3141
+ Schema.decodeEffect(BrowserRunHandoffState)({
3142
+ active: observation.active,
3143
+ ...(observation.handoffId === undefined
3144
+ ? {}
3145
+ : { handoffId: Redacted.make(observation.handoffId) }),
3146
+ ...(observation.durationMs === undefined
3147
+ ? {}
3148
+ : { durationMs: observation.durationMs }),
3149
+ }).pipe(
3150
+ Effect.mapError(() =>
3151
+ protocolError("Cloudflare returned a malformed browser handoff state"),
3152
+ ),
3153
+ ),
3154
+ ),
3155
+ ),
3156
+ currentPagePreflight,
3157
+ true,
3158
+ false,
3159
+ ),
3160
+ close,
3161
+ };
3162
+ }).pipe(Effect.provideService(Scope.Scope, scope)),
3163
+ );
3164
+
3165
+ return {
3166
+ sessionId: Redacted.make(sessionIdValue),
3167
+ connect: Effect.suspend(() => (state.closed.value ? expiredError() : connect)),
3168
+ };
3169
+ });
3170
+
3171
+ return BrowserRunInteractiveHost.of({
3172
+ acquire,
3173
+ open: (policy) => acquire(policy).pipe(Effect.flatMap((acquired) => acquired.connect)),
3174
+ resume: (checkpoint, options) =>
3175
+ Schema.decodeEffect(Schema.toType(BrowserRunInteractiveCheckpoint))(checkpoint).pipe(
3176
+ Effect.mapError(() => policyError("The browser checkpoint is malformed")),
3177
+ Effect.flatMap((decoded) => acquire(decoded.policy, decoded, options.pendingInput)),
3178
+ Effect.flatMap((acquired) => acquired.connect),
3179
+ Effect.catchTag("InteractiveBrowserProtocolError", (error) =>
3180
+ failReportedProtocol("interactive.resume", error, {
3181
+ stage: "preparation",
3182
+ dispatch: "not-dispatched",
3183
+ session: "disconnected",
3184
+ }),
3185
+ ),
3186
+ ),
3187
+ closeSession,
3188
+ cleanupSemantics: "confirmed-terminal",
3189
+ });
3190
+ };
3191
+
3192
+ /** Cloudflare host controls and private session identity for one scoped Browser Run pass. */
3193
+ export const browserRunInteractiveHostLayer = (): Layer.Layer<
3194
+ BrowserRunInteractiveHost,
3195
+ never,
3196
+ BrowserRunInteractiveBinding
3197
+ > =>
3198
+ Layer.effect(
3199
+ BrowserRunInteractiveHost,
3200
+ Effect.gen(function* () {
3201
+ return makeHostService(yield* BrowserRunInteractiveBinding);
3202
+ }),
3203
+ );
3204
+
3205
+ /** Worker-only generic adapter; Cloudflare identity and controls remain host-only. */
3206
+ export const browserRunInteractiveLayer = (): Layer.Layer<
3207
+ InteractiveBrowser,
3208
+ never,
3209
+ BrowserRunInteractiveBinding
3210
+ > =>
3211
+ Layer.effect(
3212
+ InteractiveBrowser,
3213
+ Effect.gen(function* () {
3214
+ const binding = yield* BrowserRunInteractiveBinding;
3215
+ const host = makeHostService(binding);
3216
+
3217
+ return InteractiveBrowser.of({
3218
+ open: (policy) => host.open(policy).pipe(Effect.map((session) => session.handle)),
3219
+ });
3220
+ }),
3221
+ );
3222
+
3223
+ /** Resolved Worker binding, cleanup credentials, and optional initial viewport. */
3224
+ export interface CloudflareInteractiveBrowserOptions extends BrowserRunLifecycleOptions {
3225
+ readonly browser: BrowserRun;
3226
+ readonly viewport?: BrowserRunViewport;
3227
+ }
3228
+
3229
+ const interactiveBindingLayer = (options: CloudflareInteractiveBrowserOptions) =>
3230
+ BrowserRunInteractiveBinding.layer(options).pipe(
3231
+ Layer.provide(BrowserRunSessionLifecycle.layer(options)),
3232
+ );
3233
+
3234
+ /** Worker-only assembly; importing ordinary capture never loads Puppeteer. */
3235
+ export const CloudflareInteractiveBrowser = {
3236
+ /**
3237
+ * Assemble binding, confirmed-session cleanup, and the generic browser service.
3238
+ * HttpClient and construction errors remain visible. Opening a pass still requires
3239
+ * an explicit policy and Scope; no browser is launched during Layer construction.
3240
+ */
3241
+ layer: (options: CloudflareInteractiveBrowserOptions) =>
3242
+ browserRunInteractiveLayer().pipe(Layer.provide(interactiveBindingLayer(options))),
3243
+ /** Opt into private host controls instead of exposing them through the generic service. */
3244
+ hostLayer: (options: CloudflareInteractiveBrowserOptions) =>
3245
+ browserRunInteractiveHostLayer().pipe(Layer.provide(interactiveBindingLayer(options))),
3246
+ };