@yielded/agent 0.1.0-beta.173 → 0.1.0-beta.174

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 (226) hide show
  1. package/dist/{Admin-BX9ns28E.d.mts → Admin-BHmp2V9p.d.mts} +25 -16
  2. package/dist/{Agent-9aBoIi74.d.mts → Agent-B39jRnFv.d.mts} +2 -2
  3. package/dist/{Agent-0WvBWWbM.mjs → Agent-BiRbr73L.mjs} +7 -6
  4. package/dist/Agent-BiRbr73L.mjs.map +1 -0
  5. package/dist/{AgentRuntime-CQ-qcETl.mjs → AgentRuntime-B6qZlD3f.mjs} +199 -191
  6. package/dist/AgentRuntime-B6qZlD3f.mjs.map +1 -0
  7. package/dist/{AgentRuntime-BfP14534.d.mts → AgentRuntime-BD3ZHAMq.d.mts} +10 -10
  8. package/dist/{Digest-DCuPlhNk.mjs → Digest-EpeqWEdv.mjs} +41 -14
  9. package/dist/Digest-EpeqWEdv.mjs.map +1 -0
  10. package/dist/{DurableAgentRuntime-BAmSkWYr.mjs → DurableAgentRuntime-CBBjRNJN.mjs} +1447 -1424
  11. package/dist/DurableAgentRuntime-CBBjRNJN.mjs.map +1 -0
  12. package/dist/{EventSource-BwliwQz9.d.mts → EventSource-C9aaJaXT.d.mts} +2 -2
  13. package/dist/{MessageDelivery-B943ebI_.d.mts → MessageDelivery-BGDm-c46.d.mts} +42 -42
  14. package/dist/{Messaging-C_6OOg_s.d.mts → Messaging-SVu6rWV8.d.mts} +12 -6
  15. package/dist/{MessagingHost-B8oKM7AC.d.mts → MessagingHost-C6SOAcoG.d.mts} +2 -2
  16. package/dist/{Output-Dsx6k52t.d.mts → Output-CRamN1Fy.d.mts} +2 -2
  17. package/dist/{PreparedInputAdmission-CxSJSiTl.d.mts → PreparedInputAdmission-BvDqlgiP.d.mts} +3 -3
  18. package/dist/{RunContinuation-DHYNAQFi.mjs → RunContinuation-4ZATcVLB.mjs} +113 -56
  19. package/dist/RunContinuation-4ZATcVLB.mjs.map +1 -0
  20. package/dist/{RunContinuation-FHM7XPjq.d.mts → RunContinuation-CTJ1jGrO.d.mts} +6 -6
  21. package/dist/{RunJournal-kfKVxJj7.mjs → RunJournal-CNZqA3Ge.mjs} +33 -5
  22. package/dist/RunJournal-CNZqA3Ge.mjs.map +1 -0
  23. package/dist/{RunOptions-D8zxFIrZ.d.mts → RunOptions-Be77lKVZ.d.mts} +2 -2
  24. package/dist/{RunStorage-uqPxps09.mjs → RunStorage-BHjuuERI.mjs} +9 -6
  25. package/dist/RunStorage-BHjuuERI.mjs.map +1 -0
  26. package/dist/{Scheduling-CVyfXlBR.mjs → Scheduling-NG8slKdI.mjs} +11 -11
  27. package/dist/Scheduling-NG8slKdI.mjs.map +1 -0
  28. package/dist/{Subagent-vpffemql.mjs → Subagent-CTIpnzlB.mjs} +53 -40
  29. package/dist/Subagent-CTIpnzlB.mjs.map +1 -0
  30. package/dist/{Subagent-E6tvd7-k.d.mts → Subagent-DKhZA72u.d.mts} +19 -8
  31. package/dist/{SubagentHost-B6w2m-SI.d.mts → SubagentHost-D1xBgn9g.d.mts} +2 -2
  32. package/dist/{Subscription-DONig54Q.d.mts → Subscription-BNg9VCRl.d.mts} +2 -2
  33. package/dist/{SubscriptionInput-mJIRxWJM.d.mts → SubscriptionInput-BUoXv-_K.d.mts} +2 -2
  34. package/dist/{ThreadImport-DpHxjBrA.d.mts → ThreadImport-CMgzttvr.d.mts} +5 -5
  35. package/dist/{ThreadImport-DckUMEqJ.mjs → ThreadImport-CodYoJoa.mjs} +7 -7
  36. package/dist/ThreadImport-CodYoJoa.mjs.map +1 -0
  37. package/dist/{ThreadStore-CEekRa80.mjs → ThreadStore-59uDGXul.mjs} +163 -84
  38. package/dist/ThreadStore-59uDGXul.mjs.map +1 -0
  39. package/dist/{ThreadTransfer-B4gTQLIl.mjs → ThreadTransfer-3jigUl3g.mjs} +3 -3
  40. package/dist/{ThreadTransfer-B4gTQLIl.mjs.map → ThreadTransfer-3jigUl3g.mjs.map} +1 -1
  41. package/dist/{WorkerAdmission-DFVbbVh2.mjs → WorkerAdmission-DDYJdOsU.mjs} +4 -4
  42. package/dist/{WorkerAdmission-DFVbbVh2.mjs.map → WorkerAdmission-DDYJdOsU.mjs.map} +1 -1
  43. package/dist/{agent-registration-ByMZ_cK5.mjs → agent-registration-DRbyhAu-.mjs} +69 -56
  44. package/dist/agent-registration-DRbyhAu-.mjs.map +1 -0
  45. package/dist/capabilities/Approval.mjs +2 -2
  46. package/dist/capabilities/Approval.mjs.map +1 -1
  47. package/dist/capabilities/BrowserUse.d.mts +102 -1867
  48. package/dist/capabilities/BrowserUse.mjs +74 -798
  49. package/dist/capabilities/BrowserUse.mjs.map +1 -1
  50. package/dist/capabilities/Budget.mjs +3 -1
  51. package/dist/capabilities/Budget.mjs.map +1 -1
  52. package/dist/capabilities/CodeMode.d.mts +1 -1
  53. package/dist/capabilities/CodeMode.mjs +16 -9
  54. package/dist/capabilities/CodeMode.mjs.map +1 -1
  55. package/dist/capabilities/Commands.d.mts +1 -1
  56. package/dist/capabilities/McpClient.mjs +1 -1
  57. package/dist/capabilities/McpClient.mjs.map +1 -1
  58. package/dist/capabilities/Messaging.d.mts +1 -1
  59. package/dist/capabilities/Messaging.mjs +4 -4
  60. package/dist/capabilities/Messaging.mjs.map +1 -1
  61. package/dist/capabilities/ModelContext.mjs +7 -5
  62. package/dist/capabilities/ModelContext.mjs.map +1 -1
  63. package/dist/capabilities/Redaction.mjs +49 -19
  64. package/dist/capabilities/Redaction.mjs.map +1 -1
  65. package/dist/capabilities/RunHooks.d.mts +1 -1
  66. package/dist/capabilities/RunHooks.mjs +1 -1
  67. package/dist/capabilities/RunHooks.mjs.map +1 -1
  68. package/dist/capabilities/Subagent.d.mts +1 -1
  69. package/dist/capabilities/Subagent.mjs +1 -1
  70. package/dist/capabilities/SubagentReservations.mjs +3 -1
  71. package/dist/capabilities/SubagentReservations.mjs.map +1 -1
  72. package/dist/capabilities/WebCapture.mjs.map +1 -1
  73. package/dist/capabilities/WebSearch.mjs +7 -7
  74. package/dist/capabilities/WebSearch.mjs.map +1 -1
  75. package/dist/core/Agent.d.mts +1 -1
  76. package/dist/core/Agent.mjs +1 -1
  77. package/dist/core/AgentUpdates.mjs +8 -8
  78. package/dist/core/AgentUpdates.mjs.map +1 -1
  79. package/dist/core/Thread.mjs +1 -1
  80. package/dist/core/Thread.mjs.map +1 -1
  81. package/dist/core/Usage.mjs +2 -2
  82. package/dist/core/Usage.mjs.map +1 -1
  83. package/dist/durable/Admin.d.mts +1 -1
  84. package/dist/durable/AgentRegistration.d.mts +1 -1
  85. package/dist/durable/AgentRegistration.mjs +1 -1
  86. package/dist/durable/Certification.d.mts +1 -1
  87. package/dist/durable/CommittedActivity.d.mts +1 -1
  88. package/dist/durable/CommittedActivity.mjs +2 -2
  89. package/dist/durable/Digest.mjs +1 -1
  90. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  91. package/dist/durable/DurableAgentRuntime.mjs +2 -2
  92. package/dist/durable/EventSource.d.mts +1 -1
  93. package/dist/durable/EventSource.mjs +6 -6
  94. package/dist/durable/EventSource.mjs.map +1 -1
  95. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  96. package/dist/durable/LifecyclePublication.d.mts +1 -1
  97. package/dist/durable/LifecyclePublication.mjs +1 -1
  98. package/dist/durable/MessageDelivery.d.mts +1 -1
  99. package/dist/durable/MessageDelivery.mjs +1 -1
  100. package/dist/durable/MessageDeliveryStoreConformance.d.mts +2 -2
  101. package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
  102. package/dist/durable/PersistentHistory.d.mts +1 -1
  103. package/dist/durable/PersistentHistory.mjs +3 -3
  104. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  105. package/dist/durable/RecordFormat.mjs +2 -2
  106. package/dist/durable/RecordFormat.mjs.map +1 -1
  107. package/dist/durable/Recovery.d.mts +1 -1
  108. package/dist/durable/RunContinuation.d.mts +2 -2
  109. package/dist/durable/RunContinuation.mjs +2 -2
  110. package/dist/durable/RunJournal.d.mts +1 -1
  111. package/dist/durable/RunJournal.mjs +1 -1
  112. package/dist/durable/RunStorage.d.mts +1 -1
  113. package/dist/durable/RunStorage.mjs +1 -1
  114. package/dist/durable/Scheduling.d.mts +1 -1
  115. package/dist/durable/Scheduling.mjs +1 -1
  116. package/dist/durable/SettlementPublisher.d.mts +1 -1
  117. package/dist/durable/SettlementPublisher.mjs +2 -2
  118. package/dist/durable/SubmissionLedger.d.mts +1 -1
  119. package/dist/durable/SubmissionLedger.mjs +5 -1
  120. package/dist/durable/SubmissionLedger.mjs.map +1 -1
  121. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  122. package/dist/durable/SubmissionLedgerConformance.mjs +4 -4
  123. package/dist/durable/SubmissionStatus.d.mts +1 -1
  124. package/dist/durable/Subscription.d.mts +1 -1
  125. package/dist/durable/SubscriptionInput.d.mts +1 -1
  126. package/dist/durable/SubscriptionInput.mjs +3 -3
  127. package/dist/durable/SubscriptionInput.mjs.map +1 -1
  128. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  129. package/dist/durable/SubscriptionStoreConformance.mjs +2 -2
  130. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -1
  131. package/dist/durable/SubscriptionTools.d.mts +2 -2
  132. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  133. package/dist/durable/Subscriptions.d.mts +5 -5
  134. package/dist/durable/Subscriptions.mjs +2 -2
  135. package/dist/durable/Subscriptions.mjs.map +1 -1
  136. package/dist/durable/ThreadArchiveRange.d.mts +1 -1
  137. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  138. package/dist/durable/ThreadContextHistory.mjs +1 -1
  139. package/dist/durable/ThreadImport.d.mts +1 -1
  140. package/dist/durable/ThreadImport.mjs +1 -1
  141. package/dist/durable/ThreadInvariants.d.mts +3 -3
  142. package/dist/durable/ThreadInvariants.mjs +4 -4
  143. package/dist/durable/ThreadInvariants.mjs.map +1 -1
  144. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  145. package/dist/durable/ThreadReader.d.mts +1 -1
  146. package/dist/durable/ThreadReader.mjs +1 -1
  147. package/dist/durable/ThreadStore.d.mts +1 -1
  148. package/dist/durable/ThreadStore.mjs +1 -1
  149. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  150. package/dist/durable/ThreadStoreConformance.mjs +3 -3
  151. package/dist/durable/ThreadTransfer.d.mts +1 -1
  152. package/dist/durable/ThreadTransfer.mjs +1 -1
  153. package/dist/durable/ThreadWork.d.mts +1 -1
  154. package/dist/durable/ThreadWork.mjs +4 -4
  155. package/dist/durable/ThreadWork.mjs.map +1 -1
  156. package/dist/durable/WorkerAdmission.d.mts +1 -1
  157. package/dist/durable/WorkerAdmission.mjs +1 -1
  158. package/dist/durable/WorkerHost.d.mts +2 -2
  159. package/dist/engine/AgentRuntime.d.mts +1 -1
  160. package/dist/engine/AgentRuntime.mjs +1 -1
  161. package/dist/engine/MessagingHost.d.mts +1 -1
  162. package/dist/engine/Output.d.mts +1 -1
  163. package/dist/engine/RunOptions.d.mts +1 -1
  164. package/dist/engine/SubagentHost.d.mts +1 -1
  165. package/dist/index.d.mts +19 -19
  166. package/dist/index.mjs +14 -14
  167. package/dist/{run-context-reader-OcsZr4bk.d.mts → run-context-reader-CC7ZD95F.d.mts} +2 -2
  168. package/package.json +1 -1
  169. package/src/capabilities/Approval.ts +58 -60
  170. package/src/capabilities/BrowserUse.ts +89 -944
  171. package/src/capabilities/Budget.ts +8 -1
  172. package/src/capabilities/CodeMode.ts +57 -33
  173. package/src/capabilities/McpClient.ts +2 -2
  174. package/src/capabilities/Messaging.ts +51 -55
  175. package/src/capabilities/ModelContext.ts +5 -2
  176. package/src/capabilities/Redaction.ts +64 -34
  177. package/src/capabilities/RunHooks.ts +52 -55
  178. package/src/capabilities/Subagent.ts +33 -33
  179. package/src/capabilities/SubagentReservations.ts +9 -1
  180. package/src/capabilities/WebCapture.ts +6 -0
  181. package/src/capabilities/WebSearch.ts +10 -7
  182. package/src/capabilities/internal/subagent-background.ts +202 -158
  183. package/src/core/Agent.ts +11 -6
  184. package/src/core/AgentUpdates.ts +8 -8
  185. package/src/core/Thread.ts +9 -10
  186. package/src/core/Usage.ts +7 -8
  187. package/src/core/internal/agent-updates.ts +1 -0
  188. package/src/durable/DurableAgentRuntime.ts +645 -625
  189. package/src/durable/EventSource.ts +15 -9
  190. package/src/durable/RecordFormat.ts +5 -3
  191. package/src/durable/RunContinuation.ts +233 -81
  192. package/src/durable/RunJournal.ts +10 -9
  193. package/src/durable/RunStorage.ts +122 -124
  194. package/src/durable/Scheduling.ts +639 -651
  195. package/src/durable/SubmissionLedger.ts +4 -0
  196. package/src/durable/SubscriptionInput.ts +5 -3
  197. package/src/durable/SubscriptionStoreConformance.ts +23 -23
  198. package/src/durable/Subscriptions.ts +18 -19
  199. package/src/durable/ThreadImport.ts +18 -19
  200. package/src/durable/ThreadInvariants.ts +2 -1
  201. package/src/durable/ThreadStore.ts +215 -111
  202. package/src/durable/ThreadWork.ts +1 -2
  203. package/src/durable/internal/StorageOwner.ts +10 -4
  204. package/src/durable/internal/agent-registration.ts +96 -89
  205. package/src/durable/internal/canonical-json.ts +61 -20
  206. package/src/durable/internal/prompt-history-cache.ts +13 -4
  207. package/src/durable/internal/record-encoding.ts +120 -64
  208. package/src/durable/internal/schedule-time.ts +6 -6
  209. package/src/durable/internal/usage-totals.ts +38 -0
  210. package/src/durable/internal/worker-host.ts +69 -74
  211. package/src/engine/internal/agent-runtime.ts +1067 -1018
  212. package/src/engine/internal/provisional-text.ts +12 -10
  213. package/src/engine/internal/tool-exposure.ts +22 -18
  214. package/src/engine/internal/tool-telemetry.ts +12 -7
  215. package/dist/Agent-0WvBWWbM.mjs.map +0 -1
  216. package/dist/AgentRuntime-CQ-qcETl.mjs.map +0 -1
  217. package/dist/Digest-DCuPlhNk.mjs.map +0 -1
  218. package/dist/DurableAgentRuntime-BAmSkWYr.mjs.map +0 -1
  219. package/dist/RunContinuation-DHYNAQFi.mjs.map +0 -1
  220. package/dist/RunJournal-kfKVxJj7.mjs.map +0 -1
  221. package/dist/RunStorage-uqPxps09.mjs.map +0 -1
  222. package/dist/Scheduling-CVyfXlBR.mjs.map +0 -1
  223. package/dist/Subagent-vpffemql.mjs.map +0 -1
  224. package/dist/ThreadImport-DckUMEqJ.mjs.map +0 -1
  225. package/dist/ThreadStore-CEekRa80.mjs.map +0 -1
  226. package/dist/agent-registration-ByMZ_cK5.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"Thread.mjs","names":[],"sources":["../../src/core/Thread.ts"],"sourcesContent":["import type { Scope } from \"effect\";\nimport * as Prompt from \"effect/ai/Prompt\";\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 * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport { ThreadId, RunId } from \"./Identifiers.ts\";\nimport { utf8ByteLength } from \"./internal/utf8.ts\";\n\n/** Bound applied to one text projection before it can enter a model context. */\nexport const ThreadText = Schema.String.check(Schema.isMaxLength(64 * 1024));\nconst MAX_MESSAGE_CONTENT_BYTES = 4 * 1024 * 1024;\nconst MAX_THREADS = 256;\nconst MAX_STORE_CONTENT_BYTES = 64 * 1024 * 1024;\n\n/** One append-only native Effect AI message in a conversation. */\nexport class ThreadMessage extends Schema.Class<ThreadMessage>(\n \"@effect-agent/capabilities/ThreadMessage\",\n)({\n threadId: ThreadId,\n sequence: Schema.Natural,\n runId: Schema.optionalKey(RunId),\n message: Prompt.Message,\n encodedBytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_MESSAGE_CONTENT_BYTES)),\n timestamp: Schema.DateTimeUtcFromString,\n}) {}\n\n/** An identified, ordered conversation snapshot. Storage and execution recovery are separate concerns. */\nexport class Thread extends Schema.Class<Thread>(\"@effect-agent/capabilities/ThreadSnapshot\")({\n version: Schema.Literal(1),\n threadId: ThreadId,\n nextSequence: Schema.Natural,\n contentBytes: Schema.Natural,\n messages: Schema.Array(ThreadMessage),\n}) {}\n\n/** Portable conversation snapshot. Its format is independent of the durable execution journal. */\nexport class ThreadExport extends Schema.Class<ThreadExport>(\n \"@effect-agent/capabilities/ThreadExport\",\n)({\n format: Schema.Literal(\"effect-agent/ephemeral-thread@1\"),\n exportedAt: Schema.DateTimeUtcFromString,\n snapshot: Thread,\n}) {}\n\n/** Native message accepted by the append-only thread. */\nexport class ThreadAppend extends Schema.Class<ThreadAppend>(\n \"@effect-agent/capabilities/ThreadAppend\",\n)({\n runId: Schema.optionalKey(RunId),\n message: Prompt.Message,\n}) {}\n\n/** The requested Thread has not been created in this store. */\nexport class ThreadNotFound extends Schema.TaggedError<ThreadNotFound>()(\"ThreadNotFound\", {\n threadId: ThreadId,\n}) {}\n\n/** A message or the process-local host exceeded capacity; no bound counts a Thread's lifetime. */\nexport class ThreadLimitExceeded extends Schema.TaggedError<ThreadLimitExceeded>()(\n \"ThreadLimitExceeded\",\n {\n threadId: ThreadId,\n limit: Schema.Literals([\"content-bytes\", \"threads\", \"store-content-bytes\"]),\n limitValue: Schema.Natural,\n observedValue: Schema.Natural,\n },\n) {}\n\n/** Engine history was not an append-only extension of the official snapshot. */\nexport class ThreadHistoryDiverged extends Schema.TaggedError<ThreadHistoryDiverged>()(\n \"ThreadHistoryDiverged\",\n { threadId: ThreadId, message: Schema.String },\n) {}\n\n/** Native Prompt encoding failed before a bounded state mutation. */\nexport class ThreadEncodingError extends Schema.TaggedError<ThreadEncodingError>()(\n \"ThreadEncodingError\",\n { threadId: ThreadId, message: Schema.String },\n) {}\n\n/** A scoped view cannot access another owner's history or be used after closure. */\nexport class ThreadOwnershipError extends Schema.TaggedError<ThreadOwnershipError>()(\n \"ThreadOwnershipError\",\n { threadId: ThreadId, reason: Schema.Literals([\"closed\", \"foreign\"]), message: Schema.String },\n) {}\n\nexport type ThreadError =\n | ThreadNotFound\n | ThreadLimitExceeded\n | ThreadHistoryDiverged\n | ThreadEncodingError\n | ThreadOwnershipError;\n\n/** Reconstruct exact Effect AI Prompt history, including tools, reasoning, files, and options. */\nexport const toPrompt = (snapshot: Thread): Prompt.Prompt =>\n Prompt.fromMessages(snapshot.messages.map((entry) => entry.message));\n\n/**\n * Process-local state for conversation history. Updates remain visible even\n * when a Run later fails; this service has no successful-Run commit boundary or durable recovery.\n * ThreadHistory.layer uses this store for ordinary Runs and interactive history.\n * Scope closure releases all in-memory state.\n */\ninterface StoreService {\n /**\n * Acquire an isolated ownership view over this same bounded store. Newly created Threads\n * belong to the supplied Scope; closing it releases only that view's Threads and bytes.\n * Supplied by layerMemory; custom stores may omit this capability.\n * The view rejects foreign IDs and all access after closure. Keep its Scope open through\n * all users, including streams, child Runs, snapshots and history hooks.\n */\n readonly scoped?: Effect.Effect<StoreService, never, Scope.Scope>;\n readonly create: (\n threadId: ThreadId,\n ) => Effect.Effect<Thread, ThreadLimitExceeded | ThreadOwnershipError>;\n readonly append: (\n threadId: ThreadId,\n message: ThreadAppend,\n ) => Effect.Effect<\n Thread,\n ThreadNotFound | ThreadLimitExceeded | ThreadEncodingError | ThreadOwnershipError\n >;\n /**\n * Record an engine-emitted full history only when it is an append-only\n * extension of the exact official Prompt already stored. The entire\n * suffix commits in one transaction or not at all: concurrent writers are\n * serialized, a writer whose history no longer extends the committed\n * official history fails with ThreadHistoryDiverged, and a limit\n * failure inside the suffix records nothing. Earlier updates remain committed if the Run\n * later fails or is interrupted; this transaction covers one update, not the whole Run.\n */\n readonly recordHistory: (\n threadId: ThreadId,\n runId: RunId,\n history: Prompt.Prompt,\n ) => Effect.Effect<Thread, ThreadError>;\n readonly snapshot: (\n threadId: ThreadId,\n ) => Effect.Effect<Thread, ThreadNotFound | ThreadOwnershipError>;\n readonly export: (\n threadId: ThreadId,\n ) => Effect.Effect<ThreadExport, ThreadNotFound | ThreadOwnershipError>;\n}\n\n/** Process-local conversation store supplied by layerMemory. */\nexport class Store extends Context.Service<Store, StoreService>()(\n \"@effect-agent/capabilities/EphemeralThreads\",\n) {}\n\nconst encodeMessage = (\n threadId: ThreadId,\n message: Prompt.Message,\n): Effect.Effect<string, ThreadEncodingError> =>\n Schema.encodeEffect(Prompt.Message)(message).pipe(\n Effect.map((encoded) => JSON.stringify(encoded)),\n Effect.mapError((error) =>\n ThreadEncodingError.make({\n threadId,\n message: `Could not encode native Effect AI message: ${error.message}`,\n }),\n ),\n );\n\ninterface Owner {\n closed: boolean;\n readonly parent?: Owner;\n}\n\ninterface Entry {\n readonly snapshot: Thread;\n readonly owner: Owner;\n}\n\ninterface State {\n readonly threads: ReadonlyMap<ThreadId, Entry>;\n readonly contentBytes: number;\n}\n\nconst belongsTo = (owner: Owner, ancestor: Owner): boolean => {\n for (let current: Owner | undefined = owner; current !== undefined; current = current.parent) {\n if (current === ancestor) return true;\n }\n\n return false;\n};\n\nconst access = (state: State, owner: Owner, threadId: ThreadId) => {\n for (let current: Owner | undefined = owner; current !== undefined; current = current.parent) {\n if (current.closed) {\n return Effect.fail(\n ThreadOwnershipError.make({\n threadId,\n reason: \"closed\",\n message: \"The in-memory conversation owner is closed\",\n }),\n );\n }\n }\n const entry = state.threads.get(threadId);\n\n return entry !== undefined && entry.owner !== owner\n ? Effect.fail(\n ThreadOwnershipError.make({\n threadId,\n reason: \"foreign\",\n message: \"The Thread belongs to another in-memory conversation owner\",\n }),\n )\n : Effect.succeed(entry?.snapshot);\n};\n\nconst findSnapshot = Effect.fnUntraced(function* (state: State, owner: Owner, threadId: ThreadId) {\n const snapshot = yield* access(state, owner, threadId);\n\n return snapshot === undefined ? yield* ThreadNotFound.make({ threadId }) : snapshot;\n});\n\nconst put = (state: State, owner: Owner, snapshot: Thread): State => ({\n threads: new Map(state.threads).set(snapshot.threadId, { snapshot, owner }),\n contentBytes:\n state.contentBytes +\n snapshot.contentBytes -\n (state.threads.get(snapshot.threadId)?.snapshot.contentBytes ?? 0),\n});\n\nconst messageSize = (threadId: ThreadId, encoded: string) => {\n const observedValue = utf8ByteLength(encoded);\n\n return observedValue <= MAX_MESSAGE_CONTENT_BYTES\n ? Effect.succeed(observedValue)\n : Effect.fail(\n ThreadLimitExceeded.make({\n threadId,\n limit: \"content-bytes\",\n limitValue: MAX_MESSAGE_CONTENT_BYTES,\n observedValue,\n }),\n );\n};\n\nconst appendEncoded = Effect.fnUntraced(function* (\n state: State,\n owner: Owner,\n current: Thread,\n append: ThreadAppend,\n encoded: string,\n timestamp: DateTime.Utc,\n) {\n const threadId = current.threadId;\n\n const messageBytes = yield* messageSize(threadId, encoded);\n const contentBytes = current.contentBytes + messageBytes;\n const storeBytes = state.contentBytes + messageBytes;\n\n if (storeBytes > MAX_STORE_CONTENT_BYTES) {\n return yield* ThreadLimitExceeded.make({\n threadId,\n limit: \"store-content-bytes\",\n limitValue: MAX_STORE_CONTENT_BYTES,\n observedValue: storeBytes,\n });\n }\n\n const message = ThreadMessage.make({\n threadId,\n sequence: current.nextSequence,\n ...(append.runId === undefined ? {} : { runId: append.runId }),\n message: append.message,\n encodedBytes: messageBytes,\n timestamp,\n });\n\n const next = Thread.make({\n version: current.version,\n threadId: current.threadId,\n nextSequence: current.nextSequence + 1,\n contentBytes,\n messages: [...current.messages, message],\n });\n\n return [next, put(state, owner, next)] as const;\n});\n\n/** In-memory storage shared for the consumer's Scope; it does not survive process loss. */\nexport const layerMemory = Layer.effect(\n Store,\n Effect.gen(function* () {\n const state = yield* SynchronizedRef.make<State>({ threads: new Map(), contentBytes: 0 });\n const root: Owner = { closed: false };\n\n const release = (owner: Owner) =>\n SynchronizedRef.update(state, (current) => {\n owner.closed = true;\n const threads = new Map(current.threads);\n let contentBytes = current.contentBytes;\n\n for (const [id, entry] of threads) {\n if (belongsTo(entry.owner, owner)) {\n threads.delete(id);\n contentBytes -= entry.snapshot.contentBytes;\n }\n }\n\n return { threads, contentBytes };\n });\n\n yield* Effect.addFinalizer(() => release(root));\n\n const view = (owner: Owner): StoreService => ({\n scoped: Effect.acquireRelease(\n Effect.sync((): Owner => ({ closed: false, parent: owner })),\n release,\n ).pipe(Effect.map(view)),\n create: (threadId) =>\n SynchronizedRef.modifyEffect(\n state,\n Effect.fnUntraced(function* (threads) {\n const existing = yield* access(threads, owner, threadId);\n\n if (existing !== undefined) return [existing, threads] as const;\n if (threads.threads.size >= MAX_THREADS) {\n return yield* ThreadLimitExceeded.make({\n threadId,\n limit: \"threads\",\n limitValue: MAX_THREADS,\n observedValue: threads.threads.size + 1,\n });\n }\n\n const created = Thread.make({\n version: 1,\n threadId,\n nextSequence: 0,\n contentBytes: 0,\n messages: [],\n });\n\n return [created, put(threads, owner, created)] as const;\n }),\n ),\n append: Effect.fnUntraced(function* (threadId, message) {\n const encoded = yield* encodeMessage(threadId, message.message);\n const timestamp = DateTime.toUtc(DateTime.makeUnsafe(yield* Clock.currentTimeMillis));\n\n return yield* SynchronizedRef.modifyEffect(\n state,\n Effect.fnUntraced(function* (threads) {\n const current = yield* findSnapshot(threads, owner, threadId);\n\n return yield* appendEncoded(threads, owner, current, message, encoded, timestamp);\n }),\n );\n }),\n recordHistory: Effect.fnUntraced(function* (threadId, historyRunId, history) {\n const incoming = yield* Effect.forEach(history.content, (message) =>\n encodeMessage(threadId, message).pipe(Effect.map((encoded) => ({ message, encoded }))),\n );\n\n // Publish the complete suffix only after verification and every bounded append succeed.\n return yield* SynchronizedRef.modifyEffect(\n state,\n Effect.fnUntraced(function* (threads) {\n const current = yield* findSnapshot(threads, owner, threadId);\n\n const currentEncoded = yield* Effect.forEach(current.messages, (entry) =>\n encodeMessage(threadId, entry.message),\n );\n\n if (\n incoming.length < currentEncoded.length ||\n currentEncoded.some((encoded, index) => encoded !== incoming[index]?.encoded)\n ) {\n return yield* ThreadHistoryDiverged.make({\n threadId,\n message: \"Engine history is not an append-only extension of official history\",\n });\n }\n const timestamp = DateTime.toUtc(DateTime.makeUnsafe(yield* Clock.currentTimeMillis));\n\n if (incoming.length === currentEncoded.length) return [current, threads] as const;\n\n const messages = [...current.messages];\n let contentBytes = current.contentBytes;\n let storeBytes = threads.contentBytes;\n let nextSequence = current.nextSequence;\n\n for (const entry of incoming.slice(currentEncoded.length)) {\n const append = ThreadAppend.make({ runId: historyRunId, message: entry.message });\n\n const messageBytes = yield* messageSize(threadId, entry.encoded);\n\n contentBytes += messageBytes;\n storeBytes += messageBytes;\n if (storeBytes > MAX_STORE_CONTENT_BYTES) {\n return yield* ThreadLimitExceeded.make({\n threadId,\n limit: \"store-content-bytes\",\n limitValue: MAX_STORE_CONTENT_BYTES,\n observedValue: storeBytes,\n });\n }\n messages.push(\n ThreadMessage.make({\n threadId,\n sequence: nextSequence,\n ...(append.runId === undefined ? {} : { runId: append.runId }),\n message: append.message,\n encodedBytes: messageBytes,\n timestamp,\n }),\n );\n nextSequence += 1;\n }\n\n const snapshot = Thread.make({\n version: current.version,\n threadId,\n nextSequence,\n contentBytes,\n messages,\n });\n\n return [snapshot, put(threads, owner, snapshot)] as const;\n }),\n );\n }),\n snapshot: (threadId) =>\n SynchronizedRef.get(state).pipe(\n Effect.flatMap((all) => findSnapshot(all, owner, threadId)),\n ),\n export: (threadId) =>\n Effect.gen(function* () {\n const snapshot = yield* findSnapshot(yield* SynchronizedRef.get(state), owner, threadId);\n\n return ThreadExport.make({\n format: \"effect-agent/ephemeral-thread@1\",\n exportedAt: DateTime.toUtc(DateTime.makeUnsafe(yield* Clock.currentTimeMillis)),\n snapshot,\n });\n }),\n });\n\n return view(root);\n }),\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,MAAa,aAAa,OAAO,OAAO,MAAM,OAAO,YAAY,KAAS,CAAC;AAC3E,MAAM,4BAA4B;AAClC,MAAM,cAAc;AACpB,MAAM,0BAA0B;;AAGhC,IAAa,gBAAb,cAAmC,OAAO,MACxC,0CACF,CAAC,CAAC;CACA,UAAU;CACV,UAAU,OAAO;CACjB,OAAO,OAAO,YAAY,KAAK;CAC/B,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MACA,OAAO;MACP,YAAY;MACZ,eAAe;KACjB,CAAC;KAEH,SAAS,KACP,cAAc,KAAK;MACjB;MACA,UAAU;MACV,GAAI,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,OAAO,MAAM;MAC5D,SAAS,OAAO;MAChB,cAAc;MACd;KACF,CAAC,CACH;KACA,gBAAgB;IAClB;IAEA,MAAM,WAAW,OAAO,KAAK;KAC3B,SAAS,QAAQ;KACjB;KACA;KACA;KACA;IACF,CAAC;IAED,OAAO,CAAC,UAAU,IAAI,SAAS,OAAO,QAAQ,CAAC;GACjD,CAAC,CACH;EACF,CAAC;EACD,WAAW,aACT,gBAAgB,IAAI,KAAK,CAAC,CAAC,KACzB,OAAO,SAAS,QAAQ,aAAa,KAAK,OAAO,QAAQ,CAAC,CAC5D;EACF,SAAS,aACP,OAAO,IAAI,aAAa;GACtB,MAAM,WAAW,OAAO,aAAa,OAAO,gBAAgB,IAAI,KAAK,GAAG,OAAO,QAAQ;GAEvF,OAAO,aAAa,KAAK;IACvB,QAAQ;IACR,YAAY,SAAS,MAAM,SAAS,WAAW,OAAO,MAAM,iBAAiB,CAAC;IAC9E;GACF,CAAC;EACH,CAAC;CACL;CAEA,OAAO,KAAK,IAAI;AAClB,CAAC,CACH"}
