@systemfsoftware/agent-platform-cloudflare 0.0.0-bootstrap.0 → 0.1.0-beta.192
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 +132 -5
- 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,438 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BrowserCdp,
|
|
3
|
+
BrowserUseError,
|
|
4
|
+
CloseTabRequest,
|
|
5
|
+
FrameInfo,
|
|
6
|
+
FramesRequest,
|
|
7
|
+
SendRequest,
|
|
8
|
+
Tab,
|
|
9
|
+
} from '@systemfsoftware/agent/browser-use'
|
|
10
|
+
import * as Cause from 'effect/Cause'
|
|
11
|
+
import * as Effect from 'effect/Effect'
|
|
12
|
+
import * as Layer from 'effect/Layer'
|
|
13
|
+
import * as Schema from 'effect/Schema'
|
|
14
|
+
import * as Semaphore from 'effect/Semaphore'
|
|
15
|
+
import type { CDPSession, Frame, Page } from 'puppeteer-core/lib/esm/puppeteer/puppeteer-core-browser.js'
|
|
16
|
+
|
|
17
|
+
import type { BrowserSession, BrowserSessionError } from './BrowserSession'
|
|
18
|
+
import { mapBrowserError, reportBrowserCause } from './internal/browser-failure'
|
|
19
|
+
|
|
20
|
+
export type Command =
|
|
21
|
+
| { readonly kind: 'connect' | 'tabs' | 'new-tab' }
|
|
22
|
+
| { readonly kind: 'send'; readonly request: typeof SendRequest.Type }
|
|
23
|
+
| { readonly kind: 'frames'; readonly request: typeof FramesRequest.Type }
|
|
24
|
+
| { readonly kind: 'close-tab'; readonly request: typeof CloseTabRequest.Type }
|
|
25
|
+
|
|
26
|
+
/** Current SDK metadata, never a grant supplied by page content or generated code. */
|
|
27
|
+
export interface AuthorizationContext {
|
|
28
|
+
/** Absent during initial attachment. */
|
|
29
|
+
readonly pageUrl?: string
|
|
30
|
+
readonly targetId?: string
|
|
31
|
+
readonly targetUrl?: string
|
|
32
|
+
readonly frameUrl?: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface Options<R = never> {
|
|
36
|
+
/**
|
|
37
|
+
* Runs under the BrowserSession lock before every command. Arbitrary CDP/page JavaScript
|
|
38
|
+
* is a broad capability: URL checks cannot prove that code is read-only or constrain egress.
|
|
39
|
+
* The host must authorize that capability and enforce network policy outside page code.
|
|
40
|
+
*/
|
|
41
|
+
readonly authorize: (
|
|
42
|
+
command: Command,
|
|
43
|
+
context: AuthorizationContext,
|
|
44
|
+
) => Effect.Effect<void, BrowserUseError, R>
|
|
45
|
+
/** Total native operations, including authorization refusals. Null disables the count ceiling. */
|
|
46
|
+
readonly maxCommands: number | null
|
|
47
|
+
/** Per-result UTF-8 JSON limit; does not bound the upstream CDP transfer. */
|
|
48
|
+
readonly maxReturnedBytes: number
|
|
49
|
+
/** Maximum pages discoverable through this attachment. Defaults to 8. */
|
|
50
|
+
readonly maxTabs?: number
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const Limits = Schema.Struct({
|
|
54
|
+
maxCommands: Schema.NullOr(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10_000 }))),
|
|
55
|
+
maxReturnedBytes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 8 * 1024 * 1024 })),
|
|
56
|
+
maxTabs: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 64 })),
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
const invalid = (message: string) => BrowserUseError.make({ code: 'invalid', message, dispatch: 'not-dispatched' })
|
|
60
|
+
|
|
61
|
+
const decode = <A>(schema: Schema.Codec<A>, input: unknown) =>
|
|
62
|
+
Schema.decodeUnknownEffect(schema)(input).pipe(
|
|
63
|
+
mapBrowserError((error) => BrowserUseError.withCause(invalid('Invalid browser command or limits'), error)),
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
interface AttachedPage {
|
|
67
|
+
readonly page: Page
|
|
68
|
+
readonly cdp: CDPSession
|
|
69
|
+
readonly targetId: string
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const isBrowserUseError = (value: unknown): value is BrowserUseError =>
|
|
73
|
+
Schema.is(BrowserUseError)(value) &&
|
|
74
|
+
Object.prototype.isPrototypeOf.call(BrowserUseError.prototype, value)
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* A scoped CDP bridge over an existing BrowserSession. No DOM classifier, selectors,
|
|
78
|
+
* implicit waits, input retries, or generated-code execution live in this adapter.
|
|
79
|
+
* CDP connections persist within the attachment (including remote object IDs); pages persist
|
|
80
|
+
* for the host-owned session. Scope release detaches connections without closing pages.
|
|
81
|
+
*/
|
|
82
|
+
export const make = Effect.fnUntraced(function*<R>(
|
|
83
|
+
session: Pick<BrowserSession, 'run'>,
|
|
84
|
+
options: Options<R>,
|
|
85
|
+
) {
|
|
86
|
+
const limits = yield* decode(Limits, { ...options, maxTabs: options.maxTabs ?? 8 })
|
|
87
|
+
const authority = yield* Effect.context<R>()
|
|
88
|
+
// Code Mode permits concurrent host calls; this native attachment admits one at a time.
|
|
89
|
+
const serial = yield* Semaphore.make(1)
|
|
90
|
+
|
|
91
|
+
const authorize = (command: Command, context: AuthorizationContext) =>
|
|
92
|
+
Effect.provideContext(options.authorize(command, context), authority)
|
|
93
|
+
|
|
94
|
+
const mapSessionError = (error: BrowserSessionError | BrowserUseError) =>
|
|
95
|
+
error._tag === 'BrowserUseError'
|
|
96
|
+
? error
|
|
97
|
+
: BrowserUseError.withCause(
|
|
98
|
+
BrowserUseError.make({
|
|
99
|
+
code: 'browser',
|
|
100
|
+
message: 'Browser command failed; inspect the current state before further input',
|
|
101
|
+
dispatch: error.dispatch,
|
|
102
|
+
}),
|
|
103
|
+
error,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
const mapSessionFailure = mapBrowserError(mapSessionError)
|
|
107
|
+
|
|
108
|
+
let released = false
|
|
109
|
+
|
|
110
|
+
// Register cleanup before creating any native connection, including a partially failed attachment.
|
|
111
|
+
const connections = yield* Effect.acquireRelease(
|
|
112
|
+
Effect.sync(() => new Map<Page | CDPSession, CDPSession>()),
|
|
113
|
+
(connections) =>
|
|
114
|
+
Effect.promise(async (signal) => {
|
|
115
|
+
released = true
|
|
116
|
+
for (const cdp of connections.values()) {
|
|
117
|
+
if (signal.aborted) break
|
|
118
|
+
try {
|
|
119
|
+
await cdp.detach()
|
|
120
|
+
} catch {
|
|
121
|
+
// The session may already have terminated on timeout or interruption.
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
connections.clear()
|
|
125
|
+
}).pipe(Effect.interruptible, Effect.timeoutOption('1 second'), Effect.asVoid),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
const pages = new Map<string, AttachedPage>()
|
|
129
|
+
|
|
130
|
+
const attach = async (page: Page): Promise<AttachedPage> => {
|
|
131
|
+
let cdp = connections.get(page)
|
|
132
|
+
|
|
133
|
+
if (cdp === undefined) {
|
|
134
|
+
cdp = await page.createCDPSession()
|
|
135
|
+
connections.set(page, cdp)
|
|
136
|
+
}
|
|
137
|
+
const { targetInfo } = await cdp.send('Target.getTargetInfo')
|
|
138
|
+
const attached = { page, cdp, targetId: targetInfo.targetId }
|
|
139
|
+
|
|
140
|
+
pages.set(attached.targetId, attached)
|
|
141
|
+
|
|
142
|
+
return attached
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const primary = yield* session
|
|
146
|
+
.run(authorize({ kind: 'connect' }, {}), attach)
|
|
147
|
+
.pipe(mapSessionFailure)
|
|
148
|
+
|
|
149
|
+
const context = primary.page.browserContext()
|
|
150
|
+
let calls = 0
|
|
151
|
+
|
|
152
|
+
const tab = async (attached: AttachedPage): Promise<typeof Tab.Type> => {
|
|
153
|
+
const { targetInfo } = await attached.cdp.send('Target.getTargetInfo')
|
|
154
|
+
|
|
155
|
+
return Schema.decodeSync(Tab)({
|
|
156
|
+
targetId: targetInfo.targetId,
|
|
157
|
+
url: targetInfo.url,
|
|
158
|
+
title: targetInfo.title,
|
|
159
|
+
})
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const run = Effect.fnUntraced(function*<A>(
|
|
163
|
+
command: Command,
|
|
164
|
+
action: (selected: AttachedPage, frame?: Frame) => Promise<A | BrowserUseError>,
|
|
165
|
+
targetId?: string,
|
|
166
|
+
frameId?: string,
|
|
167
|
+
) {
|
|
168
|
+
let selected = primary
|
|
169
|
+
let pageUrl = ''
|
|
170
|
+
let targetUrl = ''
|
|
171
|
+
let frame: Frame | undefined
|
|
172
|
+
let frameUrl: string | undefined
|
|
173
|
+
|
|
174
|
+
const result = yield* session
|
|
175
|
+
.run(
|
|
176
|
+
Effect.gen(function*() {
|
|
177
|
+
if (released) return yield* invalid('Browser attachment scope is closed')
|
|
178
|
+
if (limits.maxCommands !== null && calls++ >= limits.maxCommands) {
|
|
179
|
+
return yield* invalid('Browser command limit reached')
|
|
180
|
+
}
|
|
181
|
+
selected = targetId === undefined ? primary : (pages.get(targetId) ?? primary)
|
|
182
|
+
if (targetId !== undefined && !pages.has(targetId)) {
|
|
183
|
+
return yield* invalid('Unknown page; call cdp.tabs({}) to discover current targets')
|
|
184
|
+
}
|
|
185
|
+
if (selected.page.isClosed()) return yield* invalid('The selected page is closed')
|
|
186
|
+
pageUrl = primary.page.url()
|
|
187
|
+
targetUrl = selected.page.url()
|
|
188
|
+
frame = frameId === undefined
|
|
189
|
+
? undefined
|
|
190
|
+
: selected.page.frames().find((candidate) => candidate._id === frameId)
|
|
191
|
+
if (frameId !== undefined && frame === undefined) {
|
|
192
|
+
return yield* invalid('Unknown frame; call cdp.frames({}) again')
|
|
193
|
+
}
|
|
194
|
+
frameUrl = frame?.url()
|
|
195
|
+
yield* authorize(command, {
|
|
196
|
+
pageUrl,
|
|
197
|
+
targetId: selected.targetId,
|
|
198
|
+
targetUrl,
|
|
199
|
+
...(frameUrl === undefined ? {} : { frameUrl }),
|
|
200
|
+
})
|
|
201
|
+
}),
|
|
202
|
+
async () => {
|
|
203
|
+
if (
|
|
204
|
+
primary.page.url() !== pageUrl ||
|
|
205
|
+
selected.page.url() !== targetUrl ||
|
|
206
|
+
selected.page.isClosed() ||
|
|
207
|
+
(frame !== undefined && (frame.detached || frame.url() !== frameUrl))
|
|
208
|
+
) {
|
|
209
|
+
return {
|
|
210
|
+
ok: false as const,
|
|
211
|
+
error: invalid('Page changed during authorization; inspect it again'),
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return { ok: true as const, value: await action(selected, frame) }
|
|
216
|
+
},
|
|
217
|
+
)
|
|
218
|
+
.pipe(serial.withPermits(1), mapSessionFailure)
|
|
219
|
+
|
|
220
|
+
if (!result.ok) return yield* result.error
|
|
221
|
+
// Only host-created failures belong in E; a protocol response with similar fields is data.
|
|
222
|
+
if (isBrowserUseError(result.value)) return yield* result.value
|
|
223
|
+
|
|
224
|
+
const encoded = yield* Effect.try({
|
|
225
|
+
try: () => JSON.stringify(result.value),
|
|
226
|
+
catch: () =>
|
|
227
|
+
BrowserUseError.make({
|
|
228
|
+
code: 'browser',
|
|
229
|
+
message: 'Browser returned a non-JSON result',
|
|
230
|
+
dispatch: 'possibly-dispatched',
|
|
231
|
+
}),
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
if (
|
|
235
|
+
encoded === undefined ||
|
|
236
|
+
new TextEncoder().encode(encoded).byteLength > limits.maxReturnedBytes
|
|
237
|
+
) {
|
|
238
|
+
return yield* BrowserUseError.make({
|
|
239
|
+
code: 'browser',
|
|
240
|
+
message: 'Browser result exceeded its byte limit; request a smaller result without repeating mutations',
|
|
241
|
+
dispatch: 'possibly-dispatched',
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return result.value
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
const client: BrowserCdp['Service'] = {
|
|
249
|
+
send: Effect.fnUntraced(function*(request) {
|
|
250
|
+
const value = yield* decode(SendRequest, request)
|
|
251
|
+
|
|
252
|
+
if (
|
|
253
|
+
value.method.startsWith('Browser.') ||
|
|
254
|
+
value.method.startsWith('Target.') ||
|
|
255
|
+
value.method === 'Page.close' ||
|
|
256
|
+
value.method === 'Page.crash'
|
|
257
|
+
) {
|
|
258
|
+
return yield* invalid('Browser lifecycle commands belong to the host; use the tab helpers')
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const runReport = Effect.runPromiseWith(yield* Effect.context<never>())
|
|
262
|
+
|
|
263
|
+
const result: unknown = yield* run(
|
|
264
|
+
{ kind: 'send', request: value },
|
|
265
|
+
async ({ cdp, page }, frame): Promise<unknown> => {
|
|
266
|
+
let target = cdp
|
|
267
|
+
|
|
268
|
+
if (frame !== undefined) {
|
|
269
|
+
const source = frame.client
|
|
270
|
+
const originalUrl = primary.page.url()
|
|
271
|
+
const pageUrl = page.url()
|
|
272
|
+
const frameUrl = frame.url()
|
|
273
|
+
const existing = connections.get(source)
|
|
274
|
+
|
|
275
|
+
if (existing !== undefined) target = existing
|
|
276
|
+
else {
|
|
277
|
+
const connection = source.connection()
|
|
278
|
+
|
|
279
|
+
if (connection === undefined) return invalid('Frame connection is closed')
|
|
280
|
+
|
|
281
|
+
let lookup: Awaited<ReturnType<typeof source.send<'Target.getTargetInfo'>>>
|
|
282
|
+
|
|
283
|
+
try {
|
|
284
|
+
lookup = await source.send('Target.getTargetInfo')
|
|
285
|
+
} catch (cause) {
|
|
286
|
+
await runReport(
|
|
287
|
+
reportBrowserCause('browser-use.frame.target-info', Cause.fail(cause)),
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
return BrowserUseError.withCause(
|
|
291
|
+
BrowserUseError.make({
|
|
292
|
+
code: 'browser',
|
|
293
|
+
message: 'Frame inspection failed before the requested command was sent',
|
|
294
|
+
dispatch: 'not-dispatched',
|
|
295
|
+
}),
|
|
296
|
+
cause,
|
|
297
|
+
)
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Keep arbitrary commands off Puppeteer's own event-tracking session.
|
|
301
|
+
let attached: CDPSession
|
|
302
|
+
|
|
303
|
+
try {
|
|
304
|
+
attached = await connection.createSession(lookup.targetInfo)
|
|
305
|
+
} catch (cause) {
|
|
306
|
+
await runReport(reportBrowserCause('browser-use.frame.attach', Cause.fail(cause)))
|
|
307
|
+
|
|
308
|
+
return BrowserUseError.withCause(
|
|
309
|
+
BrowserUseError.make({
|
|
310
|
+
code: 'browser',
|
|
311
|
+
message: 'Frame attachment failed before the requested command was sent',
|
|
312
|
+
dispatch: 'not-dispatched',
|
|
313
|
+
}),
|
|
314
|
+
cause,
|
|
315
|
+
)
|
|
316
|
+
}
|
|
317
|
+
target = attached
|
|
318
|
+
connections.set(source, target)
|
|
319
|
+
}
|
|
320
|
+
if (
|
|
321
|
+
primary.page.url() !== originalUrl ||
|
|
322
|
+
page.url() !== pageUrl ||
|
|
323
|
+
frame.detached ||
|
|
324
|
+
frame.url() !== frameUrl ||
|
|
325
|
+
frame.client !== source
|
|
326
|
+
) {
|
|
327
|
+
return invalid('Frame changed during attachment; inspect it again')
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Bind the native receiver explicitly; decode the foreign response below.
|
|
332
|
+
try {
|
|
333
|
+
return await Reflect.apply(target.send.bind(target), undefined, [
|
|
334
|
+
value.method,
|
|
335
|
+
value.params,
|
|
336
|
+
])
|
|
337
|
+
} catch (cause) {
|
|
338
|
+
if (frame !== undefined) {
|
|
339
|
+
await runReport(reportBrowserCause('browser-use.frame.send', Cause.fail(cause)))
|
|
340
|
+
|
|
341
|
+
return BrowserUseError.withCause(
|
|
342
|
+
BrowserUseError.make({
|
|
343
|
+
code: 'browser',
|
|
344
|
+
message: 'Browser frame command failed; inspect the current state before further input',
|
|
345
|
+
dispatch: 'possibly-dispatched',
|
|
346
|
+
}),
|
|
347
|
+
cause,
|
|
348
|
+
)
|
|
349
|
+
}
|
|
350
|
+
// oxlint-disable-next-line effect/no-untyped-throw -- Preserve the native rejection for BrowserSession.run to retain and project.
|
|
351
|
+
throw cause
|
|
352
|
+
}
|
|
353
|
+
},
|
|
354
|
+
value.targetId,
|
|
355
|
+
value.frameId,
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
return yield* Schema.decodeUnknownEffect(Schema.Json)(result).pipe(
|
|
359
|
+
Effect.mapError(() =>
|
|
360
|
+
BrowserUseError.make({
|
|
361
|
+
code: 'browser',
|
|
362
|
+
message: 'Browser returned a non-JSON result',
|
|
363
|
+
dispatch: 'possibly-dispatched',
|
|
364
|
+
})
|
|
365
|
+
),
|
|
366
|
+
)
|
|
367
|
+
}),
|
|
368
|
+
tabs: Effect.gen(function*() {
|
|
369
|
+
const result = yield* run({ kind: 'tabs' }, async () => {
|
|
370
|
+
const current = await context.pages()
|
|
371
|
+
|
|
372
|
+
if (current.length > limits.maxTabs) return null
|
|
373
|
+
const result: Array<typeof Tab.Type> = []
|
|
374
|
+
|
|
375
|
+
for (const page of current) result.push(await tab(await attach(page)))
|
|
376
|
+
for (const [id, attached] of pages) {
|
|
377
|
+
if (attached.page.isClosed()) {
|
|
378
|
+
pages.delete(id)
|
|
379
|
+
connections.delete(attached.page)
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
return result
|
|
384
|
+
})
|
|
385
|
+
|
|
386
|
+
if (result === null) return yield* invalid('Browser tab limit exceeded')
|
|
387
|
+
|
|
388
|
+
return result
|
|
389
|
+
}),
|
|
390
|
+
frames: Effect.fnUntraced(function*(request) {
|
|
391
|
+
const value = yield* decode(FramesRequest, request)
|
|
392
|
+
|
|
393
|
+
const frames = yield* run(
|
|
394
|
+
{ kind: 'frames', request: value },
|
|
395
|
+
async ({ page }) =>
|
|
396
|
+
page.frames().map((frame) => ({
|
|
397
|
+
frameId: frame._id,
|
|
398
|
+
parentFrameId: frame.parentFrame()?._id ?? null,
|
|
399
|
+
url: frame.url(),
|
|
400
|
+
})),
|
|
401
|
+
value.targetId,
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
return yield* decode(Schema.Array(FrameInfo), frames)
|
|
405
|
+
}),
|
|
406
|
+
newTab: Effect.gen(function*() {
|
|
407
|
+
const result = yield* run({ kind: 'new-tab' }, async () => {
|
|
408
|
+
if ((await context.pages()).length >= limits.maxTabs) return null
|
|
409
|
+
|
|
410
|
+
return tab(await attach(await context.newPage()))
|
|
411
|
+
})
|
|
412
|
+
|
|
413
|
+
if (result === null) return yield* invalid('Browser tab limit reached')
|
|
414
|
+
|
|
415
|
+
return result
|
|
416
|
+
}),
|
|
417
|
+
closeTab: Effect.fnUntraced(function*(request) {
|
|
418
|
+
const value = yield* decode(CloseTabRequest, request)
|
|
419
|
+
|
|
420
|
+
if (value.targetId === primary.targetId) {
|
|
421
|
+
return yield* invalid('The original page belongs to the host')
|
|
422
|
+
}
|
|
423
|
+
yield* run(
|
|
424
|
+
{ kind: 'close-tab', request: value },
|
|
425
|
+
async ({ page }) => {
|
|
426
|
+
await page.close()
|
|
427
|
+
pages.delete(value.targetId)
|
|
428
|
+
connections.delete(page)
|
|
429
|
+
|
|
430
|
+
return null
|
|
431
|
+
},
|
|
432
|
+
value.targetId,
|
|
433
|
+
)
|
|
434
|
+
}),
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
return { client, layer: Layer.succeed(BrowserCdp, client) }
|
|
438
|
+
})
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import * as Context from 'effect/Context'
|
|
2
|
+
import * as Effect from 'effect/Effect'
|
|
3
|
+
import * as FetchHttpClient from 'effect/http/FetchHttpClient'
|
|
4
|
+
import * as Headers from 'effect/http/Headers'
|
|
5
|
+
import * as HttpClient from 'effect/http/HttpClient'
|
|
6
|
+
import * as HttpClientError from 'effect/http/HttpClientError'
|
|
7
|
+
import * as HttpClientRequest from 'effect/http/HttpClientRequest'
|
|
8
|
+
import * as Layer from 'effect/Layer'
|
|
9
|
+
import * as Option from 'effect/Option'
|
|
10
|
+
import * as Redactable from 'effect/Redactable'
|
|
11
|
+
import * as Redacted from 'effect/Redacted'
|
|
12
|
+
import * as Schema from 'effect/Schema'
|
|
13
|
+
|
|
14
|
+
const Segment = Schema.NonEmptyString.check(
|
|
15
|
+
Schema.isMaxLength(256),
|
|
16
|
+
Schema.isPattern(/^[a-zA-Z0-9_-]+$/),
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
const decodeSegment = Schema.decodeUnknownSync(Segment)
|
|
20
|
+
|
|
21
|
+
/** Options understood by upstream Effect AI clients; no model or provider wrapper is created. */
|
|
22
|
+
export interface ClientOptions {
|
|
23
|
+
readonly apiUrl: string
|
|
24
|
+
readonly transformClient: (client: HttpClient.HttpClient) => HttpClient.HttpClient
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ProviderOptions {
|
|
28
|
+
readonly accountId: string
|
|
29
|
+
readonly gatewayId: string
|
|
30
|
+
/** Cloudflare's provider path, such as openai, anthropic, google-ai-studio, or perplexity-ai. */
|
|
31
|
+
readonly provider: string
|
|
32
|
+
/** Omit only for an unauthenticated gateway with a separately supplied provider key. */
|
|
33
|
+
readonly apiToken?: Redacted.Redacted<string>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface RestOptions {
|
|
37
|
+
readonly accountId: string
|
|
38
|
+
readonly gatewayId: string
|
|
39
|
+
/** Cloudflare API token with Workers AI Read permission. */
|
|
40
|
+
readonly apiToken: Redacted.Redacted<string>
|
|
41
|
+
/** Matches the paths appended by the upstream Effect client. */
|
|
42
|
+
readonly protocol: 'responses' | 'chat-completions' | 'messages'
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Choose exactly one route: a native provider path or an account REST protocol. */
|
|
46
|
+
export type RouteOptions =
|
|
47
|
+
| (ProviderOptions & { readonly protocol?: never })
|
|
48
|
+
| (RestOptions & { readonly provider?: never })
|
|
49
|
+
|
|
50
|
+
const redactGatewayToken = (headers: Headers.Headers, tokenHeader: string): void => {
|
|
51
|
+
// HTTP tracing can copy headers after preprocessing. Attach the public redaction
|
|
52
|
+
// protocol to the final request as well, before a provider builds error details.
|
|
53
|
+
Object.defineProperty(headers, Redactable.symbolRedactable, {
|
|
54
|
+
configurable: true,
|
|
55
|
+
value: (context: Context.Context<never>) =>
|
|
56
|
+
Headers.redact(headers, [...Context.get(context, Headers.CurrentRedactedNames), tokenHeader]),
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const clientOptions = (
|
|
61
|
+
apiUrl: string,
|
|
62
|
+
tokenHeader: 'authorization' | 'cf-aig-authorization',
|
|
63
|
+
apiToken: Redacted.Redacted<string> | undefined,
|
|
64
|
+
gatewayId?: string,
|
|
65
|
+
): ClientOptions =>
|
|
66
|
+
Object.freeze({
|
|
67
|
+
apiUrl,
|
|
68
|
+
transformClient: (client: HttpClient.HttpClient) =>
|
|
69
|
+
client.pipe(
|
|
70
|
+
HttpClient.mapRequestEffect((request) => {
|
|
71
|
+
const url = URL.parse(request.url)
|
|
72
|
+
|
|
73
|
+
// Check the normalized URL too: dot segments must not escape this account or gateway.
|
|
74
|
+
if (
|
|
75
|
+
url === null ||
|
|
76
|
+
url.username !== '' ||
|
|
77
|
+
url.password !== '' ||
|
|
78
|
+
!(url.href === apiUrl || url.href.startsWith(`${apiUrl}/`))
|
|
79
|
+
) {
|
|
80
|
+
return Effect.fail(
|
|
81
|
+
new HttpClientError.HttpClientError({
|
|
82
|
+
reason: new HttpClientError.InvalidUrlError({
|
|
83
|
+
request,
|
|
84
|
+
description: 'Request is outside the configured Cloudflare AI Gateway endpoint',
|
|
85
|
+
}),
|
|
86
|
+
}),
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
let prepared = request
|
|
90
|
+
|
|
91
|
+
if (apiToken !== undefined) {
|
|
92
|
+
prepared = HttpClientRequest.setHeader(
|
|
93
|
+
prepared,
|
|
94
|
+
tokenHeader,
|
|
95
|
+
`Bearer ${Redacted.value(apiToken)}`,
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
if (gatewayId !== undefined) {
|
|
99
|
+
prepared = HttpClientRequest.setHeader(prepared, 'cf-aig-gateway-id', gatewayId)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return Effect.succeed(prepared)
|
|
103
|
+
}),
|
|
104
|
+
HttpClient.transformResponse((effect) =>
|
|
105
|
+
Effect.gen(function*() {
|
|
106
|
+
const defaults = yield* Effect.serviceOption(FetchHttpClient.RequestInit)
|
|
107
|
+
|
|
108
|
+
return yield* effect.pipe(
|
|
109
|
+
Effect.provideService(FetchHttpClient.RequestInit, {
|
|
110
|
+
...Option.getOrElse(defaults, () => ({})),
|
|
111
|
+
redirect: 'error',
|
|
112
|
+
}),
|
|
113
|
+
)
|
|
114
|
+
})
|
|
115
|
+
),
|
|
116
|
+
HttpClient.transformResponse((effect) =>
|
|
117
|
+
effect.pipe(
|
|
118
|
+
Effect.tap((response) => Effect.sync(() => redactGatewayToken(response.request.headers, tokenHeader))),
|
|
119
|
+
Effect.tapError((error) =>
|
|
120
|
+
Effect.sync(() => redactGatewayToken(error.reason.request.headers, tokenHeader))
|
|
121
|
+
),
|
|
122
|
+
Effect.updateService(Headers.CurrentRedactedNames, (names) => [...names, tokenHeader]),
|
|
123
|
+
)
|
|
124
|
+
),
|
|
125
|
+
),
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Provider-native proxy for model calls, streaming, embeddings, and hosted tools supported
|
|
130
|
+
* by that provider. Pass the result to the upstream client's layer along with its apiKey
|
|
131
|
+
* for BYOK-in-request, or omit apiKey for Gateway stored keys / Unified Billing.
|
|
132
|
+
* Provider model names and request bodies pass through unchanged. This module is Node-safe.
|
|
133
|
+
* Custom transforms and redirect policies must retain this endpoint and credential boundary.
|
|
134
|
+
*/
|
|
135
|
+
export const provider = (options: ProviderOptions): ClientOptions =>
|
|
136
|
+
clientOptions(
|
|
137
|
+
`https://gateway.ai.cloudflare.com/v1/${decodeSegment(options.accountId)}/${decodeSegment(options.gatewayId)}/${
|
|
138
|
+
decodeSegment(options.provider)
|
|
139
|
+
}`,
|
|
140
|
+
'cf-aig-authorization',
|
|
141
|
+
options.apiToken,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Cloudflare's account REST API (not the deprecated /compat API). Use provider-qualified
|
|
146
|
+
* model names, e.g. openai/gpt-6-sol or anthropic/claude-haiku-4.5, and omit provider apiKey.
|
|
147
|
+
* OpenAI clients append /responses or /chat/completions; Anthropic appends /v1/messages.
|
|
148
|
+
* Compatibility remains the responsibility of the selected upstream client and model.
|
|
149
|
+
*/
|
|
150
|
+
export const rest = (options: RestOptions): ClientOptions =>
|
|
151
|
+
clientOptions(
|
|
152
|
+
`https://api.cloudflare.com/client/v4/accounts/${decodeSegment(options.accountId)}/ai${
|
|
153
|
+
options.protocol === 'messages' ? '' : '/v1'
|
|
154
|
+
}`,
|
|
155
|
+
'authorization',
|
|
156
|
+
options.apiToken,
|
|
157
|
+
decodeSegment(options.gatewayId),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Provide a Gateway-configured upstream client directly in a Layer pipeline.
|
|
162
|
+
* Pass the client's `layer` factory, or a callback adding client-specific options.
|
|
163
|
+
* The factory's errors and remaining services (such as HttpClient) stay visible.
|
|
164
|
+
* Model selection and resource ownership remain with the supplied upstream Layers.
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```ts
|
|
168
|
+
* AnthropicLanguageModel.model("claude-haiku-4-5").pipe(
|
|
169
|
+
* Gateway.provide(AnthropicClient.layer, { ...options, provider: "anthropic" }),
|
|
170
|
+
* )
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
173
|
+
export const provide = <Client, E, R>(
|
|
174
|
+
clientLayer: (options: ClientOptions) => Layer.Layer<Client, E, R>,
|
|
175
|
+
options: RouteOptions,
|
|
176
|
+
) => Layer.provide(clientLayer(options.provider !== undefined ? provider(options) : rest(options)))
|