effect-agent 0.1.0-beta.84 → 0.1.0-beta.86

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 (747) hide show
  1. package/dist/Agent-CN0EWRsR.d.mts +226 -0
  2. package/dist/Agent-RklVROrm.mjs +83 -0
  3. package/dist/Agent-RklVROrm.mjs.map +1 -0
  4. package/dist/AgentError-CggcAQ7V.d.mts +101 -0
  5. package/dist/AgentPolicy-CetmQrf3.d.mts +96 -0
  6. package/dist/AgentRuntime-BLyETCPo.mjs +4562 -0
  7. package/dist/AgentRuntime-BLyETCPo.mjs.map +1 -0
  8. package/dist/AgentRuntime-uxR_a4VM.d.mts +346 -0
  9. package/dist/AgentUpdates-DMJ-_xow.d.mts +53 -0
  10. package/dist/ContextCompactor-Dxu5zhOL.d.mts +161 -0
  11. package/dist/ContextWindow-DRQ5Mbm2.d.mts +58 -0
  12. package/dist/DurableAgentRuntime-sOrBVu4B.mjs +6366 -0
  13. package/dist/DurableAgentRuntime-sOrBVu4B.mjs.map +1 -0
  14. package/dist/DurableFailpoint-Oinuuedm.d.mts +41 -0
  15. package/dist/DurableStep-Cry_iol4.d.mts +103 -0
  16. package/dist/Ephemeral.d.mts +22 -0
  17. package/dist/Ephemeral.mjs +22 -0
  18. package/dist/Ephemeral.mjs.map +1 -0
  19. package/dist/EventSource-OqS_P9ug.d.mts +51 -0
  20. package/dist/Identifiers-CN2s30fF.d.mts +40 -0
  21. package/dist/MemoryNamespace-BbRW5p71.d.mts +36 -0
  22. package/dist/MemoryReference-B8Q3UJoJ.d.mts +79 -0
  23. package/dist/Messaging-CkcIdt4I.d.mts +490 -0
  24. package/dist/MessagingHost-CRk0kXzT.d.mts +246 -0
  25. package/dist/MessagingHost-CWi_PP3g.mjs +137 -0
  26. package/dist/MessagingHost-CWi_PP3g.mjs.map +1 -0
  27. package/dist/OperationAuthorizer-TzcQtpX5.d.mts +61 -0
  28. package/dist/Output-D6SkedVx.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-C4HbjHgl.d.mts +38 -0
  32. package/dist/Receipt-BAHyigAF.d.mts +33 -0
  33. package/dist/Records-BAGkekt8.d.mts +3570 -0
  34. package/dist/RunEvent-DIrzkjLr.d.mts +460 -0
  35. package/dist/RunEventSink-D5aVhISG.d.mts +108 -0
  36. package/dist/RunJournal-Cgg1kNvc.mjs +825 -0
  37. package/dist/RunJournal-Cgg1kNvc.mjs.map +1 -0
  38. package/dist/RunOptions-g1aigcKI.d.mts +915 -0
  39. package/dist/RunPolicyUsage-ClZxyR46.d.mts +21 -0
  40. package/dist/Sandbox-CEsDWBLq.d.mts +173 -0
  41. package/dist/Schedule-H3SEYX9g.d.mts +842 -0
  42. package/dist/Scheduling-C9aIP8zT.mjs +691 -0
  43. package/dist/Scheduling-C9aIP8zT.mjs.map +1 -0
  44. package/dist/Subagent-Cy_hU1tv.mjs +1469 -0
  45. package/dist/Subagent-Cy_hU1tv.mjs.map +1 -0
  46. package/dist/Subagent-DyfzHNdv.d.mts +826 -0
  47. package/dist/SubagentContract-DdT7Cqe6.d.mts +116 -0
  48. package/dist/SubagentHost-CJUBQlcc.d.mts +140 -0
  49. package/dist/Subscription-BEP8oQO5.d.mts +921 -0
  50. package/dist/SubscriptionInput-vAAOBrK7.d.mts +41 -0
  51. package/dist/Thread-DOBQ0QUY.d.mts +96 -0
  52. package/dist/ThreadHistory-tS1KwxHR.d.mts +60 -0
  53. package/dist/ToolBroker-DWs4tZra.d.mts +133 -0
  54. package/dist/ToolExposure-9uF_Yo0T.mjs +10 -0
  55. package/dist/ToolExposure-9uF_Yo0T.mjs.map +1 -0
  56. package/dist/ToolExposure-C93U1sPu.mjs +30 -0
  57. package/dist/ToolExposure-C93U1sPu.mjs.map +1 -0
  58. package/dist/ToolExposure-UCN12eCd.d.mts +39 -0
  59. package/dist/ToolExposure-r2eOWk4F.d.mts +46 -0
  60. package/dist/ToolExposure.d.mts +6 -5
  61. package/dist/ToolExposure.mjs +17 -9
  62. package/dist/ToolExposure.mjs.map +1 -1
  63. package/dist/ToolReconciler-DQVaJfpE.d.mts +76 -0
  64. package/dist/ToolResult-DmmgoChv.d.mts +61 -0
  65. package/dist/Usage-Dx0aknfk.d.mts +121 -0
  66. package/dist/WakeScheduler-EjUF-GhC.d.mts +56 -0
  67. package/dist/Worker-CaPYykpe.d.mts +228 -0
  68. package/dist/agent-registration-CWDMOAZA.mjs +172 -0
  69. package/dist/agent-registration-CWDMOAZA.mjs.map +1 -0
  70. package/dist/capabilities/Approval.d.mts +114 -0
  71. package/dist/capabilities/Approval.mjs +226 -0
  72. package/dist/capabilities/Approval.mjs.map +1 -0
  73. package/dist/capabilities/Budget.d.mts +112 -0
  74. package/dist/capabilities/Budget.mjs +346 -0
  75. package/dist/capabilities/Budget.mjs.map +1 -0
  76. package/dist/capabilities/CodeMode.d.mts +157 -0
  77. package/dist/capabilities/CodeMode.mjs +522 -0
  78. package/dist/capabilities/CodeMode.mjs.map +1 -0
  79. package/dist/capabilities/Commands.d.mts +55 -0
  80. package/dist/capabilities/Commands.mjs +57 -0
  81. package/dist/capabilities/Commands.mjs.map +1 -0
  82. package/dist/capabilities/ContextTools.d.mts +321 -0
  83. package/dist/capabilities/ContextTools.mjs +126 -0
  84. package/dist/capabilities/ContextTools.mjs.map +1 -0
  85. package/dist/capabilities/Mcp.d.mts +108 -0
  86. package/dist/capabilities/Mcp.mjs +260 -0
  87. package/dist/capabilities/Mcp.mjs.map +1 -0
  88. package/dist/capabilities/McpClient.d.mts +115 -0
  89. package/dist/capabilities/McpClient.mjs +506 -0
  90. package/dist/capabilities/McpClient.mjs.map +1 -0
  91. package/dist/capabilities/MemoryNotes.d.mts +424 -0
  92. package/dist/capabilities/MemoryNotes.mjs +128 -0
  93. package/dist/capabilities/MemoryNotes.mjs.map +1 -0
  94. package/dist/capabilities/Messaging.d.mts +3 -0
  95. package/dist/capabilities/Messaging.mjs +151 -0
  96. package/dist/capabilities/Messaging.mjs.map +1 -0
  97. package/dist/capabilities/ModelContext.d.mts +89 -0
  98. package/dist/capabilities/ModelContext.mjs +168 -0
  99. package/dist/capabilities/ModelContext.mjs.map +1 -0
  100. package/dist/capabilities/Redaction.d.mts +37 -0
  101. package/dist/capabilities/Redaction.mjs +104 -0
  102. package/dist/capabilities/Redaction.mjs.map +1 -0
  103. package/dist/capabilities/Remembering.d.mts +434 -0
  104. package/dist/capabilities/Remembering.mjs +290 -0
  105. package/dist/capabilities/Remembering.mjs.map +1 -0
  106. package/dist/capabilities/RunHooks.d.mts +82 -0
  107. package/dist/capabilities/RunHooks.mjs +144 -0
  108. package/dist/capabilities/RunHooks.mjs.map +1 -0
  109. package/dist/capabilities/SemanticMemory.d.mts +431 -0
  110. package/dist/capabilities/SemanticMemory.mjs +315 -0
  111. package/dist/capabilities/SemanticMemory.mjs.map +1 -0
  112. package/dist/capabilities/Subagent.d.mts +4 -0
  113. package/dist/capabilities/Subagent.mjs +5 -0
  114. package/dist/capabilities/SubagentReservations.d.mts +186 -0
  115. package/dist/capabilities/SubagentReservations.mjs +479 -0
  116. package/dist/capabilities/SubagentReservations.mjs.map +1 -0
  117. package/dist/capabilities/ToolDiscovery.d.mts +109 -0
  118. package/dist/capabilities/ToolDiscovery.mjs +211 -0
  119. package/dist/capabilities/ToolDiscovery.mjs.map +1 -0
  120. package/dist/capabilities/WebCapture.d.mts +163 -0
  121. package/dist/capabilities/WebCapture.mjs +335 -0
  122. package/dist/capabilities/WebCapture.mjs.map +1 -0
  123. package/dist/capabilities/WebSearch.d.mts +71 -0
  124. package/dist/capabilities/WebSearch.mjs +112 -0
  125. package/dist/capabilities/WebSearch.mjs.map +1 -0
  126. package/dist/compaction-C2OTceKw.mjs +505 -0
  127. package/dist/compaction-C2OTceKw.mjs.map +1 -0
  128. package/dist/core/Agent.d.mts +2 -0
  129. package/dist/core/Agent.mjs +2 -0
  130. package/dist/core/AgentError.d.mts +2 -0
  131. package/dist/core/AgentError.mjs +117 -0
  132. package/dist/core/AgentError.mjs.map +1 -0
  133. package/dist/core/AgentPolicy.d.mts +2 -0
  134. package/dist/core/AgentPolicy.mjs +94 -0
  135. package/dist/core/AgentPolicy.mjs.map +1 -0
  136. package/dist/core/AgentUpdates.d.mts +2 -0
  137. package/dist/core/AgentUpdates.mjs +63 -0
  138. package/dist/core/AgentUpdates.mjs.map +1 -0
  139. package/dist/core/IdGenerator.d.mts +26 -0
  140. package/dist/core/IdGenerator.mjs +27 -0
  141. package/dist/core/IdGenerator.mjs.map +1 -0
  142. package/dist/core/Identifiers.d.mts +2 -0
  143. package/dist/core/Identifiers.mjs +43 -0
  144. package/dist/core/Identifiers.mjs.map +1 -0
  145. package/dist/core/Memory.d.mts +57 -0
  146. package/dist/core/Memory.mjs +203 -0
  147. package/dist/core/Memory.mjs.map +1 -0
  148. package/dist/core/MemoryNamespace.d.mts +2 -0
  149. package/dist/core/MemoryNamespace.mjs +116 -0
  150. package/dist/core/MemoryNamespace.mjs.map +1 -0
  151. package/dist/core/MemoryReference.d.mts +2 -0
  152. package/dist/core/MemoryReference.mjs +109 -0
  153. package/dist/core/MemoryReference.mjs.map +1 -0
  154. package/dist/core/MemoryRevalidation.d.mts +65 -0
  155. package/dist/core/MemoryRevalidation.mjs +126 -0
  156. package/dist/core/MemoryRevalidation.mjs.map +1 -0
  157. package/dist/core/MemoryStore.d.mts +186 -0
  158. package/dist/core/MemoryStore.mjs +243 -0
  159. package/dist/core/MemoryStore.mjs.map +1 -0
  160. package/dist/core/Receipt.d.mts +2 -0
  161. package/dist/core/Receipt.mjs +36 -0
  162. package/dist/core/Receipt.mjs.map +1 -0
  163. package/dist/core/RememberingStore.d.mts +1562 -0
  164. package/dist/core/RememberingStore.mjs +190 -0
  165. package/dist/core/RememberingStore.mjs.map +1 -0
  166. package/dist/core/RunEvent.d.mts +2 -0
  167. package/dist/core/RunEvent.mjs +337 -0
  168. package/dist/core/RunEvent.mjs.map +1 -0
  169. package/dist/core/RunPolicyUsage.d.mts +2 -0
  170. package/dist/core/RunPolicyUsage.mjs +21 -0
  171. package/dist/core/RunPolicyUsage.mjs.map +1 -0
  172. package/dist/core/SemanticMemoryIndex.d.mts +826 -0
  173. package/dist/core/SemanticMemoryIndex.mjs +185 -0
  174. package/dist/core/SemanticMemoryIndex.mjs.map +1 -0
  175. package/dist/core/SemanticMemoryRevalidation.d.mts +45 -0
  176. package/dist/core/SemanticMemoryRevalidation.mjs +191 -0
  177. package/dist/core/SemanticMemoryRevalidation.mjs.map +1 -0
  178. package/dist/core/SubagentContract.d.mts +2 -0
  179. package/dist/core/SubagentContract.mjs +148 -0
  180. package/dist/core/SubagentContract.mjs.map +1 -0
  181. package/dist/core/Thread.d.mts +2 -0
  182. package/dist/core/Thread.mjs +250 -0
  183. package/dist/core/Thread.mjs.map +1 -0
  184. package/dist/core/ToolResult.d.mts +2 -0
  185. package/dist/core/ToolResult.mjs +140 -0
  186. package/dist/core/ToolResult.mjs.map +1 -0
  187. package/dist/core/Usage.d.mts +2 -0
  188. package/dist/core/Usage.mjs +319 -0
  189. package/dist/core/Usage.mjs.map +1 -0
  190. package/dist/core/Worker.d.mts +3 -0
  191. package/dist/core/Worker.mjs +147 -0
  192. package/dist/core/Worker.mjs.map +1 -0
  193. package/dist/durable/ActivityStore.d.mts +116 -0
  194. package/dist/durable/ActivityStore.mjs +131 -0
  195. package/dist/durable/ActivityStore.mjs.map +1 -0
  196. package/dist/durable/Admin.d.mts +2 -0
  197. package/dist/durable/Admin.mjs +328 -0
  198. package/dist/durable/Admin.mjs.map +1 -0
  199. package/dist/durable/AgentRegistration.d.mts +2 -0
  200. package/dist/durable/AgentRegistration.mjs +14 -0
  201. package/dist/durable/AgentRegistration.mjs.map +1 -0
  202. package/dist/durable/Certification.d.mts +111 -0
  203. package/dist/durable/Certification.mjs +159 -0
  204. package/dist/durable/Certification.mjs.map +1 -0
  205. package/dist/durable/CommittedActivity.d.mts +62 -0
  206. package/dist/durable/CommittedActivity.mjs +159 -0
  207. package/dist/durable/CommittedActivity.mjs.map +1 -0
  208. package/dist/durable/Digest.d.mts +2 -0
  209. package/dist/durable/Digest.mjs +50 -0
  210. package/dist/durable/Digest.mjs.map +1 -0
  211. package/dist/durable/DurableAgentRuntime.d.mts +3 -0
  212. package/dist/durable/DurableAgentRuntime.mjs +3 -0
  213. package/dist/durable/DurableFailpoint.d.mts +2 -0
  214. package/dist/durable/DurableFailpoint.mjs +94 -0
  215. package/dist/durable/DurableFailpoint.mjs.map +1 -0
  216. package/dist/durable/DurableFailpointTestControl.d.mts +15 -0
  217. package/dist/durable/DurableFailpointTestControl.mjs +19 -0
  218. package/dist/durable/DurableFailpointTestControl.mjs.map +1 -0
  219. package/dist/durable/EventSource.d.mts +2 -0
  220. package/dist/durable/EventSource.mjs +65 -0
  221. package/dist/durable/EventSource.mjs.map +1 -0
  222. package/dist/durable/GitHubWorkflowSource.d.mts +144 -0
  223. package/dist/durable/GitHubWorkflowSource.mjs +209 -0
  224. package/dist/durable/GitHubWorkflowSource.mjs.map +1 -0
  225. package/dist/durable/MessageDelivery.d.mts +492 -0
  226. package/dist/durable/MessageDelivery.mjs +495 -0
  227. package/dist/durable/MessageDelivery.mjs.map +1 -0
  228. package/dist/durable/MessageDeliveryStoreConformance.d.mts +358 -0
  229. package/dist/durable/MessageDeliveryStoreConformance.mjs +243 -0
  230. package/dist/durable/MessageDeliveryStoreConformance.mjs.map +1 -0
  231. package/dist/durable/OperationAuthorizer.d.mts +2 -0
  232. package/dist/durable/OperationAuthorizer.mjs +70 -0
  233. package/dist/durable/OperationAuthorizer.mjs.map +1 -0
  234. package/dist/durable/PersistentHistory.d.mts +16 -0
  235. package/dist/durable/PersistentHistory.mjs +125 -0
  236. package/dist/durable/PersistentHistory.mjs.map +1 -0
  237. package/dist/durable/PreparedInputAdmission.d.mts +2 -0
  238. package/dist/durable/PreparedInputAdmission.mjs +34 -0
  239. package/dist/durable/PreparedInputAdmission.mjs.map +1 -0
  240. package/dist/durable/Records.d.mts +2 -0
  241. package/dist/durable/Records.mjs +795 -0
  242. package/dist/durable/Records.mjs.map +1 -0
  243. package/dist/durable/Recovery.d.mts +2 -0
  244. package/dist/durable/Recovery.mjs +739 -0
  245. package/dist/durable/Recovery.mjs.map +1 -0
  246. package/dist/durable/RunJournal.d.mts +2 -0
  247. package/dist/durable/RunJournal.mjs +2 -0
  248. package/dist/durable/Schedule.d.mts +2 -0
  249. package/dist/durable/Schedule.mjs +382 -0
  250. package/dist/durable/Schedule.mjs.map +1 -0
  251. package/dist/durable/ScheduleStoreConformance.d.mts +18 -0
  252. package/dist/durable/ScheduleStoreConformance.mjs +420 -0
  253. package/dist/durable/ScheduleStoreConformance.mjs.map +1 -0
  254. package/dist/durable/ScheduleTransition.d.mts +24 -0
  255. package/dist/durable/ScheduleTransition.mjs +180 -0
  256. package/dist/durable/ScheduleTransition.mjs.map +1 -0
  257. package/dist/durable/Scheduling.d.mts +54 -0
  258. package/dist/durable/Scheduling.mjs +2 -0
  259. package/dist/durable/SqlMemoryStore.d.mts +30 -0
  260. package/dist/durable/SqlMemoryStore.mjs +435 -0
  261. package/dist/durable/SqlMemoryStore.mjs.map +1 -0
  262. package/dist/durable/SqlMessageDeliveryStore.d.mts +40 -0
  263. package/dist/durable/SqlMessageDeliveryStore.mjs +167 -0
  264. package/dist/durable/SqlMessageDeliveryStore.mjs.map +1 -0
  265. package/dist/durable/SqlStorageV2Upgrade.d.mts +22 -0
  266. package/dist/durable/SqlStorageV2Upgrade.mjs +459 -0
  267. package/dist/durable/SqlStorageV2Upgrade.mjs.map +1 -0
  268. package/dist/durable/SqlSubscriptionStore.d.mts +63 -0
  269. package/dist/durable/SqlSubscriptionStore.mjs +751 -0
  270. package/dist/durable/SqlSubscriptionStore.mjs.map +1 -0
  271. package/dist/durable/SubmissionLedger.d.mts +3 -0
  272. package/dist/durable/SubmissionLedger.mjs +914 -0
  273. package/dist/durable/SubmissionLedger.mjs.map +1 -0
  274. package/dist/durable/SubmissionLedgerConformance.d.mts +30 -0
  275. package/dist/durable/SubmissionLedgerConformance.mjs +1986 -0
  276. package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -0
  277. package/dist/durable/SubmissionStatus.d.mts +2 -0
  278. package/dist/durable/SubmissionStatus.mjs +18 -0
  279. package/dist/durable/SubmissionStatus.mjs.map +1 -0
  280. package/dist/durable/Subscription.d.mts +2 -0
  281. package/dist/durable/Subscription.mjs +360 -0
  282. package/dist/durable/Subscription.mjs.map +1 -0
  283. package/dist/durable/SubscriptionInput.d.mts +2 -0
  284. package/dist/durable/SubscriptionInput.mjs +52 -0
  285. package/dist/durable/SubscriptionInput.mjs.map +1 -0
  286. package/dist/durable/SubscriptionStoreConformance.d.mts +17 -0
  287. package/dist/durable/SubscriptionStoreConformance.mjs +625 -0
  288. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -0
  289. package/dist/durable/SubscriptionTools.d.mts +273 -0
  290. package/dist/durable/SubscriptionTools.mjs +190 -0
  291. package/dist/durable/SubscriptionTools.mjs.map +1 -0
  292. package/dist/durable/SubscriptionTransition.d.mts +21 -0
  293. package/dist/durable/SubscriptionTransition.mjs +148 -0
  294. package/dist/durable/SubscriptionTransition.mjs.map +1 -0
  295. package/dist/durable/Subscriptions.d.mts +73 -0
  296. package/dist/durable/Subscriptions.mjs +627 -0
  297. package/dist/durable/Subscriptions.mjs.map +1 -0
  298. package/dist/durable/ThreadContextHistory.d.mts +32 -0
  299. package/dist/durable/ThreadContextHistory.mjs +152 -0
  300. package/dist/durable/ThreadContextHistory.mjs.map +1 -0
  301. package/dist/durable/ThreadContextHistoryProjection.d.mts +60 -0
  302. package/dist/durable/ThreadContextHistoryProjection.mjs +149 -0
  303. package/dist/durable/ThreadContextHistoryProjection.mjs.map +1 -0
  304. package/dist/durable/ThreadInvariants.d.mts +74 -0
  305. package/dist/durable/ThreadInvariants.mjs +200 -0
  306. package/dist/durable/ThreadInvariants.mjs.map +1 -0
  307. package/dist/durable/ThreadProjection.d.mts +78 -0
  308. package/dist/durable/ThreadProjection.mjs +158 -0
  309. package/dist/durable/ThreadProjection.mjs.map +1 -0
  310. package/dist/durable/ThreadProjectionMaintenance.d.mts +49 -0
  311. package/dist/durable/ThreadProjectionMaintenance.mjs +33 -0
  312. package/dist/durable/ThreadProjectionMaintenance.mjs.map +1 -0
  313. package/dist/durable/ThreadStore.d.mts +2 -0
  314. package/dist/durable/ThreadStore.mjs +147 -0
  315. package/dist/durable/ThreadStore.mjs.map +1 -0
  316. package/dist/durable/ThreadStoreConformance.d.mts +29 -0
  317. package/dist/durable/ThreadStoreConformance.mjs +248 -0
  318. package/dist/durable/ThreadStoreConformance.mjs.map +1 -0
  319. package/dist/durable/ToolReconciler.d.mts +2 -0
  320. package/dist/durable/ToolReconciler.mjs +81 -0
  321. package/dist/durable/ToolReconciler.mjs.map +1 -0
  322. package/dist/durable/WakeScheduler.d.mts +2 -0
  323. package/dist/durable/WakeScheduler.mjs +85 -0
  324. package/dist/durable/WakeScheduler.mjs.map +1 -0
  325. package/dist/durable/WorkerHost.d.mts +129 -0
  326. package/dist/durable/WorkerHost.mjs +77 -0
  327. package/dist/durable/WorkerHost.mjs.map +1 -0
  328. package/dist/engine/AgentRuntime.d.mts +2 -0
  329. package/dist/engine/AgentRuntime.mjs +2 -0
  330. package/dist/engine/Compaction.d.mts +7 -0
  331. package/dist/engine/Compaction.mjs +16 -0
  332. package/dist/engine/Compaction.mjs.map +1 -0
  333. package/dist/engine/ContextCompactor.d.mts +2 -0
  334. package/dist/engine/ContextCompactor.mjs +119 -0
  335. package/dist/engine/ContextCompactor.mjs.map +1 -0
  336. package/dist/engine/ContextHistory.d.mts +65 -0
  337. package/dist/engine/ContextHistory.mjs +76 -0
  338. package/dist/engine/ContextHistory.mjs.map +1 -0
  339. package/dist/engine/ContextWindow.d.mts +2 -0
  340. package/dist/engine/ContextWindow.mjs +59 -0
  341. package/dist/engine/ContextWindow.mjs.map +1 -0
  342. package/dist/engine/DurableStep.d.mts +2 -0
  343. package/dist/engine/DurableStep.mjs +62 -0
  344. package/dist/engine/DurableStep.mjs.map +1 -0
  345. package/dist/engine/MessagingHost.d.mts +2 -0
  346. package/dist/engine/MessagingHost.mjs +2 -0
  347. package/dist/engine/Output.d.mts +2 -0
  348. package/dist/engine/Output.mjs +8 -0
  349. package/dist/engine/Output.mjs.map +1 -0
  350. package/dist/engine/RunEventSink.d.mts +2 -0
  351. package/dist/engine/RunEventSink.mjs +22 -0
  352. package/dist/engine/RunEventSink.mjs.map +1 -0
  353. package/dist/engine/RunOptions.d.mts +2 -0
  354. package/dist/engine/RunOptions.mjs +122 -0
  355. package/dist/engine/RunOptions.mjs.map +1 -0
  356. package/dist/engine/SubagentHost.d.mts +2 -0
  357. package/dist/engine/SubagentHost.mjs +72 -0
  358. package/dist/engine/SubagentHost.mjs.map +1 -0
  359. package/dist/engine/ThreadHistory.d.mts +2 -0
  360. package/dist/engine/ThreadHistory.mjs +67 -0
  361. package/dist/engine/ThreadHistory.mjs.map +1 -0
  362. package/dist/engine/ToolBroker.d.mts +2 -0
  363. package/dist/engine/ToolBroker.mjs +42 -0
  364. package/dist/engine/ToolBroker.mjs.map +1 -0
  365. package/dist/foreign-diagnostic-DBQ1XHKh.mjs +37 -0
  366. package/dist/foreign-diagnostic-DBQ1XHKh.mjs.map +1 -0
  367. package/dist/index.d.mts +88 -53
  368. package/dist/index.mjs +97 -53
  369. package/dist/output-contract-BC7tjlGw.mjs +84 -0
  370. package/dist/output-contract-BC7tjlGw.mjs.map +1 -0
  371. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  372. package/dist/sandbox/CodeExecutor.d.mts +194 -0
  373. package/dist/sandbox/CodeExecutor.mjs +278 -0
  374. package/dist/sandbox/CodeExecutor.mjs.map +1 -0
  375. package/dist/sandbox/InteractiveBrowser.d.mts +142 -0
  376. package/dist/sandbox/InteractiveBrowser.mjs +165 -0
  377. package/dist/sandbox/InteractiveBrowser.mjs.map +1 -0
  378. package/dist/sandbox/PageCapture.d.mts +2 -0
  379. package/dist/sandbox/PageCapture.mjs +450 -0
  380. package/dist/sandbox/PageCapture.mjs.map +1 -0
  381. package/dist/sandbox/PageCrawl.d.mts +88 -0
  382. package/dist/sandbox/PageCrawl.mjs +124 -0
  383. package/dist/sandbox/PageCrawl.mjs.map +1 -0
  384. package/dist/sandbox/PageScreenshot.d.mts +2 -0
  385. package/dist/sandbox/PageScreenshot.mjs +53 -0
  386. package/dist/sandbox/PageScreenshot.mjs.map +1 -0
  387. package/dist/sandbox/ProtectedBrowser.d.mts +252 -0
  388. package/dist/sandbox/ProtectedBrowser.mjs +270 -0
  389. package/dist/sandbox/ProtectedBrowser.mjs.map +1 -0
  390. package/dist/sandbox/Sandbox.d.mts +2 -0
  391. package/dist/sandbox/Sandbox.mjs +208 -0
  392. package/dist/sandbox/Sandbox.mjs.map +1 -0
  393. package/dist/utf8-BYfhEkcj.mjs +11 -0
  394. package/dist/utf8-BYfhEkcj.mjs.map +1 -0
  395. package/dist/utf8-DchGZRBd.mjs +23 -0
  396. package/dist/utf8-DchGZRBd.mjs.map +1 -0
  397. package/package.json +1 -1
  398. package/src/Ephemeral.ts +17 -0
  399. package/src/ToolExposure.ts +2 -2
  400. package/src/capabilities/Approval.ts +352 -0
  401. package/src/capabilities/Budget.ts +536 -0
  402. package/src/capabilities/CodeMode.ts +1090 -0
  403. package/src/capabilities/Commands.ts +86 -0
  404. package/src/capabilities/ContextTools.ts +184 -0
  405. package/src/capabilities/Mcp.ts +427 -0
  406. package/src/capabilities/McpClient.ts +967 -0
  407. package/src/capabilities/MemoryNotes.ts +174 -0
  408. package/src/capabilities/Messaging.ts +261 -0
  409. package/src/capabilities/ModelContext.ts +354 -0
  410. package/src/capabilities/Redaction.ts +157 -0
  411. package/src/capabilities/Remembering.ts +550 -0
  412. package/src/capabilities/RunHooks.ts +280 -0
  413. package/src/capabilities/SemanticMemory.ts +447 -0
  414. package/src/capabilities/Subagent.ts +2277 -0
  415. package/src/capabilities/SubagentReservations.ts +850 -0
  416. package/src/capabilities/ToolDiscovery.ts +339 -0
  417. package/src/capabilities/WebCapture.ts +722 -0
  418. package/src/capabilities/WebSearch.ts +184 -0
  419. package/src/capabilities/internal/subagent-background.ts +1106 -0
  420. package/src/capabilities/internal/subagent-contract.ts +142 -0
  421. package/src/capabilities/internal/subagent-policy.ts +235 -0
  422. package/src/capabilities/internal/subagent-reporting.ts +261 -0
  423. package/src/capabilities/internal/utf8.ts +10 -0
  424. package/src/core/Agent.ts +575 -0
  425. package/src/core/AgentError.ts +152 -0
  426. package/src/core/AgentPolicy.ts +153 -0
  427. package/src/core/AgentUpdates.ts +100 -0
  428. package/src/core/IdGenerator.ts +39 -0
  429. package/src/core/Identifiers.ts +48 -0
  430. package/src/core/Memory.ts +290 -0
  431. package/src/core/MemoryNamespace.ts +196 -0
  432. package/src/core/MemoryReference.ts +121 -0
  433. package/src/core/MemoryRevalidation.ts +185 -0
  434. package/src/core/MemoryStore.ts +368 -0
  435. package/src/core/Messaging.ts +90 -0
  436. package/src/core/Receipt.ts +42 -0
  437. package/src/core/RememberingStore.ts +300 -0
  438. package/src/core/RunEvent.ts +366 -0
  439. package/src/core/RunPolicyUsage.ts +17 -0
  440. package/src/core/SemanticMemoryIndex.ts +250 -0
  441. package/src/core/SemanticMemoryRevalidation.ts +254 -0
  442. package/src/core/SubagentContract.ts +196 -0
  443. package/src/core/Thread.ts +371 -0
  444. package/src/core/ToolExposure.ts +74 -0
  445. package/src/core/ToolResult.ts +170 -0
  446. package/src/core/Usage.ts +529 -0
  447. package/src/core/Worker.ts +173 -0
  448. package/src/core/internal/agent-updates.ts +32 -0
  449. package/src/core/internal/utf8.ts +23 -0
  450. package/src/durable/ActivityStore.ts +160 -0
  451. package/src/durable/Admin.ts +496 -0
  452. package/src/durable/AgentRegistration.ts +13 -0
  453. package/src/durable/Certification.ts +210 -0
  454. package/src/durable/CommittedActivity.ts +296 -0
  455. package/src/durable/Digest.ts +93 -0
  456. package/src/durable/DurableAgentRuntime.ts +10328 -0
  457. package/src/durable/DurableFailpoint.ts +103 -0
  458. package/src/durable/DurableFailpointTestControl.ts +39 -0
  459. package/src/durable/EventSource.ts +172 -0
  460. package/src/durable/GitHubWorkflowSource.ts +453 -0
  461. package/src/durable/MessageDelivery.ts +708 -0
  462. package/src/durable/MessageDeliveryStoreConformance.ts +363 -0
  463. package/src/durable/OperationAuthorizer.ts +85 -0
  464. package/src/durable/PersistentHistory.ts +260 -0
  465. package/src/durable/PreparedInputAdmission.ts +44 -0
  466. package/src/durable/Records.ts +1010 -0
  467. package/src/durable/Recovery.ts +1018 -0
  468. package/src/durable/RunJournal.ts +1479 -0
  469. package/src/durable/Schedule.ts +504 -0
  470. package/src/durable/ScheduleStoreConformance.ts +638 -0
  471. package/src/durable/ScheduleTransition.ts +265 -0
  472. package/src/durable/Scheduling.ts +1077 -0
  473. package/src/durable/SqlMemoryStore.ts +774 -0
  474. package/src/durable/SqlMessageDeliveryStore.ts +302 -0
  475. package/src/durable/SqlStorageV2Upgrade.ts +500 -0
  476. package/src/durable/SqlSubscriptionStore.ts +1440 -0
  477. package/src/durable/SubmissionLedger.ts +1201 -0
  478. package/src/durable/SubmissionLedgerConformance.ts +4579 -0
  479. package/src/durable/SubmissionStatus.ts +14 -0
  480. package/src/durable/Subscription.ts +544 -0
  481. package/src/durable/SubscriptionInput.ts +144 -0
  482. package/src/durable/SubscriptionStoreConformance.ts +945 -0
  483. package/src/durable/SubscriptionTools.ts +327 -0
  484. package/src/durable/SubscriptionTransition.ts +302 -0
  485. package/src/durable/Subscriptions.ts +1210 -0
  486. package/src/durable/ThreadContextHistory.ts +227 -0
  487. package/src/durable/ThreadContextHistoryProjection.ts +216 -0
  488. package/src/durable/ThreadInvariants.ts +442 -0
  489. package/src/durable/ThreadProjection.ts +269 -0
  490. package/src/durable/ThreadProjectionMaintenance.ts +67 -0
  491. package/src/durable/ThreadStore.ts +242 -0
  492. package/src/durable/ThreadStoreConformance.ts +710 -0
  493. package/src/durable/ToolReconciler.ts +105 -0
  494. package/src/durable/WakeScheduler.ts +134 -0
  495. package/src/durable/WorkerHost.ts +171 -0
  496. package/src/durable/internal/agent-registration.ts +525 -0
  497. package/src/durable/internal/agent-updates.ts +302 -0
  498. package/src/durable/internal/foreign-diagnostic.ts +47 -0
  499. package/src/durable/internal/journal-checkpoint.ts +104 -0
  500. package/src/durable/internal/journal-metadata.ts +107 -0
  501. package/src/durable/internal/messaging-host.ts +608 -0
  502. package/src/durable/internal/schedule-time.ts +303 -0
  503. package/src/durable/internal/storage-v2-layout.ts +163 -0
  504. package/src/durable/internal/storage-v2.ts +73 -0
  505. package/src/durable/internal/worker-host.ts +2467 -0
  506. package/src/durable/internal/worker-runtime.ts +9 -0
  507. package/src/engine/AgentRuntime.ts +37 -0
  508. package/src/engine/Compaction.ts +11 -0
  509. package/src/engine/ContextCompactor.ts +277 -0
  510. package/src/engine/ContextHistory.ts +73 -0
  511. package/src/engine/ContextWindow.ts +72 -0
  512. package/src/engine/DurableStep.ts +132 -0
  513. package/src/engine/MessagingHost.ts +110 -0
  514. package/src/engine/Output.ts +2 -0
  515. package/src/engine/RunEventSink.ts +132 -0
  516. package/src/engine/RunOptions.ts +1077 -0
  517. package/src/engine/SubagentHost.ts +181 -0
  518. package/src/engine/ThreadHistory.ts +120 -0
  519. package/src/engine/ToolBroker.ts +157 -0
  520. package/src/engine/ToolExposure.ts +48 -0
  521. package/src/engine/internal/agent-runtime.ts +10117 -0
  522. package/src/engine/internal/bounded-value.ts +315 -0
  523. package/src/engine/internal/compaction.ts +678 -0
  524. package/src/engine/internal/error-diagnostic.ts +39 -0
  525. package/src/engine/internal/output-contract.ts +173 -0
  526. package/src/engine/internal/primitive-delta.ts +80 -0
  527. package/src/engine/internal/provider-result-staging.ts +211 -0
  528. package/src/engine/internal/tool-derivative.ts +106 -0
  529. package/src/engine/internal/tool-exposure.ts +224 -0
  530. package/src/engine/internal/tool-telemetry.ts +484 -0
  531. package/src/index.ts +96 -52
  532. package/src/sandbox/CodeExecutor.ts +352 -0
  533. package/src/sandbox/InteractiveBrowser.ts +257 -0
  534. package/src/sandbox/PageCapture.ts +692 -0
  535. package/src/sandbox/PageCrawl.ts +148 -0
  536. package/src/sandbox/PageScreenshot.ts +81 -0
  537. package/src/sandbox/ProtectedBrowser.ts +413 -0
  538. package/src/sandbox/Sandbox.ts +241 -0
  539. package/dist/Agent.d.mts +0 -5
  540. package/dist/Agent.mjs +0 -10
  541. package/dist/Agent.mjs.map +0 -1
  542. package/dist/AgentError.d.mts +0 -5
  543. package/dist/AgentError.mjs +0 -10
  544. package/dist/AgentError.mjs.map +0 -1
  545. package/dist/AgentPolicy.d.mts +0 -5
  546. package/dist/AgentPolicy.mjs +0 -10
  547. package/dist/AgentPolicy.mjs.map +0 -1
  548. package/dist/AgentRuntime.d.mts +0 -5
  549. package/dist/AgentRuntime.mjs +0 -10
  550. package/dist/AgentRuntime.mjs.map +0 -1
  551. package/dist/Approval.d.mts +0 -5
  552. package/dist/Approval.mjs +0 -10
  553. package/dist/Approval.mjs.map +0 -1
  554. package/dist/Budget.d.mts +0 -5
  555. package/dist/Budget.mjs +0 -10
  556. package/dist/Budget.mjs.map +0 -1
  557. package/dist/CodeMode.d.mts +0 -5
  558. package/dist/CodeMode.mjs +0 -10
  559. package/dist/CodeMode.mjs.map +0 -1
  560. package/dist/Commands.d.mts +0 -5
  561. package/dist/Commands.mjs +0 -10
  562. package/dist/Commands.mjs.map +0 -1
  563. package/dist/Compaction.d.mts +0 -5
  564. package/dist/Compaction.mjs +0 -10
  565. package/dist/Compaction.mjs.map +0 -1
  566. package/dist/ContextCompactor.d.mts +0 -5
  567. package/dist/ContextCompactor.mjs +0 -10
  568. package/dist/ContextCompactor.mjs.map +0 -1
  569. package/dist/ContextHistory.d.mts +0 -5
  570. package/dist/ContextHistory.mjs +0 -10
  571. package/dist/ContextHistory.mjs.map +0 -1
  572. package/dist/ContextTools.d.mts +0 -5
  573. package/dist/ContextTools.mjs +0 -10
  574. package/dist/ContextTools.mjs.map +0 -1
  575. package/dist/ContextWindow.d.mts +0 -5
  576. package/dist/ContextWindow.mjs +0 -10
  577. package/dist/ContextWindow.mjs.map +0 -1
  578. package/dist/DurableStep.d.mts +0 -5
  579. package/dist/DurableStep.mjs +0 -10
  580. package/dist/DurableStep.mjs.map +0 -1
  581. package/dist/EphemeralThreads.d.mts +0 -5
  582. package/dist/EphemeralThreads.mjs +0 -10
  583. package/dist/EphemeralThreads.mjs.map +0 -1
  584. package/dist/IdGenerator.d.mts +0 -5
  585. package/dist/IdGenerator.mjs +0 -10
  586. package/dist/IdGenerator.mjs.map +0 -1
  587. package/dist/Identifiers.d.mts +0 -5
  588. package/dist/Identifiers.mjs +0 -10
  589. package/dist/Identifiers.mjs.map +0 -1
  590. package/dist/Mcp.d.mts +0 -5
  591. package/dist/Mcp.mjs +0 -10
  592. package/dist/Mcp.mjs.map +0 -1
  593. package/dist/McpClient.d.mts +0 -5
  594. package/dist/McpClient.mjs +0 -10
  595. package/dist/McpClient.mjs.map +0 -1
  596. package/dist/Memory.d.mts +0 -5
  597. package/dist/Memory.mjs +0 -10
  598. package/dist/Memory.mjs.map +0 -1
  599. package/dist/MemoryNamespace.d.mts +0 -5
  600. package/dist/MemoryNamespace.mjs +0 -10
  601. package/dist/MemoryNamespace.mjs.map +0 -1
  602. package/dist/MemoryNotes.d.mts +0 -5
  603. package/dist/MemoryNotes.mjs +0 -10
  604. package/dist/MemoryNotes.mjs.map +0 -1
  605. package/dist/MemoryReference.d.mts +0 -5
  606. package/dist/MemoryReference.mjs +0 -10
  607. package/dist/MemoryReference.mjs.map +0 -1
  608. package/dist/MemoryRevalidation.d.mts +0 -5
  609. package/dist/MemoryRevalidation.mjs +0 -10
  610. package/dist/MemoryRevalidation.mjs.map +0 -1
  611. package/dist/MemoryStore.d.mts +0 -5
  612. package/dist/MemoryStore.mjs +0 -10
  613. package/dist/MemoryStore.mjs.map +0 -1
  614. package/dist/Messaging.d.mts +0 -5
  615. package/dist/Messaging.mjs +0 -10
  616. package/dist/Messaging.mjs.map +0 -1
  617. package/dist/MessagingHost.d.mts +0 -5
  618. package/dist/MessagingHost.mjs +0 -10
  619. package/dist/MessagingHost.mjs.map +0 -1
  620. package/dist/ModelContext.d.mts +0 -5
  621. package/dist/ModelContext.mjs +0 -10
  622. package/dist/ModelContext.mjs.map +0 -1
  623. package/dist/Receipt.d.mts +0 -5
  624. package/dist/Receipt.mjs +0 -10
  625. package/dist/Receipt.mjs.map +0 -1
  626. package/dist/Redaction.d.mts +0 -5
  627. package/dist/Redaction.mjs +0 -10
  628. package/dist/Redaction.mjs.map +0 -1
  629. package/dist/Remembering.d.mts +0 -5
  630. package/dist/Remembering.mjs +0 -10
  631. package/dist/Remembering.mjs.map +0 -1
  632. package/dist/RememberingStore.d.mts +0 -5
  633. package/dist/RememberingStore.mjs +0 -10
  634. package/dist/RememberingStore.mjs.map +0 -1
  635. package/dist/RunEvent.d.mts +0 -5
  636. package/dist/RunEvent.mjs +0 -10
  637. package/dist/RunEvent.mjs.map +0 -1
  638. package/dist/RunEventSink.d.mts +0 -5
  639. package/dist/RunEventSink.mjs +0 -10
  640. package/dist/RunEventSink.mjs.map +0 -1
  641. package/dist/RunHooks.d.mts +0 -5
  642. package/dist/RunHooks.mjs +0 -10
  643. package/dist/RunHooks.mjs.map +0 -1
  644. package/dist/RunOptions.d.mts +0 -5
  645. package/dist/RunOptions.mjs +0 -10
  646. package/dist/RunOptions.mjs.map +0 -1
  647. package/dist/RunPolicyUsage.d.mts +0 -5
  648. package/dist/RunPolicyUsage.mjs +0 -10
  649. package/dist/RunPolicyUsage.mjs.map +0 -1
  650. package/dist/SemanticMemory.d.mts +0 -5
  651. package/dist/SemanticMemory.mjs +0 -10
  652. package/dist/SemanticMemory.mjs.map +0 -1
  653. package/dist/SemanticMemoryIndex.d.mts +0 -5
  654. package/dist/SemanticMemoryIndex.mjs +0 -10
  655. package/dist/SemanticMemoryIndex.mjs.map +0 -1
  656. package/dist/SemanticMemoryRevalidation.d.mts +0 -5
  657. package/dist/SemanticMemoryRevalidation.mjs +0 -10
  658. package/dist/SemanticMemoryRevalidation.mjs.map +0 -1
  659. package/dist/Subagent.d.mts +0 -5
  660. package/dist/Subagent.mjs +0 -10
  661. package/dist/Subagent.mjs.map +0 -1
  662. package/dist/SubagentContract.d.mts +0 -5
  663. package/dist/SubagentContract.mjs +0 -10
  664. package/dist/SubagentContract.mjs.map +0 -1
  665. package/dist/SubagentHost.d.mts +0 -5
  666. package/dist/SubagentHost.mjs +0 -10
  667. package/dist/SubagentHost.mjs.map +0 -1
  668. package/dist/SubagentReservations.d.mts +0 -5
  669. package/dist/SubagentReservations.mjs +0 -10
  670. package/dist/SubagentReservations.mjs.map +0 -1
  671. package/dist/ThreadHistory.d.mts +0 -5
  672. package/dist/ThreadHistory.mjs +0 -10
  673. package/dist/ThreadHistory.mjs.map +0 -1
  674. package/dist/ToolBroker.d.mts +0 -5
  675. package/dist/ToolBroker.mjs +0 -10
  676. package/dist/ToolBroker.mjs.map +0 -1
  677. package/dist/ToolDiscovery.d.mts +0 -5
  678. package/dist/ToolDiscovery.mjs +0 -10
  679. package/dist/ToolDiscovery.mjs.map +0 -1
  680. package/dist/ToolResult.d.mts +0 -5
  681. package/dist/ToolResult.mjs +0 -10
  682. package/dist/ToolResult.mjs.map +0 -1
  683. package/dist/Usage.d.mts +0 -5
  684. package/dist/Usage.mjs +0 -10
  685. package/dist/Usage.mjs.map +0 -1
  686. package/dist/WebCapture.d.mts +0 -5
  687. package/dist/WebCapture.mjs +0 -10
  688. package/dist/WebCapture.mjs.map +0 -1
  689. package/dist/WebSearch.d.mts +0 -5
  690. package/dist/WebSearch.mjs +0 -10
  691. package/dist/WebSearch.mjs.map +0 -1
  692. package/dist/Worker.d.mts +0 -5
  693. package/dist/Worker.mjs +0 -10
  694. package/dist/Worker.mjs.map +0 -1
  695. package/dist/rolldown-runtime-BBjsoOtd.mjs +0 -27
  696. package/src/Agent.ts +0 -1
  697. package/src/AgentError.ts +0 -1
  698. package/src/AgentPolicy.ts +0 -1
  699. package/src/AgentRuntime.ts +0 -1
  700. package/src/Approval.ts +0 -1
  701. package/src/Budget.ts +0 -1
  702. package/src/CodeMode.ts +0 -1
  703. package/src/Commands.ts +0 -1
  704. package/src/Compaction.ts +0 -1
  705. package/src/ContextCompactor.ts +0 -1
  706. package/src/ContextHistory.ts +0 -1
  707. package/src/ContextTools.ts +0 -1
  708. package/src/ContextWindow.ts +0 -1
  709. package/src/DurableStep.ts +0 -1
  710. package/src/EphemeralThreads.ts +0 -1
  711. package/src/IdGenerator.ts +0 -1
  712. package/src/Identifiers.ts +0 -1
  713. package/src/Mcp.ts +0 -1
  714. package/src/McpClient.ts +0 -1
  715. package/src/Memory.ts +0 -1
  716. package/src/MemoryNamespace.ts +0 -1
  717. package/src/MemoryNotes.ts +0 -1
  718. package/src/MemoryReference.ts +0 -1
  719. package/src/MemoryRevalidation.ts +0 -1
  720. package/src/MemoryStore.ts +0 -1
  721. package/src/Messaging.ts +0 -1
  722. package/src/MessagingHost.ts +0 -1
  723. package/src/ModelContext.ts +0 -1
  724. package/src/Receipt.ts +0 -1
  725. package/src/Redaction.ts +0 -1
  726. package/src/Remembering.ts +0 -1
  727. package/src/RememberingStore.ts +0 -1
  728. package/src/RunEvent.ts +0 -1
  729. package/src/RunEventSink.ts +0 -1
  730. package/src/RunHooks.ts +0 -1
  731. package/src/RunOptions.ts +0 -1
  732. package/src/RunPolicyUsage.ts +0 -1
  733. package/src/SemanticMemory.ts +0 -1
  734. package/src/SemanticMemoryIndex.ts +0 -1
  735. package/src/SemanticMemoryRevalidation.ts +0 -1
  736. package/src/Subagent.ts +0 -1
  737. package/src/SubagentContract.ts +0 -1
  738. package/src/SubagentHost.ts +0 -1
  739. package/src/SubagentReservations.ts +0 -1
  740. package/src/ThreadHistory.ts +0 -1
  741. package/src/ToolBroker.ts +0 -1
  742. package/src/ToolDiscovery.ts +0 -1
  743. package/src/ToolResult.ts +0 -1
  744. package/src/Usage.ts +0 -1
  745. package/src/WebCapture.ts +0 -1
  746. package/src/WebSearch.ts +0 -1
  747. package/src/Worker.ts +0 -1
