@yielded/agent-platform-cloudflare 0.1.0-beta.185 → 0.1.0-beta.187

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 (128) hide show
  1. package/dist/{Alarm-C257DCAJ.mjs → Alarm-4qf-iCXC.mjs} +94 -54
  2. package/dist/Alarm-4qf-iCXC.mjs.map +1 -0
  3. package/dist/Alarm.d.mts +16 -9
  4. package/dist/Alarm.mjs +1 -1
  5. package/dist/{BrowserCredentials-C2rBhlUI.d.mts → BrowserCredentials-CysbK6UA.d.mts} +4 -2
  6. package/dist/BrowserCredentials.d.mts +1 -1
  7. package/dist/BrowserCredentials.mjs +2 -1
  8. package/dist/BrowserCredentials.mjs.map +1 -1
  9. package/dist/BrowserRestCapture.d.mts +4 -3
  10. package/dist/BrowserRestCapture.mjs +9 -3
  11. package/dist/BrowserRestCapture.mjs.map +1 -1
  12. package/dist/BrowserRestCrawl.d.mts +3 -2
  13. package/dist/BrowserRestCrawl.mjs +12 -2
  14. package/dist/BrowserRestCrawl.mjs.map +1 -1
  15. package/dist/{BrowserSession-mKnLSc3p.d.mts → BrowserSession-BLEG79zz.d.mts} +12 -5
  16. package/dist/{BrowserSession-CfivQ5JY.mjs → BrowserSession-CITvpByq.mjs} +17 -5
  17. package/dist/BrowserSession-CITvpByq.mjs.map +1 -0
  18. package/dist/BrowserSession.d.mts +2 -2
  19. package/dist/BrowserSession.mjs +2 -2
  20. package/dist/BrowserUse.d.mts +4 -2
  21. package/dist/BrowserUse.mjs +6 -2
  22. package/dist/BrowserUse.mjs.map +1 -1
  23. package/dist/CloudflareAiGateway.d.mts +3 -2
  24. package/dist/CloudflareAiGateway.mjs +12 -2
  25. package/dist/CloudflareAiGateway.mjs.map +1 -1
  26. package/dist/CloudflareBindings.d.mts +4 -1
  27. package/dist/CloudflareBindings.mjs +5 -1
  28. package/dist/CloudflareBindings.mjs.map +1 -1
  29. package/dist/{CloudflareBrowser-gu7gma0Y.d.mts → CloudflareBrowser-CZoXu_oS.d.mts} +5 -2
  30. package/dist/{CloudflareBrowser-Vt8qTdYW.mjs → CloudflareBrowser-Wfs-zRuk.mjs} +6 -2
  31. package/dist/CloudflareBrowser-Wfs-zRuk.mjs.map +1 -0
  32. package/dist/CloudflareBrowser.d.mts +1 -1
  33. package/dist/CloudflareBrowser.mjs +1 -1
  34. package/dist/CloudflareCodeMode.d.mts +2 -1
  35. package/dist/CloudflareCodeMode.mjs +10 -2
  36. package/dist/CloudflareCodeMode.mjs.map +1 -1
  37. package/dist/{CloudflareConfig-C9MvPbX8.d.mts → CloudflareConfig-D_-BMp4q.d.mts} +12 -6
  38. package/dist/CloudflareConfig.d.mts +2 -2
  39. package/dist/CloudflareConfig.mjs +12 -5
  40. package/dist/CloudflareConfig.mjs.map +1 -1
  41. package/dist/CloudflareMemory.d.mts +3 -1
  42. package/dist/CloudflareMemory.mjs +5 -1
  43. package/dist/CloudflareMemory.mjs.map +1 -1
  44. package/dist/CloudflareScheduling.d.mts +4 -1
  45. package/dist/CloudflareScheduling.mjs +9 -4
  46. package/dist/CloudflareScheduling.mjs.map +1 -1
  47. package/dist/CloudflareSubscriptions.d.mts +6 -1
  48. package/dist/CloudflareSubscriptions.mjs +10 -4
  49. package/dist/CloudflareSubscriptions.mjs.map +1 -1
  50. package/dist/{CloudflareThreadClient-CnvMXPmV.mjs → CloudflareThreadClient-DiV2xHn0.mjs} +16 -135
  51. package/dist/CloudflareThreadClient-DiV2xHn0.mjs.map +1 -0
  52. package/dist/CloudflareThreadClient.d.mts +2144 -2
  53. package/dist/CloudflareThreadClient.mjs +2 -1
  54. package/dist/{InteractiveBrowser-nukKxc87.mjs → InteractiveBrowser-Bh9wisQI.mjs} +18 -5
  55. package/dist/InteractiveBrowser-Bh9wisQI.mjs.map +1 -0
  56. package/dist/{InteractiveBrowser-wV2Bti5e.d.mts → InteractiveBrowser-DbYpKPA3.d.mts} +8 -3
  57. package/dist/InteractiveBrowser.d.mts +1 -1
  58. package/dist/InteractiveBrowser.mjs +1 -1
  59. package/dist/LiveText-D7WxSY-h.d.mts +96 -0
  60. package/dist/LiveText-DRzUabZi.mjs +151 -0
  61. package/dist/LiveText-DRzUabZi.mjs.map +1 -0
  62. package/dist/LiveText.d.mts +2 -0
  63. package/dist/LiveText.mjs +2 -0
  64. package/dist/{ThreadObject-Osn-FmcF.d.mts → ThreadObject-BcoRabnQ.d.mts} +27 -11
  65. package/dist/{ThreadObject-Cr1CFWXb.mjs → ThreadObject-EChaDQBT.mjs} +47 -18
  66. package/dist/ThreadObject-EChaDQBT.mjs.map +1 -0
  67. package/dist/ThreadObject.d.mts +1 -1
  68. package/dist/ThreadObject.mjs +1 -1
  69. package/dist/WakeScheduler.d.mts +1 -1
  70. package/dist/WakeScheduler.mjs +7 -3
  71. package/dist/WakeScheduler.mjs.map +1 -1
  72. package/dist/{boundary-BguazVkh.mjs → boundary-BLbZMBl2.mjs} +2 -2
  73. package/dist/boundary-BLbZMBl2.mjs.map +1 -0
  74. package/dist/{browser-failure-DECzRY3H.mjs → browser-failure-BrL9H7IG.mjs} +6 -2
  75. package/dist/browser-failure-BrL9H7IG.mjs.map +1 -0
  76. package/dist/index.d.mts +8 -7
  77. package/dist/index.mjs +7 -6
  78. package/dist/{prepared-admission-w2Kq32_k.mjs → prepared-admission-mGUYbSH_.mjs} +4 -3
  79. package/dist/prepared-admission-mGUYbSH_.mjs.map +1 -0
  80. package/package.json +1 -1
  81. package/src/Alarm.ts +128 -82
  82. package/src/BrowserCredentials.ts +3 -1
  83. package/src/BrowserRestCapture.ts +9 -2
  84. package/src/BrowserRestCrawl.ts +14 -18
  85. package/src/BrowserSession.ts +10 -12
  86. package/src/BrowserUse.ts +5 -1
  87. package/src/CloudflareAiGateway.ts +12 -8
  88. package/src/CloudflareBindings.ts +5 -1
  89. package/src/CloudflareCodeMode.ts +9 -1
  90. package/src/CloudflareConfig.ts +10 -3
  91. package/src/CloudflareMemory.ts +5 -1
  92. package/src/CloudflareScheduling.ts +7 -2
  93. package/src/CloudflareSubscriptions.ts +9 -2
  94. package/src/CloudflareThreadClient.ts +15 -148
  95. package/src/InteractiveBrowser.ts +10 -12
  96. package/src/LiveText.ts +141 -0
  97. package/src/ThreadObject.ts +13 -8
  98. package/src/WakeScheduler.ts +5 -1
  99. package/src/index.ts +1 -0
  100. package/src/internal/boundary.ts +1 -1
  101. package/src/internal/browser-binding.ts +5 -1
  102. package/src/internal/browser-credentials.ts +5 -1
  103. package/src/internal/browser-failure.ts +6 -2
  104. package/src/internal/browser-file-selection.ts +1 -1
  105. package/src/internal/browser-quick-action.ts +5 -1
  106. package/src/internal/browser-readonly-live-view.ts +9 -2
  107. package/src/internal/browser-session-lifecycle.ts +10 -2
  108. package/src/internal/crypto.ts +5 -2
  109. package/src/internal/due-queue.ts +2 -1
  110. package/src/internal/host-protocol-error.ts +23 -0
  111. package/src/internal/layers.ts +45 -22
  112. package/src/internal/live-text-observation.ts +8 -0
  113. package/src/internal/live-text-protocol.ts +10 -9
  114. package/src/internal/live-text.ts +28 -10
  115. package/src/internal/message-delivery.ts +7 -1
  116. package/src/internal/prepared-admission.ts +2 -1
  117. package/src/internal/progress-wait.ts +6 -1
  118. package/src/internal/transport.ts +2 -1
  119. package/dist/Alarm-C257DCAJ.mjs.map +0 -1
  120. package/dist/BrowserSession-CfivQ5JY.mjs.map +0 -1
  121. package/dist/CloudflareBrowser-Vt8qTdYW.mjs.map +0 -1
  122. package/dist/CloudflareThreadClient-CmlojpjC.d.mts +0 -2211
  123. package/dist/CloudflareThreadClient-CnvMXPmV.mjs.map +0 -1
  124. package/dist/InteractiveBrowser-nukKxc87.mjs.map +0 -1
  125. package/dist/ThreadObject-Cr1CFWXb.mjs.map +0 -1
  126. package/dist/boundary-BguazVkh.mjs.map +0 -1
  127. package/dist/browser-failure-DECzRY3H.mjs.map +0 -1
  128. package/dist/prepared-admission-w2Kq32_k.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareSubscriptions.mjs","names":["EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/CloudflareSubscriptions.ts"],"sourcesContent":["import { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport {\n DoSubscriptionAlarmControl,\n DoSubscriptionTransaction,\n doSubscriptionStoreLayer,\n} from \"@yielded/agent-storage-cloudflare/do-subscription-store\";\nimport { type EventSources } from \"@yielded/agent/event-source\";\nimport { PersistedJson } from \"@yielded/agent/records\";\nimport { Principal } from \"@yielded/agent/submission-ledger\";\nimport {\n EventAcknowledgement,\n EventSourceVersion,\n SourcePartition,\n type SubscriptionAuthorizer,\n SubscriptionConfiguration,\n SubscriptionDeliverySnapshot,\n SubscriptionDeliveryKey,\n SubscriptionError,\n SubscriptionFailpointError,\n SubscriptionKey,\n SubscriptionScope,\n type SubscriptionLimits,\n SubscriptionSnapshot,\n SubscriptionSourceError,\n defaultSubscriptionLimits,\n} from \"@yielded/agent/subscription\";\nimport { type SubscriptionInputBindings } from \"@yielded/agent/subscription-input\";\nimport {\n SubscriptionDriver,\n SubscriptionIntake,\n Subscriptions,\n} from \"@yielded/agent/subscriptions\";\nimport { Cause, Clock, Context, DateTime, Effect, Layer, Schema, type Scope } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectAlarm,\n DurableObjectState as EffectCfDurableObjectState,\n type WorkerEnvironment,\n} from \"effect-cf\";\n\nimport { type ThreadObjectNamespace } from \"./CloudflareBindings.ts\";\nimport { CloudflareThreadClient } from \"./CloudflareThreadClient.ts\";\nimport { cloudflareCryptoLayer } from \"./internal/crypto.ts\";\nimport { cloudflarePreparedInputAdmissionLayer } from \"./internal/prepared-admission.ts\";\n\nconst SUBSCRIPTION_ALARM_TAG = \"effect-agent/SubscriptionPartitionWake\";\nconst SUBSCRIPTION_ALARM_ID = \"driver\";\nconst MAX_ALARM_WALL_MILLIS = 12 * 60_000;\nconst MAX_ALARMS_PER_INVOCATION = 16;\nconst MAX_ANCILLARY_ALARM_MILLIS = 30_000;\n\nconst SubscriptionAlarmPayload = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n generation: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nexport class SubscriptionAlarmProtocolError extends Schema.TaggedError<SubscriptionAlarmProtocolError>()(\n \"SubscriptionAlarmProtocolError\",\n { message: Schema.String },\n) {}\n\n/** Bounded host diagnostic; credentials and provider responses do not belong in alarm failures. */\nexport class SubscriptionAlarmExtensionError extends Schema.TaggedError<SubscriptionAlarmExtensionError>()(\n \"SubscriptionAlarmExtensionError\",\n { code: Schema.NonEmptyString.check(Schema.isMaxLength(128)) },\n) {}\n\n/** Native partition services supplied at alarm invocation, after the host Layer is built. */\nexport type SubscriptionPartitionAlarmServices =\n | Subscriptions\n | SubscriptionIntake\n | SubscriptionDriver;\n\nexport interface SubscriptionPartitionAlarmHandler<R = SubscriptionPartitionAlarmServices> {\n readonly tag: string;\n readonly handle: (\n event: DurableObjectAlarm.DurableObjectAlarmEvent,\n ) => Effect.Effect<void, SubscriptionAlarmProtocolError | SubscriptionAlarmExtensionError, R>;\n}\n\n/** Host-only handlers; the framework reserves its namespace and rejects every unknown tag. */\nexport const SubscriptionPartitionAlarmExtension = Context.Reference<{\n readonly handlers: ReadonlyArray<SubscriptionPartitionAlarmHandler>;\n}>(\"@effect-agent/platform-cloudflare/SubscriptionPartitionAlarmExtension\", {\n defaultValue: () => ({ handlers: [] }),\n});\n\n/** Capture host services once, deferring native partition services to invocation.\n * Each invocation owns its codec/handler Scope and timeout.\n * Callback failures stay typed. Defects and interruption reach the native alarm multiplexer.\n * The host owns durable idempotency, prearming and external-effect uncertainty.\n */\nexport const makeSubscriptionPartitionAlarmHandler = Effect.fnUntraced(function* <\n Payload extends Schema.Top,\n R,\n>(options: {\n readonly tag: string;\n readonly payload: Payload;\n readonly timeoutMillis: number;\n readonly handle: (\n event: Omit<DurableObjectAlarm.DurableObjectAlarmEvent, \"payload\"> & {\n readonly payload: Payload[\"Type\"];\n },\n ) => Effect.Effect<void, SubscriptionAlarmExtensionError, R>;\n}): Effect.fn.Return<\n SubscriptionPartitionAlarmHandler<\n Exclude<\n Exclude<R | Payload[\"DecodingServices\"], Scope.Scope>,\n Exclude<\n Exclude<R | Payload[\"DecodingServices\"], Scope.Scope | SubscriptionPartitionAlarmServices>,\n SubscriptionPartitionAlarmServices\n >\n >\n >,\n SubscriptionAlarmProtocolError,\n Exclude<R | Payload[\"DecodingServices\"], Scope.Scope | SubscriptionPartitionAlarmServices>\n> {\n if (\n options.tag.length === 0 ||\n options.tag.length > 128 ||\n options.tag.startsWith(\"effect-agent/\") ||\n !Number.isSafeInteger(options.timeoutMillis) ||\n options.timeoutMillis < 1 ||\n options.timeoutMillis > MAX_ANCILLARY_ALARM_MILLIS\n )\n return yield* SubscriptionAlarmProtocolError.make({\n message: \"Invalid ancillary alarm tag or timeout\",\n });\n\n // Context capture includes unrequested services too; never retain a host override of native work.\n const services = (yield* Effect.context<\n Exclude<R | Payload[\"DecodingServices\"], Scope.Scope | SubscriptionPartitionAlarmServices>\n >()).pipe(Context.omit(Subscriptions, SubscriptionIntake, SubscriptionDriver));\n\n return {\n tag: options.tag,\n handle: Effect.fnUntraced(\n function* (event) {\n if (event.tag !== options.tag)\n return yield* SubscriptionAlarmProtocolError.make({\n message: \"Ancillary alarm tag mismatch\",\n });\n\n const payload = yield* Schema.decodeEffect(options.payload)(event.payload).pipe(\n Effect.mapError(() =>\n SubscriptionAlarmProtocolError.make({ message: \"Invalid ancillary alarm payload\" }),\n ),\n );\n\n yield* options.handle({ ...event, payload });\n },\n (effect) =>\n effect.pipe(\n Effect.scoped,\n Effect.timeoutOrElse({\n duration: options.timeoutMillis,\n orElse: () => SubscriptionAlarmExtensionError.make({ code: \"timeout\" }),\n }),\n Effect.provideContext(services),\n ),\n ),\n };\n});\n\nexport class SubscriptionPartitionProtocolError extends Schema.TaggedError<SubscriptionPartitionProtocolError>()(\n \"SubscriptionPartitionProtocolError\",\n { message: Schema.String.check(Schema.isMaxLength(4_096)) },\n) {}\n\nexport class CloudflareSubscriptionConfigError extends Schema.TaggedError<CloudflareSubscriptionConfigError>()(\n \"CloudflareSubscriptionConfigError\",\n { message: Schema.String },\n) {}\n\n/** Reject limits whose four bounded phases could exceed the safe Durable Object alarm budget. */\nexport const validateCloudflareSubscriptionLimits = (\n limits: SubscriptionLimits,\n options: { readonly ancillaryAlarms?: boolean } = {},\n): Effect.Effect<void, CloudflareSubscriptionConfigError> => {\n const worstCaseMillis =\n 4 * Math.ceil(limits.batchSize / limits.concurrency) * limits.operationTimeoutMillis +\n (options.ancillaryAlarms === true ? MAX_ALARMS_PER_INVOCATION * MAX_ANCILLARY_ALARM_MILLIS : 0);\n\n return worstCaseMillis <= MAX_ALARM_WALL_MILLIS\n ? Effect.void\n : Effect.fail(\n CloudflareSubscriptionConfigError.make({\n message: \"Subscription limits can exceed the bounded Durable Object alarm wall budget\",\n }),\n );\n};\n\nconst protocolMessage = (message: string): string =>\n message.length <= 4_096 ? message : `${message.slice(0, 4_093)}...`;\n\nconst SubscribeRequest = Schema.TaggedStruct(\"Subscribe\", {\n schemaVersion: Schema.Literal(1),\n scope: Schema.Struct({\n ...SubscriptionScope.fields,\n }),\n options: Schema.Struct({\n subscriptionId: SubscriptionKey.fields.subscriptionId,\n source: EventSourceVersion,\n parameters: PersistedJson,\n context: PersistedJson,\n mode: Schema.Literals([\"once\", \"continuous\"]),\n expiresAtMillis: Schema.NullOr(Schema.Number),\n destination: SubscriptionConfiguration.fields.destination,\n deliveryPrincipal: SubscriptionConfiguration.fields.deliveryPrincipal,\n admissionGroup: SubscriptionConfiguration.fields.admissionGroup,\n admissionFence: SubscriptionConfiguration.fields.admissionFence,\n agentId: SubscriptionConfiguration.fields.agentId,\n definitions: SubscriptionConfiguration.fields.definitions,\n }),\n});\n\nconst UpdateSubscriptionRequest = Schema.TaggedStruct(\"UpdateSubscription\", {\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n key: SubscriptionKey,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n options: SubscribeRequest.fields.options.mapFields(({ subscriptionId: _, ...fields }) => fields),\n});\n\nconst SubscriptionStateRequest = Schema.Struct({\n _tag: Schema.Literals([\"PauseSubscription\", \"ResumeSubscription\", \"RecoverSubscription\"]),\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n key: SubscriptionKey,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ListSubscriptionsRequest = Schema.TaggedStruct(\"ListSubscriptions\", {\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n after: Schema.optionalKey(Schema.Natural),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n});\n\nconst CancelSubscriptionRequest = Schema.TaggedStruct(\"CancelSubscription\", {\n expectedRevision: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n key: SubscriptionKey,\n});\n\nconst GetSubscriptionRequest = Schema.TaggedStruct(\"GetSubscription\", {\n schemaVersion: Schema.Literal(1),\n scope: SubscriptionScope,\n key: SubscriptionKey,\n});\n\nconst RecoverDeliveryRequest = Schema.TaggedStruct(\"RecoverDelivery\", {\n expectedGeneration: Schema.Natural,\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n key: SubscriptionDeliveryKey,\n});\n\nconst ListDeliveriesRequest = Schema.TaggedStruct(\"ListDeliveries\", {\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n key: SubscriptionKey,\n after: Schema.optionalKey(Schema.String),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n});\n\nconst AcceptRequest = Schema.TaggedStruct(\"Accept\", {\n schemaVersion: Schema.Literal(1),\n partition: SourcePartition,\n principal: Principal,\n source: EventSourceVersion,\n payload: PersistedJson,\n});\n\nconst StatusRequest = Schema.TaggedStruct(\"Status\", {\n schemaVersion: Schema.Literal(1),\n partition: SourcePartition,\n principal: Principal,\n source: EventSourceVersion,\n eventId: Schema.String,\n});\n\nconst SubscriptionPartitionRequest = Schema.Union([\n SubscribeRequest,\n GetSubscriptionRequest,\n UpdateSubscriptionRequest,\n SubscriptionStateRequest,\n ListSubscriptionsRequest,\n CancelSubscriptionRequest,\n ListDeliveriesRequest,\n RecoverDeliveryRequest,\n AcceptRequest,\n StatusRequest,\n]);\n\ntype SubscriptionPartitionRequest = typeof SubscriptionPartitionRequest.Type;\n\nconst SubscriptionPage = Schema.Struct({\n items: Schema.Array(SubscriptionSnapshot),\n next: Schema.NullOr(Schema.Natural),\n});\n\nconst DeliveryPage = Schema.Struct({\n items: Schema.Array(SubscriptionDeliverySnapshot),\n next: Schema.NullOr(Schema.String),\n});\n\nconst IntakeStatus = Schema.Struct({\n ...EventAcknowledgement.fields,\n routingComplete: Schema.Boolean,\n routingFailure: Schema.NullOr(Schema.String),\n nextAttemptAtMillis: Schema.Number,\n});\n\nconst SubscriptionPartitionFailure = Schema.Union([\n SubscriptionError,\n SubscriptionSourceError,\n SubscriptionFailpointError,\n SubscriptionPartitionProtocolError,\n]);\n\ntype SubscriptionPartitionFailure = typeof SubscriptionPartitionFailure.Type;\n\nconst SubscriptionPartitionResponse = Schema.Union([\n Schema.TaggedStruct(\"Snapshot\", { value: SubscriptionSnapshot }),\n Schema.TaggedStruct(\"SubscriptionPage\", { value: SubscriptionPage }),\n Schema.TaggedStruct(\"DeliveryPage\", { value: DeliveryPage }),\n Schema.TaggedStruct(\"DeliverySnapshot\", { value: SubscriptionDeliverySnapshot }),\n Schema.TaggedStruct(\"Acknowledgement\", { value: EventAcknowledgement }),\n Schema.TaggedStruct(\"Status\", { value: IntakeStatus }),\n Schema.TaggedStruct(\"Failed\", { failure: SubscriptionPartitionFailure }),\n]);\n\ntype SubscriptionPartitionResponse = typeof SubscriptionPartitionResponse.Type;\n\nconst decodeRequest = Schema.decodeUnknownEffect(SubscriptionPartitionRequest);\nconst encodeRequest = Schema.encodeEffect(SubscriptionPartitionRequest);\nconst decodeResponse = Schema.decodeUnknownEffect(SubscriptionPartitionResponse);\nconst encodeResponse = Schema.encodeEffect(SubscriptionPartitionResponse);\n\nconst protocolFailure = (message: string): SubscriptionPartitionResponse => ({\n _tag: \"Failed\",\n failure: SubscriptionPartitionProtocolError.make({ message: protocolMessage(message) }),\n});\n\nexport const sourcePartitionName = (partition: SourcePartition): string =>\n JSON.stringify([partition.tenantId, partition.address]);\n\nexport interface SubscriptionPartitionObjectRpc extends Rpc.DurableObjectBranded {\n subscription(encoded: unknown): Promise<unknown>;\n}\n\nexport class SubscriptionPartitionNamespace extends Context.Service<\n SubscriptionPartitionNamespace,\n { readonly namespace: DurableObjectNamespace<SubscriptionPartitionObjectRpc> }\n>()(\"@effect-agent/platform-cloudflare/SubscriptionPartitionNamespace\") {}\n\nconst storageFailure = (code: string): SubscriptionError =>\n SubscriptionError.make({ reason: \"storage\", code });\n\nconst corruptFailure = (code: string): SubscriptionError =>\n SubscriptionError.make({ reason: \"corrupt\", code });\n\n/** Worker-side management and trusted intake, routed to one fresh partition stub per call. */\nexport class CloudflareSubscriptionsClient {\n static layer(\n partition: SourcePartition,\n ): Layer.Layer<Subscriptions | SubscriptionIntake, never, SubscriptionPartitionNamespace> {\n return Layer.effectContext(\n Effect.gen(function* () {\n const { namespace } = yield* SubscriptionPartitionNamespace;\n\n const call = Effect.fnUntraced(function* (\n addressedPartition: SourcePartition,\n request: SubscriptionPartitionRequest,\n ) {\n if (!samePartition(partition, addressedPartition)) {\n return yield* SubscriptionError.make({ reason: \"unauthorized\", code: \"partition\" });\n }\n\n const encoded = yield* encodeRequest(request).pipe(\n Effect.mapError(() => corruptFailure(\"subscription-partition-protocol\")),\n );\n\n const raw = yield* Effect.tryPromise({\n try: () =>\n namespace\n .get(namespace.idFromName(sourcePartitionName(partition)))\n .subscription(encoded),\n catch: () => storageFailure(\"call-subscription-partition\"),\n });\n\n return yield* decodeResponse(raw).pipe(\n Effect.mapError(() => corruptFailure(\"subscription-partition-protocol\")),\n );\n });\n\n const failed = (response: SubscriptionPartitionResponse): SubscriptionPartitionFailure =>\n response._tag === \"Failed\"\n ? response.failure\n : SubscriptionPartitionProtocolError.make({\n message: \"Unexpected subscription response\",\n });\n\n const asProtocolError = (): SubscriptionError =>\n corruptFailure(\"subscription-partition-protocol\");\n\n const changeState = Effect.fnUntraced(function* (\n scope: typeof SubscriptionScope.Type,\n key: typeof SubscriptionKey.Type,\n expectedRevision: number,\n _tag: \"PauseSubscription\" | \"ResumeSubscription\" | \"RecoverSubscription\",\n ) {\n const response = yield* call(scope.partition, {\n _tag,\n schemaVersion: 1,\n scope,\n key,\n expectedRevision,\n });\n\n if (response._tag === \"Snapshot\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionFailpointError\"\n ? failure\n : asProtocolError();\n });\n\n const subscriptions = Subscriptions.of({\n recoverSubscription: (scope, key, revision) =>\n changeState(scope, key, revision, \"RecoverSubscription\"),\n getSubscription: Effect.fnUntraced(function* (scope, key) {\n const response = yield* call(scope.partition, {\n _tag: \"GetSubscription\",\n schemaVersion: 1,\n scope,\n key,\n });\n\n if (response._tag === \"Snapshot\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ? failure : asProtocolError();\n }),\n recoverDelivery: Effect.fnUntraced(function* (scope, key, expectedGeneration) {\n const response = yield* call(scope.partition, {\n _tag: \"RecoverDelivery\",\n expectedGeneration,\n schemaVersion: 1,\n scope,\n key,\n });\n\n if (response._tag === \"DeliverySnapshot\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionFailpointError\"\n ? failure\n : asProtocolError();\n }),\n updateSubscription: Effect.fnUntraced(function* (scope, key, expectedRevision, options) {\n const response = yield* call(scope.partition, {\n _tag: \"UpdateSubscription\",\n schemaVersion: 1,\n scope,\n key,\n expectedRevision,\n options,\n });\n\n if (response._tag === \"Snapshot\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionFailpointError\" ||\n failure._tag === \"SubscriptionSourceError\"\n ? failure\n : asProtocolError();\n }),\n pauseSubscription: (scope, key, revision) =>\n changeState(scope, key, revision, \"PauseSubscription\"),\n resumeSubscription: (scope, key, revision) =>\n changeState(scope, key, revision, \"ResumeSubscription\"),\n subscribe: Effect.fnUntraced(function* (scope, options) {\n const response = yield* call(scope.partition, {\n _tag: \"Subscribe\",\n schemaVersion: 1,\n scope,\n options,\n });\n\n if (response._tag === \"Snapshot\") return response.value;\n const failure = failed(response);\n\n if (\n failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionSourceError\" ||\n failure._tag === \"SubscriptionFailpointError\"\n )\n return yield* failure;\n\n return yield* asProtocolError();\n }),\n listSubscriptions: Effect.fnUntraced(function* (scope, after, limit) {\n const response = yield* call(scope.partition, {\n _tag: \"ListSubscriptions\",\n schemaVersion: 1,\n scope,\n ...(after === undefined ? {} : { after }),\n ...(limit === undefined ? {} : { limit }),\n });\n\n if (response._tag === \"SubscriptionPage\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ? failure : asProtocolError();\n }),\n cancelSubscription: Effect.fnUntraced(function* (scope, key, expectedRevision) {\n const response = yield* call(scope.partition, {\n _tag: \"CancelSubscription\",\n ...(expectedRevision === undefined ? {} : { expectedRevision }),\n schemaVersion: 1,\n scope,\n key,\n });\n\n if (response._tag === \"Snapshot\") return response.value;\n const failure = failed(response);\n\n if (\n failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionFailpointError\"\n )\n return yield* failure;\n\n return yield* asProtocolError();\n }),\n listDeliveries: Effect.fnUntraced(function* (scope, key, after, limit) {\n const response = yield* call(scope.partition, {\n _tag: \"ListDeliveries\",\n schemaVersion: 1,\n scope,\n key,\n ...(after === undefined ? {} : { after }),\n ...(limit === undefined ? {} : { limit }),\n });\n\n if (response._tag === \"DeliveryPage\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ? failure : asProtocolError();\n }),\n });\n\n const intake = SubscriptionIntake.of({\n accept: Effect.fnUntraced(function* (principal, source, payload) {\n const request = yield* Schema.decodeUnknownEffect(AcceptRequest)({\n _tag: \"Accept\",\n schemaVersion: 1,\n partition,\n principal,\n source,\n payload,\n }).pipe(\n Effect.mapError(() =>\n SubscriptionError.make({ reason: \"validation\", code: \"event-payload\" }),\n ),\n );\n\n const response = yield* call(request.partition, request);\n\n if (response._tag === \"Acknowledgement\") return response.value;\n const failure = failed(response);\n\n if (\n failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionSourceError\" ||\n failure._tag === \"SubscriptionFailpointError\"\n )\n return yield* failure;\n\n return yield* asProtocolError();\n }),\n status: Effect.fnUntraced(function* (principal, source, eventId) {\n const response = yield* call(partition, {\n _tag: \"Status\",\n schemaVersion: 1,\n partition,\n principal,\n source,\n eventId,\n });\n\n if (response._tag === \"Status\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ? failure : asProtocolError();\n }),\n });\n\n return Context.make(Subscriptions, subscriptions).pipe(\n Context.add(SubscriptionIntake, intake),\n );\n }),\n );\n }\n}\n\nexport class SubscriptionPartitionIdentity extends Context.Service<\n SubscriptionPartitionIdentity,\n { readonly partition: SourcePartition }\n>()(\"@effect-agent/platform-cloudflare/SubscriptionPartitionIdentity\") {}\n\nconst decodePartitionName = Effect.fnUntraced(function* (name: string | null | undefined) {\n if (name === null || name === undefined) {\n return yield* SubscriptionPartitionProtocolError.make({\n message: \"Subscription Partition objects require an idFromName identity\",\n });\n }\n\n const tuple = yield* Schema.decodeEffect(\n Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])),\n )(name).pipe(\n Effect.mapError(() =>\n SubscriptionPartitionProtocolError.make({\n message: \"Subscription Partition name is malformed\",\n }),\n ),\n );\n\n return yield* Schema.decodeEffect(SourcePartition)({\n tenantId: tuple[0],\n address: tuple[1],\n }).pipe(\n Effect.mapError(() =>\n SubscriptionPartitionProtocolError.make({\n message: \"Subscription Partition identity is invalid\",\n }),\n ),\n );\n});\n\nconst samePartition = Schema.toEquivalence(SourcePartition);\n\nconst requestPartition = (request: SubscriptionPartitionRequest): SourcePartition =>\n request._tag === \"Accept\" || request._tag === \"Status\"\n ? request.partition\n : request.scope.partition;\n\nconst handleRequest = Effect.fnUntraced(function* (encoded: unknown) {\n const decoded = yield* decodeRequest(encoded).pipe(Effect.result);\n\n if (decoded._tag === \"Failure\") {\n return yield* encodeResponse(\n protocolFailure(\"The subscription request could not be decoded\"),\n ).pipe(Effect.orDie);\n }\n const request = decoded.success;\n const { partition } = yield* SubscriptionPartitionIdentity;\n\n if (!samePartition(partition, requestPartition(request))) {\n return yield* encodeResponse(\n protocolFailure(\"The request partition does not match the addressed object\"),\n ).pipe(Effect.orDie);\n }\n const subscriptions = yield* Subscriptions;\n const intake = yield* SubscriptionIntake;\n\n const response = yield* Effect.gen(function* (): Effect.fn.Return<\n SubscriptionPartitionResponse,\n SubscriptionPartitionFailure\n > {\n switch (request._tag) {\n case \"GetSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.getSubscription(request.scope, request.key),\n };\n case \"Subscribe\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.subscribe(request.scope, request.options),\n };\n case \"UpdateSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.updateSubscription(\n request.scope,\n request.key,\n request.expectedRevision,\n request.options,\n ),\n };\n case \"RecoverSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.recoverSubscription(\n request.scope,\n request.key,\n request.expectedRevision,\n ),\n };\n case \"PauseSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.pauseSubscription(\n request.scope,\n request.key,\n request.expectedRevision,\n ),\n };\n case \"ResumeSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.resumeSubscription(\n request.scope,\n request.key,\n request.expectedRevision,\n ),\n };\n case \"ListSubscriptions\":\n return {\n _tag: \"SubscriptionPage\",\n value: yield* subscriptions.listSubscriptions(\n request.scope,\n request.after,\n request.limit,\n ),\n };\n case \"CancelSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.cancelSubscription(\n request.scope,\n request.key,\n request.expectedRevision,\n ),\n };\n case \"RecoverDelivery\":\n return {\n _tag: \"DeliverySnapshot\",\n value: yield* subscriptions.recoverDelivery(\n request.scope,\n request.key,\n request.expectedGeneration,\n ),\n };\n case \"ListDeliveries\":\n return {\n _tag: \"DeliveryPage\",\n value: yield* subscriptions.listDeliveries(\n request.scope,\n request.key,\n request.after,\n request.limit,\n ),\n };\n case \"Accept\":\n return {\n _tag: \"Acknowledgement\",\n value: yield* intake.accept(request.principal, request.source, request.payload),\n };\n case \"Status\":\n return {\n _tag: \"Status\",\n value: yield* intake.status(request.principal, request.source, request.eventId),\n };\n }\n }).pipe(\n Effect.catch((failure) =>\n Schema.is(SubscriptionPartitionFailure)(failure)\n ? Effect.succeed({ _tag: \"Failed\" as const, failure })\n : Effect.succeed(protocolFailure(\"The subscription operation failed outside its contract\")),\n ),\n );\n\n return yield* encodeResponse(response).pipe(Effect.orDie);\n});\n\nconst alarmStorageError = (code: string) => () => storageFailure(code);\n\nconst transactionLayer: Layer.Layer<\n DoSubscriptionTransaction,\n never,\n DurableObjectAlarm.DurableObjectAlarm\n> = Layer.effect(\n DoSubscriptionTransaction,\n Effect.gen(function* () {\n const alarms = yield* DurableObjectAlarm.DurableObjectAlarm;\n\n return DoSubscriptionTransaction.of({\n run: Effect.fnUntraced(function* (body) {\n const nowMillis = yield* Clock.currentTimeMillis;\n\n return yield* alarms\n .transaction((transaction) =>\n body((replacement) =>\n replacement.deadlineAtMillis === null\n ? transaction\n .cancelAlarm({ id: SUBSCRIPTION_ALARM_ID, tag: SUBSCRIPTION_ALARM_TAG })\n .pipe(Effect.mapError(alarmStorageError(\"cancel-subscription-alarm\")))\n : Effect.fromOption(\n DateTime.make(Math.max(replacement.deadlineAtMillis, nowMillis + 1)),\n ).pipe(\n Effect.mapError(() => corruptFailure(\"subscription-alarm-deadline\")),\n Effect.flatMap((runAt) =>\n transaction\n .scheduleAlarm({\n id: SUBSCRIPTION_ALARM_ID,\n tag: SUBSCRIPTION_ALARM_TAG,\n runAt,\n payload: { schemaVersion: 1, generation: replacement.generation },\n })\n .pipe(Effect.mapError(alarmStorageError(\"schedule-subscription-alarm\"))),\n ),\n ),\n ),\n )\n .pipe(\n Effect.catchTag(\"StorageOperationError\", () =>\n storageFailure(\"commit-subscription-transaction\"),\n ),\n );\n }),\n });\n }),\n);\n\nconst alarmHandler = (limits: SubscriptionLimits) =>\n DurableObjectAlarm.processDue(\n (event) =>\n Effect.gen(function* () {\n if (event.tag !== SUBSCRIPTION_ALARM_TAG) {\n const { handlers } = yield* SubscriptionPartitionAlarmExtension;\n const matches = handlers.filter((handler) => handler.tag === event.tag);\n const handler = matches[0];\n\n if (\n event.tag.startsWith(\"effect-agent/\") ||\n matches.length !== 1 ||\n handler === undefined\n )\n return yield* SubscriptionAlarmProtocolError.make({\n message: \"Unknown or ambiguous ancillary alarm tag\",\n });\n\n return yield* handler.handle(event).pipe(\n Effect.scoped,\n Effect.timeoutOrElse({\n duration: MAX_ANCILLARY_ALARM_MILLIS,\n orElse: () => SubscriptionAlarmExtensionError.make({ code: \"timeout\" }),\n }),\n );\n }\n if (event.id !== SUBSCRIPTION_ALARM_ID) {\n return yield* SubscriptionAlarmProtocolError.make({\n message: `Unsupported Subscription Partition alarm ${event.tag}/${event.id}`,\n });\n }\n yield* Schema.decodeUnknownEffect(SubscriptionAlarmPayload)(event.payload).pipe(\n Effect.mapError(() =>\n SubscriptionAlarmProtocolError.make({\n message: \"Unsupported subscription alarm payload\",\n }),\n ),\n );\n const driver = yield* SubscriptionDriver;\n const alarmControl = yield* DoSubscriptionAlarmControl;\n\n yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.retryMillis);\n\n const pass = yield* driver.runDue.pipe(\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterrupts(cause),\n (cause) =>\n Clock.currentTimeMillis.pipe(\n Effect.flatMap((time) => alarmControl.prearm(time + limits.retryMillis)),\n Effect.andThen(Effect.failCause(cause)),\n ),\n ),\n );\n\n if (pass.failed > 0) {\n yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.retryMillis);\n } else {\n yield* alarmControl.reconcile;\n }\n }),\n {\n limit: MAX_ALARMS_PER_INVOCATION,\n retryFailedAfter: limits.retryMillis,\n onFailure: () => Effect.logWarning(\"Subscription partition alarm retained for retry\"),\n },\n ).pipe(Effect.asVoid);\n\ntype SubscriptionRuntimeServices =\n | Subscriptions\n | SubscriptionIntake\n | SubscriptionDriver\n | DoSubscriptionAlarmControl\n | SubscriptionPartitionIdentity\n | DurableObjectAlarm.DurableObjectAlarm;\n\nexport interface SubscriptionPartitionObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, SubscriptionRuntimeServices>\n> {\n subscription(encoded: unknown): Promise<unknown>;\n alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;\n}\n\nexport interface SubscriptionPartitionObjectClass {\n new (ctx: DurableObjectState, env: Cloudflare.Env): SubscriptionPartitionObjectInstance;\n}\n\n/**\n * Build one source-addressed SQLite Durable Object. The host Layer binds the permitted source\n * catalog and authority. It must not retain cleanup-scoped resources across RPC events.\n */\nexport const makeSubscriptionPartitionObjectClass = <E>(\n host: Layer.Layer<\n SubscriptionAuthorizer | EventSources | SubscriptionInputBindings | ThreadObjectNamespace,\n E,\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n | SubscriptionPartitionIdentity\n >,\n limits: SubscriptionLimits = defaultSubscriptionLimits,\n): SubscriptionPartitionObjectClass => {\n const cloudflareLimitsLayer = Layer.effectDiscard(validateCloudflareSubscriptionLimits(limits));\n\n const identityLayer = Layer.effect(\n SubscriptionPartitionIdentity,\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n\n return SubscriptionPartitionIdentity.of({\n partition: yield* decodePartitionName(state.raw.id.name),\n });\n }),\n );\n\n const sqlLayer = Layer.unwrap(\n Effect.map(EffectCfDurableObjectState.DurableObjectState, (state) =>\n SqliteClient.layer({ storage: state.raw.storage }),\n ),\n );\n\n const partitionStore = Layer.unwrap(\n Effect.map(SubscriptionPartitionIdentity, ({ partition }) =>\n doSubscriptionStoreLayer(partition).pipe(\n Layer.provide(transactionLayer),\n Layer.provide(sqlLayer),\n ),\n ),\n );\n\n const application = Layer.mergeAll(\n Subscriptions.layer(limits),\n SubscriptionIntake.layer(limits),\n SubscriptionDriver.layer(limits),\n cloudflareLimitsLayer,\n // Capture the host reference before its scoped input Layer is hidden from the runtime.\n Layer.effect(\n SubscriptionPartitionAlarmExtension,\n Effect.gen(function* () {\n const extension = yield* SubscriptionPartitionAlarmExtension;\n const tags = extension.handlers.map((handler) => handler.tag);\n\n if (\n tags.length > MAX_ALARMS_PER_INVOCATION ||\n new Set(tags).size !== tags.length ||\n tags.some(\n (tag) => tag.length === 0 || tag.length > 128 || tag.startsWith(\"effect-agent/\"),\n )\n )\n return yield* SubscriptionAlarmProtocolError.make({\n message: \"Invalid ancillary alarm handler registry\",\n });\n\n yield* validateCloudflareSubscriptionLimits(limits, { ancillaryAlarms: tags.length > 0 });\n\n return extension;\n }),\n ),\n ).pipe(\n Layer.provideMerge(partitionStore),\n Layer.provide(\n cloudflarePreparedInputAdmissionLayer.pipe(Layer.provide(CloudflareThreadClient.layer)),\n ),\n Layer.provide(cloudflareCryptoLayer),\n Layer.provideMerge(DurableObjectAlarm.DurableObjectAlarm.layer),\n Layer.provide(host),\n Layer.provideMerge(identityLayer),\n );\n\n const runtime: Layer.Layer<\n SubscriptionRuntimeServices,\n | E\n | SubscriptionError\n | SubscriptionPartitionProtocolError\n | CloudflareSubscriptionConfigError\n | SubscriptionAlarmProtocolError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = {\n subscription: (encoded: unknown) => handleRequest(encoded),\n } satisfies EffectCfDurableObject.DurableObjectRpc<SubscriptionRuntimeServices>;\n\n const SubscriptionPartitionObject = EffectCfDurableObject.make(runtime, {\n initialize: Effect.void,\n rpc,\n alarms: alarmHandler(limits),\n });\n\n return SubscriptionPartitionObject;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,yBAAyB;AAC/B,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,4BAA4B;AAClC,MAAM,6BAA6B;AAEnC,MAAM,2BAA2B,OAAO,OAAO;CAC7C,eAAe,OAAO,QAAQ,CAAC;CAC/B,YAAY,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AACtD,CAAC;AAED,IAAa,iCAAb,cAAoD,OAAO,YAA4C,CAAC,CACtG,kCACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;;AAGH,IAAa,kCAAb,cAAqD,OAAO,YAA6C,CAAC,CACxG,mCACA,EAAE,MAAM,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC,EAAE,CAC/D,CAAC,CAAC,CAAC;;AAgBH,MAAa,sCAAsC,QAAQ,UAExD,yEAAyE,EAC1E,qBAAqB,EAAE,UAAU,CAAC,EAAE,GACtC,CAAC;;;;;;AAOD,MAAa,wCAAwC,OAAO,WAAW,WAGrE,SAqBA;CACA,IACE,QAAQ,IAAI,WAAW,KACvB,QAAQ,IAAI,SAAS,OACrB,QAAQ,IAAI,WAAW,eAAe,KACtC,CAAC,OAAO,cAAc,QAAQ,aAAa,KAC3C,QAAQ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AO,OAAO;EAE5B,OAAO,OAAO,MAAM,sBAAsB,MAAM,eAAe,aAAa,KAAK,CAAC;CACpF,CAAC,CACH;CAYA,OANoCC,cAAsB,KAAK,SAAS;EACtE,YAAY,OAAO;EACnB,KAAA,EALA,eAAe,YAAqB,cAAc,OAAO,EAKvD;EACF,QAAQ,aAAa,MAAM;CAC7B,CAEiC;AACnC"}
