effect-agent 0.1.0-beta.16 → 0.1.0-beta.161

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 (546) hide show
  1. package/dist/Admin-Dirux8PR.d.mts +4270 -0
  2. package/dist/Agent-BMATXYsI.mjs +93 -0
  3. package/dist/Agent-BMATXYsI.mjs.map +1 -0
  4. package/dist/Agent-ZfnNCQXs.d.mts +259 -0
  5. package/dist/AgentError-Bn1ytXRD.d.mts +117 -0
  6. package/dist/AgentPolicy-B4oH8TbG.d.mts +112 -0
  7. package/dist/AgentRuntime-CVMHysXm.mjs +4844 -0
  8. package/dist/AgentRuntime-CVMHysXm.mjs.map +1 -0
  9. package/dist/AgentRuntime-D1MmB_0z.d.mts +346 -0
  10. package/dist/AgentUpdates-DMJ-_xow.d.mts +53 -0
  11. package/dist/ContextCompactor-BoKQOjr5.d.mts +161 -0
  12. package/dist/ContextWindow-DRQ5Mbm2.d.mts +58 -0
  13. package/dist/Digest-COAt3Orl.d.mts +22 -0
  14. package/dist/DurableAgentRuntime-BpB5rBcu.mjs +7513 -0
  15. package/dist/DurableAgentRuntime-BpB5rBcu.mjs.map +1 -0
  16. package/dist/DurableFailpoint-Cnr3wx1L.d.mts +41 -0
  17. package/dist/DurableStep-Cry_iol4.d.mts +103 -0
  18. package/dist/EventSource-DOXB0RJR.d.mts +51 -0
  19. package/dist/FailureDiagnostic-BElLOoED.mjs +274 -0
  20. package/dist/FailureDiagnostic-BElLOoED.mjs.map +1 -0
  21. package/dist/FailureDiagnostic-CaAkzGHL.d.mts +223 -0
  22. package/dist/Identifiers-CN2s30fF.d.mts +40 -0
  23. package/dist/InMemory.d.mts +24 -0
  24. package/dist/InMemory.mjs +24 -0
  25. package/dist/InMemory.mjs.map +1 -0
  26. package/dist/MemoryNamespace-BbRW5p71.d.mts +36 -0
  27. package/dist/MemoryReference-B8Q3UJoJ.d.mts +79 -0
  28. package/dist/Messaging-7VXQnWI3.d.mts +221 -0
  29. package/dist/Messaging-CICd_CSi.d.mts +1067 -0
  30. package/dist/MessagingHost-DXwWnrMh.d.mts +74 -0
  31. package/dist/MessagingHost-DfsbMPvq.mjs +110 -0
  32. package/dist/MessagingHost-DfsbMPvq.mjs.map +1 -0
  33. package/dist/OperationAuthorizer-TzcQtpX5.d.mts +61 -0
  34. package/dist/Output-CY7NZByV.d.mts +25 -0
  35. package/dist/PageCapture-Df8Xwskw.d.mts +583 -0
  36. package/dist/PreparedInputAdmission-B7r401xJ.d.mts +42 -0
  37. package/dist/Receipt-BAHyigAF.d.mts +33 -0
  38. package/dist/Records-Bm4Qt70a.d.mts +1115 -0
  39. package/dist/RunEvent-D0aepYwN.d.mts +474 -0
  40. package/dist/RunEventSink-9CUdI9Ar.d.mts +108 -0
  41. package/dist/RunJournal-CA2bsvHn.mjs +979 -0
  42. package/dist/RunJournal-CA2bsvHn.mjs.map +1 -0
  43. package/dist/RunOptions-BHmBa05n.d.mts +960 -0
  44. package/dist/RunPolicyUsage-CUudVtg_.d.mts +23 -0
  45. package/dist/Sandbox-CEsDWBLq.d.mts +173 -0
  46. package/dist/Schedule-Bi_XVKLF.d.mts +847 -0
  47. package/dist/Scheduling-DPb2QyAK.mjs +691 -0
  48. package/dist/Scheduling-DPb2QyAK.mjs.map +1 -0
  49. package/dist/Subagent-D59om8SR.d.mts +1650 -0
  50. package/dist/Subagent-DH6G120f.mjs +1499 -0
  51. package/dist/Subagent-DH6G120f.mjs.map +1 -0
  52. package/dist/SubagentContract-tyN9v-Jv.d.mts +112 -0
  53. package/dist/SubagentHost-VTyf_wEF.d.mts +172 -0
  54. package/dist/Subscription-B3ScCBaN.d.mts +979 -0
  55. package/dist/SubscriptionInput-BP5WVsX_.d.mts +41 -0
  56. package/dist/Thread-DOBQ0QUY.d.mts +96 -0
  57. package/dist/ThreadHistory-FD-o4TsR.d.mts +60 -0
  58. package/dist/ToolBroker-DWs4tZra.d.mts +133 -0
  59. package/dist/ToolExposure-9uF_Yo0T.mjs +10 -0
  60. package/dist/ToolExposure-9uF_Yo0T.mjs.map +1 -0
  61. package/dist/ToolExposure-C93U1sPu.mjs +30 -0
  62. package/dist/ToolExposure-C93U1sPu.mjs.map +1 -0
  63. package/dist/ToolExposure-UCN12eCd.d.mts +39 -0
  64. package/dist/ToolExposure-r2eOWk4F.d.mts +46 -0
  65. package/dist/ToolExposure.d.mts +8 -0
  66. package/dist/ToolExposure.mjs +21 -0
  67. package/dist/ToolExposure.mjs.map +1 -0
  68. package/dist/ToolReconciler-BmVRAHKs.d.mts +80 -0
  69. package/dist/ToolResult-BKdqWRff.d.mts +78 -0
  70. package/dist/Usage-BNjPR7Zr.d.mts +129 -0
  71. package/dist/WakeScheduler-EjUF-GhC.d.mts +56 -0
  72. package/dist/Worker-CfwzMZEK.mjs +271 -0
  73. package/dist/Worker-CfwzMZEK.mjs.map +1 -0
  74. package/dist/Worker-XEBYxRQv.d.mts +472 -0
  75. package/dist/WorkerAdmission-Cmcxd6nS.mjs +171 -0
  76. package/dist/WorkerAdmission-Cmcxd6nS.mjs.map +1 -0
  77. package/dist/agent-registration-BIOzAej4.mjs +210 -0
  78. package/dist/agent-registration-BIOzAej4.mjs.map +1 -0
  79. package/dist/capabilities/Approval.d.mts +114 -0
  80. package/dist/capabilities/Approval.mjs +226 -0
  81. package/dist/capabilities/Approval.mjs.map +1 -0
  82. package/dist/capabilities/BrowserUse.d.mts +545 -0
  83. package/dist/capabilities/BrowserUse.mjs +254 -0
  84. package/dist/capabilities/BrowserUse.mjs.map +1 -0
  85. package/dist/capabilities/Budget.d.mts +112 -0
  86. package/dist/capabilities/Budget.mjs +346 -0
  87. package/dist/capabilities/Budget.mjs.map +1 -0
  88. package/dist/capabilities/CodeMode.d.mts +157 -0
  89. package/dist/capabilities/CodeMode.mjs +523 -0
  90. package/dist/capabilities/CodeMode.mjs.map +1 -0
  91. package/dist/capabilities/Commands.d.mts +55 -0
  92. package/dist/capabilities/Commands.mjs +57 -0
  93. package/dist/capabilities/Commands.mjs.map +1 -0
  94. package/dist/capabilities/ContextTools.d.mts +187 -0
  95. package/dist/capabilities/ContextTools.mjs +87 -0
  96. package/dist/capabilities/ContextTools.mjs.map +1 -0
  97. package/dist/capabilities/Mcp.d.mts +108 -0
  98. package/dist/capabilities/Mcp.mjs +259 -0
  99. package/dist/capabilities/Mcp.mjs.map +1 -0
  100. package/dist/capabilities/McpClient.d.mts +115 -0
  101. package/dist/capabilities/McpClient.mjs +519 -0
  102. package/dist/capabilities/McpClient.mjs.map +1 -0
  103. package/dist/capabilities/MemoryNotes.d.mts +424 -0
  104. package/dist/capabilities/MemoryNotes.mjs +128 -0
  105. package/dist/capabilities/MemoryNotes.mjs.map +1 -0
  106. package/dist/capabilities/Messaging.d.mts +3 -0
  107. package/dist/capabilities/Messaging.mjs +152 -0
  108. package/dist/capabilities/Messaging.mjs.map +1 -0
  109. package/dist/capabilities/ModelContext.d.mts +89 -0
  110. package/dist/capabilities/ModelContext.mjs +168 -0
  111. package/dist/capabilities/ModelContext.mjs.map +1 -0
  112. package/dist/capabilities/Redaction.d.mts +37 -0
  113. package/dist/capabilities/Redaction.mjs +104 -0
  114. package/dist/capabilities/Redaction.mjs.map +1 -0
  115. package/dist/capabilities/Remembering.d.mts +434 -0
  116. package/dist/capabilities/Remembering.mjs +290 -0
  117. package/dist/capabilities/Remembering.mjs.map +1 -0
  118. package/dist/capabilities/RunHooks.d.mts +82 -0
  119. package/dist/capabilities/RunHooks.mjs +144 -0
  120. package/dist/capabilities/RunHooks.mjs.map +1 -0
  121. package/dist/capabilities/SemanticMemory.d.mts +431 -0
  122. package/dist/capabilities/SemanticMemory.mjs +315 -0
  123. package/dist/capabilities/SemanticMemory.mjs.map +1 -0
  124. package/dist/capabilities/Subagent.d.mts +4 -0
  125. package/dist/capabilities/Subagent.mjs +5 -0
  126. package/dist/capabilities/SubagentReservations.d.mts +186 -0
  127. package/dist/capabilities/SubagentReservations.mjs +479 -0
  128. package/dist/capabilities/SubagentReservations.mjs.map +1 -0
  129. package/dist/capabilities/ToolDiscovery.d.mts +129 -0
  130. package/dist/capabilities/ToolDiscovery.mjs +239 -0
  131. package/dist/capabilities/ToolDiscovery.mjs.map +1 -0
  132. package/dist/capabilities/WebCapture.d.mts +163 -0
  133. package/dist/capabilities/WebCapture.mjs +335 -0
  134. package/dist/capabilities/WebCapture.mjs.map +1 -0
  135. package/dist/capabilities/WebSearch.d.mts +75 -0
  136. package/dist/capabilities/WebSearch.mjs +123 -0
  137. package/dist/capabilities/WebSearch.mjs.map +1 -0
  138. package/dist/compaction-C2OTceKw.mjs +505 -0
  139. package/dist/compaction-C2OTceKw.mjs.map +1 -0
  140. package/dist/core/Agent.d.mts +2 -0
  141. package/dist/core/Agent.mjs +2 -0
  142. package/dist/core/AgentError.d.mts +2 -0
  143. package/dist/core/AgentError.mjs +134 -0
  144. package/dist/core/AgentError.mjs.map +1 -0
  145. package/dist/core/AgentPolicy.d.mts +2 -0
  146. package/dist/core/AgentPolicy.mjs +102 -0
  147. package/dist/core/AgentPolicy.mjs.map +1 -0
  148. package/dist/core/AgentUpdates.d.mts +2 -0
  149. package/dist/core/AgentUpdates.mjs +63 -0
  150. package/dist/core/AgentUpdates.mjs.map +1 -0
  151. package/dist/core/FailureDiagnostic.d.mts +2 -0
  152. package/dist/core/FailureDiagnostic.mjs +2 -0
  153. package/dist/core/IdGenerator.d.mts +26 -0
  154. package/dist/core/IdGenerator.mjs +27 -0
  155. package/dist/core/IdGenerator.mjs.map +1 -0
  156. package/dist/core/Identifiers.d.mts +2 -0
  157. package/dist/core/Identifiers.mjs +43 -0
  158. package/dist/core/Identifiers.mjs.map +1 -0
  159. package/dist/core/Memory.d.mts +57 -0
  160. package/dist/core/Memory.mjs +203 -0
  161. package/dist/core/Memory.mjs.map +1 -0
  162. package/dist/core/MemoryNamespace.d.mts +2 -0
  163. package/dist/core/MemoryNamespace.mjs +116 -0
  164. package/dist/core/MemoryNamespace.mjs.map +1 -0
  165. package/dist/core/MemoryReference.d.mts +2 -0
  166. package/dist/core/MemoryReference.mjs +109 -0
  167. package/dist/core/MemoryReference.mjs.map +1 -0
  168. package/dist/core/MemoryRevalidation.d.mts +65 -0
  169. package/dist/core/MemoryRevalidation.mjs +126 -0
  170. package/dist/core/MemoryRevalidation.mjs.map +1 -0
  171. package/dist/core/MemoryStore.d.mts +186 -0
  172. package/dist/core/MemoryStore.mjs +243 -0
  173. package/dist/core/MemoryStore.mjs.map +1 -0
  174. package/dist/core/Receipt.d.mts +2 -0
  175. package/dist/core/Receipt.mjs +36 -0
  176. package/dist/core/Receipt.mjs.map +1 -0
  177. package/dist/core/RememberingStore.d.mts +1562 -0
  178. package/dist/core/RememberingStore.mjs +190 -0
  179. package/dist/core/RememberingStore.mjs.map +1 -0
  180. package/dist/core/RunEvent.d.mts +2 -0
  181. package/dist/core/RunEvent.mjs +346 -0
  182. package/dist/core/RunEvent.mjs.map +1 -0
  183. package/dist/core/RunPolicyUsage.d.mts +2 -0
  184. package/dist/core/RunPolicyUsage.mjs +26 -0
  185. package/dist/core/RunPolicyUsage.mjs.map +1 -0
  186. package/dist/core/SemanticMemoryIndex.d.mts +826 -0
  187. package/dist/core/SemanticMemoryIndex.mjs +185 -0
  188. package/dist/core/SemanticMemoryIndex.mjs.map +1 -0
  189. package/dist/core/SemanticMemoryRevalidation.d.mts +45 -0
  190. package/dist/core/SemanticMemoryRevalidation.mjs +191 -0
  191. package/dist/core/SemanticMemoryRevalidation.mjs.map +1 -0
  192. package/dist/core/SubagentContract.d.mts +2 -0
  193. package/dist/core/SubagentContract.mjs +142 -0
  194. package/dist/core/SubagentContract.mjs.map +1 -0
  195. package/dist/core/Thread.d.mts +2 -0
  196. package/dist/core/Thread.mjs +250 -0
  197. package/dist/core/Thread.mjs.map +1 -0
  198. package/dist/core/ToolResult.d.mts +2 -0
  199. package/dist/core/ToolResult.mjs +156 -0
  200. package/dist/core/ToolResult.mjs.map +1 -0
  201. package/dist/core/Usage.d.mts +2 -0
  202. package/dist/core/Usage.mjs +340 -0
  203. package/dist/core/Usage.mjs.map +1 -0
  204. package/dist/core/Worker.d.mts +3 -0
  205. package/dist/core/Worker.mjs +3 -0
  206. package/dist/durable/ActivityStore.d.mts +116 -0
  207. package/dist/durable/ActivityStore.mjs +131 -0
  208. package/dist/durable/ActivityStore.mjs.map +1 -0
  209. package/dist/durable/Admin.d.mts +2 -0
  210. package/dist/durable/Admin.mjs +330 -0
  211. package/dist/durable/Admin.mjs.map +1 -0
  212. package/dist/durable/AgentRegistration.d.mts +2 -0
  213. package/dist/durable/AgentRegistration.mjs +15 -0
  214. package/dist/durable/AgentRegistration.mjs.map +1 -0
  215. package/dist/durable/Certification.d.mts +110 -0
  216. package/dist/durable/Certification.mjs +159 -0
  217. package/dist/durable/Certification.mjs.map +1 -0
  218. package/dist/durable/CommittedActivity.d.mts +64 -0
  219. package/dist/durable/CommittedActivity.mjs +159 -0
  220. package/dist/durable/CommittedActivity.mjs.map +1 -0
  221. package/dist/durable/Digest.d.mts +2 -0
  222. package/dist/durable/Digest.mjs +50 -0
  223. package/dist/durable/Digest.mjs.map +1 -0
  224. package/dist/durable/DurableAgentRuntime.d.mts +3 -0
  225. package/dist/durable/DurableAgentRuntime.mjs +4 -0
  226. package/dist/durable/DurableFailpoint.d.mts +2 -0
  227. package/dist/durable/DurableFailpoint.mjs +102 -0
  228. package/dist/durable/DurableFailpoint.mjs.map +1 -0
  229. package/dist/durable/DurableFailpointTestControl.d.mts +14 -0
  230. package/dist/durable/DurableFailpointTestControl.mjs +19 -0
  231. package/dist/durable/DurableFailpointTestControl.mjs.map +1 -0
  232. package/dist/durable/EventSource.d.mts +2 -0
  233. package/dist/durable/EventSource.mjs +65 -0
  234. package/dist/durable/EventSource.mjs.map +1 -0
  235. package/dist/durable/GitHubWorkflowSource.d.mts +185 -0
  236. package/dist/durable/GitHubWorkflowSource.mjs +209 -0
  237. package/dist/durable/GitHubWorkflowSource.mjs.map +1 -0
  238. package/dist/durable/LifecyclePublication.d.mts +2 -0
  239. package/dist/durable/LifecyclePublication.mjs +189 -0
  240. package/dist/durable/LifecyclePublication.mjs.map +1 -0
  241. package/dist/durable/MessageDelivery.d.mts +949 -0
  242. package/dist/durable/MessageDelivery.mjs +589 -0
  243. package/dist/durable/MessageDelivery.mjs.map +1 -0
  244. package/dist/durable/MessageDeliveryStoreConformance.d.mts +400 -0
  245. package/dist/durable/MessageDeliveryStoreConformance.mjs +270 -0
  246. package/dist/durable/MessageDeliveryStoreConformance.mjs.map +1 -0
  247. package/dist/durable/OperationAuthorizer.d.mts +2 -0
  248. package/dist/durable/OperationAuthorizer.mjs +70 -0
  249. package/dist/durable/OperationAuthorizer.mjs.map +1 -0
  250. package/dist/durable/PersistentHistory.d.mts +16 -0
  251. package/dist/durable/PersistentHistory.mjs +125 -0
  252. package/dist/durable/PersistentHistory.mjs.map +1 -0
  253. package/dist/durable/PreparedInputAdmission.d.mts +2 -0
  254. package/dist/durable/PreparedInputAdmission.mjs +38 -0
  255. package/dist/durable/PreparedInputAdmission.mjs.map +1 -0
  256. package/dist/durable/Records.d.mts +2 -0
  257. package/dist/durable/Records.mjs +873 -0
  258. package/dist/durable/Records.mjs.map +1 -0
  259. package/dist/durable/Recovery.d.mts +2 -0
  260. package/dist/durable/Recovery.mjs +739 -0
  261. package/dist/durable/Recovery.mjs.map +1 -0
  262. package/dist/durable/RunJournal.d.mts +2 -0
  263. package/dist/durable/RunJournal.mjs +2 -0
  264. package/dist/durable/Schedule.d.mts +2 -0
  265. package/dist/durable/Schedule.mjs +391 -0
  266. package/dist/durable/Schedule.mjs.map +1 -0
  267. package/dist/durable/ScheduleStoreConformance.d.mts +17 -0
  268. package/dist/durable/ScheduleStoreConformance.mjs +420 -0
  269. package/dist/durable/ScheduleStoreConformance.mjs.map +1 -0
  270. package/dist/durable/ScheduleTransition.d.mts +24 -0
  271. package/dist/durable/ScheduleTransition.mjs +180 -0
  272. package/dist/durable/ScheduleTransition.mjs.map +1 -0
  273. package/dist/durable/Scheduling.d.mts +55 -0
  274. package/dist/durable/Scheduling.mjs +2 -0
  275. package/dist/durable/SqlMemoryStore.d.mts +742 -0
  276. package/dist/durable/SqlMemoryStore.mjs +627 -0
  277. package/dist/durable/SqlMemoryStore.mjs.map +1 -0
  278. package/dist/durable/SubmissionLedger.d.mts +3 -0
  279. package/dist/durable/SubmissionLedger.mjs +986 -0
  280. package/dist/durable/SubmissionLedger.mjs.map +1 -0
  281. package/dist/durable/SubmissionLedgerConformance.d.mts +30 -0
  282. package/dist/durable/SubmissionLedgerConformance.mjs +2254 -0
  283. package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -0
  284. package/dist/durable/SubmissionStatus.d.mts +2 -0
  285. package/dist/durable/SubmissionStatus.mjs +18 -0
  286. package/dist/durable/SubmissionStatus.mjs.map +1 -0
  287. package/dist/durable/Subscription.d.mts +2 -0
  288. package/dist/durable/Subscription.mjs +360 -0
  289. package/dist/durable/Subscription.mjs.map +1 -0
  290. package/dist/durable/SubscriptionInput.d.mts +2 -0
  291. package/dist/durable/SubscriptionInput.mjs +52 -0
  292. package/dist/durable/SubscriptionInput.mjs.map +1 -0
  293. package/dist/durable/SubscriptionStoreConformance.d.mts +16 -0
  294. package/dist/durable/SubscriptionStoreConformance.mjs +625 -0
  295. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -0
  296. package/dist/durable/SubscriptionTools.d.mts +274 -0
  297. package/dist/durable/SubscriptionTools.mjs +190 -0
  298. package/dist/durable/SubscriptionTools.mjs.map +1 -0
  299. package/dist/durable/SubscriptionTransition.d.mts +21 -0
  300. package/dist/durable/SubscriptionTransition.mjs +148 -0
  301. package/dist/durable/SubscriptionTransition.mjs.map +1 -0
  302. package/dist/durable/Subscriptions.d.mts +74 -0
  303. package/dist/durable/Subscriptions.mjs +627 -0
  304. package/dist/durable/Subscriptions.mjs.map +1 -0
  305. package/dist/durable/ThreadContextHistory.d.mts +32 -0
  306. package/dist/durable/ThreadContextHistory.mjs +152 -0
  307. package/dist/durable/ThreadContextHistory.mjs.map +1 -0
  308. package/dist/durable/ThreadContextHistoryProjection.d.mts +60 -0
  309. package/dist/durable/ThreadContextHistoryProjection.mjs +149 -0
  310. package/dist/durable/ThreadContextHistoryProjection.mjs.map +1 -0
  311. package/dist/durable/ThreadInvariants.d.mts +77 -0
  312. package/dist/durable/ThreadInvariants.mjs +246 -0
  313. package/dist/durable/ThreadInvariants.mjs.map +1 -0
  314. package/dist/durable/ThreadProjection.d.mts +78 -0
  315. package/dist/durable/ThreadProjection.mjs +158 -0
  316. package/dist/durable/ThreadProjection.mjs.map +1 -0
  317. package/dist/durable/ThreadProjectionMaintenance.d.mts +49 -0
  318. package/dist/durable/ThreadProjectionMaintenance.mjs +33 -0
  319. package/dist/durable/ThreadProjectionMaintenance.mjs.map +1 -0
  320. package/dist/durable/ThreadStore.d.mts +2 -0
  321. package/dist/durable/ThreadStore.mjs +383 -0
  322. package/dist/durable/ThreadStore.mjs.map +1 -0
  323. package/dist/durable/ThreadStoreConformance.d.mts +28 -0
  324. package/dist/durable/ThreadStoreConformance.mjs +543 -0
  325. package/dist/durable/ThreadStoreConformance.mjs.map +1 -0
  326. package/dist/durable/ToolReconciler.d.mts +2 -0
  327. package/dist/durable/ToolReconciler.mjs +85 -0
  328. package/dist/durable/ToolReconciler.mjs.map +1 -0
  329. package/dist/durable/WakeScheduler.d.mts +2 -0
  330. package/dist/durable/WakeScheduler.mjs +85 -0
  331. package/dist/durable/WakeScheduler.mjs.map +1 -0
  332. package/dist/durable/WorkerAdmission.d.mts +172 -0
  333. package/dist/durable/WorkerAdmission.mjs +2 -0
  334. package/dist/durable/WorkerHost.d.mts +156 -0
  335. package/dist/durable/WorkerHost.mjs +77 -0
  336. package/dist/durable/WorkerHost.mjs.map +1 -0
  337. package/dist/engine/AgentRuntime.d.mts +2 -0
  338. package/dist/engine/AgentRuntime.mjs +2 -0
  339. package/dist/engine/Compaction.d.mts +7 -0
  340. package/dist/engine/Compaction.mjs +16 -0
  341. package/dist/engine/Compaction.mjs.map +1 -0
  342. package/dist/engine/ContextCompactor.d.mts +2 -0
  343. package/dist/engine/ContextCompactor.mjs +119 -0
  344. package/dist/engine/ContextCompactor.mjs.map +1 -0
  345. package/dist/engine/ContextHistory.d.mts +65 -0
  346. package/dist/engine/ContextHistory.mjs +76 -0
  347. package/dist/engine/ContextHistory.mjs.map +1 -0
  348. package/dist/engine/ContextWindow.d.mts +2 -0
  349. package/dist/engine/ContextWindow.mjs +59 -0
  350. package/dist/engine/ContextWindow.mjs.map +1 -0
  351. package/dist/engine/DurableStep.d.mts +2 -0
  352. package/dist/engine/DurableStep.mjs +62 -0
  353. package/dist/engine/DurableStep.mjs.map +1 -0
  354. package/dist/engine/MessagingHost.d.mts +2 -0
  355. package/dist/engine/MessagingHost.mjs +2 -0
  356. package/dist/engine/Output.d.mts +2 -0
  357. package/dist/engine/Output.mjs +8 -0
  358. package/dist/engine/Output.mjs.map +1 -0
  359. package/dist/engine/RunEventSink.d.mts +2 -0
  360. package/dist/engine/RunEventSink.mjs +22 -0
  361. package/dist/engine/RunEventSink.mjs.map +1 -0
  362. package/dist/engine/RunOptions.d.mts +2 -0
  363. package/dist/engine/RunOptions.mjs +125 -0
  364. package/dist/engine/RunOptions.mjs.map +1 -0
  365. package/dist/engine/SubagentHost.d.mts +2 -0
  366. package/dist/engine/SubagentHost.mjs +76 -0
  367. package/dist/engine/SubagentHost.mjs.map +1 -0
  368. package/dist/engine/ThreadHistory.d.mts +2 -0
  369. package/dist/engine/ThreadHistory.mjs +67 -0
  370. package/dist/engine/ThreadHistory.mjs.map +1 -0
  371. package/dist/engine/ToolBroker.d.mts +2 -0
  372. package/dist/engine/ToolBroker.mjs +42 -0
  373. package/dist/engine/ToolBroker.mjs.map +1 -0
  374. package/dist/foreign-diagnostic-DBQ1XHKh.mjs +37 -0
  375. package/dist/foreign-diagnostic-DBQ1XHKh.mjs.map +1 -0
  376. package/dist/index.d.mts +93 -6
  377. package/dist/index.mjs +101 -6
  378. package/dist/output-contract-DS-S8mTv.mjs +135 -0
  379. package/dist/output-contract-DS-S8mTv.mjs.map +1 -0
  380. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  381. package/dist/sandbox/CodeExecutor.d.mts +194 -0
  382. package/dist/sandbox/CodeExecutor.mjs +278 -0
  383. package/dist/sandbox/CodeExecutor.mjs.map +1 -0
  384. package/dist/sandbox/InteractiveBrowser.d.mts +257 -0
  385. package/dist/sandbox/InteractiveBrowser.mjs +236 -0
  386. package/dist/sandbox/InteractiveBrowser.mjs.map +1 -0
  387. package/dist/sandbox/PageCapture.d.mts +2 -0
  388. package/dist/sandbox/PageCapture.mjs +450 -0
  389. package/dist/sandbox/PageCapture.mjs.map +1 -0
  390. package/dist/sandbox/PageCrawl.d.mts +88 -0
  391. package/dist/sandbox/PageCrawl.mjs +124 -0
  392. package/dist/sandbox/PageCrawl.mjs.map +1 -0
  393. package/dist/sandbox/PageScreenshot.d.mts +48 -0
  394. package/dist/sandbox/PageScreenshot.mjs +53 -0
  395. package/dist/sandbox/PageScreenshot.mjs.map +1 -0
  396. package/dist/sandbox/Sandbox.d.mts +2 -0
  397. package/dist/sandbox/Sandbox.mjs +208 -0
  398. package/dist/sandbox/Sandbox.mjs.map +1 -0
  399. package/dist/utf8-BYfhEkcj.mjs +11 -0
  400. package/dist/utf8-BYfhEkcj.mjs.map +1 -0
  401. package/dist/utf8-DchGZRBd.mjs +23 -0
  402. package/dist/utf8-DchGZRBd.mjs.map +1 -0
  403. package/package.json +1 -40
  404. package/src/InMemory.ts +19 -0
  405. package/src/ToolExposure.ts +2 -0
  406. package/src/capabilities/Approval.ts +352 -0
  407. package/src/capabilities/BrowserUse.ts +367 -0
  408. package/src/capabilities/Budget.ts +536 -0
  409. package/src/capabilities/CodeMode.ts +1099 -0
  410. package/src/capabilities/Commands.ts +86 -0
  411. package/src/capabilities/ContextTools.ts +129 -0
  412. package/src/capabilities/Mcp.ts +426 -0
  413. package/src/capabilities/McpClient.ts +983 -0
  414. package/src/capabilities/MemoryNotes.ts +174 -0
  415. package/src/capabilities/Messaging.ts +261 -0
  416. package/src/capabilities/ModelContext.ts +354 -0
  417. package/src/capabilities/Redaction.ts +157 -0
  418. package/src/capabilities/Remembering.ts +550 -0
  419. package/src/capabilities/RunHooks.ts +280 -0
  420. package/src/capabilities/SemanticMemory.ts +447 -0
  421. package/src/capabilities/Subagent.ts +2486 -0
  422. package/src/capabilities/SubagentReservations.ts +850 -0
  423. package/src/capabilities/ToolDiscovery.ts +383 -0
  424. package/src/capabilities/WebCapture.ts +722 -0
  425. package/src/capabilities/WebSearch.ts +205 -0
  426. package/src/capabilities/internal/subagent-background.ts +1307 -0
  427. package/src/capabilities/internal/subagent-contract.ts +146 -0
  428. package/src/capabilities/internal/subagent-policy.ts +235 -0
  429. package/src/capabilities/internal/subagent-reporting.ts +136 -0
  430. package/src/capabilities/internal/utf8.ts +10 -0
  431. package/src/core/Agent.ts +623 -0
  432. package/src/core/AgentError.ts +172 -0
  433. package/src/core/AgentPolicy.ts +161 -0
  434. package/src/core/AgentUpdates.ts +100 -0
  435. package/src/core/FailureDiagnostic.ts +343 -0
  436. package/src/core/IdGenerator.ts +39 -0
  437. package/src/core/Identifiers.ts +48 -0
  438. package/src/core/Memory.ts +290 -0
  439. package/src/core/MemoryNamespace.ts +196 -0
  440. package/src/core/MemoryReference.ts +121 -0
  441. package/src/core/MemoryRevalidation.ts +185 -0
  442. package/src/core/MemoryStore.ts +368 -0
  443. package/src/core/Messaging.ts +72 -0
  444. package/src/core/Receipt.ts +42 -0
  445. package/src/core/RememberingStore.ts +300 -0
  446. package/src/core/RunEvent.ts +375 -0
  447. package/src/core/RunPolicyUsage.ts +19 -0
  448. package/src/core/SemanticMemoryIndex.ts +250 -0
  449. package/src/core/SemanticMemoryRevalidation.ts +254 -0
  450. package/src/core/SubagentContract.ts +189 -0
  451. package/src/core/Thread.ts +371 -0
  452. package/src/core/ToolExposure.ts +74 -0
  453. package/src/core/ToolResult.ts +190 -0
  454. package/src/core/Usage.ts +570 -0
  455. package/src/core/Worker.ts +240 -0
  456. package/src/core/internal/agent-updates.ts +34 -0
  457. package/src/core/internal/message-status.ts +60 -0
  458. package/src/core/internal/strict-schema.ts +14 -0
  459. package/src/core/internal/utf8.ts +23 -0
  460. package/src/durable/ActivityStore.ts +160 -0
  461. package/src/durable/Admin.ts +505 -0
  462. package/src/durable/AgentRegistration.ts +16 -0
  463. package/src/durable/Certification.ts +210 -0
  464. package/src/durable/CommittedActivity.ts +296 -0
  465. package/src/durable/Digest.ts +87 -0
  466. package/src/durable/DurableAgentRuntime.ts +11867 -0
  467. package/src/durable/DurableFailpoint.ts +111 -0
  468. package/src/durable/DurableFailpointTestControl.ts +39 -0
  469. package/src/durable/EventSource.ts +172 -0
  470. package/src/durable/GitHubWorkflowSource.ts +447 -0
  471. package/src/durable/LifecyclePublication.ts +311 -0
  472. package/src/durable/MessageDelivery.ts +878 -0
  473. package/src/durable/MessageDeliveryStoreConformance.ts +410 -0
  474. package/src/durable/OperationAuthorizer.ts +85 -0
  475. package/src/durable/PersistentHistory.ts +260 -0
  476. package/src/durable/PreparedInputAdmission.ts +57 -0
  477. package/src/durable/Records.ts +1099 -0
  478. package/src/durable/Recovery.ts +1018 -0
  479. package/src/durable/RunJournal.ts +1768 -0
  480. package/src/durable/Schedule.ts +513 -0
  481. package/src/durable/ScheduleStoreConformance.ts +638 -0
  482. package/src/durable/ScheduleTransition.ts +265 -0
  483. package/src/durable/Scheduling.ts +1077 -0
  484. package/src/durable/SqlMemoryStore.ts +1056 -0
  485. package/src/durable/SubmissionLedger.ts +1297 -0
  486. package/src/durable/SubmissionLedgerConformance.ts +4940 -0
  487. package/src/durable/SubmissionStatus.ts +14 -0
  488. package/src/durable/Subscription.ts +544 -0
  489. package/src/durable/SubscriptionInput.ts +144 -0
  490. package/src/durable/SubscriptionStoreConformance.ts +945 -0
  491. package/src/durable/SubscriptionTools.ts +327 -0
  492. package/src/durable/SubscriptionTransition.ts +302 -0
  493. package/src/durable/Subscriptions.ts +1210 -0
  494. package/src/durable/ThreadContextHistory.ts +227 -0
  495. package/src/durable/ThreadContextHistoryProjection.ts +216 -0
  496. package/src/durable/ThreadInvariants.ts +507 -0
  497. package/src/durable/ThreadProjection.ts +269 -0
  498. package/src/durable/ThreadProjectionMaintenance.ts +67 -0
  499. package/src/durable/ThreadStore.ts +637 -0
  500. package/src/durable/ThreadStoreConformance.ts +1296 -0
  501. package/src/durable/ToolReconciler.ts +109 -0
  502. package/src/durable/WakeScheduler.ts +134 -0
  503. package/src/durable/WorkerAdmission.ts +104 -0
  504. package/src/durable/WorkerHost.ts +205 -0
  505. package/src/durable/internal/agent-registration.ts +621 -0
  506. package/src/durable/internal/agent-updates.ts +306 -0
  507. package/src/durable/internal/foreign-diagnostic.ts +47 -0
  508. package/src/durable/internal/journal-checkpoint.ts +159 -0
  509. package/src/durable/internal/journal-metadata.ts +124 -0
  510. package/src/durable/internal/message-status.ts +20 -0
  511. package/src/durable/internal/messaging-host.ts +637 -0
  512. package/src/durable/internal/schedule-time.ts +303 -0
  513. package/src/durable/internal/thread-initialization.ts +195 -0
  514. package/src/durable/internal/worker-host.ts +3309 -0
  515. package/src/durable/internal/worker-runtime.ts +9 -0
  516. package/src/engine/AgentRuntime.ts +37 -0
  517. package/src/engine/Compaction.ts +11 -0
  518. package/src/engine/ContextCompactor.ts +277 -0
  519. package/src/engine/ContextHistory.ts +73 -0
  520. package/src/engine/ContextWindow.ts +72 -0
  521. package/src/engine/DurableStep.ts +132 -0
  522. package/src/engine/MessagingHost.ts +110 -0
  523. package/src/engine/Output.ts +2 -0
  524. package/src/engine/RunEventSink.ts +132 -0
  525. package/src/engine/RunOptions.ts +1127 -0
  526. package/src/engine/SubagentHost.ts +239 -0
  527. package/src/engine/ThreadHistory.ts +120 -0
  528. package/src/engine/ToolBroker.ts +157 -0
  529. package/src/engine/ToolExposure.ts +48 -0
  530. package/src/engine/internal/agent-runtime.ts +10845 -0
  531. package/src/engine/internal/bounded-value.ts +315 -0
  532. package/src/engine/internal/compaction.ts +678 -0
  533. package/src/engine/internal/error-diagnostic.ts +39 -0
  534. package/src/engine/internal/output-contract.ts +250 -0
  535. package/src/engine/internal/primitive-delta.ts +80 -0
  536. package/src/engine/internal/provider-result-staging.ts +211 -0
  537. package/src/engine/internal/tool-derivative.ts +106 -0
  538. package/src/engine/internal/tool-exposure.ts +224 -0
  539. package/src/engine/internal/tool-telemetry.ts +484 -0
  540. package/src/index.ts +100 -22
  541. package/src/sandbox/CodeExecutor.ts +352 -0
  542. package/src/sandbox/InteractiveBrowser.ts +339 -0
  543. package/src/sandbox/PageCapture.ts +691 -0
  544. package/src/sandbox/PageCrawl.ts +148 -0
  545. package/src/sandbox/PageScreenshot.ts +81 -0
  546. package/src/sandbox/Sandbox.ts +241 -0