1
+ {"version":3,"file":"Thread.mjs","names":[],"sources":["../../src/core/Thread.ts"],"sourcesContent":["import type { Scope } from \"effect\";\nimport * as Prompt from \"effect/ai/Prompt\";\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 * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport { ThreadId, RunId } from \"./Identifiers.ts\";\nimport { utf8ByteLength } from \"./internal/utf8.ts\";\n\n/** Bound applied to one text projection before it can enter a model context. */\nexport const ThreadText = Schema.String.check(Schema.isMaxLength(64 * 1024));\nconst MAX_MESSAGE_CONTENT_BYTES = 4 * 1024 * 1024;\nconst MAX_THREADS = 256;\nconst MAX_STORE_CONTENT_BYTES = 64 * 1024 * 1024;\n\n/** One append-only native Effect AI message in a conversation. */\nexport class ThreadMessage extends Schema.Class<ThreadMessage>(\n \"@effect-agent/capabilities/ThreadMessage\",\n)({\n threadId: ThreadId,\n sequence: Schema.Natural,\n runId: Schema.optionalKey(RunId),\n message: Prompt.Message,\n encodedBytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_MESSAGE_CONTENT_BYTES)),\n timestamp: Schema.DateTimeUtcFromString,\n}) {}\n\n/** An identified, ordered conversation snapshot. Storage and execution recovery are separate concerns. */\nexport class Thread extends Schema.Class<Thread>(\"@effect-agent/capabilities/ThreadSnapshot\")({\n version: Schema.Literal(1),\n threadId: ThreadId,\n nextSequence: Schema.Natural,\n contentBytes: Schema.Natural,\n messages: Schema.Array(ThreadMessage),\n}) {}\n\n/** Portable conversation snapshot. Its format is independent of the durable execution journal. */\nexport class ThreadExport extends Schema.Class<ThreadExport>(\n \"@effect-agent/capabilities/ThreadExport\",\n)({\n format: Schema.Literal(\"effect-agent/ephemeral-thread@1\"),\n exportedAt: Schema.DateTimeUtcFromString,\n snapshot: Thread,\n}) {}\n\n/** Native message accepted by the append-only thread. */\nexport class ThreadAppend extends Schema.Class<ThreadAppend>(\n \"@effect-agent/capabilities/ThreadAppend\",\n)({\n runId: Schema.optionalKey(RunId),\n message: Prompt.Message,\n}) {}\n\n/** The requested Thread has not been created in this store. */\nexport class ThreadNotFound extends Schema.TaggedError<ThreadNotFound>()(\"ThreadNotFound\", {\n threadId: ThreadId,\n}) {}\n\n/** A message or the process-local host exceeded capacity; no bound counts a Thread's lifetime. */\nexport class ThreadLimitExceeded extends Schema.TaggedError<ThreadLimitExceeded>()(\n \"ThreadLimitExceeded\",\n {\n threadId: ThreadId,\n limit: Schema.Literals([\"content-bytes\", \"threads\", \"store-content-bytes\"]),\n limitValue: Schema.Natural,\n observedValue: Schema.Natural,\n },\n) {}\n\n/** Engine history was not an append-only extension of the official snapshot. */\nexport class ThreadHistoryDiverged extends Schema.TaggedError<ThreadHistoryDiverged>()(\n \"ThreadHistoryDiverged\",\n { threadId: ThreadId, message: Schema.String },\n) {}\n\n/** Native Prompt encoding failed before a bounded state mutation. */\nexport class ThreadEncodingError extends Schema.TaggedError<ThreadEncodingError>()(\n \"ThreadEncodingError\",\n { threadId: ThreadId, message: Schema.String },\n) {}\n\n/** A scoped view cannot access another owner's history or be used after closure. */\nexport class ThreadOwnershipError extends Schema.TaggedError<ThreadOwnershipError>()(\n \"ThreadOwnershipError\",\n { threadId: ThreadId, reason: Schema.Literals([\"closed\", \"foreign\"]), message: Schema.String },\n) {}\n\nexport type ThreadError =\n | ThreadNotFound\n | ThreadLimitExceeded\n | ThreadHistoryDiverged\n | ThreadEncodingError\n | ThreadOwnershipError;\n\n/** Reconstruct exact Effect AI Prompt history, including tools, reasoning, files, and options. */\nexport const toPrompt = (snapshot: Thread): Prompt.Prompt =>\n Prompt.fromMessages(snapshot.messages.map((entry) => entry.message));\n\n/**\n * Process-local state for conversation history. Updates remain visible even\n * when a Run later fails; this service has no successful-Run commit boundary or durable recovery.\n * ThreadHistory.layer uses this store for ordinary Runs and interactive history.\n * Scope closure releases all in-memory state.\n */\ninterface StoreService {\n /**\n * Acquire an isolated ownership view over this same bounded store. Newly created Threads\n * belong to the supplied Scope; closing it releases only that view's Threads and bytes.\n * Supplied by layerMemory; custom stores may omit this capability.\n * The view rejects foreign IDs and all access after closure. Keep its Scope open through\n * all users, including streams, child Runs, snapshots and history hooks.\n */\n readonly scoped?: Effect.Effect<StoreService, never, Scope.Scope>;\n readonly create: (\n threadId: ThreadId,\n ) => Effect.Effect<Thread, ThreadLimitExceeded | ThreadOwnershipError>;\n readonly append: (\n threadId: ThreadId,\n message: ThreadAppend,\n ) => Effect.Effect<\n Thread,\n ThreadNotFound | ThreadLimitExceeded | ThreadEncodingError | ThreadOwnershipError\n >;\n /**\n * Record an engine-emitted full history only when it is an append-only\n * extension of the exact official Prompt already stored. The entire\n * suffix commits in one transaction or not at all: concurrent writers are\n * serialized, a writer whose history no longer extends the committed\n * official history fails with ThreadHistoryDiverged, and a limit\n * failure inside the suffix records nothing. Earlier updates remain committed if the Run\n * later fails or is interrupted; this transaction covers one update, not the whole Run.\n */\n readonly recordHistory: (\n threadId: ThreadId,\n runId: RunId,\n history: Prompt.Prompt,\n ) => Effect.Effect<Thread, ThreadError>;\n readonly snapshot: (\n threadId: ThreadId,\n ) => Effect.Effect<Thread, ThreadNotFound | ThreadOwnershipError>;\n readonly export: (\n threadId: ThreadId,\n ) => Effect.Effect<ThreadExport, ThreadNotFound | ThreadOwnershipError>;\n}\n\n/** Process-local conversation store supplied by layerMemory. */\nexport class Store extends Context.Service<Store, StoreService>()(\n \"@effect-agent/capabilities/EphemeralThreads\",\n) {}\n\nconst encodeMessage = (\n threadId: ThreadId,\n message: Prompt.Message,\n): Effect.Effect<string, ThreadEncodingError> =>\n Schema.encodeEffect(Prompt.Message)(message).pipe(\n Effect.map((encoded) => JSON.stringify(encoded)),\n Effect.mapError((error) =>\n ThreadEncodingError.make({\n threadId,\n message: `Could not encode native Effect AI message: ${error.message}`,\n }),\n ),\n );\n\ninterface Owner {\n closed: boolean;\n readonly parent?: Owner;\n}\n\ninterface Entry {\n readonly snapshot: Thread;\n readonly owner: Owner;\n}\n\ninterface State {\n readonly threads: ReadonlyMap<ThreadId, Entry>;\n readonly contentBytes: number;\n}\n\nconst belongsTo = (owner: Owner, ancestor: Owner): boolean => {\n for (let current: Owner | undefined = owner; current !== undefined; current = current.parent) {\n if (current === ancestor) return true;\n }\n\n return false;\n};\n\nconst access = (state: State, owner: Owner, threadId: ThreadId) => {\n for (let current: Owner | undefined = owner; current !== undefined; current = current.parent) {\n if (current.closed) {\n return Effect.fail(\n ThreadOwnershipError.make({\n threadId,\n reason: \"closed\",\n message: \"The in-memory conversation owner is closed\",\n }),\n );\n }\n }\n const entry = state.threads.get(threadId);\n\n return entry !== undefined && entry.owner !== owner\n ? Effect.fail(\n ThreadOwnershipError.make({\n threadId,\n reason: \"foreign\",\n message: \"The Thread belongs to another in-memory conversation owner\",\n }),\n )\n : Effect.succeed(entry?.snapshot);\n};\n\nconst findSnapshot = Effect.fnUntraced(function* (state: State, owner: Owner, threadId: ThreadId) {\n const snapshot = yield* access(state, owner, threadId);\n\n return snapshot === undefined ? yield* ThreadNotFound.make({ threadId }) : snapshot;\n});\n\nconst put = (state: State, owner: Owner, snapshot: Thread): State => ({\n threads: new Map(state.threads).set(snapshot.threadId, { snapshot, owner }),\n contentBytes:\n state.contentBytes +\n snapshot.contentBytes -\n (state.threads.get(snapshot.threadId)?.snapshot.contentBytes ?? 0),\n});\n\nconst messageSize = (threadId: ThreadId, encoded: string) => {\n const observedValue = utf8ByteLength(encoded);\n\n return observedValue <= MAX_MESSAGE_CONTENT_BYTES\n ? Effect.succeed(observedValue)\n : Effect.fail(\n ThreadLimitExceeded.make({\n threadId,\n limit: \"content-bytes\",\n limitValue: MAX_MESSAGE_CONTENT_BYTES,\n observedValue,\n }),\n );\n};\n\nconst appendEncoded = Effect.fnUntraced(function* (\n state: State,\n owner: Owner,\n current: Thread,\n append: ThreadAppend,\n encoded: string,\n timestamp: DateTime.Utc,\n) {\n const threadId = current.threadId;\n\n const messageBytes = yield* messageSize(threadId, encoded);\n const contentBytes = current.contentBytes + messageBytes;\n const storeBytes = state.contentBytes + messageBytes;\n\n if (storeBytes > MAX_STORE_CONTENT_BYTES) {\n return yield* ThreadLimitExceeded.make({\n threadId,\n limit: \"store-content-bytes\",\n limitValue: MAX_STORE_CONTENT_BYTES,\n observedValue: storeBytes,\n });\n }\n\n const message = ThreadMessage.make({\n threadId,\n sequence: current.nextSequence,\n ...(append.runId === undefined ? {} : { runId: append.runId }),\n message: append.message,\n encodedBytes: messageBytes,\n timestamp,\n });\n\n const next = Thread.make({\n version: current.version,\n threadId: current.threadId,\n nextSequence: current.nextSequence + 1,\n contentBytes,\n messages: [...current.messages, message],\n });\n\n return [next, put(state, owner, next)] as const;\n});\n\n/** In-memory storage shared for the consumer's Scope; it does not survive process loss. */\nexport const layerMemory = Layer.effect(\n Store,\n Effect.gen(function* () {\n const state = yield* SynchronizedRef.make<State>({ threads: new Map(), contentBytes: 0 });\n const root: Owner = { closed: false };\n\n const release = (owner: Owner) =>\n SynchronizedRef.update(state, (current) => {\n owner.closed = true;\n const threads = new Map(current.threads);\n let contentBytes = current.contentBytes;\n\n for (const [id, entry] of threads) {\n if (belongsTo(entry.owner, owner)) {\n threads.delete(id);\n contentBytes -= entry.snapshot.contentBytes;\n }\n }\n\n return { threads, contentBytes };\n });\n\n yield* Effect.addFinalizer(() => release(root));\n\n const view = (owner: Owner): StoreService => ({\n scoped: Effect.acquireRelease(\n Effect.sync((): Owner => ({ closed: false, parent: owner })),\n release,\n ).pipe(Effect.map(view)),\n create: (threadId) =>\n SynchronizedRef.modifyEffect(\n state,\n Effect.fnUntraced(function* (threads) {\n const existing = yield* access(threads, owner, threadId);\n\n if (existing !== undefined) return [existing, threads] as const;\n if (threads.threads.size >= MAX_THREADS) {\n return yield* ThreadLimitExceeded.make({\n threadId,\n limit: \"threads\",\n limitValue: MAX_THREADS,\n observedValue: threads.threads.size + 1,\n });\n }\n\n const created = Thread.make({\n version: 1,\n threadId,\n nextSequence: 0,\n contentBytes: 0,\n messages: [],\n });\n\n return [created, put(threads, owner, created)] as const;\n }),\n ),\n append: Effect.fnUntraced(function* (threadId, message) {\n const encoded = yield* encodeMessage(threadId, message.message);\n const timestamp = DateTime.toUtc(DateTime.makeUnsafe(yield* Clock.currentTimeMillis));\n\n return yield* SynchronizedRef.modifyEffect(\n state,\n Effect.fnUntraced(function* (threads) {\n const current = yield* findSnapshot(threads, owner, threadId);\n\n return yield* appendEncoded(threads, owner, current, message, encoded, timestamp);\n }),\n );\n }),\n recordHistory: Effect.fnUntraced(function* (threadId, historyRunId, history) {\n const incoming = yield* Effect.forEach(history.content, (message) =>\n encodeMessage(threadId, message).pipe(Effect.map((encoded) => ({ message, encoded }))),\n );\n\n // Publish the complete suffix only after verification and every bounded append succeed.\n return yield* SynchronizedRef.modifyEffect(\n state,\n Effect.fnUntraced(function* (threads) {\n const current = yield* findSnapshot(threads, owner, threadId);\n\n const currentEncoded = yield* Effect.forEach(current.messages, (entry) =>\n encodeMessage(threadId, entry.message),\n );\n\n if (\n incoming.length < currentEncoded.length ||\n currentEncoded.some((encoded, index) => encoded !== incoming[index]?.encoded)\n ) {\n return yield* ThreadHistoryDiverged.make({\n threadId,\n message: \"Engine history is not an append-only extension of official history\",\n });\n }\n const timestamp = DateTime.toUtc(DateTime.makeUnsafe(yield* Clock.currentTimeMillis));\n\n if (incoming.length === currentEncoded.length) return [current, threads] as const;\n\n const messages = [...current.messages];\n let contentBytes = current.contentBytes;\n let storeBytes = threads.contentBytes;\n let nextSequence = current.nextSequence;\n\n for (const entry of incoming.slice(currentEncoded.length)) {\n const append = ThreadAppend.make({ runId: historyRunId, message: entry.message });\n\n const messageBytes = yield* messageSize(threadId, entry.encoded);\n\n contentBytes += messageBytes;\n storeBytes += messageBytes;\n if (storeBytes > MAX_STORE_CONTENT_BYTES) {\n return yield* ThreadLimitExceeded.make({\n threadId,\n limit: \"store-content-bytes\",\n limitValue: MAX_STORE_CONTENT_BYTES,\n observedValue: storeBytes,\n });\n }\n messages.push(\n ThreadMessage.make({\n threadId,\n sequence: nextSequence,\n ...(append.runId === undefined ? {} : { runId: append.runId }),\n message: append.message,\n encodedBytes: messageBytes,\n timestamp,\n }),\n );\n nextSequence += 1;\n }\n\n const snapshot = Thread.make({\n version: current.version,\n threadId,\n nextSequence,\n contentBytes,\n messages,\n });\n\n return [snapshot, put(threads, owner, snapshot)] as const;\n }),\n );\n }),\n snapshot: (threadId) =>\n SynchronizedRef.get(state).pipe(\n Effect.flatMap((all) => findSnapshot(all, owner, threadId)),\n ),\n export: Effect.fnUntraced(function* (threadId) {\n const snapshot = yield* findSnapshot(yield* SynchronizedRef.get(state), owner, threadId);\n\n return ThreadExport.make({\n format: \"effect-agent/ephemeral-thread@1\",\n exportedAt: DateTime.toUtc(DateTime.makeUnsafe(yield* Clock.currentTimeMillis)),\n snapshot,\n });\n }),\n });\n\n return view(root);\n }),\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,MAAa,aAAa,OAAO,OAAO,MAAM,OAAO,YAAY,KAAS,CAAC;AAC3E,MAAM,4BAA4B;AAClC,MAAM,cAAc;AACpB,MAAM,0BAA0B;;AAGhC,IAAa,gBAAb,cAAmC,OAAO,MACxC,0CACF,CAAC,CAAC;CACA,UAAU;CACV,UAAU,OAAO;CACjB,OAAO,OAAO,YAAY,KAAK;CAC/B,SAAS,OAAO;CAChB,cAAc,OAAO,QAAQ,MAAM,OAAO,oBAAoB,yBAAyB,CAAC;CACxF,WAAW,OAAO;AACpB,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,SAAb,cAA4B,OAAO,MAAc,2CAA2C,CAAC,CAAC;CAC5F,SAAS,OAAO,QAAQ,CAAC;CACzB,UAAU;CACV,cAAc,OAAO;CACrB,cAAc,OAAO;CACrB,UAAU,OAAO,MAAM,aAAa;AACtC,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,eAAb,cAAkC,OAAO,MACvC,yCACF,CAAC,CAAC;CACA,QAAQ,OAAO,QAAQ,iCAAiC;CACxD,YAAY,OAAO;CACnB,UAAU;AACZ,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,eAAb,cAAkC,OAAO,MACvC,yCACF,CAAC,CAAC;CACA,OAAO,OAAO,YAAY,KAAK;CAC/B,SAAS,OAAO;AAClB,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CAAC,kBAAkB,EACzF,UAAU,SACZ,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,sBAAb,cAAyC,OAAO,YAAiC,CAAC,CAChF,u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KAAK,IAAI;AAClB,CAAC,CACH"}
@@ -190,7 +190,7 @@ const sumRunTotals = Effect.fnUntraced(function* (contributions) {
190
190
  const usageStatuses = [];
191
191
  const pricingStatuses = [];
192
192
  for (const contribution of contributions) {
193
- const value = yield* Schema.decodeEffect(RunTotals)(contribution).pipe(Effect.mapError(() => new UsageAggregationError({
193
+ const value = yield* Schema.decodeEffect(RunTotals)(contribution).pipe(Effect.mapError(() => UsageAggregationError.make({
194
194
  field: "totals",
195
195
  message: "Invalid Run totals"
196
196
  })));
@@ -233,7 +233,7 @@ const runTotalsFromSummary = (summary) => RunTotals.make({
233
233
  * Empty contributions do not change completeness; the seed is never mutated.
234
234
  */
235
235
  const summarizeModelUsage = Effect.fnUntraced(function* (calls, seed) {
236
- const initial = seed === void 0 ? void 0 : yield* Schema.decodeEffect(RunUsageSummary)(seed).pipe(Effect.mapError(() => new UsageAggregationError({
236
+ const initial = seed === void 0 ? void 0 : yield* Schema.decodeEffect(RunUsageSummary)(seed).pipe(Effect.mapError(() => UsageAggregationError.make({
237
237
  field: "seed",
238
238
  message: "Canonical usage seed does not satisfy the RunUsageSummary Schema"
239
239
  })));
@@ -1 +1 @@
1
- {"version":3,"file":"Usage.mjs","names":[],"sources":["../../src/core/Usage.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { RunId } from \"./Identifiers.ts\";\n\nconst UsageIdentity = Schema.NonEmptyString.check(Schema.isMaxLength(256));\n\n/** Bounded provider response identity. Request configuration is not response evidence. */\nexport class ModelResponseIdentity extends Schema.Class<ModelResponseIdentity>(\n \"@effect-agent/core/ModelResponseIdentity\",\n)({\n id: Schema.optionalKey(UsageIdentity),\n model: Schema.optionalKey(UsageIdentity),\n}) {}\n\n/** Missing legacy status means unknown, never a free call or a complete report. */\nexport const UsageCompleteness = Schema.Literals([\"complete\", \"partial\", \"unknown\"]);\n\nconst hasAdditiveTotal = (total: number, components: ReadonlyArray<number>): boolean => {\n const sum = components.reduce((accumulator, component) => accumulator + component, 0);\n\n return Number.isSafeInteger(sum) && total === sum;\n};\n\nconst InputTokenUsageFields = Schema.Struct({\n total: Schema.Natural,\n uncached: Schema.Natural,\n cacheRead: Schema.Natural,\n cacheWrite: Schema.Natural,\n}).check(\n Schema.makeFilter(\n (usage) => hasAdditiveTotal(usage.total, [usage.uncached, usage.cacheRead, usage.cacheWrite]),\n { title: \"Input token total equals uncached, cache-read, and cache-write components\" },\n ),\n);\n\n/** Provider-reported input-token components for one completed model call. */\nexport class InputTokenUsage extends Schema.Class<InputTokenUsage>(\n \"@effect-agent/core/InputTokenUsage\",\n)(InputTokenUsageFields) {}\n\nconst OutputTokenUsageFields = Schema.Struct({\n total: Schema.Natural,\n text: Schema.Natural,\n reasoning: Schema.Natural,\n}).check(\n Schema.makeFilter((usage) => hasAdditiveTotal(usage.total, [usage.text, usage.reasoning]), {\n title: \"Output token total equals text and reasoning components\",\n }),\n);\n\n/** Provider-reported output-token components for one completed model call. */\nexport class OutputTokenUsage extends Schema.Class<OutputTokenUsage>(\n \"@effect-agent/core/OutputTokenUsage\",\n)(OutputTokenUsageFields) {}\n\n/** Canonical, provider-independent accounting for one completed model call. */\nexport class ModelCallUsage extends Schema.Class<ModelCallUsage>(\n \"@effect-agent/core/ModelCallUsage\",\n)({\n provider: UsageIdentity,\n /** Configured binding identity. See response.model for provider-reported identity. */\n model: UsageIdentity,\n serviceTier: Schema.optionalKey(UsageIdentity),\n pricingVersion: Schema.optionalKey(UsageIdentity),\n response: Schema.optionalKey(ModelResponseIdentity),\n purpose: Schema.optionalKey(Schema.Literals([\"turn\", \"summary\"])),\n usageStatus: Schema.optionalKey(UsageCompleteness),\n pricingStatus: Schema.optionalKey(Schema.Literals([\"estimated\", \"unknown\"])),\n inputTokens: InputTokenUsage,\n outputTokens: OutputTokenUsage,\n /** Observed hosted web searches; excludes OpenAI page/find actions. Absent in legacy records. */\n webSearchCalls: Schema.optionalKey(Schema.Natural),\n costMicrousd: Schema.Natural,\n}) {}\n\n/**\n * Observed model usage and estimated cost, without per-model attribution.\n * Numeric zero with unknown coverage never establishes free execution. Missing legacy\n * statuses mean unknown. Unobserved calls are excluded from the numeric call/token totals.\n */\nexport class RunTotals extends Schema.Class<RunTotals>(\"@effect-agent/core/RunTotals\")({\n modelCalls: Schema.Natural,\n inputTokens: Schema.Natural,\n outputTokens: Schema.Natural,\n /** Observed hosted web searches; excludes OpenAI page/find actions. Absent in legacy records. */\n webSearchCalls: Schema.optionalKey(Schema.Natural),\n costMicrousd: Schema.Natural,\n usageStatus: Schema.optionalKey(UsageCompleteness),\n pricingStatus: Schema.optionalKey(UsageCompleteness),\n unobservedModelCalls: Schema.optionalKey(Schema.Natural),\n}) {}\n\n/** Own Run usage and disjoint attached-descendant usage. Add each component once. */\nexport class RunUsageReport extends Schema.Class<RunUsageReport>(\n \"@effect-agent/core/RunUsageReport\",\n)({\n usage: RunTotals,\n delegatedUsage: RunTotals,\n}) {}\n\n/** A verified child report retained across durable parent Attempts. */\nexport class ChildRunUsage extends Schema.Class<ChildRunUsage>(\"@effect-agent/core/ChildRunUsage\")({\n runId: RunId,\n report: RunUsageReport,\n}) {}\n\n/** Known absence of observed work. */\nexport const emptyRunTotals = (): RunTotals =>\n RunTotals.make({\n modelCalls: 0,\n webSearchCalls: 0,\n inputTokens: 0,\n outputTokens: 0,\n costMicrousd: 0,\n usageStatus: \"complete\",\n pricingStatus: \"complete\",\n unobservedModelCalls: 0,\n });\n\n/** No accounting evidence, including legacy child reports. This is not known zero spend. */\nexport const unknownRunTotals = (): RunTotals =>\n RunTotals.make({\n ...emptyRunTotals(),\n usageStatus: \"unknown\",\n pricingStatus: \"unknown\",\n });\n\n/** Settlement-sized aggregate for calls sharing one pricing identity. */\nexport class ModelUsageGroup extends Schema.Class<ModelUsageGroup>(\n \"@effect-agent/core/ModelUsageGroup\",\n)({\n provider: UsageIdentity,\n model: UsageIdentity,\n /** Actual returned model; absent when only the configured binding is known. */\n responseModel: Schema.optionalKey(UsageIdentity),\n serviceTier: Schema.optionalKey(UsageIdentity),\n pricingVersion: Schema.optionalKey(UsageIdentity),\n modelCalls: Schema.Natural.check(Schema.isGreaterThan(0)),\n inputTokens: InputTokenUsage,\n outputTokens: OutputTokenUsage,\n /** Observed hosted web searches; excludes OpenAI page/find actions. Absent in legacy records. */\n webSearchCalls: Schema.optionalKey(Schema.Natural),\n costMicrousd: Schema.Natural,\n}) {}\n\nconst RunUsageSummaryFields = Schema.Struct({\n modelCalls: Schema.Natural,\n inputTokens: InputTokenUsage,\n outputTokens: OutputTokenUsage,\n /** Observed hosted web searches; excludes OpenAI page/find actions. Absent in legacy records. */\n webSearchCalls: Schema.optionalKey(Schema.Natural),\n costMicrousd: Schema.Natural,\n byModel: Schema.Array(ModelUsageGroup),\n /** Coverage of recorded calls only; interruptions can make the Run less complete. */\n usageStatus: Schema.optionalKey(UsageCompleteness),\n pricingStatus: Schema.optionalKey(UsageCompleteness),\n /** Observed invocations without retained accounting, excluded from numeric call/token totals. */\n unobservedModelCalls: Schema.optionalKey(Schema.Natural),\n}).check(\n Schema.makeFilter(\n (summary) => {\n const identities = summary.byModel.map((group) =>\n JSON.stringify([\n group.provider,\n group.model,\n group.responseModel ?? null,\n group.serviceTier ?? null,\n group.pricingVersion ?? null,\n ]),\n );\n\n return (\n new Set(identities).size === identities.length &&\n (summary.webSearchCalls === undefined ||\n hasAdditiveTotal(\n summary.webSearchCalls,\n summary.byModel.map((group) => group.webSearchCalls ?? 0),\n )) &&\n hasAdditiveTotal(\n summary.modelCalls,\n summary.byModel.map((group) => group.modelCalls),\n ) &&\n hasAdditiveTotal(\n summary.inputTokens.total,\n summary.byModel.map((group) => group.inputTokens.total),\n ) &&\n hasAdditiveTotal(\n summary.inputTokens.uncached,\n summary.byModel.map((group) => group.inputTokens.uncached),\n ) &&\n hasAdditiveTotal(\n summary.inputTokens.cacheRead,\n summary.byModel.map((group) => group.inputTokens.cacheRead),\n ) &&\n hasAdditiveTotal(\n summary.inputTokens.cacheWrite,\n summary.byModel.map((group) => group.inputTokens.cacheWrite),\n ) &&\n hasAdditiveTotal(\n summary.outputTokens.total,\n summary.byModel.map((group) => group.outputTokens.total),\n ) &&\n hasAdditiveTotal(\n summary.outputTokens.text,\n summary.byModel.map((group) => group.outputTokens.text),\n ) &&\n hasAdditiveTotal(\n summary.outputTokens.reasoning,\n summary.byModel.map((group) => group.outputTokens.reasoning),\n ) &&\n hasAdditiveTotal(\n summary.costMicrousd,\n summary.byModel.map((group) => group.costMicrousd),\n )\n );\n },\n {\n title:\n \"Run usage totals equal unique per-model pricing groups within safe-integer accounting\",\n },\n ),\n);\n\n/** Settlement aggregate included with a terminal Run settlement. */\nexport class RunUsageSummary extends Schema.Class<RunUsageSummary>(\n \"@effect-agent/core/RunUsageSummary\",\n)(RunUsageSummaryFields) {}\n\ninterface MutableUsageGroup {\n readonly provider: string;\n readonly model: string;\n readonly responseModel?: string | undefined;\n readonly serviceTier?: string | undefined;\n readonly pricingVersion?: string | undefined;\n modelCalls: number;\n webSearchCalls: number | undefined;\n inputTokens: {\n total: number;\n uncached: number;\n cacheRead: number;\n cacheWrite: number;\n };\n outputTokens: { total: number; text: number; reasoning: number };\n costMicrousd: number;\n}\n\nconst emptyInputTokens = () => ({ total: 0, uncached: 0, cacheRead: 0, cacheWrite: 0 });\nconst emptyOutputTokens = () => ({ total: 0, text: 0, reasoning: 0 });\n\n/** Canonical usage could not be aggregated without exceeding safe-integer accounting. */\nexport class UsageAggregationError extends Schema.TaggedError<UsageAggregationError>()(\n \"UsageAggregationError\",\n {\n field: Schema.NonEmptyString,\n message: Schema.String,\n },\n) {}\n\nconst checkedAdd = (\n field: string,\n left: number,\n right: number,\n): Effect.Effect<number, UsageAggregationError> => {\n const total = left + right;\n\n return Number.isSafeInteger(left) &&\n left >= 0 &&\n Number.isSafeInteger(right) &&\n right >= 0 &&\n Number.isSafeInteger(total)\n ? Effect.succeed(total)\n : Effect.fail(\n UsageAggregationError.make({\n field,\n message: `Canonical usage aggregation exceeded the safe-integer range at ${field}`,\n }),\n );\n};\n\n/** Combine disjoint totals, retaining uncertainty and rejecting numeric overflow. */\nexport const sumRunTotals = Effect.fnUntraced(function* (\n contributions: ReadonlyArray<RunTotals>,\n): Effect.fn.Return<RunTotals, UsageAggregationError> {\n let modelCalls = 0;\n let webSearchCalls: number | undefined = 0;\n let inputTokens = 0;\n let outputTokens = 0;\n let costMicrousd = 0;\n let unobservedModelCalls = 0;\n const usageStatuses: Array<typeof UsageCompleteness.Type> = [];\n const pricingStatuses: Array<typeof UsageCompleteness.Type> = [];\n\n for (const contribution of contributions) {\n const value = yield* Schema.decodeEffect(RunTotals)(contribution).pipe(\n Effect.mapError(\n () => new UsageAggregationError({ field: \"totals\", message: \"Invalid Run totals\" }),\n ),\n );\n\n modelCalls = yield* checkedAdd(\"modelCalls\", modelCalls, value.modelCalls);\n if (value.webSearchCalls === undefined && value.modelCalls > 0) webSearchCalls = undefined;\n else if (webSearchCalls !== undefined)\n webSearchCalls = yield* checkedAdd(\n \"webSearchCalls\",\n webSearchCalls,\n value.webSearchCalls ?? 0,\n );\n inputTokens = yield* checkedAdd(\"inputTokens\", inputTokens, value.inputTokens);\n outputTokens = yield* checkedAdd(\"outputTokens\", outputTokens, value.outputTokens);\n costMicrousd = yield* checkedAdd(\"costMicrousd\", costMicrousd, value.costMicrousd);\n unobservedModelCalls = yield* checkedAdd(\n \"unobservedModelCalls\",\n unobservedModelCalls,\n value.unobservedModelCalls ?? 0,\n );\n // Known empty contributions are identities; unknown empty contributions are evidence gaps.\n if (\n value.modelCalls > 0 ||\n (value.unobservedModelCalls ?? 0) > 0 ||\n value.usageStatus !== \"complete\"\n ) {\n usageStatuses.push(value.usageStatus ?? \"unknown\");\n }\n if (\n value.modelCalls > 0 ||\n (value.unobservedModelCalls ?? 0) > 0 ||\n value.pricingStatus !== \"complete\"\n ) {\n pricingStatuses.push(value.pricingStatus ?? \"unknown\");\n }\n }\n\n const coverage = (statuses: ReadonlyArray<typeof UsageCompleteness.Type>) =>\n statuses.every((status) => status === \"complete\")\n ? (\"complete\" as const)\n : statuses.every((status) => status === \"unknown\")\n ? (\"unknown\" as const)\n : (\"partial\" as const);\n\n return RunTotals.make({\n modelCalls,\n ...(webSearchCalls === undefined ? {} : { webSearchCalls }),\n inputTokens,\n outputTokens,\n costMicrousd,\n unobservedModelCalls,\n usageStatus: coverage(usageStatuses),\n pricingStatus: coverage(pricingStatuses),\n });\n});\n\n/** Flatten a canonical settlement summary without discarding its coverage markers. */\nexport const runTotalsFromSummary = (summary: RunUsageSummary): RunTotals =>\n RunTotals.make({\n modelCalls: summary.modelCalls,\n ...(summary.webSearchCalls === undefined ? {} : { webSearchCalls: summary.webSearchCalls }),\n inputTokens: summary.inputTokens.total,\n outputTokens: summary.outputTokens.total,\n costMicrousd: summary.costMicrousd,\n usageStatus: summary.usageStatus ?? \"unknown\",\n pricingStatus: summary.pricingStatus ?? \"unknown\",\n unobservedModelCalls: summary.unobservedModelCalls ?? 0,\n });\n\n/**\n * Deterministically aggregate canonical per-call usage without making cached tokens free.\n * A validated seed retains earlier call totals and pricing groups without retaining those calls.\n * Empty contributions do not change completeness; the seed is never mutated.\n */\nexport const summarizeModelUsage = Effect.fnUntraced(function* (\n calls: ReadonlyArray<ModelCallUsage>,\n seed?: RunUsageSummary,\n): Effect.fn.Return<RunUsageSummary, UsageAggregationError> {\n const initial =\n seed === undefined\n ? undefined\n : yield* Schema.decodeEffect(RunUsageSummary)(seed).pipe(\n Effect.mapError(\n () =>\n new UsageAggregationError({\n field: \"seed\",\n message: \"Canonical usage seed does not satisfy the RunUsageSummary Schema\",\n }),\n ),\n );\n\n const inputTokens = initial === undefined ? emptyInputTokens() : { ...initial.inputTokens };\n const outputTokens = initial === undefined ? emptyOutputTokens() : { ...initial.outputTokens };\n const groups = new Map<string, MutableUsageGroup>();\n let modelCalls = initial?.modelCalls ?? 0;\n\n let webSearchCalls =\n initial === undefined || initial.modelCalls === 0 ? 0 : initial.webSearchCalls;\n\n let costMicrousd = initial?.costMicrousd ?? 0;\n const hasSeedCalls = modelCalls > 0;\n\n let allUsageUnknown =\n !hasSeedCalls || initial?.usageStatus === undefined || initial.usageStatus === \"unknown\";\n\n let allUsageComplete = !hasSeedCalls || initial?.usageStatus === \"complete\";\n\n let allPricingUnknown =\n !hasSeedCalls || initial?.pricingStatus === undefined || initial.pricingStatus === \"unknown\";\n\n let allPricingComplete = !hasSeedCalls || initial?.pricingStatus === \"complete\";\n\n for (const group of initial?.byModel ?? []) {\n const key = JSON.stringify([\n group.provider,\n group.model,\n group.responseModel ?? null,\n group.serviceTier ?? null,\n group.pricingVersion ?? null,\n ]);\n\n groups.set(key, {\n ...group,\n webSearchCalls: group.webSearchCalls,\n inputTokens: { ...group.inputTokens },\n outputTokens: { ...group.outputTokens },\n });\n }\n\n for (const call of calls) {\n allUsageUnknown &&= call.usageStatus === undefined || call.usageStatus === \"unknown\";\n allUsageComplete &&= call.usageStatus === \"complete\";\n allPricingUnknown &&= call.pricingStatus !== \"estimated\";\n allPricingComplete &&= call.pricingStatus === \"estimated\";\n modelCalls = yield* checkedAdd(\"modelCalls\", modelCalls, 1);\n webSearchCalls =\n webSearchCalls === undefined || call.webSearchCalls === undefined\n ? undefined\n : yield* checkedAdd(\"webSearchCalls\", webSearchCalls, call.webSearchCalls);\n inputTokens.total = yield* checkedAdd(\n \"inputTokens.total\",\n inputTokens.total,\n call.inputTokens.total,\n );\n inputTokens.uncached = yield* checkedAdd(\n \"inputTokens.uncached\",\n inputTokens.uncached,\n call.inputTokens.uncached,\n );\n inputTokens.cacheRead = yield* checkedAdd(\n \"inputTokens.cacheRead\",\n inputTokens.cacheRead,\n call.inputTokens.cacheRead,\n );\n inputTokens.cacheWrite = yield* checkedAdd(\n \"inputTokens.cacheWrite\",\n inputTokens.cacheWrite,\n call.inputTokens.cacheWrite,\n );\n outputTokens.total = yield* checkedAdd(\n \"outputTokens.total\",\n outputTokens.total,\n call.outputTokens.total,\n );\n outputTokens.text = yield* checkedAdd(\n \"outputTokens.text\",\n outputTokens.text,\n call.outputTokens.text,\n );\n outputTokens.reasoning = yield* checkedAdd(\n \"outputTokens.reasoning\",\n outputTokens.reasoning,\n call.outputTokens.reasoning,\n );\n costMicrousd = yield* checkedAdd(\"costMicrousd\", costMicrousd, call.costMicrousd);\n\n const key = JSON.stringify([\n call.provider,\n call.model,\n call.response?.model ?? null,\n call.serviceTier ?? null,\n call.pricingVersion ?? null,\n ]);\n\n let group = groups.get(key);\n\n if (group === undefined) {\n group = {\n provider: call.provider,\n model: call.model,\n ...(call.response?.model === undefined ? {} : { responseModel: call.response.model }),\n ...(call.serviceTier === undefined ? {} : { serviceTier: call.serviceTier }),\n ...(call.pricingVersion === undefined ? {} : { pricingVersion: call.pricingVersion }),\n modelCalls: 0,\n webSearchCalls: 0,\n inputTokens: emptyInputTokens(),\n outputTokens: emptyOutputTokens(),\n costMicrousd: 0,\n };\n groups.set(key, group);\n }\n group.modelCalls = yield* checkedAdd(\"byModel.modelCalls\", group.modelCalls, 1);\n group.webSearchCalls =\n group.webSearchCalls === undefined || call.webSearchCalls === undefined\n ? undefined\n : yield* checkedAdd(\"byModel.webSearchCalls\", group.webSearchCalls, call.webSearchCalls);\n group.inputTokens.total = yield* checkedAdd(\n \"byModel.inputTokens.total\",\n group.inputTokens.total,\n call.inputTokens.total,\n );\n group.inputTokens.uncached = yield* checkedAdd(\n \"byModel.inputTokens.uncached\",\n group.inputTokens.uncached,\n call.inputTokens.uncached,\n );\n group.inputTokens.cacheRead = yield* checkedAdd(\n \"byModel.inputTokens.cacheRead\",\n group.inputTokens.cacheRead,\n call.inputTokens.cacheRead,\n );\n group.inputTokens.cacheWrite = yield* checkedAdd(\n \"byModel.inputTokens.cacheWrite\",\n group.inputTokens.cacheWrite,\n call.inputTokens.cacheWrite,\n );\n group.outputTokens.total = yield* checkedAdd(\n \"byModel.outputTokens.total\",\n group.outputTokens.total,\n call.outputTokens.total,\n );\n group.outputTokens.text = yield* checkedAdd(\n \"byModel.outputTokens.text\",\n group.outputTokens.text,\n call.outputTokens.text,\n );\n group.outputTokens.reasoning = yield* checkedAdd(\n \"byModel.outputTokens.reasoning\",\n group.outputTokens.reasoning,\n call.outputTokens.reasoning,\n );\n group.costMicrousd = yield* checkedAdd(\n \"byModel.costMicrousd\",\n group.costMicrousd,\n call.costMicrousd,\n );\n }\n\n return RunUsageSummary.make({\n modelCalls,\n ...(webSearchCalls === undefined ? {} : { webSearchCalls }),\n inputTokens: InputTokenUsage.make(inputTokens),\n outputTokens: OutputTokenUsage.make(outputTokens),\n costMicrousd,\n usageStatus: allUsageUnknown ? \"unknown\" : allUsageComplete ? \"complete\" : \"partial\",\n pricingStatus: allPricingUnknown ? \"unknown\" : allPricingComplete ? \"complete\" : \"partial\",\n ...(initial?.unobservedModelCalls === undefined\n ? {}\n : { unobservedModelCalls: initial.unobservedModelCalls }),\n byModel: [...groups.values()].map((group) =>\n ModelUsageGroup.make({\n provider: group.provider,\n model: group.model,\n ...(group.responseModel === undefined ? {} : { responseModel: group.responseModel }),\n ...(group.serviceTier === undefined ? {} : { serviceTier: group.serviceTier }),\n ...(group.pricingVersion === undefined ? {} : { pricingVersion: group.pricingVersion }),\n modelCalls: group.modelCalls,\n ...(group.webSearchCalls === undefined ? {} : { webSearchCalls: group.webSearchCalls }),\n inputTokens: InputTokenUsage.make(group.inputTokens),\n outputTokens: OutputTokenUsage.make(group.outputTokens),\n costMicrousd: group.costMicrousd,\n }),\n ),\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,gBAAgB,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC;;AAGzE,IAAa,wBAAb,cAA2C,OAAO,MAChD,0CACF,CAAC,CAAC;CACA,IAAI,OAAO,YAAY,aAAa;CACpC,OAAO,OAAO,YAAY,aAAa;AACzC,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAa,oBAAoB,OAAO,SAAS;CAAC;CAAY;CAAW;AAAS,CAAC;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AAe,MAAM,cAAc;GAClF,GAAI,MAAM,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,MAAM,YAAY;GAC5E,GAAI,MAAM,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAgB,MAAM,eAAe;GACrF,YAAY,MAAM;GAClB,GAAI,MAAM,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAgB,MAAM,eAAe;GACrF,aAAa,gBAAgB,KAAK,MAAM,WAAW;GACnD,cAAc,iBAAiB,KAAK,MAAM,YAAY;GACtD,cAAc,MAAM;EACtB,CAAC,CACH;CACF,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"Usage.mjs","names":[],"sources":["../../src/core/Usage.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { RunId } from \"./Identifiers.ts\";\n\nconst UsageIdentity = Schema.NonEmptyString.check(Schema.isMaxLength(256));\n\n/** Bounded provider response identity. Request configuration is not response evidence. */\nexport class ModelResponseIdentity extends Schema.Class<ModelResponseIdentity>(\n \"@effect-agent/core/ModelResponseIdentity\",\n)({\n id: Schema.optionalKey(UsageIdentity),\n model: Schema.optionalKey(UsageIdentity),\n}) {}\n\n/** Missing legacy status means unknown, never a free call or a complete report. */\nexport const UsageCompleteness = Schema.Literals([\"complete\", \"partial\", \"unknown\"]);\n\nconst hasAdditiveTotal = (total: number, components: ReadonlyArray<number>): boolean => {\n const sum = components.reduce((accumulator, component) => accumulator + component, 0);\n\n return Number.isSafeInteger(sum) && total === sum;\n};\n\nconst InputTokenUsageFields = Schema.Struct({\n total: Schema.Natural,\n uncached: Schema.Natural,\n cacheRead: Schema.Natural,\n cacheWrite: Schema.Natural,\n}).check(\n Schema.makeFilter(\n (usage) => hasAdditiveTotal(usage.total, [usage.uncached, usage.cacheRead, usage.cacheWrite]),\n { title: \"Input token total equals uncached, cache-read, and cache-write components\" },\n ),\n);\n\n/** Provider-reported input-token components for one completed model call. */\nexport class InputTokenUsage extends Schema.Class<InputTokenUsage>(\n \"@effect-agent/core/InputTokenUsage\",\n)(InputTokenUsageFields) {}\n\nconst OutputTokenUsageFields = Schema.Struct({\n total: Schema.Natural,\n text: Schema.Natural,\n reasoning: Schema.Natural,\n}).check(\n Schema.makeFilter((usage) => hasAdditiveTotal(usage.total, [usage.text, usage.reasoning]), {\n title: \"Output token total equals text and reasoning components\",\n }),\n);\n\n/** Provider-reported output-token components for one completed model call. */\nexport class OutputTokenUsage extends Schema.Class<OutputTokenUsage>(\n \"@effect-agent/core/OutputTokenUsage\",\n)(OutputTokenUsageFields) {}\n\n/** Canonical, provider-independent accounting for one completed model call. */\nexport class ModelCallUsage extends Schema.Class<ModelCallUsage>(\n \"@effect-agent/core/ModelCallUsage\",\n)({\n provider: UsageIdentity,\n /** Configured binding identity. See response.model for provider-reported identity. */\n model: UsageIdentity,\n serviceTier: Schema.optionalKey(UsageIdentity),\n pricingVersion: Schema.optionalKey(UsageIdentity),\n response: Schema.optionalKey(ModelResponseIdentity),\n purpose: Schema.optionalKey(Schema.Literals([\"turn\", \"summary\"])),\n usageStatus: Schema.optionalKey(UsageCompleteness),\n pricingStatus: Schema.optionalKey(Schema.Literals([\"estimated\", \"unknown\"])),\n inputTokens: InputTokenUsage,\n outputTokens: OutputTokenUsage,\n /** Observed hosted web searches; excludes OpenAI page/find actions. Absent in legacy records. */\n webSearchCalls: Schema.optionalKey(Schema.Natural),\n costMicrousd: Schema.Natural,\n}) {}\n\n/**\n * Observed model usage and estimated cost, without per-model attribution.\n * Numeric zero with unknown coverage never establishes free execution. Missing legacy\n * statuses mean unknown. Unobserved calls are excluded from the numeric call/token totals.\n */\nexport class RunTotals extends Schema.Class<RunTotals>(\"@effect-agent/core/RunTotals\")({\n modelCalls: Schema.Natural,\n inputTokens: Schema.Natural,\n outputTokens: Schema.Natural,\n /** Observed hosted web searches; excludes OpenAI page/find actions. Absent in legacy records. */\n webSearchCalls: Schema.optionalKey(Schema.Natural),\n costMicrousd: Schema.Natural,\n usageStatus: Schema.optionalKey(UsageCompleteness),\n pricingStatus: Schema.optionalKey(UsageCompleteness),\n unobservedModelCalls: Schema.optionalKey(Schema.Natural),\n}) {}\n\n/** Own Run usage and disjoint attached-descendant usage. Add each component once. */\nexport class RunUsageReport extends Schema.Class<RunUsageReport>(\n \"@effect-agent/core/RunUsageReport\",\n)({\n usage: RunTotals,\n delegatedUsage: RunTotals,\n}) {}\n\n/** A verified child report retained across durable parent Attempts. */\nexport class ChildRunUsage extends Schema.Class<ChildRunUsage>(\"@effect-agent/core/ChildRunUsage\")({\n runId: RunId,\n report: RunUsageReport,\n}) {}\n\n/** Known absence of observed work. */\nexport const emptyRunTotals = (): RunTotals =>\n RunTotals.make({\n modelCalls: 0,\n webSearchCalls: 0,\n inputTokens: 0,\n outputTokens: 0,\n costMicrousd: 0,\n usageStatus: \"complete\",\n pricingStatus: \"complete\",\n unobservedModelCalls: 0,\n });\n\n/** No accounting evidence, including legacy child reports. This is not known zero spend. */\nexport const unknownRunTotals = (): RunTotals =>\n RunTotals.make({\n ...emptyRunTotals(),\n usageStatus: \"unknown\",\n pricingStatus: \"unknown\",\n });\n\n/** Settlement-sized aggregate for calls sharing one pricing identity. */\nexport class ModelUsageGroup extends Schema.Class<ModelUsageGroup>(\n \"@effect-agent/core/ModelUsageGroup\",\n)({\n provider: UsageIdentity,\n model: UsageIdentity,\n /** Actual returned model; absent when only the configured binding is known. */\n responseModel: Schema.optionalKey(UsageIdentity),\n serviceTier: Schema.optionalKey(UsageIdentity),\n pricingVersion: Schema.optionalKey(UsageIdentity),\n modelCalls: Schema.Natural.check(Schema.isGreaterThan(0)),\n inputTokens: InputTokenUsage,\n outputTokens: OutputTokenUsage,\n /** Observed hosted web searches; excludes OpenAI page/find actions. Absent in legacy records. */\n webSearchCalls: Schema.optionalKey(Schema.Natural),\n costMicrousd: Schema.Natural,\n}) {}\n\nconst RunUsageSummaryFields = Schema.Struct({\n modelCalls: Schema.Natural,\n inputTokens: InputTokenUsage,\n outputTokens: OutputTokenUsage,\n /** Observed hosted web searches; excludes OpenAI page/find actions. Absent in legacy records. */\n webSearchCalls: Schema.optionalKey(Schema.Natural),\n costMicrousd: Schema.Natural,\n byModel: Schema.Array(ModelUsageGroup),\n /** Coverage of recorded calls only; interruptions can make the Run less complete. */\n usageStatus: Schema.optionalKey(UsageCompleteness),\n pricingStatus: Schema.optionalKey(UsageCompleteness),\n /** Observed invocations without retained accounting, excluded from numeric call/token totals. */\n unobservedModelCalls: Schema.optionalKey(Schema.Natural),\n}).check(\n Schema.makeFilter(\n (summary) => {\n const identities = summary.byModel.map((group) =>\n JSON.stringify([\n group.provider,\n group.model,\n group.responseModel ?? null,\n group.serviceTier ?? null,\n group.pricingVersion ?? null,\n ]),\n );\n\n return (\n new Set(identities).size === identities.length &&\n (summary.webSearchCalls === undefined ||\n hasAdditiveTotal(\n summary.webSearchCalls,\n summary.byModel.map((group) => group.webSearchCalls ?? 0),\n )) &&\n hasAdditiveTotal(\n summary.modelCalls,\n summary.byModel.map((group) => group.modelCalls),\n ) &&\n hasAdditiveTotal(\n summary.inputTokens.total,\n summary.byModel.map((group) => group.inputTokens.total),\n ) &&\n hasAdditiveTotal(\n summary.inputTokens.uncached,\n summary.byModel.map((group) => group.inputTokens.uncached),\n ) &&\n hasAdditiveTotal(\n summary.inputTokens.cacheRead,\n summary.byModel.map((group) => group.inputTokens.cacheRead),\n ) &&\n hasAdditiveTotal(\n summary.inputTokens.cacheWrite,\n summary.byModel.map((group) => group.inputTokens.cacheWrite),\n ) &&\n hasAdditiveTotal(\n summary.outputTokens.total,\n summary.byModel.map((group) => group.outputTokens.total),\n ) &&\n hasAdditiveTotal(\n summary.outputTokens.text,\n summary.byModel.map((group) => group.outputTokens.text),\n ) &&\n hasAdditiveTotal(\n summary.outputTokens.reasoning,\n summary.byModel.map((group) => group.outputTokens.reasoning),\n ) &&\n hasAdditiveTotal(\n summary.costMicrousd,\n summary.byModel.map((group) => group.costMicrousd),\n )\n );\n },\n {\n title:\n \"Run usage totals equal unique per-model pricing groups within safe-integer accounting\",\n },\n ),\n);\n\n/** Settlement aggregate included with a terminal Run settlement. */\nexport class RunUsageSummary extends Schema.Class<RunUsageSummary>(\n \"@effect-agent/core/RunUsageSummary\",\n)(RunUsageSummaryFields) {}\n\ninterface MutableUsageGroup {\n readonly provider: string;\n readonly model: string;\n readonly responseModel?: string | undefined;\n readonly serviceTier?: string | undefined;\n readonly pricingVersion?: string | undefined;\n modelCalls: number;\n webSearchCalls: number | undefined;\n inputTokens: {\n total: number;\n uncached: number;\n cacheRead: number;\n cacheWrite: number;\n };\n outputTokens: { total: number; text: number; reasoning: number };\n costMicrousd: number;\n}\n\nconst emptyInputTokens = () => ({ total: 0, uncached: 0, cacheRead: 0, cacheWrite: 0 });\nconst emptyOutputTokens = () => ({ total: 0, text: 0, reasoning: 0 });\n\n/** Canonical usage could not be aggregated without exceeding safe-integer accounting. */\nexport class UsageAggregationError extends Schema.TaggedError<UsageAggregationError>()(\n \"UsageAggregationError\",\n {\n field: Schema.NonEmptyString,\n message: Schema.String,\n },\n) {}\n\nconst checkedAdd = (\n field: string,\n left: number,\n right: number,\n): Effect.Effect<number, UsageAggregationError> => {\n const total = left + right;\n\n return Number.isSafeInteger(left) &&\n left >= 0 &&\n Number.isSafeInteger(right) &&\n right >= 0 &&\n Number.isSafeInteger(total)\n ? Effect.succeed(total)\n : Effect.fail(\n UsageAggregationError.make({\n field,\n message: `Canonical usage aggregation exceeded the safe-integer range at ${field}`,\n }),\n );\n};\n\n/** Combine disjoint totals, retaining uncertainty and rejecting numeric overflow. */\nexport const sumRunTotals = Effect.fnUntraced(function* (\n contributions: ReadonlyArray<RunTotals>,\n): Effect.fn.Return<RunTotals, UsageAggregationError> {\n let modelCalls = 0;\n let webSearchCalls: number | undefined = 0;\n let inputTokens = 0;\n let outputTokens = 0;\n let costMicrousd = 0;\n let unobservedModelCalls = 0;\n const usageStatuses: Array<typeof UsageCompleteness.Type> = [];\n const pricingStatuses: Array<typeof UsageCompleteness.Type> = [];\n\n for (const contribution of contributions) {\n const value = yield* Schema.decodeEffect(RunTotals)(contribution).pipe(\n Effect.mapError(() =>\n UsageAggregationError.make({ field: \"totals\", message: \"Invalid Run totals\" }),\n ),\n );\n\n modelCalls = yield* checkedAdd(\"modelCalls\", modelCalls, value.modelCalls);\n if (value.webSearchCalls === undefined && value.modelCalls > 0) webSearchCalls = undefined;\n else if (webSearchCalls !== undefined)\n webSearchCalls = yield* checkedAdd(\n \"webSearchCalls\",\n webSearchCalls,\n value.webSearchCalls ?? 0,\n );\n inputTokens = yield* checkedAdd(\"inputTokens\", inputTokens, value.inputTokens);\n outputTokens = yield* checkedAdd(\"outputTokens\", outputTokens, value.outputTokens);\n costMicrousd = yield* checkedAdd(\"costMicrousd\", costMicrousd, value.costMicrousd);\n unobservedModelCalls = yield* checkedAdd(\n \"unobservedModelCalls\",\n unobservedModelCalls,\n value.unobservedModelCalls ?? 0,\n );\n // Known empty contributions are identities; unknown empty contributions are evidence gaps.\n if (\n value.modelCalls > 0 ||\n (value.unobservedModelCalls ?? 0) > 0 ||\n value.usageStatus !== \"complete\"\n ) {\n usageStatuses.push(value.usageStatus ?? \"unknown\");\n }\n if (\n value.modelCalls > 0 ||\n (value.unobservedModelCalls ?? 0) > 0 ||\n value.pricingStatus !== \"complete\"\n ) {\n pricingStatuses.push(value.pricingStatus ?? \"unknown\");\n }\n }\n\n const coverage = (statuses: ReadonlyArray<typeof UsageCompleteness.Type>) =>\n statuses.every((status) => status === \"complete\")\n ? (\"complete\" as const)\n : statuses.every((status) => status === \"unknown\")\n ? (\"unknown\" as const)\n : (\"partial\" as const);\n\n return RunTotals.make({\n modelCalls,\n ...(webSearchCalls === undefined ? {} : { webSearchCalls }),\n inputTokens,\n outputTokens,\n costMicrousd,\n unobservedModelCalls,\n usageStatus: coverage(usageStatuses),\n pricingStatus: coverage(pricingStatuses),\n });\n});\n\n/** Flatten a canonical settlement summary without discarding its coverage markers. */\nexport const runTotalsFromSummary = (summary: RunUsageSummary): RunTotals =>\n RunTotals.make({\n modelCalls: summary.modelCalls,\n ...(summary.webSearchCalls === undefined ? {} : { webSearchCalls: summary.webSearchCalls }),\n inputTokens: summary.inputTokens.total,\n outputTokens: summary.outputTokens.total,\n costMicrousd: summary.costMicrousd,\n usageStatus: summary.usageStatus ?? \"unknown\",\n pricingStatus: summary.pricingStatus ?? \"unknown\",\n unobservedModelCalls: summary.unobservedModelCalls ?? 0,\n });\n\n/**\n * Deterministically aggregate canonical per-call usage without making cached tokens free.\n * A validated seed retains earlier call totals and pricing groups without retaining those calls.\n * Empty contributions do not change completeness; the seed is never mutated.\n */\nexport const summarizeModelUsage = Effect.fnUntraced(function* (\n calls: ReadonlyArray<ModelCallUsage>,\n seed?: RunUsageSummary,\n): Effect.fn.Return<RunUsageSummary, UsageAggregationError> {\n const initial =\n seed === undefined\n ? undefined\n : yield* Schema.decodeEffect(RunUsageSummary)(seed).pipe(\n Effect.mapError(() =>\n UsageAggregationError.make({\n field: \"seed\",\n message: \"Canonical usage seed does not satisfy the RunUsageSummary Schema\",\n }),\n ),\n );\n\n const inputTokens = initial === undefined ? emptyInputTokens() : { ...initial.inputTokens };\n const outputTokens = initial === undefined ? emptyOutputTokens() : { ...initial.outputTokens };\n const groups = new Map<string, MutableUsageGroup>();\n let modelCalls = initial?.modelCalls ?? 0;\n\n let webSearchCalls =\n initial === undefined || initial.modelCalls === 0 ? 0 : initial.webSearchCalls;\n\n let costMicrousd = initial?.costMicrousd ?? 0;\n const hasSeedCalls = modelCalls > 0;\n\n let allUsageUnknown =\n !hasSeedCalls || initial?.usageStatus === undefined || initial.usageStatus === \"unknown\";\n\n let allUsageComplete = !hasSeedCalls || initial?.usageStatus === \"complete\";\n\n let allPricingUnknown =\n !hasSeedCalls || initial?.pricingStatus === undefined || initial.pricingStatus === \"unknown\";\n\n let allPricingComplete = !hasSeedCalls || initial?.pricingStatus === \"complete\";\n\n for (const group of initial?.byModel ?? []) {\n const key = JSON.stringify([\n group.provider,\n group.model,\n group.responseModel ?? null,\n group.serviceTier ?? null,\n group.pricingVersion ?? null,\n ]);\n\n groups.set(key, {\n ...group,\n webSearchCalls: group.webSearchCalls,\n inputTokens: { ...group.inputTokens },\n outputTokens: { ...group.outputTokens },\n });\n }\n\n for (const call of calls) {\n allUsageUnknown &&= call.usageStatus === undefined || call.usageStatus === \"unknown\";\n allUsageComplete &&= call.usageStatus === \"complete\";\n allPricingUnknown &&= call.pricingStatus !== \"estimated\";\n allPricingComplete &&= call.pricingStatus === \"estimated\";\n modelCalls = yield* checkedAdd(\"modelCalls\", modelCalls, 1);\n webSearchCalls =\n webSearchCalls === undefined || call.webSearchCalls === undefined\n ? undefined\n : yield* checkedAdd(\"webSearchCalls\", webSearchCalls, call.webSearchCalls);\n inputTokens.total = yield* checkedAdd(\n \"inputTokens.total\",\n inputTokens.total,\n call.inputTokens.total,\n );\n inputTokens.uncached = yield* checkedAdd(\n \"inputTokens.uncached\",\n inputTokens.uncached,\n call.inputTokens.uncached,\n );\n inputTokens.cacheRead = yield* checkedAdd(\n \"inputTokens.cacheRead\",\n inputTokens.cacheRead,\n call.inputTokens.cacheRead,\n );\n inputTokens.cacheWrite = yield* checkedAdd(\n \"inputTokens.cacheWrite\",\n inputTokens.cacheWrite,\n call.inputTokens.cacheWrite,\n );\n outputTokens.total = yield* checkedAdd(\n \"outputTokens.total\",\n outputTokens.total,\n call.outputTokens.total,\n );\n outputTokens.text = yield* checkedAdd(\n \"outputTokens.text\",\n outputTokens.text,\n call.outputTokens.text,\n );\n outputTokens.reasoning = yield* checkedAdd(\n \"outputTokens.reasoning\",\n outputTokens.reasoning,\n call.outputTokens.reasoning,\n );\n costMicrousd = yield* checkedAdd(\"costMicrousd\", costMicrousd, call.costMicrousd);\n\n const key = JSON.stringify([\n call.provider,\n call.model,\n call.response?.model ?? null,\n call.serviceTier ?? null,\n call.pricingVersion ?? null,\n ]);\n\n let group = groups.get(key);\n\n if (group === undefined) {\n group = {\n provider: call.provider,\n model: call.model,\n ...(call.response?.model === undefined ? {} : { responseModel: call.response.model }),\n ...(call.serviceTier === undefined ? {} : { serviceTier: call.serviceTier }),\n ...(call.pricingVersion === undefined ? {} : { pricingVersion: call.pricingVersion }),\n modelCalls: 0,\n webSearchCalls: 0,\n inputTokens: emptyInputTokens(),\n outputTokens: emptyOutputTokens(),\n costMicrousd: 0,\n };\n groups.set(key, group);\n }\n group.modelCalls = yield* checkedAdd(\"byModel.modelCalls\", group.modelCalls, 1);\n group.webSearchCalls =\n group.webSearchCalls === undefined || call.webSearchCalls === undefined\n ? undefined\n : yield* checkedAdd(\"byModel.webSearchCalls\", group.webSearchCalls, call.webSearchCalls);\n group.inputTokens.total = yield* checkedAdd(\n \"byModel.inputTokens.total\",\n group.inputTokens.total,\n call.inputTokens.total,\n );\n group.inputTokens.uncached = yield* checkedAdd(\n \"byModel.inputTokens.uncached\",\n group.inputTokens.uncached,\n call.inputTokens.uncached,\n );\n group.inputTokens.cacheRead = yield* checkedAdd(\n \"byModel.inputTokens.cacheRead\",\n group.inputTokens.cacheRead,\n call.inputTokens.cacheRead,\n );\n group.inputTokens.cacheWrite = yield* checkedAdd(\n \"byModel.inputTokens.cacheWrite\",\n group.inputTokens.cacheWrite,\n call.inputTokens.cacheWrite,\n );\n group.outputTokens.total = yield* checkedAdd(\n \"byModel.outputTokens.total\",\n group.outputTokens.total,\n call.outputTokens.total,\n );\n group.outputTokens.text = yield* checkedAdd(\n \"byModel.outputTokens.text\",\n group.outputTokens.text,\n call.outputTokens.text,\n );\n group.outputTokens.reasoning = yield* checkedAdd(\n \"byModel.outputTokens.reasoning\",\n group.outputTokens.reasoning,\n call.outputTokens.reasoning,\n );\n group.costMicrousd = yield* checkedAdd(\n \"byModel.costMicrousd\",\n group.costMicrousd,\n call.costMicrousd,\n );\n }\n\n return RunUsageSummary.make({\n modelCalls,\n ...(webSearchCalls === undefined ? {} : { webSearchCalls }),\n inputTokens: InputTokenUsage.make(inputTokens),\n outputTokens: OutputTokenUsage.make(outputTokens),\n costMicrousd,\n usageStatus: allUsageUnknown ? \"unknown\" : allUsageComplete ? \"complete\" : \"partial\",\n pricingStatus: allPricingUnknown ? \"unknown\" : allPricingComplete ? \"complete\" : \"partial\",\n ...(initial?.unobservedModelCalls === undefined\n ? {}\n : { unobservedModelCalls: initial.unobservedModelCalls }),\n byModel: [...groups.values()].map((group) =>\n ModelUsageGroup.make({\n provider: group.provider,\n model: group.model,\n ...(group.responseModel === undefined ? {} : { responseModel: group.responseModel }),\n ...(group.serviceTier === undefined ? {} : { serviceTier: group.serviceTier }),\n ...(group.pricingVersion === undefined ? {} : { pricingVersion: group.pricingVersion }),\n modelCalls: group.modelCalls,\n ...(group.webSearchCalls === undefined ? {} : { webSearchCalls: group.webSearchCalls }),\n inputTokens: InputTokenUsage.make(group.inputTokens),\n outputTokens: OutputTokenUsage.make(group.outputTokens),\n costMicrousd: group.costMicrousd,\n }),\n ),\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,gBAAgB,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC;;AAGzE,IAAa,wBAAb,cAA2C,OAAO,MAChD,0CACF,CAAC,CAAC;CACA,IAAI,OAAO,YAAY,aAAa;CACpC,OAAO,OAAO,YAAY,aAAa;AACzC,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAa,oBAAoB,OAAO,SAAS;CAAC;CAAY;CAAW;AAAS,CAAC;AAEnF,MAAM,oBAAoB,OAAe,eAA+C;CACtF,MAAM,MAAM,WAAW,QAAQ,aAAa,cAAc,cAAc,WAAW,CAAC;CAEpF,OAAO,OAAO,cAAc,GAAG,KAAK,UAAU;AAChD;AAEA,MAAM,wBAAwB,OAAO,OAAO;CAC1C,OAAO,OAAO;CACd,UAAU,OAAO;CACjB,WAAW,OAAO;CAClB,YAAY,OAAO;AACrB,CAAC,CAAC,CAAC,MACD,OAAO,YACJ,UAAU,iBAAiB,MAAM,OAAO;CAAC,MA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AK,MAAM,YAAY;GACtD,cAAc,MAAM;EACtB,CAAC,CACH;CACF,CAAC;AACH,CAAC"}
@@ -1,2 +1,2 @@
1
- import { C as renderRecoveryExplanation, S as recoveryDecisionMeaning, _ as RetryCommand, a as IntegrityCheck, b as obligationSeverityOf, c as IntegrityReport, d as ObligationReport, f as ObligationSeverity, g as RecoveryExplanation, h as RecoveryDisposition, i as ExplainedUnknownCall, l as ObligationBlockedOn, m as RECOVERY_DECISION_MEANINGS, n as ExplainedEvidence, o as IntegrityCheckName, p as ObligationThresholds, r as ExplainedSubmission, s as IntegrityCheckStatus, u as ObligationEntry, v as RetryRefusalReason, x as predictRecoveryDisposition, y as RetryRefused } from "../Admin-BX9ns28E.mjs";
1
+ import { C as renderRecoveryExplanation, S as recoveryDecisionMeaning, _ as RetryCommand, a as IntegrityCheck, b as obligationSeverityOf, c as IntegrityReport, d as ObligationReport, f as ObligationSeverity, g as RecoveryExplanation, h as RecoveryDisposition, i as ExplainedUnknownCall, l as ObligationBlockedOn, m as RECOVERY_DECISION_MEANINGS, n as ExplainedEvidence, o as IntegrityCheckName, p as ObligationThresholds, r as ExplainedSubmission, s as IntegrityCheckStatus, u as ObligationEntry, v as RetryRefusalReason, x as predictRecoveryDisposition, y as RetryRefused } from "../Admin-BHmp2V9p.mjs";
2
2
  export { ExplainedEvidence, ExplainedSubmission, ExplainedUnknownCall, IntegrityCheck, IntegrityCheckName, IntegrityCheckStatus, IntegrityReport, ObligationBlockedOn, ObligationEntry, ObligationReport, ObligationSeverity, ObligationThresholds, RECOVERY_DECISION_MEANINGS, RecoveryDisposition, RecoveryExplanation, RetryCommand, RetryRefusalReason, RetryRefused, obligationSeverityOf, predictRecoveryDisposition, recoveryDecisionMeaning, renderRecoveryExplanation };
@@ -1,2 +1,2 @@
1
- import { As as DurableBindingFailure, Ds as BindingSelection, Es as AgentRegistration, Fs as compileBindingContracts, Is as compileRegistrations, Ls as definitionDigestsEqual, Ms as ExecutableAgentBinding, Ns as ReplayVersions, Os as BindingUnavailable, Ps as ResolvedBinding, Ts as AgentAttemptContext, js as DurableWorkerBinding, ks as CurrentBindingSelection } from "../Admin-BX9ns28E.mjs";
1
+ import { As as DurableBindingFailure, Ds as BindingSelection, Es as AgentRegistration, Fs as compileBindingContracts, Is as compileRegistrations, Ls as definitionDigestsEqual, Ms as ExecutableAgentBinding, Ns as ReplayVersions, Os as BindingUnavailable, Ps as ResolvedBinding, Ts as AgentAttemptContext, js as DurableWorkerBinding, ks as CurrentBindingSelection } from "../Admin-BHmp2V9p.mjs";
2
2
  export { type AgentAttemptContext, type AgentRegistration, type BindingSelection, BindingUnavailable, CurrentBindingSelection, type DurableBindingFailure, DurableWorkerBinding, type ExecutableAgentBinding, type ReplayVersions, type ResolvedBinding, compileBindingContracts, compileRegistrations, definitionDigestsEqual };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-D7D4PA-g.mjs";
2
- import { a as compileRegistrations, i as compileBindingContracts, n as CurrentBindingSelection, o as definitionDigestsEqual, r as DurableWorkerBinding, t as BindingUnavailable } from "../agent-registration-ByMZ_cK5.mjs";
2
+ import { a as compileRegistrations, i as compileBindingContracts, n as CurrentBindingSelection, o as definitionDigestsEqual, r as DurableWorkerBinding, t as BindingUnavailable } from "../agent-registration-DRbyhAu-.mjs";
3
3
  //#region src/durable/AgentRegistration.ts
4
4
  var AgentRegistration_exports = /* @__PURE__ */ __exportAll({
5
5
  BindingUnavailable: () => BindingUnavailable,
@@ -1,4 +1,4 @@
1
- import { Ui as ThreadStore, Wr as SettlementPublisher, dn as SubmissionLedger, vo as StorageOwner } from "../Admin-BX9ns28E.mjs";
1
+ import { Ui as ThreadStore, Wr as SettlementPublisher, dn as SubmissionLedger, vo as StorageOwner } from "../Admin-BHmp2V9p.mjs";
2
2
  import { Crypto, Effect, Schema } from "effect";
3
3
  //#region src/durable/Certification.d.ts
4
4
  declare const CertifiedAdapterIdentity_base: Schema.Class<CertifiedAdapterIdentity, Schema.Struct<{
@@ -1,7 +1,7 @@
1
1
  import { K as PersistedJson, d as CanonicalRecordEnvelope, p as CanonicalSequence } from "../Records-BTnGRdcf.mjs";
2
2
  import { ActivityProcessorKey, ActivityProcessorStore, ActivityStoreFailure, PreparedActivity } from "./ActivityStore.mjs";
3
3
  import { t as DigestError } from "../Digest-DjUgS5PG.mjs";
4
- import { Gi as ThreadStoreError, Mi as ThreadNotMaterialized, Ui as ThreadStore } from "../Admin-BX9ns28E.mjs";
4
+ import { Gi as ThreadStoreError, Mi as ThreadNotMaterialized, Ui as ThreadStore } from "../Admin-BHmp2V9p.mjs";
5
5
  import { Crypto, Effect, Schema, Scope } from "effect";
6
6
  declare namespace CommittedActivity_d_exports {
7
7
  export { ActivityPassLimits, ActivityPassResult, ActivityProcessingError, CommittedActivityProcessor, activityWorkId, processCommittedActivity };
@@ -1,8 +1,8 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { U as PersistedJson, f as CanonicalSequence, u as CanonicalRecordEnvelope } from "../Records-BiuJDWNe.mjs";
3
3
  import { ActivityProcessorKey, ActivityProcessorStore, ActivityProgress, PreparedActivity } from "./ActivityStore.mjs";
4
- import { s as digestJson } from "../Digest-DCuPlhNk.mjs";
5
- import { $ as ThreadTailRequest, J as ThreadStore, Q as ThreadTail, V as ThreadRead } from "../ThreadStore-CEekRa80.mjs";
4
+ import { s as digestJson } from "../Digest-EpeqWEdv.mjs";
5
+ import { $ as ThreadTailRequest, J as ThreadStore, Q as ThreadTail, V as ThreadRead } from "../ThreadStore-59uDGXul.mjs";
6
6
  import { Clock, Effect, Schema, Stream } from "effect";
7
7
  //#region src/durable/CommittedActivity.ts
8
8
  var CommittedActivity_exports = /* @__PURE__ */ __exportAll({
@@ -1,3 +1,3 @@
1
1
  import { n as utf8ByteLength } from "../utf8-B5pAmhTo.mjs";
2
- import { a as digestDefinition, i as digestCanonicalJson, o as digestDefinitions, r as canonicalJson, s as digestJson, t as DigestError } from "../Digest-DCuPlhNk.mjs";
2
+ import { a as digestDefinition, i as digestCanonicalJson, o as digestDefinitions, r as canonicalJson, s as digestJson, t as DigestError } from "../Digest-EpeqWEdv.mjs";
3
3
  export { DigestError, canonicalJson, digestCanonicalJson, digestDefinition, digestDefinitions, digestJson, utf8ByteLength };
@@ -1,3 +1,3 @@
1
1
  import { a as Receipt } from "../Receipt-BkM21Qiu.mjs";
2
- import { $n as DurableAwaitFailure, Cr as recoveryRepairBatchId, Er as threadCreatedRecordId, Jn as DurableAgentRuntime, Kn as ApprovalSuspensionError, Qn as DurableApprovalSuspension, Sr as isolateRecovery, Tr as threadCreatedBatchId, Xn as DurableApprovalFailure, Zn as DurableApprovalResolver, _r as RecoverySweepOptions, ar as DurableRetryFailure, br as WorkRecoveryRequest, cr as DurableSubmitAgent, dr as DurableVerifyFailure, er as DurableExplainFailure, fr as DurableWorkerFailure, gr as RecoveryReport, hr as RecoveryFailure, ir as DurableResolveFailure, lr as DurableSubmitFailure, mr as RecoveryBlocked, nr as DurableObserveOptions, or as DurableRuntimeConfig, pr as DurableWorkerRequirements, qn as DurableAbortFailure, rr as DurableProgressFailure, sr as DurableRuntimeConfigOptions, tr as DurableObligationFailure, ur as DurableSubmitOptions, vr as RecoverySweepResult, wr as recoveryRepairRecordId, xr as childReservationIdFor, yr as WorkRecoveryReport } from "../Admin-BX9ns28E.mjs";
2
+ import { $n as DurableAwaitFailure, Cr as recoveryRepairBatchId, Er as threadCreatedRecordId, Jn as DurableAgentRuntime, Kn as ApprovalSuspensionError, Qn as DurableApprovalSuspension, Sr as isolateRecovery, Tr as threadCreatedBatchId, Xn as DurableApprovalFailure, Zn as DurableApprovalResolver, _r as RecoverySweepOptions, ar as DurableRetryFailure, br as WorkRecoveryRequest, cr as DurableSubmitAgent, dr as DurableVerifyFailure, er as DurableExplainFailure, fr as DurableWorkerFailure, gr as RecoveryReport, hr as RecoveryFailure, ir as DurableResolveFailure, lr as DurableSubmitFailure, mr as RecoveryBlocked, nr as DurableObserveOptions, or as DurableRuntimeConfig, pr as DurableWorkerRequirements, qn as DurableAbortFailure, rr as DurableProgressFailure, sr as DurableRuntimeConfigOptions, tr as DurableObligationFailure, ur as DurableSubmitOptions, vr as RecoverySweepResult, wr as recoveryRepairRecordId, xr as childReservationIdFor, yr as WorkRecoveryReport } from "../Admin-BHmp2V9p.mjs";
3
3
  export { ApprovalSuspensionError, DurableAbortFailure, DurableAgentRuntime, DurableApprovalFailure, DurableApprovalResolver, DurableApprovalSuspension, DurableAwaitFailure, DurableExplainFailure, DurableObligationFailure, DurableObserveOptions, DurableProgressFailure, DurableResolveFailure, DurableRetryFailure, DurableRuntimeConfig, DurableRuntimeConfigOptions, DurableSubmitAgent, DurableSubmitFailure, DurableSubmitOptions, DurableVerifyFailure, DurableWorkerFailure, DurableWorkerRequirements, Receipt, RecoveryBlocked, RecoveryFailure, RecoveryReport, RecoverySweepOptions, RecoverySweepResult, WorkRecoveryReport, WorkRecoveryRequest, childReservationIdFor, isolateRecovery, recoveryRepairBatchId, recoveryRepairRecordId, threadCreatedBatchId, threadCreatedRecordId };
@@ -1,4 +1,4 @@
1
1
  import { Receipt } from "../core/Receipt.mjs";
2
- import { a as DurableApprovalSuspension, c as RecoveryFailure, d as WorkRecoveryReport, f as WorkRecoveryRequest, g as recoveryRepairRecordId, h as recoveryRepairBatchId, i as DurableApprovalResolver, l as RecoveryReport, m as isolateRecovery, n as DurableAgentRuntime, o as DurableRuntimeConfig, p as childReservationIdFor, s as RecoveryBlocked, t as ApprovalSuspensionError, u as RecoverySweepResult } from "../DurableAgentRuntime-BAmSkWYr.mjs";
3
- import { c as threadCreatedBatchId, l as threadCreatedRecordId } from "../WorkerAdmission-DFVbbVh2.mjs";
2
+ import { a as DurableApprovalSuspension, c as RecoveryFailure, d as WorkRecoveryReport, f as WorkRecoveryRequest, g as recoveryRepairRecordId, h as recoveryRepairBatchId, i as DurableApprovalResolver, l as RecoveryReport, m as isolateRecovery, n as DurableAgentRuntime, o as DurableRuntimeConfig, p as childReservationIdFor, s as RecoveryBlocked, t as ApprovalSuspensionError, u as RecoverySweepResult } from "../DurableAgentRuntime-CBBjRNJN.mjs";
3
+ import { c as threadCreatedBatchId, l as threadCreatedRecordId } from "../WorkerAdmission-DDYJdOsU.mjs";
4
4
  export { ApprovalSuspensionError, DurableAgentRuntime, DurableApprovalResolver, DurableApprovalSuspension, DurableRuntimeConfig, Receipt, RecoveryBlocked, RecoveryFailure, RecoveryReport, RecoverySweepResult, WorkRecoveryReport, WorkRecoveryRequest, childReservationIdFor, isolateRecovery, recoveryRepairBatchId, recoveryRepairRecordId, threadCreatedBatchId, threadCreatedRecordId };
@@ -1,2 +1,2 @@
1
- import { a as makeEventSource, i as NormalizedEvent, r as EventSources, t as EventSource } from "../EventSource-BwliwQz9.mjs";
1
+ import { a as makeEventSource, i as NormalizedEvent, r as EventSources, t as EventSource } from "../EventSource-C9aaJaXT.mjs";
2
2
  export { EventSource, EventSources, NormalizedEvent, makeEventSource };
@@ -32,19 +32,19 @@ const makeEventSource = Effect.fnUntraced(function* (options) {
32
32
  };
33
33
  });
34
34
  const normalize = (value) => Schema.decodeUnknownEffect(PersistedJson)(value).pipe(Effect.flatMap(Schema.decodeUnknownEffect(options.event)), Effect.mapError(invalid), Effect.flatMap(normalized), Effect.scoped, Effect.provideContext(services));
35
- const parameters = (value) => Effect.gen(function* () {
35
+ const parameters = Effect.fnUntraced(function* (value) {
36
36
  yield* Schema.decodeUnknownEffect(PersistedJson)(value).pipe(Effect.mapError(invalid));
37
37
  const decoded = yield* Schema.decodeUnknownEffect(options.parameters)(value).pipe(Effect.mapError(invalid));
38
38
  return {
39
39
  parameters: yield* encode(options.parameters, decoded),
40
40
  matchingKey: options.parameterKey(decoded)
41
41
  };
42
- }).pipe(Effect.scoped, Effect.provideContext(services));
43
- const matches = (event, subscription) => Effect.gen(function* () {
42
+ }, (effect) => effect.pipe(Effect.scoped, Effect.provideContext(services)));
43
+ const matches = Effect.fnUntraced(function* (event, subscription) {
44
44
  const e = yield* Schema.decodeEffect(options.event)(event.payload).pipe(Effect.mapError(invalid));
45
45
  const p = yield* Schema.decodeEffect(options.parameters)(subscription.configuration.parameters).pipe(Effect.mapError(invalid));
46
46
  return options.matches(e, p);
47
- }).pipe(Effect.scoped, Effect.provideContext(services));
47
+ }, (effect) => effect.pipe(Effect.scoped, Effect.provideContext(services)));
48
48
  const reconcile = options.reconcile;
49
49
  return {
50
50
  source: options.source,
@@ -52,11 +52,11 @@ const makeEventSource = Effect.fnUntraced(function* (options) {
52
52
  parameters,
53
53
  normalize,
54
54
  matches,
55
- ...reconcile === void 0 ? {} : { reconcile: (subscription) => Effect.gen(function* () {
55
+ ...reconcile === void 0 ? {} : { reconcile: Effect.fnUntraced(function* (subscription) {
56
56
  const p = yield* Schema.decodeEffect(options.parameters)(subscription.configuration.parameters).pipe(Effect.mapError(invalid));
57
57
  const event = yield* reconcile(p);
58
58
  return event === null ? null : yield* normalized(event);
59
- }).pipe(Effect.scoped, Effect.provideContext(services)) }
59
+ }, (effect) => effect.pipe(Effect.scoped, Effect.provideContext(services))) }
60
60
  };
61
61
  });
62
62
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"EventSource.mjs","names":[],"sources":["../../src/durable/EventSource.ts"],"sourcesContent":["import { Context, Effect, Schema, type Scope } from \"effect\";\n\nimport { PersistedJson } from \"./Records.ts\";\nimport {\n type AcceptedEvent,\n type EventSourceVersion,\n type SubscriptionRecord,\n SubscriptionSourceError,\n} from \"./Subscription.ts\";\n\nexport interface NormalizedEvent {\n readonly eventId: string;\n readonly occurredAtMillis?: number;\n readonly matchingKey: string;\n readonly payload: PersistedJson;\n}\n\n/** Runtime-only versioned behavior. Never persist this object or silently replace its version. */\nexport interface EventSource {\n readonly source: EventSourceVersion;\n readonly continuity: string;\n readonly parameters: (\n value: unknown,\n ) => Effect.Effect<\n { readonly parameters: PersistedJson; readonly matchingKey: string },\n SubscriptionSourceError\n >;\n readonly normalize: (value: unknown) => Effect.Effect<NormalizedEvent, SubscriptionSourceError>;\n readonly matches: (\n event: AcceptedEvent,\n subscription: SubscriptionRecord,\n ) => Effect.Effect<boolean, SubscriptionSourceError>;\n readonly reconcile?: (\n subscription: SubscriptionRecord,\n ) => Effect.Effect<NormalizedEvent | null, SubscriptionSourceError>;\n}\n\nexport class EventSources extends Context.Service<\n EventSources,\n {\n readonly sources: ReadonlyArray<EventSource>;\n }\n>()(\"@effect-agent/thread/EventSources\") {}\n\nconst invalid = () => SubscriptionSourceError.make({ code: \"source-schema\", retryable: false });\n\n/**\n * Capture the source's explicit Effect dependencies at host assembly. Matching and key functions\n * must be pure and bounded under this exact semantic version.\n * The returned source accepts Schema-encoded values at intake and management boundaries.\n * Each operation owns a fresh Scope for its callbacks and codecs; captured host services\n * retain their host lifetime. Operation resources finalize on success, failure, or interruption.\n */\nexport const makeEventSource = Effect.fnUntraced(function* <\n Event extends Schema.Top,\n Parameters extends Schema.Top,\n R = never,\n>(options: {\n readonly source: EventSourceVersion;\n readonly continuity: string;\n readonly event: Event;\n readonly parameters: Parameters;\n readonly identity: (event: Event[\"Type\"]) => string;\n /** Authenticated source time, stable across delivery retries; required for bounded retention. */\n readonly occurredAtMillis?: (event: Event[\"Type\"]) => number | undefined;\n readonly eventKey: (event: Event[\"Type\"]) => string;\n readonly parameterKey: (parameters: Parameters[\"Type\"]) => string;\n readonly matches: (event: Event[\"Type\"], parameters: Parameters[\"Type\"]) => boolean;\n readonly reconcile?: (\n parameters: Parameters[\"Type\"],\n ) => Effect.Effect<Event[\"Type\"] | null, SubscriptionSourceError, R>;\n}): Effect.fn.Return<\n EventSource,\n never,\n Exclude<\n | R\n | Event[\"DecodingServices\"]\n | Event[\"EncodingServices\"]\n | Parameters[\"DecodingServices\"]\n | Parameters[\"EncodingServices\"],\n Scope.Scope\n >\n> {\n const services =\n yield* Effect.context<\n Exclude<\n | R\n | Event[\"DecodingServices\"]\n | Event[\"EncodingServices\"]\n | Parameters[\"DecodingServices\"]\n | Parameters[\"EncodingServices\"],\n Scope.Scope\n >\n >();\n\n const encode = <S extends Schema.Top>(schema: S, value: S[\"Type\"]) =>\n Schema.encodeEffect(schema)(value).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(PersistedJson)),\n Effect.mapError(invalid),\n );\n\n const normalized = Effect.fnUntraced(function* (event: Event[\"Type\"]) {\n const occurredAtMillis = options.occurredAtMillis?.(event);\n\n return {\n eventId: options.identity(event),\n ...(occurredAtMillis === undefined ? {} : { occurredAtMillis }),\n matchingKey: options.eventKey(event),\n payload: yield* encode(options.event, event),\n };\n });\n\n const normalize: EventSource[\"normalize\"] = (value) =>\n Schema.decodeUnknownEffect(PersistedJson)(value).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(options.event)),\n Effect.mapError(invalid),\n Effect.flatMap(normalized),\n Effect.scoped,\n Effect.provideContext(services),\n );\n\n const parameters: EventSource[\"parameters\"] = (value) =>\n Effect.gen(function* () {\n yield* Schema.decodeUnknownEffect(PersistedJson)(value).pipe(Effect.mapError(invalid));\n\n const decoded = yield* Schema.decodeUnknownEffect(options.parameters)(value).pipe(\n Effect.mapError(invalid),\n );\n\n return {\n parameters: yield* encode(options.parameters, decoded),\n matchingKey: options.parameterKey(decoded),\n };\n }).pipe(Effect.scoped, Effect.provideContext(services));\n\n const matches: EventSource[\"matches\"] = (event, subscription) =>\n Effect.gen(function* () {\n const e = yield* Schema.decodeEffect(options.event)(event.payload).pipe(\n Effect.mapError(invalid),\n );\n\n const p = yield* Schema.decodeEffect(options.parameters)(\n subscription.configuration.parameters,\n ).pipe(Effect.mapError(invalid));\n\n return options.matches(e, p);\n }).pipe(Effect.scoped, Effect.provideContext(services));\n\n const reconcile = options.reconcile;\n\n return {\n source: options.source,\n continuity: options.continuity,\n parameters,\n normalize,\n matches,\n ...(reconcile === undefined\n ? {}\n : {\n reconcile: (subscription: SubscriptionRecord) =>\n Effect.gen(function* () {\n const p = yield* Schema.decodeEffect(options.parameters)(\n subscription.configuration.parameters,\n ).pipe(Effect.mapError(invalid));\n\n const event = yield* reconcile(p);\n\n return event === null ? null : yield* normalized(event);\n }).pipe(Effect.scoped, Effect.provideContext(services)),\n }),\n };\n});\n"],"mappings":";;;;;;;;;AAqCA,IAAa,eAAb,cAAkC,QAAQ,QAKxC,CAAC,CAAC,mCAAmC,CAAC,CAAC,CAAC;AAE1C,MAAM,gBAAgB,wBAAwB,KAAK;CAAE,MAAM;CAAiB,WAAW;AAAM,CAAC;;;;;;;;AAS9F,MAAa,kBAAkB,OAAO,WAAW,WAI/C,SAyBA;CACA,MAAM,WACJ,OAAO,OAAO,QASZ;CAEJ,MAAM,UAAgC,QAAW,UAC/C,OAAO,aAAa,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KACjC,OAAO,QAAQ,OAAO,oBAAoB,aAAa,CAAC,GACxD,OAAO,SAAS,OAAO,CACzB;CAEF,MAAM,aAAa,OAAO,WAAW,WAAW,OAAsB;EACpE,MAAM,mBAAmB,QAAQ,mBAAmB,KAAK;EAEzD,OAAO;GACL,SAAS,QAAQ,SAAS,KAAK;GAC/B,GAAI,qBAAqB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB;GAC7D,aAAa,QAAQ,SAAS,KAAK;GACnC,SAAS,OAAO,OAAO,QAAQ,OAAO,KAAK;EAC7C;CACF,CAAC;CAED,MAAM,aAAuC,UAC3C,OAAO,oBAAoB,aAAa,CAAC,CAAC,KAAK,CAAC,CAAC,KAC/C,OAAO,QAAQ,OAAO,oBAAoB,QAAQ,KAAK,CAAC,GACxD,OAAO,SAAS,OAAO,GACvB,OAAO,QAAQ,UAAU,GACzB,OAAO,QACP,OAAO,eAAe,QAAQ,CAChC;CAEF,MAAM,cAAyC,UAC7C,OAAO,IAAI,aAAa;EACtB,OAAO,OAAO,oBAAoB,aAAa,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,OAAO,SAAS,OAAO,CAAC;EAErF,MAAM,UAAU,OAAO,OAAO,oBAAoB,QAAQ,UAAU,CAAC,CAAC,KAAK,CAAC,CAAC,KAC3E,OAAO,SAAS,OAAO,CACzB;EAEA,OAAO;GACL,YAAY,OAAO,OAAO,QAAQ,YAAY,OAAO;GACrD,aAAa,QAAQ,aAAa,OAAO;EAC3C;CACF,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,eAAe,QAAQ,CAAC;CAExD,MAAM,WAAmC,OAAO,iBAC9C,OAAO,IAAI,aAAa;EACtB,MAAM,IAAI,OAAO,OAAO,aAAa,QAAQ,KAAK,CAAC,CAAC,MAAM,OAAO,CAAC,CAAC,KACjE,OAAO,SAAS,OAAO,CACzB;EAEA,MAAM,IAAI,OAAO,OAAO,aAAa,QAAQ,UAAU,CAAC,CACtD,aAAa,cAAc,UAC7B,CAAC,CAAC,KAAK,OAAO,SAAS,OAAO,CAAC;EAE/B,OAAO,QAAQ,QAAQ,GAAG,CAAC;CAC7B,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,eAAe,QAAQ,CAAC;CAExD,MAAM,YAAY,QAAQ;CAE1B,OAAO;EACL,QAAQ,QAAQ;EAChB,YAAY,QAAQ;EACpB;EACA;EACA;EACA,GAAI,cAAc,KAAA,IACd,CAAC,IACD,EACE,YAAY,iBACV,OAAO,IAAI,aAAa;GACtB,MAAM,IAAI,OAAO,OAAO,aAAa,QAAQ,UAAU,CAAC,CACtD,aAAa,cAAc,UAC7B,CAAC,CAAC,KAAK,OAAO,SAAS,OAAO,CAAC;GAE/B,MAAM,QAAQ,OAAO,UAAU,CAAC;GAEhC,OAAO,UAAU,OAAO,OAAO,OAAO,WAAW,KAAK;EACxD,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,eAAe,QAAQ,CAAC,EAC1D;CACN;AACF,CAAC"}
1
+ {"version":3,"file":"EventSource.mjs","names":[],"sources":["../../src/durable/EventSource.ts"],"sourcesContent":["import { Context, Effect, Schema, type Scope } from \"effect\";\n\nimport { PersistedJson } from \"./Records.ts\";\nimport {\n type AcceptedEvent,\n type EventSourceVersion,\n type SubscriptionRecord,\n SubscriptionSourceError,\n} from \"./Subscription.ts\";\n\nexport interface NormalizedEvent {\n readonly eventId: string;\n readonly occurredAtMillis?: number;\n readonly matchingKey: string;\n readonly payload: PersistedJson;\n}\n\n/** Runtime-only versioned behavior. Never persist this object or silently replace its version. */\nexport interface EventSource {\n readonly source: EventSourceVersion;\n readonly continuity: string;\n readonly parameters: (\n value: unknown,\n ) => Effect.Effect<\n { readonly parameters: PersistedJson; readonly matchingKey: string },\n SubscriptionSourceError\n >;\n readonly normalize: (value: unknown) => Effect.Effect<NormalizedEvent, SubscriptionSourceError>;\n readonly matches: (\n event: AcceptedEvent,\n subscription: SubscriptionRecord,\n ) => Effect.Effect<boolean, SubscriptionSourceError>;\n readonly reconcile?: (\n subscription: SubscriptionRecord,\n ) => Effect.Effect<NormalizedEvent | null, SubscriptionSourceError>;\n}\n\nexport class EventSources extends Context.Service<\n EventSources,\n {\n readonly sources: ReadonlyArray<EventSource>;\n }\n>()(\"@effect-agent/thread/EventSources\") {}\n\nconst invalid = () => SubscriptionSourceError.make({ code: \"source-schema\", retryable: false });\n\n/**\n * Capture the source's explicit Effect dependencies at host assembly. Matching and key functions\n * must be pure and bounded under this exact semantic version.\n * The returned source accepts Schema-encoded values at intake and management boundaries.\n * Each operation owns a fresh Scope for its callbacks and codecs; captured host services\n * retain their host lifetime. Operation resources finalize on success, failure, or interruption.\n */\nexport const makeEventSource = Effect.fnUntraced(function* <\n Event extends Schema.Top,\n Parameters extends Schema.Top,\n R = never,\n>(options: {\n readonly source: EventSourceVersion;\n readonly continuity: string;\n readonly event: Event;\n readonly parameters: Parameters;\n readonly identity: (event: Event[\"Type\"]) => string;\n /** Authenticated source time, stable across delivery retries; required for bounded retention. */\n readonly occurredAtMillis?: (event: Event[\"Type\"]) => number | undefined;\n readonly eventKey: (event: Event[\"Type\"]) => string;\n readonly parameterKey: (parameters: Parameters[\"Type\"]) => string;\n readonly matches: (event: Event[\"Type\"], parameters: Parameters[\"Type\"]) => boolean;\n readonly reconcile?: (\n parameters: Parameters[\"Type\"],\n ) => Effect.Effect<Event[\"Type\"] | null, SubscriptionSourceError, R>;\n}): Effect.fn.Return<\n EventSource,\n never,\n Exclude<\n | R\n | Event[\"DecodingServices\"]\n | Event[\"EncodingServices\"]\n | Parameters[\"DecodingServices\"]\n | Parameters[\"EncodingServices\"],\n Scope.Scope\n >\n> {\n const services =\n yield* Effect.context<\n Exclude<\n | R\n | Event[\"DecodingServices\"]\n | Event[\"EncodingServices\"]\n | Parameters[\"DecodingServices\"]\n | Parameters[\"EncodingServices\"],\n Scope.Scope\n >\n >();\n\n const encode = <S extends Schema.Top>(schema: S, value: S[\"Type\"]) =>\n Schema.encodeEffect(schema)(value).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(PersistedJson)),\n Effect.mapError(invalid),\n );\n\n const normalized = Effect.fnUntraced(function* (event: Event[\"Type\"]) {\n const occurredAtMillis = options.occurredAtMillis?.(event);\n\n return {\n eventId: options.identity(event),\n ...(occurredAtMillis === undefined ? {} : { occurredAtMillis }),\n matchingKey: options.eventKey(event),\n payload: yield* encode(options.event, event),\n };\n });\n\n const normalize: EventSource[\"normalize\"] = (value) =>\n Schema.decodeUnknownEffect(PersistedJson)(value).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(options.event)),\n Effect.mapError(invalid),\n Effect.flatMap(normalized),\n Effect.scoped,\n Effect.provideContext(services),\n );\n\n const parameters: EventSource[\"parameters\"] = Effect.fnUntraced(\n function* (value) {\n yield* Schema.decodeUnknownEffect(PersistedJson)(value).pipe(Effect.mapError(invalid));\n\n const decoded = yield* Schema.decodeUnknownEffect(options.parameters)(value).pipe(\n Effect.mapError(invalid),\n );\n\n return {\n parameters: yield* encode(options.parameters, decoded),\n matchingKey: options.parameterKey(decoded),\n };\n },\n (effect) => effect.pipe(Effect.scoped, Effect.provideContext(services)),\n );\n\n const matches: EventSource[\"matches\"] = Effect.fnUntraced(\n function* (event, subscription) {\n const e = yield* Schema.decodeEffect(options.event)(event.payload).pipe(\n Effect.mapError(invalid),\n );\n\n const p = yield* Schema.decodeEffect(options.parameters)(\n subscription.configuration.parameters,\n ).pipe(Effect.mapError(invalid));\n\n return options.matches(e, p);\n },\n (effect) => effect.pipe(Effect.scoped, Effect.provideContext(services)),\n );\n\n const reconcile = options.reconcile;\n\n return {\n source: options.source,\n continuity: options.continuity,\n parameters,\n normalize,\n matches,\n ...(reconcile === undefined\n ? {}\n : {\n reconcile: Effect.fnUntraced(\n function* (subscription: SubscriptionRecord) {\n const p = yield* Schema.decodeEffect(options.parameters)(\n subscription.configuration.parameters,\n ).pipe(Effect.mapError(invalid));\n\n const event = yield* reconcile(p);\n\n return event === null ? null : yield* normalized(event);\n },\n (effect) => effect.pipe(Effect.scoped, Effect.provideContext(services)),\n ),\n }),\n };\n});\n"],"mappings":";;;;;;;;;AAqCA,IAAa,eAAb,cAAkC,QAAQ,QAKxC,CAAC,CAAC,mCAAmC,CAAC,CAAC,CAAC;AAE1C,MAAM,gBAAgB,wBAAwB,KAAK;CAAE,MAAM;CAAiB,WAAW;AAAM,CAAC;;;;;;;;AAS9F,MAAa,kBAAkB,OAAO,WAAW,WAI/C,SAyBA;CACA,MAAM,WACJ,OAAO,OAAO,QASZ;CAEJ,MAAM,UAAgC,QAAW,UAC/C,OAAO,aAAa,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KACjC,OAAO,QAAQ,OAAO,oBAAoB,aAAa,CAAC,GACxD,OAAO,SAAS,OAAO,CACzB;CAEF,MAAM,aAAa,OAAO,WAAW,WAAW,OAAsB;EACpE,MAAM,mBAAmB,QAAQ,mBAAmB,KAAK;EAEzD,OAAO;GACL,SAAS,QAAQ,SAAS,KAAK;GAC/B,GAAI,qBAAqB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB;GAC7D,aAAa,QAAQ,SAAS,KAAK;GACnC,SAAS,OAAO,OAAO,QAAQ,OAAO,KAAK;EAC7C;CACF,CAAC;CAED,MAAM,aAA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AQ,UAAU,CAAC,CACtD,aAAa,cAAc,UAC7B,CAAC,CAAC,KAAK,OAAO,SAAS,OAAO,CAAC;GAE/B,MAAM,QAAQ,OAAO,UAAU,CAAC;GAEhC,OAAO,UAAU,OAAO,OAAO,OAAO,WAAW,KAAK;EACxD,IACC,WAAW,OAAO,KAAK,OAAO,QAAQ,OAAO,eAAe,QAAQ,CAAC,CACxE,EACF;CACN;AACF,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { r as Principal } from "../Receipt-BkM21Qiu.mjs";
2
- import "../Admin-BX9ns28E.mjs";
3
- import { E as SubscriptionSourceError } from "../Subscription-DONig54Q.mjs";
4
- import { t as EventSource } from "../EventSource-BwliwQz9.mjs";
2
+ import "../Admin-BHmp2V9p.mjs";
3
+ import { E as SubscriptionSourceError } from "../Subscription-BNg9VCRl.mjs";
4
+ import { t as EventSource } from "../EventSource-C9aaJaXT.mjs";
5
5
  import { SubscriptionFailure, SubscriptionIntake } from "./Subscriptions.mjs";
6
6
  import { Context, Effect, Layer, Redacted, Schema } from "effect";
7
7
  import { HttpClient } from "effect/http";
@@ -1,2 +1,2 @@
1
- import { ao as LifecyclePublicationConfig, co as LifecyclePublicationHandler, fo as drainLifecyclePublications, io as LifecyclePublicationBatch, lo as LifecyclePublicationSource, mo as lifecyclePublicationLayer, oo as LifecyclePublicationError, po as lifecyclePublicationBatchMaxFacts, ro as LifecyclePublication, so as LifecyclePublicationFact, uo as LifecyclePublicationStorage } from "../Admin-BX9ns28E.mjs";
1
+ import { ao as LifecyclePublicationConfig, co as LifecyclePublicationHandler, fo as drainLifecyclePublications, io as LifecyclePublicationBatch, lo as LifecyclePublicationSource, mo as lifecyclePublicationLayer, oo as LifecyclePublicationError, po as lifecyclePublicationBatchMaxFacts, ro as LifecyclePublication, so as LifecyclePublicationFact, uo as LifecyclePublicationStorage } from "../Admin-BHmp2V9p.mjs";
2
2
  export { LifecyclePublication, LifecyclePublicationBatch, LifecyclePublicationConfig, LifecyclePublicationError, LifecyclePublicationFact, LifecyclePublicationHandler, LifecyclePublicationSource, LifecyclePublicationStorage, drainLifecyclePublications, lifecyclePublicationBatchMaxFacts, lifecyclePublicationLayer };
@@ -4,7 +4,7 @@ import { Receipt } from "../core/Receipt.mjs";
4
4
  import { n as AssignmentTerminal } from "../Worker-DZjdMjZn.mjs";
5
5
  import { Ft as WorkerInputRequested, Nt as WorkerInputCompleted, Vt as WorkerStopRequested, _t as SubmissionSettledRecord, bt as ToolApprovalDecided, f as CanonicalSequence, ft as SubagentJoined, ht as SubagentStarted, kt as UserInputRecorded, lt as RunStartedRecord, mt as SubagentRequested, n as AgentUpdateEmitted, t as AbortRequested, xt as ToolApprovalRequested } from "../Records-BiuJDWNe.mjs";
6
6
  import { AbortIntent, Settlement, SubmissionLedger, SubmissionLookupById, SubmissionSnapshot, SuspensionReason } from "./SubmissionLedger.mjs";
7
- import { st as getRunInput } from "../ThreadStore-CEekRa80.mjs";
7
+ import { st as getRunInput } from "../ThreadStore-59uDGXul.mjs";
8
8
  import { PreparedInput } from "./Subscription.mjs";
9
9
  import { MessageDeliveryKey } from "./MessageDelivery.mjs";
10
10
  import { Cause, Clock, Context, Crypto, Effect, Layer, Option, Schema } from "effect";
@@ -1,2 +1,2 @@
1
- import { C as messageDeliveryKeyString, D as readPending, E as prepareMessageDelivery, O as sameMessageDeliveryIdentity, S as messageDeliveryDeadline, T as peerMessageRetentionDeadline, _ as applyMessageDeliveryChange, a as MessageDeliveryError, b as isWorkerUpdateDelivery, c as MessageDeliveryFailure, d as MessageDeliveryPageRequest, f as MessageDeliveryPolicy, h as MessageDeliveryStoreLimits, i as MessageDeliveryDriverLimits, k as validateMessageDelivery, l as MessageDeliveryKey, m as MessageDeliveryStore, n as MessageDeliveryCompletion, o as MessageDeliveryFailpoint, p as MessageDeliveryRecord, r as MessageDeliveryDriver, s as MessageDeliveryFailpointError, t as MessageDeliveryChange, u as MessageDeliveryPage, v as defaultMessageDeliveryPolicy, w as messageDeliveryUsesCapacity, x as messageDeliveryCapacity, y as defaultMessageDeliveryStoreLimits } from "../MessageDelivery-B943ebI_.mjs";
1
+ import { C as messageDeliveryKeyString, D as readPending, E as prepareMessageDelivery, O as sameMessageDeliveryIdentity, S as messageDeliveryDeadline, T as peerMessageRetentionDeadline, _ as applyMessageDeliveryChange, a as MessageDeliveryError, b as isWorkerUpdateDelivery, c as MessageDeliveryFailure, d as MessageDeliveryPageRequest, f as MessageDeliveryPolicy, h as MessageDeliveryStoreLimits, i as MessageDeliveryDriverLimits, k as validateMessageDelivery, l as MessageDeliveryKey, m as MessageDeliveryStore, n as MessageDeliveryCompletion, o as MessageDeliveryFailpoint, p as MessageDeliveryRecord, r as MessageDeliveryDriver, s as MessageDeliveryFailpointError, t as MessageDeliveryChange, u as MessageDeliveryPage, v as defaultMessageDeliveryPolicy, w as messageDeliveryUsesCapacity, x as messageDeliveryCapacity, y as defaultMessageDeliveryStoreLimits } from "../MessageDelivery-BGDm-c46.mjs";
2
2
  export { MessageDeliveryChange, MessageDeliveryCompletion, MessageDeliveryDriver, MessageDeliveryDriverLimits, MessageDeliveryError, MessageDeliveryFailpoint, MessageDeliveryFailpointError, MessageDeliveryFailure, MessageDeliveryKey, MessageDeliveryPage, MessageDeliveryPageRequest, MessageDeliveryPolicy, MessageDeliveryRecord, MessageDeliveryStore, MessageDeliveryStoreLimits, applyMessageDeliveryChange, defaultMessageDeliveryPolicy, defaultMessageDeliveryStoreLimits, isWorkerUpdateDelivery, messageDeliveryCapacity, messageDeliveryDeadline, messageDeliveryKeyString, messageDeliveryUsesCapacity, peerMessageRetentionDeadline, prepareMessageDelivery, readPending, sameMessageDeliveryIdentity, validateMessageDelivery };
@@ -4,7 +4,7 @@ import { IdempotencyKey, Receipt } from "../core/Receipt.mjs";
4
4
  import { o as Value, r as Diagnostic, s as capture } from "../FailureDiagnostic-D9oW23Cn.mjs";
5
5
  import { b as WorkerUpdate } from "../Worker-DZjdMjZn.mjs";
6
6
  import { b as Digest } from "../Records-BiuJDWNe.mjs";
7
- import { s as digestJson } from "../Digest-DCuPlhNk.mjs";
7
+ import { s as digestJson } from "../Digest-EpeqWEdv.mjs";
8
8
  import { Settlement } from "./SubmissionLedger.mjs";
9
9
  import { ScheduleInstant, ScheduleRetry, ScheduleRetryReason } from "./Schedule.mjs";
10
10
  import { PreparedInputAdmission, admitPreparedInput } from "./PreparedInputAdmission.mjs";
@@ -5,8 +5,8 @@ import { r as Diagnostic } from "../FailureDiagnostic-DvHruCSJ.mjs";
5
5
  import { t as AgentPolicy } from "../AgentPolicy-B4lbCU2T.mjs";
6
6
  import { b as DefinitionDigests } from "../Records-BTnGRdcf.mjs";
7
7
  import { t as DigestError } from "../Digest-DjUgS5PG.mjs";
8
- import { sn as Settlement } from "../Admin-BX9ns28E.mjs";
9
- import { a as MessageDeliveryError, c as MessageDeliveryFailure, m as MessageDeliveryStore } from "../MessageDelivery-B943ebI_.mjs";
8
+ import { sn as Settlement } from "../Admin-BHmp2V9p.mjs";
9
+ import { a as MessageDeliveryError, c as MessageDeliveryFailure, m as MessageDeliveryStore } from "../MessageDelivery-BGDm-c46.mjs";
10
10
  import { Effect, Schema } from "effect";
11
11
  //#region src/durable/MessageDeliveryStoreConformance.d.ts
12
12
  declare const MessageDeliveryConformanceViolation_base: Schema.Class<MessageDeliveryConformanceViolation, Schema.TaggedStruct<"MessageDeliveryConformanceViolation", {
@@ -3,7 +3,7 @@ import { IdempotencyKey, Principal, QueueSequence, Receipt } from "../core/Recei
3
3
  import { Update } from "../core/AgentUpdates.mjs";
4
4
  import { b as WorkerUpdate } from "../Worker-DZjdMjZn.mjs";
5
5
  import { b as Digest, v as DefinitionDigests } from "../Records-BiuJDWNe.mjs";
6
- import { s as digestJson } from "../Digest-DCuPlhNk.mjs";
6
+ import { s as digestJson } from "../Digest-EpeqWEdv.mjs";
7
7
  import { Settlement } from "./SubmissionLedger.mjs";
8
8
  import { MessageDeliveryStore, messageDeliveryCapacity, prepareMessageDelivery, readPending } from "./MessageDelivery.mjs";
9
9
  import { DateTime, Effect, Equal, Result, Schema } from "effect";
@@ -1,5 +1,5 @@
1
1
  import { t as ThreadHistory } from "../ThreadHistory-ByxS8HU1.mjs";
2
- import { Ui as ThreadStore, vo as StorageOwner } from "../Admin-BX9ns28E.mjs";
2
+ import { Ui as ThreadStore, vo as StorageOwner } from "../Admin-BHmp2V9p.mjs";
3
3
  import { Layer } from "effect";
4
4
  declare namespace PersistentHistory_d_exports {
5
5
  export { layer };
@@ -1,9 +1,9 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { ThreadHistory, ThreadHistoryError } from "../engine/ThreadHistory.mjs";
3
3
  import { L as ModelCompleted, U as PersistedJson, W as ProducerId, X as RecordEnvelope, Z as RecordId, c as CanonicalBatch, i as BatchId, kt as UserInputRecorded, nt as RunCompleted, y as DeploymentId } from "../Records-BiuJDWNe.mjs";
4
- import { _ as promptFromCanonicalRecords } from "../RunJournal-kfKVxJj7.mjs";
5
- import { F as ThreadIdentityRequest, I as ThreadMaterialization, J as ThreadStore, b as SelectedThreadRead, n as AppendRequest } from "../ThreadStore-CEekRa80.mjs";
6
- import { s as StorageOwner } from "../RunStorage-uqPxps09.mjs";
4
+ import { _ as promptFromCanonicalRecords } from "../RunJournal-CNZqA3Ge.mjs";
5
+ import { F as ThreadIdentityRequest, I as ThreadMaterialization, J as ThreadStore, b as SelectedThreadRead, n as AppendRequest } from "../ThreadStore-59uDGXul.mjs";
6
+ import { s as StorageOwner } from "../RunStorage-BHjuuERI.mjs";
7
7
  import { DateTime, Effect, Layer, Schema, Stream } from "effect";
8
8
  import { Prompt } from "effect/ai";
9
9
  //#region src/durable/PersistentHistory.ts
@@ -1,2 +1,2 @@
1
- import { r as admitPreparedInput, t as PreparedInputAdmission } from "../PreparedInputAdmission-CxSJSiTl.mjs";
1
+ import { r as admitPreparedInput, t as PreparedInputAdmission } from "../PreparedInputAdmission-BvDqlgiP.mjs";
2
2
  export { PreparedInputAdmission, admitPreparedInput };
@@ -31,7 +31,7 @@ const decodeExportRecordJson = (encoded) => parseRecordObject(encoded).pipe(Effe
31
31
  ...wire,
32
32
  wire
33
33
  })));
34
- const decodeView = SchemaGetter.transformEffect((value) => decodeRecord(value).pipe(Effect.map((record) => new ExportedRecord({
34
+ const decodeView = SchemaGetter.transformEffect((value) => decodeRecord(value).pipe(Effect.map((record) => ExportedRecord.make({
35
35
  ...record,
36
36
  wire: value
37
37
  }, { disableChecks: true })), Effect.mapError((error) => error.issue)));
@@ -64,7 +64,7 @@ const ReadEnvelope = Schema.Struct({
64
64
  ...CanonicalRecordEnvelope.fields,
65
65
  record: ReadRecord
66
66
  }).pipe(Schema.decodeTo(Schema.toType(CanonicalRecordEnvelope), {
67
- decode: SchemaGetter.transform((fields) => new CanonicalRecordEnvelope(fields, { disableChecks: true })),
67
+ decode: SchemaGetter.transform((fields) => CanonicalRecordEnvelope.make(fields, { disableChecks: true })),
68
68
  encode: SchemaGetter.transform((envelope) => envelope)
69
69
  }));
70
70
  /** Batch identity plus lossless record wire, used when checking a complete immutable log. */