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

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 (266) hide show
  1. package/dist/{Admin-BX9ns28E.d.mts → Admin-Qa3I1oA5.d.mts} +61 -21
  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-BfP14534.d.mts → AgentRuntime-CHDyRbSf.d.mts} +12 -12
  6. package/dist/{AgentRuntime-CQ-qcETl.mjs → AgentRuntime-DaDKMasp.mjs} +290 -273
  7. package/dist/AgentRuntime-DaDKMasp.mjs.map +1 -0
  8. package/dist/{Digest-DCuPlhNk.mjs → Digest-C3EODOee.mjs} +42 -15
  9. package/dist/Digest-C3EODOee.mjs.map +1 -0
  10. package/dist/{DurableAgentRuntime-BAmSkWYr.mjs → DurableAgentRuntime-CPlw5_7e.mjs} +1557 -1458
  11. package/dist/DurableAgentRuntime-CPlw5_7e.mjs.map +1 -0
  12. package/dist/{EventSource-BwliwQz9.d.mts → EventSource-BTu68yDW.d.mts} +2 -2
  13. package/dist/InMemory.d.mts +2 -2
  14. package/dist/{MessageDelivery-B943ebI_.d.mts → MessageDelivery-DjAZJ4Fd.d.mts} +42 -42
  15. package/dist/{Messaging-C_6OOg_s.d.mts → Messaging-SVu6rWV8.d.mts} +12 -6
  16. package/dist/{MessagingHost-B8oKM7AC.d.mts → MessagingHost-C6SOAcoG.d.mts} +2 -2
  17. package/dist/{MessagingHost-CRUK4JBi.mjs → MessagingHost-CZCyrnvJ.mjs} +27 -26
  18. package/dist/MessagingHost-CZCyrnvJ.mjs.map +1 -0
  19. package/dist/{Output-Dsx6k52t.d.mts → Output-CRamN1Fy.d.mts} +2 -2
  20. package/dist/{PreparedInputAdmission-CxSJSiTl.d.mts → PreparedInputAdmission-wgY4JMZY.d.mts} +3 -3
  21. package/dist/{Records-BiuJDWNe.mjs → Records-DzL4Kbtw.mjs} +2 -2
  22. package/dist/{Records-BiuJDWNe.mjs.map → Records-DzL4Kbtw.mjs.map} +1 -1
  23. package/dist/{RunContinuation-FHM7XPjq.d.mts → RunContinuation-3jB5pULC.d.mts} +13 -7
  24. package/dist/{RunContinuation-DHYNAQFi.mjs → RunContinuation-BiyKJK32.mjs} +173 -82
  25. package/dist/RunContinuation-BiyKJK32.mjs.map +1 -0
  26. package/dist/{RunJournal-kfKVxJj7.mjs → RunJournal-CPMKcfd0.mjs} +106 -73
  27. package/dist/RunJournal-CPMKcfd0.mjs.map +1 -0
  28. package/dist/{RunOptions-D8zxFIrZ.d.mts → RunOptions-Be77lKVZ.d.mts} +2 -2
  29. package/dist/{RunStorage-uqPxps09.mjs → RunStorage-CzutHJBE.mjs} +10 -6
  30. package/dist/RunStorage-CzutHJBE.mjs.map +1 -0
  31. package/dist/{Scheduling-CVyfXlBR.mjs → Scheduling-07_dsGED.mjs} +12 -12
  32. package/dist/Scheduling-07_dsGED.mjs.map +1 -0
  33. package/dist/{Subagent-vpffemql.mjs → Subagent-CexndZSp.mjs} +53 -40
  34. package/dist/Subagent-CexndZSp.mjs.map +1 -0
  35. package/dist/{Subagent-E6tvd7-k.d.mts → Subagent-xhN_aD1r.d.mts} +20 -9
  36. package/dist/{SubagentHost-B6w2m-SI.d.mts → SubagentHost-D1xBgn9g.d.mts} +2 -2
  37. package/dist/{Subscription-DONig54Q.d.mts → Subscription-DmIHlOJK.d.mts} +2 -2
  38. package/dist/{SubscriptionInput-mJIRxWJM.d.mts → SubscriptionInput-DgcQhvbe.d.mts} +2 -2
  39. package/dist/{Thread-dk-QiNml.d.mts → Thread-DzdJAY4J.d.mts} +4 -3
  40. package/dist/{ThreadHistory-ByxS8HU1.d.mts → ThreadHistory-KPPBJLJb.d.mts} +12 -2
  41. package/dist/{ThreadImport-DckUMEqJ.mjs → ThreadImport-CjlG57vH.mjs} +9 -9
  42. package/dist/ThreadImport-CjlG57vH.mjs.map +1 -0
  43. package/dist/{ThreadImport-DpHxjBrA.d.mts → ThreadImport-DP-vOk2F.d.mts} +5 -5
  44. package/dist/{ThreadStore-CEekRa80.mjs → ThreadStore-EuUilthA.mjs} +162 -85
  45. package/dist/ThreadStore-EuUilthA.mjs.map +1 -0
  46. package/dist/{ThreadTransfer-B4gTQLIl.mjs → ThreadTransfer-DB_zsrtJ.mjs} +4 -4
  47. package/dist/{ThreadTransfer-B4gTQLIl.mjs.map → ThreadTransfer-DB_zsrtJ.mjs.map} +1 -1
  48. package/dist/{WorkerAdmission-DFVbbVh2.mjs → WorkerAdmission-eBeXt_mu.mjs} +5 -5
  49. package/dist/{WorkerAdmission-DFVbbVh2.mjs.map → WorkerAdmission-eBeXt_mu.mjs.map} +1 -1
  50. package/dist/{agent-registration-ByMZ_cK5.mjs → agent-registration-a6QYaG3h.mjs} +70 -57
  51. package/dist/agent-registration-a6QYaG3h.mjs.map +1 -0
  52. package/dist/capabilities/Approval.mjs +2 -2
  53. package/dist/capabilities/Approval.mjs.map +1 -1
  54. package/dist/capabilities/BrowserUse.d.mts +102 -1867
  55. package/dist/capabilities/BrowserUse.mjs +74 -798
  56. package/dist/capabilities/BrowserUse.mjs.map +1 -1
  57. package/dist/capabilities/Budget.mjs +3 -1
  58. package/dist/capabilities/Budget.mjs.map +1 -1
  59. package/dist/capabilities/CodeMode.d.mts +1 -1
  60. package/dist/capabilities/CodeMode.mjs +16 -9
  61. package/dist/capabilities/CodeMode.mjs.map +1 -1
  62. package/dist/capabilities/Commands.d.mts +1 -1
  63. package/dist/capabilities/McpClient.mjs +1 -1
  64. package/dist/capabilities/McpClient.mjs.map +1 -1
  65. package/dist/capabilities/Messaging.d.mts +1 -1
  66. package/dist/capabilities/Messaging.mjs +5 -5
  67. package/dist/capabilities/Messaging.mjs.map +1 -1
  68. package/dist/capabilities/ModelContext.d.mts +1 -1
  69. package/dist/capabilities/ModelContext.mjs +7 -5
  70. package/dist/capabilities/ModelContext.mjs.map +1 -1
  71. package/dist/capabilities/Redaction.mjs +49 -19
  72. package/dist/capabilities/Redaction.mjs.map +1 -1
  73. package/dist/capabilities/RunHooks.d.mts +2 -2
  74. package/dist/capabilities/RunHooks.mjs +1 -1
  75. package/dist/capabilities/RunHooks.mjs.map +1 -1
  76. package/dist/capabilities/Subagent.d.mts +1 -1
  77. package/dist/capabilities/Subagent.mjs +1 -1
  78. package/dist/capabilities/SubagentReservations.mjs +3 -1
  79. package/dist/capabilities/SubagentReservations.mjs.map +1 -1
  80. package/dist/capabilities/WebCapture.mjs.map +1 -1
  81. package/dist/capabilities/WebSearch.mjs +7 -7
  82. package/dist/capabilities/WebSearch.mjs.map +1 -1
  83. package/dist/core/Agent.d.mts +1 -1
  84. package/dist/core/Agent.mjs +1 -1
  85. package/dist/core/AgentUpdates.mjs +8 -8
  86. package/dist/core/AgentUpdates.mjs.map +1 -1
  87. package/dist/core/Thread.d.mts +2 -2
  88. package/dist/core/Thread.mjs +6 -4
  89. package/dist/core/Thread.mjs.map +1 -1
  90. package/dist/core/Usage.mjs +2 -2
  91. package/dist/core/Usage.mjs.map +1 -1
  92. package/dist/durable/ActivityStore.mjs +1 -1
  93. package/dist/durable/Admin.d.mts +1 -1
  94. package/dist/durable/Admin.mjs +1 -1
  95. package/dist/durable/AgentRegistration.d.mts +1 -1
  96. package/dist/durable/AgentRegistration.mjs +1 -1
  97. package/dist/durable/Certification.d.mts +1 -1
  98. package/dist/durable/CommittedActivity.d.mts +1 -1
  99. package/dist/durable/CommittedActivity.mjs +3 -3
  100. package/dist/durable/Digest.mjs +1 -1
  101. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  102. package/dist/durable/DurableAgentRuntime.mjs +2 -2
  103. package/dist/durable/EventSource.d.mts +1 -1
  104. package/dist/durable/EventSource.mjs +7 -7
  105. package/dist/durable/EventSource.mjs.map +1 -1
  106. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  107. package/dist/durable/LifecyclePublication.d.mts +1 -1
  108. package/dist/durable/LifecyclePublication.mjs +2 -2
  109. package/dist/durable/MessageDelivery.d.mts +1 -1
  110. package/dist/durable/MessageDelivery.mjs +2 -2
  111. package/dist/durable/MessageDeliveryStoreConformance.d.mts +40 -40
  112. package/dist/durable/MessageDeliveryStoreConformance.mjs +2 -2
  113. package/dist/durable/PersistentHistory.d.mts +2 -2
  114. package/dist/durable/PersistentHistory.mjs +4 -4
  115. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  116. package/dist/durable/RecordFormat.mjs +3 -3
  117. package/dist/durable/RecordFormat.mjs.map +1 -1
  118. package/dist/durable/Records.mjs +1 -1
  119. package/dist/durable/Recovery.d.mts +1 -1
  120. package/dist/durable/Recovery.mjs +1 -1
  121. package/dist/durable/RunContinuation.d.mts +2 -2
  122. package/dist/durable/RunContinuation.mjs +3 -3
  123. package/dist/durable/RunJournal.d.mts +2 -2
  124. package/dist/durable/RunJournal.mjs +2 -2
  125. package/dist/durable/RunStorage.d.mts +1 -1
  126. package/dist/durable/RunStorage.mjs +1 -1
  127. package/dist/durable/Schedule.mjs +1 -1
  128. package/dist/durable/ScheduleStoreConformance.mjs +1 -1
  129. package/dist/durable/ScheduleTransition.mjs +1 -1
  130. package/dist/durable/Scheduling.d.mts +1 -1
  131. package/dist/durable/Scheduling.mjs +1 -1
  132. package/dist/durable/SettlementPublisher.d.mts +1 -1
  133. package/dist/durable/SettlementPublisher.mjs +3 -3
  134. package/dist/durable/SqlMemoryStore.mjs +5 -3
  135. package/dist/durable/SqlMemoryStore.mjs.map +1 -1
  136. package/dist/durable/SubmissionLedger.d.mts +1 -1
  137. package/dist/durable/SubmissionLedger.mjs +11 -3
  138. package/dist/durable/SubmissionLedger.mjs.map +1 -1
  139. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  140. package/dist/durable/SubmissionLedgerConformance.mjs +6 -6
  141. package/dist/durable/SubmissionStatus.d.mts +1 -1
  142. package/dist/durable/Subscription.d.mts +1 -1
  143. package/dist/durable/Subscription.mjs +2 -2
  144. package/dist/durable/SubscriptionInput.d.mts +1 -1
  145. package/dist/durable/SubscriptionInput.mjs +4 -4
  146. package/dist/durable/SubscriptionInput.mjs.map +1 -1
  147. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  148. package/dist/durable/SubscriptionStoreConformance.mjs +3 -3
  149. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -1
  150. package/dist/durable/SubscriptionTools.d.mts +2 -2
  151. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  152. package/dist/durable/SubscriptionTransition.mjs +1 -1
  153. package/dist/durable/Subscriptions.d.mts +5 -5
  154. package/dist/durable/Subscriptions.mjs +3 -3
  155. package/dist/durable/Subscriptions.mjs.map +1 -1
  156. package/dist/durable/ThreadArchiveRange.d.mts +1 -1
  157. package/dist/durable/ThreadArchiveRange.mjs +1 -1
  158. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  159. package/dist/durable/ThreadContextHistory.mjs +2 -2
  160. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
  161. package/dist/durable/ThreadImport.d.mts +1 -1
  162. package/dist/durable/ThreadImport.mjs +1 -1
  163. package/dist/durable/ThreadInvariants.d.mts +3 -3
  164. package/dist/durable/ThreadInvariants.mjs +5 -5
  165. package/dist/durable/ThreadInvariants.mjs.map +1 -1
  166. package/dist/durable/ThreadProjection.mjs +1 -1
  167. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  168. package/dist/durable/ThreadReader.d.mts +1 -1
  169. package/dist/durable/ThreadReader.mjs +1 -1
  170. package/dist/durable/ThreadStore.d.mts +1 -1
  171. package/dist/durable/ThreadStore.mjs +2 -2
  172. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  173. package/dist/durable/ThreadStoreConformance.mjs +4 -4
  174. package/dist/durable/ThreadTransfer.d.mts +1 -1
  175. package/dist/durable/ThreadTransfer.mjs +1 -1
  176. package/dist/durable/ThreadWork.d.mts +2 -2
  177. package/dist/durable/ThreadWork.mjs +12 -6
  178. package/dist/durable/ThreadWork.mjs.map +1 -1
  179. package/dist/durable/ToolReconciler.mjs +1 -1
  180. package/dist/durable/WakeScheduler.mjs +23 -39
  181. package/dist/durable/WakeScheduler.mjs.map +1 -1
  182. package/dist/durable/WorkerAdmission.d.mts +1 -1
  183. package/dist/durable/WorkerAdmission.mjs +1 -1
  184. package/dist/durable/WorkerHost.d.mts +2 -2
  185. package/dist/engine/AgentRuntime.d.mts +1 -1
  186. package/dist/engine/AgentRuntime.mjs +1 -1
  187. package/dist/engine/MessagingHost.d.mts +1 -1
  188. package/dist/engine/MessagingHost.mjs +1 -1
  189. package/dist/engine/Output.d.mts +1 -1
  190. package/dist/engine/Output.mjs +1 -1
  191. package/dist/engine/RunOptions.d.mts +1 -1
  192. package/dist/engine/SubagentHost.d.mts +1 -1
  193. package/dist/engine/ThreadHistory.d.mts +1 -1
  194. package/dist/engine/ThreadHistory.mjs +3 -2
  195. package/dist/engine/ThreadHistory.mjs.map +1 -1
  196. package/dist/index.d.mts +21 -21
  197. package/dist/index.mjs +16 -16
  198. package/dist/{output-contract-CMIhu4Cw.mjs → output-contract-DCnLYCdp.mjs} +12 -15
  199. package/dist/{output-contract-CMIhu4Cw.mjs.map → output-contract-DCnLYCdp.mjs.map} +1 -1
  200. package/dist/{run-context-reader-OcsZr4bk.d.mts → run-context-reader-DVhJZ1Qe.d.mts} +2 -2
  201. package/package.json +1 -1
  202. package/src/capabilities/Approval.ts +58 -60
  203. package/src/capabilities/BrowserUse.ts +89 -944
  204. package/src/capabilities/Budget.ts +8 -1
  205. package/src/capabilities/CodeMode.ts +57 -33
  206. package/src/capabilities/McpClient.ts +2 -2
  207. package/src/capabilities/Messaging.ts +51 -55
  208. package/src/capabilities/ModelContext.ts +5 -2
  209. package/src/capabilities/Redaction.ts +64 -34
  210. package/src/capabilities/RunHooks.ts +52 -55
  211. package/src/capabilities/Subagent.ts +33 -33
  212. package/src/capabilities/SubagentReservations.ts +9 -1
  213. package/src/capabilities/WebCapture.ts +6 -0
  214. package/src/capabilities/WebSearch.ts +10 -7
  215. package/src/capabilities/internal/subagent-background.ts +202 -158
  216. package/src/core/Agent.ts +11 -6
  217. package/src/core/AgentUpdates.ts +8 -8
  218. package/src/core/Thread.ts +142 -146
  219. package/src/core/Usage.ts +7 -8
  220. package/src/core/internal/agent-updates.ts +1 -0
  221. package/src/durable/DurableAgentRuntime.ts +1024 -829
  222. package/src/durable/EventSource.ts +15 -9
  223. package/src/durable/RecordFormat.ts +5 -3
  224. package/src/durable/RunContinuation.ts +316 -113
  225. package/src/durable/RunJournal.ts +106 -114
  226. package/src/durable/RunStorage.ts +129 -124
  227. package/src/durable/Scheduling.ts +639 -651
  228. package/src/durable/SqlMemoryStore.ts +8 -6
  229. package/src/durable/SubmissionLedger.ts +11 -0
  230. package/src/durable/SubscriptionInput.ts +5 -3
  231. package/src/durable/SubscriptionStoreConformance.ts +23 -23
  232. package/src/durable/Subscriptions.ts +18 -19
  233. package/src/durable/ThreadImport.ts +18 -19
  234. package/src/durable/ThreadInvariants.ts +2 -1
  235. package/src/durable/ThreadStore.ts +217 -111
  236. package/src/durable/ThreadWork.ts +11 -2
  237. package/src/durable/WakeScheduler.ts +34 -66
  238. package/src/durable/internal/StorageOwner.ts +10 -4
  239. package/src/durable/internal/agent-registration.ts +96 -89
  240. package/src/durable/internal/canonical-json.ts +61 -20
  241. package/src/durable/internal/prompt-history-cache.ts +13 -4
  242. package/src/durable/internal/record-encoding.ts +120 -64
  243. package/src/durable/internal/schedule-time.ts +6 -6
  244. package/src/durable/internal/usage-totals.ts +35 -0
  245. package/src/durable/internal/worker-host.ts +69 -74
  246. package/src/engine/MessagingHost.ts +4 -2
  247. package/src/engine/ThreadHistory.ts +47 -48
  248. package/src/engine/internal/agent-runtime.ts +1298 -1217
  249. package/src/engine/internal/output-contract.ts +15 -15
  250. package/src/engine/internal/primitive-delta.ts +2 -3
  251. package/src/engine/internal/provisional-text.ts +12 -10
  252. package/src/engine/internal/tool-exposure.ts +22 -18
  253. package/src/engine/internal/tool-telemetry.ts +15 -12
  254. package/dist/Agent-0WvBWWbM.mjs.map +0 -1
  255. package/dist/AgentRuntime-CQ-qcETl.mjs.map +0 -1
  256. package/dist/Digest-DCuPlhNk.mjs.map +0 -1
  257. package/dist/DurableAgentRuntime-BAmSkWYr.mjs.map +0 -1
  258. package/dist/MessagingHost-CRUK4JBi.mjs.map +0 -1
  259. package/dist/RunContinuation-DHYNAQFi.mjs.map +0 -1
  260. package/dist/RunJournal-kfKVxJj7.mjs.map +0 -1
  261. package/dist/RunStorage-uqPxps09.mjs.map +0 -1
  262. package/dist/Scheduling-CVyfXlBR.mjs.map +0 -1
  263. package/dist/Subagent-vpffemql.mjs.map +0 -1
  264. package/dist/ThreadImport-DckUMEqJ.mjs.map +0 -1
  265. package/dist/ThreadStore-CEekRa80.mjs.map +0 -1
  266. package/dist/agent-registration-ByMZ_cK5.mjs.map +0 -1