@@ -0,0 +1,1440 @@
1
+ import { Clock, Context, Effect, Result, Schema } from "effect";
2
+ import * as SqlClientService from "effect/unstable/sql/SqlClient";
3
+ import type { SqlError } from "effect/unstable/sql/SqlError";
4
+
5
+ import { Digest } from "./Records.ts";
6
+ import {
7
+ AcceptedEvent,
8
+ DeliveryChange,
9
+ SubscriptionChange,
10
+ SubscriptionRetentionPolicy,
11
+ type SourcePartition,
12
+ SubscriptionDelivery,
13
+ SubscriptionDeliveryKey,
14
+ SubscriptionError,
15
+ SubscriptionFailpoint,
16
+ type SubscriptionFailpointError,
17
+ SubscriptionKey,
18
+ SubscriptionLimits,
19
+ SubscriptionName,
20
+ SubscriptionRecord,
21
+ SubscriptionScanCursors,
22
+ SubscriptionStore,
23
+ subscriptionDeliveryKeyString,
24
+ } from "./Subscription.ts";
25
+ import {
26
+ applySubscriptionDeliveryChange,
27
+ applySubscriptionChange,
28
+ validateEventRetention,
29
+ sameAcceptedEventIdentity,
30
+ sameSourcePartition,
31
+ subscriptionCanSelect,
32
+ subscriptionDeliveryCanSelect,
33
+ } from "./SubscriptionTransition.ts";
34
+
35
+ const CountRow = Schema.Struct({ count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) });
36
+ const SequenceRow = Schema.Struct({ sequence: Schema.Natural });
37
+
38
+ const ScanRow = Schema.Struct({
39
+ event_scan_cursor: Schema.String,
40
+ delivery_scan_cursor: Schema.String,
41
+ recovery_scan_cursor: Schema.Natural,
42
+ });
43
+
44
+ const error = (reason: SubscriptionError["reason"], code: string) =>
45
+ SubscriptionError.make({ reason, code });
46
+
47
+ const unavailable = (operation: string) => error("storage", operation);
48
+ const corrupt = (operation: string) => error("corrupt", operation);
49
+ const bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).byteLength;
50
+
51
+ const validate = <A, I>(schema: Schema.Codec<A, I>, value: unknown, code: string) =>
52
+ Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => error("validation", code)));
53
+
54
+ const encode = <A, I>(schema: Schema.Codec<A, I>, value: A, code: string) =>
55
+ Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(
56
+ Effect.mapError(() => corrupt(code)),
57
+ );
58
+
59
+ const decode = <A, I>(schema: Schema.Codec<A, I>, value: string, code: string) =>
60
+ Schema.decodeEffect(Schema.fromJsonString(schema))(value).pipe(
61
+ Effect.mapError(() => corrupt(code)),
62
+ );
63
+
64
+ const decodeRows = <A, I>(schema: Schema.Codec<A, I>, rows: unknown, code: string) =>
65
+ Schema.decodeUnknownEffect(Schema.Array(schema))(rows).pipe(Effect.mapError(() => corrupt(code)));
66
+
67
+ const sameDeliveryIdentity = (left: SubscriptionDelivery, right: SubscriptionDelivery): boolean =>
68
+ subscriptionDeliveryKeyString(left.key) === subscriptionDeliveryKeyString(right.key) &&
69
+ left.deliveryId === right.deliveryId &&
70
+ left.source.name === right.source.name &&
71
+ left.source.version === right.source.version &&
72
+ left.threadId === right.threadId &&
73
+ left.admissionKey === right.admissionKey &&
74
+ left.subscriptionFingerprint === right.subscriptionFingerprint &&
75
+ left.eventDigest === right.eventDigest;
76
+
77
+ /** Adapter-specific storage limits. */
78
+ export interface SqlSubscriptionStoreOptions {
79
+ /** Stored JSON decoder ceiling in UTF-16 code units; admission byte limits remain separate. */
80
+ readonly maxStoredJsonLength: number;
81
+ }
82
+
83
+ /**
84
+ * Adapter-owned atomic transaction on the store's SqlClient, including any native alarm update.
85
+ * Return only after commit; a failed body must leave its writes uncommitted. Before-mutation
86
+ * failpoints run inside the body, and after-mutation failpoints run after this operation returns.
87
+ */
88
+ export class SqlSubscriptionTransaction extends Context.Service<
89
+ SqlSubscriptionTransaction,
90
+ {
91
+ readonly run: <A>(
92
+ body: Effect.Effect<A, SubscriptionError | SubscriptionFailpointError>,
93
+ ) => Effect.Effect<A, SubscriptionError | SubscriptionFailpointError>;
94
+ }
95
+ >()("@effect-agent/thread/SqlSubscriptionTransaction") {}
96
+
97
+ /**
98
+ * Shared SQLite subscription operations over an existing SqlClient. The adapter validates the
99
+ * partition, initializes its tables, and provides SqlSubscriptionTransaction at construction.
100
+ * The returned methods capture the SQL client, transaction service, and failpoint handler.
101
+ * Cloudflare's transaction also updates its native alarm before committing.
102
+ */
103
+ export const makeSqlSubscriptionStore = Effect.fn("SqlSubscriptionStore.make")(function* (
104
+ partition: SourcePartition,
105
+ options: SqlSubscriptionStoreOptions,
106
+ ): Effect.fn.Return<
107
+ SubscriptionStore["Service"],
108
+ SubscriptionError,
109
+ SqlClientService.SqlClient | SqlSubscriptionTransaction
110
+ > {
111
+ const sql = yield* SqlClientService.SqlClient;
112
+ const failpoint = yield* SubscriptionFailpoint;
113
+ const transactions = yield* SqlSubscriptionTransaction;
114
+ const StoredJson = Schema.String.check(Schema.isMaxLength(options.maxStoredJsonLength));
115
+
116
+ const JsonRow = Schema.Struct({ record_json: StoredJson });
117
+
118
+ const RegistrationRow = Schema.Struct({
119
+ owner_id: Schema.String,
120
+ subscription_id: Schema.String,
121
+ ordinal: Schema.Natural,
122
+ source_name: Schema.String,
123
+ source_version: Schema.String,
124
+ matching_key: Schema.String,
125
+ state: SubscriptionRecord.fields.state,
126
+ expires_at_millis: Schema.NullOr(Schema.Number),
127
+ recovery_at_millis: Schema.NullOr(Schema.Number),
128
+ recovery_present: Schema.Literals([0, 1]),
129
+ record_json: StoredJson,
130
+ });
131
+
132
+ const EventRow = Schema.Struct({
133
+ event_id: Schema.String,
134
+ source_name: Schema.String,
135
+ source_version: Schema.String,
136
+ matching_key: Schema.String,
137
+ payload_digest: Digest,
138
+ cutoff: Schema.Natural,
139
+ cursor: Schema.Natural,
140
+ routing_complete: Schema.Number,
141
+ tombstone: Schema.Literals([0, 1]),
142
+ next_attempt_at_millis: Schema.Number,
143
+ record_json: StoredJson,
144
+ });
145
+
146
+ const DeliveryRow = Schema.Struct({
147
+ owner_id: Schema.String,
148
+ subscription_id: Schema.String,
149
+ event_id: Schema.String,
150
+ delivery_key: Schema.String,
151
+ state: SubscriptionDelivery.fields.state,
152
+ next_attempt_at_millis: Schema.Number,
153
+ record_json: StoredJson,
154
+ });
155
+
156
+ yield* sql`CREATE TABLE IF NOT EXISTS effect_agent_event_retention (
157
+ tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, replay_horizon_millis INTEGER NOT NULL,
158
+ next_maintenance_at_millis INTEGER, tombstone_count INTEGER NOT NULL DEFAULT 0, event_cursor TEXT NOT NULL DEFAULT '', delivery_cursor TEXT NOT NULL DEFAULT '', PRIMARY KEY (tenant_id, source_address)
159
+ )`.pipe(Effect.mapError(() => unavailable("initialize event retention")));
160
+
161
+ yield* sql`
162
+ INSERT INTO effect_agent_subscription_sequences (
163
+ tenant_id, source_address, sequence, event_scan_cursor, delivery_scan_cursor, recovery_scan_cursor
164
+ ) VALUES (${partition.tenantId}, ${partition.address}, 0, '', '', 0) ON CONFLICT DO NOTHING
165
+ `.pipe(Effect.mapError(() => unavailable("initialize subscription partition")));
166
+
167
+ yield* sql`CREATE INDEX IF NOT EXISTS effect_agent_events_retention_order ON effect_agent_subscription_events
168
+ (tenant_id, source_address, tombstone, event_id)
169
+ `.pipe(Effect.mapError(() => unavailable("index event retention")));
170
+ yield* sql`CREATE INDEX IF NOT EXISTS effect_agent_subscriptions_recovery_reference ON effect_agent_subscriptions
171
+ (tenant_id, source_address, source_name, source_version, matching_key, recovery_present)
172
+ WHERE recovery_present=1
173
+ `.pipe(Effect.mapError(() => unavailable("index recovery retention")));
174
+ yield* sql`CREATE INDEX IF NOT EXISTS effect_agent_deliveries_event ON effect_agent_subscription_deliveries
175
+ (tenant_id, source_address, event_id, state)
176
+ `.pipe(Effect.mapError(() => unavailable("index delivery retention")));
177
+
178
+ const query = <A extends object>(
179
+ effect: Effect.Effect<ReadonlyArray<A>, SqlError>,
180
+ code: string,
181
+ ) => effect.pipe(Effect.mapError(() => unavailable(code)));
182
+
183
+ const requirePartition = (candidate: SourcePartition, code: string) =>
184
+ sameSourcePartition(candidate, partition)
185
+ ? Effect.void
186
+ : Effect.fail(error("validation", code));
187
+
188
+ const requireKey = Effect.fn("SqlSubscriptionStore.requireKey")(function* (
189
+ input: SubscriptionKey,
190
+ code: string,
191
+ ) {
192
+ const key = yield* validate(SubscriptionKey, input, code);
193
+
194
+ yield* requirePartition(key.partition, code);
195
+
196
+ return key;
197
+ });
198
+
199
+ const readRegistration = Effect.fn("SqlSubscriptionStore.readRegistration")(function* (
200
+ key: SubscriptionKey,
201
+ code: string,
202
+ ) {
203
+ const rows = yield* query(
204
+ sql<Record<string, unknown>>`
205
+ SELECT owner_id, subscription_id, ordinal, source_name, source_version, matching_key, state,
206
+ expires_at_millis, recovery_at_millis, recovery_present, record_json FROM effect_agent_subscriptions
207
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
208
+ AND owner_id=${key.ownerId} AND subscription_id=${key.subscriptionId}
209
+ `,
210
+ code,
211
+ );
212
+
213
+ const decodedRows = yield* decodeRows(RegistrationRow, rows, code);
214
+
215
+ if (decodedRows.length > 1) return yield* corrupt(code);
216
+ const row = decodedRows[0];
217
+
218
+ if (row === undefined) return null;
219
+ const record = yield* decode(SubscriptionRecord, row.record_json, code);
220
+
221
+ if (
222
+ !sameSourcePartition(record.key.partition, partition) ||
223
+ record.key.ownerId !== row.owner_id ||
224
+ record.key.subscriptionId !== row.subscription_id ||
225
+ record.ordinal !== row.ordinal ||
226
+ record.configuration.source.name !== row.source_name ||
227
+ record.configuration.source.version !== row.source_version ||
228
+ record.configuration.matchingKey !== row.matching_key ||
229
+ record.state !== row.state ||
230
+ record.configuration.expiresAtMillis !== row.expires_at_millis ||
231
+ (record.recovery?.nextAttemptAtMillis ?? null) !== row.recovery_at_millis ||
232
+ (record.recovery === null ? 0 : 1) !== row.recovery_present
233
+ )
234
+ return yield* corrupt(`${code}-projection`);
235
+
236
+ return record;
237
+ });
238
+
239
+ const readEvent = Effect.fn("SqlSubscriptionStore.readEvent")(function* (
240
+ eventId: string,
241
+ code: string,
242
+ ) {
243
+ const rows = yield* query(
244
+ sql<Record<string, unknown>>`
245
+ SELECT event_id, source_name, source_version, matching_key, payload_digest, cutoff, cursor,
246
+ routing_complete, tombstone, next_attempt_at_millis, record_json FROM effect_agent_subscription_events
247
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND event_id=${eventId}
248
+ `,
249
+ code,
250
+ );
251
+
252
+ const decodedRows = yield* decodeRows(EventRow, rows, code);
253
+
254
+ if (decodedRows.length > 1) return yield* corrupt(code);
255
+ const row = decodedRows[0];
256
+
257
+ if (row === undefined) return null;
258
+ const event = yield* decode(AcceptedEvent, row.record_json, code);
259
+
260
+ if (
261
+ !sameSourcePartition(event.partition, partition) ||
262
+ event.eventId !== row.event_id ||
263
+ event.source.name !== row.source_name ||
264
+ event.source.version !== row.source_version ||
265
+ event.matchingKey !== row.matching_key ||
266
+ event.payloadDigest !== row.payload_digest ||
267
+ event.cutoff !== row.cutoff ||
268
+ event.cursor !== row.cursor ||
269
+ (event.routingComplete ? 1 : 0) !== row.routing_complete ||
270
+ (event.tombstone === true ? 1 : 0) !== row.tombstone ||
271
+ event.nextAttemptAtMillis !== row.next_attempt_at_millis
272
+ )
273
+ return yield* corrupt(`${code}-projection`);
274
+
275
+ return event;
276
+ });
277
+
278
+ const readDelivery = Effect.fn("SqlSubscriptionStore.readDelivery")(function* (
279
+ key: SubscriptionDeliveryKey,
280
+ code: string,
281
+ ) {
282
+ const rows = yield* query(
283
+ sql<Record<string, unknown>>`
284
+ SELECT owner_id, subscription_id, event_id, delivery_key, state, next_attempt_at_millis, record_json
285
+ FROM effect_agent_subscription_deliveries
286
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
287
+ AND owner_id=${key.subscription.ownerId} AND subscription_id=${key.subscription.subscriptionId}
288
+ AND event_id=${key.eventId}
289
+ `,
290
+ code,
291
+ );
292
+
293
+ const decodedRows = yield* decodeRows(DeliveryRow, rows, code);
294
+
295
+ if (decodedRows.length > 1) return yield* corrupt(code);
296
+ const row = decodedRows[0];
297
+
298
+ if (row === undefined) return null;
299
+ const delivery = yield* decode(SubscriptionDelivery, row.record_json, code);
300
+
301
+ if (
302
+ !sameSourcePartition(delivery.key.subscription.partition, partition) ||
303
+ delivery.key.subscription.ownerId !== row.owner_id ||
304
+ delivery.key.subscription.subscriptionId !== row.subscription_id ||
305
+ delivery.key.eventId !== row.event_id ||
306
+ subscriptionDeliveryKeyString(delivery.key) !== row.delivery_key ||
307
+ delivery.state !== row.state ||
308
+ delivery.retry.nextAttemptAtMillis !== row.next_attempt_at_millis
309
+ )
310
+ return yield* corrupt(`${code}-projection`);
311
+
312
+ return delivery;
313
+ });
314
+
315
+ const count = Effect.fn("SqlSubscriptionStore.count")(function* (
316
+ statement: Effect.Effect<ReadonlyArray<Record<string, unknown>>, SqlError>,
317
+ code: string,
318
+ ) {
319
+ const rows = yield* query(statement, code);
320
+ const decoded = yield* decodeRows(CountRow, rows, code);
321
+
322
+ if (decoded.length !== 1) return yield* corrupt(code);
323
+
324
+ return decoded[0].count;
325
+ });
326
+
327
+ const nextSequence = Effect.fn("SqlSubscriptionStore.nextSequence")(function* () {
328
+ const rows = yield* query(
329
+ sql<Record<string, unknown>>`
330
+ UPDATE effect_agent_subscription_sequences SET sequence=sequence+1
331
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
332
+ RETURNING sequence
333
+ `,
334
+ "advance subscription sequence",
335
+ );
336
+
337
+ const decoded = yield* decodeRows(SequenceRow, rows, "advance subscription sequence");
338
+
339
+ if (decoded.length !== 1) return yield* corrupt("subscription sequence");
340
+
341
+ return decoded[0].sequence;
342
+ });
343
+
344
+ const writeRegistration = Effect.fn("SqlSubscriptionStore.writeRegistration")(function* (
345
+ record: SubscriptionRecord,
346
+ ) {
347
+ const json = yield* encode(SubscriptionRecord, record, "encode subscription");
348
+
349
+ yield* query(
350
+ sql<Record<string, unknown>>`
351
+ UPDATE effect_agent_subscriptions SET ordinal=${record.ordinal}, source_name=${record.configuration.source.name},
352
+ source_version=${record.configuration.source.version}, matching_key=${record.configuration.matchingKey}, state=${record.state}, expires_at_millis=${record.configuration.expiresAtMillis},
353
+ recovery_at_millis=${record.recovery?.nextAttemptAtMillis ?? null}, recovery_present=${record.recovery === null ? 0 : 1}, record_json=${json}
354
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
355
+ AND owner_id=${record.key.ownerId} AND subscription_id=${record.key.subscriptionId}
356
+ `,
357
+ "write subscription",
358
+ );
359
+ });
360
+
361
+ const writeEvent = Effect.fn("SqlSubscriptionStore.writeEvent")(function* (event: AcceptedEvent) {
362
+ const json = yield* encode(AcceptedEvent, event, "encode event");
363
+
364
+ yield* query(
365
+ sql<Record<string, unknown>>`
366
+ UPDATE effect_agent_subscription_events SET cursor=${event.cursor}, routing_complete=${event.routingComplete ? 1 : 0}, tombstone=${event.tombstone === true ? 1 : 0},
367
+ next_attempt_at_millis=${event.nextAttemptAtMillis}, record_json=${json}
368
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND event_id=${event.eventId}
369
+ `,
370
+ "write event",
371
+ );
372
+ });
373
+
374
+ const writeDelivery = Effect.fn("SqlSubscriptionStore.writeDelivery")(function* (
375
+ delivery: SubscriptionDelivery,
376
+ ) {
377
+ const json = yield* encode(SubscriptionDelivery, delivery, "encode delivery");
378
+
379
+ yield* query(
380
+ sql<Record<string, unknown>>`
381
+ UPDATE effect_agent_subscription_deliveries SET state=${delivery.state},
382
+ next_attempt_at_millis=${delivery.retry.nextAttemptAtMillis}, record_json=${json}
383
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
384
+ AND owner_id=${delivery.key.subscription.ownerId} AND subscription_id=${delivery.key.subscription.subscriptionId}
385
+ AND event_id=${delivery.key.eventId}
386
+ `,
387
+ "write delivery",
388
+ );
389
+ });
390
+
391
+ const register: SubscriptionStore["Service"]["register"] = Effect.fn(
392
+ "SqlSubscriptionStore.register",
393
+ )(function* (input, inputLimits) {
394
+ const record = yield* validate(SubscriptionRecord, input, "register-record");
395
+ const limits = yield* validate(SubscriptionLimits, inputLimits, "register-limits");
396
+
397
+ yield* requirePartition(record.key.partition, "register-partition");
398
+
399
+ const result = yield* transactions.run(
400
+ Effect.gen(function* () {
401
+ const existing = yield* readRegistration(record.key, "register-existing");
402
+
403
+ if (existing !== null) {
404
+ if (existing.creationFingerprint !== record.creationFingerprint)
405
+ return yield* error("conflict", "registration-identity");
406
+
407
+ return { value: existing, changed: false } as const;
408
+ }
409
+ if (bytes(record.configuration.context) > limits.maxContextBytes)
410
+ return yield* error("capacity", "context-bytes");
411
+ if (bytes(record.configuration.parameters) > limits.maxPayloadBytes)
412
+ return yield* error("capacity", "parameters-bytes");
413
+ if (
414
+ record.configuration.expiresAtMillis !== null &&
415
+ record.configuration.expiresAtMillis - record.createdAtMillis > limits.maxLifetimeMillis
416
+ )
417
+ return yield* error("capacity", "lifetime");
418
+ if (
419
+ (yield* count(
420
+ sql<
421
+ Record<string, unknown>
422
+ >`SELECT COUNT(*) AS count FROM effect_agent_subscriptions WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,
423
+ "count registrations",
424
+ )) >= limits.maxRegistrations
425
+ )
426
+ return yield* error("capacity", "registrations");
427
+ if (
428
+ (yield* count(
429
+ sql<
430
+ Record<string, unknown>
431
+ >`SELECT COUNT(*) AS count FROM effect_agent_subscriptions WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND owner_id=${record.key.ownerId}`,
432
+ "count owner registrations",
433
+ )) >= limits.maxRegistrationsPerOwner
434
+ )
435
+ return yield* error("capacity", "owner-registrations");
436
+ const assigned = { ...record, ordinal: yield* nextSequence() };
437
+ const json = yield* encode(SubscriptionRecord, assigned, "encode registration");
438
+
439
+ yield* failpoint.hit("subscription:register:before");
440
+ yield* query(
441
+ sql<Record<string, unknown>>`
442
+ INSERT INTO effect_agent_subscriptions (tenant_id, source_address, owner_id, subscription_id, ordinal,
443
+ source_name, source_version, matching_key, state, expires_at_millis, recovery_at_millis, recovery_present, record_json)
444
+ VALUES (${partition.tenantId}, ${partition.address}, ${assigned.key.ownerId}, ${assigned.key.subscriptionId}, ${assigned.ordinal},
445
+ ${assigned.configuration.source.name}, ${assigned.configuration.source.version}, ${assigned.configuration.matchingKey}, ${assigned.state},
446
+ ${assigned.configuration.expiresAtMillis}, ${assigned.recovery?.nextAttemptAtMillis ?? null}, ${assigned.recovery === null ? 0 : 1}, ${json})
447
+ `,
448
+ "insert registration",
449
+ );
450
+
451
+ return { value: assigned, changed: true } as const;
452
+ }),
453
+ );
454
+
455
+ if (result.changed) yield* failpoint.hit("subscription:register:after");
456
+
457
+ return result.value;
458
+ });
459
+
460
+ const get: SubscriptionStore["Service"]["get"] = Effect.fn("SqlSubscriptionStore.get")(
461
+ function* (input) {
462
+ return yield* readRegistration(yield* requireKey(input, "get-key"), "get subscription");
463
+ },
464
+ );
465
+
466
+ const list: SubscriptionStore["Service"]["list"] = Effect.fn("SqlSubscriptionStore.list")(
467
+ function* (ownerId, after, limit) {
468
+ const rows = yield* query(
469
+ sql<Record<string, unknown>>`
470
+ SELECT owner_id, subscription_id, ordinal FROM effect_agent_subscriptions WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
471
+ AND owner_id=${ownerId} AND ordinal>${after} ORDER BY ordinal LIMIT ${limit}
472
+ `,
473
+ "list subscriptions",
474
+ );
475
+
476
+ const decoded = yield* decodeRows(
477
+ Schema.Struct({
478
+ owner_id: Schema.String,
479
+ subscription_id: Schema.String,
480
+ ordinal: Schema.Natural,
481
+ }),
482
+ rows,
483
+ "list subscriptions",
484
+ );
485
+
486
+ return yield* Effect.forEach(
487
+ decoded,
488
+ Effect.fn("SqlSubscriptionStore.listRecord")(function* (row) {
489
+ const record = yield* readRegistration(
490
+ { partition, ownerId: row.owner_id, subscriptionId: row.subscription_id },
491
+ "list subscription",
492
+ );
493
+
494
+ if (record === null || record.ordinal !== row.ordinal)
495
+ return yield* corrupt("list subscription projection");
496
+
497
+ return record;
498
+ }),
499
+ );
500
+ },
501
+ );
502
+
503
+ const change: SubscriptionStore["Service"]["change"] = Effect.fn("SubscriptionStore.change")(
504
+ function* (input, expectedRevision, inputChange) {
505
+ const key = yield* requireKey(input, "change-key");
506
+ const change = yield* validate(SubscriptionChange, inputChange, "change");
507
+
508
+ yield* validate(Schema.Int.check(Schema.isGreaterThan(0)), expectedRevision, "revision");
509
+
510
+ const updated = yield* transactions.run(
511
+ Effect.gen(function* () {
512
+ const existing = yield* readRegistration(key, "change-registration");
513
+
514
+ if (existing === null) return yield* error("not-found", "subscription");
515
+ yield* failpoint.hit("subscription:change:before");
516
+
517
+ const revised = yield* Effect.fromResult(
518
+ applySubscriptionChange(existing, expectedRevision, change),
519
+ );
520
+
521
+ const updated = { ...revised, ordinal: yield* nextSequence() };
522
+
523
+ yield* writeRegistration(updated);
524
+
525
+ return updated;
526
+ }),
527
+ );
528
+
529
+ yield* failpoint.hit("subscription:change:after");
530
+
531
+ return updated;
532
+ },
533
+ );
534
+
535
+ const cancel: SubscriptionStore["Service"]["cancel"] = Effect.fn("SqlSubscriptionStore.cancel")(
536
+ function* (input, expectedRevision) {
537
+ const key = yield* requireKey(input, "cancel-key");
538
+
539
+ const result = yield* transactions.run(
540
+ Effect.gen(function* () {
541
+ const current = yield* readRegistration(key, "cancel subscription");
542
+
543
+ if (current === null) return yield* error("not-found", "subscription");
544
+ if (
545
+ expectedRevision !== undefined &&
546
+ expectedRevision !== current.configurationRevision &&
547
+ !(
548
+ current.state === "cancelled" &&
549
+ expectedRevision + 1 === current.configurationRevision
550
+ )
551
+ )
552
+ return yield* SubscriptionError.make({
553
+ reason: "conflict",
554
+ code: "configuration-revision",
555
+ currentRevision: current.configurationRevision,
556
+ currentState: current.state,
557
+ });
558
+ if (current.state === "cancelled") return { value: current, changed: false } as const;
559
+
560
+ const updated = {
561
+ ...current,
562
+ configurationRevision: current.configurationRevision + 1,
563
+ state: "cancelled" as const,
564
+ recovery: null,
565
+ };
566
+
567
+ yield* failpoint.hit("subscription:cancel:before");
568
+ yield* writeRegistration(updated);
569
+
570
+ return { value: updated, changed: true } as const;
571
+ }),
572
+ );
573
+
574
+ if (result.changed) yield* failpoint.hit("subscription:cancel:after");
575
+
576
+ return result.value;
577
+ },
578
+ );
579
+
580
+ const accept: SubscriptionStore["Service"]["accept"] = Effect.fn("SqlSubscriptionStore.accept")(
581
+ function* (input, inputLimits) {
582
+ const event = yield* validate(AcceptedEvent, input, "accept-event");
583
+ const limits = yield* validate(SubscriptionLimits, inputLimits, "accept-limits");
584
+
585
+ yield* requirePartition(event.partition, "accept-partition");
586
+
587
+ const result = yield* transactions.run(
588
+ Effect.gen(function* () {
589
+ const existing = yield* readEvent(event.eventId, "accept event");
590
+
591
+ if (existing !== null) {
592
+ if (!sameAcceptedEventIdentity(existing, event))
593
+ return yield* error("conflict", "event-identity");
594
+
595
+ return { value: existing, changed: false } as const;
596
+ }
597
+ yield* Effect.fromResult(
598
+ validateEventRetention(event, limits, yield* Clock.currentTimeMillis),
599
+ );
600
+
601
+ const retainedPolicies = yield* query(
602
+ sql<
603
+ Record<string, unknown>
604
+ >`SELECT replay_horizon_millis FROM effect_agent_event_retention WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,
605
+ "retained horizon",
606
+ );
607
+
608
+ if (
609
+ retainedPolicies.length > 0 &&
610
+ retainedPolicies[0]?.replay_horizon_millis !== limits.retention?.replayHorizonMillis
611
+ )
612
+ return yield* error("conflict", "retention-horizon");
613
+ if (limits.retention !== undefined) {
614
+ yield* query(
615
+ sql<
616
+ Record<string, unknown>
617
+ >`INSERT INTO effect_agent_event_retention (tenant_id,source_address,replay_horizon_millis,next_maintenance_at_millis)
618
+ VALUES (${partition.tenantId},${partition.address},${limits.retention.replayHorizonMillis},${event.acceptedAtMillis}) ON CONFLICT DO NOTHING`,
619
+ "retain event horizon",
620
+ );
621
+
622
+ const policies = yield* query(
623
+ sql<
624
+ Record<string, unknown>
625
+ >`SELECT replay_horizon_millis FROM effect_agent_event_retention WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,
626
+ "retained event horizon",
627
+ );
628
+
629
+ if (policies[0]?.replay_horizon_millis !== limits.retention.replayHorizonMillis)
630
+ return yield* error("conflict", "retention-horizon");
631
+ }
632
+
633
+ if (bytes(event.payload) > limits.maxPayloadBytes)
634
+ return yield* error("capacity", "payload-bytes");
635
+ if (
636
+ (yield* count(
637
+ sql<
638
+ Record<string, unknown>
639
+ >`SELECT COUNT(*) AS count FROM effect_agent_subscription_events WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND tombstone=0`,
640
+ "count events",
641
+ )) >= limits.maxEvents
642
+ )
643
+ return yield* error("capacity", "events");
644
+
645
+ const accepted: AcceptedEvent = {
646
+ ...event,
647
+ cutoff: yield* nextSequence(),
648
+ cursor: 0,
649
+ routingComplete: false,
650
+ routingFailure: null,
651
+ };
652
+
653
+ const json = yield* encode(AcceptedEvent, accepted, "encode accepted event");
654
+
655
+ yield* failpoint.hit("subscription:accept:before");
656
+ yield* query(
657
+ sql<Record<string, unknown>>`
658
+ INSERT INTO effect_agent_subscription_events (tenant_id, source_address, event_id, source_name, source_version,
659
+ matching_key, payload_digest, cutoff, cursor, routing_complete, next_attempt_at_millis, record_json)
660
+ VALUES (${partition.tenantId}, ${partition.address}, ${accepted.eventId}, ${accepted.source.name}, ${accepted.source.version},
661
+ ${accepted.matchingKey}, ${accepted.payloadDigest}, ${accepted.cutoff}, ${accepted.cursor}, 0, ${accepted.nextAttemptAtMillis}, ${json})
662
+ `,
663
+ "insert event",
664
+ );
665
+
666
+ return { value: accepted, changed: true } as const;
667
+ }),
668
+ );
669
+
670
+ if (result.changed) yield* failpoint.hit("subscription:accept:after");
671
+
672
+ return result.value;
673
+ },
674
+ );
675
+
676
+ const event: SubscriptionStore["Service"]["event"] = Effect.fn("SqlSubscriptionStore.event")(
677
+ (eventId) => readEvent(eventId, "get event"),
678
+ );
679
+
680
+ const pendingEvents: SubscriptionStore["Service"]["pendingEvents"] = Effect.fn(
681
+ "SqlSubscriptionStore.pendingEvents",
682
+ )(function* (nowMillis, after, limit) {
683
+ const rows = yield* query(
684
+ sql<Record<string, unknown>>`
685
+ SELECT event_id FROM effect_agent_subscription_events WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
686
+ AND routing_complete=0 AND next_attempt_at_millis<=${nowMillis} AND event_id>${after} ORDER BY event_id LIMIT ${limit}
687
+ `,
688
+ "pending events",
689
+ );
690
+
691
+ return yield* decodeRows(
692
+ Schema.Struct({ event_id: Schema.String }),
693
+ rows,
694
+ "pending event keys",
695
+ ).pipe(Effect.map((items) => items.map((item) => item.event_id)));
696
+ });
697
+
698
+ const candidates: SubscriptionStore["Service"]["candidates"] = Effect.fn(
699
+ "SqlSubscriptionStore.candidates",
700
+ )(function* (input, limit) {
701
+ const supplied = yield* validate(AcceptedEvent, input, "candidates-event");
702
+
703
+ yield* requirePartition(supplied.partition, "candidates-partition");
704
+ const stored = yield* readEvent(supplied.eventId, "candidates event");
705
+
706
+ if (stored === null) return yield* error("not-found", "event");
707
+ if (!sameAcceptedEventIdentity(stored, supplied)) return yield* error("conflict", "event");
708
+
709
+ const rows = yield* query(
710
+ sql<Record<string, unknown>>`
711
+ SELECT owner_id, subscription_id, ordinal FROM effect_agent_subscriptions WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
712
+ AND source_name=${stored.source.name} AND source_version=${stored.source.version} AND matching_key=${stored.matchingKey}
713
+ AND ordinal>${stored.cursor} AND ordinal<=${stored.cutoff} ORDER BY ordinal LIMIT ${limit}
714
+ `,
715
+ "subscription candidates",
716
+ );
717
+
718
+ const decoded = yield* decodeRows(
719
+ Schema.Struct({
720
+ owner_id: Schema.String,
721
+ subscription_id: Schema.String,
722
+ ordinal: Schema.Natural,
723
+ }),
724
+ rows,
725
+ "subscription candidates",
726
+ );
727
+
728
+ return yield* Effect.forEach(
729
+ decoded,
730
+ Effect.fn("SqlSubscriptionStore.candidateRecord")(function* (row) {
731
+ const record = yield* readRegistration(
732
+ { partition, ownerId: row.owner_id, subscriptionId: row.subscription_id },
733
+ "subscription candidate",
734
+ );
735
+
736
+ if (record === null || record.ordinal !== row.ordinal)
737
+ return yield* corrupt("subscription candidate projection");
738
+
739
+ return record;
740
+ }),
741
+ );
742
+ });
743
+
744
+ const insertDelivery = Effect.fn("SqlSubscriptionStore.insertDelivery")(function* (
745
+ delivery: SubscriptionDelivery,
746
+ ) {
747
+ const json = yield* encode(SubscriptionDelivery, delivery, "encode selected delivery");
748
+
749
+ yield* query(
750
+ sql<Record<string, unknown>>`
751
+ INSERT INTO effect_agent_subscription_deliveries (tenant_id, source_address, owner_id, subscription_id, event_id,
752
+ delivery_key, state, next_attempt_at_millis, record_json)
753
+ VALUES (${partition.tenantId}, ${partition.address}, ${delivery.key.subscription.ownerId}, ${delivery.key.subscription.subscriptionId},
754
+ ${delivery.key.eventId}, ${subscriptionDeliveryKeyString(delivery.key)}, ${delivery.state}, ${delivery.retry.nextAttemptAtMillis}, ${json})
755
+ `,
756
+ "insert delivery",
757
+ );
758
+ });
759
+
760
+ const select: SubscriptionStore["Service"]["select"] = Effect.fn("SqlSubscriptionStore.select")(
761
+ function* (inputEvent, inputDeliveries, cursor, complete, nowMillis, inputLimits) {
762
+ const supplied = yield* validate(AcceptedEvent, inputEvent, "select-event");
763
+
764
+ const deliveries = yield* validate(
765
+ Schema.Array(SubscriptionDelivery),
766
+ inputDeliveries,
767
+ "select-deliveries",
768
+ );
769
+
770
+ const limits = yield* validate(SubscriptionLimits, inputLimits, "select-limits");
771
+
772
+ yield* requirePartition(supplied.partition, "select-partition");
773
+ for (const candidate of deliveries)
774
+ yield* requirePartition(candidate.key.subscription.partition, "select-delivery-partition");
775
+
776
+ const changed = yield* transactions.run(
777
+ Effect.gen(function* () {
778
+ const accepted = yield* readEvent(supplied.eventId, "select event");
779
+
780
+ if (accepted === null) return yield* error("not-found", "event");
781
+ if (!sameAcceptedEventIdentity(accepted, supplied) || accepted.cursor !== supplied.cursor)
782
+ return yield* error("conflict", "event-cursor");
783
+ if (accepted.routingComplete) return false;
784
+ if (!Number.isSafeInteger(cursor) || cursor < accepted.cursor || cursor > accepted.cutoff)
785
+ return yield* error("validation", "cursor");
786
+ yield* failpoint.hit("subscription:select:before");
787
+ const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis);
788
+
789
+ const additions: Array<{ delivery: SubscriptionDelivery; record: SubscriptionRecord }> =
790
+ [];
791
+
792
+ for (const delivery of deliveries) {
793
+ const record = yield* readRegistration(
794
+ delivery.key.subscription,
795
+ "select registration",
796
+ );
797
+
798
+ if (record === null) return yield* error("not-found", "subscription");
799
+ if (
800
+ !subscriptionDeliveryCanSelect(delivery, record, accepted) ||
801
+ delivery.key.eventId !== accepted.eventId ||
802
+ delivery.source.name !== accepted.source.name ||
803
+ delivery.source.version !== accepted.source.version ||
804
+ record.ordinal <= accepted.cursor ||
805
+ record.ordinal > cursor
806
+ )
807
+ return yield* error("conflict", "selection");
808
+ const existing = yield* readDelivery(delivery.key, "select existing delivery");
809
+
810
+ if (existing !== null) {
811
+ if (!sameDeliveryIdentity(existing, delivery))
812
+ return yield* error("conflict", "delivery-identity");
813
+ continue;
814
+ }
815
+ if (!subscriptionCanSelect(record, accepted, effectiveNowMillis, false)) continue;
816
+ additions.push({ delivery, record });
817
+ }
818
+
819
+ const total = yield* count(
820
+ sql<
821
+ Record<string, unknown>
822
+ >`SELECT COUNT(*) AS count FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,
823
+ "count deliveries",
824
+ );
825
+
826
+ if (total + additions.length > limits.maxDeliveries)
827
+ return yield* error("capacity", "deliveries");
828
+ for (const ownerId of new Set(additions.map(({ record }) => record.key.ownerId))) {
829
+ const existing = yield* count(
830
+ sql<
831
+ Record<string, unknown>
832
+ >`SELECT COUNT(*) AS count FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND owner_id=${ownerId}`,
833
+ "count owner deliveries",
834
+ );
835
+
836
+ if (
837
+ existing + additions.filter(({ record }) => record.key.ownerId === ownerId).length >
838
+ limits.maxDeliveriesPerOwner
839
+ )
840
+ return yield* error("capacity", "owner-deliveries");
841
+ }
842
+ for (const addition of additions) {
843
+ yield* insertDelivery(addition.delivery);
844
+ if (addition.record.configuration.mode === "once")
845
+ yield* writeRegistration({ ...addition.record, state: "consumed", recovery: null });
846
+ }
847
+ yield* writeEvent({
848
+ ...accepted,
849
+ cursor,
850
+ routingComplete: complete,
851
+ routingFailure: null,
852
+ });
853
+
854
+ return true;
855
+ }),
856
+ );
857
+
858
+ if (changed) yield* failpoint.hit("subscription:select:after");
859
+ },
860
+ );
861
+
862
+ const catchUp: SubscriptionStore["Service"]["catchUp"] = Effect.fn(
863
+ "SqlSubscriptionStore.catchUp",
864
+ )(function* (inputEvent, inputDelivery, nowMillis, inputLimits) {
865
+ const supplied = yield* validate(AcceptedEvent, inputEvent, "catch-up-event");
866
+ const delivery = yield* validate(SubscriptionDelivery, inputDelivery, "catch-up-delivery");
867
+ const limits = yield* validate(SubscriptionLimits, inputLimits, "catch-up-limits");
868
+
869
+ yield* requirePartition(supplied.partition, "catch-up-partition");
870
+ yield* requirePartition(delivery.key.subscription.partition, "catch-up-delivery-partition");
871
+
872
+ const changed = yield* transactions.run(
873
+ Effect.gen(function* () {
874
+ const accepted = yield* readEvent(supplied.eventId, "catch-up event");
875
+ const record = yield* readRegistration(delivery.key.subscription, "catch-up subscription");
876
+
877
+ if (accepted === null || record === null)
878
+ return yield* error("not-found", accepted === null ? "event" : "subscription");
879
+ if (
880
+ !sameAcceptedEventIdentity(accepted, supplied) ||
881
+ !subscriptionDeliveryCanSelect(delivery, record, accepted) ||
882
+ delivery.key.eventId !== accepted.eventId ||
883
+ delivery.source.name !== accepted.source.name ||
884
+ delivery.source.version !== accepted.source.version ||
885
+ record.configuration.mode !== "once"
886
+ )
887
+ return yield* error("conflict", "catch-up-identity");
888
+ const existing = yield* readDelivery(delivery.key, "catch-up existing delivery");
889
+
890
+ if (existing !== null) {
891
+ if (!sameDeliveryIdentity(existing, delivery))
892
+ return yield* error("conflict", "delivery-identity");
893
+
894
+ return false;
895
+ }
896
+ yield* failpoint.hit("subscription:catch-up:before");
897
+ const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis);
898
+
899
+ if (!subscriptionCanSelect(record, accepted, effectiveNowMillis, true))
900
+ return yield* error("conflict", "catch-up-eligibility");
901
+ if (
902
+ (yield* count(
903
+ sql<
904
+ Record<string, unknown>
905
+ >`SELECT COUNT(*) AS count FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,
906
+ "count deliveries",
907
+ )) >= limits.maxDeliveries
908
+ )
909
+ return yield* error("capacity", "deliveries");
910
+ if (
911
+ (yield* count(
912
+ sql<
913
+ Record<string, unknown>
914
+ >`SELECT COUNT(*) AS count FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND owner_id=${record.key.ownerId}`,
915
+ "count owner deliveries",
916
+ )) >= limits.maxDeliveriesPerOwner
917
+ )
918
+ return yield* error("capacity", "owner-deliveries");
919
+ yield* insertDelivery(delivery);
920
+ yield* writeRegistration({ ...record, state: "consumed", recovery: null });
921
+
922
+ return true;
923
+ }),
924
+ );
925
+
926
+ if (changed) yield* failpoint.hit("subscription:catch-up:after");
927
+ });
928
+
929
+ const deferEvent: SubscriptionStore["Service"]["deferEvent"] = Effect.fn(
930
+ "SqlSubscriptionStore.deferEvent",
931
+ )(function* (eventId, nextAttemptAtMillis, code) {
932
+ const routingFailure =
933
+ code === undefined
934
+ ? "routing-failed"
935
+ : yield* validate(SubscriptionName, code, "routing-failure");
936
+
937
+ yield* transactions.run(
938
+ Effect.gen(function* () {
939
+ const accepted = yield* readEvent(eventId, "defer event");
940
+
941
+ if (accepted === null) return yield* error("not-found", "event");
942
+ yield* failpoint.hit("subscription:defer-event:before");
943
+ yield* writeEvent({ ...accepted, nextAttemptAtMillis, routingFailure });
944
+ }),
945
+ );
946
+ yield* failpoint.hit("subscription:defer-event:after");
947
+ });
948
+
949
+ const delivery: SubscriptionStore["Service"]["delivery"] = Effect.fn(
950
+ "SqlSubscriptionStore.delivery",
951
+ )(function* (input) {
952
+ const key = yield* validate(SubscriptionDeliveryKey, input, "delivery-key");
953
+
954
+ yield* requirePartition(key.subscription.partition, "delivery-partition");
955
+
956
+ return yield* readDelivery(key, "get delivery");
957
+ });
958
+
959
+ const pendingDeliveries: SubscriptionStore["Service"]["pendingDeliveries"] = Effect.fn(
960
+ "SqlSubscriptionStore.pendingDeliveries",
961
+ )(function* (nowMillis, after, limit) {
962
+ // Malformed bodies remain selectable for isolated decoding. Keep the same CASE guard
963
+ // in both deadline queries so corruption cannot prevent cursor commits or alarm repair.
964
+ const rows = yield* query(
965
+ sql<Record<string, unknown>>`
966
+ SELECT owner_id, subscription_id, event_id FROM effect_agent_subscription_deliveries
967
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND CASE WHEN json_valid(record_json) THEN
968
+ ((state NOT IN ('delivered','refused') AND COALESCE(json_extract(record_json, '$.retry.parked'), 0)=0) OR (state='delivered' AND json_extract(record_json, '$.observeSettlement')=1))
969
+ ELSE state<>'refused' END
970
+ AND next_attempt_at_millis<=${nowMillis} AND delivery_key>${after} ORDER BY delivery_key LIMIT ${limit}
971
+ `,
972
+ "pending deliveries",
973
+ );
974
+
975
+ const rowSchema = Schema.Struct({
976
+ owner_id: Schema.String,
977
+ subscription_id: Schema.String,
978
+ event_id: Schema.String,
979
+ });
980
+
981
+ return yield* decodeRows(rowSchema, rows, "pending delivery keys").pipe(
982
+ Effect.map((items) =>
983
+ items.map((item) => ({
984
+ subscription: { partition, ownerId: item.owner_id, subscriptionId: item.subscription_id },
985
+ eventId: item.event_id,
986
+ })),
987
+ ),
988
+ );
989
+ });
990
+
991
+ const listDeliveries: SubscriptionStore["Service"]["listDeliveries"] = Effect.fn(
992
+ "SqlSubscriptionStore.listDeliveries",
993
+ )(function* (input, after, limit) {
994
+ const key = yield* requireKey(input, "list-deliveries-key");
995
+
996
+ const rows = yield* query(
997
+ sql<Record<string, unknown>>`
998
+ SELECT record_json FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
999
+ AND owner_id=${key.ownerId} AND subscription_id=${key.subscriptionId} AND delivery_key>${after} ORDER BY delivery_key LIMIT ${limit}
1000
+ `,
1001
+ "list deliveries",
1002
+ );
1003
+
1004
+ const decoded = yield* decodeRows(JsonRow, rows, "list deliveries");
1005
+
1006
+ return yield* Effect.forEach(decoded, (row) =>
1007
+ decode(SubscriptionDelivery, row.record_json, "list delivery"),
1008
+ );
1009
+ });
1010
+
1011
+ const changeDelivery: SubscriptionStore["Service"]["changeDelivery"] = Effect.fn(
1012
+ "SqlSubscriptionStore.changeDelivery",
1013
+ )(function* (inputKey, inputDeliveryId, inputChange) {
1014
+ const key = yield* validate(SubscriptionDeliveryKey, inputKey, "change-delivery-key");
1015
+ const deliveryId = yield* validate(Digest, inputDeliveryId, "change-delivery-id");
1016
+ const change = yield* validate(DeliveryChange, inputChange, "change-delivery-change");
1017
+
1018
+ yield* requirePartition(key.subscription.partition, "change-delivery-partition");
1019
+
1020
+ const result = yield* transactions.run(
1021
+ Effect.gen(function* () {
1022
+ const existing = yield* readDelivery(key, "change delivery");
1023
+ const record = yield* readRegistration(key.subscription, "change delivery subscription");
1024
+
1025
+ if (existing === null || record === null)
1026
+ return yield* error("not-found", existing === null ? "delivery" : "subscription");
1027
+ yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:before`);
1028
+
1029
+ const effectiveChange =
1030
+ change._tag === "Prepare"
1031
+ ? { ...change, nowMillis: Math.max(change.nowMillis, yield* Clock.currentTimeMillis) }
1032
+ : change;
1033
+
1034
+ const transition = applySubscriptionDeliveryChange(
1035
+ existing,
1036
+ record,
1037
+ deliveryId,
1038
+ effectiveChange,
1039
+ );
1040
+
1041
+ if (Result.isFailure(transition)) return yield* transition.failure;
1042
+ if (transition.success === existing) return { value: existing, changed: false } as const;
1043
+ yield* writeDelivery(transition.success);
1044
+
1045
+ return { value: transition.success, changed: true } as const;
1046
+ }),
1047
+ );
1048
+
1049
+ if (result.changed)
1050
+ yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:after`);
1051
+
1052
+ return result.value;
1053
+ });
1054
+
1055
+ const recovering: SubscriptionStore["Service"]["recovering"] = Effect.fn(
1056
+ "SqlSubscriptionStore.recovering",
1057
+ )(function* (nowMillis, after, limit) {
1058
+ const rows = yield* query(
1059
+ sql<Record<string, unknown>>`
1060
+ SELECT owner_id, subscription_id, ordinal FROM effect_agent_subscriptions
1061
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND state='active'
1062
+ AND recovery_at_millis IS NOT NULL AND recovery_at_millis<=${nowMillis} AND ordinal>${after}
1063
+ ORDER BY ordinal LIMIT ${limit}
1064
+ `,
1065
+ "recovering subscriptions",
1066
+ );
1067
+
1068
+ const rowSchema = Schema.Struct({
1069
+ owner_id: Schema.String,
1070
+ subscription_id: Schema.String,
1071
+ ordinal: Schema.Natural,
1072
+ });
1073
+
1074
+ return yield* decodeRows(rowSchema, rows, "recovering subscription keys").pipe(
1075
+ Effect.map((items) =>
1076
+ items.map((item) => ({
1077
+ key: { partition, ownerId: item.owner_id, subscriptionId: item.subscription_id },
1078
+ ordinal: item.ordinal,
1079
+ })),
1080
+ ),
1081
+ );
1082
+ });
1083
+
1084
+ const deferRecovery: SubscriptionStore["Service"]["deferRecovery"] = Effect.fn(
1085
+ "SqlSubscriptionStore.deferRecovery",
1086
+ )(function* (input, expectedRevision, recovery) {
1087
+ const key = yield* requireKey(input, "defer-recovery-key");
1088
+
1089
+ yield* transactions.run(
1090
+ Effect.gen(function* () {
1091
+ const record = yield* readRegistration(key, "defer recovery");
1092
+
1093
+ if (record === null) return yield* error("not-found", "subscription");
1094
+ if (record.configurationRevision !== expectedRevision) return;
1095
+ yield* failpoint.hit("subscription:defer-recovery:before");
1096
+ yield* writeRegistration({
1097
+ ...record,
1098
+ recovery: record.state === "active" || record.state === "paused" ? recovery : null,
1099
+ });
1100
+ }),
1101
+ );
1102
+ yield* failpoint.hit("subscription:defer-recovery:after");
1103
+ });
1104
+
1105
+ const readScanCursors: SubscriptionStore["Service"]["readScanCursors"] = Effect.gen(function* () {
1106
+ const rows = yield* query(
1107
+ sql<Record<string, unknown>>`
1108
+ SELECT event_scan_cursor, delivery_scan_cursor, recovery_scan_cursor
1109
+ FROM effect_agent_subscription_sequences
1110
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
1111
+ `,
1112
+ "read subscription scan cursors",
1113
+ );
1114
+
1115
+ const decoded = yield* decodeRows(ScanRow, rows, "read subscription scan cursors");
1116
+
1117
+ if (decoded.length !== 1) return yield* corrupt("subscription scan cursors");
1118
+
1119
+ return {
1120
+ events: decoded[0].event_scan_cursor,
1121
+ deliveries: decoded[0].delivery_scan_cursor,
1122
+ recovery: decoded[0].recovery_scan_cursor,
1123
+ };
1124
+ });
1125
+
1126
+ const advanceScanCursors: SubscriptionStore["Service"]["advanceScanCursors"] = Effect.fn(
1127
+ "SqlSubscriptionStore.advanceScanCursors",
1128
+ )(function* (input) {
1129
+ const cursors = yield* validate(SubscriptionScanCursors, input, "scan-cursors");
1130
+
1131
+ yield* transactions.run(
1132
+ Effect.gen(function* () {
1133
+ yield* failpoint.hit("subscription:advance-scan-cursors:before");
1134
+ yield* query(
1135
+ sql<Record<string, unknown>>`
1136
+ UPDATE effect_agent_subscription_sequences
1137
+ SET event_scan_cursor=${cursors.events}, delivery_scan_cursor=${cursors.deliveries}, recovery_scan_cursor=${cursors.recovery}
1138
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
1139
+ `,
1140
+ "advance subscription scan cursors",
1141
+ );
1142
+ }),
1143
+ );
1144
+ yield* failpoint.hit("subscription:advance-scan-cursors:after");
1145
+ });
1146
+
1147
+ const indexedDeadline = query(
1148
+ sql<Record<string, unknown>>`
1149
+ SELECT MIN(deadline) AS deadline FROM (
1150
+ SELECT next_attempt_at_millis AS deadline FROM effect_agent_subscription_events
1151
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND routing_complete=0
1152
+ UNION ALL SELECT next_attempt_at_millis FROM effect_agent_subscription_deliveries
1153
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND CASE WHEN json_valid(record_json) THEN
1154
+ ((state NOT IN ('delivered','refused') AND COALESCE(json_extract(record_json, '$.retry.parked'), 0)=0) OR (state='delivered' AND json_extract(record_json, '$.observeSettlement')=1))
1155
+ ELSE state<>'refused' END
1156
+ UNION ALL SELECT next_maintenance_at_millis FROM effect_agent_event_retention
1157
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
1158
+ UNION ALL SELECT recovery_at_millis FROM effect_agent_subscriptions
1159
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND state='active' AND recovery_at_millis IS NOT NULL
1160
+ )
1161
+ `,
1162
+ "next subscription deadline",
1163
+ ).pipe(
1164
+ Effect.flatMap((rows) =>
1165
+ decodeRows(
1166
+ Schema.Struct({ deadline: Schema.NullOr(Schema.Number) }),
1167
+ rows,
1168
+ "next subscription deadline",
1169
+ ),
1170
+ ),
1171
+ Effect.flatMap((rows) =>
1172
+ rows.length === 1
1173
+ ? Effect.succeed(rows[0].deadline)
1174
+ : Effect.fail(corrupt("next subscription deadline")),
1175
+ ),
1176
+ );
1177
+
1178
+ const nextDeadline = Effect.gen(function* () {
1179
+ const cursors = yield* readScanCursors;
1180
+
1181
+ if (cursors.events !== "" || cursors.deliveries !== "" || cursors.recovery !== 0) return 0;
1182
+
1183
+ return yield* indexedDeadline;
1184
+ });
1185
+
1186
+ const compact: SubscriptionStore["Service"]["compact"] = Effect.fn(
1187
+ "SqlSubscriptionStore.compact",
1188
+ )(function* (nowMillis, inputPolicy, requestedLimit) {
1189
+ nowMillis = Math.min(nowMillis, yield* Clock.currentTimeMillis);
1190
+ const policy = yield* validate(SubscriptionRetentionPolicy, inputPolicy, "retention-policy");
1191
+
1192
+ const limit = yield* validate(
1193
+ Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 })),
1194
+ requestedLimit,
1195
+ "maintenance-limit",
1196
+ );
1197
+
1198
+ const removed = yield* transactions.run(
1199
+ Effect.gen(function* () {
1200
+ yield* failpoint.hit("subscription:compact:before");
1201
+ yield* query(
1202
+ sql<
1203
+ Record<string, unknown>
1204
+ >`INSERT INTO effect_agent_event_retention (tenant_id, source_address, replay_horizon_millis) VALUES (${partition.tenantId}, ${partition.address}, ${policy.replayHorizonMillis}) ON CONFLICT DO NOTHING`,
1205
+ "initialize maintenance",
1206
+ );
1207
+
1208
+ const progress = yield* query(
1209
+ sql<
1210
+ Record<string, unknown>
1211
+ >`SELECT replay_horizon_millis, tombstone_count, event_cursor, delivery_cursor FROM effect_agent_event_retention WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,
1212
+ "maintenance progress",
1213
+ ).pipe(
1214
+ Effect.flatMap((rows) =>
1215
+ decodeRows(
1216
+ Schema.Struct({
1217
+ replay_horizon_millis: Schema.Number,
1218
+ tombstone_count: Schema.Natural,
1219
+ event_cursor: Schema.String,
1220
+ delivery_cursor: Schema.String,
1221
+ }),
1222
+ rows,
1223
+ "maintenance progress",
1224
+ ),
1225
+ ),
1226
+ );
1227
+
1228
+ const cursor = progress[0];
1229
+
1230
+ if (progress.length !== 1 || cursor === undefined)
1231
+ return yield* corrupt("maintenance progress");
1232
+ if (cursor.replay_horizon_millis !== policy.replayHorizonMillis)
1233
+ return yield* error("conflict", "retention-horizon");
1234
+
1235
+ const deliveryRows = yield* query(
1236
+ sql<
1237
+ Record<string, unknown>
1238
+ >`SELECT delivery_key, record_json FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND delivery_key>${cursor.delivery_cursor} ORDER BY delivery_key LIMIT ${limit}`,
1239
+ "maintenance deliveries",
1240
+ ).pipe(
1241
+ Effect.flatMap((rows) =>
1242
+ decodeRows(
1243
+ Schema.Struct({ delivery_key: Schema.String, record_json: Schema.String }),
1244
+ rows,
1245
+ "maintenance deliveries",
1246
+ ),
1247
+ ),
1248
+ );
1249
+
1250
+ const eventRows = yield* query(
1251
+ sql<
1252
+ Record<string, unknown>
1253
+ >`SELECT event_id, record_json FROM effect_agent_subscription_events WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND event_id>${cursor.event_cursor} ORDER BY event_id LIMIT ${limit}`,
1254
+ "maintenance events",
1255
+ ).pipe(
1256
+ Effect.flatMap((rows) =>
1257
+ decodeRows(
1258
+ Schema.Struct({ event_id: Schema.String, record_json: Schema.String }),
1259
+ rows,
1260
+ "maintenance events",
1261
+ ),
1262
+ ),
1263
+ );
1264
+
1265
+ const protectedByRecovery = (event: AcceptedEvent) =>
1266
+ query(
1267
+ sql<
1268
+ Record<string, unknown>
1269
+ >`SELECT 1 FROM effect_agent_subscriptions WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND source_name=${event.source.name} AND source_version=${event.source.version} AND matching_key=${event.matchingKey} AND recovery_present=1 LIMIT 1`,
1270
+ "maintenance recovery reference",
1271
+ ).pipe(Effect.map((rows) => rows.length > 0));
1272
+
1273
+ const cutoff = nowMillis - policy.completedRetentionMillis;
1274
+
1275
+ for (const row of deliveryRows) {
1276
+ const decoded = yield* decode(
1277
+ SubscriptionDelivery,
1278
+ row.record_json,
1279
+ "maintenance delivery",
1280
+ ).pipe(Effect.result);
1281
+
1282
+ if (Result.isFailure(decoded)) {
1283
+ yield* Effect.logWarning("Subscription retention preserved corrupt delivery");
1284
+ continue;
1285
+ }
1286
+ const delivery = decoded.success;
1287
+
1288
+ if (
1289
+ subscriptionDeliveryKeyString(delivery.key) !== row.delivery_key ||
1290
+ !sameSourcePartition(delivery.key.subscription.partition, partition)
1291
+ ) {
1292
+ yield* Effect.logWarning(
1293
+ "Subscription retention preserved mismatched delivery identity",
1294
+ );
1295
+ continue;
1296
+ }
1297
+
1298
+ if (
1299
+ delivery.state !== "refused" &&
1300
+ (delivery.state !== "delivered" || delivery.settledAtMillis === undefined)
1301
+ )
1302
+ continue;
1303
+ if (
1304
+ (delivery.settledAtMillis ?? delivery.completedAtMillis ?? delivery.selectedAtMillis) >
1305
+ cutoff
1306
+ )
1307
+ continue;
1308
+
1309
+ const accepted = yield* readEvent(
1310
+ delivery.key.eventId,
1311
+ "maintenance delivery event",
1312
+ ).pipe(Effect.result);
1313
+
1314
+ if (Result.isFailure(accepted)) {
1315
+ if (accepted.failure.reason !== "corrupt") return yield* accepted.failure;
1316
+ yield* Effect.logWarning("Subscription retention preserved corrupt event");
1317
+ continue;
1318
+ }
1319
+ const event = accepted.success;
1320
+
1321
+ if (
1322
+ event === null ||
1323
+ !event.routingComplete ||
1324
+ event.occurredAtMillis === undefined ||
1325
+ event.acceptedAtMillis > cutoff ||
1326
+ (yield* protectedByRecovery(event))
1327
+ )
1328
+ continue;
1329
+ yield* query(
1330
+ sql<
1331
+ Record<string, unknown>
1332
+ >`DELETE FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND delivery_key=${row.delivery_key}`,
1333
+ "reclaim delivery",
1334
+ );
1335
+ }
1336
+ let removed = 0;
1337
+
1338
+ let tombstones = cursor.tombstone_count;
1339
+
1340
+ for (const row of eventRows) {
1341
+ const decoded = yield* decode(AcceptedEvent, row.record_json, "maintenance event").pipe(
1342
+ Effect.result,
1343
+ );
1344
+
1345
+ if (Result.isFailure(decoded)) {
1346
+ yield* Effect.logWarning("Subscription retention preserved corrupt event");
1347
+ continue;
1348
+ }
1349
+ const event = decoded.success;
1350
+
1351
+ if (event.eventId !== row.event_id || !sameSourcePartition(event.partition, partition)) {
1352
+ yield* Effect.logWarning("Subscription retention preserved mismatched event identity");
1353
+ continue;
1354
+ }
1355
+
1356
+ if (
1357
+ !event.routingComplete ||
1358
+ event.occurredAtMillis === undefined ||
1359
+ event.acceptedAtMillis > cutoff
1360
+ )
1361
+ continue;
1362
+ const expired = event.occurredAtMillis <= nowMillis - policy.replayHorizonMillis;
1363
+
1364
+ if (event.tombstone === true && !expired) continue;
1365
+ if (
1366
+ (yield* query(
1367
+ sql<
1368
+ Record<string, unknown>
1369
+ >`SELECT 1 FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND event_id=${event.eventId} LIMIT 1`,
1370
+ "maintenance delivery reference",
1371
+ )).length > 0 ||
1372
+ (yield* protectedByRecovery(event))
1373
+ )
1374
+ continue;
1375
+ if (expired) {
1376
+ yield* query(
1377
+ sql<
1378
+ Record<string, unknown>
1379
+ >`DELETE FROM effect_agent_subscription_events WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND event_id=${event.eventId}`,
1380
+ "expire event identity",
1381
+ );
1382
+ if (event.tombstone === true) tombstones--;
1383
+ } else {
1384
+ if (tombstones >= policy.maxTombstones) continue;
1385
+ yield* writeEvent({ ...event, payload: null, tombstone: true });
1386
+ tombstones++;
1387
+ }
1388
+ removed++;
1389
+ }
1390
+
1391
+ const remaining =
1392
+ (yield* query(
1393
+ sql<
1394
+ Record<string, unknown>
1395
+ >`SELECT 1 FROM effect_agent_subscription_events WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} LIMIT 1`,
1396
+ "remaining maintenance",
1397
+ )).length > 0;
1398
+
1399
+ yield* query(
1400
+ sql<
1401
+ Record<string, unknown>
1402
+ >`UPDATE effect_agent_event_retention SET tombstone_count=${tombstones}, event_cursor=${eventRows.length < limit ? "" : (eventRows.at(-1)?.event_id ?? "")}, delivery_cursor=${deliveryRows.length < limit ? "" : (deliveryRows.at(-1)?.delivery_key ?? "")}, next_maintenance_at_millis=${remaining ? nowMillis + 60_000 : null} WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,
1403
+ "advance maintenance",
1404
+ );
1405
+
1406
+ return removed;
1407
+ }),
1408
+ );
1409
+
1410
+ yield* failpoint.hit("subscription:compact:after");
1411
+
1412
+ return removed;
1413
+ });
1414
+
1415
+ return SubscriptionStore.of({
1416
+ partition,
1417
+ compact,
1418
+ register,
1419
+ get,
1420
+ list,
1421
+ cancel,
1422
+ change,
1423
+ accept,
1424
+ event,
1425
+ pendingEvents,
1426
+ candidates,
1427
+ select,
1428
+ catchUp,
1429
+ deferEvent,
1430
+ delivery,
1431
+ pendingDeliveries,
1432
+ listDeliveries,
1433
+ changeDelivery,
1434
+ recovering,
1435
+ deferRecovery,
1436
+ readScanCursors,
1437
+ advanceScanCursors,
1438
+ nextDeadline,
1439
+ });
1440
+ });