@@ -0,0 +1,1056 @@
1
+ import { Clock, Context, Effect, Layer, Schema } from "effect";
2
+ import * as SqlClientService from "effect/unstable/sql/SqlClient";
3
+ import type { SqlError } from "effect/unstable/sql/SqlError";
4
+
5
+ import { utf8ByteLength } from "../core/internal/utf8.ts";
6
+ import { type Any as MemoryNamespace, MemoryNamespaceAddress } from "../core/MemoryNamespace.ts";
7
+ import {
8
+ applyMemoryWrite,
9
+ MemoryDocument,
10
+ MemoryKey,
11
+ MemoryMutationFailpoint,
12
+ type MemoryMutationFailure,
13
+ MemoryOperationConflict,
14
+ MemoryReader,
15
+ MemoryStorageError,
16
+ MemoryWrite,
17
+ type MemoryWriteError,
18
+ MemoryWriter,
19
+ } from "../core/MemoryStore.ts";
20
+
21
+ const STORAGE_VERSION = 2 as const;
22
+ const METADATA_COMPONENT = "memory";
23
+ const DOCUMENT_TABLE = "effect_agent_memory_documents_v1";
24
+ const RECEIPT_TABLE = "effect_agent_memory_receipts_v1";
25
+ const USAGE_COMPONENT = "memory-usage";
26
+ const USAGE_TABLE = "effect_agent_memory_usage_v1";
27
+ const MAX_STORED_JSON_CODE_UNITS = 16 * 1024 * 1024;
28
+ const StoredJson = Schema.String.check(Schema.isMaxLength(MAX_STORED_JSON_CODE_UNITS));
29
+
30
+ const EncodedMemoryChange = Schema.Struct({
31
+ commandJson: StoredJson,
32
+ documentJson: StoredJson,
33
+ resultJson: StoredJson,
34
+ });
35
+
36
+ const equivalentContent = Schema.toEquivalence(
37
+ Schema.toEncoded(MemoryWrite.Wire.members[0].fields.content),
38
+ );
39
+
40
+ const equivalentScopes = Schema.toEquivalence(MemoryWrite.Wire.members[0].fields.scopes);
41
+
42
+ /** Ordered commands committed atomically by the SQL memory adapter. */
43
+ export const SqlMemoryWriteBatch = Schema.Array(MemoryWrite.Wire).check(Schema.isMaxLength(128));
44
+
45
+ /**
46
+ * SQL-only bulk writing. Results preserve input order, including exact operation replays.
47
+ * Commands see earlier staged revisions; any refusal rolls back the entire batch. Storage
48
+ * limits apply to every intermediate transition. Empty batches succeed without mutation.
49
+ * Supplied by the memory store Layers alongside MemoryWriter's single-command API.
50
+ */
51
+ export class SqlMemoryBatchWriter extends Context.Service<
52
+ SqlMemoryBatchWriter,
53
+ {
54
+ readonly changeMany: <Namespace extends MemoryNamespace>(
55
+ writes: ReadonlyArray<MemoryWrite<Namespace>>,
56
+ ) => Effect.Effect<ReadonlyArray<MemoryDocument<Namespace>>, MemoryWriteError>;
57
+ }
58
+ >()("@effect-agent/thread/SqlMemoryBatchWriter") {}
59
+
60
+ /**
61
+ * An exclusive database owner's transaction gate. All cached services over that database
62
+ * must share this identity, and every failed transaction must run its invalidators before
63
+ * releasing readers. Hosts with independent database writers must leave this unset.
64
+ */
65
+ export interface SqlStorageOwner {
66
+ /** Cache identity for transaction decorators; omission uses the owner itself.
67
+ * Shared identities must name the same database, reader gate and invalidator set. */
68
+ readonly identity?: object;
69
+ readonly read: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
70
+ readonly transaction: <A, E, R>(
71
+ effect: Effect.Effect<A, E, R>,
72
+ ) => Effect.Effect<A, E | SqlError, R | SqlClientService.SqlClient>;
73
+ readonly invalidators: Set<() => void>;
74
+ }
75
+
76
+ export const SqlStorageOwner = Context.Reference<SqlStorageOwner | undefined>(
77
+ "@effect-agent/thread/SqlStorageOwner",
78
+ { defaultValue: () => undefined },
79
+ );
80
+
81
+ /**
82
+ * Independent adapter limits. Counts and encoded bytes include durable operation receipts.
83
+ * Bytes count UTF-8 row payloads plus 128 bytes per row, excluding SQLite pages/indexes.
84
+ * Replacements charge their byte delta; receipts and tombstones are never pruned.
85
+ * Optional reserves (default zero) withhold capacity from Put, within the hard totals.
86
+ * They require exclusive upgraded writer ownership: older writers count toward usage
87
+ * but do not honor reserves. Limits are captured when the writer Layer is built.
88
+ */
89
+ export const SqlMemoryLimits = Context.Reference<{
90
+ readonly maxRowBytes: number;
91
+ readonly maxStorageBytes: number;
92
+ readonly maxDocuments: number;
93
+ readonly maxReceipts: number;
94
+ readonly reservedWithdrawalBytes?: number;
95
+ readonly reservedWithdrawalReceipts?: number;
96
+ }>("@effect-agent/thread/SqlMemoryLimits", {
97
+ defaultValue: () => ({
98
+ maxRowBytes: Number.MAX_SAFE_INTEGER,
99
+ maxStorageBytes: Number.MAX_SAFE_INTEGER,
100
+ maxDocuments: Number.MAX_SAFE_INTEGER,
101
+ maxReceipts: Number.MAX_SAFE_INTEGER,
102
+ }),
103
+ });
104
+
105
+ const Limits = Schema.Struct({
106
+ maxRowBytes: Schema.Natural,
107
+ maxStorageBytes: Schema.Natural,
108
+ maxDocuments: Schema.Natural,
109
+ maxReceipts: Schema.Natural,
110
+ reservedWithdrawalBytes: Schema.optional(Schema.Natural),
111
+ reservedWithdrawalReceipts: Schema.optional(Schema.Natural),
112
+ }).check(
113
+ Schema.makeFilter(
114
+ (limits) =>
115
+ (limits.reservedWithdrawalBytes ?? 0) <= limits.maxStorageBytes &&
116
+ (limits.reservedWithdrawalReceipts ?? 0) <= limits.maxReceipts,
117
+ { expected: "withdrawal reserves within hard storage limits" },
118
+ ),
119
+ );
120
+
121
+ const UsageRow = Schema.Struct({
122
+ documents: Schema.Natural,
123
+ receipts: Schema.Natural,
124
+ bytes: Schema.Natural,
125
+ });
126
+
127
+ type DocumentView = { readonly document: MemoryDocument; readonly bytes: number } | null;
128
+ type ReceiptView = { readonly commandJson: string; readonly result: MemoryDocument } | null;
129
+ type MemoryView =
130
+ | { readonly _tag: "Document"; readonly value: DocumentView }
131
+ | { readonly _tag: "Receipt"; readonly value: ReceiptView }
132
+ | { readonly _tag: "Usage"; readonly value: typeof UsageRow.Type };
133
+
134
+ // Demand-loaded views are disposable. The shared owner's gate keeps writes invisible
135
+ // until commit, and its rollback invalidator discards every speculative view together.
136
+ class MemoryViews {
137
+ private readonly entries = new Map<
138
+ string,
139
+ { readonly view: MemoryView; readonly bytes: number }
140
+ >();
141
+ private bytes = 0;
142
+
143
+ readonly clear = () => {
144
+ this.entries.clear();
145
+ this.bytes = 0;
146
+ };
147
+
148
+ get(key: string): MemoryView | undefined {
149
+ const entry = this.entries.get(key);
150
+
151
+ if (entry === undefined) return undefined;
152
+ this.entries.delete(key);
153
+ this.entries.set(key, entry);
154
+
155
+ return entry.view;
156
+ }
157
+
158
+ set(key: string, view: MemoryView): void {
159
+ const previous = this.entries.get(key);
160
+
161
+ if (previous !== undefined) this.bytes -= previous.bytes;
162
+ this.entries.delete(key);
163
+ const bytes = utf8ByteLength(key) + utf8ByteLength(JSON.stringify(view)) + 128;
164
+
165
+ if (bytes > 4 * 1024 * 1024) return;
166
+ this.entries.set(key, { view, bytes });
167
+ this.bytes += bytes;
168
+ while (this.entries.size > 128 || this.bytes > 4 * 1024 * 1024) {
169
+ const oldest = this.entries.entries().next().value;
170
+
171
+ if (oldest === undefined) break;
172
+ this.bytes -= oldest[1].bytes;
173
+ this.entries.delete(oldest[0]);
174
+ }
175
+ }
176
+ }
177
+
178
+ const ownedViews = new WeakMap<object, MemoryViews>();
179
+
180
+ const memoryViews = Effect.fn("SqliteMemoryStore.memoryViews")(function* () {
181
+ const owner = yield* SqlStorageOwner;
182
+
183
+ if (owner === undefined) return undefined;
184
+ const identity = owner.identity ?? owner;
185
+ let views = ownedViews.get(identity);
186
+
187
+ if (views === undefined) {
188
+ views = new MemoryViews();
189
+ ownedViews.set(identity, views);
190
+ owner.invalidators.add(views.clear);
191
+ }
192
+
193
+ return views;
194
+ });
195
+
196
+ const documentViewKey = (key: MemoryKey) =>
197
+ JSON.stringify(["document", key.namespace.address, key.id]);
198
+
199
+ const receiptViewKey = (write: MemoryWrite) =>
200
+ JSON.stringify(["receipt", write.key.namespace.address, write.operationId]);
201
+
202
+ // These expressions deliberately match the legacy aggregate's logical byte accounting.
203
+ const documentBytesSql = (row: string) =>
204
+ `length(CAST(${row}.namespace AS BLOB)) + length(CAST(${row}.source_id AS BLOB)) + length(CAST(${row}.document_json AS BLOB)) + 128`;
205
+
206
+ const receiptBytesSql = (row: string) =>
207
+ `length(CAST(${row}.namespace AS BLOB)) + length(CAST(${row}.source_id AS BLOB)) + length(CAST(${row}.operation_id AS BLOB)) + length(CAST(${row}.command_json AS BLOB)) + length(CAST(${row}.result_json AS BLOB)) + 128`;
208
+
209
+ // Triggers keep already-open version-2 writers accounted for. Their admission policy
210
+ // is still the old policy; deployment must drain them before relying on reserves.
211
+ const usageTriggers = [
212
+ { table: DOCUMENT_TABLE, count: "documents", bytes: documentBytesSql },
213
+ { table: RECEIPT_TABLE, count: "receipts", bytes: receiptBytesSql },
214
+ ].flatMap(({ table, count, bytes }) =>
215
+ ["INSERT", "UPDATE", "DELETE"].map((event) => ({
216
+ name: `${table}_usage_${event.toLowerCase()}`,
217
+ sql: `CREATE TRIGGER ${table}_usage_${event.toLowerCase()} AFTER ${event} ON ${table}
218
+ BEGIN
219
+ UPDATE ${USAGE_TABLE} SET
220
+ ${count} = ${count} + ${event === "INSERT" ? 1 : event === "DELETE" ? -1 : 0},
221
+ bytes = bytes + (${event === "DELETE" ? "0" : bytes("NEW")}) - (${event === "INSERT" ? "0" : bytes("OLD")})
222
+ WHERE singleton = 1;
223
+ SELECT CASE WHEN changes() <> 1 THEN RAISE(ABORT, 'missing memory usage') END;
224
+ END`,
225
+ })),
226
+ );
227
+
228
+ class MemoryMetadataRow extends Schema.Class<MemoryMetadataRow>(
229
+ "@effect-agent/storage-sqlite/MemoryMetadataRow",
230
+ )({
231
+ version: Schema.Int,
232
+ }) {}
233
+
234
+ class MemoryTableRow extends Schema.Class<MemoryTableRow>(
235
+ "@effect-agent/storage-sqlite/MemoryTableRow",
236
+ )({
237
+ name: Schema.NonEmptyString,
238
+ }) {}
239
+
240
+ class MemoryDocumentRow extends Schema.Class<MemoryDocumentRow>(
241
+ "@effect-agent/storage-sqlite/MemoryDocumentRow",
242
+ )({
243
+ namespace: MemoryNamespaceAddress,
244
+ source_id: MemoryKey.Wire.fields.id,
245
+ format_version: Schema.Int,
246
+ generation: Schema.Int,
247
+ revision: Schema.NonEmptyString,
248
+ document_json: StoredJson,
249
+ stored_bytes: Schema.Natural,
250
+ }) {}
251
+
252
+ class MemoryReceiptRow extends Schema.Class<MemoryReceiptRow>(
253
+ "@effect-agent/storage-sqlite/MemoryReceiptRow",
254
+ )({
255
+ namespace: MemoryNamespaceAddress,
256
+ operation_id: MemoryWrite.Wire.members[0].fields.operationId,
257
+ source_id: MemoryKey.Wire.fields.id,
258
+ format_version: Schema.Int,
259
+ command_json: StoredJson,
260
+ result_json: StoredJson,
261
+ }) {}
262
+
263
+ class MemoryChangeCountRow extends Schema.Class<MemoryChangeCountRow>(
264
+ "@effect-agent/storage-sqlite/MemoryChangeCountRow",
265
+ )({
266
+ changed: Schema.Int,
267
+ }) {}
268
+
269
+ class StoredMemoryCommand extends Schema.Class<StoredMemoryCommand>(
270
+ "@effect-agent/storage-sqlite/StoredMemoryCommand",
271
+ )({
272
+ version: Schema.Literal(STORAGE_VERSION),
273
+ value: MemoryWrite.Wire,
274
+ }) {}
275
+
276
+ class StoredMemoryResult extends Schema.Class<StoredMemoryResult>(
277
+ "@effect-agent/storage-sqlite/StoredMemoryResult",
278
+ )({
279
+ version: Schema.Literal(STORAGE_VERSION),
280
+ value: MemoryDocument.Wire,
281
+ }) {}
282
+
283
+ const StoredVersionHeader = Schema.Struct({ version: Schema.Int });
284
+
285
+ export type SqliteMemoryInitializationError = MemoryStorageError | MemoryMutationFailure;
286
+
287
+ const storageError = (
288
+ operation: string,
289
+ reason: MemoryStorageError["reason"] = "unavailable",
290
+ ): MemoryStorageError => MemoryStorageError.make({ operation, reason });
291
+
292
+ const query = <A extends object>(
293
+ effect: Effect.Effect<ReadonlyArray<A>, SqlError>,
294
+ operation: string,
295
+ ) => effect.pipe(Effect.mapError(() => storageError(operation)));
296
+
297
+ const decodeRows = Effect.fn("SqliteMemoryStore.decodeRows")(function* <A, I>(
298
+ schema: Schema.Codec<A, I, never>,
299
+ rows: ReadonlyArray<unknown>,
300
+ operation: string,
301
+ ): Effect.fn.Return<ReadonlyArray<A>, MemoryStorageError> {
302
+ return yield* Schema.decodeUnknownEffect(Schema.Array(schema))(rows).pipe(
303
+ Effect.mapError(() => storageError(operation, "corrupt")),
304
+ );
305
+ });
306
+
307
+ const decodeInput = Effect.fn("SqliteMemoryStore.decodeInput")(function* <A, I>(
308
+ schema: Schema.Codec<A, I, never>,
309
+ value: unknown,
310
+ operation: string,
311
+ ): Effect.fn.Return<A, MemoryStorageError> {
312
+ return yield* Schema.decodeUnknownEffect(schema)(value).pipe(
313
+ Effect.mapError(() => storageError(operation, "invalid-input")),
314
+ );
315
+ });
316
+
317
+ const encodeJson = Effect.fn("SqliteMemoryStore.encodeJson")(function* <A, I>(
318
+ schema: Schema.Codec<A, I, never>,
319
+ value: A,
320
+ operation: string,
321
+ ): Effect.fn.Return<string, MemoryStorageError> {
322
+ return yield* Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(
323
+ Effect.mapError(() => storageError(operation, "corrupt")),
324
+ );
325
+ });
326
+
327
+ const validateEncodedChange = Effect.fn("SqliteMemoryStore.validateEncodedChange")(function* (
328
+ encoded: typeof EncodedMemoryChange.Type,
329
+ operation: string,
330
+ ): Effect.fn.Return<void, MemoryStorageError> {
331
+ yield* Schema.decodeEffect(EncodedMemoryChange)(encoded).pipe(
332
+ Effect.mapError(() => storageError(operation, "invalid-input")),
333
+ );
334
+ });
335
+
336
+ const decodeVersionedJson = Effect.fn("SqliteMemoryStore.decodeVersionedJson")(function* <A, I>(
337
+ schema: Schema.Codec<A, I, never>,
338
+ value: string,
339
+ operation: string,
340
+ ): Effect.fn.Return<A, MemoryStorageError> {
341
+ const header = yield* Schema.decodeEffect(Schema.fromJsonString(StoredVersionHeader))(value).pipe(
342
+ Effect.mapError(() => storageError(operation, "corrupt")),
343
+ );
344
+
345
+ if (header.version !== STORAGE_VERSION) {
346
+ return yield* storageError(operation, "incompatible");
347
+ }
348
+
349
+ const decoded = yield* Schema.decodeEffect(Schema.fromJsonString(schema))(value).pipe(
350
+ Effect.mapError(() => storageError(operation, "corrupt")),
351
+ );
352
+
353
+ const canonical = yield* encodeJson(schema, decoded, operation);
354
+
355
+ if (canonical !== value) return yield* storageError(operation, "corrupt");
356
+
357
+ return decoded;
358
+ });
359
+
360
+ const validateDocument = Effect.fn("SqliteMemoryStore.validateDocument")(function* (
361
+ document: MemoryDocument,
362
+ key: MemoryKey,
363
+ operation: string,
364
+ ): Effect.fn.Return<MemoryDocument, MemoryStorageError> {
365
+ if (
366
+ document.key.namespace.address !== key.namespace.address ||
367
+ document.key.id !== key.id ||
368
+ document.source.id !== key.id ||
369
+ document.source.revision !== String(document.generation) ||
370
+ (document.generation === 1) !== (document.predecessor === null) ||
371
+ (document.predecessor !== null &&
372
+ (document.predecessor.id !== key.id ||
373
+ document.predecessor.revision !== String(document.generation - 1)))
374
+ ) {
375
+ return yield* storageError(operation, "corrupt");
376
+ }
377
+
378
+ return document;
379
+ });
380
+
381
+ const validateReceiptResult = Effect.fn("SqliteMemoryStore.validateReceiptResult")(function* (
382
+ command: MemoryWrite,
383
+ result: MemoryDocument,
384
+ operation: string,
385
+ ): Effect.fn.Return<void, MemoryStorageError> {
386
+ if ((result.predecessor?.revision ?? null) !== command.expectedRevision) {
387
+ return yield* storageError(operation, "corrupt");
388
+ }
389
+ if (command._tag === "Put") {
390
+ if (result._tag !== "ActiveMemoryDocument" || result.source.locator !== command.locator) {
391
+ return yield* storageError(operation, "corrupt");
392
+ }
393
+ if (
394
+ !equivalentContent(command.content, result.content) ||
395
+ !equivalentScopes(command.scopes, result.scopes)
396
+ ) {
397
+ return yield* storageError(operation, "corrupt");
398
+ }
399
+
400
+ return;
401
+ }
402
+ if (
403
+ result._tag !== "WithdrawnMemoryDocument" ||
404
+ result.reason !== command.reason ||
405
+ result.predecessor === null ||
406
+ result.source.locator !== result.predecessor.locator
407
+ ) {
408
+ return yield* storageError(operation, "corrupt");
409
+ }
410
+ });
411
+
412
+ const readUsage = Effect.fn("SqliteMemoryStore.readUsage")(function* () {
413
+ const sql = yield* SqlClientService.SqlClient;
414
+ const views = yield* memoryViews();
415
+ const operation = "read memory usage";
416
+
417
+ const rows = yield* query(
418
+ sql<Record<string, unknown>>`
419
+ SELECT documents, receipts, bytes FROM effect_agent_memory_usage_v1 WHERE singleton = 1
420
+ `,
421
+ operation,
422
+ ).pipe(Effect.flatMap((rows) => decodeRows(UsageRow, rows, operation)));
423
+
424
+ if (rows.length !== 1) return yield* storageError(operation, "corrupt");
425
+
426
+ views?.set("usage", { _tag: "Usage", value: rows[0] });
427
+
428
+ return rows[0];
429
+ });
430
+
431
+ // Called inside schema initialization's transaction. The separate marker distinguishes
432
+ // a legacy store from damaged established accounting; reopening never rebuilds counters.
433
+ const initializeMemoryUsage = Effect.fn("SqliteMemoryStore.initializeUsage")(function* () {
434
+ const sql = yield* SqlClientService.SqlClient;
435
+ const failpoint = yield* MemoryMutationFailpoint;
436
+ const operation = "initialize memory usage";
437
+
438
+ const metadata = yield* sql<Record<string, unknown>>`
439
+ SELECT version FROM effect_agent_memory_metadata WHERE component = ${USAGE_COMPONENT}
440
+ `.pipe(Effect.flatMap((rows) => decodeRows(MemoryMetadataRow, rows, operation)));
441
+
442
+ const objects = yield* sql<Record<string, unknown>>`
443
+ SELECT name FROM sqlite_master
444
+ WHERE name = ${USAGE_TABLE} OR name IN ${sql.in(usageTriggers.map((trigger) => trigger.name))}
445
+ `.pipe(Effect.flatMap((rows) => decodeRows(MemoryTableRow, rows, operation)));
446
+
447
+ if (metadata.length === 0) {
448
+ if (objects.length !== 0) return yield* storageError(operation, "corrupt");
449
+ yield* failpoint.hit("memory:initialize:before-accounting");
450
+ yield* sql`
451
+ CREATE TABLE effect_agent_memory_usage_v1 (
452
+ singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),
453
+ documents INTEGER NOT NULL CHECK (typeof(documents) = 'integer' AND documents BETWEEN 0 AND 9007199254740991),
454
+ receipts INTEGER NOT NULL CHECK (typeof(receipts) = 'integer' AND receipts BETWEEN 0 AND 9007199254740991),
455
+ bytes INTEGER NOT NULL CHECK (typeof(bytes) = 'integer' AND bytes BETWEEN 0 AND 9007199254740991)
456
+ )
457
+ `;
458
+ yield* sql`
459
+ INSERT INTO effect_agent_memory_usage_v1 (singleton, documents, receipts, bytes)
460
+ SELECT 1,
461
+ (SELECT COUNT(*) FROM effect_agent_memory_documents_v1),
462
+ (SELECT COUNT(*) FROM effect_agent_memory_receipts_v1),
463
+ COALESCE((SELECT SUM(length(CAST(namespace AS BLOB)) + length(CAST(source_id AS BLOB)) +
464
+ length(CAST(document_json AS BLOB)) + 128) FROM effect_agent_memory_documents_v1), 0) +
465
+ COALESCE((SELECT SUM(length(CAST(namespace AS BLOB)) + length(CAST(source_id AS BLOB)) +
466
+ length(CAST(operation_id AS BLOB)) + length(CAST(command_json AS BLOB)) +
467
+ length(CAST(result_json AS BLOB)) + 128) FROM effect_agent_memory_receipts_v1), 0)
468
+ `;
469
+ for (const trigger of usageTriggers) yield* sql.unsafe(trigger.sql);
470
+ yield* sql`
471
+ INSERT INTO effect_agent_memory_metadata (component, version) VALUES (${USAGE_COMPONENT}, 1)
472
+ `;
473
+ yield* failpoint.hit("memory:initialize:after-accounting");
474
+ } else {
475
+ if (metadata.length !== 1 || metadata[0].version !== 1) {
476
+ return yield* storageError(operation, "incompatible");
477
+ }
478
+ if (objects.length !== usageTriggers.length + 1) {
479
+ return yield* storageError(operation, "corrupt");
480
+ }
481
+ }
482
+ yield* readUsage();
483
+ });
484
+
485
+ const initializeMemorySchema = Effect.fn("SqliteMemoryStore.initialize")(function* () {
486
+ const sql = yield* SqlClientService.SqlClient;
487
+ const owner = yield* SqlStorageOwner;
488
+ const transaction = owner === undefined ? sql.withTransaction : owner.transaction;
489
+ const failpoint = yield* MemoryMutationFailpoint;
490
+
491
+ yield* failpoint.hit("memory:initialize:before");
492
+ yield* transaction(
493
+ Effect.gen(function* () {
494
+ yield* sql`
495
+ CREATE TABLE IF NOT EXISTS effect_agent_memory_metadata (
496
+ component TEXT PRIMARY KEY NOT NULL,
497
+ version INTEGER NOT NULL
498
+ )
499
+ `;
500
+
501
+ const metadataRows = yield* sql<Record<string, unknown>>`
502
+ SELECT version
503
+ FROM effect_agent_memory_metadata
504
+ WHERE component = ${METADATA_COMPONENT}
505
+ `;
506
+
507
+ const metadata = yield* decodeRows(
508
+ MemoryMetadataRow,
509
+ metadataRows,
510
+ "decode memory schema version",
511
+ );
512
+
513
+ if (metadata.length > 1)
514
+ return yield* storageError("decode memory schema version", "corrupt");
515
+ const currentVersion = metadata[0]?.version;
516
+
517
+ if (currentVersion !== undefined && currentVersion !== STORAGE_VERSION) {
518
+ return yield* storageError("initialize memory schema", "incompatible");
519
+ }
520
+ if (currentVersion === undefined) {
521
+ const tableRows = yield* sql<Record<string, unknown>>`
522
+ SELECT name
523
+ FROM sqlite_master
524
+ WHERE type = 'table' AND name IN (${DOCUMENT_TABLE}, ${RECEIPT_TABLE})
525
+ `;
526
+
527
+ const existingTables = yield* decodeRows(
528
+ MemoryTableRow,
529
+ tableRows,
530
+ "inspect memory schema",
531
+ );
532
+
533
+ if (existingTables.length > 0) {
534
+ return yield* storageError("initialize memory schema", "incompatible");
535
+ }
536
+ yield* sql`
537
+ CREATE TABLE effect_agent_memory_documents_v1 (
538
+ namespace TEXT NOT NULL,
539
+ source_id TEXT NOT NULL,
540
+ format_version INTEGER NOT NULL,
541
+ generation INTEGER NOT NULL,
542
+ revision TEXT NOT NULL,
543
+ document_json TEXT NOT NULL,
544
+ PRIMARY KEY (namespace, source_id)
545
+ )
546
+ `;
547
+ yield* sql`
548
+ CREATE TABLE effect_agent_memory_receipts_v1 (
549
+ namespace TEXT NOT NULL,
550
+ operation_id TEXT NOT NULL,
551
+ source_id TEXT NOT NULL,
552
+ format_version INTEGER NOT NULL,
553
+ command_json TEXT NOT NULL,
554
+ result_json TEXT NOT NULL,
555
+ PRIMARY KEY (namespace, operation_id)
556
+ )
557
+ `;
558
+ yield* sql`
559
+ INSERT INTO effect_agent_memory_metadata (component, version)
560
+ VALUES (${METADATA_COMPONENT}, ${STORAGE_VERSION})
561
+ `;
562
+ }
563
+ yield* sql`
564
+ SELECT namespace, source_id, format_version, generation, revision, document_json
565
+ FROM effect_agent_memory_documents_v1
566
+ LIMIT 0
567
+ `;
568
+ yield* sql`
569
+ SELECT namespace, operation_id, source_id, format_version, command_json, result_json
570
+ FROM effect_agent_memory_receipts_v1
571
+ LIMIT 0
572
+ `;
573
+ yield* initializeMemoryUsage();
574
+ }),
575
+ ).pipe(Effect.catchTag("SqlError", () => Effect.fail(storageError("initialize memory schema"))));
576
+ yield* failpoint.hit("memory:initialize:after");
577
+ });
578
+
579
+ const makeMemoryReader = Effect.fn("SqliteMemoryStore.makeReader")(function* () {
580
+ const sql = yield* SqlClientService.SqlClient;
581
+ const owner = yield* SqlStorageOwner;
582
+ const views = yield* memoryViews();
583
+
584
+ const readDocuments = Effect.fn("SqliteMemoryStore.readDocuments")(
585
+ function* (
586
+ keys: ReadonlyArray<MemoryKey>,
587
+ operation: string,
588
+ ): Effect.fn.Return<ReadonlyMap<string, DocumentView>, MemoryStorageError> {
589
+ const found = new Map<string, DocumentView>();
590
+ const missing = new Map<string, MemoryKey>();
591
+
592
+ for (const key of keys) {
593
+ const viewKey = documentViewKey(key);
594
+ const cached = views?.get(viewKey);
595
+
596
+ if (cached?._tag === "Document") found.set(viewKey, cached.value);
597
+ else missing.set(viewKey, key);
598
+ }
599
+ const pending = Array.from(missing);
600
+
601
+ // Each exact composite key uses two bindings. No history or unrelated rows are loaded.
602
+ for (let index = 0; index < pending.length; index += 50) {
603
+ const requested = new Map(pending.slice(index, index + 50));
604
+
605
+ const rawRows = yield* query(
606
+ sql<Record<string, unknown>>`
607
+ SELECT namespace, source_id, format_version, generation, revision, document_json,
608
+ length(CAST(namespace AS BLOB)) + length(CAST(source_id AS BLOB)) +
609
+ length(CAST(document_json AS BLOB)) + 128 AS stored_bytes
610
+ FROM effect_agent_memory_documents_v1
611
+ WHERE ${sql.or(
612
+ Array.from(
613
+ requested.values(),
614
+ (key) => sql`(namespace = ${key.namespace.address} AND source_id = ${key.id})`,
615
+ ),
616
+ )}
617
+ `,
618
+ operation,
619
+ );
620
+
621
+ const rows = yield* decodeRows(MemoryDocumentRow, rawRows, operation);
622
+
623
+ for (const row of rows) {
624
+ const viewKey = JSON.stringify(["document", row.namespace, row.source_id]);
625
+ const key = requested.get(viewKey);
626
+
627
+ if (key === undefined || found.has(viewKey))
628
+ return yield* storageError(operation, "corrupt");
629
+ if (row.format_version !== STORAGE_VERSION)
630
+ return yield* storageError(operation, "incompatible");
631
+
632
+ const stored = yield* decodeVersionedJson(
633
+ StoredMemoryResult,
634
+ row.document_json,
635
+ operation,
636
+ );
637
+
638
+ const document = stored.value;
639
+
640
+ yield* validateDocument(document, key, operation);
641
+ if (row.generation !== document.generation || row.revision !== document.source.revision)
642
+ return yield* storageError(operation, "corrupt");
643
+ found.set(viewKey, { document, bytes: row.stored_bytes });
644
+ }
645
+
646
+ for (const viewKey of requested.keys()) {
647
+ const value = found.get(viewKey) ?? null;
648
+
649
+ found.set(viewKey, value);
650
+ views?.set(viewKey, { _tag: "Document", value });
651
+ }
652
+ }
653
+
654
+ return found;
655
+ },
656
+ (effect) => (owner === undefined ? effect : owner.read(effect)),
657
+ );
658
+
659
+ const get = Effect.fn("SqliteMemoryStore.get")(function* (key: MemoryKey) {
660
+ const decodedKey = yield* decodeInput(MemoryKey.Wire, key, "get memory document");
661
+
662
+ const documents = yield* readDocuments([decodedKey], "get memory document");
663
+
664
+ return documents.get(documentViewKey(decodedKey))?.document ?? null;
665
+ });
666
+
667
+ return { get, readDocuments };
668
+ });
669
+
670
+ const makeMemoryServices = Effect.fn("SqliteMemoryStore.make")(function* () {
671
+ const sql = yield* SqlClientService.SqlClient;
672
+ const owner = yield* SqlStorageOwner;
673
+ const views = yield* memoryViews();
674
+
675
+ const usage = readUsage().pipe(
676
+ Effect.provideService(SqlClientService.SqlClient, sql),
677
+ Effect.provideService(SqlStorageOwner, owner),
678
+ );
679
+
680
+ const transaction = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
681
+ owner === undefined
682
+ ? sql.withTransaction(effect)
683
+ : owner.transaction(effect).pipe(Effect.provideService(SqlClientService.SqlClient, sql));
684
+
685
+ const failpoint = yield* MemoryMutationFailpoint;
686
+ const limits = yield* decodeInput(Limits, yield* SqlMemoryLimits, "memory storage limits");
687
+
688
+ yield* initializeMemorySchema();
689
+ const { get, readDocuments } = yield* makeMemoryReader();
690
+
691
+ const readReceipts = Effect.fn("SqliteMemoryStore.readReceipts")(function* (
692
+ writes: ReadonlyArray<MemoryWrite>,
693
+ operation: string,
694
+ ): Effect.fn.Return<ReadonlyMap<string, ReceiptView>, MemoryStorageError> {
695
+ const found = new Map<string, ReceiptView>();
696
+ const missing = new Map<string, MemoryWrite>();
697
+
698
+ for (const write of writes) {
699
+ const viewKey = receiptViewKey(write);
700
+ const cached = views?.get(viewKey);
701
+
702
+ if (cached?._tag === "Receipt") found.set(viewKey, cached.value);
703
+ else missing.set(viewKey, write);
704
+ }
705
+ const pending = Array.from(missing);
706
+
707
+ for (let index = 0; index < pending.length; index += 50) {
708
+ const requested = new Map(pending.slice(index, index + 50));
709
+
710
+ const rawRows = yield* query(
711
+ sql<Record<string, unknown>>`
712
+ SELECT namespace, operation_id, source_id, format_version, command_json, result_json
713
+ FROM effect_agent_memory_receipts_v1
714
+ WHERE ${sql.or(
715
+ Array.from(
716
+ requested.values(),
717
+ (write) =>
718
+ sql`(namespace = ${write.key.namespace.address} AND operation_id = ${write.operationId})`,
719
+ ),
720
+ )}
721
+ `,
722
+ operation,
723
+ );
724
+
725
+ const rows = yield* decodeRows(MemoryReceiptRow, rawRows, operation);
726
+
727
+ for (const row of rows) {
728
+ const viewKey = JSON.stringify(["receipt", row.namespace, row.operation_id]);
729
+
730
+ if (!requested.has(viewKey) || found.has(viewKey))
731
+ return yield* storageError(operation, "corrupt");
732
+ if (row.format_version !== STORAGE_VERSION)
733
+ return yield* storageError(operation, "incompatible");
734
+
735
+ const command = yield* decodeVersionedJson(
736
+ StoredMemoryCommand,
737
+ row.command_json,
738
+ `${operation} command`,
739
+ );
740
+
741
+ const result = yield* decodeVersionedJson(
742
+ StoredMemoryResult,
743
+ row.result_json,
744
+ `${operation} result`,
745
+ );
746
+
747
+ if (
748
+ row.namespace !== command.value.key.namespace.address ||
749
+ row.operation_id !== command.value.operationId ||
750
+ row.source_id !== command.value.key.id ||
751
+ result.value.key.namespace.address !== command.value.key.namespace.address ||
752
+ result.value.key.id !== command.value.key.id
753
+ ) {
754
+ return yield* storageError(operation, "corrupt");
755
+ }
756
+ yield* validateDocument(result.value, command.value.key, operation);
757
+ yield* validateReceiptResult(command.value, result.value, operation);
758
+ found.set(viewKey, { commandJson: row.command_json, result: result.value });
759
+ }
760
+
761
+ for (const viewKey of requested.keys()) {
762
+ const value = found.get(viewKey) ?? null;
763
+
764
+ found.set(viewKey, value);
765
+ views?.set(viewKey, { _tag: "Receipt", value });
766
+ }
767
+ }
768
+
769
+ return found;
770
+ });
771
+
772
+ const changeMany = Effect.fn("SqliteMemoryStore.changeMany")(function* (
773
+ writes: ReadonlyArray<MemoryWrite>,
774
+ ) {
775
+ const operation = "change memory document";
776
+ const decodedWrites = yield* decodeInput(SqlMemoryWriteBatch, writes, operation);
777
+
778
+ if (decodedWrites.length === 0) return [];
779
+
780
+ const commands = yield* Effect.forEach(decodedWrites, (write) =>
781
+ encodeJson(
782
+ StoredMemoryCommand,
783
+ StoredMemoryCommand.make({ version: STORAGE_VERSION, value: write }),
784
+ "encode memory command",
785
+ ).pipe(Effect.map((commandJson) => ({ write, commandJson }))),
786
+ );
787
+
788
+ yield* failpoint.hit("memory:change:before");
789
+
790
+ // The adapter must serialize before reading receipts and state. Node uses BEGIN
791
+ // IMMEDIATE; Durable Objects use the driver's storage-backed transaction and permit.
792
+ const transactionResult = yield* transaction(
793
+ Effect.gen(function* () {
794
+ const retainedReceipts = yield* readReceipts(decodedWrites, operation);
795
+
796
+ const retainedDocuments = yield* readDocuments(
797
+ decodedWrites
798
+ .filter((write) => retainedReceipts.get(receiptViewKey(write)) === null)
799
+ .map((write) => write.key),
800
+ operation,
801
+ );
802
+
803
+ const documents = new Map<
804
+ string,
805
+ {
806
+ readonly document: MemoryDocument;
807
+ readonly bytes: number;
808
+ readonly documentJson: string;
809
+ }
810
+ >();
811
+
812
+ const receipts = new Map<
813
+ string,
814
+ {
815
+ readonly write: MemoryWrite;
816
+ readonly commandJson: string;
817
+ readonly resultJson: string;
818
+ readonly result: MemoryDocument;
819
+ }
820
+ >();
821
+
822
+ const results: Array<MemoryDocument> = [];
823
+ let projectedUsage: typeof UsageRow.Type | undefined;
824
+
825
+ for (const { write, commandJson } of commands) {
826
+ const receiptKey = receiptViewKey(write);
827
+ const receipt = receipts.get(receiptKey) ?? retainedReceipts.get(receiptKey) ?? null;
828
+
829
+ if (receipt !== null) {
830
+ if (receipt.commandJson !== commandJson) {
831
+ return yield* MemoryOperationConflict.make({
832
+ key: write.key,
833
+ operationId: write.operationId,
834
+ });
835
+ }
836
+ results.push(receipt.result);
837
+ continue;
838
+ }
839
+
840
+ const documentKey = documentViewKey(write.key);
841
+
842
+ const currentRow =
843
+ documents.get(documentKey) ?? retainedDocuments.get(documentKey) ?? null;
844
+
845
+ const current = currentRow?.document ?? null;
846
+ const modifiedAt = yield* Clock.currentTimeMillis;
847
+ const next = yield* applyMemoryWrite(current, write, modifiedAt);
848
+
849
+ const resultJson = yield* encodeJson(
850
+ StoredMemoryResult,
851
+ StoredMemoryResult.make({ version: STORAGE_VERSION, value: next }),
852
+ "encode memory result",
853
+ );
854
+
855
+ const documentJson = resultJson;
856
+
857
+ yield* validateEncodedChange({ commandJson, documentJson, resultJson }, operation);
858
+
859
+ const bytes = utf8ByteLength;
860
+ const identityBytes = bytes(next.key.namespace.address) + bytes(next.key.id);
861
+ const resultBytes = bytes(resultJson);
862
+ const documentBytes = identityBytes + resultBytes + 128;
863
+
864
+ const receiptBytes =
865
+ identityBytes + bytes(write.operationId) + bytes(commandJson) + resultBytes + 128;
866
+
867
+ if (Math.max(documentBytes, receiptBytes) > limits.maxRowBytes) {
868
+ return yield* storageError("memory row byte limit", "invalid-input");
869
+ }
870
+
871
+ const cachedUsage = views?.get("usage");
872
+
873
+ const used =
874
+ projectedUsage ?? (cachedUsage?._tag === "Usage" ? cachedUsage.value : yield* usage);
875
+
876
+ if (used.bytes < (currentRow?.bytes ?? 0) || (current !== null && used.documents === 0)) {
877
+ return yield* storageError("read memory usage", "corrupt");
878
+ }
879
+
880
+ const maxReceipts =
881
+ limits.maxReceipts -
882
+ (write._tag === "Put" ? (limits.reservedWithdrawalReceipts ?? 0) : 0);
883
+
884
+ const maxStorageBytes =
885
+ limits.maxStorageBytes -
886
+ (write._tag === "Put" ? (limits.reservedWithdrawalBytes ?? 0) : 0);
887
+
888
+ // Check every staged transition, including intermediate document sizes and
889
+ // receipts. A later shrinking command cannot evade the earlier write's limits.
890
+ if (
891
+ used.documents > limits.maxDocuments - (current === null ? 1 : 0) ||
892
+ used.receipts >= maxReceipts ||
893
+ used.bytes - (currentRow?.bytes ?? 0) > maxStorageBytes - documentBytes - receiptBytes
894
+ ) {
895
+ return yield* storageError("memory storage limit", "invalid-input");
896
+ }
897
+
898
+ projectedUsage = {
899
+ documents: used.documents + (current === null ? 1 : 0),
900
+ receipts: used.receipts + 1,
901
+ bytes: used.bytes - (currentRow?.bytes ?? 0) + documentBytes + receiptBytes,
902
+ };
903
+ documents.set(documentKey, { document: next, bytes: documentBytes, documentJson });
904
+ receipts.set(receiptKey, { write, commandJson, resultJson, result: next });
905
+ results.push(next);
906
+ }
907
+
908
+ if (projectedUsage === undefined) return { documents: results, changed: false };
909
+
910
+ // Both persisted rows have six bound columns: sixteen rows stay below the DO
911
+ // driver's 100-parameter limit. The surrounding transaction owns all revision
912
+ // checks, and only the final row for each key needs physical writeback.
913
+ const documentRows = Array.from(documents.values(), ({ document, documentJson }) => ({
914
+ namespace: document.key.namespace.address,
915
+ source_id: document.key.id,
916
+ format_version: STORAGE_VERSION,
917
+ generation: document.generation,
918
+ revision: document.source.revision,
919
+ document_json: documentJson,
920
+ }));
921
+
922
+ for (let index = 0; index < documentRows.length; index += 16) {
923
+ const chunk = documentRows.slice(index, index + 16);
924
+
925
+ const changedRows = yield* sql<Record<string, unknown>>`
926
+ INSERT INTO effect_agent_memory_documents_v1 ${sql.insert(chunk)}
927
+ ON CONFLICT (namespace, source_id) DO UPDATE SET
928
+ format_version = excluded.format_version,
929
+ generation = excluded.generation,
930
+ revision = excluded.revision,
931
+ document_json = excluded.document_json
932
+ RETURNING 1 AS changed
933
+ `;
934
+
935
+ const changed = yield* decodeRows(MemoryChangeCountRow, changedRows, operation);
936
+
937
+ if (changed.length !== chunk.length || changed.some((row) => row.changed !== 1)) {
938
+ return yield* storageError(operation, "corrupt");
939
+ }
940
+ }
941
+ yield* failpoint.hit("memory:change:after-state");
942
+
943
+ const receiptRows = Array.from(receipts.values(), ({ write, commandJson, resultJson }) => ({
944
+ namespace: write.key.namespace.address,
945
+ operation_id: write.operationId,
946
+ source_id: write.key.id,
947
+ format_version: STORAGE_VERSION,
948
+ command_json: commandJson,
949
+ result_json: resultJson,
950
+ }));
951
+
952
+ for (let index = 0; index < receiptRows.length; index += 16) {
953
+ yield* sql`
954
+ INSERT INTO effect_agent_memory_receipts_v1 ${sql.insert(receiptRows.slice(index, index + 16))}
955
+ `;
956
+ }
957
+ yield* failpoint.hit("memory:change:after-receipt");
958
+
959
+ for (const [key, { document, bytes }] of documents)
960
+ views?.set(key, { _tag: "Document", value: { document, bytes } });
961
+ for (const [key, { commandJson, result }] of receipts)
962
+ views?.set(key, { _tag: "Receipt", value: { commandJson, result } });
963
+ views?.set("usage", { _tag: "Usage", value: projectedUsage });
964
+
965
+ return { documents: results, changed: true };
966
+ }),
967
+ ).pipe(Effect.catchTag("SqlError", () => Effect.fail(storageError(operation))));
968
+
969
+ if (transactionResult.changed) yield* failpoint.hit("memory:change:after");
970
+
971
+ return transactionResult.documents;
972
+ });
973
+
974
+ const change = Effect.fn("SqliteMemoryStore.change")(function* (write: MemoryWrite) {
975
+ return (yield* changeMany([write]))[0];
976
+ });
977
+
978
+ const batchWriter = SqlMemoryBatchWriter.of({
979
+ changeMany: Effect.fn("SqlMemoryBatchWriter.changeMany")(function* <
980
+ Namespace extends MemoryNamespace,
981
+ >(writes: ReadonlyArray<MemoryWrite<Namespace>>) {
982
+ const documents = yield* changeMany(writes);
983
+
984
+ return yield* Effect.forEach(documents, (document, index) =>
985
+ MemoryDocument.restore(writes[index].key.namespace, document),
986
+ );
987
+ }),
988
+ });
989
+
990
+ return Context.make(MemoryReader, MemoryReader.fromAdapter({ get })).pipe(
991
+ Context.add(MemoryWriter, MemoryWriter.fromAdapter({ change })),
992
+ Context.add(SqlMemoryBatchWriter, batchWriter),
993
+ );
994
+ });
995
+
996
+ /** SQLite memory ports with the mutation failpoint kept injectable for recovery tests. */
997
+ export const memoryStoreLayerWithFailpoints: Layer.Layer<
998
+ MemoryReader | MemoryWriter | SqlMemoryBatchWriter,
999
+ SqliteMemoryInitializationError,
1000
+ SqlClientService.SqlClient | MemoryMutationFailpoint
1001
+ > = Layer.effectContext(makeMemoryServices());
1002
+
1003
+ /** SQLite memory reader, single writer and batch writer with the production no-op failpoint. */
1004
+ export const memoryStoreLayer: Layer.Layer<
1005
+ MemoryReader | MemoryWriter | SqlMemoryBatchWriter,
1006
+ SqliteMemoryInitializationError,
1007
+ SqlClientService.SqlClient
1008
+ > = memoryStoreLayerWithFailpoints.pipe(Layer.provide(MemoryMutationFailpoint.layer));
1009
+
1010
+ /** Reads an existing memory schema without writes, transactions, or mutation failpoints. */
1011
+ export const memoryReaderLayer: Layer.Layer<
1012
+ MemoryReader,
1013
+ MemoryStorageError,
1014
+ SqlClientService.SqlClient
1015
+ > = Layer.effect(
1016
+ MemoryReader,
1017
+ Effect.gen(function* () {
1018
+ const sql = yield* SqlClientService.SqlClient;
1019
+ const operation = "open memory reader";
1020
+
1021
+ const tables = yield* query(
1022
+ sql<Record<string, unknown>>`
1023
+ SELECT name FROM sqlite_master
1024
+ WHERE type = 'table' AND name IN (
1025
+ 'effect_agent_memory_metadata', ${DOCUMENT_TABLE}, ${RECEIPT_TABLE}
1026
+ )
1027
+ `,
1028
+ operation,
1029
+ ).pipe(Effect.flatMap((rows) => decodeRows(MemoryTableRow, rows, operation)));
1030
+
1031
+ if (tables.length !== 3) {
1032
+ return yield* storageError(operation, tables.length === 0 ? "unavailable" : "incompatible");
1033
+ }
1034
+
1035
+ const metadata = yield* query(
1036
+ sql<Record<string, unknown>>`
1037
+ SELECT version FROM effect_agent_memory_metadata WHERE component = ${METADATA_COMPONENT}
1038
+ `,
1039
+ operation,
1040
+ ).pipe(Effect.flatMap((rows) => decodeRows(MemoryMetadataRow, rows, operation)));
1041
+
1042
+ if (metadata.length !== 1 || metadata[0].version !== STORAGE_VERSION) {
1043
+ return yield* storageError(operation, "incompatible");
1044
+ }
1045
+ yield* query(
1046
+ sql`
1047
+ SELECT namespace, source_id, format_version, generation, revision, document_json
1048
+ FROM effect_agent_memory_documents_v1 LIMIT 0
1049
+ `,
1050
+ operation,
1051
+ );
1052
+ const { get } = yield* makeMemoryReader();
1053
+
1054
+ return MemoryReader.fromAdapter({ get });
1055
+ }),
1056
+ );