@effect-agent/platform-cloudflare 0.1.0-beta.29 → 0.1.0-beta.30

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.
@@ -0,0 +1,748 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+
3
+ import puppeteer, {
4
+ type Browser,
5
+ type BrowserContext,
6
+ type HTTPRequest,
7
+ type Page,
8
+ } from "@cloudflare/puppeteer";
9
+ import {
10
+ BrowserActionResult,
11
+ BrowserNavigationResult,
12
+ BrowserTextResult,
13
+ InteractiveBrowser,
14
+ InteractiveBrowserActionError,
15
+ InteractiveBrowserBusyError,
16
+ InteractiveBrowserCapacityError,
17
+ InteractiveBrowserExpiredError,
18
+ InteractiveBrowserLimitError,
19
+ InteractiveBrowserPolicy,
20
+ InteractiveBrowserPolicyDeniedError,
21
+ InteractiveBrowserProtocolError,
22
+ SandboxImplementation,
23
+ type BrowserHandle,
24
+ type InteractiveBrowserError,
25
+ } from "@effect-agent/sandbox";
26
+ import { Context, Duration, Effect, Layer, Option, Ref, Schema, Semaphore } from "effect";
27
+
28
+ export const browserRunInteractiveImplementation = SandboxImplementation.make({
29
+ isolation: "isolated",
30
+ identity: "cloudflare-browser-run-interactive",
31
+ });
32
+
33
+ const MIN_KEEP_ALIVE_MILLIS = 10_000;
34
+ const MAX_KEEP_ALIVE_MILLIS = 600_000;
35
+ const MAX_TEXT_LENGTH = 8 * 1024 * 1024;
36
+ const BoundedRemoteText = Schema.String.check(Schema.isMaxLength(MAX_TEXT_LENGTH));
37
+ const TextObservation = Schema.Union([
38
+ Schema.Struct({ _tag: Schema.Literal("Text"), text: BoundedRemoteText }),
39
+ Schema.Struct({ _tag: Schema.Literal("MissingElement") }),
40
+ Schema.Struct({ _tag: Schema.Literal("OverLimit"), observed: Schema.Natural }),
41
+ ]);
42
+
43
+ type BrowserFailure = typeof InteractiveBrowserError.Type;
44
+ type BrowserOperation = InteractiveBrowserActionError["operation"];
45
+
46
+ interface InteractiveBrowserPolicySnapshot {
47
+ readonly allowedHosts: ReadonlyArray<string>;
48
+ readonly maxActions: number;
49
+ readonly maxElapsedMillis: number;
50
+ readonly maxReturnedBytes: number;
51
+ }
52
+
53
+ /** One intercepted Puppeteer request, narrowed to the policy-relevant surface. */
54
+ export interface BrowserRunInteractiveRequest {
55
+ readonly url: () => string;
56
+ readonly abort: () => Promise<void>;
57
+ readonly continue: () => Promise<void>;
58
+ }
59
+
60
+ export type BrowserRunInteractiveRequestListener = (request: BrowserRunInteractiveRequest) => void;
61
+
62
+ /** Narrow page boundary used by deterministic tests; SDK values remain in this package. */
63
+ export interface BrowserRunInteractivePage {
64
+ readonly close: () => Promise<void>;
65
+ readonly setBypassServiceWorker: (enabled: boolean) => Promise<void>;
66
+ readonly setRequestInterception: (enabled: boolean) => Promise<void>;
67
+ readonly onRequest: (listener: BrowserRunInteractiveRequestListener) => void;
68
+ readonly offRequest: (listener: BrowserRunInteractiveRequestListener) => void;
69
+ readonly goto: (url: string) => Promise<void>;
70
+ readonly url: () => unknown;
71
+ readonly readText: (selector: string | undefined, maximumBytes: number) => Promise<unknown>;
72
+ readonly fill: (selector: string, value: string) => Promise<void>;
73
+ readonly click: (selector: string) => Promise<void>;
74
+ }
75
+
76
+ export interface BrowserRunInteractiveContext {
77
+ readonly newPage: () => Promise<BrowserRunInteractivePage>;
78
+ readonly close: () => Promise<void>;
79
+ }
80
+
81
+ export interface BrowserRunInteractiveBrowser {
82
+ readonly createContext: () => Promise<BrowserRunInteractiveContext>;
83
+ readonly close: () => Promise<void>;
84
+ readonly isConnected: () => boolean;
85
+ readonly onDisconnected: (listener: () => void) => void;
86
+ readonly offDisconnected: (listener: () => void) => void;
87
+ }
88
+
89
+ /** Host-supplied Browser Run binding projected into one fakeable launch operation. */
90
+ export class BrowserRunInteractiveBinding extends Context.Service<
91
+ BrowserRunInteractiveBinding,
92
+ {
93
+ readonly launch: (keepAliveMillis: number) => Promise<BrowserRunInteractiveBrowser>;
94
+ }
95
+ >()("@effect-agent/platform-cloudflare/BrowserRunInteractiveBinding") {
96
+ static layer(options: {
97
+ readonly browser: BrowserRun;
98
+ }): Layer.Layer<BrowserRunInteractiveBinding> {
99
+ return Layer.succeed(BrowserRunInteractiveBinding)({
100
+ launch: async (keepAliveMillis) =>
101
+ makeProductionBrowser(
102
+ await puppeteer.launch(options.browser, {
103
+ keep_alive: keepAliveMillis,
104
+ }),
105
+ ),
106
+ });
107
+ }
108
+ }
109
+
110
+ const makeProductionRequest = (request: HTTPRequest): BrowserRunInteractiveRequest => ({
111
+ url: () => request.url(),
112
+ abort: () => request.abort("blockedbyclient"),
113
+ continue: () => request.continue(),
114
+ });
115
+
116
+ const makeProductionPage = (page: Page): BrowserRunInteractivePage => {
117
+ const listeners = new Map<BrowserRunInteractiveRequestListener, (request: HTTPRequest) => void>();
118
+ return {
119
+ close: () => page.close(),
120
+ setBypassServiceWorker: (enabled) => page.setBypassServiceWorker(enabled),
121
+ setRequestInterception: (enabled) => page.setRequestInterception(enabled),
122
+ onRequest: (listener) => {
123
+ const sdkListener = (request: HTTPRequest) => listener(makeProductionRequest(request));
124
+ listeners.set(listener, sdkListener);
125
+ page.on("request", sdkListener);
126
+ },
127
+ offRequest: (listener) => {
128
+ const sdkListener = listeners.get(listener);
129
+ if (sdkListener !== undefined) {
130
+ page.off("request", sdkListener);
131
+ listeners.delete(listener);
132
+ }
133
+ },
134
+ goto: async (url) => {
135
+ await page.goto(url, { waitUntil: "networkidle0", timeout: 0 });
136
+ },
137
+ url: () => page.url(),
138
+ readText: (selector, maximumBytes) =>
139
+ page.evaluate(
140
+ (requestedSelector, maximum) => {
141
+ const pageDocument = Reflect.get(globalThis, "document");
142
+ const element =
143
+ requestedSelector === undefined
144
+ ? Reflect.get(pageDocument, "body")
145
+ : Reflect.apply(Reflect.get(pageDocument, "querySelector"), pageDocument, [
146
+ requestedSelector,
147
+ ]);
148
+ if (element === null) return { _tag: "MissingElement" };
149
+ const innerText = Reflect.get(element, "innerText");
150
+ const textContent = Reflect.get(element, "textContent");
151
+ const text =
152
+ typeof innerText === "string"
153
+ ? innerText
154
+ : typeof textContent === "string"
155
+ ? textContent
156
+ : "";
157
+ const observed = new TextEncoder().encode(text).byteLength;
158
+ return observed > maximum ? { _tag: "OverLimit", observed } : { _tag: "Text", text };
159
+ },
160
+ selector,
161
+ maximumBytes,
162
+ ),
163
+ fill: async (selector, value) => {
164
+ await page.$eval(
165
+ selector,
166
+ (element, nextValue) => {
167
+ if (!("value" in element)) {
168
+ throw new Error("The selector did not resolve to a fillable field");
169
+ }
170
+ const focus = Reflect.get(element, "focus");
171
+ if (typeof focus === "function") Reflect.apply(focus, element, []);
172
+ Reflect.set(element, "value", nextValue);
173
+ const dispatchEvent = Reflect.get(element, "dispatchEvent");
174
+ if (typeof dispatchEvent === "function") {
175
+ Reflect.apply(dispatchEvent, element, [new Event("input", { bubbles: true })]);
176
+ Reflect.apply(dispatchEvent, element, [new Event("change", { bubbles: true })]);
177
+ }
178
+ },
179
+ value,
180
+ );
181
+ },
182
+ click: (selector) => page.click(selector),
183
+ };
184
+ };
185
+
186
+ const makeProductionContext = (context: BrowserContext): BrowserRunInteractiveContext => ({
187
+ newPage: async () => makeProductionPage(await context.newPage()),
188
+ close: () => context.close(),
189
+ });
190
+
191
+ const makeProductionBrowser = (browser: Browser): BrowserRunInteractiveBrowser => ({
192
+ createContext: async () => makeProductionContext(await browser.createBrowserContext()),
193
+ close: () => browser.close(),
194
+ isConnected: () => browser.isConnected(),
195
+ onDisconnected: (listener) => {
196
+ browser.on("disconnected", listener);
197
+ },
198
+ offDisconnected: (listener) => {
199
+ browser.off("disconnected", listener);
200
+ },
201
+ });
202
+
203
+ const protocolError = (message: string, cause?: unknown): InteractiveBrowserProtocolError =>
204
+ InteractiveBrowserProtocolError.make({
205
+ implementation: browserRunInteractiveImplementation,
206
+ message,
207
+ ...(cause === undefined ? {} : { cause }),
208
+ });
209
+
210
+ const actionError = (operation: BrowserOperation, cause?: unknown): InteractiveBrowserActionError =>
211
+ InteractiveBrowserActionError.make({
212
+ implementation: browserRunInteractiveImplementation,
213
+ operation,
214
+ message: `The interactive browser ${operation} operation failed`,
215
+ ...(cause === undefined ? {} : { cause }),
216
+ });
217
+
218
+ const policyError = (message: string): InteractiveBrowserPolicyDeniedError =>
219
+ InteractiveBrowserPolicyDeniedError.make({
220
+ implementation: browserRunInteractiveImplementation,
221
+ message,
222
+ });
223
+
224
+ const expiredError = (): InteractiveBrowserExpiredError =>
225
+ InteractiveBrowserExpiredError.make({
226
+ implementation: browserRunInteractiveImplementation,
227
+ message: "The remote browser is no longer usable",
228
+ });
229
+
230
+ const causeText = (cause: unknown): string => {
231
+ if (cause instanceof Error) return cause.message.slice(0, 8_000);
232
+ return String(cause).slice(0, 8_000);
233
+ };
234
+
235
+ const isCapacityRefusal = (cause: unknown): boolean =>
236
+ /(^|\D)429(\D|$)|browser time limit|capacity|too many concurrent/i.test(causeText(cause));
237
+
238
+ const isRemoteClosure = (cause: unknown): boolean =>
239
+ /target closed|browser.*closed|session.*closed|connection.*closed|not connected|websocket.*closed/i.test(
240
+ causeText(cause),
241
+ );
242
+
243
+ const snapshotPolicy = (
244
+ input: InteractiveBrowserPolicy,
245
+ ): Effect.Effect<InteractiveBrowserPolicySnapshot, InteractiveBrowserPolicyDeniedError> =>
246
+ Schema.decodeUnknownEffect(InteractiveBrowserPolicy)(input).pipe(
247
+ Effect.mapError(() => policyError("The interactive browser policy is malformed")),
248
+ Effect.map((decoded) =>
249
+ Object.freeze({
250
+ allowedHosts: Object.freeze([...decoded.allowedHosts]),
251
+ maxActions: decoded.maxActions,
252
+ maxElapsedMillis: decoded.maxElapsedMillis,
253
+ maxReturnedBytes: decoded.maxReturnedBytes,
254
+ }),
255
+ ),
256
+ );
257
+
258
+ const hostAllowed = (policy: InteractiveBrowserPolicySnapshot, value: string): boolean => {
259
+ try {
260
+ const url = new URL(value);
261
+ return (
262
+ url.protocol === "https:" &&
263
+ url.username === "" &&
264
+ url.password === "" &&
265
+ policy.allowedHosts.some((host) => host === url.host)
266
+ );
267
+ } catch {
268
+ return false;
269
+ }
270
+ };
271
+
272
+ const keepAliveMillis = (policy: InteractiveBrowserPolicySnapshot): number =>
273
+ Math.max(MIN_KEEP_ALIVE_MILLIS, Math.min(MAX_KEEP_ALIVE_MILLIS, policy.maxElapsedMillis));
274
+
275
+ interface CloseableRemote {
276
+ readonly close: () => Promise<void>;
277
+ }
278
+
279
+ const closeLateAcquisition = async <A extends CloseableRemote>(
280
+ signal: AbortSignal,
281
+ acquire: () => Promise<A>,
282
+ ): Promise<A> => {
283
+ const acquired = await acquire();
284
+ if (!signal.aborted) return acquired;
285
+
286
+ // The SDK does not accept AbortSignal. If an acquisition settles after Effect
287
+ // has interrupted it, ownership never reaches Scope, so close it here instead.
288
+ try {
289
+ await acquired.close();
290
+ } catch {
291
+ // No caller remains to observe a late cleanup failure, and provider details
292
+ // must not escape through an unhandled rejection.
293
+ }
294
+ throw new Error("The interrupted browser acquisition completed late");
295
+ };
296
+
297
+ const closeWithWarning = (close: () => Promise<void>, warning: string): Effect.Effect<void> =>
298
+ Effect.tryPromise({
299
+ try: close,
300
+ catch: () => protocolError(warning),
301
+ }).pipe(Effect.catchCause(() => Effect.logWarning(warning)));
302
+
303
+ const deadlineError = Effect.fn("BrowserRunInteractive.deadlineError")(function* (
304
+ policy: InteractiveBrowserPolicySnapshot,
305
+ startedAt: number,
306
+ ) {
307
+ const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
308
+ return yield* InteractiveBrowserLimitError.make({
309
+ implementation: browserRunInteractiveImplementation,
310
+ limit: "elapsed",
311
+ maximum: policy.maxElapsedMillis,
312
+ observed: Math.max(policy.maxElapsedMillis, now - startedAt),
313
+ message: "The browser elapsed-time limit was reached",
314
+ });
315
+ });
316
+
317
+ const withinDeadline = Effect.fn("BrowserRunInteractive.withinDeadline")(function* <A, E, R>(
318
+ effect: Effect.Effect<A, E, R>,
319
+ policy: InteractiveBrowserPolicySnapshot,
320
+ startedAt: number,
321
+ onTimeout?: () => void,
322
+ ): Effect.fn.Return<A, E | InteractiveBrowserLimitError, R> {
323
+ const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
324
+ const elapsed = Math.max(0, now - startedAt);
325
+ const remaining = policy.maxElapsedMillis - elapsed;
326
+ if (remaining <= 0) return yield* deadlineError(policy, startedAt);
327
+ return yield* effect.pipe(
328
+ Effect.timeoutOrElse({
329
+ duration: Duration.millis(remaining),
330
+ orElse: () =>
331
+ Effect.sync(() => onTimeout?.()).pipe(Effect.andThen(deadlineError(policy, startedAt))),
332
+ }),
333
+ );
334
+ });
335
+
336
+ interface HandleState {
337
+ readonly disconnected: { value: boolean };
338
+ readonly uncertain: { value: boolean };
339
+ readonly violation: { value: BrowserFailure | undefined };
340
+ readonly pendingRequests: Set<Promise<void>>;
341
+ }
342
+
343
+ const stateFailure = (state: HandleState): BrowserFailure | undefined => {
344
+ if (state.violation.value !== undefined) return state.violation.value;
345
+ if (state.disconnected.value || state.uncertain.value) return expiredError();
346
+ return undefined;
347
+ };
348
+
349
+ const awaitPendingRequests = (state: HandleState): Effect.Effect<void> =>
350
+ Effect.suspend(() => {
351
+ const pending = [...state.pendingRequests];
352
+ return pending.length === 0
353
+ ? Effect.void
354
+ : Effect.promise(() => Promise.all(pending)).pipe(
355
+ Effect.asVoid,
356
+ Effect.andThen(awaitPendingRequests(state)),
357
+ );
358
+ });
359
+
360
+ const decodeNavigationResult = Effect.fn("BrowserRunInteractive.decodeNavigationResult")(function* (
361
+ page: BrowserRunInteractivePage,
362
+ policy: InteractiveBrowserPolicySnapshot,
363
+ ) {
364
+ const url = yield* Effect.try({
365
+ try: page.url,
366
+ catch: (cause) => protocolError("Reading the browser navigation URL failed", cause),
367
+ });
368
+ const result = yield* Schema.decodeUnknownEffect(BrowserNavigationResult)({
369
+ url,
370
+ }).pipe(
371
+ Effect.mapError((cause) =>
372
+ protocolError("The browser returned a malformed navigation URL", cause),
373
+ ),
374
+ );
375
+ if (!hostAllowed(policy, result.url)) {
376
+ return yield* policyError("The browser returned an off-policy page URL");
377
+ }
378
+ return result;
379
+ });
380
+
381
+ const decodeActionResult = Effect.fn("BrowserRunInteractive.decodeActionResult")(function* (
382
+ page: BrowserRunInteractivePage,
383
+ policy: InteractiveBrowserPolicySnapshot,
384
+ ) {
385
+ const url = yield* Effect.try({
386
+ try: page.url,
387
+ catch: (cause) => protocolError("Reading the browser page URL failed", cause),
388
+ });
389
+ const result = yield* Schema.decodeUnknownEffect(BrowserActionResult)({ url }).pipe(
390
+ Effect.mapError((cause) => protocolError("The browser returned a malformed page URL", cause)),
391
+ );
392
+ if (!hostAllowed(policy, result.url)) {
393
+ return yield* policyError("The browser returned an off-policy page URL");
394
+ }
395
+ return result;
396
+ });
397
+
398
+ const makeRequestListener =
399
+ (
400
+ policy: InteractiveBrowserPolicySnapshot,
401
+ state: HandleState,
402
+ ): BrowserRunInteractiveRequestListener =>
403
+ (request) => {
404
+ let allowed = false;
405
+ try {
406
+ allowed = hostAllowed(policy, request.url());
407
+ } catch {
408
+ allowed = false;
409
+ }
410
+ if (!allowed) {
411
+ state.violation.value = policyError("The browser requested an off-policy URL");
412
+ }
413
+
414
+ let settlement: Promise<void>;
415
+ try {
416
+ settlement = allowed ? request.continue() : request.abort();
417
+ } catch {
418
+ state.violation.value = protocolError("Resolving an intercepted browser request failed");
419
+ return;
420
+ }
421
+ const observed = settlement
422
+ .catch(() => {
423
+ state.violation.value = protocolError("Resolving an intercepted browser request failed");
424
+ })
425
+ .finally(() => {
426
+ state.pendingRequests.delete(observed);
427
+ });
428
+ state.pendingRequests.add(observed);
429
+ };
430
+
431
+ const makeHandle = Effect.fn("BrowserRunInteractive.makeHandle")(function* (
432
+ page: BrowserRunInteractivePage,
433
+ policy: InteractiveBrowserPolicySnapshot,
434
+ startedAt: number,
435
+ state: HandleState,
436
+ ): Effect.fn.Return<BrowserHandle> {
437
+ const permits = yield* Semaphore.make(1);
438
+ const actions = yield* Ref.make(0);
439
+
440
+ const remote = <A>(operation: BrowserOperation, evaluate: () => Promise<A>) =>
441
+ Effect.tryPromise({
442
+ try: evaluate,
443
+ catch: (cause) => {
444
+ if (state.disconnected.value || isRemoteClosure(cause)) {
445
+ state.disconnected.value = true;
446
+ return expiredError();
447
+ }
448
+ return actionError(operation, cause);
449
+ },
450
+ });
451
+
452
+ const run = <A>(
453
+ effect: Effect.Effect<A, BrowserFailure>,
454
+ preflight: Effect.Effect<void, BrowserFailure> = Effect.void,
455
+ ) =>
456
+ permits
457
+ .withPermitsIfAvailable(1)(
458
+ Effect.gen(function* () {
459
+ const unavailable = stateFailure(state);
460
+ if (unavailable !== undefined) return yield* unavailable;
461
+ yield* preflight;
462
+
463
+ const admitted = yield* Ref.modify(actions, (count) =>
464
+ count >= policy.maxActions
465
+ ? [{ allowed: false, observed: count + 1 }, count]
466
+ : [{ allowed: true, observed: count + 1 }, count + 1],
467
+ );
468
+ if (!admitted.allowed) {
469
+ return yield* InteractiveBrowserLimitError.make({
470
+ implementation: browserRunInteractiveImplementation,
471
+ limit: "actions",
472
+ maximum: policy.maxActions,
473
+ observed: admitted.observed,
474
+ message: "The browser action limit was reached",
475
+ });
476
+ }
477
+
478
+ const completed = effect.pipe(
479
+ Effect.catch((error) => {
480
+ const failure = stateFailure(state);
481
+ return Effect.fail(failure ?? error);
482
+ }),
483
+ Effect.flatMap((result) =>
484
+ awaitPendingRequests(state).pipe(
485
+ Effect.flatMap(() => {
486
+ const failure = stateFailure(state);
487
+ return failure === undefined ? Effect.succeed(result) : Effect.fail(failure);
488
+ }),
489
+ ),
490
+ ),
491
+ );
492
+ return yield* withinDeadline(completed, policy, startedAt, () => {
493
+ state.uncertain.value = true;
494
+ }).pipe(
495
+ Effect.onInterrupt(() =>
496
+ Effect.sync(() => {
497
+ state.uncertain.value = true;
498
+ }),
499
+ ),
500
+ Effect.catch((error) => {
501
+ if (Schema.is(InteractiveBrowserLimitError)(error) && error.limit === "elapsed") {
502
+ return Effect.fail(error);
503
+ }
504
+ const failure = stateFailure(state);
505
+ return Effect.fail(failure ?? error);
506
+ }),
507
+ );
508
+ }),
509
+ )
510
+ .pipe(
511
+ Effect.flatMap((result) =>
512
+ Option.isSome(result)
513
+ ? Effect.succeed(result.value)
514
+ : Effect.fail(
515
+ InteractiveBrowserBusyError.make({
516
+ implementation: browserRunInteractiveImplementation,
517
+ message: "The browser handle already has an operation in flight",
518
+ }),
519
+ ),
520
+ ),
521
+ );
522
+
523
+ return {
524
+ navigate: (request) =>
525
+ run(
526
+ Effect.gen(function* () {
527
+ yield* remote("navigate", () => page.goto(request.url));
528
+ return yield* decodeNavigationResult(page, policy);
529
+ }),
530
+ Effect.suspend(() =>
531
+ hostAllowed(policy, request.url)
532
+ ? Effect.void
533
+ : Effect.fail(policyError("The navigation URL is outside the browser policy")),
534
+ ),
535
+ ),
536
+ readText: (request) =>
537
+ run(
538
+ Effect.gen(function* () {
539
+ const raw = yield* remote("read-text", () =>
540
+ page.readText(request.selector, policy.maxReturnedBytes),
541
+ );
542
+ const observation = yield* Schema.decodeUnknownEffect(TextObservation)(raw).pipe(
543
+ Effect.mapError((cause) =>
544
+ protocolError("The browser returned a malformed text observation", cause),
545
+ ),
546
+ );
547
+ if (observation._tag === "MissingElement") {
548
+ return yield* actionError("read-text");
549
+ }
550
+ if (observation._tag === "OverLimit") {
551
+ return yield* InteractiveBrowserLimitError.make({
552
+ implementation: browserRunInteractiveImplementation,
553
+ limit: "returned-bytes",
554
+ maximum: policy.maxReturnedBytes,
555
+ observed: observation.observed,
556
+ message: "The browser returned-text limit was reached",
557
+ });
558
+ }
559
+ const observed = new TextEncoder().encode(observation.text).byteLength;
560
+ if (observed > policy.maxReturnedBytes) {
561
+ return yield* InteractiveBrowserLimitError.make({
562
+ implementation: browserRunInteractiveImplementation,
563
+ limit: "returned-bytes",
564
+ maximum: policy.maxReturnedBytes,
565
+ observed,
566
+ message: "The browser returned-text limit was reached",
567
+ });
568
+ }
569
+ return yield* Schema.decodeUnknownEffect(BrowserTextResult)({
570
+ text: observation.text,
571
+ }).pipe(
572
+ Effect.mapError((cause) =>
573
+ protocolError("The browser returned malformed page text", cause),
574
+ ),
575
+ );
576
+ }),
577
+ ),
578
+ fill: (request) =>
579
+ run(
580
+ remote("fill", () => page.fill(request.selector, request.value)).pipe(
581
+ Effect.andThen(decodeActionResult(page, policy)),
582
+ ),
583
+ ),
584
+ click: (request) =>
585
+ run(
586
+ remote("click", () => page.click(request.selector)).pipe(
587
+ Effect.andThen(decodeActionResult(page, policy)),
588
+ ),
589
+ ),
590
+ };
591
+ });
592
+
593
+ /** Worker-only Cloudflare Puppeteer adapter; the caller supplies the Browser Run binding Layer. */
594
+ export const browserRunInteractiveLayer = (): Layer.Layer<
595
+ InteractiveBrowser,
596
+ never,
597
+ BrowserRunInteractiveBinding
598
+ > =>
599
+ Layer.effect(
600
+ InteractiveBrowser,
601
+ Effect.gen(function* () {
602
+ const binding = yield* BrowserRunInteractiveBinding;
603
+ return InteractiveBrowser.of({
604
+ open: (policy) =>
605
+ Effect.gen(function* () {
606
+ const fixedPolicy = yield* snapshotPolicy(policy);
607
+ const startedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
608
+ const state: HandleState = {
609
+ disconnected: { value: false },
610
+ uncertain: { value: false },
611
+ violation: { value: undefined },
612
+ pendingRequests: new Set(),
613
+ };
614
+ const browser = yield* Effect.acquireRelease(
615
+ withinDeadline(
616
+ Effect.tryPromise({
617
+ try: (signal) =>
618
+ closeLateAcquisition(signal, () =>
619
+ binding.launch(keepAliveMillis(fixedPolicy)),
620
+ ),
621
+ catch: (cause) =>
622
+ isCapacityRefusal(cause)
623
+ ? InteractiveBrowserCapacityError.make({
624
+ implementation: browserRunInteractiveImplementation,
625
+ message: "Browser Run has no capacity for a new browser session",
626
+ })
627
+ : protocolError("Launching the Browser Run session failed", cause),
628
+ }),
629
+ fixedPolicy,
630
+ startedAt,
631
+ ),
632
+ (acquired) =>
633
+ Effect.sync(() => {
634
+ state.disconnected.value = true;
635
+ }).pipe(
636
+ Effect.andThen(
637
+ closeWithWarning(acquired.close, "Closing the interactive browser failed"),
638
+ ),
639
+ ),
640
+ { interruptible: true },
641
+ );
642
+
643
+ const disconnected = () => {
644
+ state.disconnected.value = true;
645
+ };
646
+ yield* Effect.acquireRelease(
647
+ Effect.try({
648
+ try: () => browser.onDisconnected(disconnected),
649
+ catch: (cause) =>
650
+ protocolError("Installing the browser disconnect listener failed", cause),
651
+ }),
652
+ () =>
653
+ Effect.sync(() => {
654
+ browser.offDisconnected(disconnected);
655
+ }).pipe(
656
+ Effect.catchCause(() =>
657
+ Effect.logWarning("Removing the browser disconnect listener failed"),
658
+ ),
659
+ ),
660
+ );
661
+ const connected = yield* Effect.try({
662
+ try: browser.isConnected,
663
+ catch: (cause) =>
664
+ protocolError("Reading the Browser Run connection state failed", cause),
665
+ });
666
+ if (!connected) {
667
+ state.disconnected.value = true;
668
+ return yield* expiredError();
669
+ }
670
+
671
+ const context = yield* Effect.acquireRelease(
672
+ withinDeadline(
673
+ Effect.tryPromise({
674
+ try: (signal) => closeLateAcquisition(signal, browser.createContext),
675
+ catch: (cause) =>
676
+ state.disconnected.value || isRemoteClosure(cause)
677
+ ? expiredError()
678
+ : protocolError("Creating the browser context failed", cause),
679
+ }),
680
+ fixedPolicy,
681
+ startedAt,
682
+ ),
683
+ (acquired) =>
684
+ closeWithWarning(acquired.close, "Closing the interactive browser context failed"),
685
+ { interruptible: true },
686
+ );
687
+ const page = yield* Effect.acquireRelease(
688
+ withinDeadline(
689
+ Effect.tryPromise({
690
+ try: (signal) => closeLateAcquisition(signal, context.newPage),
691
+ catch: (cause) =>
692
+ state.disconnected.value || isRemoteClosure(cause)
693
+ ? expiredError()
694
+ : protocolError("Creating the browser page failed", cause),
695
+ }),
696
+ fixedPolicy,
697
+ startedAt,
698
+ ),
699
+ (acquired) =>
700
+ closeWithWarning(acquired.close, "Closing the interactive browser page failed"),
701
+ { interruptible: true },
702
+ );
703
+
704
+ yield* withinDeadline(
705
+ Effect.tryPromise({
706
+ try: () => page.setBypassServiceWorker(true),
707
+ catch: (cause) => protocolError("Bypassing browser service workers failed", cause),
708
+ }),
709
+ fixedPolicy,
710
+ startedAt,
711
+ );
712
+
713
+ const requestListener = makeRequestListener(fixedPolicy, state);
714
+ yield* Effect.acquireRelease(
715
+ Effect.try({
716
+ try: () => page.onRequest(requestListener),
717
+ catch: (cause) =>
718
+ protocolError("Installing the browser request listener failed", cause),
719
+ }),
720
+ () =>
721
+ Effect.sync(() => {
722
+ page.offRequest(requestListener);
723
+ }).pipe(
724
+ Effect.catchCause(() =>
725
+ Effect.logWarning("Removing the browser request policy failed"),
726
+ ),
727
+ ),
728
+ );
729
+
730
+ yield* withinDeadline(
731
+ Effect.tryPromise({
732
+ try: () => page.setRequestInterception(true),
733
+ catch: (cause) =>
734
+ protocolError("Installing the browser request policy failed", cause),
735
+ }),
736
+ fixedPolicy,
737
+ startedAt,
738
+ );
739
+
740
+ yield* withinDeadline(awaitPendingRequests(state), fixedPolicy, startedAt);
741
+ const setupFailure = stateFailure(state);
742
+ if (setupFailure !== undefined) return yield* setupFailure;
743
+
744
+ return yield* makeHandle(page, fixedPolicy, startedAt, state);
745
+ }),
746
+ });
747
+ }),
748
+ );