@systemfsoftware/agent 0.0.0-bootstrap.0 → 0.1.0-beta.192

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 (717) hide show
  1. package/LICENSE +21 -0
  2. package/dist/ActivityStore-CEy3oY41.mjs +90 -0
  3. package/dist/ActivityStore-CEy3oY41.mjs.map +1 -0
  4. package/dist/ActivityStore-CPXWRHGz.d.mts +91 -0
  5. package/dist/Admin-BcQDrWKY.mjs +329 -0
  6. package/dist/Admin-BcQDrWKY.mjs.map +1 -0
  7. package/dist/Admin-BfolLkHj.d.mts +5678 -0
  8. package/dist/Agent-Bn3zMhDH.mjs +60 -0
  9. package/dist/Agent-Bn3zMhDH.mjs.map +1 -0
  10. package/dist/Agent-DSVEpq4e.d.mts +219 -0
  11. package/dist/AgentError-RkUaetX8.d.mts +128 -0
  12. package/dist/AgentError-yFdnS9bl.mjs +141 -0
  13. package/dist/AgentError-yFdnS9bl.mjs.map +1 -0
  14. package/dist/AgentPolicy-CI7LRBQa.mjs +116 -0
  15. package/dist/AgentPolicy-CI7LRBQa.mjs.map +1 -0
  16. package/dist/AgentPolicy-D-GmZQex.d.mts +128 -0
  17. package/dist/AgentRegistration-Dg53p6du.mjs +14 -0
  18. package/dist/AgentRegistration-Dg53p6du.mjs.map +1 -0
  19. package/dist/AgentRuntime-CoGy_5dm.d.mts +751 -0
  20. package/dist/AgentRuntime-CzP4I4RB.mjs +5249 -0
  21. package/dist/AgentRuntime-CzP4I4RB.mjs.map +1 -0
  22. package/dist/AgentUpdates-7xT0It_R.d.mts +54 -0
  23. package/dist/AgentUpdates-BS_6gR5K.mjs +66 -0
  24. package/dist/AgentUpdates-BS_6gR5K.mjs.map +1 -0
  25. package/dist/BrowserUse-C9vict2M.d.mts +196 -0
  26. package/dist/BrowserUse-DjEyFDLZ.mjs +156 -0
  27. package/dist/BrowserUse-DjEyFDLZ.mjs.map +1 -0
  28. package/dist/Budget-CXh_ChFJ.d.mts +112 -0
  29. package/dist/Budget-j1UkthgY.mjs +351 -0
  30. package/dist/Budget-j1UkthgY.mjs.map +1 -0
  31. package/dist/CodeExecutor-B_Vt1Ghy.mjs +281 -0
  32. package/dist/CodeExecutor-B_Vt1Ghy.mjs.map +1 -0
  33. package/dist/CodeExecutor-D5-Rda75.d.mts +198 -0
  34. package/dist/CodeMode-B7JvfKAD.d.mts +159 -0
  35. package/dist/CodeMode-BI7WhUkr.mjs +555 -0
  36. package/dist/CodeMode-BI7WhUkr.mjs.map +1 -0
  37. package/dist/CommittedActivity-DXyCKCtX.mjs +146 -0
  38. package/dist/CommittedActivity-DXyCKCtX.mjs.map +1 -0
  39. package/dist/CommittedActivity-LWOKXqdi.d.mts +62 -0
  40. package/dist/Compaction-C0hWAmOG.mjs +15 -0
  41. package/dist/Compaction-C0hWAmOG.mjs.map +1 -0
  42. package/dist/Compaction-e5cNeFmY.d.mts +5 -0
  43. package/dist/ContextCompactor-Chm9BLrD.d.mts +165 -0
  44. package/dist/ContextCompactor-DV4NOQvg.mjs +134 -0
  45. package/dist/ContextCompactor-DV4NOQvg.mjs.map +1 -0
  46. package/dist/ContextHistory-C80rW5M7.mjs +76 -0
  47. package/dist/ContextHistory-C80rW5M7.mjs.map +1 -0
  48. package/dist/ContextHistory-akQ1Td7a.d.mts +65 -0
  49. package/dist/ContextTools-917r7gpv.d.mts +186 -0
  50. package/dist/ContextTools-p8JDPo-W.mjs +88 -0
  51. package/dist/ContextTools-p8JDPo-W.mjs.map +1 -0
  52. package/dist/ContextWindow-BJZI4MMt.d.mts +61 -0
  53. package/dist/ContextWindow-kbFcs1IF.mjs +63 -0
  54. package/dist/ContextWindow-kbFcs1IF.mjs.map +1 -0
  55. package/dist/Digest-BDToAbaX.d.mts +25 -0
  56. package/dist/Digest-CU6IWj-2.mjs +106 -0
  57. package/dist/Digest-CU6IWj-2.mjs.map +1 -0
  58. package/dist/DurableAgentRuntime-BHXo8GPJ.mjs +8432 -0
  59. package/dist/DurableAgentRuntime-BHXo8GPJ.mjs.map +1 -0
  60. package/dist/DurableFailpoint-BD5nowNl.mjs +98 -0
  61. package/dist/DurableFailpoint-BD5nowNl.mjs.map +1 -0
  62. package/dist/DurableFailpoint-Cqi5tyof.d.mts +42 -0
  63. package/dist/DurableStep-CzVIho7y.mjs +54 -0
  64. package/dist/DurableStep-CzVIho7y.mjs.map +1 -0
  65. package/dist/DurableStep-cI_Ho_rU.d.mts +109 -0
  66. package/dist/EventSource-BwZVkEQi.mjs +66 -0
  67. package/dist/EventSource-BwZVkEQi.mjs.map +1 -0
  68. package/dist/EventSource-C0TCBeIf.d.mts +52 -0
  69. package/dist/FailureDiagnostic-DdHV2eFs.mjs +304 -0
  70. package/dist/FailureDiagnostic-DdHV2eFs.mjs.map +1 -0
  71. package/dist/FailureDiagnostic-DpzYNI8f.d.mts +232 -0
  72. package/dist/IdGenerator-BCzwV0ZI.mjs +29 -0
  73. package/dist/IdGenerator-BCzwV0ZI.mjs.map +1 -0
  74. package/dist/IdGenerator-BY8NH74o.d.mts +26 -0
  75. package/dist/Identifiers-LWd4837I.mjs +41 -0
  76. package/dist/Identifiers-LWd4837I.mjs.map +1 -0
  77. package/dist/Identifiers-qafW4EP0.d.mts +38 -0
  78. package/dist/InMemory-BrTm6XEO.mjs +57 -0
  79. package/dist/InMemory-BrTm6XEO.mjs.map +1 -0
  80. package/dist/InMemory-C3qXFT5k.d.mts +46 -0
  81. package/dist/InMemory.d.mts +2 -0
  82. package/dist/InMemory.mjs +1 -0
  83. package/dist/InteractiveBrowser-B-hlNJy5.mjs +237 -0
  84. package/dist/InteractiveBrowser-B-hlNJy5.mjs.map +1 -0
  85. package/dist/InteractiveBrowser-nnML0r7w.d.mts +258 -0
  86. package/dist/LifecyclePublication-BDc_ug5v.mjs +204 -0
  87. package/dist/LifecyclePublication-BDc_ug5v.mjs.map +1 -0
  88. package/dist/Memory-CT5bDZqi.d.mts +57 -0
  89. package/dist/Memory-Dl9ecPpm.mjs +204 -0
  90. package/dist/Memory-Dl9ecPpm.mjs.map +1 -0
  91. package/dist/MemoryNamespace-BtnlH_E6.d.mts +35 -0
  92. package/dist/MemoryNamespace-DZSpjLj9.mjs +116 -0
  93. package/dist/MemoryNamespace-DZSpjLj9.mjs.map +1 -0
  94. package/dist/MemoryNotes-4CRzkPBD.d.mts +425 -0
  95. package/dist/MemoryNotes-i41TsH11.mjs +132 -0
  96. package/dist/MemoryNotes-i41TsH11.mjs.map +1 -0
  97. package/dist/MemoryReference-Dd3KSMa7.d.mts +77 -0
  98. package/dist/MemoryReference-RFU0HQJG.mjs +108 -0
  99. package/dist/MemoryReference-RFU0HQJG.mjs.map +1 -0
  100. package/dist/MemoryRevalidation--aAh_Pfq.mjs +136 -0
  101. package/dist/MemoryRevalidation--aAh_Pfq.mjs.map +1 -0
  102. package/dist/MemoryRevalidation-FsJ8E61W.d.mts +64 -0
  103. package/dist/MemoryStore-Bg5RunTk.d.mts +187 -0
  104. package/dist/MemoryStore-E0J99hb2.mjs +245 -0
  105. package/dist/MemoryStore-E0J99hb2.mjs.map +1 -0
  106. package/dist/MessageDelivery-BE2Yf3FC.mjs +615 -0
  107. package/dist/MessageDelivery-BE2Yf3FC.mjs.map +1 -0
  108. package/dist/MessageDelivery-Dh6GZBt_.d.mts +1129 -0
  109. package/dist/Messaging-BqWHYf93.d.mts +216 -0
  110. package/dist/Messaging-DgSiv4f4.mjs +154 -0
  111. package/dist/Messaging-DgSiv4f4.mjs.map +1 -0
  112. package/dist/Messaging-DhM-APnP.d.mts +1074 -0
  113. package/dist/MessagingHost-Bm5e-kAX.mjs +117 -0
  114. package/dist/MessagingHost-Bm5e-kAX.mjs.map +1 -0
  115. package/dist/MessagingHost-CubWeYKN.d.mts +80 -0
  116. package/dist/OperationAuthorizer-VSiHCC2S.mjs +72 -0
  117. package/dist/OperationAuthorizer-VSiHCC2S.mjs.map +1 -0
  118. package/dist/OperationAuthorizer-y-F-Ox_Q.d.mts +62 -0
  119. package/dist/Output-DQ8mWcgf.mjs +7 -0
  120. package/dist/Output-DQ8mWcgf.mjs.map +1 -0
  121. package/dist/Output-SbOdlBFL.d.mts +22 -0
  122. package/dist/PageCapture-BfRURUOA.mjs +275 -0
  123. package/dist/PageCapture-BfRURUOA.mjs.map +1 -0
  124. package/dist/PageCapture-C_mE72Sd.d.mts +216 -0
  125. package/dist/PageScreenshot-BJTASs4o.mjs +53 -0
  126. package/dist/PageScreenshot-BJTASs4o.mjs.map +1 -0
  127. package/dist/PageScreenshot-CaoaH7mc.d.mts +48 -0
  128. package/dist/PersistentHistory-BrtZ0g2j.d.mts +14 -0
  129. package/dist/PersistentHistory-CTAVhHKH.mjs +147 -0
  130. package/dist/PersistentHistory-CTAVhHKH.mjs.map +1 -0
  131. package/dist/PreparedInputAdmission-Ci18uY4s.d.mts +973 -0
  132. package/dist/PreparedInputAdmission-adqVJJa6.mjs +95 -0
  133. package/dist/PreparedInputAdmission-adqVJJa6.mjs.map +1 -0
  134. package/dist/ProvisionalText-BcKpPYKQ.d.mts +70 -0
  135. package/dist/ProvisionalText-DXddTK4c.mjs +47 -0
  136. package/dist/ProvisionalText-DXddTK4c.mjs.map +1 -0
  137. package/dist/Receipt-B-FlCaNH.mjs +35 -0
  138. package/dist/Receipt-B-FlCaNH.mjs.map +1 -0
  139. package/dist/Receipt-B4feBxMY.d.mts +31 -0
  140. package/dist/RecordFormat-DoNh-AFe.mjs +79 -0
  141. package/dist/RecordFormat-DoNh-AFe.mjs.map +1 -0
  142. package/dist/RecordFormat-ZMus8Dx8.d.mts +52 -0
  143. package/dist/Records-C645aQks.mjs +1145 -0
  144. package/dist/Records-C645aQks.mjs.map +1 -0
  145. package/dist/Records-C9I1nCL9.d.mts +1423 -0
  146. package/dist/Recovery-zWy_kmZq.mjs +736 -0
  147. package/dist/Recovery-zWy_kmZq.mjs.map +1 -0
  148. package/dist/Redaction-C0zLBAn6.d.mts +28 -0
  149. package/dist/Redaction-CtyCBMEj.mjs +116 -0
  150. package/dist/Redaction-CtyCBMEj.mjs.map +1 -0
  151. package/dist/RememberingStore-BO-OnCgP.mjs +23 -0
  152. package/dist/RememberingStore-BO-OnCgP.mjs.map +1 -0
  153. package/dist/RememberingStore-DgqXmILx.d.mts +14 -0
  154. package/dist/RunContinuation-BVAHoYlN.d.mts +127 -0
  155. package/dist/RunContinuation-Bpfp087i.mjs +1060 -0
  156. package/dist/RunContinuation-Bpfp087i.mjs.map +1 -0
  157. package/dist/RunEvent-CwgDzXcH.d.mts +465 -0
  158. package/dist/RunEvent-DJxENnJi.mjs +345 -0
  159. package/dist/RunEvent-DJxENnJi.mjs.map +1 -0
  160. package/dist/RunEventSink-B8uM8bw2.mjs +22 -0
  161. package/dist/RunEventSink-B8uM8bw2.mjs.map +1 -0
  162. package/dist/RunEventSink-f-T4jbNB.d.mts +105 -0
  163. package/dist/RunHooks-Bob22Bcj.d.mts +40 -0
  164. package/dist/RunHooks-DWuLBVdU.mjs +60 -0
  165. package/dist/RunHooks-DWuLBVdU.mjs.map +1 -0
  166. package/dist/RunJournal-C_1eqQdr.mjs +1107 -0
  167. package/dist/RunJournal-C_1eqQdr.mjs.map +1 -0
  168. package/dist/RunOptions-BVSa3BO2.d.mts +560 -0
  169. package/dist/RunOptions-COEUCrx4.mjs +61 -0
  170. package/dist/RunOptions-COEUCrx4.mjs.map +1 -0
  171. package/dist/RunPolicyUsage-B-JXRZYO.mjs +25 -0
  172. package/dist/RunPolicyUsage-B-JXRZYO.mjs.map +1 -0
  173. package/dist/RunPolicyUsage-jvJo0vJp.d.mts +21 -0
  174. package/dist/RunStorage-CsQQ0Y5u.mjs +304 -0
  175. package/dist/RunStorage-CsQQ0Y5u.mjs.map +1 -0
  176. package/dist/Sandbox-37vXP0BV.d.mts +24 -0
  177. package/dist/Sandbox-Bze6pHYc.mjs +30 -0
  178. package/dist/Sandbox-Bze6pHYc.mjs.map +1 -0
  179. package/dist/Schedule-BY0lzbij.mjs +336 -0
  180. package/dist/Schedule-BY0lzbij.mjs.map +1 -0
  181. package/dist/ScheduleTransition-CjVP48I8.d.mts +22 -0
  182. package/dist/ScheduleTransition-DtNzlN9k.mjs +180 -0
  183. package/dist/ScheduleTransition-DtNzlN9k.mjs.map +1 -0
  184. package/dist/Scheduling-BpJN9E1j.mjs +699 -0
  185. package/dist/Scheduling-BpJN9E1j.mjs.map +1 -0
  186. package/dist/Scheduling-DYTM29s9.d.mts +57 -0
  187. package/dist/SemanticMemory-BRV0cuWg.mjs +300 -0
  188. package/dist/SemanticMemory-BRV0cuWg.mjs.map +1 -0
  189. package/dist/SemanticMemory-rgWlhW87.d.mts +431 -0
  190. package/dist/SemanticMemoryIndex-D7yNEWpt.d.mts +826 -0
  191. package/dist/SemanticMemoryIndex-godQDjNx.mjs +186 -0
  192. package/dist/SemanticMemoryIndex-godQDjNx.mjs.map +1 -0
  193. package/dist/SemanticMemoryRevalidation-Bm3_pfsI.d.mts +44 -0
  194. package/dist/SemanticMemoryRevalidation-D8VV-eU6.mjs +179 -0
  195. package/dist/SemanticMemoryRevalidation-D8VV-eU6.mjs.map +1 -0
  196. package/dist/Subagent-CSIRUgUo.mjs +1315 -0
  197. package/dist/Subagent-CSIRUgUo.mjs.map +1 -0
  198. package/dist/Subagent-CXEI5YZ8.d.mts +2368 -0
  199. package/dist/SubagentContract-B7vQPueI.d.mts +176 -0
  200. package/dist/SubagentContract-C-7AxTm_.mjs +187 -0
  201. package/dist/SubagentContract-C-7AxTm_.mjs.map +1 -0
  202. package/dist/SubagentHost-BEnICu7g.mjs +70 -0
  203. package/dist/SubagentHost-BEnICu7g.mjs.map +1 -0
  204. package/dist/SubagentHost-CKhz1vbH.d.mts +167 -0
  205. package/dist/SubagentReservations-BYNAHPpm.mjs +465 -0
  206. package/dist/SubagentReservations-BYNAHPpm.mjs.map +1 -0
  207. package/dist/SubagentReservations-WrmIVzO5.d.mts +185 -0
  208. package/dist/SubmissionLedger-WG0beEyt.mjs +921 -0
  209. package/dist/SubmissionLedger-WG0beEyt.mjs.map +1 -0
  210. package/dist/SubmissionStatus-CPZsOM5a.mjs +17 -0
  211. package/dist/SubmissionStatus-CPZsOM5a.mjs.map +1 -0
  212. package/dist/Subscription-BhQbmUD-.mjs +340 -0
  213. package/dist/Subscription-BhQbmUD-.mjs.map +1 -0
  214. package/dist/Subscription-CC--_OnU.d.mts +815 -0
  215. package/dist/SubscriptionInput-BEeB0Cj8.d.mts +42 -0
  216. package/dist/SubscriptionInput-Xcd4JjEs.mjs +53 -0
  217. package/dist/SubscriptionInput-Xcd4JjEs.mjs.map +1 -0
  218. package/dist/SubscriptionTransition-CWt9UVH0.d.mts +23 -0
  219. package/dist/SubscriptionTransition-lrf733c8.mjs +154 -0
  220. package/dist/SubscriptionTransition-lrf733c8.mjs.map +1 -0
  221. package/dist/Subscriptions-4K_qu_2f.mjs +638 -0
  222. package/dist/Subscriptions-4K_qu_2f.mjs.map +1 -0
  223. package/dist/Subscriptions-BF3aSf8X.d.mts +75 -0
  224. package/dist/Thread-B8JApGHa.mjs +283 -0
  225. package/dist/Thread-B8JApGHa.mjs.map +1 -0
  226. package/dist/Thread-BnAtkJl4.d.mts +116 -0
  227. package/dist/ThreadArchiveRange-1PMdjpdJ.mjs +64 -0
  228. package/dist/ThreadArchiveRange-1PMdjpdJ.mjs.map +1 -0
  229. package/dist/ThreadContextHistory-BSStMOLX.mjs +211 -0
  230. package/dist/ThreadContextHistory-BSStMOLX.mjs.map +1 -0
  231. package/dist/ThreadContextHistory-lTZ8Ftq1.d.mts +33 -0
  232. package/dist/ThreadContextHistoryProjection-Cp7_RR6V.d.mts +59 -0
  233. package/dist/ThreadContextHistoryProjection-_8uNz-h1.mjs +149 -0
  234. package/dist/ThreadContextHistoryProjection-_8uNz-h1.mjs.map +1 -0
  235. package/dist/ThreadHistory-BkyGfv5E.d.mts +76 -0
  236. package/dist/ThreadHistory-Blt_W31N.mjs +69 -0
  237. package/dist/ThreadHistory-Blt_W31N.mjs.map +1 -0
  238. package/dist/ThreadImport-C8Tqiezd.mjs +491 -0
  239. package/dist/ThreadImport-C8Tqiezd.mjs.map +1 -0
  240. package/dist/ThreadImport-DaSmrlRi.d.mts +843 -0
  241. package/dist/ThreadInvariants-DyPhMeo-.d.mts +23 -0
  242. package/dist/ThreadInvariants-fniroLRY.mjs +154 -0
  243. package/dist/ThreadInvariants-fniroLRY.mjs.map +1 -0
  244. package/dist/ThreadProjectionMaintenance-D6fBjr1q.mjs +37 -0
  245. package/dist/ThreadProjectionMaintenance-D6fBjr1q.mjs.map +1 -0
  246. package/dist/ThreadProjectionMaintenance-DjUy7kCa.d.mts +51 -0
  247. package/dist/ThreadStore-BMUAp5Ta.mjs +937 -0
  248. package/dist/ThreadStore-BMUAp5Ta.mjs.map +1 -0
  249. package/dist/ThreadTransfer-B3NkyO_y.mjs +154 -0
  250. package/dist/ThreadTransfer-B3NkyO_y.mjs.map +1 -0
  251. package/dist/ThreadTransfer-BM02cbOo.d.mts +63 -0
  252. package/dist/ThreadWork-C-xa2Boi.mjs +484 -0
  253. package/dist/ThreadWork-C-xa2Boi.mjs.map +1 -0
  254. package/dist/ToolBroker-DkoVyx6T.mjs +42 -0
  255. package/dist/ToolBroker-DkoVyx6T.mjs.map +1 -0
  256. package/dist/ToolBroker-Dy2xM6ht.d.mts +134 -0
  257. package/dist/ToolDiscovery-DHySvLQd.mjs +211 -0
  258. package/dist/ToolDiscovery-DHySvLQd.mjs.map +1 -0
  259. package/dist/ToolDiscovery-VjamzX3q.d.mts +119 -0
  260. package/dist/ToolExposure-Cn7xETn5.d.mts +6 -0
  261. package/dist/ToolExposure-D7id9Gt5.d.mts +37 -0
  262. package/dist/ToolExposure-DCvQWFIa.mjs +9 -0
  263. package/dist/ToolExposure-DCvQWFIa.mjs.map +1 -0
  264. package/dist/ToolExposure-DNME8BkG.d.mts +44 -0
  265. package/dist/ToolExposure-DPnq8Won.mjs +30 -0
  266. package/dist/ToolExposure-DPnq8Won.mjs.map +1 -0
  267. package/dist/ToolExposure-DaGaF5tj.mjs +20 -0
  268. package/dist/ToolExposure-DaGaF5tj.mjs.map +1 -0
  269. package/dist/ToolExposure.d.mts +4 -0
  270. package/dist/ToolExposure.mjs +4 -0
  271. package/dist/ToolReconciler-6bb7xlip.d.mts +81 -0
  272. package/dist/ToolReconciler-DJQd3SZA.mjs +87 -0
  273. package/dist/ToolReconciler-DJQd3SZA.mjs.map +1 -0
  274. package/dist/ToolResult-By5KAje4.d.mts +79 -0
  275. package/dist/ToolResult-DwZxjlHw.mjs +160 -0
  276. package/dist/ToolResult-DwZxjlHw.mjs.map +1 -0
  277. package/dist/ToolResultStorage-BmoRewhh.mjs +46 -0
  278. package/dist/ToolResultStorage-BmoRewhh.mjs.map +1 -0
  279. package/dist/ToolResultStorage-Bp5fm0do.d.mts +49 -0
  280. package/dist/ToolResults-C4-HsMCp.d.mts +33 -0
  281. package/dist/ToolResults-nCgBlTp2.mjs +45 -0
  282. package/dist/ToolResults-nCgBlTp2.mjs.map +1 -0
  283. package/dist/Usage-B0xgME5f.mjs +340 -0
  284. package/dist/Usage-B0xgME5f.mjs.map +1 -0
  285. package/dist/Usage-Bc-jXe_9.d.mts +128 -0
  286. package/dist/WakeScheduler-DVYj66C-.mjs +74 -0
  287. package/dist/WakeScheduler-DVYj66C-.mjs.map +1 -0
  288. package/dist/WakeScheduler-SFqj67Sk.d.mts +74 -0
  289. package/dist/WebCapture-CA4ZarW2.mjs +64 -0
  290. package/dist/WebCapture-CA4ZarW2.mjs.map +1 -0
  291. package/dist/WebCapture-pzIeUJ5W.d.mts +49 -0
  292. package/dist/WebSearch-CD0V--qh.d.mts +18 -0
  293. package/dist/WebSearch-DnbOzRL_.mjs +30 -0
  294. package/dist/WebSearch-DnbOzRL_.mjs.map +1 -0
  295. package/dist/Worker-CQu8Qp1j.mjs +267 -0
  296. package/dist/Worker-CQu8Qp1j.mjs.map +1 -0
  297. package/dist/Worker-xxucY_0b.d.mts +468 -0
  298. package/dist/WorkerAdmission-BhFjx86s.mjs +162 -0
  299. package/dist/WorkerAdmission-BhFjx86s.mjs.map +1 -0
  300. package/dist/WorkerAdmission-BnRuXLWF.d.mts +171 -0
  301. package/dist/WorkerHost-DtYzi54D.d.mts +150 -0
  302. package/dist/WorkerHost-DuQug9Bq.mjs +73 -0
  303. package/dist/WorkerHost-DuQug9Bq.mjs.map +1 -0
  304. package/dist/agent-registration-CNs2twrr.mjs +262 -0
  305. package/dist/agent-registration-CNs2twrr.mjs.map +1 -0
  306. package/dist/capabilities/BrowserUse.d.mts +2 -0
  307. package/dist/capabilities/BrowserUse.mjs +1 -0
  308. package/dist/capabilities/Budget.d.mts +2 -0
  309. package/dist/capabilities/Budget.mjs +1 -0
  310. package/dist/capabilities/CodeMode.d.mts +2 -0
  311. package/dist/capabilities/CodeMode.mjs +1 -0
  312. package/dist/capabilities/ContextTools.d.mts +2 -0
  313. package/dist/capabilities/ContextTools.mjs +1 -0
  314. package/dist/capabilities/MemoryNotes.d.mts +2 -0
  315. package/dist/capabilities/MemoryNotes.mjs +1 -0
  316. package/dist/capabilities/Messaging.d.mts +3 -0
  317. package/dist/capabilities/Messaging.mjs +4 -0
  318. package/dist/capabilities/Redaction.d.mts +2 -0
  319. package/dist/capabilities/Redaction.mjs +1 -0
  320. package/dist/capabilities/RunHooks.d.mts +2 -0
  321. package/dist/capabilities/RunHooks.mjs +1 -0
  322. package/dist/capabilities/SemanticMemory.d.mts +2 -0
  323. package/dist/capabilities/SemanticMemory.mjs +1 -0
  324. package/dist/capabilities/Subagent.d.mts +4 -0
  325. package/dist/capabilities/Subagent.mjs +6 -0
  326. package/dist/capabilities/SubagentReservations.d.mts +2 -0
  327. package/dist/capabilities/SubagentReservations.mjs +1 -0
  328. package/dist/capabilities/ToolDiscovery.d.mts +2 -0
  329. package/dist/capabilities/ToolDiscovery.mjs +1 -0
  330. package/dist/capabilities/ToolResults.d.mts +2 -0
  331. package/dist/capabilities/ToolResults.mjs +1 -0
  332. package/dist/capabilities/WebCapture.d.mts +2 -0
  333. package/dist/capabilities/WebCapture.mjs +1 -0
  334. package/dist/capabilities/WebSearch.d.mts +2 -0
  335. package/dist/capabilities/WebSearch.mjs +1 -0
  336. package/dist/compaction-C3hXuO4Z.mjs +539 -0
  337. package/dist/compaction-C3hXuO4Z.mjs.map +1 -0
  338. package/dist/completion-B_WDnSg-.d.mts +11 -0
  339. package/dist/core/Agent.d.mts +2 -0
  340. package/dist/core/Agent.mjs +1 -0
  341. package/dist/core/AgentError.d.mts +2 -0
  342. package/dist/core/AgentError.mjs +1 -0
  343. package/dist/core/AgentPolicy.d.mts +2 -0
  344. package/dist/core/AgentPolicy.mjs +1 -0
  345. package/dist/core/AgentUpdates.d.mts +2 -0
  346. package/dist/core/AgentUpdates.mjs +1 -0
  347. package/dist/core/FailureDiagnostic.d.mts +2 -0
  348. package/dist/core/FailureDiagnostic.mjs +1 -0
  349. package/dist/core/IdGenerator.d.mts +2 -0
  350. package/dist/core/IdGenerator.mjs +1 -0
  351. package/dist/core/Identifiers.d.mts +2 -0
  352. package/dist/core/Identifiers.mjs +1 -0
  353. package/dist/core/Memory.d.mts +2 -0
  354. package/dist/core/Memory.mjs +1 -0
  355. package/dist/core/MemoryNamespace.d.mts +2 -0
  356. package/dist/core/MemoryNamespace.mjs +1 -0
  357. package/dist/core/MemoryReference.d.mts +2 -0
  358. package/dist/core/MemoryReference.mjs +1 -0
  359. package/dist/core/MemoryRevalidation.d.mts +2 -0
  360. package/dist/core/MemoryRevalidation.mjs +1 -0
  361. package/dist/core/MemoryStore.d.mts +2 -0
  362. package/dist/core/MemoryStore.mjs +1 -0
  363. package/dist/core/ProvisionalText.d.mts +2 -0
  364. package/dist/core/ProvisionalText.mjs +1 -0
  365. package/dist/core/Receipt.d.mts +2 -0
  366. package/dist/core/Receipt.mjs +1 -0
  367. package/dist/core/RememberingStore.d.mts +2 -0
  368. package/dist/core/RememberingStore.mjs +1 -0
  369. package/dist/core/RunEvent.d.mts +3 -0
  370. package/dist/core/RunEvent.mjs +1 -0
  371. package/dist/core/RunPolicyUsage.d.mts +2 -0
  372. package/dist/core/RunPolicyUsage.mjs +1 -0
  373. package/dist/core/SemanticMemoryIndex.d.mts +2 -0
  374. package/dist/core/SemanticMemoryIndex.mjs +1 -0
  375. package/dist/core/SemanticMemoryRevalidation.d.mts +2 -0
  376. package/dist/core/SemanticMemoryRevalidation.mjs +1 -0
  377. package/dist/core/SubagentContract.d.mts +2 -0
  378. package/dist/core/SubagentContract.mjs +1 -0
  379. package/dist/core/Thread.d.mts +2 -0
  380. package/dist/core/Thread.mjs +1 -0
  381. package/dist/core/ToolResult.d.mts +2 -0
  382. package/dist/core/ToolResult.mjs +1 -0
  383. package/dist/core/ToolResultStorage.d.mts +2 -0
  384. package/dist/core/ToolResultStorage.mjs +1 -0
  385. package/dist/core/Usage.d.mts +2 -0
  386. package/dist/core/Usage.mjs +1 -0
  387. package/dist/core/Worker.d.mts +3 -0
  388. package/dist/core/Worker.mjs +3 -0
  389. package/dist/durable/ActivityStore.d.mts +2 -0
  390. package/dist/durable/ActivityStore.mjs +1 -0
  391. package/dist/durable/Admin.d.mts +2 -0
  392. package/dist/durable/Admin.mjs +1 -0
  393. package/dist/durable/AgentRegistration.d.mts +3 -0
  394. package/dist/durable/AgentRegistration.mjs +2 -0
  395. package/dist/durable/CommittedActivity.d.mts +2 -0
  396. package/dist/durable/CommittedActivity.mjs +1 -0
  397. package/dist/durable/Digest.d.mts +2 -0
  398. package/dist/durable/Digest.mjs +3 -0
  399. package/dist/durable/DurableAgentRuntime.d.mts +3 -0
  400. package/dist/durable/DurableAgentRuntime.mjs +4 -0
  401. package/dist/durable/DurableFailpoint.d.mts +2 -0
  402. package/dist/durable/DurableFailpoint.mjs +1 -0
  403. package/dist/durable/DurableFailpointTestControl.d.mts +14 -0
  404. package/dist/durable/DurableFailpointTestControl.mjs +21 -0
  405. package/dist/durable/DurableFailpointTestControl.mjs.map +1 -0
  406. package/dist/durable/EventSource.d.mts +2 -0
  407. package/dist/durable/EventSource.mjs +1 -0
  408. package/dist/durable/LifecyclePublication.d.mts +2 -0
  409. package/dist/durable/LifecyclePublication.mjs +1 -0
  410. package/dist/durable/MessageDelivery.d.mts +2 -0
  411. package/dist/durable/MessageDelivery.mjs +1 -0
  412. package/dist/durable/MessageDeliveryStoreConformance.d.mts +401 -0
  413. package/dist/durable/MessageDeliveryStoreConformance.mjs +273 -0
  414. package/dist/durable/MessageDeliveryStoreConformance.mjs.map +1 -0
  415. package/dist/durable/OperationAuthorizer.d.mts +2 -0
  416. package/dist/durable/OperationAuthorizer.mjs +1 -0
  417. package/dist/durable/PersistentHistory.d.mts +2 -0
  418. package/dist/durable/PersistentHistory.mjs +1 -0
  419. package/dist/durable/PreparedInputAdmission.d.mts +2 -0
  420. package/dist/durable/PreparedInputAdmission.mjs +1 -0
  421. package/dist/durable/RecordFormat.d.mts +2 -0
  422. package/dist/durable/RecordFormat.mjs +1 -0
  423. package/dist/durable/Records.d.mts +2 -0
  424. package/dist/durable/Records.mjs +1 -0
  425. package/dist/durable/Recovery.d.mts +2 -0
  426. package/dist/durable/Recovery.mjs +1 -0
  427. package/dist/durable/RunContinuation.d.mts +4 -0
  428. package/dist/durable/RunContinuation.mjs +4 -0
  429. package/dist/durable/RunJournal.d.mts +2 -0
  430. package/dist/durable/RunJournal.mjs +1 -0
  431. package/dist/durable/RunStorage.d.mts +2 -0
  432. package/dist/durable/RunStorage.mjs +1 -0
  433. package/dist/durable/Schedule.d.mts +2 -0
  434. package/dist/durable/Schedule.mjs +1 -0
  435. package/dist/durable/ScheduleStoreConformance.d.mts +16 -0
  436. package/dist/durable/ScheduleStoreConformance.mjs +421 -0
  437. package/dist/durable/ScheduleStoreConformance.mjs.map +1 -0
  438. package/dist/durable/ScheduleTransition.d.mts +2 -0
  439. package/dist/durable/ScheduleTransition.mjs +1 -0
  440. package/dist/durable/Scheduling.d.mts +2 -0
  441. package/dist/durable/Scheduling.mjs +1 -0
  442. package/dist/durable/SettlementPublisher.d.mts +2 -0
  443. package/dist/durable/SettlementPublisher.mjs +99 -0
  444. package/dist/durable/SettlementPublisher.mjs.map +1 -0
  445. package/dist/durable/SqlMemoryStore.d.mts +729 -0
  446. package/dist/durable/SqlMemoryStore.mjs +626 -0
  447. package/dist/durable/SqlMemoryStore.mjs.map +1 -0
  448. package/dist/durable/SqlStorageOwner.d.mts +18 -0
  449. package/dist/durable/SqlStorageOwner.mjs +6 -0
  450. package/dist/durable/SqlStorageOwner.mjs.map +1 -0
  451. package/dist/durable/SubmissionLedger.d.mts +3 -0
  452. package/dist/durable/SubmissionLedger.mjs +3 -0
  453. package/dist/durable/SubmissionLedgerConformance.d.mts +31 -0
  454. package/dist/durable/SubmissionLedgerConformance.mjs +2090 -0
  455. package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -0
  456. package/dist/durable/SubmissionStatus.d.mts +2 -0
  457. package/dist/durable/SubmissionStatus.mjs +1 -0
  458. package/dist/durable/Subscription.d.mts +2 -0
  459. package/dist/durable/Subscription.mjs +1 -0
  460. package/dist/durable/SubscriptionInput.d.mts +2 -0
  461. package/dist/durable/SubscriptionInput.mjs +1 -0
  462. package/dist/durable/SubscriptionStoreConformance.d.mts +15 -0
  463. package/dist/durable/SubscriptionStoreConformance.mjs +816 -0
  464. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -0
  465. package/dist/durable/SubscriptionTransition.d.mts +2 -0
  466. package/dist/durable/SubscriptionTransition.mjs +1 -0
  467. package/dist/durable/Subscriptions.d.mts +2 -0
  468. package/dist/durable/Subscriptions.mjs +1 -0
  469. package/dist/durable/ThreadArchiveRange.d.mts +2 -0
  470. package/dist/durable/ThreadArchiveRange.mjs +1 -0
  471. package/dist/durable/ThreadContextHistory.d.mts +2 -0
  472. package/dist/durable/ThreadContextHistory.mjs +1 -0
  473. package/dist/durable/ThreadContextHistoryProjection.d.mts +2 -0
  474. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -0
  475. package/dist/durable/ThreadImport.d.mts +2 -0
  476. package/dist/durable/ThreadImport.mjs +1 -0
  477. package/dist/durable/ThreadInvariants.d.mts +2 -0
  478. package/dist/durable/ThreadInvariants.mjs +1 -0
  479. package/dist/durable/ThreadProjectionMaintenance.d.mts +2 -0
  480. package/dist/durable/ThreadProjectionMaintenance.mjs +1 -0
  481. package/dist/durable/ThreadReader.d.mts +2 -0
  482. package/dist/durable/ThreadReader.mjs +1 -0
  483. package/dist/durable/ThreadStore.d.mts +3 -0
  484. package/dist/durable/ThreadStore.mjs +3 -0
  485. package/dist/durable/ThreadStoreConformance.d.mts +53 -0
  486. package/dist/durable/ThreadStoreConformance.mjs +402 -0
  487. package/dist/durable/ThreadStoreConformance.mjs.map +1 -0
  488. package/dist/durable/ThreadTransfer.d.mts +2 -0
  489. package/dist/durable/ThreadTransfer.mjs +1 -0
  490. package/dist/durable/ThreadWork.d.mts +2 -0
  491. package/dist/durable/ThreadWork.mjs +1 -0
  492. package/dist/durable/ToolReconciler.d.mts +2 -0
  493. package/dist/durable/ToolReconciler.mjs +1 -0
  494. package/dist/durable/WakeScheduler.d.mts +2 -0
  495. package/dist/durable/WakeScheduler.mjs +1 -0
  496. package/dist/durable/WorkerAdmission.d.mts +2 -0
  497. package/dist/durable/WorkerAdmission.mjs +1 -0
  498. package/dist/durable/WorkerHost.d.mts +2 -0
  499. package/dist/durable/WorkerHost.mjs +1 -0
  500. package/dist/engine/AgentRuntime.d.mts +2 -0
  501. package/dist/engine/AgentRuntime.mjs +1 -0
  502. package/dist/engine/Compaction.d.mts +4 -0
  503. package/dist/engine/Compaction.mjs +2 -0
  504. package/dist/engine/ContextCompactor.d.mts +2 -0
  505. package/dist/engine/ContextCompactor.mjs +1 -0
  506. package/dist/engine/ContextHistory.d.mts +2 -0
  507. package/dist/engine/ContextHistory.mjs +1 -0
  508. package/dist/engine/ContextWindow.d.mts +2 -0
  509. package/dist/engine/ContextWindow.mjs +1 -0
  510. package/dist/engine/DurableStep.d.mts +2 -0
  511. package/dist/engine/DurableStep.mjs +3 -0
  512. package/dist/engine/MessagingHost.d.mts +2 -0
  513. package/dist/engine/MessagingHost.mjs +1 -0
  514. package/dist/engine/Output.d.mts +3 -0
  515. package/dist/engine/Output.mjs +2 -0
  516. package/dist/engine/RunEventSink.d.mts +2 -0
  517. package/dist/engine/RunEventSink.mjs +1 -0
  518. package/dist/engine/RunOptions.d.mts +2 -0
  519. package/dist/engine/RunOptions.mjs +1 -0
  520. package/dist/engine/SubagentHost.d.mts +2 -0
  521. package/dist/engine/SubagentHost.mjs +1 -0
  522. package/dist/engine/ThreadHistory.d.mts +2 -0
  523. package/dist/engine/ThreadHistory.mjs +1 -0
  524. package/dist/engine/ToolBroker.d.mts +2 -0
  525. package/dist/engine/ToolBroker.mjs +1 -0
  526. package/dist/index.d.mts +90 -0
  527. package/dist/index.mjs +101 -0
  528. package/dist/output-contract-CYA4oBhe.mjs +128 -0
  529. package/dist/output-contract-CYA4oBhe.mjs.map +1 -0
  530. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  531. package/dist/run-context-reader-CHox63hg.d.mts +17 -0
  532. package/dist/sandbox/CodeExecutor.d.mts +2 -0
  533. package/dist/sandbox/CodeExecutor.mjs +1 -0
  534. package/dist/sandbox/InteractiveBrowser.d.mts +2 -0
  535. package/dist/sandbox/InteractiveBrowser.mjs +1 -0
  536. package/dist/sandbox/PageCapture.d.mts +2 -0
  537. package/dist/sandbox/PageCapture.mjs +1 -0
  538. package/dist/sandbox/PageScreenshot.d.mts +2 -0
  539. package/dist/sandbox/PageScreenshot.mjs +1 -0
  540. package/dist/sandbox/Sandbox.d.mts +2 -0
  541. package/dist/sandbox/Sandbox.mjs +1 -0
  542. package/dist/subagent-policy-xRJhrc0a.mjs +133 -0
  543. package/dist/subagent-policy-xRJhrc0a.mjs.map +1 -0
  544. package/dist/tool-execution-Cl7v8fXU.mjs +16 -0
  545. package/dist/tool-execution-Cl7v8fXU.mjs.map +1 -0
  546. package/dist/tool-operations-CauPonM8.mjs +84 -0
  547. package/dist/tool-operations-CauPonM8.mjs.map +1 -0
  548. package/dist/utf8-Bl0ZhhGe.mjs +27 -0
  549. package/dist/utf8-Bl0ZhhGe.mjs.map +1 -0
  550. package/package.json +489 -5
  551. package/src/InMemory.ts +79 -0
  552. package/src/ToolExposure.ts +2 -0
  553. package/src/capabilities/BrowserUse.ts +212 -0
  554. package/src/capabilities/Budget.ts +544 -0
  555. package/src/capabilities/CodeMode.ts +1129 -0
  556. package/src/capabilities/ContextTools.ts +131 -0
  557. package/src/capabilities/MemoryNotes.ts +177 -0
  558. package/src/capabilities/Messaging.ts +260 -0
  559. package/src/capabilities/Redaction.ts +163 -0
  560. package/src/capabilities/RunHooks.ts +116 -0
  561. package/src/capabilities/SemanticMemory.ts +402 -0
  562. package/src/capabilities/Subagent.ts +2343 -0
  563. package/src/capabilities/SubagentReservations.ts +807 -0
  564. package/src/capabilities/ToolDiscovery.ts +291 -0
  565. package/src/capabilities/ToolResults.ts +50 -0
  566. package/src/capabilities/WebCapture.ts +64 -0
  567. package/src/capabilities/WebSearch.ts +45 -0
  568. package/src/capabilities/internal/subagent-background.ts +1137 -0
  569. package/src/capabilities/internal/subagent-contract.ts +92 -0
  570. package/src/capabilities/internal/subagent-policy.ts +205 -0
  571. package/src/capabilities/internal/subagent-reporting.ts +152 -0
  572. package/src/core/Agent.ts +528 -0
  573. package/src/core/AgentError.ts +189 -0
  574. package/src/core/AgentPolicy.ts +194 -0
  575. package/src/core/AgentUpdates.ts +104 -0
  576. package/src/core/FailureDiagnostic.ts +392 -0
  577. package/src/core/IdGenerator.ts +42 -0
  578. package/src/core/Identifiers.ts +64 -0
  579. package/src/core/Memory.ts +283 -0
  580. package/src/core/MemoryNamespace.ts +202 -0
  581. package/src/core/MemoryReference.ts +120 -0
  582. package/src/core/MemoryRevalidation.ts +151 -0
  583. package/src/core/MemoryStore.ts +371 -0
  584. package/src/core/Messaging.ts +72 -0
  585. package/src/core/ProvisionalText.ts +53 -0
  586. package/src/core/Receipt.ts +42 -0
  587. package/src/core/RememberingStore.ts +22 -0
  588. package/src/core/RunEvent.ts +345 -0
  589. package/src/core/RunPolicyUsage.ts +19 -0
  590. package/src/core/SemanticMemoryIndex.ts +259 -0
  591. package/src/core/SemanticMemoryRevalidation.ts +220 -0
  592. package/src/core/SubagentContract.ts +263 -0
  593. package/src/core/Thread.ts +447 -0
  594. package/src/core/ToolExposure.ts +75 -0
  595. package/src/core/ToolResult.ts +204 -0
  596. package/src/core/ToolResultStorage.ts +56 -0
  597. package/src/core/Usage.ts +562 -0
  598. package/src/core/Worker.ts +236 -0
  599. package/src/core/internal/agent-updates.ts +42 -0
  600. package/src/core/internal/completion.ts +33 -0
  601. package/src/core/internal/json.ts +17 -0
  602. package/src/core/internal/memory-document.ts +39 -0
  603. package/src/core/internal/message-status.ts +60 -0
  604. package/src/core/internal/strict-schema.ts +14 -0
  605. package/src/core/internal/tool-execution.ts +33 -0
  606. package/src/core/internal/utf8.ts +32 -0
  607. package/src/durable/ActivityStore.ts +131 -0
  608. package/src/durable/Admin.ts +504 -0
  609. package/src/durable/AgentRegistration.ts +16 -0
  610. package/src/durable/CommittedActivity.ts +262 -0
  611. package/src/durable/Digest.ts +57 -0
  612. package/src/durable/DurableAgentRuntime.ts +12758 -0
  613. package/src/durable/DurableFailpoint.ts +108 -0
  614. package/src/durable/DurableFailpointTestControl.ts +39 -0
  615. package/src/durable/EventSource.ts +179 -0
  616. package/src/durable/LifecyclePublication.ts +343 -0
  617. package/src/durable/MessageDelivery.ts +949 -0
  618. package/src/durable/MessageDeliveryStoreConformance.ts +407 -0
  619. package/src/durable/OperationAuthorizer.ts +89 -0
  620. package/src/durable/PersistentHistory.ts +322 -0
  621. package/src/durable/PreparedInputAdmission.ts +128 -0
  622. package/src/durable/RecordFormat.ts +113 -0
  623. package/src/durable/Records.ts +1396 -0
  624. package/src/durable/Recovery.ts +1022 -0
  625. package/src/durable/RunContinuation.ts +1946 -0
  626. package/src/durable/RunJournal.ts +1926 -0
  627. package/src/durable/RunStorage.ts +533 -0
  628. package/src/durable/Schedule.ts +445 -0
  629. package/src/durable/ScheduleStoreConformance.ts +642 -0
  630. package/src/durable/ScheduleTransition.ts +267 -0
  631. package/src/durable/Scheduling.ts +1031 -0
  632. package/src/durable/SettlementPublisher.ts +172 -0
  633. package/src/durable/SqlMemoryStore.ts +1042 -0
  634. package/src/durable/SqlStorageOwner.ts +25 -0
  635. package/src/durable/SubmissionLedger.ts +1247 -0
  636. package/src/durable/SubmissionLedgerConformance.ts +4695 -0
  637. package/src/durable/SubmissionStatus.ts +14 -0
  638. package/src/durable/Subscription.ts +527 -0
  639. package/src/durable/SubscriptionInput.ts +145 -0
  640. package/src/durable/SubscriptionStoreConformance.ts +1275 -0
  641. package/src/durable/SubscriptionTransition.ts +330 -0
  642. package/src/durable/Subscriptions.ts +1245 -0
  643. package/src/durable/ThreadArchiveRange.ts +91 -0
  644. package/src/durable/ThreadContextHistory.ts +338 -0
  645. package/src/durable/ThreadContextHistoryProjection.ts +219 -0
  646. package/src/durable/ThreadImport.ts +1199 -0
  647. package/src/durable/ThreadInvariants.ts +312 -0
  648. package/src/durable/ThreadProjectionMaintenance.ts +72 -0
  649. package/src/durable/ThreadReader.ts +21 -0
  650. package/src/durable/ThreadStore.ts +1258 -0
  651. package/src/durable/ThreadStoreConformance.ts +877 -0
  652. package/src/durable/ThreadTransfer.ts +263 -0
  653. package/src/durable/ThreadWork.ts +713 -0
  654. package/src/durable/ToolReconciler.ts +112 -0
  655. package/src/durable/WakeScheduler.ts +125 -0
  656. package/src/durable/WorkerAdmission.ts +98 -0
  657. package/src/durable/WorkerHost.ts +204 -0
  658. package/src/durable/internal/StorageOwner.ts +181 -0
  659. package/src/durable/internal/agent-registration.ts +713 -0
  660. package/src/durable/internal/agent-updates.ts +338 -0
  661. package/src/durable/internal/canonical-json.ts +110 -0
  662. package/src/durable/internal/evidence.ts +29 -0
  663. package/src/durable/internal/foreign-diagnostic.ts +48 -0
  664. package/src/durable/internal/history-prompt.ts +87 -0
  665. package/src/durable/internal/initial-context.ts +215 -0
  666. package/src/durable/internal/journal-metadata.ts +188 -0
  667. package/src/durable/internal/message-status.ts +18 -0
  668. package/src/durable/internal/messaging-host.ts +615 -0
  669. package/src/durable/internal/prompt-footprint.ts +47 -0
  670. package/src/durable/internal/prompt-history-cache.ts +604 -0
  671. package/src/durable/internal/record-encoding.ts +258 -0
  672. package/src/durable/internal/record-ownership.ts +68 -0
  673. package/src/durable/internal/run-context-reader.ts +51 -0
  674. package/src/durable/internal/run-context.ts +211 -0
  675. package/src/durable/internal/schedule-time.ts +304 -0
  676. package/src/durable/internal/thread-import-reader.ts +85 -0
  677. package/src/durable/internal/thread-initialization.ts +181 -0
  678. package/src/durable/internal/thread-transfer-source.ts +7 -0
  679. package/src/durable/internal/tool-operations.ts +138 -0
  680. package/src/durable/internal/transfer-dependencies.ts +40 -0
  681. package/src/durable/internal/usage-totals.ts +36 -0
  682. package/src/durable/internal/worker-host.ts +4041 -0
  683. package/src/durable/internal/worker-runtime.ts +10 -0
  684. package/src/engine/AgentRuntime.ts +100 -0
  685. package/src/engine/Compaction.ts +11 -0
  686. package/src/engine/ContextCompactor.ts +302 -0
  687. package/src/engine/ContextHistory.ts +75 -0
  688. package/src/engine/ContextWindow.ts +81 -0
  689. package/src/engine/DurableStep.ts +115 -0
  690. package/src/engine/MessagingHost.ts +118 -0
  691. package/src/engine/Output.ts +2 -0
  692. package/src/engine/RunEventSink.ts +124 -0
  693. package/src/engine/RunOptions.ts +664 -0
  694. package/src/engine/SubagentHost.ts +231 -0
  695. package/src/engine/ThreadHistory.ts +125 -0
  696. package/src/engine/ToolBroker.ts +159 -0
  697. package/src/engine/ToolExposure.ts +49 -0
  698. package/src/engine/internal/agent-runtime.ts +11137 -0
  699. package/src/engine/internal/bounded-value.ts +312 -0
  700. package/src/engine/internal/compaction.ts +673 -0
  701. package/src/engine/internal/error-diagnostic.ts +39 -0
  702. package/src/engine/internal/image-tokens.ts +61 -0
  703. package/src/engine/internal/interpreter-options.ts +569 -0
  704. package/src/engine/internal/output-contract.ts +226 -0
  705. package/src/engine/internal/primitive-delta.ts +103 -0
  706. package/src/engine/internal/provider-result-staging.ts +211 -0
  707. package/src/engine/internal/provisional-text.ts +107 -0
  708. package/src/engine/internal/tool-derivative.ts +47 -0
  709. package/src/engine/internal/tool-exposure.ts +228 -0
  710. package/src/engine/internal/tool-telemetry.ts +488 -0
  711. package/src/index.ts +100 -0
  712. package/src/sandbox/CodeExecutor.ts +352 -0
  713. package/src/sandbox/InteractiveBrowser.ts +343 -0
  714. package/src/sandbox/PageCapture.ts +391 -0
  715. package/src/sandbox/PageScreenshot.ts +83 -0
  716. package/src/sandbox/Sandbox.ts +29 -0
  717. package/README.md +0 -3
