@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.
- package/LICENSE +21 -0
- package/dist/Alarm-CbhflIzz.mjs +1931 -0
- package/dist/Alarm-CbhflIzz.mjs.map +1 -0
- package/dist/Alarm-Nz1gIjfv.d.mts +252 -0
- package/dist/Alarm.d.mts +3 -0
- package/dist/Alarm.mjs +3 -0
- package/dist/BrowserCredentials-BWC4RqRn.d.mts +116 -0
- package/dist/BrowserCredentials-CktBoPgE.mjs +140 -0
- package/dist/BrowserCredentials-CktBoPgE.mjs.map +1 -0
- package/dist/BrowserCredentials.d.mts +2 -0
- package/dist/BrowserCredentials.mjs +1 -0
- package/dist/BrowserRestCapture.d.mts +14 -0
- package/dist/BrowserRestCapture.mjs +195 -0
- package/dist/BrowserRestCapture.mjs.map +1 -0
- package/dist/BrowserSession-5bdpqPIT.d.mts +152 -0
- package/dist/BrowserSession-Ce8cWN1A.mjs +673 -0
- package/dist/BrowserSession-Ce8cWN1A.mjs.map +1 -0
- package/dist/BrowserSession.d.mts +3 -0
- package/dist/BrowserSession.mjs +4 -0
- package/dist/BrowserUse-Bsi830Yv.mjs +263 -0
- package/dist/BrowserUse-Bsi830Yv.mjs.map +1 -0
- package/dist/BrowserUse-DF8afbNt.d.mts +59 -0
- package/dist/BrowserUse.d.mts +2 -0
- package/dist/BrowserUse.mjs +1 -0
- package/dist/CloudflareAiGateway-By8C8c5z.mjs +79 -0
- package/dist/CloudflareAiGateway-By8C8c5z.mjs.map +1 -0
- package/dist/CloudflareAiGateway-ukN34014.d.mts +63 -0
- package/dist/CloudflareAiGateway.d.mts +2 -0
- package/dist/CloudflareAiGateway.mjs +1 -0
- package/dist/CloudflareBindings-Dylkir84.mjs +123 -0
- package/dist/CloudflareBindings-Dylkir84.mjs.map +1 -0
- package/dist/CloudflareBindings-E1Sty9Vq.d.mts +134 -0
- package/dist/CloudflareBindings.d.mts +2 -0
- package/dist/CloudflareBindings.mjs +1 -0
- package/dist/CloudflareBrowser-CmiQpslZ.d.mts +41 -0
- package/dist/CloudflareBrowser-DmMCFeIQ.mjs +397 -0
- package/dist/CloudflareBrowser-DmMCFeIQ.mjs.map +1 -0
- package/dist/CloudflareBrowser.d.mts +3 -0
- package/dist/CloudflareBrowser.mjs +1 -0
- package/dist/CloudflareCodeMode-BMva6dCs.mjs +627 -0
- package/dist/CloudflareCodeMode-BMva6dCs.mjs.map +1 -0
- package/dist/CloudflareCodeMode-CeGXZtHv.d.mts +43 -0
- package/dist/CloudflareCodeMode.d.mts +2 -0
- package/dist/CloudflareCodeMode.mjs +1 -0
- package/dist/CloudflareConfig-BFWgEyhH.d.mts +102 -0
- package/dist/CloudflareConfig-rBlbPSIZ.mjs +125 -0
- package/dist/CloudflareConfig-rBlbPSIZ.mjs.map +1 -0
- package/dist/CloudflareConfig.d.mts +2 -0
- package/dist/CloudflareConfig.mjs +1 -0
- package/dist/CloudflareMemory-Bzp32ZpR.d.mts +120 -0
- package/dist/CloudflareMemory-DejIVKBT.mjs +207 -0
- package/dist/CloudflareMemory-DejIVKBT.mjs.map +1 -0
- package/dist/CloudflareMemory.d.mts +2 -0
- package/dist/CloudflareMemory.mjs +1 -0
- package/dist/CloudflareScheduling-BleqfC44.mjs +395 -0
- package/dist/CloudflareScheduling-BleqfC44.mjs.map +1 -0
- package/dist/CloudflareScheduling-vZ7iSR57.d.mts +54 -0
- package/dist/CloudflareScheduling.d.mts +2 -0
- package/dist/CloudflareScheduling.mjs +1 -0
- package/dist/CloudflareSubscriptions-IHSo19MU.d.mts +91 -0
- package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs +529 -0
- package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs.map +1 -0
- package/dist/CloudflareSubscriptions.d.mts +2 -0
- package/dist/CloudflareSubscriptions.mjs +1 -0
- package/dist/CloudflareThreadClient-BUv9Te1s.d.mts +2141 -0
- package/dist/CloudflareThreadClient-K7QJHYpK.mjs +496 -0
- package/dist/CloudflareThreadClient-K7QJHYpK.mjs.map +1 -0
- package/dist/CloudflareThreadClient.d.mts +3 -0
- package/dist/CloudflareThreadClient.mjs +3 -0
- package/dist/InteractiveBrowser-CMbA7YPP.d.mts +228 -0
- package/dist/InteractiveBrowser-e8ZvxC1C.mjs +2013 -0
- package/dist/InteractiveBrowser-e8ZvxC1C.mjs.map +1 -0
- package/dist/InteractiveBrowser.d.mts +2 -0
- package/dist/InteractiveBrowser.mjs +1 -0
- package/dist/LiveText-CfpcZaGb.d.mts +91 -0
- package/dist/LiveText-DaF0tN_p.mjs +148 -0
- package/dist/LiveText-DaF0tN_p.mjs.map +1 -0
- package/dist/LiveText.d.mts +2 -0
- package/dist/LiveText.mjs +1 -0
- package/dist/R2ToolResultStorage.d.mts +27 -0
- package/dist/R2ToolResultStorage.mjs +84 -0
- package/dist/R2ToolResultStorage.mjs.map +1 -0
- package/dist/ThreadObject-B2-PqnpT.d.mts +390 -0
- package/dist/ThreadObject-D1pCeNrq.mjs +1225 -0
- package/dist/ThreadObject-D1pCeNrq.mjs.map +1 -0
- package/dist/ThreadObject.d.mts +2 -0
- package/dist/ThreadObject.mjs +1 -0
- package/dist/WakeScheduler-67UeXBYK.d.mts +22 -0
- package/dist/WakeScheduler-DV4J4TRe.mjs +69 -0
- package/dist/WakeScheduler-DV4J4TRe.mjs.map +1 -0
- package/dist/WakeScheduler.d.mts +2 -0
- package/dist/WakeScheduler.mjs +1 -0
- package/dist/boundary-YrOnE2zO.mjs +41 -0
- package/dist/boundary-YrOnE2zO.mjs.map +1 -0
- package/dist/browser-failure-CWBBnf1j.mjs +70 -0
- package/dist/browser-failure-CWBBnf1j.mjs.map +1 -0
- package/dist/index.d.mts +17 -0
- package/dist/index.mjs +17 -0
- package/dist/prepared-admission-DngoYN74.mjs +57 -0
- package/dist/prepared-admission-DngoYN74.mjs.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/package.json +134 -3
- package/src/Alarm.ts +3402 -0
- package/src/BrowserCredentials.ts +181 -0
- package/src/BrowserRestCapture.ts +383 -0
- package/src/BrowserSession.ts +993 -0
- package/src/BrowserUse.ts +438 -0
- package/src/CloudflareAiGateway.ts +176 -0
- package/src/CloudflareBindings.ts +225 -0
- package/src/CloudflareBrowser.ts +9 -0
- package/src/CloudflareCodeMode.ts +896 -0
- package/src/CloudflareConfig.ts +142 -0
- package/src/CloudflareMemory.ts +418 -0
- package/src/CloudflareScheduling.ts +736 -0
- package/src/CloudflareSubscriptions.ts +1032 -0
- package/src/CloudflareThreadClient.ts +980 -0
- package/src/InteractiveBrowser.ts +3300 -0
- package/src/LiveText.ts +145 -0
- package/src/R2ToolResultStorage.ts +131 -0
- package/src/ThreadObject.ts +1348 -0
- package/src/WakeScheduler.ts +102 -0
- package/src/index.ts +16 -0
- package/src/internal/boundary.ts +53 -0
- package/src/internal/browser-binding.ts +483 -0
- package/src/internal/browser-credentials.ts +481 -0
- package/src/internal/browser-failure.ts +145 -0
- package/src/internal/browser-file-selection.ts +146 -0
- package/src/internal/browser-quick-action.ts +666 -0
- package/src/internal/browser-readonly-live-view.ts +121 -0
- package/src/internal/browser-session-lifecycle.ts +200 -0
- package/src/internal/crypto.ts +44 -0
- package/src/internal/due-queue.ts +452 -0
- package/src/internal/host-protocol-error.ts +23 -0
- package/src/internal/layers.ts +1181 -0
- package/src/internal/live-text-observation.ts +8 -0
- package/src/internal/live-text-protocol.ts +59 -0
- package/src/internal/live-text.ts +339 -0
- package/src/internal/message-delivery.ts +149 -0
- package/src/internal/page-function.ts +12 -0
- package/src/internal/prepared-admission.ts +83 -0
- package/src/internal/progress-wait.ts +121 -0
- package/src/internal/transport.ts +53 -0
- package/README.md +0 -3
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
PageCapture,
|
|
5
|
+
type PageCaptureAction,
|
|
6
|
+
type PageCaptureCapture,
|
|
7
|
+
type PageCaptureError,
|
|
8
|
+
PageCaptureNavigationError,
|
|
9
|
+
type PageCaptureOutput,
|
|
10
|
+
PageCaptureOutputLimitError,
|
|
11
|
+
PageCaptureProtocolError,
|
|
12
|
+
PageCaptureRateLimitedError,
|
|
13
|
+
type PageCaptureRequest,
|
|
14
|
+
PageCaptureResourceUse,
|
|
15
|
+
PageCaptureResult,
|
|
16
|
+
PageContentCaptured,
|
|
17
|
+
PageLinksCaptured,
|
|
18
|
+
PageMarkdownCaptured,
|
|
19
|
+
PageScrapeCaptured,
|
|
20
|
+
} from '@systemfsoftware/agent/page-capture'
|
|
21
|
+
import {
|
|
22
|
+
PageScreenshot,
|
|
23
|
+
type PageScreenshotCapture,
|
|
24
|
+
type PageScreenshotError,
|
|
25
|
+
PageScreenshotOutputLimitError,
|
|
26
|
+
type PageScreenshotRequest,
|
|
27
|
+
PageScreenshotResult,
|
|
28
|
+
} from '@systemfsoftware/agent/page-screenshot'
|
|
29
|
+
import { SandboxImplementation } from '@systemfsoftware/agent/sandbox'
|
|
30
|
+
import * as Context from 'effect/Context'
|
|
31
|
+
import * as Effect from 'effect/Effect'
|
|
32
|
+
import * as Layer from 'effect/Layer'
|
|
33
|
+
import * as Option from 'effect/Option'
|
|
34
|
+
import * as Schema from 'effect/Schema'
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The Cloudflare Browser Run Quick Action `PageCapture` adapter (capability
|
|
38
|
+
* spec §9.2). Each capture is one stateless `quickAction()` RPC on the
|
|
39
|
+
* Wrangler `browser` binding: the platform renders the target in a managed
|
|
40
|
+
* headless browser and returns one bounded output; the adapter holds no
|
|
41
|
+
* session and no state between passes. The binding requires a Worker
|
|
42
|
+
* compatibility date of `2026-03-24` or later, and local `wrangler dev` needs
|
|
43
|
+
* remote mode (`"remote": true` on the binding) because `quickAction` has no
|
|
44
|
+
* local implementation.
|
|
45
|
+
*
|
|
46
|
+
* Rendered output is untrusted, attacker-influenced content; this adapter
|
|
47
|
+
* only bounds and types it. Deployment class `E` only: no durability claim.
|
|
48
|
+
*/
|
|
49
|
+
export const browserQuickActionImplementation = SandboxImplementation.make({
|
|
50
|
+
isolation: 'isolated',
|
|
51
|
+
identity: 'cloudflare-browser-quick-action',
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Effect-native client captured by the binding service. Compose the pinned
|
|
56
|
+
* action types with the documented Kitesurf selector for links and scrape.
|
|
57
|
+
*/
|
|
58
|
+
export interface BrowserQuickActionClient {
|
|
59
|
+
readonly screenshot: (
|
|
60
|
+
options: BrowserRunScreenshotOptions,
|
|
61
|
+
) => Effect.Effect<Response, BrowserQuickActionRpcError>
|
|
62
|
+
readonly content: (
|
|
63
|
+
options: BrowserRunContentOptions,
|
|
64
|
+
) => Effect.Effect<Response, BrowserQuickActionRpcError>
|
|
65
|
+
readonly markdown: (
|
|
66
|
+
options: BrowserRunMarkdownOptions,
|
|
67
|
+
) => Effect.Effect<Response, BrowserQuickActionRpcError>
|
|
68
|
+
readonly links: (
|
|
69
|
+
options: BrowserRunLinksOptions & BrowserRunAlternateBackendOptions,
|
|
70
|
+
) => Effect.Effect<Response, BrowserQuickActionRpcError>
|
|
71
|
+
readonly scrape: (
|
|
72
|
+
options: BrowserRunScrapeOptions & BrowserRunAlternateBackendOptions,
|
|
73
|
+
) => Effect.Effect<Response, BrowserQuickActionRpcError>
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A native binding RPC rejected before it returned an HTTP response. */
|
|
77
|
+
export class BrowserQuickActionRpcError extends Schema.TaggedError<BrowserQuickActionRpcError>()(
|
|
78
|
+
'BrowserQuickActionRpcError',
|
|
79
|
+
{
|
|
80
|
+
action: Schema.Literals(['screenshot', 'content', 'markdown', 'links', 'scrape']),
|
|
81
|
+
cause: Schema.Defect(),
|
|
82
|
+
},
|
|
83
|
+
) {}
|
|
84
|
+
|
|
85
|
+
export interface BrowserQuickActionCaptureOptions {
|
|
86
|
+
/** The resolved Wrangler `browser` binding (DEPLOY-014: supplied, never ambient). */
|
|
87
|
+
readonly browser: BrowserRun
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Host-owned browser binding authority, supplied explicitly at the composition root. */
|
|
91
|
+
export class BrowserQuickActionBrowserBinding extends Context.Service<
|
|
92
|
+
BrowserQuickActionBrowserBinding,
|
|
93
|
+
BrowserQuickActionClient
|
|
94
|
+
>()('@effect-agent/platform-cloudflare/BrowserQuickActionBrowserBinding') {
|
|
95
|
+
static layer(
|
|
96
|
+
options: BrowserQuickActionCaptureOptions,
|
|
97
|
+
): Layer.Layer<BrowserQuickActionBrowserBinding> {
|
|
98
|
+
const browser = options.browser
|
|
99
|
+
|
|
100
|
+
const invoke = (
|
|
101
|
+
action: 'screenshot' | 'content' | 'markdown' | 'links' | 'scrape',
|
|
102
|
+
evaluate: () => Promise<Response>,
|
|
103
|
+
): Effect.Effect<Response, BrowserQuickActionRpcError> =>
|
|
104
|
+
Effect.tryPromise({
|
|
105
|
+
try: evaluate,
|
|
106
|
+
catch: (cause) => BrowserQuickActionRpcError.make({ action, cause }),
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
return Layer.succeed(BrowserQuickActionBrowserBinding)({
|
|
110
|
+
screenshot: (request) => invoke('screenshot', () => browser.quickAction('screenshot', request)),
|
|
111
|
+
content: (request) => invoke('content', () => browser.quickAction('content', request)),
|
|
112
|
+
markdown: (request) => invoke('markdown', () => browser.quickAction('markdown', request)),
|
|
113
|
+
links: (request) => invoke('links', () => browser.quickAction('links', request)),
|
|
114
|
+
scrape: (request) => invoke('scrape', () => browser.quickAction('scrape', request)),
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const MAX_DIAGNOSTIC_LENGTH = 8_000
|
|
120
|
+
const boundedDiagnostic = (message: string): string => message.slice(0, MAX_DIAGNOSTIC_LENGTH)
|
|
121
|
+
|
|
122
|
+
const QuickActionSuccessEnvelope = Schema.Struct({
|
|
123
|
+
success: Schema.Literal(true),
|
|
124
|
+
result: Schema.Json,
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
const QuickActionErrorEnvelope = Schema.Struct({
|
|
128
|
+
success: Schema.Literal(false),
|
|
129
|
+
errors: Schema.Array(
|
|
130
|
+
Schema.Struct({
|
|
131
|
+
message: Schema.String,
|
|
132
|
+
code: Schema.optionalKey(Schema.Finite),
|
|
133
|
+
detail: Schema.optionalKey(Schema.String),
|
|
134
|
+
path: Schema.optionalKey(Schema.String),
|
|
135
|
+
}),
|
|
136
|
+
),
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
const QuickActionEnvelope = Schema.Union([QuickActionSuccessEnvelope, QuickActionErrorEnvelope])
|
|
140
|
+
const decodeEnvelope = Schema.decodeUnknownOption(Schema.fromJsonString(QuickActionEnvelope))
|
|
141
|
+
|
|
142
|
+
/** Recognize only the provider's exact timeout grammar; never forward arbitrary error text. */
|
|
143
|
+
const navigationFailureMessage = (bodyText: string, response: Response): string => {
|
|
144
|
+
const fallback =
|
|
145
|
+
`The Browser Run Quick Action API answered HTTP ${response.status}; the destination status is unknown`
|
|
146
|
+
|
|
147
|
+
if (!isJsonResponse(response)) return fallback
|
|
148
|
+
const envelope = decodeEnvelope(bodyText)
|
|
149
|
+
|
|
150
|
+
if (Option.isNone(envelope) || envelope.value.success) return fallback
|
|
151
|
+
for (const error of envelope.value.errors) {
|
|
152
|
+
if (error.code !== 6002) continue
|
|
153
|
+
|
|
154
|
+
const timeout = /^Navigation timeout of ([1-9][0-9]{0,5}) ms exceeded$/.exec(
|
|
155
|
+
error.detail ?? '',
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
if (timeout !== null) {
|
|
159
|
+
return `Browser Run navigation timed out after ${
|
|
160
|
+
timeout[1]
|
|
161
|
+
} ms (Quick Action API HTTP ${response.status}); the destination status is unknown`
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return fallback
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Project the schema-validated request onto Cloudflare's native common options. */
|
|
169
|
+
const quickActionCommonOptions = (
|
|
170
|
+
request: PageCaptureRequest | PageScreenshotRequest,
|
|
171
|
+
): BrowserRunCommonOptions & BrowserRunAlternateBackendOptions => {
|
|
172
|
+
const options: BrowserRunBaseOptions & BrowserRunAlternateBackendOptions = {}
|
|
173
|
+
const navigation = request.navigation
|
|
174
|
+
|
|
175
|
+
if (request.engine === 'kitesurf') options.browser = 'kitesurf'
|
|
176
|
+
if (navigation !== undefined) {
|
|
177
|
+
const goto: NonNullable<BrowserRunBaseOptions['gotoOptions']> = {}
|
|
178
|
+
|
|
179
|
+
if (navigation.waitUntil !== undefined) goto.waitUntil = navigation.waitUntil
|
|
180
|
+
if (navigation.timeoutMillis !== undefined) goto.timeout = navigation.timeoutMillis
|
|
181
|
+
if (Object.keys(goto).length > 0) options.gotoOptions = goto
|
|
182
|
+
if (navigation.waitForSelector !== undefined) {
|
|
183
|
+
options.waitForSelector = {
|
|
184
|
+
selector: navigation.waitForSelector.selector,
|
|
185
|
+
...(navigation.waitForSelector.timeoutMillis === undefined
|
|
186
|
+
? {}
|
|
187
|
+
: { timeout: navigation.waitForSelector.timeoutMillis }),
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (request.viewport !== undefined) {
|
|
192
|
+
options.viewport = { width: request.viewport.width, height: request.viewport.height }
|
|
193
|
+
}
|
|
194
|
+
if (request.resourcePolicy !== undefined) {
|
|
195
|
+
if (request.resourcePolicy.rejectResourceTypes !== undefined) {
|
|
196
|
+
options.rejectResourceTypes = [...request.resourcePolicy.rejectResourceTypes]
|
|
197
|
+
}
|
|
198
|
+
if (request.resourcePolicy.allowRequestPatterns !== undefined) {
|
|
199
|
+
options.allowRequestPattern = [...request.resourcePolicy.allowRequestPatterns]
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return request.target._tag === 'PageUrlTarget'
|
|
204
|
+
? { ...options, url: request.target.url }
|
|
205
|
+
: { ...options, html: request.target.html }
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Dispatch through Cloudflare's native action-specific overloads. */
|
|
209
|
+
const executeQuickAction = (
|
|
210
|
+
browser: BrowserQuickActionClient,
|
|
211
|
+
request: PageCaptureRequest,
|
|
212
|
+
): Effect.Effect<Response, BrowserQuickActionRpcError> => {
|
|
213
|
+
const options = quickActionCommonOptions(request)
|
|
214
|
+
|
|
215
|
+
switch (request.action._tag) {
|
|
216
|
+
case 'CapturePageContent': {
|
|
217
|
+
return browser.content(options)
|
|
218
|
+
}
|
|
219
|
+
case 'CapturePageMarkdown': {
|
|
220
|
+
return browser.markdown(options)
|
|
221
|
+
}
|
|
222
|
+
case 'CapturePageLinks': {
|
|
223
|
+
return browser.links({
|
|
224
|
+
...options,
|
|
225
|
+
...(request.action.visibleLinksOnly === undefined
|
|
226
|
+
? {}
|
|
227
|
+
: { visibleLinksOnly: request.action.visibleLinksOnly }),
|
|
228
|
+
})
|
|
229
|
+
}
|
|
230
|
+
case 'CapturePageScrape': {
|
|
231
|
+
return browser.scrape({
|
|
232
|
+
...options,
|
|
233
|
+
elements: request.action.selectors.map((selector) => ({ selector })),
|
|
234
|
+
})
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const protocolError = (message: string, cause?: unknown): PageCaptureProtocolError =>
|
|
240
|
+
PageCaptureProtocolError.make({
|
|
241
|
+
implementation: browserQuickActionImplementation,
|
|
242
|
+
message: boundedDiagnostic(message),
|
|
243
|
+
...(cause === undefined ? {} : { cause }),
|
|
244
|
+
})
|
|
245
|
+
|
|
246
|
+
const navigationError = (message: string, cause?: unknown): PageCaptureNavigationError =>
|
|
247
|
+
PageCaptureNavigationError.make({
|
|
248
|
+
implementation: browserQuickActionImplementation,
|
|
249
|
+
message: boundedDiagnostic(message),
|
|
250
|
+
...(cause === undefined ? {} : { cause }),
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
/** Preserve bounded remote diagnostics for the host without exposing their text to a model. */
|
|
254
|
+
const privateResponseCause = (bodyText: string, response: Response): Error =>
|
|
255
|
+
// oxlint-disable-next-line effect/no-native-error -- Bounded foreign response diagnostic retains host metadata as cause, never as the Effect failure.
|
|
256
|
+
new Error(boundedDiagnostic(bodyText), {
|
|
257
|
+
cause: {
|
|
258
|
+
provider: 'cloudflare-browser-run',
|
|
259
|
+
httpStatus: response.status,
|
|
260
|
+
httpStatusSource: 'browser-api',
|
|
261
|
+
headers: Object.fromEntries(
|
|
262
|
+
['content-type', 'cf-ray', 'x-request-id', 'retry-after', 'x-browser-ms-used'].flatMap(
|
|
263
|
+
(name) => {
|
|
264
|
+
const value = response.headers.get(name)
|
|
265
|
+
|
|
266
|
+
return value === null ? [] : [[name, boundedDiagnostic(value)]]
|
|
267
|
+
},
|
|
268
|
+
),
|
|
269
|
+
),
|
|
270
|
+
bodyCharacters: bodyText.length,
|
|
271
|
+
bodyTruncated: bodyText.length > MAX_DIAGNOSTIC_LENGTH,
|
|
272
|
+
},
|
|
273
|
+
})
|
|
274
|
+
|
|
275
|
+
/** Foreign cancellation must not keep a response Scope open indefinitely. */
|
|
276
|
+
const cancelResponse = (cancel: () => Promise<void>, warning: string): Effect.Effect<void> =>
|
|
277
|
+
Effect.tryPromise({ try: cancel, catch: () => undefined }).pipe(
|
|
278
|
+
Effect.interruptible,
|
|
279
|
+
Effect.timeoutOrElse({
|
|
280
|
+
duration: '1 second',
|
|
281
|
+
orElse: () => Effect.fail(undefined),
|
|
282
|
+
}),
|
|
283
|
+
Effect.catch(() => Effect.logWarning(warning)),
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
const releaseResponseReader = (
|
|
287
|
+
reader: ReadableStreamDefaultReader<Uint8Array>,
|
|
288
|
+
): Effect.Effect<void> =>
|
|
289
|
+
cancelResponse(() => reader.cancel(), 'Canceling the Quick Action response failed').pipe(
|
|
290
|
+
Effect.ensuring(
|
|
291
|
+
Effect.try({
|
|
292
|
+
try: () => reader.releaseLock(),
|
|
293
|
+
catch: (cause) => protocolError('Releasing the Quick Action response failed', cause),
|
|
294
|
+
}).pipe(Effect.catch((error) => Effect.logWarning(error.message))),
|
|
295
|
+
),
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
const readBoundedResponse = Effect.fnUntraced(function*(
|
|
299
|
+
response: Response,
|
|
300
|
+
request: PageCaptureRequest,
|
|
301
|
+
) {
|
|
302
|
+
const body = response.body
|
|
303
|
+
|
|
304
|
+
if (body === null) return ''
|
|
305
|
+
|
|
306
|
+
const reader = yield* Effect.acquireRelease(
|
|
307
|
+
Effect.try({
|
|
308
|
+
try: () => body.getReader(),
|
|
309
|
+
catch: (cause) => protocolError('Opening the Quick Action response failed', cause),
|
|
310
|
+
}),
|
|
311
|
+
releaseResponseReader,
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: false })
|
|
315
|
+
let observedBytes = 0
|
|
316
|
+
let bodyText = ''
|
|
317
|
+
|
|
318
|
+
while (true) {
|
|
319
|
+
const chunk = yield* Effect.tryPromise({
|
|
320
|
+
try: () => reader.read(),
|
|
321
|
+
catch: (cause) => protocolError('Reading the Quick Action response failed', cause),
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
if (chunk.done) break
|
|
325
|
+
|
|
326
|
+
observedBytes += chunk.value.byteLength
|
|
327
|
+
if (observedBytes > request.limits.maxOutputBytes) {
|
|
328
|
+
return yield* PageCaptureOutputLimitError.make({
|
|
329
|
+
implementation: browserQuickActionImplementation,
|
|
330
|
+
limit: request.limits.maxOutputBytes,
|
|
331
|
+
observed: observedBytes,
|
|
332
|
+
})
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
bodyText += yield* Effect.try({
|
|
336
|
+
try: () => decoder.decode(chunk.value, { stream: true }),
|
|
337
|
+
catch: (cause) => protocolError('Decoding the Quick Action response failed', cause),
|
|
338
|
+
})
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
return (
|
|
342
|
+
bodyText +
|
|
343
|
+
(yield* Effect.try({
|
|
344
|
+
try: () => decoder.decode(),
|
|
345
|
+
catch: (cause) => protocolError('Decoding the Quick Action response failed', cause),
|
|
346
|
+
}))
|
|
347
|
+
)
|
|
348
|
+
}, Effect.scoped)
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Retry-After arrives in whole seconds; a non-integer form (an HTTP date) is
|
|
352
|
+
* dropped rather than guessed at.
|
|
353
|
+
*/
|
|
354
|
+
const retryAfterMillis = (response: Response): number | undefined => {
|
|
355
|
+
const header = response.headers.get('Retry-After')
|
|
356
|
+
|
|
357
|
+
if (header === null) return undefined
|
|
358
|
+
const seconds = Number(header)
|
|
359
|
+
|
|
360
|
+
if (!Number.isSafeInteger(seconds) || seconds < 0) return undefined
|
|
361
|
+
const millis = seconds * 1_000
|
|
362
|
+
|
|
363
|
+
return Number.isSafeInteger(millis) ? millis : undefined
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const browserMillis = (response: Response): number | undefined => {
|
|
367
|
+
const header = response.headers.get('X-Browser-Ms-Used')
|
|
368
|
+
|
|
369
|
+
if (header === null) return undefined
|
|
370
|
+
const millis = Number(header)
|
|
371
|
+
|
|
372
|
+
return Number.isSafeInteger(millis) && millis >= 0 ? millis : undefined
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Only trusted response metadata chooses transport framing; page text never does. */
|
|
376
|
+
const isJsonResponse = (response: Response): boolean => {
|
|
377
|
+
const contentType = response.headers.get('Content-Type')
|
|
378
|
+
|
|
379
|
+
if (contentType === null) return false
|
|
380
|
+
const mediaType = contentType.split(';', 1)[0]?.trim().toLowerCase()
|
|
381
|
+
|
|
382
|
+
return mediaType === 'application/json' || mediaType?.endsWith('+json') === true
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const parseOutput = (
|
|
386
|
+
action: PageCaptureAction,
|
|
387
|
+
bodyText: string,
|
|
388
|
+
response: Response,
|
|
389
|
+
): PageCaptureOutput | PageCaptureNavigationError | PageCaptureProtocolError => {
|
|
390
|
+
if (!isJsonResponse(response)) {
|
|
391
|
+
return protocolError(
|
|
392
|
+
'The Quick Action success response was not a JSON response envelope',
|
|
393
|
+
privateResponseCause(bodyText, response),
|
|
394
|
+
)
|
|
395
|
+
}
|
|
396
|
+
const envelope = decodeEnvelope(bodyText)
|
|
397
|
+
|
|
398
|
+
if (Option.isNone(envelope)) {
|
|
399
|
+
return protocolError(
|
|
400
|
+
'The JSON Quick Action response did not carry a valid response envelope',
|
|
401
|
+
privateResponseCause(bodyText, response),
|
|
402
|
+
)
|
|
403
|
+
}
|
|
404
|
+
if (!envelope.value.success) {
|
|
405
|
+
return navigationError(
|
|
406
|
+
navigationFailureMessage(bodyText, response),
|
|
407
|
+
privateResponseCause(bodyText, response),
|
|
408
|
+
)
|
|
409
|
+
}
|
|
410
|
+
switch (action._tag) {
|
|
411
|
+
case 'CapturePageContent':
|
|
412
|
+
case 'CapturePageMarkdown': {
|
|
413
|
+
if (typeof envelope.value.result !== 'string') {
|
|
414
|
+
return protocolError('The Quick Action envelope carried a non-text result')
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
return action._tag === 'CapturePageContent'
|
|
418
|
+
? PageContentCaptured.make({ html: envelope.value.result })
|
|
419
|
+
: PageMarkdownCaptured.make({ markdown: envelope.value.result })
|
|
420
|
+
}
|
|
421
|
+
case 'CapturePageLinks': {
|
|
422
|
+
const decoded = Schema.decodeUnknownOption(PageLinksCaptured)({
|
|
423
|
+
_tag: 'PageLinksCaptured',
|
|
424
|
+
links: envelope.value.result,
|
|
425
|
+
})
|
|
426
|
+
|
|
427
|
+
if (Option.isNone(decoded)) {
|
|
428
|
+
return protocolError('The links Quick Action did not return a bounded array of valid URLs')
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
return decoded.value
|
|
432
|
+
}
|
|
433
|
+
case 'CapturePageScrape': {
|
|
434
|
+
const decoded = Schema.decodeUnknownOption(PageScrapeCaptured)({
|
|
435
|
+
_tag: 'PageScrapeCaptured',
|
|
436
|
+
groups: envelope.value.result,
|
|
437
|
+
})
|
|
438
|
+
|
|
439
|
+
if (Option.isNone(decoded)) {
|
|
440
|
+
return protocolError(
|
|
441
|
+
'The scrape Quick Action did not return bounded grouped element records',
|
|
442
|
+
)
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
return decoded.value
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const isQuotaMessage = (text: string): boolean => /time limit|daily|quota/i.test(text)
|
|
451
|
+
|
|
452
|
+
const makeCapture = (browser: BrowserQuickActionClient): PageCaptureCapture =>
|
|
453
|
+
Effect.fnUntraced(function*(
|
|
454
|
+
request: PageCaptureRequest,
|
|
455
|
+
): Effect.fn.Return<PageCaptureResult, PageCaptureError> {
|
|
456
|
+
const response = yield* executeQuickAction(browser, request).pipe(
|
|
457
|
+
Effect.mapError((error) => protocolError('The browser binding rejected the Quick Action', error.cause)),
|
|
458
|
+
)
|
|
459
|
+
|
|
460
|
+
const bodyText = yield* readBoundedResponse(response, request)
|
|
461
|
+
|
|
462
|
+
if (response.status === 429) {
|
|
463
|
+
const retryAfter = retryAfterMillis(response)
|
|
464
|
+
const reason = isQuotaMessage(bodyText) ? 'quota' : 'rate'
|
|
465
|
+
const cause = privateResponseCause(bodyText, response)
|
|
466
|
+
|
|
467
|
+
return yield* PageCaptureRateLimitedError.make({
|
|
468
|
+
implementation: browserQuickActionImplementation,
|
|
469
|
+
reason,
|
|
470
|
+
...(retryAfter === undefined ? {} : { retryAfterMillis: retryAfter }),
|
|
471
|
+
...(cause === undefined ? {} : { cause }),
|
|
472
|
+
message: reason === 'quota'
|
|
473
|
+
? 'The Quick Action exceeded its browser quota'
|
|
474
|
+
: 'The Quick Action was rate limited',
|
|
475
|
+
})
|
|
476
|
+
}
|
|
477
|
+
if (!response.ok) {
|
|
478
|
+
const message = navigationFailureMessage(bodyText, response)
|
|
479
|
+
const cause = privateResponseCause(bodyText, response)
|
|
480
|
+
|
|
481
|
+
if (response.status >= 500) {
|
|
482
|
+
return yield* protocolError(message, cause)
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
return yield* navigationError(message, cause)
|
|
486
|
+
}
|
|
487
|
+
const output = parseOutput(request.action, bodyText, response)
|
|
488
|
+
|
|
489
|
+
if (
|
|
490
|
+
output._tag === 'PageCaptureNavigationError' ||
|
|
491
|
+
output._tag === 'PageCaptureProtocolError'
|
|
492
|
+
) {
|
|
493
|
+
return yield* output
|
|
494
|
+
}
|
|
495
|
+
const millis = browserMillis(response)
|
|
496
|
+
|
|
497
|
+
return PageCaptureResult.make({
|
|
498
|
+
implementation: browserQuickActionImplementation,
|
|
499
|
+
output,
|
|
500
|
+
resourceUse: PageCaptureResourceUse.make(
|
|
501
|
+
millis === undefined ? {} : { browserMillis: millis },
|
|
502
|
+
),
|
|
503
|
+
})
|
|
504
|
+
})
|
|
505
|
+
|
|
506
|
+
/** Stateless captures require explicit host-owned browser binding authority. */
|
|
507
|
+
export const browserQuickActionCaptureLayer: Layer.Layer<
|
|
508
|
+
PageCapture,
|
|
509
|
+
never,
|
|
510
|
+
BrowserQuickActionBrowserBinding
|
|
511
|
+
> = Layer.fresh(
|
|
512
|
+
Layer.effect(
|
|
513
|
+
PageCapture,
|
|
514
|
+
Effect.map(BrowserQuickActionBrowserBinding, (browser) => PageCapture.of({ capture: makeCapture(browser) })),
|
|
515
|
+
),
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
const screenshotOptions = (request: PageScreenshotRequest): BrowserRunScreenshotOptions => ({
|
|
519
|
+
...quickActionCommonOptions(request),
|
|
520
|
+
screenshotOptions: { type: 'png', encoding: 'binary', fullPage: request.fullPage },
|
|
521
|
+
})
|
|
522
|
+
|
|
523
|
+
const cancelBody = (body: ReadableStream<Uint8Array>): Effect.Effect<void> =>
|
|
524
|
+
cancelResponse(() => body.cancel(), 'Canceling the screenshot response failed')
|
|
525
|
+
|
|
526
|
+
const releaseScreenshotReader = (
|
|
527
|
+
reader: ReadableStreamDefaultReader<Uint8Array>,
|
|
528
|
+
): Effect.Effect<void> =>
|
|
529
|
+
cancelResponse(() => reader.cancel(), 'Canceling the screenshot response failed').pipe(
|
|
530
|
+
Effect.ensuring(
|
|
531
|
+
Effect.try({
|
|
532
|
+
try: () => reader.releaseLock(),
|
|
533
|
+
catch: () => undefined,
|
|
534
|
+
}).pipe(Effect.catch(() => Effect.logWarning('Releasing the screenshot response failed'))),
|
|
535
|
+
),
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
const pngResponse = (response: Response): boolean =>
|
|
539
|
+
response.headers.get('Content-Type')?.split(';', 1)[0]?.trim().toLowerCase() === 'image/png'
|
|
540
|
+
|
|
541
|
+
const declaredLength = (response: Response): number | undefined => {
|
|
542
|
+
const raw = response.headers.get('Content-Length')
|
|
543
|
+
|
|
544
|
+
if (raw === null || !/^(0|[1-9][0-9]*)$/.test(raw)) return undefined
|
|
545
|
+
const length = Number(raw)
|
|
546
|
+
|
|
547
|
+
return Number.isSafeInteger(length) ? length : undefined
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const readScreenshot = Effect.fnUntraced(function*(
|
|
551
|
+
response: Response,
|
|
552
|
+
request: PageScreenshotRequest,
|
|
553
|
+
) {
|
|
554
|
+
const body = response.body
|
|
555
|
+
|
|
556
|
+
if (body === null) {
|
|
557
|
+
return yield* protocolError('The screenshot response had no body')
|
|
558
|
+
}
|
|
559
|
+
if (!pngResponse(response)) {
|
|
560
|
+
yield* cancelBody(body)
|
|
561
|
+
|
|
562
|
+
return yield* protocolError('The screenshot response was not image/png')
|
|
563
|
+
}
|
|
564
|
+
const length = declaredLength(response)
|
|
565
|
+
|
|
566
|
+
if (length !== undefined && length > request.limits.maxOutputBytes) {
|
|
567
|
+
yield* cancelBody(body)
|
|
568
|
+
|
|
569
|
+
return yield* PageScreenshotOutputLimitError.make({
|
|
570
|
+
implementation: browserQuickActionImplementation,
|
|
571
|
+
limit: request.limits.maxOutputBytes,
|
|
572
|
+
observed: length,
|
|
573
|
+
})
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
const reader = yield* Effect.acquireRelease(
|
|
577
|
+
Effect.try({
|
|
578
|
+
try: () => body.getReader(),
|
|
579
|
+
catch: (cause) => protocolError('Opening the screenshot response failed', cause),
|
|
580
|
+
}),
|
|
581
|
+
releaseScreenshotReader,
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
const chunks: Array<Uint8Array> = []
|
|
585
|
+
let observed = 0
|
|
586
|
+
|
|
587
|
+
while (true) {
|
|
588
|
+
const next = yield* Effect.tryPromise({
|
|
589
|
+
try: () => reader.read(),
|
|
590
|
+
catch: (cause) => protocolError('Reading the screenshot response failed', cause),
|
|
591
|
+
})
|
|
592
|
+
|
|
593
|
+
if (next.done) break
|
|
594
|
+
observed += next.value.byteLength
|
|
595
|
+
if (observed > request.limits.maxOutputBytes) {
|
|
596
|
+
return yield* PageScreenshotOutputLimitError.make({
|
|
597
|
+
implementation: browserQuickActionImplementation,
|
|
598
|
+
limit: request.limits.maxOutputBytes,
|
|
599
|
+
observed,
|
|
600
|
+
})
|
|
601
|
+
}
|
|
602
|
+
chunks.push(next.value)
|
|
603
|
+
}
|
|
604
|
+
const bytes = new Uint8Array(observed)
|
|
605
|
+
let offset = 0
|
|
606
|
+
|
|
607
|
+
for (const chunk of chunks) {
|
|
608
|
+
bytes.set(chunk, offset)
|
|
609
|
+
offset += chunk.byteLength
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
return bytes
|
|
613
|
+
}, Effect.scoped)
|
|
614
|
+
|
|
615
|
+
const makeScreenshot = (browser: BrowserQuickActionClient): PageScreenshotCapture =>
|
|
616
|
+
Effect.fnUntraced(function*(
|
|
617
|
+
request: PageScreenshotRequest,
|
|
618
|
+
): Effect.fn.Return<PageScreenshotResult, PageScreenshotError> {
|
|
619
|
+
const response = yield* browser
|
|
620
|
+
.screenshot(screenshotOptions(request))
|
|
621
|
+
.pipe(
|
|
622
|
+
Effect.mapError((error) => protocolError('The browser binding rejected the screenshot', error.cause)),
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
if (response.status === 429) {
|
|
626
|
+
const body = response.body
|
|
627
|
+
|
|
628
|
+
if (body !== null) yield* cancelBody(body)
|
|
629
|
+
|
|
630
|
+
return yield* PageCaptureRateLimitedError.make({
|
|
631
|
+
implementation: browserQuickActionImplementation,
|
|
632
|
+
reason: 'rate',
|
|
633
|
+
...(retryAfterMillis(response) === undefined
|
|
634
|
+
? {}
|
|
635
|
+
: { retryAfterMillis: retryAfterMillis(response) }),
|
|
636
|
+
message: 'The screenshot Quick Action was rate limited',
|
|
637
|
+
})
|
|
638
|
+
}
|
|
639
|
+
if (!response.ok) {
|
|
640
|
+
const body = response.body
|
|
641
|
+
|
|
642
|
+
if (body !== null) yield* cancelBody(body)
|
|
643
|
+
const message = `The screenshot Quick Action answered HTTP ${response.status}`
|
|
644
|
+
|
|
645
|
+
return yield* response.status >= 500 ? protocolError(message) : navigationError(message)
|
|
646
|
+
}
|
|
647
|
+
const bytes = yield* readScreenshot(response, request)
|
|
648
|
+
|
|
649
|
+
return PageScreenshotResult.make({
|
|
650
|
+
implementation: browserQuickActionImplementation,
|
|
651
|
+
mediaType: 'image/png',
|
|
652
|
+
bytes,
|
|
653
|
+
})
|
|
654
|
+
})
|
|
655
|
+
|
|
656
|
+
/** Native Browser Run screenshot adapter. It retains PNG bytes only for the caller's result. */
|
|
657
|
+
export const browserQuickActionScreenshotLayer: Layer.Layer<
|
|
658
|
+
PageScreenshot,
|
|
659
|
+
never,
|
|
660
|
+
BrowserQuickActionBrowserBinding
|
|
661
|
+
> = Layer.fresh(
|
|
662
|
+
Layer.effect(
|
|
663
|
+
PageScreenshot,
|
|
664
|
+
Effect.map(BrowserQuickActionBrowserBinding, (browser) => PageScreenshot.of({ capture: makeScreenshot(browser) })),
|
|
665
|
+
),
|
|
666
|
+
)
|