@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.
@@ -11,6 +11,12 @@ import {
11
11
  PageCaptureResourceUse,
12
12
  PageCaptureResult,
13
13
  PageCaptureUnsupportedError,
14
+ PageScreenshot,
15
+ PageScreenshotOutputLimitError,
16
+ PageScreenshotResult,
17
+ type PageScreenshotCapture,
18
+ type PageScreenshotError,
19
+ type PageScreenshotRequest,
14
20
  PageContentCaptured,
15
21
  PageLinksCaptured,
16
22
  PageMarkdownCaptured,
@@ -47,6 +53,9 @@ export const browserQuickActionImplementation = SandboxImplementation.make({
47
53
  * directly from the pinned Workers declarations rather than a local copy.
48
54
  */
49
55
  export interface BrowserQuickActionClient {
56
+ readonly screenshot: (
57
+ options: BrowserRunScreenshotOptions,
58
+ ) => Effect.Effect<Response, BrowserQuickActionRpcError>;
50
59
  readonly content: (
51
60
  options: BrowserRunContentOptions,
52
61
  ) => Effect.Effect<Response, BrowserQuickActionRpcError>;
@@ -65,7 +74,7 @@ export interface BrowserQuickActionClient {
65
74
  export class BrowserQuickActionRpcError extends Schema.TaggedError<BrowserQuickActionRpcError>()(
66
75
  "BrowserQuickActionRpcError",
67
76
  {
68
- action: Schema.Literals(["content", "markdown", "links", "json"]),
77
+ action: Schema.Literals(["screenshot", "content", "markdown", "links", "json"]),
69
78
  cause: Schema.Defect(),
70
79
  },
71
80
  ) {}
@@ -85,7 +94,7 @@ export class BrowserQuickActionBrowserBinding extends Context.Service<
85
94
  ): Layer.Layer<BrowserQuickActionBrowserBinding> {
86
95
  const browser = options.browser;
87
96
  const invoke = Effect.fn("BrowserQuickActionBrowserBinding.invoke")(function* (
88
- action: "content" | "markdown" | "links" | "json",
97
+ action: "screenshot" | "content" | "markdown" | "links" | "json",
89
98
  evaluate: () => Promise<Response>,
90
99
  ): Effect.fn.Return<Response, BrowserQuickActionRpcError> {
91
100
  return yield* Effect.tryPromise({
@@ -94,6 +103,8 @@ export class BrowserQuickActionBrowserBinding extends Context.Service<
94
103
  });
95
104
  });
96
105
  return Layer.succeed(BrowserQuickActionBrowserBinding)({
106
+ screenshot: (request) =>
107
+ invoke("screenshot", () => browser.quickAction("screenshot", request)),
97
108
  content: (request) => invoke("content", () => browser.quickAction("content", request)),
98
109
  markdown: (request) => invoke("markdown", () => browser.quickAction("markdown", request)),
99
110
  links: (request) => invoke("links", () => browser.quickAction("links", request)),
@@ -512,3 +523,185 @@ export const browserQuickActionWorkersAiCaptureLayer = (): Layer.Layer<
512
523
  return PageCapture.of({ capture: makeCapture(browser, workersAi) });
513
524
  }),
514
525
  );
526
+
527
+ const screenshotOptions = (request: PageScreenshotRequest): BrowserRunScreenshotOptions => {
528
+ const options: BrowserRunBaseOptions = {};
529
+ if (
530
+ request.navigation?.waitUntil !== undefined ||
531
+ request.navigation?.timeoutMillis !== undefined
532
+ ) {
533
+ options.gotoOptions = {
534
+ ...(request.navigation.waitUntil === undefined
535
+ ? {}
536
+ : { waitUntil: request.navigation.waitUntil }),
537
+ ...(request.navigation.timeoutMillis === undefined
538
+ ? {}
539
+ : { timeout: request.navigation.timeoutMillis }),
540
+ };
541
+ }
542
+ if (request.navigation?.waitForSelector !== undefined) {
543
+ options.waitForSelector = {
544
+ selector: request.navigation.waitForSelector.selector,
545
+ ...(request.navigation.waitForSelector.timeoutMillis === undefined
546
+ ? {}
547
+ : { timeout: request.navigation.waitForSelector.timeoutMillis }),
548
+ };
549
+ }
550
+ if (request.viewport !== undefined) {
551
+ options.viewport = { width: request.viewport.width, height: request.viewport.height };
552
+ }
553
+ if (request.resourcePolicy?.rejectResourceTypes !== undefined) {
554
+ options.rejectResourceTypes = [...request.resourcePolicy.rejectResourceTypes];
555
+ }
556
+ if (request.resourcePolicy?.allowRequestPatterns !== undefined) {
557
+ options.allowRequestPattern = [...request.resourcePolicy.allowRequestPatterns];
558
+ }
559
+ return {
560
+ ...options,
561
+ ...(request.target._tag === "PageUrlTarget"
562
+ ? { url: request.target.url }
563
+ : { html: request.target.html }),
564
+ screenshotOptions: { type: "png", encoding: "binary", fullPage: request.fullPage },
565
+ };
566
+ };
567
+
568
+ const cancelBody = (body: ReadableStream<Uint8Array>): Effect.Effect<void> =>
569
+ Effect.tryPromise({
570
+ try: () => body.cancel(),
571
+ catch: () => undefined,
572
+ }).pipe(Effect.catch(() => Effect.void));
573
+
574
+ const releaseScreenshotReader = (
575
+ reader: ReadableStreamDefaultReader<Uint8Array>,
576
+ ): Effect.Effect<void> =>
577
+ Effect.tryPromise({ try: () => reader.cancel(), catch: () => undefined }).pipe(
578
+ Effect.catch(() => Effect.logWarning("Canceling the screenshot response failed")),
579
+ Effect.ensuring(
580
+ Effect.try({
581
+ try: () => reader.releaseLock(),
582
+ catch: () => undefined,
583
+ }).pipe(Effect.catch(() => Effect.logWarning("Releasing the screenshot response failed"))),
584
+ ),
585
+ );
586
+
587
+ const pngResponse = (response: Response): boolean =>
588
+ response.headers.get("Content-Type")?.split(";", 1)[0]?.trim().toLowerCase() === "image/png";
589
+
590
+ const declaredLength = (response: Response): number | undefined => {
591
+ const raw = response.headers.get("Content-Length");
592
+ if (raw === null || !/^(0|[1-9][0-9]*)$/.test(raw)) return undefined;
593
+ const length = Number(raw);
594
+ return Number.isSafeInteger(length) ? length : undefined;
595
+ };
596
+
597
+ const readScreenshot = Effect.fn("BrowserQuickActionScreenshot.read")(function* (
598
+ response: Response,
599
+ request: PageScreenshotRequest,
600
+ ) {
601
+ const body = response.body;
602
+ if (body === null) {
603
+ return yield* protocolError("The screenshot response had no body");
604
+ }
605
+ if (!pngResponse(response)) {
606
+ yield* cancelBody(body);
607
+ return yield* protocolError("The screenshot response was not image/png");
608
+ }
609
+ const length = declaredLength(response);
610
+ if (length !== undefined && length > request.limits.maxOutputBytes) {
611
+ yield* cancelBody(body);
612
+ return yield* PageScreenshotOutputLimitError.make({
613
+ implementation: browserQuickActionImplementation,
614
+ limit: request.limits.maxOutputBytes,
615
+ observed: length,
616
+ });
617
+ }
618
+ const reader = yield* Effect.acquireRelease(
619
+ Effect.try({
620
+ try: () => body.getReader(),
621
+ catch: (cause) => protocolError("Opening the screenshot response failed", cause),
622
+ }),
623
+ releaseScreenshotReader,
624
+ );
625
+ const chunks: Array<Uint8Array> = [];
626
+ let observed = 0;
627
+ while (true) {
628
+ const next = yield* Effect.tryPromise({
629
+ try: () => reader.read(),
630
+ catch: (cause) => protocolError("Reading the screenshot response failed", cause),
631
+ });
632
+ if (next.done) break;
633
+ observed += next.value.byteLength;
634
+ if (observed > request.limits.maxOutputBytes) {
635
+ return yield* PageScreenshotOutputLimitError.make({
636
+ implementation: browserQuickActionImplementation,
637
+ limit: request.limits.maxOutputBytes,
638
+ observed,
639
+ });
640
+ }
641
+ chunks.push(next.value);
642
+ }
643
+ const bytes = new Uint8Array(observed);
644
+ let offset = 0;
645
+ for (const chunk of chunks) {
646
+ bytes.set(chunk, offset);
647
+ offset += chunk.byteLength;
648
+ }
649
+ return bytes;
650
+ }, Effect.scoped);
651
+
652
+ const makeScreenshot = (browser: BrowserQuickActionClient): PageScreenshotCapture =>
653
+ Effect.fn("BrowserQuickActionScreenshot.capture")(function* (
654
+ request: PageScreenshotRequest,
655
+ ): Effect.fn.Return<PageScreenshotResult, PageScreenshotError> {
656
+ if (request.engine !== "chromium") {
657
+ return yield* PageCaptureUnsupportedError.make({
658
+ implementation: browserQuickActionImplementation,
659
+ feature: "engine",
660
+ message: "The browser binding's screenshot action exposes no engine selector",
661
+ });
662
+ }
663
+ const response = yield* browser
664
+ .screenshot(screenshotOptions(request))
665
+ .pipe(
666
+ Effect.mapError((error) =>
667
+ protocolError("The browser binding rejected the screenshot", error.cause),
668
+ ),
669
+ );
670
+ if (response.status === 429) {
671
+ const body = response.body;
672
+ if (body !== null) yield* cancelBody(body);
673
+ return yield* PageCaptureRateLimitedError.make({
674
+ implementation: browserQuickActionImplementation,
675
+ reason: "rate",
676
+ ...(retryAfterMillis(response) === undefined
677
+ ? {}
678
+ : { retryAfterMillis: retryAfterMillis(response) }),
679
+ message: "The screenshot Quick Action was rate limited",
680
+ });
681
+ }
682
+ if (!response.ok) {
683
+ const body = response.body;
684
+ if (body !== null) yield* cancelBody(body);
685
+ const message = `The screenshot Quick Action answered HTTP ${response.status}`;
686
+ return yield* response.status >= 500 ? protocolError(message) : navigationError(message);
687
+ }
688
+ const bytes = yield* readScreenshot(response, request);
689
+ return PageScreenshotResult.make({
690
+ implementation: browserQuickActionImplementation,
691
+ mediaType: "image/png",
692
+ bytes,
693
+ });
694
+ });
695
+
696
+ /** Native Browser Run screenshot adapter. It retains PNG bytes only for the caller's result. */
697
+ export const browserQuickActionScreenshotLayer = (): Layer.Layer<
698
+ PageScreenshot,
699
+ never,
700
+ BrowserQuickActionBrowserBinding
701
+ > =>
702
+ Layer.effect(
703
+ PageScreenshot,
704
+ Effect.map(BrowserQuickActionBrowserBinding, (browser) =>
705
+ PageScreenshot.of({ capture: makeScreenshot(browser) }),
706
+ ),
707
+ );
@@ -0,0 +1,401 @@
1
+ import {
2
+ PageCapture,
3
+ PageCaptureInferencePolicyError,
4
+ PageCaptureInferenceUse,
5
+ PageCaptureNavigationError,
6
+ PageCaptureOutputLimitError,
7
+ PageCaptureProtocolError,
8
+ PageCaptureRateLimitedError,
9
+ PageCaptureResourceUse,
10
+ PageCaptureResult,
11
+ PageContentCaptured,
12
+ PageLinksCaptured,
13
+ PageMarkdownCaptured,
14
+ PageStructuredCaptured,
15
+ PageCaptureUnsupportedError,
16
+ SandboxImplementation,
17
+ type PageCaptureAction,
18
+ type PageCaptureCapture,
19
+ type PageCaptureError,
20
+ type PageCaptureOutput,
21
+ type PageCaptureRequest,
22
+ } from "@effect-agent/sandbox";
23
+ import { Effect, Layer, Option, Redacted, Schema, Stream } from "effect";
24
+ import { HttpClient, HttpClientRequest, type HttpClientError } from "effect/unstable/http";
25
+
26
+ import {
27
+ BrowserQuickActionWorkersAi,
28
+ type BrowserQuickActionWorkersAiPolicy,
29
+ } from "./browser-quick-action.ts";
30
+
31
+ /** Node-safe REST PageCapture implementation; it never imports Worker runtime modules. */
32
+ export const browserRestCaptureImplementation = SandboxImplementation.make({
33
+ isolation: "isolated",
34
+ identity: "cloudflare-browser-rest",
35
+ });
36
+
37
+ const API_ORIGIN = "https://api.cloudflare.com";
38
+ const MAX_DIAGNOSTIC_LENGTH = 8_000;
39
+ const boundedDiagnostic = (message: string): string => message.slice(0, MAX_DIAGNOSTIC_LENGTH);
40
+
41
+ /** Explicit construction inputs; credentials are only projected into the fixed-origin Authorization header. */
42
+ export interface BrowserRestCaptureOptions {
43
+ readonly accountId: string;
44
+ readonly apiToken: Redacted.Redacted<string>;
45
+ }
46
+
47
+ const RestSuccessEnvelope = Schema.Struct({
48
+ success: Schema.Literal(true),
49
+ result: Schema.Json,
50
+ errors: Schema.optionalKey(Schema.Array(Schema.Unknown)),
51
+ meta: Schema.optionalKey(Schema.Unknown),
52
+ });
53
+ const RestErrorEnvelope = Schema.Struct({
54
+ success: Schema.Literal(false),
55
+ errors: Schema.Array(
56
+ Schema.Struct({
57
+ message: Schema.String,
58
+ code: Schema.optionalKey(Schema.Number),
59
+ }),
60
+ ),
61
+ result: Schema.optionalKey(Schema.Json),
62
+ meta: Schema.optionalKey(Schema.Unknown),
63
+ });
64
+ const RestEnvelope = Schema.Union([RestSuccessEnvelope, RestErrorEnvelope]);
65
+ const decodeEnvelope = Schema.decodeUnknownOption(Schema.fromJsonString(RestEnvelope));
66
+
67
+ const protocolError = (message: string, cause?: unknown): PageCaptureProtocolError =>
68
+ PageCaptureProtocolError.make({
69
+ implementation: browserRestCaptureImplementation,
70
+ message: boundedDiagnostic(message),
71
+ ...(cause === undefined ? {} : { cause }),
72
+ });
73
+
74
+ const navigationError = (message: string, cause?: unknown): PageCaptureNavigationError =>
75
+ PageCaptureNavigationError.make({
76
+ implementation: browserRestCaptureImplementation,
77
+ message: boundedDiagnostic(message),
78
+ ...(cause === undefined ? {} : { cause }),
79
+ });
80
+
81
+ const privateResponseCause = (
82
+ bodyText: string,
83
+ apiToken: Redacted.Redacted<string>,
84
+ ): Error | undefined => {
85
+ if (bodyText.length === 0) return undefined;
86
+ const token = Redacted.value(apiToken);
87
+ const diagnostic = boundedDiagnostic(bodyText);
88
+ return new Error(token.length === 0 ? diagnostic : diagnostic.replaceAll(token, "[REDACTED]"));
89
+ };
90
+
91
+ const requestBody = (request: PageCaptureRequest): Record<string, unknown> => {
92
+ const body: Record<string, unknown> =
93
+ request.target._tag === "PageUrlTarget"
94
+ ? { url: request.target.url }
95
+ : { html: request.target.html };
96
+ if (request.navigation !== undefined) {
97
+ const goto: Record<string, unknown> = {};
98
+ if (request.navigation.waitUntil !== undefined) goto.waitUntil = request.navigation.waitUntil;
99
+ if (request.navigation.timeoutMillis !== undefined)
100
+ goto.timeout = request.navigation.timeoutMillis;
101
+ if (Object.keys(goto).length > 0) body.gotoOptions = goto;
102
+ if (request.navigation.waitForSelector !== undefined) {
103
+ body.waitForSelector = {
104
+ selector: request.navigation.waitForSelector.selector,
105
+ ...(request.navigation.waitForSelector.timeoutMillis === undefined
106
+ ? {}
107
+ : { timeout: request.navigation.waitForSelector.timeoutMillis }),
108
+ };
109
+ }
110
+ }
111
+ if (request.viewport !== undefined) body.viewport = request.viewport;
112
+ if (request.resourcePolicy?.rejectResourceTypes !== undefined) {
113
+ body.rejectResourceTypes = [...request.resourcePolicy.rejectResourceTypes];
114
+ }
115
+ if (request.resourcePolicy?.allowRequestPatterns !== undefined) {
116
+ body.allowRequestPattern = [...request.resourcePolicy.allowRequestPatterns];
117
+ }
118
+ return body;
119
+ };
120
+
121
+ const actionName = (action: PageCaptureAction): "content" | "markdown" | "links" | "json" => {
122
+ switch (action._tag) {
123
+ case "CapturePageContent":
124
+ return "content";
125
+ case "CapturePageMarkdown":
126
+ return "markdown";
127
+ case "CapturePageLinks":
128
+ return "links";
129
+ case "CapturePageStructured":
130
+ return "json";
131
+ }
132
+ };
133
+
134
+ const actionBody = (request: PageCaptureRequest): Record<string, unknown> => {
135
+ const body = requestBody(request);
136
+ switch (request.action._tag) {
137
+ case "CapturePageContent":
138
+ case "CapturePageMarkdown":
139
+ return body;
140
+ case "CapturePageLinks":
141
+ return {
142
+ ...body,
143
+ ...(request.action.visibleLinksOnly === undefined
144
+ ? {}
145
+ : { visibleLinksOnly: request.action.visibleLinksOnly }),
146
+ };
147
+ case "CapturePageStructured":
148
+ return {
149
+ ...body,
150
+ response_format: { type: "json_schema", json_schema: request.action.responseFormat },
151
+ ...(request.action.prompt === undefined ? {} : { prompt: request.action.prompt }),
152
+ };
153
+ }
154
+ };
155
+
156
+ const retryAfterMillis = (
157
+ headers: Readonly<Record<string, string | undefined>>,
158
+ ): number | undefined => {
159
+ const seconds = Number(headers["retry-after"]);
160
+ if (!Number.isSafeInteger(seconds) || seconds < 0) return undefined;
161
+ const millis = seconds * 1_000;
162
+ return Number.isSafeInteger(millis) ? millis : undefined;
163
+ };
164
+
165
+ const browserMillis = (
166
+ headers: Readonly<Record<string, string | undefined>>,
167
+ ): number | undefined => {
168
+ const millis = Number(headers["x-browser-ms-used"]);
169
+ return Number.isSafeInteger(millis) && millis >= 0 ? millis : undefined;
170
+ };
171
+
172
+ /** Response framing is provider metadata, never content controlled by the rendered page. */
173
+ const isJsonResponse = (headers: Readonly<Record<string, string | undefined>>): boolean => {
174
+ const contentType = headers["content-type"];
175
+ if (contentType === undefined) return false;
176
+ const mediaType = contentType.split(";", 1)[0]?.trim().toLowerCase();
177
+ return mediaType === "application/json" || mediaType?.endsWith("+json") === true;
178
+ };
179
+
180
+ const readBoundedResponse = Effect.fn("BrowserRestCapture.readResponse")(function* (
181
+ response: { readonly stream: Stream.Stream<Uint8Array, HttpClientError.HttpClientError> },
182
+ request: PageCaptureRequest,
183
+ ): Effect.fn.Return<string, PageCaptureError> {
184
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false });
185
+ const chunks = yield* Stream.runFoldEffect<
186
+ Uint8Array,
187
+ HttpClientError.HttpClientError,
188
+ never,
189
+ { readonly observed: number; readonly text: string },
190
+ PageCaptureOutputLimitError | PageCaptureProtocolError,
191
+ never
192
+ >(
193
+ response.stream,
194
+ () => ({ observed: 0, text: "" }),
195
+ (state, chunk) => {
196
+ const observed = state.observed + chunk.byteLength;
197
+ if (observed > request.limits.maxOutputBytes) {
198
+ return Effect.fail(
199
+ PageCaptureOutputLimitError.make({
200
+ implementation: browserRestCaptureImplementation,
201
+ limit: request.limits.maxOutputBytes,
202
+ observed,
203
+ }),
204
+ );
205
+ }
206
+ return Effect.try({
207
+ try: () => ({ observed, text: state.text + decoder.decode(chunk, { stream: true }) }),
208
+ catch: (cause) => protocolError("Decoding the Browser Run response failed", cause),
209
+ });
210
+ },
211
+ ).pipe(
212
+ Effect.mapError((error) =>
213
+ Schema.is(PageCaptureOutputLimitError)(error) || Schema.is(PageCaptureProtocolError)(error)
214
+ ? error
215
+ : protocolError("Reading the Browser Run response failed", error),
216
+ ),
217
+ );
218
+ return yield* Effect.try({
219
+ try: () => chunks.text + decoder.decode(),
220
+ catch: (cause) => protocolError("Decoding the Browser Run response failed", cause),
221
+ });
222
+ });
223
+
224
+ const parseOutput = (
225
+ action: PageCaptureAction,
226
+ bodyText: string,
227
+ apiToken: Redacted.Redacted<string>,
228
+ ): PageCaptureOutput | PageCaptureNavigationError | PageCaptureProtocolError => {
229
+ const envelope = decodeEnvelope(bodyText);
230
+ if (Option.isNone(envelope)) {
231
+ return protocolError(
232
+ "The Browser Run response did not carry a valid response envelope",
233
+ privateResponseCause(bodyText, apiToken),
234
+ );
235
+ }
236
+ if (!envelope.value.success) {
237
+ return navigationError(
238
+ "Browser Run reported a navigation failure",
239
+ privateResponseCause(bodyText, apiToken),
240
+ );
241
+ }
242
+ switch (action._tag) {
243
+ case "CapturePageContent":
244
+ case "CapturePageMarkdown":
245
+ if (typeof envelope.value.result !== "string") {
246
+ return protocolError("The Browser Run response envelope carried a non-text result");
247
+ }
248
+ return action._tag === "CapturePageContent"
249
+ ? PageContentCaptured.make({ html: envelope.value.result })
250
+ : PageMarkdownCaptured.make({ markdown: envelope.value.result });
251
+ case "CapturePageLinks": {
252
+ const decoded = Schema.decodeUnknownOption(PageLinksCaptured)({
253
+ _tag: "PageLinksCaptured",
254
+ links: envelope.value.result,
255
+ });
256
+ return Option.isSome(decoded)
257
+ ? decoded.value
258
+ : protocolError("Browser Run links did not return a bounded array of valid URLs");
259
+ }
260
+ case "CapturePageStructured":
261
+ return PageStructuredCaptured.make({ value: envelope.value.result });
262
+ }
263
+ };
264
+
265
+ const isQuotaMessage = (text: string): boolean => /time limit|daily|quota/i.test(text);
266
+
267
+ const makeCapture = (
268
+ client: HttpClient.HttpClient,
269
+ options: BrowserRestCaptureOptions,
270
+ workersAi?: BrowserQuickActionWorkersAiPolicy,
271
+ ): PageCaptureCapture =>
272
+ Effect.fn("BrowserRestCapture.capture")(function* (
273
+ request: PageCaptureRequest,
274
+ ): Effect.fn.Return<PageCaptureResult, PageCaptureError> {
275
+ const usesWorkersAi = request.action._tag === "CapturePageStructured";
276
+ if (usesWorkersAi) {
277
+ if (workersAi === undefined) {
278
+ return yield* PageCaptureUnsupportedError.make({
279
+ implementation: browserRestCaptureImplementation,
280
+ feature: "action",
281
+ message:
282
+ "Structured capture invokes separately billed Workers AI and requires an explicit authorization and accounting policy",
283
+ });
284
+ }
285
+ yield* workersAi.authorizeAndAccount(request).pipe(
286
+ Effect.mapError((cause) =>
287
+ PageCaptureInferencePolicyError.make({
288
+ implementation: browserRestCaptureImplementation,
289
+ provider: "cloudflare-workers-ai",
290
+ reason: cause.reason,
291
+ message:
292
+ cause.reason === "authorization"
293
+ ? "Workers AI extraction was not authorized"
294
+ : "Workers AI extraction could not be accounted for",
295
+ cause,
296
+ }),
297
+ ),
298
+ );
299
+ }
300
+ const action = actionName(request.action);
301
+ const path = `${API_ORIGIN}/client/v4/accounts/${encodeURIComponent(options.accountId)}/browser-rendering/${action}`;
302
+ const requestWithBody = yield* HttpClientRequest.post(path).pipe(
303
+ request.engine === "kitesurf"
304
+ ? HttpClientRequest.setUrlParam("browser", "kitesurf")
305
+ : (value) => value,
306
+ HttpClientRequest.bearerToken(options.apiToken),
307
+ HttpClientRequest.acceptJson,
308
+ HttpClientRequest.bodyJson(actionBody(request)),
309
+ Effect.mapError((cause) => protocolError("Encoding the Browser Run request failed", cause)),
310
+ );
311
+ const response = yield* client
312
+ .execute(requestWithBody)
313
+ .pipe(
314
+ Effect.mapError((cause) => protocolError("Calling the Browser Run REST API failed", cause)),
315
+ );
316
+ const bodyText = yield* readBoundedResponse(response, request);
317
+ if (response.status === 429) {
318
+ const reason = isQuotaMessage(bodyText) ? "quota" : "rate";
319
+ return yield* PageCaptureRateLimitedError.make({
320
+ implementation: browserRestCaptureImplementation,
321
+ reason,
322
+ ...(retryAfterMillis(response.headers) === undefined
323
+ ? {}
324
+ : { retryAfterMillis: retryAfterMillis(response.headers) }),
325
+ ...(privateResponseCause(bodyText, options.apiToken) === undefined
326
+ ? {}
327
+ : { cause: privateResponseCause(bodyText, options.apiToken) }),
328
+ message:
329
+ reason === "quota"
330
+ ? "Browser Run exceeded its browser quota"
331
+ : "Browser Run was rate limited",
332
+ });
333
+ }
334
+ if (response.status < 200 || response.status >= 300) {
335
+ const error =
336
+ response.status >= 500
337
+ ? protocolError(
338
+ `Browser Run answered HTTP ${String(response.status)}`,
339
+ privateResponseCause(bodyText, options.apiToken),
340
+ )
341
+ : navigationError(
342
+ `Browser Run answered HTTP ${String(response.status)}`,
343
+ privateResponseCause(bodyText, options.apiToken),
344
+ );
345
+ return yield* error;
346
+ }
347
+ if (!isJsonResponse(response.headers)) {
348
+ return yield* protocolError(
349
+ "The Browser Run success response was not a JSON response envelope",
350
+ privateResponseCause(bodyText, options.apiToken),
351
+ );
352
+ }
353
+ const output = parseOutput(request.action, bodyText, options.apiToken);
354
+ if (
355
+ output._tag === "PageCaptureNavigationError" ||
356
+ output._tag === "PageCaptureProtocolError"
357
+ ) {
358
+ return yield* output;
359
+ }
360
+ return PageCaptureResult.make({
361
+ implementation: browserRestCaptureImplementation,
362
+ output,
363
+ resourceUse: PageCaptureResourceUse.make({
364
+ ...(browserMillis(response.headers) === undefined
365
+ ? {}
366
+ : { browserMillis: browserMillis(response.headers) }),
367
+ ...(usesWorkersAi
368
+ ? {
369
+ inference: PageCaptureInferenceUse.make({
370
+ provider: "cloudflare-workers-ai",
371
+ modelCalls: 1,
372
+ }),
373
+ }
374
+ : {}),
375
+ }),
376
+ });
377
+ });
378
+
379
+ /** REST PageCapture layer for Node and other non-Worker composition roots. */
380
+ export const browserRestCaptureLayer = (
381
+ options: BrowserRestCaptureOptions,
382
+ ): Layer.Layer<PageCapture, never, HttpClient.HttpClient> =>
383
+ Layer.effect(
384
+ PageCapture,
385
+ Effect.map(HttpClient.HttpClient, (client) =>
386
+ PageCapture.of({ capture: makeCapture(client, options) }),
387
+ ),
388
+ );
389
+
390
+ /** REST structured extraction additionally requires explicit Workers AI authorization/accounting. */
391
+ export const browserRestWorkersAiCaptureLayer = (
392
+ options: BrowserRestCaptureOptions,
393
+ ): Layer.Layer<PageCapture, never, HttpClient.HttpClient | BrowserQuickActionWorkersAi> =>
394
+ Layer.effect(
395
+ PageCapture,
396
+ Effect.gen(function* () {
397
+ const client = yield* HttpClient.HttpClient;
398
+ const workersAi = yield* BrowserQuickActionWorkersAi;
399
+ return PageCapture.of({ capture: makeCapture(client, options, workersAi) });
400
+ }),
401
+ );