@effect-agent/platform-cloudflare 0.1.0-beta.84 → 0.1.0-beta.85

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.
Files changed (40) hide show
  1. package/dist/Alarm.mjs +1 -1
  2. package/dist/Alarm.mjs.map +1 -1
  3. package/dist/BrowserRestCrawl.mjs +1 -1
  4. package/dist/BrowserRestCrawl.mjs.map +1 -1
  5. package/dist/CloudflareMemory.mjs +5 -5
  6. package/dist/CloudflareMemory.mjs.map +1 -1
  7. package/dist/CloudflareScheduling.mjs +2 -2
  8. package/dist/CloudflareScheduling.mjs.map +1 -1
  9. package/dist/CloudflareSubscriptions.mjs +12 -6
  10. package/dist/CloudflareSubscriptions.mjs.map +1 -1
  11. package/dist/CloudflareThreadClient.d.mts +216 -6
  12. package/dist/CloudflareThreadClient.mjs +2 -2
  13. package/dist/CloudflareThreadClient.mjs.map +1 -1
  14. package/dist/InteractiveBrowser.mjs +15 -15
  15. package/dist/InteractiveBrowser.mjs.map +1 -1
  16. package/dist/ProtectedBrowser.mjs +12 -12
  17. package/dist/ProtectedBrowser.mjs.map +1 -1
  18. package/dist/{ThreadObject-BS1gRV0V.d.mts → ThreadObject-DZMkwIBh.d.mts} +8 -12
  19. package/dist/{ThreadObject-mmWMMWdY.mjs → ThreadObject-gyx8Qq03.mjs} +5 -3
  20. package/dist/ThreadObject-gyx8Qq03.mjs.map +1 -0
  21. package/dist/ThreadObject.d.mts +1 -1
  22. package/dist/ThreadObject.mjs +1 -1
  23. package/dist/{browser-session-lifecycle-CUbVfEgP.mjs → browser-session-lifecycle-CmbQABHC.mjs} +5 -5
  24. package/dist/browser-session-lifecycle-CmbQABHC.mjs.map +1 -0
  25. package/dist/index.d.mts +1 -1
  26. package/dist/index.mjs +1 -1
  27. package/package.json +1 -1
  28. package/src/Alarm.ts +6 -6
  29. package/src/BrowserRestCrawl.ts +1 -1
  30. package/src/CloudflareMemory.ts +7 -7
  31. package/src/CloudflareScheduling.ts +2 -2
  32. package/src/CloudflareSubscriptions.ts +18 -18
  33. package/src/CloudflareThreadClient.ts +2 -2
  34. package/src/InteractiveBrowser.ts +19 -22
  35. package/src/internal/browser-session-lifecycle.ts +8 -8
  36. package/src/internal/message-delivery.ts +5 -6
  37. package/src/protected-browser/binding.ts +1 -1
  38. package/src/protected-browser/policy.ts +29 -31
  39. package/dist/ThreadObject-mmWMMWdY.mjs.map +0 -1
  40. package/dist/browser-session-lifecycle-CUbVfEgP.mjs.map +0 -1
package/dist/Alarm.mjs CHANGED
@@ -253,7 +253,7 @@ var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effe
253
253
  const projection = yield* ThreadProjectionMaintenance;
254
254
  const messages = yield* ThreadMessageDelivery;
255
255
  const host = yield* ThreadHostMaintenance;
256
- const projectionDeadline = projection.pendingDeadline.pipe(Effect.catchCause((cause) => Cause.hasInterrupts(cause) ? Effect.failCause(cause) : Effect.logError("Thread projection deadline unavailable", cause).pipe(Effect.as(Option.some(0)))));
256
+ const projectionDeadline = projection.pendingDeadline.pipe(Effect.catchCauseIf((cause) => !Cause.hasInterrupts(cause), (cause) => Effect.logError("Thread projection deadline unavailable", cause).pipe(Effect.as(Option.some(0)))));
257
257
  const pendingDeadline = Effect.gen(function* () {
258
258
  return earliestDeadline(earliestDeadline(yield* publication.pendingDeadline, yield* messages.pendingDeadline), earliestDeadline(yield* projectionDeadline, yield* host.pendingDeadline));
259
259
  });
