@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,993 @@
|
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
|
|
3
|
+
import * as FailureDiagnostic from '@systemfsoftware/agent/failure-diagnostic'
|
|
4
|
+
import * as Cause from 'effect/Cause'
|
|
5
|
+
import * as Clock from 'effect/Clock'
|
|
6
|
+
import * as Context from 'effect/Context'
|
|
7
|
+
import type * as Duration from 'effect/Duration'
|
|
8
|
+
import * as Effect from 'effect/Effect'
|
|
9
|
+
import * as Exit from 'effect/Exit'
|
|
10
|
+
import * as Fiber from 'effect/Fiber'
|
|
11
|
+
import * as Layer from 'effect/Layer'
|
|
12
|
+
import * as Redacted from 'effect/Redacted'
|
|
13
|
+
import * as Schema from 'effect/Schema'
|
|
14
|
+
import * as Scope from 'effect/Scope'
|
|
15
|
+
import * as Semaphore from 'effect/Semaphore'
|
|
16
|
+
import type { Browser, CDPSession, Page } from 'puppeteer-core/lib/esm/puppeteer/puppeteer-core-browser.js'
|
|
17
|
+
|
|
18
|
+
import {
|
|
19
|
+
type BrowserCredentialAccess,
|
|
20
|
+
type CredentialBinding,
|
|
21
|
+
CredentialFillError,
|
|
22
|
+
type CredentialFillResult,
|
|
23
|
+
type CredentialForm,
|
|
24
|
+
type FillCredentialRequest,
|
|
25
|
+
} from './BrowserCredentials'
|
|
26
|
+
import {
|
|
27
|
+
BrowserRunHandoffRequest,
|
|
28
|
+
BrowserRunHandoffResult,
|
|
29
|
+
BrowserRunHandoffState,
|
|
30
|
+
BrowserRunLiveViewRequest,
|
|
31
|
+
BrowserRunLiveViewResult,
|
|
32
|
+
} from './InteractiveBrowser'
|
|
33
|
+
import { type BrowserRunAttachment, BrowserRunBinding, BrowserRunRefusal } from './internal/browser-binding'
|
|
34
|
+
import { BrowserSessionPage, fillCredential, prepareCredential } from './internal/browser-credentials'
|
|
35
|
+
import {
|
|
36
|
+
BrowserRunFailure,
|
|
37
|
+
inheritBrowserReport,
|
|
38
|
+
mapBrowserError,
|
|
39
|
+
reportBrowserCause,
|
|
40
|
+
reportedBrowserError,
|
|
41
|
+
} from './internal/browser-failure'
|
|
42
|
+
import { BrowserRunReadonlyLiveView } from './internal/browser-readonly-live-view'
|
|
43
|
+
import { type BrowserRunLifecycleOptions, BrowserRunSessionLifecycle } from './internal/browser-session-lifecycle'
|
|
44
|
+
|
|
45
|
+
export {
|
|
46
|
+
BrowserRunHandoffRequest,
|
|
47
|
+
BrowserRunHandoffResult,
|
|
48
|
+
BrowserRunHandoffState,
|
|
49
|
+
BrowserRunLiveViewRequest,
|
|
50
|
+
BrowserRunLiveViewResult,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const PositiveMillis = Schema.Int.check(
|
|
54
|
+
Schema.isGreaterThan(0),
|
|
55
|
+
Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
const SessionId = Schema.Redacted(Schema.String.check(Schema.isUUID()))
|
|
59
|
+
const ProviderId = Schema.Redacted(Schema.NonEmptyString.check(Schema.isMaxLength(256)))
|
|
60
|
+
|
|
61
|
+
/** Private host record, not a model capability. Persist together with the owner's controller state. */
|
|
62
|
+
export class BrowserSessionReference extends Schema.Class<BrowserSessionReference>(
|
|
63
|
+
'BrowserSessionReference',
|
|
64
|
+
)({
|
|
65
|
+
version: Schema.Literal(1),
|
|
66
|
+
sessionId: SessionId,
|
|
67
|
+
contextId: ProviderId,
|
|
68
|
+
targetId: ProviderId,
|
|
69
|
+
expiresAt: PositiveMillis,
|
|
70
|
+
commandTimeoutMillis: PositiveMillis,
|
|
71
|
+
}) {}
|
|
72
|
+
|
|
73
|
+
export class BrowserSessionOptions extends Schema.Class<BrowserSessionOptions>(
|
|
74
|
+
'BrowserSessionOptions',
|
|
75
|
+
)({
|
|
76
|
+
maxElapsedMillis: PositiveMillis,
|
|
77
|
+
keepAliveMillis: Schema.optionalKey(PositiveMillis.check(Schema.isLessThanOrEqualTo(600_000))),
|
|
78
|
+
commandTimeoutMillis: Schema.optionalKey(PositiveMillis),
|
|
79
|
+
}) {}
|
|
80
|
+
|
|
81
|
+
/** No SDK text, selectors, page data, or credential values are retained in public failures. */
|
|
82
|
+
export class BrowserSessionError extends Schema.TaggedError<BrowserSessionError>()(
|
|
83
|
+
'BrowserSessionError',
|
|
84
|
+
{
|
|
85
|
+
reason: Schema.Literals([
|
|
86
|
+
'invalid',
|
|
87
|
+
'expired',
|
|
88
|
+
'missing-page',
|
|
89
|
+
'busy',
|
|
90
|
+
'closed',
|
|
91
|
+
'provider',
|
|
92
|
+
'timeout',
|
|
93
|
+
'cleanup',
|
|
94
|
+
]),
|
|
95
|
+
dispatch: Schema.Literals(['not-dispatched', 'possibly-dispatched']),
|
|
96
|
+
cleanup: Schema.Literals(['not-requested', 'confirmed', 'unconfirmed']),
|
|
97
|
+
},
|
|
98
|
+
) {
|
|
99
|
+
/** Original host-only cause. Excluded from the error Schema and JSON transport. */
|
|
100
|
+
declare readonly cause?: unknown
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* One local attachment to an application-owned browser. Scope release disconnects; it never
|
|
105
|
+
* transfers ownership or closes a healthy remote session. The owner serializes attachments,
|
|
106
|
+
* fences old attempts, authorizes human access, and calls BrowserSessions.close on expiry/stop.
|
|
107
|
+
* Native callbacks are trusted host code: never start unawaited work. Adapters retaining SDK
|
|
108
|
+
* handles must scope their release and use run for every operation on the retained page.
|
|
109
|
+
*/
|
|
110
|
+
export interface BrowserSession {
|
|
111
|
+
readonly reference: BrowserSessionReference
|
|
112
|
+
/**
|
|
113
|
+
* Check current authority under the lock before native dispatch. A settled SDK rejection leaves
|
|
114
|
+
* the session available for inspection, but may have changed the website; never retry blindly.
|
|
115
|
+
* Timeout/interruption fences outstanding SDK work and terminates the exact browser.
|
|
116
|
+
* An optional timeoutMillis narrows the command deadline, for example for bounded preparation.
|
|
117
|
+
*/
|
|
118
|
+
readonly run: <A, E, R>(
|
|
119
|
+
authorize: Effect.Effect<void, E, R>,
|
|
120
|
+
action: (page: Page) => Promise<A>,
|
|
121
|
+
options?: { readonly timeoutMillis: number },
|
|
122
|
+
) => Effect.Effect<A, E | BrowserSessionError, R>
|
|
123
|
+
/**
|
|
124
|
+
* Prepare a delayed private-entry request within the command/session deadline; timeout closes
|
|
125
|
+
* the browser. The host owns persistence, expiry and one-use consumption.
|
|
126
|
+
*/
|
|
127
|
+
readonly prepareCredential: (
|
|
128
|
+
request: CredentialForm,
|
|
129
|
+
) => Effect.Effect<CredentialBinding, CredentialFillError | BrowserSessionError>
|
|
130
|
+
/**
|
|
131
|
+
* Resolves host-owned material under fresh credential grants. Never submits or retries a write.
|
|
132
|
+
* Credential timeouts retain acknowledged writes and dispatch evidence alongside cleanup.
|
|
133
|
+
*/
|
|
134
|
+
readonly fillCredential: (
|
|
135
|
+
request: FillCredentialRequest,
|
|
136
|
+
) => Effect.Effect<
|
|
137
|
+
CredentialFillResult,
|
|
138
|
+
CredentialFillError | BrowserSessionError,
|
|
139
|
+
BrowserCredentialAccess
|
|
140
|
+
>
|
|
141
|
+
readonly handoff: <E, R>(
|
|
142
|
+
authorize: Effect.Effect<void, E, R>,
|
|
143
|
+
request: BrowserRunHandoffRequest,
|
|
144
|
+
) => Effect.Effect<BrowserRunHandoffResult, E | BrowserSessionError, R>
|
|
145
|
+
readonly getLiveView: <E, R>(
|
|
146
|
+
authorize: Effect.Effect<void, E, R>,
|
|
147
|
+
request: BrowserRunLiveViewRequest,
|
|
148
|
+
) => Effect.Effect<BrowserRunLiveViewResult, E | BrowserSessionError, R>
|
|
149
|
+
/**
|
|
150
|
+
* Mint a provider-enforced read-only connection to this exact page. Requires REST credentials;
|
|
151
|
+
* missing read-only confirmation fails closed, never falling back to an interactive URL.
|
|
152
|
+
* Expiry limits new connections, not established connections or access to visible page data.
|
|
153
|
+
*/
|
|
154
|
+
readonly getReadOnlyLiveView: <E, R>(
|
|
155
|
+
authorize: Effect.Effect<void, E, R>,
|
|
156
|
+
request: BrowserRunLiveViewRequest,
|
|
157
|
+
) => Effect.Effect<BrowserRunLiveViewResult, E | BrowserSessionError, R>
|
|
158
|
+
readonly getHandoffState: <E, R>(
|
|
159
|
+
authorize: Effect.Effect<void, E, R>,
|
|
160
|
+
) => Effect.Effect<BrowserRunHandoffState, E | BrowserSessionError, R>
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const failure = (
|
|
164
|
+
reason: BrowserSessionError['reason'],
|
|
165
|
+
dispatch: BrowserSessionError['dispatch'] = 'not-dispatched',
|
|
166
|
+
cleanup: BrowserSessionError['cleanup'] = 'not-requested',
|
|
167
|
+
cause?: unknown,
|
|
168
|
+
) => {
|
|
169
|
+
const error = BrowserSessionError.make({ reason, dispatch, cleanup })
|
|
170
|
+
|
|
171
|
+
return cause === undefined ? error : FailureDiagnostic.withCause(error, cause)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Effect promotes typed failures to defects when a cleanup defect joins them.
|
|
175
|
+
// Preserve that fatal classification while retaining the session's cleanup evidence.
|
|
176
|
+
const annotateSessionCleanup = <E>(
|
|
177
|
+
error: E,
|
|
178
|
+
cleanup: BrowserSessionError['cleanup'],
|
|
179
|
+
): E | BrowserSessionError =>
|
|
180
|
+
Schema.is(BrowserSessionError)(error) &&
|
|
181
|
+
Object.prototype.isPrototypeOf.call(BrowserSessionError.prototype, error)
|
|
182
|
+
? inheritBrowserReport(
|
|
183
|
+
error,
|
|
184
|
+
FailureDiagnostic.withCause(BrowserSessionError.make({ ...error, cleanup }), error),
|
|
185
|
+
)
|
|
186
|
+
: error
|
|
187
|
+
|
|
188
|
+
const decode = <A>(schema: Schema.Codec<A>, input: unknown) =>
|
|
189
|
+
Schema.decodeUnknownEffect(schema, { onExcessProperty: 'error' })(input).pipe(
|
|
190
|
+
mapBrowserError((error) => failure('invalid', 'not-dispatched', 'not-requested', error)),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
/** Scope finalizers require E=never. Preserve pure cancellation and wrap every other cause privately. */
|
|
194
|
+
const cleanupFinalizer = <A, R>(effect: Effect.Effect<A, BrowserSessionError, R>) =>
|
|
195
|
+
effect.pipe(
|
|
196
|
+
Effect.asVoid,
|
|
197
|
+
Effect.catchCause((cause) =>
|
|
198
|
+
Cause.hasInterruptsOnly(cause)
|
|
199
|
+
? Effect.failCause(Cause.fromReasons<never>(cause.reasons.filter(Cause.isInterruptReason)))
|
|
200
|
+
: Effect.die(failure('cleanup', 'not-dispatched', 'unconfirmed', cause))
|
|
201
|
+
),
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
/** A deadline owns its work until stopped; cleanup failures join the timeout outcome. */
|
|
205
|
+
const timeout = <B, E2, R2>(options: {
|
|
206
|
+
readonly duration: Duration.Input
|
|
207
|
+
readonly orElse: () => Effect.Effect<B, E2, R2>
|
|
208
|
+
}) =>
|
|
209
|
+
<A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A | B, E | E2, R | R2> =>
|
|
210
|
+
Effect.suspend(() => {
|
|
211
|
+
let consumed = false
|
|
212
|
+
|
|
213
|
+
const stop = (fiber: Fiber.Fiber<A, E>) =>
|
|
214
|
+
Effect.uninterruptible(
|
|
215
|
+
Effect.gen(function*() {
|
|
216
|
+
if (consumed) return
|
|
217
|
+
yield* Fiber.interrupt(fiber)
|
|
218
|
+
const exit = yield* Fiber.await(fiber)
|
|
219
|
+
|
|
220
|
+
consumed = true
|
|
221
|
+
if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {
|
|
222
|
+
return yield* Effect.failCause(exit.cause)
|
|
223
|
+
}
|
|
224
|
+
}),
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
return Effect.uninterruptibleMask((restore) =>
|
|
228
|
+
Effect.acquireUseRelease(
|
|
229
|
+
Effect.gen(function*() {
|
|
230
|
+
// Own the fiber separately without replacing the operation's resource Scope.
|
|
231
|
+
const scope = yield* Scope.make()
|
|
232
|
+
const fiber = yield* Effect.forkIn(self.pipe(Effect.interruptible), scope)
|
|
233
|
+
|
|
234
|
+
return { scope, fiber }
|
|
235
|
+
}),
|
|
236
|
+
({ fiber }) =>
|
|
237
|
+
restore(
|
|
238
|
+
Fiber.await(fiber).pipe(
|
|
239
|
+
Effect.timeoutOrElse({
|
|
240
|
+
duration: options.duration,
|
|
241
|
+
orElse: () => Effect.as(Effect.void, undefined),
|
|
242
|
+
}),
|
|
243
|
+
),
|
|
244
|
+
).pipe(
|
|
245
|
+
Effect.flatMap((exit): Effect.Effect<A | B, E | E2, R2> => {
|
|
246
|
+
if (exit !== undefined) {
|
|
247
|
+
consumed = true
|
|
248
|
+
|
|
249
|
+
return exit
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return Effect.uninterruptible(
|
|
253
|
+
Effect.exit(stop(fiber)).pipe(
|
|
254
|
+
Effect.flatMap((stopped) =>
|
|
255
|
+
options
|
|
256
|
+
.orElse()
|
|
257
|
+
.pipe(
|
|
258
|
+
Effect.onExit(() => Exit.isFailure(stopped) ? Effect.failCause(stopped.cause) : Effect.void),
|
|
259
|
+
)
|
|
260
|
+
),
|
|
261
|
+
),
|
|
262
|
+
)
|
|
263
|
+
}),
|
|
264
|
+
),
|
|
265
|
+
({ scope, fiber }) => stop(fiber).pipe(Effect.onExit((exit) => Scope.close(scope, exit))),
|
|
266
|
+
)
|
|
267
|
+
)
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
// Catch inside the Promise before workerd can report an unhandled foreign diagnostic.
|
|
271
|
+
const native = Effect.fnUntraced(function*<A>(
|
|
272
|
+
operation: string,
|
|
273
|
+
action: (signal: AbortSignal) => Promise<A>,
|
|
274
|
+
) {
|
|
275
|
+
const runReport = Effect.runPromiseWith(yield* Effect.context<never>())
|
|
276
|
+
|
|
277
|
+
return yield* Effect.tryPromise({
|
|
278
|
+
try: async (signal) => {
|
|
279
|
+
try {
|
|
280
|
+
return { ok: true as const, value: await action(signal) }
|
|
281
|
+
} catch (cause) {
|
|
282
|
+
if (!signal.aborted || cause !== signal.reason) {
|
|
283
|
+
await runReport(reportBrowserCause(operation, Cause.fail(cause)))
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return { ok: false as const, cause }
|
|
287
|
+
}
|
|
288
|
+
},
|
|
289
|
+
catch: (cause) => failure('provider', 'not-dispatched', 'not-requested', cause),
|
|
290
|
+
}).pipe(
|
|
291
|
+
Effect.flatMap((result) =>
|
|
292
|
+
result.ok
|
|
293
|
+
? Effect.succeed(result.value)
|
|
294
|
+
: Effect.fail(
|
|
295
|
+
reportedBrowserError(
|
|
296
|
+
failure('provider', 'not-dispatched', 'not-requested', result.cause),
|
|
297
|
+
),
|
|
298
|
+
)
|
|
299
|
+
),
|
|
300
|
+
Effect.withTracerEnabled(false),
|
|
301
|
+
)
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
const withCdp = Effect.fnUntraced(function*<A, E, R>(
|
|
305
|
+
page: Page,
|
|
306
|
+
commandTimeoutMillis: number,
|
|
307
|
+
action: (cdp: CDPSession) => Effect.Effect<A, E, R>,
|
|
308
|
+
) {
|
|
309
|
+
const runCleanup = Effect.runPromiseWith(yield* Effect.context<never>())
|
|
310
|
+
let acquired: CDPSession | undefined
|
|
311
|
+
let released = false
|
|
312
|
+
|
|
313
|
+
const release = Effect.uninterruptible(
|
|
314
|
+
Effect.suspend(() => {
|
|
315
|
+
if (acquired === undefined || released) return Effect.void
|
|
316
|
+
released = true
|
|
317
|
+
const cdp = acquired
|
|
318
|
+
|
|
319
|
+
return native('session.cdp.detach', () => cdp.detach()).pipe(
|
|
320
|
+
timeout({
|
|
321
|
+
duration: commandTimeoutMillis,
|
|
322
|
+
orElse: () => Effect.fail(failure('cleanup', 'not-dispatched', 'unconfirmed', failure('timeout'))),
|
|
323
|
+
}),
|
|
324
|
+
)
|
|
325
|
+
}),
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
return yield* Effect.uninterruptibleMask((restore) =>
|
|
329
|
+
Effect.acquireUseRelease(
|
|
330
|
+
restore(
|
|
331
|
+
native('session.cdp.attach', async (signal) => {
|
|
332
|
+
const cdp = await page.createCDPSession()
|
|
333
|
+
|
|
334
|
+
acquired = cdp
|
|
335
|
+
|
|
336
|
+
// The SDK cannot cancel attachment; dispose a handle that arrives after cancellation.
|
|
337
|
+
if (signal.aborted) {
|
|
338
|
+
await runCleanup(release)
|
|
339
|
+
signal.throwIfAborted()
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
return cdp
|
|
343
|
+
}),
|
|
344
|
+
),
|
|
345
|
+
(cdp) => restore(action(cdp)),
|
|
346
|
+
() => release,
|
|
347
|
+
).pipe(
|
|
348
|
+
// Cover cancellation after the Promise resolves but before acquisition resumes.
|
|
349
|
+
Effect.onExit(() => release),
|
|
350
|
+
)
|
|
351
|
+
)
|
|
352
|
+
})
|
|
353
|
+
|
|
354
|
+
const targetId = (page: Page, commandTimeoutMillis: number) =>
|
|
355
|
+
withCdp(page, commandTimeoutMillis, (cdp) =>
|
|
356
|
+
native(
|
|
357
|
+
'session.target',
|
|
358
|
+
async () => (await cdp.send('Target.getTargetInfo')).targetInfo.targetId,
|
|
359
|
+
))
|
|
360
|
+
|
|
361
|
+
export interface BrowserSessionsOptions extends BrowserRunLifecycleOptions {
|
|
362
|
+
readonly browser: Pick<BrowserRun, 'fetch'>
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Native Cloudflare sessions; no framework browser workflow, checkpoint transfer, or observation policy. */
|
|
366
|
+
export class BrowserSessions extends Context.Service<
|
|
367
|
+
BrowserSessions,
|
|
368
|
+
{
|
|
369
|
+
/**
|
|
370
|
+
* Allocate once and commit its private reference in retain. Failed/uncommitted creation closes
|
|
371
|
+
* the allocation. After retain succeeds the application owns remote cleanup, independent of
|
|
372
|
+
* attempt Scopes. A lost allocation reply can remain indeterminate until provider idle expiry.
|
|
373
|
+
*/
|
|
374
|
+
readonly create: <E, R>(
|
|
375
|
+
options: BrowserSessionOptions,
|
|
376
|
+
retain: (reference: BrowserSessionReference) => Effect.Effect<void, E, R>,
|
|
377
|
+
) => Effect.Effect<BrowserSessionReference, E | BrowserSessionError, R>
|
|
378
|
+
/**
|
|
379
|
+
* Allocate and retain as create does, keeping the initial attachment in the caller's Scope.
|
|
380
|
+
* No session is exposed before retain succeeds. Failed acquisition releases its attachment
|
|
381
|
+
* immediately; after retention the application owns remote cleanup. The 30-second acquisition
|
|
382
|
+
* timeout ends before use; each command retains its own timeout and the fixed session expiry.
|
|
383
|
+
* Failed acquisition reports confirmed cleanup only after exact-session termination succeeds.
|
|
384
|
+
*/
|
|
385
|
+
readonly createAttached: <E, R>(
|
|
386
|
+
options: BrowserSessionOptions,
|
|
387
|
+
retain: (reference: BrowserSessionReference) => Effect.Effect<void, E, R>,
|
|
388
|
+
) => Effect.Effect<BrowserSession, E | BrowserSessionError, R | Scope.Scope>
|
|
389
|
+
/** Attach only the exact saved context/page. Never recreate missing/expired state. */
|
|
390
|
+
readonly attach: (
|
|
391
|
+
reference: BrowserSessionReference,
|
|
392
|
+
) => Effect.Effect<BrowserSession, BrowserSessionError, Scope.Scope>
|
|
393
|
+
/** Refresh provider inactivity only; the owner must still enforce its expiresAt. */
|
|
394
|
+
readonly keepAlive: (
|
|
395
|
+
sessionId: Redacted.Redacted<string>,
|
|
396
|
+
) => Effect.Effect<void, BrowserSessionError>
|
|
397
|
+
readonly close: (
|
|
398
|
+
sessionId: Redacted.Redacted<string>,
|
|
399
|
+
) => Effect.Effect<void, BrowserSessionError>
|
|
400
|
+
}
|
|
401
|
+
>()('@effect-agent/platform-cloudflare/BrowserSessions') {
|
|
402
|
+
static readonly layerNoDeps = Layer.effect(
|
|
403
|
+
this,
|
|
404
|
+
Effect.gen(function*() {
|
|
405
|
+
const binding = yield* BrowserRunBinding
|
|
406
|
+
const lifecycle = yield* BrowserRunSessionLifecycle
|
|
407
|
+
const readonlyLiveView = yield* BrowserRunReadonlyLiveView
|
|
408
|
+
|
|
409
|
+
const close = (sessionId: Redacted.Redacted<string>) =>
|
|
410
|
+
decode(SessionId, sessionId).pipe(
|
|
411
|
+
Effect.flatMap((id) =>
|
|
412
|
+
lifecycle
|
|
413
|
+
.close(id)
|
|
414
|
+
.pipe(
|
|
415
|
+
mapBrowserError((error) => failure('cleanup', 'not-dispatched', 'unconfirmed', error)),
|
|
416
|
+
)
|
|
417
|
+
),
|
|
418
|
+
)
|
|
419
|
+
|
|
420
|
+
const cleanup = (sessionId: Redacted.Redacted<string>) =>
|
|
421
|
+
close(sessionId).pipe(
|
|
422
|
+
Effect.as('confirmed' as const),
|
|
423
|
+
Effect.tapCause((cause) => reportBrowserCause('session.close', cause)),
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
const connect = Effect.fnUntraced(function*(sessionId: Redacted.Redacted<string>) {
|
|
427
|
+
let attachment: BrowserRunAttachment | undefined
|
|
428
|
+
|
|
429
|
+
const retire = Effect.suspend(() =>
|
|
430
|
+
attachment === undefined
|
|
431
|
+
? Effect.void
|
|
432
|
+
: attachment.retire.pipe(
|
|
433
|
+
// Dispatch is already fenced; give the socket close handshake the same
|
|
434
|
+
// bounded window as keepalive instead of failing a settled command after 1s.
|
|
435
|
+
timeout({
|
|
436
|
+
duration: '10 seconds',
|
|
437
|
+
orElse: () => Effect.fail(failure('cleanup')),
|
|
438
|
+
}),
|
|
439
|
+
Effect.tapCause((cause) => reportBrowserCause('session.disconnect', cause)),
|
|
440
|
+
mapBrowserError((error) => failure('cleanup', 'not-dispatched', 'unconfirmed', error)),
|
|
441
|
+
)
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
yield* Effect.addFinalizer(() => cleanupFinalizer(retire))
|
|
445
|
+
|
|
446
|
+
const browser = yield* native('session.connect', (signal) => {
|
|
447
|
+
attachment = binding.connect(Redacted.value(sessionId), 'session.connect', signal)
|
|
448
|
+
|
|
449
|
+
return attachment.browser
|
|
450
|
+
})
|
|
451
|
+
|
|
452
|
+
return { browser, retire }
|
|
453
|
+
})
|
|
454
|
+
|
|
455
|
+
const allocate = Effect.fnUntraced(function*<E, R>(
|
|
456
|
+
input: BrowserSessionOptions,
|
|
457
|
+
retain: (reference: BrowserSessionReference) => Effect.Effect<void, E, R>,
|
|
458
|
+
cleanupState: { result: BrowserSessionError['cleanup'] },
|
|
459
|
+
) {
|
|
460
|
+
const options = yield* decode(BrowserSessionOptions, input)
|
|
461
|
+
const expiresAt = (yield* Clock.currentTimeMillis) + options.maxElapsedMillis
|
|
462
|
+
|
|
463
|
+
if (!Number.isSafeInteger(expiresAt)) return yield* failure('invalid')
|
|
464
|
+
let sessionId: Redacted.Redacted<string> | undefined
|
|
465
|
+
let retained = false
|
|
466
|
+
const runCleanup = Effect.runPromiseWith(yield* Effect.context<never>())
|
|
467
|
+
|
|
468
|
+
yield* Effect.addFinalizer(() =>
|
|
469
|
+
sessionId === undefined || retained
|
|
470
|
+
? Effect.void
|
|
471
|
+
: cleanupFinalizer(
|
|
472
|
+
cleanup(sessionId).pipe(
|
|
473
|
+
Effect.tap((result) =>
|
|
474
|
+
Effect.sync(() => {
|
|
475
|
+
cleanupState.result = result
|
|
476
|
+
})
|
|
477
|
+
),
|
|
478
|
+
),
|
|
479
|
+
)
|
|
480
|
+
)
|
|
481
|
+
cleanupState.result = 'unconfirmed'
|
|
482
|
+
let refusal: BrowserRunRefusal | undefined
|
|
483
|
+
let acquisitionExited = false
|
|
484
|
+
|
|
485
|
+
sessionId = yield* Effect.uninterruptibleMask((restore) =>
|
|
486
|
+
restore(
|
|
487
|
+
native('session.acquire', async (signal) => {
|
|
488
|
+
const acquired = await binding.acquire(
|
|
489
|
+
options.keepAliveMillis ?? 600_000,
|
|
490
|
+
'session.acquire',
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
if (acquired instanceof BrowserRunRefusal) {
|
|
494
|
+
refusal = acquired
|
|
495
|
+
if (acquisitionExited) {
|
|
496
|
+
await runCleanup(
|
|
497
|
+
acquired.collect.pipe(
|
|
498
|
+
Effect.andThen(
|
|
499
|
+
reportBrowserCause('session.acquire', Cause.fail(acquired.error)),
|
|
500
|
+
),
|
|
501
|
+
),
|
|
502
|
+
)
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
return acquired
|
|
506
|
+
}
|
|
507
|
+
const id = Redacted.make(acquired)
|
|
508
|
+
|
|
509
|
+
if (signal.aborted) {
|
|
510
|
+
await runCleanup(cleanup(id))
|
|
511
|
+
signal.throwIfAborted()
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
return id
|
|
515
|
+
}),
|
|
516
|
+
).pipe(
|
|
517
|
+
Effect.onExit((exit) => {
|
|
518
|
+
acquisitionExited = true
|
|
519
|
+
|
|
520
|
+
return Exit.isFailure(exit) && refusal !== undefined ? refusal.failure : Effect.void
|
|
521
|
+
}),
|
|
522
|
+
Effect.filterOrElse(
|
|
523
|
+
(
|
|
524
|
+
acquired: BrowserRunRefusal | Redacted.Redacted<string>,
|
|
525
|
+
): acquired is Redacted.Redacted<string> => !(acquired instanceof BrowserRunRefusal),
|
|
526
|
+
(refusal) => refusal.failure,
|
|
527
|
+
),
|
|
528
|
+
Effect.tapCause((cause) => reportBrowserCause('session.acquire', cause)),
|
|
529
|
+
mapBrowserError((error) =>
|
|
530
|
+
error instanceof BrowserRunFailure
|
|
531
|
+
? reportedBrowserError(
|
|
532
|
+
failure('provider', 'not-dispatched', 'not-requested', error),
|
|
533
|
+
)
|
|
534
|
+
: error
|
|
535
|
+
),
|
|
536
|
+
)
|
|
537
|
+
)
|
|
538
|
+
const connection = yield* connect(sessionId)
|
|
539
|
+
|
|
540
|
+
const page = yield* native('session.page', async () => {
|
|
541
|
+
const context = await connection.browser.createBrowserContext()
|
|
542
|
+
|
|
543
|
+
return await context.newPage()
|
|
544
|
+
})
|
|
545
|
+
|
|
546
|
+
const reference = yield* decode(BrowserSessionReference, {
|
|
547
|
+
version: 1,
|
|
548
|
+
sessionId,
|
|
549
|
+
contextId: Redacted.make(page.browserContext().id ?? ''),
|
|
550
|
+
targetId: Redacted.make(yield* targetId(page, options.commandTimeoutMillis ?? 30_000)),
|
|
551
|
+
expiresAt,
|
|
552
|
+
commandTimeoutMillis: options.commandTimeoutMillis ?? 30_000,
|
|
553
|
+
})
|
|
554
|
+
|
|
555
|
+
yield* Effect.uninterruptibleMask((restore) =>
|
|
556
|
+
restore(retain(reference)).pipe(
|
|
557
|
+
Effect.tap(() =>
|
|
558
|
+
Effect.sync(() => {
|
|
559
|
+
retained = true
|
|
560
|
+
cleanupState.result = 'not-requested'
|
|
561
|
+
})
|
|
562
|
+
),
|
|
563
|
+
)
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
return { reference, page, ...connection }
|
|
567
|
+
})
|
|
568
|
+
|
|
569
|
+
const create = Effect.fnUntraced(function*<E, R>(
|
|
570
|
+
input: BrowserSessionOptions,
|
|
571
|
+
retain: (reference: BrowserSessionReference) => Effect.Effect<void, E, R>,
|
|
572
|
+
) {
|
|
573
|
+
const cleanupState: { result: BrowserSessionError['cleanup'] } = {
|
|
574
|
+
result: 'not-requested',
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
return yield* allocate(input, retain, cleanupState).pipe(
|
|
578
|
+
Effect.map(({ reference }) => reference),
|
|
579
|
+
timeout({
|
|
580
|
+
duration: '30 seconds',
|
|
581
|
+
orElse: () => Effect.fail(failure('timeout')),
|
|
582
|
+
}),
|
|
583
|
+
Effect.scoped,
|
|
584
|
+
mapBrowserError(
|
|
585
|
+
(error: E | BrowserSessionError) => annotateSessionCleanup(error, cleanupState.result),
|
|
586
|
+
(defect) => annotateSessionCleanup(defect, cleanupState.result),
|
|
587
|
+
),
|
|
588
|
+
Effect.withTracerEnabled(false),
|
|
589
|
+
)
|
|
590
|
+
})
|
|
591
|
+
|
|
592
|
+
const makeSession = Effect.fnUntraced(function*(
|
|
593
|
+
reference: BrowserSessionReference,
|
|
594
|
+
browser: Browser,
|
|
595
|
+
currentPage: Page,
|
|
596
|
+
retire: Effect.Effect<void, BrowserSessionError>,
|
|
597
|
+
) {
|
|
598
|
+
const scope = yield* Effect.scope
|
|
599
|
+
const lock = yield* Semaphore.make(1)
|
|
600
|
+
let invalid = false
|
|
601
|
+
let cleanupResult: BrowserSessionError['cleanup'] = 'not-requested'
|
|
602
|
+
|
|
603
|
+
const terminate = Effect.suspend(() => {
|
|
604
|
+
if (invalid) return Effect.void
|
|
605
|
+
invalid = true
|
|
606
|
+
cleanupResult = 'unconfirmed'
|
|
607
|
+
|
|
608
|
+
return retire.pipe(
|
|
609
|
+
Effect.onExit(() =>
|
|
610
|
+
cleanup(reference.sessionId).pipe(
|
|
611
|
+
Effect.tap((result) =>
|
|
612
|
+
Effect.sync(() => {
|
|
613
|
+
cleanupResult = result
|
|
614
|
+
})
|
|
615
|
+
),
|
|
616
|
+
Effect.asVoid,
|
|
617
|
+
)
|
|
618
|
+
),
|
|
619
|
+
)
|
|
620
|
+
})
|
|
621
|
+
|
|
622
|
+
const failAfterTermination = <E, E2>(
|
|
623
|
+
cause: Cause.Cause<E>,
|
|
624
|
+
annotate: (error: E, cleanup: BrowserSessionError['cleanup']) => E2,
|
|
625
|
+
) =>
|
|
626
|
+
Effect.uninterruptible(
|
|
627
|
+
terminate.pipe(
|
|
628
|
+
Effect.exit,
|
|
629
|
+
Effect.flatMap((exit) => {
|
|
630
|
+
const original = Cause.map(cause, (error) => annotate(error, cleanupResult))
|
|
631
|
+
|
|
632
|
+
return Effect.failCause(
|
|
633
|
+
Exit.isFailure(exit) ? Cause.combine(original, exit.cause) : original,
|
|
634
|
+
)
|
|
635
|
+
}),
|
|
636
|
+
),
|
|
637
|
+
)
|
|
638
|
+
|
|
639
|
+
const runEffect = <A, E, R>(
|
|
640
|
+
action: (commandTimeoutMillis: number) => Effect.Effect<A, E, R>,
|
|
641
|
+
) =>
|
|
642
|
+
lock
|
|
643
|
+
.withPermitsIfAvailable(1)(
|
|
644
|
+
Effect.gen(function*() {
|
|
645
|
+
if (invalid || scope.state._tag === 'Closed' || !browser.isConnected()) {
|
|
646
|
+
return yield* failure('closed')
|
|
647
|
+
}
|
|
648
|
+
const remaining = reference.expiresAt - (yield* Clock.currentTimeMillis)
|
|
649
|
+
|
|
650
|
+
if (remaining <= 0) {
|
|
651
|
+
return yield* failAfterTermination(
|
|
652
|
+
Cause.fail(failure('expired')),
|
|
653
|
+
(error, cleanup) => failure(error.reason, error.dispatch, cleanup, error),
|
|
654
|
+
)
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
return yield* action(Math.min(remaining, reference.commandTimeoutMillis)).pipe(
|
|
658
|
+
Effect.onExit((exit) =>
|
|
659
|
+
!invalid &&
|
|
660
|
+
Exit.isFailure(exit) &&
|
|
661
|
+
(Cause.hasDies(exit.cause) || Cause.hasInterrupts(exit.cause))
|
|
662
|
+
? (Cause.hasInterruptsOnly(exit.cause)
|
|
663
|
+
? Effect.void
|
|
664
|
+
: reportBrowserCause('session.command', exit.cause)).pipe(Effect.onExit(() => terminate))
|
|
665
|
+
: Effect.void
|
|
666
|
+
),
|
|
667
|
+
)
|
|
668
|
+
}),
|
|
669
|
+
)
|
|
670
|
+
.pipe(
|
|
671
|
+
Effect.flatMap(Effect.fromOption(() => failure('busy'))),
|
|
672
|
+
Effect.withTracerEnabled(false),
|
|
673
|
+
)
|
|
674
|
+
|
|
675
|
+
const runAction = <A, E, R>(
|
|
676
|
+
authorize: Effect.Effect<void, E, R>,
|
|
677
|
+
action: (commandTimeoutMillis: number) => Effect.Effect<A, BrowserSessionError>,
|
|
678
|
+
terminateOnError = false,
|
|
679
|
+
timeoutMillis?: number,
|
|
680
|
+
) =>
|
|
681
|
+
runEffect((commandTimeoutMillis) =>
|
|
682
|
+
authorize.pipe(
|
|
683
|
+
Effect.andThen(() =>
|
|
684
|
+
Effect.uninterruptibleMask((restore) =>
|
|
685
|
+
restore(
|
|
686
|
+
action(Math.min(commandTimeoutMillis, timeoutMillis ?? commandTimeoutMillis)),
|
|
687
|
+
).pipe(
|
|
688
|
+
Effect.catchCause((cause) => {
|
|
689
|
+
const annotate = (
|
|
690
|
+
error: BrowserSessionError,
|
|
691
|
+
cleanup: BrowserSessionError['cleanup'],
|
|
692
|
+
) =>
|
|
693
|
+
inheritBrowserReport(
|
|
694
|
+
error,
|
|
695
|
+
failure(error.reason, 'possibly-dispatched', cleanup, error),
|
|
696
|
+
)
|
|
697
|
+
|
|
698
|
+
return terminateOnError && !invalid
|
|
699
|
+
? failAfterTermination(cause, annotate)
|
|
700
|
+
: Effect.failCause(
|
|
701
|
+
Cause.map(cause, (error) => annotate(error, error.cleanup)),
|
|
702
|
+
)
|
|
703
|
+
}),
|
|
704
|
+
)
|
|
705
|
+
)
|
|
706
|
+
),
|
|
707
|
+
timeout({
|
|
708
|
+
duration: Math.min(commandTimeoutMillis, timeoutMillis ?? commandTimeoutMillis),
|
|
709
|
+
orElse: () =>
|
|
710
|
+
failAfterTermination(
|
|
711
|
+
Cause.fail(failure('timeout', 'possibly-dispatched')),
|
|
712
|
+
(error, cleanup) => failure(error.reason, error.dispatch, cleanup, error),
|
|
713
|
+
),
|
|
714
|
+
}),
|
|
715
|
+
)
|
|
716
|
+
)
|
|
717
|
+
|
|
718
|
+
const run = <A, E, R>(
|
|
719
|
+
authorize: Effect.Effect<void, E, R>,
|
|
720
|
+
action: (page: Page) => Promise<A>,
|
|
721
|
+
terminateOnError = false,
|
|
722
|
+
timeoutMillis?: number,
|
|
723
|
+
) =>
|
|
724
|
+
runAction(
|
|
725
|
+
authorize,
|
|
726
|
+
() => native('session.command', () => action(currentPage)),
|
|
727
|
+
terminateOnError,
|
|
728
|
+
timeoutMillis,
|
|
729
|
+
)
|
|
730
|
+
|
|
731
|
+
const command = <A, E, R>(
|
|
732
|
+
authorize: Effect.Effect<void, E, R>,
|
|
733
|
+
method: string,
|
|
734
|
+
parameters: Record<string, string | number>,
|
|
735
|
+
schema: Schema.Codec<A>,
|
|
736
|
+
) =>
|
|
737
|
+
runAction(
|
|
738
|
+
authorize,
|
|
739
|
+
(commandTimeoutMillis) =>
|
|
740
|
+
withCdp(currentPage, commandTimeoutMillis, (cdp) =>
|
|
741
|
+
native('session.command', (): Promise<unknown> =>
|
|
742
|
+
Reflect.apply(Reflect.get(cdp, 'send'), cdp, [method, parameters])).pipe(
|
|
743
|
+
Effect.flatMap((result) =>
|
|
744
|
+
Schema.decodeUnknownEffect(schema)(result).pipe(
|
|
745
|
+
mapBrowserError((error) =>
|
|
746
|
+
failure('provider', 'not-dispatched', 'not-requested', error)
|
|
747
|
+
),
|
|
748
|
+
)
|
|
749
|
+
),
|
|
750
|
+
)),
|
|
751
|
+
method === 'Cloudflare.handoff',
|
|
752
|
+
)
|
|
753
|
+
|
|
754
|
+
const session: BrowserSession = {
|
|
755
|
+
reference,
|
|
756
|
+
run: (authorize, action, options) =>
|
|
757
|
+
options === undefined
|
|
758
|
+
? run(authorize, action)
|
|
759
|
+
: decode(PositiveMillis, options.timeoutMillis).pipe(
|
|
760
|
+
Effect.flatMap((timeoutMillis) => run(authorize, action, false, timeoutMillis)),
|
|
761
|
+
),
|
|
762
|
+
prepareCredential: (request) =>
|
|
763
|
+
runEffect((commandTimeoutMillis) =>
|
|
764
|
+
prepareCredential(request).pipe(
|
|
765
|
+
Effect.provideService(BrowserSessionPage, {
|
|
766
|
+
page: currentPage,
|
|
767
|
+
commandTimeoutMillis,
|
|
768
|
+
}),
|
|
769
|
+
timeout({
|
|
770
|
+
duration: commandTimeoutMillis,
|
|
771
|
+
orElse: () =>
|
|
772
|
+
failAfterTermination(
|
|
773
|
+
Cause.fail(failure('timeout')),
|
|
774
|
+
(error, cleanup) => failure(error.reason, error.dispatch, cleanup, error),
|
|
775
|
+
),
|
|
776
|
+
}),
|
|
777
|
+
)
|
|
778
|
+
),
|
|
779
|
+
fillCredential: (request) =>
|
|
780
|
+
runEffect((commandTimeoutMillis) =>
|
|
781
|
+
fillCredential(request).pipe(
|
|
782
|
+
Effect.provideService(BrowserSessionPage, {
|
|
783
|
+
page: currentPage,
|
|
784
|
+
commandTimeoutMillis,
|
|
785
|
+
}),
|
|
786
|
+
Effect.catchCauseIf(
|
|
787
|
+
(cause) =>
|
|
788
|
+
cause.reasons.some(
|
|
789
|
+
(reason) =>
|
|
790
|
+
Cause.isFailReason(reason) &&
|
|
791
|
+
(reason.error.reason === 'timeout' ||
|
|
792
|
+
reason.error.dispatch === 'possibly-dispatched'),
|
|
793
|
+
),
|
|
794
|
+
(cause) =>
|
|
795
|
+
failAfterTermination(cause, (error, cleanup) =>
|
|
796
|
+
FailureDiagnostic.withCause(
|
|
797
|
+
CredentialFillError.make({ ...error, cleanup }),
|
|
798
|
+
error,
|
|
799
|
+
)),
|
|
800
|
+
),
|
|
801
|
+
)
|
|
802
|
+
),
|
|
803
|
+
handoff: (authorize, request) =>
|
|
804
|
+
decode(BrowserRunHandoffRequest, request).pipe(
|
|
805
|
+
Effect.flatMap((value) =>
|
|
806
|
+
command(
|
|
807
|
+
authorize,
|
|
808
|
+
'Cloudflare.handoff',
|
|
809
|
+
{ instructions: value.instructions, timeout: value.timeout },
|
|
810
|
+
Schema.Struct({
|
|
811
|
+
handoffId: Schema.NonEmptyString.check(Schema.isMaxLength(1024)),
|
|
812
|
+
}),
|
|
813
|
+
)
|
|
814
|
+
),
|
|
815
|
+
Effect.map((value) => BrowserRunHandoffResult.make({ handoffId: Redacted.make(value.handoffId) })),
|
|
816
|
+
),
|
|
817
|
+
getLiveView: (authorize, request) =>
|
|
818
|
+
decode(BrowserRunLiveViewRequest, request).pipe(
|
|
819
|
+
Effect.flatMap((value) =>
|
|
820
|
+
command(
|
|
821
|
+
authorize,
|
|
822
|
+
'Cloudflare.getLiveView',
|
|
823
|
+
{ mode: value.mode, expiresInMs: value.expiresInMs },
|
|
824
|
+
Schema.Struct({ devtoolsFrontendUrl: Schema.String }),
|
|
825
|
+
)
|
|
826
|
+
),
|
|
827
|
+
Effect.flatMap((value) =>
|
|
828
|
+
decode(BrowserRunLiveViewResult, {
|
|
829
|
+
devtoolsFrontendUrl: Redacted.make(value.devtoolsFrontendUrl),
|
|
830
|
+
})
|
|
831
|
+
),
|
|
832
|
+
),
|
|
833
|
+
getReadOnlyLiveView: (authorize, request) =>
|
|
834
|
+
decode(BrowserRunLiveViewRequest, request).pipe(
|
|
835
|
+
Effect.flatMap((value) =>
|
|
836
|
+
runEffect((commandTimeoutMillis) =>
|
|
837
|
+
authorize.pipe(
|
|
838
|
+
Effect.andThen(() =>
|
|
839
|
+
readonlyLiveView.mint(reference.sessionId, reference.targetId, value).pipe(
|
|
840
|
+
Effect.tapCause((cause) => reportBrowserCause('session.readonlyLiveView', cause)),
|
|
841
|
+
mapBrowserError((error) =>
|
|
842
|
+
reportedBrowserError(
|
|
843
|
+
failure('provider', 'not-dispatched', 'not-requested', error),
|
|
844
|
+
)
|
|
845
|
+
),
|
|
846
|
+
)
|
|
847
|
+
),
|
|
848
|
+
timeout({
|
|
849
|
+
duration: commandTimeoutMillis,
|
|
850
|
+
orElse: () => Effect.fail(failure('timeout')),
|
|
851
|
+
}),
|
|
852
|
+
)
|
|
853
|
+
)
|
|
854
|
+
),
|
|
855
|
+
),
|
|
856
|
+
getHandoffState: (authorize) =>
|
|
857
|
+
command(
|
|
858
|
+
authorize,
|
|
859
|
+
'Cloudflare.getHandoffState',
|
|
860
|
+
{},
|
|
861
|
+
Schema.Struct({
|
|
862
|
+
active: Schema.Boolean,
|
|
863
|
+
handoffId: Schema.optionalKey(
|
|
864
|
+
Schema.NonEmptyString.check(Schema.isMaxLength(1024)),
|
|
865
|
+
),
|
|
866
|
+
durationMs: Schema.optionalKey(Schema.Natural),
|
|
867
|
+
}),
|
|
868
|
+
).pipe(
|
|
869
|
+
Effect.map((value) =>
|
|
870
|
+
BrowserRunHandoffState.make({
|
|
871
|
+
active: value.active,
|
|
872
|
+
...(value.handoffId === undefined
|
|
873
|
+
? {}
|
|
874
|
+
: { handoffId: Redacted.make(value.handoffId) }),
|
|
875
|
+
...(value.durationMs === undefined ? {} : { durationMs: value.durationMs }),
|
|
876
|
+
})
|
|
877
|
+
),
|
|
878
|
+
),
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
return session
|
|
882
|
+
})
|
|
883
|
+
|
|
884
|
+
const createAttached = Effect.fnUntraced(function*<E, R>(
|
|
885
|
+
input: BrowserSessionOptions,
|
|
886
|
+
retain: (reference: BrowserSessionReference) => Effect.Effect<void, E, R>,
|
|
887
|
+
) {
|
|
888
|
+
const scope = yield* Scope.fork(yield* Effect.scope)
|
|
889
|
+
|
|
890
|
+
const cleanupState: { result: BrowserSessionError['cleanup'] } = {
|
|
891
|
+
result: 'not-requested',
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
return yield* allocate(input, retain, cleanupState).pipe(
|
|
895
|
+
Effect.flatMap(({ reference, browser, page, retire }) => makeSession(reference, browser, page, retire)),
|
|
896
|
+
Effect.provideService(Scope.Scope, scope),
|
|
897
|
+
timeout({
|
|
898
|
+
duration: '30 seconds',
|
|
899
|
+
orElse: () => Effect.fail(failure('timeout')),
|
|
900
|
+
}),
|
|
901
|
+
Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(scope, exit) : Effect.void)),
|
|
902
|
+
mapBrowserError(
|
|
903
|
+
(error: E | BrowserSessionError) => annotateSessionCleanup(error, cleanupState.result),
|
|
904
|
+
(defect) => annotateSessionCleanup(defect, cleanupState.result),
|
|
905
|
+
),
|
|
906
|
+
Effect.withTracerEnabled(false),
|
|
907
|
+
)
|
|
908
|
+
})
|
|
909
|
+
|
|
910
|
+
const attachPage = Effect.fnUntraced(function*(input: BrowserSessionReference) {
|
|
911
|
+
const reference = yield* decode(BrowserSessionReference, input)
|
|
912
|
+
|
|
913
|
+
if (reference.expiresAt <= (yield* Clock.currentTimeMillis)) {
|
|
914
|
+
return yield* failure('expired')
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
const { browser, retire } = yield* connect(reference.sessionId)
|
|
918
|
+
|
|
919
|
+
const context = browser
|
|
920
|
+
.browserContexts()
|
|
921
|
+
.find((value) => value.id === Redacted.value(reference.contextId))
|
|
922
|
+
|
|
923
|
+
if (context === undefined) return yield* failure('missing-page')
|
|
924
|
+
|
|
925
|
+
for (const page of yield* native('session.pages', () => context.pages())) {
|
|
926
|
+
if (
|
|
927
|
+
(yield* targetId(page, reference.commandTimeoutMillis)) ===
|
|
928
|
+
Redacted.value(reference.targetId)
|
|
929
|
+
) {
|
|
930
|
+
return yield* makeSession(reference, browser, page, retire)
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
return yield* failure('missing-page')
|
|
935
|
+
})
|
|
936
|
+
|
|
937
|
+
const attach = Effect.fnUntraced(function*(input: BrowserSessionReference) {
|
|
938
|
+
const reference = yield* decode(BrowserSessionReference, input)
|
|
939
|
+
const scope = yield* Scope.fork(yield* Effect.scope)
|
|
940
|
+
|
|
941
|
+
return yield* attachPage(reference).pipe(
|
|
942
|
+
Effect.provideService(Scope.Scope, scope),
|
|
943
|
+
timeout({
|
|
944
|
+
duration: reference.commandTimeoutMillis,
|
|
945
|
+
orElse: () =>
|
|
946
|
+
reportBrowserCause('session.connect', Cause.fail(failure('timeout'))).pipe(
|
|
947
|
+
Effect.andThen(Effect.fail(reportedBrowserError(failure('timeout')))),
|
|
948
|
+
),
|
|
949
|
+
}),
|
|
950
|
+
Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(scope, exit) : Effect.void)),
|
|
951
|
+
)
|
|
952
|
+
})
|
|
953
|
+
|
|
954
|
+
return BrowserSessions.of({
|
|
955
|
+
create,
|
|
956
|
+
createAttached,
|
|
957
|
+
attach,
|
|
958
|
+
close,
|
|
959
|
+
keepAlive: (sessionId) =>
|
|
960
|
+
decode(SessionId, sessionId).pipe(
|
|
961
|
+
Effect.flatMap((id) =>
|
|
962
|
+
binding.keepAlive(Redacted.value(id)).pipe(
|
|
963
|
+
timeout({
|
|
964
|
+
duration: '10 seconds',
|
|
965
|
+
orElse: () => Effect.fail(failure('timeout')),
|
|
966
|
+
}),
|
|
967
|
+
Effect.tapCause((cause) => reportBrowserCause('session.keepAlive', cause)),
|
|
968
|
+
mapBrowserError((error) =>
|
|
969
|
+
reportedBrowserError(
|
|
970
|
+
failure(
|
|
971
|
+
error.reason === 'timeout' ? 'timeout' : 'provider',
|
|
972
|
+
'not-dispatched',
|
|
973
|
+
'not-requested',
|
|
974
|
+
error,
|
|
975
|
+
),
|
|
976
|
+
)
|
|
977
|
+
),
|
|
978
|
+
)
|
|
979
|
+
),
|
|
980
|
+
Effect.withTracerEnabled(false),
|
|
981
|
+
),
|
|
982
|
+
})
|
|
983
|
+
}),
|
|
984
|
+
)
|
|
985
|
+
|
|
986
|
+
static layer(options: BrowserSessionsOptions) {
|
|
987
|
+
return this.layerNoDeps.pipe(
|
|
988
|
+
Layer.provide(BrowserRunBinding.layer(options.browser)),
|
|
989
|
+
Layer.provide(BrowserRunSessionLifecycle.layer(options)),
|
|
990
|
+
Layer.provide(BrowserRunReadonlyLiveView.layer(options)),
|
|
991
|
+
)
|
|
992
|
+
}
|
|
993
|
+
}
|