@systemfsoftware/agent-platform-cloudflare 0.0.0-stage → 0.1.0

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