@@ -1 +1 @@
1
- {"version":3,"file":"Alarm.mjs","names":[],"sources":["../src/Alarm.ts"],"sourcesContent":["import { ThreadId } from \"@effect-agent/core/Identifiers\";\nimport { type DurableBindingFailure } from \"@effect-agent/thread/AgentRegistration\";\nimport {\n DurableAgentRuntime,\n type DurableWorkerFailure,\n type RecoveryReport,\n} from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { SubmissionLedger, type SubmissionSnapshot } from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n ThreadProjectionMaintenance,\n drainDue,\n type ThreadProjectionError,\n} from \"@effect-agent/thread/ThreadProjectionMaintenance\";\nimport {\n Cause,\n Clock,\n Context,\n DateTime,\n Deferred,\n Effect,\n Exit,\n Fiber,\n Layer,\n Option,\n Random,\n Ref,\n Schema,\n Semaphore,\n Stream,\n} from \"effect\";\nimport { SqlClient } from \"effect/unstable/sql/SqlClient\";\n\nimport { DurableObjectContext } from \"./CloudflareBindings.ts\";\nimport { CloudflareDurableRuntimeConfig } from \"./CloudflareConfig.ts\";\nimport { safeCauseMessage } from \"./internal/boundary.ts\";\n\n/**\n * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE\n * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement\n * and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and\n * the slot always holds the EARLIEST deadline any caller asked for.\n *\n * The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable\n * maintenance generation and a committed alarm. Stable externally-driven waits may be\n * nonterminal without retaining an alarm; their resolving mutation advances the generation and\n * restores the alarm atomically.\n */\n\n/** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */\nexport class DurableAlarmError extends Schema.TaggedError<DurableAlarmError>()(\n \"DurableAlarmError\",\n {\n operation: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\nconst alarmFailure =\n (operation: string) =>\n (cause: unknown): DurableAlarmError =>\n DurableAlarmError.make({\n operation,\n message: safeCauseMessage(cause, \"The Cloudflare alarm API failed without a diagnostic\"),\n cause,\n });\n\n// SQL and raw KV/alarm operations share one physical SQLite transaction. Reserve its\n// connection for each short storage operation, never around a mutation or snapshot body.\nconst makeStorageOperation = Effect.map(\n SqlClient,\n (sql) =>\n <A>(operation: string, execute: () => Promise<A>) =>\n Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => {\n const body = Effect.uninterruptible(\n Effect.tryPromise({ try: execute, catch: alarmFailure(operation) }),\n );\n\n return current._tag === \"Some\"\n ? body\n : Effect.scoped(\n Effect.andThen(sql.reserve.pipe(Effect.mapError(alarmFailure(operation))), body),\n );\n }),\n);\n\n/** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */\nexport class DurableAlarmService extends Context.Service<\n DurableAlarmService,\n {\n /** The scheduled deadline in epoch milliseconds, if any. */\n readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n /** Replace the slot with this deadline. */\n readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /** Keep the EARLIER of the existing deadline and this one (the multiplexing rule). */\n readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /**\n * Arm an immediate alarm (the durable, coalescing local wake) — DEFERRED while a\n * maintenance pass is executing. Workerd cancels an in-flight alarm handler when a new\n * EARLIER deadline is written during its execution (`requestScheduledAlarm`), and the\n * maintenance pass runs INSIDE the alarm handler: an immediate wake landing mid-pass\n * (a routed port mutation, a sibling's `wake()`, the coordinator's own local notify)\n * would kill the running Attempt — manufacturing an ownership loss no real eviction\n * caused, and routing open uncertain-class Tool Calls into spurious Unknown Outcomes.\n * Deferral is contract-safe: wakes are droppable hints, every mutating entry point\n * pre-arms BEFORE its first durable mutation (the alarm invariant never rests on this\n * call). The pass's durable generation check observes any racing mutation, so the\n * in-memory hint does not need to be flushed after a stable wait is acknowledged.\n */\n readonly scheduleNow: Effect.Effect<void, DurableAlarmError>;\n /**\n * Run one maintenance pass with wake deferral (see `scheduleNow`). Calls made while `body`\n * executes are droppable promptness hints; correctness rests on the durable generation.\n */\n readonly withWakesDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n /** Clear the slot; correctness-sensitive clears live in maintenance generation transactions. */\n readonly cancel: Effect.Effect<void, DurableAlarmError>;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableAlarmService\") {\n static readonly layer: Layer.Layer<DurableAlarmService, never, DurableObjectContext | SqlClient> =\n Layer.effect(DurableAlarmService)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n /**\n * In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no\n * running pass, and a deferred wake lost to eviction was only ever a promptness hint\n * on top of the already-committed pre-armed alarm.\n */\n const runningPasses = yield* Ref.make(0);\n\n const storageOperation = yield* makeStorageOperation;\n\n const scheduled = storageOperation(\"get alarm\", () => ctx.storage.getAlarm()).pipe(\n Effect.map((deadline) =>\n deadline === null ? Option.none<number>() : Option.some(deadline),\n ),\n );\n\n const scheduleAt = (epochMillis: number) =>\n storageOperation(\"set alarm\", () => ctx.storage.setAlarm(epochMillis));\n\n const ensureScheduledBy = (epochMillis: number) =>\n storageOperation(\"ensure alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const existing = await transaction.getAlarm();\n\n if (existing === null || existing > epochMillis) {\n await transaction.setAlarm(epochMillis);\n }\n }),\n );\n\n const armNow = Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => ensureScheduledBy(now)),\n );\n\n const scheduleNow = Ref.get(runningPasses).pipe(\n Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),\n );\n\n const withWakesDeferred = <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Ref.update(runningPasses, (passes) => passes + 1).pipe(\n Effect.andThen(body),\n Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1)),\n );\n\n const cancel = storageOperation(\"delete alarm\", () => ctx.storage.deleteAlarm());\n\n return DurableAlarmService.of({\n scheduled,\n scheduleAt,\n ensureScheduledBy,\n scheduleNow,\n withWakesDeferred,\n cancel,\n });\n }),\n );\n}\n\n/** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */\nexport class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(\n \"@effect-agent/platform-cloudflare/MaintenancePassReport\",\n)({\n /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */\n phase: Schema.Literals([\"caught-up\", \"actionable\"]),\n /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */\n recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Whether the head Attempt settled. Joined input may settle with that head. */\n settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */\n alarm: Schema.Literals([\"rearmed\", \"cleared\"]),\n}) {}\n\n/** Fault boundaries around every maintenance-owned durable mutation. */\nexport type ThreadMaintenanceFailpointLocation =\n | \"maintenance:dirty:before\"\n | \"maintenance:dirty:after\"\n | \"maintenance:mutation:armed\"\n | \"maintenance:mutation:finished\"\n | \"maintenance:ensure:before\"\n | \"maintenance:ensure:after\"\n | \"maintenance:begin:before\"\n | \"maintenance:begin:after\"\n | \"maintenance:select:before\"\n | \"maintenance:select:after\"\n | \"maintenance:finish:before\"\n | \"maintenance:finish:after\";\n\nexport type ThreadMaintenanceFailpointHandler = (\n location: ThreadMaintenanceFailpointLocation,\n) => Effect.Effect<void>;\n\n/** Test-only fault authority; production uses the inert layer. */\nexport class ThreadMaintenanceFailpoint extends Context.Service<\n ThreadMaintenanceFailpoint,\n {\n readonly hit: ThreadMaintenanceFailpointHandler;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint\") {\n static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });\n}\n\n/**\n * Durable host publication of canonical records and ledger approval/abort/resolution intents.\n * The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery\n * is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.\n *\n * `invalidate`, `prepareGeneration` and `pendingDeadline` must be bounded local operations.\n * `prepareGeneration` durably invalidates a scan only when its generation changes; repeated\n * calls must preserve partial scan progress. It runs with no source mutation in flight.\n * `drain` performs bounded delivery and persists retries before returning. A pending deadline\n * defers runtime recovery/Attempts, allowing committed host publications to drain first.\n * Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call\n * resources with Effect.scoped; Layer construction owns incarnation resources (eviction need\n * not run finalizers). Do not hold a local hook behind network I/O or call back into producers.\n */\nexport interface ThreadPublicationService {\n readonly invalidate: Effect.Effect<void, DurableAlarmError>;\n readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>;\n readonly drain: Effect.Effect<void, DurableAlarmError>;\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n}\n\n/** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */\nexport class ThreadPublication extends Context.Service<\n ThreadPublication,\n ThreadPublicationService\n>()(\"@effect-agent/platform-cloudflare/ThreadPublication\") {\n static readonly layer = Layer.succeed(this)({\n invalidate: Effect.void,\n prepareGeneration: () => Effect.void,\n drain: Effect.void,\n pendingDeadline: Effect.succeed(Option.none()),\n });\n}\n\n/**\n * Host-assembled message recovery, supplied by ThreadObject.layer even when the application\n * rebuilds ThreadMaintenance. These obligations outlive source Runs and never defer a ready\n * source Attempt while a destination is processing an accepted message.\n */\nexport const ThreadMessageDelivery = Context.Reference<{\n readonly drain: Effect.Effect<void, DurableAlarmError>;\n /** Drain inserts and due retries during source work, finishing the bounded wave on completion. */\n readonly drainUntil?: (\n finished: Deferred.Deferred<void>,\n ) => Effect.Effect<void, DurableAlarmError>;\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n}>(\"@effect-agent/platform-cloudflare/ThreadMessageDelivery\", {\n defaultValue: () => ({ drain: Effect.void, pendingDeadline: Effect.succeed(Option.none()) }),\n});\n\n/**\n * Application obligations sharing this Object's alarm. The deadline read is local and\n * read-only. Drain beside the native Attempt and always finish one initial bounded wave,\n * even when `finished` was already signalled. Then stop starting new waves on that signal\n * and finish the bounded current wave before returning. Native maintenance joins that work\n * before acknowledging a generation. Mutations use the same ThreadMutationGate; hooks never\n * write the raw alarm slot. Pending host work does not defer a ready model Attempt.\n */\nexport const ThreadHostMaintenance = Context.Reference<{\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n readonly drainUntil: (\n finished: Deferred.Deferred<void>,\n ) => Effect.Effect<void, DurableAlarmError>;\n}>(\"@effect-agent/platform-cloudflare/ThreadHostMaintenance\", {\n defaultValue: () => ({\n pendingDeadline: Effect.succeed(Option.none()),\n drainUntil: () => Effect.void,\n }),\n});\n\nconst earliestDeadline = (\n left: Option.Option<number>,\n right: Option.Option<number>,\n): Option.Option<number> =>\n Option.isSome(left)\n ? Option.isSome(right)\n ? Option.some(Math.min(left.value, right.value))\n : left\n : right;\n\n/** @internal A committed source operation must not become a failed operation because delivery failed. */\nexport const publishCommitted = Effect.gen(function* () {\n const publication = yield* ThreadPublication;\n\n yield* publication.invalidate.pipe(Effect.andThen(publication.drain));\n}).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.logError(\"Thread publication deferred after source commit\", cause),\n ),\n);\n\nconst MaintenanceGeneration = Schema.BigIntFromString.check(\n Schema.isGreaterThanOrEqualToBigInt(0n),\n);\n\n/** Versioned, platform-private maintenance state stored through Durable Object KV. */\nclass ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(\n \"@effect-agent/platform-cloudflare/ThreadMaintenanceState\",\n)({\n schemaVersion: Schema.Literal(1),\n dirty: MaintenanceGeneration,\n processed: MaintenanceGeneration,\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** One physical-owner cursor; old single-lane records need no conversion. */\n lastServedThreadId: Schema.optionalKey(ThreadId),\n}) {}\n\nconst MAINTENANCE_STATE_KEY = \"effect-agent:thread-maintenance:v1\";\nconst decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);\nconst encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);\n\nconst initialMaintenanceState = (): ThreadMaintenanceState =>\n ThreadMaintenanceState.make({\n schemaVersion: 1,\n // Bootstrap Objects created by the pre-generation release without scanning the ledger in\n // the constructor. One useful pass classifies and acknowledges any existing obligation.\n dirty: 1n,\n processed: 0n,\n nonterminal: 0,\n });\n\nconst readMaintenanceState = async (\n transaction: DurableObjectTransaction,\n): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {\n const encoded = await transaction.get(MAINTENANCE_STATE_KEY);\n\n return encoded === undefined\n ? { state: initialMaintenanceState(), initialized: false }\n : { state: decodeMaintenanceState(encoded), initialized: true };\n};\n\nconst ensureTransactionAlarmBy = async (\n transaction: DurableObjectTransaction,\n deadline: number,\n): Promise<void> => {\n const scheduled = await transaction.getAlarm();\n\n if (scheduled === null || scheduled > deadline) {\n await transaction.setAlarm(deadline);\n }\n};\n\nconst stableExternalWait = (\n snapshot: SubmissionSnapshot,\n reports: ReadonlyMap<string, RecoveryReport>,\n): boolean => {\n const decision = reports.get(snapshot.submissionId)?.decision._tag;\n\n // An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.\n if (decision === \"SettleAborted\") return false;\n switch (snapshot.state) {\n case \"suspended\":\n case \"joined\":\n return true;\n case \"unknown\":\n return decision === \"AwaitUnknownResolution\" || decision === \"MarkUnknown\";\n case \"admitted\":\n return reports.get(snapshot.submissionId)?.decision._tag === \"AwaitParentEstablishment\";\n case \"input-applied\":\n case \"joining\":\n case \"ready\":\n case \"running\":\n case \"settled\":\n case \"terminalizing\":\n return false;\n }\n};\n\n/**\n * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.\n * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance\n * Layers must reuse that instance; a second gate cannot observe the native producers' activity.\n */\nexport class ThreadMutationGate extends Context.Service<\n ThreadMutationGate,\n {\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n readonly withSnapshot: <A, E, R>(\n body: (active: number) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/internal/ThreadMutationGate\") {\n static readonly layer = Layer.effect(this)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* CloudflareDurableRuntimeConfig;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n // A fresh incarnation has no live mutations; durable generations survive eviction.\n const activeMutations = yield* Ref.make(0);\n const generationGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = yield* makeStorageOperation;\n\n const beginMutation = Effect.fn(\"ThreadMaintenance.beginMutation\")(function* () {\n yield* failpoint.hit(\"maintenance:dirty:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"advance maintenance generation\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const next = ThreadMaintenanceState.make({\n ...state,\n dirty: state.dirty + 1n,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n // The earliest configured retry bounds a newly actionable mutation without relying\n // on its best-effort immediate wake hint.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n }),\n );\n yield* failpoint.hit(\"maintenance:dirty:after\");\n yield* Ref.update(activeMutations, (active) => active + 1);\n });\n\n const endMutation = generationGate.withPermit(\n Ref.update(activeMutations, (active) => Math.max(0, active - 1)),\n );\n\n const withMutation = <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ): Effect.Effect<A, E | DurableAlarmError, R> =>\n Effect.acquireUseRelease(\n generationGate.withPermit(beginMutation()),\n () =>\n failpoint.hit(\"maintenance:mutation:armed\").pipe(\n Effect.andThen(body),\n Effect.tap(() => failpoint.hit(\"maintenance:mutation:finished\")),\n ),\n () => endMutation,\n );\n\n return ThreadMutationGate.of({\n withMutation,\n withSnapshot: (body) =>\n generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body)),\n });\n }),\n );\n}\n\nexport type MaintenancePassFailure =\n | DurableWorkerFailure\n | DurableBindingFailure\n | DurableAlarmError\n | ThreadProjectionError;\n\n/**\n * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).\n *\n * `pass` = generation snapshot/pre-arm → recovery → one head Attempt → generation acknowledgement:\n *\n * 1. One storage transaction reads dirty/processed and re-arms before work. A caught-up forced\n * alarm takes an O(1) path without recovery, ledger scans, or canonical-history reads.\n * 2. Recovery strictly precedes a new claim. One head Attempt advances the lane and requests\n * a safe yield after ten minutes. The whole event has a fourteen-minute cooperative timeout.\n * 3. The final transaction acknowledges only the generation observed at pass start. A racing\n * mutation therefore remains `dirty > processed` and retains its atomically-established alarm.\n * 4. Stable external waits acknowledge and clear. Autonomous retry, indeterminate, and lease\n * recovery states leave their generation dirty and retain bounded backoff rearming.\n */\nexport class ThreadMaintenance extends Context.Service<\n ThreadMaintenance,\n {\n /** One idempotent maintenance pass; failures propagate so workerd retries the alarm. */\n readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>;\n /**\n * Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty\n * generation has an alarm. It never scans the ledger or canonical history.\n */\n readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>;\n /**\n * Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty\n * generation and arm the alarm in one transaction BEFORE running the caller's mutation.\n * A pass cannot acknowledge while that mutation remains in flight.\n */\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenance\") {\n static readonly layer: Layer.Layer<\n ThreadMaintenance,\n never,\n | ThreadMutationGate\n | ThreadPublication\n | ThreadProjectionMaintenance\n | DurableAgentRuntime\n | SubmissionLedger\n | DurableAlarmService\n | ThreadMaintenanceFailpoint\n | CloudflareDurableRuntimeConfig\n | DurableObjectContext\n | SqlClient\n > = Layer.effect(ThreadMaintenance)(\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const alarm = yield* DurableAlarmService;\n const config = yield* CloudflareDurableRuntimeConfig;\n const { ctx } = yield* DurableObjectContext;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n\n /**\n * Consecutive no-progress passes — an in-memory CACHE, not state: a fresh incarnation\n * restarts at zero and merely re-arms sooner than a long-lived one would have.\n */\n const stalls = yield* Ref.make(0);\n const mutations = yield* ThreadMutationGate;\n const publication = yield* ThreadPublication;\n const projection = yield* ThreadProjectionMaintenance;\n const messages = yield* ThreadMessageDelivery;\n const host = yield* ThreadHostMaintenance;\n\n // A broken disposable index still needs a retry alarm and must not prevent startup.\n const projectionDeadline = projection.pendingDeadline.pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"Thread projection deadline unavailable\", cause).pipe(\n Effect.as(Option.some(0)),\n ),\n ),\n );\n\n const pendingDeadline = Effect.gen(function* () {\n return earliestDeadline(\n earliestDeadline(yield* publication.pendingDeadline, yield* messages.pendingDeadline),\n earliestDeadline(yield* projectionDeadline, yield* host.pendingDeadline),\n );\n });\n\n const maintenancePassGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = yield* makeStorageOperation;\n\n const ensureAlarm = Effect.fn(\"ThreadMaintenance.ensureAlarm\")(function* () {\n yield* failpoint.hit(\"maintenance:ensure:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"ensure maintenance alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.dirty > state.processed) {\n await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);\n }\n }),\n );\n const deadline = yield* pendingDeadline;\n\n if (Option.isSome(deadline)) {\n yield* runTransaction(\"ensure publication alarm\", () =>\n ctx.storage.transaction((transaction) =>\n ensureTransactionAlarmBy(\n transaction,\n Math.max(now + minimumAlarmDelay, deadline.value),\n ),\n ),\n );\n }\n yield* failpoint.hit(\"maintenance:ensure:after\");\n });\n\n const beginPass = Effect.fn(\"ThreadMaintenance.beginPass\")(function* () {\n yield* failpoint.hit(\"maintenance:begin:before\");\n const now = yield* Clock.currentTimeMillis;\n\n const result = yield* runTransaction(\"begin maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.processed >= state.dirty) {\n // Prearm even a publication-only pass before invoking any host hook.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return { _tag: \"CaughtUp\" as const, nonterminal: state.nonterminal };\n }\n // Pre-arm the earliest retry before recovery. A successful finish may move this slot\n // LATER to its bounded backoff, which does not cancel the running handler.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return {\n _tag: \"Actionable\" as const,\n generation: state.dirty,\n nonterminal: state.nonterminal,\n };\n }),\n );\n\n yield* failpoint.hit(\"maintenance:begin:after\");\n\n return result;\n });\n\n const rearmDelay = Effect.fn(\"ThreadMaintenance.rearmDelay\")(function* (progressed: boolean) {\n const priorStalls = yield* Ref.getAndUpdate(stalls, (count) =>\n progressed ? 0 : count + 1,\n );\n\n if (progressed) return config.alarmBackoffBase;\n const exponent = Math.min(priorStalls, 30);\n const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** exponent);\n const jitter = yield* Random.next;\n // Full jitter over [backoff/2, backoff]: desynchronizes retry storms without ever\n // waiting longer than the deterministic bound.\n const jittered = Math.ceil(backoff / 2 + (backoff / 2) * jitter);\n\n return Math.min(jittered, config.wakeScanInterval);\n });\n\n const pass = Effect.fn(\"ThreadMaintenance.pass\")(function* (\n yieldAfter: DateTime.Utc,\n ): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure> {\n const annotate = (report: MaintenancePassReport) =>\n Effect.annotateCurrentSpan({\n phase: report.phase,\n recovered: report.recovered,\n settled: report.settled,\n nonterminal: report.nonterminal,\n alarm: report.alarm,\n }).pipe(Effect.as(report));\n\n const started = yield* mutations.withSnapshot((activeAtStart) =>\n Effect.gen(function* () {\n const generation = yield* beginPass();\n\n if (generation._tag === \"Actionable\" && activeAtStart === 0) {\n // The gate excludes a producer starting between the snapshot and certification.\n yield* publication.prepareGeneration(generation.generation);\n }\n\n return { ...generation, activeAtStart };\n }),\n );\n\n // Deliver beside source work, including messages inserted by the running Attempt.\n // Slow destination RPCs never consume the source execution window. Stop starting\n // waves when source work ends, then join the bounded current wave before acknowledgement.\n const deliveryFinished = yield* Deferred.make<void>();\n\n const delivery = yield* Effect.forkChild(\n messages.drainUntil?.(deliveryFinished) ?? messages.drain,\n );\n\n const hostWork = yield* Effect.forkChild(host.drainUntil(deliveryFinished));\n\n const finishDelivery = Deferred.succeed(deliveryFinished, undefined).pipe(\n Effect.andThen(Fiber.awaitAll([delivery, hostWork])),\n Effect.flatMap((outcomes) =>\n Effect.forEach(outcomes, (outcome) => outcome, { discard: true }),\n ),\n );\n\n // Capture derived-index failures until canonical work has had its turn. Interruption\n // still stops the event; ordinary failures and defects retain the prearmed generation.\n const projected = yield* Effect.exit(\n drainDue.pipe(Effect.provideService(ThreadProjectionMaintenance, projection)),\n );\n\n if (Exit.isFailure(projected) && Cause.hasInterrupts(projected.cause))\n return yield* Effect.failCause(projected.cause);\n const deadline = yield* publication.pendingDeadline;\n\n if (\n started._tag === \"Actionable\" ||\n (Option.isSome(deadline) && deadline.value <= (yield* Clock.currentTimeMillis))\n ) {\n yield* publication.drain;\n }\n const pending = yield* publication.pendingDeadline;\n\n if (started._tag === \"CaughtUp\" || Option.isSome(pending)) {\n yield* finishDelivery;\n if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const disposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n // Re-read under the producer gate: a concurrent append/host mutation cannot be\n // cleared using a stale empty deadline. Dirty generations bound all producer races.\n const latest = yield* pendingDeadline;\n const now = yield* Clock.currentTimeMillis;\n\n return yield* runTransaction(\"finish publication pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const nativeDeadline =\n active > 0 || state.dirty > state.processed\n ? now + config.wakeScanInterval\n : Infinity;\n\n const next = Option.isSome(latest)\n ? Math.min(nativeDeadline, latest.value)\n : nativeDeadline;\n\n if (Number.isFinite(next)) {\n await transaction.setAlarm(Math.max(now + minimumAlarmDelay, next));\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"caught-up\",\n recovered: 0,\n settled: 0,\n nonterminal: started.nonterminal,\n alarm: disposition,\n }),\n );\n }\n // Step 2 — reconciliation strictly precedes new work in this pass (exit gate).\n const recovered: ReadonlyArray<RecoveryReport> = yield* runtime.runRecovery;\n const reports = new Map(recovered.map((report) => [report.submissionId, report]));\n const current = yield* Stream.runCollect(ledger.scanNonterminal);\n const heads = new Map<ThreadId, SubmissionSnapshot>();\n\n for (const row of current) {\n if (!heads.has(row.threadId)) heads.set(row.threadId, row);\n }\n\n const eligible = [...heads.values()]\n .filter((head) => !stableExternalWait(head, reports))\n .map((head) => head.threadId)\n .sort();\n\n let selected = eligible[0];\n\n if (heads.size > 1 && selected !== undefined) {\n yield* failpoint.hit(\"maintenance:select:before\");\n selected = yield* runTransaction(\"select maintenance lane\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const next =\n eligible.find(\n (threadId) =>\n state.lastServedThreadId === undefined || threadId > state.lastServedThreadId,\n ) ?? eligible[0];\n\n if (next !== undefined) {\n // Persist before the Attempt so an eviction or repeated yield cannot\n // monopolize the first lane. The generation and prearmed alarm survive.\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({ ...state, lastServedThreadId: next }),\n ),\n );\n }\n\n return next;\n }),\n );\n yield* failpoint.hit(\"maintenance:select:after\");\n }\n\n // One FIFO head per event, across all local lanes. The runtime keeps its normal\n // bounded Attempt and recovery contracts; followers belong to another alarm.\n const settlement =\n selected === undefined\n ? Option.none()\n : yield* runtime.processThreadHead(selected, { yieldAfter });\n\n yield* finishDelivery;\n if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);\n // Observe residual state before acknowledging this exact pass-start generation.\n const remaining = yield* Stream.runCollect(ledger.scanNonterminal);\n const waitingHeads = new Map<ThreadId, boolean>();\n\n const autonomous = remaining.some((snapshot) => {\n const headWaiting = waitingHeads.get(snapshot.threadId);\n\n if (headWaiting === undefined)\n waitingHeads.set(snapshot.threadId, stableExternalWait(snapshot, reports));\n // FIFO followers cannot execute through a stable external wait. Only plain queued\n // input is dormant here; admission repairs and accepted aborts still need a pass.\n if (\n headWaiting === true &&\n snapshot.state === \"ready\" &&\n reports.get(snapshot.submissionId)?.decision._tag === \"ApplyInput\"\n )\n return false;\n\n return !stableExternalWait(snapshot, reports);\n });\n\n const progressed =\n Option.isSome(settlement) ||\n recovered.some((report) => report.disposition === \"repaired\");\n\n const delay = autonomous ? yield* rearmDelay(progressed) : 0;\n const now = yield* Clock.currentTimeMillis;\n\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const alarmDisposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n const publicationDeadline = yield* pendingDeadline;\n\n return yield* runTransaction(\"finish maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n // Autonomous work and in-flight mutations intentionally leave the observed\n // generation dirty. Otherwise acknowledge only the pass-start generation.\n const processed =\n autonomous || started.activeAtStart > 0 || active > 0\n ? state.processed\n : state.processed > started.generation\n ? state.processed\n : started.generation;\n\n const next = ThreadMaintenanceState.make({\n ...state,\n processed,\n nonterminal: remaining.length,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n if (autonomous) {\n // Replace the crash-fallback slot with this pass's bounded backoff. The target\n // is never earlier than the begin-pass fallback, so workerd does not cancel\n // this running alarm handler before its report/span can complete.\n await transaction.setAlarm(\n Option.isSome(publicationDeadline)\n ? Math.max(\n now + minimumAlarmDelay,\n Math.min(now + delay, publicationDeadline.value),\n )\n : now + delay,\n );\n\n return \"rearmed\" as const;\n }\n if (started.activeAtStart > 0 || active > 0 || next.dirty > next.processed) {\n // A mutation overlapped this pass's observation window or raced\n // acknowledgement. It stays dirty and its pre-armed bounded alarm survives;\n // unseen effects are never acknowledged. Do not accelerate that future alarm\n // from inside the current handler: workerd cancels a running handler when it\n // writes an earlier slot.\n await ensureTransactionAlarmBy(\n transaction,\n Option.isSome(publicationDeadline)\n ? Math.max(\n now + minimumAlarmDelay,\n Math.min(now + config.wakeScanInterval, publicationDeadline.value),\n )\n : now + config.wakeScanInterval,\n );\n\n return \"rearmed\" as const;\n }\n if (Option.isSome(publicationDeadline)) {\n await transaction.setAlarm(\n Math.max(now + minimumAlarmDelay, publicationDeadline.value),\n );\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n if (alarmDisposition === \"cleared\") {\n yield* Ref.set(stalls, 0);\n }\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"actionable\",\n recovered: recovered.length,\n settled: Option.isSome(settlement) ? 1 : 0,\n nonterminal: remaining.length,\n alarm: alarmDisposition,\n }),\n );\n });\n\n return ThreadMaintenance.of({\n // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.\n pass: Effect.gen(function* () {\n const yieldAfter = DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 10 * 60_000);\n\n return yield* alarm.withWakesDeferred(maintenancePassGate.withPermit(pass(yieldAfter)));\n }).pipe(\n // Include permit waiting, recovery and acknowledgement in the event deadline.\n // Interruption releases Attempt ownership, leaving the prearmed dirty generation\n // for recovery. It never changes the logical Run duration or settles a policy failure.\n // This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.\n Effect.timeoutOrElse({\n duration: \"14 minutes\",\n orElse: () =>\n DurableAlarmError.make({\n operation: \"maintenance pass deadline\",\n message:\n \"The maintenance event exceeded its 14 minute deadline; durable recovery remains pending\",\n }),\n }),\n ),\n ensureAlarm: mutations.withSnapshot(() => ensureAlarm()),\n withMutation: (body) =>\n mutations.withMutation(\n body.pipe(\n Effect.tap(() =>\n publishCommitted.pipe(Effect.provideService(ThreadPublication, publication)),\n ),\n ),\n ),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA;CACE,WAAW,OAAO;CAClB,SAAS,OAAO;CAChB,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;AAC3C,CACF,CAAC,CAAC,CAAC;AAEH,MAAM,gBACH,eACA,UACC,kBAAkB,KAAK;CACrB;CACA,SAAS,iBAAiB,OAAO,sDAAsD;CACvF;AACF,CAAC;AAIL,MAAM,uBAAuB,OAAO,IAClC,YACC,SACK,WAAmB,YACrB,OAAO,QAAQ,OAAO,cAAc,IAAI,kBAAkB,IAAI,YAAY;CACxE,MAAM,OAAO,OAAO,gBAClB,OAAO,WAAW;EAAE,KAAK;EAAS,OAAO,aAAa,SAAS;CAAE,CAAC,CACpE;CAEA,OAAO,QAAQ,SAAS,SACpB,OACA,OAAO,OACL,OAAO,QAAQ,IAAI,QAAQ,KAAK,OAAO,SAAS,aAAa,SAAS,CAAC,CAAC,GAAG,IAAI,CACjF;AACN,CAAC,CACP;;AAGA,IAAa,sBAAb,MAAa,4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B,KAAK,OAAO,eAAe,mBAAmB,WAAW,CAAC,CAC7E,CACF,CACF;EACJ,CAAC;CACH,CAAC,CACH;AACF"}
1
+ {"version":3,"file":"Alarm.mjs","names":[],"sources":["../src/Alarm.ts"],"sourcesContent":["import { ThreadId } from \"@effect-agent/core/Identifiers\";\nimport { type DurableBindingFailure } from \"@effect-agent/thread/AgentRegistration\";\nimport {\n DurableAgentRuntime,\n type DurableWorkerFailure,\n type RecoveryReport,\n} from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { SubmissionLedger, type SubmissionSnapshot } from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n ThreadProjectionMaintenance,\n drainDue,\n type ThreadProjectionError,\n} from \"@effect-agent/thread/ThreadProjectionMaintenance\";\nimport {\n Cause,\n Clock,\n Context,\n DateTime,\n Deferred,\n Effect,\n Exit,\n Fiber,\n Layer,\n Option,\n Random,\n Ref,\n Schema,\n Semaphore,\n Stream,\n} from \"effect\";\nimport { SqlClient } from \"effect/unstable/sql/SqlClient\";\n\nimport { DurableObjectContext } from \"./CloudflareBindings.ts\";\nimport { CloudflareDurableRuntimeConfig } from \"./CloudflareConfig.ts\";\nimport { safeCauseMessage } from \"./internal/boundary.ts\";\n\n/**\n * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE\n * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement\n * and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and\n * the slot always holds the EARLIEST deadline any caller asked for.\n *\n * The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable\n * maintenance generation and a committed alarm. Stable externally-driven waits may be\n * nonterminal without retaining an alarm; their resolving mutation advances the generation and\n * restores the alarm atomically.\n */\n\n/** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */\nexport class DurableAlarmError extends Schema.TaggedError<DurableAlarmError>()(\n \"DurableAlarmError\",\n {\n operation: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\nconst alarmFailure =\n (operation: string) =>\n (cause: unknown): DurableAlarmError =>\n DurableAlarmError.make({\n operation,\n message: safeCauseMessage(cause, \"The Cloudflare alarm API failed without a diagnostic\"),\n cause,\n });\n\n// SQL and raw KV/alarm operations share one physical SQLite transaction. Reserve its\n// connection for each short storage operation, never around a mutation or snapshot body.\nconst makeStorageOperation = Effect.map(\n SqlClient,\n (sql) =>\n <A>(operation: string, execute: () => Promise<A>) =>\n Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => {\n const body = Effect.uninterruptible(\n Effect.tryPromise({ try: execute, catch: alarmFailure(operation) }),\n );\n\n return current._tag === \"Some\"\n ? body\n : Effect.scoped(\n Effect.andThen(sql.reserve.pipe(Effect.mapError(alarmFailure(operation))), body),\n );\n }),\n);\n\n/** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */\nexport class DurableAlarmService extends Context.Service<\n DurableAlarmService,\n {\n /** The scheduled deadline in epoch milliseconds, if any. */\n readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n /** Replace the slot with this deadline. */\n readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /** Keep the EARLIER of the existing deadline and this one (the multiplexing rule). */\n readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /**\n * Arm an immediate alarm (the durable, coalescing local wake) — DEFERRED while a\n * maintenance pass is executing. Workerd cancels an in-flight alarm handler when a new\n * EARLIER deadline is written during its execution (`requestScheduledAlarm`), and the\n * maintenance pass runs INSIDE the alarm handler: an immediate wake landing mid-pass\n * (a routed port mutation, a sibling's `wake()`, the coordinator's own local notify)\n * would kill the running Attempt — manufacturing an ownership loss no real eviction\n * caused, and routing open uncertain-class Tool Calls into spurious Unknown Outcomes.\n * Deferral is contract-safe: wakes are droppable hints, every mutating entry point\n * pre-arms BEFORE its first durable mutation (the alarm invariant never rests on this\n * call). The pass's durable generation check observes any racing mutation, so the\n * in-memory hint does not need to be flushed after a stable wait is acknowledged.\n */\n readonly scheduleNow: Effect.Effect<void, DurableAlarmError>;\n /**\n * Run one maintenance pass with wake deferral (see `scheduleNow`). Calls made while `body`\n * executes are droppable promptness hints; correctness rests on the durable generation.\n */\n readonly withWakesDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n /** Clear the slot; correctness-sensitive clears live in maintenance generation transactions. */\n readonly cancel: Effect.Effect<void, DurableAlarmError>;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableAlarmService\") {\n static readonly layer: Layer.Layer<DurableAlarmService, never, DurableObjectContext | SqlClient> =\n Layer.effect(DurableAlarmService)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n /**\n * In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no\n * running pass, and a deferred wake lost to eviction was only ever a promptness hint\n * on top of the already-committed pre-armed alarm.\n */\n const runningPasses = yield* Ref.make(0);\n\n const storageOperation = yield* makeStorageOperation;\n\n const scheduled = storageOperation(\"get alarm\", () => ctx.storage.getAlarm()).pipe(\n Effect.map((deadline) =>\n deadline === null ? Option.none<number>() : Option.some(deadline),\n ),\n );\n\n const scheduleAt = (epochMillis: number) =>\n storageOperation(\"set alarm\", () => ctx.storage.setAlarm(epochMillis));\n\n const ensureScheduledBy = (epochMillis: number) =>\n storageOperation(\"ensure alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const existing = await transaction.getAlarm();\n\n if (existing === null || existing > epochMillis) {\n await transaction.setAlarm(epochMillis);\n }\n }),\n );\n\n const armNow = Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => ensureScheduledBy(now)),\n );\n\n const scheduleNow = Ref.get(runningPasses).pipe(\n Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),\n );\n\n const withWakesDeferred = <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Ref.update(runningPasses, (passes) => passes + 1).pipe(\n Effect.andThen(body),\n Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1)),\n );\n\n const cancel = storageOperation(\"delete alarm\", () => ctx.storage.deleteAlarm());\n\n return DurableAlarmService.of({\n scheduled,\n scheduleAt,\n ensureScheduledBy,\n scheduleNow,\n withWakesDeferred,\n cancel,\n });\n }),\n );\n}\n\n/** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */\nexport class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(\n \"@effect-agent/platform-cloudflare/MaintenancePassReport\",\n)({\n /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */\n phase: Schema.Literals([\"caught-up\", \"actionable\"]),\n /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */\n recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Whether the head Attempt settled. Joined input may settle with that head. */\n settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */\n alarm: Schema.Literals([\"rearmed\", \"cleared\"]),\n}) {}\n\n/** Fault boundaries around every maintenance-owned durable mutation. */\nexport type ThreadMaintenanceFailpointLocation =\n | \"maintenance:dirty:before\"\n | \"maintenance:dirty:after\"\n | \"maintenance:mutation:armed\"\n | \"maintenance:mutation:finished\"\n | \"maintenance:ensure:before\"\n | \"maintenance:ensure:after\"\n | \"maintenance:begin:before\"\n | \"maintenance:begin:after\"\n | \"maintenance:select:before\"\n | \"maintenance:select:after\"\n | \"maintenance:finish:before\"\n | \"maintenance:finish:after\";\n\nexport type ThreadMaintenanceFailpointHandler = (\n location: ThreadMaintenanceFailpointLocation,\n) => Effect.Effect<void>;\n\n/** Test-only fault authority; production uses the inert layer. */\nexport class ThreadMaintenanceFailpoint extends Context.Service<\n ThreadMaintenanceFailpoint,\n {\n readonly hit: ThreadMaintenanceFailpointHandler;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint\") {\n static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });\n}\n\n/**\n * Durable host publication of canonical records and ledger approval/abort/resolution intents.\n * The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery\n * is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.\n *\n * `invalidate`, `prepareGeneration` and `pendingDeadline` must be bounded local operations.\n * `prepareGeneration` durably invalidates a scan only when its generation changes; repeated\n * calls must preserve partial scan progress. It runs with no source mutation in flight.\n * `drain` performs bounded delivery and persists retries before returning. A pending deadline\n * defers runtime recovery/Attempts, allowing committed host publications to drain first.\n * Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call\n * resources with Effect.scoped; Layer construction owns incarnation resources (eviction need\n * not run finalizers). Do not hold a local hook behind network I/O or call back into producers.\n */\nexport interface ThreadPublicationService {\n readonly invalidate: Effect.Effect<void, DurableAlarmError>;\n readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>;\n readonly drain: Effect.Effect<void, DurableAlarmError>;\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n}\n\n/** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */\nexport class ThreadPublication extends Context.Service<\n ThreadPublication,\n ThreadPublicationService\n>()(\"@effect-agent/platform-cloudflare/ThreadPublication\") {\n static readonly layer = Layer.succeed(this)({\n invalidate: Effect.void,\n prepareGeneration: () => Effect.void,\n drain: Effect.void,\n pendingDeadline: Effect.succeed(Option.none()),\n });\n}\n\n/**\n * Host-assembled message recovery, supplied by ThreadObject.layer even when the application\n * rebuilds ThreadMaintenance. These obligations outlive source Runs and never defer a ready\n * source Attempt while a destination is processing an accepted message.\n */\nexport const ThreadMessageDelivery = Context.Reference<{\n readonly drain: Effect.Effect<void, DurableAlarmError>;\n /** Drain inserts and due retries during source work, finishing the bounded wave on completion. */\n readonly drainUntil?: (\n finished: Deferred.Deferred<void>,\n ) => Effect.Effect<void, DurableAlarmError>;\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n}>(\"@effect-agent/platform-cloudflare/ThreadMessageDelivery\", {\n defaultValue: () => ({ drain: Effect.void, pendingDeadline: Effect.succeed(Option.none()) }),\n});\n\n/**\n * Application obligations sharing this Object's alarm. The deadline read is local and\n * read-only. Drain beside the native Attempt and always finish one initial bounded wave,\n * even when `finished` was already signalled. Then stop starting new waves on that signal\n * and finish the bounded current wave before returning. Native maintenance joins that work\n * before acknowledging a generation. Mutations use the same ThreadMutationGate; hooks never\n * write the raw alarm slot. Pending host work does not defer a ready model Attempt.\n */\nexport const ThreadHostMaintenance = Context.Reference<{\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n readonly drainUntil: (\n finished: Deferred.Deferred<void>,\n ) => Effect.Effect<void, DurableAlarmError>;\n}>(\"@effect-agent/platform-cloudflare/ThreadHostMaintenance\", {\n defaultValue: () => ({\n pendingDeadline: Effect.succeed(Option.none()),\n drainUntil: () => Effect.void,\n }),\n});\n\nconst earliestDeadline = (\n left: Option.Option<number>,\n right: Option.Option<number>,\n): Option.Option<number> =>\n Option.isSome(left)\n ? Option.isSome(right)\n ? Option.some(Math.min(left.value, right.value))\n : left\n : right;\n\n/** @internal A committed source operation must not become a failed operation because delivery failed. */\nexport const publishCommitted = Effect.gen(function* () {\n const publication = yield* ThreadPublication;\n\n yield* publication.invalidate.pipe(Effect.andThen(publication.drain));\n}).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.logError(\"Thread publication deferred after source commit\", cause),\n ),\n);\n\nconst MaintenanceGeneration = Schema.BigIntFromString.check(\n Schema.isGreaterThanOrEqualToBigInt(0n),\n);\n\n/** Versioned, platform-private maintenance state stored through Durable Object KV. */\nclass ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(\n \"@effect-agent/platform-cloudflare/ThreadMaintenanceState\",\n)({\n schemaVersion: Schema.Literal(1),\n dirty: MaintenanceGeneration,\n processed: MaintenanceGeneration,\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** One physical-owner cursor; old single-lane records need no conversion. */\n lastServedThreadId: Schema.optionalKey(ThreadId),\n}) {}\n\nconst MAINTENANCE_STATE_KEY = \"effect-agent:thread-maintenance:v1\";\nconst decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);\nconst encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);\n\nconst initialMaintenanceState = (): ThreadMaintenanceState =>\n ThreadMaintenanceState.make({\n schemaVersion: 1,\n // Bootstrap Objects created by the pre-generation release without scanning the ledger in\n // the constructor. One useful pass classifies and acknowledges any existing obligation.\n dirty: 1n,\n processed: 0n,\n nonterminal: 0,\n });\n\nconst readMaintenanceState = async (\n transaction: DurableObjectTransaction,\n): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {\n const encoded = await transaction.get(MAINTENANCE_STATE_KEY);\n\n return encoded === undefined\n ? { state: initialMaintenanceState(), initialized: false }\n : { state: decodeMaintenanceState(encoded), initialized: true };\n};\n\nconst ensureTransactionAlarmBy = async (\n transaction: DurableObjectTransaction,\n deadline: number,\n): Promise<void> => {\n const scheduled = await transaction.getAlarm();\n\n if (scheduled === null || scheduled > deadline) {\n await transaction.setAlarm(deadline);\n }\n};\n\nconst stableExternalWait = (\n snapshot: SubmissionSnapshot,\n reports: ReadonlyMap<string, RecoveryReport>,\n): boolean => {\n const decision = reports.get(snapshot.submissionId)?.decision._tag;\n\n // An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.\n if (decision === \"SettleAborted\") return false;\n switch (snapshot.state) {\n case \"suspended\":\n case \"joined\":\n return true;\n case \"unknown\":\n return decision === \"AwaitUnknownResolution\" || decision === \"MarkUnknown\";\n case \"admitted\":\n return reports.get(snapshot.submissionId)?.decision._tag === \"AwaitParentEstablishment\";\n case \"input-applied\":\n case \"joining\":\n case \"ready\":\n case \"running\":\n case \"settled\":\n case \"terminalizing\":\n return false;\n }\n};\n\n/**\n * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.\n * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance\n * Layers must reuse that instance; a second gate cannot observe the native producers' activity.\n */\nexport class ThreadMutationGate extends Context.Service<\n ThreadMutationGate,\n {\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n readonly withSnapshot: <A, E, R>(\n body: (active: number) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/internal/ThreadMutationGate\") {\n static readonly layer = Layer.effect(this)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* CloudflareDurableRuntimeConfig;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n // A fresh incarnation has no live mutations; durable generations survive eviction.\n const activeMutations = yield* Ref.make(0);\n const generationGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = yield* makeStorageOperation;\n\n const beginMutation = Effect.fn(\"ThreadMaintenance.beginMutation\")(function* () {\n yield* failpoint.hit(\"maintenance:dirty:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"advance maintenance generation\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const next = ThreadMaintenanceState.make({\n ...state,\n dirty: state.dirty + 1n,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n // The earliest configured retry bounds a newly actionable mutation without relying\n // on its best-effort immediate wake hint.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n }),\n );\n yield* failpoint.hit(\"maintenance:dirty:after\");\n yield* Ref.update(activeMutations, (active) => active + 1);\n });\n\n const endMutation = generationGate.withPermit(\n Ref.update(activeMutations, (active) => Math.max(0, active - 1)),\n );\n\n const withMutation = <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ): Effect.Effect<A, E | DurableAlarmError, R> =>\n Effect.acquireUseRelease(\n generationGate.withPermit(beginMutation()),\n () =>\n failpoint.hit(\"maintenance:mutation:armed\").pipe(\n Effect.andThen(body),\n Effect.tap(() => failpoint.hit(\"maintenance:mutation:finished\")),\n ),\n () => endMutation,\n );\n\n return ThreadMutationGate.of({\n withMutation,\n withSnapshot: (body) =>\n generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body)),\n });\n }),\n );\n}\n\nexport type MaintenancePassFailure =\n | DurableWorkerFailure\n | DurableBindingFailure\n | DurableAlarmError\n | ThreadProjectionError;\n\n/**\n * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).\n *\n * `pass` = generation snapshot/pre-arm → recovery → one head Attempt → generation acknowledgement:\n *\n * 1. One storage transaction reads dirty/processed and re-arms before work. A caught-up forced\n * alarm takes an O(1) path without recovery, ledger scans, or canonical-history reads.\n * 2. Recovery strictly precedes a new claim. One head Attempt advances the lane and requests\n * a safe yield after ten minutes. The whole event has a fourteen-minute cooperative timeout.\n * 3. The final transaction acknowledges only the generation observed at pass start. A racing\n * mutation therefore remains `dirty > processed` and retains its atomically-established alarm.\n * 4. Stable external waits acknowledge and clear. Autonomous retry, indeterminate, and lease\n * recovery states leave their generation dirty and retain bounded backoff rearming.\n */\nexport class ThreadMaintenance extends Context.Service<\n ThreadMaintenance,\n {\n /** One idempotent maintenance pass; failures propagate so workerd retries the alarm. */\n readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>;\n /**\n * Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty\n * generation has an alarm. It never scans the ledger or canonical history.\n */\n readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>;\n /**\n * Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty\n * generation and arm the alarm in one transaction BEFORE running the caller's mutation.\n * A pass cannot acknowledge while that mutation remains in flight.\n */\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenance\") {\n static readonly layer: Layer.Layer<\n ThreadMaintenance,\n never,\n | ThreadMutationGate\n | ThreadPublication\n | ThreadProjectionMaintenance\n | DurableAgentRuntime\n | SubmissionLedger\n | DurableAlarmService\n | ThreadMaintenanceFailpoint\n | CloudflareDurableRuntimeConfig\n | DurableObjectContext\n | SqlClient\n > = Layer.effect(ThreadMaintenance)(\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const alarm = yield* DurableAlarmService;\n const config = yield* CloudflareDurableRuntimeConfig;\n const { ctx } = yield* DurableObjectContext;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n\n /**\n * Consecutive no-progress passes — an in-memory CACHE, not state: a fresh incarnation\n * restarts at zero and merely re-arms sooner than a long-lived one would have.\n */\n const stalls = yield* Ref.make(0);\n const mutations = yield* ThreadMutationGate;\n const publication = yield* ThreadPublication;\n const projection = yield* ThreadProjectionMaintenance;\n const messages = yield* ThreadMessageDelivery;\n const host = yield* ThreadHostMaintenance;\n\n // A broken disposable index still needs a retry alarm and must not prevent startup.\n const projectionDeadline = projection.pendingDeadline.pipe(\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterrupts(cause),\n (cause) =>\n Effect.logError(\"Thread projection deadline unavailable\", cause).pipe(\n Effect.as(Option.some(0)),\n ),\n ),\n );\n\n const pendingDeadline = Effect.gen(function* () {\n return earliestDeadline(\n earliestDeadline(yield* publication.pendingDeadline, yield* messages.pendingDeadline),\n earliestDeadline(yield* projectionDeadline, yield* host.pendingDeadline),\n );\n });\n\n const maintenancePassGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = yield* makeStorageOperation;\n\n const ensureAlarm = Effect.fn(\"ThreadMaintenance.ensureAlarm\")(function* () {\n yield* failpoint.hit(\"maintenance:ensure:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"ensure maintenance alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.dirty > state.processed) {\n await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);\n }\n }),\n );\n const deadline = yield* pendingDeadline;\n\n if (Option.isSome(deadline)) {\n yield* runTransaction(\"ensure publication alarm\", () =>\n ctx.storage.transaction((transaction) =>\n ensureTransactionAlarmBy(\n transaction,\n Math.max(now + minimumAlarmDelay, deadline.value),\n ),\n ),\n );\n }\n yield* failpoint.hit(\"maintenance:ensure:after\");\n });\n\n const beginPass = Effect.fn(\"ThreadMaintenance.beginPass\")(function* () {\n yield* failpoint.hit(\"maintenance:begin:before\");\n const now = yield* Clock.currentTimeMillis;\n\n const result = yield* runTransaction(\"begin maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.processed >= state.dirty) {\n // Prearm even a publication-only pass before invoking any host hook.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return { _tag: \"CaughtUp\" as const, nonterminal: state.nonterminal };\n }\n // Pre-arm the earliest retry before recovery. A successful finish may move this slot\n // LATER to its bounded backoff, which does not cancel the running handler.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return {\n _tag: \"Actionable\" as const,\n generation: state.dirty,\n nonterminal: state.nonterminal,\n };\n }),\n );\n\n yield* failpoint.hit(\"maintenance:begin:after\");\n\n return result;\n });\n\n const rearmDelay = Effect.fn(\"ThreadMaintenance.rearmDelay\")(function* (progressed: boolean) {\n const priorStalls = yield* Ref.getAndUpdate(stalls, (count) =>\n progressed ? 0 : count + 1,\n );\n\n if (progressed) return config.alarmBackoffBase;\n const exponent = Math.min(priorStalls, 30);\n const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** exponent);\n const jitter = yield* Random.next;\n // Full jitter over [backoff/2, backoff]: desynchronizes retry storms without ever\n // waiting longer than the deterministic bound.\n const jittered = Math.ceil(backoff / 2 + (backoff / 2) * jitter);\n\n return Math.min(jittered, config.wakeScanInterval);\n });\n\n const pass = Effect.fn(\"ThreadMaintenance.pass\")(function* (\n yieldAfter: DateTime.Utc,\n ): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure> {\n const annotate = (report: MaintenancePassReport) =>\n Effect.annotateCurrentSpan({\n phase: report.phase,\n recovered: report.recovered,\n settled: report.settled,\n nonterminal: report.nonterminal,\n alarm: report.alarm,\n }).pipe(Effect.as(report));\n\n const started = yield* mutations.withSnapshot((activeAtStart) =>\n Effect.gen(function* () {\n const generation = yield* beginPass();\n\n if (generation._tag === \"Actionable\" && activeAtStart === 0) {\n // The gate excludes a producer starting between the snapshot and certification.\n yield* publication.prepareGeneration(generation.generation);\n }\n\n return { ...generation, activeAtStart };\n }),\n );\n\n // Deliver beside source work, including messages inserted by the running Attempt.\n // Slow destination RPCs never consume the source execution window. Stop starting\n // waves when source work ends, then join the bounded current wave before acknowledgement.\n const deliveryFinished = yield* Deferred.make<void>();\n\n const delivery = yield* Effect.forkChild(\n messages.drainUntil?.(deliveryFinished) ?? messages.drain,\n );\n\n const hostWork = yield* Effect.forkChild(host.drainUntil(deliveryFinished));\n\n const finishDelivery = Deferred.succeed(deliveryFinished, undefined).pipe(\n Effect.andThen(Fiber.awaitAll([delivery, hostWork])),\n Effect.flatMap((outcomes) =>\n Effect.forEach(outcomes, (outcome) => outcome, { discard: true }),\n ),\n );\n\n // Capture derived-index failures until canonical work has had its turn. Interruption\n // still stops the event; ordinary failures and defects retain the prearmed generation.\n const projected = yield* Effect.exit(\n drainDue.pipe(Effect.provideService(ThreadProjectionMaintenance, projection)),\n );\n\n if (Exit.isFailure(projected) && Cause.hasInterrupts(projected.cause))\n return yield* Effect.failCause(projected.cause);\n const deadline = yield* publication.pendingDeadline;\n\n if (\n started._tag === \"Actionable\" ||\n (Option.isSome(deadline) && deadline.value <= (yield* Clock.currentTimeMillis))\n ) {\n yield* publication.drain;\n }\n const pending = yield* publication.pendingDeadline;\n\n if (started._tag === \"CaughtUp\" || Option.isSome(pending)) {\n yield* finishDelivery;\n if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const disposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n // Re-read under the producer gate: a concurrent append/host mutation cannot be\n // cleared using a stale empty deadline. Dirty generations bound all producer races.\n const latest = yield* pendingDeadline;\n const now = yield* Clock.currentTimeMillis;\n\n return yield* runTransaction(\"finish publication pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const nativeDeadline =\n active > 0 || state.dirty > state.processed\n ? now + config.wakeScanInterval\n : Infinity;\n\n const next = Option.isSome(latest)\n ? Math.min(nativeDeadline, latest.value)\n : nativeDeadline;\n\n if (Number.isFinite(next)) {\n await transaction.setAlarm(Math.max(now + minimumAlarmDelay, next));\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"caught-up\",\n recovered: 0,\n settled: 0,\n nonterminal: started.nonterminal,\n alarm: disposition,\n }),\n );\n }\n // Step 2 — reconciliation strictly precedes new work in this pass (exit gate).\n const recovered: ReadonlyArray<RecoveryReport> = yield* runtime.runRecovery;\n const reports = new Map(recovered.map((report) => [report.submissionId, report]));\n const current = yield* Stream.runCollect(ledger.scanNonterminal);\n const heads = new Map<ThreadId, SubmissionSnapshot>();\n\n for (const row of current) {\n if (!heads.has(row.threadId)) heads.set(row.threadId, row);\n }\n\n const eligible = [...heads.values()]\n .filter((head) => !stableExternalWait(head, reports))\n .map((head) => head.threadId)\n .sort();\n\n let selected = eligible[0];\n\n if (heads.size > 1 && selected !== undefined) {\n yield* failpoint.hit(\"maintenance:select:before\");\n selected = yield* runTransaction(\"select maintenance lane\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const next =\n eligible.find(\n (threadId) =>\n state.lastServedThreadId === undefined || threadId > state.lastServedThreadId,\n ) ?? eligible[0];\n\n if (next !== undefined) {\n // Persist before the Attempt so an eviction or repeated yield cannot\n // monopolize the first lane. The generation and prearmed alarm survive.\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({ ...state, lastServedThreadId: next }),\n ),\n );\n }\n\n return next;\n }),\n );\n yield* failpoint.hit(\"maintenance:select:after\");\n }\n\n // One FIFO head per event, across all local lanes. The runtime keeps its normal\n // bounded Attempt and recovery contracts; followers belong to another alarm.\n const settlement =\n selected === undefined\n ? Option.none()\n : yield* runtime.processThreadHead(selected, { yieldAfter });\n\n yield* finishDelivery;\n if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);\n // Observe residual state before acknowledging this exact pass-start generation.\n const remaining = yield* Stream.runCollect(ledger.scanNonterminal);\n const waitingHeads = new Map<ThreadId, boolean>();\n\n const autonomous = remaining.some((snapshot) => {\n const headWaiting = waitingHeads.get(snapshot.threadId);\n\n if (headWaiting === undefined)\n waitingHeads.set(snapshot.threadId, stableExternalWait(snapshot, reports));\n // FIFO followers cannot execute through a stable external wait. Only plain queued\n // input is dormant here; admission repairs and accepted aborts still need a pass.\n if (\n headWaiting === true &&\n snapshot.state === \"ready\" &&\n reports.get(snapshot.submissionId)?.decision._tag === \"ApplyInput\"\n )\n return false;\n\n return !stableExternalWait(snapshot, reports);\n });\n\n const progressed =\n Option.isSome(settlement) ||\n recovered.some((report) => report.disposition === \"repaired\");\n\n const delay = autonomous ? yield* rearmDelay(progressed) : 0;\n const now = yield* Clock.currentTimeMillis;\n\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const alarmDisposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n const publicationDeadline = yield* pendingDeadline;\n\n return yield* runTransaction(\"finish maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n // Autonomous work and in-flight mutations intentionally leave the observed\n // generation dirty. Otherwise acknowledge only the pass-start generation.\n const processed =\n autonomous || started.activeAtStart > 0 || active > 0\n ? state.processed\n : state.processed > started.generation\n ? state.processed\n : started.generation;\n\n const next = ThreadMaintenanceState.make({\n ...state,\n processed,\n nonterminal: remaining.length,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n if (autonomous) {\n // Replace the crash-fallback slot with this pass's bounded backoff. The target\n // is never earlier than the begin-pass fallback, so workerd does not cancel\n // this running alarm handler before its report/span can complete.\n await transaction.setAlarm(\n Option.isSome(publicationDeadline)\n ? Math.max(\n now + minimumAlarmDelay,\n Math.min(now + delay, publicationDeadline.value),\n )\n : now + delay,\n );\n\n return \"rearmed\" as const;\n }\n if (started.activeAtStart > 0 || active > 0 || next.dirty > next.processed) {\n // A mutation overlapped this pass's observation window or raced\n // acknowledgement. It stays dirty and its pre-armed bounded alarm survives;\n // unseen effects are never acknowledged. Do not accelerate that future alarm\n // from inside the current handler: workerd cancels a running handler when it\n // writes an earlier slot.\n await ensureTransactionAlarmBy(\n transaction,\n Option.isSome(publicationDeadline)\n ? Math.max(\n now + minimumAlarmDelay,\n Math.min(now + config.wakeScanInterval, publicationDeadline.value),\n )\n : now + config.wakeScanInterval,\n );\n\n return \"rearmed\" as const;\n }\n if (Option.isSome(publicationDeadline)) {\n await transaction.setAlarm(\n Math.max(now + minimumAlarmDelay, publicationDeadline.value),\n );\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n if (alarmDisposition === \"cleared\") {\n yield* Ref.set(stalls, 0);\n }\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"actionable\",\n recovered: recovered.length,\n settled: Option.isSome(settlement) ? 1 : 0,\n nonterminal: remaining.length,\n alarm: alarmDisposition,\n }),\n );\n });\n\n return ThreadMaintenance.of({\n // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.\n pass: Effect.gen(function* () {\n const yieldAfter = DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 10 * 60_000);\n\n return yield* alarm.withWakesDeferred(maintenancePassGate.withPermit(pass(yieldAfter)));\n }).pipe(\n // Include permit waiting, recovery and acknowledgement in the event deadline.\n // Interruption releases Attempt ownership, leaving the prearmed dirty generation\n // for recovery. It never changes the logical Run duration or settles a policy failure.\n // This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.\n Effect.timeoutOrElse({\n duration: \"14 minutes\",\n orElse: () =>\n DurableAlarmError.make({\n operation: \"maintenance pass deadline\",\n message:\n \"The maintenance event exceeded its 14 minute deadline; durable recovery remains pending\",\n }),\n }),\n ),\n ensureAlarm: mutations.withSnapshot(() => ensureAlarm()),\n withMutation: (body) =>\n mutations.withMutation(\n body.pipe(\n Effect.tap(() =>\n publishCommitted.pipe(Effect.provideService(ThreadPublication, publication)),\n ),\n ),\n ),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA;CACE,WAAW,OAAO;CAClB,SAAS,OAAO;CAChB,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;AAC3C,CACF,CAAC,CAAC,CAAC;AAEH,MAAM,gBACH,eACA,UACC,kBAAkB,KAAK;CACrB;CACA,SAAS,iBAAiB,OAAO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,kBAAkB,GAAG;GAE1B,MAAM,OAAO,IAAI,aAAa;IAC5B,MAAM,aAAa,SAAS,YAAY,OAAO,MAAM,qBAAqB,GAAW;IAErF,OAAO,OAAO,MAAM,kBAAkB,oBAAoB,WAAW,KAAK,UAAU,CAAC,CAAC;GACxF,CAAC,CAAC,CAAC,KAKD,OAAO,cAAc;IACnB,UAAU;IACV,cACE,kBAAkB,KAAK;KACrB,WAAW;KACX,SACE;IACJ,CAAC;GACL,CAAC,CACH;GACA,aAAa,UAAU,mBAAmB,YAAY,CAAC;GACvD,eAAe,SACb,UAAU,aACR,KAAK,KACH,OAAO,UACL,iBAAiB,KAAK,OAAO,eAAe,mBAAmB,WAAW,CAAC,CAC7E,CACF,CACF;EACJ,CAAC;CACH,CAAC,CACH;AACF"}
@@ -152,7 +152,7 @@ const makeCrawl = (client, options) => (input) => Stream.unwrap(Effect.gen(funct
152
152
  }
153
153
  if (response.status < 200 || response.status >= 300) return yield* protocolError(`Browser Run crawl answered HTTP ${String(response.status)}`, privateCause(bodyText, options.apiToken));
154
154
  if (!isJsonResponse(response.headers)) return yield* protocolError("The Browser Run crawl success response was not JSON", privateCause(bodyText, options.apiToken));
155
- return yield* Schema.decodeUnknownEffect(Schema.fromJsonString(schema))(bodyText).pipe(Effect.mapError((cause) => protocolError("Browser Run returned a malformed crawl response", privateCause(cause, options.apiToken))));
155
+ return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(bodyText).pipe(Effect.mapError((cause) => protocolError("Browser Run returned a malformed crawl response", privateCause(cause, options.apiToken))));
156
156
  });
157
157
  const createJob = Effect.gen(function* () {
158
158
  const requestWithBody = yield* HttpClientRequest.post(endpoint(options)).pipe(HttpClientRequest.bodyJson({
@@ -1 +1 @@
1
- {"version":3,"file":"BrowserRestCrawl.mjs","names":[],"sources":["../src/BrowserRestCrawl.ts"],"sourcesContent":["import {\n PageCrawl,\n PageCrawlLimitError,\n PageCrawlProtocolError,\n PageCrawlRateLimitedError,\n PageCrawlRecord,\n PageCrawlTerminalError,\n type PageCrawlCrawl,\n type PageCrawlError,\n type PageCrawlRequest,\n} from \"@effect-agent/sandbox/PageCrawl\";\nimport { SandboxImplementation } from \"@effect-agent/sandbox/Sandbox\";\nimport {\n Duration,\n Effect,\n Layer,\n Option,\n Redacted,\n Ref,\n Schedule,\n Schema,\n Scope,\n Stream,\n} from \"effect\";\nimport {\n HttpClient,\n HttpClientRequest,\n type HttpClientError,\n type HttpClientResponse,\n} from \"effect/unstable/http\";\n\n/** Node-safe REST crawl implementation. It never exposes or persists provider job identity. */\nexport const browserRestCrawlImplementation = SandboxImplementation.make({\n isolation: \"isolated\",\n identity: \"cloudflare-browser-rest-crawl\",\n});\n\nconst API_ORIGIN = \"https://api.cloudflare.com\";\nconst POLL_INTERVAL = Duration.seconds(1);\nconst CANCEL_TIMEOUT = Duration.seconds(30);\nconst MAX_CONTROL_RESPONSE_BYTES = 64 * 1024;\nconst MAX_RESULTS_RESPONSE_BYTES = 12 * 1024 * 1024;\nconst MAX_DIAGNOSTIC_LENGTH = 8_000;\nconst MAX_CURSOR_LENGTH = 1_024;\nconst MAX_RECORDS_PER_RESPONSE = 10_000;\nconst BoundedJobId = Schema.NonEmptyString.check(Schema.isMaxLength(256));\nconst BoundedCursorString = Schema.NonEmptyString.check(Schema.isMaxLength(MAX_CURSOR_LENGTH));\n// The generated API response Schema says string; the current product example returns a number.\nconst ProviderCursor = Schema.Union([BoundedCursorString, Schema.Natural]);\n\nconst ProviderJobStatus = Schema.Literals([\n \"running\",\n \"completed\",\n \"errored\",\n \"cancelled_by_user\",\n \"cancelled_due_to_timeout\",\n \"cancelled_due_to_limits\",\n]);\n\nconst ProviderResult = Schema.Struct({\n id: BoundedJobId,\n status: ProviderJobStatus,\n browserSecondsUsed: Schema.optionalKey(Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))),\n total: Schema.optionalKey(Schema.Natural),\n finished: Schema.optionalKey(Schema.Natural),\n skipped: Schema.optionalKey(Schema.Natural),\n records: Schema.Array(PageCrawlRecord).check(Schema.isMaxLength(MAX_RECORDS_PER_RESPONSE)),\n cursor: Schema.optionalKey(ProviderCursor),\n});\n\nconst CreateEnvelope = Schema.Struct({\n success: Schema.Literal(true),\n result: BoundedJobId,\n});\n\nconst ResultEnvelope = Schema.Struct({\n success: Schema.Literal(true),\n result: ProviderResult,\n});\n\nconst DeleteEnvelope = Schema.Struct({\n success: Schema.Literal(true),\n result: Schema.Struct({\n job_id: BoundedJobId,\n message: Schema.String.check(Schema.isMaxLength(MAX_DIAGNOSTIC_LENGTH)),\n }),\n});\n\n/** Explicit credentials. The token is projected only into fixed-origin Authorization headers. */\nexport interface BrowserRestCrawlOptions {\n readonly accountId: string;\n readonly apiToken: Redacted.Redacted<string>;\n}\n\nconst boundedDiagnostic = (message: string): string => message.slice(0, MAX_DIAGNOSTIC_LENGTH);\n\nconst privateCause = (value: unknown, apiToken: Redacted.Redacted<string>): Error | undefined => {\n const raw = boundedDiagnostic(String(value));\n\n if (raw.length === 0) return undefined;\n const token = Redacted.value(apiToken);\n\n return new Error(token.length === 0 ? raw : raw.replaceAll(token, \"[REDACTED]\"));\n};\n\nconst protocolError = (message: string, cause?: unknown): PageCrawlProtocolError =>\n PageCrawlProtocolError.make({\n implementation: browserRestCrawlImplementation,\n message: boundedDiagnostic(message),\n ...(cause === undefined ? {} : { cause }),\n });\n\nconst limitError = (\n request: PageCrawlRequest,\n limit: PageCrawlLimitError[\"limit\"],\n observed: number,\n): PageCrawlLimitError => {\n const maximum =\n limit === \"pages\"\n ? request.limits.maxPages\n : limit === \"page-bytes\"\n ? request.limits.maxPageBytes\n : limit === \"total-bytes\"\n ? request.limits.maxTotalBytes\n : request.limits.deadlineMillis;\n\n return PageCrawlLimitError.make({\n implementation: browserRestCrawlImplementation,\n limit,\n maximum,\n observed,\n message: `The crawl exceeded its ${limit} limit`,\n });\n};\n\nconst retryAfterMillis = (\n headers: Readonly<Record<string, string | undefined>>,\n): number | undefined => {\n const seconds = Number(headers[\"retry-after\"]);\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 isJsonResponse = (headers: Readonly<Record<string, string | undefined>>): boolean => {\n const contentType = headers[\"content-type\"];\n\n if (contentType === undefined) return false;\n const mediaType = contentType.split(\";\", 1)[0]?.trim().toLowerCase();\n\n return mediaType === \"application/json\" || mediaType?.endsWith(\"+json\") === true;\n};\n\nconst isQuotaMessage = (bodyText: string): boolean => /time limit|daily|quota/i.test(bodyText);\n\nconst endpoint = (options: BrowserRestCrawlOptions, jobId?: string): string =>\n `${API_ORIGIN}/client/v4/accounts/${encodeURIComponent(options.accountId)}/browser-rendering/crawl${\n jobId === undefined ? \"\" : `/${encodeURIComponent(jobId)}`\n }`;\n\nconst readBoundedResponse = Effect.fn(\"BrowserRestCrawl.readBoundedResponse\")(function* (\n response: HttpClientResponse.HttpClientResponse,\n maximum: number,\n): Effect.fn.Return<string, PageCrawlProtocolError> {\n const decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false });\n\n const state = yield* Stream.runFoldEffect<\n Uint8Array,\n HttpClientError.HttpClientError,\n never,\n { readonly observed: number; readonly text: string },\n PageCrawlProtocolError,\n never\n >(\n response.stream,\n () => ({ observed: 0, text: \"\" }),\n (current, chunk) => {\n const observed = current.observed + chunk.byteLength;\n\n if (observed > maximum) {\n return Effect.fail(\n protocolError(\n `The Browser Run crawl response exceeded ${String(maximum)} transport bytes`,\n ),\n );\n }\n\n return Effect.try({\n try: () => ({ observed, text: current.text + decoder.decode(chunk, { stream: true }) }),\n catch: (cause) => protocolError(\"Decoding the Browser Run crawl response failed\", cause),\n });\n },\n ).pipe(\n Effect.mapError((cause) =>\n Schema.is(PageCrawlProtocolError)(cause)\n ? cause\n : protocolError(\"Reading the Browser Run crawl response failed\", cause),\n ),\n );\n\n return yield* Effect.try({\n try: () => state.text + decoder.decode(),\n catch: (cause) => protocolError(\"Decoding the Browser Run crawl response failed\", cause),\n });\n});\n\nconst deadlineFailure = Effect.fn(\"BrowserRestCrawl.deadlineFailure\")(function* (\n request: PageCrawlRequest,\n startedAt: number,\n) {\n const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\n return yield* limitError(request, \"deadline\", Math.max(0, now - startedAt));\n});\n\nconst withinDeadline = Effect.fn(\"BrowserRestCrawl.withinDeadline\")(function* <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n request: PageCrawlRequest,\n startedAt: number,\n): Effect.fn.Return<A, E | PageCrawlLimitError, R> {\n const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n const elapsed = Math.max(0, now - startedAt);\n const remaining = request.limits.deadlineMillis - elapsed;\n\n if (remaining <= 0) return yield* limitError(request, \"deadline\", elapsed);\n\n return yield* effect.pipe(\n Effect.timeoutOrElse({\n duration: Duration.millis(remaining),\n orElse: () => deadlineFailure(request, startedAt),\n }),\n );\n});\n\nconst checkDeadline = Effect.fn(\"BrowserRestCrawl.checkDeadline\")(function* (\n request: PageCrawlRequest,\n startedAt: number,\n) {\n const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n const elapsed = Math.max(0, now - startedAt);\n\n if (elapsed >= request.limits.deadlineMillis) {\n return yield* limitError(request, \"deadline\", elapsed);\n }\n});\n\nconst normalizedCursor = (cursor: typeof ProviderCursor.Type): string => String(cursor);\n\ninterface PaginationState {\n readonly cursor: Option.Option<string>;\n readonly seen: ReadonlyArray<string>;\n}\n\ninterface RecordLimitsState {\n readonly pages: number;\n readonly totalBytes: number;\n}\n\nconst sameHost = (expectedHost: string, url: string): boolean => new URL(url).host === expectedHost;\n\nconst makeCrawl =\n (client: HttpClient.HttpClient, options: BrowserRestCrawlOptions): PageCrawlCrawl =>\n (input) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const startedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n const startHost = new URL(input.startUrl).host;\n\n const executeJson = Effect.fn(\"BrowserRestCrawl.executeJson\")(function* <\n S extends Schema.Top,\n >(request: HttpClientRequest.HttpClientRequest, schema: S, maximum: number) {\n const authorized = HttpClientRequest.bearerToken(request, options.apiToken).pipe(\n HttpClientRequest.acceptJson,\n );\n\n const response = yield* client\n .execute(authorized)\n .pipe(\n Effect.mapError((cause) =>\n protocolError(\n \"Calling the Browser Run crawl REST API failed\",\n privateCause(cause, options.apiToken),\n ),\n ),\n );\n\n const bodyText = yield* readBoundedResponse(response, maximum);\n\n if (response.status === 429) {\n const reason = isQuotaMessage(bodyText) ? \"quota\" : \"rate\";\n\n return yield* PageCrawlRateLimitedError.make({\n implementation: browserRestCrawlImplementation,\n reason,\n ...(retryAfterMillis(response.headers) === undefined\n ? {}\n : { retryAfterMillis: retryAfterMillis(response.headers) }),\n message:\n reason === \"quota\"\n ? \"Browser Run exceeded its browser quota\"\n : \"Browser Run crawl was rate limited\",\n ...(privateCause(bodyText, options.apiToken) === undefined\n ? {}\n : { cause: privateCause(bodyText, options.apiToken) }),\n });\n }\n if (response.status < 200 || response.status >= 300) {\n return yield* protocolError(\n `Browser Run crawl answered HTTP ${String(response.status)}`,\n privateCause(bodyText, options.apiToken),\n );\n }\n if (!isJsonResponse(response.headers)) {\n return yield* protocolError(\n \"The Browser Run crawl success response was not JSON\",\n privateCause(bodyText, options.apiToken),\n );\n }\n\n return yield* Schema.decodeUnknownEffect(Schema.fromJsonString(schema))(bodyText).pipe(\n Effect.mapError((cause) =>\n protocolError(\n \"Browser Run returned a malformed crawl response\",\n privateCause(cause, options.apiToken),\n ),\n ),\n );\n });\n\n const createJob = Effect.gen(function* () {\n const requestWithBody = yield* HttpClientRequest.post(endpoint(options)).pipe(\n HttpClientRequest.bodyJson({\n url: input.startUrl,\n crawlPurposes: [...input.purposes],\n limit: input.limits.maxPages,\n depth: input.limits.maxDepth,\n formats: [\"markdown\"],\n render: true,\n options: {\n includeExternalLinks: false,\n includeSubdomains: false,\n },\n }),\n Effect.mapError((cause) =>\n protocolError(\"Encoding the Browser Run crawl request failed\", cause),\n ),\n );\n\n const created = yield* withinDeadline(\n executeJson(requestWithBody, CreateEnvelope, MAX_CONTROL_RESPONSE_BYTES),\n input,\n startedAt,\n );\n\n return created.result;\n });\n\n const job = yield* Effect.uninterruptibleMask((restore) =>\n restore(createJob).pipe(\n Effect.flatMap((id) =>\n Effect.gen(function* () {\n const state = yield* Ref.make<\"running\" | \"terminal\">(\"running\");\n const scope = yield* Effect.scope;\n\n const cancelIfRunning = Ref.modify(state, (current) =>\n current === \"running\"\n ? [true, \"terminal\" as const]\n : [false, \"terminal\" as const],\n ).pipe(\n Effect.flatMap((shouldCancel) => {\n if (!shouldCancel) return Effect.void;\n\n const cancellation = executeJson(\n HttpClientRequest.delete(endpoint(options, id)),\n DeleteEnvelope,\n MAX_CONTROL_RESPONSE_BYTES,\n ).pipe(\n Effect.flatMap((deleted) =>\n deleted.result.job_id === id\n ? Effect.void\n : protocolError(\"Browser Run cancelled a different crawl job\"),\n ),\n );\n\n return cancellation.pipe(\n Effect.timeoutOrElse({\n duration: CANCEL_TIMEOUT,\n orElse: () =>\n protocolError(\"Cancelling the Browser Run crawl exceeded 30 seconds\"),\n }),\n );\n }),\n );\n\n yield* Scope.addFinalizer(\n scope,\n cancelIfRunning.pipe(\n Effect.catchCause(() =>\n Effect.logWarning(\"Browser Run crawl cancellation failed\"),\n ),\n ),\n );\n\n return { id, state } as const;\n }),\n ),\n ),\n );\n\n const fetchResult = Effect.fn(\"BrowserRestCrawl.fetchResult\")(function* (\n cursor: Option.Option<string>,\n statusOnly: boolean,\n ) {\n let request = HttpClientRequest.get(endpoint(options, job.id));\n\n if (statusOnly) request = HttpClientRequest.setUrlParam(request, \"limit\", \"1\");\n if (Option.isSome(cursor)) {\n request = HttpClientRequest.setUrlParam(request, \"cursor\", cursor.value);\n }\n\n // `limit=1` still permits one complete record, so poll GETs use the bounded result cap.\n const envelope = yield* withinDeadline(\n executeJson(request, ResultEnvelope, MAX_RESULTS_RESPONSE_BYTES),\n input,\n startedAt,\n );\n\n if (envelope.result.id !== job.id) {\n return yield* protocolError(\"Browser Run returned a different crawl job identity\");\n }\n\n return envelope.result;\n });\n\n const terminal = yield* Effect.uninterruptibleMask((restore) =>\n restore(\n withinDeadline(\n Effect.repeat(fetchResult(Option.none(), true), {\n schedule: Schedule.spaced(POLL_INTERVAL),\n until: (result) => result.status !== \"running\",\n }),\n input,\n startedAt,\n ),\n ).pipe(Effect.tap(() => Ref.set(job.state, \"terminal\"))),\n );\n\n if (terminal.status === \"running\") {\n return yield* protocolError(\"Browser Run polling stopped before a terminal status\");\n }\n if (terminal.status !== \"completed\") {\n return yield* PageCrawlTerminalError.make({\n implementation: browserRestCrawlImplementation,\n status: terminal.status,\n message: `Browser Run crawl ended with status ${terminal.status}`,\n });\n }\n\n const pages = Stream.paginate<PaginationState, PageCrawlRecord, PageCrawlError>(\n { cursor: Option.none(), seen: [] },\n (state) =>\n Effect.gen(function* () {\n const result = yield* fetchResult(state.cursor, false);\n\n if (result.status !== \"completed\") {\n return yield* protocolError(\n \"Browser Run changed crawl status during result pagination\",\n );\n }\n if (result.cursor === undefined) {\n return [result.records, Option.none()] as const;\n }\n const cursor = normalizedCursor(result.cursor);\n\n if (state.seen.includes(cursor)) {\n return yield* protocolError(\"Browser Run repeated a crawl result cursor\");\n }\n if (state.seen.length >= input.limits.maxPages) {\n return yield* protocolError(\"Browser Run returned too many crawl result cursors\");\n }\n\n return [\n result.records,\n Option.some({ cursor: Option.some(cursor), seen: [...state.seen, cursor] }),\n ] as const;\n }),\n );\n\n return pages.pipe(\n Stream.rechunk(1),\n Stream.mapAccumEffect(\n (): RecordLimitsState => ({ pages: 0, totalBytes: 0 }),\n (state, record) =>\n Effect.gen(function* () {\n yield* checkDeadline(input, startedAt);\n const pages = state.pages + 1;\n\n if (pages > input.limits.maxPages) {\n return yield* limitError(input, \"pages\", pages);\n }\n if (!sameHost(startHost, record.url)) {\n return yield* protocolError(\"Browser Run returned an off-host crawl record\");\n }\n if (record.metadata !== undefined && !sameHost(startHost, record.metadata.url)) {\n return yield* protocolError(\"Browser Run returned off-host crawl metadata\");\n }\n\n const pageBytes =\n record.markdown === undefined\n ? 0\n : new TextEncoder().encode(record.markdown).byteLength;\n\n if (pageBytes > input.limits.maxPageBytes) {\n return yield* limitError(input, \"page-bytes\", pageBytes);\n }\n const totalBytes = state.totalBytes + pageBytes;\n\n if (totalBytes > input.limits.maxTotalBytes) {\n return yield* limitError(input, \"total-bytes\", totalBytes);\n }\n\n return [{ pages, totalBytes }, [record]] as const;\n }),\n ),\n );\n }),\n );\n\n/** Cloudflare REST PageCrawl Layer for Node and other non-Worker composition roots. */\nexport const browserRestCrawlLayer = (\n options: BrowserRestCrawlOptions,\n): Layer.Layer<PageCrawl, never, HttpClient.HttpClient> =>\n Layer.effect(\n PageCrawl,\n Effect.map(HttpClient.HttpClient, (client) =>\n PageCrawl.of({ crawl: makeCrawl(client, options) }),\n ),\n );\n"],"mappings":";;;;;;AAgCA,MAAa,iCAAiC,sBAAsB,KAAK;CACvE,WAAW;CACX,UAAU;AACZ,CAAC;AAED,MAAM,aAAa;AACnB,MAAM,gBAAgB,SAAS,QAAQ,CAAC;AACxC,MAAM,iBAAiB,SAAS,QAAQ,EAAE;AAC1C,MAAM,6BAA6B;AACnC,MAAM,6BAA6B;AACnC,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B;AACjC,MAAM,eAAe,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC;AACxE,MAAM,sBAAsB,OAAO,eAAe,MAAM,OAAO,YAAY,iBAAiB,CAAC;AAE7F,MAAM,iBAAiB,OAAO,MAAM,CAAC,qBAAqB,OAAO,OAAO,CAAC;AAEzE,MAAM,oBAAoB,OAAO,SAAS;CACxC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,iBAAiB,OAAO,OAAO;CACnC,IAAI;CACJ,QAAQ;CACR,oBAAoB,OAAO,YAAY,OAAO,OAAO,MAA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AAW,GAAG,CAAC,MAAM,CAAC;CACzC,CAAC,CACL,CACF;AACF,CAAC,CACH;;AAGJ,MAAa,yBACX,YAEA,MAAM,OACJ,WACA,OAAO,IAAI,WAAW,aAAa,WACjC,UAAU,GAAG,EAAE,OAAO,UAAU,QAAQ,OAAO,EAAE,CAAC,CACpD,CACF"}
1
+ {"version":3,"file":"BrowserRestCrawl.mjs","names":[],"sources":["../src/BrowserRestCrawl.ts"],"sourcesContent":["import {\n PageCrawl,\n PageCrawlLimitError,\n PageCrawlProtocolError,\n PageCrawlRateLimitedError,\n PageCrawlRecord,\n PageCrawlTerminalError,\n type PageCrawlCrawl,\n type PageCrawlError,\n type PageCrawlRequest,\n} from \"@effect-agent/sandbox/PageCrawl\";\nimport { SandboxImplementation } from \"@effect-agent/sandbox/Sandbox\";\nimport {\n Duration,\n Effect,\n Layer,\n Option,\n Redacted,\n Ref,\n Schedule,\n Schema,\n Scope,\n Stream,\n} from \"effect\";\nimport {\n HttpClient,\n HttpClientRequest,\n type HttpClientError,\n type HttpClientResponse,\n} from \"effect/unstable/http\";\n\n/** Node-safe REST crawl implementation. It never exposes or persists provider job identity. */\nexport const browserRestCrawlImplementation = SandboxImplementation.make({\n isolation: \"isolated\",\n identity: \"cloudflare-browser-rest-crawl\",\n});\n\nconst API_ORIGIN = \"https://api.cloudflare.com\";\nconst POLL_INTERVAL = Duration.seconds(1);\nconst CANCEL_TIMEOUT = Duration.seconds(30);\nconst MAX_CONTROL_RESPONSE_BYTES = 64 * 1024;\nconst MAX_RESULTS_RESPONSE_BYTES = 12 * 1024 * 1024;\nconst MAX_DIAGNOSTIC_LENGTH = 8_000;\nconst MAX_CURSOR_LENGTH = 1_024;\nconst MAX_RECORDS_PER_RESPONSE = 10_000;\nconst BoundedJobId = Schema.NonEmptyString.check(Schema.isMaxLength(256));\nconst BoundedCursorString = Schema.NonEmptyString.check(Schema.isMaxLength(MAX_CURSOR_LENGTH));\n// The generated API response Schema says string; the current product example returns a number.\nconst ProviderCursor = Schema.Union([BoundedCursorString, Schema.Natural]);\n\nconst ProviderJobStatus = Schema.Literals([\n \"running\",\n \"completed\",\n \"errored\",\n \"cancelled_by_user\",\n \"cancelled_due_to_timeout\",\n \"cancelled_due_to_limits\",\n]);\n\nconst ProviderResult = Schema.Struct({\n id: BoundedJobId,\n status: ProviderJobStatus,\n browserSecondsUsed: Schema.optionalKey(Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))),\n total: Schema.optionalKey(Schema.Natural),\n finished: Schema.optionalKey(Schema.Natural),\n skipped: Schema.optionalKey(Schema.Natural),\n records: Schema.Array(PageCrawlRecord).check(Schema.isMaxLength(MAX_RECORDS_PER_RESPONSE)),\n cursor: Schema.optionalKey(ProviderCursor),\n});\n\nconst CreateEnvelope = Schema.Struct({\n success: Schema.Literal(true),\n result: BoundedJobId,\n});\n\nconst ResultEnvelope = Schema.Struct({\n success: Schema.Literal(true),\n result: ProviderResult,\n});\n\nconst DeleteEnvelope = Schema.Struct({\n success: Schema.Literal(true),\n result: Schema.Struct({\n job_id: BoundedJobId,\n message: Schema.String.check(Schema.isMaxLength(MAX_DIAGNOSTIC_LENGTH)),\n }),\n});\n\n/** Explicit credentials. The token is projected only into fixed-origin Authorization headers. */\nexport interface BrowserRestCrawlOptions {\n readonly accountId: string;\n readonly apiToken: Redacted.Redacted<string>;\n}\n\nconst boundedDiagnostic = (message: string): string => message.slice(0, MAX_DIAGNOSTIC_LENGTH);\n\nconst privateCause = (value: unknown, apiToken: Redacted.Redacted<string>): Error | undefined => {\n const raw = boundedDiagnostic(String(value));\n\n if (raw.length === 0) return undefined;\n const token = Redacted.value(apiToken);\n\n return new Error(token.length === 0 ? raw : raw.replaceAll(token, \"[REDACTED]\"));\n};\n\nconst protocolError = (message: string, cause?: unknown): PageCrawlProtocolError =>\n PageCrawlProtocolError.make({\n implementation: browserRestCrawlImplementation,\n message: boundedDiagnostic(message),\n ...(cause === undefined ? {} : { cause }),\n });\n\nconst limitError = (\n request: PageCrawlRequest,\n limit: PageCrawlLimitError[\"limit\"],\n observed: number,\n): PageCrawlLimitError => {\n const maximum =\n limit === \"pages\"\n ? request.limits.maxPages\n : limit === \"page-bytes\"\n ? request.limits.maxPageBytes\n : limit === \"total-bytes\"\n ? request.limits.maxTotalBytes\n : request.limits.deadlineMillis;\n\n return PageCrawlLimitError.make({\n implementation: browserRestCrawlImplementation,\n limit,\n maximum,\n observed,\n message: `The crawl exceeded its ${limit} limit`,\n });\n};\n\nconst retryAfterMillis = (\n headers: Readonly<Record<string, string | undefined>>,\n): number | undefined => {\n const seconds = Number(headers[\"retry-after\"]);\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 isJsonResponse = (headers: Readonly<Record<string, string | undefined>>): boolean => {\n const contentType = headers[\"content-type\"];\n\n if (contentType === undefined) return false;\n const mediaType = contentType.split(\";\", 1)[0]?.trim().toLowerCase();\n\n return mediaType === \"application/json\" || mediaType?.endsWith(\"+json\") === true;\n};\n\nconst isQuotaMessage = (bodyText: string): boolean => /time limit|daily|quota/i.test(bodyText);\n\nconst endpoint = (options: BrowserRestCrawlOptions, jobId?: string): string =>\n `${API_ORIGIN}/client/v4/accounts/${encodeURIComponent(options.accountId)}/browser-rendering/crawl${\n jobId === undefined ? \"\" : `/${encodeURIComponent(jobId)}`\n }`;\n\nconst readBoundedResponse = Effect.fn(\"BrowserRestCrawl.readBoundedResponse\")(function* (\n response: HttpClientResponse.HttpClientResponse,\n maximum: number,\n): Effect.fn.Return<string, PageCrawlProtocolError> {\n const decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false });\n\n const state = yield* Stream.runFoldEffect<\n Uint8Array,\n HttpClientError.HttpClientError,\n never,\n { readonly observed: number; readonly text: string },\n PageCrawlProtocolError,\n never\n >(\n response.stream,\n () => ({ observed: 0, text: \"\" }),\n (current, chunk) => {\n const observed = current.observed + chunk.byteLength;\n\n if (observed > maximum) {\n return Effect.fail(\n protocolError(\n `The Browser Run crawl response exceeded ${String(maximum)} transport bytes`,\n ),\n );\n }\n\n return Effect.try({\n try: () => ({ observed, text: current.text + decoder.decode(chunk, { stream: true }) }),\n catch: (cause) => protocolError(\"Decoding the Browser Run crawl response failed\", cause),\n });\n },\n ).pipe(\n Effect.mapError((cause) =>\n Schema.is(PageCrawlProtocolError)(cause)\n ? cause\n : protocolError(\"Reading the Browser Run crawl response failed\", cause),\n ),\n );\n\n return yield* Effect.try({\n try: () => state.text + decoder.decode(),\n catch: (cause) => protocolError(\"Decoding the Browser Run crawl response failed\", cause),\n });\n});\n\nconst deadlineFailure = Effect.fn(\"BrowserRestCrawl.deadlineFailure\")(function* (\n request: PageCrawlRequest,\n startedAt: number,\n) {\n const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\n return yield* limitError(request, \"deadline\", Math.max(0, now - startedAt));\n});\n\nconst withinDeadline = Effect.fn(\"BrowserRestCrawl.withinDeadline\")(function* <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n request: PageCrawlRequest,\n startedAt: number,\n): Effect.fn.Return<A, E | PageCrawlLimitError, R> {\n const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n const elapsed = Math.max(0, now - startedAt);\n const remaining = request.limits.deadlineMillis - elapsed;\n\n if (remaining <= 0) return yield* limitError(request, \"deadline\", elapsed);\n\n return yield* effect.pipe(\n Effect.timeoutOrElse({\n duration: Duration.millis(remaining),\n orElse: () => deadlineFailure(request, startedAt),\n }),\n );\n});\n\nconst checkDeadline = Effect.fn(\"BrowserRestCrawl.checkDeadline\")(function* (\n request: PageCrawlRequest,\n startedAt: number,\n) {\n const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n const elapsed = Math.max(0, now - startedAt);\n\n if (elapsed >= request.limits.deadlineMillis) {\n return yield* limitError(request, \"deadline\", elapsed);\n }\n});\n\nconst normalizedCursor = (cursor: typeof ProviderCursor.Type): string => String(cursor);\n\ninterface PaginationState {\n readonly cursor: Option.Option<string>;\n readonly seen: ReadonlyArray<string>;\n}\n\ninterface RecordLimitsState {\n readonly pages: number;\n readonly totalBytes: number;\n}\n\nconst sameHost = (expectedHost: string, url: string): boolean => new URL(url).host === expectedHost;\n\nconst makeCrawl =\n (client: HttpClient.HttpClient, options: BrowserRestCrawlOptions): PageCrawlCrawl =>\n (input) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const startedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n const startHost = new URL(input.startUrl).host;\n\n const executeJson = Effect.fn(\"BrowserRestCrawl.executeJson\")(function* <\n S extends Schema.Top,\n >(request: HttpClientRequest.HttpClientRequest, schema: S, maximum: number) {\n const authorized = HttpClientRequest.bearerToken(request, options.apiToken).pipe(\n HttpClientRequest.acceptJson,\n );\n\n const response = yield* client\n .execute(authorized)\n .pipe(\n Effect.mapError((cause) =>\n protocolError(\n \"Calling the Browser Run crawl REST API failed\",\n privateCause(cause, options.apiToken),\n ),\n ),\n );\n\n const bodyText = yield* readBoundedResponse(response, maximum);\n\n if (response.status === 429) {\n const reason = isQuotaMessage(bodyText) ? \"quota\" : \"rate\";\n\n return yield* PageCrawlRateLimitedError.make({\n implementation: browserRestCrawlImplementation,\n reason,\n ...(retryAfterMillis(response.headers) === undefined\n ? {}\n : { retryAfterMillis: retryAfterMillis(response.headers) }),\n message:\n reason === \"quota\"\n ? \"Browser Run exceeded its browser quota\"\n : \"Browser Run crawl was rate limited\",\n ...(privateCause(bodyText, options.apiToken) === undefined\n ? {}\n : { cause: privateCause(bodyText, options.apiToken) }),\n });\n }\n if (response.status < 200 || response.status >= 300) {\n return yield* protocolError(\n `Browser Run crawl answered HTTP ${String(response.status)}`,\n privateCause(bodyText, options.apiToken),\n );\n }\n if (!isJsonResponse(response.headers)) {\n return yield* protocolError(\n \"The Browser Run crawl success response was not JSON\",\n privateCause(bodyText, options.apiToken),\n );\n }\n\n return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(bodyText).pipe(\n Effect.mapError((cause) =>\n protocolError(\n \"Browser Run returned a malformed crawl response\",\n privateCause(cause, options.apiToken),\n ),\n ),\n );\n });\n\n const createJob = Effect.gen(function* () {\n const requestWithBody = yield* HttpClientRequest.post(endpoint(options)).pipe(\n HttpClientRequest.bodyJson({\n url: input.startUrl,\n crawlPurposes: [...input.purposes],\n limit: input.limits.maxPages,\n depth: input.limits.maxDepth,\n formats: [\"markdown\"],\n render: true,\n options: {\n includeExternalLinks: false,\n includeSubdomains: false,\n },\n }),\n Effect.mapError((cause) =>\n protocolError(\"Encoding the Browser Run crawl request failed\", cause),\n ),\n );\n\n const created = yield* withinDeadline(\n executeJson(requestWithBody, CreateEnvelope, MAX_CONTROL_RESPONSE_BYTES),\n input,\n startedAt,\n );\n\n return created.result;\n });\n\n const job = yield* Effect.uninterruptibleMask((restore) =>\n restore(createJob).pipe(\n Effect.flatMap((id) =>\n Effect.gen(function* () {\n const state = yield* Ref.make<\"running\" | \"terminal\">(\"running\");\n const scope = yield* Effect.scope;\n\n const cancelIfRunning = Ref.modify(state, (current) =>\n current === \"running\"\n ? [true, \"terminal\" as const]\n : [false, \"terminal\" as const],\n ).pipe(\n Effect.flatMap((shouldCancel) => {\n if (!shouldCancel) return Effect.void;\n\n const cancellation = executeJson(\n HttpClientRequest.delete(endpoint(options, id)),\n DeleteEnvelope,\n MAX_CONTROL_RESPONSE_BYTES,\n ).pipe(\n Effect.flatMap((deleted) =>\n deleted.result.job_id === id\n ? Effect.void\n : protocolError(\"Browser Run cancelled a different crawl job\"),\n ),\n );\n\n return cancellation.pipe(\n Effect.timeoutOrElse({\n duration: CANCEL_TIMEOUT,\n orElse: () =>\n protocolError(\"Cancelling the Browser Run crawl exceeded 30 seconds\"),\n }),\n );\n }),\n );\n\n yield* Scope.addFinalizer(\n scope,\n cancelIfRunning.pipe(\n Effect.catchCause(() =>\n Effect.logWarning(\"Browser Run crawl cancellation failed\"),\n ),\n ),\n );\n\n return { id, state } as const;\n }),\n ),\n ),\n );\n\n const fetchResult = Effect.fn(\"BrowserRestCrawl.fetchResult\")(function* (\n cursor: Option.Option<string>,\n statusOnly: boolean,\n ) {\n let request = HttpClientRequest.get(endpoint(options, job.id));\n\n if (statusOnly) request = HttpClientRequest.setUrlParam(request, \"limit\", \"1\");\n if (Option.isSome(cursor)) {\n request = HttpClientRequest.setUrlParam(request, \"cursor\", cursor.value);\n }\n\n // `limit=1` still permits one complete record, so poll GETs use the bounded result cap.\n const envelope = yield* withinDeadline(\n executeJson(request, ResultEnvelope, MAX_RESULTS_RESPONSE_BYTES),\n input,\n startedAt,\n );\n\n if (envelope.result.id !== job.id) {\n return yield* protocolError(\"Browser Run returned a different crawl job identity\");\n }\n\n return envelope.result;\n });\n\n const terminal = yield* Effect.uninterruptibleMask((restore) =>\n restore(\n withinDeadline(\n Effect.repeat(fetchResult(Option.none(), true), {\n schedule: Schedule.spaced(POLL_INTERVAL),\n until: (result) => result.status !== \"running\",\n }),\n input,\n startedAt,\n ),\n ).pipe(Effect.tap(() => Ref.set(job.state, \"terminal\"))),\n );\n\n if (terminal.status === \"running\") {\n return yield* protocolError(\"Browser Run polling stopped before a terminal status\");\n }\n if (terminal.status !== \"completed\") {\n return yield* PageCrawlTerminalError.make({\n implementation: browserRestCrawlImplementation,\n status: terminal.status,\n message: `Browser Run crawl ended with status ${terminal.status}`,\n });\n }\n\n const pages = Stream.paginate<PaginationState, PageCrawlRecord, PageCrawlError>(\n { cursor: Option.none(), seen: [] },\n (state) =>\n Effect.gen(function* () {\n const result = yield* fetchResult(state.cursor, false);\n\n if (result.status !== \"completed\") {\n return yield* protocolError(\n \"Browser Run changed crawl status during result pagination\",\n );\n }\n if (result.cursor === undefined) {\n return [result.records, Option.none()] as const;\n }\n const cursor = normalizedCursor(result.cursor);\n\n if (state.seen.includes(cursor)) {\n return yield* protocolError(\"Browser Run repeated a crawl result cursor\");\n }\n if (state.seen.length >= input.limits.maxPages) {\n return yield* protocolError(\"Browser Run returned too many crawl result cursors\");\n }\n\n return [\n result.records,\n Option.some({ cursor: Option.some(cursor), seen: [...state.seen, cursor] }),\n ] as const;\n }),\n );\n\n return pages.pipe(\n Stream.rechunk(1),\n Stream.mapAccumEffect(\n (): RecordLimitsState => ({ pages: 0, totalBytes: 0 }),\n (state, record) =>\n Effect.gen(function* () {\n yield* checkDeadline(input, startedAt);\n const pages = state.pages + 1;\n\n if (pages > input.limits.maxPages) {\n return yield* limitError(input, \"pages\", pages);\n }\n if (!sameHost(startHost, record.url)) {\n return yield* protocolError(\"Browser Run returned an off-host crawl record\");\n }\n if (record.metadata !== undefined && !sameHost(startHost, record.metadata.url)) {\n return yield* protocolError(\"Browser Run returned off-host crawl metadata\");\n }\n\n const pageBytes =\n record.markdown === undefined\n ? 0\n : new TextEncoder().encode(record.markdown).byteLength;\n\n if (pageBytes > input.limits.maxPageBytes) {\n return yield* limitError(input, \"page-bytes\", pageBytes);\n }\n const totalBytes = state.totalBytes + pageBytes;\n\n if (totalBytes > input.limits.maxTotalBytes) {\n return yield* limitError(input, \"total-bytes\", totalBytes);\n }\n\n return [{ pages, totalBytes }, [record]] as const;\n }),\n ),\n );\n }),\n );\n\n/** Cloudflare REST PageCrawl Layer for Node and other non-Worker composition roots. */\nexport const browserRestCrawlLayer = (\n options: BrowserRestCrawlOptions,\n): Layer.Layer<PageCrawl, never, HttpClient.HttpClient> =>\n Layer.effect(\n PageCrawl,\n Effect.map(HttpClient.HttpClient, (client) =>\n PageCrawl.of({ crawl: makeCrawl(client, options) }),\n ),\n );\n"],"mappings":";;;;;;AAgCA,MAAa,iCAAiC,sBAAsB,KAAK;CACvE,WAAW;CACX,UAAU;AACZ,CAAC;AAED,MAAM,aAAa;AACnB,MAAM,gBAAgB,SAAS,QAAQ,CAAC;AACxC,MAAM,iBAAiB,SAAS,QAAQ,EAAE;AAC1C,MAAM,6BAA6B;AACnC,MAAM,6BAA6B;AACnC,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B;A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AS,GAAG,GAC3E,OAAO,OAAO,cAAc,8CAA8C;EAG5E,MAAM,YACJ,OAAO,aAAa,KAAA,IAChB,IACA,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,QAAQ,CAAC,CAAC;EAEhD,IAAI,YAAY,MAAM,OAAO,cAC3B,OAAO,OAAO,WAAW,OAAO,cAAc,SAAS;EAEzD,MAAM,aAAa,MAAM,aAAa;EAEtC,IAAI,aAAa,MAAM,OAAO,eAC5B,OAAO,OAAO,WAAW,OAAO,eAAe,UAAU;EAG3D,OAAO,CAAC;GAAE;GAAO;EAAW,GAAG,CAAC,MAAM,CAAC;CACzC,CAAC,CACL,CACF;AACF,CAAC,CACH;;AAGJ,MAAa,yBACX,YAEA,MAAM,OACJ,WACA,OAAO,IAAI,WAAW,aAAa,WACjC,UAAU,GAAG,EAAE,OAAO,UAAU,QAAQ,OAAO,EAAE,CAAC,CACpD,CACF"}
@@ -30,12 +30,12 @@ const memoryObjectName = (namespace) => namespace.address;
30
30
  * may have committed: reconcile by sending the identical operation ID and command.
31
31
  */
32
32
  const makeMemoryClient = Effect.fn("CloudflareMemoryClient.make")(function* (access, principal, rpcLimits = defaultMemoryRpcLimits) {
33
- const validated = yield* Schema.decodeUnknownEffect(MemoryRpcLimits)(rpcLimits).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
33
+ const validated = yield* Schema.decodeEffect(MemoryRpcLimits)(rpcLimits).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
34
34
  const bound = yield* Schema.decodeUnknownEffect(MemoryAccess.Wire)(access).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
35
- principal = yield* Schema.decodeUnknownEffect(Principal)(principal).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
35
+ principal = yield* Schema.decodeEffect(Principal)(principal).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
36
36
  const { namespace } = yield* MemoryObjectNamespace;
37
37
  const call = Effect.fn("CloudflareMemoryClient.call")(function* (request) {
38
- const decoded = yield* Schema.decodeUnknownEffect(MemoryOwnerRequest)(request).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
38
+ const decoded = yield* Schema.decodeEffect(MemoryOwnerRequest)(request).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
39
39
  const encoded = yield* encodeMemoryWire(MemoryOwnerRequest, decoded, validated.maxRequestBytes);
40
40
  const unavailable = (cause) => {
41
41
  const error = MemoryRpcError.make({ reason: "unavailable" });
@@ -58,7 +58,7 @@ const makeMemoryClient = Effect.fn("CloudflareMemoryClient.make")(function* (acc
58
58
  orElse: () => Effect.fail(MemoryRpcError.make({ reason: "timeout" }))
59
59
  }));
60
60
  const revalidate = Effect.fn("CloudflareMemoryClient.revalidate")(function* (lookup, limits) {
61
- limits = yield* Schema.decodeUnknownEffect(MemoryRecallLimits)(limits).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
61
+ limits = yield* Schema.decodeEffect(MemoryRecallLimits)(limits).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
62
62
  const timeoutMillis = Math.min(validated.timeoutMillis, limits.timeoutMillis);
63
63
  return yield* Effect.gen(function* () {
64
64
  const response = yield* call({
@@ -188,7 +188,7 @@ const makeMemoryObject = (host, options = {}) => {
188
188
  const runtime = Layer.effectContext(Effect.gen(function* () {
189
189
  const state = yield* DurableObjectState.DurableObjectState;
190
190
  const scope = yield* Effect.scope;
191
- yield* Schema.decodeUnknownEffect(MemoryRpcLimits)(options.rpcLimits ?? defaultMemoryRpcLimits).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
191
+ yield* Schema.decodeEffect(MemoryRpcLimits)(options.rpcLimits ?? defaultMemoryRpcLimits).pipe(Effect.mapError(() => MemoryRpcError.make({ reason: "protocol" })));
192
192
  return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));
193
193
  }));
194
194
  return DurableObject.make(runtime, { rpc: { memory: (encoded) => handleMemoryOwnerRequest(encoded, options.rpcLimits) } });
@@ -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 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 RpcTargets,\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 unavailable = (cause: unknown) => {\n const error = MemoryRpcError.make({ reason: \"unavailable\" });\n\n error.cause = cause;\n\n return error;\n };\n\n const address = memoryObjectName(bound.namespace);\n\n const target = yield* RpcTargets.get(namespace, address, () =>\n namespace.get(namespace.idFromName(address)),\n ).pipe(Effect.mapError(unavailable));\n\n const raw = yield* Effect.tryPromise({\n try: () => target.memory(encoded),\n catch: unavailable,\n }).pipe(Effect.tapCause(() => RpcTargets.invalidate(target)));\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":";;;;;;;;;;;;;;;;;;;;;;AAkDA,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,eAA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,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 RpcTargets,\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.decodeEffect(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.decodeEffect(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.decodeEffect(MemoryOwnerRequest)(request).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\n\n const encoded = yield* encodeMemoryWire(MemoryOwnerRequest, decoded, validated.maxRequestBytes);\n\n const unavailable = (cause: unknown) => {\n const error = MemoryRpcError.make({ reason: \"unavailable\" });\n\n error.cause = cause;\n\n return error;\n };\n\n const address = memoryObjectName(bound.namespace);\n\n const target = yield* RpcTargets.get(namespace, address, () =>\n namespace.get(namespace.idFromName(address)),\n ).pipe(Effect.mapError(unavailable));\n\n const raw = yield* Effect.tryPromise({\n try: () => target.memory(encoded),\n catch: unavailable,\n }).pipe(Effect.tapCause(() => RpcTargets.invalidate(target)));\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.decodeEffect(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.decodeEffect(MemoryRpcLimits)(options.rpcLimits ?? defaultMemoryRpcLimits).pipe(\n Effect.mapError(() => MemoryRpcError.make({ reason: \"protocol\" })),\n );\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":";;;;;;;;;;;;;;;;;;;;;;AAkDA,IAAa,wB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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,aAAa,eAAe,CAAC,CAAC,QAAQ,aAAa,sBAAsB,CAAC,CAAC,KACvF,OAAO,eAAe,eAAe,KAAK,EAAE,QAAQ,WAAW,CAAC,CAAC,CACnE;EAEA,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"}
@@ -248,8 +248,8 @@ var CloudflareSchedulingClient = class {
248
248
  var ScheduleOwnerIdentity = class extends Context.Service()("@effect-agent/platform-cloudflare/ScheduleOwnerIdentity") {};
249
249
  const decodeOwnerName = Effect.fn("decodeScheduleOwnerName")(function* (name) {
250
250
  if (name === null || name === void 0) return yield* ScheduleOwnerProtocolError.make({ message: "Schedule Owner objects require an idFromName identity" });
251
- const tuple = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])))(name).pipe(Effect.mapError(() => ScheduleOwnerProtocolError.make({ message: "Schedule Owner object name is malformed" })));
252
- return yield* Schema.decodeUnknownEffect(ScheduleOwner)({
251
+ const tuple = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])))(name).pipe(Effect.mapError(() => ScheduleOwnerProtocolError.make({ message: "Schedule Owner object name is malformed" })));
252
+ return yield* Schema.decodeEffect(ScheduleOwner)({
253
253
  tenantId: tuple[0],
254
254
  ownerId: tuple[1]
255
255
  }).pipe(Effect.mapError(() => ScheduleOwnerProtocolError.make({ message: "Schedule Owner object identity is invalid" })));