effect-agent 0.1.0-beta.10 → 0.1.0-beta.101

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 (544) hide show
  1. package/dist/Agent-CG_VMrtA.mjs +83 -0
  2. package/dist/Agent-CG_VMrtA.mjs.map +1 -0
  3. package/dist/Agent-CM6JubNX.d.mts +226 -0
  4. package/dist/AgentError-CggcAQ7V.d.mts +101 -0
  5. package/dist/AgentPolicy-BqDoSXO6.d.mts +96 -0
  6. package/dist/AgentRuntime-B1SXMVN7.d.mts +346 -0
  7. package/dist/AgentRuntime-BWOnNc0d.mjs +4690 -0
  8. package/dist/AgentRuntime-BWOnNc0d.mjs.map +1 -0
  9. package/dist/AgentUpdates-DMJ-_xow.d.mts +53 -0
  10. package/dist/ContextCompactor-WwSIG_Z2.d.mts +161 -0
  11. package/dist/ContextWindow-DRQ5Mbm2.d.mts +58 -0
  12. package/dist/DurableAgentRuntime-HOZ3AeSi.mjs +6672 -0
  13. package/dist/DurableAgentRuntime-HOZ3AeSi.mjs.map +1 -0
  14. package/dist/DurableFailpoint-mx3-nsxU.d.mts +41 -0
  15. package/dist/DurableStep-Cry_iol4.d.mts +103 -0
  16. package/dist/EventSource-K7XUzurY.d.mts +51 -0
  17. package/dist/Identifiers-CN2s30fF.d.mts +40 -0
  18. package/dist/InMemory.d.mts +24 -0
  19. package/dist/InMemory.mjs +24 -0
  20. package/dist/InMemory.mjs.map +1 -0
  21. package/dist/MemoryNamespace-BbRW5p71.d.mts +36 -0
  22. package/dist/MemoryReference-B8Q3UJoJ.d.mts +79 -0
  23. package/dist/Messaging-QMYhp297.d.mts +490 -0
  24. package/dist/MessagingHost-CWi_PP3g.mjs +137 -0
  25. package/dist/MessagingHost-CWi_PP3g.mjs.map +1 -0
  26. package/dist/MessagingHost-gAxs5gme.d.mts +246 -0
  27. package/dist/OperationAuthorizer-TzcQtpX5.d.mts +61 -0
  28. package/dist/Output-CjocJzsl.d.mts +25 -0
  29. package/dist/PageCapture-Df8Xwskw.d.mts +583 -0
  30. package/dist/PageScreenshot-BpgZKAxl.d.mts +48 -0
  31. package/dist/PreparedInputAdmission-KLk5rGFI.d.mts +38 -0
  32. package/dist/Receipt-BAHyigAF.d.mts +33 -0
  33. package/dist/Records-Bidb7ByL.d.mts +3803 -0
  34. package/dist/Records-D8167fHn.mjs +844 -0
  35. package/dist/Records-D8167fHn.mjs.map +1 -0
  36. package/dist/RunEvent-DIrzkjLr.d.mts +460 -0
  37. package/dist/RunEventSink-D5aVhISG.d.mts +108 -0
  38. package/dist/RunJournal-srpbEBEy.mjs +909 -0
  39. package/dist/RunJournal-srpbEBEy.mjs.map +1 -0
  40. package/dist/RunOptions-Bruk54SE.d.mts +930 -0
  41. package/dist/RunPolicyUsage-ClZxyR46.d.mts +21 -0
  42. package/dist/Sandbox-CEsDWBLq.d.mts +173 -0
  43. package/dist/Schedule-Cy9up8Uf.d.mts +842 -0
  44. package/dist/Scheduling-CHCsSCGo.mjs +691 -0
  45. package/dist/Scheduling-CHCsSCGo.mjs.map +1 -0
  46. package/dist/Subagent-C2s8PFrd.mjs +1469 -0
  47. package/dist/Subagent-C2s8PFrd.mjs.map +1 -0
  48. package/dist/Subagent-DP0CzO16.d.mts +826 -0
  49. package/dist/SubagentContract-DdT7Cqe6.d.mts +116 -0
  50. package/dist/SubagentHost-CYcxkpRc.d.mts +140 -0
  51. package/dist/Subscription-CHyoQelH.d.mts +921 -0
  52. package/dist/SubscriptionInput-DqrHW-Ja.d.mts +41 -0
  53. package/dist/Thread-DOBQ0QUY.d.mts +96 -0
  54. package/dist/ThreadHistory-tS1KwxHR.d.mts +60 -0
  55. package/dist/ToolBroker-DWs4tZra.d.mts +133 -0
  56. package/dist/ToolExposure-9uF_Yo0T.mjs +10 -0
  57. package/dist/ToolExposure-9uF_Yo0T.mjs.map +1 -0
  58. package/dist/ToolExposure-C93U1sPu.mjs +30 -0
  59. package/dist/ToolExposure-C93U1sPu.mjs.map +1 -0
  60. package/dist/ToolExposure-UCN12eCd.d.mts +39 -0
  61. package/dist/ToolExposure-r2eOWk4F.d.mts +46 -0
  62. package/dist/ToolExposure.d.mts +8 -0
  63. package/dist/ToolExposure.mjs +21 -0
  64. package/dist/ToolExposure.mjs.map +1 -0
  65. package/dist/ToolReconciler-BmVRAHKs.d.mts +80 -0
  66. package/dist/ToolResult-BKdqWRff.d.mts +78 -0
  67. package/dist/Usage-Dx0aknfk.d.mts +121 -0
  68. package/dist/WakeScheduler-EjUF-GhC.d.mts +56 -0
  69. package/dist/Worker--j87JI__.d.mts +228 -0
  70. package/dist/agent-registration-ByeHejH3.mjs +199 -0
  71. package/dist/agent-registration-ByeHejH3.mjs.map +1 -0
  72. package/dist/capabilities/Approval.d.mts +114 -0
  73. package/dist/capabilities/Approval.mjs +226 -0
  74. package/dist/capabilities/Approval.mjs.map +1 -0
  75. package/dist/capabilities/Budget.d.mts +112 -0
  76. package/dist/capabilities/Budget.mjs +346 -0
  77. package/dist/capabilities/Budget.mjs.map +1 -0
  78. package/dist/capabilities/CodeMode.d.mts +157 -0
  79. package/dist/capabilities/CodeMode.mjs +522 -0
  80. package/dist/capabilities/CodeMode.mjs.map +1 -0
  81. package/dist/capabilities/Commands.d.mts +55 -0
  82. package/dist/capabilities/Commands.mjs +57 -0
  83. package/dist/capabilities/Commands.mjs.map +1 -0
  84. package/dist/capabilities/ContextTools.d.mts +321 -0
  85. package/dist/capabilities/ContextTools.mjs +126 -0
  86. package/dist/capabilities/ContextTools.mjs.map +1 -0
  87. package/dist/capabilities/Mcp.d.mts +108 -0
  88. package/dist/capabilities/Mcp.mjs +260 -0
  89. package/dist/capabilities/Mcp.mjs.map +1 -0
  90. package/dist/capabilities/McpClient.d.mts +115 -0
  91. package/dist/capabilities/McpClient.mjs +506 -0
  92. package/dist/capabilities/McpClient.mjs.map +1 -0
  93. package/dist/capabilities/MemoryNotes.d.mts +424 -0
  94. package/dist/capabilities/MemoryNotes.mjs +128 -0
  95. package/dist/capabilities/MemoryNotes.mjs.map +1 -0
  96. package/dist/capabilities/Messaging.d.mts +3 -0
  97. package/dist/capabilities/Messaging.mjs +151 -0
  98. package/dist/capabilities/Messaging.mjs.map +1 -0
  99. package/dist/capabilities/ModelContext.d.mts +89 -0
  100. package/dist/capabilities/ModelContext.mjs +168 -0
  101. package/dist/capabilities/ModelContext.mjs.map +1 -0
  102. package/dist/capabilities/Redaction.d.mts +37 -0
  103. package/dist/capabilities/Redaction.mjs +104 -0
  104. package/dist/capabilities/Redaction.mjs.map +1 -0
  105. package/dist/capabilities/Remembering.d.mts +434 -0
  106. package/dist/capabilities/Remembering.mjs +290 -0
  107. package/dist/capabilities/Remembering.mjs.map +1 -0
  108. package/dist/capabilities/RunHooks.d.mts +82 -0
  109. package/dist/capabilities/RunHooks.mjs +144 -0
  110. package/dist/capabilities/RunHooks.mjs.map +1 -0
  111. package/dist/capabilities/SemanticMemory.d.mts +431 -0
  112. package/dist/capabilities/SemanticMemory.mjs +315 -0
  113. package/dist/capabilities/SemanticMemory.mjs.map +1 -0
  114. package/dist/capabilities/Subagent.d.mts +4 -0
  115. package/dist/capabilities/Subagent.mjs +5 -0
  116. package/dist/capabilities/SubagentReservations.d.mts +186 -0
  117. package/dist/capabilities/SubagentReservations.mjs +479 -0
  118. package/dist/capabilities/SubagentReservations.mjs.map +1 -0
  119. package/dist/capabilities/ToolDiscovery.d.mts +124 -0
  120. package/dist/capabilities/ToolDiscovery.mjs +230 -0
  121. package/dist/capabilities/ToolDiscovery.mjs.map +1 -0
  122. package/dist/capabilities/WebCapture.d.mts +163 -0
  123. package/dist/capabilities/WebCapture.mjs +335 -0
  124. package/dist/capabilities/WebCapture.mjs.map +1 -0
  125. package/dist/capabilities/WebSearch.d.mts +71 -0
  126. package/dist/capabilities/WebSearch.mjs +115 -0
  127. package/dist/capabilities/WebSearch.mjs.map +1 -0
  128. package/dist/compaction-C2OTceKw.mjs +505 -0
  129. package/dist/compaction-C2OTceKw.mjs.map +1 -0
  130. package/dist/core/Agent.d.mts +2 -0
  131. package/dist/core/Agent.mjs +2 -0
  132. package/dist/core/AgentError.d.mts +2 -0
  133. package/dist/core/AgentError.mjs +117 -0
  134. package/dist/core/AgentError.mjs.map +1 -0
  135. package/dist/core/AgentPolicy.d.mts +2 -0
  136. package/dist/core/AgentPolicy.mjs +94 -0
  137. package/dist/core/AgentPolicy.mjs.map +1 -0
  138. package/dist/core/AgentUpdates.d.mts +2 -0
  139. package/dist/core/AgentUpdates.mjs +63 -0
  140. package/dist/core/AgentUpdates.mjs.map +1 -0
  141. package/dist/core/IdGenerator.d.mts +26 -0
  142. package/dist/core/IdGenerator.mjs +27 -0
  143. package/dist/core/IdGenerator.mjs.map +1 -0
  144. package/dist/core/Identifiers.d.mts +2 -0
  145. package/dist/core/Identifiers.mjs +43 -0
  146. package/dist/core/Identifiers.mjs.map +1 -0
  147. package/dist/core/Memory.d.mts +57 -0
  148. package/dist/core/Memory.mjs +203 -0
  149. package/dist/core/Memory.mjs.map +1 -0
  150. package/dist/core/MemoryNamespace.d.mts +2 -0
  151. package/dist/core/MemoryNamespace.mjs +116 -0
  152. package/dist/core/MemoryNamespace.mjs.map +1 -0
  153. package/dist/core/MemoryReference.d.mts +2 -0
  154. package/dist/core/MemoryReference.mjs +109 -0
  155. package/dist/core/MemoryReference.mjs.map +1 -0
  156. package/dist/core/MemoryRevalidation.d.mts +65 -0
  157. package/dist/core/MemoryRevalidation.mjs +126 -0
  158. package/dist/core/MemoryRevalidation.mjs.map +1 -0
  159. package/dist/core/MemoryStore.d.mts +186 -0
  160. package/dist/core/MemoryStore.mjs +243 -0
  161. package/dist/core/MemoryStore.mjs.map +1 -0
  162. package/dist/core/Receipt.d.mts +2 -0
  163. package/dist/core/Receipt.mjs +36 -0
  164. package/dist/core/Receipt.mjs.map +1 -0
  165. package/dist/core/RememberingStore.d.mts +1562 -0
  166. package/dist/core/RememberingStore.mjs +190 -0
  167. package/dist/core/RememberingStore.mjs.map +1 -0
  168. package/dist/core/RunEvent.d.mts +2 -0
  169. package/dist/core/RunEvent.mjs +337 -0
  170. package/dist/core/RunEvent.mjs.map +1 -0
  171. package/dist/core/RunPolicyUsage.d.mts +2 -0
  172. package/dist/core/RunPolicyUsage.mjs +21 -0
  173. package/dist/core/RunPolicyUsage.mjs.map +1 -0
  174. package/dist/core/SemanticMemoryIndex.d.mts +826 -0
  175. package/dist/core/SemanticMemoryIndex.mjs +185 -0
  176. package/dist/core/SemanticMemoryIndex.mjs.map +1 -0
  177. package/dist/core/SemanticMemoryRevalidation.d.mts +45 -0
  178. package/dist/core/SemanticMemoryRevalidation.mjs +191 -0
  179. package/dist/core/SemanticMemoryRevalidation.mjs.map +1 -0
  180. package/dist/core/SubagentContract.d.mts +2 -0
  181. package/dist/core/SubagentContract.mjs +148 -0
  182. package/dist/core/SubagentContract.mjs.map +1 -0
  183. package/dist/core/Thread.d.mts +2 -0
  184. package/dist/core/Thread.mjs +250 -0
  185. package/dist/core/Thread.mjs.map +1 -0
  186. package/dist/core/ToolResult.d.mts +2 -0
  187. package/dist/core/ToolResult.mjs +156 -0
  188. package/dist/core/ToolResult.mjs.map +1 -0
  189. package/dist/core/Usage.d.mts +2 -0
  190. package/dist/core/Usage.mjs +319 -0
  191. package/dist/core/Usage.mjs.map +1 -0
  192. package/dist/core/Worker.d.mts +3 -0
  193. package/dist/core/Worker.mjs +147 -0
  194. package/dist/core/Worker.mjs.map +1 -0
  195. package/dist/durable/ActivityStore.d.mts +116 -0
  196. package/dist/durable/ActivityStore.mjs +131 -0
  197. package/dist/durable/ActivityStore.mjs.map +1 -0
  198. package/dist/durable/Admin.d.mts +2 -0
  199. package/dist/durable/Admin.mjs +330 -0
  200. package/dist/durable/Admin.mjs.map +1 -0
  201. package/dist/durable/AgentRegistration.d.mts +2 -0
  202. package/dist/durable/AgentRegistration.mjs +14 -0
  203. package/dist/durable/AgentRegistration.mjs.map +1 -0
  204. package/dist/durable/Certification.d.mts +110 -0
  205. package/dist/durable/Certification.mjs +159 -0
  206. package/dist/durable/Certification.mjs.map +1 -0
  207. package/dist/durable/CommittedActivity.d.mts +62 -0
  208. package/dist/durable/CommittedActivity.mjs +159 -0
  209. package/dist/durable/CommittedActivity.mjs.map +1 -0
  210. package/dist/durable/Digest.d.mts +2 -0
  211. package/dist/durable/Digest.mjs +50 -0
  212. package/dist/durable/Digest.mjs.map +1 -0
  213. package/dist/durable/DurableAgentRuntime.d.mts +3 -0
  214. package/dist/durable/DurableAgentRuntime.mjs +3 -0
  215. package/dist/durable/DurableFailpoint.d.mts +2 -0
  216. package/dist/durable/DurableFailpoint.mjs +98 -0
  217. package/dist/durable/DurableFailpoint.mjs.map +1 -0
  218. package/dist/durable/DurableFailpointTestControl.d.mts +14 -0
  219. package/dist/durable/DurableFailpointTestControl.mjs +19 -0
  220. package/dist/durable/DurableFailpointTestControl.mjs.map +1 -0
  221. package/dist/durable/EventSource.d.mts +2 -0
  222. package/dist/durable/EventSource.mjs +65 -0
  223. package/dist/durable/EventSource.mjs.map +1 -0
  224. package/dist/durable/GitHubWorkflowSource.d.mts +185 -0
  225. package/dist/durable/GitHubWorkflowSource.mjs +209 -0
  226. package/dist/durable/GitHubWorkflowSource.mjs.map +1 -0
  227. package/dist/durable/MessageDelivery.d.mts +832 -0
  228. package/dist/durable/MessageDelivery.mjs +529 -0
  229. package/dist/durable/MessageDelivery.mjs.map +1 -0
  230. package/dist/durable/MessageDeliveryStoreConformance.d.mts +357 -0
  231. package/dist/durable/MessageDeliveryStoreConformance.mjs +270 -0
  232. package/dist/durable/MessageDeliveryStoreConformance.mjs.map +1 -0
  233. package/dist/durable/OperationAuthorizer.d.mts +2 -0
  234. package/dist/durable/OperationAuthorizer.mjs +70 -0
  235. package/dist/durable/OperationAuthorizer.mjs.map +1 -0
  236. package/dist/durable/PersistentHistory.d.mts +16 -0
  237. package/dist/durable/PersistentHistory.mjs +125 -0
  238. package/dist/durable/PersistentHistory.mjs.map +1 -0
  239. package/dist/durable/PreparedInputAdmission.d.mts +2 -0
  240. package/dist/durable/PreparedInputAdmission.mjs +34 -0
  241. package/dist/durable/PreparedInputAdmission.mjs.map +1 -0
  242. package/dist/durable/Records.d.mts +2 -0
  243. package/dist/durable/Records.mjs +2 -0
  244. package/dist/durable/Recovery.d.mts +2 -0
  245. package/dist/durable/Recovery.mjs +739 -0
  246. package/dist/durable/Recovery.mjs.map +1 -0
  247. package/dist/durable/RunJournal.d.mts +2 -0
  248. package/dist/durable/RunJournal.mjs +2 -0
  249. package/dist/durable/Schedule.d.mts +2 -0
  250. package/dist/durable/Schedule.mjs +382 -0
  251. package/dist/durable/Schedule.mjs.map +1 -0
  252. package/dist/durable/ScheduleStoreConformance.d.mts +17 -0
  253. package/dist/durable/ScheduleStoreConformance.mjs +420 -0
  254. package/dist/durable/ScheduleStoreConformance.mjs.map +1 -0
  255. package/dist/durable/ScheduleTransition.d.mts +24 -0
  256. package/dist/durable/ScheduleTransition.mjs +180 -0
  257. package/dist/durable/ScheduleTransition.mjs.map +1 -0
  258. package/dist/durable/Scheduling.d.mts +54 -0
  259. package/dist/durable/Scheduling.mjs +2 -0
  260. package/dist/durable/SqlMemoryStore.d.mts +29 -0
  261. package/dist/durable/SqlMemoryStore.mjs +436 -0
  262. package/dist/durable/SqlMemoryStore.mjs.map +1 -0
  263. package/dist/durable/SqlMessageDeliveryStore.d.mts +42 -0
  264. package/dist/durable/SqlMessageDeliveryStore.mjs +171 -0
  265. package/dist/durable/SqlMessageDeliveryStore.mjs.map +1 -0
  266. package/dist/durable/SqlStorageV2Upgrade.d.mts +21 -0
  267. package/dist/durable/SqlStorageV2Upgrade.mjs +459 -0
  268. package/dist/durable/SqlStorageV2Upgrade.mjs.map +1 -0
  269. package/dist/durable/SqlSubscriptionStore.d.mts +62 -0
  270. package/dist/durable/SqlSubscriptionStore.mjs +751 -0
  271. package/dist/durable/SqlSubscriptionStore.mjs.map +1 -0
  272. package/dist/durable/SqlThreadNativeReads.d.mts +49 -0
  273. package/dist/durable/SqlThreadNativeReads.mjs +153 -0
  274. package/dist/durable/SqlThreadNativeReads.mjs.map +1 -0
  275. package/dist/durable/SubmissionLedger.d.mts +3 -0
  276. package/dist/durable/SubmissionLedger.mjs +915 -0
  277. package/dist/durable/SubmissionLedger.mjs.map +1 -0
  278. package/dist/durable/SubmissionLedgerConformance.d.mts +29 -0
  279. package/dist/durable/SubmissionLedgerConformance.mjs +1993 -0
  280. package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -0
  281. package/dist/durable/SubmissionStatus.d.mts +2 -0
  282. package/dist/durable/SubmissionStatus.mjs +18 -0
  283. package/dist/durable/SubmissionStatus.mjs.map +1 -0
  284. package/dist/durable/Subscription.d.mts +2 -0
  285. package/dist/durable/Subscription.mjs +360 -0
  286. package/dist/durable/Subscription.mjs.map +1 -0
  287. package/dist/durable/SubscriptionInput.d.mts +2 -0
  288. package/dist/durable/SubscriptionInput.mjs +52 -0
  289. package/dist/durable/SubscriptionInput.mjs.map +1 -0
  290. package/dist/durable/SubscriptionStoreConformance.d.mts +16 -0
  291. package/dist/durable/SubscriptionStoreConformance.mjs +625 -0
  292. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -0
  293. package/dist/durable/SubscriptionTools.d.mts +273 -0
  294. package/dist/durable/SubscriptionTools.mjs +190 -0
  295. package/dist/durable/SubscriptionTools.mjs.map +1 -0
  296. package/dist/durable/SubscriptionTransition.d.mts +21 -0
  297. package/dist/durable/SubscriptionTransition.mjs +148 -0
  298. package/dist/durable/SubscriptionTransition.mjs.map +1 -0
  299. package/dist/durable/Subscriptions.d.mts +73 -0
  300. package/dist/durable/Subscriptions.mjs +627 -0
  301. package/dist/durable/Subscriptions.mjs.map +1 -0
  302. package/dist/durable/ThreadContextHistory.d.mts +32 -0
  303. package/dist/durable/ThreadContextHistory.mjs +152 -0
  304. package/dist/durable/ThreadContextHistory.mjs.map +1 -0
  305. package/dist/durable/ThreadContextHistoryProjection.d.mts +60 -0
  306. package/dist/durable/ThreadContextHistoryProjection.mjs +149 -0
  307. package/dist/durable/ThreadContextHistoryProjection.mjs.map +1 -0
  308. package/dist/durable/ThreadInvariants.d.mts +76 -0
  309. package/dist/durable/ThreadInvariants.mjs +246 -0
  310. package/dist/durable/ThreadInvariants.mjs.map +1 -0
  311. package/dist/durable/ThreadProjection.d.mts +78 -0
  312. package/dist/durable/ThreadProjection.mjs +158 -0
  313. package/dist/durable/ThreadProjection.mjs.map +1 -0
  314. package/dist/durable/ThreadProjectionMaintenance.d.mts +49 -0
  315. package/dist/durable/ThreadProjectionMaintenance.mjs +33 -0
  316. package/dist/durable/ThreadProjectionMaintenance.mjs.map +1 -0
  317. package/dist/durable/ThreadStore.d.mts +2 -0
  318. package/dist/durable/ThreadStore.mjs +336 -0
  319. package/dist/durable/ThreadStore.mjs.map +1 -0
  320. package/dist/durable/ThreadStoreConformance.d.mts +28 -0
  321. package/dist/durable/ThreadStoreConformance.mjs +503 -0
  322. package/dist/durable/ThreadStoreConformance.mjs.map +1 -0
  323. package/dist/durable/ToolReconciler.d.mts +2 -0
  324. package/dist/durable/ToolReconciler.mjs +85 -0
  325. package/dist/durable/ToolReconciler.mjs.map +1 -0
  326. package/dist/durable/WakeScheduler.d.mts +2 -0
  327. package/dist/durable/WakeScheduler.mjs +85 -0
  328. package/dist/durable/WakeScheduler.mjs.map +1 -0
  329. package/dist/durable/WorkerHost.d.mts +129 -0
  330. package/dist/durable/WorkerHost.mjs +77 -0
  331. package/dist/durable/WorkerHost.mjs.map +1 -0
  332. package/dist/engine/AgentRuntime.d.mts +2 -0
  333. package/dist/engine/AgentRuntime.mjs +2 -0
  334. package/dist/engine/Compaction.d.mts +7 -0
  335. package/dist/engine/Compaction.mjs +16 -0
  336. package/dist/engine/Compaction.mjs.map +1 -0
  337. package/dist/engine/ContextCompactor.d.mts +2 -0
  338. package/dist/engine/ContextCompactor.mjs +119 -0
  339. package/dist/engine/ContextCompactor.mjs.map +1 -0
  340. package/dist/engine/ContextHistory.d.mts +65 -0
  341. package/dist/engine/ContextHistory.mjs +76 -0
  342. package/dist/engine/ContextHistory.mjs.map +1 -0
  343. package/dist/engine/ContextWindow.d.mts +2 -0
  344. package/dist/engine/ContextWindow.mjs +59 -0
  345. package/dist/engine/ContextWindow.mjs.map +1 -0
  346. package/dist/engine/DurableStep.d.mts +2 -0
  347. package/dist/engine/DurableStep.mjs +62 -0
  348. package/dist/engine/DurableStep.mjs.map +1 -0
  349. package/dist/engine/MessagingHost.d.mts +2 -0
  350. package/dist/engine/MessagingHost.mjs +2 -0
  351. package/dist/engine/Output.d.mts +2 -0
  352. package/dist/engine/Output.mjs +8 -0
  353. package/dist/engine/Output.mjs.map +1 -0
  354. package/dist/engine/RunEventSink.d.mts +2 -0
  355. package/dist/engine/RunEventSink.mjs +22 -0
  356. package/dist/engine/RunEventSink.mjs.map +1 -0
  357. package/dist/engine/RunOptions.d.mts +2 -0
  358. package/dist/engine/RunOptions.mjs +122 -0
  359. package/dist/engine/RunOptions.mjs.map +1 -0
  360. package/dist/engine/SubagentHost.d.mts +2 -0
  361. package/dist/engine/SubagentHost.mjs +72 -0
  362. package/dist/engine/SubagentHost.mjs.map +1 -0
  363. package/dist/engine/ThreadHistory.d.mts +2 -0
  364. package/dist/engine/ThreadHistory.mjs +67 -0
  365. package/dist/engine/ThreadHistory.mjs.map +1 -0
  366. package/dist/engine/ToolBroker.d.mts +2 -0
  367. package/dist/engine/ToolBroker.mjs +42 -0
  368. package/dist/engine/ToolBroker.mjs.map +1 -0
  369. package/dist/foreign-diagnostic-DBQ1XHKh.mjs +37 -0
  370. package/dist/foreign-diagnostic-DBQ1XHKh.mjs.map +1 -0
  371. package/dist/index.d.mts +90 -6
  372. package/dist/index.mjs +99 -6
  373. package/dist/output-contract-BC7tjlGw.mjs +84 -0
  374. package/dist/output-contract-BC7tjlGw.mjs.map +1 -0
  375. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  376. package/dist/sandbox/CodeExecutor.d.mts +194 -0
  377. package/dist/sandbox/CodeExecutor.mjs +278 -0
  378. package/dist/sandbox/CodeExecutor.mjs.map +1 -0
  379. package/dist/sandbox/InteractiveBrowser.d.mts +142 -0
  380. package/dist/sandbox/InteractiveBrowser.mjs +165 -0
  381. package/dist/sandbox/InteractiveBrowser.mjs.map +1 -0
  382. package/dist/sandbox/PageCapture.d.mts +2 -0
  383. package/dist/sandbox/PageCapture.mjs +450 -0
  384. package/dist/sandbox/PageCapture.mjs.map +1 -0
  385. package/dist/sandbox/PageCrawl.d.mts +88 -0
  386. package/dist/sandbox/PageCrawl.mjs +124 -0
  387. package/dist/sandbox/PageCrawl.mjs.map +1 -0
  388. package/dist/sandbox/PageScreenshot.d.mts +2 -0
  389. package/dist/sandbox/PageScreenshot.mjs +53 -0
  390. package/dist/sandbox/PageScreenshot.mjs.map +1 -0
  391. package/dist/sandbox/ProtectedBrowser.d.mts +273 -0
  392. package/dist/sandbox/ProtectedBrowser.mjs +287 -0
  393. package/dist/sandbox/ProtectedBrowser.mjs.map +1 -0
  394. package/dist/sandbox/Sandbox.d.mts +2 -0
  395. package/dist/sandbox/Sandbox.mjs +208 -0
  396. package/dist/sandbox/Sandbox.mjs.map +1 -0
  397. package/dist/utf8-BYfhEkcj.mjs +11 -0
  398. package/dist/utf8-BYfhEkcj.mjs.map +1 -0
  399. package/dist/utf8-DchGZRBd.mjs +23 -0
  400. package/dist/utf8-DchGZRBd.mjs.map +1 -0
  401. package/package.json +1 -40
  402. package/src/InMemory.ts +19 -0
  403. package/src/ToolExposure.ts +2 -0
  404. package/src/capabilities/Approval.ts +352 -0
  405. package/src/capabilities/Budget.ts +536 -0
  406. package/src/capabilities/CodeMode.ts +1090 -0
  407. package/src/capabilities/Commands.ts +86 -0
  408. package/src/capabilities/ContextTools.ts +184 -0
  409. package/src/capabilities/Mcp.ts +427 -0
  410. package/src/capabilities/McpClient.ts +967 -0
  411. package/src/capabilities/MemoryNotes.ts +174 -0
  412. package/src/capabilities/Messaging.ts +261 -0
  413. package/src/capabilities/ModelContext.ts +354 -0
  414. package/src/capabilities/Redaction.ts +157 -0
  415. package/src/capabilities/Remembering.ts +550 -0
  416. package/src/capabilities/RunHooks.ts +280 -0
  417. package/src/capabilities/SemanticMemory.ts +447 -0
  418. package/src/capabilities/Subagent.ts +2277 -0
  419. package/src/capabilities/SubagentReservations.ts +850 -0
  420. package/src/capabilities/ToolDiscovery.ts +369 -0
  421. package/src/capabilities/WebCapture.ts +722 -0
  422. package/src/capabilities/WebSearch.ts +190 -0
  423. package/src/capabilities/internal/subagent-background.ts +1106 -0
  424. package/src/capabilities/internal/subagent-contract.ts +142 -0
  425. package/src/capabilities/internal/subagent-policy.ts +235 -0
  426. package/src/capabilities/internal/subagent-reporting.ts +261 -0
  427. package/src/capabilities/internal/utf8.ts +10 -0
  428. package/src/core/Agent.ts +575 -0
  429. package/src/core/AgentError.ts +152 -0
  430. package/src/core/AgentPolicy.ts +153 -0
  431. package/src/core/AgentUpdates.ts +100 -0
  432. package/src/core/IdGenerator.ts +39 -0
  433. package/src/core/Identifiers.ts +48 -0
  434. package/src/core/Memory.ts +290 -0
  435. package/src/core/MemoryNamespace.ts +196 -0
  436. package/src/core/MemoryReference.ts +121 -0
  437. package/src/core/MemoryRevalidation.ts +185 -0
  438. package/src/core/MemoryStore.ts +368 -0
  439. package/src/core/Messaging.ts +90 -0
  440. package/src/core/Receipt.ts +42 -0
  441. package/src/core/RememberingStore.ts +300 -0
  442. package/src/core/RunEvent.ts +366 -0
  443. package/src/core/RunPolicyUsage.ts +17 -0
  444. package/src/core/SemanticMemoryIndex.ts +250 -0
  445. package/src/core/SemanticMemoryRevalidation.ts +254 -0
  446. package/src/core/SubagentContract.ts +196 -0
  447. package/src/core/Thread.ts +371 -0
  448. package/src/core/ToolExposure.ts +74 -0
  449. package/src/core/ToolResult.ts +190 -0
  450. package/src/core/Usage.ts +529 -0
  451. package/src/core/Worker.ts +173 -0
  452. package/src/core/internal/agent-updates.ts +32 -0
  453. package/src/core/internal/strict-schema.ts +14 -0
  454. package/src/core/internal/utf8.ts +23 -0
  455. package/src/durable/ActivityStore.ts +160 -0
  456. package/src/durable/Admin.ts +505 -0
  457. package/src/durable/AgentRegistration.ts +14 -0
  458. package/src/durable/Certification.ts +210 -0
  459. package/src/durable/CommittedActivity.ts +296 -0
  460. package/src/durable/Digest.ts +93 -0
  461. package/src/durable/DurableAgentRuntime.ts +10911 -0
  462. package/src/durable/DurableFailpoint.ts +107 -0
  463. package/src/durable/DurableFailpointTestControl.ts +39 -0
  464. package/src/durable/EventSource.ts +172 -0
  465. package/src/durable/GitHubWorkflowSource.ts +447 -0
  466. package/src/durable/MessageDelivery.ts +759 -0
  467. package/src/durable/MessageDeliveryStoreConformance.ts +410 -0
  468. package/src/durable/OperationAuthorizer.ts +85 -0
  469. package/src/durable/PersistentHistory.ts +260 -0
  470. package/src/durable/PreparedInputAdmission.ts +44 -0
  471. package/src/durable/Records.ts +1061 -0
  472. package/src/durable/Recovery.ts +1018 -0
  473. package/src/durable/RunJournal.ts +1594 -0
  474. package/src/durable/Schedule.ts +504 -0
  475. package/src/durable/ScheduleStoreConformance.ts +638 -0
  476. package/src/durable/ScheduleTransition.ts +265 -0
  477. package/src/durable/Scheduling.ts +1077 -0
  478. package/src/durable/SqlMemoryStore.ts +778 -0
  479. package/src/durable/SqlMessageDeliveryStore.ts +309 -0
  480. package/src/durable/SqlStorageV2Upgrade.ts +500 -0
  481. package/src/durable/SqlSubscriptionStore.ts +1440 -0
  482. package/src/durable/SqlThreadNativeReads.ts +256 -0
  483. package/src/durable/SubmissionLedger.ts +1202 -0
  484. package/src/durable/SubmissionLedgerConformance.ts +4590 -0
  485. package/src/durable/SubmissionStatus.ts +14 -0
  486. package/src/durable/Subscription.ts +544 -0
  487. package/src/durable/SubscriptionInput.ts +144 -0
  488. package/src/durable/SubscriptionStoreConformance.ts +945 -0
  489. package/src/durable/SubscriptionTools.ts +327 -0
  490. package/src/durable/SubscriptionTransition.ts +302 -0
  491. package/src/durable/Subscriptions.ts +1210 -0
  492. package/src/durable/ThreadContextHistory.ts +227 -0
  493. package/src/durable/ThreadContextHistoryProjection.ts +216 -0
  494. package/src/durable/ThreadInvariants.ts +507 -0
  495. package/src/durable/ThreadProjection.ts +269 -0
  496. package/src/durable/ThreadProjectionMaintenance.ts +67 -0
  497. package/src/durable/ThreadStore.ts +552 -0
  498. package/src/durable/ThreadStoreConformance.ts +1156 -0
  499. package/src/durable/ToolReconciler.ts +109 -0
  500. package/src/durable/WakeScheduler.ts +134 -0
  501. package/src/durable/WorkerHost.ts +171 -0
  502. package/src/durable/internal/agent-registration.ts +589 -0
  503. package/src/durable/internal/agent-updates.ts +302 -0
  504. package/src/durable/internal/foreign-diagnostic.ts +47 -0
  505. package/src/durable/internal/journal-checkpoint.ts +104 -0
  506. package/src/durable/internal/journal-metadata.ts +107 -0
  507. package/src/durable/internal/messaging-host.ts +641 -0
  508. package/src/durable/internal/schedule-time.ts +303 -0
  509. package/src/durable/internal/storage-v2-layout.ts +163 -0
  510. package/src/durable/internal/storage-v2.ts +73 -0
  511. package/src/durable/internal/worker-host.ts +2553 -0
  512. package/src/durable/internal/worker-runtime.ts +9 -0
  513. package/src/engine/AgentRuntime.ts +37 -0
  514. package/src/engine/Compaction.ts +11 -0
  515. package/src/engine/ContextCompactor.ts +277 -0
  516. package/src/engine/ContextHistory.ts +73 -0
  517. package/src/engine/ContextWindow.ts +72 -0
  518. package/src/engine/DurableStep.ts +132 -0
  519. package/src/engine/MessagingHost.ts +110 -0
  520. package/src/engine/Output.ts +2 -0
  521. package/src/engine/RunEventSink.ts +132 -0
  522. package/src/engine/RunOptions.ts +1093 -0
  523. package/src/engine/SubagentHost.ts +181 -0
  524. package/src/engine/ThreadHistory.ts +120 -0
  525. package/src/engine/ToolBroker.ts +157 -0
  526. package/src/engine/ToolExposure.ts +48 -0
  527. package/src/engine/internal/agent-runtime.ts +10402 -0
  528. package/src/engine/internal/bounded-value.ts +315 -0
  529. package/src/engine/internal/compaction.ts +678 -0
  530. package/src/engine/internal/error-diagnostic.ts +39 -0
  531. package/src/engine/internal/output-contract.ts +173 -0
  532. package/src/engine/internal/primitive-delta.ts +80 -0
  533. package/src/engine/internal/provider-result-staging.ts +211 -0
  534. package/src/engine/internal/tool-derivative.ts +106 -0
  535. package/src/engine/internal/tool-exposure.ts +224 -0
  536. package/src/engine/internal/tool-telemetry.ts +484 -0
  537. package/src/index.ts +98 -21
  538. package/src/sandbox/CodeExecutor.ts +352 -0
  539. package/src/sandbox/InteractiveBrowser.ts +257 -0
  540. package/src/sandbox/PageCapture.ts +691 -0
  541. package/src/sandbox/PageCrawl.ts +148 -0
  542. package/src/sandbox/PageScreenshot.ts +81 -0
  543. package/src/sandbox/ProtectedBrowser.ts +436 -0
  544. package/src/sandbox/Sandbox.ts +241 -0
