@effect-agent/platform-cloudflare 0.1.0-beta.77 → 0.1.0-beta.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BrowserRestCapture.mjs +1 -1
- package/dist/{CloudflareBrowser-Bj22nNUT.mjs → CloudflareBrowser-BSJRWmlW.mjs} +23 -7
- package/dist/CloudflareBrowser-BSJRWmlW.mjs.map +1 -0
- package/dist/CloudflareBrowser.mjs +1 -1
- package/dist/CloudflareMemory.d.mts +3 -1
- package/dist/CloudflareMemory.mjs +28 -1
- package/dist/CloudflareMemory.mjs.map +1 -1
- package/dist/CloudflareThreadClient.d.mts +44 -26
- package/dist/{ThreadObject-BnmDkg5W.d.mts → ThreadObject-D7G1M59T.d.mts} +28 -28
- package/dist/ThreadObject.d.mts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/src/CloudflareMemory.ts +48 -1
- package/src/internal/browser-quick-action.ts +24 -7
- package/dist/CloudflareBrowser-Bj22nNUT.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as BrowserQuickActionWorkersAi } from "./CloudflareBrowser-
|
|
1
|
+
import { i as BrowserQuickActionWorkersAi } from "./CloudflareBrowser-BSJRWmlW.mjs";
|
|
2
2
|
import { Effect, Layer, Option, Redacted, Schema, Stream } from "effect";
|
|
3
3
|
import { PageCapture, PageCaptureInferencePolicyError, PageCaptureInferenceUse, PageCaptureNavigationError, PageCaptureOutputLimitError, PageCaptureProtocolError, PageCaptureRateLimitedError, PageCaptureResourceUse, PageCaptureResult, PageCaptureUnsupportedError, PageContentCaptured, PageLinksCaptured, PageMarkdownCaptured, PageScrapeCaptured, PageStructuredCaptured } from "@effect-agent/sandbox/PageCapture";
|
|
4
4
|
import { SandboxImplementation } from "@effect-agent/sandbox/Sandbox";
|
|
@@ -151,7 +151,23 @@ const navigationError = (message, cause) => PageCaptureNavigationError.make({
|
|
|
151
151
|
...cause === void 0 ? {} : { cause }
|
|
152
152
|
});
|
|
153
153
|
/** Preserve bounded remote diagnostics for the host without exposing their text to a model. */
|
|
154
|
-
const privateResponseCause = (bodyText) =>
|
|
154
|
+
const privateResponseCause = (bodyText, response) => new Error(boundedDiagnostic(bodyText), { cause: {
|
|
155
|
+
provider: "cloudflare-browser-run",
|
|
156
|
+
httpStatus: response.status,
|
|
157
|
+
httpStatusSource: "browser-api",
|
|
158
|
+
headers: Object.fromEntries([
|
|
159
|
+
"content-type",
|
|
160
|
+
"cf-ray",
|
|
161
|
+
"x-request-id",
|
|
162
|
+
"retry-after",
|
|
163
|
+
"x-browser-ms-used"
|
|
164
|
+
].flatMap((name) => {
|
|
165
|
+
const value = response.headers.get(name);
|
|
166
|
+
return value === null ? [] : [[name, boundedDiagnostic(value)]];
|
|
167
|
+
})),
|
|
168
|
+
bodyCharacters: bodyText.length,
|
|
169
|
+
bodyTruncated: bodyText.length > MAX_DIAGNOSTIC_LENGTH
|
|
170
|
+
} });
|
|
155
171
|
/** Foreign cancellation must not keep a response Scope open indefinitely. */
|
|
156
172
|
const cancelResponse = (cancel, warning) => Effect.tryPromise({
|
|
157
173
|
try: cancel,
|
|
@@ -225,10 +241,10 @@ const isJsonResponse = (response) => {
|
|
|
225
241
|
return mediaType === "application/json" || mediaType?.endsWith("+json") === true;
|
|
226
242
|
};
|
|
227
243
|
const parseOutput = (action, bodyText, response) => {
|
|
228
|
-
if (!isJsonResponse(response)) return protocolError("The Quick Action success response was not a JSON response envelope", privateResponseCause(bodyText));
|
|
244
|
+
if (!isJsonResponse(response)) return protocolError("The Quick Action success response was not a JSON response envelope", privateResponseCause(bodyText, response));
|
|
229
245
|
const envelope = decodeEnvelope(bodyText);
|
|
230
|
-
if (Option.isNone(envelope)) return protocolError("The JSON Quick Action response did not carry a valid response envelope", privateResponseCause(bodyText));
|
|
231
|
-
if (!envelope.value.success) return navigationError("The Quick Action reported a navigation failure", privateResponseCause(bodyText));
|
|
246
|
+
if (Option.isNone(envelope)) return protocolError("The JSON Quick Action response did not carry a valid response envelope", privateResponseCause(bodyText, response));
|
|
247
|
+
if (!envelope.value.success) return navigationError("The Quick Action reported a navigation failure", privateResponseCause(bodyText, response));
|
|
232
248
|
switch (action._tag) {
|
|
233
249
|
case "CapturePageContent":
|
|
234
250
|
case "CapturePageMarkdown":
|
|
@@ -280,7 +296,7 @@ const makeCapture = (browser, workersAi) => Effect.fn("BrowserQuickActionCapture
|
|
|
280
296
|
if (response.status === 429) {
|
|
281
297
|
const retryAfter = retryAfterMillis(response);
|
|
282
298
|
const reason = isQuotaMessage(bodyText) ? "quota" : "rate";
|
|
283
|
-
const cause = privateResponseCause(bodyText);
|
|
299
|
+
const cause = privateResponseCause(bodyText, response);
|
|
284
300
|
return yield* PageCaptureRateLimitedError.make({
|
|
285
301
|
implementation: browserQuickActionImplementation,
|
|
286
302
|
reason,
|
|
@@ -291,7 +307,7 @@ const makeCapture = (browser, workersAi) => Effect.fn("BrowserQuickActionCapture
|
|
|
291
307
|
}
|
|
292
308
|
if (!response.ok) {
|
|
293
309
|
const message = `The Quick Action answered HTTP ${response.status}`;
|
|
294
|
-
const cause = privateResponseCause(bodyText);
|
|
310
|
+
const cause = privateResponseCause(bodyText, response);
|
|
295
311
|
if (response.status >= 500) return yield* protocolError(message, cause);
|
|
296
312
|
return yield* navigationError(message, cause);
|
|
297
313
|
}
|
|
@@ -463,4 +479,4 @@ var CloudflareBrowser_exports = /* @__PURE__ */ __exportAll({
|
|
|
463
479
|
//#endregion
|
|
464
480
|
export { BrowserQuickActionWorkersAiPolicyError as a, browserQuickActionScreenshotLayer as c, BrowserQuickActionWorkersAi as i, browserQuickActionWorkersAiCaptureLayer as l, BrowserQuickActionBrowserBinding as n, CloudflareBrowser as o, BrowserQuickActionRpcError as r, browserQuickActionCaptureLayer as s, CloudflareBrowser_exports as t };
|
|
465
481
|
|
|
466
|
-
//# sourceMappingURL=CloudflareBrowser-
|
|
482
|
+
//# sourceMappingURL=CloudflareBrowser-BSJRWmlW.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CloudflareBrowser-BSJRWmlW.mjs","names":[],"sources":["../src/internal/browser-quick-action.ts","../src/CloudflareBrowser.ts"],"sourcesContent":["/// <reference types=\"@cloudflare/workers-types\" />\n\nimport {\n PageCapture,\n PageCaptureInferenceUse,\n PageCaptureInferencePolicyError,\n PageCaptureNavigationError,\n PageCaptureOutputLimitError,\n PageCaptureProtocolError,\n PageCaptureRateLimitedError,\n PageCaptureResourceUse,\n PageCaptureResult,\n PageCaptureUnsupportedError,\n PageContentCaptured,\n PageLinksCaptured,\n PageMarkdownCaptured,\n PageScrapeCaptured,\n PageStructuredCaptured,\n type PageCaptureAction,\n type PageCaptureCapture,\n type PageCaptureError,\n type PageCaptureOutput,\n type PageCaptureRequest,\n} from \"@effect-agent/sandbox/PageCapture\";\nimport {\n PageScreenshot,\n PageScreenshotOutputLimitError,\n PageScreenshotResult,\n type PageScreenshotCapture,\n type PageScreenshotError,\n type PageScreenshotRequest,\n} from \"@effect-agent/sandbox/PageScreenshot\";\nimport { SandboxImplementation } from \"@effect-agent/sandbox/Sandbox\";\nimport { Context, Effect, Layer, Option, Schema } from \"effect\";\n\n/**\n * The Cloudflare Browser Run Quick Action `PageCapture` adapter (capability\n * spec §9.2). Each capture is one stateless `quickAction()` RPC on the\n * Wrangler `browser` binding: the platform renders the target in a managed\n * headless browser and returns one bounded output; the adapter holds no\n * session and no state between passes. The binding requires a Worker\n * compatibility date of `2026-03-24` or later, and local `wrangler dev` needs\n * remote mode (`\"remote\": true` on the binding) because `quickAction` has no\n * local implementation.\n *\n * Rendered output is untrusted, attacker-influenced content; this adapter\n * only bounds and types it. Deployment class `E` only: no durability claim.\n */\nexport const browserQuickActionImplementation = SandboxImplementation.make({\n isolation: \"isolated\",\n identity: \"cloudflare-browser-quick-action\",\n});\n\n/**\n * Effect-native client captured by the binding service. Its option types come\n * directly from the pinned Workers declarations rather than a local copy.\n */\nexport interface BrowserQuickActionClient {\n readonly screenshot: (\n options: BrowserRunScreenshotOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n readonly content: (\n options: BrowserRunContentOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n readonly markdown: (\n options: BrowserRunMarkdownOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n readonly links: (\n options: BrowserRunLinksOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n readonly scrape: (\n options: BrowserRunScrapeOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n readonly json: (\n options: BrowserRunJsonOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n}\n\n/** A native binding RPC rejected before it returned an HTTP response. */\nexport class BrowserQuickActionRpcError extends Schema.TaggedError<BrowserQuickActionRpcError>()(\n \"BrowserQuickActionRpcError\",\n {\n action: Schema.Literals([\"screenshot\", \"content\", \"markdown\", \"links\", \"scrape\", \"json\"]),\n cause: Schema.Defect(),\n },\n) {}\n\nexport interface BrowserQuickActionCaptureOptions {\n /** The resolved Wrangler `browser` binding (DEPLOY-014: supplied, never ambient). */\n readonly browser: BrowserRun;\n}\n\n/** Host-owned browser binding authority, supplied explicitly at the composition root. */\nexport class BrowserQuickActionBrowserBinding extends Context.Service<\n BrowserQuickActionBrowserBinding,\n BrowserQuickActionClient\n>()(\"@effect-agent/platform-cloudflare/BrowserQuickActionBrowserBinding\") {\n static layer(\n options: BrowserQuickActionCaptureOptions,\n ): Layer.Layer<BrowserQuickActionBrowserBinding> {\n const browser = options.browser;\n\n const invoke = Effect.fn(\"BrowserQuickActionBrowserBinding.invoke\")(function* (\n action: \"screenshot\" | \"content\" | \"markdown\" | \"links\" | \"scrape\" | \"json\",\n evaluate: () => Promise<Response>,\n ): Effect.fn.Return<Response, BrowserQuickActionRpcError> {\n return yield* Effect.tryPromise({\n try: evaluate,\n catch: (cause) => BrowserQuickActionRpcError.make({ action, cause }),\n });\n });\n\n return Layer.succeed(BrowserQuickActionBrowserBinding)({\n screenshot: (request) =>\n invoke(\"screenshot\", () => browser.quickAction(\"screenshot\", request)),\n content: (request) => invoke(\"content\", () => browser.quickAction(\"content\", request)),\n markdown: (request) => invoke(\"markdown\", () => browser.quickAction(\"markdown\", request)),\n links: (request) => invoke(\"links\", () => browser.quickAction(\"links\", request)),\n scrape: (request) => invoke(\"scrape\", () => browser.quickAction(\"scrape\", request)),\n json: (request) => invoke(\"json\", () => browser.quickAction(\"json\", request)),\n });\n }\n}\n\n/** Host-owned authorization and accounting for one Workers AI extraction. */\nexport interface BrowserQuickActionWorkersAiPolicy {\n readonly authorizeAndAccount: (\n request: PageCaptureRequest,\n ) => Effect.Effect<void, BrowserQuickActionWorkersAiPolicyError>;\n}\n\n/** Host-only diagnostic for a denied or unaccounted Workers AI extraction. */\nexport class BrowserQuickActionWorkersAiPolicyError extends Schema.TaggedError<BrowserQuickActionWorkersAiPolicyError>()(\n \"BrowserQuickActionWorkersAiPolicyError\",\n {\n reason: Schema.Literals([\"authorization\", \"accounting\"]),\n message: Schema.String.check(Schema.isMaxLength(8_000)),\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\n/** Explicit host-owned authority and accounting for separately billed Workers AI extraction. */\nexport class BrowserQuickActionWorkersAi extends Context.Service<\n BrowserQuickActionWorkersAi,\n BrowserQuickActionWorkersAiPolicy\n>()(\"@effect-agent/platform-cloudflare/BrowserQuickActionWorkersAi\") {\n static layer(\n policy: BrowserQuickActionWorkersAiPolicy,\n ): Layer.Layer<BrowserQuickActionWorkersAi> {\n return Layer.succeed(BrowserQuickActionWorkersAi)(policy);\n }\n}\n\nconst MAX_DIAGNOSTIC_LENGTH = 8_000;\nconst boundedDiagnostic = (message: string): string => message.slice(0, MAX_DIAGNOSTIC_LENGTH);\n\nconst QuickActionSuccessEnvelope = Schema.Struct({\n success: Schema.Literal(true),\n result: Schema.Json,\n});\n\nconst QuickActionErrorEnvelope = Schema.Struct({\n success: Schema.Literal(false),\n errors: Schema.Array(\n Schema.Struct({\n message: Schema.String,\n code: Schema.optionalKey(Schema.Number),\n detail: Schema.optionalKey(Schema.String),\n path: Schema.optionalKey(Schema.String),\n }),\n ),\n rawAiResponse: Schema.optionalKey(Schema.String),\n});\n\nconst QuickActionEnvelope = Schema.Union([QuickActionSuccessEnvelope, QuickActionErrorEnvelope]);\nconst decodeEnvelope = Schema.decodeUnknownOption(Schema.fromJsonString(QuickActionEnvelope));\n\n/** Project the schema-validated request onto Cloudflare's native common options. */\nconst quickActionCommonOptions = (request: PageCaptureRequest): BrowserRunCommonOptions => {\n const options: BrowserRunBaseOptions = {};\n const navigation = request.navigation;\n\n if (navigation !== undefined) {\n const goto: NonNullable<BrowserRunBaseOptions[\"gotoOptions\"]> = {};\n\n if (navigation.waitUntil !== undefined) goto.waitUntil = navigation.waitUntil;\n if (navigation.timeoutMillis !== undefined) goto.timeout = navigation.timeoutMillis;\n if (Object.keys(goto).length > 0) options.gotoOptions = goto;\n if (navigation.waitForSelector !== undefined) {\n options.waitForSelector = {\n selector: navigation.waitForSelector.selector,\n ...(navigation.waitForSelector.timeoutMillis === undefined\n ? {}\n : { timeout: navigation.waitForSelector.timeoutMillis }),\n };\n }\n }\n if (request.viewport !== undefined) {\n options.viewport = { width: request.viewport.width, height: request.viewport.height };\n }\n if (request.resourcePolicy !== undefined) {\n if (request.resourcePolicy.rejectResourceTypes !== undefined) {\n options.rejectResourceTypes = [...request.resourcePolicy.rejectResourceTypes];\n }\n if (request.resourcePolicy.allowRequestPatterns !== undefined) {\n options.allowRequestPattern = [...request.resourcePolicy.allowRequestPatterns];\n }\n }\n\n return request.target._tag === \"PageUrlTarget\"\n ? { ...options, url: request.target.url }\n : { ...options, html: request.target.html };\n};\n\n/** Dispatch through Cloudflare's native action-specific overloads. */\nconst executeQuickAction = (\n browser: BrowserQuickActionClient,\n request: PageCaptureRequest,\n): Effect.Effect<Response, BrowserQuickActionRpcError> => {\n const options = quickActionCommonOptions(request);\n\n switch (request.action._tag) {\n case \"CapturePageContent\": {\n return browser.content(options);\n }\n case \"CapturePageMarkdown\": {\n return browser.markdown(options);\n }\n case \"CapturePageLinks\": {\n return browser.links({\n ...options,\n ...(request.action.visibleLinksOnly === undefined\n ? {}\n : { visibleLinksOnly: request.action.visibleLinksOnly }),\n });\n }\n case \"CapturePageScrape\": {\n return browser.scrape({\n ...options,\n elements: request.action.selectors.map((selector) => ({ selector })),\n });\n }\n case \"CapturePageStructured\": {\n return browser.json({\n ...options,\n response_format: {\n type: \"json_schema\",\n json_schema: request.action.responseFormat,\n },\n ...(request.action.prompt === undefined ? {} : { prompt: request.action.prompt }),\n });\n }\n }\n};\n\nconst protocolError = (message: string, cause?: unknown): PageCaptureProtocolError =>\n PageCaptureProtocolError.make({\n implementation: browserQuickActionImplementation,\n message: boundedDiagnostic(message),\n ...(cause === undefined ? {} : { cause }),\n });\n\nconst navigationError = (message: string, cause?: unknown): PageCaptureNavigationError =>\n PageCaptureNavigationError.make({\n implementation: browserQuickActionImplementation,\n message: boundedDiagnostic(message),\n ...(cause === undefined ? {} : { cause }),\n });\n\n/** Preserve bounded remote diagnostics for the host without exposing their text to a model. */\nconst privateResponseCause = (bodyText: string, response: Response): Error =>\n new Error(boundedDiagnostic(bodyText), {\n cause: {\n provider: \"cloudflare-browser-run\",\n httpStatus: response.status,\n httpStatusSource: \"browser-api\",\n headers: Object.fromEntries(\n [\"content-type\", \"cf-ray\", \"x-request-id\", \"retry-after\", \"x-browser-ms-used\"].flatMap(\n (name) => {\n const value = response.headers.get(name);\n\n return value === null ? [] : [[name, boundedDiagnostic(value)]];\n },\n ),\n ),\n bodyCharacters: bodyText.length,\n bodyTruncated: bodyText.length > MAX_DIAGNOSTIC_LENGTH,\n },\n });\n\n/** Foreign cancellation must not keep a response Scope open indefinitely. */\nconst cancelResponse = (cancel: () => Promise<void>, warning: string): Effect.Effect<void> =>\n Effect.tryPromise({ try: cancel, catch: () => undefined }).pipe(\n Effect.interruptible,\n Effect.timeoutOrElse({\n duration: \"1 second\",\n orElse: () => Effect.fail(undefined),\n }),\n Effect.catch(() => Effect.logWarning(warning)),\n );\n\nconst releaseResponseReader = (\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): Effect.Effect<void> =>\n cancelResponse(() => reader.cancel(), \"Canceling the Quick Action response failed\").pipe(\n Effect.ensuring(\n Effect.try({\n try: () => reader.releaseLock(),\n catch: (cause) => protocolError(\"Releasing the Quick Action response failed\", cause),\n }).pipe(Effect.catch((error) => Effect.logWarning(error.message))),\n ),\n );\n\nconst readBoundedResponse = Effect.fn(\"BrowserQuickActionCapture.readResponse\")(function* (\n response: Response,\n request: PageCaptureRequest,\n) {\n const body = response.body;\n\n if (body === null) return \"\";\n\n const reader = yield* Effect.acquireRelease(\n Effect.try({\n try: () => body.getReader(),\n catch: (cause) => protocolError(\"Opening the Quick Action response failed\", cause),\n }),\n releaseResponseReader,\n );\n\n const decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false });\n let observedBytes = 0;\n let bodyText = \"\";\n\n while (true) {\n const chunk = yield* Effect.tryPromise({\n try: () => reader.read(),\n catch: (cause) => protocolError(\"Reading the Quick Action response failed\", cause),\n });\n\n if (chunk.done) break;\n\n observedBytes += chunk.value.byteLength;\n if (observedBytes > request.limits.maxOutputBytes) {\n return yield* PageCaptureOutputLimitError.make({\n implementation: browserQuickActionImplementation,\n limit: request.limits.maxOutputBytes,\n observed: observedBytes,\n });\n }\n\n bodyText += yield* Effect.try({\n try: () => decoder.decode(chunk.value, { stream: true }),\n catch: (cause) => protocolError(\"Decoding the Quick Action response failed\", cause),\n });\n }\n\n return (\n bodyText +\n (yield* Effect.try({\n try: () => decoder.decode(),\n catch: (cause) => protocolError(\"Decoding the Quick Action response failed\", cause),\n }))\n );\n}, Effect.scoped);\n\n/**\n * Retry-After arrives in whole seconds; a non-integer form (an HTTP date) is\n * dropped rather than guessed at.\n */\nconst retryAfterMillis = (response: Response): number | undefined => {\n const header = response.headers.get(\"Retry-After\");\n\n if (header === null) return undefined;\n const seconds = Number(header);\n\n if (!Number.isSafeInteger(seconds) || seconds < 0) return undefined;\n const millis = seconds * 1_000;\n\n return Number.isSafeInteger(millis) ? millis : undefined;\n};\n\nconst browserMillis = (response: Response): number | undefined => {\n const header = response.headers.get(\"X-Browser-Ms-Used\");\n\n if (header === null) return undefined;\n const millis = Number(header);\n\n return Number.isSafeInteger(millis) && millis >= 0 ? millis : undefined;\n};\n\n/** Only trusted response metadata chooses transport framing; page text never does. */\nconst isJsonResponse = (response: Response): boolean => {\n const contentType = response.headers.get(\"Content-Type\");\n\n if (contentType === null) return false;\n const mediaType = contentType.split(\";\", 1)[0]?.trim().toLowerCase();\n\n return mediaType === \"application/json\" || mediaType?.endsWith(\"+json\") === true;\n};\n\nconst parseOutput = (\n action: PageCaptureAction,\n bodyText: string,\n response: Response,\n): PageCaptureOutput | PageCaptureNavigationError | PageCaptureProtocolError => {\n if (!isJsonResponse(response)) {\n return protocolError(\n \"The Quick Action success response was not a JSON response envelope\",\n privateResponseCause(bodyText, response),\n );\n }\n const envelope = decodeEnvelope(bodyText);\n\n if (Option.isNone(envelope)) {\n return protocolError(\n \"The JSON Quick Action response did not carry a valid response envelope\",\n privateResponseCause(bodyText, response),\n );\n }\n if (!envelope.value.success) {\n return navigationError(\n \"The Quick Action reported a navigation failure\",\n privateResponseCause(bodyText, response),\n );\n }\n switch (action._tag) {\n case \"CapturePageContent\":\n case \"CapturePageMarkdown\": {\n if (typeof envelope.value.result !== \"string\") {\n return protocolError(\"The Quick Action envelope carried a non-text result\");\n }\n\n return action._tag === \"CapturePageContent\"\n ? PageContentCaptured.make({ html: envelope.value.result })\n : PageMarkdownCaptured.make({ markdown: envelope.value.result });\n }\n case \"CapturePageLinks\": {\n const decoded = Schema.decodeUnknownOption(PageLinksCaptured)({\n _tag: \"PageLinksCaptured\",\n links: envelope.value.result,\n });\n\n if (Option.isNone(decoded)) {\n return protocolError(\"The links Quick Action did not return a bounded array of valid URLs\");\n }\n\n return decoded.value;\n }\n case \"CapturePageScrape\": {\n const decoded = Schema.decodeUnknownOption(PageScrapeCaptured)({\n _tag: \"PageScrapeCaptured\",\n groups: envelope.value.result,\n });\n\n if (Option.isNone(decoded)) {\n return protocolError(\n \"The scrape Quick Action did not return bounded grouped element records\",\n );\n }\n\n return decoded.value;\n }\n case \"CapturePageStructured\": {\n return PageStructuredCaptured.make({ value: envelope.value.result });\n }\n }\n};\n\nconst isQuotaMessage = (text: string): boolean => /time limit|daily|quota/i.test(text);\n\nconst makeCapture = (\n browser: BrowserQuickActionClient,\n workersAi?: BrowserQuickActionWorkersAiPolicy,\n): PageCaptureCapture =>\n Effect.fn(\"BrowserQuickActionCapture.capture\")(function* (\n request: PageCaptureRequest,\n ): Effect.fn.Return<PageCaptureResult, PageCaptureError> {\n if (request.engine !== \"chromium\") {\n return yield* PageCaptureUnsupportedError.make({\n implementation: browserQuickActionImplementation,\n feature: \"engine\",\n message:\n \"The browser binding's quickAction() exposes no engine selector; kitesurf requires the REST or CDP surface\",\n });\n }\n\n const usesWorkersAi = request.action._tag === \"CapturePageStructured\";\n\n if (usesWorkersAi) {\n if (workersAi === undefined) {\n return yield* PageCaptureUnsupportedError.make({\n implementation: browserQuickActionImplementation,\n feature: \"action\",\n message:\n \"Structured capture invokes separately billed Workers AI and requires an explicit authorization and accounting policy\",\n });\n }\n yield* workersAi.authorizeAndAccount(request).pipe(\n Effect.mapError((cause) =>\n PageCaptureInferencePolicyError.make({\n implementation: browserQuickActionImplementation,\n provider: \"cloudflare-workers-ai\",\n reason: cause.reason,\n message:\n cause.reason === \"authorization\"\n ? \"Workers AI extraction was not authorized\"\n : \"Workers AI extraction could not be accounted for\",\n cause,\n }),\n ),\n );\n }\n\n const response = yield* executeQuickAction(browser, request).pipe(\n Effect.mapError((error) =>\n protocolError(\"The browser binding rejected the Quick Action\", error.cause),\n ),\n );\n\n const bodyText = yield* readBoundedResponse(response, request);\n\n if (response.status === 429) {\n const retryAfter = retryAfterMillis(response);\n const reason = isQuotaMessage(bodyText) ? \"quota\" : \"rate\";\n const cause = privateResponseCause(bodyText, response);\n\n return yield* PageCaptureRateLimitedError.make({\n implementation: browserQuickActionImplementation,\n reason,\n ...(retryAfter === undefined ? {} : { retryAfterMillis: retryAfter }),\n ...(cause === undefined ? {} : { cause }),\n message:\n reason === \"quota\"\n ? \"The Quick Action exceeded its browser quota\"\n : \"The Quick Action was rate limited\",\n });\n }\n if (!response.ok) {\n const message = `The Quick Action answered HTTP ${response.status}`;\n const cause = privateResponseCause(bodyText, response);\n\n if (response.status >= 500) {\n return yield* protocolError(message, cause);\n }\n\n return yield* navigationError(message, cause);\n }\n const output = parseOutput(request.action, bodyText, response);\n\n if (\n output._tag === \"PageCaptureNavigationError\" ||\n output._tag === \"PageCaptureProtocolError\"\n ) {\n return yield* output;\n }\n const millis = browserMillis(response);\n\n return PageCaptureResult.make({\n implementation: browserQuickActionImplementation,\n output,\n resourceUse: PageCaptureResourceUse.make({\n ...(millis === undefined ? {} : { browserMillis: millis }),\n ...(usesWorkersAi\n ? {\n inference: PageCaptureInferenceUse.make({\n provider: \"cloudflare-workers-ai\",\n modelCalls: 1,\n }),\n }\n : {}),\n }),\n });\n });\n\n/**\n * Ordinary Quick Actions require host-owned browser binding authority. Workers\n * AI stays unavailable unless the host deliberately selects its separate Layer.\n */\nexport const browserQuickActionCaptureLayer = (): Layer.Layer<\n PageCapture,\n never,\n BrowserQuickActionBrowserBinding\n> =>\n Layer.effect(\n PageCapture,\n Effect.map(BrowserQuickActionBrowserBinding, (browser) =>\n PageCapture.of({ capture: makeCapture(browser) }),\n ),\n );\n\n/** Structured Quick Actions require host-owned browser and Workers AI authority. */\nexport const browserQuickActionWorkersAiCaptureLayer = (): Layer.Layer<\n PageCapture,\n never,\n BrowserQuickActionBrowserBinding | BrowserQuickActionWorkersAi\n> =>\n Layer.effect(\n PageCapture,\n Effect.gen(function* () {\n const browser = yield* BrowserQuickActionBrowserBinding;\n const workersAi = yield* BrowserQuickActionWorkersAi;\n\n return PageCapture.of({ capture: makeCapture(browser, workersAi) });\n }),\n );\n\n/** Host-owned Quick Action binding and optional, separately billed extraction authority. */\nexport interface CloudflareBrowserOptions extends BrowserQuickActionCaptureOptions {\n readonly workersAi?: BrowserQuickActionWorkersAiPolicy;\n}\n\n/** Compose WebCapture handlers with the Cloudflare Quick Action adapter. */\nexport const CloudflareBrowser = {\n /**\n * Supply a WebCapture definition and the resolved Worker browser binding.\n * Supports capture, scrape, and extraction definitions without importing capabilities.\n * Only PageCapture is provided; other handler requirements and errors stay visible.\n * Extraction fails closed unless workersAi explicitly authorizes and accounts for it.\n * Capture limits, typed failures, tracing, and scoped response cleanup are unchanged.\n */\n layer: <A, E, R>(\n definition: { readonly handlers: Layer.Layer<A, E, R> },\n options: CloudflareBrowserOptions,\n ): Layer.Layer<A, E, Exclude<R, PageCapture>> => {\n const capture =\n options.workersAi === undefined\n ? browserQuickActionCaptureLayer()\n : browserQuickActionWorkersAiCaptureLayer().pipe(\n Layer.provide(BrowserQuickActionWorkersAi.layer(options.workersAi)),\n );\n\n return definition.handlers.pipe(\n Layer.provide(capture.pipe(Layer.provide(BrowserQuickActionBrowserBinding.layer(options)))),\n );\n },\n};\n\nconst screenshotOptions = (request: PageScreenshotRequest): BrowserRunScreenshotOptions => {\n const options: BrowserRunBaseOptions = {};\n\n if (\n request.navigation?.waitUntil !== undefined ||\n request.navigation?.timeoutMillis !== undefined\n ) {\n options.gotoOptions = {\n ...(request.navigation.waitUntil === undefined\n ? {}\n : { waitUntil: request.navigation.waitUntil }),\n ...(request.navigation.timeoutMillis === undefined\n ? {}\n : { timeout: request.navigation.timeoutMillis }),\n };\n }\n if (request.navigation?.waitForSelector !== undefined) {\n options.waitForSelector = {\n selector: request.navigation.waitForSelector.selector,\n ...(request.navigation.waitForSelector.timeoutMillis === undefined\n ? {}\n : { timeout: request.navigation.waitForSelector.timeoutMillis }),\n };\n }\n if (request.viewport !== undefined) {\n options.viewport = { width: request.viewport.width, height: request.viewport.height };\n }\n if (request.resourcePolicy?.rejectResourceTypes !== undefined) {\n options.rejectResourceTypes = [...request.resourcePolicy.rejectResourceTypes];\n }\n if (request.resourcePolicy?.allowRequestPatterns !== undefined) {\n options.allowRequestPattern = [...request.resourcePolicy.allowRequestPatterns];\n }\n\n return {\n ...options,\n ...(request.target._tag === \"PageUrlTarget\"\n ? { url: request.target.url }\n : { html: request.target.html }),\n screenshotOptions: { type: \"png\", encoding: \"binary\", fullPage: request.fullPage },\n };\n};\n\nconst cancelBody = (body: ReadableStream<Uint8Array>): Effect.Effect<void> =>\n cancelResponse(() => body.cancel(), \"Canceling the screenshot response failed\");\n\nconst releaseScreenshotReader = (\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): Effect.Effect<void> =>\n cancelResponse(() => reader.cancel(), \"Canceling the screenshot response failed\").pipe(\n Effect.ensuring(\n Effect.try({\n try: () => reader.releaseLock(),\n catch: () => undefined,\n }).pipe(Effect.catch(() => Effect.logWarning(\"Releasing the screenshot response failed\"))),\n ),\n );\n\nconst pngResponse = (response: Response): boolean =>\n response.headers.get(\"Content-Type\")?.split(\";\", 1)[0]?.trim().toLowerCase() === \"image/png\";\n\nconst declaredLength = (response: Response): number | undefined => {\n const raw = response.headers.get(\"Content-Length\");\n\n if (raw === null || !/^(0|[1-9][0-9]*)$/.test(raw)) return undefined;\n const length = Number(raw);\n\n return Number.isSafeInteger(length) ? length : undefined;\n};\n\nconst readScreenshot = Effect.fn(\"BrowserQuickActionScreenshot.read\")(function* (\n response: Response,\n request: PageScreenshotRequest,\n) {\n const body = response.body;\n\n if (body === null) {\n return yield* protocolError(\"The screenshot response had no body\");\n }\n if (!pngResponse(response)) {\n yield* cancelBody(body);\n\n return yield* protocolError(\"The screenshot response was not image/png\");\n }\n const length = declaredLength(response);\n\n if (length !== undefined && length > request.limits.maxOutputBytes) {\n yield* cancelBody(body);\n\n return yield* PageScreenshotOutputLimitError.make({\n implementation: browserQuickActionImplementation,\n limit: request.limits.maxOutputBytes,\n observed: length,\n });\n }\n\n const reader = yield* Effect.acquireRelease(\n Effect.try({\n try: () => body.getReader(),\n catch: (cause) => protocolError(\"Opening the screenshot response failed\", cause),\n }),\n releaseScreenshotReader,\n );\n\n const chunks: Array<Uint8Array> = [];\n let observed = 0;\n\n while (true) {\n const next = yield* Effect.tryPromise({\n try: () => reader.read(),\n catch: (cause) => protocolError(\"Reading the screenshot response failed\", cause),\n });\n\n if (next.done) break;\n observed += next.value.byteLength;\n if (observed > request.limits.maxOutputBytes) {\n return yield* PageScreenshotOutputLimitError.make({\n implementation: browserQuickActionImplementation,\n limit: request.limits.maxOutputBytes,\n observed,\n });\n }\n chunks.push(next.value);\n }\n const bytes = new Uint8Array(observed);\n let offset = 0;\n\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return bytes;\n}, Effect.scoped);\n\nconst makeScreenshot = (browser: BrowserQuickActionClient): PageScreenshotCapture =>\n Effect.fn(\"BrowserQuickActionScreenshot.capture\")(function* (\n request: PageScreenshotRequest,\n ): Effect.fn.Return<PageScreenshotResult, PageScreenshotError> {\n if (request.engine !== \"chromium\") {\n return yield* PageCaptureUnsupportedError.make({\n implementation: browserQuickActionImplementation,\n feature: \"engine\",\n message: \"The browser binding's screenshot action exposes no engine selector\",\n });\n }\n\n const response = yield* browser\n .screenshot(screenshotOptions(request))\n .pipe(\n Effect.mapError((error) =>\n protocolError(\"The browser binding rejected the screenshot\", error.cause),\n ),\n );\n\n if (response.status === 429) {\n const body = response.body;\n\n if (body !== null) yield* cancelBody(body);\n\n return yield* PageCaptureRateLimitedError.make({\n implementation: browserQuickActionImplementation,\n reason: \"rate\",\n ...(retryAfterMillis(response) === undefined\n ? {}\n : { retryAfterMillis: retryAfterMillis(response) }),\n message: \"The screenshot Quick Action was rate limited\",\n });\n }\n if (!response.ok) {\n const body = response.body;\n\n if (body !== null) yield* cancelBody(body);\n const message = `The screenshot Quick Action answered HTTP ${response.status}`;\n\n return yield* response.status >= 500 ? protocolError(message) : navigationError(message);\n }\n const bytes = yield* readScreenshot(response, request);\n\n return PageScreenshotResult.make({\n implementation: browserQuickActionImplementation,\n mediaType: \"image/png\",\n bytes,\n });\n });\n\n/** Native Browser Run screenshot adapter. It retains PNG bytes only for the caller's result. */\nexport const browserQuickActionScreenshotLayer = (): Layer.Layer<\n PageScreenshot,\n never,\n BrowserQuickActionBrowserBinding\n> =>\n Layer.effect(\n PageScreenshot,\n Effect.map(BrowserQuickActionBrowserBinding, (browser) =>\n PageScreenshot.of({ capture: makeScreenshot(browser) }),\n ),\n );\n","/** Public CloudflareBrowser API. Implementation helpers remain private. */\nexport {\n BrowserQuickActionBrowserBinding,\n BrowserQuickActionRpcError,\n BrowserQuickActionWorkersAi,\n BrowserQuickActionWorkersAiPolicyError,\n browserQuickActionCaptureLayer,\n browserQuickActionWorkersAiCaptureLayer,\n browserQuickActionScreenshotLayer,\n CloudflareBrowser,\n type BrowserQuickActionCaptureOptions,\n type BrowserQuickActionClient,\n type BrowserQuickActionWorkersAiPolicy,\n type CloudflareBrowserOptions,\n} from \"./internal/browser-quick-action.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgDA,MAAa,mCAAmC,sBAAsB,KAAK;CACzE,WAAW;CACX,UAAU;AACZ,CAAC;;AA4BD,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA;CACE,QAAQ,OAAO,SAAS;EAAC;EAAc;EAAW;EAAY;EAAS;EAAU;CAAM,CAAC;CACxF,OAAO,OAAO,OAAO;AACvB,CACF,CAAC,CAAC,CAAC;;AAQH,IAAa,mCAAb,MAAa,yCAAyC,QAAQ,QAG5D,CAAC,CAAC,oEAAoE,CAAC,CAAC;CACxE,OAAO,MACL,SAC+C;EAC/C,MAAM,UAAU,QAAQ;EAExB,MAAM,SAAS,OAAO,GAAG,yCAAyC,CAAC,CAAC,WAClE,QACA,UACwD;GACxD,OAAO,OAAO,OAAO,W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uickActionScreenshotLayer, i as BrowserQuickActionWorkersAi, l as browserQuickActionWorkersAiCaptureLayer, n as BrowserQuickActionBrowserBinding, o as CloudflareBrowser, r as BrowserQuickActionRpcError, s as browserQuickActionCaptureLayer } from "./CloudflareBrowser-
|
|
1
|
+
import { a as BrowserQuickActionWorkersAiPolicyError, c as browserQuickActionScreenshotLayer, i as BrowserQuickActionWorkersAi, l as browserQuickActionWorkersAiCaptureLayer, n as BrowserQuickActionBrowserBinding, o as CloudflareBrowser, r as BrowserQuickActionRpcError, s as browserQuickActionCaptureLayer } from "./CloudflareBrowser-BSJRWmlW.mjs";
|
|
2
2
|
export { BrowserQuickActionBrowserBinding, BrowserQuickActionRpcError, BrowserQuickActionWorkersAi, BrowserQuickActionWorkersAiPolicyError, CloudflareBrowser, browserQuickActionCaptureLayer, browserQuickActionScreenshotLayer, browserQuickActionWorkersAiCaptureLayer };
|
|
@@ -4,7 +4,7 @@ import * as Memory from "@effect-agent/core/Memory";
|
|
|
4
4
|
import * as MemoryNamespace from "@effect-agent/core/MemoryNamespace";
|
|
5
5
|
import { MemoryRecallLimits } from "@effect-agent/core/MemoryReference";
|
|
6
6
|
import { MemoryAccess } from "@effect-agent/core/MemoryRevalidation";
|
|
7
|
-
import { MemoryDocument, MemoryMutationFailpoint, MemoryReader, MemoryStorageError, MemoryWrite, MemoryWriter } from "@effect-agent/core/MemoryStore";
|
|
7
|
+
import { MemoryDocument, MemoryKey, MemoryMutationFailpoint, MemoryReader, MemoryStorageError, MemoryWrite, MemoryWriter } from "@effect-agent/core/MemoryStore";
|
|
8
8
|
import { MemoryIndexSearch, SemanticMemoryProfile } from "@effect-agent/core/SemanticMemoryIndex";
|
|
9
9
|
import { SemanticCandidateLimits } from "@effect-agent/core/SemanticMemoryRevalidation";
|
|
10
10
|
import { DoMemoryStorageLimits } from "@effect-agent/storage-cloudflare/DoMemoryStore";
|
|
@@ -25,6 +25,7 @@ declare const memoryObjectName: (namespace: MemoryNamespace.Any) => string;
|
|
|
25
25
|
declare const CloudflareMemoryClient: {
|
|
26
26
|
/** Bind access and principal using the MemoryObjectNamespace supplied by the application. */
|
|
27
27
|
make: <Namespace extends MemoryNamespace.Any>(access: MemoryAccess<Namespace>, principal: string & import("effect/Brand").Brand<"@effect-agent/thread/Principal">, rpcLimits?: MemoryRpcLimits | undefined) => Effect.Effect<{
|
|
28
|
+
get: (key: MemoryKey<Namespace>) => Effect.Effect<MemoryDocument<Namespace> | null, import("@effect-agent/core/MemoryStore").MemoryConflict | import("@effect-agent/core/SemanticMemoryIndex").MemoryIndexError | import("@effect-agent/core/MemoryStore").MemoryMutationFailure | import("@effect-agent/core/MemoryStore").MemoryOperationConflict | import("@effect-agent/core/MemoryReference").MemoryRecallError | MemoryRpcError | MemoryStorageError | import("@effect-agent/core/MemoryStore").MemoryWithdrawn | import("@effect-agent/core/SemanticMemoryRevalidation").SemanticMemoryError, never>;
|
|
28
29
|
recall: (lookup: {
|
|
29
30
|
readonly _tag: "Found";
|
|
30
31
|
readonly passages: readonly import("@effect-agent/core/MemoryReference").MemoryPassage[];
|
|
@@ -69,6 +70,7 @@ declare const CloudflareMemoryClient: {
|
|
|
69
70
|
readonly principal: Principal;
|
|
70
71
|
readonly rpcLimits?: MemoryRpcLimits;
|
|
71
72
|
}) => Effect.Effect<{
|
|
73
|
+
get: (key: MemoryKey<Namespace>) => Effect.Effect<MemoryDocument<Namespace> | null, import("@effect-agent/core/MemoryStore").MemoryConflict | import("@effect-agent/core/SemanticMemoryIndex").MemoryIndexError | import("@effect-agent/core/MemoryStore").MemoryMutationFailure | import("@effect-agent/core/MemoryStore").MemoryOperationConflict | import("@effect-agent/core/MemoryReference").MemoryRecallError | MemoryRpcError | MemoryStorageError | import("@effect-agent/core/MemoryStore").MemoryWithdrawn | import("@effect-agent/core/SemanticMemoryRevalidation").SemanticMemoryError, never>;
|
|
72
74
|
recall: (lookup: {
|
|
73
75
|
readonly _tag: "Found";
|
|
74
76
|
readonly passages: readonly import("@effect-agent/core/MemoryReference").MemoryPassage[];
|
|
@@ -6,7 +6,7 @@ import * as MemoryNamespace from "@effect-agent/core/MemoryNamespace";
|
|
|
6
6
|
import { MemoryNamespaceAddress } from "@effect-agent/core/MemoryNamespace";
|
|
7
7
|
import { MemoryRecallLimits } from "@effect-agent/core/MemoryReference";
|
|
8
8
|
import { MemoryAccess } from "@effect-agent/core/MemoryRevalidation";
|
|
9
|
-
import { MemoryDocument, MemoryMutationFailpoint, MemoryStorageError, MemoryWriter } from "@effect-agent/core/MemoryStore";
|
|
9
|
+
import { MemoryDocument, MemoryKey, MemoryMutationFailpoint, MemoryStorageError, MemoryWriter } from "@effect-agent/core/MemoryStore";
|
|
10
10
|
import "@effect-agent/core/SemanticMemoryIndex";
|
|
11
11
|
import "@effect-agent/core/SemanticMemoryRevalidation";
|
|
12
12
|
import { defaultDoMemoryStorageLimits, doMemoryStoreLayerWithFailpoints } from "@effect-agent/storage-cloudflare/DoMemoryStore";
|
|
@@ -82,6 +82,32 @@ const makeMemoryClient = Effect.fn("CloudflareMemoryClient.make")(function* (acc
|
|
|
82
82
|
return yield* MemoryDocument.restore(access.namespace, response.document);
|
|
83
83
|
}).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));
|
|
84
84
|
});
|
|
85
|
+
/**
|
|
86
|
+
* Read one exact current document in one owner RPC. Null means absent; withdrawals return
|
|
87
|
+
* tombstones. Denial, unavailable storage and deadlines fail typed, never become absence.
|
|
88
|
+
* Reads begun after an acknowledged write observe it or a later revision. The owner checks
|
|
89
|
+
* exact-key authority and active document scopes; source-dependent provenance policy remains
|
|
90
|
+
* application-owned. No extraction, job draining, embedding, discovery or rendering occurs.
|
|
91
|
+
*/
|
|
92
|
+
const get = Effect.fn("CloudflareMemoryClient.get")(function* (key) {
|
|
93
|
+
const decodedKey = yield* Schema.decodeUnknownEffect(MemoryKey.Wire)(key).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
|
|
94
|
+
if (!MemoryNamespace.equals(decodedKey.namespace, bound.namespace)) return yield* MemoryRpcError.make({ reason: "denied" });
|
|
95
|
+
return yield* Effect.gen(function* () {
|
|
96
|
+
const response = yield* call({
|
|
97
|
+
_tag: "Get",
|
|
98
|
+
version: 1,
|
|
99
|
+
access: bound,
|
|
100
|
+
principal,
|
|
101
|
+
key: decodedKey,
|
|
102
|
+
deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis
|
|
103
|
+
});
|
|
104
|
+
if (response._tag !== "Document" || !MemoryNamespace.equals(response.key.namespace, bound.namespace) || response.key.id !== decodedKey.id) return yield* MemoryRpcError.make({ reason: "protocol" });
|
|
105
|
+
if (response.document === null) return null;
|
|
106
|
+
if (response.document.key.id !== decodedKey.id || response.document.source.id !== decodedKey.id || response.document._tag === "ActiveMemoryDocument" && !response.document.scopes.includes(bound.scope)) return yield* MemoryRpcError.make({ reason: "protocol" });
|
|
107
|
+
yield* encodeMemoryWire(MemoryDocument.Wire, response.document, validated.maxSourceBytes);
|
|
108
|
+
return yield* MemoryDocument.restore(access.namespace, response.document);
|
|
109
|
+
}).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));
|
|
110
|
+
});
|
|
85
111
|
const revalidateSemantic = Effect.fn("CloudflareMemoryClient.revalidateSemantic")(function* (found, profile, limits) {
|
|
86
112
|
return yield* Effect.gen(function* () {
|
|
87
113
|
const response = yield* call({
|
|
@@ -99,6 +125,7 @@ const makeMemoryClient = Effect.fn("CloudflareMemoryClient.make")(function* (acc
|
|
|
99
125
|
}).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));
|
|
100
126
|
});
|
|
101
127
|
return {
|
|
128
|
+
get,
|
|
102
129
|
recall: Effect.fn("CloudflareMemoryClient.recall")(function* (lookup, limits, estimateTokens) {
|
|
103
130
|
return yield* Memory.recall([{
|
|
104
131
|
id: "memory",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CloudflareMemory.mjs","names":["EffectCfDurableObject"],"sources":["../src/CloudflareMemory.ts"],"sourcesContent":["import * as Memory from \"@effect-agent/core/Memory\";\nimport * as MemoryNamespace from \"@effect-agent/core/MemoryNamespace\";\nimport { MemoryNamespaceAddress } from \"@effect-agent/core/MemoryNamespace\";\nimport { type MemoryLookup, MemoryRecallLimits } from \"@effect-agent/core/MemoryReference\";\nimport { MemoryAccess } from \"@effect-agent/core/MemoryRevalidation\";\nimport {\n type MemoryReader,\n type MemoryWrite,\n MemoryDocument,\n MemoryMutationFailpoint,\n MemoryStorageError,\n MemoryWriter,\n} from \"@effect-agent/core/MemoryStore\";\nimport {\n type MemoryIndexSearch,\n type SemanticMemoryProfile,\n} from \"@effect-agent/core/SemanticMemoryIndex\";\nimport { type SemanticCandidateLimits } from \"@effect-agent/core/SemanticMemoryRevalidation\";\nimport {\n type DoMemoryStorageLimits,\n defaultDoMemoryStorageLimits,\n doMemoryStoreLayerWithFailpoints,\n} from \"@effect-agent/storage-cloudflare/DoMemoryStore\";\nimport {\n type MemoryOwnerAuthorizer,\n decodeMemoryWire,\n defaultMemoryRpcLimits,\n encodeMemoryWire,\n handleMemoryOwnerRequest,\n MemoryOwnerIdentity,\n MemoryOwnerRequest,\n MemoryOwnerResponse,\n MemoryRpcError,\n MemoryRpcLimits,\n type MemoryOwnerFailure,\n} from \"@effect-agent/storage-cloudflare/MemoryProtocol\";\nimport { Principal } from \"@effect-agent/thread/SubmissionLedger\";\nimport { Clock, Context, Effect, Layer, Schema } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectState,\n type WorkerEnvironment,\n} from \"effect-cf\";\n\nexport interface MemoryObjectRpc extends Rpc.DurableObjectBranded {\n memory(encoded: string): Promise<string>;\n}\n\nexport class MemoryObjectNamespace extends Context.Service<\n MemoryObjectNamespace,\n {\n readonly namespace: DurableObjectNamespace<MemoryObjectRpc>;\n }\n>()(\"@effect-agent/platform-cloudflare/MemoryObjectNamespace\") {}\n\n/** Namespace version and identity are already canonicalized by MemoryNamespace. */\nexport const memoryObjectName = (namespace: MemoryNamespace.Any): string => namespace.address;\n\n/**\n * Effect-native, host-bound memory client. Recall revalidates the entire admitted lookup\n * in one RPC and renders it locally. No retries or per-source splitting occur here.\n * Interrupted callers stop waiting; the owner has its own deadline. A timed-out write\n * may have committed: reconcile by sending the identical operation ID and command.\n */\nconst makeMemoryClient = Effect.fn(\"CloudflareMemoryClient.make\")(function* <\n Namespace extends MemoryNamespace.Any,\n>(\n access: MemoryAccess<Namespace>,\n principal: Principal,\n rpcLimits: MemoryRpcLimits = defaultMemoryRpcLimits,\n) {\n const validated = yield* Schema.decodeUnknownEffect(MemoryRpcLimits)(rpcLimits).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n const bound = yield* Schema.decodeUnknownEffect(MemoryAccess.Wire)(access).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n principal = yield* Schema.decodeUnknownEffect(Principal)(principal).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n const { namespace } = yield* MemoryObjectNamespace;\n\n const call = Effect.fn(\"CloudflareMemoryClient.call\")(function* (request: MemoryOwnerRequest) {\n const decoded = yield* Schema.decodeUnknownEffect(MemoryOwnerRequest)(request).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n const encoded = yield* encodeMemoryWire(MemoryOwnerRequest, decoded, validated.maxRequestBytes);\n\n const raw = yield* Effect.tryPromise({\n try: () =>\n namespace.get(namespace.idFromName(memoryObjectName(bound.namespace))).memory(encoded),\n catch: () => MemoryRpcError.make({ reason: \"unavailable\" }),\n });\n\n const response = yield* decodeMemoryWire(MemoryOwnerResponse, raw, validated.maxResponseBytes);\n\n if (response._tag === \"Failed\") return yield* response.failure;\n if (\n !MemoryNamespace.equals(response.access.namespace, bound.namespace) ||\n response.access.scope !== bound.scope\n )\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response;\n });\n\n const withinDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>, timeoutMillis: number) =>\n effect.pipe(\n Effect.timeoutOrElse({\n duration: timeoutMillis,\n orElse: () => Effect.fail(MemoryRpcError.make({ reason: \"timeout\" })),\n }),\n );\n\n const revalidate = Effect.fn(\"CloudflareMemoryClient.revalidate\")(function* (\n lookup: MemoryLookup,\n limits: MemoryRecallLimits,\n ) {\n limits = yield* Schema.decodeUnknownEffect(MemoryRecallLimits)(limits).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n const timeoutMillis = Math.min(validated.timeoutMillis, limits.timeoutMillis);\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Revalidate\",\n version: 1,\n access: bound,\n principal,\n lookup,\n limits,\n deadlineMillis: (yield* Clock.currentTimeMillis) + timeoutMillis,\n });\n\n if (response._tag !== \"Lookup\") return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response.lookup;\n }).pipe((effect) => withinDeadline(effect, timeoutMillis));\n });\n\n const change = Effect.fn(\"CloudflareMemoryClient.change\")(function* (\n write: MemoryWrite<Namespace>,\n ) {\n if (!MemoryNamespace.equals(write.key.namespace, bound.namespace))\n return yield* MemoryRpcError.make({ reason: \"denied\" });\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Change\",\n version: 1,\n access: bound,\n principal,\n write,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (response._tag !== \"Changed\" || response.document.key.id !== write.key.id)\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return yield* MemoryDocument.restore(access.namespace, response.document);\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n const revalidateSemantic = Effect.fn(\"CloudflareMemoryClient.revalidateSemantic\")(function* (\n found: MemoryIndexSearch<Namespace>,\n profile: SemanticMemoryProfile,\n limits: SemanticCandidateLimits,\n ) {\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"RevalidateSemantic\",\n version: 1,\n access: bound,\n principal,\n found,\n profile,\n limits,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (response._tag !== \"Semantic\") return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response.result;\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n /**\n * Revalidate in one owner RPC, then render whole passages within the caller's budget.\n * The bound source is essential: unavailable/stale results and matches that cannot fit\n * fail instead of silently producing empty context. No-match remains successful.\n * The single outcome has sourceId \"memory\". No embedding or candidate search is performed.\n * Use revalidate with Memory.recall for multiple readers sharing one output budget.\n */\n const recall = Effect.fn(\"CloudflareMemoryClient.recall\")(function* (\n lookup: MemoryLookup,\n limits: MemoryRecallLimits,\n estimateTokens?: (text: string) => number,\n ) {\n return yield* Memory.recall(\n [{ id: \"memory\", essential: true, read: revalidate(lookup, limits) }],\n limits,\n estimateTokens,\n );\n });\n\n return { recall, revalidate, revalidateSemantic, change };\n});\n\nexport const CloudflareMemoryClient = {\n /** Bind access and principal using the MemoryObjectNamespace supplied by the application. */\n make: makeMemoryClient,\n /** Use a resolved Worker or Durable Object binding without manual service provisioning. */\n fromBinding: Effect.fn(\"CloudflareMemoryClient.fromBinding\")(function* <\n Namespace extends MemoryNamespace.Any,\n >(\n binding: DurableObjectNamespace<MemoryObjectRpc>,\n options: {\n readonly access: MemoryAccess<Namespace>;\n readonly principal: Principal;\n readonly rpcLimits?: MemoryRpcLimits;\n },\n ) {\n return yield* makeMemoryClient(options.access, options.principal, options.rpcLimits).pipe(\n Effect.provideService(MemoryObjectNamespace, { namespace: binding }),\n );\n }),\n};\n\n/**\n * Optional activity-processor destination. Keeps domain write errors intact; transport,\n * authorization and deadline failures become the existing MemoryStorageError contract.\n * Receipts remain authoritative, including after caller interruption or lost replies.\n */\nexport const cloudflareMemoryWriterLayer = (\n access: MemoryAccess,\n principal: Principal,\n limits: MemoryRpcLimits = defaultMemoryRpcLimits,\n) =>\n Layer.effect(\n MemoryWriter,\n Effect.gen(function* () {\n const client = yield* CloudflareMemoryClient.make(access, principal, limits);\n\n return MemoryWriter.fromAdapter({\n change: (write) =>\n client.change(write).pipe(\n Effect.catchTag(\"MemoryRpcError\", (error) =>\n Effect.fail(\n MemoryStorageError.make({\n operation: `memory RPC ${error.reason}`,\n reason:\n error.reason === \"unavailable\" || error.reason === \"timeout\"\n ? \"unavailable\"\n : \"invalid-input\",\n }),\n ),\n ),\n Effect.catchTag([\"MemoryRecallError\", \"MemoryIndexError\", \"SemanticMemoryError\"], () =>\n Effect.fail(\n MemoryStorageError.make({ operation: \"memory RPC response\", reason: \"corrupt\" }),\n ),\n ),\n ),\n });\n }),\n );\n\ntype OwnerServices = MemoryReader | MemoryWriter | MemoryOwnerAuthorizer | MemoryOwnerIdentity;\n\nexport interface MemoryObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, OwnerServices>\n> {\n memory(encoded: string): Promise<string>;\n}\n\nexport interface MemoryObjectClass {\n new (ctx: globalThis.DurableObjectState, env: Cloudflare.Env): MemoryObjectInstance;\n}\n\n/**\n * Dedicated SQLite owner, independent of Thread lifetimes. The host binds authorization\n * after restoring its namespace definition from MemoryOwnerIdentity. Do not retain\n * cleanup-scoped resources in the host Layer; it lives for the DO incarnation.\n */\nconst makeMemoryObject = <E>(\n host: Layer.Layer<\n MemoryOwnerAuthorizer,\n E,\n MemoryOwnerIdentity | DurableObjectState.DurableObjectState | WorkerEnvironment\n >,\n options: {\n readonly storageLimits?: DoMemoryStorageLimits;\n readonly rpcLimits?: MemoryRpcLimits;\n readonly failpoints?: Layer.Layer<\n MemoryMutationFailpoint,\n never,\n DurableObjectState.DurableObjectState\n >;\n } = {},\n): MemoryObjectClass => {\n const identity = Layer.effect(\n MemoryOwnerIdentity,\n Effect.gen(function* () {\n const state = yield* DurableObjectState.DurableObjectState;\n\n const address = yield* Schema.decodeUnknownEffect(MemoryNamespaceAddress)(\n state.raw.id.name,\n ).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: \"denied\" })));\n\n return { namespace: MemoryNamespace.Any.make({ address }) };\n }),\n );\n\n const store = Layer.unwrap(\n Effect.map(DurableObjectState.DurableObjectState, (state) =>\n doMemoryStoreLayerWithFailpoints(\n state.raw.storage,\n options.storageLimits ?? defaultDoMemoryStorageLimits,\n ),\n ),\n ).pipe(Layer.provide(options.failpoints ?? MemoryMutationFailpoint.layer));\n\n const application = Layer.merge(store, host).pipe(Layer.provideMerge(identity));\n\n const runtime: Layer.Layer<\n OwnerServices,\n E | MemoryOwnerFailure,\n DurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* DurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n yield* Schema.decodeUnknownEffect(MemoryRpcLimits)(\n options.rpcLimits ?? defaultMemoryRpcLimits,\n ).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })));\n\n return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = { memory: (encoded: string) => handleMemoryOwnerRequest(encoded, options.rpcLimits) };\n\n return EffectCfDurableObject.make<\n OwnerServices,\n E | MemoryOwnerFailure,\n never,\n never,\n typeof rpc\n >(runtime, { rpc });\n};\n\nexport const MemoryObject = {\n /** Build the SQLite Durable Object class with the application's owner authorization Layer. */\n make: makeMemoryObject,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,wBAAb,cAA2C,QAAQ,QAKjD,CAAC,CAAC,yDAAyD,CAAC,CAAC,CAAC;;AAGhE,MAAa,oBAAoB,cAA2C,UAAU;;;;;;;AAQtF,MAAM,mBAAmB,OAAO,GAAG,6BAA6B,CAAC,CAAC,WAGhE,QACA,WACA,YAA6B,wBAC7B;CACA,MAAM,YAAY,OAAO,OAAO,oBAAoB,eAAe,CAAC,CAAC,SAAS,CAAC,CAAC,KAC9E,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAAW,CAAC,CAAC,C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yBAAyB,SAAS,QAAQ,SAAS,EAQ/E,EAAE,CAAC;AACpB;AAEA,MAAa,eAAe;;AAE1B,MAAM,iBACR"}
|
|
1
|
+
{"version":3,"file":"CloudflareMemory.mjs","names":["EffectCfDurableObject"],"sources":["../src/CloudflareMemory.ts"],"sourcesContent":["import * as Memory from \"@effect-agent/core/Memory\";\nimport * as MemoryNamespace from \"@effect-agent/core/MemoryNamespace\";\nimport { MemoryNamespaceAddress } from \"@effect-agent/core/MemoryNamespace\";\nimport { type MemoryLookup, MemoryRecallLimits } from \"@effect-agent/core/MemoryReference\";\nimport { MemoryAccess } from \"@effect-agent/core/MemoryRevalidation\";\nimport {\n type MemoryReader,\n type MemoryWrite,\n MemoryKey,\n MemoryDocument,\n MemoryMutationFailpoint,\n MemoryStorageError,\n MemoryWriter,\n} from \"@effect-agent/core/MemoryStore\";\nimport {\n type MemoryIndexSearch,\n type SemanticMemoryProfile,\n} from \"@effect-agent/core/SemanticMemoryIndex\";\nimport { type SemanticCandidateLimits } from \"@effect-agent/core/SemanticMemoryRevalidation\";\nimport {\n type DoMemoryStorageLimits,\n defaultDoMemoryStorageLimits,\n doMemoryStoreLayerWithFailpoints,\n} from \"@effect-agent/storage-cloudflare/DoMemoryStore\";\nimport {\n type MemoryOwnerAuthorizer,\n decodeMemoryWire,\n defaultMemoryRpcLimits,\n encodeMemoryWire,\n handleMemoryOwnerRequest,\n MemoryOwnerIdentity,\n MemoryOwnerRequest,\n MemoryOwnerResponse,\n MemoryRpcError,\n MemoryRpcLimits,\n type MemoryOwnerFailure,\n} from \"@effect-agent/storage-cloudflare/MemoryProtocol\";\nimport { Principal } from \"@effect-agent/thread/SubmissionLedger\";\nimport { Clock, Context, Effect, Layer, Schema } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectState,\n type WorkerEnvironment,\n} from \"effect-cf\";\n\nexport interface MemoryObjectRpc extends Rpc.DurableObjectBranded {\n memory(encoded: string): Promise<string>;\n}\n\nexport class MemoryObjectNamespace extends Context.Service<\n MemoryObjectNamespace,\n {\n readonly namespace: DurableObjectNamespace<MemoryObjectRpc>;\n }\n>()(\"@effect-agent/platform-cloudflare/MemoryObjectNamespace\") {}\n\n/** Namespace version and identity are already canonicalized by MemoryNamespace. */\nexport const memoryObjectName = (namespace: MemoryNamespace.Any): string => namespace.address;\n\n/**\n * Effect-native, host-bound memory client. Recall revalidates the entire admitted lookup\n * in one RPC and renders it locally. No retries or per-source splitting occur here.\n * Interrupted callers stop waiting; the owner has its own deadline. A timed-out write\n * may have committed: reconcile by sending the identical operation ID and command.\n */\nconst makeMemoryClient = Effect.fn(\"CloudflareMemoryClient.make\")(function* <\n Namespace extends MemoryNamespace.Any,\n>(\n access: MemoryAccess<Namespace>,\n principal: Principal,\n rpcLimits: MemoryRpcLimits = defaultMemoryRpcLimits,\n) {\n const validated = yield* Schema.decodeUnknownEffect(MemoryRpcLimits)(rpcLimits).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n const bound = yield* Schema.decodeUnknownEffect(MemoryAccess.Wire)(access).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n principal = yield* Schema.decodeUnknownEffect(Principal)(principal).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n const { namespace } = yield* MemoryObjectNamespace;\n\n const call = Effect.fn(\"CloudflareMemoryClient.call\")(function* (request: MemoryOwnerRequest) {\n const decoded = yield* Schema.decodeUnknownEffect(MemoryOwnerRequest)(request).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n const encoded = yield* encodeMemoryWire(MemoryOwnerRequest, decoded, validated.maxRequestBytes);\n\n const raw = yield* Effect.tryPromise({\n try: () =>\n namespace.get(namespace.idFromName(memoryObjectName(bound.namespace))).memory(encoded),\n catch: () => MemoryRpcError.make({ reason: \"unavailable\" }),\n });\n\n const response = yield* decodeMemoryWire(MemoryOwnerResponse, raw, validated.maxResponseBytes);\n\n if (response._tag === \"Failed\") return yield* response.failure;\n if (\n !MemoryNamespace.equals(response.access.namespace, bound.namespace) ||\n response.access.scope !== bound.scope\n )\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response;\n });\n\n const withinDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>, timeoutMillis: number) =>\n effect.pipe(\n Effect.timeoutOrElse({\n duration: timeoutMillis,\n orElse: () => Effect.fail(MemoryRpcError.make({ reason: \"timeout\" })),\n }),\n );\n\n const revalidate = Effect.fn(\"CloudflareMemoryClient.revalidate\")(function* (\n lookup: MemoryLookup,\n limits: MemoryRecallLimits,\n ) {\n limits = yield* Schema.decodeUnknownEffect(MemoryRecallLimits)(limits).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n const timeoutMillis = Math.min(validated.timeoutMillis, limits.timeoutMillis);\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Revalidate\",\n version: 1,\n access: bound,\n principal,\n lookup,\n limits,\n deadlineMillis: (yield* Clock.currentTimeMillis) + timeoutMillis,\n });\n\n if (response._tag !== \"Lookup\") return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response.lookup;\n }).pipe((effect) => withinDeadline(effect, timeoutMillis));\n });\n\n const change = Effect.fn(\"CloudflareMemoryClient.change\")(function* (\n write: MemoryWrite<Namespace>,\n ) {\n if (!MemoryNamespace.equals(write.key.namespace, bound.namespace))\n return yield* MemoryRpcError.make({ reason: \"denied\" });\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Change\",\n version: 1,\n access: bound,\n principal,\n write,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (response._tag !== \"Changed\" || response.document.key.id !== write.key.id)\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return yield* MemoryDocument.restore(access.namespace, response.document);\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n /**\n * Read one exact current document in one owner RPC. Null means absent; withdrawals return\n * tombstones. Denial, unavailable storage and deadlines fail typed, never become absence.\n * Reads begun after an acknowledged write observe it or a later revision. The owner checks\n * exact-key authority and active document scopes; source-dependent provenance policy remains\n * application-owned. No extraction, job draining, embedding, discovery or rendering occurs.\n */\n const get = Effect.fn(\"CloudflareMemoryClient.get\")(function* (key: MemoryKey<Namespace>) {\n const decodedKey = yield* Schema.decodeUnknownEffect(MemoryKey.Wire)(key).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n if (!MemoryNamespace.equals(decodedKey.namespace, bound.namespace))\n return yield* MemoryRpcError.make({ reason: \"denied\" });\n\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"Get\",\n version: 1,\n access: bound,\n principal,\n key: decodedKey,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (\n response._tag !== \"Document\" ||\n !MemoryNamespace.equals(response.key.namespace, bound.namespace) ||\n response.key.id !== decodedKey.id\n )\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n if (response.document === null) return null;\n if (\n response.document.key.id !== decodedKey.id ||\n response.document.source.id !== decodedKey.id ||\n (response.document._tag === \"ActiveMemoryDocument\" &&\n !response.document.scopes.includes(bound.scope))\n )\n return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n yield* encodeMemoryWire(MemoryDocument.Wire, response.document, validated.maxSourceBytes);\n\n return yield* MemoryDocument.restore(access.namespace, response.document);\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n const revalidateSemantic = Effect.fn(\"CloudflareMemoryClient.revalidateSemantic\")(function* (\n found: MemoryIndexSearch<Namespace>,\n profile: SemanticMemoryProfile,\n limits: SemanticCandidateLimits,\n ) {\n return yield* Effect.gen(function* () {\n const response = yield* call({\n _tag: \"RevalidateSemantic\",\n version: 1,\n access: bound,\n principal,\n found,\n profile,\n limits,\n deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,\n });\n\n if (response._tag !== \"Semantic\") return yield* MemoryRpcError.make({ reason: \"protocol\" });\n\n return response.result;\n }).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));\n });\n\n /**\n * Revalidate in one owner RPC, then render whole passages within the caller's budget.\n * The bound source is essential: unavailable/stale results and matches that cannot fit\n * fail instead of silently producing empty context. No-match remains successful.\n * The single outcome has sourceId \"memory\". No embedding or candidate search is performed.\n * Use revalidate with Memory.recall for multiple readers sharing one output budget.\n */\n const recall = Effect.fn(\"CloudflareMemoryClient.recall\")(function* (\n lookup: MemoryLookup,\n limits: MemoryRecallLimits,\n estimateTokens?: (text: string) => number,\n ) {\n return yield* Memory.recall(\n [{ id: \"memory\", essential: true, read: revalidate(lookup, limits) }],\n limits,\n estimateTokens,\n );\n });\n\n return { get, recall, revalidate, revalidateSemantic, change };\n});\n\nexport const CloudflareMemoryClient = {\n /** Bind access and principal using the MemoryObjectNamespace supplied by the application. */\n make: makeMemoryClient,\n /** Use a resolved Worker or Durable Object binding without manual service provisioning. */\n fromBinding: Effect.fn(\"CloudflareMemoryClient.fromBinding\")(function* <\n Namespace extends MemoryNamespace.Any,\n >(\n binding: DurableObjectNamespace<MemoryObjectRpc>,\n options: {\n readonly access: MemoryAccess<Namespace>;\n readonly principal: Principal;\n readonly rpcLimits?: MemoryRpcLimits;\n },\n ) {\n return yield* makeMemoryClient(options.access, options.principal, options.rpcLimits).pipe(\n Effect.provideService(MemoryObjectNamespace, { namespace: binding }),\n );\n }),\n};\n\n/**\n * Optional activity-processor destination. Keeps domain write errors intact; transport,\n * authorization and deadline failures become the existing MemoryStorageError contract.\n * Receipts remain authoritative, including after caller interruption or lost replies.\n */\nexport const cloudflareMemoryWriterLayer = (\n access: MemoryAccess,\n principal: Principal,\n limits: MemoryRpcLimits = defaultMemoryRpcLimits,\n) =>\n Layer.effect(\n MemoryWriter,\n Effect.gen(function* () {\n const client = yield* CloudflareMemoryClient.make(access, principal, limits);\n\n return MemoryWriter.fromAdapter({\n change: (write) =>\n client.change(write).pipe(\n Effect.catchTag(\"MemoryRpcError\", (error) =>\n Effect.fail(\n MemoryStorageError.make({\n operation: `memory RPC ${error.reason}`,\n reason:\n error.reason === \"unavailable\" || error.reason === \"timeout\"\n ? \"unavailable\"\n : \"invalid-input\",\n }),\n ),\n ),\n Effect.catchTag([\"MemoryRecallError\", \"MemoryIndexError\", \"SemanticMemoryError\"], () =>\n Effect.fail(\n MemoryStorageError.make({ operation: \"memory RPC response\", reason: \"corrupt\" }),\n ),\n ),\n ),\n });\n }),\n );\n\ntype OwnerServices = MemoryReader | MemoryWriter | MemoryOwnerAuthorizer | MemoryOwnerIdentity;\n\nexport interface MemoryObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, OwnerServices>\n> {\n memory(encoded: string): Promise<string>;\n}\n\nexport interface MemoryObjectClass {\n new (ctx: globalThis.DurableObjectState, env: Cloudflare.Env): MemoryObjectInstance;\n}\n\n/**\n * Dedicated SQLite owner, independent of Thread lifetimes. The host binds authorization\n * after restoring its namespace definition from MemoryOwnerIdentity. Do not retain\n * cleanup-scoped resources in the host Layer; it lives for the DO incarnation.\n */\nconst makeMemoryObject = <E>(\n host: Layer.Layer<\n MemoryOwnerAuthorizer,\n E,\n MemoryOwnerIdentity | DurableObjectState.DurableObjectState | WorkerEnvironment\n >,\n options: {\n readonly storageLimits?: DoMemoryStorageLimits;\n readonly rpcLimits?: MemoryRpcLimits;\n readonly failpoints?: Layer.Layer<\n MemoryMutationFailpoint,\n never,\n DurableObjectState.DurableObjectState\n >;\n } = {},\n): MemoryObjectClass => {\n const identity = Layer.effect(\n MemoryOwnerIdentity,\n Effect.gen(function* () {\n const state = yield* DurableObjectState.DurableObjectState;\n\n const address = yield* Schema.decodeUnknownEffect(MemoryNamespaceAddress)(\n state.raw.id.name,\n ).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: \"denied\" })));\n\n return { namespace: MemoryNamespace.Any.make({ address }) };\n }),\n );\n\n const store = Layer.unwrap(\n Effect.map(DurableObjectState.DurableObjectState, (state) =>\n doMemoryStoreLayerWithFailpoints(\n state.raw.storage,\n options.storageLimits ?? defaultDoMemoryStorageLimits,\n ),\n ),\n ).pipe(Layer.provide(options.failpoints ?? MemoryMutationFailpoint.layer));\n\n const application = Layer.merge(store, host).pipe(Layer.provideMerge(identity));\n\n const runtime: Layer.Layer<\n OwnerServices,\n E | MemoryOwnerFailure,\n DurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* DurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n yield* Schema.decodeUnknownEffect(MemoryRpcLimits)(\n options.rpcLimits ?? defaultMemoryRpcLimits,\n ).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })));\n\n return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = { memory: (encoded: string) => handleMemoryOwnerRequest(encoded, options.rpcLimits) };\n\n return EffectCfDurableObject.make<\n OwnerServices,\n E | MemoryOwnerFailure,\n never,\n never,\n typeof rpc\n >(runtime, { rpc });\n};\n\nexport const MemoryObject = {\n /** Build the SQLite Durable Object class with the application's owner authorization Layer. */\n make: makeMemoryObject,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,wBAAb,cAA2C,QAAQ,QAKjD,CAAC,CAAC,yDAAyD,CAAC,CAAC,CAAC;;AAGhE,MAAa,oBAAoB,cAA2C,UAAU;;;;;;;AAQtF,MAAM,mBAAmB,OAAO,GAAG,6BAA6B,CAAC,CAAC,WAGhE,QACA,WACA,YAA6B,wBAC7B;CACA,MAAM,YAAY,OAAO,OAAO,oBAAoB,eAAe,CAAC,CAAC,SAAS,CAAC,CAAC,KAC9E,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAAW,CAAC,CAAC,CACnE;CAEA,MAAM,QAAQ,OAAO,OAAO,oBAAoB,aAAa,I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
340
340
|
readonly author: string;
|
|
341
341
|
readonly reason: string;
|
|
342
342
|
readonly resolution: {
|
|
343
|
+
readonly _tag: "SafeToRetry";
|
|
344
|
+
} | {
|
|
343
345
|
readonly _tag: "CompletedWithResult";
|
|
344
346
|
readonly result: Schema.Json;
|
|
345
347
|
readonly isFailure: boolean;
|
|
346
348
|
} | {
|
|
347
349
|
readonly _tag: "NeverHappened";
|
|
348
|
-
} | {
|
|
349
|
-
readonly _tag: "SafeToRetry";
|
|
350
350
|
} | {
|
|
351
351
|
readonly _tag: "AbortSubmission";
|
|
352
352
|
};
|
|
@@ -482,6 +482,11 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
|
|
|
482
482
|
readonly createdAt: string;
|
|
483
483
|
readonly deploymentId: string;
|
|
484
484
|
readonly payload: {
|
|
485
|
+
readonly _tag: "AbortRequested";
|
|
486
|
+
readonly submissionId: string;
|
|
487
|
+
readonly author: string;
|
|
488
|
+
readonly reason: string;
|
|
489
|
+
} | {
|
|
485
490
|
readonly _tag: "ThreadCreated";
|
|
486
491
|
readonly agentId: string;
|
|
487
492
|
readonly definitions: {
|
|
@@ -656,11 +661,6 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
|
|
|
656
661
|
readonly runDisposition?: Schema.Json | undefined;
|
|
657
662
|
readonly finishReason?: "budget-exhausted" | undefined;
|
|
658
663
|
readonly exhausted?: "tokens" | "tool-calls" | "turns" | undefined;
|
|
659
|
-
} | {
|
|
660
|
-
readonly _tag: "AbortRequested";
|
|
661
|
-
readonly submissionId: string;
|
|
662
|
-
readonly author: string;
|
|
663
|
-
readonly reason: string;
|
|
664
664
|
} | {
|
|
665
665
|
readonly _tag: "SubmissionSettled";
|
|
666
666
|
readonly submissionId: string;
|
|
@@ -806,6 +806,24 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
|
|
|
806
806
|
readonly childResultDigest: string;
|
|
807
807
|
readonly projectedResultDigest: string;
|
|
808
808
|
readonly usageSummary: Schema.Json;
|
|
809
|
+
readonly usage?: {
|
|
810
|
+
readonly modelCalls: number;
|
|
811
|
+
readonly inputTokens: number;
|
|
812
|
+
readonly outputTokens: number;
|
|
813
|
+
readonly costMicrousd: number;
|
|
814
|
+
readonly usageStatus?: "complete" | "partial" | "unknown" | undefined;
|
|
815
|
+
readonly pricingStatus?: "complete" | "partial" | "unknown" | undefined;
|
|
816
|
+
readonly unobservedModelCalls?: number | undefined;
|
|
817
|
+
} | undefined;
|
|
818
|
+
readonly delegatedUsage?: {
|
|
819
|
+
readonly modelCalls: number;
|
|
820
|
+
readonly inputTokens: number;
|
|
821
|
+
readonly outputTokens: number;
|
|
822
|
+
readonly costMicrousd: number;
|
|
823
|
+
readonly usageStatus?: "complete" | "partial" | "unknown" | undefined;
|
|
824
|
+
readonly pricingStatus?: "complete" | "partial" | "unknown" | undefined;
|
|
825
|
+
readonly unobservedModelCalls?: number | undefined;
|
|
826
|
+
} | undefined;
|
|
809
827
|
readonly reservationId: string;
|
|
810
828
|
readonly finalAccounting: Schema.Json;
|
|
811
829
|
} | {
|
|
@@ -1104,13 +1122,13 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
|
|
|
1104
1122
|
readonly author: string;
|
|
1105
1123
|
readonly reason: string;
|
|
1106
1124
|
readonly resolution: {
|
|
1125
|
+
readonly _tag: "SafeToRetry";
|
|
1126
|
+
} | {
|
|
1107
1127
|
readonly _tag: "CompletedWithResult";
|
|
1108
1128
|
readonly result: Schema.Json;
|
|
1109
1129
|
readonly isFailure: boolean;
|
|
1110
1130
|
} | {
|
|
1111
1131
|
readonly _tag: "NeverHappened";
|
|
1112
|
-
} | {
|
|
1113
|
-
readonly _tag: "SafeToRetry";
|
|
1114
1132
|
} | {
|
|
1115
1133
|
readonly _tag: "AbortSubmission";
|
|
1116
1134
|
};
|
|
@@ -1122,13 +1140,6 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
|
|
|
1122
1140
|
readonly failure: {
|
|
1123
1141
|
readonly _tag: "HostProtocolError";
|
|
1124
1142
|
readonly message: string;
|
|
1125
|
-
} | {
|
|
1126
|
-
readonly _tag: "AgentInputError";
|
|
1127
|
-
readonly message: string;
|
|
1128
|
-
} | {
|
|
1129
|
-
readonly _tag: "DigestError";
|
|
1130
|
-
readonly message: string;
|
|
1131
|
-
readonly cause?: Schema.Json | undefined;
|
|
1132
1143
|
} | {
|
|
1133
1144
|
readonly _tag: "AdmissionConflict";
|
|
1134
1145
|
readonly threadId: string;
|
|
@@ -1144,15 +1155,6 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
|
|
|
1144
1155
|
readonly _tag: "SettlementConflict";
|
|
1145
1156
|
readonly submissionId: string;
|
|
1146
1157
|
readonly existingOutcome: "aborted" | "completed" | "failed";
|
|
1147
|
-
} | {
|
|
1148
|
-
readonly _tag: "ApprovalConflict";
|
|
1149
|
-
readonly submissionId: string;
|
|
1150
|
-
readonly toolCallId: string;
|
|
1151
|
-
readonly existingDecision: "approved" | "denied";
|
|
1152
|
-
} | {
|
|
1153
|
-
readonly _tag: "UnknownResolutionConflict";
|
|
1154
|
-
readonly submissionId: string;
|
|
1155
|
-
readonly toolCallId: string;
|
|
1156
1158
|
} | {
|
|
1157
1159
|
readonly _tag: "JoinedToHost";
|
|
1158
1160
|
readonly submissionId: string;
|
|
@@ -1182,9 +1184,25 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
|
|
|
1182
1184
|
readonly threadId: string;
|
|
1183
1185
|
readonly actualEpoch: number;
|
|
1184
1186
|
readonly attemptedEpoch: number;
|
|
1187
|
+
} | {
|
|
1188
|
+
readonly _tag: "AgentInputError";
|
|
1189
|
+
readonly message: string;
|
|
1190
|
+
} | {
|
|
1191
|
+
readonly _tag: "DigestError";
|
|
1192
|
+
readonly message: string;
|
|
1193
|
+
readonly cause?: Schema.Json | undefined;
|
|
1194
|
+
} | {
|
|
1195
|
+
readonly _tag: "ApprovalConflict";
|
|
1196
|
+
readonly submissionId: string;
|
|
1197
|
+
readonly toolCallId: string;
|
|
1198
|
+
readonly existingDecision: "approved" | "denied";
|
|
1199
|
+
} | {
|
|
1200
|
+
readonly _tag: "UnknownResolutionConflict";
|
|
1201
|
+
readonly submissionId: string;
|
|
1202
|
+
readonly toolCallId: string;
|
|
1185
1203
|
} | {
|
|
1186
1204
|
readonly _tag: "DurableRuntimeFailpointError";
|
|
1187
|
-
readonly location: "abort:after-intent" | "approval:after-request-append" | "approval:after-suspend" | "checkpoint:after-save" | "checkpoint:before-save" | "claim:after-claim" | "compaction:after-canonical-append" | "compaction:before-canonical-append" | "input:after-canonical-append" | "join:after-canonical-append" | "join:after-claim" | "policy:after-reservation-append" | "policy:before-reservation-append" | "resolve:after-intent" | "run:after-start-append" | "run:before-start-append" | "step:after-step-append" | "subagent:after-admit" | "subagent:after-child-abort-intent" | "subagent:after-child-ready" | "subagent:after-join-append" | "subagent:after-release" | "subagent:after-release-pending" | "subagent:after-request-append" | "subagent:after-reserve" | "subagent:after-sibling-settle" | "subagent:after-start-append" | "subagent:after-suspend" | "submit:after-admit" | "submit:after-materialize" | "terminalize:after-canonical-append" | "terminalize:after-reserve" | "tools:after-prepared-append" | "tools:before-prepared-append" | "turn:after-canonical-append" | "turn:after-response-append" | "turn:after-results-append" | "worker:after-completion-append" | "worker:after-origin-append" | "worker:after-report-append" | "worker:after-report-delivery" | "worker:after-source-append" | "worker:after-subtree-append" | "worker:before-completion-append" | "worker:before-origin-append" | "worker:before-report-append" | "worker:before-report-delivery" | "worker:before-source-append" | "worker:before-subtree-append";
|
|
1205
|
+
readonly location: "abort:after-intent" | "approval:after-request-append" | "approval:after-suspend" | "checkpoint:after-save" | "checkpoint:before-save" | "claim:after-claim" | "compaction:after-canonical-append" | "compaction:before-canonical-append" | "input:after-canonical-append" | "join:after-canonical-append" | "join:after-claim" | "policy:after-reservation-append" | "policy:before-reservation-append" | "resolve:after-intent" | "run:after-start-append" | "run:before-start-append" | "step:after-step-append" | "subagent:after-admit" | "subagent:after-child-abort-intent" | "subagent:after-child-ready" | "subagent:after-join-append" | "subagent:after-release" | "subagent:after-release-pending" | "subagent:after-request-append" | "subagent:after-reserve" | "subagent:after-sibling-settle" | "subagent:after-start-append" | "subagent:after-suspend" | "subagent:before-join-append" | "submit:after-admit" | "submit:after-materialize" | "terminalize:after-canonical-append" | "terminalize:after-reserve" | "tools:after-prepared-append" | "tools:before-prepared-append" | "turn:after-canonical-append" | "turn:after-response-append" | "turn:after-results-append" | "worker:after-completion-append" | "worker:after-origin-append" | "worker:after-report-append" | "worker:after-report-delivery" | "worker:after-source-append" | "worker:after-subtree-append" | "worker:before-completion-append" | "worker:before-origin-append" | "worker:before-report-append" | "worker:before-report-delivery" | "worker:before-source-append" | "worker:before-subtree-append";
|
|
1188
1206
|
} | {
|
|
1189
1207
|
readonly _tag: "AdmissionLimitExceeded";
|
|
1190
1208
|
readonly limit: "database-bytes" | "input-bytes" | "queue-depth";
|
|
@@ -672,38 +672,14 @@ declare const encodeAdminResponse: (input: AdminFailed | ExplainedRecovery | Obl
|
|
|
672
672
|
readonly reason: "occupied" | "refused" | "unavailable";
|
|
673
673
|
readonly code: string;
|
|
674
674
|
} | {
|
|
675
|
-
readonly _tag: "
|
|
676
|
-
readonly operation: "abort" | "awaitSettlement" | "explain" | "observe" | "resolveApproval" | "resolveUnknown" | "retry" | "scanObligations" | "verify" | "wake";
|
|
677
|
-
readonly reason: string;
|
|
678
|
-
readonly threadId?: string | undefined;
|
|
679
|
-
readonly submissionId?: string | undefined;
|
|
680
|
-
} | {
|
|
681
|
-
readonly _tag: "RetryRefused";
|
|
675
|
+
readonly _tag: "SettlementConflict";
|
|
682
676
|
readonly submissionId: string;
|
|
683
|
-
readonly
|
|
684
|
-
readonly decisionTag: string;
|
|
685
|
-
readonly message: string;
|
|
677
|
+
readonly existingOutcome: "aborted" | "completed" | "failed";
|
|
686
678
|
} | {
|
|
687
679
|
readonly _tag: "LedgerError";
|
|
688
680
|
readonly operation: string;
|
|
689
681
|
readonly message: string;
|
|
690
682
|
readonly cause?: Schema.Json | undefined;
|
|
691
|
-
} | {
|
|
692
|
-
readonly _tag: "RunJournalError";
|
|
693
|
-
readonly message: string;
|
|
694
|
-
readonly cause?: Schema.Json | undefined;
|
|
695
|
-
} | {
|
|
696
|
-
readonly _tag: "DigestError";
|
|
697
|
-
readonly message: string;
|
|
698
|
-
readonly cause?: Schema.Json | undefined;
|
|
699
|
-
} | {
|
|
700
|
-
readonly _tag: "OwnershipLost";
|
|
701
|
-
readonly submissionId: string;
|
|
702
|
-
readonly actualEpoch: number;
|
|
703
|
-
} | {
|
|
704
|
-
readonly _tag: "SettlementConflict";
|
|
705
|
-
readonly submissionId: string;
|
|
706
|
-
readonly existingOutcome: "aborted" | "completed" | "failed";
|
|
707
683
|
} | {
|
|
708
684
|
readonly _tag: "ThreadStoreError";
|
|
709
685
|
readonly operation: string;
|
|
@@ -724,9 +700,33 @@ declare const encodeAdminResponse: (input: AdminFailed | ExplainedRecovery | Obl
|
|
|
724
700
|
readonly threadId: string;
|
|
725
701
|
readonly actualEpoch: number;
|
|
726
702
|
readonly attemptedEpoch: number;
|
|
703
|
+
} | {
|
|
704
|
+
readonly _tag: "OperationDenied";
|
|
705
|
+
readonly operation: "abort" | "awaitSettlement" | "explain" | "observe" | "resolveApproval" | "resolveUnknown" | "retry" | "scanObligations" | "verify" | "wake";
|
|
706
|
+
readonly reason: string;
|
|
707
|
+
readonly threadId?: string | undefined;
|
|
708
|
+
readonly submissionId?: string | undefined;
|
|
709
|
+
} | {
|
|
710
|
+
readonly _tag: "RetryRefused";
|
|
711
|
+
readonly submissionId: string;
|
|
712
|
+
readonly refusal: "await-approval-decision" | "await-unknown-resolution" | "settled";
|
|
713
|
+
readonly decisionTag: string;
|
|
714
|
+
readonly message: string;
|
|
715
|
+
} | {
|
|
716
|
+
readonly _tag: "RunJournalError";
|
|
717
|
+
readonly message: string;
|
|
718
|
+
readonly cause?: Schema.Json | undefined;
|
|
719
|
+
} | {
|
|
720
|
+
readonly _tag: "DigestError";
|
|
721
|
+
readonly message: string;
|
|
722
|
+
readonly cause?: Schema.Json | undefined;
|
|
723
|
+
} | {
|
|
724
|
+
readonly _tag: "OwnershipLost";
|
|
725
|
+
readonly submissionId: string;
|
|
726
|
+
readonly actualEpoch: number;
|
|
727
727
|
} | {
|
|
728
728
|
readonly _tag: "DurableRuntimeFailpointError";
|
|
729
|
-
readonly location: "abort:after-intent" | "approval:after-request-append" | "approval:after-suspend" | "checkpoint:after-save" | "checkpoint:before-save" | "claim:after-claim" | "compaction:after-canonical-append" | "compaction:before-canonical-append" | "input:after-canonical-append" | "join:after-canonical-append" | "join:after-claim" | "policy:after-reservation-append" | "policy:before-reservation-append" | "resolve:after-intent" | "run:after-start-append" | "run:before-start-append" | "step:after-step-append" | "subagent:after-admit" | "subagent:after-child-abort-intent" | "subagent:after-child-ready" | "subagent:after-join-append" | "subagent:after-release" | "subagent:after-release-pending" | "subagent:after-request-append" | "subagent:after-reserve" | "subagent:after-sibling-settle" | "subagent:after-start-append" | "subagent:after-suspend" | "submit:after-admit" | "submit:after-materialize" | "terminalize:after-canonical-append" | "terminalize:after-reserve" | "tools:after-prepared-append" | "tools:before-prepared-append" | "turn:after-canonical-append" | "turn:after-response-append" | "turn:after-results-append" | "worker:after-completion-append" | "worker:after-origin-append" | "worker:after-report-append" | "worker:after-report-delivery" | "worker:after-source-append" | "worker:after-subtree-append" | "worker:before-completion-append" | "worker:before-origin-append" | "worker:before-report-append" | "worker:before-report-delivery" | "worker:before-source-append" | "worker:before-subtree-append";
|
|
729
|
+
readonly location: "abort:after-intent" | "approval:after-request-append" | "approval:after-suspend" | "checkpoint:after-save" | "checkpoint:before-save" | "claim:after-claim" | "compaction:after-canonical-append" | "compaction:before-canonical-append" | "input:after-canonical-append" | "join:after-canonical-append" | "join:after-claim" | "policy:after-reservation-append" | "policy:before-reservation-append" | "resolve:after-intent" | "run:after-start-append" | "run:before-start-append" | "step:after-step-append" | "subagent:after-admit" | "subagent:after-child-abort-intent" | "subagent:after-child-ready" | "subagent:after-join-append" | "subagent:after-release" | "subagent:after-release-pending" | "subagent:after-request-append" | "subagent:after-reserve" | "subagent:after-sibling-settle" | "subagent:after-start-append" | "subagent:after-suspend" | "subagent:before-join-append" | "submit:after-admit" | "submit:after-materialize" | "terminalize:after-canonical-append" | "terminalize:after-reserve" | "tools:after-prepared-append" | "tools:before-prepared-append" | "turn:after-canonical-append" | "turn:after-response-append" | "turn:after-results-append" | "worker:after-completion-append" | "worker:after-origin-append" | "worker:after-report-append" | "worker:after-report-delivery" | "worker:after-source-append" | "worker:after-subtree-append" | "worker:before-completion-append" | "worker:before-origin-append" | "worker:before-report-append" | "worker:before-report-delivery" | "worker:before-source-append" | "worker:before-subtree-append";
|
|
730
730
|
} | {
|
|
731
731
|
readonly _tag: "DurableAlarmError";
|
|
732
732
|
readonly operation: string;
|
|
@@ -775,4 +775,4 @@ interface Class<EventServices = never> {
|
|
|
775
775
|
declare const make: <ApplicationServices, ApplicationError, EventServices = never, EventLayerError = never>(applicationLayer: Layer.Layer<CloudflareDurableRuntimeServices | ApplicationServices, ApplicationError, CloudflareBootstrapServices | DurableObjectState$1.DurableObjectState | WorkerEnvironment | DurableObjectContext | ThreadObjectNamespace>, options: Options<ApplicationServices, EventServices, EventLayerError>) => Class<ApplicationServices | EventServices>;
|
|
776
776
|
//#endregion
|
|
777
777
|
export { CloudflareDurableRuntimeOptions as C, layerConfig as D, layer as E, CloudflareDurableRuntimeInitializationError as S, ThreadPublicationOptions as T, decodeObligationThresholds as _, AdminVerifyRequest as a, make as b, Instance as c, RetryExecuted as d, ThreadObject_d_exports as f, decodeAdminVerifyRequest as g, decodeAdminResponse as h, AdminResponse as i, ObligationsScanned as l, decodeAdminExplainRequest as m, AdminFailed as n, Class as o, VerifiedIntegrity as p, AdminFailure as r, ExplainedRecovery as s, AdminExplainRequest as t, Options as u, decodeRetryCommand as v, CloudflareDurableRuntimeServices as w, CloudflareBootstrapServices as x, encodeAdminResponse as y };
|
|
778
|
-
//# sourceMappingURL=ThreadObject-
|
|
778
|
+
//# sourceMappingURL=ThreadObject-D7G1M59T.d.mts.map
|
package/dist/ThreadObject.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as CloudflareDurableRuntimeOptions, D as layerConfig, E as layer, S as CloudflareDurableRuntimeInitializationError, T as ThreadPublicationOptions, _ as decodeObligationThresholds, a as AdminVerifyRequest, b as make, c as Instance, d as RetryExecuted, g as decodeAdminVerifyRequest, h as decodeAdminResponse, i as AdminResponse, l as ObligationsScanned, m as decodeAdminExplainRequest, n as AdminFailed, o as Class, p as VerifiedIntegrity, r as AdminFailure, s as ExplainedRecovery, t as AdminExplainRequest, u as Options, v as decodeRetryCommand, w as CloudflareDurableRuntimeServices, x as CloudflareBootstrapServices, y as encodeAdminResponse } from "./ThreadObject-
|
|
1
|
+
import { C as CloudflareDurableRuntimeOptions, D as layerConfig, E as layer, S as CloudflareDurableRuntimeInitializationError, T as ThreadPublicationOptions, _ as decodeObligationThresholds, a as AdminVerifyRequest, b as make, c as Instance, d as RetryExecuted, g as decodeAdminVerifyRequest, h as decodeAdminResponse, i as AdminResponse, l as ObligationsScanned, m as decodeAdminExplainRequest, n as AdminFailed, o as Class, p as VerifiedIntegrity, r as AdminFailure, s as ExplainedRecovery, t as AdminExplainRequest, u as Options, v as decodeRetryCommand, w as CloudflareDurableRuntimeServices, x as CloudflareBootstrapServices, y as encodeAdminResponse } from "./ThreadObject-D7G1M59T.mjs";
|
|
2
2
|
export { AdminExplainRequest, AdminFailed, AdminFailure, AdminResponse, AdminVerifyRequest, type CloudflareBootstrapServices as BootstrapServices, Class, ExplainedRecovery, type CloudflareDurableRuntimeInitializationError as InitializationError, Instance, ObligationsScanned, Options, type ThreadPublicationOptions as PublicationOptions, RetryExecuted, type CloudflareDurableRuntimeOptions as RuntimeOptions, type CloudflareDurableRuntimeServices as Services, VerifiedIntegrity, decodeAdminExplainRequest, decodeAdminResponse, decodeAdminVerifyRequest, decodeObligationThresholds, decodeRetryCommand, encodeAdminResponse, layer, layerConfig, make };
|
package/dist/index.d.mts
CHANGED
|
@@ -8,6 +8,6 @@ import { t as CloudflareMemory_d_exports } from "./CloudflareMemory.mjs";
|
|
|
8
8
|
import { t as CloudflareScheduling_d_exports } from "./CloudflareScheduling.mjs";
|
|
9
9
|
import { t as CloudflareSubscriptions_d_exports } from "./CloudflareSubscriptions.mjs";
|
|
10
10
|
import { t as CloudflareThreadClient_d_exports } from "./CloudflareThreadClient.mjs";
|
|
11
|
-
import { f as ThreadObject_d_exports } from "./ThreadObject-
|
|
11
|
+
import { f as ThreadObject_d_exports } from "./ThreadObject-D7G1M59T.mjs";
|
|
12
12
|
import { t as WakeScheduler_d_exports } from "./WakeScheduler.mjs";
|
|
13
13
|
export { Alarm_d_exports as Alarm, CloudflareAiGateway_d_exports as CloudflareAiGateway, CloudflareBindings_d_exports as CloudflareBindings, CloudflareBrowser_d_exports as CloudflareBrowser, CloudflareCodeMode_d_exports as CloudflareCodeMode, CloudflareConfig_d_exports as CloudflareConfig, CloudflareMemory_d_exports as CloudflareMemory, CloudflareScheduling_d_exports as CloudflareScheduling, CloudflareSubscriptions_d_exports as CloudflareSubscriptions, CloudflareThreadClient_d_exports as CloudflareThreadClient, ThreadObject_d_exports as ThreadObject, WakeScheduler_d_exports as WakeScheduler };
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as CloudflareBindings_exports } from "./CloudflareBindings.mjs";
|
|
2
2
|
import { t as CloudflareConfig_exports } from "./CloudflareConfig.mjs";
|
|
3
3
|
import { t as Alarm_exports } from "./Alarm.mjs";
|
|
4
|
-
import { t as CloudflareBrowser_exports } from "./CloudflareBrowser-
|
|
4
|
+
import { t as CloudflareBrowser_exports } from "./CloudflareBrowser-BSJRWmlW.mjs";
|
|
5
5
|
import { t as CloudflareCodeMode_exports } from "./CloudflareCodeMode.mjs";
|
|
6
6
|
import { t as CloudflareMemory_exports } from "./CloudflareMemory.mjs";
|
|
7
7
|
import { t as CloudflareThreadClient_exports } from "./CloudflareThreadClient.mjs";
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@effect-agent/platform-cloudflare","version":"0.1.0-beta.
|
|
1
|
+
{"name":"@effect-agent/platform-cloudflare","version":"0.1.0-beta.78","dependencies":{"@effect-agent/core":"0.1.0-beta.78","@effect-agent/engine":"0.1.0-beta.78","@effect-agent/sandbox":"0.1.0-beta.78","@effect-agent/storage-cloudflare":"0.1.0-beta.78","@effect-agent/thread":"0.1.0-beta.78","@effect/platform-browser":"4.0.0-rc.112","@effect/sql-sqlite-do":"4.0.0-rc.112"},"devDependencies":{"@cloudflare/puppeteer":"1.1.0","@cloudflare/vitest-pool-workers":"0.21.3","@cloudflare/workers-types":"5.20260825.1","@effect-agent/capabilities":"0.1.0-beta.78","@effect-agent/testing":"0.1.0-beta.78","@effect/platform-node":"4.0.0-rc.112","@effect/sql-d1":"4.0.0-rc.112","@effect/vitest":"4.0.0-rc.112","effect":"4.0.0-rc.112","effect-cf":"0.40.0","esbuild":"0.28.1","miniflare":"5.20260811.1-alpha","typescript":"7.0.2","vite-plus":"0.3.0","vitest":"4.1.11"},"peerDependencies":{"@cloudflare/puppeteer":"^1.1.0","effect":"^4.0.0-rc.112","effect-cf":"^0.40.0"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./Alarm":{"types":"./dist/Alarm.d.mts","default":"./dist/Alarm.mjs"},"./BrowserRestCapture":{"types":"./dist/BrowserRestCapture.d.mts","default":"./dist/BrowserRestCapture.mjs"},"./BrowserRestCrawl":{"types":"./dist/BrowserRestCrawl.d.mts","default":"./dist/BrowserRestCrawl.mjs"},"./CloudflareBindings":{"types":"./dist/CloudflareBindings.d.mts","default":"./dist/CloudflareBindings.mjs"},"./CloudflareBrowser":{"types":"./dist/CloudflareBrowser.d.mts","default":"./dist/CloudflareBrowser.mjs"},"./CloudflareCodeMode":{"types":"./dist/CloudflareCodeMode.d.mts","default":"./dist/CloudflareCodeMode.mjs"},"./CloudflareConfig":{"types":"./dist/CloudflareConfig.d.mts","default":"./dist/CloudflareConfig.mjs"},"./CloudflareMemory":{"types":"./dist/CloudflareMemory.d.mts","default":"./dist/CloudflareMemory.mjs"},"./CloudflareScheduling":{"types":"./dist/CloudflareScheduling.d.mts","default":"./dist/CloudflareScheduling.mjs"},"./CloudflareSubscriptions":{"types":"./dist/CloudflareSubscriptions.d.mts","default":"./dist/CloudflareSubscriptions.mjs"},"./CloudflareThreadClient":{"types":"./dist/CloudflareThreadClient.d.mts","default":"./dist/CloudflareThreadClient.mjs"},"./InteractiveBrowser":{"types":"./dist/InteractiveBrowser.d.mts","default":"./dist/InteractiveBrowser.mjs"},"./ProtectedBrowser":{"types":"./dist/ProtectedBrowser.d.mts","default":"./dist/ProtectedBrowser.mjs"},"./ThreadObject":{"types":"./dist/ThreadObject.d.mts","default":"./dist/ThreadObject.mjs"},"./WakeScheduler":{"types":"./dist/WakeScheduler.d.mts","default":"./dist/WakeScheduler.mjs"},"./CloudflareAiGateway":{"types":"./dist/CloudflareAiGateway.d.mts","default":"./dist/CloudflareAiGateway.mjs"}},"description":"Cloudflare Layer assembly for Effect Agent: Durable Objects and Browser Run adapters.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/platform-cloudflare"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json"},"peerDependenciesMeta":{"@cloudflare/puppeteer":{"optional":true}}}
|
package/src/CloudflareMemory.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { MemoryAccess } from "@effect-agent/core/MemoryRevalidation";
|
|
|
6
6
|
import {
|
|
7
7
|
type MemoryReader,
|
|
8
8
|
type MemoryWrite,
|
|
9
|
+
MemoryKey,
|
|
9
10
|
MemoryDocument,
|
|
10
11
|
MemoryMutationFailpoint,
|
|
11
12
|
MemoryStorageError,
|
|
@@ -164,6 +165,52 @@ const makeMemoryClient = Effect.fn("CloudflareMemoryClient.make")(function* <
|
|
|
164
165
|
}).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));
|
|
165
166
|
});
|
|
166
167
|
|
|
168
|
+
/**
|
|
169
|
+
* Read one exact current document in one owner RPC. Null means absent; withdrawals return
|
|
170
|
+
* tombstones. Denial, unavailable storage and deadlines fail typed, never become absence.
|
|
171
|
+
* Reads begun after an acknowledged write observe it or a later revision. The owner checks
|
|
172
|
+
* exact-key authority and active document scopes; source-dependent provenance policy remains
|
|
173
|
+
* application-owned. No extraction, job draining, embedding, discovery or rendering occurs.
|
|
174
|
+
*/
|
|
175
|
+
const get = Effect.fn("CloudflareMemoryClient.get")(function* (key: MemoryKey<Namespace>) {
|
|
176
|
+
const decodedKey = yield* Schema.decodeUnknownEffect(MemoryKey.Wire)(key).pipe(
|
|
177
|
+
Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })),
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
if (!MemoryNamespace.equals(decodedKey.namespace, bound.namespace))
|
|
181
|
+
return yield* MemoryRpcError.make({ reason: "denied" });
|
|
182
|
+
|
|
183
|
+
return yield* Effect.gen(function* () {
|
|
184
|
+
const response = yield* call({
|
|
185
|
+
_tag: "Get",
|
|
186
|
+
version: 1,
|
|
187
|
+
access: bound,
|
|
188
|
+
principal,
|
|
189
|
+
key: decodedKey,
|
|
190
|
+
deadlineMillis: (yield* Clock.currentTimeMillis) + validated.timeoutMillis,
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
if (
|
|
194
|
+
response._tag !== "Document" ||
|
|
195
|
+
!MemoryNamespace.equals(response.key.namespace, bound.namespace) ||
|
|
196
|
+
response.key.id !== decodedKey.id
|
|
197
|
+
)
|
|
198
|
+
return yield* MemoryRpcError.make({ reason: "protocol" });
|
|
199
|
+
if (response.document === null) return null;
|
|
200
|
+
if (
|
|
201
|
+
response.document.key.id !== decodedKey.id ||
|
|
202
|
+
response.document.source.id !== decodedKey.id ||
|
|
203
|
+
(response.document._tag === "ActiveMemoryDocument" &&
|
|
204
|
+
!response.document.scopes.includes(bound.scope))
|
|
205
|
+
)
|
|
206
|
+
return yield* MemoryRpcError.make({ reason: "protocol" });
|
|
207
|
+
|
|
208
|
+
yield* encodeMemoryWire(MemoryDocument.Wire, response.document, validated.maxSourceBytes);
|
|
209
|
+
|
|
210
|
+
return yield* MemoryDocument.restore(access.namespace, response.document);
|
|
211
|
+
}).pipe((effect) => withinDeadline(effect, validated.timeoutMillis));
|
|
212
|
+
});
|
|
213
|
+
|
|
167
214
|
const revalidateSemantic = Effect.fn("CloudflareMemoryClient.revalidateSemantic")(function* (
|
|
168
215
|
found: MemoryIndexSearch<Namespace>,
|
|
169
216
|
profile: SemanticMemoryProfile,
|
|
@@ -206,7 +253,7 @@ const makeMemoryClient = Effect.fn("CloudflareMemoryClient.make")(function* <
|
|
|
206
253
|
);
|
|
207
254
|
});
|
|
208
255
|
|
|
209
|
-
return { recall, revalidate, revalidateSemantic, change };
|
|
256
|
+
return { get, recall, revalidate, revalidateSemantic, change };
|
|
210
257
|
});
|
|
211
258
|
|
|
212
259
|
export const CloudflareMemoryClient = {
|
|
@@ -268,8 +268,25 @@ const navigationError = (message: string, cause?: unknown): PageCaptureNavigatio
|
|
|
268
268
|
});
|
|
269
269
|
|
|
270
270
|
/** Preserve bounded remote diagnostics for the host without exposing their text to a model. */
|
|
271
|
-
const privateResponseCause = (bodyText: string): Error
|
|
272
|
-
|
|
271
|
+
const privateResponseCause = (bodyText: string, response: Response): Error =>
|
|
272
|
+
new Error(boundedDiagnostic(bodyText), {
|
|
273
|
+
cause: {
|
|
274
|
+
provider: "cloudflare-browser-run",
|
|
275
|
+
httpStatus: response.status,
|
|
276
|
+
httpStatusSource: "browser-api",
|
|
277
|
+
headers: Object.fromEntries(
|
|
278
|
+
["content-type", "cf-ray", "x-request-id", "retry-after", "x-browser-ms-used"].flatMap(
|
|
279
|
+
(name) => {
|
|
280
|
+
const value = response.headers.get(name);
|
|
281
|
+
|
|
282
|
+
return value === null ? [] : [[name, boundedDiagnostic(value)]];
|
|
283
|
+
},
|
|
284
|
+
),
|
|
285
|
+
),
|
|
286
|
+
bodyCharacters: bodyText.length,
|
|
287
|
+
bodyTruncated: bodyText.length > MAX_DIAGNOSTIC_LENGTH,
|
|
288
|
+
},
|
|
289
|
+
});
|
|
273
290
|
|
|
274
291
|
/** Foreign cancellation must not keep a response Scope open indefinitely. */
|
|
275
292
|
const cancelResponse = (cancel: () => Promise<void>, warning: string): Effect.Effect<void> =>
|
|
@@ -389,7 +406,7 @@ const parseOutput = (
|
|
|
389
406
|
if (!isJsonResponse(response)) {
|
|
390
407
|
return protocolError(
|
|
391
408
|
"The Quick Action success response was not a JSON response envelope",
|
|
392
|
-
privateResponseCause(bodyText),
|
|
409
|
+
privateResponseCause(bodyText, response),
|
|
393
410
|
);
|
|
394
411
|
}
|
|
395
412
|
const envelope = decodeEnvelope(bodyText);
|
|
@@ -397,13 +414,13 @@ const parseOutput = (
|
|
|
397
414
|
if (Option.isNone(envelope)) {
|
|
398
415
|
return protocolError(
|
|
399
416
|
"The JSON Quick Action response did not carry a valid response envelope",
|
|
400
|
-
privateResponseCause(bodyText),
|
|
417
|
+
privateResponseCause(bodyText, response),
|
|
401
418
|
);
|
|
402
419
|
}
|
|
403
420
|
if (!envelope.value.success) {
|
|
404
421
|
return navigationError(
|
|
405
422
|
"The Quick Action reported a navigation failure",
|
|
406
|
-
privateResponseCause(bodyText),
|
|
423
|
+
privateResponseCause(bodyText, response),
|
|
407
424
|
);
|
|
408
425
|
}
|
|
409
426
|
switch (action._tag) {
|
|
@@ -505,7 +522,7 @@ const makeCapture = (
|
|
|
505
522
|
if (response.status === 429) {
|
|
506
523
|
const retryAfter = retryAfterMillis(response);
|
|
507
524
|
const reason = isQuotaMessage(bodyText) ? "quota" : "rate";
|
|
508
|
-
const cause = privateResponseCause(bodyText);
|
|
525
|
+
const cause = privateResponseCause(bodyText, response);
|
|
509
526
|
|
|
510
527
|
return yield* PageCaptureRateLimitedError.make({
|
|
511
528
|
implementation: browserQuickActionImplementation,
|
|
@@ -520,7 +537,7 @@ const makeCapture = (
|
|
|
520
537
|
}
|
|
521
538
|
if (!response.ok) {
|
|
522
539
|
const message = `The Quick Action answered HTTP ${response.status}`;
|
|
523
|
-
const cause = privateResponseCause(bodyText);
|
|
540
|
+
const cause = privateResponseCause(bodyText, response);
|
|
524
541
|
|
|
525
542
|
if (response.status >= 500) {
|
|
526
543
|
return yield* protocolError(message, cause);
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"CloudflareBrowser-Bj22nNUT.mjs","names":[],"sources":["../src/internal/browser-quick-action.ts","../src/CloudflareBrowser.ts"],"sourcesContent":["/// <reference types=\"@cloudflare/workers-types\" />\n\nimport {\n PageCapture,\n PageCaptureInferenceUse,\n PageCaptureInferencePolicyError,\n PageCaptureNavigationError,\n PageCaptureOutputLimitError,\n PageCaptureProtocolError,\n PageCaptureRateLimitedError,\n PageCaptureResourceUse,\n PageCaptureResult,\n PageCaptureUnsupportedError,\n PageContentCaptured,\n PageLinksCaptured,\n PageMarkdownCaptured,\n PageScrapeCaptured,\n PageStructuredCaptured,\n type PageCaptureAction,\n type PageCaptureCapture,\n type PageCaptureError,\n type PageCaptureOutput,\n type PageCaptureRequest,\n} from \"@effect-agent/sandbox/PageCapture\";\nimport {\n PageScreenshot,\n PageScreenshotOutputLimitError,\n PageScreenshotResult,\n type PageScreenshotCapture,\n type PageScreenshotError,\n type PageScreenshotRequest,\n} from \"@effect-agent/sandbox/PageScreenshot\";\nimport { SandboxImplementation } from \"@effect-agent/sandbox/Sandbox\";\nimport { Context, Effect, Layer, Option, Schema } from \"effect\";\n\n/**\n * The Cloudflare Browser Run Quick Action `PageCapture` adapter (capability\n * spec §9.2). Each capture is one stateless `quickAction()` RPC on the\n * Wrangler `browser` binding: the platform renders the target in a managed\n * headless browser and returns one bounded output; the adapter holds no\n * session and no state between passes. The binding requires a Worker\n * compatibility date of `2026-03-24` or later, and local `wrangler dev` needs\n * remote mode (`\"remote\": true` on the binding) because `quickAction` has no\n * local implementation.\n *\n * Rendered output is untrusted, attacker-influenced content; this adapter\n * only bounds and types it. Deployment class `E` only: no durability claim.\n */\nexport const browserQuickActionImplementation = SandboxImplementation.make({\n isolation: \"isolated\",\n identity: \"cloudflare-browser-quick-action\",\n});\n\n/**\n * Effect-native client captured by the binding service. Its option types come\n * directly from the pinned Workers declarations rather than a local copy.\n */\nexport interface BrowserQuickActionClient {\n readonly screenshot: (\n options: BrowserRunScreenshotOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n readonly content: (\n options: BrowserRunContentOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n readonly markdown: (\n options: BrowserRunMarkdownOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n readonly links: (\n options: BrowserRunLinksOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n readonly scrape: (\n options: BrowserRunScrapeOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n readonly json: (\n options: BrowserRunJsonOptions,\n ) => Effect.Effect<Response, BrowserQuickActionRpcError>;\n}\n\n/** A native binding RPC rejected before it returned an HTTP response. */\nexport class BrowserQuickActionRpcError extends Schema.TaggedError<BrowserQuickActionRpcError>()(\n \"BrowserQuickActionRpcError\",\n {\n action: Schema.Literals([\"screenshot\", \"content\", \"markdown\", \"links\", \"scrape\", \"json\"]),\n cause: Schema.Defect(),\n },\n) {}\n\nexport interface BrowserQuickActionCaptureOptions {\n /** The resolved Wrangler `browser` binding (DEPLOY-014: supplied, never ambient). */\n readonly browser: BrowserRun;\n}\n\n/** Host-owned browser binding authority, supplied explicitly at the composition root. */\nexport class BrowserQuickActionBrowserBinding extends Context.Service<\n BrowserQuickActionBrowserBinding,\n BrowserQuickActionClient\n>()(\"@effect-agent/platform-cloudflare/BrowserQuickActionBrowserBinding\") {\n static layer(\n options: BrowserQuickActionCaptureOptions,\n ): Layer.Layer<BrowserQuickActionBrowserBinding> {\n const browser = options.browser;\n\n const invoke = Effect.fn(\"BrowserQuickActionBrowserBinding.invoke\")(function* (\n action: \"screenshot\" | \"content\" | \"markdown\" | \"links\" | \"scrape\" | \"json\",\n evaluate: () => Promise<Response>,\n ): Effect.fn.Return<Response, BrowserQuickActionRpcError> {\n return yield* Effect.tryPromise({\n try: evaluate,\n catch: (cause) => BrowserQuickActionRpcError.make({ action, cause }),\n });\n });\n\n return Layer.succeed(BrowserQuickActionBrowserBinding)({\n screenshot: (request) =>\n invoke(\"screenshot\", () => browser.quickAction(\"screenshot\", request)),\n content: (request) => invoke(\"content\", () => browser.quickAction(\"content\", request)),\n markdown: (request) => invoke(\"markdown\", () => browser.quickAction(\"markdown\", request)),\n links: (request) => invoke(\"links\", () => browser.quickAction(\"links\", request)),\n scrape: (request) => invoke(\"scrape\", () => browser.quickAction(\"scrape\", request)),\n json: (request) => invoke(\"json\", () => browser.quickAction(\"json\", request)),\n });\n }\n}\n\n/** Host-owned authorization and accounting for one Workers AI extraction. */\nexport interface BrowserQuickActionWorkersAiPolicy {\n readonly authorizeAndAccount: (\n request: PageCaptureRequest,\n ) => Effect.Effect<void, BrowserQuickActionWorkersAiPolicyError>;\n}\n\n/** Host-only diagnostic for a denied or unaccounted Workers AI extraction. */\nexport class BrowserQuickActionWorkersAiPolicyError extends Schema.TaggedError<BrowserQuickActionWorkersAiPolicyError>()(\n \"BrowserQuickActionWorkersAiPolicyError\",\n {\n reason: Schema.Literals([\"authorization\", \"accounting\"]),\n message: Schema.String.check(Schema.isMaxLength(8_000)),\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\n/** Explicit host-owned authority and accounting for separately billed Workers AI extraction. */\nexport class BrowserQuickActionWorkersAi extends Context.Service<\n BrowserQuickActionWorkersAi,\n BrowserQuickActionWorkersAiPolicy\n>()(\"@effect-agent/platform-cloudflare/BrowserQuickActionWorkersAi\") {\n static layer(\n policy: BrowserQuickActionWorkersAiPolicy,\n ): Layer.Layer<BrowserQuickActionWorkersAi> {\n return Layer.succeed(BrowserQuickActionWorkersAi)(policy);\n }\n}\n\nconst MAX_DIAGNOSTIC_LENGTH = 8_000;\nconst boundedDiagnostic = (message: string): string => message.slice(0, MAX_DIAGNOSTIC_LENGTH);\n\nconst QuickActionSuccessEnvelope = Schema.Struct({\n success: Schema.Literal(true),\n result: Schema.Json,\n});\n\nconst QuickActionErrorEnvelope = Schema.Struct({\n success: Schema.Literal(false),\n errors: Schema.Array(\n Schema.Struct({\n message: Schema.String,\n code: Schema.optionalKey(Schema.Number),\n detail: Schema.optionalKey(Schema.String),\n path: Schema.optionalKey(Schema.String),\n }),\n ),\n rawAiResponse: Schema.optionalKey(Schema.String),\n});\n\nconst QuickActionEnvelope = Schema.Union([QuickActionSuccessEnvelope, QuickActionErrorEnvelope]);\nconst decodeEnvelope = Schema.decodeUnknownOption(Schema.fromJsonString(QuickActionEnvelope));\n\n/** Project the schema-validated request onto Cloudflare's native common options. */\nconst quickActionCommonOptions = (request: PageCaptureRequest): BrowserRunCommonOptions => {\n const options: BrowserRunBaseOptions = {};\n const navigation = request.navigation;\n\n if (navigation !== undefined) {\n const goto: NonNullable<BrowserRunBaseOptions[\"gotoOptions\"]> = {};\n\n if (navigation.waitUntil !== undefined) goto.waitUntil = navigation.waitUntil;\n if (navigation.timeoutMillis !== undefined) goto.timeout = navigation.timeoutMillis;\n if (Object.keys(goto).length > 0) options.gotoOptions = goto;\n if (navigation.waitForSelector !== undefined) {\n options.waitForSelector = {\n selector: navigation.waitForSelector.selector,\n ...(navigation.waitForSelector.timeoutMillis === undefined\n ? {}\n : { timeout: navigation.waitForSelector.timeoutMillis }),\n };\n }\n }\n if (request.viewport !== undefined) {\n options.viewport = { width: request.viewport.width, height: request.viewport.height };\n }\n if (request.resourcePolicy !== undefined) {\n if (request.resourcePolicy.rejectResourceTypes !== undefined) {\n options.rejectResourceTypes = [...request.resourcePolicy.rejectResourceTypes];\n }\n if (request.resourcePolicy.allowRequestPatterns !== undefined) {\n options.allowRequestPattern = [...request.resourcePolicy.allowRequestPatterns];\n }\n }\n\n return request.target._tag === \"PageUrlTarget\"\n ? { ...options, url: request.target.url }\n : { ...options, html: request.target.html };\n};\n\n/** Dispatch through Cloudflare's native action-specific overloads. */\nconst executeQuickAction = (\n browser: BrowserQuickActionClient,\n request: PageCaptureRequest,\n): Effect.Effect<Response, BrowserQuickActionRpcError> => {\n const options = quickActionCommonOptions(request);\n\n switch (request.action._tag) {\n case \"CapturePageContent\": {\n return browser.content(options);\n }\n case \"CapturePageMarkdown\": {\n return browser.markdown(options);\n }\n case \"CapturePageLinks\": {\n return browser.links({\n ...options,\n ...(request.action.visibleLinksOnly === undefined\n ? {}\n : { visibleLinksOnly: request.action.visibleLinksOnly }),\n });\n }\n case \"CapturePageScrape\": {\n return browser.scrape({\n ...options,\n elements: request.action.selectors.map((selector) => ({ selector })),\n });\n }\n case \"CapturePageStructured\": {\n return browser.json({\n ...options,\n response_format: {\n type: \"json_schema\",\n json_schema: request.action.responseFormat,\n },\n ...(request.action.prompt === undefined ? {} : { prompt: request.action.prompt }),\n });\n }\n }\n};\n\nconst protocolError = (message: string, cause?: unknown): PageCaptureProtocolError =>\n PageCaptureProtocolError.make({\n implementation: browserQuickActionImplementation,\n message: boundedDiagnostic(message),\n ...(cause === undefined ? {} : { cause }),\n });\n\nconst navigationError = (message: string, cause?: unknown): PageCaptureNavigationError =>\n PageCaptureNavigationError.make({\n implementation: browserQuickActionImplementation,\n message: boundedDiagnostic(message),\n ...(cause === undefined ? {} : { cause }),\n });\n\n/** Preserve bounded remote diagnostics for the host without exposing their text to a model. */\nconst privateResponseCause = (bodyText: string): Error | undefined =>\n bodyText.length === 0 ? undefined : new Error(boundedDiagnostic(bodyText));\n\n/** Foreign cancellation must not keep a response Scope open indefinitely. */\nconst cancelResponse = (cancel: () => Promise<void>, warning: string): Effect.Effect<void> =>\n Effect.tryPromise({ try: cancel, catch: () => undefined }).pipe(\n Effect.interruptible,\n Effect.timeoutOrElse({\n duration: \"1 second\",\n orElse: () => Effect.fail(undefined),\n }),\n Effect.catch(() => Effect.logWarning(warning)),\n );\n\nconst releaseResponseReader = (\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): Effect.Effect<void> =>\n cancelResponse(() => reader.cancel(), \"Canceling the Quick Action response failed\").pipe(\n Effect.ensuring(\n Effect.try({\n try: () => reader.releaseLock(),\n catch: (cause) => protocolError(\"Releasing the Quick Action response failed\", cause),\n }).pipe(Effect.catch((error) => Effect.logWarning(error.message))),\n ),\n );\n\nconst readBoundedResponse = Effect.fn(\"BrowserQuickActionCapture.readResponse\")(function* (\n response: Response,\n request: PageCaptureRequest,\n) {\n const body = response.body;\n\n if (body === null) return \"\";\n\n const reader = yield* Effect.acquireRelease(\n Effect.try({\n try: () => body.getReader(),\n catch: (cause) => protocolError(\"Opening the Quick Action response failed\", cause),\n }),\n releaseResponseReader,\n );\n\n const decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false });\n let observedBytes = 0;\n let bodyText = \"\";\n\n while (true) {\n const chunk = yield* Effect.tryPromise({\n try: () => reader.read(),\n catch: (cause) => protocolError(\"Reading the Quick Action response failed\", cause),\n });\n\n if (chunk.done) break;\n\n observedBytes += chunk.value.byteLength;\n if (observedBytes > request.limits.maxOutputBytes) {\n return yield* PageCaptureOutputLimitError.make({\n implementation: browserQuickActionImplementation,\n limit: request.limits.maxOutputBytes,\n observed: observedBytes,\n });\n }\n\n bodyText += yield* Effect.try({\n try: () => decoder.decode(chunk.value, { stream: true }),\n catch: (cause) => protocolError(\"Decoding the Quick Action response failed\", cause),\n });\n }\n\n return (\n bodyText +\n (yield* Effect.try({\n try: () => decoder.decode(),\n catch: (cause) => protocolError(\"Decoding the Quick Action response failed\", cause),\n }))\n );\n}, Effect.scoped);\n\n/**\n * Retry-After arrives in whole seconds; a non-integer form (an HTTP date) is\n * dropped rather than guessed at.\n */\nconst retryAfterMillis = (response: Response): number | undefined => {\n const header = response.headers.get(\"Retry-After\");\n\n if (header === null) return undefined;\n const seconds = Number(header);\n\n if (!Number.isSafeInteger(seconds) || seconds < 0) return undefined;\n const millis = seconds * 1_000;\n\n return Number.isSafeInteger(millis) ? millis : undefined;\n};\n\nconst browserMillis = (response: Response): number | undefined => {\n const header = response.headers.get(\"X-Browser-Ms-Used\");\n\n if (header === null) return undefined;\n const millis = Number(header);\n\n return Number.isSafeInteger(millis) && millis >= 0 ? millis : undefined;\n};\n\n/** Only trusted response metadata chooses transport framing; page text never does. */\nconst isJsonResponse = (response: Response): boolean => {\n const contentType = response.headers.get(\"Content-Type\");\n\n if (contentType === null) return false;\n const mediaType = contentType.split(\";\", 1)[0]?.trim().toLowerCase();\n\n return mediaType === \"application/json\" || mediaType?.endsWith(\"+json\") === true;\n};\n\nconst parseOutput = (\n action: PageCaptureAction,\n bodyText: string,\n response: Response,\n): PageCaptureOutput | PageCaptureNavigationError | PageCaptureProtocolError => {\n if (!isJsonResponse(response)) {\n return protocolError(\n \"The Quick Action success response was not a JSON response envelope\",\n privateResponseCause(bodyText),\n );\n }\n const envelope = decodeEnvelope(bodyText);\n\n if (Option.isNone(envelope)) {\n return protocolError(\n \"The JSON Quick Action response did not carry a valid response envelope\",\n privateResponseCause(bodyText),\n );\n }\n if (!envelope.value.success) {\n return navigationError(\n \"The Quick Action reported a navigation failure\",\n privateResponseCause(bodyText),\n );\n }\n switch (action._tag) {\n case \"CapturePageContent\":\n case \"CapturePageMarkdown\": {\n if (typeof envelope.value.result !== \"string\") {\n return protocolError(\"The Quick Action envelope carried a non-text result\");\n }\n\n return action._tag === \"CapturePageContent\"\n ? PageContentCaptured.make({ html: envelope.value.result })\n : PageMarkdownCaptured.make({ markdown: envelope.value.result });\n }\n case \"CapturePageLinks\": {\n const decoded = Schema.decodeUnknownOption(PageLinksCaptured)({\n _tag: \"PageLinksCaptured\",\n links: envelope.value.result,\n });\n\n if (Option.isNone(decoded)) {\n return protocolError(\"The links Quick Action did not return a bounded array of valid URLs\");\n }\n\n return decoded.value;\n }\n case \"CapturePageScrape\": {\n const decoded = Schema.decodeUnknownOption(PageScrapeCaptured)({\n _tag: \"PageScrapeCaptured\",\n groups: envelope.value.result,\n });\n\n if (Option.isNone(decoded)) {\n return protocolError(\n \"The scrape Quick Action did not return bounded grouped element records\",\n );\n }\n\n return decoded.value;\n }\n case \"CapturePageStructured\": {\n return PageStructuredCaptured.make({ value: envelope.value.result });\n }\n }\n};\n\nconst isQuotaMessage = (text: string): boolean => /time limit|daily|quota/i.test(text);\n\nconst makeCapture = (\n browser: BrowserQuickActionClient,\n workersAi?: BrowserQuickActionWorkersAiPolicy,\n): PageCaptureCapture =>\n Effect.fn(\"BrowserQuickActionCapture.capture\")(function* (\n request: PageCaptureRequest,\n ): Effect.fn.Return<PageCaptureResult, PageCaptureError> {\n if (request.engine !== \"chromium\") {\n return yield* PageCaptureUnsupportedError.make({\n implementation: browserQuickActionImplementation,\n feature: \"engine\",\n message:\n \"The browser binding's quickAction() exposes no engine selector; kitesurf requires the REST or CDP surface\",\n });\n }\n\n const usesWorkersAi = request.action._tag === \"CapturePageStructured\";\n\n if (usesWorkersAi) {\n if (workersAi === undefined) {\n return yield* PageCaptureUnsupportedError.make({\n implementation: browserQuickActionImplementation,\n feature: \"action\",\n message:\n \"Structured capture invokes separately billed Workers AI and requires an explicit authorization and accounting policy\",\n });\n }\n yield* workersAi.authorizeAndAccount(request).pipe(\n Effect.mapError((cause) =>\n PageCaptureInferencePolicyError.make({\n implementation: browserQuickActionImplementation,\n provider: \"cloudflare-workers-ai\",\n reason: cause.reason,\n message:\n cause.reason === \"authorization\"\n ? \"Workers AI extraction was not authorized\"\n : \"Workers AI extraction could not be accounted for\",\n cause,\n }),\n ),\n );\n }\n\n const response = yield* executeQuickAction(browser, request).pipe(\n Effect.mapError((error) =>\n protocolError(\"The browser binding rejected the Quick Action\", error.cause),\n ),\n );\n\n const bodyText = yield* readBoundedResponse(response, request);\n\n if (response.status === 429) {\n const retryAfter = retryAfterMillis(response);\n const reason = isQuotaMessage(bodyText) ? \"quota\" : \"rate\";\n const cause = privateResponseCause(bodyText);\n\n return yield* PageCaptureRateLimitedError.make({\n implementation: browserQuickActionImplementation,\n reason,\n ...(retryAfter === undefined ? {} : { retryAfterMillis: retryAfter }),\n ...(cause === undefined ? {} : { cause }),\n message:\n reason === \"quota\"\n ? \"The Quick Action exceeded its browser quota\"\n : \"The Quick Action was rate limited\",\n });\n }\n if (!response.ok) {\n const message = `The Quick Action answered HTTP ${response.status}`;\n const cause = privateResponseCause(bodyText);\n\n if (response.status >= 500) {\n return yield* protocolError(message, cause);\n }\n\n return yield* navigationError(message, cause);\n }\n const output = parseOutput(request.action, bodyText, response);\n\n if (\n output._tag === \"PageCaptureNavigationError\" ||\n output._tag === \"PageCaptureProtocolError\"\n ) {\n return yield* output;\n }\n const millis = browserMillis(response);\n\n return PageCaptureResult.make({\n implementation: browserQuickActionImplementation,\n output,\n resourceUse: PageCaptureResourceUse.make({\n ...(millis === undefined ? {} : { browserMillis: millis }),\n ...(usesWorkersAi\n ? {\n inference: PageCaptureInferenceUse.make({\n provider: \"cloudflare-workers-ai\",\n modelCalls: 1,\n }),\n }\n : {}),\n }),\n });\n });\n\n/**\n * Ordinary Quick Actions require host-owned browser binding authority. Workers\n * AI stays unavailable unless the host deliberately selects its separate Layer.\n */\nexport const browserQuickActionCaptureLayer = (): Layer.Layer<\n PageCapture,\n never,\n BrowserQuickActionBrowserBinding\n> =>\n Layer.effect(\n PageCapture,\n Effect.map(BrowserQuickActionBrowserBinding, (browser) =>\n PageCapture.of({ capture: makeCapture(browser) }),\n ),\n );\n\n/** Structured Quick Actions require host-owned browser and Workers AI authority. */\nexport const browserQuickActionWorkersAiCaptureLayer = (): Layer.Layer<\n PageCapture,\n never,\n BrowserQuickActionBrowserBinding | BrowserQuickActionWorkersAi\n> =>\n Layer.effect(\n PageCapture,\n Effect.gen(function* () {\n const browser = yield* BrowserQuickActionBrowserBinding;\n const workersAi = yield* BrowserQuickActionWorkersAi;\n\n return PageCapture.of({ capture: makeCapture(browser, workersAi) });\n }),\n );\n\n/** Host-owned Quick Action binding and optional, separately billed extraction authority. */\nexport interface CloudflareBrowserOptions extends BrowserQuickActionCaptureOptions {\n readonly workersAi?: BrowserQuickActionWorkersAiPolicy;\n}\n\n/** Compose WebCapture handlers with the Cloudflare Quick Action adapter. */\nexport const CloudflareBrowser = {\n /**\n * Supply a WebCapture definition and the resolved Worker browser binding.\n * Supports capture, scrape, and extraction definitions without importing capabilities.\n * Only PageCapture is provided; other handler requirements and errors stay visible.\n * Extraction fails closed unless workersAi explicitly authorizes and accounts for it.\n * Capture limits, typed failures, tracing, and scoped response cleanup are unchanged.\n */\n layer: <A, E, R>(\n definition: { readonly handlers: Layer.Layer<A, E, R> },\n options: CloudflareBrowserOptions,\n ): Layer.Layer<A, E, Exclude<R, PageCapture>> => {\n const capture =\n options.workersAi === undefined\n ? browserQuickActionCaptureLayer()\n : browserQuickActionWorkersAiCaptureLayer().pipe(\n Layer.provide(BrowserQuickActionWorkersAi.layer(options.workersAi)),\n );\n\n return definition.handlers.pipe(\n Layer.provide(capture.pipe(Layer.provide(BrowserQuickActionBrowserBinding.layer(options)))),\n );\n },\n};\n\nconst screenshotOptions = (request: PageScreenshotRequest): BrowserRunScreenshotOptions => {\n const options: BrowserRunBaseOptions = {};\n\n if (\n request.navigation?.waitUntil !== undefined ||\n request.navigation?.timeoutMillis !== undefined\n ) {\n options.gotoOptions = {\n ...(request.navigation.waitUntil === undefined\n ? {}\n : { waitUntil: request.navigation.waitUntil }),\n ...(request.navigation.timeoutMillis === undefined\n ? {}\n : { timeout: request.navigation.timeoutMillis }),\n };\n }\n if (request.navigation?.waitForSelector !== undefined) {\n options.waitForSelector = {\n selector: request.navigation.waitForSelector.selector,\n ...(request.navigation.waitForSelector.timeoutMillis === undefined\n ? {}\n : { timeout: request.navigation.waitForSelector.timeoutMillis }),\n };\n }\n if (request.viewport !== undefined) {\n options.viewport = { width: request.viewport.width, height: request.viewport.height };\n }\n if (request.resourcePolicy?.rejectResourceTypes !== undefined) {\n options.rejectResourceTypes = [...request.resourcePolicy.rejectResourceTypes];\n }\n if (request.resourcePolicy?.allowRequestPatterns !== undefined) {\n options.allowRequestPattern = [...request.resourcePolicy.allowRequestPatterns];\n }\n\n return {\n ...options,\n ...(request.target._tag === \"PageUrlTarget\"\n ? { url: request.target.url }\n : { html: request.target.html }),\n screenshotOptions: { type: \"png\", encoding: \"binary\", fullPage: request.fullPage },\n };\n};\n\nconst cancelBody = (body: ReadableStream<Uint8Array>): Effect.Effect<void> =>\n cancelResponse(() => body.cancel(), \"Canceling the screenshot response failed\");\n\nconst releaseScreenshotReader = (\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): Effect.Effect<void> =>\n cancelResponse(() => reader.cancel(), \"Canceling the screenshot response failed\").pipe(\n Effect.ensuring(\n Effect.try({\n try: () => reader.releaseLock(),\n catch: () => undefined,\n }).pipe(Effect.catch(() => Effect.logWarning(\"Releasing the screenshot response failed\"))),\n ),\n );\n\nconst pngResponse = (response: Response): boolean =>\n response.headers.get(\"Content-Type\")?.split(\";\", 1)[0]?.trim().toLowerCase() === \"image/png\";\n\nconst declaredLength = (response: Response): number | undefined => {\n const raw = response.headers.get(\"Content-Length\");\n\n if (raw === null || !/^(0|[1-9][0-9]*)$/.test(raw)) return undefined;\n const length = Number(raw);\n\n return Number.isSafeInteger(length) ? length : undefined;\n};\n\nconst readScreenshot = Effect.fn(\"BrowserQuickActionScreenshot.read\")(function* (\n response: Response,\n request: PageScreenshotRequest,\n) {\n const body = response.body;\n\n if (body === null) {\n return yield* protocolError(\"The screenshot response had no body\");\n }\n if (!pngResponse(response)) {\n yield* cancelBody(body);\n\n return yield* protocolError(\"The screenshot response was not image/png\");\n }\n const length = declaredLength(response);\n\n if (length !== undefined && length > request.limits.maxOutputBytes) {\n yield* cancelBody(body);\n\n return yield* PageScreenshotOutputLimitError.make({\n implementation: browserQuickActionImplementation,\n limit: request.limits.maxOutputBytes,\n observed: length,\n });\n }\n\n const reader = yield* Effect.acquireRelease(\n Effect.try({\n try: () => body.getReader(),\n catch: (cause) => protocolError(\"Opening the screenshot response failed\", cause),\n }),\n releaseScreenshotReader,\n );\n\n const chunks: Array<Uint8Array> = [];\n let observed = 0;\n\n while (true) {\n const next = yield* Effect.tryPromise({\n try: () => reader.read(),\n catch: (cause) => protocolError(\"Reading the screenshot response failed\", cause),\n });\n\n if (next.done) break;\n observed += next.value.byteLength;\n if (observed > request.limits.maxOutputBytes) {\n return yield* PageScreenshotOutputLimitError.make({\n implementation: browserQuickActionImplementation,\n limit: request.limits.maxOutputBytes,\n observed,\n });\n }\n chunks.push(next.value);\n }\n const bytes = new Uint8Array(observed);\n let offset = 0;\n\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return bytes;\n}, Effect.scoped);\n\nconst makeScreenshot = (browser: BrowserQuickActionClient): PageScreenshotCapture =>\n Effect.fn(\"BrowserQuickActionScreenshot.capture\")(function* (\n request: PageScreenshotRequest,\n ): Effect.fn.Return<PageScreenshotResult, PageScreenshotError> {\n if (request.engine !== \"chromium\") {\n return yield* PageCaptureUnsupportedError.make({\n implementation: browserQuickActionImplementation,\n feature: \"engine\",\n message: \"The browser binding's screenshot action exposes no engine selector\",\n });\n }\n\n const response = yield* browser\n .screenshot(screenshotOptions(request))\n .pipe(\n Effect.mapError((error) =>\n protocolError(\"The browser binding rejected the screenshot\", error.cause),\n ),\n );\n\n if (response.status === 429) {\n const body = response.body;\n\n if (body !== null) yield* cancelBody(body);\n\n return yield* PageCaptureRateLimitedError.make({\n implementation: browserQuickActionImplementation,\n reason: \"rate\",\n ...(retryAfterMillis(response) === undefined\n ? {}\n : { retryAfterMillis: retryAfterMillis(response) }),\n message: \"The screenshot Quick Action was rate limited\",\n });\n }\n if (!response.ok) {\n const body = response.body;\n\n if (body !== null) yield* cancelBody(body);\n const message = `The screenshot Quick Action answered HTTP ${response.status}`;\n\n return yield* response.status >= 500 ? protocolError(message) : navigationError(message);\n }\n const bytes = yield* readScreenshot(response, request);\n\n return PageScreenshotResult.make({\n implementation: browserQuickActionImplementation,\n mediaType: \"image/png\",\n bytes,\n });\n });\n\n/** Native Browser Run screenshot adapter. It retains PNG bytes only for the caller's result. */\nexport const browserQuickActionScreenshotLayer = (): Layer.Layer<\n PageScreenshot,\n never,\n BrowserQuickActionBrowserBinding\n> =>\n Layer.effect(\n PageScreenshot,\n Effect.map(BrowserQuickActionBrowserBinding, (browser) =>\n PageScreenshot.of({ capture: makeScreenshot(browser) }),\n ),\n );\n","/** Public CloudflareBrowser API. Implementation helpers remain private. */\nexport {\n BrowserQuickActionBrowserBinding,\n BrowserQuickActionRpcError,\n BrowserQuickActionWorkersAi,\n BrowserQuickActionWorkersAiPolicyError,\n browserQuickActionCaptureLayer,\n browserQuickActionWorkersAiCaptureLayer,\n browserQuickActionScreenshotLayer,\n CloudflareBrowser,\n type BrowserQuickActionCaptureOptions,\n type BrowserQuickActionClient,\n type BrowserQuickActionWorkersAiPolicy,\n type CloudflareBrowserOptions,\n} from \"./internal/browser-quick-action.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgDA,MAAa,mCAAmC,sBAAsB,KAAK;CACzE,WAAW;CACX,UAAU;AACZ,CAAC;;AA4BD,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA;CACE,QAAQ,OAAO,SAAS;EAAC;EAAc;EAAW;EAAY;EAAS;EAAU;CAAM,CAAC;CACxF,OAAO,OAAO,OAAO;AACvB,CACF,CAAC,CAAC,CAAC;;AAQH,IAAa,mCAAb,MAAa,yCAAyC,QAAQ,QAG5D,CAAC,CAAC,oEAAoE,CAAC,CAAC;CACxE,OAAO,MACL,SAC+C;EAC/C,MAAM,UAAU,QAA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