@effect-agent/platform-cloudflare 0.1.0-beta.76 → 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.
@@ -1,4 +1,4 @@
1
- import { i as BrowserQuickActionWorkersAi } from "./CloudflareBrowser-Bj22nNUT.mjs";
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";
@@ -0,0 +1,64 @@
1
+ import { Layer, Redacted } from "effect";
2
+ import { HttpClient } from "effect/unstable/http";
3
+ declare namespace CloudflareAiGateway_d_exports {
4
+ export { ClientOptions, ProviderOptions, RestOptions, RouteOptions, provide, provider, rest };
5
+ }
6
+ /** Options understood by upstream Effect AI clients; no model or provider wrapper is created. */
7
+ interface ClientOptions {
8
+ readonly apiUrl: string;
9
+ readonly transformClient: (client: HttpClient.HttpClient) => HttpClient.HttpClient;
10
+ }
11
+ interface ProviderOptions {
12
+ readonly accountId: string;
13
+ readonly gatewayId: string;
14
+ /** Cloudflare's provider path, such as openai, anthropic, google-ai-studio, or perplexity-ai. */
15
+ readonly provider: string;
16
+ /** Omit only for an unauthenticated gateway with a separately supplied provider key. */
17
+ readonly apiToken?: Redacted.Redacted<string>;
18
+ }
19
+ interface RestOptions {
20
+ readonly accountId: string;
21
+ readonly gatewayId: string;
22
+ /** Cloudflare API token with Workers AI Read permission. */
23
+ readonly apiToken: Redacted.Redacted<string>;
24
+ /** Matches the paths appended by the upstream Effect client. */
25
+ readonly protocol: "responses" | "chat-completions" | "messages";
26
+ }
27
+ /** Choose exactly one route: a native provider path or an account REST protocol. */
28
+ type RouteOptions = (ProviderOptions & {
29
+ readonly protocol?: never;
30
+ }) | (RestOptions & {
31
+ readonly provider?: never;
32
+ });
33
+ /**
34
+ * Provider-native proxy for model calls, streaming, embeddings, and hosted tools supported
35
+ * by that provider. Pass the result to the upstream client's layer along with its apiKey
36
+ * for BYOK-in-request, or omit apiKey for Gateway stored keys / Unified Billing.
37
+ * Provider model names and request bodies pass through unchanged. This module is Node-safe.
38
+ * Custom transforms and redirect policies must retain this endpoint and credential boundary.
39
+ */
40
+ declare const provider: (options: ProviderOptions) => ClientOptions;
41
+ /**
42
+ * Cloudflare's account REST API (not the deprecated /compat API). Use provider-qualified
43
+ * model names, e.g. openai/gpt-4.1 or anthropic/claude-haiku-4.5, and omit provider apiKey.
44
+ * OpenAI clients append /responses or /chat/completions; Anthropic appends /v1/messages.
45
+ * Compatibility remains the responsibility of the selected upstream client and model.
46
+ */
47
+ declare const rest: (options: RestOptions) => ClientOptions;
48
+ /**
49
+ * Provide a Gateway-configured upstream client directly in a Layer pipeline.
50
+ * Pass the client's `layer` factory, or a callback adding client-specific options.
51
+ * The factory's errors and remaining services (such as HttpClient) stay visible.
52
+ * Model selection and resource ownership remain with the supplied upstream Layers.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * AnthropicLanguageModel.model("claude-haiku-4-5").pipe(
57
+ * Gateway.provide(AnthropicClient.layer, { ...options, provider: "anthropic" }),
58
+ * )
59
+ * ```
60
+ */
61
+ declare const provide: <Client, E, R>(clientLayer: (options: ClientOptions) => Layer.Layer<Client, E, R>, options: RouteOptions) => <RIn2, E2, ROut2>(self: Layer.Layer<ROut2, E2, RIn2>) => Layer.Layer<ROut2, E | E2, R | Exclude<RIn2, Client>>;
62
+ //#endregion
63
+ export { ClientOptions, ProviderOptions, RestOptions, RouteOptions, provide, provider, rest, CloudflareAiGateway_d_exports as t };
64
+ //# sourceMappingURL=CloudflareAiGateway.d.mts.map
@@ -0,0 +1,70 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { Context, Effect, Layer, Option, Redactable, Redacted, Schema } from "effect";
3
+ import { FetchHttpClient, Headers, HttpClient, HttpClientError, HttpClientRequest } from "effect/unstable/http";
4
+ //#region src/CloudflareAiGateway.ts
5
+ var CloudflareAiGateway_exports = /* @__PURE__ */ __exportAll({
6
+ provide: () => provide,
7
+ provider: () => provider,
8
+ rest: () => rest
9
+ });
10
+ const Segment = Schema.NonEmptyString.check(Schema.isMaxLength(256), Schema.isPattern(/^[a-zA-Z0-9_-]+$/));
11
+ const decodeSegment = Schema.decodeUnknownSync(Segment);
12
+ const redactGatewayToken = (headers, tokenHeader) => {
13
+ Object.defineProperty(headers, Redactable.symbolRedactable, {
14
+ configurable: true,
15
+ value: (context) => Headers.redact(headers, [...Context.get(context, Headers.CurrentRedactedNames), tokenHeader])
16
+ });
17
+ };
18
+ const clientOptions = (apiUrl, tokenHeader, apiToken, gatewayId) => Object.freeze({
19
+ apiUrl,
20
+ transformClient: (client) => client.pipe(HttpClient.mapRequestEffect((request) => {
21
+ const url = URL.parse(request.url);
22
+ if (url === null || url.username !== "" || url.password !== "" || !(url.href === apiUrl || url.href.startsWith(`${apiUrl}/`))) return Effect.fail(new HttpClientError.HttpClientError({ reason: new HttpClientError.InvalidUrlError({
23
+ request,
24
+ description: "Request is outside the configured Cloudflare AI Gateway endpoint"
25
+ }) }));
26
+ let prepared = request;
27
+ if (apiToken !== void 0) prepared = HttpClientRequest.setHeader(prepared, tokenHeader, `Bearer ${Redacted.value(apiToken)}`);
28
+ if (gatewayId !== void 0) prepared = HttpClientRequest.setHeader(prepared, "cf-aig-gateway-id", gatewayId);
29
+ return Effect.succeed(prepared);
30
+ }), HttpClient.transformResponse((effect) => Effect.gen(function* () {
31
+ const defaults = yield* Effect.serviceOption(FetchHttpClient.RequestInit);
32
+ return yield* effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, {
33
+ ...Option.getOrElse(defaults, () => ({})),
34
+ redirect: "error"
35
+ }));
36
+ })), HttpClient.transformResponse((effect) => effect.pipe(Effect.tap((response) => Effect.sync(() => redactGatewayToken(response.request.headers, tokenHeader))), Effect.tapError((error) => Effect.sync(() => redactGatewayToken(error.reason.request.headers, tokenHeader))), Effect.updateService(Headers.CurrentRedactedNames, (names) => [...names, tokenHeader]))))
37
+ });
38
+ /**
39
+ * Provider-native proxy for model calls, streaming, embeddings, and hosted tools supported
40
+ * by that provider. Pass the result to the upstream client's layer along with its apiKey
41
+ * for BYOK-in-request, or omit apiKey for Gateway stored keys / Unified Billing.
42
+ * Provider model names and request bodies pass through unchanged. This module is Node-safe.
43
+ * Custom transforms and redirect policies must retain this endpoint and credential boundary.
44
+ */
45
+ const provider = (options) => clientOptions(`https://gateway.ai.cloudflare.com/v1/${decodeSegment(options.accountId)}/${decodeSegment(options.gatewayId)}/${decodeSegment(options.provider)}`, "cf-aig-authorization", options.apiToken);
46
+ /**
47
+ * Cloudflare's account REST API (not the deprecated /compat API). Use provider-qualified
48
+ * model names, e.g. openai/gpt-4.1 or anthropic/claude-haiku-4.5, and omit provider apiKey.
49
+ * OpenAI clients append /responses or /chat/completions; Anthropic appends /v1/messages.
50
+ * Compatibility remains the responsibility of the selected upstream client and model.
51
+ */
52
+ const rest = (options) => clientOptions(`https://api.cloudflare.com/client/v4/accounts/${decodeSegment(options.accountId)}/ai${options.protocol === "messages" ? "" : "/v1"}`, "authorization", options.apiToken, decodeSegment(options.gatewayId));
53
+ /**
54
+ * Provide a Gateway-configured upstream client directly in a Layer pipeline.
55
+ * Pass the client's `layer` factory, or a callback adding client-specific options.
56
+ * The factory's errors and remaining services (such as HttpClient) stay visible.
57
+ * Model selection and resource ownership remain with the supplied upstream Layers.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * AnthropicLanguageModel.model("claude-haiku-4-5").pipe(
62
+ * Gateway.provide(AnthropicClient.layer, { ...options, provider: "anthropic" }),
63
+ * )
64
+ * ```
65
+ */
66
+ const provide = (clientLayer, options) => Layer.provide(clientLayer(options.provider !== void 0 ? provider(options) : rest(options)));
67
+ //#endregion
68
+ export { provide, provider, rest, CloudflareAiGateway_exports as t };
69
+
70
+ //# sourceMappingURL=CloudflareAiGateway.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CloudflareAiGateway.mjs","names":[],"sources":["../src/CloudflareAiGateway.ts"],"sourcesContent":["import { Context, Effect, Layer, Option, Redactable, Redacted, Schema } from \"effect\";\nimport {\n FetchHttpClient,\n Headers,\n HttpClient,\n HttpClientError,\n HttpClientRequest,\n} from \"effect/unstable/http\";\n\nconst Segment = Schema.NonEmptyString.check(\n Schema.isMaxLength(256),\n Schema.isPattern(/^[a-zA-Z0-9_-]+$/),\n);\n\nconst decodeSegment = Schema.decodeUnknownSync(Segment);\n\n/** Options understood by upstream Effect AI clients; no model or provider wrapper is created. */\nexport interface ClientOptions {\n readonly apiUrl: string;\n readonly transformClient: (client: HttpClient.HttpClient) => HttpClient.HttpClient;\n}\n\nexport interface ProviderOptions {\n readonly accountId: string;\n readonly gatewayId: string;\n /** Cloudflare's provider path, such as openai, anthropic, google-ai-studio, or perplexity-ai. */\n readonly provider: string;\n /** Omit only for an unauthenticated gateway with a separately supplied provider key. */\n readonly apiToken?: Redacted.Redacted<string>;\n}\n\nexport interface RestOptions {\n readonly accountId: string;\n readonly gatewayId: string;\n /** Cloudflare API token with Workers AI Read permission. */\n readonly apiToken: Redacted.Redacted<string>;\n /** Matches the paths appended by the upstream Effect client. */\n readonly protocol: \"responses\" | \"chat-completions\" | \"messages\";\n}\n\n/** Choose exactly one route: a native provider path or an account REST protocol. */\nexport type RouteOptions =\n | (ProviderOptions & { readonly protocol?: never })\n | (RestOptions & { readonly provider?: never });\n\nconst redactGatewayToken = (headers: Headers.Headers, tokenHeader: string): void => {\n // HTTP tracing can copy headers after preprocessing. Attach the public redaction\n // protocol to the final request as well, before a provider builds error details.\n Object.defineProperty(headers, Redactable.symbolRedactable, {\n configurable: true,\n value: (context: Context.Context<never>) =>\n Headers.redact(headers, [...Context.get(context, Headers.CurrentRedactedNames), tokenHeader]),\n });\n};\n\nconst clientOptions = (\n apiUrl: string,\n tokenHeader: \"authorization\" | \"cf-aig-authorization\",\n apiToken: Redacted.Redacted<string> | undefined,\n gatewayId?: string,\n): ClientOptions =>\n Object.freeze({\n apiUrl,\n transformClient: (client: HttpClient.HttpClient) =>\n client.pipe(\n HttpClient.mapRequestEffect((request) => {\n const url = URL.parse(request.url);\n\n // Check the normalized URL too: dot segments must not escape this account or gateway.\n if (\n url === null ||\n url.username !== \"\" ||\n url.password !== \"\" ||\n !(url.href === apiUrl || url.href.startsWith(`${apiUrl}/`))\n ) {\n return Effect.fail(\n new HttpClientError.HttpClientError({\n reason: new HttpClientError.InvalidUrlError({\n request,\n description: \"Request is outside the configured Cloudflare AI Gateway endpoint\",\n }),\n }),\n );\n }\n let prepared = request;\n\n if (apiToken !== undefined) {\n prepared = HttpClientRequest.setHeader(\n prepared,\n tokenHeader,\n `Bearer ${Redacted.value(apiToken)}`,\n );\n }\n if (gatewayId !== undefined) {\n prepared = HttpClientRequest.setHeader(prepared, \"cf-aig-gateway-id\", gatewayId);\n }\n\n return Effect.succeed(prepared);\n }),\n HttpClient.transformResponse((effect) =>\n Effect.gen(function* () {\n const defaults = yield* Effect.serviceOption(FetchHttpClient.RequestInit);\n\n return yield* effect.pipe(\n Effect.provideService(FetchHttpClient.RequestInit, {\n ...Option.getOrElse(defaults, () => ({})),\n redirect: \"error\",\n }),\n );\n }),\n ),\n HttpClient.transformResponse((effect) =>\n effect.pipe(\n Effect.tap((response) =>\n Effect.sync(() => redactGatewayToken(response.request.headers, tokenHeader)),\n ),\n Effect.tapError((error) =>\n Effect.sync(() => redactGatewayToken(error.reason.request.headers, tokenHeader)),\n ),\n Effect.updateService(Headers.CurrentRedactedNames, (names) => [...names, tokenHeader]),\n ),\n ),\n ),\n });\n\n/**\n * Provider-native proxy for model calls, streaming, embeddings, and hosted tools supported\n * by that provider. Pass the result to the upstream client's layer along with its apiKey\n * for BYOK-in-request, or omit apiKey for Gateway stored keys / Unified Billing.\n * Provider model names and request bodies pass through unchanged. This module is Node-safe.\n * Custom transforms and redirect policies must retain this endpoint and credential boundary.\n */\nexport const provider = (options: ProviderOptions): ClientOptions =>\n clientOptions(\n `https://gateway.ai.cloudflare.com/v1/${decodeSegment(options.accountId)}/${decodeSegment(options.gatewayId)}/${decodeSegment(options.provider)}`,\n \"cf-aig-authorization\",\n options.apiToken,\n );\n\n/**\n * Cloudflare's account REST API (not the deprecated /compat API). Use provider-qualified\n * model names, e.g. openai/gpt-4.1 or anthropic/claude-haiku-4.5, and omit provider apiKey.\n * OpenAI clients append /responses or /chat/completions; Anthropic appends /v1/messages.\n * Compatibility remains the responsibility of the selected upstream client and model.\n */\nexport const rest = (options: RestOptions): ClientOptions =>\n clientOptions(\n `https://api.cloudflare.com/client/v4/accounts/${decodeSegment(options.accountId)}/ai${options.protocol === \"messages\" ? \"\" : \"/v1\"}`,\n \"authorization\",\n options.apiToken,\n decodeSegment(options.gatewayId),\n );\n\n/**\n * Provide a Gateway-configured upstream client directly in a Layer pipeline.\n * Pass the client's `layer` factory, or a callback adding client-specific options.\n * The factory's errors and remaining services (such as HttpClient) stay visible.\n * Model selection and resource ownership remain with the supplied upstream Layers.\n *\n * @example\n * ```ts\n * AnthropicLanguageModel.model(\"claude-haiku-4-5\").pipe(\n * Gateway.provide(AnthropicClient.layer, { ...options, provider: \"anthropic\" }),\n * )\n * ```\n */\nexport const provide = <Client, E, R>(\n clientLayer: (options: ClientOptions) => Layer.Layer<Client, E, R>,\n options: RouteOptions,\n) => Layer.provide(clientLayer(options.provider !== undefined ? provider(options) : rest(options)));\n"],"mappings":";;;;;;;;;AASA,MAAM,UAAU,OAAO,eAAe,MACpC,OAAO,YAAY,GAAG,GACtB,OAAO,UAAU,kBAAkB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AC7E,GACA,OAAO,UAAU,UACf,OAAO,WAAW,mBAAmB,MAAM,OAAO,QAAQ,SAAS,WAAW,CAAC,CACjF,GACA,OAAO,cAAc,QAAQ,uBAAuB,UAAU,CAAC,GAAG,OAAO,WAAW,CAAC,CACvF,CACF,CACF;AACJ,CAAC;;;;;;;;AASH,MAAa,YAAY,YACvB,cACE,wCAAwC,cAAc,QAAQ,SAAS,EAAE,GAAG,cAAc,QAAQ,SAAS,EAAE,GAAG,cAAc,QAAQ,QAAQ,KAC9I,wBACA,QAAQ,QACV;;;;;;;AAQF,MAAa,QAAQ,YACnB,cACE,iDAAiD,cAAc,QAAQ,SAAS,EAAE,KAAK,QAAQ,aAAa,aAAa,KAAK,SAC9H,iBACA,QAAQ,UACR,cAAc,QAAQ,SAAS,CACjC;;;;;;;;;;;;;;AAeF,MAAa,WACX,aACA,YACG,MAAM,QAAQ,YAAY,QAAQ,aAAa,KAAA,IAAY,SAAS,OAAO,IAAI,KAAK,OAAO,CAAC,CAAC"}
@@ -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) => bodyText.length === 0 ? void 0 : new Error(boundedDiagnostic(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-Bj22nNUT.mjs.map
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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O,eAAe,UAAU,OAAO;CAErD,OAAO,qBAAqB,KAAK;EAC/B,gBAAgB;EAChB,WAAW;EACX;CACF,CAAC;AACH,CAAC;;AAGH,MAAa,0CAKX,MAAM,OACJ,gBACA,OAAO,IAAI,mCAAmC,YAC5C,eAAe,GAAG,EAAE,SAAS,eAAe,OAAO,EAAE,CAAC,CACxD,CACF"}
@@ -1,2 +1,2 @@
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-Bj22nNUT.mjs";
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,CACnE;CAEA,MAAM,QAAQ,OAAO,OAAO,oBAAoB,aAAa,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,KACzE,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAAW,CAAC,CAAC,CACnE;CAEA,YAAY,OAAO,OAAO,oBAAoB,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,KAClE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,WAAW,MAAM,OACrB,qBACA,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO,mBAAmB;EAExC,MAAM,UAAU,OAAO,OAAO,oBAAoB,sBAAsB,CAAC,CACvE,MAAM,IAAI,GAAG,IACf,CAAC,CAAC,KAAK,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,SAAS,CAAC,CAAC,CAAC;EAEvE,OAAO,EAAE,WAAW,gBAAgB,IAAI,KAAK,EAAE,QAAQ,CAAC,EAAE;CAC5D,CAAC,CACH;CAEA,MAAM,QAAQ,MAAM,OAClB,OAAO,IAAI,mBAAmB,qBAAqB,UACjD,iCACE,MAAM,IAAI,SACV,QAAQ,iBAAiB,4BAC3B,CACF,CACF,CAAC,CAAC,KAAK,MAAM,QAAQ,QAAQ,cAAc,wBAAwB,KAAK,CAAC;CAEzE,MAAM,cAAc,MAAM,MAAM,OAAO,IAAI,CAAC,CAAC,KAAK,MAAM,aAAa,QAAQ,CAAC;CAE9E,MAAM,UAIF,MAAM,cACR,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO,mBAAmB;EACxC,MAAM,QAAQ,OAAO,OAAO;EAE5B,OAAO,OAAO,oBAAoB,eAAe,CAAC,CAChD,QAAQ,aAAa,sBACvB,CAAC,CAAC,KAAK,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAAW,CAAC,CAAC,CAAC;EAEzE,OAAO,OAAO,MAAM,sBAAsB,MAAM,eAAe,aAAa,KAAK,CAAC;CACpF,CAAC,CACH;CAIA,OAAOA,cAAsB,KAM3B,SAAS,EAAE,KAAA,EARC,SAAS,YAAoB,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,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,KACzE,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAAW,CAAC,CAAC,CACnE;CAEA,YAAY,OAAO,OAAO,oBAAoB,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,KAClE,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAAW,CAAC,CAAC,CAC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