@@ -2,13 +2,12 @@ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { ToolCallId } from "./core/Identifiers.mjs";
3
3
  import { n as utf8ByteLength } from "./utf8-B5pAmhTo.mjs";
4
4
  import { AgentPersistenceCapacityError } from "./core/AgentError.mjs";
5
- import { summarizeModelUsage } from "./core/Usage.mjs";
6
- import { G as PromptRecord, J as RUN_TERMINAL_RESERVE_BYTES, O as MAX_RUN_CONTINUATION_BYTES, V as PROMPT_EVIDENCE_TAGS, X as RecordEnvelope, Z as RecordId, c as CanonicalBatch, f as CanonicalSequence, it as RunContinuation, rt as RunContextRecorded, w as MAX_PERSISTED_JSON_BYTES, x as EvidenceReference } from "./Records-BiuJDWNe.mjs";
7
- import { i as digestCanonicalJson, r as canonicalJson } from "./Digest-DCuPlhNk.mjs";
5
+ import { G as PromptRecord, J as RUN_TERMINAL_RESERVE_BYTES, O as MAX_RUN_CONTINUATION_BYTES, V as PROMPT_EVIDENCE_TAGS, X as RecordEnvelope, Z as RecordId, c as CanonicalBatch, f as CanonicalSequence, it as RunContinuation, rt as RunContextRecorded, w as MAX_PERSISTED_JSON_BYTES, x as EvidenceReference } from "./Records-DzL4Kbtw.mjs";
6
+ import { i as digestCanonicalJson, r as canonicalJson } from "./Digest-C3EODOee.mjs";
8
7
  import { submissionAbortRecordId, submissionInputRecordId, submissionSettlementBatchId, submissionSettlementRecordId } from "./durable/SubmissionLedger.mjs";