1
+ {"version":3,"file":"CloudflareSubscriptions.mjs","names":["EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/CloudflareSubscriptions.ts"],"sourcesContent":["import * as SqliteClient from \"@effect/sql-sqlite-do/SqliteClient\";\nimport {\n DoSubscriptionAlarmControl,\n DoSubscriptionTransaction,\n doSubscriptionStoreLayer,\n} from \"@yielded/agent-storage-cloudflare/do-subscription-store\";\nimport { type EventSources } from \"@yielded/agent/event-source\";\nimport { PersistedJson } from \"@yielded/agent/records\";\nimport { Principal } from \"@yielded/agent/submission-ledger\";\nimport {\n EventAcknowledgement,\n EventSourceVersion,\n SourcePartition,\n type SubscriptionAuthorizer,\n SubscriptionConfiguration,\n SubscriptionDeliverySnapshot,\n SubscriptionDeliveryKey,\n SubscriptionError,\n SubscriptionFailpointError,\n SubscriptionKey,\n SubscriptionScope,\n type SubscriptionLimits,\n SubscriptionSnapshot,\n SubscriptionSourceError,\n defaultSubscriptionLimits,\n} from \"@yielded/agent/subscription\";\nimport { type SubscriptionInputBindings } from \"@yielded/agent/subscription-input\";\nimport {\n SubscriptionDriver,\n SubscriptionIntake,\n Subscriptions,\n} from \"@yielded/agent/subscriptions\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectAlarm,\n DurableObjectState as EffectCfDurableObjectState,\n type WorkerEnvironment,\n} from \"effect-cf\";\nimport * as Cause from \"effect/Cause\";\nimport * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport type * as Scope from \"effect/Scope\";\n\nimport { type ThreadObjectNamespace } from \"./CloudflareBindings.ts\";\nimport { CloudflareThreadClient } from \"./CloudflareThreadClient.ts\";\nimport { cloudflareCryptoLayer } from \"./internal/crypto.ts\";\nimport { cloudflarePreparedInputAdmissionLayer } from \"./internal/prepared-admission.ts\";\n\nconst SUBSCRIPTION_ALARM_TAG = \"effect-agent/SubscriptionPartitionWake\";\nconst SUBSCRIPTION_ALARM_ID = \"driver\";\nconst MAX_ALARM_WALL_MILLIS = 12 * 60_000;\nconst MAX_ALARMS_PER_INVOCATION = 16;\nconst MAX_ANCILLARY_ALARM_MILLIS = 30_000;\n\nconst SubscriptionAlarmPayload = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n generation: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nexport class SubscriptionAlarmProtocolError extends Schema.TaggedError<SubscriptionAlarmProtocolError>()(\n \"SubscriptionAlarmProtocolError\",\n { message: Schema.String },\n) {}\n\n/** Bounded host diagnostic; credentials and provider responses do not belong in alarm failures. */\nexport class SubscriptionAlarmExtensionError extends Schema.TaggedError<SubscriptionAlarmExtensionError>()(\n \"SubscriptionAlarmExtensionError\",\n { code: Schema.NonEmptyString.check(Schema.isMaxLength(128)) },\n) {}\n\n/** Native partition services supplied at alarm invocation, after the host Layer is built. */\nexport type SubscriptionPartitionAlarmServices =\n | Subscriptions\n | SubscriptionIntake\n | SubscriptionDriver;\n\nexport interface SubscriptionPartitionAlarmHandler<R = SubscriptionPartitionAlarmServices> {\n readonly tag: string;\n readonly handle: (\n event: DurableObjectAlarm.DurableObjectAlarmEvent,\n ) => Effect.Effect<void, SubscriptionAlarmProtocolError | SubscriptionAlarmExtensionError, R>;\n}\n\n/** Host-only handlers; the framework reserves its namespace and rejects every unknown tag. */\nexport const SubscriptionPartitionAlarmExtension = Context.Reference<{\n readonly handlers: ReadonlyArray<SubscriptionPartitionAlarmHandler>;\n}>(\"@effect-agent/platform-cloudflare/SubscriptionPartitionAlarmExtension\", {\n defaultValue: () => ({ handlers: [] }),\n});\n\n/** Capture host services once, deferring native partition services to invocation.\n * Each invocation owns its codec/handler Scope and timeout.\n * Callback failures stay typed. Defects and interruption reach the native alarm multiplexer.\n * The host owns durable idempotency, prearming and external-effect uncertainty.\n */\nexport const makeSubscriptionPartitionAlarmHandler = Effect.fnUntraced(function* <\n Payload extends Schema.Top,\n R,\n>(options: {\n readonly tag: string;\n readonly payload: Payload;\n readonly timeoutMillis: number;\n readonly handle: (\n event: Omit<DurableObjectAlarm.DurableObjectAlarmEvent, \"payload\"> & {\n readonly payload: Payload[\"Type\"];\n },\n ) => Effect.Effect<void, SubscriptionAlarmExtensionError, R>;\n}): Effect.fn.Return<\n SubscriptionPartitionAlarmHandler<\n Exclude<\n Exclude<R | Payload[\"DecodingServices\"], Scope.Scope>,\n Exclude<\n Exclude<R | Payload[\"DecodingServices\"], Scope.Scope | SubscriptionPartitionAlarmServices>,\n SubscriptionPartitionAlarmServices\n >\n >\n >,\n SubscriptionAlarmProtocolError,\n Exclude<R | Payload[\"DecodingServices\"], Scope.Scope | SubscriptionPartitionAlarmServices>\n> {\n if (\n options.tag.length === 0 ||\n options.tag.length > 128 ||\n options.tag.startsWith(\"effect-agent/\") ||\n !Number.isSafeInteger(options.timeoutMillis) ||\n options.timeoutMillis < 1 ||\n options.timeoutMillis > MAX_ANCILLARY_ALARM_MILLIS\n )\n return yield* SubscriptionAlarmProtocolError.make({\n message: \"Invalid ancillary alarm tag or timeout\",\n });\n\n // Context capture includes unrequested services too; never retain a host override of native work.\n const services = (yield* Effect.context<\n Exclude<R | Payload[\"DecodingServices\"], Scope.Scope | SubscriptionPartitionAlarmServices>\n >()).pipe(Context.omit(Subscriptions, SubscriptionIntake, SubscriptionDriver));\n\n return {\n tag: options.tag,\n handle: Effect.fnUntraced(\n function* (event) {\n if (event.tag !== options.tag)\n return yield* SubscriptionAlarmProtocolError.make({\n message: \"Ancillary alarm tag mismatch\",\n });\n\n const payload = yield* Schema.decodeEffect(options.payload)(event.payload).pipe(\n Effect.mapError(() =>\n SubscriptionAlarmProtocolError.make({ message: \"Invalid ancillary alarm payload\" }),\n ),\n );\n\n yield* options.handle({ ...event, payload });\n },\n (effect) =>\n effect.pipe(\n Effect.scoped,\n Effect.timeoutOrElse({\n duration: options.timeoutMillis,\n orElse: () => SubscriptionAlarmExtensionError.make({ code: \"timeout\" }),\n }),\n Effect.provideContext(services),\n ),\n ),\n };\n});\n\nexport class SubscriptionPartitionProtocolError extends Schema.TaggedError<SubscriptionPartitionProtocolError>()(\n \"SubscriptionPartitionProtocolError\",\n { message: Schema.String.check(Schema.isMaxLength(4_096)) },\n) {}\n\nexport class CloudflareSubscriptionConfigError extends Schema.TaggedError<CloudflareSubscriptionConfigError>()(\n \"CloudflareSubscriptionConfigError\",\n { message: Schema.String },\n) {}\n\n/** Reject limits whose four bounded phases could exceed the safe Durable Object alarm budget. */\nexport const validateCloudflareSubscriptionLimits = (\n limits: SubscriptionLimits,\n options: { readonly ancillaryAlarms?: boolean } = {},\n): Effect.Effect<void, CloudflareSubscriptionConfigError> => {\n const worstCaseMillis =\n 4 * Math.ceil(limits.batchSize / limits.concurrency) * limits.operationTimeoutMillis +\n (options.ancillaryAlarms === true ? MAX_ALARMS_PER_INVOCATION * MAX_ANCILLARY_ALARM_MILLIS : 0);\n\n return worstCaseMillis <= MAX_ALARM_WALL_MILLIS\n ? Effect.void\n : Effect.fail(\n CloudflareSubscriptionConfigError.make({\n message: \"Subscription limits can exceed the bounded Durable Object alarm wall budget\",\n }),\n );\n};\n\nconst protocolMessage = (message: string): string =>\n message.length <= 4_096 ? message : `${message.slice(0, 4_093)}...`;\n\nconst SubscribeRequest = Schema.TaggedStruct(\"Subscribe\", {\n schemaVersion: Schema.Literal(1),\n scope: Schema.Struct({\n ...SubscriptionScope.fields,\n }),\n options: Schema.Struct({\n subscriptionId: SubscriptionKey.fields.subscriptionId,\n source: EventSourceVersion,\n parameters: PersistedJson,\n context: PersistedJson,\n mode: Schema.Literals([\"once\", \"continuous\"]),\n expiresAtMillis: Schema.NullOr(Schema.Number),\n destination: SubscriptionConfiguration.fields.destination,\n deliveryPrincipal: SubscriptionConfiguration.fields.deliveryPrincipal,\n admissionGroup: SubscriptionConfiguration.fields.admissionGroup,\n admissionFence: SubscriptionConfiguration.fields.admissionFence,\n agentId: SubscriptionConfiguration.fields.agentId,\n definitions: SubscriptionConfiguration.fields.definitions,\n }),\n});\n\nconst UpdateSubscriptionRequest = Schema.TaggedStruct(\"UpdateSubscription\", {\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n key: SubscriptionKey,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n options: SubscribeRequest.fields.options.mapFields(({ subscriptionId: _, ...fields }) => fields),\n});\n\nconst SubscriptionStateRequest = Schema.Struct({\n _tag: Schema.Literals([\"PauseSubscription\", \"ResumeSubscription\", \"RecoverSubscription\"]),\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n key: SubscriptionKey,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ListSubscriptionsRequest = Schema.TaggedStruct(\"ListSubscriptions\", {\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n after: Schema.optionalKey(Schema.Natural),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n});\n\nconst CancelSubscriptionRequest = Schema.TaggedStruct(\"CancelSubscription\", {\n expectedRevision: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n key: SubscriptionKey,\n});\n\nconst GetSubscriptionRequest = Schema.TaggedStruct(\"GetSubscription\", {\n schemaVersion: Schema.Literal(1),\n scope: SubscriptionScope,\n key: SubscriptionKey,\n});\n\nconst RecoverDeliveryRequest = Schema.TaggedStruct(\"RecoverDelivery\", {\n expectedGeneration: Schema.Natural,\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n key: SubscriptionDeliveryKey,\n});\n\nconst ListDeliveriesRequest = Schema.TaggedStruct(\"ListDeliveries\", {\n schemaVersion: Schema.Literal(1),\n scope: SubscribeRequest.fields.scope,\n key: SubscriptionKey,\n after: Schema.optionalKey(Schema.String),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),\n});\n\nconst AcceptRequest = Schema.TaggedStruct(\"Accept\", {\n schemaVersion: Schema.Literal(1),\n partition: SourcePartition,\n principal: Principal,\n source: EventSourceVersion,\n payload: PersistedJson,\n});\n\nconst StatusRequest = Schema.TaggedStruct(\"Status\", {\n schemaVersion: Schema.Literal(1),\n partition: SourcePartition,\n principal: Principal,\n source: EventSourceVersion,\n eventId: Schema.String,\n});\n\nconst SubscriptionPartitionRequest = Schema.Union([\n SubscribeRequest,\n GetSubscriptionRequest,\n UpdateSubscriptionRequest,\n SubscriptionStateRequest,\n ListSubscriptionsRequest,\n CancelSubscriptionRequest,\n ListDeliveriesRequest,\n RecoverDeliveryRequest,\n AcceptRequest,\n StatusRequest,\n]);\n\ntype SubscriptionPartitionRequest = typeof SubscriptionPartitionRequest.Type;\n\nconst SubscriptionPage = Schema.Struct({\n items: Schema.Array(SubscriptionSnapshot),\n next: Schema.NullOr(Schema.Natural),\n});\n\nconst DeliveryPage = Schema.Struct({\n items: Schema.Array(SubscriptionDeliverySnapshot),\n next: Schema.NullOr(Schema.String),\n});\n\nconst IntakeStatus = Schema.Struct({\n ...EventAcknowledgement.fields,\n routingComplete: Schema.Boolean,\n routingFailure: Schema.NullOr(Schema.String),\n nextAttemptAtMillis: Schema.Number,\n});\n\nconst SubscriptionPartitionFailure = Schema.Union([\n SubscriptionError,\n SubscriptionSourceError,\n SubscriptionFailpointError,\n SubscriptionPartitionProtocolError,\n]);\n\ntype SubscriptionPartitionFailure = typeof SubscriptionPartitionFailure.Type;\n\nconst SubscriptionPartitionResponse = Schema.Union([\n Schema.TaggedStruct(\"Snapshot\", { value: SubscriptionSnapshot }),\n Schema.TaggedStruct(\"SubscriptionPage\", { value: SubscriptionPage }),\n Schema.TaggedStruct(\"DeliveryPage\", { value: DeliveryPage }),\n Schema.TaggedStruct(\"DeliverySnapshot\", { value: SubscriptionDeliverySnapshot }),\n Schema.TaggedStruct(\"Acknowledgement\", { value: EventAcknowledgement }),\n Schema.TaggedStruct(\"Status\", { value: IntakeStatus }),\n Schema.TaggedStruct(\"Failed\", { failure: SubscriptionPartitionFailure }),\n]);\n\ntype SubscriptionPartitionResponse = typeof SubscriptionPartitionResponse.Type;\n\nconst decodeRequest = Schema.decodeUnknownEffect(SubscriptionPartitionRequest);\nconst encodeRequest = Schema.encodeEffect(SubscriptionPartitionRequest);\nconst decodeResponse = Schema.decodeUnknownEffect(SubscriptionPartitionResponse);\nconst encodeResponse = Schema.encodeEffect(SubscriptionPartitionResponse);\n\nconst protocolFailure = (message: string): SubscriptionPartitionResponse => ({\n _tag: \"Failed\",\n failure: SubscriptionPartitionProtocolError.make({ message: protocolMessage(message) }),\n});\n\nexport const sourcePartitionName = (partition: SourcePartition): string =>\n JSON.stringify([partition.tenantId, partition.address]);\n\nexport interface SubscriptionPartitionObjectRpc extends Rpc.DurableObjectBranded {\n subscription(encoded: unknown): Promise<unknown>;\n}\n\nexport class SubscriptionPartitionNamespace extends Context.Service<\n SubscriptionPartitionNamespace,\n { readonly namespace: DurableObjectNamespace<SubscriptionPartitionObjectRpc> }\n>()(\"@effect-agent/platform-cloudflare/SubscriptionPartitionNamespace\") {}\n\nconst storageFailure = (code: string): SubscriptionError =>\n SubscriptionError.make({ reason: \"storage\", code });\n\nconst corruptFailure = (code: string): SubscriptionError =>\n SubscriptionError.make({ reason: \"corrupt\", code });\n\n/** Worker-side management and trusted intake, routed to one fresh partition stub per call. */\nexport class CloudflareSubscriptionsClient {\n static layer(\n partition: SourcePartition,\n ): Layer.Layer<Subscriptions | SubscriptionIntake, never, SubscriptionPartitionNamespace> {\n return Layer.effectContext(\n Effect.gen(function* () {\n const { namespace } = yield* SubscriptionPartitionNamespace;\n\n const call = Effect.fnUntraced(function* (\n addressedPartition: SourcePartition,\n request: SubscriptionPartitionRequest,\n ) {\n if (!samePartition(partition, addressedPartition)) {\n return yield* SubscriptionError.make({ reason: \"unauthorized\", code: \"partition\" });\n }\n\n const encoded = yield* encodeRequest(request).pipe(\n Effect.mapError(() => corruptFailure(\"subscription-partition-protocol\")),\n );\n\n const raw = yield* Effect.tryPromise({\n try: () =>\n namespace\n .get(namespace.idFromName(sourcePartitionName(partition)))\n .subscription(encoded),\n catch: () => storageFailure(\"call-subscription-partition\"),\n });\n\n return yield* decodeResponse(raw).pipe(\n Effect.mapError(() => corruptFailure(\"subscription-partition-protocol\")),\n );\n });\n\n const failed = (response: SubscriptionPartitionResponse): SubscriptionPartitionFailure =>\n response._tag === \"Failed\"\n ? response.failure\n : SubscriptionPartitionProtocolError.make({\n message: \"Unexpected subscription response\",\n });\n\n const asProtocolError = (): SubscriptionError =>\n corruptFailure(\"subscription-partition-protocol\");\n\n const changeState = Effect.fnUntraced(function* (\n scope: typeof SubscriptionScope.Type,\n key: typeof SubscriptionKey.Type,\n expectedRevision: number,\n _tag: \"PauseSubscription\" | \"ResumeSubscription\" | \"RecoverSubscription\",\n ) {\n const response = yield* call(scope.partition, {\n _tag,\n schemaVersion: 1,\n scope,\n key,\n expectedRevision,\n });\n\n if (response._tag === \"Snapshot\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionFailpointError\"\n ? failure\n : asProtocolError();\n });\n\n const subscriptions = Subscriptions.of({\n recoverSubscription: (scope, key, revision) =>\n changeState(scope, key, revision, \"RecoverSubscription\"),\n getSubscription: Effect.fnUntraced(function* (scope, key) {\n const response = yield* call(scope.partition, {\n _tag: \"GetSubscription\",\n schemaVersion: 1,\n scope,\n key,\n });\n\n if (response._tag === \"Snapshot\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ? failure : asProtocolError();\n }),\n recoverDelivery: Effect.fnUntraced(function* (scope, key, expectedGeneration) {\n const response = yield* call(scope.partition, {\n _tag: \"RecoverDelivery\",\n expectedGeneration,\n schemaVersion: 1,\n scope,\n key,\n });\n\n if (response._tag === \"DeliverySnapshot\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionFailpointError\"\n ? failure\n : asProtocolError();\n }),\n updateSubscription: Effect.fnUntraced(function* (scope, key, expectedRevision, options) {\n const response = yield* call(scope.partition, {\n _tag: \"UpdateSubscription\",\n schemaVersion: 1,\n scope,\n key,\n expectedRevision,\n options,\n });\n\n if (response._tag === \"Snapshot\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionFailpointError\" ||\n failure._tag === \"SubscriptionSourceError\"\n ? failure\n : asProtocolError();\n }),\n pauseSubscription: (scope, key, revision) =>\n changeState(scope, key, revision, \"PauseSubscription\"),\n resumeSubscription: (scope, key, revision) =>\n changeState(scope, key, revision, \"ResumeSubscription\"),\n subscribe: Effect.fnUntraced(function* (scope, options) {\n const response = yield* call(scope.partition, {\n _tag: \"Subscribe\",\n schemaVersion: 1,\n scope,\n options,\n });\n\n if (response._tag === \"Snapshot\") return response.value;\n const failure = failed(response);\n\n if (\n failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionSourceError\" ||\n failure._tag === \"SubscriptionFailpointError\"\n )\n return yield* failure;\n\n return yield* asProtocolError();\n }),\n listSubscriptions: Effect.fnUntraced(function* (scope, after, limit) {\n const response = yield* call(scope.partition, {\n _tag: \"ListSubscriptions\",\n schemaVersion: 1,\n scope,\n ...(after === undefined ? {} : { after }),\n ...(limit === undefined ? {} : { limit }),\n });\n\n if (response._tag === \"SubscriptionPage\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ? failure : asProtocolError();\n }),\n cancelSubscription: Effect.fnUntraced(function* (scope, key, expectedRevision) {\n const response = yield* call(scope.partition, {\n _tag: \"CancelSubscription\",\n ...(expectedRevision === undefined ? {} : { expectedRevision }),\n schemaVersion: 1,\n scope,\n key,\n });\n\n if (response._tag === \"Snapshot\") return response.value;\n const failure = failed(response);\n\n if (\n failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionFailpointError\"\n )\n return yield* failure;\n\n return yield* asProtocolError();\n }),\n listDeliveries: Effect.fnUntraced(function* (scope, key, after, limit) {\n const response = yield* call(scope.partition, {\n _tag: \"ListDeliveries\",\n schemaVersion: 1,\n scope,\n key,\n ...(after === undefined ? {} : { after }),\n ...(limit === undefined ? {} : { limit }),\n });\n\n if (response._tag === \"DeliveryPage\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ? failure : asProtocolError();\n }),\n });\n\n const intake = SubscriptionIntake.of({\n accept: Effect.fnUntraced(function* (principal, source, payload) {\n const request = yield* Schema.decodeUnknownEffect(AcceptRequest)({\n _tag: \"Accept\",\n schemaVersion: 1,\n partition,\n principal,\n source,\n payload,\n }).pipe(\n Effect.mapError(() =>\n SubscriptionError.make({ reason: \"validation\", code: \"event-payload\" }),\n ),\n );\n\n const response = yield* call(request.partition, request);\n\n if (response._tag === \"Acknowledgement\") return response.value;\n const failure = failed(response);\n\n if (\n failure._tag === \"SubscriptionError\" ||\n failure._tag === \"SubscriptionSourceError\" ||\n failure._tag === \"SubscriptionFailpointError\"\n )\n return yield* failure;\n\n return yield* asProtocolError();\n }),\n status: Effect.fnUntraced(function* (principal, source, eventId) {\n const response = yield* call(partition, {\n _tag: \"Status\",\n schemaVersion: 1,\n partition,\n principal,\n source,\n eventId,\n });\n\n if (response._tag === \"Status\") return response.value;\n const failure = failed(response);\n\n return yield* failure._tag === \"SubscriptionError\" ? failure : asProtocolError();\n }),\n });\n\n return Context.make(Subscriptions, subscriptions).pipe(\n Context.add(SubscriptionIntake, intake),\n );\n }),\n );\n }\n}\n\nexport class SubscriptionPartitionIdentity extends Context.Service<\n SubscriptionPartitionIdentity,\n { readonly partition: SourcePartition }\n>()(\"@effect-agent/platform-cloudflare/SubscriptionPartitionIdentity\") {}\n\nconst decodePartitionName = Effect.fnUntraced(function* (name: string | null | undefined) {\n if (name === null || name === undefined) {\n return yield* SubscriptionPartitionProtocolError.make({\n message: \"Subscription Partition objects require an idFromName identity\",\n });\n }\n\n const tuple = yield* Schema.decodeEffect(\n Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])),\n )(name).pipe(\n Effect.mapError(() =>\n SubscriptionPartitionProtocolError.make({\n message: \"Subscription Partition name is malformed\",\n }),\n ),\n );\n\n return yield* Schema.decodeEffect(SourcePartition)({\n tenantId: tuple[0],\n address: tuple[1],\n }).pipe(\n Effect.mapError(() =>\n SubscriptionPartitionProtocolError.make({\n message: \"Subscription Partition identity is invalid\",\n }),\n ),\n );\n});\n\nconst samePartition = Schema.toEquivalence(SourcePartition);\n\nconst requestPartition = (request: SubscriptionPartitionRequest): SourcePartition =>\n request._tag === \"Accept\" || request._tag === \"Status\"\n ? request.partition\n : request.scope.partition;\n\nconst handleRequest = Effect.fnUntraced(function* (encoded: unknown) {\n const decoded = yield* decodeRequest(encoded).pipe(Effect.result);\n\n if (decoded._tag === \"Failure\") {\n return yield* encodeResponse(\n protocolFailure(\"The subscription request could not be decoded\"),\n ).pipe(Effect.orDie);\n }\n const request = decoded.success;\n const { partition } = yield* SubscriptionPartitionIdentity;\n\n if (!samePartition(partition, requestPartition(request))) {\n return yield* encodeResponse(\n protocolFailure(\"The request partition does not match the addressed object\"),\n ).pipe(Effect.orDie);\n }\n const subscriptions = yield* Subscriptions;\n const intake = yield* SubscriptionIntake;\n\n const response = yield* Effect.gen(function* (): Effect.fn.Return<\n SubscriptionPartitionResponse,\n SubscriptionPartitionFailure\n > {\n switch (request._tag) {\n case \"GetSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.getSubscription(request.scope, request.key),\n };\n case \"Subscribe\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.subscribe(request.scope, request.options),\n };\n case \"UpdateSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.updateSubscription(\n request.scope,\n request.key,\n request.expectedRevision,\n request.options,\n ),\n };\n case \"RecoverSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.recoverSubscription(\n request.scope,\n request.key,\n request.expectedRevision,\n ),\n };\n case \"PauseSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.pauseSubscription(\n request.scope,\n request.key,\n request.expectedRevision,\n ),\n };\n case \"ResumeSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.resumeSubscription(\n request.scope,\n request.key,\n request.expectedRevision,\n ),\n };\n case \"ListSubscriptions\":\n return {\n _tag: \"SubscriptionPage\",\n value: yield* subscriptions.listSubscriptions(\n request.scope,\n request.after,\n request.limit,\n ),\n };\n case \"CancelSubscription\":\n return {\n _tag: \"Snapshot\",\n value: yield* subscriptions.cancelSubscription(\n request.scope,\n request.key,\n request.expectedRevision,\n ),\n };\n case \"RecoverDelivery\":\n return {\n _tag: \"DeliverySnapshot\",\n value: yield* subscriptions.recoverDelivery(\n request.scope,\n request.key,\n request.expectedGeneration,\n ),\n };\n case \"ListDeliveries\":\n return {\n _tag: \"DeliveryPage\",\n value: yield* subscriptions.listDeliveries(\n request.scope,\n request.key,\n request.after,\n request.limit,\n ),\n };\n case \"Accept\":\n return {\n _tag: \"Acknowledgement\",\n value: yield* intake.accept(request.principal, request.source, request.payload),\n };\n case \"Status\":\n return {\n _tag: \"Status\",\n value: yield* intake.status(request.principal, request.source, request.eventId),\n };\n }\n }).pipe(\n Effect.catch((failure) =>\n Schema.is(SubscriptionPartitionFailure)(failure)\n ? Effect.succeed({ _tag: \"Failed\" as const, failure })\n : Effect.succeed(protocolFailure(\"The subscription operation failed outside its contract\")),\n ),\n );\n\n return yield* encodeResponse(response).pipe(Effect.orDie);\n});\n\nconst alarmStorageError = (code: string) => () => storageFailure(code);\n\nconst transactionLayer: Layer.Layer<\n DoSubscriptionTransaction,\n never,\n DurableObjectAlarm.DurableObjectAlarm\n> = Layer.effect(\n DoSubscriptionTransaction,\n Effect.gen(function* () {\n const alarms = yield* DurableObjectAlarm.DurableObjectAlarm;\n\n return DoSubscriptionTransaction.of({\n run: Effect.fnUntraced(function* (body) {\n const nowMillis = yield* Clock.currentTimeMillis;\n\n return yield* alarms\n .transaction((transaction) =>\n body((replacement) =>\n replacement.deadlineAtMillis === null\n ? transaction\n .cancelAlarm({ id: SUBSCRIPTION_ALARM_ID, tag: SUBSCRIPTION_ALARM_TAG })\n .pipe(Effect.mapError(alarmStorageError(\"cancel-subscription-alarm\")))\n : Effect.fromOption(\n DateTime.make(Math.max(replacement.deadlineAtMillis, nowMillis + 1)),\n ).pipe(\n Effect.mapError(() => corruptFailure(\"subscription-alarm-deadline\")),\n Effect.flatMap((runAt) =>\n transaction\n .scheduleAlarm({\n id: SUBSCRIPTION_ALARM_ID,\n tag: SUBSCRIPTION_ALARM_TAG,\n runAt,\n payload: { schemaVersion: 1, generation: replacement.generation },\n })\n .pipe(Effect.mapError(alarmStorageError(\"schedule-subscription-alarm\"))),\n ),\n ),\n ),\n )\n .pipe(\n Effect.catchTag(\"StorageOperationError\", () =>\n storageFailure(\"commit-subscription-transaction\"),\n ),\n );\n }),\n });\n }),\n);\n\nconst alarmHandler = (limits: SubscriptionLimits) =>\n DurableObjectAlarm.processDue(\n (event) =>\n Effect.gen(function* () {\n if (event.tag !== SUBSCRIPTION_ALARM_TAG) {\n const { handlers } = yield* SubscriptionPartitionAlarmExtension;\n const matches = handlers.filter((handler) => handler.tag === event.tag);\n const handler = matches[0];\n\n if (\n event.tag.startsWith(\"effect-agent/\") ||\n matches.length !== 1 ||\n handler === undefined\n )\n return yield* SubscriptionAlarmProtocolError.make({\n message: \"Unknown or ambiguous ancillary alarm tag\",\n });\n\n return yield* handler.handle(event).pipe(\n Effect.scoped,\n Effect.timeoutOrElse({\n duration: MAX_ANCILLARY_ALARM_MILLIS,\n orElse: () => SubscriptionAlarmExtensionError.make({ code: \"timeout\" }),\n }),\n );\n }\n if (event.id !== SUBSCRIPTION_ALARM_ID) {\n return yield* SubscriptionAlarmProtocolError.make({\n message: `Unsupported Subscription Partition alarm ${event.tag}/${event.id}`,\n });\n }\n yield* Schema.decodeUnknownEffect(SubscriptionAlarmPayload)(event.payload).pipe(\n Effect.mapError(() =>\n SubscriptionAlarmProtocolError.make({\n message: \"Unsupported subscription alarm payload\",\n }),\n ),\n );\n const driver = yield* SubscriptionDriver;\n const alarmControl = yield* DoSubscriptionAlarmControl;\n\n yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.retryMillis);\n\n const pass = yield* driver.runDue.pipe(\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterrupts(cause),\n (cause) =>\n Clock.currentTimeMillis.pipe(\n Effect.flatMap((time) => alarmControl.prearm(time + limits.retryMillis)),\n Effect.andThen(Effect.failCause(cause)),\n ),\n ),\n );\n\n if (pass.failed > 0) {\n yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.retryMillis);\n } else {\n yield* alarmControl.reconcile;\n }\n }),\n {\n limit: MAX_ALARMS_PER_INVOCATION,\n retryFailedAfter: limits.retryMillis,\n onFailure: () => Effect.logWarning(\"Subscription partition alarm retained for retry\"),\n },\n ).pipe(Effect.asVoid);\n\ntype SubscriptionRuntimeServices =\n | Subscriptions\n | SubscriptionIntake\n | SubscriptionDriver\n | DoSubscriptionAlarmControl\n | SubscriptionPartitionIdentity\n | DurableObjectAlarm.DurableObjectAlarm;\n\nexport interface SubscriptionPartitionObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, SubscriptionRuntimeServices>\n> {\n subscription(encoded: unknown): Promise<unknown>;\n alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;\n}\n\nexport interface SubscriptionPartitionObjectClass {\n new (ctx: DurableObjectState, env: Cloudflare.Env): SubscriptionPartitionObjectInstance;\n}\n\n/**\n * Build one source-addressed SQLite Durable Object. The host Layer binds the permitted source\n * catalog and authority. It must not retain cleanup-scoped resources across RPC events.\n */\nexport const makeSubscriptionPartitionObjectClass = <E>(\n host: Layer.Layer<\n SubscriptionAuthorizer | EventSources | SubscriptionInputBindings | ThreadObjectNamespace,\n E,\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n | SubscriptionPartitionIdentity\n >,\n limits: SubscriptionLimits = defaultSubscriptionLimits,\n): SubscriptionPartitionObjectClass => {\n const cloudflareLimitsLayer = Layer.effectDiscard(validateCloudflareSubscriptionLimits(limits));\n\n const identityLayer = Layer.effect(\n SubscriptionPartitionIdentity,\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n\n return SubscriptionPartitionIdentity.of({\n partition: yield* decodePartitionName(state.raw.id.name),\n });\n }),\n );\n\n const sqlLayer = Layer.unwrap(\n Effect.map(EffectCfDurableObjectState.DurableObjectState, (state) =>\n SqliteClient.layer({ storage: state.raw.storage }),\n ),\n );\n\n const partitionStore = Layer.unwrap(\n Effect.map(SubscriptionPartitionIdentity, ({ partition }) =>\n doSubscriptionStoreLayer(partition).pipe(\n Layer.provide(transactionLayer),\n Layer.provide(sqlLayer),\n ),\n ),\n );\n\n const application = Layer.mergeAll(\n Subscriptions.layer(limits),\n SubscriptionIntake.layer(limits),\n SubscriptionDriver.layer(limits),\n cloudflareLimitsLayer,\n // Capture the host reference before its scoped input Layer is hidden from the runtime.\n Layer.effect(\n SubscriptionPartitionAlarmExtension,\n Effect.gen(function* () {\n const extension = yield* SubscriptionPartitionAlarmExtension;\n const tags = extension.handlers.map((handler) => handler.tag);\n\n if (\n tags.length > MAX_ALARMS_PER_INVOCATION ||\n new Set(tags).size !== tags.length ||\n tags.some(\n (tag) => tag.length === 0 || tag.length > 128 || tag.startsWith(\"effect-agent/\"),\n )\n )\n return yield* SubscriptionAlarmProtocolError.make({\n message: \"Invalid ancillary alarm handler registry\",\n });\n\n yield* validateCloudflareSubscriptionLimits(limits, { ancillaryAlarms: tags.length > 0 });\n\n return extension;\n }),\n ),\n ).pipe(\n Layer.provideMerge(partitionStore),\n Layer.provide(\n cloudflarePreparedInputAdmissionLayer.pipe(Layer.provide(CloudflareThreadClient.layer)),\n ),\n Layer.provide(cloudflareCryptoLayer),\n Layer.provideMerge(DurableObjectAlarm.DurableObjectAlarm.layer),\n Layer.provide(host),\n Layer.provideMerge(identityLayer),\n );\n\n const runtime: Layer.Layer<\n SubscriptionRuntimeServices,\n | E\n | SubscriptionError\n | SubscriptionPartitionProtocolError\n | CloudflareSubscriptionConfigError\n | SubscriptionAlarmProtocolError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = {\n subscription: (encoded: unknown) => handleRequest(encoded),\n } satisfies EffectCfDurableObject.DurableObjectRpc<SubscriptionRuntimeServices>;\n\n const SubscriptionPartitionObject = EffectCfDurableObject.make(runtime, {\n initialize: Effect.void,\n rpc,\n alarms: alarmHandler(limits),\n });\n\n return SubscriptionPartitionObject;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,MAAM,yBAAyB;AAC/B,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,4BAA4B;AAClC,MAAM,6BAA6B;AAEnC,MAAM,2BAA2B,OAAO,OAAO;CAC7C,eAAe,OAAO,QAAQ,CAAC;CAC/B,YAAY,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AACtD,CAAC;AAED,IAAa,iCAAb,cAAoD,OAAO,YAA4C,CAAC,CACtG,kCACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;;AAGH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O,qCAAqC,QAAQ,EAAE,iBAAiB,KAAK,SAAS,EAAE,CAAC;EAExF,OAAO;CACT,CAAC,CACH,CACF,CAAC,CAAC,KACA,MAAM,aAAa,cAAc,GACjC,MAAM,QACJ,sCAAsC,KAAK,MAAM,QAAQ,uBAAuB,KAAK,CAAC,CACxF,GACA,MAAM,QAAQ,qBAAqB,GACnC,MAAM,aAAa,mBAAmB,mBAAmB,KAAK,GAC9D,MAAM,QAAQ,IAAI,GAClB,MAAM,aAAa,aAAa,CAClC;CAEA,MAAM,UAQF,MAAM,cACR,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAOA,mBAA2B;EAChD,MAAM,QAAQ,OAAO,OAAO;EAE5B,OAAO,OAAO,MAAM,sBAAsB,MAAM,eAAe,aAAa,KAAK,CAAC;CACpF,CAAC,CACH;CAYA,OANoCC,cAAsB,KAAK,SAAS;EACtE,YAAY,OAAO;EACnB,KAAA,EALA,eAAe,YAAqB,cAAc,OAAO,EAKvD;EACF,QAAQ,aAAa,MAAM;CAC7B,CAEiC;AACnC"}
@@ -1,13 +1,20 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { DurableAlarmError, ThreadObjectNamespace, callThreadObject } from "./CloudflareBindings.mjs";
3
3
  import { AdmissionLimitExceeded } from "./CloudflareConfig.mjs";
4
- import { r as safeCauseMessage, t as cloudflareFailureSignals } from "./boundary-BguazVkh.mjs";
4
+ import { r as safeCauseMessage, t as cloudflareFailureSignals } from "./boundary-BLbZMBl2.mjs";
5
+ import { d as boundHostDiagnostic, l as liveTextProtocolFailure, n as decodeLiveText, r as Frame, s as Request, u as HostProtocolError } from "./LiveText-DRzUabZi.mjs";
5
6
  import "@yielded/agent/durable-agent-runtime";
6
- import { AgentId, ThreadId } from "@yielded/agent/identifiers";
7
+ import { AgentId } from "@yielded/agent/identifiers";
7
8
  import { AbortCommand, AbortIntent, AdmissionConflict, AdmissionFence, AdmissionGroup, AdmissionPolicyError, ApprovalConflict, ApprovalDecisionCommand, ApprovalDecisionIntent, IdempotencyKey, JoinedToHost, LedgerError, OwnershipLost, Principal, Settlement, SettlementConflict, UnknownResolutionCommand, UnknownResolutionConflict, UnknownResolutionIntent } from "@yielded/agent/submission-ledger";
8
- import { Context, Crypto, Duration, Effect, Layer, PlatformError, Predicate, Schema, Stream } from "effect";
9
9
  import { Rpc, RpcTargets, RpcTracing } from "effect-cf";
10
+ import * as Context from "effect/Context";
11
+ import * as Effect from "effect/Effect";
12
+ import * as Layer from "effect/Layer";
13
+ import * as Schema from "effect/Schema";
14
+ import * as Stream from "effect/Stream";
10
15
  import { CanonicalRecordEnvelope, CanonicalSequence, DefinitionDigests, PersistedJson, SubmissionSettledRecord, WorkerAdmission } from "@yielded/agent/records";
16
+ import * as Predicate from "effect/Predicate";
17
+ import * as Duration from "effect/Duration";
11
18
  import { AgentInputError } from "@yielded/agent/agent-error";
12
19
  import { DigestError } from "@yielded/agent/digest";
13
20
  import { DurableRuntimeFailpointError } from "@yielded/agent/durable-failpoint";
@@ -16,9 +23,10 @@ import { OperationDenied } from "@yielded/agent/operation-authorizer";
16
23
  import { Receipt } from "@yielded/agent/receipt";
17
24
  import { SubmissionStatus } from "@yielded/agent/submission-status";
18
25
  import { AppendConflict, ThreadNotMaterialized, ThreadStoreError } from "@yielded/agent/thread-store";
26
+ import * as Crypto from "effect/Crypto";
19
27
  import { createHash } from "node:crypto";
20
- import { BrowserCrypto } from "@effect/platform-browser";
21
- import { Event } from "@yielded/agent/provisional-text";
28
+ import * as BrowserCrypto from "@effect/platform-browser/BrowserCrypto";
29
+ import * as PlatformError from "effect/PlatformError";
22
30
  //#region src/internal/crypto.ts
23
31
  /** Workers use native SHA-256 while retaining BrowserCrypto's services and overrides. */
24
32
  const cloudflareCryptoLayer = Layer.effect(Crypto.Crypto, Effect.gen(function* () {
@@ -43,43 +51,12 @@ const cloudflareCryptoLayer = Layer.effect(Crypto.Crypto, Effect.gen(function* (
43
51
  });
44
52
  })).pipe(Layer.provide(BrowserCrypto.layer));
45
53
  //#endregion
46
- //#region src/internal/live-text-protocol.ts
47
- const MAX_FRAME_BYTES = 32768;
48
- const MAX_DELTA_LENGTH = 4096;
49
- const MAX_DRAFT_LENGTH = 2097152;
50
- const streamId = Schema.NonEmptyString.check(Schema.isMaxLength(256));
51
- const Request = Schema.Struct({ schemaVersion: Schema.Literal(1) });
54
+ //#region src/internal/live-text-observation.ts
52
55
  /** The RPC lifetime survives an idle byte stream and is disposed on caller disconnect. */
53
56
  const Observation = Schema.Struct({
54
57
  stream: Schema.instanceOf(ReadableStream),
55
58
  lifetime: Schema.declare(Rpc.isDisposable)
56
59
  });
57
- /**
58
- * Reset replaces all drafts with a snapshot, streamed as native Text parts before live deltas.
59
- * Each snapshot starts a fresh streamId. Its sequences are unrelated to canonical sequences.
60
- */
61
- const Frame = Schema.Union([Schema.TaggedStruct("Reset", {
62
- schemaVersion: Schema.Literal(1),
63
- streamId,
64
- threadId: ThreadId,
65
- sequence: Schema.Literal(0)
66
- }), Schema.TaggedStruct("Event", {
67
- schemaVersion: Schema.Literal(1),
68
- streamId,
69
- sequence: Schema.Int.check(Schema.isGreaterThan(0)),
70
- event: Event
71
- })]);
72
- /** Bounds are checked before queueing; provider metadata is deliberately absent. */
73
- const isBoundedEvent = (event) => {
74
- const ids = [
75
- event.threadId,
76
- event.submissionId,
77
- event.attemptId
78
- ];
79
- if (event._tag !== "AttemptEnded") ids.push(event.runId, event.turnId);
80
- if (ids.some((id) => id.length > 256)) return false;
81
- return event._tag !== "Text" || event.part.id.length <= 256 && Object.keys(event.part.metadata).length === 0 && (event.part.type !== "text-delta" || event.part.delta.length <= 4096);
82
- };
83
60
  //#endregion
84
61
  //#region src/CloudflareThreadClient.ts
85
62
  var CloudflareThreadClient_exports = /* @__PURE__ */ __exportAll({
@@ -136,17 +113,7 @@ var CloudflareThreadClient_exports = /* @__PURE__ */ __exportAll({
136
113
  * failures travel as their own tagged classes and RE-DECODE to identical tags on the caller
137
114
  * (error-tag fidelity), and protocol anomalies are answered typed instead of thrown.
138
115
  */
139
- /** Ceiling for host protocol diagnostic strings. */
140
- const MAX_HOST_DIAGNOSTIC_LENGTH = 4096;
141
116
  const PROGRESS_CANCELLATION_TIMEOUT = "1 second";
142
- const BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_HOST_DIAGNOSTIC_LENGTH));
143
- /** Truncate a diagnostic string to the host protocol's bounded length. */
144
- const boundHostDiagnostic = (value) => value.length > MAX_HOST_DIAGNOSTIC_LENGTH ? `${value.slice(0, 4093)}...` : value;
145
- /**
146
- * The envelope itself could not be honored: the Object could not decode the request, or a
147
- * response could not be encoded/decoded. Never carries operation semantics.
148
- */
149
- var HostProtocolError = class extends Schema.TaggedError()("HostProtocolError", { message: BoundedDiagnostic }) {};
150
117
  /** The Worker-side stub call itself failed (RPC rejection, overload, eviction mid-call). */
151
118
  var ThreadClientError = class extends Schema.TaggedError()("ThreadClientError", {
152
119
  threadId: Schema.String,
@@ -321,92 +288,6 @@ const ClientUnknownHostFailure = Schema.Union([
321
288
  DurableAlarmError,
322
289
  HostProtocolError
323
290
  ]);
324
- const liveTextProtocolFailure = () => HostProtocolError.make({ message: "Provisional text is incomplete or invalid; discard drafts and read canonical records" });
325
- const decodeLiveTextFrame = Schema.decodeUnknownSync(Schema.fromJsonString(Frame));
326
- /**
327
- * Validate untrusted NDJSON at the final consumer, including frame bounds, thread,
328
- * sequence and text lifecycle. Stream loss invalidates all provisional drafts.
329
- */
330
- const decodeLiveText = (threadId, source) => Stream.suspend(() => {
331
- const decoder = new TextDecoder("utf-8", {
332
- fatal: true,
333
- ignoreBOM: false
334
- });
335
- let pending = "";
336
- let pendingBytes = 0;
337
- let expected = 0;
338
- let streamId;
339
- const models = /* @__PURE__ */ new Map();
340
- const accept = Effect.fnUntraced(function* (frame) {
341
- if (frame._tag === "Reset") {
342
- if (frame.streamId === streamId || frame.threadId !== threadId) return yield* liveTextProtocolFailure();
343
- streamId = frame.streamId;
344
- expected = 1;
345
- models.clear();
346
- return true;
347
- }
348
- if (streamId === void 0 || frame.streamId !== streamId || frame.sequence !== expected++ || frame.event.threadId !== threadId || !isBoundedEvent(frame.event)) return yield* liveTextProtocolFailure();
349
- const event = frame.event;
350
- if (event._tag === "AttemptEnded") {
351
- for (const [key, model] of models) if (model.attemptId === event.attemptId) models.delete(key);
352
- return true;
353
- }
354
- const key = JSON.stringify([
355
- event.attemptId,
356
- event.runId,
357
- event.turnId,
358
- event.generation
359
- ]);
360
- if (event._tag === "Discard") {
361
- models.delete(key);
362
- return true;
363
- }
364
- let model = models.get(key);
365
- if (event.part.type === "text-start") {
366
- if (model?.parts.has(event.part.id)) return yield* liveTextProtocolFailure();
367
- if ([...models.values()].reduce((size, value) => size + value.parts.size, 0) >= 32) return yield* liveTextProtocolFailure();
368
- if (model === void 0) {
369
- model = {
370
- attemptId: event.attemptId,
371
- parts: /* @__PURE__ */ new Set()
372
- };
373
- models.set(key, model);
374
- }
375
- model.parts.add(event.part.id);
376
- return true;
377
- }
378
- if (!model?.parts.has(event.part.id)) return yield* liveTextProtocolFailure();
379
- if (event.part.type === "text-end") {
380
- model.parts.delete(event.part.id);
381
- if (model.parts.size === 0) models.delete(key);
382
- }
383
- return true;
384
- });
385
- return source.pipe(Stream.mapEffect(Effect.fnUntraced(function* (chunk) {
386
- if (!(chunk instanceof Uint8Array)) return yield* liveTextProtocolFailure();
387
- const frames = [];
388
- for (let offset = 0; offset < chunk.byteLength;) {
389
- const newline = chunk.indexOf(10, offset);
390
- const end = newline < 0 ? chunk.byteLength : newline;
391
- pendingBytes += end - offset;
392
- if (pendingBytes > 32768) return yield* liveTextProtocolFailure();
393
- pending += yield* Effect.try({
394
- try: () => decoder.decode(chunk.subarray(offset, end), { stream: newline < 0 }),
395
- catch: liveTextProtocolFailure
396
- });
397
- offset = end + 1;
398
- if (newline < 0) break;
399
- const frame = yield* Effect.try({
400
- try: () => decodeLiveTextFrame(pending),
401
- catch: liveTextProtocolFailure
402
- });
403
- pending = "";
404
- pendingBytes = 0;
405
- if (yield* accept(frame)) frames.push(frame);
406
- }
407
- return frames;
408
- })), Stream.flatMap(Stream.fromArray), Stream.concat(Stream.fail(liveTextProtocolFailure())));
409
- });
410
291
  const outOfContract = (threadId, operation, observed) => ThreadClientError.make({
411
292
  threadId,
412
293
  message: boundHostDiagnostic(`The Thread Object answered ${operation} with the out-of-contract ${observed}.`)
@@ -617,6 +498,6 @@ var CloudflareThreadClient = class CloudflareThreadClient extends Context.Servic
617
498
  }));
618
499
  };
619
500
  //#endregion
620
- export { decodeLiveText as A, encodeHostResponse as B, boundHostDiagnostic as C, decodeAwaitSettlementRequest as D, decodeAwaitProgressRequest as E, encodeAbortCommand as F, Frame as G, encodeReceipt as H, encodeApprovalDecisionCommand as I, MAX_FRAME_BYTES as J, MAX_DELTA_LENGTH as K, encodeAwaitProgressRequest as L, decodeReceipt as M, decodeSubmitRequest as N, decodeCancelProgressRequest as O, decodeUnknownResolutionCommand as P, cloudflareCryptoLayer as Q, encodeAwaitSettlementRequest as R, UnknownResolutionRecorded as S, decodeApprovalDecisionCommand as T, encodeSubmitRequest as U, encodeObservePageRequest as V, encodeUnknownResolutionCommand as W, Request as X, Observation as Y, isBoundedEvent as Z, SettlementRecordReached as _, CancelProgressRequest as a, SubmitSucceeded as b, HostFailed as c, HostResponse as d, ObservePageRequest as f, SettlementReached as g, ProgressObserved as h, AwaitSettlementRequest as i, decodeObservePageRequest as j, decodeHostResponse as k, HostFailure as l, ProgressCancelled as m, ApprovalRecorded as n, CloudflareThreadClient as o, ObservedPage as p, MAX_DRAFT_LENGTH as q, AwaitProgressRequest as r, CloudflareThreadClient_exports as s, AbortRecorded as t, HostProtocolError as u, SubmissionStatusResponse as v, decodeAbortCommand as w, ThreadClientError as x, SubmitRequest as y, encodeCancelProgressRequest as z };
501
+ export { decodeSubmitRequest as A, encodeSubmitRequest as B, decodeApprovalDecisionCommand as C, decodeHostResponse as D, decodeCancelProgressRequest as E, encodeAwaitSettlementRequest as F, Observation as H, encodeCancelProgressRequest as I, encodeHostResponse as L, encodeAbortCommand as M, encodeApprovalDecisionCommand as N, decodeObservePageRequest as O, encodeAwaitProgressRequest as P, encodeObservePageRequest as R, decodeAbortCommand as S, decodeAwaitSettlementRequest as T, cloudflareCryptoLayer as U, encodeUnknownResolutionCommand as V, SubmissionStatusResponse as _, CancelProgressRequest as a, ThreadClientError as b, HostFailed as c, ObservePageRequest as d, ObservedPage as f, SettlementRecordReached as g, SettlementReached as h, AwaitSettlementRequest as i, decodeUnknownResolutionCommand as j, decodeReceipt as k, HostFailure as l, ProgressObserved as m, ApprovalRecorded as n, CloudflareThreadClient as o, ProgressCancelled as p, AwaitProgressRequest as r, CloudflareThreadClient_exports as s, AbortRecorded as t, HostResponse as u, SubmitRequest as v, decodeAwaitProgressRequest as w, UnknownResolutionRecorded as x, SubmitSucceeded as y, encodeReceipt as z };
621
502
 
622
- //# sourceMappingURL=CloudflareThreadClient-CnvMXPmV.mjs.map
503
+ //# sourceMappingURL=CloudflareThreadClient-DiV2xHn0.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CloudflareThreadClient-DiV2xHn0.mjs","names":["LiveTextObservation","WatchTextRequest"],"sources":["../src/internal/crypto.ts","../src/internal/live-text-observation.ts","../src/CloudflareThreadClient.ts"],"sourcesContent":["// Implement the Effect Crypto service with the Workers native hashing primitive.\n// @effect-diagnostics-next-line nodeBuiltinImport:off\nimport { createHash } from \"node:crypto\";\n\nimport * as BrowserCrypto from \"@effect/platform-browser/BrowserCrypto\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PlatformError from \"effect/PlatformError\";\n\n/** Workers use native SHA-256 while retaining BrowserCrypto's services and overrides. */\nexport const cloudflareCryptoLayer: Layer.Layer<Crypto.Crypto> = Layer.effect(\n Crypto.Crypto,\n Effect.gen(function* () {\n const base = yield* Crypto.Crypto;\n const webCrypto = yield* BrowserCrypto.WebCrypto;\n const hostGlobals: object = globalThis;\n\n return Crypto.Crypto.of({\n ...base,\n digest: (algorithm, data) => {\n if (\n algorithm !== \"SHA-256\" ||\n !(\"crypto\" in hostGlobals) ||\n webCrypto !== hostGlobals.crypto ||\n typeof webCrypto.subtle?.digest !== \"function\"\n )\n return base.digest(algorithm, data);\n\n return Effect.try({\n try: () => Uint8Array.from(createHash(\"sha256\").update(data).digest()),\n catch: (cause) =>\n PlatformError.systemError({\n module: \"Crypto\",\n method: \"digest\",\n _tag: \"Unknown\",\n description: \"Could not compute digest\",\n cause,\n }),\n });\n },\n });\n }),\n).pipe(Layer.provide(BrowserCrypto.layer));\n","import { Rpc } from \"effect-cf\";\nimport * as Schema from \"effect/Schema\";\n\n/** The RPC lifetime survives an idle byte stream and is disposed on caller disconnect. */\nexport const Observation = Schema.Struct({\n stream: Schema.instanceOf(ReadableStream<Uint8Array>),\n lifetime: Schema.declare(Rpc.isDisposable),\n});\n","import { AgentInputError } from \"@yielded/agent/agent-error\";\nimport { DigestError } from \"@yielded/agent/digest\";\nimport {\n type DurableSubmitAgent,\n type DurableSubmitOptions,\n} from \"@yielded/agent/durable-agent-runtime\";\nimport { DurableRuntimeFailpointError } from \"@yielded/agent/durable-failpoint\";\nimport { AgentId, type ThreadId } from \"@yielded/agent/identifiers\";\nimport { InputMessage } from \"@yielded/agent/messaging\";\nimport { OperationDenied } from \"@yielded/agent/operation-authorizer\";\nimport { Receipt } from \"@yielded/agent/receipt\";\nimport {\n CanonicalRecordEnvelope,\n CanonicalSequence,\n DefinitionDigests,\n PersistedJson,\n SubmissionSettledRecord,\n WorkerAdmission,\n} from \"@yielded/agent/records\";\nimport {\n AdmissionFence,\n AdmissionGroup,\n AbortCommand,\n AbortIntent,\n AdmissionConflict,\n AdmissionPolicyError,\n ApprovalConflict,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n IdempotencyKey,\n JoinedToHost,\n LedgerError,\n OwnershipLost,\n Principal,\n Settlement,\n SettlementConflict,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n} from \"@yielded/agent/submission-ledger\";\nimport { SubmissionStatus } from \"@yielded/agent/submission-status\";\nimport {\n AppendConflict,\n ThreadNotMaterialized,\n ThreadStoreError,\n} from \"@yielded/agent/thread-store\";\nimport { RpcTargets, RpcTracing } from \"effect-cf\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n callThreadObject,\n DurableAlarmError,\n ThreadObjectNamespace,\n type ThreadObjectRpc,\n} from \"./CloudflareBindings.ts\";\nimport { AdmissionLimitExceeded } from \"./CloudflareConfig.ts\";\nimport { cloudflareFailureSignals, safeCauseMessage } from \"./internal/boundary.ts\";\nimport { cloudflareCryptoLayer } from \"./internal/crypto.ts\";\nimport { boundHostDiagnostic, HostProtocolError } from \"./internal/host-protocol-error.ts\";\nimport { Observation as LiveTextObservation } from \"./internal/live-text-observation.ts\";\nimport {\n liveTextProtocolFailure,\n Request as WatchTextRequest,\n} from \"./internal/live-text-protocol.ts\";\nimport { decodeLiveText, type LiveTextFrame } from \"./LiveText.ts\";\n\nexport { boundHostDiagnostic, HostProtocolError } from \"./internal/host-protocol-error.ts\";\nexport { decodeLiveText, LiveTextFrame } from \"./LiveText.ts\";\n\n/**\n * The Worker↔Thread-Object host protocol (plan §1.4): Schema envelopes for the host\n * entry points (`submitEncoded`, `awaitSettlementEncoded`, `observePage`, `abortEncoded`,\n * `resolveApprovalEncoded`, `resolveUnknownEncoded`) plus the Worker-side client that speaks\n * it. Mirrors the WP2 port protocol: requests and responses are closed Schema unions, typed\n * failures travel as their own tagged classes and RE-DECODE to identical tags on the caller\n * (error-tag fidelity), and protocol anomalies are answered typed instead of thrown.\n */\n\nconst PROGRESS_CANCELLATION_TIMEOUT = \"1 second\";\n\n/** The Worker-side stub call itself failed (RPC rejection, overload, eviction mid-call). */\nexport class ThreadClientError extends Schema.TaggedError<ThreadClientError>()(\n \"ThreadClientError\",\n {\n threadId: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n /** Cloudflare's own classification for a failure safe to retry with a fresh stub. */\n retryable: Schema.optionalKey(Schema.Boolean),\n /** Cloudflare overloads are surfaced immediately instead of adding retry pressure. */\n overloaded: Schema.optionalKey(Schema.Boolean),\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Requests\n// ---------------------------------------------------------------------------\n\n/**\n * One durable submission, input ALREADY encoded by the caller through the Agent Binding's\n * input schema (the Worker bundles the same Agent definitions as the Object, so schema\n * validation happens client-side; the resolved Binding re-validates at claim time). The\n * Thread identity is deliberately absent — the addressed Object IS the lane.\n */\nexport class SubmitRequest extends Schema.Class<SubmitRequest>(\n \"@effect-agent/platform-cloudflare/SubmitRequest\",\n)({\n agentId: AgentId,\n principal: Principal,\n idempotencyKey: IdempotencyKey,\n admissionGroup: Schema.optionalKey(AdmissionGroup),\n admissionFence: Schema.optionalKey(AdmissionFence),\n workerAdmission: Schema.optionalKey(WorkerAdmission),\n messageAdmission: Schema.optionalKey(InputMessage),\n definitions: DefinitionDigests,\n inputPayload: PersistedJson,\n}) {}\n\n/** One bounded page of canonical records after an optional sequence. */\nexport class ObservePageRequest extends Schema.Class<ObservePageRequest>(\n \"@effect-agent/platform-cloudflare/ObservePageRequest\",\n)({\n afterSequence: Schema.optionalKey(CanonicalSequence),\n limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),\n}) {}\n\n/** Receipt-shaped observation request; the optional identity owns only the remote wait. */\nexport class AwaitSettlementRequest extends Receipt.extend<AwaitSettlementRequest>(\n \"@effect-agent/platform-cloudflare/AwaitSettlementRequest\",\n)({\n waiterId: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256))),\n}) {}\n\n/** One event-driven wait for canonical progress strictly after this sequence. */\nexport class AwaitProgressRequest extends Schema.Class<AwaitProgressRequest>(\n \"@effect-agent/platform-cloudflare/AwaitProgressRequest\",\n)({\n afterSequence: CanonicalSequence,\n waiterId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),\n}) {}\n\n/** Best-effort cancellation of one in-flight progress or settlement observation. */\nexport class CancelProgressRequest extends Schema.Class<CancelProgressRequest>(\n \"@effect-agent/platform-cloudflare/CancelProgressRequest\",\n)({\n waiterId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Responses\n// ---------------------------------------------------------------------------\n\n/**\n * Every typed failure a host entry point can produce, plus the protocol's own errors. Same\n * closed-union discipline as the WP2 `PortFailure`: members re-decode to the SAME tagged\n * classes on the Worker side; `cause` chains travel as Schema defects without instance\n * fidelity (plan §2.8).\n */\nexport const HostFailure = Schema.Union([\n AgentInputError,\n DigestError,\n AdmissionConflict,\n AdmissionPolicyError,\n SettlementConflict,\n ApprovalConflict,\n UnknownResolutionConflict,\n JoinedToHost,\n LedgerError,\n OwnershipLost,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n DurableRuntimeFailpointError,\n AdmissionLimitExceeded,\n DurableAlarmError,\n OperationDenied,\n HostProtocolError,\n]);\n\nexport type HostFailure = typeof HostFailure.Type;\n\nexport class SubmitSucceeded extends Schema.TaggedClass<SubmitSucceeded>(\n \"@effect-agent/platform-cloudflare/SubmitSucceeded\",\n)(\"SubmitSucceeded\", {\n receipt: Receipt,\n}) {}\n\nexport class SubmissionStatusResponse extends Schema.TaggedClass<SubmissionStatusResponse>(\n \"@effect-agent/platform-cloudflare/SubmissionStatusResponse\",\n)(\"SubmissionStatusResponse\", { status: SubmissionStatus }) {}\n\nexport class SettlementReached extends Schema.TaggedClass<SettlementReached>(\n \"@effect-agent/platform-cloudflare/SettlementReached\",\n)(\"SettlementReached\", {\n settlement: Settlement,\n}) {}\n\n/** The exact canonical record of an operationally finalized Submission. */\nexport class SettlementRecordReached extends Schema.TaggedClass<SettlementRecordReached>(\n \"@effect-agent/platform-cloudflare/SettlementRecordReached\",\n)(\"SettlementRecordReached\", {\n record: SubmissionSettledRecord,\n}) {}\n\nexport class ObservedPage extends Schema.TaggedClass<ObservedPage>(\n \"@effect-agent/platform-cloudflare/ObservedPage\",\n)(\"ObservedPage\", {\n records: Schema.Array(CanonicalRecordEnvelope).check(Schema.isMaxLength(1_024)),\n}) {}\n\n/** A record was already committed or an incarnation-local hint says the caller should re-read. */\nexport class ProgressObserved extends Schema.TaggedClass<ProgressObserved>(\n \"@effect-agent/platform-cloudflare/ProgressObserved\",\n)(\"ProgressObserved\", {}) {}\n\nexport class ProgressCancelled extends Schema.TaggedClass<ProgressCancelled>(\n \"@effect-agent/platform-cloudflare/ProgressCancelled\",\n)(\"ProgressCancelled\", {}) {}\n\nexport class AbortRecorded extends Schema.TaggedClass<AbortRecorded>(\n \"@effect-agent/platform-cloudflare/AbortRecorded\",\n)(\"AbortRecorded\", {\n intent: AbortIntent,\n}) {}\n\nexport class ApprovalRecorded extends Schema.TaggedClass<ApprovalRecorded>(\n \"@effect-agent/platform-cloudflare/ApprovalRecorded\",\n)(\"ApprovalRecorded\", {\n intent: ApprovalDecisionIntent,\n}) {}\n\nexport class UnknownResolutionRecorded extends Schema.TaggedClass<UnknownResolutionRecorded>(\n \"@effect-agent/platform-cloudflare/UnknownResolutionRecorded\",\n)(\"UnknownResolutionRecorded\", {\n intent: UnknownResolutionIntent,\n}) {}\n\n/** The entry point failed TYPED on the Object; the failure re-decodes verbatim. */\nexport class HostFailed extends Schema.TaggedClass<HostFailed>(\n \"@effect-agent/platform-cloudflare/HostFailed\",\n)(\"HostFailed\", {\n failure: HostFailure,\n}) {}\n\n/** The uniform answer of one host entry point. Callers narrow by the tag their call implies. */\nexport const HostResponse = Schema.Union([\n SubmitSucceeded,\n SettlementReached,\n SettlementRecordReached,\n SubmissionStatusResponse,\n ObservedPage,\n ProgressObserved,\n ProgressCancelled,\n AbortRecorded,\n ApprovalRecorded,\n UnknownResolutionRecorded,\n HostFailed,\n]);\n\nexport type HostResponse = typeof HostResponse.Type;\n\n// ---------------------------------------------------------------------------\n// Codecs (shared by the Object endpoints and the Worker client)\n// ---------------------------------------------------------------------------\n\nexport const decodeSubmitRequest = Schema.decodeUnknownEffect(SubmitRequest);\n// Encode the caller's fields directly: constructing a Class first would validate the\n// same envelope twice. The Object still decodes its untrusted request independently.\nexport const encodeSubmitRequest = Schema.encodeEffect(Schema.Struct(SubmitRequest.fields));\nexport const decodeReceipt = Schema.decodeUnknownEffect(Receipt);\nexport const encodeReceipt = Schema.encodeEffect(Receipt);\nexport const decodeAwaitSettlementRequest = Schema.decodeUnknownEffect(AwaitSettlementRequest);\nexport const encodeAwaitSettlementRequest = Schema.encodeEffect(AwaitSettlementRequest);\nexport const decodeObservePageRequest = Schema.decodeUnknownEffect(ObservePageRequest);\nexport const encodeObservePageRequest = Schema.encodeEffect(ObservePageRequest);\nexport const decodeAwaitProgressRequest = Schema.decodeUnknownEffect(AwaitProgressRequest);\nexport const encodeAwaitProgressRequest = Schema.encodeEffect(AwaitProgressRequest);\nexport const decodeCancelProgressRequest = Schema.decodeUnknownEffect(CancelProgressRequest);\nexport const encodeCancelProgressRequest = Schema.encodeEffect(CancelProgressRequest);\nexport const decodeAbortCommand = Schema.decodeUnknownEffect(AbortCommand);\nexport const encodeAbortCommand = Schema.encodeEffect(AbortCommand);\nexport const decodeApprovalDecisionCommand = Schema.decodeUnknownEffect(ApprovalDecisionCommand);\nexport const encodeApprovalDecisionCommand = Schema.encodeEffect(ApprovalDecisionCommand);\nexport const decodeUnknownResolutionCommand = Schema.decodeUnknownEffect(UnknownResolutionCommand);\nexport const encodeUnknownResolutionCommand = Schema.encodeEffect(UnknownResolutionCommand);\nexport const encodeHostResponse = Schema.encodeEffect(HostResponse);\nexport const decodeHostResponse = Schema.decodeUnknownEffect(HostResponse);\n\n// ---------------------------------------------------------------------------\n// Worker-side client\n// ---------------------------------------------------------------------------\n\n/** Failure surface of `CloudflareThreadClient.submit`. */\nconst ClientSubmitHostFailure = Schema.Union([\n AgentInputError,\n DigestError,\n AdmissionConflict,\n AdmissionPolicyError,\n LedgerError,\n OwnershipLost,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n DurableRuntimeFailpointError,\n AdmissionLimitExceeded,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nconst ClientAwaitHostFailure = Schema.Union([\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n OperationDenied,\n HostProtocolError,\n]);\n\nconst ClientObserveHostFailure = Schema.Union([\n ThreadStoreError,\n ThreadNotMaterialized,\n OperationDenied,\n HostProtocolError,\n]);\n\nconst ClientAbortHostFailure = Schema.Union([\n OperationDenied,\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n JoinedToHost,\n DurableRuntimeFailpointError,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nconst ClientApprovalHostFailure = Schema.Union([\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n ApprovalConflict,\n OperationDenied,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nconst ClientUnknownHostFailure = Schema.Union([\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n UnknownResolutionConflict,\n JoinedToHost,\n DurableRuntimeFailpointError,\n OperationDenied,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nexport type ClientSubmitFailure = typeof ClientSubmitHostFailure.Type | ThreadClientError;\nexport type ClientAwaitFailure = typeof ClientAwaitHostFailure.Type | ThreadClientError;\nexport type ClientObserveFailure = typeof ClientObserveHostFailure.Type | ThreadClientError;\nexport type ClientProgressFailure = ClientObserveFailure;\nexport type ClientAbortFailure = typeof ClientAbortHostFailure.Type | ThreadClientError;\nexport type ClientApprovalFailure = typeof ClientApprovalHostFailure.Type | ThreadClientError;\nexport type ClientUnknownFailure = typeof ClientUnknownHostFailure.Type | ThreadClientError;\n\nconst outOfContract = (threadId: string, operation: string, observed: string): ThreadClientError =>\n ThreadClientError.make({\n threadId,\n message: boundHostDiagnostic(\n `The Thread Object answered ${operation} with the out-of-contract ${observed}.`,\n ),\n });\n\nconst hostRpcMethods = {\n submit: \"submitEncoded\",\n awaitSettlement: \"awaitSettlementEncoded\",\n awaitSettlementRecord: \"awaitSettlementRecordEncoded\",\n submissionStatus: \"submissionStatusEncoded\",\n awaitProgress: \"awaitProgressEncoded\",\n cancelProgress: \"cancelProgressEncoded\",\n observePage: \"observePage\",\n abort: \"abortEncoded\",\n resolveApproval: \"resolveApprovalEncoded\",\n resolveUnknown: \"resolveUnknownEncoded\",\n} as const satisfies Record<string, keyof ThreadObjectRpc>;\n\n/** Worker-side client over the Thread Object namespace (DEPLOY-010). */\nexport class CloudflareThreadClient extends Context.Service<\n CloudflareThreadClient,\n {\n /** Encode the input client-side, then durably submit to the owning Object. */\n readonly submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) => Effect.Effect<Receipt, ClientSubmitFailure, InputSchema[\"EncodingServices\"]>;\n /** Wake-hinted, poll-guaranteed settlement wait executed inside the owning Object. */\n readonly submissionStatus: (\n receipt: Receipt,\n ) => Effect.Effect<SubmissionStatus, ClientAwaitFailure>;\n /**\n * Wait for settlement; interruption spends at most one second cancelling the remote\n * observation best effort. Cancellation never aborts the admitted Run.\n */\n readonly awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, ClientAwaitFailure>;\n /**\n * Wait for finalization and return this Receipt's canonical terminal record in one RPC.\n * Requires both settlement and observation authority. Decode an ordinary completed\n * record's result through the Agent output Schema; joined completion may have no result.\n * Interruption uses the same bounded observation cancellation as `awaitSettlement`.\n */\n readonly awaitSettlementRecord: (\n receipt: Receipt,\n ) => Effect.Effect<SubmissionSettledRecord, ClientAwaitFailure>;\n /**\n * Wait without polling until progress after `afterSequence` is already durable or hinted.\n * The result is deliberately void: canonical records remain authoritative and must be read.\n * Interruption waits at most one second for best-effort remote cancellation.\n */\n readonly awaitProgress: (\n threadId: ThreadId,\n afterSequence: CanonicalSequence,\n ) => Effect.Effect<void, ClientProgressFailure>;\n /**\n * Current provisional text followed by native deltas. Reset starts a replacement snapshot,\n * including when a slow consumer exceeds the fixed backlog. Reconcile by\n * Run/Turn identity to canonical records; discard drafts on Discard, AttemptEnded,\n * Reset or stream failure. Snapshots exist only in the Object incarnation's memory.\n * Scope the stream: interruption cancels its remote subscription.\n */\n readonly watchText: (threadId: ThreadId) => Stream.Stream<LiveTextFrame, ClientObserveFailure>;\n /**\n * Forward producer NDJSON bytes without decoding or re-encoding frames.\n * Blank keepalive lines every 15 seconds expose idle transport disconnects.\n * The final consumer must use `decodeLiveText` to validate untrusted frames.\n * Interruption cancels the remote subscription; buffers remain producer-bounded.\n */\n readonly watchTextBytes: (\n threadId: ThreadId,\n ) => Stream.Stream<Uint8Array, ClientObserveFailure>;\n /** One bounded page of canonical records. */\n readonly readPage: (\n threadId: ThreadId,\n options?: {\n readonly afterSequence?: CanonicalSequence | undefined;\n readonly limit?: number | undefined;\n },\n ) => Effect.Effect<ReadonlyArray<CanonicalRecordEnvelope>, ClientObserveFailure>;\n /**\n * Every canonical record up to the CURRENT committed tail, via repeated pages. A\n * snapshot read, not a live observation — callers wanting liveness re-read after\n * `awaitSettlement`.\n */\n readonly readAll: (\n threadId: ThreadId,\n ) => Effect.Effect<ReadonlyArray<CanonicalRecordEnvelope>, ClientObserveFailure>;\n /**\n * Submission-addressed operations take the owning Thread explicitly (from the\n * Receipt): minted Submission identities stay OPAQUE outside the storage adapter that\n * minted them (D-P6-5), so the client never parses one to find the lane.\n */\n readonly abort: (\n threadId: ThreadId,\n command: AbortCommand,\n ) => Effect.Effect<AbortIntent, ClientAbortFailure>;\n readonly resolveApproval: (\n threadId: ThreadId,\n command: ApprovalDecisionCommand,\n ) => Effect.Effect<ApprovalDecisionIntent, ClientApprovalFailure>;\n readonly resolveUnknown: (\n threadId: ThreadId,\n command: UnknownResolutionCommand,\n ) => Effect.Effect<UnknownResolutionIntent, ClientUnknownFailure>;\n }\n>()(\"@effect-agent/platform-cloudflare/CloudflareThreadClient\") {\n /**\n * Assemble the client from a resolved namespace and the platform Crypto implementation.\n * rpcTracing is the binding name and remains opt-in. Caller authentication, principals,\n * idempotency keys, and definition digests are still explicit submission inputs.\n */\n static layerFromBinding(options: {\n readonly namespace: DurableObjectNamespace<ThreadObjectRpc>;\n readonly rpcTracing?: string;\n }): Layer.Layer<CloudflareThreadClient> {\n return CloudflareThreadClient.layer.pipe(\n Layer.provide([\n ThreadObjectNamespace.layer(options.namespace, options),\n cloudflareCryptoLayer,\n ]),\n );\n }\n\n static readonly layer: Layer.Layer<\n CloudflareThreadClient,\n never,\n ThreadObjectNamespace | Crypto.Crypto\n > = Layer.effect(CloudflareThreadClient)(\n Effect.gen(function* () {\n const namespace = yield* ThreadObjectNamespace;\n const { rpcTracing } = namespace;\n const crypto = yield* Crypto.Crypto;\n\n const call = Effect.fnUntraced(\n function* (\n threadId: ThreadId,\n operation: keyof typeof hostRpcMethods,\n encoded: unknown,\n ): Effect.fn.Return<HostResponse, ThreadClientError | HostProtocolError> {\n // Empty arguments preserve native arity. Passing `undefined` still adds an argument.\n const traceArgs =\n rpcTracing === undefined ? [] : yield* RpcTracing.withRpcTraceContext([]);\n\n const raw = yield* callThreadObject(\n threadId,\n (stub) => stub[hostRpcMethods[operation]](encoded, ...traceArgs),\n (cause) =>\n ThreadClientError.make({\n threadId,\n message: boundHostDiagnostic(\n `${operation} did not reach the Thread Object: ${safeCauseMessage(\n cause,\n \"the RPC failed without a diagnostic\",\n )}`,\n ),\n cause,\n ...cloudflareFailureSignals(cause),\n }),\n ).pipe(Effect.provideService(ThreadObjectNamespace, namespace));\n\n return yield* decodeHostResponse(raw).pipe(\n Effect.mapError((error): HostProtocolError =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `The ${operation} answer could not be decoded: ${error.message}`,\n ),\n }),\n ),\n );\n },\n (effect, threadId, operation) =>\n rpcTracing === undefined\n ? Effect.withSpan(effect, \"CloudflareThreadClient.call\", {\n attributes: { threadId, operation },\n })\n : RpcTracing.withRpcClientSpan(effect, rpcTracing, hostRpcMethods[operation]),\n );\n\n const expect = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n threadId: string,\n operation: string,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ) => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n\n return (\n response: HostResponse,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ThreadClientError> => {\n if (response._tag === \"HostFailed\") {\n const failure = response.failure;\n\n return isExpectedFailure(failure)\n ? Effect.fail(failure)\n : Effect.fail(outOfContract(threadId, operation, `failure ${failure._tag}`));\n }\n if (!isExpectedResult(response)) {\n return Effect.fail(outOfContract(threadId, operation, `result ${response._tag}`));\n }\n\n return Effect.succeed(response);\n };\n };\n\n const readPage = Effect.fnUntraced(function* (\n threadId: ThreadId,\n options?: {\n readonly afterSequence?: CanonicalSequence | undefined;\n readonly limit?: number | undefined;\n },\n ) {\n const request = ObservePageRequest.make({\n ...(options?.afterSequence === undefined ? {} : { afterSequence: options.afterSequence }),\n limit: options?.limit ?? 256,\n });\n\n const encoded = yield* encodeObservePageRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`observePage request encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(threadId, \"observePage\", encoded);\n\n const page = yield* expect(\n threadId,\n \"observePage\",\n ObservedPage,\n ClientObserveHostFailure,\n )(response);\n\n return page.records;\n });\n\n const cancelProgress = (threadId: ThreadId, waiterId: string): Effect.Effect<void> =>\n encodeCancelProgressRequest(CancelProgressRequest.make({ waiterId })).pipe(\n Effect.mapError(() => undefined),\n Effect.flatMap((encoded) => call(threadId, \"cancelProgress\", encoded)),\n // Finalizers are uninterruptible; only the foreign RPC branch must remain\n // interruptible so a lost cancellation reply cannot prevent local shutdown.\n Effect.interruptible,\n Effect.timeout(PROGRESS_CANCELLATION_TIMEOUT),\n Effect.asVoid,\n Effect.ignore,\n );\n\n const awaitSettlementCall = Effect.fnUntraced(function* (\n receipt: Receipt,\n operation: \"awaitSettlement\" | \"awaitSettlementRecord\",\n ): Effect.fn.Return<HostResponse, ClientAwaitFailure> {\n const waiterId = yield* crypto.randomUUIDv4().pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `${operation} cancellation identity generation failed: ${error.message}`,\n ),\n }),\n ),\n );\n\n const encoded = yield* encodeAwaitSettlementRequest(\n AwaitSettlementRequest.make({ ...receipt, waiterId }),\n ).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`${operation} request encode failed: ${error.message}`),\n }),\n ),\n );\n\n return yield* call(receipt.threadId, operation, encoded).pipe(\n Effect.onInterrupt(() => cancelProgress(receipt.threadId, waiterId)),\n );\n });\n\n const watchTextBytes = (\n threadId: ThreadId,\n ): Stream.Stream<Uint8Array, ClientObserveFailure> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const traceArgs =\n rpcTracing === undefined ? [] : yield* RpcTracing.withRpcTraceContext([]);\n\n const openingFailure = (cause: unknown) =>\n ThreadClientError.make({\n threadId,\n message: \"Provisional text observation could not reach the Thread Object\",\n cause,\n ...cloudflareFailureSignals(cause),\n });\n\n // Retain the original RPC promise: resolving through callThreadObject would\n // erase its optional native disposer before an interrupted opening can use it.\n const target = yield* RpcTargets.get(namespace, threadId, () =>\n namespace.get(threadId),\n ).pipe(Effect.mapError(openingFailure));\n\n let request: Promise<unknown> | undefined;\n let received: unknown;\n let closed = false;\n\n const cancel = () => {\n const value = received;\n\n received = undefined;\n\n const observation = Schema.is(LiveTextObservation)(value) ? value : undefined;\n\n // Native RPC disposes the capability with the request; also release\n // it for application-owned endpoints and late opening responses.\n try {\n observation?.lifetime[Symbol.dispose]();\n } catch {\n // A request disposer may already have revoked this stub.\n }\n const stream = observation?.stream ?? value;\n\n return stream instanceof ReadableStream && !stream.locked\n ? stream.cancel().catch(() => undefined)\n : Promise.resolve();\n };\n\n // Install ownership before invoking foreign code, not after its promise settles.\n yield* Effect.addFinalizer(() =>\n Effect.try({\n try: () => {\n closed = true;\n if (Predicate.hasProperty(request, Symbol.dispose)) {\n const dispose = request[Symbol.dispose];\n\n if (typeof dispose === \"function\") dispose.call(request);\n }\n },\n catch: () => undefined,\n }).pipe(\n Effect.ignore,\n Effect.andThen(\n Effect.tryPromise({ try: cancel, catch: () => undefined }).pipe(\n Effect.interruptible,\n Effect.timeout(PROGRESS_CANCELLATION_TIMEOUT),\n Effect.ignore,\n ),\n ),\n ),\n );\n\n const raw = yield* Effect.tryPromise({\n try: () => {\n request = target.watchTextEncoded(\n Schema.encodeSync(WatchTextRequest)({ schemaVersion: 1 }),\n ...traceArgs,\n );\n\n return request.then((value) => {\n received = value;\n\n // A custom endpoint may return a plain, non-cancellable promise. Keep\n // late cleanup on that native promise chain; it starts no Effect fiber.\n return closed ? cancel().then(() => value) : value;\n });\n },\n catch: openingFailure,\n }).pipe(\n Effect.interruptible,\n Effect.tapCause(() => RpcTargets.invalidate(target)),\n );\n\n const stream = Schema.is(LiveTextObservation)(raw) ? raw.stream : raw;\n\n if (stream instanceof ReadableStream)\n return Stream.fromReadableStream<Uint8Array, ThreadClientError>({\n evaluate: () => stream,\n // The subscription Scope cancels after the reader releases its lock.\n releaseLockOnEnd: true,\n onError: (cause) =>\n ThreadClientError.make({\n threadId,\n message:\n \"Provisional text disconnected; discard drafts and read canonical records\",\n cause,\n }),\n });\n\n const response = yield* decodeHostResponse(raw).pipe(\n Effect.mapError(liveTextProtocolFailure),\n );\n\n if (\n response._tag === \"HostFailed\" &&\n Schema.is(ClientObserveHostFailure)(response.failure)\n )\n return yield* response.failure;\n\n return yield* liveTextProtocolFailure();\n }),\n );\n\n return CloudflareThreadClient.of({\n submit: Effect.fnUntraced(function* <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) {\n // Client-side half of `DurableAgentRuntime.submit`'s input boundary: encode\n // through the Agent's input schema and prove the canonical persistence bounds.\n const encodedInput = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError((cause) =>\n AgentInputError.make({ message: `Unable to encode Agent input: ${cause.message}` }),\n ),\n );\n\n const inputPayload = yield* Schema.decodeUnknownEffect(PersistedJson)(encodedInput).pipe(\n Effect.mapError(() =>\n AgentInputError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n\n const request = {\n agentId: agent.definition.id,\n principal: options.principal,\n idempotencyKey: options.idempotencyKey,\n ...(options.admissionGroup === undefined\n ? {}\n : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined\n ? {}\n : { admissionFence: options.admissionFence }),\n ...(options.workerAdmission === undefined\n ? {}\n : { workerAdmission: options.workerAdmission }),\n ...(options.messageAdmission === undefined\n ? {}\n : { messageAdmission: options.messageAdmission }),\n definitions: options.definitions,\n inputPayload,\n };\n\n const encoded = yield* encodeSubmitRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`submit request encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(options.threadId, \"submit\", encoded);\n\n const succeeded = yield* expect(\n options.threadId,\n \"submit\",\n SubmitSucceeded,\n ClientSubmitHostFailure,\n )(response);\n\n return succeeded.receipt;\n }),\n\n submissionStatus: Effect.fnUntraced(function* (receipt) {\n const encoded = yield* encodeReceipt(receipt).pipe(\n Effect.mapError(() => HostProtocolError.make({ message: \"Invalid receipt\" })),\n );\n\n const response = yield* call(receipt.threadId, \"submissionStatus\", encoded);\n\n const result = yield* expect(\n receipt.threadId,\n \"submissionStatus\",\n SubmissionStatusResponse,\n ClientAwaitHostFailure,\n )(response);\n\n return result.status;\n }),\n awaitSettlement: Effect.fnUntraced(function* (receipt) {\n const response = yield* awaitSettlementCall(receipt, \"awaitSettlement\");\n\n const settled = yield* expect(\n receipt.threadId,\n \"awaitSettlement\",\n SettlementReached,\n ClientAwaitHostFailure,\n )(response);\n\n return settled.settlement;\n }),\n\n awaitSettlementRecord: Effect.fnUntraced(function* (receipt) {\n const response = yield* awaitSettlementCall(receipt, \"awaitSettlementRecord\");\n\n const settled = yield* expect(\n receipt.threadId,\n \"awaitSettlementRecord\",\n SettlementRecordReached,\n ClientAwaitHostFailure,\n )(response);\n\n return settled.record;\n }),\n\n awaitProgress: Effect.fnUntraced(function* (threadId, afterSequence) {\n const waiterId = yield* crypto.randomUUIDv4().pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `awaitProgress cancellation identity generation failed: ${error.message}`,\n ),\n }),\n ),\n );\n\n const request = AwaitProgressRequest.make({ afterSequence, waiterId });\n\n const encoded = yield* encodeAwaitProgressRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `awaitProgress request encode failed: ${error.message}`,\n ),\n }),\n ),\n );\n\n const attempt = (retry: number): Effect.Effect<void, ClientProgressFailure> =>\n call(threadId, \"awaitProgress\", encoded).pipe(\n Effect.flatMap(\n expect(threadId, \"awaitProgress\", ProgressObserved, ClientObserveHostFailure),\n ),\n Effect.asVoid,\n Effect.catchTag(\"ThreadClientError\", (error) =>\n error.retryable === true && error.overloaded !== true && retry < 5\n ? Effect.sleep(Duration.millis(10 * 2 ** retry)).pipe(\n Effect.andThen(attempt(retry + 1)),\n )\n : Effect.fail(error),\n ),\n );\n\n yield* attempt(0).pipe(Effect.onInterrupt(() => cancelProgress(threadId, waiterId)));\n }),\n\n watchText: (threadId) => decodeLiveText(threadId, watchTextBytes(threadId)),\n watchTextBytes,\n\n readPage,\n\n readAll: Effect.fnUntraced(function* (threadId) {\n const all: Array<CanonicalRecordEnvelope> = [];\n let after: CanonicalSequence | undefined;\n\n for (;;) {\n const page = yield* readPage(threadId, { afterSequence: after, limit: 1_024 });\n\n all.push(...page);\n const last = page.at(-1);\n\n if (page.length < 1_024 || last === undefined) return all;\n after = last.sequence;\n }\n }),\n\n abort: Effect.fnUntraced(function* (threadId, command) {\n const encoded = yield* encodeAbortCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`abort command encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(threadId, \"abort\", encoded);\n\n const recorded = yield* expect(\n threadId,\n \"abort\",\n AbortRecorded,\n ClientAbortHostFailure,\n )(response);\n\n return recorded.intent;\n }),\n\n resolveApproval: Effect.fnUntraced(function* (threadId, command) {\n const encoded = yield* encodeApprovalDecisionCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`approval command encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(threadId, \"resolveApproval\", encoded);\n\n const recorded = yield* expect(\n threadId,\n \"resolveApproval\",\n ApprovalRecorded,\n ClientApprovalHostFailure,\n )(response);\n\n return recorded.intent;\n }),\n\n resolveUnknown: Effect.fnUntraced(function* (threadId, command) {\n const encoded = yield* encodeUnknownResolutionCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`resolution command encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(threadId, \"resolveUnknown\", encoded);\n\n const recorded = yield* expect(\n threadId,\n \"resolveUnknown\",\n UnknownResolutionRecorded,\n ClientUnknownHostFailure,\n )(response);\n\n return recorded.intent;\n }),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,MAAa,wBAAoD,MAAM,OACrE,OAAO,QACP,OAAO,IAAI,aAAa;CACtB,MAAM,OAAO,OAAO,OAAO;CAC3B,MAAM,YAAY,OAAO,cAAc;CACvC,MAAM,c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