@effect-agent/platform-cloudflare 0.1.0-beta.8 → 0.1.0-beta.80
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.
- package/dist/Alarm.d.mts +183 -0
- package/dist/Alarm.mjs +454 -0
- package/dist/Alarm.mjs.map +1 -0
- package/dist/BrowserRestCapture.d.mts +35 -0
- package/dist/BrowserRestCapture.mjs +238 -0
- package/dist/BrowserRestCapture.mjs.map +1 -0
- package/dist/BrowserRestCrawl.d.mts +17 -0
- package/dist/BrowserRestCrawl.mjs +244 -0
- package/dist/BrowserRestCrawl.mjs.map +1 -0
- package/dist/CloudflareAiGateway.d.mts +64 -0
- package/dist/CloudflareAiGateway.mjs +70 -0
- package/dist/CloudflareAiGateway.mjs.map +1 -0
- package/dist/CloudflareBindings.d.mts +112 -0
- package/dist/CloudflareBindings.mjs +101 -0
- package/dist/CloudflareBindings.mjs.map +1 -0
- package/dist/CloudflareBrowser-D4YqaTAl.mjs +495 -0
- package/dist/CloudflareBrowser-D4YqaTAl.mjs.map +1 -0
- package/dist/CloudflareBrowser-DJq53niJ.d.mts +80 -0
- package/dist/CloudflareBrowser.d.mts +2 -0
- package/dist/CloudflareBrowser.mjs +2 -0
- package/dist/CloudflareCodeMode.d.mts +44 -0
- package/dist/CloudflareCodeMode.mjs +616 -0
- package/dist/CloudflareCodeMode.mjs.map +1 -0
- package/dist/CloudflareConfig-f3CqTel1.d.mts +101 -0
- package/dist/CloudflareConfig.d.mts +2 -0
- package/dist/CloudflareConfig.mjs +122 -0
- package/dist/CloudflareConfig.mjs.map +1 -0
- package/dist/CloudflareMemory.d.mts +142 -0
- package/dist/CloudflareMemory.mjs +195 -0
- package/dist/CloudflareMemory.mjs.map +1 -0
- package/dist/CloudflareScheduling.d.mts +52 -0
- package/dist/CloudflareScheduling.mjs +389 -0
- package/dist/CloudflareScheduling.mjs.map +1 -0
- package/dist/CloudflareSubscriptions.d.mts +87 -0
- package/dist/CloudflareSubscriptions.mjs +524 -0
- package/dist/CloudflareSubscriptions.mjs.map +1 -0
- package/dist/CloudflareThreadClient.d.mts +1286 -0
- package/dist/CloudflareThreadClient.mjs +386 -0
- package/dist/CloudflareThreadClient.mjs.map +1 -0
- package/dist/InteractiveBrowser.d.mts +144 -0
- package/dist/InteractiveBrowser.mjs +1090 -0
- package/dist/InteractiveBrowser.mjs.map +1 -0
- package/dist/ProtectedBrowser.d.mts +65 -0
- package/dist/ProtectedBrowser.mjs +859 -0
- package/dist/ProtectedBrowser.mjs.map +1 -0
- package/dist/ThreadObject-3uDpKfB3.d.mts +816 -0
- package/dist/ThreadObject-DGkXv41C.mjs +836 -0
- package/dist/ThreadObject-DGkXv41C.mjs.map +1 -0
- package/dist/ThreadObject.d.mts +2 -0
- package/dist/ThreadObject.mjs +3 -0
- package/dist/WakeScheduler.d.mts +23 -0
- package/dist/WakeScheduler.mjs +60 -0
- package/dist/WakeScheduler.mjs.map +1 -0
- package/dist/boundary-BguazVkh.mjs +42 -0
- package/dist/boundary-BguazVkh.mjs.map +1 -0
- package/dist/browser-session-lifecycle-CUbVfEgP.mjs +84 -0
- package/dist/browser-session-lifecycle-CUbVfEgP.mjs.map +1 -0
- package/dist/browser-session-lifecycle-DJpqLXy_.d.mts +21 -0
- package/dist/index.d.mts +13 -1547
- package/dist/index.mjs +13 -1636
- package/dist/prepared-admission-DSi55W-7.mjs +73 -0
- package/dist/prepared-admission-DSi55W-7.mjs.map +1 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/package.json +1 -53
- package/src/Alarm.ts +953 -0
- package/src/BrowserRestCapture.ts +477 -0
- package/src/BrowserRestCrawl.ts +540 -0
- package/src/CloudflareAiGateway.ts +170 -0
- package/src/CloudflareBindings.ts +180 -0
- package/src/CloudflareBrowser.ts +15 -0
- package/src/{code-mode-executor.ts → CloudflareCodeMode.ts} +372 -204
- package/src/{config.ts → CloudflareConfig.ts} +9 -8
- package/src/CloudflareMemory.ts +406 -0
- package/src/CloudflareScheduling.ts +733 -0
- package/src/CloudflareSubscriptions.ts +1045 -0
- package/src/CloudflareThreadClient.ts +807 -0
- package/src/InteractiveBrowser.ts +2357 -0
- package/src/ProtectedBrowser.ts +2 -0
- package/src/ThreadObject.ts +1179 -0
- package/src/{wake-scheduler.ts → WakeScheduler.ts} +23 -23
- package/src/index.ts +12 -23
- package/src/internal/boundary.ts +55 -0
- package/src/internal/browser-quick-action.ts +857 -0
- package/src/internal/browser-session-lifecycle.ts +160 -0
- package/src/internal/layers.ts +751 -0
- package/src/internal/message-delivery.ts +148 -0
- package/src/internal/prepared-admission.ts +116 -0
- package/src/internal/progress-wait.ts +121 -0
- package/src/internal/transport.ts +42 -0
- package/src/protected-browser/binding.ts +187 -0
- package/src/protected-browser/inspect-frame.ts +125 -0
- package/src/protected-browser/native.ts +429 -0
- package/src/protected-browser/policy.ts +719 -0
- package/dist/index.mjs.map +0 -1
- package/src/alarm.ts +0 -334
- package/src/bindings.ts +0 -145
- package/src/client.ts +0 -646
- package/src/conversation-object.ts +0 -768
- package/src/layers.ts +0 -376
- package/src/transport.ts +0 -38
|
@@ -0,0 +1,477 @@
|
|
|
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
|
+
PageScrapeCaptured,
|
|
15
|
+
PageStructuredCaptured,
|
|
16
|
+
PageCaptureUnsupportedError,
|
|
17
|
+
type PageCaptureAction,
|
|
18
|
+
type PageCaptureCapture,
|
|
19
|
+
type PageCaptureError,
|
|
20
|
+
type PageCaptureOutput,
|
|
21
|
+
type PageCaptureRequest,
|
|
22
|
+
} from "@effect-agent/sandbox/PageCapture";
|
|
23
|
+
import { SandboxImplementation } from "@effect-agent/sandbox/Sandbox";
|
|
24
|
+
import { Effect, Layer, Option, Redacted, Schema, Stream } from "effect";
|
|
25
|
+
import { HttpClient, HttpClientRequest, type HttpClientError } from "effect/unstable/http";
|
|
26
|
+
|
|
27
|
+
import {
|
|
28
|
+
BrowserQuickActionWorkersAi,
|
|
29
|
+
type BrowserQuickActionWorkersAiPolicy,
|
|
30
|
+
} from "./CloudflareBrowser.ts";
|
|
31
|
+
|
|
32
|
+
/** Node-safe REST PageCapture implementation; it never imports Worker runtime modules. */
|
|
33
|
+
export const browserRestCaptureImplementation = SandboxImplementation.make({
|
|
34
|
+
isolation: "isolated",
|
|
35
|
+
identity: "cloudflare-browser-rest",
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const API_ORIGIN = "https://api.cloudflare.com";
|
|
39
|
+
const MAX_DIAGNOSTIC_LENGTH = 8_000;
|
|
40
|
+
const boundedDiagnostic = (message: string): string => message.slice(0, MAX_DIAGNOSTIC_LENGTH);
|
|
41
|
+
|
|
42
|
+
/** Explicit construction inputs; credentials are only projected into the fixed-origin Authorization header. */
|
|
43
|
+
export interface BrowserRestCaptureOptions {
|
|
44
|
+
readonly accountId: string;
|
|
45
|
+
readonly apiToken: Redacted.Redacted<string>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const RestSuccessEnvelope = Schema.Struct({
|
|
49
|
+
success: Schema.Literal(true),
|
|
50
|
+
result: Schema.Json,
|
|
51
|
+
errors: Schema.optionalKey(Schema.Array(Schema.Unknown)),
|
|
52
|
+
meta: Schema.optionalKey(Schema.Unknown),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const RestErrorEnvelope = Schema.Struct({
|
|
56
|
+
success: Schema.Literal(false),
|
|
57
|
+
errors: Schema.Array(
|
|
58
|
+
Schema.Struct({
|
|
59
|
+
message: Schema.String,
|
|
60
|
+
code: Schema.optionalKey(Schema.Number),
|
|
61
|
+
}),
|
|
62
|
+
),
|
|
63
|
+
result: Schema.optionalKey(Schema.Json),
|
|
64
|
+
meta: Schema.optionalKey(Schema.Unknown),
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const RestEnvelope = Schema.Union([RestSuccessEnvelope, RestErrorEnvelope]);
|
|
68
|
+
const decodeEnvelope = Schema.decodeUnknownOption(Schema.fromJsonString(RestEnvelope));
|
|
69
|
+
|
|
70
|
+
const protocolError = (message: string, cause?: unknown): PageCaptureProtocolError =>
|
|
71
|
+
PageCaptureProtocolError.make({
|
|
72
|
+
implementation: browserRestCaptureImplementation,
|
|
73
|
+
message: boundedDiagnostic(message),
|
|
74
|
+
...(cause === undefined ? {} : { cause }),
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const navigationError = (message: string, cause?: unknown): PageCaptureNavigationError =>
|
|
78
|
+
PageCaptureNavigationError.make({
|
|
79
|
+
implementation: browserRestCaptureImplementation,
|
|
80
|
+
message: boundedDiagnostic(message),
|
|
81
|
+
...(cause === undefined ? {} : { cause }),
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const privateResponseCause = (
|
|
85
|
+
bodyText: string,
|
|
86
|
+
apiToken: Redacted.Redacted<string>,
|
|
87
|
+
): Error | undefined => {
|
|
88
|
+
if (bodyText.length === 0) return undefined;
|
|
89
|
+
const token = Redacted.value(apiToken);
|
|
90
|
+
const diagnostic = boundedDiagnostic(bodyText);
|
|
91
|
+
|
|
92
|
+
return new Error(token.length === 0 ? diagnostic : diagnostic.replaceAll(token, "[REDACTED]"));
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const requestBody = (request: PageCaptureRequest): Record<string, unknown> => {
|
|
96
|
+
const body: Record<string, unknown> =
|
|
97
|
+
request.target._tag === "PageUrlTarget"
|
|
98
|
+
? { url: request.target.url }
|
|
99
|
+
: { html: request.target.html };
|
|
100
|
+
|
|
101
|
+
if (request.navigation !== undefined) {
|
|
102
|
+
const goto: Record<string, unknown> = {};
|
|
103
|
+
|
|
104
|
+
if (request.navigation.waitUntil !== undefined) goto.waitUntil = request.navigation.waitUntil;
|
|
105
|
+
if (request.navigation.timeoutMillis !== undefined)
|
|
106
|
+
goto.timeout = request.navigation.timeoutMillis;
|
|
107
|
+
if (Object.keys(goto).length > 0) body.gotoOptions = goto;
|
|
108
|
+
if (request.navigation.waitForSelector !== undefined) {
|
|
109
|
+
body.waitForSelector = {
|
|
110
|
+
selector: request.navigation.waitForSelector.selector,
|
|
111
|
+
...(request.navigation.waitForSelector.timeoutMillis === undefined
|
|
112
|
+
? {}
|
|
113
|
+
: { timeout: request.navigation.waitForSelector.timeoutMillis }),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (request.viewport !== undefined) body.viewport = request.viewport;
|
|
118
|
+
if (request.resourcePolicy?.rejectResourceTypes !== undefined) {
|
|
119
|
+
body.rejectResourceTypes = [...request.resourcePolicy.rejectResourceTypes];
|
|
120
|
+
}
|
|
121
|
+
if (request.resourcePolicy?.allowRequestPatterns !== undefined) {
|
|
122
|
+
body.allowRequestPattern = [...request.resourcePolicy.allowRequestPatterns];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return body;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const actionName = (
|
|
129
|
+
action: PageCaptureAction,
|
|
130
|
+
): "content" | "markdown" | "links" | "scrape" | "json" => {
|
|
131
|
+
switch (action._tag) {
|
|
132
|
+
case "CapturePageContent":
|
|
133
|
+
return "content";
|
|
134
|
+
case "CapturePageMarkdown":
|
|
135
|
+
return "markdown";
|
|
136
|
+
case "CapturePageLinks":
|
|
137
|
+
return "links";
|
|
138
|
+
case "CapturePageScrape":
|
|
139
|
+
return "scrape";
|
|
140
|
+
case "CapturePageStructured":
|
|
141
|
+
return "json";
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const actionBody = (request: PageCaptureRequest): Record<string, unknown> => {
|
|
146
|
+
const body = requestBody(request);
|
|
147
|
+
|
|
148
|
+
switch (request.action._tag) {
|
|
149
|
+
case "CapturePageContent":
|
|
150
|
+
case "CapturePageMarkdown":
|
|
151
|
+
return body;
|
|
152
|
+
case "CapturePageLinks":
|
|
153
|
+
return {
|
|
154
|
+
...body,
|
|
155
|
+
...(request.action.visibleLinksOnly === undefined
|
|
156
|
+
? {}
|
|
157
|
+
: { visibleLinksOnly: request.action.visibleLinksOnly }),
|
|
158
|
+
};
|
|
159
|
+
case "CapturePageScrape":
|
|
160
|
+
return {
|
|
161
|
+
...body,
|
|
162
|
+
elements: request.action.selectors.map((selector) => ({ selector })),
|
|
163
|
+
};
|
|
164
|
+
case "CapturePageStructured":
|
|
165
|
+
return {
|
|
166
|
+
...body,
|
|
167
|
+
response_format: { type: "json_schema", json_schema: request.action.responseFormat },
|
|
168
|
+
...(request.action.prompt === undefined ? {} : { prompt: request.action.prompt }),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const retryAfterMillis = (
|
|
174
|
+
headers: Readonly<Record<string, string | undefined>>,
|
|
175
|
+
): number | undefined => {
|
|
176
|
+
const seconds = Number(headers["retry-after"]);
|
|
177
|
+
|
|
178
|
+
if (!Number.isSafeInteger(seconds) || seconds < 0) return undefined;
|
|
179
|
+
const millis = seconds * 1_000;
|
|
180
|
+
|
|
181
|
+
return Number.isSafeInteger(millis) ? millis : undefined;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const browserMillis = (
|
|
185
|
+
headers: Readonly<Record<string, string | undefined>>,
|
|
186
|
+
): number | undefined => {
|
|
187
|
+
const millis = Number(headers["x-browser-ms-used"]);
|
|
188
|
+
|
|
189
|
+
return Number.isSafeInteger(millis) && millis >= 0 ? millis : undefined;
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
/** Response framing is provider metadata, never content controlled by the rendered page. */
|
|
193
|
+
const isJsonResponse = (headers: Readonly<Record<string, string | undefined>>): boolean => {
|
|
194
|
+
const contentType = headers["content-type"];
|
|
195
|
+
|
|
196
|
+
if (contentType === undefined) return false;
|
|
197
|
+
const mediaType = contentType.split(";", 1)[0]?.trim().toLowerCase();
|
|
198
|
+
|
|
199
|
+
return mediaType === "application/json" || mediaType?.endsWith("+json") === true;
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const readBoundedResponse = Effect.fn("BrowserRestCapture.readResponse")(function* (
|
|
203
|
+
response: { readonly stream: Stream.Stream<Uint8Array, HttpClientError.HttpClientError> },
|
|
204
|
+
request: PageCaptureRequest,
|
|
205
|
+
): Effect.fn.Return<string, PageCaptureError> {
|
|
206
|
+
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false });
|
|
207
|
+
|
|
208
|
+
const chunks = yield* Stream.runFoldEffect<
|
|
209
|
+
Uint8Array,
|
|
210
|
+
HttpClientError.HttpClientError,
|
|
211
|
+
never,
|
|
212
|
+
{ readonly observed: number; readonly text: string },
|
|
213
|
+
PageCaptureOutputLimitError | PageCaptureProtocolError,
|
|
214
|
+
never
|
|
215
|
+
>(
|
|
216
|
+
response.stream,
|
|
217
|
+
() => ({ observed: 0, text: "" }),
|
|
218
|
+
(state, chunk) => {
|
|
219
|
+
const observed = state.observed + chunk.byteLength;
|
|
220
|
+
|
|
221
|
+
if (observed > request.limits.maxOutputBytes) {
|
|
222
|
+
return Effect.fail(
|
|
223
|
+
PageCaptureOutputLimitError.make({
|
|
224
|
+
implementation: browserRestCaptureImplementation,
|
|
225
|
+
limit: request.limits.maxOutputBytes,
|
|
226
|
+
observed,
|
|
227
|
+
}),
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return Effect.try({
|
|
232
|
+
try: () => ({ observed, text: state.text + decoder.decode(chunk, { stream: true }) }),
|
|
233
|
+
catch: (cause) => protocolError("Decoding the Browser Run response failed", cause),
|
|
234
|
+
});
|
|
235
|
+
},
|
|
236
|
+
).pipe(
|
|
237
|
+
Effect.mapError((error) =>
|
|
238
|
+
Schema.is(PageCaptureOutputLimitError)(error) || Schema.is(PageCaptureProtocolError)(error)
|
|
239
|
+
? error
|
|
240
|
+
: protocolError("Reading the Browser Run response failed", error),
|
|
241
|
+
),
|
|
242
|
+
);
|
|
243
|
+
|
|
244
|
+
return yield* Effect.try({
|
|
245
|
+
try: () => chunks.text + decoder.decode(),
|
|
246
|
+
catch: (cause) => protocolError("Decoding the Browser Run response failed", cause),
|
|
247
|
+
});
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
const parseOutput = (
|
|
251
|
+
action: PageCaptureAction,
|
|
252
|
+
bodyText: string,
|
|
253
|
+
apiToken: Redacted.Redacted<string>,
|
|
254
|
+
): PageCaptureOutput | PageCaptureNavigationError | PageCaptureProtocolError => {
|
|
255
|
+
const envelope = decodeEnvelope(bodyText);
|
|
256
|
+
|
|
257
|
+
if (Option.isNone(envelope)) {
|
|
258
|
+
return protocolError(
|
|
259
|
+
"The Browser Run response did not carry a valid response envelope",
|
|
260
|
+
privateResponseCause(bodyText, apiToken),
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
if (!envelope.value.success) {
|
|
264
|
+
return navigationError(
|
|
265
|
+
"Browser Run reported a navigation failure",
|
|
266
|
+
privateResponseCause(bodyText, apiToken),
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
switch (action._tag) {
|
|
270
|
+
case "CapturePageContent":
|
|
271
|
+
case "CapturePageMarkdown":
|
|
272
|
+
if (typeof envelope.value.result !== "string") {
|
|
273
|
+
return protocolError("The Browser Run response envelope carried a non-text result");
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return action._tag === "CapturePageContent"
|
|
277
|
+
? PageContentCaptured.make({ html: envelope.value.result })
|
|
278
|
+
: PageMarkdownCaptured.make({ markdown: envelope.value.result });
|
|
279
|
+
case "CapturePageLinks": {
|
|
280
|
+
const decoded = Schema.decodeUnknownOption(PageLinksCaptured)({
|
|
281
|
+
_tag: "PageLinksCaptured",
|
|
282
|
+
links: envelope.value.result,
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
return Option.isSome(decoded)
|
|
286
|
+
? decoded.value
|
|
287
|
+
: protocolError("Browser Run links did not return a bounded array of valid URLs");
|
|
288
|
+
}
|
|
289
|
+
case "CapturePageScrape": {
|
|
290
|
+
const decoded = Schema.decodeUnknownOption(PageScrapeCaptured)({
|
|
291
|
+
_tag: "PageScrapeCaptured",
|
|
292
|
+
groups: envelope.value.result,
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
return Option.isSome(decoded)
|
|
296
|
+
? decoded.value
|
|
297
|
+
: protocolError("Browser Run scrape did not return bounded grouped element records");
|
|
298
|
+
}
|
|
299
|
+
case "CapturePageStructured":
|
|
300
|
+
return PageStructuredCaptured.make({ value: envelope.value.result });
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
const isQuotaMessage = (text: string): boolean => /time limit|daily|quota/i.test(text);
|
|
305
|
+
|
|
306
|
+
const makeCapture = (
|
|
307
|
+
client: HttpClient.HttpClient,
|
|
308
|
+
options: BrowserRestCaptureOptions,
|
|
309
|
+
workersAi?: BrowserQuickActionWorkersAiPolicy,
|
|
310
|
+
): PageCaptureCapture =>
|
|
311
|
+
Effect.fn("BrowserRestCapture.capture")(function* (
|
|
312
|
+
request: PageCaptureRequest,
|
|
313
|
+
): Effect.fn.Return<PageCaptureResult, PageCaptureError> {
|
|
314
|
+
const usesWorkersAi = request.action._tag === "CapturePageStructured";
|
|
315
|
+
|
|
316
|
+
if (usesWorkersAi) {
|
|
317
|
+
if (workersAi === undefined) {
|
|
318
|
+
return yield* PageCaptureUnsupportedError.make({
|
|
319
|
+
implementation: browserRestCaptureImplementation,
|
|
320
|
+
feature: "action",
|
|
321
|
+
message:
|
|
322
|
+
"Structured capture invokes separately billed Workers AI and requires an explicit authorization and accounting policy",
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
yield* workersAi.authorizeAndAccount(request).pipe(
|
|
326
|
+
Effect.mapError((cause) =>
|
|
327
|
+
PageCaptureInferencePolicyError.make({
|
|
328
|
+
implementation: browserRestCaptureImplementation,
|
|
329
|
+
provider: "cloudflare-workers-ai",
|
|
330
|
+
reason: cause.reason,
|
|
331
|
+
message:
|
|
332
|
+
cause.reason === "authorization"
|
|
333
|
+
? "Workers AI extraction was not authorized"
|
|
334
|
+
: "Workers AI extraction could not be accounted for",
|
|
335
|
+
cause,
|
|
336
|
+
}),
|
|
337
|
+
),
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
const action = actionName(request.action);
|
|
341
|
+
const path = `${API_ORIGIN}/client/v4/accounts/${encodeURIComponent(options.accountId)}/browser-rendering/${action}`;
|
|
342
|
+
|
|
343
|
+
const requestWithBody = yield* HttpClientRequest.post(path).pipe(
|
|
344
|
+
request.engine === "kitesurf"
|
|
345
|
+
? HttpClientRequest.setUrlParam("browser", "kitesurf")
|
|
346
|
+
: (value) => value,
|
|
347
|
+
HttpClientRequest.bearerToken(options.apiToken),
|
|
348
|
+
HttpClientRequest.acceptJson,
|
|
349
|
+
HttpClientRequest.bodyJson(actionBody(request)),
|
|
350
|
+
Effect.mapError((cause) => protocolError("Encoding the Browser Run request failed", cause)),
|
|
351
|
+
);
|
|
352
|
+
|
|
353
|
+
const response = yield* client
|
|
354
|
+
.execute(requestWithBody)
|
|
355
|
+
.pipe(
|
|
356
|
+
Effect.mapError((cause) => protocolError("Calling the Browser Run REST API failed", cause)),
|
|
357
|
+
);
|
|
358
|
+
|
|
359
|
+
const bodyText = yield* readBoundedResponse(response, request);
|
|
360
|
+
|
|
361
|
+
if (response.status === 429) {
|
|
362
|
+
const reason = isQuotaMessage(bodyText) ? "quota" : "rate";
|
|
363
|
+
|
|
364
|
+
return yield* PageCaptureRateLimitedError.make({
|
|
365
|
+
implementation: browserRestCaptureImplementation,
|
|
366
|
+
reason,
|
|
367
|
+
...(retryAfterMillis(response.headers) === undefined
|
|
368
|
+
? {}
|
|
369
|
+
: { retryAfterMillis: retryAfterMillis(response.headers) }),
|
|
370
|
+
...(privateResponseCause(bodyText, options.apiToken) === undefined
|
|
371
|
+
? {}
|
|
372
|
+
: { cause: privateResponseCause(bodyText, options.apiToken) }),
|
|
373
|
+
message:
|
|
374
|
+
reason === "quota"
|
|
375
|
+
? "Browser Run exceeded its browser quota"
|
|
376
|
+
: "Browser Run was rate limited",
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
if (response.status < 200 || response.status >= 300) {
|
|
380
|
+
const error =
|
|
381
|
+
response.status >= 500
|
|
382
|
+
? protocolError(
|
|
383
|
+
`Browser Run answered HTTP ${String(response.status)}`,
|
|
384
|
+
privateResponseCause(bodyText, options.apiToken),
|
|
385
|
+
)
|
|
386
|
+
: navigationError(
|
|
387
|
+
`Browser Run answered HTTP ${String(response.status)}`,
|
|
388
|
+
privateResponseCause(bodyText, options.apiToken),
|
|
389
|
+
);
|
|
390
|
+
|
|
391
|
+
return yield* error;
|
|
392
|
+
}
|
|
393
|
+
if (!isJsonResponse(response.headers)) {
|
|
394
|
+
return yield* protocolError(
|
|
395
|
+
"The Browser Run success response was not a JSON response envelope",
|
|
396
|
+
privateResponseCause(bodyText, options.apiToken),
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
const output = parseOutput(request.action, bodyText, options.apiToken);
|
|
400
|
+
|
|
401
|
+
if (
|
|
402
|
+
output._tag === "PageCaptureNavigationError" ||
|
|
403
|
+
output._tag === "PageCaptureProtocolError"
|
|
404
|
+
) {
|
|
405
|
+
return yield* output;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
return PageCaptureResult.make({
|
|
409
|
+
implementation: browserRestCaptureImplementation,
|
|
410
|
+
output,
|
|
411
|
+
resourceUse: PageCaptureResourceUse.make({
|
|
412
|
+
...(browserMillis(response.headers) === undefined
|
|
413
|
+
? {}
|
|
414
|
+
: { browserMillis: browserMillis(response.headers) }),
|
|
415
|
+
...(usesWorkersAi
|
|
416
|
+
? {
|
|
417
|
+
inference: PageCaptureInferenceUse.make({
|
|
418
|
+
provider: "cloudflare-workers-ai",
|
|
419
|
+
modelCalls: 1,
|
|
420
|
+
}),
|
|
421
|
+
}
|
|
422
|
+
: {}),
|
|
423
|
+
}),
|
|
424
|
+
});
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
/** REST PageCapture layer for Node and other non-Worker composition roots. */
|
|
428
|
+
export const browserRestCaptureLayer = (
|
|
429
|
+
options: BrowserRestCaptureOptions,
|
|
430
|
+
): Layer.Layer<PageCapture, never, HttpClient.HttpClient> =>
|
|
431
|
+
Layer.effect(
|
|
432
|
+
PageCapture,
|
|
433
|
+
Effect.map(HttpClient.HttpClient, (client) =>
|
|
434
|
+
PageCapture.of({ capture: makeCapture(client, options) }),
|
|
435
|
+
),
|
|
436
|
+
);
|
|
437
|
+
|
|
438
|
+
/** REST structured extraction additionally requires explicit Workers AI authorization/accounting. */
|
|
439
|
+
export const browserRestWorkersAiCaptureLayer = (
|
|
440
|
+
options: BrowserRestCaptureOptions,
|
|
441
|
+
): Layer.Layer<PageCapture, never, HttpClient.HttpClient | BrowserQuickActionWorkersAi> =>
|
|
442
|
+
Layer.effect(
|
|
443
|
+
PageCapture,
|
|
444
|
+
Effect.gen(function* () {
|
|
445
|
+
const client = yield* HttpClient.HttpClient;
|
|
446
|
+
const workersAi = yield* BrowserQuickActionWorkersAi;
|
|
447
|
+
|
|
448
|
+
return PageCapture.of({ capture: makeCapture(client, options, workersAi) });
|
|
449
|
+
}),
|
|
450
|
+
);
|
|
451
|
+
|
|
452
|
+
/** Explicit REST credentials and optional authorization for separately billed extraction. */
|
|
453
|
+
export interface CloudflareBrowserRestOptions extends BrowserRestCaptureOptions {
|
|
454
|
+
readonly workersAi?: BrowserQuickActionWorkersAiPolicy;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** Node-safe WebCapture handler assembly; the application supplies its HttpClient. */
|
|
458
|
+
export const CloudflareBrowserRest = {
|
|
459
|
+
/**
|
|
460
|
+
* Supports capture, scrape, and extraction definitions. Only PageCapture is supplied;
|
|
461
|
+
* handler errors and other services remain visible. Extraction fails closed without
|
|
462
|
+
* workersAi. Existing host policies, response limits, and scoped cleanup are unchanged.
|
|
463
|
+
*/
|
|
464
|
+
layer: <A, E, R>(
|
|
465
|
+
definition: { readonly handlers: Layer.Layer<A, E, R> },
|
|
466
|
+
options: CloudflareBrowserRestOptions,
|
|
467
|
+
): Layer.Layer<A, E, Exclude<R, PageCapture> | HttpClient.HttpClient> => {
|
|
468
|
+
const capture =
|
|
469
|
+
options.workersAi === undefined
|
|
470
|
+
? browserRestCaptureLayer(options)
|
|
471
|
+
: browserRestWorkersAiCaptureLayer(options).pipe(
|
|
472
|
+
Layer.provide(BrowserQuickActionWorkersAi.layer(options.workersAi)),
|
|
473
|
+
);
|
|
474
|
+
|
|
475
|
+
return definition.handlers.pipe(Layer.provide(capture));
|
|
476
|
+
},
|
|
477
|
+
};
|