9
- import { I as toolCallResultBatchId, Q as toolCallSettledRecordId, g as projectRunJournalStream, j as subagentStartedRecordId, k as subagentRequestedRecordId, t as RunJournalError, v as runCompletedRecordId, x as runIdForSubmission } from "./RunJournal-kfKVxJj7.mjs";
10
- import { U as ThreadReader, X as ThreadStoreError, _t as isPreContinuationFact, a as CommitBatch, bt as terminalUsageCharge, c as ExecutionUpdate, gt as executionRunIds, ht as canonicalRunIds, mt as recordEncoding, o as ExecutionCheckpoint, ot as getRecord, pt as captureRecord, st as getRunInput, vt as isTerminalBudgetFact, yt as isWorkHandoff } from "./ThreadStore-CEekRa80.mjs";
11
- import { Context, Crypto, DateTime, Effect, Layer, Option, Schema, Semaphore, Stream } from "effect";
8
+ import { A as subagentRequestedRecordId, L as toolCallResultBatchId, M as subagentStartedRecordId, Q as continuationUsage, S as runIdForSubmission, _ as projectRunJournalStream, et as toolCallSettledRecordId, t as RunJournalError, y as runCompletedRecordId } from "./RunJournal-CPMKcfd0.mjs";
9
+ import { U as ThreadReader, X as ThreadStoreError, _t as isPreContinuationFact, a as CommitBatch, bt as terminalUsageCharge, c as ExecutionUpdate, gt as executionRunIds, ht as canonicalRunIds, mt as recordEncoding, o as ExecutionCheckpoint, ot as getRecord, pt as captureRecord, st as getRunInput, vt as isTerminalBudgetFact, yt as isWorkHandoff } from "./ThreadStore-EuUilthA.mjs";
10
+ import { Context, DateTime, Effect, Layer, Option, Result, Schema, Semaphore, Stream } from "effect";
12
11
  import { Prompt } from "effect/ai";
