@eloxiv/kernel 0.0.0-stage → 0.1.0

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 (1167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/AccountMail.d.ts +40 -0
  4. package/dist/AccountMail.d.ts.map +1 -0
  5. package/dist/AccountMail.js +169 -0
  6. package/dist/AccountMail.js.map +1 -0
  7. package/dist/AppConfig.d.ts +72 -0
  8. package/dist/AppConfig.d.ts.map +1 -0
  9. package/dist/AppConfig.js +87 -0
  10. package/dist/AppConfig.js.map +1 -0
  11. package/dist/Approvals.d.ts +132 -0
  12. package/dist/Approvals.d.ts.map +1 -0
  13. package/dist/Approvals.js +342 -0
  14. package/dist/Approvals.js.map +1 -0
  15. package/dist/Audit.d.ts +93 -0
  16. package/dist/Audit.d.ts.map +1 -0
  17. package/dist/Audit.js +275 -0
  18. package/dist/Audit.js.map +1 -0
  19. package/dist/AuthSeam.d.ts +58 -0
  20. package/dist/AuthSeam.d.ts.map +1 -0
  21. package/dist/AuthSeam.js +101 -0
  22. package/dist/AuthSeam.js.map +1 -0
  23. package/dist/Authority.d.ts +160 -0
  24. package/dist/Authority.d.ts.map +1 -0
  25. package/dist/Authority.js +325 -0
  26. package/dist/Authority.js.map +1 -0
  27. package/dist/Avatars.d.ts +26 -0
  28. package/dist/Avatars.d.ts.map +1 -0
  29. package/dist/Avatars.js +140 -0
  30. package/dist/Avatars.js.map +1 -0
  31. package/dist/Base64url.d.ts +9 -0
  32. package/dist/Base64url.d.ts.map +1 -0
  33. package/dist/Base64url.js +26 -0
  34. package/dist/Base64url.js.map +1 -0
  35. package/dist/BasePath.d.ts +39 -0
  36. package/dist/BasePath.d.ts.map +1 -0
  37. package/dist/BasePath.js +70 -0
  38. package/dist/BasePath.js.map +1 -0
  39. package/dist/CallActed.d.ts +10 -0
  40. package/dist/CallActed.d.ts.map +1 -0
  41. package/dist/CallActed.js +10 -0
  42. package/dist/CallActed.js.map +1 -0
  43. package/dist/Config.d.ts +459 -0
  44. package/dist/Config.d.ts.map +1 -0
  45. package/dist/Config.js +415 -0
  46. package/dist/Config.js.map +1 -0
  47. package/dist/DeliveryPolicy.d.ts +20 -0
  48. package/dist/DeliveryPolicy.d.ts.map +1 -0
  49. package/dist/DeliveryPolicy.js +35 -0
  50. package/dist/DeliveryPolicy.js.map +1 -0
  51. package/dist/DesktopSignIn.d.ts +24 -0
  52. package/dist/DesktopSignIn.d.ts.map +1 -0
  53. package/dist/DesktopSignIn.js +148 -0
  54. package/dist/DesktopSignIn.js.map +1 -0
  55. package/dist/Directory.d.ts +179 -0
  56. package/dist/Directory.d.ts.map +1 -0
  57. package/dist/Directory.js +1184 -0
  58. package/dist/Directory.js.map +1 -0
  59. package/dist/Flags.d.ts +59 -0
  60. package/dist/Flags.d.ts.map +1 -0
  61. package/dist/Flags.js +195 -0
  62. package/dist/Flags.js.map +1 -0
  63. package/dist/Gate.d.ts +42 -0
  64. package/dist/Gate.d.ts.map +1 -0
  65. package/dist/Gate.js +132 -0
  66. package/dist/Gate.js.map +1 -0
  67. package/dist/Hash.d.ts +4 -0
  68. package/dist/Hash.d.ts.map +1 -0
  69. package/dist/Hash.js +16 -0
  70. package/dist/Hash.js.map +1 -0
  71. package/dist/Identity.d.ts +327 -0
  72. package/dist/Identity.d.ts.map +1 -0
  73. package/dist/Identity.js +1232 -0
  74. package/dist/Identity.js.map +1 -0
  75. package/dist/IntervalJob.d.ts +40 -0
  76. package/dist/IntervalJob.d.ts.map +1 -0
  77. package/dist/IntervalJob.js +76 -0
  78. package/dist/IntervalJob.js.map +1 -0
  79. package/dist/Invocation.d.ts +210 -0
  80. package/dist/Invocation.d.ts.map +1 -0
  81. package/dist/Invocation.js +1680 -0
  82. package/dist/Invocation.js.map +1 -0
  83. package/dist/KernelHandlers.d.ts +19 -0
  84. package/dist/KernelHandlers.d.ts.map +1 -0
  85. package/dist/KernelHandlers.js +15 -0
  86. package/dist/KernelHandlers.js.map +1 -0
  87. package/dist/KernelModule.d.ts +65 -0
  88. package/dist/KernelModule.d.ts.map +1 -0
  89. package/dist/KernelModule.js +116 -0
  90. package/dist/KernelModule.js.map +1 -0
  91. package/dist/MemberRoutes.d.ts +6 -0
  92. package/dist/MemberRoutes.d.ts.map +1 -0
  93. package/dist/MemberRoutes.js +107 -0
  94. package/dist/MemberRoutes.js.map +1 -0
  95. package/dist/Module.d.ts +479 -0
  96. package/dist/Module.d.ts.map +1 -0
  97. package/dist/Module.js +30 -0
  98. package/dist/Module.js.map +1 -0
  99. package/dist/ModuleIdentity.d.ts +17 -0
  100. package/dist/ModuleIdentity.d.ts.map +1 -0
  101. package/dist/ModuleIdentity.js +106 -0
  102. package/dist/ModuleIdentity.js.map +1 -0
  103. package/dist/Notifications.d.ts +107 -0
  104. package/dist/Notifications.d.ts.map +1 -0
  105. package/dist/Notifications.js +475 -0
  106. package/dist/Notifications.js.map +1 -0
  107. package/dist/Outbox.d.ts +146 -0
  108. package/dist/Outbox.d.ts.map +1 -0
  109. package/dist/Outbox.js +518 -0
  110. package/dist/Outbox.js.map +1 -0
  111. package/dist/Privacy.d.ts +50 -0
  112. package/dist/Privacy.d.ts.map +1 -0
  113. package/dist/Privacy.js +167 -0
  114. package/dist/Privacy.js.map +1 -0
  115. package/dist/Progress.d.ts +42 -0
  116. package/dist/Progress.d.ts.map +1 -0
  117. package/dist/Progress.js +215 -0
  118. package/dist/Progress.js.map +1 -0
  119. package/dist/QuerySurface.d.ts +73 -0
  120. package/dist/QuerySurface.d.ts.map +1 -0
  121. package/dist/QuerySurface.js +440 -0
  122. package/dist/QuerySurface.js.map +1 -0
  123. package/dist/QueryViews.d.ts +70 -0
  124. package/dist/QueryViews.d.ts.map +1 -0
  125. package/dist/QueryViews.js +94 -0
  126. package/dist/QueryViews.js.map +1 -0
  127. package/dist/Readiness.d.ts +40 -0
  128. package/dist/Readiness.d.ts.map +1 -0
  129. package/dist/Readiness.js +203 -0
  130. package/dist/Readiness.js.map +1 -0
  131. package/dist/Redact.d.ts +11 -0
  132. package/dist/Redact.d.ts.map +1 -0
  133. package/dist/Redact.js +21 -0
  134. package/dist/Redact.js.map +1 -0
  135. package/dist/Registry.d.ts +117 -0
  136. package/dist/Registry.d.ts.map +1 -0
  137. package/dist/Registry.js +297 -0
  138. package/dist/Registry.js.map +1 -0
  139. package/dist/Release.d.ts +205 -0
  140. package/dist/Release.d.ts.map +1 -0
  141. package/dist/Release.js +880 -0
  142. package/dist/Release.js.map +1 -0
  143. package/dist/Retention.d.ts +43 -0
  144. package/dist/Retention.d.ts.map +1 -0
  145. package/dist/Retention.js +124 -0
  146. package/dist/Retention.js.map +1 -0
  147. package/dist/Scheduler.d.ts +56 -0
  148. package/dist/Scheduler.d.ts.map +1 -0
  149. package/dist/Scheduler.js +470 -0
  150. package/dist/Scheduler.js.map +1 -0
  151. package/dist/Server.d.ts +341 -0
  152. package/dist/Server.d.ts.map +1 -0
  153. package/dist/Server.js +1106 -0
  154. package/dist/Server.js.map +1 -0
  155. package/dist/Sessions.d.ts +38 -0
  156. package/dist/Sessions.d.ts.map +1 -0
  157. package/dist/Sessions.js +45 -0
  158. package/dist/Sessions.js.map +1 -0
  159. package/dist/Settings.d.ts +63 -0
  160. package/dist/Settings.d.ts.map +1 -0
  161. package/dist/Settings.js +219 -0
  162. package/dist/Settings.js.map +1 -0
  163. package/dist/Sharing.d.ts +99 -0
  164. package/dist/Sharing.d.ts.map +1 -0
  165. package/dist/Sharing.js +315 -0
  166. package/dist/Sharing.js.map +1 -0
  167. package/dist/Sync.d.ts +188 -0
  168. package/dist/Sync.d.ts.map +1 -0
  169. package/dist/Sync.js +1100 -0
  170. package/dist/Sync.js.map +1 -0
  171. package/dist/Telemetry.d.ts +154 -0
  172. package/dist/Telemetry.d.ts.map +1 -0
  173. package/dist/Telemetry.js +536 -0
  174. package/dist/Telemetry.js.map +1 -0
  175. package/dist/Versioning.d.ts +98 -0
  176. package/dist/Versioning.d.ts.map +1 -0
  177. package/dist/Versioning.js +387 -0
  178. package/dist/Versioning.js.map +1 -0
  179. package/dist/WorkItems.d.ts +67 -0
  180. package/dist/WorkItems.d.ts.map +1 -0
  181. package/dist/WorkItems.js +211 -0
  182. package/dist/WorkItems.js.map +1 -0
  183. package/dist/Workflows.d.ts +78 -0
  184. package/dist/Workflows.d.ts.map +1 -0
  185. package/dist/Workflows.js +478 -0
  186. package/dist/Workflows.js.map +1 -0
  187. package/dist/agent/Admission.d.ts +22 -0
  188. package/dist/agent/Admission.d.ts.map +1 -0
  189. package/dist/agent/Admission.js +34 -0
  190. package/dist/agent/Admission.js.map +1 -0
  191. package/dist/agent/Channels.d.ts +15 -0
  192. package/dist/agent/Channels.d.ts.map +1 -0
  193. package/dist/agent/Channels.js +50 -0
  194. package/dist/agent/Channels.js.map +1 -0
  195. package/dist/agent/Context.d.ts +73 -0
  196. package/dist/agent/Context.d.ts.map +1 -0
  197. package/dist/agent/Context.js +338 -0
  198. package/dist/agent/Context.js.map +1 -0
  199. package/dist/agent/Http.d.ts +18 -0
  200. package/dist/agent/Http.d.ts.map +1 -0
  201. package/dist/agent/Http.js +410 -0
  202. package/dist/agent/Http.js.map +1 -0
  203. package/dist/agent/Metering.d.ts +162 -0
  204. package/dist/agent/Metering.d.ts.map +1 -0
  205. package/dist/agent/Metering.js +315 -0
  206. package/dist/agent/Metering.js.map +1 -0
  207. package/dist/agent/ModelSetup.d.ts +10 -0
  208. package/dist/agent/ModelSetup.d.ts.map +1 -0
  209. package/dist/agent/ModelSetup.js +331 -0
  210. package/dist/agent/ModelSetup.js.map +1 -0
  211. package/dist/agent/Models.d.ts +197 -0
  212. package/dist/agent/Models.d.ts.map +1 -0
  213. package/dist/agent/Models.js +489 -0
  214. package/dist/agent/Models.js.map +1 -0
  215. package/dist/agent/Processors.d.ts +102 -0
  216. package/dist/agent/Processors.d.ts.map +1 -0
  217. package/dist/agent/Processors.js +80 -0
  218. package/dist/agent/Processors.js.map +1 -0
  219. package/dist/agent/Queue.d.ts +21 -0
  220. package/dist/agent/Queue.d.ts.map +1 -0
  221. package/dist/agent/Queue.js +64 -0
  222. package/dist/agent/Queue.js.map +1 -0
  223. package/dist/agent/Receipts.d.ts +41 -0
  224. package/dist/agent/Receipts.d.ts.map +1 -0
  225. package/dist/agent/Receipts.js +142 -0
  226. package/dist/agent/Receipts.js.map +1 -0
  227. package/dist/agent/Resources.d.ts +68 -0
  228. package/dist/agent/Resources.d.ts.map +1 -0
  229. package/dist/agent/Resources.js +207 -0
  230. package/dist/agent/Resources.js.map +1 -0
  231. package/dist/agent/Run.d.ts +178 -0
  232. package/dist/agent/Run.d.ts.map +1 -0
  233. package/dist/agent/Run.js +2896 -0
  234. package/dist/agent/Run.js.map +1 -0
  235. package/dist/agent/Runtime.d.ts +79 -0
  236. package/dist/agent/Runtime.d.ts.map +1 -0
  237. package/dist/agent/Runtime.js +366 -0
  238. package/dist/agent/Runtime.js.map +1 -0
  239. package/dist/agent/Settings.d.ts +126 -0
  240. package/dist/agent/Settings.d.ts.map +1 -0
  241. package/dist/agent/Settings.js +44 -0
  242. package/dist/agent/Settings.js.map +1 -0
  243. package/dist/agent/Skills.d.ts +73 -0
  244. package/dist/agent/Skills.d.ts.map +1 -0
  245. package/dist/agent/Skills.js +95 -0
  246. package/dist/agent/Skills.js.map +1 -0
  247. package/dist/agent/Store.d.ts +37 -0
  248. package/dist/agent/Store.d.ts.map +1 -0
  249. package/dist/agent/Store.js +50 -0
  250. package/dist/agent/Store.js.map +1 -0
  251. package/dist/agent/ToolSearch.d.ts +37 -0
  252. package/dist/agent/ToolSearch.d.ts.map +1 -0
  253. package/dist/agent/ToolSearch.js +119 -0
  254. package/dist/agent/ToolSearch.js.map +1 -0
  255. package/dist/agent/index.d.ts +37 -0
  256. package/dist/agent/index.d.ts.map +1 -0
  257. package/dist/agent/index.js +44 -0
  258. package/dist/agent/index.js.map +1 -0
  259. package/dist/agent/module.d.ts +12889 -0
  260. package/dist/agent/module.d.ts.map +1 -0
  261. package/dist/agent/module.js +1550 -0
  262. package/dist/agent/module.js.map +1 -0
  263. package/dist/appState/Sweep.d.ts +21 -0
  264. package/dist/appState/Sweep.d.ts.map +1 -0
  265. package/dist/appState/Sweep.js +46 -0
  266. package/dist/appState/Sweep.js.map +1 -0
  267. package/dist/appState/module.d.ts +1710 -0
  268. package/dist/appState/module.d.ts.map +1 -0
  269. package/dist/appState/module.js +344 -0
  270. package/dist/appState/module.js.map +1 -0
  271. package/dist/audit/module.d.ts +158 -0
  272. package/dist/audit/module.d.ts.map +1 -0
  273. package/dist/audit/module.js +72 -0
  274. package/dist/audit/module.js.map +1 -0
  275. package/dist/auth/AuthProvider.d.ts +224 -0
  276. package/dist/auth/AuthProvider.d.ts.map +1 -0
  277. package/dist/auth/AuthProvider.js +104 -0
  278. package/dist/auth/AuthProvider.js.map +1 -0
  279. package/dist/auth/BetterAuthProvider.d.ts +40 -0
  280. package/dist/auth/BetterAuthProvider.d.ts.map +1 -0
  281. package/dist/auth/BetterAuthProvider.js +458 -0
  282. package/dist/auth/BetterAuthProvider.js.map +1 -0
  283. package/dist/auth/Methods.d.ts +7 -0
  284. package/dist/auth/Methods.d.ts.map +1 -0
  285. package/dist/auth/Methods.js +7 -0
  286. package/dist/auth/Methods.js.map +1 -0
  287. package/dist/auth/SessionTokens.d.ts +23 -0
  288. package/dist/auth/SessionTokens.d.ts.map +1 -0
  289. package/dist/auth/SessionTokens.js +150 -0
  290. package/dist/auth/SessionTokens.js.map +1 -0
  291. package/dist/collab/Collab.d.ts +105 -0
  292. package/dist/collab/Collab.d.ts.map +1 -0
  293. package/dist/collab/Collab.js +475 -0
  294. package/dist/collab/Collab.js.map +1 -0
  295. package/dist/collab/Housekeeping.d.ts +38 -0
  296. package/dist/collab/Housekeeping.d.ts.map +1 -0
  297. package/dist/collab/Housekeeping.js +146 -0
  298. package/dist/collab/Housekeeping.js.map +1 -0
  299. package/dist/collab/LiveCopy.d.ts +7 -0
  300. package/dist/collab/LiveCopy.d.ts.map +1 -0
  301. package/dist/collab/LiveCopy.js +79 -0
  302. package/dist/collab/LiveCopy.js.map +1 -0
  303. package/dist/collab/Socket.d.ts +19 -0
  304. package/dist/collab/Socket.d.ts.map +1 -0
  305. package/dist/collab/Socket.js +323 -0
  306. package/dist/collab/Socket.js.map +1 -0
  307. package/dist/collab/Store.d.ts +42 -0
  308. package/dist/collab/Store.d.ts.map +1 -0
  309. package/dist/collab/Store.js +59 -0
  310. package/dist/collab/Store.js.map +1 -0
  311. package/dist/collab/Ydoc.d.ts +88 -0
  312. package/dist/collab/Ydoc.d.ts.map +1 -0
  313. package/dist/collab/Ydoc.js +314 -0
  314. package/dist/collab/Ydoc.js.map +1 -0
  315. package/dist/collab/derive/bundle.gen.d.ts +2 -0
  316. package/dist/collab/derive/bundle.gen.d.ts.map +1 -0
  317. package/dist/collab/derive/bundle.gen.js +3 -0
  318. package/dist/collab/derive/bundle.gen.js.map +1 -0
  319. package/dist/collab/derive/entry.d.ts +3 -0
  320. package/dist/collab/derive/entry.d.ts.map +1 -0
  321. package/dist/collab/derive/entry.js +35 -0
  322. package/dist/collab/derive/entry.js.map +1 -0
  323. package/dist/collab/derive/polyfill.d.ts +3 -0
  324. package/dist/collab/derive/polyfill.d.ts.map +1 -0
  325. package/dist/collab/derive/polyfill.js +17 -0
  326. package/dist/collab/derive/polyfill.js.map +1 -0
  327. package/dist/collab/module.d.ts +305 -0
  328. package/dist/collab/module.d.ts.map +1 -0
  329. package/dist/collab/module.js +161 -0
  330. package/dist/collab/module.js.map +1 -0
  331. package/dist/connections/Connections.d.ts +199 -0
  332. package/dist/connections/Connections.d.ts.map +1 -0
  333. package/dist/connections/Connections.js +1633 -0
  334. package/dist/connections/Connections.js.map +1 -0
  335. package/dist/connections/Connector.d.ts +213 -0
  336. package/dist/connections/Connector.d.ts.map +1 -0
  337. package/dist/connections/Connector.js +55 -0
  338. package/dist/connections/Connector.js.map +1 -0
  339. package/dist/connections/Crypto.d.ts +55 -0
  340. package/dist/connections/Crypto.d.ts.map +1 -0
  341. package/dist/connections/Crypto.js +100 -0
  342. package/dist/connections/Crypto.js.map +1 -0
  343. package/dist/connections/Destinations.d.ts +63 -0
  344. package/dist/connections/Destinations.d.ts.map +1 -0
  345. package/dist/connections/Destinations.js +338 -0
  346. package/dist/connections/Destinations.js.map +1 -0
  347. package/dist/connections/Discovery.d.ts +53 -0
  348. package/dist/connections/Discovery.d.ts.map +1 -0
  349. package/dist/connections/Discovery.js +209 -0
  350. package/dist/connections/Discovery.js.map +1 -0
  351. package/dist/connections/EffectKinds.d.ts +17 -0
  352. package/dist/connections/EffectKinds.d.ts.map +1 -0
  353. package/dist/connections/EffectKinds.js +26 -0
  354. package/dist/connections/EffectKinds.js.map +1 -0
  355. package/dist/connections/Effects.d.ts +49 -0
  356. package/dist/connections/Effects.d.ts.map +1 -0
  357. package/dist/connections/Effects.js +347 -0
  358. package/dist/connections/Effects.js.map +1 -0
  359. package/dist/connections/Metering.d.ts +40 -0
  360. package/dist/connections/Metering.d.ts.map +1 -0
  361. package/dist/connections/Metering.js +142 -0
  362. package/dist/connections/Metering.js.map +1 -0
  363. package/dist/connections/ProviderApi.d.ts +47 -0
  364. package/dist/connections/ProviderApi.d.ts.map +1 -0
  365. package/dist/connections/ProviderApi.js +103 -0
  366. package/dist/connections/ProviderApi.js.map +1 -0
  367. package/dist/connections/Secrets.d.ts +78 -0
  368. package/dist/connections/Secrets.d.ts.map +1 -0
  369. package/dist/connections/Secrets.js +342 -0
  370. package/dist/connections/Secrets.js.map +1 -0
  371. package/dist/connections/Sync.d.ts +85 -0
  372. package/dist/connections/Sync.d.ts.map +1 -0
  373. package/dist/connections/Sync.js +201 -0
  374. package/dist/connections/Sync.js.map +1 -0
  375. package/dist/connections/module.d.ts +1061 -0
  376. package/dist/connections/module.d.ts.map +1 -0
  377. package/dist/connections/module.js +485 -0
  378. package/dist/connections/module.js.map +1 -0
  379. package/dist/data/Corpus.d.ts +79 -0
  380. package/dist/data/Corpus.d.ts.map +1 -0
  381. package/dist/data/Corpus.js +343 -0
  382. package/dist/data/Corpus.js.map +1 -0
  383. package/dist/data/Datasets.d.ts +88 -0
  384. package/dist/data/Datasets.d.ts.map +1 -0
  385. package/dist/data/Datasets.js +375 -0
  386. package/dist/data/Datasets.js.map +1 -0
  387. package/dist/data/Programs.d.ts +58 -0
  388. package/dist/data/Programs.d.ts.map +1 -0
  389. package/dist/data/Programs.js +197 -0
  390. package/dist/data/Programs.js.map +1 -0
  391. package/dist/data/module.d.ts +210 -0
  392. package/dist/data/module.d.ts.map +1 -0
  393. package/dist/data/module.js +140 -0
  394. package/dist/data/module.js.map +1 -0
  395. package/dist/db/Bootstrap.d.ts +508 -0
  396. package/dist/db/Bootstrap.d.ts.map +1 -0
  397. package/dist/db/Bootstrap.js +2368 -0
  398. package/dist/db/Bootstrap.js.map +1 -0
  399. package/dist/db/Catalog.d.ts +10 -0
  400. package/dist/db/Catalog.d.ts.map +1 -0
  401. package/dist/db/Catalog.js +9 -0
  402. package/dist/db/Catalog.js.map +1 -0
  403. package/dist/db/Conflicts.d.ts +18 -0
  404. package/dist/db/Conflicts.d.ts.map +1 -0
  405. package/dist/db/Conflicts.js +29 -0
  406. package/dist/db/Conflicts.js.map +1 -0
  407. package/dist/db/DirectoryLock.d.ts +16 -0
  408. package/dist/db/DirectoryLock.d.ts.map +1 -0
  409. package/dist/db/DirectoryLock.js +15 -0
  410. package/dist/db/DirectoryLock.js.map +1 -0
  411. package/dist/db/HandlerGate.d.ts +28 -0
  412. package/dist/db/HandlerGate.d.ts.map +1 -0
  413. package/dist/db/HandlerGate.js +76 -0
  414. package/dist/db/HandlerGate.js.map +1 -0
  415. package/dist/db/Host.d.ts +94 -0
  416. package/dist/db/Host.d.ts.map +1 -0
  417. package/dist/db/Host.js +189 -0
  418. package/dist/db/Host.js.map +1 -0
  419. package/dist/db/KernelSchema.d.ts +52 -0
  420. package/dist/db/KernelSchema.d.ts.map +1 -0
  421. package/dist/db/KernelSchema.js +4313 -0
  422. package/dist/db/KernelSchema.js.map +1 -0
  423. package/dist/db/MigrationCheck.d.ts +38 -0
  424. package/dist/db/MigrationCheck.d.ts.map +1 -0
  425. package/dist/db/MigrationCheck.js +180 -0
  426. package/dist/db/MigrationCheck.js.map +1 -0
  427. package/dist/db/QueryViewCheck.d.ts +172 -0
  428. package/dist/db/QueryViewCheck.d.ts.map +1 -0
  429. package/dist/db/QueryViewCheck.js +967 -0
  430. package/dist/db/QueryViewCheck.js.map +1 -0
  431. package/dist/db/ReadOnly.d.ts +13 -0
  432. package/dist/db/ReadOnly.d.ts.map +1 -0
  433. package/dist/db/ReadOnly.js +16 -0
  434. package/dist/db/ReadOnly.js.map +1 -0
  435. package/dist/db/Scram.d.ts +5 -0
  436. package/dist/db/Scram.d.ts.map +1 -0
  437. package/dist/db/Scram.js +17 -0
  438. package/dist/db/Scram.js.map +1 -0
  439. package/dist/db/SqlState.d.ts +36 -0
  440. package/dist/db/SqlState.d.ts.map +1 -0
  441. package/dist/db/SqlState.js +64 -0
  442. package/dist/db/SqlState.js.map +1 -0
  443. package/dist/db/Startup.d.ts +18 -0
  444. package/dist/db/Startup.d.ts.map +1 -0
  445. package/dist/db/Startup.js +22 -0
  446. package/dist/db/Startup.js.map +1 -0
  447. package/dist/db/ZeroDdl.d.ts +85 -0
  448. package/dist/db/ZeroDdl.d.ts.map +1 -0
  449. package/dist/db/ZeroDdl.js +240 -0
  450. package/dist/db/ZeroDdl.js.map +1 -0
  451. package/dist/db/ZeroPush.d.ts +7 -0
  452. package/dist/db/ZeroPush.d.ts.map +1 -0
  453. package/dist/db/ZeroPush.js +126 -0
  454. package/dist/db/ZeroPush.js.map +1 -0
  455. package/dist/devices/Devices.d.ts +130 -0
  456. package/dist/devices/Devices.d.ts.map +1 -0
  457. package/dist/devices/Devices.js +769 -0
  458. package/dist/devices/Devices.js.map +1 -0
  459. package/dist/devices/Flow.d.ts +47 -0
  460. package/dist/devices/Flow.d.ts.map +1 -0
  461. package/dist/devices/Flow.js +131 -0
  462. package/dist/devices/Flow.js.map +1 -0
  463. package/dist/devices/Http.d.ts +6 -0
  464. package/dist/devices/Http.d.ts.map +1 -0
  465. package/dist/devices/Http.js +103 -0
  466. package/dist/devices/Http.js.map +1 -0
  467. package/dist/devices/module.d.ts +1313 -0
  468. package/dist/devices/module.d.ts.map +1 -0
  469. package/dist/devices/module.js +266 -0
  470. package/dist/devices/module.js.map +1 -0
  471. package/dist/durable/Cluster.d.ts +13 -0
  472. package/dist/durable/Cluster.d.ts.map +1 -0
  473. package/dist/durable/Cluster.js +57 -0
  474. package/dist/durable/Cluster.js.map +1 -0
  475. package/dist/durable/Definition.d.ts +215 -0
  476. package/dist/durable/Definition.d.ts.map +1 -0
  477. package/dist/durable/Definition.js +18 -0
  478. package/dist/durable/Definition.js.map +1 -0
  479. package/dist/durable/Schedule.d.ts +46 -0
  480. package/dist/durable/Schedule.d.ts.map +1 -0
  481. package/dist/durable/Schedule.js +120 -0
  482. package/dist/durable/Schedule.js.map +1 -0
  483. package/dist/durable/Trust.d.ts +90 -0
  484. package/dist/durable/Trust.d.ts.map +1 -0
  485. package/dist/durable/Trust.js +61 -0
  486. package/dist/durable/Trust.js.map +1 -0
  487. package/dist/enterprise/Routes.d.ts +32 -0
  488. package/dist/enterprise/Routes.d.ts.map +1 -0
  489. package/dist/enterprise/Routes.js +448 -0
  490. package/dist/enterprise/Routes.js.map +1 -0
  491. package/dist/enterprise/WorkOs.d.ts +42 -0
  492. package/dist/enterprise/WorkOs.d.ts.map +1 -0
  493. package/dist/enterprise/WorkOs.js +109 -0
  494. package/dist/enterprise/WorkOs.js.map +1 -0
  495. package/dist/files/FileTable.d.ts +937 -0
  496. package/dist/files/FileTable.d.ts.map +1 -0
  497. package/dist/files/FileTable.js +79 -0
  498. package/dist/files/FileTable.js.map +1 -0
  499. package/dist/files/Files.d.ts +169 -0
  500. package/dist/files/Files.d.ts.map +1 -0
  501. package/dist/files/Files.js +1232 -0
  502. package/dist/files/Files.js.map +1 -0
  503. package/dist/files/Http.d.ts +13 -0
  504. package/dist/files/Http.d.ts.map +1 -0
  505. package/dist/files/Http.js +30 -0
  506. package/dist/files/Http.js.map +1 -0
  507. package/dist/files/LocalStorage.d.ts +7 -0
  508. package/dist/files/LocalStorage.d.ts.map +1 -0
  509. package/dist/files/LocalStorage.js +284 -0
  510. package/dist/files/LocalStorage.js.map +1 -0
  511. package/dist/files/Providers.d.ts +64 -0
  512. package/dist/files/Providers.d.ts.map +1 -0
  513. package/dist/files/Providers.js +245 -0
  514. package/dist/files/Providers.js.map +1 -0
  515. package/dist/files/S3Storage.d.ts +27 -0
  516. package/dist/files/S3Storage.d.ts.map +1 -0
  517. package/dist/files/S3Storage.js +301 -0
  518. package/dist/files/S3Storage.js.map +1 -0
  519. package/dist/files/SigV4.d.ts +65 -0
  520. package/dist/files/SigV4.d.ts.map +1 -0
  521. package/dist/files/SigV4.js +152 -0
  522. package/dist/files/SigV4.js.map +1 -0
  523. package/dist/files/Sniff.d.ts +50 -0
  524. package/dist/files/Sniff.d.ts.map +1 -0
  525. package/dist/files/Sniff.js +223 -0
  526. package/dist/files/Sniff.js.map +1 -0
  527. package/dist/files/Storage.d.ts +75 -0
  528. package/dist/files/Storage.d.ts.map +1 -0
  529. package/dist/files/Storage.js +70 -0
  530. package/dist/files/Storage.js.map +1 -0
  531. package/dist/files/module.d.ts +666 -0
  532. package/dist/files/module.d.ts.map +1 -0
  533. package/dist/files/module.js +217 -0
  534. package/dist/files/module.js.map +1 -0
  535. package/dist/flags/module.d.ts +966 -0
  536. package/dist/flags/module.d.ts.map +1 -0
  537. package/dist/flags/module.js +146 -0
  538. package/dist/flags/module.js.map +1 -0
  539. package/dist/inbox/Flow.d.ts +49 -0
  540. package/dist/inbox/Flow.d.ts.map +1 -0
  541. package/dist/inbox/Flow.js +425 -0
  542. package/dist/inbox/Flow.js.map +1 -0
  543. package/dist/inbox/System.d.ts +11 -0
  544. package/dist/inbox/System.d.ts.map +1 -0
  545. package/dist/inbox/System.js +26 -0
  546. package/dist/inbox/System.js.map +1 -0
  547. package/dist/inbox/approvals.d.ts +1548 -0
  548. package/dist/inbox/approvals.d.ts.map +1 -0
  549. package/dist/inbox/approvals.js +268 -0
  550. package/dist/inbox/approvals.js.map +1 -0
  551. package/dist/inbox/consent.d.ts +1213 -0
  552. package/dist/inbox/consent.d.ts.map +1 -0
  553. package/dist/inbox/consent.js +281 -0
  554. package/dist/inbox/consent.js.map +1 -0
  555. package/dist/inbox/index.d.ts +2231 -0
  556. package/dist/inbox/index.d.ts.map +1 -0
  557. package/dist/inbox/index.js +22 -0
  558. package/dist/inbox/index.js.map +1 -0
  559. package/dist/inbox/notifications.d.ts +2743 -0
  560. package/dist/inbox/notifications.d.ts.map +1 -0
  561. package/dist/inbox/notifications.js +362 -0
  562. package/dist/inbox/notifications.js.map +1 -0
  563. package/dist/inbox/tables.d.ts +1992 -0
  564. package/dist/inbox/tables.d.ts.map +1 -0
  565. package/dist/inbox/tables.js +149 -0
  566. package/dist/inbox/tables.js.map +1 -0
  567. package/dist/inbox/workItems.d.ts +1188 -0
  568. package/dist/inbox/workItems.d.ts.map +1 -0
  569. package/dist/inbox/workItems.js +158 -0
  570. package/dist/inbox/workItems.js.map +1 -0
  571. package/dist/index.d.ts +152 -0
  572. package/dist/index.d.ts.map +1 -0
  573. package/dist/index.js +154 -0
  574. package/dist/index.js.map +1 -0
  575. package/dist/ingestion/Chunk.d.ts +15 -0
  576. package/dist/ingestion/Chunk.d.ts.map +1 -0
  577. package/dist/ingestion/Chunk.js +49 -0
  578. package/dist/ingestion/Chunk.js.map +1 -0
  579. package/dist/ingestion/Extract.d.ts +69 -0
  580. package/dist/ingestion/Extract.d.ts.map +1 -0
  581. package/dist/ingestion/Extract.js +376 -0
  582. package/dist/ingestion/Extract.js.map +1 -0
  583. package/dist/ingestion/ExtractChild.d.ts +2 -0
  584. package/dist/ingestion/ExtractChild.d.ts.map +1 -0
  585. package/dist/ingestion/ExtractChild.js +54 -0
  586. package/dist/ingestion/ExtractChild.js.map +1 -0
  587. package/dist/ingestion/ExtractPool.d.ts +38 -0
  588. package/dist/ingestion/ExtractPool.d.ts.map +1 -0
  589. package/dist/ingestion/ExtractPool.js +203 -0
  590. package/dist/ingestion/ExtractPool.js.map +1 -0
  591. package/dist/ingestion/Ingestion.d.ts +183 -0
  592. package/dist/ingestion/Ingestion.d.ts.map +1 -0
  593. package/dist/ingestion/Ingestion.js +650 -0
  594. package/dist/ingestion/Ingestion.js.map +1 -0
  595. package/dist/ingestion/Isolated.d.ts +18 -0
  596. package/dist/ingestion/Isolated.d.ts.map +1 -0
  597. package/dist/ingestion/Isolated.js +15 -0
  598. package/dist/ingestion/Isolated.js.map +1 -0
  599. package/dist/ingestion/Markup.d.ts +29 -0
  600. package/dist/ingestion/Markup.d.ts.map +1 -0
  601. package/dist/ingestion/Markup.js +111 -0
  602. package/dist/ingestion/Markup.js.map +1 -0
  603. package/dist/ingestion/Pdf.d.ts +6 -0
  604. package/dist/ingestion/Pdf.d.ts.map +1 -0
  605. package/dist/ingestion/Pdf.js +192 -0
  606. package/dist/ingestion/Pdf.js.map +1 -0
  607. package/dist/ingestion/Runs.d.ts +59 -0
  608. package/dist/ingestion/Runs.d.ts.map +1 -0
  609. package/dist/ingestion/Runs.js +128 -0
  610. package/dist/ingestion/Runs.js.map +1 -0
  611. package/dist/ingestion/Scrub.d.ts +16 -0
  612. package/dist/ingestion/Scrub.d.ts.map +1 -0
  613. package/dist/ingestion/Scrub.js +15 -0
  614. package/dist/ingestion/Scrub.js.map +1 -0
  615. package/dist/ingestion/Zip.d.ts +19 -0
  616. package/dist/ingestion/Zip.d.ts.map +1 -0
  617. package/dist/ingestion/Zip.js +85 -0
  618. package/dist/ingestion/Zip.js.map +1 -0
  619. package/dist/ingestion/module.d.ts +111 -0
  620. package/dist/ingestion/module.d.ts.map +1 -0
  621. package/dist/ingestion/module.js +51 -0
  622. package/dist/ingestion/module.js.map +1 -0
  623. package/dist/ingress/Definition.d.ts +146 -0
  624. package/dist/ingress/Definition.d.ts.map +1 -0
  625. package/dist/ingress/Definition.js +12 -0
  626. package/dist/ingress/Definition.js.map +1 -0
  627. package/dist/ingress/Ingress.d.ts +61 -0
  628. package/dist/ingress/Ingress.d.ts.map +1 -0
  629. package/dist/ingress/Ingress.js +929 -0
  630. package/dist/ingress/Ingress.js.map +1 -0
  631. package/dist/ingress/Verifiers.d.ts +43 -0
  632. package/dist/ingress/Verifiers.d.ts.map +1 -0
  633. package/dist/ingress/Verifiers.js +137 -0
  634. package/dist/ingress/Verifiers.js.map +1 -0
  635. package/dist/machine/MachineIdentity.d.ts +34 -0
  636. package/dist/machine/MachineIdentity.d.ts.map +1 -0
  637. package/dist/machine/MachineIdentity.js +200 -0
  638. package/dist/machine/MachineIdentity.js.map +1 -0
  639. package/dist/machine/Managed.d.ts +40 -0
  640. package/dist/machine/Managed.d.ts.map +1 -0
  641. package/dist/machine/Managed.js +163 -0
  642. package/dist/machine/Managed.js.map +1 -0
  643. package/dist/machine/OAuth.d.ts +11 -0
  644. package/dist/machine/OAuth.d.ts.map +1 -0
  645. package/dist/machine/OAuth.js +913 -0
  646. package/dist/machine/OAuth.js.map +1 -0
  647. package/dist/machine/Pages.d.ts +64 -0
  648. package/dist/machine/Pages.d.ts.map +1 -0
  649. package/dist/machine/Pages.js +54 -0
  650. package/dist/machine/Pages.js.map +1 -0
  651. package/dist/machine/Tokens.d.ts +25 -0
  652. package/dist/machine/Tokens.d.ts.map +1 -0
  653. package/dist/machine/Tokens.js +62 -0
  654. package/dist/machine/Tokens.js.map +1 -0
  655. package/dist/make/Credentials.d.ts +8 -0
  656. package/dist/make/Credentials.d.ts.map +1 -0
  657. package/dist/make/Credentials.js +29 -0
  658. package/dist/make/Credentials.js.map +1 -0
  659. package/dist/make/Example.d.ts +159 -0
  660. package/dist/make/Example.d.ts.map +1 -0
  661. package/dist/make/Example.js +94 -0
  662. package/dist/make/Example.js.map +1 -0
  663. package/dist/make/Execute.d.ts +151 -0
  664. package/dist/make/Execute.d.ts.map +1 -0
  665. package/dist/make/Execute.js +316 -0
  666. package/dist/make/Execute.js.map +1 -0
  667. package/dist/make/Http.d.ts +17 -0
  668. package/dist/make/Http.d.ts.map +1 -0
  669. package/dist/make/Http.js +63 -0
  670. package/dist/make/Http.js.map +1 -0
  671. package/dist/make/Lifecycle.d.ts +167 -0
  672. package/dist/make/Lifecycle.d.ts.map +1 -0
  673. package/dist/make/Lifecycle.js +580 -0
  674. package/dist/make/Lifecycle.js.map +1 -0
  675. package/dist/make/Manifest.d.ts +61 -0
  676. package/dist/make/Manifest.d.ts.map +1 -0
  677. package/dist/make/Manifest.js +792 -0
  678. package/dist/make/Manifest.js.map +1 -0
  679. package/dist/make/Repair.d.ts +111 -0
  680. package/dist/make/Repair.d.ts.map +1 -0
  681. package/dist/make/Repair.js +236 -0
  682. package/dist/make/Repair.js.map +1 -0
  683. package/dist/make/Runtime.d.ts +144 -0
  684. package/dist/make/Runtime.d.ts.map +1 -0
  685. package/dist/make/Runtime.js +309 -0
  686. package/dist/make/Runtime.js.map +1 -0
  687. package/dist/make/Session.d.ts +19 -0
  688. package/dist/make/Session.d.ts.map +1 -0
  689. package/dist/make/Session.js +27 -0
  690. package/dist/make/Session.js.map +1 -0
  691. package/dist/make/SqlGuard.d.ts +48 -0
  692. package/dist/make/SqlGuard.d.ts.map +1 -0
  693. package/dist/make/SqlGuard.js +333 -0
  694. package/dist/make/SqlGuard.js.map +1 -0
  695. package/dist/make/Subscribe.d.ts +18 -0
  696. package/dist/make/Subscribe.d.ts.map +1 -0
  697. package/dist/make/Subscribe.js +175 -0
  698. package/dist/make/Subscribe.js.map +1 -0
  699. package/dist/make/Validate.d.ts +47 -0
  700. package/dist/make/Validate.d.ts.map +1 -0
  701. package/dist/make/Validate.js +222 -0
  702. package/dist/make/Validate.js.map +1 -0
  703. package/dist/make/ViewStep.d.ts +27 -0
  704. package/dist/make/ViewStep.d.ts.map +1 -0
  705. package/dist/make/ViewStep.js +43 -0
  706. package/dist/make/ViewStep.js.map +1 -0
  707. package/dist/make/module.d.ts +808 -0
  708. package/dist/make/module.d.ts.map +1 -0
  709. package/dist/make/module.js +232 -0
  710. package/dist/make/module.js.map +1 -0
  711. package/dist/notifications/Decide.d.ts +29 -0
  712. package/dist/notifications/Decide.d.ts.map +1 -0
  713. package/dist/notifications/Decide.js +395 -0
  714. package/dist/notifications/Decide.js.map +1 -0
  715. package/dist/notifications/Providers.d.ts +110 -0
  716. package/dist/notifications/Providers.d.ts.map +1 -0
  717. package/dist/notifications/Providers.js +404 -0
  718. package/dist/notifications/Providers.js.map +1 -0
  719. package/dist/notifications/Push.d.ts +189 -0
  720. package/dist/notifications/Push.d.ts.map +1 -0
  721. package/dist/notifications/Push.js +457 -0
  722. package/dist/notifications/Push.js.map +1 -0
  723. package/dist/notifications/Smtp.d.ts +74 -0
  724. package/dist/notifications/Smtp.d.ts.map +1 -0
  725. package/dist/notifications/Smtp.js +344 -0
  726. package/dist/notifications/Smtp.js.map +1 -0
  727. package/dist/policy/CedarSchema.d.ts +47 -0
  728. package/dist/policy/CedarSchema.d.ts.map +1 -0
  729. package/dist/policy/CedarSchema.js +115 -0
  730. package/dist/policy/CedarSchema.js.map +1 -0
  731. package/dist/policy/Compiler.d.ts +364 -0
  732. package/dist/policy/Compiler.d.ts.map +1 -0
  733. package/dist/policy/Compiler.js +1311 -0
  734. package/dist/policy/Compiler.js.map +1 -0
  735. package/dist/policy/Policy.d.ts +70 -0
  736. package/dist/policy/Policy.d.ts.map +1 -0
  737. package/dist/policy/Policy.js +114 -0
  738. package/dist/policy/Policy.js.map +1 -0
  739. package/dist/policy/Rls.d.ts +110 -0
  740. package/dist/policy/Rls.d.ts.map +1 -0
  741. package/dist/policy/Rls.js +314 -0
  742. package/dist/policy/Rls.js.map +1 -0
  743. package/dist/policy/Row.d.ts +17 -0
  744. package/dist/policy/Row.d.ts.map +1 -0
  745. package/dist/policy/Row.js +3 -0
  746. package/dist/policy/Row.js.map +1 -0
  747. package/dist/privacy/Flow.d.ts +20 -0
  748. package/dist/privacy/Flow.d.ts.map +1 -0
  749. package/dist/privacy/Flow.js +193 -0
  750. package/dist/privacy/Flow.js.map +1 -0
  751. package/dist/privacy/Inventory.d.ts +110 -0
  752. package/dist/privacy/Inventory.d.ts.map +1 -0
  753. package/dist/privacy/Inventory.js +1704 -0
  754. package/dist/privacy/Inventory.js.map +1 -0
  755. package/dist/privacy/Sources.d.ts +86 -0
  756. package/dist/privacy/Sources.d.ts.map +1 -0
  757. package/dist/privacy/Sources.js +598 -0
  758. package/dist/privacy/Sources.js.map +1 -0
  759. package/dist/privacy/Visits.d.ts +21 -0
  760. package/dist/privacy/Visits.d.ts.map +1 -0
  761. package/dist/privacy/Visits.js +279 -0
  762. package/dist/privacy/Visits.js.map +1 -0
  763. package/dist/privacy/ZeroCvr.d.ts +15 -0
  764. package/dist/privacy/ZeroCvr.d.ts.map +1 -0
  765. package/dist/privacy/ZeroCvr.js +63 -0
  766. package/dist/privacy/ZeroCvr.js.map +1 -0
  767. package/dist/privacy/module.d.ts +2505 -0
  768. package/dist/privacy/module.d.ts.map +1 -0
  769. package/dist/privacy/module.js +228 -0
  770. package/dist/privacy/module.js.map +1 -0
  771. package/dist/progress/module.d.ts +1572 -0
  772. package/dist/progress/module.d.ts.map +1 -0
  773. package/dist/progress/module.js +139 -0
  774. package/dist/progress/module.js.map +1 -0
  775. package/dist/proposals/module.d.ts +275 -0
  776. package/dist/proposals/module.d.ts.map +1 -0
  777. package/dist/proposals/module.js +269 -0
  778. package/dist/proposals/module.js.map +1 -0
  779. package/dist/query/module.d.ts +91 -0
  780. package/dist/query/module.d.ts.map +1 -0
  781. package/dist/query/module.js +50 -0
  782. package/dist/query/module.js.map +1 -0
  783. package/dist/records/Access.d.ts +26 -0
  784. package/dist/records/Access.d.ts.map +1 -0
  785. package/dist/records/Access.js +43 -0
  786. package/dist/records/Access.js.map +1 -0
  787. package/dist/records/References.d.ts +18 -0
  788. package/dist/records/References.d.ts.map +1 -0
  789. package/dist/records/References.js +47 -0
  790. package/dist/records/References.js.map +1 -0
  791. package/dist/runtime/bun.d.ts +29 -0
  792. package/dist/runtime/bun.d.ts.map +1 -0
  793. package/dist/runtime/bun.js +71 -0
  794. package/dist/runtime/bun.js.map +1 -0
  795. package/dist/runtime/idle.d.ts +5 -0
  796. package/dist/runtime/idle.d.ts.map +1 -0
  797. package/dist/runtime/idle.js +61 -0
  798. package/dist/runtime/idle.js.map +1 -0
  799. package/dist/runtime/node.d.ts +36 -0
  800. package/dist/runtime/node.d.ts.map +1 -0
  801. package/dist/runtime/node.js +86 -0
  802. package/dist/runtime/node.js.map +1 -0
  803. package/dist/runtime/resolve.d.ts +8 -0
  804. package/dist/runtime/resolve.d.ts.map +1 -0
  805. package/dist/runtime/resolve.js +136 -0
  806. package/dist/runtime/resolve.js.map +1 -0
  807. package/dist/sandbox/Sandbox.d.ts +86 -0
  808. package/dist/sandbox/Sandbox.d.ts.map +1 -0
  809. package/dist/sandbox/Sandbox.js +246 -0
  810. package/dist/sandbox/Sandbox.js.map +1 -0
  811. package/dist/sandbox/worker.d.ts +93 -0
  812. package/dist/sandbox/worker.d.ts.map +1 -0
  813. package/dist/sandbox/worker.js +503 -0
  814. package/dist/sandbox/worker.js.map +1 -0
  815. package/dist/scheduler/Automations.d.ts +99 -0
  816. package/dist/scheduler/Automations.d.ts.map +1 -0
  817. package/dist/scheduler/Automations.js +247 -0
  818. package/dist/scheduler/Automations.js.map +1 -0
  819. package/dist/scheduler/History.d.ts +61 -0
  820. package/dist/scheduler/History.d.ts.map +1 -0
  821. package/dist/scheduler/History.js +154 -0
  822. package/dist/scheduler/History.js.map +1 -0
  823. package/dist/scheduler/module.d.ts +2365 -0
  824. package/dist/scheduler/module.d.ts.map +1 -0
  825. package/dist/scheduler/module.js +370 -0
  826. package/dist/scheduler/module.js.map +1 -0
  827. package/dist/search/RecordLock.d.ts +22 -0
  828. package/dist/search/RecordLock.d.ts.map +1 -0
  829. package/dist/search/RecordLock.js +21 -0
  830. package/dist/search/RecordLock.js.map +1 -0
  831. package/dist/search/Search.d.ts +63 -0
  832. package/dist/search/Search.d.ts.map +1 -0
  833. package/dist/search/Search.js +424 -0
  834. package/dist/search/Search.js.map +1 -0
  835. package/dist/search/Sources.d.ts +56 -0
  836. package/dist/search/Sources.d.ts.map +1 -0
  837. package/dist/search/Sources.js +121 -0
  838. package/dist/search/Sources.js.map +1 -0
  839. package/dist/search/module.d.ts +72 -0
  840. package/dist/search/module.d.ts.map +1 -0
  841. package/dist/search/module.js +44 -0
  842. package/dist/search/module.js.map +1 -0
  843. package/dist/settings/module.d.ts +677 -0
  844. package/dist/settings/module.d.ts.map +1 -0
  845. package/dist/settings/module.js +103 -0
  846. package/dist/settings/module.js.map +1 -0
  847. package/dist/sharing/module.d.ts +1105 -0
  848. package/dist/sharing/module.d.ts.map +1 -0
  849. package/dist/sharing/module.js +295 -0
  850. package/dist/sharing/module.js.map +1 -0
  851. package/dist/spaces/module.d.ts +1787 -0
  852. package/dist/spaces/module.d.ts.map +1 -0
  853. package/dist/spaces/module.js +248 -0
  854. package/dist/spaces/module.js.map +1 -0
  855. package/dist/surfaces/Agent.d.ts +89 -0
  856. package/dist/surfaces/Agent.d.ts.map +1 -0
  857. package/dist/surfaces/Agent.js +112 -0
  858. package/dist/surfaces/Agent.js.map +1 -0
  859. package/dist/surfaces/CookieGuard.d.ts +77 -0
  860. package/dist/surfaces/CookieGuard.d.ts.map +1 -0
  861. package/dist/surfaces/CookieGuard.js +373 -0
  862. package/dist/surfaces/CookieGuard.js.map +1 -0
  863. package/dist/surfaces/Http.d.ts +15 -0
  864. package/dist/surfaces/Http.d.ts.map +1 -0
  865. package/dist/surfaces/Http.js +250 -0
  866. package/dist/surfaces/Http.js.map +1 -0
  867. package/dist/surfaces/Mcp.d.ts +90 -0
  868. package/dist/surfaces/Mcp.d.ts.map +1 -0
  869. package/dist/surfaces/Mcp.js +443 -0
  870. package/dist/surfaces/Mcp.js.map +1 -0
  871. package/dist/surfaces/Rpc.d.ts +15 -0
  872. package/dist/surfaces/Rpc.d.ts.map +1 -0
  873. package/dist/surfaces/Rpc.js +68 -0
  874. package/dist/surfaces/Rpc.js.map +1 -0
  875. package/dist/surfaces/headers.d.ts +9 -0
  876. package/dist/surfaces/headers.d.ts.map +1 -0
  877. package/dist/surfaces/headers.js +15 -0
  878. package/dist/surfaces/headers.js.map +1 -0
  879. package/dist/surfaces/request.d.ts +68 -0
  880. package/dist/surfaces/request.d.ts.map +1 -0
  881. package/dist/surfaces/request.js +130 -0
  882. package/dist/surfaces/request.js.map +1 -0
  883. package/dist/telemetry/module.d.ts +74 -0
  884. package/dist/telemetry/module.d.ts.map +1 -0
  885. package/dist/telemetry/module.js +77 -0
  886. package/dist/telemetry/module.js.map +1 -0
  887. package/dist/versioning/module.d.ts +231 -0
  888. package/dist/versioning/module.d.ts.map +1 -0
  889. package/dist/versioning/module.js +151 -0
  890. package/dist/versioning/module.js.map +1 -0
  891. package/package.json +71 -3
  892. package/src/AccountMail.ts +218 -0
  893. package/src/AppConfig.ts +148 -0
  894. package/src/Approvals.ts +555 -0
  895. package/src/Audit.ts +381 -0
  896. package/src/AuthSeam.ts +136 -0
  897. package/src/Authority.ts +577 -0
  898. package/src/Avatars.ts +172 -0
  899. package/src/Base64url.ts +23 -0
  900. package/src/BasePath.ts +80 -0
  901. package/src/CallActed.ts +10 -0
  902. package/src/Config.ts +857 -0
  903. package/src/DeliveryPolicy.ts +52 -0
  904. package/src/DesktopSignIn.ts +181 -0
  905. package/src/Directory.ts +1792 -0
  906. package/src/Flags.ts +281 -0
  907. package/src/Gate.ts +159 -0
  908. package/src/Hash.ts +14 -0
  909. package/src/Identity.ts +1811 -0
  910. package/src/IntervalJob.ts +96 -0
  911. package/src/Invocation.ts +2387 -0
  912. package/src/KernelHandlers.ts +29 -0
  913. package/src/KernelModule.ts +165 -0
  914. package/src/MemberRoutes.ts +146 -0
  915. package/src/Module.ts +573 -0
  916. package/src/ModuleIdentity.ts +134 -0
  917. package/src/Notifications.ts +665 -0
  918. package/src/Outbox.ts +761 -0
  919. package/src/Privacy.ts +265 -0
  920. package/src/Progress.ts +360 -0
  921. package/src/QuerySurface.ts +559 -0
  922. package/src/QueryViews.ts +165 -0
  923. package/src/Readiness.ts +284 -0
  924. package/src/Redact.ts +22 -0
  925. package/src/Registry.ts +399 -0
  926. package/src/Release.ts +1197 -0
  927. package/src/Retention.ts +167 -0
  928. package/src/Scheduler.ts +657 -0
  929. package/src/Server.ts +1838 -0
  930. package/src/Sessions.ts +56 -0
  931. package/src/Settings.ts +312 -0
  932. package/src/Sharing.ts +525 -0
  933. package/src/Sync.ts +1478 -0
  934. package/src/Telemetry.ts +754 -0
  935. package/src/Versioning.ts +588 -0
  936. package/src/WorkItems.ts +367 -0
  937. package/src/Workflows.ts +746 -0
  938. package/src/agent/Admission.ts +37 -0
  939. package/src/agent/Channels.ts +58 -0
  940. package/src/agent/Context.ts +430 -0
  941. package/src/agent/Http.ts +523 -0
  942. package/src/agent/Metering.ts +625 -0
  943. package/src/agent/ModelSetup.ts +414 -0
  944. package/src/agent/Models.ts +850 -0
  945. package/src/agent/Processors.ts +156 -0
  946. package/src/agent/Queue.ts +97 -0
  947. package/src/agent/Receipts.ts +192 -0
  948. package/src/agent/Resources.ts +376 -0
  949. package/src/agent/Run.ts +3762 -0
  950. package/src/agent/Runtime.ts +635 -0
  951. package/src/agent/Settings.ts +171 -0
  952. package/src/agent/Skills.ts +118 -0
  953. package/src/agent/Store.ts +73 -0
  954. package/src/agent/ToolSearch.ts +152 -0
  955. package/src/agent/index.ts +68 -0
  956. package/src/agent/migrations/agent/0000_agent.sql +162 -0
  957. package/src/agent/migrations/agent/0001_model_call.sql +33 -0
  958. package/src/agent/migrations/agent/0002_device.sql +2 -0
  959. package/src/agent/migrations/agent/0003_authority.sql +1 -0
  960. package/src/agent/migrations/agent/0004_budget_alert.sql +2 -0
  961. package/src/agent/migrations/agent/0005_feedback.sql +13 -0
  962. package/src/agent/migrations/agent/0095_run_options.sql +3 -0
  963. package/src/agent/migrations/agent/0096_conversation_meta.sql +7 -0
  964. package/src/agent/migrations/agent/0097_submission.sql +26 -0
  965. package/src/agent/migrations/agent/0098_threads.sql +21 -0
  966. package/src/agent/migrations/agent/0099_submission_refused.sql +4 -0
  967. package/src/agent/migrations/agent/0142_teams.sql +19 -0
  968. package/src/agent/module.ts +1793 -0
  969. package/src/appState/Sweep.ts +66 -0
  970. package/src/appState/migrations/0000_app_state.sql +35 -0
  971. package/src/appState/module.ts +418 -0
  972. package/src/audit/migrations/README.md +1 -0
  973. package/src/audit/module.ts +95 -0
  974. package/src/auth/AuthProvider.ts +293 -0
  975. package/src/auth/BetterAuthProvider.ts +476 -0
  976. package/src/auth/Methods.ts +7 -0
  977. package/src/auth/SessionTokens.ts +156 -0
  978. package/src/collab/Collab.ts +708 -0
  979. package/src/collab/Housekeeping.ts +193 -0
  980. package/src/collab/LiveCopy.ts +98 -0
  981. package/src/collab/Socket.ts +380 -0
  982. package/src/collab/Store.ts +105 -0
  983. package/src/collab/Ydoc.ts +337 -0
  984. package/src/collab/derive/bundle.gen.ts +2 -0
  985. package/src/collab/derive/entry.ts +34 -0
  986. package/src/collab/derive/polyfill.ts +15 -0
  987. package/src/collab/migrations/.gitkeep +0 -0
  988. package/src/collab/module.ts +237 -0
  989. package/src/connections/Connections.ts +2315 -0
  990. package/src/connections/Connector.ts +304 -0
  991. package/src/connections/Crypto.ts +134 -0
  992. package/src/connections/Destinations.ts +351 -0
  993. package/src/connections/Discovery.ts +251 -0
  994. package/src/connections/EffectKinds.ts +30 -0
  995. package/src/connections/Effects.ts +541 -0
  996. package/src/connections/Metering.ts +205 -0
  997. package/src/connections/ProviderApi.ts +137 -0
  998. package/src/connections/Secrets.ts +581 -0
  999. package/src/connections/Sync.ts +318 -0
  1000. package/src/connections/migrations/.gitkeep +0 -0
  1001. package/src/connections/module.ts +584 -0
  1002. package/src/data/Corpus.ts +434 -0
  1003. package/src/data/Datasets.ts +479 -0
  1004. package/src/data/Programs.ts +285 -0
  1005. package/src/data/migrations/README.md +1 -0
  1006. package/src/data/module.ts +177 -0
  1007. package/src/db/Bootstrap.ts +2832 -0
  1008. package/src/db/Catalog.ts +10 -0
  1009. package/src/db/Conflicts.ts +42 -0
  1010. package/src/db/DirectoryLock.ts +19 -0
  1011. package/src/db/HandlerGate.ts +107 -0
  1012. package/src/db/Host.ts +250 -0
  1013. package/src/db/KernelSchema.ts +4422 -0
  1014. package/src/db/MigrationCheck.ts +221 -0
  1015. package/src/db/QueryViewCheck.ts +1035 -0
  1016. package/src/db/ReadOnly.ts +23 -0
  1017. package/src/db/Scram.ts +20 -0
  1018. package/src/db/SqlState.ts +77 -0
  1019. package/src/db/Startup.ts +25 -0
  1020. package/src/db/ZeroDdl.ts +272 -0
  1021. package/src/db/ZeroPush.ts +128 -0
  1022. package/src/db/schema.snapshot.json +13831 -0
  1023. package/src/devices/Devices.ts +1219 -0
  1024. package/src/devices/Flow.ts +198 -0
  1025. package/src/devices/Http.ts +212 -0
  1026. package/src/devices/migrations/0000_devices.sql +53 -0
  1027. package/src/devices/migrations/0001_parent_run.sql +2 -0
  1028. package/src/devices/migrations/0002_authority.sql +1 -0
  1029. package/src/devices/migrations/0003_follow_up.sql +4 -0
  1030. package/src/devices/migrations/0004_commands.sql +30 -0
  1031. package/src/devices/migrations/0005_command_cancel.sql +7 -0
  1032. package/src/devices/module.ts +313 -0
  1033. package/src/durable/Cluster.ts +90 -0
  1034. package/src/durable/Definition.ts +244 -0
  1035. package/src/durable/Schedule.ts +155 -0
  1036. package/src/durable/Trust.ts +149 -0
  1037. package/src/enterprise/Routes.ts +501 -0
  1038. package/src/enterprise/WorkOs.ts +133 -0
  1039. package/src/files/FileTable.ts +84 -0
  1040. package/src/files/Files.ts +1652 -0
  1041. package/src/files/Http.ts +46 -0
  1042. package/src/files/LocalStorage.ts +348 -0
  1043. package/src/files/Providers.ts +356 -0
  1044. package/src/files/S3Storage.ts +403 -0
  1045. package/src/files/SigV4.ts +222 -0
  1046. package/src/files/Sniff.ts +218 -0
  1047. package/src/files/Storage.ts +143 -0
  1048. package/src/files/migrations/README.md +1 -0
  1049. package/src/files/module.ts +282 -0
  1050. package/src/flags/migrations/0000_flags.sql +20 -0
  1051. package/src/flags/module.ts +178 -0
  1052. package/src/inbox/Flow.ts +548 -0
  1053. package/src/inbox/System.ts +33 -0
  1054. package/src/inbox/approvals.ts +335 -0
  1055. package/src/inbox/consent.ts +331 -0
  1056. package/src/inbox/index.ts +24 -0
  1057. package/src/inbox/migrations/approvals/0000_approvals.sql +36 -0
  1058. package/src/inbox/migrations/approvals/0001_provenance.sql +1 -0
  1059. package/src/inbox/migrations/approvals/0002_withdrawn.sql +3 -0
  1060. package/src/inbox/migrations/approvals/0003_title.sql +11 -0
  1061. package/src/inbox/migrations/consent/0000_consent.sql +31 -0
  1062. package/src/inbox/migrations/consent/0001_consent_revoked.sql +3 -0
  1063. package/src/inbox/migrations/consent/0002_permission_request.sql +1 -0
  1064. package/src/inbox/migrations/consent/0003_title.sql +11 -0
  1065. package/src/inbox/migrations/inbox/0000_work_items.sql +31 -0
  1066. package/src/inbox/migrations/notifications/0000_notifications.sql +66 -0
  1067. package/src/inbox/notifications.ts +471 -0
  1068. package/src/inbox/tables.ts +163 -0
  1069. package/src/inbox/workItems.ts +199 -0
  1070. package/src/index.ts +229 -0
  1071. package/src/ingestion/Chunk.ts +49 -0
  1072. package/src/ingestion/Extract.ts +387 -0
  1073. package/src/ingestion/ExtractChild.ts +67 -0
  1074. package/src/ingestion/ExtractPool.ts +270 -0
  1075. package/src/ingestion/Ingestion.ts +929 -0
  1076. package/src/ingestion/Isolated.ts +26 -0
  1077. package/src/ingestion/Markup.ts +117 -0
  1078. package/src/ingestion/Pdf.ts +167 -0
  1079. package/src/ingestion/Runs.ts +192 -0
  1080. package/src/ingestion/Scrub.ts +22 -0
  1081. package/src/ingestion/Zip.ts +87 -0
  1082. package/src/ingestion/migrations/README.md +1 -0
  1083. package/src/ingestion/module.ts +65 -0
  1084. package/src/ingress/Definition.ts +158 -0
  1085. package/src/ingress/Ingress.ts +1220 -0
  1086. package/src/ingress/Verifiers.ts +166 -0
  1087. package/src/machine/MachineIdentity.ts +310 -0
  1088. package/src/machine/Managed.ts +228 -0
  1089. package/src/machine/OAuth.ts +1140 -0
  1090. package/src/machine/Pages.ts +139 -0
  1091. package/src/machine/Tokens.ts +75 -0
  1092. package/src/make/Credentials.ts +36 -0
  1093. package/src/make/Example.ts +104 -0
  1094. package/src/make/Execute.ts +534 -0
  1095. package/src/make/Http.ts +71 -0
  1096. package/src/make/Lifecycle.ts +911 -0
  1097. package/src/make/Manifest.ts +884 -0
  1098. package/src/make/Repair.ts +262 -0
  1099. package/src/make/Runtime.ts +494 -0
  1100. package/src/make/Session.ts +33 -0
  1101. package/src/make/SqlGuard.ts +362 -0
  1102. package/src/make/Subscribe.ts +282 -0
  1103. package/src/make/Validate.ts +247 -0
  1104. package/src/make/ViewStep.ts +64 -0
  1105. package/src/make/migrations/README.md +1 -0
  1106. package/src/make/module.ts +261 -0
  1107. package/src/notifications/Decide.ts +483 -0
  1108. package/src/notifications/Providers.ts +532 -0
  1109. package/src/notifications/Push.ts +594 -0
  1110. package/src/notifications/Smtp.ts +379 -0
  1111. package/src/policy/CedarSchema.ts +156 -0
  1112. package/src/policy/Compiler.ts +1627 -0
  1113. package/src/policy/Policy.ts +178 -0
  1114. package/src/policy/Rls.ts +460 -0
  1115. package/src/policy/Row.ts +15 -0
  1116. package/src/privacy/Flow.ts +283 -0
  1117. package/src/privacy/Inventory.ts +2414 -0
  1118. package/src/privacy/Sources.ts +831 -0
  1119. package/src/privacy/Visits.ts +339 -0
  1120. package/src/privacy/ZeroCvr.ts +66 -0
  1121. package/src/privacy/migrations/0000_privacy.sql +48 -0
  1122. package/src/privacy/module.ts +280 -0
  1123. package/src/progress/migrations/0000_progress.sql +27 -0
  1124. package/src/progress/migrations/0001_notify.sql +1 -0
  1125. package/src/progress/module.ts +161 -0
  1126. package/src/proposals/migrations/README.md +1 -0
  1127. package/src/proposals/module.ts +338 -0
  1128. package/src/query/migrations/README.md +1 -0
  1129. package/src/query/module.ts +66 -0
  1130. package/src/records/Access.ts +97 -0
  1131. package/src/records/References.ts +65 -0
  1132. package/src/runtime/bun.ts +131 -0
  1133. package/src/runtime/idle.ts +88 -0
  1134. package/src/runtime/node.ts +140 -0
  1135. package/src/runtime/resolve.ts +141 -0
  1136. package/src/sandbox/Sandbox.ts +330 -0
  1137. package/src/sandbox/worker.ts +577 -0
  1138. package/src/scheduler/Automations.ts +319 -0
  1139. package/src/scheduler/History.ts +231 -0
  1140. package/src/scheduler/migrations/0000_schedules.sql +11 -0
  1141. package/src/scheduler/migrations/0001_resumed_at.sql +1 -0
  1142. package/src/scheduler/migrations/0002_origin.sql +3 -0
  1143. package/src/scheduler/migrations/0003_authority.sql +1 -0
  1144. package/src/scheduler/migrations/0004_operate.sql +18 -0
  1145. package/src/scheduler/module.ts +445 -0
  1146. package/src/search/RecordLock.ts +25 -0
  1147. package/src/search/Search.ts +563 -0
  1148. package/src/search/Sources.ts +157 -0
  1149. package/src/search/migrations/README.md +1 -0
  1150. package/src/search/module.ts +49 -0
  1151. package/src/settings/migrations/0000_settings.sql +15 -0
  1152. package/src/settings/module.ts +126 -0
  1153. package/src/sharing/migrations/0000_access_requests.sql +17 -0
  1154. package/src/sharing/module.ts +351 -0
  1155. package/src/spaces/migrations/0000_spaces.sql +35 -0
  1156. package/src/spaces/module.ts +287 -0
  1157. package/src/surfaces/Agent.ts +224 -0
  1158. package/src/surfaces/CookieGuard.ts +433 -0
  1159. package/src/surfaces/Http.ts +341 -0
  1160. package/src/surfaces/Mcp.ts +585 -0
  1161. package/src/surfaces/Rpc.ts +101 -0
  1162. package/src/surfaces/headers.ts +16 -0
  1163. package/src/surfaces/request.ts +173 -0
  1164. package/src/telemetry/migrations/.gitkeep +0 -0
  1165. package/src/telemetry/module.ts +94 -0
  1166. package/src/versioning/migrations/.gitkeep +0 -0
  1167. package/src/versioning/module.ts +194 -0
@@ -0,0 +1,3762 @@
1
+ /**
2
+ * A durable agent run (the AgentRuntime contract): the kernel workflow `eloxiv.agent-run`, one execution per
3
+ * run, keyed by the run id, acting as the person the run serves.
4
+ *
5
+ * start the run's spec: limits, tools, the conversation's agent session (issued once)
6
+ * model/<i> meter calls of this step lost to a crash, assemble the context (compacting the conversation
7
+ * when it is over budget and the compaction fits the run's limits), reserve the call's worst
8
+ * case against the budgets (recording it as started), call the model, and settle its usage and
9
+ * persist the assistant message and context inventory in one transaction. Fenced: the message's
10
+ * id is the step's, so one response is applied per step. A call whose answer was lost to a
11
+ * crash is made again; both attempts are metered (the lost one at what it reserved)
12
+ * tool/<i>/<call> invoke the tool's action through the invocation path, agent-originated through the agent
13
+ * session, with the step's idempotency key (`<execution id>:tool/<i>/<call>`): a step re-run
14
+ * after the action committed gets the replay receipt, never a second effect. Persist the result
15
+ * (consent) a call held for consent suspends the run until the person decides (`consent.decided`
16
+ * resumes it), then `tool/<i>/<call>/decided` runs it once (or reports the refusal)
17
+ * delegate/<i>/<call> start a child run (Delegation) and wait, durably, for its answer
18
+ * team/<i>/<call> the team tool's spawn: start a seat (a child run its parent does not wait for)
19
+ * team/<i>/<call>/<k> the team tool's wait, send or list; a wait that finds nothing yet waits, durably, for its
20
+ * team (a seat's end, a message) and looks again in step k + 1
21
+ * finish record the outcome, end the event stream, and tell a parent run
22
+ *
23
+ * Every step is journalled (Workflow): a run killed at any point resumes from its last journalled step on any
24
+ * kernel that takes its shard, and only one kernel advances a run at a time (shard locks), with the step ids
25
+ * above as a second fence in the database.
26
+ *
27
+ * Loop limits: model calls (`maxSteps`) and tokens (`maxTokens`, each call's worst case before it is made), counting
28
+ * compaction, lost attempts and sub-agents (whose limits are carved from what is left); wall time (`maxWallMs`).
29
+ * Cancellation is durable state (`cancel_requested_at`): read before every step, where a wait is recorded, where a
30
+ * sub-agent starts, where a consent decision is applied, and inside every tool call's own transaction (holding the
31
+ * run's row until it commits); a waiting run is also signalled. Nothing runs after a cancellation commits, and the
32
+ * run ends `cancelled`: a reply in flight (a model's or a device's) is applied holding the run's row, so one that
33
+ * arrives after the cancellation committed is metered and recorded as `reply-discarded`, never applied, and `finish`
34
+ * records `cancelled` for a run whose flag is set. `agent.cancel` holds the same row, so a run that finished first
35
+ * keeps its outcome and the cancellation is refused. A sub-agent reads its parent's flag too, holding its row first.
36
+ */
37
+ import type {
38
+ ExecutionIdentity,
39
+ ModelUsage as ModelUsageType,
40
+ RunLimits,
41
+ RunVerification,
42
+ ToolCall,
43
+ ToolDefinition,
44
+ } from "@eloxiv/contracts"
45
+ import {
46
+ decisionLabel,
47
+ AgentToolPolicy,
48
+ AuthorityChain,
49
+ AuthorityRecord,
50
+ Forbidden,
51
+ ModelUsage,
52
+ RunDevice,
53
+ RunLimits as RunLimitsSchema,
54
+ RunContinuation,
55
+ RunMode,
56
+ RunVerification as RunVerificationSchema,
57
+ StopReason,
58
+ TurnUsage,
59
+ WorkflowFailed,
60
+ WriteReceipt,
61
+ } from "@eloxiv/contracts"
62
+ import { Cause, Context, Effect, Option, Schema } from "effect"
63
+ import { SqlClient } from "effect/sql"
64
+ import type { ModelMessage } from "ai"
65
+ import { Audit } from "../Audit.ts"
66
+ import { Authority, extend, type AssertRequest, type Asserted } from "../Authority.ts"
67
+ import { defineKernelWorkflow } from "../durable/Trust.ts"
68
+ import { canonicalJson, sha256 } from "../Hash.ts"
69
+ import { Identity, SYSTEM_ACTOR } from "../Identity.ts"
70
+ import { Invocation } from "../Invocation.ts"
71
+ import { asSystem } from "../inbox/System.ts"
72
+ import { Outbox, type ReactionEvent } from "../Outbox.ts"
73
+ import { QueryViews } from "../QueryViews.ts"
74
+ import { Registry } from "../Registry.ts"
75
+ import { scopeAllows } from "../machine/Tokens.ts"
76
+ import { AgentTools, type AgentToolResult } from "../surfaces/Agent.ts"
77
+ import type { WorkflowsShape } from "../Workflows.ts"
78
+ import { assemble, ATTACHMENT_LIMITS, countTokens, type StoredMessage } from "./Context.ts"
79
+ import { abandonCalls, Metering, recordSubscriptionUsage, settleCall } from "./Metering.ts"
80
+ import { ModelProviders } from "./Models.ts"
81
+ import { PERSON_ONLY_ACTIONS } from "./module.ts"
82
+ import { chunkGuard, finalGuard, toolGuard, type ProcessorRun, type Tripped } from "./Processors.ts"
83
+ import { annotation, checkMessage, flagged, needsChallenge, writeReceipt, type ToolReceipt } from "./Receipts.ts"
84
+ import { searchTools, toolIndex, TOOL_SEARCH, toolSearchDefinition } from "./ToolSearch.ts"
85
+ import { AgentResources } from "./Resources.ts"
86
+ import { AgentHub, AgentSettings } from "./Settings.ts"
87
+ import { promoteQueued } from "./Queue.ts"
88
+ import { AGENT_MODULE, appendEvent, asAgent, clockSeq, inAgent, inAgentFor, mayReply } from "./Store.ts"
89
+
90
+ export const AGENT_RUN_WORKFLOW = "eloxiv.agent-run"
91
+
92
+ /** The action the query surface publishes (another part of the kernel); used when the app has it. */
93
+ export const QUERY_ACTION = "eloxiv.query"
94
+
95
+ type RunServices =
96
+ | SqlClient.SqlClient
97
+ | ModelProviders
98
+ | Metering
99
+ | AgentResources
100
+ | AgentTools
101
+ | AgentSettings
102
+ | AgentHub
103
+ | Identity
104
+ | Outbox
105
+ | QueryViews
106
+ | Audit
107
+ | Authority
108
+ | Registry
109
+ | Invocation
110
+
111
+ /**
112
+ * How a run acts, recorded on it when it is queued (`run.options`): its mode, its tool policy (the organisation's
113
+ * `agent.tools`), its delegation depth (0 for a person's run) and, for a sub-agent, the profile it runs as.
114
+ */
115
+ const RunOptions = Schema.Struct({
116
+ mode: RunMode,
117
+ tools: AgentToolPolicy,
118
+ depth: Schema.Number,
119
+ profile: Schema.optionalKey(Schema.String),
120
+ /** A seat of its parent's team (the `team` tool's `spawn`): its name. The run then has the team tool for messages. */
121
+ seat: Schema.optionalKey(Schema.String),
122
+ /** How many files the person attached to the message that started the run (their content is read at its start). */
123
+ attachments: Schema.optionalKey(Schema.Number),
124
+ /** The interrupted turn it continues (`agent.continue`, or an automatic continuation). */
125
+ continuation: Schema.optionalKey(RunContinuation),
126
+ /**
127
+ * The agent edit group its changes are kept with (the Versioning contract): the conversation and the person's
128
+ * message that started the run, or its parent's (a sub-agent's). Absent for a run queued before groups were kept.
129
+ */
130
+ editGroup: Schema.optionalKey(
131
+ Schema.Struct({ conversationId: Schema.String, messageId: Schema.NullOr(Schema.String) }),
132
+ ),
133
+ })
134
+ type RunOptions = typeof RunOptions.Type
135
+ const DEFAULT_OPTIONS: RunOptions = { mode: "act", tools: { discovery: "all" }, depth: 0 }
136
+ // (A sub-agent queued before options were recorded is at depth 1.)
137
+ const optionsOf = (spec: Spec): RunOptions =>
138
+ spec.options ?? (spec.kind === "subagent" ? { ...DEFAULT_OPTIONS, depth: 1 } : DEFAULT_OPTIONS)
139
+
140
+ const Spec = Schema.Struct({
141
+ runId: Schema.String,
142
+ orgId: Schema.String,
143
+ userId: Schema.String,
144
+ conversationId: Schema.String,
145
+ parentRunId: Schema.NullOr(Schema.String),
146
+ kind: Schema.String,
147
+ limits: RunLimitsSchema,
148
+ tools: Schema.NullOr(Schema.Array(Schema.String)),
149
+ agentSessionId: Schema.NullOr(Schema.String),
150
+ startedAt: Schema.Number,
151
+ /** Where the run executes instead of the deployment's model: one of the person's paired devices. */
152
+ device: Schema.optionalKey(Schema.NullOr(RunDevice)),
153
+ /**
154
+ * The authority of the call that started the run (`agent.send`): its scope, which every tool call stays within
155
+ * (beside the run's own tool rules), and its chain, which every tool call and every read or write the run makes on
156
+ * the person's behalf asserts (Authority), with the conversation's agent session. A delegate inherits it.
157
+ * `unrecorded`: a run queued before authorities were recorded, which acts on nothing.
158
+ */
159
+ authority: Schema.optionalKey(Schema.Union([AuthorityRecord, Schema.Literal("unrecorded")])),
160
+ /** How the run acts (recorded when it was queued; absent for a run queued before options were). */
161
+ options: Schema.optionalKey(RunOptions),
162
+ /** The conversation's owner, when it is not the run's person (a reply in a conversation shared with them). */
163
+ conversationOwner: Schema.optionalKey(Schema.String),
164
+ /**
165
+ * The run's agent edit group (the Versioning contract): the run, and the conversation and message that started its
166
+ * top-level run (a sub-agent's, its parent's). Every tool call carries it, so the changes it makes are kept with it.
167
+ */
168
+ editGroup: Schema.optionalKey(
169
+ Schema.Struct({ runId: Schema.String, conversationId: Schema.String, messageId: Schema.NullOr(Schema.String) }),
170
+ ),
171
+ })
172
+ type Spec = typeof Spec.Type
173
+
174
+ const ToolCallSchema = Schema.Struct({ toolCallId: Schema.String, toolName: Schema.String, input: Schema.Unknown })
175
+
176
+ const ModelOutcome = Schema.Union([
177
+ Schema.Struct({
178
+ kind: Schema.Literal("response"),
179
+ text: Schema.String,
180
+ toolCalls: Schema.Array(ToolCallSchema),
181
+ usage: ModelUsage,
182
+ /** Every model call the step made (lost attempts, compaction and this one) and their tokens: the run's limits count them. */
183
+ calls: Schema.optionalKey(Schema.Number),
184
+ tokens: Schema.optionalKey(Schema.Number),
185
+ }),
186
+ Schema.Struct({
187
+ kind: Schema.Literal("stop"),
188
+ reason: StopReason,
189
+ message: Schema.String,
190
+ /** A transient failure of the model call (the provider rate-limited or timed it out): the turn may continue. */
191
+ retryable: Schema.optionalKey(Schema.Boolean),
192
+ }),
193
+ ])
194
+ type ModelOutcome = typeof ModelOutcome.Type
195
+
196
+ const Decision = Schema.Union([
197
+ Schema.Struct({ kind: Schema.Literal("consent"), status: Schema.Literals(["approved", "rejected"]) }),
198
+ Schema.Struct({ kind: Schema.Literal("cancel") }),
199
+ Schema.Struct({ kind: Schema.Literal("child"), status: Schema.String, result: Schema.NullOr(Schema.String) }),
200
+ /** A device turn the run waits for settled (`devices.turnSettled`). */
201
+ Schema.Struct({ kind: Schema.Literal("device"), status: Schema.String }),
202
+ /** A seat of the run's team finished, or a message arrived for it (`team` waits). */
203
+ Schema.Struct({ kind: Schema.Literal("team") }),
204
+ ])
205
+ type Decision = typeof Decision.Type
206
+
207
+ /** What a run (or a sub-agent, for its parent) has spent of its limits: model calls and tokens. */
208
+ const Consumed = Schema.Struct({ calls: Schema.Number, tokens: Schema.Number })
209
+ type Consumed = typeof Consumed.Type
210
+
211
+ const ToolOutcome = Schema.Union([
212
+ Schema.Struct({
213
+ kind: Schema.Literal("result"),
214
+ result: Schema.Unknown,
215
+ /** A sub-agent's answer: what it spent, which its parent's limits count. */
216
+ consumed: Schema.optionalKey(Consumed),
217
+ /** A processor tripped its guard on this result: the run stops before its next model call. */
218
+ tripped: Schema.optionalKey(Schema.Struct({ processor: Schema.String, reason: Schema.String })),
219
+ }),
220
+ Schema.Struct({
221
+ kind: Schema.Literal("consent"),
222
+ consentId: Schema.String,
223
+ signal: Schema.String,
224
+ decided: Schema.NullOr(Decision),
225
+ }),
226
+ Schema.Struct({ kind: Schema.Literal("started"), childRunId: Schema.String, signal: Schema.String }),
227
+ Schema.Struct({ kind: Schema.Literal("cancelled") }),
228
+ ])
229
+ type ToolOutcome = typeof ToolOutcome.Type
230
+
231
+ const Finished = Schema.Struct({
232
+ status: Schema.String,
233
+ stopReason: Schema.NullOr(Schema.String),
234
+ result: Schema.NullOr(Schema.String),
235
+ })
236
+
237
+ /** The kernel's own instructions, first in every model call. */
238
+ export const BASE_INSTRUCTIONS = `You are the agent of one person in their organisation, working in an Eloxiv app. You act only through the tools you are given: each is an action of the app, run with the person's own permissions, checked by policy and audited. Read data with the query tool (published, policy-filtered views); change data only with actions.
239
+ - A tool result {"ok":true,"output":{"kind":"output",...}} is the action's output; {"kind":"replay",...} means the call had already run and returns its receipt. {"ok":false,"error":...} is a refusal or failure: explain it, never retry blindly.
240
+ - ConsentRejected means the person declined that call: do not ask again unless they say so.
241
+ - Read a skill with load_skill before relying on it; one the person invokes (/name) or mentions (@name) is already given to you whole. Remember durable facts the person asks you to keep with agent_remember.
242
+ - Answer concisely once the work is done.`
243
+
244
+ const COMPACTION_INSTRUCTIONS = `You compact a conversation between a person and their agent into an observation: a dense, dated record of what happened in the stretch below, which replaces it. Write a dense summary that replaces the transcript below. Keep, verbatim: names, numbers, identifiers, dates, decisions, commitments, what each tool call did and its outcome, open questions, and every fact the person asked to remember. Leave out pleasantries. Write in the third person, past tense.`
245
+
246
+ const REFLECTION_INSTRUCTIONS = `You condense the observations (and any earlier reflection) of a long conversation between a person and their agent into one reflection: the long-arc summary that replaces them. Keep, verbatim: names, numbers, identifiers, dates, decisions, commitments, the outcome of each piece of work, open questions, and every fact the person asked to remember. Leave out what later observations superseded. Write in the third person, past tense.`
247
+
248
+ /**
249
+ * A step of the run failed unexpectedly: the cause is the kernel's (its message and trace may carry what the kernel
250
+ * holds), so it is logged under a reference, and the run's error, which its owner reads, names only the reference.
251
+ */
252
+ const unexpected = (what: string) => (cause: Cause.Cause<unknown>) =>
253
+ Effect.gen(function* () {
254
+ // A refusal is not a failure of the kernel's: the run's authority no longer holds (a credential revoked, the
255
+ // person removed, a consent withdrawn), and the run ends saying so.
256
+ const failure = Cause.findErrorOption(cause)
257
+ if (Option.isSome(failure) && isRefusal(failure.value)) {
258
+ return yield* new WorkflowFailed({
259
+ message: `The authority this run acts under no longer holds: ${failure.value.message}`,
260
+ })
261
+ }
262
+ const reference = crypto.randomUUID()
263
+ yield* Effect.logError(`Agent ${what} failed unexpectedly (reference ${reference})`, cause)
264
+ return yield* new WorkflowFailed({
265
+ message: `Agent ${what} failed unexpectedly (reference ${reference}); the kernel's log has the details`,
266
+ })
267
+ })
268
+
269
+ /** An authority's refusal (`Unauthenticated`, `Forbidden`): what `Authority.assert` fails with. */
270
+ const isRefusal = (error: unknown): error is { readonly _tag: string; readonly message: string } =>
271
+ typeof error === "object" &&
272
+ error !== null &&
273
+ ((error as { _tag?: unknown })._tag === "Unauthenticated" || (error as { _tag?: unknown })._tag === "Forbidden")
274
+
275
+ const withServices =
276
+ (services: Context.Context<RunServices>, what: string) =>
277
+ <A, E>(effect: Effect.Effect<A, E, RunServices>): Effect.Effect<A, WorkflowFailed> =>
278
+ effect.pipe(
279
+ Effect.updateContext((current: Context.Context<never>) => Context.merge(current, services)),
280
+ Effect.catchCause(unexpected(what)),
281
+ )
282
+
283
+ /**
284
+ * The tools a run in `orgId` may use: every action except people's own (the app's, and the MAKE modules'
285
+ * installed in the organisation), the agent's internal tools (with `tool_search` when its tools are found by
286
+ * search), narrowed by `allowed`.
287
+ */
288
+ export const runTools = (orgId: string, options: RunOptions = DEFAULT_OPTIONS) =>
289
+ Effect.gen(function* () {
290
+ const tools = yield* AgentTools
291
+ const registry = yield* Registry
292
+ const queryViews = yield* QueryViews
293
+ const resources = yield* AgentResources
294
+ const definitions: Array<ToolDefinition> = []
295
+ for (const definition of (yield* tools.definitionsFor(orgId)).values()) {
296
+ // A person's action, or one the agent surface does not offer: not the agent's tool.
297
+ if (PERSON_ONLY_ACTIONS.has(definition.action)) continue
298
+ if (registry.actions.get(definition.action)?.contract.exposure.agent === false) continue
299
+ definitions.push({
300
+ name: definition.name,
301
+ description: definition.description,
302
+ inputSchema: definition.inputSchema,
303
+ })
304
+ }
305
+ if (!registry.actions.has(QUERY_ACTION)) {
306
+ const views = queryViews.views.map((v) => `${v.id} (${v.description})`).join("; ")
307
+ definitions.push({
308
+ name: "query",
309
+ description: `Read rows of a published query view, filtered by what you may read (read-only). Views: ${views || "none"}.`,
310
+ inputSchema: {
311
+ type: "object",
312
+ properties: { view: { type: "string" }, limit: { type: "number" } },
313
+ required: ["view"],
314
+ additionalProperties: false,
315
+ },
316
+ })
317
+ }
318
+ const skills = resources.app.filter((r) => r.kind === "skill").map((r) => r.path)
319
+ definitions.push({
320
+ name: "load_skill",
321
+ description: `Read a skill's document (personal, organisation or app). Skills: ${skills.join(", ") || "none"}.`,
322
+ inputSchema: {
323
+ type: "object",
324
+ properties: { skill: { type: "string" } },
325
+ required: ["skill"],
326
+ additionalProperties: false,
327
+ },
328
+ })
329
+ const { maxOutputTokens, maxDelegationDepth, profiles } = yield* AgentSettings
330
+ if (options.tools.discovery === "search") definitions.push(toolSearchDefinition)
331
+ const deeper = options.depth + 1 < maxDelegationDepth
332
+ definitions.push({
333
+ name: "delegate",
334
+ description:
335
+ `Hand a self-contained task to a sub-agent with a subset of your tools (by name); you get its final answer. ${deeper ? "A sub-agent may delegate further only if you give it the delegate tool." : "Sub-agents cannot delegate further."} ` +
336
+ (profiles.length === 0
337
+ ? ""
338
+ : `To use a custom agent, name its profile (its instructions apply; without tools it gets the profile's): ${profiles.map((p) => `${p.name} (${p.description})`).join("; ")}. `) +
339
+ `Leave out limits unless you must constrain it: it then gets up to 8 model calls and the tokens you have left. maxSteps counts its model calls (a task that calls one tool and then answers needs 2); maxTokens counts the input and output of all of them, and each call needs room for ${maxOutputTokens} output tokens.`,
340
+ inputSchema: {
341
+ type: "object",
342
+ properties: {
343
+ task: { type: "string" },
344
+ tools: { type: "array", items: { type: "string" } },
345
+ ...(profiles.length === 0 ? {} : { profile: { type: "string", enum: profiles.map((p) => p.name) } }),
346
+ limits: {
347
+ type: "object",
348
+ properties: { maxSteps: { type: "number" }, maxTokens: { type: "number" }, maxWallMs: { type: "number" } },
349
+ additionalProperties: false,
350
+ },
351
+ },
352
+ required: profiles.length === 0 ? ["task", "tools"] : ["task"],
353
+ additionalProperties: false,
354
+ },
355
+ })
356
+ definitions.push(teamDefinition(profiles))
357
+ return definitions.sort((a, b) => a.name.localeCompare(b.name))
358
+ })
359
+
360
+ /** The tool that runs sub-agents in parallel (a team of seats) and carries messages between them. */
361
+ export const TEAM = "team"
362
+
363
+ const TEAM_DESCRIPTION = `Work with a team of sub-agents running in parallel. action "spawn" starts a seat on a self-contained task with a subset of your tools (by name, as for delegate) and returns its id at once, while it works. action "wait" waits until all (until "all", the default) or any (until "any") of your running seats (or those named in seats) finished, or until a message arrives for you. action "send" messages a seat ("to": its id, or "lead" for the run that started you). action "list" shows your team. Every result also carries the messages that arrived for you and the answers of your seats that finished since your last team call. A seat's limits are reserved from yours while it runs; leave them out and it gets up to 8 model calls, at most half of those you have left, and half your tokens. Seats still running when you answer are cancelled: wait for them first.`
364
+
365
+ const SEAT_DESCRIPTION = `Talk with your team: you are a seat working in parallel with others. action "send" messages your lead ("to": "lead") or another seat (its id); action "wait" waits until a message arrives for you; action "list" shows your team. Every result also carries the messages that arrived for you. Your final answer goes to your lead.`
366
+
367
+ const teamDefinition = (profiles: ReadonlyArray<{ readonly name: string }>): ToolDefinition => ({
368
+ name: TEAM,
369
+ description: TEAM_DESCRIPTION,
370
+ inputSchema: {
371
+ type: "object",
372
+ properties: {
373
+ action: { type: "string", enum: ["spawn", "wait", "send", "list"] },
374
+ task: { type: "string" },
375
+ name: { type: "string" },
376
+ tools: { type: "array", items: { type: "string" } },
377
+ ...(profiles.length === 0 ? {} : { profile: { type: "string", enum: profiles.map((p) => p.name) } }),
378
+ limits: {
379
+ type: "object",
380
+ properties: { maxSteps: { type: "number" }, maxTokens: { type: "number" }, maxWallMs: { type: "number" } },
381
+ additionalProperties: false,
382
+ },
383
+ seats: { type: "array", items: { type: "string" } },
384
+ until: { type: "string", enum: ["all", "any"] },
385
+ to: { type: "string" },
386
+ text: { type: "string" },
387
+ },
388
+ required: ["action"],
389
+ additionalProperties: false,
390
+ },
391
+ })
392
+
393
+ /**
394
+ * The team tool as a run is offered it: with `spawn` (and the tools a seat may be given) when the run may start seats
395
+ * (given the tool, within the delegation depth); a seat that may not is offered only its messages.
396
+ */
397
+ const teamWithChoices = (tool: ToolDefinition, choices: ReadonlyArray<string>, spawns: boolean): ToolDefinition => {
398
+ const schema = tool.inputSchema as { readonly properties: Record<string, unknown> }
399
+ if (spawns) {
400
+ return {
401
+ ...tool,
402
+ inputSchema: {
403
+ ...schema,
404
+ properties: { ...schema.properties, tools: { type: "array", items: { type: "string", enum: [...choices] } } },
405
+ },
406
+ }
407
+ }
408
+ const { to, text, until } = schema.properties
409
+ return {
410
+ ...tool,
411
+ description: SEAT_DESCRIPTION,
412
+ inputSchema: {
413
+ ...schema,
414
+ properties: { action: { type: "string", enum: ["wait", "send", "list"] }, to, text, until },
415
+ },
416
+ }
417
+ }
418
+
419
+ /** May the run start seats: it was given the team tool (a seat always has it, for its messages) within the depth. */
420
+ const spawnsSeats = (spec: Spec, maxDelegationDepth: number) =>
421
+ (spec.tools === null || spec.tools.includes(TEAM)) && optionsOf(spec).depth < maxDelegationDepth
422
+
423
+ const allowedTools = (all: ReadonlyArray<ToolDefinition>, spec: Spec) =>
424
+ spec.tools === null
425
+ ? all
426
+ : all.filter(
427
+ (tool) => spec.tools!.includes(tool.name) || (tool.name === TEAM && optionsOf(spec).seat !== undefined),
428
+ )
429
+
430
+ /** Is `action` read-only (`hints.readOnly`)? An action the registry does not declare (a MAKE module's) is not. */
431
+ const readOnly = (
432
+ registry: {
433
+ readonly actions: ReadonlyMap<string, { readonly contract: { readonly hints: { readonly readOnly: boolean } } }>
434
+ },
435
+ action: string,
436
+ ) => registry.actions.get(action)?.contract.hints.readOnly === true
437
+
438
+ /** What people see `action` called: its title in the registry, or its readable name (always, for a MAKE action). */
439
+ const actionTitle = (
440
+ registry: { readonly actions: ReadonlyMap<string, { readonly contract: { readonly title: string } }> },
441
+ action: string,
442
+ ) => decisionLabel(action, registry.actions.get(action)?.contract.title)
443
+
444
+ /** The run's own tools that change nothing (offered in plan mode). */
445
+ const READ_TOOLS: ReadonlySet<string> = new Set(["query", "load_skill", TOOL_SEARCH, "delegate", TEAM])
446
+
447
+ /**
448
+ * The tools the run may be offered now: its allowed tools, without the actions its agent cannot reach now
449
+ * (`AgentTools.reachable`: hidden by the policy, or in a tool group the app disabled for agents) and, in plan mode,
450
+ * without every action that is not read-only. A call the model makes to one anyway is refused: by the run (plan
451
+ * mode) or by the invocation path, which audits it.
452
+ */
453
+ const availableTools = (spec: Spec) =>
454
+ Effect.gen(function* () {
455
+ const tools = yield* AgentTools
456
+ const registry = yield* Registry
457
+ const options = optionsOf(spec)
458
+ const allowed = allowedTools(yield* runTools(spec.orgId, options), spec)
459
+ const identity = identityOf(spec)
460
+ const reachable = new Set(
461
+ yield* tools.reachable(
462
+ spec.agentSessionId === null ? { identity } : { identity, agentSession: spec.agentSessionId },
463
+ ),
464
+ )
465
+ // Every action tool, the app's and the organisation's MAKE modules', is offered only if reach lets the agent call
466
+ // it; the run's own tools (query, load_skill, tool_search, delegate) are not actions.
467
+ const actionTools = yield* tools.definitionsFor(spec.orgId)
468
+ const available = allowed.filter((tool) => {
469
+ const action = actionTools.get(tool.name)
470
+ if (action === undefined) return options.mode === "act" || READ_TOOLS.has(tool.name)
471
+ return reachable.has(tool.name) && (options.mode === "act" || readOnly(registry, action.action))
472
+ })
473
+ return { available, actionTools }
474
+ })
475
+
476
+ /**
477
+ * The tools offered to the model on this call. With every tool (`discovery: all`): all the run may be offered.
478
+ * Found by search: the run's own tools, the policy's `eager` tools and those the run loaded with `tool_search`; the
479
+ * others are named in the tool index (`deferred`).
480
+ */
481
+ const offeredTools = (spec: Spec, loaded: ReadonlySet<string> = new Set()) =>
482
+ Effect.gen(function* () {
483
+ const { available, actionTools } = yield* availableTools(spec)
484
+ const policy = optionsOf(spec).tools
485
+ const eager = new Set(policy.eager ?? [])
486
+ const offered =
487
+ policy.discovery === "all"
488
+ ? available
489
+ : available.filter((tool) => !actionTools.has(tool.name) || eager.has(tool.name) || loaded.has(tool.name))
490
+ const deferred = available.filter((tool) => !offered.includes(tool))
491
+ // The delegate tool names the tools a sub-agent may be given: exactly the others the run may use (never one the
492
+ // policy hides), so the model picks real names (a real model was seen writing `functions.notebook_write`); the
493
+ // delegate tool itself only while the sub-agent would be within the delegation depth.
494
+ const { maxDelegationDepth } = yield* AgentSettings
495
+ const deeper = optionsOf(spec).depth + 2 <= maxDelegationDepth
496
+ const spawns = spawnsSeats(spec, maxDelegationDepth)
497
+ const choices = available
498
+ .map((tool) => tool.name)
499
+ .filter(
500
+ (name) =>
501
+ ((name !== "delegate" && name !== TEAM) || deeper) && (name !== TEAM || spawns) && name !== TOOL_SEARCH,
502
+ )
503
+ return {
504
+ offered: [
505
+ ...offered.map((tool) =>
506
+ tool.name === "delegate"
507
+ ? delegateWithChoices(tool, choices)
508
+ : tool.name === TEAM
509
+ ? teamWithChoices(tool, choices, spawns)
510
+ : tool,
511
+ ),
512
+ // A run a job or schedule started may say it found nothing to do, distinct from finishing with nothing to show.
513
+ ...(spec.kind === "job" ? [NO_OP_TOOL] : []),
514
+ ],
515
+ deferred,
516
+ }
517
+ })
518
+
519
+ /** The tool a run of kind `job` ends with when it finds nothing to do: the run succeeds as a no-op, with the reason. */
520
+ export const NO_OP_TOOL: ToolDefinition = {
521
+ name: "no_op",
522
+ description:
523
+ "Call this, instead of answering, when this background job finds nothing to do: say why in one sentence (no personal data). The run then ends as a no-op, distinct from work done.",
524
+ inputSchema: {
525
+ type: "object",
526
+ properties: { reason: { type: "string" } },
527
+ required: ["reason"],
528
+ additionalProperties: false,
529
+ },
530
+ }
531
+
532
+ const delegateWithChoices = (tool: ToolDefinition, choices: ReadonlyArray<string>): ToolDefinition => {
533
+ const schema = tool.inputSchema as { readonly properties: Record<string, unknown> }
534
+ return {
535
+ ...tool,
536
+ inputSchema: {
537
+ ...schema,
538
+ properties: { ...schema.properties, tools: { type: "array", items: { type: "string", enum: [...choices] } } },
539
+ },
540
+ }
541
+ }
542
+
543
+ const refused = (tag: string, message: string, extra: Record<string, unknown> = {}): AgentToolResult => ({
544
+ ok: false,
545
+ error: { _tag: tag, message, ...extra },
546
+ })
547
+
548
+ const identityOf = (spec: Spec): ExecutionIdentity =>
549
+ spec.userId === SYSTEM_ACTOR
550
+ ? {
551
+ kind: "system",
552
+ orgId: spec.orgId,
553
+ // A system run started within a scope (a tool-limited parent's) stays within it.
554
+ ...(typeof spec.authority === "object" && spec.authority.scope !== null
555
+ ? { scope: [...spec.authority.scope] }
556
+ : {}),
557
+ }
558
+ : {
559
+ kind: "user",
560
+ userId: spec.userId,
561
+ orgId: spec.orgId,
562
+ // The authority the run was started with: every call of the run is within it, and only while it holds.
563
+ authority: spec.authority ?? "unrecorded",
564
+ }
565
+
566
+ /**
567
+ * The run's effective authority, as a record a successor can carry: its scope, and its chain with the agent session its
568
+ * calls were made through. Null for a run that recorded none (it acts on nothing).
569
+ */
570
+ const effectiveAuthority = (spec: Spec): AuthorityRecord | null => {
571
+ const chain = runChain(spec)
572
+ return chain === "unrecorded" || spec.authority === undefined || spec.authority === "unrecorded"
573
+ ? null
574
+ : { ...spec.authority, chain }
575
+ }
576
+
577
+ /**
578
+ * The identity a tool call acts as: the run's, within the scope it was started with and, when the run may use only
579
+ * some tools (a sub-agent's, a profile's), within the actions those tools are. The narrowed scope is the call's
580
+ * recorded authority, so a deputy the call reaches (a read program's reads, a collection's pages, a nested call)
581
+ * stays within the run's tools too, not only the call the model made.
582
+ */
583
+ const toolIdentity = (spec: Spec) =>
584
+ Effect.gen(function* () {
585
+ const identity = identityOf(spec)
586
+ if (spec.tools === null) return identity
587
+ // The tool subset applies whoever the run acts as: a person (within the scope it was started with) or the
588
+ // organisation's system actor (a job's run, its sub-agents).
589
+ const kept =
590
+ identity.kind === "system"
591
+ ? (identity.scope ?? null)
592
+ : typeof identity.authority === "object"
593
+ ? identity.authority.scope
594
+ : undefined
595
+ if (kept === undefined) return identity
596
+ const tools = yield* AgentTools
597
+ const registry = yield* Registry
598
+ const allowed = new Set(spec.tools)
599
+ const actions = [...(yield* tools.definitionsFor(spec.orgId)).values()]
600
+ .filter((definition) => allowed.has(definition.name))
601
+ .map((definition) => definition.action)
602
+ const scope = [...new Set(actions)]
603
+ .filter((action) => scopeAllows(kept, action, (permission) => registry.permissions.get(permission)?.actions))
604
+ .map((action) => `action:${action}`)
605
+ return identity.kind === "system"
606
+ ? ({ ...identity, scope } satisfies ExecutionIdentity)
607
+ : ({ ...identity, authority: { ...(identity.authority as AuthorityRecord), scope } } satisfies ExecutionIdentity)
608
+ })
609
+
610
+ /** The run's chain of authorities (Authority), with the agent session its calls are made through. */
611
+ const runChain = (spec: Spec): AuthorityChain | "unrecorded" =>
612
+ spec.authority === undefined || spec.authority === "unrecorded"
613
+ ? "unrecorded"
614
+ : extend(
615
+ spec.authority.chain,
616
+ spec.agentSessionId === null ? [] : [{ kind: "agent-session", id: spec.agentSessionId }],
617
+ )
618
+
619
+ /**
620
+ * What the run asserts (Authority) whenever it reads or writes the person's data itself (not through an action,
621
+ * which asserts in the invocation path): its whole chain, with the conversation's agent session and the person's
622
+ * membership, within the scope it was started with. The capability `Authority.within` gives for it is what the
623
+ * person's resources, memory, skills, query views and transcript are read and written with.
624
+ */
625
+ const runAuthority = (spec: Spec): AssertRequest => ({
626
+ chain: runChain(spec),
627
+ who: { userId: spec.userId, orgId: spec.orgId },
628
+ scope:
629
+ spec.authority === undefined || spec.authority === "unrecorded" || spec.authority.scope === null
630
+ ? null
631
+ : [...spec.authority.scope],
632
+ })
633
+
634
+ /**
635
+ * Read or write the person's transcript (their conversation's messages, and the run's events that carry them) on their
636
+ * behalf: in a transaction of its own whose first act is asserting the run's authority, with the capability
637
+ * `inAgentFor` requires. A refusal fails with the reason (the run then ends saying so).
638
+ */
639
+ /**
640
+ * The team a conversation's runs work in: the one it is bound to (`agent.updateConversation`'s `team`), or undefined,
641
+ * which AgentResources takes as the person's active team. The one resolution for the run's context and `load_skill`.
642
+ */
643
+ const teamOfConversation = (asserted: Asserted, sql: SqlClient.SqlClient, conversationId: string) =>
644
+ inAgentFor(
645
+ asserted,
646
+ sql,
647
+ sql<{ team: string | null }>`SELECT team FROM eloxiv_agent.conversation WHERE id = ${conversationId}`,
648
+ ).pipe(
649
+ Effect.orDie,
650
+ Effect.map(([bound]) => bound?.team ?? undefined),
651
+ )
652
+
653
+ const inTranscript = <A, E, R>(spec: Spec, write: (sql: SqlClient.SqlClient) => Effect.Effect<A, E, R>) =>
654
+ Effect.gen(function* () {
655
+ const sql = yield* SqlClient.SqlClient
656
+ return yield* (yield* Authority).within(runAuthority(spec), (asserted) =>
657
+ replying(sql, spec).pipe(Effect.andThen(inAgentFor(asserted, sql, write(sql)))),
658
+ )
659
+ })
660
+
661
+ /**
662
+ * A reply in a conversation shared with the run's person: before every read or write of its transcript, inside that
663
+ * transaction, the person must still hold `reply` on it (the conversation's `send` policy, as them). A revoked grant
664
+ * stops the run at its next read or write (the run ends saying its authority no longer holds). Nothing for a run in
665
+ * its person's own conversation.
666
+ */
667
+ const replying = (sql: SqlClient.SqlClient, spec: Spec) =>
668
+ spec.conversationOwner === undefined
669
+ ? Effect.void
670
+ : mayReply(sql, { userId: spec.userId, orgId: spec.orgId, conversationId: spec.conversationId }).pipe(
671
+ Effect.catchTag("SqlError", (e) => Effect.die(e)),
672
+ Effect.flatMap((allowed) =>
673
+ allowed
674
+ ? Effect.void
675
+ : Effect.fail(
676
+ new Forbidden({
677
+ action: "agent.send",
678
+ message: "The conversation is no longer shared with you to reply in",
679
+ }),
680
+ ),
681
+ ),
682
+ )
683
+
684
+ // --- start -----------------------------------------------------------------------------------------------------------
685
+
686
+ const startRun = (runId: string, orgId: string) =>
687
+ Effect.gen(function* () {
688
+ const sql = yield* SqlClient.SqlClient
689
+ const settings = yield* AgentSettings
690
+ const identity = yield* Identity
691
+ const [run] = yield* inAgent(
692
+ sql,
693
+ orgId,
694
+ sql<{
695
+ userId: string
696
+ conversationId: string
697
+ parentRunId: string | null
698
+ kind: string
699
+ limits: Partial<RunLimits> | null
700
+ tools: ReadonlyArray<string> | null
701
+ sessionId: string | null
702
+ startedAt: Date | null
703
+ device: RunDevice | null
704
+ authority: AuthorityRecord | null
705
+ options: RunOptions | null
706
+ ownerId: string
707
+ }>`SELECT r.user_id AS "userId", r.conversation_id AS "conversationId", r.parent_run_id AS "parentRunId", r.kind,
708
+ r.limits, r.tools, c.agent_session_id AS "sessionId", r.started_at AS "startedAt", r.device, r.authority,
709
+ r.options, c.user_id AS "ownerId"
710
+ FROM eloxiv_agent.run r JOIN eloxiv_agent.conversation c ON c.id = r.conversation_id WHERE r.id = ${runId}`,
711
+ )
712
+ if (run === undefined) return yield* Effect.die(new Error(`No agent run ${runId}`))
713
+ // The conversation's agent session: every tool call of its runs is agent-originated through it (consent's
714
+ // session-scoped permissions cover the conversation). Issued once; a sub-agent uses its parent's and never gets a
715
+ // new one: if the parent's was revoked, the sub-agent's calls are refused.
716
+ let sessionId: string | null = null
717
+ if (run.userId !== SYSTEM_ACTOR && run.parentRunId !== null) {
718
+ sessionId = run.sessionId
719
+ } else if (run.userId !== SYSTEM_ACTOR && run.userId !== run.ownerId) {
720
+ // A reply in a conversation shared with the person: the conversation's session is its owner's, never theirs. The
721
+ // run gets a session of its own person's, for as long as it may run.
722
+ const issued = yield* identity.issueAgentSession({
723
+ userId: run.userId,
724
+ orgId,
725
+ label: `agent reply in conversation ${run.conversationId}`,
726
+ ttlMs: Math.max(60 * 60 * 1000, (run.limits?.maxWallMs ?? settings.limits.maxWallMs) + 60 * 60 * 1000),
727
+ authority: { scope: null, chain: [] },
728
+ })
729
+ sessionId = issued.id
730
+ } else if (run.userId !== SYSTEM_ACTOR) {
731
+ sessionId = run.sessionId
732
+ const valid =
733
+ sessionId !== null &&
734
+ (yield* sql<{ ok: boolean }>`SELECT (revoked_at IS NULL AND expires_at > now() + interval '1 hour'
735
+ AND authority IS NOT NULL) AS ok
736
+ FROM eloxiv.agent_session WHERE id = ${sessionId}`)[0]?.ok === true
737
+ if (!valid) {
738
+ const issued = yield* identity.issueAgentSession({
739
+ userId: run.userId,
740
+ orgId,
741
+ label: `agent conversation ${run.conversationId}`,
742
+ ttlMs: 30 * 24 * 60 * 60 * 1000,
743
+ // The conversation's own session: a link of each run's chain, standing for nothing beyond itself (each run
744
+ // records what it was started under).
745
+ authority: { scope: null, chain: [] },
746
+ })
747
+ sessionId = issued.id
748
+ yield* inAgent(
749
+ sql,
750
+ orgId,
751
+ sql`UPDATE eloxiv_agent.conversation SET agent_session_id = ${sessionId} WHERE id = ${run.conversationId}`,
752
+ )
753
+ }
754
+ }
755
+ // The run's limits: the deployment's, with what was recorded on the run when it was queued (the organisation's
756
+ // loop policy, a sub-agent's carved limits) over them, each capped at the deployment's ceiling.
757
+ const recorded = { ...settings.limits, ...run.limits }
758
+ const limits: RunLimits = {
759
+ maxSteps: Math.min(recorded.maxSteps, settings.maxLimits.maxSteps),
760
+ maxTokens: Math.min(recorded.maxTokens, settings.maxLimits.maxTokens),
761
+ maxWallMs: Math.min(recorded.maxWallMs, settings.maxLimits.maxWallMs),
762
+ }
763
+ const [started] = yield* inAgent(
764
+ sql,
765
+ orgId,
766
+ sql<{
767
+ startedAt: Date
768
+ }>`UPDATE eloxiv_agent.run SET status = 'running', limits = ${JSON.stringify(limits)}::jsonb,
769
+ started_at = coalesce(started_at, now()) WHERE id = ${runId} RETURNING started_at AS "startedAt"`,
770
+ )
771
+ return {
772
+ runId,
773
+ orgId,
774
+ userId: run.userId,
775
+ conversationId: run.conversationId,
776
+ parentRunId: run.parentRunId,
777
+ kind: run.kind,
778
+ limits,
779
+ tools: run.tools === null ? null : [...run.tools],
780
+ agentSessionId: sessionId,
781
+ startedAt: new Date(started!.startedAt).getTime(),
782
+ device: run.device,
783
+ // A run queued before authorities were recorded acts on nothing (it fails closed at its first act).
784
+ authority: run.authority ?? "unrecorded",
785
+ ...(run.options === null ? {} : { options: run.options }),
786
+ ...(run.ownerId === run.userId || run.parentRunId !== null ? {} : { conversationOwner: run.ownerId }),
787
+ ...(run.options?.editGroup === undefined ? {} : { editGroup: { runId, ...run.options.editGroup } }),
788
+ } satisfies Spec
789
+ })
790
+
791
+ // --- context -----------------------------------------------------------------------------------------------------------
792
+
793
+ /** The kernel's instructions for a run in plan mode. */
794
+ const PLAN_INSTRUCTIONS = `You are in plan mode: read what you need and answer with a plan, but change nothing. Only read-only tools are available; actions that change data are refused in this mode. Describe each change you would make (which action, with what input) so the person can approve the plan and run it.`
795
+
796
+ /**
797
+ * The kernel's instructions for a run: its own, plus plan mode's, the sub-agent's profile's, and (tools found by
798
+ * search) the index of tools it may load.
799
+ */
800
+ const instructionsFor = (spec: Spec, deferred: ReadonlyArray<ToolDefinition>, note: string | null = null) =>
801
+ Effect.gen(function* () {
802
+ const options = optionsOf(spec)
803
+ const { profiles } = yield* AgentSettings
804
+ const profile = options.profile === undefined ? undefined : profiles.find((p) => p.name === options.profile)
805
+ return [
806
+ BASE_INSTRUCTIONS,
807
+ ...(options.mode === "plan" ? [PLAN_INSTRUCTIONS] : []),
808
+ ...(profile === undefined ? [] : [`You are the custom agent "${profile.name}".\n${profile.instructions}`]),
809
+ ...(options.seat === undefined
810
+ ? []
811
+ : [
812
+ `You are the seat "${options.seat}" (${spec.runId}) of a team working in parallel on your lead's task. Use the team tool to message your lead or another seat, and to wait for their messages. Your final answer goes to your lead.`,
813
+ ]),
814
+ ...(options.tools.discovery === "search" && deferred.length > 0 ? [toolIndex(deferred)] : []),
815
+ ...(note === null ? [] : [note]),
816
+ ].join("\n\n")
817
+ })
818
+
819
+ /** What the model is sent for the next call of `spec`'s run: assembled from the stored state, with its inventory. */
820
+ const contextFor = (
821
+ spec: Spec,
822
+ tools: ReadonlyArray<ToolDefinition>,
823
+ deferred: ReadonlyArray<ToolDefinition> = [],
824
+ note: string | null = null,
825
+ ) =>
826
+ Effect.gen(function* () {
827
+ const sql = yield* SqlClient.SqlClient
828
+ const settings = yield* AgentSettings
829
+ const resources = yield* AgentResources
830
+ const authority = yield* Authority
831
+ // The person's conversation, memory and resources, read under the run's authority.
832
+ const { effective, memory, messages, directives, about } = yield* authority
833
+ .within(runAuthority(spec), (asserted) =>
834
+ Effect.gen(function* () {
835
+ yield* replying(sql, spec)
836
+ const team = yield* teamOfConversation(asserted, sql, spec.conversationId)
837
+ const effective = yield* resources.effective(asserted, undefined, team)
838
+ const memory = yield* resources.recall(asserted, team)
839
+ const read = yield* inAgentFor(
840
+ asserted,
841
+ sql,
842
+ Effect.gen(function* () {
843
+ const rows = yield* sql<StoredMessage & { userId: string }>`SELECT id, role, content,
844
+ seq::float8 AS seq, user_id AS "userId" FROM eloxiv_agent.message
845
+ WHERE conversation_id = ${spec.conversationId} AND covered_by IS NULL ORDER BY seq, id`
846
+ const directives = yield* sql<{ ref: string; directive: "pin" | "evict" | "restore" }>`
847
+ SELECT ref, directive FROM eloxiv_agent.directive WHERE conversation_id = ${spec.conversationId}`
848
+ const [conversation] = yield* sql<{ module: string | null; entity: string | null; id: string | null }>`
849
+ SELECT resource_module AS module, resource_entity AS entity, resource_id AS id
850
+ FROM eloxiv_agent.conversation WHERE id = ${spec.conversationId}`
851
+ return { messages: ownView(spec, rows), directives, about: conversation }
852
+ }),
853
+ )
854
+ return { effective, memory, ...read }
855
+ }),
856
+ )
857
+ .pipe(Effect.catchTag("SqlError", (e) => Effect.die(e)))
858
+ const base = yield* instructionsFor(spec, deferred, note)
859
+ return assemble({
860
+ base:
861
+ about?.module == null || about.entity == null || about.id == null
862
+ ? base
863
+ : `${base}\n\nThis conversation is about the record ${about.module}.${about.entity} ${JSON.stringify(about.id)}: read it with your tools (under the person's permissions) when you need it.`,
864
+ resources: effective.filter((r) => r.kind !== "file"),
865
+ memory,
866
+ messages,
867
+ tools,
868
+ budgets: settings.budgets,
869
+ directives: new Map(directives.map((d) => [d.ref, d.directive])),
870
+ })
871
+ })
872
+
873
+ /**
874
+ * A conversation's messages as one person's run sees them: everyone's words, but tool calls, their results and
875
+ * compaction summaries only of the run's own person. In a shared conversation another participant's agent read what that person may read, so
876
+ * its tool results (and the calls they answer) stay out of this person's context.
877
+ */
878
+ const ownView = (spec: Spec, rows: ReadonlyArray<StoredMessage & { readonly userId: string }>) =>
879
+ rows.flatMap((row): ReadonlyArray<StoredMessage> => {
880
+ const message: StoredMessage = { id: row.id, role: row.role, content: row.content, seq: row.seq }
881
+ if (row.userId === spec.userId) return [message]
882
+ // (A summary another person's run wrote can quote its tool results.)
883
+ if (row.role === "tool" || row.role === "summary") return []
884
+ // Another person's message in its public form only: their words or their agent's answer, never their attachments'
885
+ // text, their agent's tool calls or what those read.
886
+ const text = String(row.content?.text ?? "")
887
+ if (text === "") return []
888
+ return [{ ...message, content: row.role === "assistant" ? { text, toolCalls: [] } : { text, attachments: [] } }]
889
+ })
890
+
891
+ /** Render stored messages as a plain transcript for the compaction model. */
892
+ const transcript = (messages: ReadonlyArray<StoredMessage>) =>
893
+ messages
894
+ .map((m) => {
895
+ const c = m.content ?? {}
896
+ if (m.role === "summary") return `${c.tier === "reflection" ? "Reflection" : "Observation"}: ${c.text ?? ""}`
897
+ if (m.role === "user") return `Person: ${c.text ?? ""}`
898
+ if (m.role === "assistant") {
899
+ const calls = ((c.toolCalls ?? []) as ReadonlyArray<ToolCall>)
900
+ .map((t) => ` [called ${t.toolName} with ${JSON.stringify(t.input)}]`)
901
+ .join("")
902
+ return `Agent: ${c.text ?? ""}${calls}`
903
+ }
904
+ return `Tool ${c.toolName ?? ""} result: ${JSON.stringify(c.result ?? null).slice(0, 2_000)}`
905
+ })
906
+ .join("\n")
907
+
908
+ /** What a fold writes (Memory's tiers): an observation over raw messages, a reflection over observations. */
909
+ type Tier = "observation" | "reflection"
910
+
911
+ const tierOf = (m: StoredMessage): Tier => (m.content?.tier === "reflection" ? "reflection" : "observation")
912
+
913
+ const TIER_INSTRUCTIONS: Readonly<Record<Tier, string>> = {
914
+ observation: COMPACTION_INSTRUCTIONS,
915
+ reflection: REFLECTION_INSTRUCTIONS,
916
+ }
917
+
918
+ /**
919
+ * One fold of Memory's tiers: `items` (raw messages for an observation; observations, and an earlier reflection, for a
920
+ * reflection) summarised by the organisation's model into one `summary` message of `tier`, which records what it
921
+ * covers (their ids, the time they span, their tokens before and after) and marks them covered by it. Metered like any
922
+ * model call (its worst case reserved first) and counted in its run; written, with the covered marks and the
923
+ * `compacted` event, in one transaction under `authorityOf`, which is asserted again there (a refused write is not
924
+ * made: null). Its id is derived from what it covers, so a fold made again after a crash writes nothing new.
925
+ */
926
+ const fold = (
927
+ spec: {
928
+ readonly orgId: string
929
+ readonly userId: string
930
+ readonly conversationId: string
931
+ readonly runId: string | null
932
+ readonly step?: number | undefined
933
+ },
934
+ authorityOf: AssertRequest,
935
+ tier: Tier,
936
+ items: ReadonlyArray<StoredMessage>,
937
+ room: { readonly tokens: number } | undefined,
938
+ ) =>
939
+ Effect.gen(function* () {
940
+ const sql = yield* SqlClient.SqlClient
941
+ const settings = yield* AgentSettings
942
+ const models = yield* ModelProviders
943
+ const metering = yield* Metering
944
+ const authority = yield* Authority
945
+ const text = transcript(items)
946
+ const instructions = TIER_INSTRUCTIONS[tier]
947
+ const { choice } = yield* models.resolveFor(spec.orgId, spec.userId)
948
+ const prompt: ReadonlyArray<ModelMessage> = [
949
+ { role: "system", content: instructions },
950
+ { role: "user", content: [{ type: "text", text }] },
951
+ ]
952
+ const estimate = countTokens(instructions) + countTokens(text)
953
+ if (room !== undefined && estimate + settings.maxOutputTokens > room.tokens) return null
954
+ const pricing = models.pricing(choice)
955
+ // Metering: the call's worst case is reserved before it is made, and settled with the fold.
956
+ const reservation = yield* metering.reserve({
957
+ orgId: spec.orgId,
958
+ userId: spec.userId,
959
+ runId: spec.runId,
960
+ step: spec.step ?? null,
961
+ kind: "compaction",
962
+ choice,
963
+ pricing,
964
+ inputTokens: estimate,
965
+ maxOutputTokens: settings.maxOutputTokens,
966
+ })
967
+ const generated = yield* models
968
+ .generate({
969
+ orgId: spec.orgId,
970
+ userId: spec.userId,
971
+ model: choice,
972
+ messages: prompt,
973
+ maxOutputTokens: settings.maxOutputTokens,
974
+ timeoutMs: settings.modelCallTimeoutMs,
975
+ })
976
+ .pipe(Effect.onError(() => metering.release(reservation)))
977
+ const summaryId = `${spec.conversationId}:${tier}:${items[items.length - 1]!.id}`
978
+ const covers = items.map((m) => m.id)
979
+ const tokensBefore = items.reduce((sum, m) => sum + countTokens(JSON.stringify(m.content ?? null)), 0)
980
+ const tokensAfter = countTokens(generated.text)
981
+ const spans = items.map((m) => m.createdAt).filter((at): at is string => typeof at === "string")
982
+ const content = {
983
+ text: generated.text,
984
+ tier,
985
+ covers,
986
+ tokensBefore,
987
+ tokensAfter,
988
+ // When what it covers was said (an observation is dated).
989
+ from: spans.length === 0 ? null : spans.reduce((a, b) => (a < b ? a : b)),
990
+ to: spans.length === 0 ? null : spans.reduce((a, b) => (a > b ? a : b)),
991
+ }
992
+ const written = yield* authority
993
+ .within(authorityOf, (asserted) =>
994
+ inAgentFor(
995
+ asserted,
996
+ sql,
997
+ Effect.gen(function* () {
998
+ // The call was made: it is metered (and counted in its run) whether or not its fold is the one kept.
999
+ if (yield* settleCall(sql, reservation, generated.usage)) {
1000
+ if (spec.runId !== null) {
1001
+ yield* sql`UPDATE eloxiv_agent.run SET steps = steps + 1,
1002
+ input_tokens = input_tokens + ${generated.usage.inputTokens},
1003
+ output_tokens = output_tokens + ${generated.usage.outputTokens} WHERE id = ${spec.runId}`
1004
+ }
1005
+ }
1006
+ const inserted = yield* sql<{ id: string }>`INSERT INTO eloxiv_agent.message
1007
+ (id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
1008
+ VALUES (${summaryId}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId}, ${spec.runId}, ${Math.min(...items.map((m) => m.seq))},
1009
+ 'summary', ${JSON.stringify(content)}::jsonb, ${generated.text})
1010
+ ON CONFLICT (id) DO NOTHING RETURNING id`
1011
+ if (inserted.length === 0) return
1012
+ yield* sql`UPDATE eloxiv_agent.message SET covered_by = ${summaryId} WHERE id = ANY(${covers}::text[])`
1013
+ if (spec.runId !== null) {
1014
+ yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "compacted", {
1015
+ summaryId,
1016
+ tier,
1017
+ covers: covers.length,
1018
+ tokensBefore,
1019
+ tokensAfter,
1020
+ })
1021
+ }
1022
+ }),
1023
+ ),
1024
+ )
1025
+ .pipe(
1026
+ Effect.as(true),
1027
+ Effect.catchTag("SqlError", (e) => Effect.die(e)),
1028
+ Effect.catchTags({ Unauthenticated: () => Effect.succeed(false), Forbidden: () => Effect.succeed(false) }),
1029
+ )
1030
+ if (!written) {
1031
+ yield* inAgent(sql, spec.orgId, settleCall(sql, reservation, generated.usage)).pipe(Effect.orDie)
1032
+ return null
1033
+ }
1034
+ return {
1035
+ summary: {
1036
+ id: summaryId,
1037
+ conversationId: spec.conversationId,
1038
+ covers,
1039
+ content: generated.text,
1040
+ tokensBefore,
1041
+ tokensAfter,
1042
+ },
1043
+ usage: generated.usage,
1044
+ }
1045
+ })
1046
+
1047
+ /**
1048
+ * Compaction (Memory), in three tiers. The last `keepRecentMessages` messages stay **raw**, verbatim (the kept window
1049
+ * starts at a person's message, so no tool call is parted from its result). The older raw messages are folded into an
1050
+ * **observation** (a dense, dated record of that stretch); observations accumulate, each covering its own stretch.
1051
+ * Once the observations not yet reflected pass `reflectAbove` tokens, they (and an earlier reflection) are folded into
1052
+ * a **reflection**, the long-arc summary. Every fold keeps provenance: it lists what it covers, which stays, marked
1053
+ * covered by it. Only the compacting person's own messages are folded (in a shared conversation another participant's
1054
+ * stay as they are). A run's folds are its model calls: `room.calls` is how many it may make (the reflection is made
1055
+ * only with a call to spare), `room.tokens` what they may spend. Returns the last fold and what all of them used, or
1056
+ * null when nothing was old enough or nothing fit.
1057
+ */
1058
+ export const compactConversation = (
1059
+ spec: {
1060
+ readonly orgId: string
1061
+ readonly userId: string
1062
+ readonly conversationId: string
1063
+ readonly runId: string | null
1064
+ /** The run's step that compacts (its `model/<step>`), for a run's compaction. */
1065
+ readonly step?: number | undefined
1066
+ },
1067
+ /**
1068
+ * What the compaction reads and writes the transcript under (Authority): a run's, or the person's credential's.
1069
+ * Its read, and its writes after each model call, assert it; a write it refuses is not made.
1070
+ */
1071
+ authorityOf: AssertRequest,
1072
+ /** For a run: the model calls and tokens its folds may spend. */
1073
+ room?: { readonly tokens: number; readonly calls: number },
1074
+ ) =>
1075
+ Effect.gen(function* () {
1076
+ const sql = yield* SqlClient.SqlClient
1077
+ const settings = yield* AgentSettings
1078
+ const authority = yield* Authority
1079
+ const read = () =>
1080
+ authority
1081
+ .within(authorityOf, (asserted) =>
1082
+ inAgentFor(
1083
+ asserted,
1084
+ sql,
1085
+ // Only the compacting person's own messages: another participant's (in a shared conversation) are theirs,
1086
+ // and stay as they are, never folded into this person's tiers.
1087
+ sql<StoredMessage>`SELECT id, role, content, seq::float8 AS seq, created_at::text AS "createdAt"
1088
+ FROM eloxiv_agent.message
1089
+ WHERE conversation_id = ${spec.conversationId} AND covered_by IS NULL AND user_id = ${spec.userId}
1090
+ ORDER BY seq, id`,
1091
+ ),
1092
+ )
1093
+ .pipe(Effect.catchTag("SqlError", (e) => Effect.die(e)))
1094
+ let calls = 0
1095
+ let tokens = 0
1096
+ let last: { readonly summary: CompactionSummaryValue; readonly usage: ModelUsageType } | null = null
1097
+ const roomLeft = () =>
1098
+ room === undefined ? undefined : { tokens: room.tokens - tokens, calls: room.calls - calls }
1099
+
1100
+ // Observe: the raw messages before the recent window.
1101
+ const stored = yield* read()
1102
+ const raw = stored.filter((m) => m.role !== "summary")
1103
+ let boundary = Math.max(0, raw.length - settings.keepRecentMessages)
1104
+ while (boundary > 0 && raw[boundary]?.role !== "user") boundary--
1105
+ if (boundary > 0 && (roomLeft()?.calls ?? 1) >= 1) {
1106
+ const observed = yield* fold(spec, authorityOf, "observation", raw.slice(0, boundary), roomLeft())
1107
+ if (observed !== null) {
1108
+ calls += 1
1109
+ tokens += observed.usage.inputTokens + observed.usage.outputTokens
1110
+ last = observed
1111
+ }
1112
+ }
1113
+
1114
+ // Reflect: the observations not yet reflected, once they pass the threshold (with an earlier reflection).
1115
+ const tiers = (yield* read()).filter((m) => m.role === "summary")
1116
+ const observations = tiers.filter((m) => tierOf(m) === "observation")
1117
+ const observed = observations.reduce((sum, m) => sum + countTokens(String(m.content?.text ?? "")), 0)
1118
+ if (observations.length > 0 && observed > settings.reflectAbove && (roomLeft()?.calls ?? 1) >= 1) {
1119
+ const reflections = tiers.filter((m) => tierOf(m) === "reflection")
1120
+ const reflected = yield* fold(spec, authorityOf, "reflection", [...reflections, ...observations], roomLeft())
1121
+ if (reflected !== null) {
1122
+ calls += 1
1123
+ tokens += reflected.usage.inputTokens + reflected.usage.outputTokens
1124
+ last = reflected
1125
+ }
1126
+ }
1127
+ if (last === null) return null
1128
+ return { summary: last.summary, usage: last.usage, calls, tokens }
1129
+ })
1130
+
1131
+ type CompactionSummaryValue = {
1132
+ readonly id: string
1133
+ readonly conversationId: string
1134
+ readonly covers: ReadonlyArray<string>
1135
+ readonly content: string
1136
+ readonly tokensBefore: number
1137
+ readonly tokensAfter: number
1138
+ }
1139
+
1140
+ // --- model step ------------------------------------------------------------------------------------------------------
1141
+
1142
+ /** Make the call ids of one response unique (a repeated id gets `#2`, `#3`), so each call has its own result. */
1143
+ const uniqueCallIds = (calls: ReadonlyArray<ToolCall>): ReadonlyArray<ToolCall> => {
1144
+ const seen = new Map<string, number>()
1145
+ return calls.map((call) => {
1146
+ const n = (seen.get(call.toolCallId) ?? 0) + 1
1147
+ seen.set(call.toolCallId, n)
1148
+ return n === 1 ? call : { ...call, toolCallId: `${call.toolCallId}#${n}` }
1149
+ })
1150
+ }
1151
+
1152
+ const CANCELLED_ERROR = "The run was cancelled"
1153
+ const CANCELLED = { kind: "stop", reason: "cancelled", message: CANCELLED_ERROR } satisfies ModelOutcome
1154
+
1155
+ /**
1156
+ * The ancestors of a run (its parent, the parent's parent, up to the person's run) as a recursive CTE fragment named
1157
+ * `ancestors (id, depth)`, depth 1 for the parent.
1158
+ */
1159
+ const ANCESTORS = (
1160
+ sql: SqlClient.SqlClient,
1161
+ parentRunId: string,
1162
+ ) => sql`WITH RECURSIVE ancestors (id, parent, depth) AS (
1163
+ SELECT id, parent_run_id, 1 FROM eloxiv_agent.run WHERE id = ${parentRunId}
1164
+ UNION ALL
1165
+ SELECT r.id, r.parent_run_id, a.depth + 1 FROM eloxiv_agent.run r JOIN ancestors a ON r.id = a.parent
1166
+ )`
1167
+
1168
+ /**
1169
+ * Whether any of a sub-agent's ancestors was cancelled or has ended, every ancestor's row held (FOR SHARE) until the
1170
+ * caller's transaction ends, the oldest first (false for a run without a parent). A sub-agent is cancelled with every
1171
+ * run above it: `agent.cancel` commits a run's flag holding that run's row, so every check of a sub-agent that holds
1172
+ * its own row holds all its ancestors' first (always in that order), and sees a cancellation of any of them that
1173
+ * committed before it, while one that commits after waits for it. (The kernel's reaction then records the flag on
1174
+ * the cancelled run's whole subtree, and wakes each.) A run that ended while seats of its team still ran is the same:
1175
+ * its seats (an orphaned seat, too, resumed after a restart) stop at their next check.
1176
+ */
1177
+ const parentCancelled = (sql: SqlClient.SqlClient, run: { readonly parentRunId: string | null }) =>
1178
+ run.parentRunId === null
1179
+ ? Effect.succeed(false)
1180
+ : sql<{ cancelled: boolean }>`${ANCESTORS(sql, run.parentRunId)}
1181
+ SELECT r.finished_at IS NOT NULL OR r.cancel_requested_at IS NOT NULL AS cancelled
1182
+ FROM eloxiv_agent.run r JOIN ancestors a ON a.id = r.id
1183
+ ORDER BY a.depth DESC FOR SHARE OF r`.pipe(Effect.map((rows) => rows.some((row) => row.cancelled)))
1184
+
1185
+ /**
1186
+ * The run's row, locked, in the transaction that applies a model's or a device's reply: whether its cancellation
1187
+ * (or its parent's) committed. `agent.cancel` locks the same row, so a cancellation either committed first (and the
1188
+ * reply is discarded) or commits after the reply is applied (and the run ends cancelled at its finish).
1189
+ */
1190
+ const cancelledForUpdate = (sql: SqlClient.SqlClient, spec: Spec) =>
1191
+ Effect.gen(function* () {
1192
+ const parent = yield* parentCancelled(sql, spec)
1193
+ const [row] = yield* sql<{ cancelled: boolean }>`SELECT cancel_requested_at IS NOT NULL AS cancelled
1194
+ FROM eloxiv_agent.run WHERE id = ${spec.runId} FOR UPDATE`
1195
+ return parent || row?.cancelled === true
1196
+ })
1197
+
1198
+ /** The run as processors see it. */
1199
+ const processorRun = (spec: Spec): ProcessorRun => ({
1200
+ runId: spec.runId,
1201
+ orgId: spec.orgId,
1202
+ userId: spec.userId,
1203
+ conversationId: spec.conversationId,
1204
+ parentRunId: spec.parentRunId,
1205
+ })
1206
+
1207
+ const trippedStop = (tripped: Tripped) =>
1208
+ ({
1209
+ kind: "stop",
1210
+ reason: "processor",
1211
+ message: `The processor ${tripped.processor} stopped the run: ${tripped.reason}`,
1212
+ }) satisfies ModelOutcome
1213
+
1214
+ const modelStep = (
1215
+ spec: Spec,
1216
+ step: number,
1217
+ consumed: Consumed,
1218
+ loaded: ReadonlySet<string>,
1219
+ note: string | null = null,
1220
+ ) =>
1221
+ Effect.gen(function* () {
1222
+ const sql = yield* SqlClient.SqlClient
1223
+ const settings = yield* AgentSettings
1224
+ const models = yield* ModelProviders
1225
+ const metering = yield* Metering
1226
+ const hub = yield* AgentHub
1227
+ const messageId = `${spec.runId}:m:${step}`
1228
+ const run = { id: spec.runId, orgId: spec.orgId, userId: spec.userId }
1229
+ const maxOutputTokens = settings.maxOutputTokens
1230
+
1231
+ const stored = (content: any): ModelOutcome => ({
1232
+ kind: "response",
1233
+ text: String(content.text ?? ""),
1234
+ toolCalls: content.toolCalls ?? [],
1235
+ usage: content.usage ?? { inputTokens: 0, outputTokens: 0 },
1236
+ calls: content.consumed?.calls ?? 1,
1237
+ tokens: content.consumed?.tokens ?? (content.usage?.inputTokens ?? 0) + (content.usage?.outputTokens ?? 0),
1238
+ })
1239
+ // Fenced: a step that already persisted its response (and was cut off before the journal recorded it)
1240
+ // returns that response; one response is applied per step.
1241
+ const [persisted] = yield* inTranscript(
1242
+ spec,
1243
+ (sql) => sql<{ content: any }>`SELECT content FROM eloxiv_agent.message WHERE id = ${messageId}`,
1244
+ )
1245
+ if (persisted !== undefined) return stored(persisted.content)
1246
+
1247
+ // Calls this step started whose answers were lost (the process died between the provider's answer and its
1248
+ // record): the step runs again and calls the model again, and each lost call is metered, and counted in the
1249
+ // run, at what it reserved. Also when the run was cancelled meanwhile: the lost call was made all the same.
1250
+ const lost = yield* inAgent(
1251
+ sql,
1252
+ spec.orgId,
1253
+ Effect.gen(function* () {
1254
+ const lost = yield* abandonCalls(sql, { orgId: spec.orgId, runId: spec.runId, step })
1255
+ if (lost.calls > 0) {
1256
+ yield* sql`UPDATE eloxiv_agent.run SET steps = steps + ${lost.calls},
1257
+ input_tokens = input_tokens + ${lost.inputTokens}, output_tokens = output_tokens + ${lost.outputTokens}
1258
+ WHERE id = ${spec.runId}`
1259
+ }
1260
+ return lost
1261
+ }),
1262
+ )
1263
+ if (yield* isCancelled(spec)) return CANCELLED
1264
+ let calls = lost.calls
1265
+ let tokens = lost.tokens
1266
+ if (consumed.calls + calls >= spec.limits.maxSteps) {
1267
+ return {
1268
+ kind: "stop",
1269
+ reason: "steps",
1270
+ message: `The run reached its step limit (${spec.limits.maxSteps})`,
1271
+ } satisfies ModelOutcome
1272
+ }
1273
+ if (Date.now() - spec.startedAt > spec.limits.maxWallMs) {
1274
+ return {
1275
+ kind: "stop",
1276
+ reason: "wall-time",
1277
+ message: `The run reached its wall-time limit (${spec.limits.maxWallMs} ms)`,
1278
+ } satisfies ModelOutcome
1279
+ }
1280
+
1281
+ const { offered: tools, deferred } = yield* offeredTools(spec, loaded)
1282
+ let context = yield* contextFor(spec, tools, deferred, note)
1283
+ const conversationTokens = (context.totals["messages"] ?? 0) + (context.totals["tool-results"] ?? 0)
1284
+ // (Only the conversation's owner's runs compact it: a summary another person's run wrote would quote what that
1285
+ // person's agent read with their permissions.)
1286
+ if (
1287
+ spec.conversationOwner === undefined &&
1288
+ conversationTokens > settings.budgets.messages &&
1289
+ consumed.calls + calls + 1 < spec.limits.maxSteps
1290
+ ) {
1291
+ // Over the conversation budget, with room for the compaction and the call: compact, then assemble again.
1292
+ // The compaction is one of the run's model calls. A compaction that does not fit the run's tokens or a
1293
+ // budget is not made (the call's own checks below then decide).
1294
+ // Its folds may take every model call but the one after them.
1295
+ const compacted = yield* compactConversation({ ...spec, step }, runAuthority(spec), {
1296
+ tokens: spec.limits.maxTokens - consumed.tokens - tokens,
1297
+ calls: spec.limits.maxSteps - consumed.calls - calls - 1,
1298
+ }).pipe(Effect.catchTag("BudgetExceeded", () => Effect.succeed(null)))
1299
+ if (compacted !== null) {
1300
+ calls += compacted.calls
1301
+ tokens += compacted.tokens
1302
+ context = yield* contextFor(spec, tools, deferred, note)
1303
+ }
1304
+ }
1305
+
1306
+ // The run's token limit counts the call's worst case: its context and the most it may write.
1307
+ const used = consumed.tokens + tokens
1308
+ if (used + context.total + maxOutputTokens > spec.limits.maxTokens) {
1309
+ return {
1310
+ kind: "stop",
1311
+ reason: "tokens",
1312
+ message: `The next model call (about ${context.total} tokens in, up to ${maxOutputTokens} out) would pass the run's token limit (${spec.limits.maxTokens}; ${used} used)`,
1313
+ } satisfies ModelOutcome
1314
+ }
1315
+ const resolved = yield* models.resolveFor(spec.orgId, spec.userId).pipe(Effect.result)
1316
+ if (resolved._tag === "Failure")
1317
+ return { kind: "stop", reason: "model-error", message: resolved.failure.message } satisfies ModelOutcome
1318
+ const choice = { success: resolved.success.choice }
1319
+ const pricing = models.pricing(choice.success)
1320
+ // Metering: the call's worst case is reserved before it is made (the call is recorded as started), never after.
1321
+ const reserved = yield* metering
1322
+ .reserve({
1323
+ orgId: spec.orgId,
1324
+ userId: spec.userId,
1325
+ runId: spec.runId,
1326
+ step,
1327
+ kind: "run",
1328
+ choice: choice.success,
1329
+ pricing,
1330
+ inputTokens: context.total,
1331
+ maxOutputTokens,
1332
+ })
1333
+ .pipe(Effect.result)
1334
+ if (reserved._tag === "Failure")
1335
+ return { kind: "stop", reason: "budget", message: reserved.failure.message } satisfies ModelOutcome
1336
+ const reservation = reserved.success
1337
+
1338
+ // This model call of the step: its streamed text is told apart from an earlier call's (one cut off by a restart).
1339
+ const attempt = reservation.id
1340
+ // The app's processors see each streamed piece; once one trips, nothing more reaches the clients following the
1341
+ // run, and the reply is not applied.
1342
+ const guard = chunkGuard(settings.processors, processorRun(spec), step)
1343
+ const generated = yield* models
1344
+ .generate({
1345
+ orgId: spec.orgId,
1346
+ userId: spec.userId,
1347
+ model: choice.success,
1348
+ messages: context.messages,
1349
+ tools: context.tools,
1350
+ maxOutputTokens,
1351
+ timeoutMs: settings.modelCallTimeoutMs,
1352
+ onDelta: (delta) => {
1353
+ if (guard.push(delta)) hub.publish(spec.runId, { step, attempt, delta })
1354
+ },
1355
+ })
1356
+ .pipe(Effect.result)
1357
+ if (generated._tag === "Failure") {
1358
+ yield* metering.release(reservation)
1359
+ const transient = generated.failure.reason === "rate-limited" || generated.failure.reason === "timeout"
1360
+ return {
1361
+ kind: "stop",
1362
+ reason: "model-error",
1363
+ message: generated.failure.message,
1364
+ ...(transient ? { retryable: true } : {}),
1365
+ } satisfies ModelOutcome
1366
+ }
1367
+ const result = { ...generated.success, toolCalls: uniqueCallIds(generated.success.toolCalls) }
1368
+ const tripped = guard.tripped()
1369
+ calls += 1
1370
+ tokens += result.usage.inputTokens + result.usage.outputTokens
1371
+ const inventory = {
1372
+ runId: spec.runId,
1373
+ step,
1374
+ items: context.items,
1375
+ totals: context.totals,
1376
+ budgets: settings.budgets,
1377
+ total: context.total,
1378
+ evicted: context.evicted,
1379
+ }
1380
+ const content = {
1381
+ text: result.text,
1382
+ toolCalls: result.toolCalls,
1383
+ usage: result.usage,
1384
+ model: choice.success,
1385
+ finishReason: result.finishReason,
1386
+ consumed: { calls, tokens },
1387
+ }
1388
+ // The call was made: metered once, whatever happens to its response (counted in the run).
1389
+ const settle = Effect.gen(function* () {
1390
+ if (yield* settleCall(sql, reservation, result.usage)) {
1391
+ yield* sql`UPDATE eloxiv_agent.run SET steps = steps + 1, input_tokens = input_tokens + ${result.usage.inputTokens},
1392
+ output_tokens = output_tokens + ${result.usage.outputTokens} WHERE id = ${spec.runId}`
1393
+ }
1394
+ })
1395
+ // The reply joins the person's transcript only while the run's authority holds; a refused reply is metered all
1396
+ // the same, and the run ends with the refusal. A reply that arrives after the run's cancellation committed is
1397
+ // metered and recorded as discarded (`reply-discarded`, with its usage), never applied: not in the conversation,
1398
+ // none of its tool calls made, and the run ends cancelled.
1399
+ const applied = yield* inTranscript(spec, (sql) =>
1400
+ Effect.gen(function* () {
1401
+ const cancelled = yield* cancelledForUpdate(sql, spec)
1402
+ yield* settle
1403
+ if (cancelled) {
1404
+ // (A response stored first for this step stays the step's.)
1405
+ const [first] = yield* sql<{ content: any }>`SELECT content FROM eloxiv_agent.message WHERE id = ${messageId}`
1406
+ if (first !== undefined) return stored(first.content)
1407
+ yield* appendEvent(sql, run, "reply-discarded", {
1408
+ step,
1409
+ attempt,
1410
+ reason: "cancelled",
1411
+ usage: result.usage,
1412
+ toolCalls: result.toolCalls.length,
1413
+ // A late answer: kept (the owner's) for a continuation to see, never acted on.
1414
+ text: result.text,
1415
+ })
1416
+ return CANCELLED
1417
+ }
1418
+ if (tripped !== undefined) {
1419
+ // A processor stopped the reply: metered (above), recorded, never applied (no message, no tool call).
1420
+ const [first] = yield* sql<{ content: any }>`SELECT content FROM eloxiv_agent.message WHERE id = ${messageId}`
1421
+ if (first !== undefined) return stored(first.content)
1422
+ yield* appendEvent(sql, run, "processor-tripped", {
1423
+ step,
1424
+ attempt,
1425
+ at: "chunk",
1426
+ processor: tripped.processor,
1427
+ reason: tripped.reason,
1428
+ usage: result.usage,
1429
+ toolCalls: result.toolCalls.length,
1430
+ })
1431
+ return trippedStop(tripped)
1432
+ }
1433
+ const seq = yield* clockSeq(sql)
1434
+ const inserted = yield* sql<{ id: string }>`INSERT INTO eloxiv_agent.message
1435
+ (id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
1436
+ VALUES (${messageId}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId}, ${spec.runId}, ${seq}, 'assistant',
1437
+ ${JSON.stringify(content)}::jsonb, ${result.text})
1438
+ ON CONFLICT (id) DO NOTHING RETURNING id`
1439
+ // One response is applied per step: one stored first wins, and this one's effects never happen.
1440
+ if (inserted.length === 0) {
1441
+ const [first] = yield* sql<{ content: any }>`SELECT content FROM eloxiv_agent.message WHERE id = ${messageId}`
1442
+ return stored(first!.content)
1443
+ }
1444
+ yield* sql`INSERT INTO eloxiv_agent.inventory (id, org_id, user_id, run_id, step, data)
1445
+ VALUES (${`${spec.runId}:${step}`}, ${spec.orgId}, ${spec.userId}, ${spec.runId}, ${step}, ${JSON.stringify(inventory)}::jsonb)`
1446
+ yield* appendEvent(sql, run, "model-step", {
1447
+ step,
1448
+ text: result.text,
1449
+ toolCalls: result.toolCalls,
1450
+ usage: result.usage,
1451
+ contextTokens: context.total,
1452
+ })
1453
+ return undefined
1454
+ }),
1455
+ ).pipe(
1456
+ Effect.tapError((refusal) =>
1457
+ isRefusal(refusal) ? inAgent(sql, spec.orgId, settle).pipe(Effect.orDie) : Effect.void,
1458
+ ),
1459
+ )
1460
+ yield* metering.alert(spec.orgId, spec.userId)
1461
+ if (applied !== undefined) return applied
1462
+ return {
1463
+ kind: "response",
1464
+ text: result.text,
1465
+ toolCalls: result.toolCalls,
1466
+ usage: result.usage,
1467
+ calls,
1468
+ tokens,
1469
+ } satisfies ModelOutcome
1470
+ })
1471
+
1472
+ // --- attachments ------------------------------------------------------------------------------------------------------
1473
+
1474
+ const READ_TEXT = "files.readText"
1475
+
1476
+ /**
1477
+ * Read the content of the files attached to the run's message (C-027), each with `files.readText` called as the
1478
+ * person's agent through the invocation path: so only a file the person may read now, under the run's authority and
1479
+ * the agent's reach, audited; a refusal is kept as the reason. Each file's text is bounded (`ATTACHMENT_LIMITS`), and
1480
+ * recorded on the message (`content.attachmentText`, by file id), which the model is shown with the message. Read-only:
1481
+ * a step run again reads again.
1482
+ */
1483
+ const readAttachments = (spec: Spec, key: string) =>
1484
+ Effect.gen(function* () {
1485
+ const [message] = yield* inTranscript(
1486
+ spec,
1487
+ (sql) => sql<{ id: string; content: { attachments?: ReadonlyArray<{ fileId: string }> } }>`SELECT id, content
1488
+ FROM eloxiv_agent.message WHERE run_id = ${spec.runId} AND role = 'user' ORDER BY seq LIMIT 1`,
1489
+ )
1490
+ if (message === undefined) return null
1491
+ const read: Record<string, unknown> = {}
1492
+ let left: number = ATTACHMENT_LIMITS.total
1493
+ // Each file once, at most `files` of them.
1494
+ const attachments = [...new Map((message.content.attachments ?? []).map((a) => [a.fileId, a])).values()].slice(
1495
+ 0,
1496
+ ATTACHMENT_LIMITS.files,
1497
+ )
1498
+ for (const [index, attachment] of attachments.entries()) {
1499
+ if (left <= 0) {
1500
+ read[attachment.fileId] = { refused: "LimitReached", message: "The attachments' text limit was reached" }
1501
+ continue
1502
+ }
1503
+ const limit = Math.min(ATTACHMENT_LIMITS.perFile, left)
1504
+ // A read: a fresh key per attempt, so a step run again after a crash reads the text again (never a replay).
1505
+ const { result, cancelled } = yield* executeTool(
1506
+ spec,
1507
+ { action: READ_TEXT },
1508
+ { toolCallId: `attachment-${index}`, toolName: "files_readText", input: { fileId: attachment.fileId, limit } },
1509
+ `${key}:${index}:${crypto.randomUUID()}`,
1510
+ )
1511
+ if (cancelled) return null
1512
+ if (!result.ok) {
1513
+ read[attachment.fileId] = { refused: result.error._tag }
1514
+ continue
1515
+ }
1516
+ const page = (result.output as { readonly output?: { readonly text?: string; readonly nextOffset?: unknown } })
1517
+ .output
1518
+ const text = (page?.text ?? "").slice(0, limit)
1519
+ left -= text.length
1520
+ read[attachment.fileId] = { text, truncated: page?.nextOffset !== null && page?.nextOffset !== undefined }
1521
+ }
1522
+ yield* inTranscript(
1523
+ spec,
1524
+ (
1525
+ sql,
1526
+ ) => sql`UPDATE eloxiv_agent.message SET content = jsonb_set(content, '{attachmentText}', ${JSON.stringify(read)}::jsonb)
1527
+ WHERE id = ${message.id}`,
1528
+ )
1529
+ return null
1530
+ })
1531
+
1532
+ // --- tool steps -------------------------------------------------------------------------------------------------------
1533
+
1534
+ const isCancelled = (spec: Spec) =>
1535
+ Effect.gen(function* () {
1536
+ const sql = yield* SqlClient.SqlClient
1537
+ const [state] = yield* inAgent(
1538
+ sql,
1539
+ spec.orgId,
1540
+ // The run's own flag, or any ancestor's (or an ancestor that ended: its seats stop with it).
1541
+ sql<{ cancelled: boolean }>`WITH RECURSIVE chain (id, parent, cancelled) AS (
1542
+ SELECT id, parent_run_id, cancel_requested_at IS NOT NULL FROM eloxiv_agent.run WHERE id = ${spec.runId}
1543
+ UNION ALL
1544
+ SELECT r.id, r.parent_run_id, r.cancel_requested_at IS NOT NULL OR r.finished_at IS NOT NULL
1545
+ FROM eloxiv_agent.run r JOIN chain c ON r.id = c.parent
1546
+ ) SELECT bool_or(cancelled) AS cancelled FROM chain`,
1547
+ )
1548
+ return state?.cancelled === true
1549
+ })
1550
+
1551
+ /**
1552
+ * The run's cancellation, checked inside a tool call's own transaction (`InvocationRequest.guard`): it reads the
1553
+ * run's flag and holds the run's row (FOR SHARE) until the call commits, so a cancellation either committed
1554
+ * before (and the call is refused, nothing of it commits) or commits after the call did. `cancelled` is set when
1555
+ * it refuses. It runs in the invocation's fiber (needing nothing from its context, so the invocation's own
1556
+ * transaction connection is the one it uses).
1557
+ */
1558
+ const cancelGuard = (sql: SqlClient.SqlClient, spec: Spec, refused: { cancelled: boolean }) =>
1559
+ Effect.gen(function* () {
1560
+ const cancelled = yield* asAgent(
1561
+ sql,
1562
+ spec.orgId,
1563
+ Effect.gen(function* () {
1564
+ const parent = yield* parentCancelled(sql, spec)
1565
+ const [row] = yield* sql<{ cancelled: boolean }>`SELECT cancel_requested_at IS NOT NULL AS cancelled
1566
+ FROM eloxiv_agent.run WHERE id = ${spec.runId} FOR SHARE`
1567
+ return parent || row?.cancelled === true
1568
+ }),
1569
+ ).pipe(Effect.orDie)
1570
+ if (!cancelled) return
1571
+ refused.cancelled = true
1572
+ return yield* new Forbidden({ action: "agent.run", message: "The agent run was cancelled; this call did not run" })
1573
+ })
1574
+
1575
+ /**
1576
+ * Run a tool's action as the run's person, refused inside its transaction if the run was cancelled, unless the
1577
+ * call is the run's own clean-up after its cancellation (`unguarded`: cancelling its device turn).
1578
+ */
1579
+ const executeTool = (
1580
+ spec: Spec,
1581
+ definition: { readonly action: string },
1582
+ call: ToolCall,
1583
+ key: string,
1584
+ options: { readonly unguarded?: boolean; readonly step?: number } = {},
1585
+ ) =>
1586
+ Effect.gen(function* () {
1587
+ const tools = yield* AgentTools
1588
+ const sql = yield* SqlClient.SqlClient
1589
+ const refusal = { cancelled: false }
1590
+ const guard = options.unguarded === true ? undefined : cancelGuard(sql, spec, refusal)
1591
+ const identity = yield* toolIdentity(spec)
1592
+ const agentRun = {
1593
+ runId: spec.runId,
1594
+ conversationId: spec.conversationId,
1595
+ step: options.step ?? 0,
1596
+ toolCallId: call.toolCallId,
1597
+ }
1598
+ const result = yield* tools.execute({
1599
+ action: definition.action,
1600
+ input: call.input,
1601
+ idempotencyKey: key,
1602
+ caller:
1603
+ spec.agentSessionId === null
1604
+ ? { identity, agentRun, editGroup: spec.editGroup, ...(guard === undefined ? {} : { guard }) }
1605
+ : {
1606
+ identity,
1607
+ agentSession: spec.agentSessionId,
1608
+ agentRun,
1609
+ editGroup: spec.editGroup,
1610
+ ...(guard === undefined ? {} : { guard }),
1611
+ },
1612
+ })
1613
+ return { result, cancelled: refusal.cancelled }
1614
+ })
1615
+
1616
+ /** What a tool event names for people: the action a tool call is and its title (as the tool's definition has it). */
1617
+ interface ToolLabel {
1618
+ readonly action: string
1619
+ readonly title: string
1620
+ }
1621
+ const labelOf = (definition: { readonly action: string; readonly title: string }): ToolLabel => ({
1622
+ action: definition.action,
1623
+ title: definition.title,
1624
+ })
1625
+
1626
+ /**
1627
+ * Persist a tool call's result (once: the message id is the step's) and announce it, with the action and its title
1628
+ * (`label`) when the call is an action's, so a client names it without a table of modules.
1629
+ */
1630
+ const persistResult = (
1631
+ spec: Spec,
1632
+ step: number,
1633
+ call: ToolCall,
1634
+ raw: AgentToolResult,
1635
+ consumed?: Consumed,
1636
+ label?: ToolLabel,
1637
+ ) =>
1638
+ Effect.gen(function* () {
1639
+ const messageId = `${spec.runId}:t:${step}:${call.toolCallId}`
1640
+ // Stored, journalled and read by the model as JSON (a Date becomes its ISO string): the step's result is
1641
+ // exactly what the conversation holds.
1642
+ const result = JSON.parse(JSON.stringify(raw)) as AgentToolResult
1643
+ // Into the person's transcript only while the run's authority holds.
1644
+ yield* inTranscript(spec, (sql) =>
1645
+ Effect.gen(function* () {
1646
+ const seq = yield* clockSeq(sql)
1647
+ const content = { toolCallId: call.toolCallId, toolName: call.toolName, result }
1648
+ const inserted = yield* sql<{ id: string }>`INSERT INTO eloxiv_agent.message
1649
+ (id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
1650
+ VALUES (${messageId}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId}, ${spec.runId}, ${seq}, 'tool',
1651
+ ${JSON.stringify(content)}::jsonb, '')
1652
+ ON CONFLICT (id) DO NOTHING RETURNING id`
1653
+ if (inserted.length > 0) {
1654
+ yield* sql`UPDATE eloxiv_agent.run SET status = 'running', wait = NULL WHERE id = ${spec.runId}`
1655
+ yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "tool-result", {
1656
+ step,
1657
+ toolCallId: call.toolCallId,
1658
+ toolName: call.toolName,
1659
+ ...label,
1660
+ ok: result.ok,
1661
+ error: result.ok ? null : result.error._tag,
1662
+ result,
1663
+ })
1664
+ }
1665
+ }),
1666
+ )
1667
+ return (
1668
+ consumed === undefined ? { kind: "result", result } : { kind: "result", result, consumed }
1669
+ ) satisfies ToolOutcome
1670
+ })
1671
+
1672
+ /**
1673
+ * The internal tools that are not actions: the query fallback and `load_skill`. Each reads the person's data with
1674
+ * the capability the run's authority gives (`Authority.within`): refused, audited, once any link of the run's chain
1675
+ * no longer holds, or when the run's scope does not cover the read (a view read is the query surface's).
1676
+ */
1677
+ const internalTool = (spec: Spec, call: ToolCall, key: string, loaded: ReadonlySet<string>) =>
1678
+ Effect.gen(function* () {
1679
+ const input = (call.input ?? {}) as Record<string, unknown>
1680
+ const refusedBy = (error: { readonly _tag: string; readonly message: string }) => refused(error._tag, error.message)
1681
+ if (call.toolName === TOOL_SEARCH) {
1682
+ // Over exactly the action tools the run could be offered now (allowed, reachable, plan mode).
1683
+ const { available, actionTools } = yield* availableTools(spec)
1684
+ const searchable = available.filter((tool) => actionTools.has(tool.name))
1685
+ return { ok: true, output: searchTools(call.input, searchable, loaded) } satisfies AgentToolResult
1686
+ }
1687
+ if (call.toolName === "load_skill") {
1688
+ const resources = yield* AgentResources
1689
+ const sql = yield* SqlClient.SqlClient
1690
+ // The same team as the run's context: the conversation's bound team, else the person's active team.
1691
+ const skills = yield* (yield* Authority)
1692
+ .within(runAuthority(spec), (asserted) =>
1693
+ teamOfConversation(asserted, sql, spec.conversationId).pipe(
1694
+ Effect.flatMap((team) => resources.effective(asserted, "skill", team)),
1695
+ ),
1696
+ )
1697
+ .pipe(Effect.result)
1698
+ if (skills._tag === "Failure") return refusedBy(skills.failure)
1699
+ const skill = skills.success.find((s) => s.path === input["skill"])
1700
+ return skill === undefined
1701
+ ? refused("InvalidInput", `No skill ${String(input["skill"])}`)
1702
+ : ({
1703
+ ok: true,
1704
+ output: { skill: skill.path, scope: skill.scope, content: skill.content },
1705
+ } satisfies AgentToolResult)
1706
+ }
1707
+ // query: a published view read as the person (read-only, filtered by their read policy), audited as the agent's.
1708
+ const queryViews = yield* QueryViews
1709
+ const identity = yield* Identity
1710
+ const audit = yield* Audit
1711
+ // As the agent session's person (a revoked session stops reads too), or the system actor for a job's run.
1712
+ const actor = yield* (
1713
+ spec.agentSessionId === null
1714
+ ? identity.resolve(identityOf(spec))
1715
+ : identity.resolveAgentSession(spec.agentSessionId, identityOf(spec)).pipe(Effect.map((r) => r.actor))
1716
+ ).pipe(Effect.result)
1717
+ const view = typeof input["view"] === "string" ? input["view"] : ""
1718
+ const inputHash = yield* Effect.promise(() => sha256(canonicalJson(call.input ?? null)))
1719
+ const record = (outcome: "succeeded" | "failed" | "denied", errorTag: string | null) =>
1720
+ audit.record({
1721
+ invocationId: crypto.randomUUID(),
1722
+ action: "eloxiv.queryView",
1723
+ surface: "agent",
1724
+ actorUserId: spec.userId,
1725
+ orgId: spec.orgId,
1726
+ outcome,
1727
+ inputHash,
1728
+ idempotencyKey: key,
1729
+ errorTag,
1730
+ affected: null,
1731
+ requested: null,
1732
+ completion: null,
1733
+ })
1734
+ if (actor._tag === "Failure") {
1735
+ yield* record("denied", actor.failure._tag)
1736
+ return refused(actor.failure._tag, actor.failure.message)
1737
+ }
1738
+ const limit = typeof input["limit"] === "number" ? Math.min(Math.max(0, input["limit"]), 200) : 50
1739
+ const rows = yield* (yield* Authority)
1740
+ .within(runAuthority(spec), (asserted) => queryViews.readAs({ asserted, actor: actor.success, view, limit }))
1741
+ .pipe(Effect.result)
1742
+ if (rows._tag === "Failure") {
1743
+ const denied = rows.failure._tag === "Unauthenticated" || rows.failure._tag === "Forbidden"
1744
+ yield* record(denied ? "denied" : "failed", rows.failure._tag)
1745
+ return refusedBy(rows.failure)
1746
+ }
1747
+ yield* record("succeeded", null)
1748
+ // As JSON (timestamps as ISO strings): the result is journalled and stored, and the model reads JSON.
1749
+ return { ok: true, output: { view, rows: JSON.parse(JSON.stringify(rows.success)) } } satisfies AgentToolResult
1750
+ })
1751
+
1752
+ /**
1753
+ * A call held for the person's consent: record the run's wait for it, unless the run is cancelled, in one
1754
+ * statement (a cancellation that committed before it is seen here; one that commits after finds the wait and
1755
+ * signals it), and read whether the person already decided (before the wait was recorded, nothing would wake it).
1756
+ */
1757
+ const holdForConsent = (spec: Spec, step: number, call: ToolCall, action: string, title: string, consentId: string) =>
1758
+ Effect.gen(function* () {
1759
+ const sql = yield* SqlClient.SqlClient
1760
+ const signal = `wait/${step}/${call.toolCallId}`
1761
+ const waiting = yield* inAgent(
1762
+ sql,
1763
+ spec.orgId,
1764
+ Effect.gen(function* () {
1765
+ // Every ancestor's row held first: a cancellation of any of them that committed before is seen here.
1766
+ if (yield* parentCancelled(sql, spec)) return false
1767
+ const waiting = yield* sql<{ id: string }>`UPDATE eloxiv_agent.run SET status = 'waiting',
1768
+ wait = ${JSON.stringify({ signal, consentId, toolCallId: call.toolCallId })}::jsonb
1769
+ WHERE id = ${spec.runId} AND cancel_requested_at IS NULL RETURNING id`
1770
+ if (waiting.length === 0) return false
1771
+ yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "consent-required", {
1772
+ step,
1773
+ toolCallId: call.toolCallId,
1774
+ action,
1775
+ // What the person sees it called (the action's title), so a client needs no table of modules.
1776
+ title,
1777
+ consentId,
1778
+ })
1779
+ return true
1780
+ }),
1781
+ )
1782
+ if (!waiting) return { kind: "cancel", signal } as const
1783
+ const [request] = yield* sql.withTransaction(
1784
+ asSystem(
1785
+ sql,
1786
+ "consent",
1787
+ spec.orgId,
1788
+ sql<{ status: string }>`SELECT status FROM eloxiv_consent.request WHERE id = ${consentId}`,
1789
+ ),
1790
+ )
1791
+ const decided: Decision | null =
1792
+ request?.status === "approved" || request?.status === "used"
1793
+ ? { kind: "consent", status: "approved" }
1794
+ : request?.status === "rejected"
1795
+ ? { kind: "consent", status: "rejected" }
1796
+ : null
1797
+ return { kind: "held", signal, decided } as const
1798
+ })
1799
+
1800
+ /**
1801
+ * Apply the person's decision on a held call to the run: back to running (recorded as `consent-decided`). True
1802
+ * when the run was cancelled meanwhile: then nothing runs.
1803
+ */
1804
+ const consentDecided = (spec: Spec, step: number, call: ToolCall, consentId: string, approved: boolean) =>
1805
+ Effect.gen(function* () {
1806
+ const sql = yield* SqlClient.SqlClient
1807
+ return yield* inAgent(
1808
+ sql,
1809
+ spec.orgId,
1810
+ Effect.gen(function* () {
1811
+ const parent = yield* parentCancelled(sql, spec)
1812
+ const [run] = yield* sql<{ status: string; cancelled: boolean }>`
1813
+ SELECT status, cancel_requested_at IS NOT NULL AS cancelled FROM eloxiv_agent.run WHERE id = ${spec.runId}
1814
+ FOR UPDATE`
1815
+ const cancelled = parent || run?.cancelled === true
1816
+ if (run?.status !== "waiting") return cancelled
1817
+ yield* sql`UPDATE eloxiv_agent.run SET status = 'running', wait = NULL WHERE id = ${spec.runId}`
1818
+ yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "consent-decided", {
1819
+ step,
1820
+ toolCallId: call.toolCallId,
1821
+ consentId,
1822
+ status: approved ? "approved" : "rejected",
1823
+ ran: approved && !cancelled,
1824
+ })
1825
+ return cancelled
1826
+ }),
1827
+ )
1828
+ })
1829
+
1830
+ const toolStep = (spec: Spec, step: number, call: ToolCall, key: string, loaded: ReadonlySet<string>) =>
1831
+ Effect.gen(function* () {
1832
+ const tools = yield* AgentTools
1833
+ if (yield* isCancelled(spec)) return { kind: "cancelled" } satisfies ToolOutcome
1834
+ const allowed = allowedTools(yield* runTools(spec.orgId, optionsOf(spec)), spec)
1835
+ if (!allowed.some((t) => t.name === call.toolName)) {
1836
+ return yield* persistResult(
1837
+ spec,
1838
+ step,
1839
+ call,
1840
+ refused("ToolNotAllowed", `This run may not use the tool ${call.toolName}`, { tool: call.toolName }),
1841
+ )
1842
+ }
1843
+ const definition = (yield* tools.definitionsFor(spec.orgId)).get(call.toolName)
1844
+ if (definition === undefined)
1845
+ return yield* persistResult(spec, step, call, yield* internalTool(spec, call, key, loaded))
1846
+ // Plan mode: an action that is not read-only is refused here, before the invocation path (it never runs).
1847
+ if (optionsOf(spec).mode === "plan" && !readOnly(yield* Registry, definition.action)) {
1848
+ return yield* persistResult(
1849
+ spec,
1850
+ step,
1851
+ call,
1852
+ refused(
1853
+ "PlanMode",
1854
+ `This run is in plan mode: ${definition.action} changes data, so it was not called. Describe it in your plan instead.`,
1855
+ { action: definition.action },
1856
+ ),
1857
+ undefined,
1858
+ labelOf(definition),
1859
+ )
1860
+ }
1861
+ const { result, cancelled } = yield* executeTool(spec, definition, call, key, { step })
1862
+ if (cancelled) return { kind: "cancelled" } satisfies ToolOutcome
1863
+ if (!result.ok && result.error._tag === "ConsentRequired") {
1864
+ const consentId = String(result.error["consentId"])
1865
+ const held = yield* holdForConsent(spec, step, call, definition.action, definition.title, consentId)
1866
+ if (held.kind === "cancel")
1867
+ return { kind: "consent", consentId, signal: held.signal, decided: { kind: "cancel" } } satisfies ToolOutcome
1868
+ return { kind: "consent", consentId, signal: held.signal, decided: held.decided } satisfies ToolOutcome
1869
+ }
1870
+ return yield* persistResult(spec, step, call, result, undefined, labelOf(definition))
1871
+ })
1872
+
1873
+ /**
1874
+ * A tool's result through the app's processors (inside the tool's journalled step): a trip is recorded on the run's
1875
+ * stream (`processor-tripped`) and carried on the outcome, so the run stops before its next model call.
1876
+ */
1877
+ const processTool = (spec: Spec, step: number, call: ToolCall, outcome: ToolOutcome) =>
1878
+ Effect.gen(function* () {
1879
+ const { processors } = yield* AgentSettings
1880
+ if (outcome.kind !== "result" || !processors.some((p) => p.onToolResult !== undefined)) return outcome
1881
+ const tripped = yield* toolGuard(processors, { run: processorRun(spec), step, call, result: outcome.result })
1882
+ if (tripped === undefined) return outcome
1883
+ yield* inTranscript(spec, (sql) =>
1884
+ appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "processor-tripped", {
1885
+ step,
1886
+ at: "tool-result",
1887
+ toolCallId: call.toolCallId,
1888
+ processor: tripped.processor,
1889
+ reason: tripped.reason,
1890
+ }),
1891
+ )
1892
+ return { ...outcome, tripped } satisfies ToolOutcome
1893
+ })
1894
+
1895
+ /**
1896
+ * The person decided a held call. A decision that finds the run cancelled is recorded (`consent-decided`, with
1897
+ * `ran: false`) and runs nothing; an approved call runs once, refused inside its transaction if a cancellation
1898
+ * commits before it does.
1899
+ */
1900
+ const afterConsent = (spec: Spec, step: number, call: ToolCall, decision: Decision, consentId: string, key: string) =>
1901
+ Effect.gen(function* () {
1902
+ const tools = yield* AgentTools
1903
+ const approved = decision.kind === "consent" && decision.status === "approved"
1904
+ const cancelled = yield* consentDecided(spec, step, call, consentId, approved)
1905
+ if (cancelled) return { kind: "cancelled" } satisfies ToolOutcome
1906
+ // The tool's definition now: gone when its action was removed while the call waited (a MAKE rollback).
1907
+ const definition = (yield* tools.definitionsFor(spec.orgId)).get(call.toolName)
1908
+ const label = definition === undefined ? undefined : labelOf(definition)
1909
+ if (!approved) {
1910
+ // The decision never needs the definition: its label is omitted when it is gone (a client keeps the one the
1911
+ // held call showed).
1912
+ return yield* persistResult(
1913
+ spec,
1914
+ step,
1915
+ call,
1916
+ refused("ConsentRejected", "The person declined this call; it did not run."),
1917
+ undefined,
1918
+ label,
1919
+ )
1920
+ }
1921
+ if (definition === undefined) {
1922
+ return yield* persistResult(
1923
+ spec,
1924
+ step,
1925
+ call,
1926
+ refused(
1927
+ "ToolUnavailable",
1928
+ `The tool ${call.toolName} is no longer available (its action was removed while the call waited); it did not run.`,
1929
+ { tool: call.toolName },
1930
+ ),
1931
+ )
1932
+ }
1933
+ const executed = yield* executeTool(spec, definition, call, key, { step })
1934
+ if (executed.cancelled) return { kind: "cancelled" } satisfies ToolOutcome
1935
+ return yield* persistResult(spec, step, call, executed.result, undefined, labelOf(definition))
1936
+ })
1937
+
1938
+ // --- a run on a paired device ------------------------------------------------------------------------------------------
1939
+
1940
+ /**
1941
+ * A run whose spec names a device executes there (the Daemon contract's integration with the agent runtime): the
1942
+ * device's local harness runs the whole turn on the person's own subscription, so the run asks for it with
1943
+ * `devices.sendTurn` (as the person's agent, so their consent applies), records itself as the turn's parent run,
1944
+ * waits durably for `devices.turnSettled` (the kernel's `devices.settled` reaction signals it), then takes the
1945
+ * turn's answer as its reply, its events as run events and its usage as the run's (recorded with Metering as
1946
+ * subscription usage, which no deployment budget counts).
1947
+ */
1948
+ const SEND_TURN = "devices.sendTurn"
1949
+ const CANCEL_TURN = "devices.cancelTurn"
1950
+ const DEVICE_CALL_ID = "device"
1951
+
1952
+ const DeviceSent = Schema.Union([
1953
+ Schema.Struct({ kind: Schema.Literal("sent"), turnId: Schema.String }),
1954
+ Schema.Struct({
1955
+ kind: Schema.Literal("consent"),
1956
+ consentId: Schema.String,
1957
+ signal: Schema.String,
1958
+ decided: Schema.NullOr(Decision),
1959
+ }),
1960
+ Schema.Struct({ kind: Schema.Literal("refused"), message: Schema.String }),
1961
+ Schema.Struct({ kind: Schema.Literal("cancelled") }),
1962
+ ])
1963
+ type DeviceSent = typeof DeviceSent.Type
1964
+
1965
+ const DeviceWait = Schema.Union([
1966
+ Schema.Struct({ kind: Schema.Literal("waiting"), signal: Schema.String }),
1967
+ Schema.Struct({ kind: Schema.Literal("settled") }),
1968
+ Schema.Struct({ kind: Schema.Literal("cancelled") }),
1969
+ ])
1970
+
1971
+ /** The device's turn request: the person's latest message, and the device's options (journalled once). */
1972
+ const deviceCall = (spec: Spec, device: RunDevice) =>
1973
+ Effect.gen(function* () {
1974
+ const sql = yield* SqlClient.SqlClient
1975
+ // The person's message, read under the run's authority (a refusal fails the step).
1976
+ const [message] = yield* (yield* Authority)
1977
+ .within(runAuthority(spec), (asserted) =>
1978
+ inAgentFor(
1979
+ asserted,
1980
+ sql,
1981
+ sql<{ text: string }>`SELECT text FROM eloxiv_agent.message
1982
+ WHERE conversation_id = ${spec.conversationId} AND run_id = ${spec.runId} AND role = 'user'
1983
+ ORDER BY seq DESC LIMIT 1`,
1984
+ ),
1985
+ )
1986
+ .pipe(Effect.catchTag("SqlError", (e) => Effect.die(e)))
1987
+ return {
1988
+ toolCallId: DEVICE_CALL_ID,
1989
+ toolName: SEND_TURN,
1990
+ input: { ...device, prompt: message?.text ?? "" },
1991
+ } satisfies ToolCall
1992
+ })
1993
+
1994
+ /** What a sendTurn result says: the turn it created (from its output, or a replay receipt's created record). */
1995
+ const sentTurn = (result: AgentToolResult): DeviceSent => {
1996
+ if (!result.ok) {
1997
+ const message = result.error["message"]
1998
+ return { kind: "refused", message: `${result.error._tag}: ${typeof message === "string" ? message : ""}` }
1999
+ }
2000
+ const envelope = result.output as
2001
+ | { readonly kind: "output"; readonly output: { readonly turnId: string } }
2002
+ | { readonly kind: "replay"; readonly receipt: { readonly created: ReadonlyArray<string> } }
2003
+ const turnId = envelope.kind === "output" ? envelope.output.turnId : envelope.receipt.created[0]
2004
+ return turnId === undefined
2005
+ ? { kind: "refused", message: "The device turn was not created" }
2006
+ : { kind: "sent", turnId }
2007
+ }
2008
+
2009
+ /** Ask the device for the turn, as the person's agent; a call held for consent suspends the run (as a tool's). */
2010
+ const sendToDevice = (spec: Spec, call: ToolCall, key: string) =>
2011
+ Effect.gen(function* () {
2012
+ if (yield* isCancelled(spec)) return { kind: "cancelled" } satisfies DeviceSent
2013
+ const run = { id: spec.runId, orgId: spec.orgId, userId: spec.userId }
2014
+ // The device's request (its prompt) joins the person's run events only while the run's authority holds.
2015
+ const title = actionTitle(yield* Registry, SEND_TURN)
2016
+ yield* inTranscript(spec, (sql) =>
2017
+ appendEvent(sql, run, "tool-call", {
2018
+ step: 0,
2019
+ toolCallId: call.toolCallId,
2020
+ toolName: call.toolName,
2021
+ action: SEND_TURN,
2022
+ title,
2023
+ input: call.input,
2024
+ }),
2025
+ )
2026
+ const { result, cancelled } = yield* executeTool(spec, { action: SEND_TURN }, call, key)
2027
+ if (cancelled) return { kind: "cancelled" } satisfies DeviceSent
2028
+ if (!result.ok && result.error._tag === "ConsentRequired") {
2029
+ const consentId = String(result.error["consentId"])
2030
+ const held = yield* holdForConsent(spec, 0, call, SEND_TURN, title, consentId)
2031
+ return held.kind === "cancel"
2032
+ ? ({ kind: "consent", consentId, signal: held.signal, decided: { kind: "cancel" } } satisfies DeviceSent)
2033
+ : ({ kind: "consent", consentId, signal: held.signal, decided: held.decided } satisfies DeviceSent)
2034
+ }
2035
+ return sentTurn(result)
2036
+ })
2037
+
2038
+ /**
2039
+ * The device turn the run asked for, in the person's run events: the result of its `devices.sendTurn` call (its
2040
+ * `tool-call` event went before), naming the turn, so a client follows a run on a device to the turn it is.
2041
+ */
2042
+ const announceTurn = (spec: Spec, call: ToolCall, turnId: string) =>
2043
+ Effect.flatMap(Registry, (registry) =>
2044
+ inTranscript(spec, (sql) =>
2045
+ appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "tool-result", {
2046
+ step: 0,
2047
+ toolCallId: call.toolCallId,
2048
+ toolName: call.toolName,
2049
+ action: SEND_TURN,
2050
+ title: actionTitle(registry, SEND_TURN),
2051
+ ok: true,
2052
+ error: null,
2053
+ result: { ok: true, output: { turnId } },
2054
+ }),
2055
+ ),
2056
+ ).pipe(Effect.as(null))
2057
+
2058
+ /** The person decided the held request: an approved one is sent once (refused if the run was cancelled meanwhile). */
2059
+ const sendAfterConsent = (spec: Spec, call: ToolCall, decision: Decision, consentId: string, key: string) =>
2060
+ Effect.gen(function* () {
2061
+ const approved = decision.kind === "consent" && decision.status === "approved"
2062
+ if (yield* consentDecided(spec, 0, call, consentId, approved)) return { kind: "cancelled" } satisfies DeviceSent
2063
+ if (!approved) return { kind: "refused", message: "The person declined the device turn; it was not sent." } as const
2064
+ const executed = yield* executeTool(spec, { action: SEND_TURN }, call, key)
2065
+ if (executed.cancelled) return { kind: "cancelled" } satisfies DeviceSent
2066
+ return sentTurn(executed.result)
2067
+ })
2068
+
2069
+ /**
2070
+ * Record the run as the turn's parent and its wait, in one transaction holding the turn's row: a settlement that
2071
+ * committed first is seen here (no wait), one that commits after finds the parent and the wait, and signals it.
2072
+ */
2073
+ const awaitTurn = (spec: Spec, turnId: string) =>
2074
+ Effect.gen(function* () {
2075
+ const sql = yield* SqlClient.SqlClient
2076
+ const signal = `device/${turnId}`
2077
+ return yield* sql.withTransaction(
2078
+ Effect.gen(function* () {
2079
+ const [turn] = yield* asSystem(
2080
+ sql,
2081
+ "devices",
2082
+ spec.orgId,
2083
+ sql<{ status: string }>`UPDATE eloxiv_devices.turn SET parent_run_id = ${spec.runId}
2084
+ WHERE id = ${turnId} AND requested_by = ${spec.userId} RETURNING status`,
2085
+ )
2086
+ if (turn === undefined) return yield* Effect.die(new Error(`No device turn ${turnId} for run ${spec.runId}`))
2087
+ if (turn.status !== "queued" && turn.status !== "running") return { kind: "settled" } as const
2088
+ const waiting = yield* asAgent(
2089
+ sql,
2090
+ spec.orgId,
2091
+ sql<{ id: string }>`UPDATE eloxiv_agent.run SET status = 'waiting',
2092
+ wait = ${JSON.stringify({ signal, turnId })}::jsonb
2093
+ WHERE id = ${spec.runId} AND cancel_requested_at IS NULL RETURNING id`,
2094
+ )
2095
+ return waiting.length === 0 ? ({ kind: "cancelled" } as const) : ({ kind: "waiting", signal } as const)
2096
+ }),
2097
+ )
2098
+ })
2099
+
2100
+ /**
2101
+ * Cancel the run's device turn (as the person's agent), when the run is cancelled while the device works. The
2102
+ * run is cancelled by then, so this call is not refused for it (`unguarded`: the cancellation guard of the run's
2103
+ * tool calls refused it, and the turn ran on). A refusal of the cancellation itself is logged as an error.
2104
+ */
2105
+ const cancelDeviceTurn = (spec: Spec, turnId: string, key: string) =>
2106
+ Effect.gen(function* () {
2107
+ const { result } = yield* executeTool(
2108
+ spec,
2109
+ { action: CANCEL_TURN },
2110
+ { toolCallId: `${DEVICE_CALL_ID}-cancel`, toolName: CANCEL_TURN, input: { id: turnId } },
2111
+ key,
2112
+ { unguarded: true },
2113
+ )
2114
+ if (!result.ok) {
2115
+ yield* Effect.logError(`Run ${spec.runId}: its device turn ${turnId} was not cancelled`, result.error)
2116
+ }
2117
+ return null
2118
+ })
2119
+
2120
+ /** A turn event as the run's: text as a model step's text, tool calls and results as the run's. */
2121
+ const runEventOf = (event: { readonly type: string; readonly data: unknown }) => {
2122
+ const data = (event.data ?? {}) as Record<string, unknown>
2123
+ switch (event.type) {
2124
+ case "text":
2125
+ return {
2126
+ type: "model-step",
2127
+ data: { step: 0, text: typeof data["text"] === "string" ? data["text"] : "", toolCalls: [], device: true },
2128
+ }
2129
+ case "tool-call":
2130
+ return { type: "tool-call", data: { step: 0, ...data, device: true } }
2131
+ case "tool-result":
2132
+ return { type: "tool-result", data: { step: 0, ...data, device: true } }
2133
+ default:
2134
+ return undefined
2135
+ }
2136
+ }
2137
+
2138
+ /**
2139
+ * Take the settled turn as the run's outcome, once (the reply's message id is the turn's): its result as the
2140
+ * assistant's reply, its events as run events, its usage as the run's and as subscription usage with Metering.
2141
+ */
2142
+ const takeTurn = (spec: Spec, turnId: string) =>
2143
+ Effect.gen(function* () {
2144
+ const sql = yield* SqlClient.SqlClient
2145
+ const { turn, events } = yield* sql.withTransaction(
2146
+ asSystem(
2147
+ sql,
2148
+ "devices",
2149
+ spec.orgId,
2150
+ Effect.gen(function* () {
2151
+ const [turn] = yield* sql<{
2152
+ status: string
2153
+ result: string | null
2154
+ error: string | null
2155
+ harness: string
2156
+ model: string | null
2157
+ usage: TurnUsage | null
2158
+ }>`SELECT status, result, error, harness, model, usage FROM eloxiv_devices.turn WHERE id = ${turnId}`
2159
+ const events = yield* sql<{ type: string; data: unknown }>`SELECT type, data FROM eloxiv_devices.turn_event
2160
+ WHERE turn_id = ${turnId} AND attempt = (SELECT attempt FROM eloxiv_devices.turn WHERE id = ${turnId})
2161
+ ORDER BY seq`
2162
+ return { turn, events }
2163
+ }),
2164
+ ),
2165
+ )
2166
+ if (turn === undefined) return yield* Effect.die(new Error(`No device turn ${turnId}`))
2167
+ const usage = turn.usage ?? { inputTokens: 0, outputTokens: 0, cachedInputTokens: null, costUsd: null }
2168
+ const run = { id: spec.runId, orgId: spec.orgId, userId: spec.userId }
2169
+ const text = turn.result ?? ""
2170
+ // The device's reply joins the person's transcript only while the run's authority holds, and only if the run's
2171
+ // cancellation had not committed: then it is metered and recorded as discarded (once), and the run ends cancelled.
2172
+ const discarded = yield* inTranscript(spec, (sql) =>
2173
+ Effect.gen(function* () {
2174
+ const cancelled = yield* cancelledForUpdate(sql, spec)
2175
+ const meter = Effect.gen(function* () {
2176
+ yield* sql`UPDATE eloxiv_agent.run SET status = 'running', wait = NULL, steps = steps + 1,
2177
+ input_tokens = input_tokens + ${usage.inputTokens}, output_tokens = output_tokens + ${usage.outputTokens}
2178
+ WHERE id = ${spec.runId}`
2179
+ yield* recordSubscriptionUsage(sql, {
2180
+ orgId: spec.orgId,
2181
+ userId: spec.userId,
2182
+ runId: spec.runId,
2183
+ provider: `device:${turn.harness}`,
2184
+ model: turn.model ?? turn.harness,
2185
+ inputTokens: usage.inputTokens,
2186
+ outputTokens: usage.outputTokens,
2187
+ costMicros: Math.round((usage.costUsd ?? 0) * 1_000_000),
2188
+ callId: `device:${turnId}`,
2189
+ })
2190
+ })
2191
+ const [applied] = yield* sql<{ id: string }>`SELECT id FROM eloxiv_agent.message
2192
+ WHERE id = ${`${spec.runId}:device:${turnId}`}`
2193
+ if (applied !== undefined) return false
2194
+ if (cancelled) {
2195
+ const [recorded] = yield* sql<{ id: string }>`SELECT id FROM eloxiv_agent.run_event
2196
+ WHERE run_id = ${spec.runId} AND type = 'reply-discarded' AND data->>'turnId' = ${turnId}`
2197
+ if (recorded === undefined) {
2198
+ yield* appendEvent(sql, run, "reply-discarded", {
2199
+ step: 0,
2200
+ turnId,
2201
+ reason: "cancelled",
2202
+ usage: { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens },
2203
+ device: true,
2204
+ text,
2205
+ })
2206
+ yield* meter
2207
+ }
2208
+ return true
2209
+ }
2210
+ const seq = yield* clockSeq(sql)
2211
+ const content = { text, toolCalls: [], usage, device: { turnId, harness: turn.harness, model: turn.model } }
2212
+ const inserted = yield* sql<{ id: string }>`INSERT INTO eloxiv_agent.message
2213
+ (id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
2214
+ VALUES (${`${spec.runId}:device:${turnId}`}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId},
2215
+ ${spec.runId}, ${seq}, 'assistant', ${JSON.stringify(content)}::jsonb, ${text})
2216
+ ON CONFLICT (id) DO NOTHING RETURNING id`
2217
+ if (inserted.length === 0) return false
2218
+ for (const event of events) {
2219
+ const mapped = runEventOf(event)
2220
+ if (mapped !== undefined) yield* appendEvent(sql, run, mapped.type, mapped.data)
2221
+ }
2222
+ yield* meter
2223
+ return false
2224
+ }),
2225
+ )
2226
+ if (discarded) return { status: "cancelled", stopReason: "cancelled", result: null, error: CANCELLED_ERROR }
2227
+ const succeeded = turn.status === "succeeded"
2228
+ return {
2229
+ status: succeeded ? "succeeded" : turn.status === "cancelled" ? "cancelled" : "failed",
2230
+ stopReason: succeeded ? "completed" : turn.status === "cancelled" ? "cancelled" : "error",
2231
+ result: turn.result,
2232
+ error: succeeded ? null : (turn.error ?? `The device turn ${turn.status}`),
2233
+ }
2234
+ })
2235
+
2236
+ const PLAN_ON_DEVICE = "Plan mode is not available for a run on a device: its harness runs its own tools"
2237
+
2238
+ /**
2239
+ * A device's answer through the app's processors: its text through `onChunk` (as one piece) and `onFinal`. A trip is
2240
+ * recorded (`processor-tripped`) and returned as the run's error; null when none tripped.
2241
+ */
2242
+ const deviceCheck = (spec: Spec, text: string) =>
2243
+ Effect.gen(function* () {
2244
+ const { processors } = yield* AgentSettings
2245
+ const guard = chunkGuard(processors, processorRun(spec), 0)
2246
+ guard.push(text)
2247
+ const tripped =
2248
+ guard.tripped() ??
2249
+ (yield* finalGuard(processors, { run: processorRun(spec), text, receipts: [], challenged: true })).tripped
2250
+ if (tripped === undefined) return null
2251
+ yield* inTranscript(spec, (sql) =>
2252
+ appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "processor-tripped", {
2253
+ step: 0,
2254
+ at: "final",
2255
+ device: true,
2256
+ processor: tripped.processor,
2257
+ reason: tripped.reason,
2258
+ }),
2259
+ )
2260
+ return trippedStop(tripped).message
2261
+ })
2262
+
2263
+ const DeviceOutcome = Schema.Struct({
2264
+ status: Schema.String,
2265
+ stopReason: Schema.String,
2266
+ result: Schema.NullOr(Schema.String),
2267
+ error: Schema.NullOr(Schema.String),
2268
+ })
2269
+
2270
+ // --- delegation --------------------------------------------------------------------------------------------------------
2271
+
2272
+ const DelegateInput = Schema.Struct({
2273
+ task: Schema.String,
2274
+ /** A seat's name (the team tool's `spawn`). */
2275
+ name: Schema.optionalKey(Schema.String),
2276
+ tools: Schema.optionalKey(Schema.Array(Schema.String)),
2277
+ profile: Schema.optionalKey(Schema.String),
2278
+ limits: Schema.optionalKey(
2279
+ Schema.Struct({
2280
+ maxSteps: Schema.optionalKey(Schema.Number),
2281
+ maxTokens: Schema.optionalKey(Schema.Number),
2282
+ maxWallMs: Schema.optionalKey(Schema.Number),
2283
+ }),
2284
+ ),
2285
+ })
2286
+
2287
+ /**
2288
+ * Start a child run: its tools must all be ones the parent may use (never `delegate`), its limits at most what
2289
+ * the parent has left, and it acts as the same person through the same agent session, so it cannot exceed the
2290
+ * parent's permissions. Returns the child's id and the signal its end sends, or a refusal for the model.
2291
+ *
2292
+ * A seat (`seat`: the team tool's `spawn`) is started the same way, but its parent does not wait: the seat's id is
2293
+ * the tool's result at once, and its limits are reserved from the parent's (`consumed`, which the parent's limits
2294
+ * count until it collects the seat's answer and what it really spent). Its parent keeps a model call of its own.
2295
+ */
2296
+ const startChild = (spec: Spec, step: number, call: ToolCall, consumed: Consumed, seat = false) =>
2297
+ Effect.gen(function* () {
2298
+ const sql = yield* SqlClient.SqlClient
2299
+ const outbox = yield* Outbox
2300
+ if (yield* isCancelled(spec)) return { kind: "cancelled" } satisfies ToolOutcome
2301
+ const decoded = Schema.decodeUnknownOption(DelegateInput)(call.input)
2302
+ if (decoded._tag === "None") {
2303
+ return yield* persistResult(
2304
+ spec,
2305
+ step,
2306
+ call,
2307
+ refused("InvalidInput", "delegate needs a task and a list of tools"),
2308
+ )
2309
+ }
2310
+ const request = decoded.value
2311
+ const options = optionsOf(spec)
2312
+ const { maxDelegationDepth, profiles } = yield* AgentSettings
2313
+ const profile = request.profile === undefined ? undefined : profiles.find((p) => p.name === request.profile)
2314
+ if (request.profile !== undefined && profile === undefined) {
2315
+ return yield* persistResult(spec, step, call, refused("InvalidInput", `No agent profile ${request.profile}`))
2316
+ }
2317
+ // (A seat's own team tool, for its messages, is a tool it may give only when it may start seats itself.)
2318
+ const parentTools = new Set(
2319
+ allowedTools(yield* runTools(spec.orgId, options), spec)
2320
+ .map((t) => t.name)
2321
+ .filter((name) => name !== TEAM || spawnsSeats(spec, maxDelegationDepth)),
2322
+ )
2323
+ // A profile's tools, when the call names none, narrowed to the parent's own.
2324
+ const childTools = request.tools ?? (profile?.tools ?? []).filter((t) => parentTools.has(t))
2325
+ if (request.tools === undefined && profile === undefined) {
2326
+ return yield* persistResult(
2327
+ spec,
2328
+ step,
2329
+ call,
2330
+ refused("InvalidInput", "delegate needs a list of tools (or a profile)"),
2331
+ )
2332
+ }
2333
+ // The child is one level deeper; it may delegate (or start seats) only while that is within the deployment's depth.
2334
+ const childMayDelegate = options.depth + 2 <= maxDelegationDepth
2335
+ const outside = childTools.filter(
2336
+ (t) => ((t === "delegate" || t === TEAM) && !childMayDelegate) || t === TOOL_SEARCH || !parentTools.has(t),
2337
+ )
2338
+ if (outside.length > 0) {
2339
+ return yield* persistResult(
2340
+ spec,
2341
+ step,
2342
+ call,
2343
+ refused(
2344
+ "ToolNotAllowed",
2345
+ `A sub-agent may only use tools this run may use${childMayDelegate ? "" : " (not delegate: the delegation depth is reached)"}: ${outside.join(", ")}`,
2346
+ {
2347
+ tool: outside[0],
2348
+ },
2349
+ ),
2350
+ )
2351
+ }
2352
+ const childOptions: RunOptions = {
2353
+ mode: options.mode,
2354
+ // A sub-agent is offered its few tools directly.
2355
+ tools: { discovery: "all" },
2356
+ depth: options.depth + 1,
2357
+ ...(profile === undefined ? {} : { profile: profile.name }),
2358
+ ...(seat ? { seat: (request.name ?? request.task).trim().slice(0, 60) || "seat" } : {}),
2359
+ // Its changes belong to its parent's group: reverting the parent's message undoes them too.
2360
+ ...(spec.editGroup === undefined
2361
+ ? {}
2362
+ : { editGroup: { conversationId: spec.editGroup.conversationId, messageId: spec.editGroup.messageId } }),
2363
+ }
2364
+ const elapsed = Date.now() - spec.startedAt
2365
+ // Carved from what the parent has left (its own calls and earlier sub-agents' all count), so the parent and its
2366
+ // sub-agents together never pass the parent's limits.
2367
+ // (A seat's parent goes on while it runs: it keeps one model call for itself, and a seat left without limits gets
2368
+ // a share of what is left, so the parent can start others beside it.)
2369
+ const remaining: RunLimits = {
2370
+ maxSteps: Math.max(0, spec.limits.maxSteps - consumed.calls - (seat ? 1 : 0)),
2371
+ maxTokens: Math.max(0, spec.limits.maxTokens - consumed.tokens),
2372
+ maxWallMs: Math.max(0, spec.limits.maxWallMs - elapsed),
2373
+ }
2374
+ const limits: RunLimits = {
2375
+ maxSteps: Math.min(
2376
+ request.limits?.maxSteps ?? (seat ? Math.min(8, Math.max(1, Math.floor(remaining.maxSteps / 2))) : 8),
2377
+ remaining.maxSteps,
2378
+ ),
2379
+ maxTokens: Math.min(
2380
+ request.limits?.maxTokens ?? (seat ? Math.floor(remaining.maxTokens / 2) : remaining.maxTokens),
2381
+ remaining.maxTokens,
2382
+ ),
2383
+ maxWallMs: Math.min(request.limits?.maxWallMs ?? remaining.maxWallMs, remaining.maxWallMs),
2384
+ }
2385
+ if (limits.maxSteps < 1 || limits.maxTokens < 1 || limits.maxWallMs < 1) {
2386
+ return yield* persistResult(spec, step, call, refused("LimitReached", "This run has no budget left to delegate"))
2387
+ }
2388
+ // A sub-agent whose token limit cannot hold even one model call's worst case (its output limit alone) would stop
2389
+ // before doing anything: refuse it now, telling the model why, instead of starting a child that cannot act.
2390
+ const { maxOutputTokens } = yield* AgentSettings
2391
+ if (limits.maxTokens <= maxOutputTokens) {
2392
+ return yield* persistResult(
2393
+ spec,
2394
+ step,
2395
+ call,
2396
+ request.limits?.maxTokens !== undefined && request.limits.maxTokens < remaining.maxTokens
2397
+ ? refused(
2398
+ "InvalidInput",
2399
+ `maxTokens ${request.limits.maxTokens} is too small for a sub-agent: each model call needs room for ${maxOutputTokens} output tokens plus its input. Leave maxTokens out, or give more than ${maxOutputTokens}.`,
2400
+ )
2401
+ : refused("LimitReached", "This run has too few tokens left to delegate"),
2402
+ )
2403
+ }
2404
+ // A sub-agent acts under its parent's agent session and authority: none is started once they no longer hold
2405
+ // (asserted again, locked, in the transaction that creates it).
2406
+ const parentHolds = yield* (yield* Authority).check(runAuthority(spec)).pipe(Effect.result)
2407
+ if (parentHolds._tag === "Failure") {
2408
+ return yield* persistResult(
2409
+ spec,
2410
+ step,
2411
+ call,
2412
+ refused(
2413
+ parentHolds.failure._tag,
2414
+ `This run's authority no longer holds, so it cannot delegate: ${parentHolds.failure.message}`,
2415
+ ),
2416
+ )
2417
+ }
2418
+ const childRunId = `${spec.runId}:sub:${step}:${call.toolCallId}`
2419
+ const conversationId = `${childRunId}:conversation`
2420
+ const signal = `child/${childRunId}`
2421
+ // The child's records as the agent module; its start request in the kernel's outbox, in the same transaction.
2422
+ const created = yield* sql.withTransaction(
2423
+ Effect.gen(function* () {
2424
+ // Authority: the parent's chain still holds, its rows held until the child is recorded.
2425
+ const asserted = yield* (yield* Authority).assert(runAuthority(spec))
2426
+ const created = yield* inAgentFor(
2427
+ asserted,
2428
+ sql,
2429
+ Effect.gen(function* () {
2430
+ // Its ancestors' rows and then its own, locked: a cancellation of any of them committed before is seen, and
2431
+ // one after finds the child (and cancels it, with the whole subtree).
2432
+ if (yield* parentCancelled(sql, spec)) return "cancelled" as const
2433
+ const [parent] = yield* sql<{ cancelled: boolean }>`SELECT cancel_requested_at IS NOT NULL AS cancelled
2434
+ FROM eloxiv_agent.run WHERE id = ${spec.runId} FOR UPDATE`
2435
+ if (parent?.cancelled === true) return "cancelled" as const
2436
+ // The child inherits the parent's authority: the scope and chain it was started with (and, through its
2437
+ // conversation, the parent's agent session).
2438
+ const created = yield* sql<{ id: string }>`INSERT INTO eloxiv_agent.run
2439
+ (id, org_id, user_id, conversation_id, parent_run_id, kind, status, task, limits, tools, authority, options)
2440
+ VALUES (${childRunId}, ${spec.orgId}, ${spec.userId}, ${conversationId}, ${spec.runId}, 'subagent', 'queued',
2441
+ ${request.task}, ${JSON.stringify(limits)}::jsonb, ${JSON.stringify(childTools)}::jsonb,
2442
+ ${spec.authority === undefined || spec.authority === "unrecorded" ? null : JSON.stringify(spec.authority)}::jsonb,
2443
+ ${JSON.stringify(childOptions)}::jsonb)
2444
+ ON CONFLICT (id) DO NOTHING RETURNING id`
2445
+ if (created.length === 0) return false
2446
+ // The parent's own agent session (the one its calls are made with), never a renewed one.
2447
+ yield* sql`INSERT INTO eloxiv_agent.conversation (id, org_id, user_id, title, agent_session_id)
2448
+ VALUES (${conversationId}, ${spec.orgId}, ${spec.userId}, ${`Sub-agent: ${request.task.slice(0, 60)}`},
2449
+ ${spec.agentSessionId})`
2450
+ const seq = yield* clockSeq(sql)
2451
+ yield* sql`INSERT INTO eloxiv_agent.message (id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
2452
+ VALUES (${`${childRunId}:task`}, ${spec.orgId}, ${spec.userId}, ${conversationId}, ${childRunId}, ${seq}, 'user',
2453
+ ${JSON.stringify({ text: request.task, attachments: [] })}::jsonb, ${request.task})`
2454
+ yield* appendEvent(sql, { id: childRunId, orgId: spec.orgId, userId: spec.userId }, "run-started", {
2455
+ conversationId,
2456
+ parentRunId: spec.runId,
2457
+ })
2458
+ if (!seat) {
2459
+ yield* sql`UPDATE eloxiv_agent.run SET status = 'waiting',
2460
+ wait = ${JSON.stringify({ signal, childRunId, toolCallId: call.toolCallId })}::jsonb WHERE id = ${spec.runId}`
2461
+ }
2462
+ yield* appendEvent(
2463
+ sql,
2464
+ { id: spec.runId, orgId: spec.orgId, userId: spec.userId },
2465
+ seat ? "seat-spawned" : "delegated",
2466
+ {
2467
+ step,
2468
+ toolCallId: call.toolCallId,
2469
+ childRunId,
2470
+ task: request.task,
2471
+ tools: childTools,
2472
+ limits,
2473
+ ...(profile === undefined ? {} : { profile: profile.name }),
2474
+ ...(childOptions.seat === undefined ? {} : { name: childOptions.seat }),
2475
+ depth: childOptions.depth,
2476
+ },
2477
+ )
2478
+ return true
2479
+ }),
2480
+ )
2481
+ if (created === true) {
2482
+ yield* outbox.publish({
2483
+ invocationId: childRunId,
2484
+ type: "agent.runRequested",
2485
+ module: AGENT_MODULE,
2486
+ orgId: spec.orgId,
2487
+ payload: { runId: childRunId },
2488
+ })
2489
+ }
2490
+ return created
2491
+ }),
2492
+ )
2493
+ if (created === "cancelled") return { kind: "cancelled" } satisfies ToolOutcome
2494
+ if (!seat) return { kind: "started", childRunId, signal } satisfies ToolOutcome
2495
+ // The seat's limits, reserved from the parent's until its answer is collected (a re-run step reserves the same).
2496
+ return yield* persistResult(
2497
+ spec,
2498
+ step,
2499
+ call,
2500
+ { ok: true, output: { seat: childRunId, name: childOptions.seat, status: "running", limits } },
2501
+ { calls: limits.maxSteps, tokens: limits.maxTokens },
2502
+ )
2503
+ })
2504
+
2505
+ // --- teams --------------------------------------------------------------------------------------------------------------
2506
+
2507
+ /**
2508
+ * What a sub-agent that ended is charged with, with everything below it, for its parent's limits (each run's counters
2509
+ * are its own model calls only, so the subtree is summed). A run below it that has not ended, or still has a model
2510
+ * call open (a reply in flight, or one lost to a crash and not yet metered), is charged its whole limits: what it may
2511
+ * still spend stays reserved, so a late or abandoned call can never take the parent past its limits.
2512
+ */
2513
+ const SUBTREE_CHARGE = (sql: SqlClient.SqlClient, runId: string) => sql<Consumed>`WITH RECURSIVE subtree (id) AS (
2514
+ SELECT id FROM eloxiv_agent.run WHERE id = ${runId}
2515
+ UNION ALL
2516
+ SELECT r.id FROM eloxiv_agent.run r JOIN subtree t ON r.parent_run_id = t.id
2517
+ ), charged AS (
2518
+ SELECT r.steps, r.input_tokens + r.output_tokens AS tokens,
2519
+ r.finished_at IS NULL OR EXISTS (SELECT 1 FROM eloxiv_agent.model_call c
2520
+ WHERE c.run_id = r.id AND c.status = 'started') AS open,
2521
+ coalesce((r.limits->>'maxSteps')::int, 0) AS max_steps, coalesce((r.limits->>'maxTokens')::int, 0) AS max_tokens
2522
+ FROM eloxiv_agent.run r JOIN subtree t ON t.id = r.id
2523
+ )
2524
+ SELECT coalesce(sum(CASE WHEN open THEN greatest(steps, max_steps) ELSE steps END), 0)::int AS calls,
2525
+ coalesce(sum(CASE WHEN open THEN greatest(tokens, max_tokens) ELSE tokens END), 0)::int AS tokens
2526
+ FROM charged`
2527
+
2528
+ const TeamInput = Schema.Struct({
2529
+ action: Schema.Literals(["spawn", "wait", "send", "list"]),
2530
+ seats: Schema.optionalKey(Schema.Array(Schema.String)),
2531
+ until: Schema.optionalKey(Schema.Literals(["all", "any"])),
2532
+ to: Schema.optionalKey(Schema.String),
2533
+ text: Schema.optionalKey(Schema.String),
2534
+ })
2535
+
2536
+ /** A team call's step: its result, or (`wait`) the signal it waits for before it looks again. */
2537
+ const TeamOutcome = Schema.Union([
2538
+ ToolOutcome,
2539
+ Schema.Struct({ kind: Schema.Literal("team-wait"), signal: Schema.String }),
2540
+ ])
2541
+ type TeamOutcome = typeof TeamOutcome.Type
2542
+
2543
+ /**
2544
+ * What a run knows of its team, from its journalled team results only (so a replay knows the same): the messages
2545
+ * delivered to it (the last sequence number of each sender's), the seats whose answers it collected, and what each of
2546
+ * its seats reserved of its limits when it was started.
2547
+ */
2548
+ interface TeamLedger {
2549
+ readonly seen: Record<string, number>
2550
+ readonly collected: ReadonlyArray<string>
2551
+ readonly reserved: Record<string, Consumed>
2552
+ }
2553
+
2554
+ interface SeatRow {
2555
+ readonly id: string
2556
+ readonly name: string
2557
+ readonly status: string
2558
+ readonly result: string | null
2559
+ readonly finished: boolean
2560
+ }
2561
+
2562
+ /** A team call's result as the model reads it, and what the ledger learns from it. */
2563
+ interface TeamOutput {
2564
+ readonly finished?: ReadonlyArray<{ readonly seat: string; readonly spent: Consumed }>
2565
+ readonly messages?: ReadonlyArray<{ readonly sender: string; readonly seq: number }>
2566
+ readonly seat?: string
2567
+ readonly limits?: RunLimits
2568
+ }
2569
+
2570
+ /**
2571
+ * A team call's result, stored once (the message id is the step's): a step re-run after its result committed returns
2572
+ * the stored one, so the transcript, the journal and the ledger agree on which messages and answers were delivered.
2573
+ * Seats collected give back what they reserved, less what they spent with everything below them.
2574
+ */
2575
+ const persistTeam = (spec: Spec, step: number, call: ToolCall, raw: AgentToolResult, ledger: TeamLedger) =>
2576
+ Effect.gen(function* () {
2577
+ const messageId = `${spec.runId}:t:${step}:${call.toolCallId}`
2578
+ const result = JSON.parse(JSON.stringify(raw)) as AgentToolResult
2579
+ const stored = yield* inTranscript(spec, (sql) =>
2580
+ Effect.gen(function* () {
2581
+ const seq = yield* clockSeq(sql)
2582
+ const content = { toolCallId: call.toolCallId, toolName: call.toolName, result }
2583
+ const inserted = yield* sql<{ id: string }>`INSERT INTO eloxiv_agent.message
2584
+ (id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
2585
+ VALUES (${messageId}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId}, ${spec.runId}, ${seq}, 'tool',
2586
+ ${JSON.stringify(content)}::jsonb, '')
2587
+ ON CONFLICT (id) DO NOTHING RETURNING id`
2588
+ if (inserted.length === 0) {
2589
+ const [row] = yield* sql<{ result: AgentToolResult }>`SELECT content->'result' AS result
2590
+ FROM eloxiv_agent.message WHERE id = ${messageId}`
2591
+ return row?.result ?? result
2592
+ }
2593
+ yield* sql`UPDATE eloxiv_agent.run SET status = 'running', wait = NULL WHERE id = ${spec.runId}`
2594
+ yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "tool-result", {
2595
+ step,
2596
+ toolCallId: call.toolCallId,
2597
+ toolName: call.toolName,
2598
+ ok: result.ok,
2599
+ error: result.ok ? null : result.error._tag,
2600
+ result,
2601
+ })
2602
+ return result
2603
+ }),
2604
+ )
2605
+ const finished = stored.ok ? ((stored.output as TeamOutput | null)?.finished ?? []) : []
2606
+ if (finished.length === 0) return { kind: "result", result: stored } satisfies ToolOutcome
2607
+ const consumed = { calls: 0, tokens: 0 }
2608
+ for (const seat of finished) {
2609
+ const reserved = ledger.reserved[seat.seat] ?? { calls: 0, tokens: 0 }
2610
+ consumed.calls += seat.spent.calls - reserved.calls
2611
+ consumed.tokens += seat.spent.tokens - reserved.tokens
2612
+ }
2613
+ return { kind: "result", result: stored, consumed } satisfies ToolOutcome
2614
+ })
2615
+
2616
+ /**
2617
+ * The team tool's `wait`, `send` and `list` (`spawn` is `startChild`). In one transaction, under the run's authority,
2618
+ * its ancestors' rows and then its own held (a `wait` holds its own for update): `send` records the message on the
2619
+ * sender's stream, holding the recipient's row, and asks the kernel to wake the recipient; then the run's seats and
2620
+ * the messages addressed to it are read. A `wait` that finds nothing yet records that it waits (`wait.team`), so a
2621
+ * seat that finishes or a message sent after this transaction finds the wait and signals it, and one that committed
2622
+ * before is seen here: no wake-up is lost. Every result carries the messages not yet delivered and the answers of the
2623
+ * seats not yet collected.
2624
+ */
2625
+ const teamCall = (spec: Spec, step: number, call: ToolCall, k: number, ledger: TeamLedger) =>
2626
+ Effect.gen(function* () {
2627
+ const sql = yield* SqlClient.SqlClient
2628
+ const outbox = yield* Outbox
2629
+ const decoded = Schema.decodeUnknownOption(TeamInput)(call.input)
2630
+ if (decoded._tag === "None") {
2631
+ return yield* persistTeam(
2632
+ spec,
2633
+ step,
2634
+ call,
2635
+ refused("InvalidInput", 'team needs an action: "spawn", "wait", "send" or "list"'),
2636
+ ledger,
2637
+ )
2638
+ }
2639
+ const input = decoded.value
2640
+ const seat = optionsOf(spec).seat
2641
+ const lead = seat === undefined ? null : spec.parentRunId
2642
+ const key = `${spec.runId}:team/${step}/${call.toolCallId}`
2643
+ const signal = `team/${step}/${call.toolCallId}/${k}`
2644
+ const me = { id: spec.runId, orgId: spec.orgId, userId: spec.userId }
2645
+ const SEATS = (parent: string) => sql<SeatRow>`SELECT id, options->>'seat' AS name, status, result,
2646
+ finished_at IS NOT NULL AS finished
2647
+ FROM eloxiv_agent.run WHERE parent_run_id = ${parent} AND options ? 'seat' ORDER BY created_at, id`
2648
+ const read = yield* sql.withTransaction(
2649
+ Effect.gen(function* () {
2650
+ const asserted = yield* (yield* Authority).assert(runAuthority(spec))
2651
+ yield* replying(sql, spec)
2652
+ const read = yield* inAgentFor(
2653
+ asserted,
2654
+ sql,
2655
+ Effect.gen(function* () {
2656
+ if (yield* parentCancelled(sql, spec)) return { kind: "cancelled" } as const
2657
+ const [own] =
2658
+ input.action === "wait"
2659
+ ? yield* sql<{ cancelled: boolean }>`SELECT cancel_requested_at IS NOT NULL AS cancelled
2660
+ FROM eloxiv_agent.run WHERE id = ${spec.runId} FOR UPDATE`
2661
+ : yield* sql<{ cancelled: boolean }>`SELECT cancel_requested_at IS NOT NULL AS cancelled
2662
+ FROM eloxiv_agent.run WHERE id = ${spec.runId} FOR SHARE`
2663
+ if (own?.cancelled === true) return { kind: "cancelled" } as const
2664
+ const refusal = (message: string) => ({ kind: "refused", error: refused("InvalidInput", message) }) as const
2665
+ let sent: string | null = null
2666
+ // A send this step committed before (re-run after a crash before its result was stored) was delivered,
2667
+ // whatever its recipient has done since: it succeeds again, and its recipient was woken then.
2668
+ const [sentBefore] =
2669
+ input.action === "send"
2670
+ ? yield* sql<{ recipient: string }>`SELECT data->>'to' AS recipient FROM eloxiv_agent.run_event
2671
+ WHERE run_id = ${spec.runId} AND type = 'team-message' AND data->>'key' = ${key}`
2672
+ : []
2673
+ if (sentBefore !== undefined) sent = sentBefore.recipient
2674
+ else if (input.action === "send") {
2675
+ const to = input.to === "lead" ? lead : (input.to ?? null)
2676
+ const text = (input.text ?? "").trim()
2677
+ if (text === "") return refusal("send needs a text")
2678
+ // A member of the run's team (its lead, its seats, its lead's other seats), its row held until this
2679
+ // commits: the recipient's wait either saw this message or is woken for it.
2680
+ const [target] = yield* sql<{ finished: boolean }>`SELECT finished_at IS NOT NULL AS finished
2681
+ FROM eloxiv_agent.run WHERE id = ${to} AND id <> ${spec.runId} AND (id = ${lead} OR parent_run_id = ${spec.runId}
2682
+ OR (parent_run_id = ${lead} AND options ? 'seat')) FOR SHARE`
2683
+ if (target === undefined) return refusal(`${String(input.to)} is not in your team (list shows who is)`)
2684
+ if (target.finished) return refusal(`${to} has finished; it reads no more messages`)
2685
+ yield* appendEvent(sql, me, "team-message", { key, to, text: text.slice(0, 8_000), name: seat ?? "lead" })
2686
+ sent = to
2687
+ }
2688
+ // The messages addressed to the run by its team (a sender's own messages are to others).
2689
+ const addressed = yield* sql<{ runId: string; seq: number; data: { text: string; name?: string } }>`
2690
+ SELECT run_id AS "runId", seq, data FROM eloxiv_agent.run_event
2691
+ WHERE type = 'team-message' AND data->>'to' = ${spec.runId} AND run_id IN (SELECT id FROM eloxiv_agent.run
2692
+ WHERE id = ${lead} OR parent_run_id = ${spec.runId} OR (parent_run_id = ${lead} AND options ? 'seat'))
2693
+ ORDER BY at, run_id, seq`
2694
+ const seats = yield* SEATS(spec.runId)
2695
+ const others = lead === null ? [] : (yield* SEATS(lead)).filter((s) => s.id !== spec.runId)
2696
+ const messages = addressed
2697
+ .filter((m) => m.seq > (ledger.seen[m.runId] ?? -1))
2698
+ .map((m) => ({
2699
+ from: m.runId === lead ? "lead" : m.runId,
2700
+ name: m.data.name ?? "lead",
2701
+ text: m.data.text,
2702
+ seq: m.seq,
2703
+ sender: m.runId,
2704
+ }))
2705
+ const fresh = seats.filter((s) => s.finished && !ledger.collected.includes(s.id))
2706
+ if (input.action === "wait") {
2707
+ const unknown = (input.seats ?? []).filter((id) => !seats.some((s) => s.id === id))
2708
+ if (unknown.length > 0) return refusal(`Not your seats: ${unknown.join(", ")}`)
2709
+ const watched = input.seats === undefined ? seats : seats.filter((s) => input.seats!.includes(s.id))
2710
+ const ready =
2711
+ messages.length > 0 ||
2712
+ (watched.length === 0
2713
+ ? seat === undefined
2714
+ : input.until === "any"
2715
+ ? watched.some((s) => s.finished && !ledger.collected.includes(s.id)) ||
2716
+ watched.every((s) => s.finished)
2717
+ : watched.every((s) => s.finished))
2718
+ if (!ready) {
2719
+ yield* sql`UPDATE eloxiv_agent.run SET status = 'waiting',
2720
+ wait = ${JSON.stringify({ signal, team: true, toolCallId: call.toolCallId })}::jsonb
2721
+ WHERE id = ${spec.runId}`
2722
+ return { kind: "waiting" } as const
2723
+ }
2724
+ }
2725
+ // What each seat collected is charged, with everything below it (SUBTREE_CHARGE).
2726
+ const finished: Array<{
2727
+ seat: string
2728
+ name: string
2729
+ status: string
2730
+ result: string | null
2731
+ spent: Consumed
2732
+ }> = []
2733
+ for (const s of fresh) {
2734
+ const [spent] = yield* SUBTREE_CHARGE(sql, s.id)
2735
+ finished.push({
2736
+ seat: s.id,
2737
+ name: s.name,
2738
+ status: s.status,
2739
+ result: s.result,
2740
+ spent: { calls: spent?.calls ?? 0, tokens: spent?.tokens ?? 0 },
2741
+ })
2742
+ }
2743
+ return { kind: "ready", seats, others, messages, finished, sent, wakes: sentBefore === undefined } as const
2744
+ }),
2745
+ )
2746
+ if (read.kind === "ready" && read.sent !== null && read.wakes) {
2747
+ yield* outbox.publish({
2748
+ invocationId: key,
2749
+ type: "agent.teamWake",
2750
+ module: AGENT_MODULE,
2751
+ orgId: spec.orgId,
2752
+ payload: { runId: read.sent },
2753
+ })
2754
+ }
2755
+ return read
2756
+ }),
2757
+ )
2758
+ if (read.kind === "cancelled") return { kind: "cancelled" } satisfies TeamOutcome
2759
+ if (read.kind === "waiting") return { kind: "team-wait", signal } satisfies TeamOutcome
2760
+ if (read.kind === "refused") return yield* persistTeam(spec, step, call, read.error, ledger)
2761
+ const view = (s: SeatRow) => ({ seat: s.id, name: s.name, status: s.status })
2762
+ const delivered = { finished: read.finished, messages: read.messages }
2763
+ const output =
2764
+ input.action === "list"
2765
+ ? { lead, seats: read.seats.map(view), team: read.others.map(view), ...delivered }
2766
+ : input.action === "send"
2767
+ ? { sent: read.sent, ...delivered }
2768
+ : { ...delivered, running: read.seats.filter((s) => !s.finished).map(view) }
2769
+ return yield* persistTeam(spec, step, call, { ok: true, output }, ledger)
2770
+ })
2771
+
2772
+ // --- interrupted turns ------------------------------------------------------------------------------------------------
2773
+
2774
+ const Reconciled = Schema.Struct({
2775
+ note: Schema.NullOr(Schema.String),
2776
+ /** The receipts of the logical turn's writes so far (recorded or reconciled), the continuation's evidence. */
2777
+ receipts: Schema.optionalKey(Schema.Array(Schema.Struct({ tool: Schema.String, receipt: WriteReceipt }))),
2778
+ })
2779
+
2780
+ const NOT_RUN = (message: string): AgentToolResult => ({ ok: false, error: { _tag: "NotRun", message } })
2781
+
2782
+ /**
2783
+ * Before a continuation's first model call (its journalled `reconcile` step): every tool call the run it continues
2784
+ * asked for but never recorded a result of is given its outcome, from the receipt store (C-033), and recorded in the
2785
+ * conversation as that call's result: `completed` (it committed before the interruption: its replay receipt), `unknown`
2786
+ * (it committed, and scheduled external effects the provider has not confirmed) or `not-run` (no receipt: it never
2787
+ * committed, and the run that could have made it has ended). A sub-agent the call started answers with its outcome.
2788
+ * The answers that arrived after that run was cancelled (`reply-discarded`: never applied, none of their tool calls
2789
+ * made) are collected as late answers. The continuation is told all of it (the returned note), and the stream records
2790
+ * it (`reconciled`). A step run again finds the results recorded (their ids are the calls').
2791
+ */
2792
+ const reconcile = (spec: Spec, continuation: RunContinuation) =>
2793
+ Effect.gen(function* () {
2794
+ const sql = yield* SqlClient.SqlClient
2795
+ const tools = yield* AgentTools
2796
+ const invocation = yield* Invocation
2797
+ const registry = yield* Registry
2798
+ const authority = yield* Authority
2799
+ const previous = continuation.previous
2800
+ // The interrupted run's execution: its tool steps' idempotency keys start with its id.
2801
+ const [execution] = yield* sql<{ id: string }>`SELECT id FROM eloxiv.workflow_execution
2802
+ WHERE workflow = ${AGENT_RUN_WORKFLOW} AND key = ${previous}`
2803
+ const read = yield* inTranscript(spec, (sql) =>
2804
+ Effect.gen(function* () {
2805
+ const assistant = yield* sql<{ id: string; content: { toolCalls?: ReadonlyArray<ToolCall> } }>`
2806
+ SELECT id, content FROM eloxiv_agent.message WHERE run_id = ${previous} AND role = 'assistant' ORDER BY seq`
2807
+ const results = yield* sql<{ id: string }>`SELECT id FROM eloxiv_agent.message
2808
+ WHERE run_id = ${previous} AND role = 'tool'`
2809
+ const late = yield* sql<{ data: { text?: unknown } }>`SELECT data FROM eloxiv_agent.run_event
2810
+ WHERE run_id = ${previous} AND type = 'reply-discarded' ORDER BY seq`
2811
+ const children = yield* sql<{ id: string; status: string; result: string | null; finished: boolean }>`
2812
+ SELECT id, status, result, finished_at IS NOT NULL AS finished FROM eloxiv_agent.run
2813
+ WHERE parent_run_id = ${previous}`
2814
+ return { assistant, results, late, children }
2815
+ }),
2816
+ )
2817
+ const recorded = new Set(read.results.map((m) => m.id))
2818
+ const missing = read.assistant.flatMap((message) => {
2819
+ const step = /:m:(\d+)$/u.exec(message.id)?.[1]
2820
+ return step === undefined
2821
+ ? []
2822
+ : (message.content.toolCalls ?? [])
2823
+ .filter((call) => !recorded.has(`${previous}:t:${step}:${call.toolCallId}`))
2824
+ .map((call) => ({ step: Number(step), call }))
2825
+ })
2826
+ const definitions = yield* tools.definitionsFor(spec.orgId)
2827
+ const outcomes: Array<{ toolCallId: string; tool: string; outcome: "completed" | "unknown" | "not-run" }> = []
2828
+ for (const { step, call } of missing) {
2829
+ let result = NOT_RUN("The interrupted run did not make this call")
2830
+ let outcome: "completed" | "unknown" | "not-run" = "not-run"
2831
+ const definition = definitions.get(call.toolName)
2832
+ if (call.toolName === "delegate") {
2833
+ const child = read.children.find((c) => c.id === `${previous}:sub:${step}:${call.toolCallId}`)
2834
+ if (child?.finished === true) {
2835
+ result = { ok: true, output: { runId: child.id, status: child.status, result: child.result } }
2836
+ outcome = "completed"
2837
+ }
2838
+ } else if (definition !== undefined && execution !== undefined) {
2839
+ const key = `${execution.id}:tool/${previous}/${step}/${call.toolCallId}`
2840
+ let receipt = null
2841
+ for (const candidate of [key, `${key}/decided`]) {
2842
+ receipt ??= yield* authority.within(runAuthority(spec), (asserted) =>
2843
+ invocation.receiptFor(asserted, definition.action, candidate),
2844
+ )
2845
+ }
2846
+ if (receipt !== null) {
2847
+ const contract = registry.actions.get(definition.action)?.contract
2848
+ const envelope = { kind: "replay", receipt }
2849
+ const written = contract === undefined ? undefined : writeReceipt(contract, envelope)
2850
+ result = { ok: true, output: envelope, ...(written === undefined ? {} : { receipt: written }) }
2851
+ outcome = (receipt.effects?.length ?? 0) > 0 ? "unknown" : "completed"
2852
+ }
2853
+ }
2854
+ const reconciled = outcome
2855
+ yield* inTranscript(spec, (sql) =>
2856
+ Effect.gen(function* () {
2857
+ const seq = yield* clockSeq(sql)
2858
+ const content = { toolCallId: call.toolCallId, toolName: call.toolName, result, reconciled }
2859
+ yield* sql`INSERT INTO eloxiv_agent.message (id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
2860
+ VALUES (${`${previous}:t:${step}:${call.toolCallId}`}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId},
2861
+ ${previous}, ${seq}, 'tool', ${JSON.stringify(content)}::jsonb, '')
2862
+ ON CONFLICT (id) DO NOTHING`
2863
+ }),
2864
+ )
2865
+ outcomes.push({ toolCallId: call.toolCallId, tool: call.toolName, outcome })
2866
+ }
2867
+ const late = read.late.flatMap((event) =>
2868
+ typeof event.data.text === "string" && event.data.text !== "" ? [event.data.text.slice(0, 2_000)] : [],
2869
+ )
2870
+ yield* inTranscript(spec, (sql) =>
2871
+ appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "reconciled", {
2872
+ previous,
2873
+ calls: outcomes,
2874
+ late: late.length,
2875
+ }),
2876
+ )
2877
+ // The turn's writes so far, by every run of it before this one (their recorded and reconciled results): the
2878
+ // continuation's final answer is checked against them as against its own.
2879
+ const written = yield* inTranscript(
2880
+ spec,
2881
+ (sql) =>
2882
+ sql<{
2883
+ tool: string
2884
+ receipt: unknown
2885
+ }>`SELECT m.content->>'toolName' AS tool, m.content->'result'->'receipt' AS receipt
2886
+ FROM eloxiv_agent.message m JOIN eloxiv_agent.run r ON r.id = m.run_id
2887
+ WHERE m.conversation_id = ${spec.conversationId} AND m.role = 'tool' AND r.id <> ${spec.runId}
2888
+ AND (m.content->'result'->>'ok')::boolean AND m.content->'result'->'receipt' IS NOT NULL
2889
+ AND (r.id = ${continuation.of} OR r.options->'continuation'->>'of' = ${continuation.of})
2890
+ ORDER BY m.seq`,
2891
+ )
2892
+ const receipts = written.map((row) => ({
2893
+ tool: row.tool,
2894
+ receipt: Schema.decodeUnknownSync(WriteReceipt)(row.receipt),
2895
+ }))
2896
+ const lines = [
2897
+ `You are continuing the person's last request: the run working on it was interrupted (continuation ${continuation.attempt}${continuation.automatic ? ", started automatically after the model failed" : ", asked for by the person"}). Every tool call it asked for is accounted for in the conversation: a result of kind "replay" ran before the interruption, NotRun did not run, and a call marked unknown ran but its external effects are not confirmed yet. Never repeat a call that already ran; go on from where it stopped.`,
2898
+ ...(late.length === 0
2899
+ ? []
2900
+ : [
2901
+ `These answers arrived after the interruption and were not acted on (nothing they asked for was done):\n${late.map((text) => `- ${text}`).join("\n")}`,
2902
+ ]),
2903
+ ]
2904
+ return { note: lines.join("\n\n"), receipts }
2905
+ })
2906
+
2907
+ /**
2908
+ * A person's (or a job's) run that failed transiently continues its logical turn, at most `max` times: a new run (in
2909
+ * the transaction that recorded the failure), with the same authority, limits and options, marked as the turn's next
2910
+ * continuation. Null when the turn has had its continuations, or the run executed on a device.
2911
+ */
2912
+ const continueAutomatically = (
2913
+ sql: SqlClient.SqlClient,
2914
+ runId: string,
2915
+ max: number,
2916
+ /** The interrupted run's effective authority: its record, its chain extended by its agent session. */
2917
+ effective: AuthorityRecord,
2918
+ ) =>
2919
+ Effect.gen(function* () {
2920
+ const [run] = yield* sql<{
2921
+ orgId: string
2922
+ userId: string
2923
+ conversationId: string
2924
+ kind: string
2925
+ device: unknown
2926
+ limits: unknown
2927
+ authority: unknown
2928
+ options: (RunOptions & { readonly continuation?: RunContinuation }) | null
2929
+ }>`SELECT org_id AS "orgId", user_id AS "userId", conversation_id AS "conversationId", kind, device, limits,
2930
+ authority, options FROM eloxiv_agent.run WHERE id = ${runId}`
2931
+ if (run === undefined || run.device !== null || run.options === null) return null
2932
+ const attempt = (run.options.continuation?.attempt ?? 0) + 1
2933
+ if (attempt > max) return null
2934
+ const id = crypto.randomUUID()
2935
+ const options = {
2936
+ ...run.options,
2937
+ continuation: { of: run.options.continuation?.of ?? runId, previous: runId, attempt, automatic: true },
2938
+ }
2939
+ const json = (value: unknown) => (value === null || value === undefined ? null : JSON.stringify(value))
2940
+ yield* sql`INSERT INTO eloxiv_agent.run (id, org_id, user_id, conversation_id, kind, status, authority, limits, options)
2941
+ VALUES (${id}, ${run.orgId}, ${run.userId}, ${run.conversationId}, ${run.kind}, 'queued',
2942
+ ${JSON.stringify(effective)}::jsonb, ${json(run.limits)}::jsonb, ${JSON.stringify(options)}::jsonb)`
2943
+ yield* appendEvent(sql, { id, orgId: run.orgId, userId: run.userId }, "run-started", {
2944
+ conversationId: run.conversationId,
2945
+ continues: runId,
2946
+ automatic: true,
2947
+ })
2948
+ return id
2949
+ })
2950
+
2951
+ // --- the final-answer check ---------------------------------------------------------------------------------------
2952
+
2953
+ const CheckOutcome = Schema.Union([
2954
+ Schema.Struct({ kind: Schema.Literal("retry"), challengedBy: Schema.Array(Schema.String) }),
2955
+ Schema.Struct({ kind: Schema.Literal("abort"), message: Schema.String }),
2956
+ Schema.Struct({
2957
+ kind: Schema.Literal("accept"),
2958
+ result: Schema.String,
2959
+ verification: Schema.NullOr(RunVerificationSchema),
2960
+ }),
2961
+ ])
2962
+ type CheckOutcome = typeof CheckOutcome.Type
2963
+
2964
+ /**
2965
+ * The final answer, checked against the receipts of the run's writes and the app's final-answer processors (in its
2966
+ * own journalled step). A receipt saying a write changed nothing or failed a check, or a processor's challenge, gets
2967
+ * the model challenged once (if the run has a model call left): the challenge joins the conversation as the run's
2968
+ * next user turn (`content.check`), and the model answers again. Receipts still unverified after that annotate the
2969
+ * answer (`Write check: ...`). What the check found is persisted on the run (`verification`) and on its stream
2970
+ * (`answer-checked`); a processor's trip ends the run `stopped`.
2971
+ */
2972
+ const finalCheck = (
2973
+ spec: Spec,
2974
+ step: number,
2975
+ text: string,
2976
+ receipts: ReadonlyArray<ToolReceipt>,
2977
+ /** The processors whose challenge the run already answered (it is challenged at most once). */
2978
+ challengers: ReadonlyArray<string> | null,
2979
+ room: boolean,
2980
+ ) =>
2981
+ Effect.gen(function* () {
2982
+ const { processors } = yield* AgentSettings
2983
+ const run = { id: spec.runId, orgId: spec.orgId, userId: spec.userId }
2984
+ const retried = challengers !== null
2985
+ const pending = flagged(receipts)
2986
+ const verdict = yield* finalGuard(processors, { run: processorRun(spec), text, receipts, challenged: retried })
2987
+ if (verdict.tripped !== undefined) {
2988
+ const tripped = verdict.tripped
2989
+ yield* inTranscript(spec, (sql) =>
2990
+ appendEvent(sql, run, "processor-tripped", {
2991
+ step,
2992
+ at: "final",
2993
+ processor: tripped.processor,
2994
+ reason: tripped.reason,
2995
+ }),
2996
+ )
2997
+ return { kind: "abort", message: trippedStop(tripped).message } satisfies CheckOutcome
2998
+ }
2999
+ const challengedBy = verdict.challenges.map((c) => c.processor)
3000
+ if ((needsChallenge(pending) || verdict.challenges.length > 0) && !retried && room) {
3001
+ const message = checkMessage(
3002
+ pending,
3003
+ verdict.challenges.map((c) => c.message),
3004
+ )
3005
+ yield* inTranscript(spec, (sql) =>
3006
+ Effect.gen(function* () {
3007
+ const seq = yield* clockSeq(sql)
3008
+ const inserted = yield* sql<{ id: string }>`INSERT INTO eloxiv_agent.message
3009
+ (id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
3010
+ VALUES (${`${spec.runId}:check:${step}`}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId}, ${spec.runId},
3011
+ ${seq}, 'user', ${JSON.stringify({ text: message, attachments: [], check: { receipts: pending, challengedBy } })}::jsonb,
3012
+ ${message})
3013
+ ON CONFLICT (id) DO NOTHING RETURNING id`
3014
+ if (inserted.length > 0) {
3015
+ yield* appendEvent(sql, run, "answer-checked", {
3016
+ step,
3017
+ outcome: "retried",
3018
+ receipts: pending,
3019
+ challengedBy,
3020
+ })
3021
+ }
3022
+ }),
3023
+ )
3024
+ return { kind: "retry", challengedBy } satisfies CheckOutcome
3025
+ }
3026
+ const outcome = pending.length > 0 ? "annotated" : retried ? "retried" : "passed"
3027
+ // Who challenged the answer in this run: before (the challenge answered) or now (not acted on).
3028
+ const challenged = [...new Set([...(challengers ?? []), ...challengedBy])]
3029
+ if (pending.length > 0) {
3030
+ yield* inTranscript(spec, (sql) =>
3031
+ appendEvent(sql, run, "answer-checked", { step, outcome, receipts: pending, challengedBy: challenged }),
3032
+ )
3033
+ }
3034
+ return {
3035
+ kind: "accept",
3036
+ result: pending.length > 0 ? `${text}${annotation(pending)}` : text,
3037
+ verification:
3038
+ receipts.length === 0 && !retried
3039
+ ? null
3040
+ : { outcome, receipts: [...receipts], ...(challenged.length === 0 ? {} : { challengedBy: challenged }) },
3041
+ } satisfies CheckOutcome
3042
+ })
3043
+
3044
+ // --- finish ---------------------------------------------------------------------------------------------------------
3045
+
3046
+ interface Outcome {
3047
+ readonly status: string
3048
+ readonly stopReason: string | null
3049
+ readonly result: string | null
3050
+ readonly error: string | null
3051
+ /** What the final-answer check found (persisted on the run). */
3052
+ readonly verification?: RunVerification | null | undefined
3053
+ /** The run failed transiently (its model call was rate-limited or timed out): the kernel may continue its turn. */
3054
+ readonly retryable?: boolean | undefined
3055
+ }
3056
+
3057
+ /**
3058
+ * Record a run's outcome (once), end its event stream, and tell its parent. Inside a transaction. A run whose
3059
+ * cancellation committed ends `cancelled`, whatever outcome its execution reached: the one statement that records
3060
+ * the outcome reads the flag on the run's row it locks, and `agent.cancel` locks the same row, so either the
3061
+ * cancellation committed first (and the run ends cancelled) or the outcome did (and the cancellation is refused).
3062
+ * Returns the run's outcome as recorded.
3063
+ */
3064
+ const recordFinish = (
3065
+ run: {
3066
+ readonly runId: string
3067
+ readonly orgId: string
3068
+ readonly userId: string
3069
+ readonly parentRunId: string | null
3070
+ /** The run's own spec, when its execution records the finish (an automatic continuation inherits its authority). */
3071
+ readonly spec?: Spec | undefined
3072
+ },
3073
+ outcome: Outcome,
3074
+ ) =>
3075
+ Effect.gen(function* () {
3076
+ const sql = yield* SqlClient.SqlClient
3077
+ const outbox = yield* Outbox
3078
+ const recorded = yield* asAgent(
3079
+ sql,
3080
+ run.orgId,
3081
+ Effect.gen(function* () {
3082
+ // (A sub-agent ends cancelled with its parent.)
3083
+ const parent = yield* parentCancelled(sql, run)
3084
+ const [updated] = yield* sql<
3085
+ Outcome & {
3086
+ inputTokens: number
3087
+ outputTokens: number
3088
+ steps: number
3089
+ conversationId: string
3090
+ }
3091
+ >`UPDATE eloxiv_agent.run
3092
+ SET status = CASE WHEN cancel_requested_at IS NULL AND NOT ${parent} THEN ${outcome.status}
3093
+ ELSE 'cancelled' END,
3094
+ stop_reason = CASE WHEN cancel_requested_at IS NULL AND NOT ${parent} THEN ${outcome.stopReason}
3095
+ ELSE 'cancelled' END,
3096
+ error = CASE WHEN (cancel_requested_at IS NULL AND NOT ${parent}) OR ${outcome.status} = 'cancelled'
3097
+ THEN ${outcome.error} ELSE ${CANCELLED_ERROR} END,
3098
+ result = ${outcome.result}, wait = NULL, finished_at = now(),
3099
+ verification = ${outcome.verification == null ? null : JSON.stringify(outcome.verification)}::jsonb
3100
+ WHERE id = ${run.runId} AND finished_at IS NULL
3101
+ RETURNING status, stop_reason AS "stopReason", result, error,
3102
+ input_tokens AS "inputTokens", output_tokens AS "outputTokens", steps, conversation_id AS "conversationId"`
3103
+ if (updated === undefined) {
3104
+ // Recorded already (a finish step re-run after its commit): the outcome stored is the run's.
3105
+ const [stored] = yield* sql<Outcome>`SELECT status, stop_reason AS "stopReason", result, error
3106
+ FROM eloxiv_agent.run WHERE id = ${run.runId}`
3107
+ return { recorded: false, outcome: stored ?? outcome, conversationId: null, orphans: false } as const
3108
+ }
3109
+ const final: Outcome = {
3110
+ status: updated.status,
3111
+ stopReason: updated.stopReason,
3112
+ result: updated.result,
3113
+ error: updated.error,
3114
+ }
3115
+ yield* appendEvent(sql, { id: run.runId, orgId: run.orgId, userId: run.userId }, "run-finished", {
3116
+ ...final,
3117
+ usage: { inputTokens: updated.inputTokens, outputTokens: updated.outputTokens },
3118
+ steps: updated.steps,
3119
+ })
3120
+ // Seats of its team (or a sub-agent left by a failed execution) still running: they stop with it (each reads
3121
+ // that its ancestor ended at its next check), and the kernel's reaction records it on them and wakes them.
3122
+ const [live] = yield* sql<{ n: number }>`WITH RECURSIVE subtree (id) AS (
3123
+ SELECT id FROM eloxiv_agent.run WHERE parent_run_id = ${run.runId}
3124
+ UNION ALL
3125
+ SELECT r.id FROM eloxiv_agent.run r JOIN subtree t ON r.parent_run_id = t.id
3126
+ )
3127
+ SELECT count(*)::int AS n FROM eloxiv_agent.run WHERE id IN (SELECT id FROM subtree) AND finished_at IS NULL`
3128
+ return {
3129
+ recorded: true,
3130
+ outcome: final,
3131
+ conversationId: updated.conversationId,
3132
+ orphans: (live?.n ?? 0) > 0,
3133
+ } as const
3134
+ }),
3135
+ )
3136
+ // A person's (or a job's) run that failed transiently continues its turn (at most the deployment's number of times);
3137
+ // otherwise, a run that ended makes way for the conversation's next queued message, in the same transaction (each
3138
+ // queued reply's access checked as its sender).
3139
+ const { automaticContinuations } = yield* AgentSettings
3140
+ const continuing =
3141
+ recorded.recorded &&
3142
+ run.parentRunId === null &&
3143
+ outcome.retryable === true &&
3144
+ recorded.outcome.status === "failed" &&
3145
+ run.spec !== undefined
3146
+ // The successor acts under the interrupted run's whole chain, its agent session included (a link `runChain` adds):
3147
+ // a session revoked meanwhile is in its chain, so it can act on nothing; and none is started once that chain no
3148
+ // longer holds.
3149
+ const effective = continuing && run.spec !== undefined ? effectiveAuthority(run.spec) : null
3150
+ const holds =
3151
+ effective === null
3152
+ ? false
3153
+ : (yield* (yield* Authority).check(runAuthority(run.spec!)).pipe(Effect.result))._tag === "Success"
3154
+ const continued =
3155
+ effective !== null && holds
3156
+ ? yield* asAgent(sql, run.orgId, continueAutomatically(sql, run.runId, automaticContinuations, effective))
3157
+ : null
3158
+ const promoted =
3159
+ continued !== null
3160
+ ? continued
3161
+ : recorded.recorded && run.parentRunId === null
3162
+ ? yield* promoteQueued(sql, { orgId: run.orgId, userId: run.userId, conversationId: recorded.conversationId })
3163
+ : null
3164
+ if (promoted !== null) {
3165
+ yield* outbox.publish({
3166
+ invocationId: promoted,
3167
+ type: "agent.runRequested",
3168
+ module: AGENT_MODULE,
3169
+ orgId: run.orgId,
3170
+ payload: { runId: promoted },
3171
+ })
3172
+ }
3173
+ if (recorded.orphans) {
3174
+ yield* outbox.publish({
3175
+ invocationId: run.runId,
3176
+ type: "agent.cancelRequested",
3177
+ module: AGENT_MODULE,
3178
+ orgId: run.orgId,
3179
+ payload: { runId: run.runId },
3180
+ })
3181
+ }
3182
+ if (recorded.recorded && run.parentRunId !== null) {
3183
+ yield* outbox.publish({
3184
+ invocationId: run.runId,
3185
+ type: "agent.runFinished",
3186
+ module: AGENT_MODULE,
3187
+ orgId: run.orgId,
3188
+ payload: {
3189
+ runId: run.runId,
3190
+ parentRunId: run.parentRunId,
3191
+ status: recorded.outcome.status,
3192
+ result: recorded.outcome.result,
3193
+ },
3194
+ })
3195
+ }
3196
+ return recorded.outcome
3197
+ })
3198
+
3199
+ const finishRun = (spec: Spec, outcome: Outcome) =>
3200
+ Effect.gen(function* () {
3201
+ const sql = yield* SqlClient.SqlClient
3202
+ const recorded = yield* sql.withTransaction(recordFinish({ ...spec, spec }, outcome))
3203
+ return { status: recorded.status, stopReason: recorded.stopReason, result: recorded.result }
3204
+ })
3205
+
3206
+ /**
3207
+ * The run's execution failed outside the loop's own handling (its start, its finish, a defect): the run ends
3208
+ * `failed` all the same, its stream closes, its parent hears, and a model call it left open is metered as lost.
3209
+ */
3210
+ const failRun = (runId: string, orgId: string, message: string) =>
3211
+ Effect.gen(function* () {
3212
+ const sql = yield* SqlClient.SqlClient
3213
+ yield* sql.withTransaction(
3214
+ Effect.gen(function* () {
3215
+ const run = yield* asAgent(
3216
+ sql,
3217
+ orgId,
3218
+ Effect.gen(function* () {
3219
+ const [run] = yield* sql<{ userId: string; parentRunId: string | null }>`SELECT user_id AS "userId",
3220
+ parent_run_id AS "parentRunId" FROM eloxiv_agent.run WHERE id = ${runId} AND finished_at IS NULL FOR UPDATE`
3221
+ if (run === undefined) return undefined
3222
+ const lost = yield* abandonCalls(sql, { orgId, runId })
3223
+ if (lost.calls > 0) {
3224
+ yield* sql`UPDATE eloxiv_agent.run SET steps = steps + ${lost.calls},
3225
+ input_tokens = input_tokens + ${lost.inputTokens}, output_tokens = output_tokens + ${lost.outputTokens}
3226
+ WHERE id = ${runId}`
3227
+ }
3228
+ return run
3229
+ }),
3230
+ )
3231
+ if (run === undefined) return
3232
+ yield* recordFinish(
3233
+ { runId, orgId, userId: run.userId, parentRunId: run.parentRunId },
3234
+ { status: "failed", stopReason: "error", result: null, error: message.slice(0, 2_000) },
3235
+ )
3236
+ }),
3237
+ )
3238
+ })
3239
+
3240
+ /** What a finished sub-agent is charged, with everything below it, for its parent's limits (SUBTREE_CHARGE). */
3241
+ const childConsumed = (spec: Spec, childRunId: string) =>
3242
+ Effect.gen(function* () {
3243
+ const sql = yield* SqlClient.SqlClient
3244
+ const [child] = yield* inAgent(sql, spec.orgId, SUBTREE_CHARGE(sql, childRunId))
3245
+ return { calls: child?.calls ?? 0, tokens: child?.tokens ?? 0 } satisfies Consumed
3246
+ })
3247
+
3248
+ // --- the workflow -------------------------------------------------------------------------------------------------------
3249
+
3250
+ export const agentRunWorkflow = defineKernelWorkflow({
3251
+ name: AGENT_RUN_WORKFLOW,
3252
+ input: Schema.Struct({ runId: Schema.String }),
3253
+ output: Finished,
3254
+ run: ({ runId }, ctx) =>
3255
+ Effect.gen(function* () {
3256
+ const services = yield* Effect.context<RunServices>()
3257
+ const R = (what: string) => withServices(services, what)
3258
+ const spec = yield* ctx.step("start", Spec, () => R("start")(startRun(runId, ctx.identity.orgId)))
3259
+ const finish = (
3260
+ status: string,
3261
+ stopReason: string | null,
3262
+ result: string | null,
3263
+ error: string | null = null,
3264
+ verification: RunVerification | null = null,
3265
+ retryable = false,
3266
+ ) =>
3267
+ ctx.step("finish", Finished, () =>
3268
+ R("finish")(finishRun(spec, { status, stopReason, result, error, verification, retryable })),
3269
+ )
3270
+ const device = spec.device
3271
+ const checksDevice = (yield* AgentSettings).processors.some(
3272
+ (p) => p.onChunk !== undefined || p.onFinal !== undefined,
3273
+ )
3274
+ if (device !== undefined && device !== null) {
3275
+ // The run executes on the person's device: one turn there, waited for durably, is the whole run. Plan mode
3276
+ // cannot be enforced there (the device's harness runs its own tools), so such a run is refused (`agent.send`
3277
+ // refuses it too).
3278
+ if (optionsOf(spec).mode === "plan") {
3279
+ return yield* finish("failed", "error", null, PLAN_ON_DEVICE)
3280
+ }
3281
+ const deviceRun = Effect.gen(function* () {
3282
+ const call = yield* ctx.step("device/call", ToolCallSchema, () => R("device turn")(deviceCall(spec, device)))
3283
+ let sent: DeviceSent = yield* ctx.step("device/send", DeviceSent, (key) =>
3284
+ R("device turn")(sendToDevice(spec, call, key)),
3285
+ )
3286
+ if (sent.kind === "consent") {
3287
+ const decision = sent.decided ?? (yield* ctx.waitForSignal(sent.signal, Decision))
3288
+ if (decision.kind === "cancel")
3289
+ return yield* finish("cancelled", "cancelled", null, "The run was cancelled")
3290
+ const consentId = sent.consentId
3291
+ sent = yield* ctx.step("device/send/decided", DeviceSent, (key) =>
3292
+ R("device turn")(sendAfterConsent(spec, call, decision, consentId, key)),
3293
+ )
3294
+ }
3295
+ if (sent.kind === "cancelled") return yield* finish("cancelled", "cancelled", null, "The run was cancelled")
3296
+ if (sent.kind !== "sent") {
3297
+ return yield* finish(
3298
+ "failed",
3299
+ "error",
3300
+ null,
3301
+ sent.kind === "refused" ? sent.message : "The turn was not sent",
3302
+ )
3303
+ }
3304
+ const turnId = sent.turnId
3305
+ yield* ctx.step("device/sent", Schema.Null, () => R("device turn")(announceTurn(spec, call, turnId)))
3306
+ const wait = yield* ctx.step("device/wait", DeviceWait, () => R("device turn")(awaitTurn(spec, turnId)))
3307
+ const woken = wait.kind === "waiting" ? yield* ctx.waitForSignal(wait.signal, Decision) : undefined
3308
+ if (wait.kind === "cancelled" || woken?.kind === "cancel") {
3309
+ yield* ctx.step("device/cancel", Schema.Null, (key) =>
3310
+ R("device turn")(cancelDeviceTurn(spec, turnId, key)),
3311
+ )
3312
+ return yield* finish("cancelled", "cancelled", null, "The run was cancelled")
3313
+ }
3314
+ const outcome = yield* ctx.step("device/result", DeviceOutcome, () =>
3315
+ R("device turn")(takeTurn(spec, turnId)),
3316
+ )
3317
+ // The app's processors see the device's answer as they see a model's (its text, then the final answer); a
3318
+ // trip stops the run. The answer was the device's whole turn, so a challenge cannot be acted on.
3319
+ if (outcome.status === "succeeded" && checksDevice) {
3320
+ const tripped = yield* ctx.step("device/check", Schema.NullOr(Schema.String), () =>
3321
+ R("device turn")(deviceCheck(spec, outcome.result ?? "")),
3322
+ )
3323
+ if (tripped !== null) return yield* finish("stopped", "processor", outcome.result, tripped)
3324
+ }
3325
+ return yield* finish(outcome.status, outcome.stopReason, outcome.result, outcome.error)
3326
+ })
3327
+ return yield* deviceRun.pipe(
3328
+ Effect.catchTag("WorkflowFailed", (failure) => finish("failed", "error", null, failure.message)),
3329
+ )
3330
+ }
3331
+ // What the run has spent of its limits: its model calls (compaction and lost attempts included) and its
3332
+ // sub-agents', and their tokens. From journalled step results only, so a replay counts the same.
3333
+ // The attached files' content, read once as the person's agent before the first model call.
3334
+ // A continuation of an interrupted turn: an automatic one waits out its backoff, then every continuation first
3335
+ // reconciles what the run it continues did (journalled), and is told so.
3336
+ const continuation = optionsOf(spec).continuation
3337
+ let note: string | null = null
3338
+ let inherited: ReadonlyArray<ToolReceipt> = []
3339
+ if (continuation !== undefined) {
3340
+ const { continuationBackoffMs } = yield* AgentSettings
3341
+ if (continuation.automatic && continuationBackoffMs > 0) {
3342
+ yield* ctx.sleep("continuation/backoff", continuationBackoffMs * 2 ** (continuation.attempt - 1))
3343
+ }
3344
+ const reconciled = yield* ctx.step("reconcile", Reconciled, () => R("reconcile")(reconcile(spec, continuation)))
3345
+ note = reconciled.note
3346
+ inherited = reconciled.receipts ?? []
3347
+ }
3348
+ if ((optionsOf(spec).attachments ?? 0) > 0) {
3349
+ yield* ctx.step("attachments", Schema.Null, (key) => R("attachments")(readAttachments(spec, key)))
3350
+ }
3351
+ const consumed = { calls: 0, tokens: 0 }
3352
+ let last = ""
3353
+ // Also from journalled results only: the tools the run loaded with tool_search, the receipts of its writes, and
3354
+ // whether its answer was challenged already.
3355
+ const loaded = new Set<string>()
3356
+ // A continuation starts from its logical turn's writes (journalled in its `reconcile` step).
3357
+ const receipts: Array<ToolReceipt> = [...inherited]
3358
+ // The processors whose challenge was answered, once the answer was challenged (null before).
3359
+ let challengers: ReadonlyArray<string> | null = null
3360
+ const { processors, maxDelegationDepth } = yield* AgentSettings
3361
+ const checksAnswers = processors.some((p) => p.onFinal !== undefined)
3362
+ // The run's team (also from journalled results only): see TeamLedger.
3363
+ const team = {
3364
+ seen: {} as Record<string, number>,
3365
+ collected: [] as Array<string>,
3366
+ reserved: {} as Record<string, Consumed>,
3367
+ }
3368
+ const loop = Effect.gen(function* () {
3369
+ for (let step = 0; ; step++) {
3370
+ if (consumed.calls >= spec.limits.maxSteps) {
3371
+ return yield* finish(
3372
+ "stopped",
3373
+ "steps",
3374
+ last || null,
3375
+ `The run reached its step limit (${spec.limits.maxSteps})`,
3376
+ )
3377
+ }
3378
+ const spent = { ...consumed }
3379
+ const offered = new Set(loaded)
3380
+ const outcome = yield* ctx.step(`model/${step}`, ModelOutcome, () =>
3381
+ R("model call")(modelStep(spec, step, spent, offered, note)),
3382
+ )
3383
+ if (outcome.kind === "stop") {
3384
+ const status =
3385
+ outcome.reason === "cancelled" ? "cancelled" : outcome.reason === "model-error" ? "failed" : "stopped"
3386
+ return yield* finish(
3387
+ status,
3388
+ outcome.reason,
3389
+ last || null,
3390
+ outcome.message,
3391
+ null,
3392
+ "retryable" in outcome && outcome.retryable,
3393
+ )
3394
+ }
3395
+ consumed.calls += outcome.calls ?? 1
3396
+ consumed.tokens += outcome.tokens ?? outcome.usage.inputTokens + outcome.usage.outputTokens
3397
+ if (outcome.text.length > 0) last = outcome.text
3398
+ if (outcome.toolCalls.length === 0) {
3399
+ // Nothing to check (no write left unverified, no final-answer processor, no challenge answered): the answer
3400
+ // stands, with its writes' receipts as the run's evidence, decided from journalled results alone.
3401
+ if (flagged(receipts).length === 0 && !checksAnswers && challengers === null) {
3402
+ return yield* finish(
3403
+ "succeeded",
3404
+ "completed",
3405
+ outcome.text,
3406
+ null,
3407
+ receipts.length === 0 ? null : { outcome: "passed", receipts: [...receipts] },
3408
+ )
3409
+ }
3410
+ const answer = outcome.text
3411
+ const check = yield* ctx.step(`check/${step}`, CheckOutcome, () =>
3412
+ R("answer check")(
3413
+ finalCheck(spec, step, answer, [...receipts], challengers, consumed.calls < spec.limits.maxSteps),
3414
+ ),
3415
+ )
3416
+ if (check.kind === "retry") {
3417
+ challengers = check.challengedBy
3418
+ continue
3419
+ }
3420
+ if (check.kind === "abort") return yield* finish("stopped", "processor", answer || null, check.message)
3421
+ return yield* finish("succeeded", "completed", check.result, null, check.verification)
3422
+ }
3423
+ for (const call of outcome.toolCalls) {
3424
+ // A job's run that found nothing to do: it ends a no-op (the execution's typed outcome too), with the reason.
3425
+ if (call.toolName === "no_op" && spec.kind === "job") {
3426
+ const given = (call.input as { readonly reason?: unknown } | null)?.reason
3427
+ const reason = (typeof given === "string" && given.trim() !== "" ? given.trim() : "Nothing to do").slice(
3428
+ 0,
3429
+ 500,
3430
+ )
3431
+ yield* ctx.noop(reason)
3432
+ return yield* finish("succeeded", "noop", reason)
3433
+ }
3434
+ // The run's id is in the step's name, so its idempotency key (and every audit record of the call)
3435
+ // names the run: `<execution id>:tool/<run id>/<step>/<tool call id>`.
3436
+ const name = `tool/${spec.runId}/${step}/${call.toolCallId}`
3437
+ let tool: ToolOutcome
3438
+ if (
3439
+ call.toolName === "delegate" &&
3440
+ (spec.tools === null || spec.tools.includes("delegate")) &&
3441
+ optionsOf(spec).depth < maxDelegationDepth
3442
+ ) {
3443
+ const before = { ...consumed }
3444
+ const started = yield* ctx.step(`delegate/${step}/${call.toolCallId}`, ToolOutcome, () =>
3445
+ R("delegation")(startChild(spec, step, call, before)),
3446
+ )
3447
+ if (started.kind === "started") {
3448
+ const decision = yield* ctx.waitForSignal(started.signal, Decision)
3449
+ if (decision.kind === "cancel")
3450
+ return yield* finish("cancelled", "cancelled", last || null, "The run was cancelled")
3451
+ const child = decision.kind === "child" ? decision : { status: "failed", result: null }
3452
+ tool = yield* ctx.step(name, ToolOutcome, () =>
3453
+ R("delegation result")(
3454
+ Effect.gen(function* () {
3455
+ const spentByChild = yield* childConsumed(spec, started.childRunId)
3456
+ const persisted = yield* persistResult(
3457
+ spec,
3458
+ step,
3459
+ call,
3460
+ { ok: true, output: { runId: started.childRunId, status: child.status, result: child.result } },
3461
+ spentByChild,
3462
+ )
3463
+ return yield* processTool(spec, step, call, persisted)
3464
+ }),
3465
+ ),
3466
+ )
3467
+ } else tool = started
3468
+ } else if (
3469
+ call.toolName === TEAM &&
3470
+ (spec.tools === null || spec.tools.includes(TEAM) || optionsOf(spec).seat !== undefined)
3471
+ ) {
3472
+ const ledger: TeamLedger = {
3473
+ seen: { ...team.seen },
3474
+ collected: [...team.collected],
3475
+ reserved: { ...team.reserved },
3476
+ }
3477
+ if ((call.input as { readonly action?: unknown } | null)?.action === "spawn") {
3478
+ const before = { ...consumed }
3479
+ tool = yield* ctx.step(`team/${step}/${call.toolCallId}`, ToolOutcome, () =>
3480
+ R("team")(
3481
+ (spawnsSeats(spec, maxDelegationDepth)
3482
+ ? startChild(spec, step, call, before, true)
3483
+ : persistResult(
3484
+ spec,
3485
+ step,
3486
+ call,
3487
+ refused(
3488
+ "ToolNotAllowed",
3489
+ "This run may not start seats (it was not given the team tool, or the delegation depth is reached)",
3490
+ { tool: TEAM },
3491
+ ),
3492
+ )
3493
+ ).pipe(Effect.flatMap((o) => processTool(spec, step, call, o))),
3494
+ ),
3495
+ )
3496
+ } else {
3497
+ for (let k = 0; ; k++) {
3498
+ const outcome: TeamOutcome = yield* ctx.step(
3499
+ `team/${step}/${call.toolCallId}/${k}`,
3500
+ TeamOutcome,
3501
+ () =>
3502
+ R("team")(
3503
+ teamCall(spec, step, call, k, ledger).pipe(
3504
+ Effect.flatMap((o): Effect.Effect<TeamOutcome, unknown, RunServices> =>
3505
+ o.kind === "team-wait" ? Effect.succeed(o) : processTool(spec, step, call, o),
3506
+ ),
3507
+ ),
3508
+ ),
3509
+ )
3510
+ if (outcome.kind !== "team-wait") {
3511
+ tool = outcome
3512
+ break
3513
+ }
3514
+ const woken = yield* ctx.waitForSignal(outcome.signal, Decision)
3515
+ if (woken.kind === "cancel")
3516
+ return yield* finish("cancelled", "cancelled", last || null, "The run was cancelled")
3517
+ }
3518
+ }
3519
+ if (tool.kind === "result" && (tool.result as AgentToolResult).ok) {
3520
+ const output = ((tool.result as AgentToolResult & { ok: true }).output ?? {}) as TeamOutput
3521
+ if (output.seat !== undefined && output.limits !== undefined) {
3522
+ team.reserved[output.seat] = { calls: output.limits.maxSteps, tokens: output.limits.maxTokens }
3523
+ }
3524
+ for (const seat of output.finished ?? []) team.collected.push(seat.seat)
3525
+ for (const message of output.messages ?? []) {
3526
+ team.seen[message.sender] = Math.max(team.seen[message.sender] ?? -1, message.seq)
3527
+ }
3528
+ }
3529
+ } else {
3530
+ tool = yield* ctx.step(name, ToolOutcome, (key) =>
3531
+ R("tool call")(
3532
+ toolStep(spec, step, call, key, offered).pipe(
3533
+ Effect.flatMap((o) => processTool(spec, step, call, o)),
3534
+ ),
3535
+ ),
3536
+ )
3537
+ }
3538
+ if (tool.kind === "consent") {
3539
+ const decision = tool.decided ?? (yield* ctx.waitForSignal(tool.signal, Decision))
3540
+ if (decision.kind === "cancel")
3541
+ return yield* finish("cancelled", "cancelled", last || null, "The run was cancelled")
3542
+ const consentId = tool.consentId
3543
+ tool = yield* ctx.step(`${name}/decided`, ToolOutcome, (key) =>
3544
+ R("consented tool call")(
3545
+ afterConsent(spec, step, call, decision, consentId, key).pipe(
3546
+ Effect.flatMap((o) => processTool(spec, step, call, o)),
3547
+ ),
3548
+ ),
3549
+ )
3550
+ }
3551
+ if (tool.kind === "cancelled")
3552
+ return yield* finish("cancelled", "cancelled", last || null, "The run was cancelled")
3553
+ if (tool.kind === "result" && tool.consumed !== undefined) {
3554
+ consumed.calls += tool.consumed.calls
3555
+ consumed.tokens += tool.consumed.tokens
3556
+ }
3557
+ if (tool.kind === "result") {
3558
+ const result = tool.result as AgentToolResult
3559
+ if (result.ok && result.receipt !== undefined) {
3560
+ receipts.push({ tool: call.toolName, receipt: Schema.decodeUnknownSync(WriteReceipt)(result.receipt) })
3561
+ }
3562
+ if (result.ok && call.toolName === TOOL_SEARCH) {
3563
+ const found = result.output as {
3564
+ readonly loaded?: ReadonlyArray<string>
3565
+ readonly removed?: ReadonlyArray<string>
3566
+ }
3567
+ for (const name of found.loaded ?? []) loaded.add(name)
3568
+ for (const name of found.removed ?? []) loaded.delete(name)
3569
+ }
3570
+ if (tool.tripped !== undefined) {
3571
+ return yield* finish("stopped", "processor", last || null, trippedStop(tool.tripped).message)
3572
+ }
3573
+ }
3574
+ }
3575
+ }
3576
+ })
3577
+ // A step that failed (after its retries) ends the run as failed, so its record and stream say so.
3578
+ return yield* loop.pipe(
3579
+ Effect.catchTag("WorkflowFailed", (failure) => finish("failed", "error", last || null, failure.message)),
3580
+ )
3581
+ }),
3582
+ // Anything else that fails the execution (its start, its finish, a defect) still ends the run `failed`.
3583
+ onFailure: ({ runId }, failure, ctx) =>
3584
+ failRun(runId, ctx.identity.orgId, `The run's execution failed (${failure.tag}): ${failure.message}`),
3585
+ })
3586
+
3587
+ // --- reactions ---------------------------------------------------------------------------------------------------------
3588
+
3589
+ const RunPayload = Schema.Struct({ runId: Schema.String })
3590
+ const FinishedPayload = Schema.Struct({
3591
+ runId: Schema.String,
3592
+ parentRunId: Schema.String,
3593
+ status: Schema.String,
3594
+ result: Schema.NullOr(Schema.String),
3595
+ })
3596
+ const ConsentPayload = Schema.Struct({ id: Schema.String, status: Schema.Literals(["approved", "rejected"]) })
3597
+
3598
+ /**
3599
+ * The kernel reactions that drive runs from outbox events: start a run's execution when it is requested (by
3600
+ * `agent.send` or a delegation), wake a waiting run when it is cancelled, when the person decides a consent it
3601
+ * waits on, or when its sub-agent finishes.
3602
+ */
3603
+ /** Signal a run waiting on something (its recorded `wait`), with what happened; nothing if it does not wait. */
3604
+ const wakeRun =
3605
+ (workflows: WorkflowsShape, sql: SqlClient.SqlClient) => (orgId: string, runId: string, value: Decision) =>
3606
+ Effect.gen(function* () {
3607
+ const [run] = yield* inAgent(
3608
+ sql,
3609
+ orgId,
3610
+ sql<{ wait: { signal?: string } | null }>`SELECT wait FROM eloxiv_agent.run WHERE id = ${runId}`,
3611
+ ).pipe(Effect.orDie)
3612
+ const signal = run?.wait?.signal
3613
+ if (signal === undefined) return
3614
+ yield* workflows.signal({
3615
+ executionId: yield* workflows.executionIdFor(AGENT_RUN_WORKFLOW, runId),
3616
+ signal,
3617
+ value,
3618
+ })
3619
+ })
3620
+
3621
+ /**
3622
+ * Wake a run waiting on its team (a `team` wait, `wait.team`): one of its seats finished, or a message arrived for it.
3623
+ * Nothing for a run that waits on anything else (a consent, a device turn) or not at all; a wake for a wait already
3624
+ * over finds the next one (if any), which looks again and waits on.
3625
+ */
3626
+ const wakeTeam = (workflows: WorkflowsShape, sql: SqlClient.SqlClient) => (orgId: string, runId: string) =>
3627
+ Effect.gen(function* () {
3628
+ const [run] = yield* inAgent(
3629
+ sql,
3630
+ orgId,
3631
+ sql<{ wait: { signal?: string; team?: boolean } | null }>`SELECT wait FROM eloxiv_agent.run WHERE id = ${runId}`,
3632
+ ).pipe(Effect.orDie)
3633
+ if (run?.wait?.team !== true || run.wait.signal === undefined) return
3634
+ yield* workflows.signal({
3635
+ executionId: yield* workflows.executionIdFor(AGENT_RUN_WORKFLOW, runId),
3636
+ signal: run.wait.signal,
3637
+ value: { kind: "team" } satisfies Decision,
3638
+ })
3639
+ })
3640
+
3641
+ /**
3642
+ * A device turn settled (the kernel's `devices.settled` reaction): wake the agent run it executes for, if any
3643
+ * (its parent run, recorded by the run when it sent the turn).
3644
+ */
3645
+ export const wakeRunForTurn =
3646
+ (workflows: WorkflowsShape, sql: SqlClient.SqlClient) =>
3647
+ (settled: { readonly orgId: string; readonly turnId: string; readonly status: string }) =>
3648
+ Effect.gen(function* () {
3649
+ const [turn] = yield* sql
3650
+ .withTransaction(
3651
+ asSystem(
3652
+ sql,
3653
+ "devices",
3654
+ settled.orgId,
3655
+ sql<{ parentRunId: string | null }>`SELECT parent_run_id AS "parentRunId" FROM eloxiv_devices.turn
3656
+ WHERE id = ${settled.turnId}`,
3657
+ ),
3658
+ )
3659
+ .pipe(Effect.orDie)
3660
+ if (turn?.parentRunId == null) return
3661
+ yield* wakeRun(workflows, sql)(settled.orgId, turn.parentRunId, { kind: "device", status: settled.status })
3662
+ })
3663
+
3664
+ export const agentReactions = (workflows: WorkflowsShape, sql: SqlClient.SqlClient) => {
3665
+ const wake = wakeRun(workflows, sql)
3666
+ const wakeLead = wakeTeam(workflows, sql)
3667
+ return [
3668
+ {
3669
+ id: "agent.start",
3670
+ event: "agent.runRequested",
3671
+ handle: (event: ReactionEvent) =>
3672
+ Effect.gen(function* () {
3673
+ const { runId } = yield* Schema.decodeUnknownEffect(RunPayload)(event.payload)
3674
+ const [run] = yield* inAgent(
3675
+ sql,
3676
+ event.orgId,
3677
+ sql<{ userId: string }>`SELECT user_id AS "userId" FROM eloxiv_agent.run WHERE id = ${runId}`,
3678
+ ).pipe(Effect.orDie)
3679
+ if (run === undefined) return
3680
+ yield* workflows.start({
3681
+ workflow: AGENT_RUN_WORKFLOW,
3682
+ key: runId,
3683
+ identity:
3684
+ run.userId === SYSTEM_ACTOR
3685
+ ? { kind: "system", orgId: event.orgId }
3686
+ : { kind: "user", userId: run.userId, orgId: event.orgId },
3687
+ input: { runId },
3688
+ })
3689
+ }),
3690
+ },
3691
+ {
3692
+ id: "agent.cancel",
3693
+ event: "agent.cancelRequested",
3694
+ handle: (event: ReactionEvent) =>
3695
+ Effect.gen(function* () {
3696
+ const { runId } = yield* Schema.decodeUnknownEffect(RunPayload)(event.payload)
3697
+ // Its whole subtree is cancelled with it (each sub-agent reads every ancestor's flag too, from the moment it
3698
+ // commits): the flag is recorded on each, at any depth, and each is woken if it waits.
3699
+ const children = yield* inAgent(
3700
+ sql,
3701
+ event.orgId,
3702
+ sql<{ id: string }>`WITH RECURSIVE subtree (id) AS (
3703
+ SELECT id FROM eloxiv_agent.run WHERE parent_run_id = ${runId}
3704
+ UNION ALL
3705
+ SELECT r.id FROM eloxiv_agent.run r JOIN subtree t ON r.parent_run_id = t.id
3706
+ )
3707
+ UPDATE eloxiv_agent.run SET cancel_requested_at = coalesce(cancel_requested_at, now())
3708
+ WHERE id IN (SELECT id FROM subtree) AND finished_at IS NULL RETURNING id`,
3709
+ ).pipe(Effect.orDie)
3710
+ for (const child of children) yield* wake(event.orgId, child.id, { kind: "cancel" })
3711
+ yield* wake(event.orgId, runId, { kind: "cancel" })
3712
+ }),
3713
+ },
3714
+ {
3715
+ id: "agent.consent",
3716
+ event: "consent.decided",
3717
+ handle: (event: ReactionEvent) =>
3718
+ Effect.gen(function* () {
3719
+ const { id, status } = yield* Schema.decodeUnknownEffect(ConsentPayload)(event.payload)
3720
+ const waiting = yield* inAgent(
3721
+ sql,
3722
+ event.orgId,
3723
+ sql<{
3724
+ id: string
3725
+ }>`SELECT id FROM eloxiv_agent.run WHERE wait->>'consentId' = ${id} AND finished_at IS NULL`,
3726
+ ).pipe(Effect.orDie)
3727
+ for (const run of waiting) yield* wake(event.orgId, run.id, { kind: "consent", status })
3728
+ }),
3729
+ },
3730
+ {
3731
+ id: "agent.child",
3732
+ event: "agent.runFinished",
3733
+ handle: (event: ReactionEvent) =>
3734
+ Effect.gen(function* () {
3735
+ const payload = yield* Schema.decodeUnknownEffect(FinishedPayload)(event.payload)
3736
+ // A seat's lead never waits for this one child: it may wait on its team, and is woken only for that. (Every
3737
+ // signal a run is sent is one it awaits: the engine resumes a run for each, and one it never awaits kept a
3738
+ // lead replaying without end.)
3739
+ const [child] = yield* inAgent(
3740
+ sql,
3741
+ event.orgId,
3742
+ sql<{ seat: boolean }>`SELECT options ? 'seat' AS seat FROM eloxiv_agent.run WHERE id = ${payload.runId}`,
3743
+ ).pipe(Effect.orDie)
3744
+ if (child?.seat === true) return yield* wakeLead(event.orgId, payload.parentRunId)
3745
+ yield* workflows.signal({
3746
+ executionId: yield* workflows.executionIdFor(AGENT_RUN_WORKFLOW, payload.parentRunId),
3747
+ signal: `child/${payload.runId}`,
3748
+ value: { kind: "child", status: payload.status, result: payload.result } satisfies Decision,
3749
+ })
3750
+ }),
3751
+ },
3752
+ {
3753
+ id: "agent.team",
3754
+ event: "agent.teamWake",
3755
+ handle: (event: ReactionEvent) =>
3756
+ Effect.gen(function* () {
3757
+ const { runId } = yield* Schema.decodeUnknownEffect(RunPayload)(event.payload)
3758
+ yield* wakeLead(event.orgId, runId)
3759
+ }),
3760
+ },
3761
+ ]
3762
+ }