@@ -0,0 +1,1926 @@
1
+ import * as Prompt from 'effect/ai/Prompt'
2
+ import * as Brand from 'effect/Brand'
3
+ import type * as DateTime from 'effect/DateTime'
4
+ import * as Effect from 'effect/Effect'
5
+ import * as Predicate from 'effect/Predicate'
6
+ import * as Schema from 'effect/Schema'
7
+ import * as Stream from 'effect/Stream'
8
+
9
+ import { type RunId, type SubmissionId, ThreadId, ToolCallId, type TurnId } from '../core/Identifiers'
10
+ import { type ExhaustedLimit } from '../core/RunEvent'
11
+ import { RunPolicyUsage } from '../core/RunPolicyUsage'
12
+ import { type Selection, type Snapshot } from '../core/ToolExposure'
13
+ import type { ToolParameterRejection } from '../core/ToolResult'
14
+ import { type ModelCallUsage, type RunUsageSummary, summarizeModelUsage } from '../core/Usage'
15
+ import type { WorkerRef } from '../core/Worker'
16
+ import {
17
+ CLEARED_TOOL_RESULT,
18
+ COMPACTION_SUMMARY_PREFIX,
19
+ contextWindowId,
20
+ contextWindowMessage,
21
+ } from '../engine/Compaction'
22
+ import { type RunTurnToolResult } from '../engine/internal/interpreter-options'
23
+ import { digestJson } from './Digest'
24
+ import {
25
+ type JournalMetadata,
26
+ type JournalRecordEnvelope,
27
+ makeJournalMetadata,
28
+ toolCallSettledRecordId,
29
+ } from './internal/journal-metadata'
30
+ import { continuationUsage } from './internal/usage-totals'
31
+ import {
32
+ type BatchId,
33
+ CanonicalBatch,
34
+ type CanonicalRecordEnvelope,
35
+ CanonicalSequence,
36
+ type CompactionCreated,
37
+ type DeploymentId,
38
+ MAX_PERSISTED_JSON_BYTES,
39
+ ModelResponseRecorded,
40
+ type PersistedJson,
41
+ type ProducerId,
42
+ RecordEnvelope,
43
+ type RecordId,
44
+ RunCompleted,
45
+ ToolCallSettled,
46
+ } from './Records'
47
+ import { IdempotencyKey } from './SubmissionLedger'
48
+
49
+ /** A canonical record could not be projected into Run/Prompt state. */
50
+ export class RunJournalError extends Schema.TaggedError<RunJournalError>()('RunJournalError', {
51
+ message: Schema.String,
52
+ cause: Schema.optionalKey(Schema.Defect()),
53
+ }) {}
54
+
55
+ const journalError = (message: string, cause?: unknown): RunJournalError =>
56
+ cause === undefined
57
+ ? RunJournalError.make({ message })
58
+ : RunJournalError.make({ message, cause })
59
+
60
+ // These constructors produce nonempty strings from fixed prefixes or validated nonempty IDs.
61
+ // Keep the canonical Schemas as the validation boundary for incoming and persisted values.
62
+ const makeRunId = Brand.nominal<RunId>()
63
+ const makeTurnId = Brand.nominal<TurnId>()
64
+ const makeBatchId = Brand.nominal<BatchId>()
65
+ const makeRecordId = Brand.nominal<RecordId>()
66
+
67
+ /**
68
+ * Deterministic Run identity pinned per Submission (plan §Coordinator flow). Every Attempt of one
69
+ * Submission shares this Run identity, so canonical per-Turn records from different Attempts
70
+ * belong to one logical Run.
71
+ */
72
+ export const runIdForSubmission = (submissionId: SubmissionId): RunId => makeRunId(`run:${submissionId}`)
73
+
74
+ /** Stable canonical clock identity shared by every Attempt of one Run. */
75
+ export const runStartedRecordId = (runId: RunId): RecordId => makeRecordId(`run-start:${runId}`)
76
+
77
+ export const runStartedBatchId = (runId: RunId): BatchId => makeBatchId(`run-start:${runId}`)
78
+
79
+ export const runDurationRecordId = (runId: RunId): RecordId => makeRecordId(`run-duration:${runId}`)
80
+
81
+ export const runDurationBatchId = (runId: RunId): BatchId => makeBatchId(`run-duration:${runId}`)
82
+
83
+ /** Deterministic Turn identity: Attempt-independent for one (Run, canonical turn) pair. */
84
+ export const turnIdForRun = (runId: RunId, turn: number): TurnId => makeTurnId(`turn:${runId}:${turn}`)
85
+
86
+ /** Deterministic batch identity of a response committed atomically with its closed Turn outcomes. */
87
+ export const turnBatchId = (runId: RunId, turn: number): BatchId => makeBatchId(`turn:${runId}:${turn}`)
88
+
89
+ /**
90
+ * Deterministic batch identity of a tool-declaring Turn's RESPONSE commit (plan §2.1 commit 1):
91
+ * the assistant response plus pending steering becomes canonical before approval preflight and
92
+ * dispatch fencing, or when readonly execution first requires a persisted call-scoped capability.
93
+ * Unsettled declarations conservatively record possible execution.
94
+ */
95
+ export const turnResponseBatchId = (runId: RunId, turn: number): BatchId =>
96
+ makeBatchId(`turn-response:${runId}:${turn}`)
97
+
98
+ /**
99
+ * Deterministic batch identity of a tool-declaring Turn's RESULTS commit (plan §2.1 commit 5):
100
+ * every `ToolCallSettled` record of the Turn, in declaration order, model-visible atomically.
101
+ */
102
+ export const turnResultsBatchId = (runId: RunId, turn: number): BatchId => makeBatchId(`turn-results:${runId}:${turn}`)
103
+
104
+ /**
105
+ * Deterministic per-call late-settle batch identity used by the resolution path when one
106
+ * recovered/resolved call settles outside its Turn's results batch. Record identity
107
+ * (`tool-settled:{runId}:{turn}:{toolCallId}`) dedupes double-settles across both paths.
108
+ */
109
+ export const toolCallResultBatchId = (
110
+ runId: RunId,
111
+ turn: number,
112
+ toolCallId: ToolCallId,
113
+ ): BatchId => makeBatchId(`turn-results:${runId}:${turn}:${toolCallId}`)
114
+
115
+ /**
116
+ * Deterministic identity of one pre-Turn compaction record (RUN-026,
117
+ * RUN-026). Keyed by Run, Turn, and kind — the engine performs at most one
118
+ * threshold compaction per Turn plus at most one overflow-forced summarize,
119
+ * so a superseding Attempt that re-decides the same compaction replays the
120
+ * batch identity instead of duplicating the record.
121
+ */
122
+ export const compactionRecordId = (
123
+ runId: RunId,
124
+ turn: number,
125
+ kind: 'clear-tool-results' | 'summarize' | 'rollover',
126
+ ): RecordId => makeRecordId(`compaction:${runId}:${turn}:${kind}`)
127
+
128
+ /** Deterministic batch identity of one compaction append (same string as its record id). */
129
+ export const compactionBatchId = (
130
+ runId: RunId,
131
+ turn: number,
132
+ kind: 'clear-tool-results' | 'summarize' | 'rollover',
133
+ ): BatchId => makeBatchId(`compaction:${runId}:${turn}:${kind}`)
134
+
135
+ /** Deterministic canonical record identity of one Turn's `ModelResponseRecorded` record. */
136
+ export const modelResponseRecordId = (runId: RunId, turn: number): RecordId =>
137
+ makeRecordId(`model-response:${runId}:${turn}`)
138
+
139
+ /** Terminal Tool completion marker committed atomically with its settled Tool result. */
140
+ export const runCompletedRecordId = (runId: RunId): RecordId => makeRecordId(`run-completed:${runId}`)
141
+
142
+ /** Native source reservation locator, including the first admission of a continuing worker. */
143
+ export const workerInputRecordId = (messageId: IdempotencyKey): RecordId => makeRecordId(`worker-input:${messageId}`)
144
+
145
+ /** Source-owned first reservation; native worker identity is minted from its first message. */
146
+ export const firstWorkerInputRecordId = (worker: WorkerRef): RecordId => makeRecordId(`worker-input:${worker.threadId}`)
147
+
148
+ export const workerOriginRecordId = (threadId: ThreadId): RecordId => makeRecordId(`worker-origin:${threadId}`)
149
+
150
+ export const workerReportRecordId = (messageId: IdempotencyKey): RecordId => makeRecordId(`worker-report:${messageId}`)
151
+
152
+ export const peerMessageRecordId = (messageId: IdempotencyKey): RecordId => makeRecordId(messageId)
153
+
154
+ /** Same immutable tuple used by native update admission; callers never parse its hash. */
155
+ export const agentUpdateRecordId = Effect.fnUntraced(function*(
156
+ threadId: ThreadId,
157
+ runId: RunId,
158
+ updateId: IdempotencyKey,
159
+ ) {
160
+ return makeRecordId(`agent-update:${yield* digestJson([threadId, runId, updateId])}`)
161
+ })
162
+
163
+ /** Deterministic canonical record identity of one Turn's `ToolCallSettled` record. */
164
+ export { toolCallSettledRecordId }
165
+
166
+ /** Deterministic batch identity of one Turn's `ToolCallUnknown` marking append. */
167
+ export const markUnknownBatchId = (submissionId: SubmissionId, turn: number): BatchId =>
168
+ makeBatchId(`mark-unknown:${submissionId}:${turn}`)
169
+
170
+ /** Deterministic canonical record identity of one Tool Call's `ToolCallUnknown` record. */
171
+ export const toolCallUnknownRecordId = (
172
+ runId: RunId,
173
+ turn: number,
174
+ toolCallId: ToolCallId,
175
+ ): RecordId => makeRecordId(`tool-unknown:${runId}:${turn}:${toolCallId}`)
176
+
177
+ /** Deterministic batch identity of one Tool Call's resolution append (DUR-017). */
178
+ export const toolCallResolutionBatchId = (
179
+ submissionId: SubmissionId,
180
+ toolCallId: ToolCallId,
181
+ ): BatchId => makeBatchId(`resolve:${submissionId}:${toolCallId}`)
182
+
183
+ /** Deterministic canonical record identity of one Tool Call's `ToolCallResolved` record. */
184
+ export const toolCallResolvedRecordId = (
185
+ runId: RunId,
186
+ turn: number,
187
+ toolCallId: ToolCallId,
188
+ ): RecordId => makeRecordId(`tool-resolved:${runId}:${turn}:${toolCallId}`)
189
+
190
+ /**
191
+ * Deterministic identity of one accepted Durable Step result. The one-record batch reuses the
192
+ * SAME string, so batch idempotency plus the epoch fence realize the durability §11
193
+ * racing-writers rule: only the fenced winner's record commits; the loser replays it.
194
+ * A versioned JSON tuple keeps separator characters in each identity component distinct.
195
+ * Replay derives this key from the structured payload, including records with legacy IDs.
196
+ */
197
+ export const toolStepSettledRecordId = (
198
+ runId: RunId,
199
+ toolCallId: ToolCallId,
200
+ stepName: string,
201
+ ): RecordId => makeRecordId(JSON.stringify(['step@2', runId, toolCallId, stepName]))
202
+
203
+ /** Deterministic batch identity of one Durable Step commit (same string as its record id). */
204
+ export const toolStepSettledBatchId = (
205
+ runId: RunId,
206
+ toolCallId: ToolCallId,
207
+ stepName: string,
208
+ ): BatchId => makeBatchId(toolStepSettledRecordId(runId, toolCallId, stepName))
209
+
210
+ /** Deterministic batch identity of one Turn's canonical approval-request append (plan §2.6). */
211
+ export const turnApprovalsBatchId = (runId: RunId, turn: number): BatchId =>
212
+ makeBatchId(`turn-approvals:${runId}:${turn}`)
213
+
214
+ /** Deterministic canonical record identity of one Tool Call's `ToolApprovalRequested` record. */
215
+ export const toolApprovalRequestRecordId = (
216
+ runId: RunId,
217
+ turn: number,
218
+ toolCallId: ToolCallId,
219
+ ): RecordId => makeRecordId(`approval-request:${runId}:${turn}:${toolCallId}`)
220
+
221
+ /** Deterministic batch identity of one Tool Call's canonical approval-decision append. */
222
+ export const approvalDecisionBatchId = (
223
+ submissionId: SubmissionId,
224
+ toolCallId: ToolCallId,
225
+ ): BatchId => makeBatchId(`approval-decision:${submissionId}:${toolCallId}`)
226
+
227
+ /** Deterministic canonical record identity of one Tool Call's `ToolApprovalDecided` record. */
228
+ export const toolApprovalDecisionRecordId = (
229
+ runId: RunId,
230
+ turn: number,
231
+ toolCallId: ToolCallId,
232
+ ): RecordId => makeRecordId(`approval-decision:${runId}:${turn}:${toolCallId}`)
233
+
234
+ /**
235
+ * One conservative incomplete-usage marker per Run, regardless of how often recovery occurs.
236
+ */
237
+ export const modelResponseInterruptedRecordId = (runId: RunId): RecordId => makeRecordId(`interrupted:${runId}`)
238
+
239
+ /** Deterministic batch identity of one `ModelResponseInterrupted` append (same string). */
240
+ export const modelResponseInterruptedBatchId = (runId: RunId): BatchId => makeBatchId(`interrupted:${runId}`)
241
+
242
+ const decodeThreadId = Schema.decodeSync(ThreadId)
243
+ const decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey)
244
+
245
+ /**
246
+ * Deterministic canonical record identity of one parent Tool Call's `SubagentRequested` record.
247
+ * The one-record batch reuses the same string, so batch
248
+ * idempotency plus the parent epoch fence make the request append exactly-once-canonical.
249
+ */
250
+ export const subagentRequestedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>
251
+ makeRecordId(`subagent-requested:${runId}:${toolCallId}`)
252
+
253
+ /** Deterministic batch identity of one `SubagentRequested` append (same string). */
254
+ export const subagentRequestedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>
255
+ makeBatchId(`subagent-requested:${runId}:${toolCallId}`)
256
+
257
+ /**
258
+ * Deterministic canonical record identity of one parent Tool Call's `SubagentStarted` record.
259
+ * Recovery's start-link repair appends the EXACT same record
260
+ * under this identity, so a raced repair replays instead of duplicating (SUB-016/SUB-017).
261
+ */
262
+ export const subagentStartedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>
263
+ makeRecordId(`subagent-started:${runId}:${toolCallId}`)
264
+
265
+ /** Deterministic batch identity of one `SubagentStarted` append (same string). */
266
+ export const subagentStartedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>
267
+ makeBatchId(`subagent-started:${runId}:${toolCallId}`)
268
+
269
+ /**
270
+ * Deterministic batch identity of one parent Tool Call's atomic settlement join: the
271
+ * `SubagentJoined` record plus the parent's `ToolCallSettled` record (its existing
272
+ * `tool-settled:{runId}:{turn}:{toolCallId}` identity) commit as ONE canonical batch (SUB-019).
273
+ */
274
+ export const subagentJoinBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>
275
+ makeBatchId(`subagent-join:${runId}:${toolCallId}`)
276
+
277
+ /** Deterministic canonical record identity of one parent Tool Call's `SubagentJoined` record. */
278
+ export const subagentJoinedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>
279
+ makeRecordId(`subagent-joined:${runId}:${toolCallId}`)
280
+
281
+ /**
282
+ * Deterministic identity of one child Thread's `SubagentLineageRecorded` record.
283
+ * Its own single-record batch reuses the same string so the generic
284
+ * `thread-created:{cid}` batch identity is never contradicted.
285
+ */
286
+ export const subagentLineageRecordId = (threadId: ThreadId): RecordId => makeRecordId(`subagent-lineage:${threadId}`)
287
+
288
+ /** Deterministic batch identity of one `SubagentLineageRecorded` append (same string). */
289
+ export const subagentLineageBatchId = (threadId: ThreadId): BatchId => makeBatchId(`subagent-lineage:${threadId}`)
290
+
291
+ /**
292
+ * Deterministic intended child Thread identity: the
293
+ * parent Submission and Tool Call pair addresses exactly one child Thread, so a replayed
294
+ * establishment converges on the one existing child (SUB-016).
295
+ */
296
+ export const childThreadIdFor = (
297
+ parentSubmissionId: SubmissionId,
298
+ toolCallId: ToolCallId,
299
+ ): ThreadId => decodeThreadId(`subagent:${parentSubmissionId}:${toolCallId}`)
300
+
301
+ /**
302
+ * Deterministic child admission idempotency key: scoped to
303
+ * the parent Run and Tool Call identity, so duplicate admission attempts resolve through the
304
+ * ledger's idempotency contract to one child Receipt (SUB-016, SUB-031). The ledger key is
305
+ * bounded (256); coordinator-minted Run and Tool Call identities stay far below that bound.
306
+ */
307
+ export const childIdempotencyKeyFor = (
308
+ parentRunId: RunId,
309
+ toolCallId: ToolCallId,
310
+ ): IdempotencyKey => decodeIdempotencyKey(`subagent:${parentRunId}:${toolCallId}`)
311
+
312
+ const decodePersistedPrompt = (
313
+ messages: PersistedJson,
314
+ ): Effect.Effect<Prompt.Prompt, RunJournalError> =>
315
+ Schema.decodeUnknownEffect(Prompt.Prompt)(messages).pipe(
316
+ Effect.mapError((cause) => journalError('Canonical messages are not Schema-encoded Prompt messages', cause)),
317
+ )
318
+
319
+ // Canonical payloads are immutable. Weak keys let retained storage rows own the lifetime
320
+ // while repeated projections of an advancing tail reuse their validated Prompt values.
321
+ const decodedMessages = new WeakMap<object, Prompt.Prompt>()
322
+
323
+ const decodePromptMessages = (messages: PersistedJson | Prompt.Prompt) =>
324
+ Effect.suspend(() => {
325
+ if (Prompt.isPrompt(messages)) return Effect.succeed(messages)
326
+ if (!Predicate.isObject(messages)) return decodePersistedPrompt(messages)
327
+ const cached = decodedMessages.get(messages)
328
+
329
+ return cached === undefined
330
+ ? decodePersistedPrompt(messages).pipe(
331
+ Effect.tap((prompt) =>
332
+ Effect.sync(() => {
333
+ decodedMessages.set(messages, prompt)
334
+ })
335
+ ),
336
+ )
337
+ : Effect.succeed(cached)
338
+ })
339
+
340
+ interface PendingSettledTool {
341
+ readonly record: Pick<ToolCallSettled, 'toolCallId' | 'toolName' | 'result' | 'isFailure'>
342
+ /** RUN-026: a `clear-tool-results` compaction covers this record's sequence. */
343
+ readonly cleared: boolean
344
+ }
345
+
346
+ const toolMessageFromSettled = (
347
+ settled: ReadonlyArray<PendingSettledTool>,
348
+ ): Effect.Effect<Prompt.Message, RunJournalError> =>
349
+ Effect.try({
350
+ try: () =>
351
+ Prompt.makeMessage('tool', {
352
+ content: settled.map(({ record, cleared }) =>
353
+ Prompt.makePart('tool-result', {
354
+ id: record.toolCallId,
355
+ name: record.toolName,
356
+ result: cleared ? CLEARED_TOOL_RESULT : record.result,
357
+ isFailure: record.isFailure,
358
+ providerExecuted: false,
359
+ })
360
+ ),
361
+ }),
362
+ catch: (cause) => journalError('Unable to rebuild Tool message from ToolCallSettled', cause),
363
+ })
364
+
365
+ /**
366
+ * Pure canonical projection of one Run's durable execution state.
367
+ *
368
+ * Prompt reconstruction contract (D8):
369
+ *
370
+ * - `ModelResponseRecorded.messages` carries the Schema-encoded Prompt messages the Turn appended
371
+ * to the model-visible prompt — for the Run's FIRST committed Turn that includes the evaluated
372
+ * instruction and user-input messages, for later Turns only the assistant response messages.
373
+ * Tool messages are excluded from `messages`.
374
+ * - `ToolCallSettled` records (committed in the same per-Turn batch, in declaration order)
375
+ * deterministically rebuild the Turn's single Tool message.
376
+ * - `UserInputRecorded` records input, with a Submission identity only for durable admission. Its
377
+ * Prompt-visible form (instructions + user message) becomes canonical inside the owning Run's
378
+ * first `ModelResponseRecorded`. The projection consumes it only for Run correlation.
379
+ * - Immediate retained history uses `ModelCompleted.history` as a full retained model-context
380
+ * snapshot. Its `messages` separately preserve the successful Run's exact source contribution
381
+ * for recall. It has no resumable Turn state.
382
+ */
383
+ /** Cumulative committed usage of the projected Run (RUN-023 resume re-seed). */
384
+ export interface RunJournalUsage {
385
+ readonly modelCalls: number
386
+ /** Known accounting gaps retained across Attempts without changing numeric usage totals. */
387
+ readonly unobservedModelCalls?: number | undefined
388
+ readonly inputTokens: number
389
+ readonly outputTokens: number
390
+ readonly lastInputTokens: number
391
+ readonly lastOutputTokens: number
392
+ /** Cumulative persisted spend of the projected Run's committed calls (RUN-023). */
393
+ readonly costMicrousd: number
394
+ /** Canonical per-call detail used for settlement aggregation and recovery. */
395
+ readonly modelUsage: ReadonlyArray<ModelCallUsage>
396
+ /** Detailed usage of retired records, grouped without retaining per-call payloads. */
397
+ readonly summarizedModelUsage?: RunUsageSummary | undefined
398
+ }
399
+
400
+ export interface RunJournalProjection {
401
+ readonly toolSelection?: Selection | undefined
402
+ readonly policyUsage: RunPolicyUsage
403
+ /** Canonical projection for the requested Run; may end at its resumable Tool declaration. */
404
+ readonly prompt: Prompt.Prompt
405
+ /** Prior-Run history with model-only unknown results closing incomplete application calls. */
406
+ readonly historyBefore: Prompt.Prompt
407
+ /** Inclusive range after effective summarize/rollover coverage; earlier used facts stay retained. */
408
+ readonly historyFrom: CanonicalSequence
409
+ /** Number of canonical Turns already committed for the projected Run. */
410
+ readonly committedTurns: number
411
+ /** Summed per-call usage of the projected Run's committed responses; zeros for records predating usage capture. */
412
+ readonly usage: RunJournalUsage
413
+ /** Latest committed context window identity, retained across ownership changes. */
414
+ readonly contextWindowId?: string | undefined
415
+ /** Canonical evaluated instructions and initial input for this Run, independent of the view. */
416
+ readonly protectedContext?: Prompt.Prompt | undefined
417
+ /** Last successful singleton Tool awaiting possible context-control interpretation by the engine. */
418
+ readonly pendingContextToolCallId?: string | undefined
419
+ }
420
+
421
+ const initialPolicyUsage = () => ({
422
+ committedTurns: 0,
423
+ toolCalls: 0,
424
+ programmaticToolCalls: 0,
425
+ consecutiveToolFailures: 0,
426
+ finalizationUsed: false,
427
+ modelRestarts: 0,
428
+ })
429
+
430
+ const initialUsage = (modelUsage: Array<ModelCallUsage>) => ({
431
+ modelCalls: 0,
432
+ inputTokens: 0,
433
+ outputTokens: 0,
434
+ lastInputTokens: 0,
435
+ lastOutputTokens: 0,
436
+ costMicrousd: 0,
437
+ modelUsage,
438
+ })
439
+
440
+ /** Internal first-Run projection after exact input/checkpoint-absence verification. The
441
+ * new UserInputRecorded contributes no model message; the engine evaluates it later. */
442
+ export const initialRunJournal = (history: Prompt.Prompt): RunJournalProjection => ({
443
+ policyUsage: RunPolicyUsage.make(initialPolicyUsage()),
444
+ usage: initialUsage([]),
445
+ prompt: history,
446
+ historyBefore: history,
447
+ historyFrom: CanonicalSequence.make(1),
448
+ committedTurns: 0,
449
+ })
450
+
451
+ interface ProjectedResponseUsage {
452
+ readonly modelCalls: number
453
+ readonly inputTokens: number
454
+ readonly outputTokens: number
455
+ readonly costMicrousd: number
456
+ readonly modelUsage: ReadonlyArray<ModelCallUsage>
457
+ }
458
+
459
+ const projectedResponseUsage = (
460
+ response: ModelResponseRecorded,
461
+ ): Effect.Effect<ProjectedResponseUsage, RunJournalError> =>
462
+ Effect.gen(function*() {
463
+ const calls = response.modelUsage
464
+
465
+ if (calls === undefined) {
466
+ return {
467
+ modelCalls: 1,
468
+ inputTokens: response.inputTokens ?? 0,
469
+ outputTokens: response.outputTokens ?? 0,
470
+ costMicrousd: response.costMicrousd ?? 0,
471
+ modelUsage: [],
472
+ }
473
+ }
474
+ if (calls.length === 0) {
475
+ return yield* journalError('A canonical modelUsage list must not be empty')
476
+ }
477
+
478
+ const summary = yield* summarizeModelUsage(calls).pipe(
479
+ Effect.mapError((cause) => journalError('Canonical model usage exceeds accounting bounds', cause)),
480
+ )
481
+
482
+ if (
483
+ (response.inputTokens !== undefined && response.inputTokens !== summary.inputTokens.total) ||
484
+ (response.outputTokens !== undefined &&
485
+ response.outputTokens !== summary.outputTokens.total) ||
486
+ (response.costMicrousd !== undefined && response.costMicrousd !== summary.costMicrousd)
487
+ ) {
488
+ return yield* journalError('Canonical detailed and aggregate model usage disagree')
489
+ }
490
+
491
+ return {
492
+ modelCalls: summary.modelCalls,
493
+ inputTokens: summary.inputTokens.total,
494
+ outputTokens: summary.outputTokens.total,
495
+ costMicrousd: summary.costMicrousd,
496
+ modelUsage: calls,
497
+ }
498
+ })
499
+
500
+ const addProjectedUsage = (
501
+ field: string,
502
+ left: number,
503
+ right: number,
504
+ ): Effect.Effect<number, RunJournalError> =>
505
+ Schema.decodeEffect(Schema.Natural)(left + right).pipe(
506
+ Effect.mapError((cause) =>
507
+ journalError(`Canonical projected usage exceeds safe-integer bounds at ${field}`, cause)
508
+ ),
509
+ )
510
+
511
+ interface FoldState {
512
+ readonly all: Array<Prompt.Message>
513
+ readonly before: Array<Prompt.Message>
514
+ readonly pendingTools: Array<PendingSettledTool>
515
+ readonly pendingToolsForRun: boolean
516
+ readonly committedTurns: number
517
+ }
518
+
519
+ const decodeToolCallId = Schema.decodeSync(ToolCallId)
520
+ const decodeToolCallIdEffect = Schema.decodeEffect(ToolCallId)
521
+
522
+ const declaredApplicationToolCallIds = (prompt: Prompt.Prompt): ReadonlyArray<string> => {
523
+ const ids: Array<string> = []
524
+
525
+ for (const message of prompt.content) {
526
+ if (message.role !== 'assistant') continue
527
+ for (const part of message.content) {
528
+ if (part.type === 'tool-call' && !part.providerExecuted) ids.push(part.id)
529
+ }
530
+ }
531
+
532
+ return ids
533
+ }
534
+
535
+ /**
536
+ * Phase 5 audit tags that are prompt-transparent: they carry durability evidence (approval,
537
+ * unknown marking, resolution, Step results, approvals, interruption) but contribute nothing to
538
+ * the model-visible Prompt, and — unlike the P4 tags — they do NOT split a contiguous
539
+ * `ToolCallSettled` group into separate Tool messages, so a late-settled call's audit records
540
+ * cannot change the replayed prompt shape.
541
+ *
542
+ * The four S2 Subagent lifecycle tags are prompt-transparent for the same reason (spec §5/§11):
543
+ * the parent prompt never carries child transcript or establishment evidence — the joined child
544
+ * result reaches the model exclusively through the paired `ToolCallSettled` record, and the
545
+ * child-log lineage record is not model input.
546
+ */
547
+ const PROMPT_TRANSPARENT_TAGS: ReadonlySet<string> = new Set([
548
+ 'RunPolicyUsageReserved',
549
+ 'RunStarted',
550
+ 'RunContextRecorded',
551
+ 'RunContinuation',
552
+ 'RunDurationExhausted',
553
+ 'ToolCallUnknown',
554
+ 'ToolCallResolved',
555
+ 'ToolStepSettled',
556
+ 'ToolApprovalRequested',
557
+ 'ToolApprovalDecided',
558
+ 'ModelResponseInterrupted',
559
+ 'ModelCallAborted',
560
+ 'SubagentRequested',
561
+ 'SubagentStarted',
562
+ 'SubagentJoined',
563
+ 'SubagentLineageRecorded',
564
+ 'WorkerInputRequested',
565
+ 'WorkerOriginRecorded',
566
+ 'WorkerInputCompleted',
567
+ 'WorkerInputRefused',
568
+ 'WorkerReportPrepared',
569
+ 'AgentUpdateEmitted',
570
+ 'WorkerReportRefused',
571
+ 'PeerMessagePrepared',
572
+ 'SubtreeBudgetReserved',
573
+ ])
574
+
575
+ /**
576
+ * Pure projection: rebuild one Run's resume state from canonical records (DUR-015). Canonical
577
+ * order is authoritative; the fold projects each `ModelResponseRecorded` Turn and the
578
+ * owning Run's resumable incomplete Tool Turn. It flushes each contiguous group of valid `ToolCallSettled` records into one Tool message,
579
+ * exactly mirroring the per-Turn commit shape produced by `turnCanonicalBatch` and the
580
+ * `turnResponseBatch`/`turnResultsBatch` split. The Phase 5 audit tags
581
+ * are skipped transparently, so split-batch commits replay to the same prompt as P4 single-batch
582
+ * commits.
583
+ *
584
+ * An incomplete application Tool turn remains visible while projecting its owning Run so active
585
+ * recovery can resume the declared batch. It is not a valid model-visible Turn boundary for a
586
+ * later Run until model-only unknown results close its missing calls. Those explanatory results
587
+ * are never canonical settlements or evidence for compaction, recovery or accounting. Real
588
+ * results replace them at the original declaration, including results appended after another Run.
589
+ * Prior user intent and assistant text remain visible; prior system instructions do not.
590
+ * Each Run retains the history preceding its start and its own continuation. Other Runs'
591
+ * subsequent Turns cannot replace its input. Compaction covers only its creator's Run view;
592
+ * a projection without an owner retains interleaved exchanges from the complete Thread history.
593
+ */
594
+ /** @internal Lightweight canonical boundaries collected without retaining record payloads. */
595
+ export interface JournalBoundary {
596
+ readonly sequence: CanonicalSequence
597
+ readonly tag:
598
+ | 'ModelCompleted'
599
+ | 'ModelResponseRecorded'
600
+ | 'ToolCallSettled'
601
+ | 'CompactionCreated'
602
+ readonly promptLength: number
603
+ /** A declaration without all settled results requires terminal-prior-Run proof for coverage. */
604
+ readonly incomplete?: true | undefined
605
+ /** The Run terminated after its last response and differs from the projection's owner. */
606
+ readonly terminalPriorRun?: true | undefined
607
+ }
608
+
609
+ /** Resolved immutable context. Persistence keeps a canonical range and digest, not this Prompt. */
610
+ export interface RunJournalContext {
611
+ readonly runId: RunId
612
+ readonly prompt: Prompt.Prompt
613
+ readonly priorHistoryLength: number
614
+ readonly historyFrom: CanonicalSequence
615
+ readonly boundaries: ReadonlyArray<JournalBoundary>
616
+ readonly contextWindowId?: string | undefined
617
+ readonly recordId: RecordId
618
+ }
619
+
620
+ /**
621
+ * Reconstruct a fixed canonical prefix from a re-readable stream. The caller must keep the same
622
+ * records visible on every traversal. The first collects compaction and settlement metadata;
623
+ * rollovers additionally validate covered Tool batches before rebuilding Prompt and usage. Metadata and the
624
+ * live Prompt remain resident; covered historical message/tool payloads do not. An uncompacted Prompt still grows
625
+ * with its conversation, so hosts must configure an appropriate context compaction policy.
626
+ * Prepared metadata must describe exactly this stream through the same fixed tail;
627
+ * it skips only the metadata scan, never covered-Tool validation or the canonical fold.
628
+ * @internal
629
+ */
630
+ export const projectRunJournalStream = Effect.fnUntraced(function*<
631
+ E,
632
+ R,
633
+ A extends JournalRecordEnvelope,
634
+ >(
635
+ records: Stream.Stream<A, E, R>,
636
+ ownerRunId: RunId | undefined,
637
+ onBoundary?: (boundary: JournalBoundary) => void,
638
+ savedContext?: RunJournalContext,
639
+ preparedMetadata?: JournalMetadata,
640
+ onEvidence?: (envelope: A) => void,
641
+ ): Effect.fn.Return<RunJournalProjection, RunJournalError | E, R> {
642
+ if (savedContext !== undefined && savedContext.runId !== ownerRunId) {
643
+ return yield* journalError('Saved original context belongs to another Run')
644
+ }
645
+
646
+ const initialContext = savedContext?.prompt
647
+
648
+ if (
649
+ initialContext !== undefined &&
650
+ savedContext !== undefined &&
651
+ savedContext.priorHistoryLength > initialContext.content.length
652
+ ) {
653
+ return yield* journalError('Saved original context has an invalid ownership boundary')
654
+ }
655
+ const historical = initialContext?.content.slice(0, savedContext?.priorHistoryLength) ?? []
656
+
657
+ let state: FoldState = {
658
+ all: [],
659
+ before: [],
660
+ pendingTools: [],
661
+ pendingToolsForRun: false,
662
+ committedTurns: 0,
663
+ }
664
+
665
+ // RUN-026 pre-scan: valid compactions retire only their creator's Run view. A bound
666
+ // stays below its own sequence and cannot split a visible response from its settled results.
667
+ // Pruning and rollovers may cover complete owner-Run batches; a summarize record carries
668
+ // its summary. Invalid records leave full history authoritative. A wider containing view
669
+ // replaces earlier coverage, with equal bounds preferring the later record.
670
+ // Exact declaration spans are validated at each compaction's own captured prefix.
671
+ // Later results preserve committed coverage and close retained or summarized calls below.
672
+ if (preparedMetadata !== undefined && preparedMetadata.ownerRunId !== ownerRunId) {
673
+ return yield* journalError('Prepared journal metadata belongs to another replay')
674
+ }
675
+
676
+ let metadata = preparedMetadata
677
+
678
+ if (metadata === undefined) {
679
+ const collected = makeJournalMetadata(ownerRunId)
680
+
681
+ yield* Stream.runForEach(records, (envelope) => Effect.sync(() => collected.add(envelope)))
682
+ metadata = collected.finish()
683
+ }
684
+
685
+ const {
686
+ firstSequenceByRun,
687
+ responseSequencesByRun,
688
+ terminalSequenceByRun,
689
+ settledSpans,
690
+ settledSequenceById,
691
+ settledToolCallRecordIds,
692
+ settledById,
693
+ } = metadata
694
+
695
+ const declarationByResultSequence = new Map(settledSpans.map(({ from, to }) => [to, from]))
696
+ const spansByDeclaration = new Map<number, Array<(typeof settledSpans)[number]>>()
697
+
698
+ for (const span of settledSpans) {
699
+ const spans = spansByDeclaration.get(span.from) ?? []
700
+
701
+ spans.push(span)
702
+ spansByDeclaration.set(span.from, spans)
703
+ }
704
+
705
+ const isInRunView = (
706
+ sequence: number,
707
+ payload: { readonly _tag: string; readonly runId?: RunId | undefined },
708
+ runId: RunId | undefined,
709
+ ): boolean => {
710
+ if (runId === undefined || payload.runId === undefined || payload.runId === runId) return true
711
+ const first = firstSequenceByRun.get(runId) ?? Number.POSITIVE_INFINITY
712
+
713
+ return (
714
+ sequence < first ||
715
+ (payload._tag === 'ToolCallSettled' &&
716
+ (declarationByResultSequence.get(sequence) ?? Number.POSITIVE_INFINITY) < first)
717
+ )
718
+ }
719
+
720
+ const compactions = metadata.compactions.filter(({ sequence, payload }) => isInRunView(sequence, payload, ownerRunId))
721
+
722
+ const recordsForRun = records.pipe(
723
+ Stream.filter(({ sequence, record: { payload } }) => isInRunView(sequence, payload, ownerRunId)),
724
+ )
725
+
726
+ const isCovered = (envelope: JournalRecordEnvelope, compaction: CompactionCreated): boolean =>
727
+ envelope.sequence <= compaction.coversThrough &&
728
+ isInRunView(envelope.sequence, envelope.record.payload, compaction.runId)
729
+
730
+ const settledCoverage = compactions.reduce(
731
+ (through, { payload }) => payload.kind !== 'summarize' ? Math.max(through, payload.coversThrough) : through,
732
+ 0,
733
+ )
734
+
735
+ // Terminality changes only prompt coverage; it never settles or resolves the Tool Call.
736
+ // Compare against the compaction's Run and sequence, independent of the replay's owner.
737
+ const isTerminalPriorRun = (
738
+ candidateRunId: RunId,
739
+ compactionRunId: RunId | undefined,
740
+ beforeSequence: number,
741
+ ): boolean => {
742
+ const terminal = terminalSequenceByRun.get(candidateRunId)
743
+
744
+ return (
745
+ candidateRunId !== compactionRunId &&
746
+ terminal !== undefined &&
747
+ terminal < beforeSequence &&
748
+ terminal >
749
+ (responseSequencesByRun
750
+ .get(candidateRunId)
751
+ ?.findLast((sequence) => sequence < beforeSequence) ?? 0)
752
+ )
753
+ }
754
+
755
+ const incompleteResponseSequences: Array<{
756
+ readonly sequence: number
757
+ readonly runId: RunId
758
+ readonly lastSettlementSequence: number
759
+ }> = []
760
+
761
+ let ownerPrefixSequence = firstSequenceByRun.get(ownerRunId ?? '') ?? Number.POSITIVE_INFINITY
762
+
763
+ let protectedContext: Prompt.Prompt | undefined = initialContext === undefined
764
+ ? undefined
765
+ : Prompt.fromMessages(initialContext.content.slice(savedContext?.priorHistoryLength))
766
+
767
+ if (settledCoverage > 0) {
768
+ yield* Stream.runForEach(recordsForRun, (envelope) =>
769
+ Effect.gen(function*() {
770
+ const payload = envelope.record.payload
771
+
772
+ if (payload._tag !== 'ModelResponseRecorded' || envelope.sequence > settledCoverage) return
773
+ const messages = yield* decodePromptMessages(payload.messages)
774
+ const declared = declaredApplicationToolCallIds(messages)
775
+
776
+ let lastSettlementSequence = 0
777
+
778
+ for (const id of declared) {
779
+ const callId = yield* decodeToolCallIdEffect(id).pipe(
780
+ Effect.mapError((cause) => journalError('Failed to decode a declared Tool Call ID', cause)),
781
+ )
782
+
783
+ lastSettlementSequence = Math.max(
784
+ lastSettlementSequence,
785
+ settledSequenceById.get(toolCallSettledRecordId(payload.runId, payload.turn, callId)) ??
786
+ Infinity,
787
+ )
788
+ }
789
+ if (declared.length > 0) {
790
+ incompleteResponseSequences.push({
791
+ sequence: envelope.sequence,
792
+ runId: payload.runId,
793
+ lastSettlementSequence,
794
+ })
795
+ }
796
+ if (
797
+ payload.runId === ownerRunId &&
798
+ payload.turn === 1 &&
799
+ payload.runScopedPrefixLength !== undefined
800
+ ) {
801
+ ownerPrefixSequence = envelope.sequence
802
+ protectedContext = Prompt.fromMessages(
803
+ messages.content.slice(0, payload.runScopedPrefixLength),
804
+ )
805
+ }
806
+ }))
807
+ }
808
+
809
+ const boundIsValid = (
810
+ payload: CompactionCreated,
811
+ ownSequence: number,
812
+ evidence?: Set<number>,
813
+ ): boolean => {
814
+ const { runId, coversThrough } = payload
815
+
816
+ if (coversThrough <= 0 || coversThrough >= ownSequence) return false
817
+ const ownerFirst = firstSequenceByRun.get(runId)
818
+
819
+ if (payload.kind === 'summarize' && ownerFirst !== undefined && coversThrough >= ownerFirst) {
820
+ return false
821
+ }
822
+ if (
823
+ payload.kind !== 'summarize' &&
824
+ savedContext?.boundaries.some(
825
+ (boundary) =>
826
+ boundary.sequence <= coversThrough &&
827
+ boundary.incomplete === true &&
828
+ boundary.terminalPriorRun !== true,
829
+ )
830
+ ) {
831
+ return false
832
+ }
833
+ if (payload.kind !== 'summarize') {
834
+ for (const response of incompleteResponseSequences) {
835
+ if (
836
+ response.sequence > coversThrough ||
837
+ response.lastSettlementSequence < ownSequence ||
838
+ !isInRunView(
839
+ response.sequence,
840
+ { _tag: 'ModelResponseRecorded', runId: response.runId },
841
+ runId,
842
+ )
843
+ ) {
844
+ continue
845
+ }
846
+ if (evidence !== undefined) {
847
+ evidence.add(response.sequence)
848
+ const terminal = terminalSequenceByRun.get(response.runId)
849
+
850
+ const lastResponse = responseSequencesByRun
851
+ .get(response.runId)
852
+ ?.findLast((sequence) => sequence < ownSequence)
853
+
854
+ if (terminal !== undefined) evidence.add(terminal)
855
+ if (lastResponse !== undefined) evidence.add(lastResponse)
856
+ }
857
+ if (!isTerminalPriorRun(response.runId, runId, ownSequence)) return false
858
+ }
859
+ }
860
+ for (const span of settledSpans) {
861
+ if (
862
+ span.from <= coversThrough &&
863
+ coversThrough < span.to &&
864
+ span.to < ownSequence &&
865
+ isInRunView(span.from, { _tag: 'ModelResponseRecorded', runId: span.runId }, runId)
866
+ ) {
867
+ evidence?.add(span.from)
868
+ evidence?.add(span.to)
869
+
870
+ return false
871
+ }
872
+ }
873
+
874
+ return true
875
+ }
876
+
877
+ type CompactionView = (typeof compactions)[number]
878
+
879
+ let replacements: ReadonlyArray<CompactionView> = []
880
+ let clearings: ReadonlyArray<CompactionView> = []
881
+
882
+ const retainCompaction = (views: ReadonlyArray<CompactionView>, next: CompactionView) => {
883
+ // Independent Run views overlap without containing one another. Retire an overlay only
884
+ // when the replacement actually contains its view, not merely a larger sequence number.
885
+ if (
886
+ views.some(
887
+ (prior) =>
888
+ prior.payload.coversThrough > next.payload.coversThrough &&
889
+ isInRunView(next.sequence, next.payload, prior.payload.runId),
890
+ )
891
+ ) {
892
+ return views
893
+ }
894
+
895
+ return [
896
+ ...views.filter(
897
+ (prior) =>
898
+ next.payload.coversThrough < prior.payload.coversThrough ||
899
+ !isInRunView(prior.sequence, prior.payload, next.payload.runId),
900
+ ),
901
+ next,
902
+ ]
903
+ }
904
+
905
+ let latestWindowId: string | undefined = savedContext?.contextWindowId
906
+ let latestWindowSequence = -1
907
+ let latestWindow: CompactionView | undefined
908
+ let rolloverCoveredThrough = 0
909
+
910
+ for (const { payload, sequence } of compactions) {
911
+ if (!boundIsValid(payload, sequence)) continue
912
+ if (payload.kind === 'rollover' && sequence > latestWindowSequence) {
913
+ latestWindowId = contextWindowId(payload.runId, payload.turn)
914
+ latestWindowSequence = sequence
915
+ latestWindow = { payload, sequence }
916
+ }
917
+ if (payload.kind === 'rollover') {
918
+ rolloverCoveredThrough = Math.max(rolloverCoveredThrough, payload.coversThrough)
919
+ }
920
+ if (payload.kind === 'summarize' || payload.kind === 'rollover') {
921
+ if (payload.kind === 'summarize' && payload.summary === undefined) continue
922
+ replacements = retainCompaction(replacements, { payload, sequence })
923
+ } else clearings = retainCompaction(clearings, { payload, sequence })
924
+ }
925
+
926
+ // A superseding summary retires the overlay, but the latest rollover still owns the window.
927
+ const contextViews = [
928
+ ...replacements,
929
+ ...clearings,
930
+ ...(latestWindow === undefined ? [] : [latestWindow]),
931
+ ]
932
+
933
+ const contextCompactions = new Set(contextViews.map(({ sequence }) => sequence))
934
+
935
+ const historyFrom = CanonicalSequence.make(
936
+ replacements.reduce(
937
+ (from, { payload }) => Math.max(from, payload.coversThrough + 1),
938
+ savedContext?.historyFrom ?? 1,
939
+ ),
940
+ )
941
+
942
+ const contextValidationViews = compactions.filter(
943
+ ({ sequence }) => sequence >= historyFrom || contextCompactions.has(sequence),
944
+ )
945
+
946
+ const contextEvidence = new Set(
947
+ contextValidationViews.flatMap(({ payload }) => {
948
+ const sequence = firstSequenceByRun.get(payload.runId)
949
+
950
+ return sequence === undefined ? [] : [sequence]
951
+ }),
952
+ )
953
+
954
+ // Reread compactions must keep the facts that accepted or rejected their original bounds.
955
+ if (onEvidence !== undefined) {
956
+ for (const { payload, sequence } of contextValidationViews) {
957
+ boundIsValid(payload, sequence, contextEvidence)
958
+ }
959
+ }
960
+
961
+ const retainEvidence = (envelope: A): void => {
962
+ if (onEvidence === undefined) return
963
+ onEvidence(envelope)
964
+ if (envelope.sequence < historyFrom && envelope.record.payload._tag === 'ModelResponseRecorded') {
965
+ // A retained declaration must preserve its already-settled siblings for later coverage checks.
966
+ for (const span of spansByDeclaration.get(envelope.sequence) ?? []) {
967
+ if (span.to < historyFrom) contextEvidence.add(span.to)
968
+ }
969
+ }
970
+ }
971
+
972
+ let summaryEmitted = false
973
+
974
+ const retainedPrefix = replacements.some(
975
+ ({ payload }) =>
976
+ payload.kind === 'rollover' &&
977
+ payload.runId === ownerRunId &&
978
+ ownerPrefixSequence <= payload.coversThrough,
979
+ )
980
+ ? (protectedContext?.content ?? [])
981
+ : []
982
+
983
+ const replacementLength = retainedPrefix.length + replacements.length
984
+
985
+ const emitSummary = () => {
986
+ if (summaryEmitted || replacements.length === 0) return
987
+ summaryEmitted = true
988
+ state.all.push(...retainedPrefix)
989
+ for (const { payload: replacement } of replacements) {
990
+ const message = replacement.kind === 'rollover'
991
+ ? contextWindowMessage(
992
+ contextWindowId(replacement.runId, replacement.turn),
993
+ replacement.handoff,
994
+ )
995
+ : Prompt.makeMessage('user', {
996
+ content: [
997
+ Prompt.makePart('text', {
998
+ text: `${COMPACTION_SUMMARY_PREFIX}${replacement.summary}`,
999
+ }),
1000
+ ],
1001
+ })
1002
+
1003
+ state.all.push(message)
1004
+ if (replacement.kind !== 'rollover' || replacement.runId !== ownerRunId) {
1005
+ state.before.push(message)
1006
+ }
1007
+ // Marker coverage comes from its compaction, even when covered facts leave the saved range.
1008
+ onBoundary?.({
1009
+ sequence: replacement.coversThrough,
1010
+ tag: 'CompactionCreated',
1011
+ promptLength: state.all.length,
1012
+ })
1013
+ }
1014
+ }
1015
+
1016
+ // The original context is canonical model input, not a reconstruction of later Thread
1017
+ // traffic. Its bounded mapping lets compaction cover exactly the same historical prefix.
1018
+ if (savedContext !== undefined) {
1019
+ emitSummary()
1020
+ for (const [index, message] of historical.entries()) {
1021
+ const boundary = savedContext.boundaries.find((entry) => entry.promptLength > index)
1022
+
1023
+ if (boundary === undefined && replacements.length > 0) {
1024
+ return yield* journalError('Saved context lacks its canonical compaction boundary')
1025
+ }
1026
+ if (
1027
+ boundary !== undefined &&
1028
+ replacements.some(({ payload }) => boundary.sequence <= payload.coversThrough)
1029
+ ) {
1030
+ continue
1031
+ }
1032
+
1033
+ const visible = message.role === 'tool' &&
1034
+ boundary !== undefined &&
1035
+ clearings.some(({ payload }) => boundary.sequence <= payload.coversThrough)
1036
+ ? Prompt.makeMessage('tool', {
1037
+ content: message.content.map((part) =>
1038
+ part.type === 'tool-result'
1039
+ ? Prompt.makePart('tool-result', { ...part, result: CLEARED_TOOL_RESULT })
1040
+ : part
1041
+ ),
1042
+ })
1043
+ : message
1044
+
1045
+ state.all.push(visible)
1046
+ state.before.push(visible)
1047
+ }
1048
+ for (const boundary of savedContext.boundaries) {
1049
+ const removed = savedContext.boundaries.reduce(
1050
+ (length, candidate) =>
1051
+ candidate.sequence <= boundary.sequence &&
1052
+ replacements.some(({ payload }) => candidate.sequence <= payload.coversThrough)
1053
+ ? Math.max(length, candidate.promptLength)
1054
+ : length,
1055
+ 0,
1056
+ )
1057
+
1058
+ onBoundary?.({
1059
+ ...boundary,
1060
+ promptLength: replacementLength + Math.max(0, boundary.promptLength - removed),
1061
+ })
1062
+ }
1063
+ }
1064
+
1065
+ const modelUsage: Array<ModelCallUsage> = []
1066
+ let unobservedModelCalls = 0
1067
+
1068
+ const usage = initialUsage(modelUsage)
1069
+
1070
+ let toolSelection: Selection | undefined
1071
+ let usageTurn = 0
1072
+
1073
+ const incompleteToolTurns = new Set<string>()
1074
+ const incompleteToolCalls = new Set<string>()
1075
+ const incompleteContextRuns = new Set<RunId>()
1076
+
1077
+ for (const response of incompleteResponseSequences) {
1078
+ if (
1079
+ contextViews.some(
1080
+ (view) =>
1081
+ view.payload.kind !== 'summarize' &&
1082
+ response.sequence <= view.payload.coversThrough &&
1083
+ response.lastSettlementSequence >= view.sequence,
1084
+ )
1085
+ ) {
1086
+ incompleteContextRuns.add(response.runId)
1087
+ }
1088
+ }
1089
+ let pendingContextToolCallId: string | undefined
1090
+ let ownerTerminated = false
1091
+
1092
+ const policyUsage = initialPolicyUsage()
1093
+
1094
+ const accountResponse = Effect.fnUntraced(function*(
1095
+ envelope: JournalRecordEnvelope,
1096
+ payload: Extract<
1097
+ JournalRecordEnvelope['record']['payload'],
1098
+ { readonly _tag: 'ModelResponseRecorded' }
1099
+ >,
1100
+ messages: Prompt.Prompt,
1101
+ ) {
1102
+ const record = envelope.record
1103
+
1104
+ const declared = declaredApplicationToolCallIds(messages)
1105
+ const actualResultIds: Array<RecordId> = []
1106
+ let incomplete = false
1107
+
1108
+ for (const id of declared) {
1109
+ const toolCallId = yield* Effect.try({
1110
+ try: () => decodeToolCallId(id),
1111
+ catch: (cause) => journalError('Failed to decode a declared Tool Call ID', cause),
1112
+ })
1113
+
1114
+ const resultId = toolCallSettledRecordId(payload.runId, payload.turn, toolCallId)
1115
+
1116
+ if (settledToolCallRecordIds.has(resultId)) actualResultIds.push(resultId)
1117
+ else incomplete = true
1118
+ }
1119
+ if (incomplete) {
1120
+ incompleteToolTurns.add(envelope.record.recordId)
1121
+ incompleteContextRuns.add(payload.runId)
1122
+ for (const recordId of actualResultIds) incompleteToolCalls.add(recordId)
1123
+ }
1124
+ if (payload.runId !== ownerRunId) return
1125
+ if (!('toolOperations' in payload)) {
1126
+ return yield* journalError('Owning Run execution requires full canonical evidence')
1127
+ }
1128
+ if (payload.turn === 1 && payload.runScopedPrefixLength !== undefined) {
1129
+ protectedContext = Prompt.fromMessages(
1130
+ messages.content.slice(0, payload.runScopedPrefixLength),
1131
+ )
1132
+ }
1133
+
1134
+ const responseUsage = yield* projectedResponseUsage(payload)
1135
+
1136
+ unobservedModelCalls = yield* addProjectedUsage(
1137
+ 'unobservedModelCalls',
1138
+ unobservedModelCalls,
1139
+ payload.unobservedModelCalls ?? 0,
1140
+ )
1141
+
1142
+ usage.modelCalls = yield* addProjectedUsage(
1143
+ 'modelCalls',
1144
+ usage.modelCalls,
1145
+ responseUsage.modelCalls,
1146
+ )
1147
+ usage.inputTokens = yield* addProjectedUsage(
1148
+ 'inputTokens',
1149
+ usage.inputTokens,
1150
+ responseUsage.inputTokens,
1151
+ )
1152
+ usage.outputTokens = yield* addProjectedUsage(
1153
+ 'outputTokens',
1154
+ usage.outputTokens,
1155
+ responseUsage.outputTokens,
1156
+ )
1157
+ usage.costMicrousd = yield* addProjectedUsage(
1158
+ 'costMicrousd',
1159
+ usage.costMicrousd,
1160
+ responseUsage.costMicrousd,
1161
+ )
1162
+ usage.modelUsage.push(...responseUsage.modelUsage)
1163
+ if (payload.turn > usageTurn) {
1164
+ usageTurn = payload.turn
1165
+ usage.lastInputTokens = responseUsage.inputTokens
1166
+ usage.lastOutputTokens = responseUsage.outputTokens
1167
+ }
1168
+
1169
+ policyUsage.committedTurns = Math.max(policyUsage.committedTurns, payload.turn)
1170
+
1171
+ const calls = messages.content.flatMap((message) =>
1172
+ message.role === 'assistant'
1173
+ ? message.content.filter((part) => part.type === 'tool-call')
1174
+ : []
1175
+ )
1176
+
1177
+ const candidate = calls.length === 1 ? calls[0] : undefined
1178
+
1179
+ const candidateResult = candidate === undefined
1180
+ ? undefined
1181
+ : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${candidate.id}`)
1182
+
1183
+ pendingContextToolCallId = candidate !== undefined &&
1184
+ !candidate.providerExecuted &&
1185
+ candidateResult?.isFailure === false &&
1186
+ candidateResult.budgetRejected !== true &&
1187
+ envelope.sequence > rolloverCoveredThrough
1188
+ ? candidate.id
1189
+ : undefined
1190
+
1191
+ policyUsage.toolCalls += calls.length
1192
+ if (payload.toolExposure !== undefined) toolSelection = payload.toolExposure.selection
1193
+ if (incompleteToolTurns.has(record.recordId)) return
1194
+ for (const call of calls) {
1195
+ const result = call.providerExecuted
1196
+ ? messages.content
1197
+ .flatMap((message) => (message.role === 'assistant' ? message.content : []))
1198
+ .find(
1199
+ (part) => part.type === 'tool-result' && part.providerExecuted && part.id === call.id,
1200
+ )
1201
+ : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${call.id}`)
1202
+
1203
+ if (result === undefined || ('budgetRejected' in result && result.budgetRejected === true)) {
1204
+ continue
1205
+ }
1206
+ if (!('isFailure' in result)) continue
1207
+ if (!result.isFailure && 'toolSelection' in result && result.toolSelection !== undefined) {
1208
+ toolSelection = result.toolSelection
1209
+ }
1210
+ policyUsage.consecutiveToolFailures = result.isFailure
1211
+ ? policyUsage.consecutiveToolFailures + 1
1212
+ : 0
1213
+ }
1214
+ })
1215
+
1216
+ // Slots refer to the retained Prompt itself, not an additional history payload index.
1217
+ // Only still-unseen results retain a slot; late results fill the original declaration in place.
1218
+ const historicalResults = new Map<
1219
+ string,
1220
+ {
1221
+ readonly allIndex: number
1222
+ readonly beforeIndex: number
1223
+ readonly parts: Array<Prompt.ToolResultPart>
1224
+ readonly partIndex: number
1225
+ }
1226
+ >()
1227
+
1228
+ // Only exact calls needed by late results survive retirement, never their old messages.
1229
+ const retiredLateCalls = new Map<string, Prompt.ToolCallPart>()
1230
+
1231
+ let pendingToolOrder = new Map<string, number>()
1232
+
1233
+ const flushTools = Effect.fnUntraced(function*(
1234
+ current: FoldState,
1235
+ ): Effect.fn.Return<FoldState, RunJournalError> {
1236
+ if (current.pendingTools.length === 0) return current
1237
+
1238
+ // Suspension can persist an ordinary sibling before a delegated call joins. Model context
1239
+ // still uses declaration order, matching the live interpreter's completed results batch.
1240
+ const ordered = current.pendingTools.toSorted(
1241
+ (left, right) =>
1242
+ (pendingToolOrder.get(left.record.toolCallId) ?? Number.MAX_SAFE_INTEGER) -
1243
+ (pendingToolOrder.get(right.record.toolCallId) ?? Number.MAX_SAFE_INTEGER),
1244
+ )
1245
+
1246
+ const toolMessage = yield* toolMessageFromSettled(ordered)
1247
+
1248
+ current.all.push(toolMessage)
1249
+ if (!current.pendingToolsForRun) current.before.push(toolMessage)
1250
+
1251
+ return {
1252
+ ...current,
1253
+ pendingTools: [],
1254
+ pendingToolsForRun: false,
1255
+ }
1256
+ })
1257
+
1258
+ yield* Stream.runForEach(recordsForRun, (envelope) =>
1259
+ Effect.gen(function*() {
1260
+ const payload = envelope.record.payload
1261
+
1262
+ if (contextEvidence.has(envelope.sequence)) retainEvidence(envelope)
1263
+ if (
1264
+ (payload._tag === 'RunCompleted' ||
1265
+ payload._tag === 'RunFailed' ||
1266
+ payload._tag === 'SubmissionSettled') &&
1267
+ payload.runId !== undefined &&
1268
+ incompleteContextRuns.has(payload.runId)
1269
+ ) {
1270
+ retainEvidence(envelope)
1271
+ }
1272
+
1273
+ if (
1274
+ ((payload._tag === 'RunCompleted' || payload._tag === 'RunFailed') &&
1275
+ payload.runId === ownerRunId) ||
1276
+ (payload._tag === 'SubmissionSettled' &&
1277
+ runIdForSubmission(payload.submissionId) === ownerRunId)
1278
+ ) {
1279
+ ownerTerminated = true
1280
+ }
1281
+
1282
+ if (payload._tag === 'RunPolicyUsageReserved' && payload.runId === ownerRunId) {
1283
+ if (
1284
+ payload.programmaticToolCalls < policyUsage.programmaticToolCalls ||
1285
+ (policyUsage.finalizationUsed && !payload.finalizationUsed)
1286
+ ) {
1287
+ return yield* journalError('Run policy reservations must be monotonic')
1288
+ }
1289
+ policyUsage.programmaticToolCalls = payload.programmaticToolCalls
1290
+ policyUsage.finalizationUsed = payload.finalizationUsed
1291
+ }
1292
+ if (payload._tag === 'ModelCallAborted' && payload.runId === ownerRunId) {
1293
+ if (payload.restart !== policyUsage.modelRestarts + 1) {
1294
+ return yield* journalError('Model restart reservations must advance once')
1295
+ }
1296
+ policyUsage.modelRestarts = payload.restart
1297
+
1298
+ const summary = yield* summarizeModelUsage(payload.modelUsage).pipe(
1299
+ Effect.mapError((cause) => journalError('Aborted model usage exceeds accounting bounds', cause)),
1300
+ )
1301
+
1302
+ usage.modelCalls = yield* addProjectedUsage(
1303
+ 'modelCalls',
1304
+ usage.modelCalls,
1305
+ summary.modelCalls,
1306
+ )
1307
+ usage.inputTokens = yield* addProjectedUsage(
1308
+ 'inputTokens',
1309
+ usage.inputTokens,
1310
+ summary.inputTokens.total,
1311
+ )
1312
+ usage.outputTokens = yield* addProjectedUsage(
1313
+ 'outputTokens',
1314
+ usage.outputTokens,
1315
+ summary.outputTokens.total,
1316
+ )
1317
+ usage.costMicrousd = yield* addProjectedUsage(
1318
+ 'costMicrousd',
1319
+ usage.costMicrousd,
1320
+ summary.costMicrousd,
1321
+ )
1322
+ usage.modelUsage.push(...payload.modelUsage)
1323
+ unobservedModelCalls = yield* addProjectedUsage(
1324
+ 'unobservedModelCalls',
1325
+ unobservedModelCalls,
1326
+ payload.unobservedModelCalls,
1327
+ )
1328
+ }
1329
+ if (PROMPT_TRANSPARENT_TAGS.has(payload._tag)) return
1330
+ // The compaction record governs the fold (pre-scan) and contributes no
1331
+ // message of its own; records at or below the summarize bound render as
1332
+ // the one summary message emitted at the covered/kept transition.
1333
+ if (payload._tag === 'CompactionCreated') {
1334
+ if (contextCompactions.has(envelope.sequence)) retainEvidence(envelope)
1335
+
1336
+ return
1337
+ }
1338
+ if (replacements.some(({ payload }) => isCovered(envelope, payload))) {
1339
+ if (payload._tag === 'ModelResponseRecorded' && payload.runId !== ownerRunId) {
1340
+ const late = (spansByDeclaration.get(envelope.sequence) ?? []).filter((span) =>
1341
+ replacements.some(
1342
+ (view) => isCovered(envelope, view.payload) && span.to > view.sequence,
1343
+ )
1344
+ )
1345
+
1346
+ if (late.length > 0) {
1347
+ // Even a rollover-hidden late result needs its exact declaration to stay hidden.
1348
+ retainEvidence(envelope)
1349
+ if (latestWindow !== undefined && isCovered(envelope, latestWindow.payload)) return
1350
+ const messages = yield* decodePromptMessages(payload.messages)
1351
+
1352
+ for (const message of messages.content) {
1353
+ if (message.role !== 'assistant') continue
1354
+ for (const call of message.content) {
1355
+ if (call.type !== 'tool-call' || call.providerExecuted) continue
1356
+
1357
+ const callId = yield* decodeToolCallIdEffect(call.id).pipe(
1358
+ Effect.mapError((cause) => journalError('Invalid retired Tool Call ID', cause)),
1359
+ )
1360
+
1361
+ const id = toolCallSettledRecordId(payload.runId, payload.turn, callId)
1362
+
1363
+ if (late.some((span) => span.recordId === id)) retiredLateCalls.set(id, call)
1364
+ }
1365
+ }
1366
+ }
1367
+ }
1368
+ // Retiring Prompt payloads does not retire the owning Run's policy or usage accounting.
1369
+ if (payload._tag === 'ModelResponseRecorded' && payload.runId === ownerRunId) {
1370
+ const messages = yield* decodePromptMessages(payload.messages)
1371
+
1372
+ yield* accountResponse(envelope, payload, messages)
1373
+ state = { ...state, committedTurns: Math.max(state.committedTurns, payload.turn) }
1374
+ }
1375
+
1376
+ return
1377
+ }
1378
+ emitSummary()
1379
+ if (payload._tag === 'ToolCallSettled') {
1380
+ const declaration = declarationByResultSequence.get(envelope.sequence)
1381
+
1382
+ const declarationFact = {
1383
+ sequence: declaration ?? Infinity,
1384
+ record: { payload: { _tag: 'ModelResponseRecorded', runId: payload.runId } },
1385
+ }
1386
+
1387
+ const declarationCovered = (compaction: CompactionCreated) =>
1388
+ declarationFact.sequence <= compaction.coversThrough &&
1389
+ isInRunView(declarationFact.sequence, declarationFact.record.payload, compaction.runId)
1390
+
1391
+ if (latestWindow !== undefined && declarationCovered(latestWindow.payload)) return
1392
+ retainEvidence(envelope)
1393
+ if (payload.runId !== ownerRunId) {
1394
+ const slot = historicalResults.get(envelope.record.recordId)
1395
+
1396
+ if (slot === undefined) {
1397
+ const call = retiredLateCalls.get(envelope.record.recordId)
1398
+
1399
+ if (
1400
+ call === undefined ||
1401
+ call.id !== payload.toolCallId ||
1402
+ call.name !== payload.toolName
1403
+ ) {
1404
+ return yield* journalError('Historical Tool result has no matching declaration')
1405
+ }
1406
+
1407
+ const pair = [
1408
+ Prompt.makeMessage('assistant', { content: [call] }),
1409
+ Prompt.makeMessage('tool', {
1410
+ content: [
1411
+ Prompt.makePart('tool-result', {
1412
+ id: call.id,
1413
+ name: call.name,
1414
+ result: clearings.some(({ payload }) => declarationCovered(payload))
1415
+ ? CLEARED_TOOL_RESULT
1416
+ : payload.result,
1417
+ isFailure: payload.isFailure,
1418
+ providerExecuted: false,
1419
+ }),
1420
+ ],
1421
+ }),
1422
+ ]
1423
+
1424
+ state.all.push(...pair)
1425
+ state.before.push(...pair)
1426
+ retiredLateCalls.delete(envelope.record.recordId)
1427
+ onBoundary?.({
1428
+ sequence: envelope.sequence,
1429
+ tag: payload._tag,
1430
+ promptLength: state.all.length,
1431
+ })
1432
+
1433
+ return
1434
+ }
1435
+ const declared = slot.parts[slot.partIndex]
1436
+
1437
+ if (declared?.id !== payload.toolCallId || declared.name !== payload.toolName) {
1438
+ return yield* journalError('Historical Tool result differs from its declaration')
1439
+ }
1440
+ slot.parts[slot.partIndex] = Prompt.makePart('tool-result', {
1441
+ id: payload.toolCallId,
1442
+ name: payload.toolName,
1443
+ result: clearings.some(
1444
+ ({ payload }) => isCovered(envelope, payload) || declarationCovered(payload),
1445
+ )
1446
+ ? CLEARED_TOOL_RESULT
1447
+ : payload.result,
1448
+ isFailure: payload.isFailure,
1449
+ providerExecuted: false,
1450
+ })
1451
+ const message = Prompt.makeMessage('tool', { content: [...slot.parts] })
1452
+
1453
+ state.all[slot.allIndex] = message
1454
+ state.before[slot.beforeIndex] = message
1455
+ historicalResults.delete(envelope.record.recordId)
1456
+ onBoundary?.({
1457
+ sequence: envelope.sequence,
1458
+ tag: payload._tag,
1459
+ promptLength: state.all.length,
1460
+ ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),
1461
+ ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)
1462
+ ? { terminalPriorRun: true }
1463
+ : {}),
1464
+ })
1465
+
1466
+ return
1467
+ }
1468
+ if (
1469
+ state.pendingTools.length > 0 &&
1470
+ state.pendingToolsForRun !== (payload.runId === ownerRunId)
1471
+ ) {
1472
+ state = yield* flushTools(state)
1473
+ }
1474
+ state.pendingTools.push({
1475
+ record: payload,
1476
+ cleared: clearings.some(({ payload }) => isCovered(envelope, payload)),
1477
+ })
1478
+ state = {
1479
+ ...state,
1480
+ pendingToolsForRun: payload.runId === ownerRunId,
1481
+ }
1482
+ onBoundary?.({
1483
+ sequence: envelope.sequence,
1484
+ tag: payload._tag,
1485
+ promptLength: state.all.length + 1,
1486
+ ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)
1487
+ ? { terminalPriorRun: true }
1488
+ : {}),
1489
+ ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),
1490
+ })
1491
+
1492
+ return
1493
+ }
1494
+ state = yield* flushTools(state)
1495
+ if (payload._tag === 'ModelCompleted' && payload.history !== undefined) {
1496
+ retainEvidence(envelope)
1497
+ const messages = yield* decodePromptMessages(payload.history)
1498
+
1499
+ state.all.length = 0
1500
+ state.before.length = 0
1501
+ historicalResults.clear()
1502
+
1503
+ for (const message of messages.content) {
1504
+ state.all.push(message)
1505
+ if (payload.runId !== ownerRunId) state.before.push(message)
1506
+ }
1507
+ // Persistent, non-durable model history needs the same original compaction mapping
1508
+ // as durable responses; cold selected-Run recovery cannot infer it from later history.
1509
+ onBoundary?.({
1510
+ sequence: envelope.sequence,
1511
+ tag: payload._tag,
1512
+ promptLength: state.all.length,
1513
+ })
1514
+
1515
+ return
1516
+ }
1517
+ if (payload._tag !== 'ModelResponseRecorded') return
1518
+ retainEvidence(envelope)
1519
+ const messages = yield* decodePromptMessages(payload.messages)
1520
+ const forRun = payload.runId === ownerRunId
1521
+
1522
+ pendingToolOrder = new Map(
1523
+ declaredApplicationToolCallIds(messages).map((id, index) => [id, index]),
1524
+ )
1525
+
1526
+ yield* accountResponse(envelope, payload, messages)
1527
+
1528
+ const visibleMessages = forRun
1529
+ ? messages.content
1530
+ : messages.content.filter((message) => message.role !== 'system')
1531
+
1532
+ for (const message of visibleMessages) {
1533
+ state.all.push(message)
1534
+ if (!forRun) state.before.push(message)
1535
+ }
1536
+ if (!forRun) {
1537
+ const calls = messages.content.flatMap((message) =>
1538
+ message.role === 'assistant'
1539
+ ? message.content.filter(
1540
+ (part): part is Prompt.ToolCallPart => part.type === 'tool-call' && !part.providerExecuted,
1541
+ )
1542
+ : []
1543
+ )
1544
+
1545
+ if (calls.length > 0) {
1546
+ const parts = calls.map((call) =>
1547
+ Prompt.makePart('tool-result', {
1548
+ id: call.id,
1549
+ name: call.name,
1550
+ result: {
1551
+ _tag: 'ToolOutcomeUnknown',
1552
+ message:
1553
+ 'This earlier operation has no recorded outcome. It may have executed. Do not assume success or retry it; its original operation remains unresolved.',
1554
+ },
1555
+ isFailure: true,
1556
+ providerExecuted: false,
1557
+ })
1558
+ )
1559
+
1560
+ const allIndex = state.all.length
1561
+ const beforeIndex = state.before.length
1562
+ const message = Prompt.makeMessage('tool', { content: parts })
1563
+
1564
+ state.all.push(message)
1565
+ state.before.push(message)
1566
+ for (const [partIndex, call] of calls.entries()) {
1567
+ const callId = yield* decodeToolCallIdEffect(call.id).pipe(
1568
+ Effect.mapError((cause) => journalError('Invalid historical Tool Call ID', cause)),
1569
+ )
1570
+
1571
+ const resultId = toolCallSettledRecordId(payload.runId, payload.turn, callId)
1572
+
1573
+ // A fixed replay can fill only a result present in its captured metadata. Missing
1574
+ // calls retain their visible Unknown part without an expanded identity directory.
1575
+ if (!settledToolCallRecordIds.has(resultId)) continue
1576
+ historicalResults.set(resultId, {
1577
+ allIndex,
1578
+ beforeIndex,
1579
+ parts,
1580
+ partIndex,
1581
+ })
1582
+ }
1583
+ }
1584
+ }
1585
+ state = {
1586
+ ...state,
1587
+ committedTurns: forRun
1588
+ ? Math.max(state.committedTurns, payload.turn)
1589
+ : state.committedTurns,
1590
+ }
1591
+ onBoundary?.({
1592
+ sequence: envelope.sequence,
1593
+ tag: payload._tag,
1594
+ promptLength: state.all.length,
1595
+ ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)
1596
+ ? { terminalPriorRun: true }
1597
+ : {}),
1598
+ ...(incompleteToolTurns.has(envelope.record.recordId) ? { incomplete: true } : {}),
1599
+ })
1600
+ }))
1601
+ emitSummary()
1602
+ state = yield* flushTools(state)
1603
+
1604
+ const validatedPolicyUsage = yield* Schema.decodeEffect(RunPolicyUsage)(policyUsage).pipe(
1605
+ Effect.mapError((cause) => journalError('Run policy accounting exceeds its Schema bounds', cause)),
1606
+ )
1607
+
1608
+ return {
1609
+ ...(toolSelection === undefined ? {} : { toolSelection }),
1610
+ policyUsage: validatedPolicyUsage,
1611
+ prompt: Prompt.fromMessages(state.all),
1612
+ historyBefore: Prompt.fromMessages(state.before),
1613
+ historyFrom,
1614
+ committedTurns: state.committedTurns,
1615
+ usage: unobservedModelCalls === 0 ? usage : { ...usage, unobservedModelCalls },
1616
+ ...(latestWindowId === undefined ? {} : { contextWindowId: latestWindowId }),
1617
+ ...(protectedContext === undefined ? {} : { protectedContext }),
1618
+ ...(ownerTerminated || pendingContextToolCallId === undefined
1619
+ ? {}
1620
+ : { pendingContextToolCallId }),
1621
+ }
1622
+ })
1623
+
1624
+ /** Pure projection of one Run's durable recovery state from canonical records. */
1625
+ export const projectRunJournal = (
1626
+ records: ReadonlyArray<CanonicalRecordEnvelope>,
1627
+ runId: RunId,
1628
+ ): Effect.Effect<RunJournalProjection, RunJournalError> => projectRunJournalStream(Stream.fromIterable(records), runId)
1629
+
1630
+ /**
1631
+ * Pure valid-prompt projection from canonical records: `UserInputRecorded` +
1632
+ * `ModelResponseRecorded` + complete `ToolCallSettled` batches → the deterministic model-visible
1633
+ * Prompt (plan §Coordinator flow step 3).
1634
+ */
1635
+ export const promptFromCanonicalRecords = (
1636
+ records: ReadonlyArray<CanonicalRecordEnvelope>,
1637
+ ): Effect.Effect<Prompt.Prompt, RunJournalError> =>
1638
+ projectRunJournalStream(Stream.fromIterable(records), undefined).pipe(
1639
+ Effect.map((projection) => projection.prompt),
1640
+ )
1641
+
1642
+ /** Everything one committed Turn contributes to its canonical batch. */
1643
+ export interface TurnCommitInput {
1644
+ readonly toolResultMaxBytes?: number | undefined
1645
+ readonly toolSelectionMaxBytes?: number | undefined
1646
+ readonly toolOperations?: ModelResponseRecorded['toolOperations'] | undefined
1647
+ readonly toolParameterRejections?: ReadonlyArray<ToolParameterRejection> | undefined
1648
+ readonly toolExposure?: Snapshot | undefined
1649
+ readonly runId: RunId
1650
+ /** Canonical (Run-relative, Attempt-independent) Turn number; must be positive. */
1651
+ readonly turn: number
1652
+ readonly turnId: TurnId
1653
+ /**
1654
+ * Exact response and leading input/instruction messages. Application Tool outcomes
1655
+ * are supplied separately; the journal does not reconstruct them from Prompt history.
1656
+ */
1657
+ readonly responseMessages: ReadonlyArray<Prompt.Message>
1658
+ readonly toolResults: ReadonlyArray<RunTurnToolResult>
1659
+ readonly producerId: ProducerId
1660
+ readonly deploymentId: DeploymentId
1661
+ readonly createdAt: DateTime.Utc
1662
+ /** Leading instruction/wake messages that stay canonical but are hidden from later Runs. */
1663
+ readonly runScopedPrefixLength?: number | undefined
1664
+ /** Terminal output committed atomically with this Turn's final canonical batch. */
1665
+ readonly runCompletion?:
1666
+ | {
1667
+ readonly output: PersistedJson
1668
+ readonly runDisposition?: PersistedJson | undefined
1669
+ readonly finishReason?: 'budget-exhausted' | undefined
1670
+ readonly exhausted?: ExhaustedLimit | undefined
1671
+ }
1672
+ | undefined
1673
+ /** Known missing-accounting invocations staged before this canonical response. */
1674
+ readonly unobservedModelCalls?: number | undefined
1675
+ /** Per-call provider usage staged by the engine's `noteTurnUsage` (RUN-023). */
1676
+ readonly usage?:
1677
+ | {
1678
+ readonly inputTokens: number
1679
+ readonly outputTokens: number
1680
+ readonly costMicrousd?: number | undefined
1681
+ readonly modelUsage?: ReadonlyArray<ModelCallUsage> | undefined
1682
+ }
1683
+ | undefined
1684
+ }
1685
+
1686
+ const decodeModelResponse = Schema.decodeUnknownEffect(ModelResponseRecorded)
1687
+ const decodeToolSettled = Schema.decodeUnknownEffect(ToolCallSettled)
1688
+ const encodePrompt = Schema.encodeEffect(Prompt.Prompt)
1689
+
1690
+ const requireCanonicalTurn = (turn: number): Effect.Effect<void, RunJournalError> =>
1691
+ !Number.isInteger(turn) || turn <= 0
1692
+ ? Effect.fail(journalError(`Canonical turn number must be a positive integer: ${turn}`))
1693
+ : Effect.void
1694
+
1695
+ const modelResponseRecord = Effect.fnUntraced(function*(
1696
+ input: TurnCommitInput,
1697
+ ): Effect.fn.Return<RecordEnvelope, RunJournalError> {
1698
+ const promptMessages = input.responseMessages
1699
+
1700
+ if (promptMessages.some((message) => message.role === 'tool')) {
1701
+ return yield* journalError('Application Tool outcomes must be supplied as terminal facts')
1702
+ }
1703
+ const runScopedPrefixLength = input.runScopedPrefixLength
1704
+
1705
+ if (
1706
+ runScopedPrefixLength !== undefined &&
1707
+ (input.turn !== 1 ||
1708
+ !Number.isSafeInteger(runScopedPrefixLength) ||
1709
+ runScopedPrefixLength <= 0 ||
1710
+ runScopedPrefixLength > promptMessages.length ||
1711
+ promptMessages
1712
+ .slice(0, runScopedPrefixLength)
1713
+ .some((message) => message.role !== 'system' && message.role !== 'user'))
1714
+ ) {
1715
+ return yield* journalError(
1716
+ 'Run-scoped Prompt provenance must identify a non-empty system/user prefix of Turn 1 before its assistant response',
1717
+ )
1718
+ }
1719
+
1720
+ const encodedMessages = yield* encodePrompt(Prompt.fromMessages([...promptMessages])).pipe(
1721
+ Effect.mapErrorEager((cause) => journalError('Turn Prompt messages failed to encode', cause)),
1722
+ )
1723
+
1724
+ // Validate messages and usage together. The progress writer captures the complete record
1725
+ // before acquiring its mutation gate; a separate JSON copy here adds no ownership proof.
1726
+ const modelUsage = input.usage?.modelUsage
1727
+
1728
+ const payload = yield* decodeModelResponse({
1729
+ _tag: 'ModelResponseRecorded',
1730
+ toolResultMaxBytes: input.toolResultMaxBytes ?? MAX_PERSISTED_JSON_BYTES,
1731
+ toolSelectionMaxBytes: input.toolSelectionMaxBytes ?? 0,
1732
+ toolOperations: input.toolOperations ?? [],
1733
+ ...(input.toolParameterRejections === undefined || input.toolParameterRejections.length === 0
1734
+ ? {}
1735
+ : { toolParameterRejections: input.toolParameterRejections }),
1736
+ ...(input.toolExposure === undefined ? {} : { toolExposure: input.toolExposure }),
1737
+ runId: input.runId,
1738
+ turnId: input.turnId,
1739
+ turn: input.turn,
1740
+ messages: encodedMessages,
1741
+ ...(runScopedPrefixLength === undefined ? {} : { runScopedPrefixLength }),
1742
+ ...(modelUsage === undefined ? {} : { modelUsage }),
1743
+ ...(input.unobservedModelCalls === undefined || input.unobservedModelCalls === 0
1744
+ ? {}
1745
+ : {
1746
+ unobservedModelCalls: input.unobservedModelCalls,
1747
+ }),
1748
+ ...(input.usage === undefined
1749
+ ? {}
1750
+ : {
1751
+ inputTokens: input.usage.inputTokens,
1752
+ outputTokens: input.usage.outputTokens,
1753
+ // Written only when non-zero: absent re-seeds as zero, so the
1754
+ // no-estimator case stays byte-identical to pre-cost histories.
1755
+ ...(input.usage.costMicrousd === undefined || input.usage.costMicrousd === 0
1756
+ ? {}
1757
+ : {
1758
+ costMicrousd: input.usage.costMicrousd,
1759
+ }),
1760
+ }),
1761
+ }).pipe(
1762
+ Effect.mapErrorEager((cause) => journalError('Invalid model response operation evidence', cause)),
1763
+ )
1764
+
1765
+ if (payload.modelUsage !== undefined) {
1766
+ if (payload.modelUsage.length === 0) {
1767
+ return yield* journalError('Turn model usage must contain at least one completed call')
1768
+ }
1769
+
1770
+ const summary = yield* continuationUsage(payload.modelUsage).pipe(
1771
+ Effect.mapErrorEager((cause) => journalError('Turn model usage exceeds accounting bounds', cause)),
1772
+ )
1773
+
1774
+ if (
1775
+ payload.inputTokens !== summary.inputTokens ||
1776
+ payload.outputTokens !== summary.outputTokens ||
1777
+ (payload.costMicrousd ?? 0) !== summary.costMicrousd
1778
+ ) {
1779
+ return yield* journalError('Turn detailed and aggregate model usage disagree')
1780
+ }
1781
+ }
1782
+
1783
+ return RecordEnvelope.make({
1784
+ recordId: modelResponseRecordId(input.runId, input.turn),
1785
+ family: 'thread',
1786
+ schemaVersion: 1,
1787
+ createdAt: input.createdAt,
1788
+ deploymentId: input.deploymentId,
1789
+ payload,
1790
+ })
1791
+ })
1792
+
1793
+ const toolSettledRecords = Effect.fnUntraced(function*(
1794
+ input: TurnCommitInput,
1795
+ ): Effect.fn.Return<Array<RecordEnvelope>, RunJournalError> {
1796
+ const toolRecords: Array<RecordEnvelope> = []
1797
+
1798
+ for (const part of input.toolResults) {
1799
+ const payload = yield* decodeToolSettled({
1800
+ _tag: 'ToolCallSettled',
1801
+ ...(part.toolSelection === undefined ? {} : { toolSelection: part.toolSelection }),
1802
+ runId: input.runId,
1803
+ toolCallId: part.toolCallId,
1804
+ toolName: part.toolName,
1805
+ result: part.result,
1806
+ isFailure: part.isFailure,
1807
+ ...(part.budgetRejected === true ? { budgetRejected: true } : {}),
1808
+ }).pipe(
1809
+ Effect.mapError((cause) => journalError(`Invalid Tool result ${part.toolCallId}`, cause)),
1810
+ )
1811
+
1812
+ toolRecords.push(
1813
+ RecordEnvelope.make({
1814
+ recordId: toolCallSettledRecordId(input.runId, input.turn, payload.toolCallId),
1815
+ family: 'thread',
1816
+ schemaVersion: 1,
1817
+ createdAt: input.createdAt,
1818
+ deploymentId: input.deploymentId,
1819
+ payload,
1820
+ }),
1821
+ )
1822
+ }
1823
+
1824
+ return toolRecords
1825
+ })
1826
+
1827
+ const runCompletionRecord = (input: TurnCommitInput) => {
1828
+ if (input.runCompletion === undefined) return undefined
1829
+ const completion = { runId: input.runId, ...input.runCompletion }
1830
+
1831
+ return RecordEnvelope.make({
1832
+ recordId: runCompletedRecordId(input.runId),
1833
+ family: 'thread',
1834
+ schemaVersion: 1,
1835
+ createdAt: input.createdAt,
1836
+ deploymentId: input.deploymentId,
1837
+ payload: RunCompleted.make({
1838
+ ...completion,
1839
+ }),
1840
+ })
1841
+ }
1842
+
1843
+ /**
1844
+ * Build a canonical batch from interpreter-validated Turn facts: one
1845
+ * `ModelResponseRecorded` record plus one `ToolCallSettled` record per terminal Tool result, all
1846
+ * under the WP0-style deterministic identities, committed as ONE atomic batch. The same input
1847
+ * always yields byte-identical content, so an in-Attempt append retry is an honest batch replay.
1848
+ *
1849
+ * No-tool Turns and eligible readonly Turns use this shape; a terminal `RunCompleted` marker
1850
+ * joins the response in the same atomic batch. Other application Turns split into
1851
+ * `turnResponseBatch` + `turnResultsBatch` before execution.
1852
+ */
1853
+ export const turnCanonicalBatch = Effect.fnUntraced(function*(
1854
+ input: TurnCommitInput,
1855
+ ): Effect.fn.Return<CanonicalBatch, RunJournalError> {
1856
+ yield* requireCanonicalTurn(input.turn)
1857
+ const modelResponse = yield* modelResponseRecord(input)
1858
+ const toolRecords = yield* toolSettledRecords(input)
1859
+ const completionRecord = runCompletionRecord(input)
1860
+
1861
+ return CanonicalBatch.make({
1862
+ batchId: turnBatchId(input.runId, input.turn),
1863
+ producerId: input.producerId,
1864
+ records: completionRecord === undefined
1865
+ ? [modelResponse, ...toolRecords]
1866
+ : [modelResponse, ...toolRecords, completionRecord],
1867
+ })
1868
+ })
1869
+
1870
+ /**
1871
+ * Commit the normalized response and original operation contracts before application Tools
1872
+ * execute, or promote a deferred readonly response before a persisted call-scoped capability.
1873
+ * An unsettled application declaration is conservative uncertainty after ownership
1874
+ * loss; approvals and the dispatch fence remain separate execution requirements. Provider
1875
+ * results stay in assistant content. Application outcomes belong to the results commit.
1876
+ */
1877
+ export const turnResponseBatch = Effect.fnUntraced(function*(
1878
+ input: TurnCommitInput,
1879
+ ): Effect.fn.Return<CanonicalBatch, RunJournalError> {
1880
+ yield* requireCanonicalTurn(input.turn)
1881
+ const modelResponse = yield* modelResponseRecord(input)
1882
+
1883
+ return CanonicalBatch.make({
1884
+ batchId: turnResponseBatchId(input.runId, input.turn),
1885
+ producerId: input.producerId,
1886
+ records: [modelResponse],
1887
+ })
1888
+ })
1889
+
1890
+ /**
1891
+ * Commit 5 of a tool-declaring Turn (plan §2.1): the Turn's `ToolCallSettled` records in
1892
+ * declaration order under batch identity `turn-results:{runId}:{turn}` — the batch becomes
1893
+ * model-visible atomically. A completion after already committed Tool results gets its own
1894
+ * terminal batch; it never rewrites or repeats the earlier Tool outcomes.
1895
+ */
1896
+ export const turnResultsBatch = Effect.fnUntraced(function*(
1897
+ input: TurnCommitInput,
1898
+ ): Effect.fn.Return<CanonicalBatch, RunJournalError> {
1899
+ yield* requireCanonicalTurn(input.turn)
1900
+ const toolRecords = yield* toolSettledRecords(input)
1901
+ const first = toolRecords[0]
1902
+ const completionRecord = runCompletionRecord(input)
1903
+
1904
+ if (first === undefined) {
1905
+ if (completionRecord === undefined) {
1906
+ return yield* journalError(`Turn ${input.turn} has no terminal Tool results to commit`)
1907
+ }
1908
+
1909
+ return CanonicalBatch.make({
1910
+ batchId: makeBatchId(runCompletedRecordId(input.runId)),
1911
+ producerId: input.producerId,
1912
+ records: [completionRecord],
1913
+ })
1914
+ }
1915
+ if (input.runCompletion !== undefined && toolRecords.length !== 1) {
1916
+ return yield* journalError('A terminal Tool completion requires exactly one settled result')
1917
+ }
1918
+
1919
+ return CanonicalBatch.make({
1920
+ batchId: turnResultsBatchId(input.runId, input.turn),
1921
+ producerId: input.producerId,
1922
+ records: completionRecord === undefined
1923
+ ? [first, ...toolRecords.slice(1)]
1924
+ : [first, ...toolRecords.slice(1), completionRecord],
1925
+ })
1926
+ })