13
12
  //#region src/durable/internal/evidence.ts
14
13
  const failure$1 = (message, cause) => ThreadStoreError.make({
@@ -173,33 +172,74 @@ const failure = (message, cause) => ThreadStoreError.make({
173
172
  const capacityFailure = (message) => failure(message, AgentPersistenceCapacityError.make({ message }));
174
173
  const isExecutionProgressRecord = (record) => record.payload._tag === "RunContinuation";
175
174
  const decodeResponsePrompt = Schema.decodeUnknownEffect(Prompt.Prompt);
176
- const validateBatchHeader = Schema.decodeSync(Schema.Struct({
175
+ const responsePrompts = /* @__PURE__ */ new WeakMap();
176
+ /** Cache eligibility only: freezing does not make accessors or custom iterators immutable. */
177
+ const isFrozenJsonData = (input) => {
178
+ const pending = [input];
179
+ const seen = /* @__PURE__ */ new WeakSet();
180
+ while (pending.length > 0) {
181
+ const value = pending.pop();
182
+ if (value === null) continue;
183
+ if (typeof value !== "object") {
184
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") return false;
185
+ continue;
186
+ }
187
+ if (seen.has(value)) continue;
188
+ seen.add(value);
189
+ const prototype = Object.getPrototypeOf(value);
190
+ if (!Object.isFrozen(value) || prototype !== null && prototype !== Object.prototype && prototype !== Array.prototype) return false;
191
+ for (const key of Reflect.ownKeys(value)) {
192
+ if (typeof key !== "string") return false;
193
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
194
+ if (descriptor === void 0 || !("value" in descriptor)) return false;
195
+ pending.push(descriptor.value);
196
+ }
197
+ }
198
+ return true;
199
+ };
200
+ const validateBatchShape = Schema.decodeUnknownSync(Schema.Struct({
177
201
  batchId: CanonicalBatch.fields.batchId,
178
- producerId: CanonicalBatch.fields.producerId
202
+ producerId: CanonicalBatch.fields.producerId,
203
+ records: Schema.NonEmptyArray(Schema.Unknown).check(Schema.isMaxLength(256))
179
204
  }));
180
- const validateBatchCount = Schema.decodeUnknownSync(Schema.NonEmptyArray(Schema.Unknown).check(Schema.isMaxLength(256)));
181
205
  const ContinuationBytes = Schema.Struct({
182
206
  turnBytes: RunContinuation.fields.turnBytes,
183
207
  terminalBytes: RunContinuation.fields.terminalBytes
184
208
  });
209
+ const decodeExecutionFrontier = Schema.decodeUnknownEffect(Schema.Struct({
210
+ canonicalRecords: ExecutionCheckpoint.fields.canonicalRecords,
211
+ throughSequence: ExecutionCheckpoint.fields.throughSequence
212
+ }));
185
213
  /** One private snapshot for every retry; callers cannot change facts while awaiting the gate. */
186
214
  const captureFacts = (batch) => Effect.try({
187
- try: () => {
188
- const header = validateBatchHeader(batch);
189
- validateBatchCount(batch.records);
190
- const records = batch.records.map((record) => captureRecord(record).canonical);
191
- return Object.freeze(new CanonicalBatch({
192
- ...header,
215
+ try: () => Result.gen(function* () {
216
+ const inputs = batch.records;
217
+ const { batchId, producerId } = validateBatchShape({
218
+ batchId: batch.batchId,
219
+ producerId: batch.producerId,
220
+ records: inputs
221
+ });
222
+ const records = (yield* Result.all(inputs.map(captureRecord))).map((record) => record.canonical);
223
+ return Object.freeze(CanonicalBatch.make({
224
+ batchId,
225
+ producerId,
193
226
  records: [records[0], ...records.slice(1)]
194
227
  }, { disableChecks: true }));
195
- },
228
+ }),
196
229
  catch: (cause) => failure("Cannot capture canonical progress facts", cause)
197
- });
230
+ }).pipe(Effect.flatMap(Effect.fromResult), Effect.mapError((cause) => Schema.is(ThreadStoreError)(cause) ? cause : failure("Cannot capture canonical progress facts", cause)));
198
231
  /** Exact UTF-8 wire accounting reuses the append's privately captured Schema encoding. */
199
- const canonicalRecordBytes = (record) => recordEncoding(record).bytes;
232
+ const canonicalRecordBytes = (record) => {
233
+ const encoded = recordEncoding(record);
234
+ if (Result.isFailure(encoded)) throw encoded.failure.cause ?? new RangeError(encoded.failure.message);
235
+ return encoded.success.bytes;
236
+ };
200
237
  /** Capture before acquiring the mutation owner; summaries never cross a wire boundary. */
201
- const prepareProgressAppend = (records) => Object.freeze(records.map((record) => captureRecord(record).progress));
202
- const factUsageCharge = (facts) => facts.reduce((bytes, record) => bytes + recordEncoding(record).progress.terminalUsageBytes, 0);
238
+ const prepareProgressAppend = (records) => {
239
+ const encodings = Result.all(records.map(captureRecord));
240
+ if (Result.isFailure(encodings)) throw encodings.failure.cause ?? new RangeError(encodings.failure.message);
241
+ return Object.freeze(encodings.success.map((record) => record.progress));
242
+ };
203
243
  /** These values belong to the active Run, not its permanent conversation history. */
204
244
  const isOperationalRecord = ({ payload }) => payload._tag === "RunStarted" || payload._tag === "RunContextRecorded" || payload._tag === "RunCompleted";
205
245
  const readContinuation = Effect.fnUntraced(function* (threadId, runId, throughSequence) {
@@ -414,34 +454,55 @@ const advanceFacts = Effect.fnUntraced(function* (previous, facts, submissionId,
414
454
  let results = new Map(previous?.results);
415
455
  let childResults = new Map(previous?.childResults);
416
456
  let completionBytes = previous?.completionBytes;
457
+ let factBytes = 0;
458
+ let turn = previous?.continuation.turn ?? 1;
459
+ let usageCharge = 0;
460
+ let closingBytes = 0;
461
+ let closingCount = 0;
417
462
  for (const fact of facts) {
418
463
  const payload = fact.payload;
464
+ const captured = recordEncoding(fact);
465
+ if (Result.isFailure(captured)) return yield* failure("Cannot account canonical progress facts", captured.failure);
466
+ const encoded = captured.success;
467
+ factBytes += encoded.bytes;
468
+ if ("turn" in payload) turn = Math.max(turn, payload.turn);
469
+ usageCharge += encoded.progress.terminalUsageBytes;
470
+ if (encoded.progress.terminal) {
471
+ closingBytes += encoded.bytes;
472
+ closingCount++;
473
+ }
419
474
  switch (payload._tag) {
420
475
  case "RunStarted":
421
476
  position = "awaiting-model";
422
477
  break;
423
478
  case "RunContextRecorded":
424
479
  if (savedContext !== void 0) return yield* failure("A Run's original context cannot be replaced");
425
- savedContext = yield* reference(fact);
480
+ savedContext = EvidenceReference.make({ recordId: fact.recordId });
426
481
  position = "awaiting-model";
427
482
  break;
428
483
  case "ModelResponseRecorded": {
429
484
  if (savedContext === void 0) return yield* failure("A model response has no saved original Run context");
430
485
  if (payload.turn !== accounting.committedTurns + 1) return yield* failure("Canonical Turn progress must advance once");
431
- const messages = yield* decodeResponsePrompt(payload.messages).pipe(Effect.mapError((cause) => failure("Invalid model evidence", cause)));
486
+ const promptInput = payload.messages;
487
+ const retainedPrompt = responsePrompts.get(payload);
488
+ const messages = retainedPrompt ?? (yield* decodeResponsePrompt(promptInput).pipe(Effect.mapError((cause) => failure("Invalid model evidence", cause))));
489
+ if (retainedPrompt === void 0) {
490
+ const property = Object.getOwnPropertyDescriptor(payload, "messages");
491
+ if (Object.isFrozen(payload) && property !== void 0 && "value" in property && property.value === promptInput && isFrozenJsonData(promptInput)) responsePrompts.set(payload, messages);
492
+ }
432
493
  responsePrompt = messages;
433
494
  const calls = messages.content.flatMap((message) => message.role === "assistant" ? message.content.filter((part) => part.type === "tool-call") : []);
434
- const summary = payload.modelUsage === void 0 ? void 0 : yield* summarizeModelUsage(payload.modelUsage).pipe(Effect.mapError((cause) => failure("Invalid usage evidence", cause)));
495
+ const summary = payload.modelUsage === void 0 ? void 0 : yield* continuationUsage(payload.modelUsage).pipe(Effect.mapError((cause) => failure("Invalid usage evidence", cause)));
435
496
  accounting.committedTurns = payload.turn;
436
497
  accounting.toolCalls += calls.length;
437
498
  accounting.modelCalls += summary?.modelCalls ?? 1;
438
- accounting.inputTokens += summary?.inputTokens.total ?? payload.inputTokens ?? 0;
439
- accounting.outputTokens += summary?.outputTokens.total ?? payload.outputTokens ?? 0;
499
+ accounting.inputTokens += summary?.inputTokens ?? payload.inputTokens ?? 0;
500
+ accounting.outputTokens += summary?.outputTokens ?? payload.outputTokens ?? 0;
440
501
  accounting.costMicrousd += summary?.costMicrousd ?? payload.costMicrousd ?? 0;
441
- accounting.lastInputTokens = summary?.inputTokens.total ?? payload.inputTokens ?? 0;
442
- accounting.lastOutputTokens = summary?.outputTokens.total ?? payload.outputTokens ?? 0;
502
+ accounting.lastInputTokens = summary?.inputTokens ?? payload.inputTokens ?? 0;
503
+ accounting.lastOutputTokens = summary?.outputTokens ?? payload.outputTokens ?? 0;
443
504
  accounting.unobservedModelCalls += payload.unobservedModelCalls ?? 0;
444
- latestResponse = yield* reference(fact);
505
+ latestResponse = EvidenceReference.make({ recordId: fact.recordId });
445
506
  response = payload;
446
507
  results = /* @__PURE__ */ new Map();
447
508
  childResults = /* @__PURE__ */ new Map();
@@ -490,11 +551,11 @@ const advanceFacts = Effect.fnUntraced(function* (previous, facts, submissionId,
490
551
  break;
491
552
  case "ModelCallAborted": {
492
553
  if (payload.restart !== (accounting.modelRestarts ?? 0) + 1) return yield* failure("Model restart progress must advance once");
493
- const summary = yield* summarizeModelUsage(payload.modelUsage).pipe(Effect.mapError((cause) => failure("Invalid cancelled model usage", cause)));
554
+ const summary = yield* continuationUsage(payload.modelUsage).pipe(Effect.mapError((cause) => failure("Invalid cancelled model usage", cause)));
494
555
  accounting.modelRestarts = payload.restart;
495
556
  accounting.modelCalls += summary.modelCalls;
496
- accounting.inputTokens += summary.inputTokens.total;
497
- accounting.outputTokens += summary.outputTokens.total;
557
+ accounting.inputTokens += summary.inputTokens;
558
+ accounting.outputTokens += summary.outputTokens;
498
559
  accounting.costMicrousd += summary.costMicrousd;
499
560
  accounting.unobservedModelCalls += payload.unobservedModelCalls;
500
561
  break;
@@ -502,12 +563,12 @@ const advanceFacts = Effect.fnUntraced(function* (previous, facts, submissionId,
502
563
  case "RunCompleted":
503
564
  case "RunFailed":
504
565
  completionBytes = payload._tag === "RunCompleted" ? utf8ByteLength(JSON.stringify(payload.output)) + (payload.runDisposition === void 0 ? 0 : utf8ByteLength(JSON.stringify(payload.runDisposition))) : void 0;
505
- terminal = yield* reference(fact);
566
+ terminal = EvidenceReference.make({ recordId: fact.recordId });
506
567
  position = "settling";
507
568
  break;
508
569
  case "SubmissionSettled":
509
570
  if (payload.submissionId !== submissionId) break;
510
- terminal = yield* reference(fact);
571
+ terminal = EvidenceReference.make({ recordId: fact.recordId });
511
572
  position = "settled";
512
573
  if (payload.usageSummary !== void 0) {
513
574
  accounting.modelCalls = payload.usageSummary.modelCalls;
@@ -519,7 +580,7 @@ const advanceFacts = Effect.fnUntraced(function* (previous, facts, submissionId,
519
580
  }
520
581
  }
521
582
  if (response !== void 0 && response.turn > accounting.accountedToolTurn && response.toolOperations.every((operation) => results.has(operation.toolCallId))) {
522
- const parts = (responsePrompt ?? (yield* decodeResponsePrompt(response.messages).pipe(Effect.mapError((cause) => failure("Invalid batch evidence", cause))))).content.flatMap((message) => message.role === "assistant" ? message.content : []);
583
+ const parts = (responsePrompt ?? responsePrompts.get(response) ?? (yield* decodeResponsePrompt(response.messages).pipe(Effect.mapError((cause) => failure("Invalid batch evidence", cause))))).content.flatMap((message) => message.role === "assistant" ? message.content : []);
523
584
  for (const call of parts) {
524
585
  if (call.type !== "tool-call") continue;
525
586
  const result = call.providerExecuted ? parts.find((part) => part.type === "tool-result" && part.id === call.id) : results.get(ToolCallId.make(call.id));
@@ -534,12 +595,8 @@ const advanceFacts = Effect.fnUntraced(function* (previous, facts, submissionId,
534
595
  if (last === void 0) return yield* failure("Progress has no owning fact");
535
596
  if (previous?.continuation.position === "settled") position = "settled";
536
597
  else if (previous?.continuation.position === "settling" && position !== "settled") position = "settling";
537
- const factBytes = facts.reduce((bytes, fact) => bytes + canonicalRecordBytes(fact), 0);
538
- const turn = facts.reduce((current, fact) => "turn" in fact.payload ? Math.max(current, fact.payload.turn) : current, previous?.continuation.turn ?? 1);
539
598
  const turnBase = (previous?.continuation.turn === turn ? previous.continuation.turnBytes : initialBytes) + factBytes;
540
- const usageCharge = factUsageCharge(facts);
541
599
  const terminalUsageBytes = (previous?.continuation.terminalUsageBytes ?? 0) + usageCharge;
542
- const closing = facts.filter(isTerminalBudgetFact);
543
600
  return {
544
601
  accounting,
545
602
  savedContext,
@@ -556,9 +613,9 @@ const advanceFacts = Effect.fnUntraced(function* (previous, facts, submissionId,
556
613
  turnBase,
557
614
  usageCharge,
558
615
  terminalUsageBytes,
559
- terminalBytes: (previous?.continuation.terminalBytes ?? 0) + closing.reduce((bytes, fact) => bytes + canonicalRecordBytes(fact), 0),
560
- terminalRecords: (previous?.continuation.terminalRecords ?? 0) + closing.length,
561
- closing: closing.length > 0
616
+ terminalBytes: (previous?.continuation.terminalBytes ?? 0) + closingBytes,
617
+ terminalRecords: (previous?.continuation.terminalRecords ?? 0) + closingCount,
618
+ closing: closingCount > 0
562
619
  };
563
620
  });
564
621
  /**
@@ -598,15 +655,13 @@ const verifyRunContinuations = Effect.fnUntraced(function* (records, options) {
598
655
  */
599
656
  const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId) {
600
657
  const reader = yield* ThreadReader;
601
- const crypto = yield* Crypto.Crypto;
602
658
  const gate = yield* Semaphore.make(1);
603
659
  const cached = /* @__PURE__ */ new Map();
660
+ let verifiedEmpty;
604
661
  const reservations = /* @__PURE__ */ new Map();
605
662
  const stagedUsage = /* @__PURE__ */ new Map();
606
- const provide = (effect) => effect.pipe(Effect.provideService(ThreadReader, reader), Effect.provideService(Crypto.Crypto, crypto));
607
- const loadState = Effect.fnUntraced(function* (runId, after) {
608
- const retained = cached.get(runId);
609
- if (retained !== void 0) return retained;
663
+ const provide = (effect) => Effect.provideService(effect, ThreadReader, reader);
664
+ const loadUncachedState = Effect.fnUntraced(function* (runId, after) {
610
665
  const loaded = yield* provide(readContinuation(threadId, runId, after));
611
666
  if (Option.isNone(loaded)) return void 0;
612
667
  const continuation = loaded.value.continuation;
@@ -663,10 +718,10 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
663
718
  ...completionBytes === void 0 ? {} : { completionBytes }
664
719
  };
665
720
  });
666
- const checkFutureShapes = (state) => {
721
+ const checkFutureShapes = (state, cursorBytes) => {
667
722
  const progress = state.continuation;
668
723
  if (progress.position === "settled") return Effect.void;
669
- const size = canonicalRecordBytes(state.record);
724
+ const size = cursorBytes ?? canonicalRecordBytes(state.record);
670
725
  const textBytes = (value) => utf8ByteLength(JSON.stringify(value));
671
726
  const refBytes = (value) => utf8ByteLength(JSON.stringify(value));
672
727
  const ref = (recordId) => EvidenceReference.make({ recordId });
@@ -698,12 +753,9 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
698
753
  if (turnBytes > 4194304 || recordBytes > 33554432 || recordCount > 16384) return Effect.fail(failure("Run has no remaining canonical dispatch capacity", AgentPersistenceCapacityError.make({ message: "Run has no room for the next result and a bounded terminal settlement" })));
699
754
  return Effect.void;
700
755
  };
701
- const prepare = Effect.fnUntraced(function* (batch, after) {
756
+ const prepare = Effect.fnUntraced(function* (batch, after, mode = "commit") {
702
757
  if (batch.records.some((record) => record.payload._tag === "RunContinuation")) return yield* failure("A caller cannot supply interpreter progress to the progress writer");
703
- const ownedRecords = yield* Effect.try({
704
- try: () => batch.records.map((record) => captureRecord(record).canonical),
705
- catch: (cause) => failure("Cannot capture canonical progress facts", cause)
706
- });
758
+ const ownedRecords = [...batch.records];
707
759
  const groups = /* @__PURE__ */ new Map();
708
760
  for (const record of ownedRecords) for (const runId of executionRunIds(record)) {
709
761
  const facts = groups.get(runId) ?? [];
@@ -712,8 +764,10 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
712
764
  }
713
765
  const executions = [];
714
766
  const accepted = /* @__PURE__ */ new Map();
767
+ let executionCount = 0;
715
768
  for (const [runId, facts] of groups) {
716
- const previous = yield* loadState(runId, after);
769
+ const empty = verifiedEmpty?.runId === runId && verifiedEmpty.through === after && verifiedEmpty.writer === Option.getOrUndefined(yield* Effect.serviceOption(CurrentRunWriter));
770
+ const previous = empty ? void 0 : cached.get(runId) ?? (yield* loadUncachedState(runId, after));
717
771
  let original = facts.find((record) => record.payload._tag === "UserInputRecorded" && record.payload.kind === "user" && record.payload.runId === runId && record.payload.submissionId !== void 0);
718
772
  let originalCount = 0;
719
773
  let initialBytes = 0;
@@ -731,7 +785,7 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
731
785
  if (submissionId === void 0) return yield* failure("Run progress has no original admission identity");
732
786
  if (runId !== runIdForSubmission(submissionId)) return yield* failure("Run progress conflicts with its original admission");
733
787
  if (previous === void 0 && original === void 0) return yield* failure("Run has no accepted original input");
734
- if (previous === void 0) {
788
+ if (previous === void 0 && !empty) {
735
789
  const settled = yield* provide(getRecord({
736
790
  threadId,
737
791
  recordId: submissionSettlementRecordId(submissionId)
@@ -747,18 +801,18 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
747
801
  const fact = facts[index];
748
802
  const payload = fact.payload;
749
803
  if (payload._tag !== "SubmissionSettled" || payload.runId !== runId) continue;
750
- const retained = captureRecord(RecordEnvelope.make({
804
+ const retained = yield* Effect.fromResult(captureRecord(RecordEnvelope.make({
751
805
  ...fact,
752
806
  payload: {
753
807
  ...payload,
754
808
  historyRecordCount: canonicalRecords
755
809
  }
756
- })).canonical;
810
+ }))).pipe(Effect.map((record) => record.canonical), Effect.mapError((cause) => failure("Cannot capture canonical progress facts", cause)));
757
811
  facts[index] = retained;
758
812
  ownedRecords[ownedRecords.indexOf(fact)] = retained;
759
813
  }
760
- const originalInput = previous !== void 0 ? previous.continuation.originalInput : original === void 0 ? yield* failure("Run progress has no original input") : yield* provide(reference(original));
761
- const next = yield* provide(advanceFacts(previous, facts, submissionId, initialBytes));
814
+ const originalInput = previous !== void 0 ? previous.continuation.originalInput : original === void 0 ? yield* failure("Run progress has no original input") : EvidenceReference.make({ recordId: original.recordId });
815
+ const next = yield* advanceFacts(previous, facts, submissionId, initialBytes);
762
816
  const { accounting, savedContext, latestResponse, terminal, position, response, results, childResults, completionBytes, last, factBytes, turn, turnBase, usageCharge, terminalUsageBytes } = next;
763
817
  let continuation = yield* RunContinuation.makeEffect({
764
818
  version: 1,
@@ -776,7 +830,7 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
776
830
  ...savedContext === void 0 ? {} : { savedContext },
777
831
  ...latestResponse === void 0 ? {} : { latestResponse },
778
832
  ...terminal === void 0 ? {} : { terminal },
779
- lastFact: yield* provide(reference(last)),
833
+ lastFact: EvidenceReference.make({ recordId: last.recordId }),
780
834
  position,
781
835
  accounting
782
836
  }).pipe(Effect.mapError(() => capacityFailure("Canonical continuation exceeds its protocol bounds")));
@@ -813,22 +867,42 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
813
867
  turnBytes,
814
868
  terminalBytes
815
869
  }).pipe(Effect.mapError(() => capacityFailure("Turn exceeds its incremental canonical byte budget")));
816
- continuation = new RunContinuation({
870
+ continuation = RunContinuation.make({
817
871
  ...continuation,
818
872
  ...checkedBytes
819
873
  }, { disableChecks: true });
820
- const record = captureRecord(new RecordEnvelope({
874
+ const proposedRecord = RecordEnvelope.make({
821
875
  ...header,
822
876
  payload: continuation
823
- }, { disableChecks: true })).canonical;
877
+ }, { disableChecks: true });
878
+ const cursorBytes = turnBytes - turnBase;
879
+ if (cursorBytes > 8192) return yield* capacityFailure("Encoded continuation exceeds 8192 bytes including its envelope");
880
+ executionCount++;
881
+ if (mode === "preflight" && previous?.checkpoint !== void 0 && facts.every(({ payload }) => payload._tag === "ModelResponseRecorded")) {
882
+ yield* decodeExecutionFrontier({
883
+ canonicalRecords,
884
+ throughSequence: after + ownedRecords.filter((fact) => !isOperationalRecord(fact)).length
885
+ }).pipe(Effect.mapError((cause) => failure("Active execution exceeds its bounds", cause)));
886
+ const state = {
887
+ continuation,
888
+ record: proposedRecord,
889
+ ...response === void 0 ? {} : { response },
890
+ results,
891
+ childResults,
892
+ ...completionBytes === void 0 ? {} : { completionBytes }
893
+ };
894
+ yield* checkCapacity(state, new Set(batch.records.map(({ recordId }) => recordId)), void 0, usageCharge);
895
+ yield* checkFutureShapes(state, cursorBytes);
896
+ continue;
897
+ }
898
+ const record = yield* Effect.fromResult(captureRecord(proposedRecord)).pipe(Effect.map((record) => record.canonical), Effect.mapError((cause) => failure("Cannot capture canonical progress facts", cause)));
824
899
  if (!isExecutionProgressRecord(record)) return yield* failure("Captured execution has no Run continuation");
825
- if (canonicalRecordBytes(record) !== turnBytes - turnBase) return yield* failure("Continuation byte accounting differs from its Schema encoding");
826
- if (canonicalRecordBytes(record) > 8192) return yield* capacityFailure("Encoded continuation exceeds 8192 bytes including its envelope");
900
+ if (canonicalRecordBytes(record) !== cursorBytes) return yield* failure("Continuation byte accounting differs from its Schema encoding");
827
901
  const operational = new Map((previous?.checkpoint?.operational ?? []).map((fact) => [fact.recordId, fact]));
828
902
  const changed = facts.filter(isOperationalRecord);
829
903
  for (const fact of changed) {
830
904
  const prior = operational.get(fact.recordId);
831
- if (prior !== void 0 && recordEncoding(prior).json !== recordEncoding(fact).json) return yield* failure("An active Run fact cannot change after becoming durable");
905
+ if (prior !== void 0 && (yield* Effect.fromResult(recordEncoding(prior)).pipe(Effect.mapError((cause) => failure("Cannot encode active Run fact", cause)))).json !== (yield* Effect.fromResult(recordEncoding(fact)).pipe(Effect.mapError((cause) => failure("Cannot encode active Run fact", cause)))).json) return yield* failure("An active Run fact cannot change after becoming durable");
832
906
  operational.set(fact.recordId, fact);
833
907
  }
834
908
  const checkpoint = yield* ExecutionCheckpoint.makeEffect({
@@ -859,9 +933,9 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
859
933
  }));
860
934
  accepted.set(runId, state);
861
935
  }
862
- if (ownedRecords.length + executions.length > 256) return yield* failure("Progress and facts exceed the atomic batch bound");
936
+ if (ownedRecords.length + executionCount > 256) return yield* failure("Progress and facts exceed the atomic batch bound");
863
937
  return {
864
- batch: new CommitBatch({
938
+ batch: CommitBatch.make({
865
939
  ...batch,
866
940
  records: ownedRecords.filter((fact) => !isOperationalRecord(fact))
867
941
  }, { disableChecks: true }),
@@ -877,11 +951,7 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
877
951
  }
878
952
  };
879
953
  });
880
- const tail = Effect.gen(function* () {
881
- const writer = yield* CurrentRunWriter;
882
- if (writer.threadId !== threadId) return yield* failure("Progress writer belongs to another Thread");
883
- return (yield* writer.tail).sequence;
884
- });
954
+ const tail = Effect.flatMap(CurrentRunWriter, (writer) => writer.threadId !== threadId ? Effect.fail(failure("Progress writer belongs to another Thread")) : Effect.map(writer.tail, (position) => position.sequence));
885
955
  const commitCaptured = Effect.fnUntraced(function* (batch) {
886
956
  const writer = yield* CurrentRunWriter;
887
957
  for (let retries = 0;; retries++) {
@@ -925,7 +995,7 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
925
995
  const after = yield* tail;
926
996
  yield* prepare(yield* captureFacts(probe), after);
927
997
  const recordId = probe.records[0].recordId;
928
- const state = yield* loadState(runId, after);
998
+ const state = cached.get(runId) ?? (yield* loadUncachedState(runId, after));
929
999
  if (state === void 0) return yield* failure("Dispatch has no canonical Run progress");
930
1000
  if (reservations.has(recordId)) return yield* failure("Dispatch capacity is already reserved");
931
1001
  yield* checkCapacity(state, /* @__PURE__ */ new Set(), {
@@ -946,10 +1016,10 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
946
1016
  const defer = (batch) => gate.withPermits(1)(Effect.gen(function* () {
947
1017
  const after = yield* tail;
948
1018
  const owned = yield* captureFacts(batch);
949
- yield* prepare(owned, after);
1019
+ yield* prepare(owned, after, "preflight");
950
1020
  const response = owned.records.find((record) => record.payload._tag === "ModelResponseRecorded");
951
1021
  if (response === void 0 || response.payload._tag !== "ModelResponseRecorded") return yield* failure("Deferred dispatch has no response");
952
- const progress = yield* loadState(response.payload.runId, after);
1022
+ const progress = cached.get(response.payload.runId) ?? (yield* loadUncachedState(response.payload.runId, after));
953
1023
  if (progress === void 0) return yield* failure("Deferred dispatch has no Run progress");
954
1024
  const pending = resultCapacity({
955
1025
  ...progress,
@@ -979,11 +1049,16 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
979
1049
  });
980
1050
  return owned;
981
1051
  }));
982
- const check = (runId) => gate.withPermits(1)(Effect.gen(function* () {
983
- const state = yield* loadState(runId, yield* tail);
984
- if (state === void 0) return yield* failure("Execution has no canonical Run progress");
985
- if (cached.get(runId) !== state) yield* checkFutureShapes(state);
986
- if (state.continuation.position !== "settling" && state.continuation.position !== "settled") yield* checkCapacity(state);
1052
+ const checkState = (state, recovered) => {
1053
+ if (state === void 0) return Effect.fail(failure("Execution has no canonical Run progress"));
1054
+ const capacity = () => state.continuation.position === "settling" || state.continuation.position === "settled" ? Effect.void : checkCapacity(state);
1055
+ return recovered ? Effect.andThen(checkFutureShapes(state), capacity) : capacity();
1056
+ };
1057
+ const check = (runId) => gate.withPermits(1)(Effect.flatMap(CurrentRunWriter, (writer) => {
1058
+ if (writer.threadId !== threadId) return Effect.fail(failure("Progress writer belongs to another Thread"));
1059
+ const retained = cached.get(runId);
1060
+ if (retained !== void 0) return checkState(retained, false);
1061
+ return Effect.flatMap(writer.tail, (position) => Effect.flatMap(loadUncachedState(runId, position.sequence), (state) => checkState(state, true)));
987
1062
  }));
988
1063
  return {
989
1064
  commit,
@@ -991,6 +1066,22 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
991
1066
  reserve,
992
1067
  defer,
993
1068
  check,
1069
+ /** Internal read view immediately after this writer's acknowledged commit, while
1070
+ * holding its initialization gates. Never authority across ownership or writes. */
1071
+ acceptedCheckpoint: (runId) => cached.get(runId)?.checkpoint,
1072
+ /** Scope a verified empty execution/evidence view to one owned initialization body.
1073
+ * The caller holds progress+mutation gates; a changed writer or tail never reuses it. */
1074
+ withVerifiedEmptyRun: (runId, through, body) => Effect.flatMap(CurrentRunWriter, (writer) => {
1075
+ const view = {
1076
+ runId,
1077
+ through,
1078
+ writer
1079
+ };
1080
+ verifiedEmpty = view;
1081
+ return body.pipe(Effect.ensuring(Effect.sync(() => {
1082
+ if (verifiedEmpty === view) verifiedEmpty = void 0;
1083
+ })));
1084
+ }),
994
1085
  stageUsage: (runId, bytes) => {
995
1086
  if (bytes === 0) stagedUsage.delete(runId);
996
1087
  else stagedUsage.set(runId, bytes);
@@ -1000,4 +1091,4 @@ const makeProgressWriter = Effect.fnUntraced(function* (threadId, deploymentId)
1000
1091
  //#endregion
1001
1092
  export { readRunContext as _, canonicalRecordBytes as a, reference as b, prepareProgressAppend as c, resolveExecutionEvidence as d, runEvidence as f, digestRunHistory as g, verifyRunContinuations as h, RunContinuation_exports as i, readContinuation as l, validateSuffix as m, CurrentRunWriter as n, isOperationalRecord as o, validateProgressAppend as p, ProgressAppendReader as r, makeProgressWriter as s, CurrentRunSettlement as t, readRunEvidenceSnapshot as u, validateContextBoundary as v, resolveEvidence as x, RunContextReader as y };
1002
1093
 
1003
- //# sourceMappingURL=RunContinuation-DHYNAQFi.mjs.map
1094
+ //# sourceMappingURL=RunContinuation-BiyKJK32.mjs.map