@@ -0,0 +1,1594 @@
1
+ import { type Crypto, Effect, Schema, Stream, type DateTime } from "effect";
2
+ import { Prompt } from "effect/unstable/ai";
3
+
4
+ import { ThreadId, RunId, ToolCallId, TurnId, type SubmissionId } from "../core/Identifiers.ts";
5
+ import { type ExhaustedLimit } from "../core/RunEvent.ts";
6
+ import { RunPolicyUsage } from "../core/RunPolicyUsage.ts";
7
+ import { type Selection, type Snapshot } from "../core/ToolExposure.ts";
8
+ import type { ToolParameterRejection } from "../core/ToolResult.ts";
9
+ import { ModelCallUsage, summarizeModelUsage, type RunUsageSummary } from "../core/Usage.ts";
10
+ import type { WorkerRef } from "../core/Worker.ts";
11
+ import {
12
+ CLEARED_TOOL_RESULT,
13
+ COMPACTION_SUMMARY_PREFIX,
14
+ contextWindowId,
15
+ contextWindowMessage,
16
+ } from "../engine/Compaction.ts";
17
+ import { digestJson, type DigestError } from "./Digest.ts";
18
+ import { type JournalCheckpointSeed } from "./internal/journal-checkpoint.ts";
19
+ import { makeJournalMetadata, type JournalMetadata } from "./internal/journal-metadata.ts";
20
+ import {
21
+ BatchId,
22
+ CanonicalBatch,
23
+ CompactionCreated,
24
+ ModelResponseRecorded,
25
+ PersistedJson,
26
+ RecordEnvelope,
27
+ RecordId,
28
+ RunCompleted,
29
+ ToolCallSettled,
30
+ type CanonicalRecordEnvelope,
31
+ type CanonicalSequence,
32
+ type DeploymentId,
33
+ type ProducerId,
34
+ } from "./Records.ts";
35
+ import { IdempotencyKey } from "./SubmissionLedger.ts";
36
+
37
+ /** A canonical record could not be projected into Run/Prompt state. */
38
+ export class RunJournalError extends Schema.TaggedError<RunJournalError>()("RunJournalError", {
39
+ message: Schema.String,
40
+ cause: Schema.optionalKey(Schema.Defect()),
41
+ }) {}
42
+
43
+ const journalError = (message: string, cause?: unknown): RunJournalError =>
44
+ cause === undefined
45
+ ? RunJournalError.make({ message })
46
+ : RunJournalError.make({ message, cause });
47
+
48
+ const decodeRunId = Schema.decodeSync(RunId);
49
+ const decodeTurnId = Schema.decodeSync(TurnId);
50
+ const decodeBatchId = Schema.decodeSync(BatchId);
51
+ const decodeRecordId = Schema.decodeSync(RecordId);
52
+
53
+ /**
54
+ * Deterministic Run identity pinned per Submission (plan §Coordinator flow). Every Attempt of one
55
+ * Submission shares this Run identity, so canonical per-Turn records from different Attempts
56
+ * belong to one logical Run.
57
+ */
58
+ export const runIdForSubmission = (submissionId: SubmissionId): RunId =>
59
+ decodeRunId(`run:${submissionId}`);
60
+
61
+ /** Stable canonical clock identity shared by every Attempt of one Run. */
62
+ export const runStartedRecordId = (runId: RunId): RecordId => decodeRecordId(`run-start:${runId}`);
63
+
64
+ export const runStartedBatchId = (runId: RunId): BatchId => decodeBatchId(`run-start:${runId}`);
65
+
66
+ export const runDurationRecordId = (runId: RunId): RecordId =>
67
+ decodeRecordId(`run-duration:${runId}`);
68
+
69
+ export const runDurationBatchId = (runId: RunId): BatchId => decodeBatchId(`run-duration:${runId}`);
70
+
71
+ /** Deterministic Turn identity: Attempt-independent for one (Run, canonical turn) pair. */
72
+ export const turnIdForRun = (runId: RunId, turn: number): TurnId =>
73
+ decodeTurnId(`turn:${runId}:${turn}`);
74
+
75
+ /** Deterministic batch identity of one committed canonical no-tool Turn (P4 single-batch shape). */
76
+ export const turnBatchId = (runId: RunId, turn: number): BatchId =>
77
+ decodeBatchId(`turn:${runId}:${turn}`);
78
+
79
+ /**
80
+ * Deterministic batch identity of a tool-declaring Turn's RESPONSE commit (plan §2.1 commit 1):
81
+ * the assistant response plus pending steering becomes canonical BEFORE approval preflight and
82
+ * tool preparation, creating the durability §15 "resume tool scheduling" window.
83
+ */
84
+ export const turnResponseBatchId = (runId: RunId, turn: number): BatchId =>
85
+ decodeBatchId(`turn-response:${runId}:${turn}`);
86
+
87
+ /**
88
+ * Deterministic batch identity of a tool-declaring Turn's RESULTS commit (plan §2.1 commit 5):
89
+ * every `ToolCallSettled` record of the Turn, in declaration order, model-visible atomically.
90
+ */
91
+ export const turnResultsBatchId = (runId: RunId, turn: number): BatchId =>
92
+ decodeBatchId(`turn-results:${runId}:${turn}`);
93
+
94
+ /**
95
+ * Deterministic per-call late-settle batch identity used by the resolution path when one
96
+ * recovered/resolved call settles outside its Turn's results batch. Record identity
97
+ * (`tool-settled:{runId}:{turn}:{toolCallId}`) dedupes double-settles across both paths.
98
+ */
99
+ export const toolCallResultBatchId = (
100
+ runId: RunId,
101
+ turn: number,
102
+ toolCallId: ToolCallId,
103
+ ): BatchId => decodeBatchId(`turn-results:${runId}:${turn}:${toolCallId}`);
104
+
105
+ /** Deterministic batch identity of one Turn's `ToolCallPrepared` commit (plan §2.1 commit 3). */
106
+ export const turnPreparedBatchId = (runId: RunId, turn: number): BatchId =>
107
+ decodeBatchId(`turn-prepared:${runId}:${turn}`);
108
+
109
+ /**
110
+ * Deterministic identity of one pre-Turn compaction record (RUN-026,
111
+ * RUN-026). Keyed by Run, Turn, and kind — the engine performs at most one
112
+ * threshold compaction per Turn plus at most one overflow-forced summarize,
113
+ * so a superseding Attempt that re-decides the same compaction replays the
114
+ * batch identity instead of duplicating the record.
115
+ */
116
+ export const compactionRecordId = (
117
+ runId: RunId,
118
+ turn: number,
119
+ kind: "clear-tool-results" | "summarize" | "rollover",
120
+ ): RecordId => decodeRecordId(`compaction:${runId}:${turn}:${kind}`);
121
+
122
+ /** Deterministic batch identity of one compaction append (same string as its record id). */
123
+ export const compactionBatchId = (
124
+ runId: RunId,
125
+ turn: number,
126
+ kind: "clear-tool-results" | "summarize" | "rollover",
127
+ ): BatchId => decodeBatchId(`compaction:${runId}:${turn}:${kind}`);
128
+
129
+ /** Deterministic canonical record identity of one Turn's `ModelResponseRecorded` record. */
130
+ export const modelResponseRecordId = (runId: RunId, turn: number): RecordId =>
131
+ decodeRecordId(`model-response:${runId}:${turn}`);
132
+
133
+ /** Terminal Tool completion marker committed atomically with its settled Tool result. */
134
+ export const runCompletedRecordId = (runId: RunId): RecordId =>
135
+ decodeRecordId(`run-completed:${runId}`);
136
+
137
+ /** Native source reservation locator, including the first admission of a continuing worker. */
138
+ export const workerInputRecordId = (messageId: IdempotencyKey): RecordId =>
139
+ decodeRecordId(`worker-input:${messageId}`);
140
+
141
+ /** Source-owned first reservation; native worker identity is minted from its first message. */
142
+ export const firstWorkerInputRecordId = (worker: WorkerRef): RecordId =>
143
+ decodeRecordId(`worker-input:${worker.threadId}`);
144
+
145
+ export const workerOriginRecordId = (threadId: ThreadId): RecordId =>
146
+ decodeRecordId(`worker-origin:${threadId}`);
147
+
148
+ export const workerReportRecordId = (messageId: IdempotencyKey): RecordId =>
149
+ decodeRecordId(`worker-report:${messageId}`);
150
+
151
+ export const peerMessageRecordId = (messageId: IdempotencyKey): RecordId =>
152
+ decodeRecordId(messageId);
153
+
154
+ /** Same immutable tuple used by native update admission; callers never parse its hash. */
155
+ export const agentUpdateRecordId = Effect.fn("RunJournal.agentUpdateRecordId")(function* (
156
+ threadId: ThreadId,
157
+ runId: RunId,
158
+ updateId: IdempotencyKey,
159
+ ) {
160
+ return decodeRecordId(`agent-update:${yield* digestJson([threadId, runId, updateId])}`);
161
+ });
162
+
163
+ /** Deterministic canonical record identity of one Turn's `ToolCallSettled` record. */
164
+ export const toolCallSettledRecordId = (
165
+ runId: RunId,
166
+ turn: number,
167
+ toolCallId: ToolCallId,
168
+ ): RecordId => decodeRecordId(`tool-settled:${runId}:${turn}:${toolCallId}`);
169
+
170
+ /** Deterministic canonical record identity of one Tool Call's `ToolCallPrepared` record. */
171
+ export const toolCallPreparedRecordId = (
172
+ runId: RunId,
173
+ turn: number,
174
+ toolCallId: ToolCallId,
175
+ ): RecordId => decodeRecordId(`tool-prepared:${runId}:${turn}:${toolCallId}`);
176
+
177
+ /** Deterministic batch identity of one Turn's `ToolCallUnknown` marking append. */
178
+ export const markUnknownBatchId = (submissionId: SubmissionId, turn: number): BatchId =>
179
+ decodeBatchId(`mark-unknown:${submissionId}:${turn}`);
180
+
181
+ /** Deterministic canonical record identity of one Tool Call's `ToolCallUnknown` record. */
182
+ export const toolCallUnknownRecordId = (
183
+ runId: RunId,
184
+ turn: number,
185
+ toolCallId: ToolCallId,
186
+ ): RecordId => decodeRecordId(`tool-unknown:${runId}:${turn}:${toolCallId}`);
187
+
188
+ /** Deterministic batch identity of one Tool Call's resolution append (DUR-017). */
189
+ export const toolCallResolutionBatchId = (
190
+ submissionId: SubmissionId,
191
+ toolCallId: ToolCallId,
192
+ ): BatchId => decodeBatchId(`resolve:${submissionId}:${toolCallId}`);
193
+
194
+ /** Deterministic canonical record identity of one Tool Call's `ToolCallResolved` record. */
195
+ export const toolCallResolvedRecordId = (
196
+ runId: RunId,
197
+ turn: number,
198
+ toolCallId: ToolCallId,
199
+ ): RecordId => decodeRecordId(`tool-resolved:${runId}:${turn}:${toolCallId}`);
200
+
201
+ /**
202
+ * Deterministic identity of one accepted Durable Step result. The one-record batch reuses the
203
+ * SAME string, so batch idempotency plus the epoch fence realize the durability §11
204
+ * racing-writers rule: only the fenced winner's record commits; the loser replays it.
205
+ * A versioned JSON tuple keeps separator characters in each identity component distinct.
206
+ * Replay derives this key from the structured payload, including records with legacy IDs.
207
+ */
208
+ export const toolStepSettledRecordId = (
209
+ runId: RunId,
210
+ toolCallId: ToolCallId,
211
+ stepName: string,
212
+ ): RecordId => decodeRecordId(JSON.stringify(["step@2", runId, toolCallId, stepName]));
213
+
214
+ /** Deterministic batch identity of one Durable Step commit (same string as its record id). */
215
+ export const toolStepSettledBatchId = (
216
+ runId: RunId,
217
+ toolCallId: ToolCallId,
218
+ stepName: string,
219
+ ): BatchId => decodeBatchId(toolStepSettledRecordId(runId, toolCallId, stepName));
220
+
221
+ /** Deterministic batch identity of one Turn's canonical approval-request append (plan §2.6). */
222
+ export const turnApprovalsBatchId = (runId: RunId, turn: number): BatchId =>
223
+ decodeBatchId(`turn-approvals:${runId}:${turn}`);
224
+
225
+ /** Deterministic canonical record identity of one Tool Call's `ToolApprovalRequested` record. */
226
+ export const toolApprovalRequestRecordId = (
227
+ runId: RunId,
228
+ turn: number,
229
+ toolCallId: ToolCallId,
230
+ ): RecordId => decodeRecordId(`approval-request:${runId}:${turn}:${toolCallId}`);
231
+
232
+ /** Deterministic batch identity of one Tool Call's canonical approval-decision append. */
233
+ export const approvalDecisionBatchId = (
234
+ submissionId: SubmissionId,
235
+ toolCallId: ToolCallId,
236
+ ): BatchId => decodeBatchId(`approval-decision:${submissionId}:${toolCallId}`);
237
+
238
+ /** Deterministic canonical record identity of one Tool Call's `ToolApprovalDecided` record. */
239
+ export const toolApprovalDecisionRecordId = (
240
+ runId: RunId,
241
+ turn: number,
242
+ toolCallId: ToolCallId,
243
+ ): RecordId => decodeRecordId(`approval-decision:${runId}:${turn}:${toolCallId}`);
244
+
245
+ /**
246
+ * Deterministic identity of one superseded Attempt's `ModelResponseInterrupted` audit record
247
+ * (durability §9). Keyed by the superseded epoch, so each interrupted ownership period is
248
+ * recorded at most once; the one-record batch reuses the same string.
249
+ */
250
+ export const modelResponseInterruptedRecordId = (runId: RunId, supersededEpoch: number): RecordId =>
251
+ decodeRecordId(`interrupted:${runId}:${supersededEpoch}`);
252
+
253
+ /** Deterministic batch identity of one `ModelResponseInterrupted` append (same string). */
254
+ export const modelResponseInterruptedBatchId = (runId: RunId, supersededEpoch: number): BatchId =>
255
+ decodeBatchId(`interrupted:${runId}:${supersededEpoch}`);
256
+
257
+ const decodeThreadId = Schema.decodeSync(ThreadId);
258
+ const decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);
259
+
260
+ /**
261
+ * Deterministic canonical record identity of one parent Tool Call's `SubagentRequested` record.
262
+ * The one-record batch reuses the same string, so batch
263
+ * idempotency plus the parent epoch fence make the request append exactly-once-canonical.
264
+ */
265
+ export const subagentRequestedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>
266
+ decodeRecordId(`subagent-requested:${runId}:${toolCallId}`);
267
+
268
+ /** Deterministic batch identity of one `SubagentRequested` append (same string). */
269
+ export const subagentRequestedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>
270
+ decodeBatchId(`subagent-requested:${runId}:${toolCallId}`);
271
+
272
+ /**
273
+ * Deterministic canonical record identity of one parent Tool Call's `SubagentStarted` record.
274
+ * Recovery's start-link repair appends the EXACT same record
275
+ * under this identity, so a raced repair replays instead of duplicating (SUB-016/SUB-017).
276
+ */
277
+ export const subagentStartedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>
278
+ decodeRecordId(`subagent-started:${runId}:${toolCallId}`);
279
+
280
+ /** Deterministic batch identity of one `SubagentStarted` append (same string). */
281
+ export const subagentStartedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>
282
+ decodeBatchId(`subagent-started:${runId}:${toolCallId}`);
283
+
284
+ /**
285
+ * Deterministic batch identity of one parent Tool Call's atomic settlement join: the
286
+ * `SubagentJoined` record plus the parent's `ToolCallSettled` record (its existing
287
+ * `tool-settled:{runId}:{turn}:{toolCallId}` identity) commit as ONE canonical batch (SUB-019).
288
+ */
289
+ export const subagentJoinBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>
290
+ decodeBatchId(`subagent-join:${runId}:${toolCallId}`);
291
+
292
+ /** Deterministic canonical record identity of one parent Tool Call's `SubagentJoined` record. */
293
+ export const subagentJoinedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>
294
+ decodeRecordId(`subagent-joined:${runId}:${toolCallId}`);
295
+
296
+ /**
297
+ * Deterministic identity of one child Thread's `SubagentLineageRecorded` record.
298
+ * Its own single-record batch reuses the same string so the generic
299
+ * `thread-created:{cid}` batch identity is never contradicted.
300
+ */
301
+ export const subagentLineageRecordId = (threadId: ThreadId): RecordId =>
302
+ decodeRecordId(`subagent-lineage:${threadId}`);
303
+
304
+ /** Deterministic batch identity of one `SubagentLineageRecorded` append (same string). */
305
+ export const subagentLineageBatchId = (threadId: ThreadId): BatchId =>
306
+ decodeBatchId(`subagent-lineage:${threadId}`);
307
+
308
+ /**
309
+ * Deterministic intended child Thread identity: the
310
+ * parent Submission and Tool Call pair addresses exactly one child Thread, so a replayed
311
+ * establishment converges on the one existing child (SUB-016).
312
+ */
313
+ export const childThreadIdFor = (
314
+ parentSubmissionId: SubmissionId,
315
+ toolCallId: ToolCallId,
316
+ ): ThreadId => decodeThreadId(`subagent:${parentSubmissionId}:${toolCallId}`);
317
+
318
+ /**
319
+ * Deterministic child admission idempotency key: scoped to
320
+ * the parent Run and Tool Call identity, so duplicate admission attempts resolve through the
321
+ * ledger's idempotency contract to one child Receipt (SUB-016, SUB-031). The ledger key is
322
+ * bounded (256); coordinator-minted Run and Tool Call identities stay far below that bound.
323
+ */
324
+ export const childIdempotencyKeyFor = (
325
+ parentRunId: RunId,
326
+ toolCallId: ToolCallId,
327
+ ): IdempotencyKey => decodeIdempotencyKey(`subagent:${parentRunId}:${toolCallId}`);
328
+
329
+ const decodePromptMessages = Effect.fn("RunJournal.decodePromptMessages")(
330
+ (messages: PersistedJson): Effect.Effect<Prompt.Prompt, RunJournalError> =>
331
+ Schema.decodeUnknownEffect(Prompt.Prompt)(messages).pipe(
332
+ Effect.mapError((cause) =>
333
+ journalError("Canonical messages are not Schema-encoded Prompt messages", cause),
334
+ ),
335
+ ),
336
+ );
337
+
338
+ interface PendingSettledTool {
339
+ readonly record: ToolCallSettled;
340
+ /** RUN-026: a `clear-tool-results` compaction covers this record's sequence. */
341
+ readonly cleared: boolean;
342
+ }
343
+
344
+ const toolMessageFromSettled = Effect.fn("RunJournal.toolMessageFromSettled")(
345
+ (settled: ReadonlyArray<PendingSettledTool>): Effect.Effect<Prompt.Message, RunJournalError> =>
346
+ Effect.try({
347
+ try: () =>
348
+ Prompt.makeMessage("tool", {
349
+ content: settled.map(({ record, cleared }) =>
350
+ Prompt.makePart("tool-result", {
351
+ id: record.toolCallId,
352
+ name: record.toolName,
353
+ result: cleared ? CLEARED_TOOL_RESULT : record.result,
354
+ isFailure: record.isFailure,
355
+ providerExecuted: false,
356
+ }),
357
+ ),
358
+ }),
359
+ catch: (cause) => journalError("Unable to rebuild Tool message from ToolCallSettled", cause),
360
+ }),
361
+ );
362
+
363
+ /**
364
+ * Pure canonical projection of one Run's durable execution state.
365
+ *
366
+ * Prompt reconstruction contract (D8):
367
+ *
368
+ * - `ModelResponseRecorded.messages` carries the Schema-encoded Prompt messages the Turn appended
369
+ * to the model-visible prompt — for the Run's FIRST committed Turn that includes the evaluated
370
+ * instruction and user-input messages, for later Turns only the assistant response messages.
371
+ * Tool messages are excluded from `messages`.
372
+ * - `ToolCallSettled` records (committed in the same per-Turn batch, in declaration order)
373
+ * deterministically rebuild the Turn's single Tool message.
374
+ * - `UserInputRecorded` records input, with a Submission identity only for durable admission. Its
375
+ * Prompt-visible form (instructions + user message) becomes canonical inside the owning Run's
376
+ * first `ModelResponseRecorded`. The projection consumes it only for Run correlation.
377
+ * - Immediate retained history uses `ModelCompleted.messages` for the successful Run's exact
378
+ * native Prompt suffix, including any input examples. It has no resumable Turn state.
379
+ */
380
+ /** Cumulative committed usage of the projected Run (RUN-023 resume re-seed). */
381
+ export interface RunJournalUsage {
382
+ readonly modelCalls: number;
383
+ /** Known accounting gaps retained across Attempts without changing numeric usage totals. */
384
+ readonly unobservedModelCalls?: number | undefined;
385
+ readonly inputTokens: number;
386
+ readonly outputTokens: number;
387
+ readonly lastInputTokens: number;
388
+ readonly lastOutputTokens: number;
389
+ /** Cumulative persisted spend of the projected Run's committed calls (RUN-023). */
390
+ readonly costMicrousd: number;
391
+ /** Canonical per-call detail used for settlement aggregation and recovery. */
392
+ readonly modelUsage: ReadonlyArray<ModelCallUsage>;
393
+ /** Detailed usage of retired records, grouped without retaining per-call payloads. */
394
+ readonly summarizedModelUsage?: RunUsageSummary | undefined;
395
+ }
396
+
397
+ export interface RunJournalProjection {
398
+ readonly toolSelection?: Selection | undefined;
399
+ readonly policyUsage: RunPolicyUsage;
400
+ /** Canonical projection for the requested Run; may end at its resumable Tool declaration. */
401
+ readonly prompt: Prompt.Prompt;
402
+ /** Prior-Run history with model-only unknown results closing incomplete application calls. */
403
+ readonly historyBefore: Prompt.Prompt;
404
+ /** Number of canonical Turns already committed for the projected Run. */
405
+ readonly committedTurns: number;
406
+ /** Summed per-call usage of the projected Run's committed responses; zeros for records predating usage capture. */
407
+ readonly usage: RunJournalUsage;
408
+ /** Latest committed context window identity, retained across ownership changes. */
409
+ readonly contextWindowId?: string | undefined;
410
+ /** Canonical evaluated instructions and initial input for this Run, independent of the view. */
411
+ readonly protectedContext?: Prompt.Prompt | undefined;
412
+ /** Last successful singleton Tool awaiting possible context-control interpretation by the engine. */
413
+ readonly pendingContextToolCallId?: string | undefined;
414
+ }
415
+
416
+ interface ProjectedResponseUsage {
417
+ readonly modelCalls: number;
418
+ readonly inputTokens: number;
419
+ readonly outputTokens: number;
420
+ readonly costMicrousd: number;
421
+ readonly modelUsage: ReadonlyArray<ModelCallUsage>;
422
+ }
423
+
424
+ const projectedResponseUsage = (
425
+ response: ModelResponseRecorded,
426
+ ): Effect.Effect<ProjectedResponseUsage, RunJournalError> =>
427
+ Effect.gen(function* () {
428
+ const calls = response.modelUsage;
429
+
430
+ if (calls === undefined) {
431
+ return {
432
+ modelCalls: 1,
433
+ inputTokens: response.inputTokens ?? 0,
434
+ outputTokens: response.outputTokens ?? 0,
435
+ costMicrousd: response.costMicrousd ?? 0,
436
+ modelUsage: [],
437
+ };
438
+ }
439
+ if (calls.length === 0) {
440
+ return yield* journalError("A canonical modelUsage list must not be empty");
441
+ }
442
+
443
+ const summary = yield* summarizeModelUsage(calls).pipe(
444
+ Effect.mapError((cause) =>
445
+ journalError("Canonical model usage exceeds accounting bounds", cause),
446
+ ),
447
+ );
448
+
449
+ if (
450
+ (response.inputTokens !== undefined && response.inputTokens !== summary.inputTokens.total) ||
451
+ (response.outputTokens !== undefined &&
452
+ response.outputTokens !== summary.outputTokens.total) ||
453
+ (response.costMicrousd !== undefined && response.costMicrousd !== summary.costMicrousd)
454
+ ) {
455
+ return yield* journalError("Canonical detailed and aggregate model usage disagree");
456
+ }
457
+
458
+ return {
459
+ modelCalls: summary.modelCalls,
460
+ inputTokens: summary.inputTokens.total,
461
+ outputTokens: summary.outputTokens.total,
462
+ costMicrousd: summary.costMicrousd,
463
+ modelUsage: calls,
464
+ };
465
+ });
466
+
467
+ const addProjectedUsage = (
468
+ field: string,
469
+ left: number,
470
+ right: number,
471
+ ): Effect.Effect<number, RunJournalError> =>
472
+ Schema.decodeEffect(Schema.Natural)(left + right).pipe(
473
+ Effect.mapError((cause) =>
474
+ journalError(`Canonical projected usage exceeds safe-integer bounds at ${field}`, cause),
475
+ ),
476
+ );
477
+
478
+ interface FoldState {
479
+ readonly all: Array<Prompt.Message>;
480
+ readonly before: Array<Prompt.Message>;
481
+ readonly pendingTools: Array<PendingSettledTool>;
482
+ readonly pendingToolsForRun: boolean;
483
+ readonly committedTurns: number;
484
+ }
485
+
486
+ const decodeToolCallId = Schema.decodeSync(ToolCallId);
487
+
488
+ const declaredApplicationToolCallIds = (prompt: Prompt.Prompt): ReadonlyArray<string> => {
489
+ const ids: Array<string> = [];
490
+
491
+ for (const message of prompt.content) {
492
+ if (message.role !== "assistant") continue;
493
+ for (const part of message.content) {
494
+ if (part.type === "tool-call" && !part.providerExecuted) ids.push(part.id);
495
+ }
496
+ }
497
+
498
+ return ids;
499
+ };
500
+
501
+ /**
502
+ * Phase 5 audit tags that are prompt-transparent: they carry durability evidence (preparation,
503
+ * unknown marking, resolution, Step results, approvals, interruption) but contribute nothing to
504
+ * the model-visible Prompt, and — unlike the P4 tags — they do NOT split a contiguous
505
+ * `ToolCallSettled` group into separate Tool messages, so a late-settled call's audit records
506
+ * cannot change the replayed prompt shape.
507
+ *
508
+ * The four S2 Subagent lifecycle tags are prompt-transparent for the same reason (spec §5/§11):
509
+ * the parent prompt never carries child transcript or establishment evidence — the joined child
510
+ * result reaches the model exclusively through the paired `ToolCallSettled` record, and the
511
+ * child-log lineage record is not model input.
512
+ */
513
+ const PROMPT_TRANSPARENT_TAGS: ReadonlySet<string> = new Set([
514
+ "RunPolicyUsageReserved",
515
+ "RunStarted",
516
+ "RunDurationExhausted",
517
+ "ToolCallPrepared",
518
+ "ToolCallUnknown",
519
+ "ToolCallResolved",
520
+ "ToolStepSettled",
521
+ "ToolApprovalRequested",
522
+ "ToolApprovalDecided",
523
+ "ModelResponseInterrupted",
524
+ "SubagentRequested",
525
+ "SubagentStarted",
526
+ "SubagentJoined",
527
+ "SubagentLineageRecorded",
528
+ "WorkerInputRequested",
529
+ "WorkerOriginRecorded",
530
+ "WorkerInputCompleted",
531
+ "WorkerReportPrepared",
532
+ "AgentUpdateEmitted",
533
+ "WorkerReportRefused",
534
+ "PeerMessagePrepared",
535
+ "SubtreeBudgetReserved",
536
+ ]);
537
+
538
+ /**
539
+ * Pure projection: rebuild one Run's resume state from canonical records (DUR-015). Canonical
540
+ * order is authoritative; the fold projects each `ModelResponseRecorded` Turn and the
541
+ * owning Run's resumable incomplete Tool Turn. It flushes each contiguous group of valid `ToolCallSettled` records into one Tool message,
542
+ * exactly mirroring the per-Turn commit shape produced by `turnCanonicalBatch` (no-tool Turns) and
543
+ * by the
544
+ * `turnResponseBatch`/`turnResultsBatch` split (tool-declaring Turns). The Phase 5 audit tags
545
+ * are skipped transparently, so split-batch commits replay to the same prompt as P4 single-batch
546
+ * commits.
547
+ *
548
+ * An incomplete application Tool turn remains visible while projecting its owning Run so active
549
+ * recovery can resume the declared batch. It is not a valid model-visible Turn boundary for a
550
+ * later Run until model-only unknown results close its missing calls. Those explanatory results
551
+ * are never canonical settlements or evidence for compaction, recovery or accounting. Real
552
+ * results replace them at the original declaration, including results appended after another Run.
553
+ * Prior user intent and assistant text remain visible; prior system instructions do not.
554
+ */
555
+ /** @internal Lightweight canonical boundaries collected without retaining record payloads. */
556
+ export interface JournalBoundary {
557
+ readonly sequence: CanonicalSequence;
558
+ readonly tag: "ModelResponseRecorded" | "ToolCallSettled";
559
+ readonly promptLength: number;
560
+ /** A declaration without all settled results requires terminal-prior-Run proof for coverage. */
561
+ readonly incomplete?: true | undefined;
562
+ /** The Run terminated after its last response and differs from the projection's owner. */
563
+ readonly terminalPriorRun?: true | undefined;
564
+ }
565
+
566
+ /**
567
+ * Reconstruct a fixed canonical prefix from a re-readable stream. The caller must keep the same
568
+ * records visible on every traversal. The first collects compaction and settlement metadata;
569
+ * rollovers additionally validate covered Tool batches before rebuilding Prompt and usage. Metadata and the
570
+ * live Prompt remain resident; covered historical message/tool payloads do not. An uncompacted Prompt still grows
571
+ * with its conversation, so hosts must configure an appropriate context compaction policy.
572
+ * Prepared metadata must describe exactly this stream and seed through the same fixed tail;
573
+ * it skips only the metadata scan, never covered-Tool validation or the canonical fold.
574
+ * @internal
575
+ */
576
+ export const projectRunJournalStream = Effect.fn("RunJournal.projectRunJournalStream")(function* <
577
+ E,
578
+ R,
579
+ >(
580
+ records: Stream.Stream<CanonicalRecordEnvelope, E, R>,
581
+ ownerRunId: RunId | undefined,
582
+ onBoundary?: (boundary: JournalBoundary) => void,
583
+ seed?: JournalCheckpointSeed,
584
+ preparedMetadata?: JournalMetadata,
585
+ ): Effect.fn.Return<RunJournalProjection, RunJournalError | E, R> {
586
+ if (seed !== undefined && seed.runId !== ownerRunId)
587
+ return yield* journalError("Recovery checkpoint belongs to another Run");
588
+
589
+ let state: FoldState = {
590
+ all: [],
591
+ before: [],
592
+ pendingTools: [],
593
+ pendingToolsForRun: false,
594
+ committedTurns: seed?.committedTurns ?? 0,
595
+ };
596
+
597
+ // RUN-026 pre-scan: the widest VALID compaction bounds govern the fold. A
598
+ // valid record covers strictly below its own sequence and never splits a response from its
599
+ // settled tool results. Pruning and rollovers may cover complete owner-Run batches;
600
+ // a summarize record must carry its summary. Invalid records
601
+ // are ignored fail-safe — the full history stays authoritative. Ties on
602
+ // coversThrough resolve to the record appended later (higher sequence),
603
+ // matching at-most-once replay intent.
604
+ // One span per settled record, paired with its declaring response the same
605
+ // way the fold pairs them: a settled belongs to the most recent
606
+ // ModelResponseRecorded of its Run. A bound inside (response, settled)
607
+ // would orphan the tool message from its declaring response. Orphaned
608
+ // settleds (filtered later by the fold) still contribute spans —
609
+ // over-invalidating is the fail-safe direction.
610
+ if (
611
+ preparedMetadata !== undefined &&
612
+ (preparedMetadata.ownerRunId !== ownerRunId || preparedMetadata.seed !== seed)
613
+ )
614
+ return yield* journalError("Prepared journal metadata belongs to another replay");
615
+
616
+ let metadata = preparedMetadata;
617
+
618
+ if (metadata === undefined) {
619
+ const collected = makeJournalMetadata(ownerRunId, seed);
620
+
621
+ yield* Stream.runForEach(records, (envelope) => Effect.sync(() => collected.add(envelope)));
622
+ metadata = collected.snapshot();
623
+ }
624
+
625
+ const {
626
+ firstSequenceByRun,
627
+ lastResponseSequenceByRun,
628
+ terminalSequenceByRun,
629
+ settledSpans,
630
+ settledToolCallRecordIds,
631
+ settledById,
632
+ compactions,
633
+ } = metadata;
634
+
635
+ const settledCoverage = compactions.reduce(
636
+ (through, { payload }) =>
637
+ payload.kind !== "summarize" ? Math.max(through, payload.coversThrough) : through,
638
+ 0,
639
+ );
640
+
641
+ // Terminality changes only prompt coverage; it never settles or resolves the Tool Call.
642
+ // Compare against the compaction's Run and sequence, independent of the replay's owner.
643
+ const isTerminalPriorRun = (
644
+ candidateRunId: RunId,
645
+ compactionRunId: RunId | undefined,
646
+ beforeSequence: number,
647
+ ): boolean => {
648
+ const terminal = terminalSequenceByRun.get(candidateRunId);
649
+
650
+ return (
651
+ candidateRunId !== compactionRunId &&
652
+ terminal !== undefined &&
653
+ terminal < beforeSequence &&
654
+ terminal > (lastResponseSequenceByRun.get(candidateRunId) ?? 0)
655
+ );
656
+ };
657
+
658
+ const incompleteResponseSequences: Array<{ readonly sequence: number; readonly runId: RunId }> =
659
+ [];
660
+
661
+ let ownerPrefixSequence = seed?.firstSequence ?? Number.POSITIVE_INFINITY;
662
+
663
+ let protectedContext: Prompt.Prompt | undefined =
664
+ seed?.protectedContext === undefined
665
+ ? undefined
666
+ : yield* decodePromptMessages(seed.protectedContext);
667
+
668
+ if (settledCoverage > 0) {
669
+ yield* Stream.runForEach(records, (envelope) =>
670
+ Effect.gen(function* () {
671
+ const payload = envelope.record.payload;
672
+
673
+ if (payload._tag !== "ModelResponseRecorded" || envelope.sequence > settledCoverage) return;
674
+ const messages = yield* decodePromptMessages(payload.messages);
675
+ const declared = declaredApplicationToolCallIds(messages);
676
+
677
+ for (const id of declared) {
678
+ const callId = yield* Schema.decodeEffect(ToolCallId)(id).pipe(
679
+ Effect.mapError((cause) =>
680
+ journalError("Failed to decode a declared Tool Call ID", cause),
681
+ ),
682
+ );
683
+
684
+ if (
685
+ !settledToolCallRecordIds.has(
686
+ toolCallSettledRecordId(payload.runId, payload.turn, callId),
687
+ )
688
+ ) {
689
+ incompleteResponseSequences.push({ sequence: envelope.sequence, runId: payload.runId });
690
+ break;
691
+ }
692
+ }
693
+ if (
694
+ payload.runId === ownerRunId &&
695
+ payload.turn === 1 &&
696
+ payload.runScopedPrefixLength !== undefined
697
+ ) {
698
+ ownerPrefixSequence = envelope.sequence;
699
+ protectedContext = Prompt.fromMessages(
700
+ messages.content.slice(0, payload.runScopedPrefixLength),
701
+ );
702
+ }
703
+ }),
704
+ );
705
+ }
706
+
707
+ const boundIsValid = (payload: CompactionCreated, ownSequence: number): boolean => {
708
+ const { runId, coversThrough } = payload;
709
+
710
+ if (coversThrough <= 0 || coversThrough >= ownSequence) return false;
711
+ if (seed !== undefined && ownSequence === seed.compaction.sequence)
712
+ return (
713
+ seed.compaction.record.payload._tag === "CompactionCreated" &&
714
+ Schema.toEquivalence(CompactionCreated)(payload, seed.compaction.record.payload)
715
+ );
716
+ const ownerFirst = firstSequenceByRun.get(runId);
717
+
718
+ if (payload.kind === "summarize" && ownerFirst !== undefined && coversThrough >= ownerFirst)
719
+ return false;
720
+ if (
721
+ payload.kind !== "summarize" &&
722
+ incompleteResponseSequences.some(
723
+ (response) =>
724
+ response.sequence <= coversThrough &&
725
+ !isTerminalPriorRun(response.runId, runId, ownSequence),
726
+ )
727
+ )
728
+ return false;
729
+ for (const span of settledSpans) {
730
+ if (span.from <= coversThrough && coversThrough < span.to) return false;
731
+ }
732
+
733
+ return true;
734
+ };
735
+
736
+ let summarizeBound = 0;
737
+ let replacement: CompactionCreated | undefined;
738
+ let summarizeSequence = -1;
739
+ let clearBound = 0;
740
+ let latestWindowId: string | undefined = seed?.contextWindowId;
741
+ let latestWindowSequence = seed?.throughSequence ?? -1;
742
+ let rolloverCoveredThrough = 0;
743
+
744
+ for (const { payload, sequence } of compactions) {
745
+ if (!boundIsValid(payload, sequence)) continue;
746
+ if (payload.kind === "rollover" && sequence > latestWindowSequence) {
747
+ latestWindowId = contextWindowId(payload.runId, payload.turn);
748
+ latestWindowSequence = sequence;
749
+ }
750
+ if (payload.kind === "rollover")
751
+ rolloverCoveredThrough = Math.max(rolloverCoveredThrough, payload.coversThrough);
752
+ if (payload.kind === "summarize" || payload.kind === "rollover") {
753
+ if (payload.kind === "summarize" && payload.summary === undefined) continue;
754
+ if (
755
+ payload.coversThrough > summarizeBound ||
756
+ (payload.coversThrough === summarizeBound && sequence > summarizeSequence)
757
+ ) {
758
+ summarizeBound = payload.coversThrough;
759
+ summarizeSequence = sequence;
760
+ replacement = payload;
761
+ }
762
+ } else if (payload.coversThrough > clearBound) {
763
+ clearBound = payload.coversThrough;
764
+ }
765
+ }
766
+ let summaryEmitted = false;
767
+
768
+ const retainedPrefix =
769
+ replacement?.kind === "rollover" &&
770
+ replacement.runId === ownerRunId &&
771
+ ownerPrefixSequence <= summarizeBound
772
+ ? (protectedContext?.content ?? [])
773
+ : [];
774
+
775
+ const replacementLength = replacement === undefined ? 0 : retainedPrefix.length + 1;
776
+
777
+ if (seed?.frontier !== undefined)
778
+ onBoundary?.({ ...seed.frontier, promptLength: replacementLength });
779
+
780
+ const emitSummary = () => {
781
+ if (summaryEmitted || replacement === undefined) return;
782
+ summaryEmitted = true;
783
+
784
+ const message =
785
+ replacement.kind === "rollover"
786
+ ? contextWindowMessage(
787
+ contextWindowId(replacement.runId, replacement.turn),
788
+ replacement.handoff,
789
+ )
790
+ : Prompt.makeMessage("user", {
791
+ content: [
792
+ Prompt.makePart("text", {
793
+ text: `${COMPACTION_SUMMARY_PREFIX}${replacement.summary}`,
794
+ }),
795
+ ],
796
+ });
797
+
798
+ state.all.push(...retainedPrefix, message);
799
+ if (replacement.kind !== "rollover" || replacement.runId !== ownerRunId)
800
+ state.before.push(message);
801
+ };
802
+
803
+ const modelUsage: Array<ModelCallUsage> = [];
804
+ let unobservedModelCalls = seed?.unobservedModelCalls ?? 0;
805
+
806
+ const usage = {
807
+ modelCalls: seed?.modelCalls ?? 0,
808
+ inputTokens: seed?.inputTokens ?? 0,
809
+ outputTokens: seed?.outputTokens ?? 0,
810
+ lastInputTokens: seed?.lastInputTokens ?? 0,
811
+ lastOutputTokens: seed?.lastOutputTokens ?? 0,
812
+ costMicrousd: seed?.costMicrousd ?? 0,
813
+ modelUsage,
814
+ ...(seed === undefined ? {} : { summarizedModelUsage: seed.summarizedModelUsage }),
815
+ };
816
+
817
+ let toolSelection = seed?.toolSelection;
818
+ let usageTurn = seed?.committedTurns ?? 0;
819
+
820
+ const incompleteToolTurns = new Set<string>();
821
+ const incompleteToolCalls = new Set<string>();
822
+ let pendingContextToolCallId: string | undefined;
823
+ let ownerTerminated = false;
824
+
825
+ const policyUsage = {
826
+ committedTurns: seed?.policyUsage.committedTurns ?? 0,
827
+ toolCalls: seed?.policyUsage.toolCalls ?? 0,
828
+ programmaticToolCalls: seed?.policyUsage.programmaticToolCalls ?? 0,
829
+ consecutiveToolFailures: seed?.policyUsage.consecutiveToolFailures ?? 0,
830
+ finalizationUsed: seed?.policyUsage.finalizationUsed ?? false,
831
+ };
832
+
833
+ const accountResponse = Effect.fn("RunJournal.accountResponse")(function* (
834
+ envelope: CanonicalRecordEnvelope,
835
+ payload: ModelResponseRecorded,
836
+ messages: Prompt.Prompt,
837
+ ) {
838
+ const record = envelope.record;
839
+
840
+ const declared = declaredApplicationToolCallIds(messages);
841
+ const declaredRecordIds: Array<RecordId> = [];
842
+
843
+ for (const id of declared) {
844
+ const toolCallId = yield* Effect.try({
845
+ try: () => decodeToolCallId(id),
846
+ catch: (cause) => journalError("Failed to decode a declared Tool Call ID", cause),
847
+ });
848
+
849
+ declaredRecordIds.push(toolCallSettledRecordId(payload.runId, payload.turn, toolCallId));
850
+ }
851
+ if (declaredRecordIds.some((recordId) => !settledToolCallRecordIds.has(recordId))) {
852
+ incompleteToolTurns.add(envelope.record.recordId);
853
+ for (const recordId of declaredRecordIds) incompleteToolCalls.add(recordId);
854
+ }
855
+ if (payload.runId !== ownerRunId) return;
856
+ if (seed !== undefined && envelope.sequence <= seed.throughSequence) return;
857
+ if (payload.turn === 1 && payload.runScopedPrefixLength !== undefined) {
858
+ protectedContext = Prompt.fromMessages(
859
+ messages.content.slice(0, payload.runScopedPrefixLength),
860
+ );
861
+ }
862
+
863
+ const responseUsage = yield* projectedResponseUsage(payload);
864
+
865
+ unobservedModelCalls = yield* addProjectedUsage(
866
+ "unobservedModelCalls",
867
+ unobservedModelCalls,
868
+ payload.unobservedModelCalls ?? 0,
869
+ );
870
+
871
+ usage.modelCalls = yield* addProjectedUsage(
872
+ "modelCalls",
873
+ usage.modelCalls,
874
+ responseUsage.modelCalls,
875
+ );
876
+ usage.inputTokens = yield* addProjectedUsage(
877
+ "inputTokens",
878
+ usage.inputTokens,
879
+ responseUsage.inputTokens,
880
+ );
881
+ usage.outputTokens = yield* addProjectedUsage(
882
+ "outputTokens",
883
+ usage.outputTokens,
884
+ responseUsage.outputTokens,
885
+ );
886
+ usage.costMicrousd = yield* addProjectedUsage(
887
+ "costMicrousd",
888
+ usage.costMicrousd,
889
+ responseUsage.costMicrousd,
890
+ );
891
+ usage.modelUsage.push(...responseUsage.modelUsage);
892
+ if (payload.turn > usageTurn) {
893
+ usageTurn = payload.turn;
894
+ usage.lastInputTokens = responseUsage.inputTokens;
895
+ usage.lastOutputTokens = responseUsage.outputTokens;
896
+ }
897
+
898
+ policyUsage.committedTurns = Math.max(policyUsage.committedTurns, payload.turn);
899
+
900
+ const calls = messages.content.flatMap((message) =>
901
+ message.role === "assistant"
902
+ ? message.content.filter((part) => part.type === "tool-call")
903
+ : [],
904
+ );
905
+
906
+ const candidate = calls.length === 1 ? calls[0] : undefined;
907
+
908
+ const candidateResult =
909
+ candidate === undefined
910
+ ? undefined
911
+ : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${candidate.id}`);
912
+
913
+ pendingContextToolCallId =
914
+ candidate !== undefined &&
915
+ !candidate.providerExecuted &&
916
+ candidateResult?.isFailure === false &&
917
+ candidateResult.budgetRejected !== true &&
918
+ envelope.sequence > rolloverCoveredThrough
919
+ ? candidate.id
920
+ : undefined;
921
+
922
+ policyUsage.toolCalls += calls.length;
923
+ if (payload.toolExposure !== undefined) toolSelection = payload.toolExposure.selection;
924
+ if (incompleteToolTurns.has(record.recordId)) return;
925
+ for (const call of calls) {
926
+ const result = call.providerExecuted
927
+ ? messages.content
928
+ .flatMap((message) => (message.role === "assistant" ? message.content : []))
929
+ .find(
930
+ (part) => part.type === "tool-result" && part.providerExecuted && part.id === call.id,
931
+ )
932
+ : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${call.id}`);
933
+
934
+ if (result === undefined || ("budgetRejected" in result && result.budgetRejected === true))
935
+ continue;
936
+ if (!("isFailure" in result)) continue;
937
+ if (!result.isFailure && "toolSelection" in result && result.toolSelection !== undefined)
938
+ toolSelection = result.toolSelection;
939
+ policyUsage.consecutiveToolFailures = result.isFailure
940
+ ? policyUsage.consecutiveToolFailures + 1
941
+ : 0;
942
+ }
943
+ });
944
+
945
+ // Slots refer to the retained Prompt itself, not an additional history payload index.
946
+ // Only still-unseen results retain a slot; late results fill the original declaration in place.
947
+ const historicalResults = new Map<
948
+ string,
949
+ {
950
+ readonly allIndex: number;
951
+ readonly beforeIndex: number;
952
+ readonly parts: Array<Prompt.ToolResultPart>;
953
+ readonly partIndex: number;
954
+ }
955
+ >();
956
+
957
+ let pendingToolOrder = new Map<string, number>();
958
+
959
+ const flushTools = Effect.fn("RunJournal.flushTools")(function* (
960
+ current: FoldState,
961
+ ): Effect.fn.Return<FoldState, RunJournalError> {
962
+ if (current.pendingTools.length === 0) return current;
963
+
964
+ // Suspension can persist an ordinary sibling before a delegated call joins. Model context
965
+ // still uses declaration order, matching the live interpreter's completed results batch.
966
+ const ordered = current.pendingTools.toSorted(
967
+ (left, right) =>
968
+ (pendingToolOrder.get(left.record.toolCallId) ?? Number.MAX_SAFE_INTEGER) -
969
+ (pendingToolOrder.get(right.record.toolCallId) ?? Number.MAX_SAFE_INTEGER),
970
+ );
971
+
972
+ const toolMessage = yield* toolMessageFromSettled(ordered);
973
+
974
+ current.all.push(toolMessage);
975
+ if (!current.pendingToolsForRun) current.before.push(toolMessage);
976
+
977
+ return {
978
+ ...current,
979
+ pendingTools: [],
980
+ pendingToolsForRun: false,
981
+ };
982
+ });
983
+
984
+ yield* Stream.runForEach(records, (envelope) =>
985
+ Effect.gen(function* () {
986
+ const payload = envelope.record.payload;
987
+
988
+ if (
989
+ ((payload._tag === "RunCompleted" || payload._tag === "RunFailed") &&
990
+ payload.runId === ownerRunId) ||
991
+ (payload._tag === "SubmissionSettled" &&
992
+ runIdForSubmission(payload.submissionId) === ownerRunId)
993
+ )
994
+ ownerTerminated = true;
995
+
996
+ if (payload._tag === "RunPolicyUsageReserved" && payload.runId === ownerRunId) {
997
+ if (seed !== undefined && envelope.sequence <= seed.throughSequence) return;
998
+ if (
999
+ payload.programmaticToolCalls < policyUsage.programmaticToolCalls ||
1000
+ (policyUsage.finalizationUsed && !payload.finalizationUsed)
1001
+ ) {
1002
+ return yield* journalError("Run policy reservations must be monotonic");
1003
+ }
1004
+ policyUsage.programmaticToolCalls = payload.programmaticToolCalls;
1005
+ policyUsage.finalizationUsed = payload.finalizationUsed;
1006
+ }
1007
+ if (PROMPT_TRANSPARENT_TAGS.has(payload._tag)) return;
1008
+ // The compaction record governs the fold (pre-scan) and contributes no
1009
+ // message of its own; records at or below the summarize bound render as
1010
+ // the one summary message emitted at the covered/kept transition.
1011
+ if (payload._tag === "CompactionCreated") return;
1012
+ if (
1013
+ seed !== undefined &&
1014
+ envelope.sequence <= seed.throughSequence &&
1015
+ (payload._tag === "ModelResponseRecorded" || payload._tag === "ToolCallSettled")
1016
+ )
1017
+ return;
1018
+ if (envelope.sequence <= summarizeBound) {
1019
+ // Projecting an earlier Run after a later summary still accounts for its covered responses.
1020
+ if (payload._tag === "ModelResponseRecorded" && payload.runId === ownerRunId) {
1021
+ const messages = yield* decodePromptMessages(payload.messages);
1022
+
1023
+ yield* accountResponse(envelope, payload, messages);
1024
+ state = { ...state, committedTurns: Math.max(state.committedTurns, payload.turn) };
1025
+ }
1026
+ if (payload._tag === "ModelResponseRecorded" || payload._tag === "ToolCallSettled") {
1027
+ onBoundary?.({
1028
+ sequence: envelope.sequence,
1029
+ tag: payload._tag,
1030
+ promptLength: replacementLength,
1031
+ ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)
1032
+ ? { terminalPriorRun: true }
1033
+ : {}),
1034
+ ...(incompleteToolTurns.has(envelope.record.recordId) ||
1035
+ incompleteToolCalls.has(envelope.record.recordId)
1036
+ ? { incomplete: true }
1037
+ : {}),
1038
+ });
1039
+ }
1040
+
1041
+ return;
1042
+ }
1043
+ emitSummary();
1044
+ if (payload._tag === "ToolCallSettled") {
1045
+ if (payload.runId !== ownerRunId) {
1046
+ const slot = historicalResults.get(envelope.record.recordId);
1047
+
1048
+ if (slot === undefined)
1049
+ return yield* journalError("Historical Tool result has no matching declaration");
1050
+ const declared = slot.parts[slot.partIndex];
1051
+
1052
+ if (declared?.id !== payload.toolCallId || declared.name !== payload.toolName)
1053
+ return yield* journalError("Historical Tool result differs from its declaration");
1054
+ slot.parts[slot.partIndex] = Prompt.makePart("tool-result", {
1055
+ id: payload.toolCallId,
1056
+ name: payload.toolName,
1057
+ result: envelope.sequence <= clearBound ? CLEARED_TOOL_RESULT : payload.result,
1058
+ isFailure: payload.isFailure,
1059
+ providerExecuted: false,
1060
+ });
1061
+ const message = Prompt.makeMessage("tool", { content: [...slot.parts] });
1062
+
1063
+ state.all[slot.allIndex] = message;
1064
+ state.before[slot.beforeIndex] = message;
1065
+ historicalResults.delete(envelope.record.recordId);
1066
+ onBoundary?.({
1067
+ sequence: envelope.sequence,
1068
+ tag: payload._tag,
1069
+ promptLength: state.all.length,
1070
+ ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),
1071
+ ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)
1072
+ ? { terminalPriorRun: true }
1073
+ : {}),
1074
+ });
1075
+
1076
+ return;
1077
+ }
1078
+ if (
1079
+ state.pendingTools.length > 0 &&
1080
+ state.pendingToolsForRun !== (payload.runId === ownerRunId)
1081
+ ) {
1082
+ state = yield* flushTools(state);
1083
+ }
1084
+ state.pendingTools.push({ record: payload, cleared: envelope.sequence <= clearBound });
1085
+ state = {
1086
+ ...state,
1087
+ pendingToolsForRun: payload.runId === ownerRunId,
1088
+ };
1089
+ onBoundary?.({
1090
+ sequence: envelope.sequence,
1091
+ tag: payload._tag,
1092
+ promptLength: state.all.length + 1,
1093
+ ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)
1094
+ ? { terminalPriorRun: true }
1095
+ : {}),
1096
+ ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),
1097
+ });
1098
+
1099
+ return;
1100
+ }
1101
+ state = yield* flushTools(state);
1102
+ if (payload._tag === "ModelCompleted" && payload.messages !== undefined) {
1103
+ const messages = yield* decodePromptMessages(payload.messages);
1104
+
1105
+ for (const message of messages.content) {
1106
+ state.all.push(message);
1107
+ if (payload.runId !== ownerRunId) state.before.push(message);
1108
+ }
1109
+
1110
+ return;
1111
+ }
1112
+ if (payload._tag !== "ModelResponseRecorded") return;
1113
+ const messages = yield* decodePromptMessages(payload.messages);
1114
+ const forRun = payload.runId === ownerRunId;
1115
+
1116
+ pendingToolOrder = new Map(
1117
+ declaredApplicationToolCallIds(messages).map((id, index) => [id, index]),
1118
+ );
1119
+
1120
+ yield* accountResponse(envelope, payload, messages);
1121
+
1122
+ const visibleMessages = forRun
1123
+ ? messages.content
1124
+ : messages.content.filter((message) => message.role !== "system");
1125
+
1126
+ for (const message of visibleMessages) {
1127
+ state.all.push(message);
1128
+ if (!forRun) state.before.push(message);
1129
+ }
1130
+ if (!forRun) {
1131
+ const calls = messages.content.flatMap((message) =>
1132
+ message.role === "assistant"
1133
+ ? message.content.filter(
1134
+ (part): part is Prompt.ToolCallPart =>
1135
+ part.type === "tool-call" && !part.providerExecuted,
1136
+ )
1137
+ : [],
1138
+ );
1139
+
1140
+ if (calls.length > 0) {
1141
+ const parts = calls.map((call) =>
1142
+ Prompt.makePart("tool-result", {
1143
+ id: call.id,
1144
+ name: call.name,
1145
+ result: {
1146
+ _tag: "ToolOutcomeUnknown",
1147
+ message:
1148
+ "This earlier operation has no recorded outcome. It may have executed. Do not assume success or retry it; its original operation remains unresolved.",
1149
+ },
1150
+ isFailure: true,
1151
+ providerExecuted: false,
1152
+ }),
1153
+ );
1154
+
1155
+ const allIndex = state.all.length;
1156
+ const beforeIndex = state.before.length;
1157
+ const message = Prompt.makeMessage("tool", { content: parts });
1158
+
1159
+ state.all.push(message);
1160
+ state.before.push(message);
1161
+ for (const [partIndex, call] of calls.entries()) {
1162
+ const callId = yield* Schema.decodeEffect(ToolCallId)(call.id).pipe(
1163
+ Effect.mapError((cause) => journalError("Invalid historical Tool Call ID", cause)),
1164
+ );
1165
+
1166
+ historicalResults.set(toolCallSettledRecordId(payload.runId, payload.turn, callId), {
1167
+ allIndex,
1168
+ beforeIndex,
1169
+ parts,
1170
+ partIndex,
1171
+ });
1172
+ }
1173
+ }
1174
+ }
1175
+ state = {
1176
+ ...state,
1177
+ committedTurns: forRun
1178
+ ? Math.max(state.committedTurns, payload.turn)
1179
+ : state.committedTurns,
1180
+ };
1181
+ onBoundary?.({
1182
+ sequence: envelope.sequence,
1183
+ tag: payload._tag,
1184
+ promptLength: state.all.length,
1185
+ ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)
1186
+ ? { terminalPriorRun: true }
1187
+ : {}),
1188
+ ...(incompleteToolTurns.has(envelope.record.recordId) ? { incomplete: true } : {}),
1189
+ });
1190
+ }),
1191
+ );
1192
+ emitSummary();
1193
+ state = yield* flushTools(state);
1194
+
1195
+ const validatedPolicyUsage = yield* Schema.decodeEffect(RunPolicyUsage)(policyUsage).pipe(
1196
+ Effect.mapError((cause) =>
1197
+ journalError("Run policy accounting exceeds its Schema bounds", cause),
1198
+ ),
1199
+ );
1200
+
1201
+ return {
1202
+ ...(toolSelection === undefined ? {} : { toolSelection }),
1203
+ policyUsage: validatedPolicyUsage,
1204
+ prompt: Prompt.fromMessages(state.all),
1205
+ historyBefore: Prompt.fromMessages(state.before),
1206
+ committedTurns: state.committedTurns,
1207
+ usage: unobservedModelCalls === 0 ? usage : { ...usage, unobservedModelCalls },
1208
+ ...(latestWindowId === undefined ? {} : { contextWindowId: latestWindowId }),
1209
+ ...(protectedContext === undefined ? {} : { protectedContext }),
1210
+ ...(ownerTerminated || pendingContextToolCallId === undefined
1211
+ ? {}
1212
+ : { pendingContextToolCallId }),
1213
+ };
1214
+ });
1215
+
1216
+ /** Pure projection of one Run's durable recovery state from canonical records. */
1217
+ export const projectRunJournal = Effect.fn("RunJournal.projectRunJournal")(
1218
+ (
1219
+ records: ReadonlyArray<CanonicalRecordEnvelope>,
1220
+ runId: RunId,
1221
+ ): Effect.Effect<RunJournalProjection, RunJournalError> =>
1222
+ projectRunJournalStream(Stream.fromIterable(records), runId),
1223
+ );
1224
+
1225
+ /**
1226
+ * Pure valid-prompt projection from canonical records: `UserInputRecorded` +
1227
+ * `ModelResponseRecorded` + complete `ToolCallSettled` batches → the deterministic model-visible
1228
+ * Prompt (plan §Coordinator flow step 3).
1229
+ */
1230
+ export const promptFromCanonicalRecords = Effect.fn("RunJournal.promptFromCanonicalRecords")(
1231
+ (
1232
+ records: ReadonlyArray<CanonicalRecordEnvelope>,
1233
+ ): Effect.Effect<Prompt.Prompt, RunJournalError> =>
1234
+ projectRunJournalStream(Stream.fromIterable(records), undefined).pipe(
1235
+ Effect.map((projection) => projection.prompt),
1236
+ ),
1237
+ );
1238
+
1239
+ /** Everything one committed Turn contributes to its canonical batch. */
1240
+ /**
1241
+ * Staged usage is validated, never repaired: clamping negatives or truncating
1242
+ * fractions would under-record canonical usage, and NaN/Infinity must fail
1243
+ * typed instead of escaping as a record-construction defect (RUN-023).
1244
+ */
1245
+ const validStagedUsage = (label: string, value: number): Effect.Effect<number, RunJournalError> =>
1246
+ Number.isSafeInteger(value) && value >= 0
1247
+ ? Effect.succeed(value)
1248
+ : Effect.fail(
1249
+ journalError(`Staged ${label} must be a non-negative safe integer, got ${String(value)}`),
1250
+ );
1251
+
1252
+ export interface TurnCommitInput {
1253
+ readonly toolOperations?: ModelResponseRecorded["toolOperations"] | undefined;
1254
+ readonly toolParameterRejections?: ReadonlyArray<ToolParameterRejection> | undefined;
1255
+ readonly toolExposure?: Snapshot | undefined;
1256
+ readonly toolSelections?: ReadonlyMap<string, Selection> | undefined;
1257
+ readonly budgetRejectedCalls?: ReadonlySet<string>;
1258
+ readonly runId: RunId;
1259
+ /** Canonical (Run-relative, Attempt-independent) Turn number; must be positive. */
1260
+ readonly turn: number;
1261
+ readonly turnId: TurnId;
1262
+ /**
1263
+ * The Prompt messages this Turn appended to official history, in order, including the Turn's
1264
+ * Tool message when application Tools ran. Tool messages become `ToolCallSettled` records; the
1265
+ * remaining messages become the Turn's `ModelResponseRecorded.messages`.
1266
+ */
1267
+ readonly appended: ReadonlyArray<Prompt.Message>;
1268
+ readonly producerId: ProducerId;
1269
+ readonly deploymentId: DeploymentId;
1270
+ readonly createdAt: DateTime.Utc;
1271
+ /** Leading instruction/wake messages that stay canonical but are hidden from later Runs. */
1272
+ readonly runScopedPrefixLength?: number | undefined;
1273
+ /** Terminal output committed atomically with this Turn's final canonical batch. */
1274
+ readonly runCompletion?:
1275
+ | {
1276
+ readonly output: PersistedJson;
1277
+ readonly runDisposition?: PersistedJson | undefined;
1278
+ readonly finishReason?: "budget-exhausted" | undefined;
1279
+ readonly exhausted?: ExhaustedLimit | undefined;
1280
+ }
1281
+ | undefined;
1282
+ /** Known missing-accounting invocations staged before this canonical response. */
1283
+ readonly unobservedModelCalls?: number | undefined;
1284
+ /** Per-call provider usage staged by the engine's `noteTurnUsage` (RUN-023). */
1285
+ readonly usage?:
1286
+ | {
1287
+ readonly inputTokens: number;
1288
+ readonly outputTokens: number;
1289
+ readonly costMicrousd?: number | undefined;
1290
+ readonly modelUsage?: ReadonlyArray<ModelCallUsage> | undefined;
1291
+ }
1292
+ | undefined;
1293
+ }
1294
+
1295
+ const decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);
1296
+ const encodePrompt = Schema.encodeEffect(Prompt.Prompt);
1297
+ const decodeModelUsage = Schema.decodeUnknownEffect(Schema.Array(ModelCallUsage));
1298
+
1299
+ const requireCanonicalTurn = (turn: number): Effect.Effect<void, RunJournalError> =>
1300
+ !Number.isInteger(turn) || turn <= 0
1301
+ ? Effect.fail(journalError(`Canonical turn number must be a positive integer: ${turn}`))
1302
+ : Effect.void;
1303
+
1304
+ interface SplitTurnMessages {
1305
+ readonly promptMessages: ReadonlyArray<Prompt.Message>;
1306
+ readonly toolParts: ReadonlyArray<Prompt.ToolResultPart>;
1307
+ }
1308
+
1309
+ const splitTurnMessages = (appended: ReadonlyArray<Prompt.Message>): SplitTurnMessages => {
1310
+ const promptMessages: Array<Prompt.Message> = [];
1311
+ const toolParts: Array<Prompt.ToolResultPart> = [];
1312
+
1313
+ for (const message of appended) {
1314
+ if (message.role !== "tool") {
1315
+ promptMessages.push(message);
1316
+ continue;
1317
+ }
1318
+ for (const part of message.content) {
1319
+ if (part.type !== "tool-result") continue;
1320
+ toolParts.push(part);
1321
+ }
1322
+ }
1323
+
1324
+ return { promptMessages, toolParts };
1325
+ };
1326
+
1327
+ const modelResponseRecord = Effect.fn("RunJournal.modelResponseRecord")(function* (
1328
+ input: TurnCommitInput,
1329
+ promptMessages: ReadonlyArray<Prompt.Message>,
1330
+ ): Effect.fn.Return<RecordEnvelope, RunJournalError | DigestError, Crypto.Crypto> {
1331
+ if (promptMessages.length === 0) {
1332
+ return yield* journalError(`Turn ${input.turn} appended no model-visible Prompt messages`);
1333
+ }
1334
+ const runScopedPrefixLength = input.runScopedPrefixLength;
1335
+
1336
+ if (
1337
+ runScopedPrefixLength !== undefined &&
1338
+ (input.turn !== 1 ||
1339
+ !Number.isSafeInteger(runScopedPrefixLength) ||
1340
+ runScopedPrefixLength <= 0 ||
1341
+ runScopedPrefixLength >= promptMessages.length ||
1342
+ promptMessages
1343
+ .slice(0, runScopedPrefixLength)
1344
+ .some((message) => message.role !== "system" && message.role !== "user"))
1345
+ ) {
1346
+ return yield* journalError(
1347
+ "Run-scoped Prompt provenance must identify a non-empty system/user prefix of Turn 1 before its assistant response",
1348
+ );
1349
+ }
1350
+
1351
+ const encodedMessages = yield* encodePrompt(Prompt.fromMessages([...promptMessages])).pipe(
1352
+ Effect.mapError((cause) => journalError("Turn Prompt messages failed to encode", cause)),
1353
+ );
1354
+
1355
+ const messages = yield* decodePersistedJson(encodedMessages).pipe(
1356
+ Effect.mapError((cause) =>
1357
+ journalError("Turn Prompt messages exceed canonical persistence bounds", cause),
1358
+ ),
1359
+ );
1360
+
1361
+ const messagesDigest = yield* digestJson(messages);
1362
+
1363
+ const modelUsage =
1364
+ input.usage?.modelUsage === undefined
1365
+ ? undefined
1366
+ : yield* decodeModelUsage(input.usage.modelUsage).pipe(
1367
+ Effect.mapError((cause) => journalError("Turn model usage failed to decode", cause)),
1368
+ );
1369
+
1370
+ if (modelUsage !== undefined) {
1371
+ if (modelUsage.length === 0) {
1372
+ return yield* journalError("Turn model usage must contain at least one completed call");
1373
+ }
1374
+
1375
+ const summary = yield* summarizeModelUsage(modelUsage).pipe(
1376
+ Effect.mapError((cause) => journalError("Turn model usage exceeds accounting bounds", cause)),
1377
+ );
1378
+
1379
+ if (
1380
+ input.usage === undefined ||
1381
+ input.usage.inputTokens !== summary.inputTokens.total ||
1382
+ input.usage.outputTokens !== summary.outputTokens.total ||
1383
+ (input.usage.costMicrousd ?? 0) !== summary.costMicrousd
1384
+ ) {
1385
+ return yield* journalError("Turn detailed and aggregate model usage disagree");
1386
+ }
1387
+ }
1388
+
1389
+ return RecordEnvelope.make({
1390
+ recordId: modelResponseRecordId(input.runId, input.turn),
1391
+ family: "thread",
1392
+ schemaVersion: 1,
1393
+ createdAt: input.createdAt,
1394
+ deploymentId: input.deploymentId,
1395
+ payload: ModelResponseRecorded.make({
1396
+ ...(input.toolOperations === undefined ? {} : { toolOperations: input.toolOperations }),
1397
+ ...(input.toolParameterRejections === undefined || input.toolParameterRejections.length === 0
1398
+ ? {}
1399
+ : { toolParameterRejections: input.toolParameterRejections }),
1400
+ ...(input.toolExposure === undefined ? {} : { toolExposure: input.toolExposure }),
1401
+ runId: input.runId,
1402
+ turnId: input.turnId,
1403
+ turn: input.turn,
1404
+ messages,
1405
+ messagesDigest,
1406
+ ...(runScopedPrefixLength === undefined ? {} : { runScopedPrefixLength }),
1407
+ ...(modelUsage === undefined ? {} : { modelUsage }),
1408
+ ...(input.unobservedModelCalls === undefined || input.unobservedModelCalls === 0
1409
+ ? {}
1410
+ : {
1411
+ unobservedModelCalls: yield* validStagedUsage(
1412
+ "unobservedModelCalls",
1413
+ input.unobservedModelCalls,
1414
+ ),
1415
+ }),
1416
+ ...(input.usage === undefined
1417
+ ? {}
1418
+ : {
1419
+ inputTokens: yield* validStagedUsage("inputTokens", input.usage.inputTokens),
1420
+ outputTokens: yield* validStagedUsage("outputTokens", input.usage.outputTokens),
1421
+ // Written only when non-zero: absent re-seeds as zero, so the
1422
+ // no-estimator case stays byte-identical to pre-cost histories.
1423
+ ...(input.usage.costMicrousd === undefined || input.usage.costMicrousd === 0
1424
+ ? {}
1425
+ : {
1426
+ costMicrousd: yield* validStagedUsage("costMicrousd", input.usage.costMicrousd),
1427
+ }),
1428
+ }),
1429
+ }),
1430
+ });
1431
+ });
1432
+
1433
+ const toolSettledRecords = Effect.fn("RunJournal.toolSettledRecords")(function* (
1434
+ input: TurnCommitInput,
1435
+ toolParts: ReadonlyArray<Prompt.ToolResultPart>,
1436
+ ): Effect.fn.Return<Array<RecordEnvelope>, RunJournalError> {
1437
+ const toolRecords: Array<RecordEnvelope> = [];
1438
+
1439
+ for (const part of toolParts) {
1440
+ const result = yield* decodePersistedJson(part.result).pipe(
1441
+ Effect.mapError((cause) =>
1442
+ journalError(`Tool result ${part.id} exceeds canonical persistence bounds`, cause),
1443
+ ),
1444
+ );
1445
+
1446
+ const toolCallId = yield* Effect.try({
1447
+ try: () => decodeToolCallId(part.id),
1448
+ catch: (cause) => journalError(`Invalid Tool Call ID ${part.id}`, cause),
1449
+ });
1450
+
1451
+ toolRecords.push(
1452
+ RecordEnvelope.make({
1453
+ recordId: toolCallSettledRecordId(input.runId, input.turn, toolCallId),
1454
+ family: "thread",
1455
+ schemaVersion: 1,
1456
+ createdAt: input.createdAt,
1457
+ deploymentId: input.deploymentId,
1458
+ payload: ToolCallSettled.make({
1459
+ ...(input.toolSelections?.get(part.id) === undefined
1460
+ ? {}
1461
+ : { toolSelection: input.toolSelections.get(part.id) }),
1462
+ runId: input.runId,
1463
+ toolCallId,
1464
+ toolName: part.name,
1465
+ result,
1466
+ isFailure: part.isFailure,
1467
+ ...(input.budgetRejectedCalls?.has(part.id) === true ? { budgetRejected: true } : {}),
1468
+ }),
1469
+ }),
1470
+ );
1471
+ }
1472
+
1473
+ return toolRecords;
1474
+ });
1475
+
1476
+ /** Integrity of the original validated terminal values; never a current-code projection. */
1477
+ export const runCompletionDigest = (
1478
+ completion: Pick<
1479
+ RunCompleted,
1480
+ "runId" | "output" | "runDisposition" | "finishReason" | "exhausted"
1481
+ >,
1482
+ ) =>
1483
+ digestJson({
1484
+ runId: completion.runId,
1485
+ output: completion.output,
1486
+ runDisposition: completion.runDisposition ?? null,
1487
+ finishReason: completion.finishReason ?? null,
1488
+ exhausted: completion.exhausted ?? null,
1489
+ });
1490
+
1491
+ const runCompletionRecord = Effect.fn("RunJournal.runCompletionRecord")(function* (
1492
+ input: TurnCommitInput,
1493
+ ) {
1494
+ if (input.runCompletion === undefined) return undefined;
1495
+ const completion = { runId: input.runId, ...input.runCompletion };
1496
+
1497
+ return RecordEnvelope.make({
1498
+ recordId: runCompletedRecordId(input.runId),
1499
+ family: "thread",
1500
+ schemaVersion: 1,
1501
+ createdAt: input.createdAt,
1502
+ deploymentId: input.deploymentId,
1503
+ payload: RunCompleted.make({
1504
+ ...completion,
1505
+ resultDigest: yield* runCompletionDigest(completion),
1506
+ }),
1507
+ });
1508
+ });
1509
+
1510
+ /**
1511
+ * Pure per-Turn canonical batch builder (TurnCompleted seam fold, D6/D8): one
1512
+ * `ModelResponseRecorded` record plus one `ToolCallSettled` record per terminal Tool result, all
1513
+ * under the WP0-style deterministic identities, committed as ONE atomic batch. The same input
1514
+ * always yields byte-identical content, so an in-Attempt append retry is an honest batch replay.
1515
+ *
1516
+ * Phase 5 keeps this shape for Turns that declare no application Tool calls; their terminal
1517
+ * `RunCompleted` marker joins the response in this same atomic batch. Tool-declaring Turns split
1518
+ * into `turnResponseBatch` + `turnResultsBatch`.
1519
+ */
1520
+ export const turnCanonicalBatch = Effect.fn("RunJournal.turnCanonicalBatch")(function* (
1521
+ input: TurnCommitInput,
1522
+ ): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {
1523
+ yield* requireCanonicalTurn(input.turn);
1524
+ const { promptMessages, toolParts } = splitTurnMessages(input.appended);
1525
+ const modelResponse = yield* modelResponseRecord(input, promptMessages);
1526
+ const toolRecords = yield* toolSettledRecords(input, toolParts);
1527
+ const completionRecord = yield* runCompletionRecord(input);
1528
+
1529
+ return CanonicalBatch.make({
1530
+ batchId: turnBatchId(input.runId, input.turn),
1531
+ producerId: input.producerId,
1532
+ records:
1533
+ completionRecord === undefined
1534
+ ? [modelResponse, ...toolRecords]
1535
+ : [modelResponse, ...toolRecords, completionRecord],
1536
+ });
1537
+ });
1538
+
1539
+ /**
1540
+ * Commit 1 of a tool-declaring Turn: the Turn's `ModelResponseRecorded` record, including
1541
+ * provider results retained in assistant content before application Tools execute.
1542
+ * — pending steering plus the assistant response with its declared tool calls — under batch
1543
+ * identity `turn-response:{runId}:{turn}`. Committing the response before preparation creates
1544
+ * the provably-safe durability §15 window ("after model item commit, before tool preparation →
1545
+ * resume tool scheduling"): a crash there resumes the declared batch with no model re-invocation
1546
+ * and no Unknown. Tool messages in `appended` are ignored; the record identity is the same
1547
+ * `model-response:{runId}:{turn}` as the single-batch shape, so record-id assertions and the
1548
+ * prompt projection are unchanged.
1549
+ */
1550
+ export const turnResponseBatch = Effect.fn("RunJournal.turnResponseBatch")(function* (
1551
+ input: TurnCommitInput,
1552
+ ): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {
1553
+ yield* requireCanonicalTurn(input.turn);
1554
+ const { promptMessages } = splitTurnMessages(input.appended);
1555
+ const modelResponse = yield* modelResponseRecord(input, promptMessages);
1556
+
1557
+ return CanonicalBatch.make({
1558
+ batchId: turnResponseBatchId(input.runId, input.turn),
1559
+ producerId: input.producerId,
1560
+ records: [modelResponse],
1561
+ });
1562
+ });
1563
+
1564
+ /**
1565
+ * Commit 5 of a tool-declaring Turn (plan §2.1): the Turn's `ToolCallSettled` records in
1566
+ * declaration order under batch identity `turn-results:{runId}:{turn}` — the batch becomes
1567
+ * model-visible atomically. Non-tool messages in `appended` are ignored; a Turn without any
1568
+ * terminal Tool result has no results batch and fails typed.
1569
+ */
1570
+ export const turnResultsBatch = Effect.fn("RunJournal.turnResultsBatch")(function* (
1571
+ input: TurnCommitInput,
1572
+ ): Effect.fn.Return<CanonicalBatch, RunJournalError | DigestError, Crypto.Crypto> {
1573
+ yield* requireCanonicalTurn(input.turn);
1574
+ const { toolParts } = splitTurnMessages(input.appended);
1575
+ const toolRecords = yield* toolSettledRecords(input, toolParts);
1576
+ const first = toolRecords[0];
1577
+
1578
+ if (first === undefined) {
1579
+ return yield* journalError(`Turn ${input.turn} has no terminal Tool results to commit`);
1580
+ }
1581
+ if (input.runCompletion !== undefined && toolRecords.length !== 1) {
1582
+ return yield* journalError("A terminal Tool completion requires exactly one settled result");
1583
+ }
1584
+ const completionRecord = yield* runCompletionRecord(input);
1585
+
1586
+ return CanonicalBatch.make({
1587
+ batchId: turnResultsBatchId(input.runId, input.turn),
1588
+ producerId: input.producerId,
1589
+ records:
1590
+ completionRecord === undefined
1591
+ ? [first, ...toolRecords.slice(1)]
1592
+ : [first, ...toolRecords.slice(1), completionRecord],
1593
+ });
1594
+ });