@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,2387 @@
1
+ /**
2
+ * The one invocation path every surface calls:
3
+ *
4
+ * (lookup, decode) -> identity -> policy -> approval -> idempotency -> execute -> audit -> outbox
5
+ *
6
+ * The action is looked up and its input decoded before identity, so an unknown
7
+ * action or undecodable input fails as such even for an unauthenticated caller.
8
+ *
9
+ * Record-level authorisation uses the action's Cedar policy compiled into a SQL
10
+ * filter (decision 2), inside the transaction:
11
+ * - before the handler: the action's declared targets (one id or a list) are
12
+ * locked and must satisfy the filter, so a handler cannot change ownership
13
+ * or clear a lock to make a forbidden target pass. A best-effort action
14
+ * continues with the targets the caller may act on;
15
+ * - after the handler: every row the handler inserted, updated or deleted
16
+ * (from the trigger-backed write log, keyed by the top-level transaction)
17
+ * must be authorised. Rows of the target entity must be declared, permitted
18
+ * targets; every declared target of an exact action must have been affected;
19
+ * deletes are allowed only for targets; surviving rows must satisfy the
20
+ * filter. A database refusal (row-level security, privileges) is Forbidden;
21
+ * - on an idempotent replay (same actor, organisation, action, key and
22
+ * input): the call is not run again and its output is not kept. The
23
+ * replay returns a receipt of the original call's own effects (records it
24
+ * wrote or deleted, completion), after the caller is authenticated as a
25
+ * member of the organisation and the action's policy is checked.
26
+ *
27
+ * Idempotency, execution, the checks, the audit record and the outbox events
28
+ * share one transaction. Anything that fails before or outside it, including
29
+ * unknown actions, invalid input and policies that cannot be compiled, is
30
+ * audited by the outer boundary.
31
+ */
32
+ import type {
33
+ Actor,
34
+ AnyAction,
35
+ AnyEntity,
36
+ AnyEvent,
37
+ AuditChange,
38
+ ReceiptEventRef,
39
+ ReceiptProvenance,
40
+ WrittenCounts,
41
+ AuditLineage,
42
+ AuditOutcome,
43
+ AuthorityChain,
44
+ AuthorityRecord,
45
+ ExecutionIdentity,
46
+ InvocationError,
47
+ InvocationReceipt,
48
+ ReplayEnvelope,
49
+ Surface,
50
+ TrackEvent,
51
+ } from "@eloxiv/contracts"
52
+ import {
53
+ declaredEntityNames,
54
+ RECEIPT_VERSION,
55
+ ActionFailed,
56
+ isNoOp,
57
+ exposedOn,
58
+ ApprovalRequired,
59
+ ConsentRequired,
60
+ CLIENT_VERSION_HEADER,
61
+ ClientOutdated,
62
+ Forbidden,
63
+ ProviderForbidden,
64
+ IdempotencyConflict,
65
+ InvalidInput,
66
+ isRecordKeyNonce,
67
+ newRecordKeyNonce,
68
+ recordKey,
69
+ Unauthenticated,
70
+ UnknownAction,
71
+ TrackEvent as TrackEventSchema,
72
+ ACTION_INVOKED_EVENT,
73
+ AUDIT_CHANGED_IDS,
74
+ } from "@eloxiv/contracts"
75
+ import { Cause, Context, Effect, Exit, Layer, Metric, Option, Schema } from "effect"
76
+ import { executeMake } from "./make/Execute.ts"
77
+ import { MakeRuntime, VERSION_BUSY } from "./make/Runtime.ts"
78
+ import { SqlClient, SqlError } from "effect/sql"
79
+ import { CLIENT_ADDRESS_HEADER } from "./surfaces/headers.ts"
80
+ import { Approvals, isAgentOrigin, type CallProvenance } from "./Approvals.ts"
81
+ import { Authority, bindDeferred, credentialLinks, deferrable, extend, recordOf, type Asserted } from "./Authority.ts"
82
+ import { Audit } from "./Audit.ts"
83
+ import { canonicalJson, sha256 } from "./Hash.ts"
84
+ import {
85
+ CallerAuthority,
86
+ CallerCredential,
87
+ Identity,
88
+ SYSTEM_ACTOR,
89
+ type CallSession,
90
+ type HeldCredential,
91
+ type ResolvedCall,
92
+ } from "./Identity.ts"
93
+ import { scopeAllows } from "./machine/Tokens.ts"
94
+ import { asModuleCode, isKernelProvided } from "./KernelModule.ts"
95
+ import {
96
+ MAX_EFFECT_DELAY_DAYS,
97
+ type EffectStatus,
98
+ type CallOrigin,
99
+ type ConnectionsApi,
100
+ type EffectOutcome,
101
+ type HandlerContext,
102
+ type ScheduleEffect,
103
+ } from "./Module.ts"
104
+ import { Connections } from "./connections/Connections.ts"
105
+ import { EFFECT_SCHEDULED, isExternal, operationOf, readsOnly } from "./connections/EffectKinds.ts"
106
+ import { CallActed } from "./CallActed.ts"
107
+
108
+ /**
109
+ * Test hooks of the invocation path (fault injection): `afterCommit` runs once a call's transaction has committed
110
+ * and before it is answered; a failure there is a call whose commit took effect but whose answer was lost, so it is
111
+ * answered `ActionFailed` with `effect: "unknown"`, as a failure while committing is.
112
+ */
113
+ export const InvocationHooks = Context.Reference<{
114
+ readonly afterCommit: (call: {
115
+ readonly action: string
116
+ readonly idempotencyKey: string | undefined
117
+ }) => Effect.Effect<void, ActionFailed>
118
+ }>("@eloxiv/kernel/InvocationHooks", { defaultValue: () => ({ afterCommit: () => Effect.void }) })
119
+ import { CONNECTIONS_MODULE as CONNECTIONS_MODULE_NAME } from "./connections/module.ts"
120
+ import { Notifications } from "./Notifications.ts"
121
+ import { toSql, type Pred } from "./policy/Compiler.ts"
122
+ import { Outbox } from "./Outbox.ts"
123
+ import { Policy } from "./policy/Policy.ts"
124
+ import type { PolicyRow } from "./policy/Row.ts"
125
+ import { scopedToDeclaration } from "./policy/Rls.ts"
126
+ import { readOnly } from "./db/ReadOnly.ts"
127
+ import { isLockConflictError, retryingConflicts } from "./db/Conflicts.ts"
128
+ import { CONSTRAINT_CONFLICT_MESSAGE, CONSTRAINT_CONFLICTS, sqlStateOf } from "./db/SqlState.ts"
129
+ import { readOwnView } from "./QueryViews.ts"
130
+ import { readReference } from "./records/References.ts"
131
+ import { handlerGate } from "./db/HandlerGate.ts"
132
+ import { Registry, type RegisteredAction } from "./Registry.ts"
133
+ import { WorkItems } from "./WorkItems.ts"
134
+ import { Sharing } from "./Sharing.ts"
135
+ import { sharingModule } from "./sharing/module.ts"
136
+ import { compareVersions, ReleaseSettings } from "./Release.ts"
137
+ import { Flags } from "./Flags.ts"
138
+ import { KernelActionHandlers } from "./KernelHandlers.ts"
139
+ import { Files } from "./files/Files.ts"
140
+ import { Ingestion } from "./ingestion/Ingestion.ts"
141
+ import { Settings } from "./Settings.ts"
142
+ import { Progress } from "./Progress.ts"
143
+ import { Analytics, ErrorCapture, invocationMetrics, type PendingEvent as PendingAnalytics } from "./Telemetry.ts"
144
+ import { Versioning, type EditGroup, type LoggedWrite } from "./Versioning.ts"
145
+
146
+ export type InvocationInput =
147
+ /** Already decoded by the surface (RPC, HttpApi, MCP). */
148
+ | { readonly decoded: unknown }
149
+ /** Raw JSON from the surface (agent tools, internal callers). */
150
+ | { readonly encoded: unknown }
151
+
152
+ interface InvocationRequestBase {
153
+ readonly action: string
154
+ readonly input: InvocationInput
155
+ readonly surface: Surface
156
+ readonly idempotencyKey?: string | undefined
157
+ /**
158
+ * Kernel surfaces only (sync's push, `/zero/mutate`), which decide a call's place in its client's order before
159
+ * calling, so that no stage that commits on its own (consent, business approval) runs for a call that may not:
160
+ *
161
+ * - `next`: the call is the client's next one. `advance` runs first inside the call's transaction, before its
162
+ * idempotency claim, and commits or rolls back with it; its failure (the order moved on meanwhile) refuses the
163
+ * call and nothing of it commits;
164
+ * - `replay`: the call was answered before. It skips consent and business approval and may only replay the
165
+ * receipt stored under its idempotency key; with none it is refused (`IdempotencyConflict`) and nothing runs.
166
+ *
167
+ * A MAKE action, whose writes commit in its module's own transaction (not the kernel's, which a sequence advances
168
+ * in), is never sequenced: such a call is refused.
169
+ */
170
+ readonly sequence?:
171
+ | { readonly kind: "next"; readonly advance: Effect.Effect<void, Forbidden> }
172
+ | { readonly kind: "replay" }
173
+ | undefined
174
+ }
175
+
176
+ export type InvocationRequest = InvocationRequestBase &
177
+ (
178
+ | {
179
+ /** Credentials travel as headers on every surface (bearer token or session cookie). */
180
+ readonly headers: Headers
181
+ readonly identity?: undefined
182
+ }
183
+ | {
184
+ /**
185
+ * Internal callers only (workflow steps, scheduled runs): act as a resolved execution identity. It is
186
+ * resolved again at every call and before a replay is released (a user must still be a member of the
187
+ * organisation), and the call still runs policy, approval, idempotency, audit and outbox. No surface
188
+ * accepts it.
189
+ */
190
+ readonly identity: ExecutionIdentity
191
+ readonly headers?: undefined
192
+ /**
193
+ * The agent runtime only: the call is the agent's, acting for the identity's user through this agent
194
+ * session (ActionConsent). The session must be valid and the user's, in the identity's organisation; the
195
+ * call is then agent-originated exactly as one made with the session's bearer token, so consent holds it
196
+ * the same way and session-scoped permissions apply.
197
+ */
198
+ readonly agentSession?: string | undefined
199
+ /**
200
+ * Kernel workflows only: this call executes the approved business-approval request with this id. The
201
+ * approval stage requires the request to be approved for exactly this requester, action and input.
202
+ */
203
+ readonly approval?: string | undefined
204
+ /** The agent runtime only: the run, step and tool call this call is made from (its audit lineage). */
205
+ readonly agentRun?: AuditLineage["agentRun"] | undefined
206
+ /** Durable work only: the execution (a workflow's, a schedule run's, a webhook delivery's) this call is a step of. */
207
+ readonly execution?: string | undefined
208
+ /**
209
+ * The agent runtime only: the edit group of the run the call is made from (the Versioning contract's agent
210
+ * edit groups): the run, and the conversation and message that started it (a sub-agent's, its parent's). The
211
+ * call's record versions and document autosaves are kept with it.
212
+ */
213
+ readonly editGroup?: EditGroup | undefined
214
+ /**
215
+ * Internal callers only: checked first inside the call's transaction, before its idempotency claim and
216
+ * its handler. A failure refuses the call and nothing of it commits. The agent runtime uses it to read
217
+ * (and hold, until the call commits) the run's cancellation, so no call runs after a cancellation commits.
218
+ */
219
+ readonly guard?: Effect.Effect<void, Forbidden> | undefined
220
+ /**
221
+ * The kernel only (a MAKE module's code calling another action): the call keeps the provenance of the call
222
+ * it is made from (its origin, and the agent session it came through), so it is held, audited and scoped
223
+ * exactly as that call is.
224
+ */
225
+ readonly provenance?: { readonly origin: CallOrigin; readonly session: CallSession | undefined } | undefined
226
+ }
227
+ )
228
+
229
+ export interface InvocationResult {
230
+ readonly invocationId: string
231
+ readonly replayed: boolean
232
+ /** The decoded action output (first execution only; a replay has none). */
233
+ readonly output: unknown
234
+ /** What every surface returns: `{ kind: "output", output }` or `{ kind: "replay", receipt }` (decoded). */
235
+ readonly envelope: unknown
236
+ /** The same envelope, JSON-encoded (what agent tools return). */
237
+ readonly encoded: unknown
238
+ /** The external effects the first execution scheduled (their ids); a replay's receipt names its own. */
239
+ readonly effects?: ReadonlyArray<string> | undefined
240
+ }
241
+
242
+ /**
243
+ * Checks an action runs before the invocation path holds a call for consent or business approval: what would make
244
+ * the call fail anyway (an install of a draft that does not match, or was never previewed), refused at once, so the
245
+ * caller (or their agent) learns it, and no one is asked to approve a call that cannot run. They read and change
246
+ * nothing; the handler checks again when the call runs.
247
+ */
248
+ /** One action's precheck: what would make the call fail anyway, refused before it is held. */
249
+ export type ActionPrecheck = (
250
+ actor: Actor,
251
+ input: unknown,
252
+ ) => Effect.Effect<void, InvalidInput | Forbidden | ActionFailed>
253
+
254
+ export class ActionPrechecks extends Context.Service<
255
+ ActionPrechecks,
256
+ { readonly checks: ReadonlyMap<string, ActionPrecheck> }
257
+ >()("@eloxiv/kernel/ActionPrechecks") {}
258
+
259
+ /** Who asks what they can reach: a surface's credentials, or an internal caller's execution identity. */
260
+ export type ReachRequest =
261
+ | { readonly surface: Surface; readonly headers: Headers; readonly identity?: undefined }
262
+ | {
263
+ readonly surface: Surface
264
+ readonly identity: ExecutionIdentity
265
+ readonly agentSession?: string | undefined
266
+ readonly headers?: undefined
267
+ }
268
+
269
+ /** What a caller can reach now: the actions `invoke` would not refuse before looking at their input. */
270
+ export interface Reach {
271
+ readonly actor: Actor
272
+ readonly origin: CallOrigin
273
+ /** Action names, sorted. */
274
+ readonly actions: ReadonlyArray<string>
275
+ }
276
+
277
+ export interface InvocationShape {
278
+ readonly invoke: (request: InvocationRequest) => Effect.Effect<InvocationResult, InvocationError>
279
+ /**
280
+ * The actions the caller can reach, by exactly the checks `invoke` makes before it reads the input: the
281
+ * credential (or execution identity) resolved now, the credential's scope, the action's agent tool group for
282
+ * an agent's call, and the action's policy for this actor (an action whose policy is constant false for the
283
+ * actor is hidden from it). Surfaces list only these (MCP `tools/list`, the caller's OpenAPI document, agent
284
+ * tools); `invoke` still refuses, and audits, a call to any other.
285
+ */
286
+ readonly reach: (request: ReachRequest) => Effect.Effect<Reach, Unauthenticated | Forbidden>
287
+ /**
288
+ * The receipt of the call of `action` its person made under the idempotency key `key` in the organisation, if one
289
+ * committed (the receipt store): what a client whose answer was lost asks to know the call ran. Read in the
290
+ * transaction `asserted` was asserted in (a defect elsewhere). None means none has committed yet, not that none will
291
+ * (a call still in flight commits its receipt with it).
292
+ */
293
+ readonly receiptFor: (asserted: Asserted, action: string, key: string) => Effect.Effect<InvocationReceipt | null>
294
+ }
295
+
296
+ interface PendingEvent {
297
+ readonly event: AnyEvent
298
+ readonly payload: unknown
299
+ }
300
+
301
+ /** A record, by entity Cedar type and primary key. */
302
+ interface RowRef {
303
+ readonly entity: string
304
+ readonly pk: string
305
+ }
306
+
307
+ /** The declared targets of a call, and those the caller may act on (all of them, unless best effort). */
308
+ interface Targets {
309
+ readonly entity: AnyEntity
310
+ readonly requested: ReadonlyArray<string>
311
+ readonly permitted: ReadonlySet<string>
312
+ readonly bestEffort: boolean
313
+ }
314
+
315
+ interface Completion {
316
+ readonly affected: number
317
+ readonly requested: number
318
+ readonly completion: "complete" | "partial"
319
+ }
320
+
321
+ /**
322
+ * The format of stored receipts. A receipt stored under any other format is not replayed (the retry is an
323
+ * IdempotencyConflict), so changing what a receipt holds invalidates old ones without a migration.
324
+ */
325
+ const RECEIPT_FORMAT = 2
326
+
327
+ /** The API transports: what a person's client calls on, and what an agent session's bearer may also be shown to. */
328
+ const API_SURFACES: ReadonlySet<Surface> = new Set<Surface>(["rpc", "http", "cli", "sync"])
329
+
330
+ /** Every string or number value in an encoded output (not object keys), as strings. */
331
+ const valuesIn = (value: unknown, into: Set<string> = new Set()): Set<string> => {
332
+ if (typeof value === "string" || typeof value === "number") into.add(String(value))
333
+ else if (Array.isArray(value)) for (const item of value) valuesIn(item, into)
334
+ else if (typeof value === "object" && value !== null) for (const item of Object.values(value)) valuesIn(item, into)
335
+ return into
336
+ }
337
+
338
+ const quoteIdent = (name: string) => `"${name.replaceAll('"', '""')}"`
339
+ const tableOf = (entity: AnyEntity) => `${quoteIdent(entity.table.schema)}.${quoteIdent(entity.table.name)}`
340
+ const pkColumn = (entity: AnyEntity) => (entity.columns as Record<string, string>)[entity.primaryKey]!
341
+
342
+ /**
343
+ * The input an action's handler receives. For an action predicting an insert (`optimistic.insert`), the input
344
+ * field naming the record's key holds the record's primary key instead: `recordKey` of the key the caller named
345
+ * (or of a fresh one), for the acting user and organisation and the entity written. A key that is not one is
346
+ * refused.
347
+ */
348
+ const withRecordKey = (
349
+ registered: RegisteredAction,
350
+ input: unknown,
351
+ actor: Actor,
352
+ ): { readonly ok: true; readonly input: unknown } | { readonly ok: false; readonly message: string } => {
353
+ const effect = registered.contract.optimistic
354
+ if (effect?.kind !== "insert" || registered.writes === undefined) return { ok: true, input }
355
+ const fields = input as Readonly<Record<string, unknown>>
356
+ const named = fields[effect.key]
357
+ if (named !== undefined && !isRecordKeyNonce(named)) {
358
+ return { ok: false, message: `${effect.key} must be 1 to 128 letters, digits, _ or -` }
359
+ }
360
+ return {
361
+ ok: true,
362
+ input: { ...fields, [effect.key]: recordKey(actor, registered.writes.cedarType, named ?? newRecordKeyNonce()) },
363
+ }
364
+ }
365
+
366
+ const hashOf = (value: unknown) =>
367
+ Effect.promise(() => {
368
+ try {
369
+ return sha256(canonicalJson(value))
370
+ } catch {
371
+ return Promise.resolve("unhashable")
372
+ }
373
+ })
374
+
375
+ export class Invocation extends Context.Service<Invocation, InvocationShape>()("@eloxiv/kernel/Invocation") {
376
+ static readonly layer = Layer.effect(
377
+ Invocation,
378
+ Effect.gen(function* () {
379
+ const sql = yield* SqlClient.SqlClient
380
+ const registry = yield* Registry
381
+ const invocationHooks = yield* InvocationHooks
382
+ const consentInstalled = registry.modules.some((module) => module.contract.name === "consent")
383
+ const identity = yield* Identity
384
+ const authority = yield* Authority
385
+ const policy = yield* Policy
386
+ const approvals = yield* Approvals
387
+ const audit = yield* Audit
388
+ const outbox = yield* Outbox
389
+ const workItems = yield* WorkItems
390
+ // What the kernel's own modules' handlers may use: every service built before the invocation path.
391
+ const kernelContext = yield* Effect.context()
392
+ const notifications = yield* Notifications
393
+ const sharing = yield* Sharing
394
+ const release = yield* Effect.serviceOption(ReleaseSettings)
395
+ const minClientVersion = Option.isSome(release) ? release.value.minClientVersion : undefined
396
+ const kernelHandlers = yield* Effect.serviceOption(KernelActionHandlers)
397
+ const settingsService = yield* Effect.serviceOption(Settings)
398
+ const filesService = yield* Effect.serviceOption(Files)
399
+ const ingestionService = yield* Effect.serviceOption(Ingestion)
400
+ const flagsService = yield* Effect.serviceOption(Flags)
401
+ const connectionsService = yield* Effect.serviceOption(Connections)
402
+ const progressService = yield* Effect.serviceOption(Progress)
403
+ const versioning = yield* Effect.serviceOption(Versioning)
404
+ const analytics = yield* Effect.serviceOption(Analytics)
405
+ const analyticsOn = Option.isSome(analytics) && analytics.value.enabled
406
+ const errors = yield* Effect.serviceOption(ErrorCapture)
407
+ const capture = (invocationId: string) =>
408
+ Option.isSome(errors) ? errors.value.capture("Defect", invocationId) : Effect.void
409
+ // MAKE modules (when the app installs the kernel's make module): looked up by name, run in the sandbox.
410
+ const makeRuntime = yield* Effect.serviceOption(MakeRuntime)
411
+ const prechecks = yield* Effect.serviceOption(ActionPrechecks)
412
+ const missing = (what: string) => Effect.die(new Error(`The kernel's ${what} service is not provided`))
413
+
414
+ /**
415
+ * A handler's Connections (`ctx.connections`): the kernel's own operations, run with the kernel's context and
416
+ * never the handler's, so their statements use a connection of their own (not the call's transaction, where
417
+ * the module's role could not read a Connection) and a provider request holds no transaction open. Connector
418
+ * code inside them still runs as module code (`Connections.capability`). Only the caller's own Connections.
419
+ */
420
+ const outside = <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<A, E> =>
421
+ Effect.updateContext(effect, () => kernelContext) as Effect.Effect<A, E>
422
+ /**
423
+ * The effects a call scheduled: recorded (with the event that starts their delivery) with the kernel's own
424
+ * writes, after the handler's are checked, in the call's transaction.
425
+ */
426
+ const effectBuffer = (
427
+ actor: Actor,
428
+ registered: RegisteredAction,
429
+ invocationId: string,
430
+ idempotencyKey: string | undefined,
431
+ asserted: Asserted,
432
+ ) => {
433
+ const pending: Array<{ readonly id: string; readonly effect: ScheduleEffect }> = []
434
+ /** Effects of the caller's to cancel, with the call's writes: in its transaction, so both commit or neither. */
435
+ const cancels: Array<string> = []
436
+ /**
437
+ * What a scheduled effect is delivered (and its module told) under: the call's authority, bound to the work it
438
+ * queues, which runs once; the delivery asserts it again, with the Connection it goes through as a link.
439
+ */
440
+ const authorityOf = () => bindDeferred(recordOf(asserted), "once")
441
+ /** The places taken in the call: each effect's name, or its number in the order it was scheduled. */
442
+ const places = new Set<string>()
443
+ let unnamed = 0
444
+ /**
445
+ * An effect's place in the call, taken synchronously before anything else runs (so effects scheduled
446
+ * concurrently never take the same one): its name, or the next number. A name given twice is refused.
447
+ */
448
+ const claim = (name: string | undefined) => {
449
+ const place = name === undefined ? `#${unnamed++}` : `name:${name}`
450
+ if (places.has(place)) return undefined
451
+ places.add(place)
452
+ return place
453
+ }
454
+ /**
455
+ * An effect's id: with an idempotency key, derived from it and the effect's place, so the call and its
456
+ * replays name the same effects (the receipt lists them) and no two effects of a call share one; without
457
+ * one, random.
458
+ */
459
+ const idOf = (place: string) =>
460
+ idempotencyKey === undefined
461
+ ? Effect.succeed(`eff_${crypto.randomUUID()}`)
462
+ : Effect.promise(() =>
463
+ sha256(canonicalJson([actor.orgId, actor.userId, registered.contract.name, idempotencyKey, place])),
464
+ ).pipe(Effect.map((hash) => `eff_${hash.slice(0, 40)}`))
465
+ const apply = Effect.forEach(
466
+ pending,
467
+ ({ id, effect }) =>
468
+ Effect.gen(function* () {
469
+ // One to run later waits like a rate-limited one (the claim refuses it before `not_before`), and says
470
+ // why while it waits (`waiting.reason`).
471
+ const later = effect.notBefore ?? null
472
+ yield* sql`INSERT INTO eloxiv.connection_effect (id, org_id, owner_id, module, action, invocation_id,
473
+ connection_id, capability, operation, input, on_done, authority, not_before, error)
474
+ VALUES (${id}, ${actor.orgId}, ${actor.userId}, ${registered.module.contract.name},
475
+ ${registered.contract.name}, ${invocationId}, ${effect.connectionId}, ${effect.capability},
476
+ ${effect.operation}, ${JSON.stringify(effect.input ?? null)}::jsonb, ${effect.onDone ?? null},
477
+ ${JSON.stringify(authorityOf())}::jsonb, ${later}::timestamptz,
478
+ ${later === null ? null : "Scheduled"})`
479
+ yield* outbox.publish({
480
+ invocationId,
481
+ type: EFFECT_SCHEDULED,
482
+ module: CONNECTIONS_MODULE_NAME,
483
+ orgId: actor.orgId,
484
+ payload: { effectId: id },
485
+ })
486
+ }),
487
+ { discard: true },
488
+ ).pipe(
489
+ Effect.orDie,
490
+ // The cancellations, last: the delivery's claim takes only a pending row under its lock, so each effect is
491
+ // either cancelled with this call or already running, and then the call fails and nothing of it commits.
492
+ Effect.andThen(
493
+ Effect.forEach(
494
+ cancels,
495
+ (effectId) =>
496
+ sql<{ id: string }>`
497
+ UPDATE eloxiv.connection_effect SET state = 'failed', error = 'Cancelled', input = NULL, result = NULL,
498
+ not_before = NULL, updated_at = now(), finished_at = now()
499
+ WHERE id = ${effectId} AND org_id = ${actor.orgId} AND owner_id = ${actor.userId} AND state = 'pending'
500
+ RETURNING id`.pipe(
501
+ Effect.orDie,
502
+ Effect.flatMap((rows) =>
503
+ rows.length > 0
504
+ ? Effect.void
505
+ : Effect.fail(
506
+ new InvalidInput({
507
+ message: `Effect ${effectId} started before the call could cancel it: nothing was changed`,
508
+ }),
509
+ ),
510
+ ),
511
+ ),
512
+ { discard: true },
513
+ ),
514
+ ),
515
+ )
516
+ return { pending, apply, claim, idOf, cancels }
517
+ }
518
+
519
+ const connectionsApi = (
520
+ actor: Actor,
521
+ registered: RegisteredAction,
522
+ buffer: ReturnType<typeof effectBuffer>,
523
+ asserted: Asserted,
524
+ /** Told before a direct operation that changes the account's data runs: a rollback does not undo it. */
525
+ acting: () => void,
526
+ ): ConnectionsApi => {
527
+ /** On the caller's behalf: only under the call's own capability (its transaction, its person). */
528
+ const held = authority.bound(asserted, actor)
529
+ const action = registered.contract.name
530
+ const declared: Readonly<Record<string, ReadonlyArray<string>>> = registered.contract.connections ?? {}
531
+ const allowed = (capability: string, operation: string) => declared[capability]?.includes(operation) === true
532
+ if (Option.isNone(connectionsService)) {
533
+ return {
534
+ list: () => missing("Connections"),
535
+ capability: () => missing("Connections"),
536
+ schedule: () => missing("Connections"),
537
+ effect: () => missing("Connections"),
538
+ cancel: () => missing("Connections"),
539
+ effects: () => missing("Connections"),
540
+ }
541
+ }
542
+ const service = connectionsService.value
543
+ // The module's handler uses it: a shared Connection must be granted to this module too.
544
+ const by = { userId: actor.userId, orgId: actor.orgId, module: registered.module.contract.name }
545
+ const refused = (connectionId: string, message: string) =>
546
+ Effect.fail(new ProviderForbidden({ message, connectionId, missingScopes: [], consent: null }))
547
+ return {
548
+ list: () => held.pipe(Effect.andThen(outside(service.usableBy(actor, registered.module.contract.name)))),
549
+ capability: (connectionId, name) =>
550
+ held
551
+ .pipe(Effect.andThen(outside(service.capability(connectionId, name, by))))
552
+ .pipe(
553
+ Effect.map(
554
+ (bound) =>
555
+ Object.fromEntries(
556
+ Object.entries(bound.operations).map(([operation, run]) => [
557
+ operation,
558
+ (input: unknown) =>
559
+ !allowed(name, operation)
560
+ ? refused(connectionId, `${action} does not declare ${name}.${operation} (connections)`)
561
+ : isExternal(name, operation)
562
+ ? refused(
563
+ connectionId,
564
+ `${name}.${operation} has effects others see: ${action} schedules it (ctx.connections.schedule)`,
565
+ )
566
+ : readsOnly(name, operation)
567
+ ? outside(run(input))
568
+ : Effect.sync(acting).pipe(Effect.andThen(outside(run(input)))),
569
+ ]),
570
+ ) as never,
571
+ ),
572
+ ),
573
+ schedule: (effect) =>
574
+ Effect.gen(function* () {
575
+ yield* held
576
+ // The effect's place first, before anything that waits.
577
+ if (effect.name !== undefined && !/^[A-Za-z0-9._:-]{1,100}$/u.test(effect.name)) {
578
+ return yield* new InvalidInput({ message: `An effect's name is letters, digits, ., _, : and -` })
579
+ }
580
+ const place = buffer.claim(effect.name)
581
+ if (place === undefined) {
582
+ return yield* new InvalidInput({ message: `${action} names two effects ${effect.name}` })
583
+ }
584
+ if (!allowed(effect.capability, effect.operation)) {
585
+ return yield* new Forbidden({
586
+ action,
587
+ message: `${action} does not declare ${effect.capability}.${effect.operation} (connections)`,
588
+ })
589
+ }
590
+ const operation = operationOf(effect.capability, effect.operation)!
591
+ const input = yield* Schema.decodeUnknownEffect(operation.input as Schema.Codec<unknown, unknown>)(
592
+ effect.input,
593
+ ).pipe(
594
+ Effect.mapError(
595
+ (e) => new InvalidInput({ message: `${effect.capability}.${effect.operation}: ${String(e)}` }),
596
+ ),
597
+ )
598
+ if (effect.notBefore !== undefined) {
599
+ const when = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/u.test(
600
+ effect.notBefore,
601
+ )
602
+ ? Date.parse(effect.notBefore)
603
+ : Number.NaN
604
+ if (Number.isNaN(when)) {
605
+ return yield* new InvalidInput({ message: "notBefore must be an ISO instant with its offset" })
606
+ }
607
+ if (when > Date.now() + MAX_EFFECT_DELAY_DAYS * 86_400_000) {
608
+ return yield* new InvalidInput({
609
+ message: `An effect can be scheduled at most ${MAX_EFFECT_DELAY_DAYS} days ahead`,
610
+ })
611
+ }
612
+ }
613
+ if (effect.onDone !== undefined) {
614
+ const done = registry.actions.get(effect.onDone)
615
+ if (done === undefined || done.module !== registered.module) {
616
+ return yield* Effect.die(
617
+ new Error(`${effect.onDone} is not an action of ${registered.module.contract.name}`),
618
+ )
619
+ }
620
+ }
621
+ // A Connection the caller may use from this module: refused now rather than failing after commit.
622
+ const usableNow = yield* outside(service.usableBy(actor, registered.module.contract.name))
623
+ if (!usableNow.some((c) => c.id === effect.connectionId)) {
624
+ return yield* new Forbidden({ action, message: "The Connection is not one you may use here" })
625
+ }
626
+ const id = yield* buffer.idOf(place)
627
+ if (buffer.pending.some((p) => p.id === id)) return yield* Effect.die(new Error(`Effect ${id} twice`))
628
+ buffer.pending.push({ id, effect: { ...effect, input } })
629
+ return { effectId: id }
630
+ }),
631
+ effect: (effectId) =>
632
+ held.pipe(
633
+ Effect.andThen(
634
+ outside(
635
+ sql<EffectOutcome>`
636
+ SELECT id, state, result, reconciled, told_at IS NOT NULL AS told, result_cleared AS cleared,
637
+ CASE WHEN state IN ('pending', 'running') THEN NULL ELSE error END AS error,
638
+ CASE WHEN state = 'pending' AND not_before IS NOT NULL
639
+ THEN json_build_object('reason', coalesce(error, 'RateLimited'), 'retryAt',
640
+ to_char(not_before AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'))
641
+ END AS waiting
642
+ FROM eloxiv.connection_effect
643
+ WHERE id = ${effectId} AND org_id = ${actor.orgId} AND owner_id = ${actor.userId}`.pipe(Effect.orDie),
644
+ ),
645
+ ),
646
+ Effect.map(([row]) => row),
647
+ ),
648
+ // Committed at once on the kernel's own connection: the claim (`Effects.ts`) takes only a `pending` row
649
+ // under its lock, so an effect is either cancelled here or run there, never both.
650
+ effects: (filter) =>
651
+ held.pipe(
652
+ Effect.andThen(
653
+ outside(
654
+ sql<EffectStatus>`
655
+ SELECT id, module, action, capability, operation, state, attempts,
656
+ CASE WHEN state = 'pending' AND not_before IS NOT NULL
657
+ THEN json_build_object('reason', coalesce(error, 'RateLimited'), 'retryAt',
658
+ to_char(not_before AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'))
659
+ END AS waiting,
660
+ CASE WHEN state IN ('pending', 'running') THEN NULL ELSE error END AS error, reported,
661
+ to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "createdAt",
662
+ to_char(finished_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "finishedAt"
663
+ FROM eloxiv.connection_effect
664
+ WHERE org_id = ${actor.orgId} AND owner_id = ${actor.userId}
665
+ AND (${filter?.ids === undefined} OR id = ANY(${[...(filter?.ids ?? [])]}::text[]))
666
+ ORDER BY created_at DESC, id LIMIT 100`.pipe(Effect.orDie),
667
+ ),
668
+ ),
669
+ ),
670
+ // Whether it can be cancelled now (the caller's, pending); the cancellation itself is written with the call's
671
+ // own writes, in its transaction (`effectBuffer`), so a call that fails or rolls back cancels nothing.
672
+ cancel: (effectId) =>
673
+ held.pipe(
674
+ Effect.andThen(
675
+ outside(
676
+ sql<{ id: string }>`
677
+ SELECT id FROM eloxiv.connection_effect
678
+ WHERE id = ${effectId} AND org_id = ${actor.orgId} AND owner_id = ${actor.userId} AND state = 'pending'`.pipe(
679
+ Effect.orDie,
680
+ ),
681
+ ),
682
+ ),
683
+ Effect.map((rows) => {
684
+ if (rows.length === 0) return false
685
+ if (!buffer.cancels.includes(effectId)) buffer.cancels.push(effectId)
686
+ return true
687
+ }),
688
+ ),
689
+ }
690
+ }
691
+
692
+ /**
693
+ * Version skew (the Release contract): a write from a client that declares a version older than the
694
+ * minimum (or one that is not a version) is refused before anything else runs. Clients that declare no
695
+ * version, internal callers and read-only actions are not gated.
696
+ */
697
+ const checkClientVersion = (action: string, request: InvocationRequest) => {
698
+ if (minClientVersion === undefined || request.headers === undefined) return Effect.void
699
+ const declared = request.headers.get(CLIENT_VERSION_HEADER)
700
+ if (declared === null) return Effect.void
701
+ const order = compareVersions(declared, minClientVersion)
702
+ if (order !== undefined && order >= 0) return Effect.void
703
+ return Effect.fail(
704
+ new ClientOutdated({
705
+ action,
706
+ clientVersion: declared,
707
+ minClientVersion,
708
+ message:
709
+ `This client (version ${declared}) is older than the oldest version this server accepts writes from ` +
710
+ `(${minClientVersion}). Reload or upgrade the app, then try again; reading still works.`,
711
+ }),
712
+ )
713
+ }
714
+
715
+ const entitiesByTable = new Map<string, AnyEntity>()
716
+ for (const { entity } of registry.entities.values())
717
+ entitiesByTable.set(`${entity.table.schema}.${entity.table.name}`, entity)
718
+
719
+ interface AuditContext {
720
+ invocationId: string
721
+ action: string
722
+ surface: Surface
723
+ inputHash: string
724
+ idempotencyKey: string | undefined
725
+ actor: Actor | undefined
726
+ /** The client address, when the call came over HTTP. */
727
+ address?: string | undefined
728
+ /** What a kernel action asked to keep on its audit record (see `KernelHandlerApi`). */
729
+ detail?: unknown
730
+ /** Where the call came from, once decided (telemetry). */
731
+ origin?: CallOrigin
732
+ /** Analytics events the call asked for: queued once it commits (the Telemetry contract). */
733
+ events: Array<PendingAnalytics>
734
+ /** Where the call came from and what it acts under, once its identity resolved (the Audit contract). */
735
+ lineage?: AuditLineage
736
+ /** What a successful call changed, by entity. */
737
+ changes?: ReadonlyArray<AuditChange>
738
+ /**
739
+ * What a failure of the call may have left (ActionFailed's `effect`): a direct provider operation that changes
740
+ * data ran (not undone by a rollback), or the call's transaction began committing.
741
+ */
742
+ acted?: "provider" | "setup" | "committing" | undefined
743
+ }
744
+
745
+ /**
746
+ * The call's lineage for its audit record, from what the kernel decided: never a header but the client version
747
+ * (bounded), never the person's sign-in session (`deferrable` drops it) and never a person's id.
748
+ */
749
+ const lineageOf = (
750
+ request: InvocationRequest,
751
+ origin: CallOrigin,
752
+ credential: ResolvedCall["credential"],
753
+ chain: AuthorityChain,
754
+ basis: { readonly request?: string | undefined; readonly permission?: string | undefined } | undefined,
755
+ ): AuditLineage => ({
756
+ origin,
757
+ credential: request.identity !== undefined ? "identity" : credential.kind,
758
+ // The person's membership is the record's own actor and organisation: not repeated (with their id) here.
759
+ authority: deferrable(chain)
760
+ .filter((link) => link.kind !== "membership")
761
+ .map((link) => ({ kind: link.kind, id: link.id })),
762
+ agentRun: request.identity !== undefined ? (request.agentRun ?? null) : null,
763
+ approval: request.identity !== undefined ? (request.approval ?? null) : null,
764
+ consent:
765
+ basis === undefined || (basis.request === undefined && basis.permission === undefined)
766
+ ? null
767
+ : { request: basis.request ?? null, permission: basis.permission ?? null },
768
+ clientVersion: request.headers?.get(CLIENT_VERSION_HEADER)?.slice(0, 64) ?? null,
769
+ })
770
+
771
+ /**
772
+ * What an untargeted writing call wrote (backlog 2): the records of its declared entities it inserted, and those it
773
+ * updated that it did not insert. Only rows it wrote: one row-level security kept it from is not in the log.
774
+ */
775
+ const writtenOf = (
776
+ actor: Actor,
777
+ registered: RegisteredAction,
778
+ log: ReadonlyArray<LoggedWrite>,
779
+ ): Effect.Effect<WrittenCounts | undefined> =>
780
+ Effect.gen(function* () {
781
+ const contract = registered.contract
782
+ if (contract.writes === undefined || contract.target !== undefined) return undefined
783
+ const declared = new Set(
784
+ declaredEntityNames(contract).map((name) => registered.module.contract.entities[name]),
785
+ )
786
+ const byEntity = new Map<AnyEntity, { inserted: Set<string>; updated: Set<string> }>()
787
+ for (const write of log) {
788
+ const entity = entitiesByTable.get(`${write.schema}.${write.table}`)
789
+ if (entity === undefined || !declared.has(entity) || write.pk === null) continue
790
+ const entry = byEntity.get(entity) ?? { inserted: new Set<string>(), updated: new Set<string>() }
791
+ if (write.op === "INSERT") entry.inserted.add(write.pk)
792
+ else if (write.op === "UPDATE") entry.updated.add(write.pk)
793
+ byEntity.set(entity, entry)
794
+ }
795
+ // Only rows the caller may read: an action may write wider than its caller reads (row-level security lets a
796
+ // statement through on the action's permission or the read permission), and a count of the rest would
797
+ // say how many records there are that they cannot see. A read policy that cannot be compiled counts none.
798
+ let inserted = 0
799
+ let updated = 0
800
+ for (const [entity, entry] of byEntity) {
801
+ for (const pk of entry.inserted) entry.updated.delete(pk)
802
+ const readAction = { type: registered.cedarAction.type, id: "read" }
803
+ const read = yield* (
804
+ registered.module.make !== undefined && Option.isSome(makeRuntime)
805
+ ? makeRuntime.value.filterFor(registered.module, actor, readAction, entity, "old")
806
+ : policy.filterFor(actor, readAction, entity, "old")
807
+ ).pipe(Effect.orElseSucceed((): Pred => ({ kind: "false" })))
808
+ inserted += (yield* satisfying(registered, entity, read, [...entry.inserted], false).pipe(Effect.orDie))
809
+ .size
810
+ updated += (yield* satisfying(registered, entity, read, [...entry.updated], false).pipe(Effect.orDie)).size
811
+ }
812
+ return { inserted, updated }
813
+ })
814
+
815
+ /** Where a call came from, for its receipt: ids only (Receipt.ts `ReceiptProvenance`). */
816
+ const provenanceFor = (
817
+ request: InvocationRequest,
818
+ invocationId: string,
819
+ key: string,
820
+ origin: CallOrigin,
821
+ ): ReceiptProvenance => {
822
+ const runId = request.identity !== undefined ? (request.agentRun?.runId ?? null) : null
823
+ const causationId =
824
+ request.identity !== undefined ? (request.approval ?? runId ?? request.execution ?? null) : null
825
+ return { correlationId: causationId ?? invocationId, causationId, runId, idempotencyKey: key, origin }
826
+ }
827
+
828
+ /** What the call's write log changed, by entity: counts and ids (bounded), never values. */
829
+ const changesOf = (log: ReadonlyArray<LoggedWrite>): ReadonlyArray<AuditChange> => {
830
+ const byEntity = new Map<string, { inserted: number; updated: number; deleted: number; ids: Set<string> }>()
831
+ for (const write of log) {
832
+ const entity = entitiesByTable.get(`${write.schema}.${write.table}`)
833
+ if (entity === undefined) continue
834
+ const entry = byEntity.get(entity.cedarType) ?? { inserted: 0, updated: 0, deleted: 0, ids: new Set() }
835
+ if (write.op === "INSERT") entry.inserted++
836
+ else if (write.op === "DELETE") entry.deleted++
837
+ else entry.updated++
838
+ if (write.pk !== null) entry.ids.add(write.pk)
839
+ byEntity.set(entity.cedarType, entry)
840
+ }
841
+ return [...byEntity].map(([entity, e]) => ({
842
+ entity,
843
+ inserted: e.inserted,
844
+ updated: e.updated,
845
+ deleted: e.deleted,
846
+ ids: [...e.ids].slice(0, AUDIT_CHANGED_IDS),
847
+ truncated: e.ids.size > AUDIT_CHANGED_IDS,
848
+ }))
849
+ }
850
+
851
+ const writeAudit = (
852
+ context: AuditContext,
853
+ outcome: AuditOutcome,
854
+ errorTag: string | undefined,
855
+ completion?: Completion,
856
+ ) =>
857
+ // A refusal or failure of a caller the kernel could not identify (no credential, an action it does not have,
858
+ // input that does not decode) is bounded per action and address (Audit.denied); an action name it does not
859
+ // have is counted under one name, so a caller cannot spread its records over names it makes up.
860
+ (outcome === "denied" || outcome === "failed") && context.actor === undefined
861
+ ? audit.denied({
862
+ invocationId: context.invocationId,
863
+ action: context.action,
864
+ bucket: registry.actions.has(context.action) ? context.action : "(an action the kernel does not have)",
865
+ outcome,
866
+ surface: context.surface,
867
+ actorUserId: null,
868
+ orgId: null,
869
+ errorTag: errorTag ?? "Unknown",
870
+ address: context.address,
871
+ inputHash: context.inputHash,
872
+ idempotencyKey: context.idempotencyKey,
873
+ })
874
+ : audit.record({
875
+ invocationId: context.invocationId,
876
+ action: context.action,
877
+ surface: context.surface,
878
+ actorUserId: context.actor?.userId ?? null,
879
+ orgId: context.actor?.orgId ?? null,
880
+ outcome,
881
+ inputHash: context.inputHash,
882
+ idempotencyKey: context.idempotencyKey ?? null,
883
+ errorTag: errorTag ?? null,
884
+ affected: completion?.affected ?? null,
885
+ requested: completion?.requested ?? null,
886
+ completion: completion?.completion ?? null,
887
+ ...(context.detail === undefined ? {} : { detail: context.detail }),
888
+ ...(context.lineage === undefined ? {} : { lineage: context.lineage }),
889
+ ...(outcome === "succeeded" && context.changes !== undefined && context.changes.length > 0
890
+ ? { changes: context.changes }
891
+ : {}),
892
+ })
893
+
894
+ const forbidden = (action: string, message: string) => new Forbidden({ action, message })
895
+
896
+ /** The actions a permission of the vocabulary names (for `permission:<id>` scopes). */
897
+ const permissionActions = (permission: string) => registry.permissions.get(permission)?.actions
898
+
899
+ /**
900
+ * The action's compiled filter for `entity`; a policy that cannot be compiled denies (fail closed). Like
901
+ * row-level security, the action's policy grants nothing on an entity it does not declare, and an
902
+ * organisation-wide action only records of the acting organisation.
903
+ */
904
+ const filterFor = (
905
+ actor: Actor,
906
+ registered: RegisteredAction,
907
+ entity: AnyEntity | undefined,
908
+ row: PolicyRow = "old",
909
+ ) =>
910
+ // A MAKE module's actions are compiled from its own policy alone.
911
+ (registered.module.make !== undefined && Option.isSome(makeRuntime)
912
+ ? makeRuntime.value.filterFor(registered.module, actor, registered.cedarAction, entity, row)
913
+ : policy.filterFor(actor, registered.cedarAction, entity, row)
914
+ ).pipe(
915
+ Effect.map((pred) =>
916
+ entity === undefined
917
+ ? pred
918
+ : scopedToDeclaration(registered.module.contract, registered.contract, entity, pred, actor.orgId),
919
+ ),
920
+ Effect.mapError((e) =>
921
+ forbidden(registered.contract.name, `Policy cannot be compiled into a filter: ${e.message}`),
922
+ ),
923
+ )
924
+
925
+ /**
926
+ * Run `effect` as the module's runtime role, where row-level security applies, and make sure it is
927
+ * still that role afterwards (a handler that switched roles is refused).
928
+ */
929
+ const asModule = <A, E>(registered: RegisteredAction, effect: Effect.Effect<A, E>) =>
930
+ Effect.gen(function* () {
931
+ yield* sql.unsafe(`SET LOCAL ROLE ${quoteIdent(registered.module.role)}`).pipe(Effect.orDie)
932
+ const result = yield* effect
933
+ const [role] = yield* sql<{ role: string }>`SELECT current_user AS role`.pipe(Effect.orDie)
934
+ if (role?.role !== registered.module.role) {
935
+ return yield* forbidden(registered.contract.name, "The handler changed its database role")
936
+ }
937
+ yield* sql.unsafe(`RESET ROLE`).pipe(Effect.orDie)
938
+ return result
939
+ })
940
+
941
+ /** The `pks` of `entity` that exist and satisfy `pred`, optionally locked. Runs as the module's role. */
942
+ const satisfying = (
943
+ registered: RegisteredAction,
944
+ entity: AnyEntity,
945
+ pred: Pred,
946
+ pks: ReadonlyArray<string>,
947
+ lock: boolean,
948
+ ) =>
949
+ Effect.gen(function* () {
950
+ if (pks.length === 0) return new Set<string>()
951
+ const filter = toSql(pred, entity, "r", 2, policy.referencesOf(entity))
952
+ const rows = yield* asModule(
953
+ registered,
954
+ sql
955
+ .unsafe<{ pk: string }>(
956
+ `SELECT r.${quoteIdent(pkColumn(entity))}::text AS pk FROM ${tableOf(entity)} r
957
+ WHERE r.${quoteIdent(pkColumn(entity))}::text = ANY($1) AND ${filter.text}${lock ? " FOR UPDATE OF r" : ""}`,
958
+ [[...new Set(pks)], ...filter.params] as Array<any>,
959
+ )
960
+ .pipe(Effect.orDie),
961
+ )
962
+ return new Set(rows.map((r) => r.pk))
963
+ })
964
+
965
+ /** Do all `pks` of `entity` exist and satisfy `pred`? */
966
+ const allSatisfy = (
967
+ registered: RegisteredAction,
968
+ entity: AnyEntity,
969
+ pred: Pred,
970
+ pks: ReadonlyArray<string>,
971
+ lock: boolean,
972
+ ) => satisfying(registered, entity, pred, pks, lock).pipe(Effect.map((found) => found.size === new Set(pks).size))
973
+
974
+ const targetEntity = (registered: RegisteredAction) =>
975
+ registered.contract.target === undefined
976
+ ? undefined
977
+ : (registered.module.contract.entities as Record<string, AnyEntity>)[registered.contract.target.entity]
978
+
979
+ /** The declared target ids: the target field holds one id or a list of ids. */
980
+ const targetIds = (registered: RegisteredAction, input: unknown): ReadonlyArray<string> | undefined => {
981
+ const field = registered.contract.target?.field
982
+ if (field === undefined) return undefined
983
+ const value = (input as Record<string, unknown> | null)?.[field]
984
+ const one = (v: unknown) => (typeof v === "string" || typeof v === "number" ? String(v) : undefined)
985
+ if (Array.isArray(value)) {
986
+ const ids = value.map(one).filter((id) => id !== undefined)
987
+ return ids.length === value.length ? [...new Set(ids)] : undefined
988
+ }
989
+ const id = one(value)
990
+ return id === undefined ? undefined : [id]
991
+ }
992
+
993
+ /**
994
+ * Before the handler: lock the declared targets the caller may act on. An exact action fails unless that
995
+ * is every target; a best-effort action continues with the permitted subset.
996
+ */
997
+ const authoriseTargets = (actor: Actor, registered: RegisteredAction, input: unknown) =>
998
+ Effect.gen(function* () {
999
+ const entity = targetEntity(registered)
1000
+ if (entity === undefined) return undefined
1001
+ const requested = targetIds(registered, input)
1002
+ if (requested === undefined)
1003
+ return yield* new InvalidInput({ message: `Missing target ${registered.contract.target!.field}` })
1004
+ const pred = yield* filterFor(actor, registered, entity)
1005
+ const permitted = yield* satisfying(registered, entity, pred, requested, true)
1006
+ const bestEffort = registered.contract.bestEffort
1007
+ if (!bestEffort && permitted.size !== requested.length) {
1008
+ return yield* forbidden(registered.contract.name, "The caller may not act on this record")
1009
+ }
1010
+ // What row-level security admits as an exact action's inserts and updates (`eloxiv_ctx.is_target`).
1011
+ if (!bestEffort && requested.length > 0) {
1012
+ yield* sql
1013
+ .unsafe(`INSERT INTO eloxiv.invocation_target (pk) SELECT unnest($1::text[]) ON CONFLICT DO NOTHING`, [
1014
+ [...requested],
1015
+ ] as Array<any>)
1016
+ .pipe(Effect.orDie)
1017
+ }
1018
+ return { entity, requested, permitted, bestEffort } satisfies Targets
1019
+ })
1020
+
1021
+ /**
1022
+ * After the handler: authorise every row the transaction wrote, and check the declared targets were
1023
+ * affected exactly (best effort: report how many were).
1024
+ */
1025
+ const authoriseWrites = (
1026
+ actor: Actor,
1027
+ registered: RegisteredAction,
1028
+ targets: Targets | undefined,
1029
+ revertDeletes?: ReadonlySet<string>,
1030
+ ) =>
1031
+ Effect.gen(function* () {
1032
+ const name = registered.contract.name
1033
+ const log = yield* sql<LoggedWrite>`
1034
+ DELETE FROM eloxiv.invocation_write WHERE xid = pg_current_xact_id()
1035
+ RETURNING id, table_schema AS schema, table_name AS "table", pk, op, row`.pipe(Effect.orDie)
1036
+ const byEntity = new Map<AnyEntity, Set<string>>()
1037
+ const affected = new Set<string>()
1038
+ const inserted = new Set<string>()
1039
+ // In the order the writes were made (a revert's delete allowance is taken by the first delete of its row).
1040
+ for (const write of [...log].sort((a, b) => Number(a.id) - Number(b.id))) {
1041
+ const entity = entitiesByTable.get(`${write.schema}.${write.table}`)
1042
+ if (entity === undefined || write.pk === null) {
1043
+ return yield* forbidden(name, `Write to ${write.schema}.${write.table}, which no entity contract governs`)
1044
+ }
1045
+ const isTarget = targets !== undefined && targets.entity === entity
1046
+ if (isTarget && !targets.permitted.has(write.pk)) {
1047
+ return yield* forbidden(name, "The action changed a record other than its declared targets")
1048
+ }
1049
+ if (write.op === "DELETE") {
1050
+ // Without a target, only the DELETE each `ctx.history.revert` issued (of a record its group created): the
1051
+ // exact write-log entry it made, which is gone if a savepoint rolled it back. Any other delete is refused.
1052
+ if (!isTarget && revertDeletes?.has(String(write.id)) !== true) {
1053
+ return yield* forbidden(name, "The action deleted a record it was not authorised to act on")
1054
+ }
1055
+ affected.add(write.pk)
1056
+ continue
1057
+ }
1058
+ if (isTarget) affected.add(write.pk)
1059
+ if (write.op === "INSERT") inserted.add(`${entity.cedarType}\u0000${write.pk}`)
1060
+ byEntity.set(entity, (byEntity.get(entity) ?? new Set()).add(write.pk))
1061
+ }
1062
+ // Records this call inserted that still exist (candidates for the receipt's `created`).
1063
+ const created: Array<RowRef> = []
1064
+ for (const [entity, pks] of byEntity) {
1065
+ // Rows inserted and then deleted again in the same call no longer exist; only surviving rows are checked.
1066
+ const surviving = (yield* asModule(
1067
+ registered,
1068
+ sql
1069
+ .unsafe<{ pk: string }>(
1070
+ `SELECT r.${quoteIdent(pkColumn(entity))}::text AS pk FROM ${tableOf(entity)} r WHERE r.${quoteIdent(pkColumn(entity))}::text = ANY($1)`,
1071
+ [[...pks]] as Array<any>,
1072
+ )
1073
+ .pipe(Effect.orDie),
1074
+ )).map((r) => r.pk)
1075
+ // The rows as the action left them: its policy for the new row.
1076
+ const pred = yield* filterFor(actor, registered, entity, "new")
1077
+ if (!(yield* allSatisfy(registered, entity, pred, surviving, false))) {
1078
+ return yield* forbidden(name, "A record written by the action does not satisfy the action's policy")
1079
+ }
1080
+ for (const pk of surviving) {
1081
+ if (inserted.has(`${entity.cedarType}\u0000${pk}`)) created.push({ entity: entity.cedarType, pk })
1082
+ }
1083
+ }
1084
+ let completion: Completion | undefined
1085
+ if (targets !== undefined) {
1086
+ if (!targets.bestEffort && affected.size !== targets.requested.length) {
1087
+ return yield* forbidden(name, "The action did not affect its declared target")
1088
+ }
1089
+ completion = {
1090
+ affected: affected.size,
1091
+ requested: targets.requested.length,
1092
+ completion: affected.size === targets.requested.length ? "complete" : "partial",
1093
+ }
1094
+ }
1095
+ return { created, completion, log }
1096
+ })
1097
+
1098
+ /** The database refused the statement for lack of privilege or a row-level security check. */
1099
+ const refused = (e: unknown) =>
1100
+ SqlError.isSqlError(e) &&
1101
+ (e.reason._tag === "AuthorizationError" ||
1102
+ // read_only_sql_transaction: a write inside a read-only scope (a read-only action or a view read).
1103
+ (e.reason.cause as { readonly code?: unknown } | undefined)?.code === "25006")
1104
+
1105
+ /** The identity step: a surface's credentials, or an internal caller's execution identity (resolved now). */
1106
+ const authenticateRequest = (
1107
+ request: ReachRequest | InvocationRequest,
1108
+ ): Effect.Effect<
1109
+ {
1110
+ readonly actor: Actor
1111
+ readonly credential: ResolvedCall["credential"]
1112
+ readonly session: CallSession | undefined
1113
+ },
1114
+ Unauthenticated | Forbidden
1115
+ > => {
1116
+ // Work asked for with a scoped credential stays within its scope (work with none recorded never acts), and the
1117
+ // system's work within the scope it was narrowed to (an agent run's tools).
1118
+ const kept = request.identity?.kind === "user" ? request.identity.authority : undefined
1119
+ const scope =
1120
+ request.identity?.kind === "system"
1121
+ ? request.identity.scope == null
1122
+ ? null
1123
+ : [...request.identity.scope]
1124
+ : typeof kept === "object" && kept.scope !== null
1125
+ ? [...kept.scope]
1126
+ : null
1127
+ return request.identity !== undefined
1128
+ ? request.agentSession !== undefined
1129
+ ? identity
1130
+ .resolveAgentSession(request.agentSession, request.identity)
1131
+ .pipe(Effect.map((resolved) => ({ ...resolved, credential: { ...resolved.credential, scope } })))
1132
+ : identity.resolve(request.identity).pipe(
1133
+ Effect.map((actor) => ({
1134
+ actor,
1135
+ credential: { kind: "session" as const, id: null, scope },
1136
+ // Work an agent set up keeps the agent's origin (and consent binds to its session).
1137
+ session:
1138
+ request.identity?.kind === "user" && request.identity.agentSession !== undefined
1139
+ ? { id: `agent:${request.identity.agentSession}`, agent: true }
1140
+ : undefined,
1141
+ })),
1142
+ )
1143
+ : identity.authenticateCall(request.headers, request.surface)
1144
+ }
1145
+
1146
+ /**
1147
+ * The chain of authorities a call acts under (Authority): for deferred work, the chain it recorded and the agent
1148
+ * session it is made through; for a call with a credential, the credential and the chain the session it is was
1149
+ * issued under (a device turn's).
1150
+ */
1151
+ const chainOf = (
1152
+ request: InvocationRequest | ReachRequest,
1153
+ credential: ResolvedCall["credential"],
1154
+ ): AuthorityChain | "unrecorded" => {
1155
+ if (request.identity !== undefined) {
1156
+ // A person's identity that does not say what it acts under is work queued before chains were recorded (or
1157
+ // a caller that forgot to say): it fails closed. Trusted kernel code that acts with no link says so.
1158
+ const kept = request.identity.kind === "user" ? (request.identity.authority ?? "unrecorded") : undefined
1159
+ if (kept === "unrecorded") return "unrecorded"
1160
+ const through: AuthorityChain =
1161
+ request.agentSession === undefined ? [] : [{ kind: "agent-session", id: request.agentSession }]
1162
+ return extend(kept?.chain ?? [], through)
1163
+ }
1164
+ return credentialLinks(credential)
1165
+ }
1166
+
1167
+ /** Where a call comes from, decided by the kernel from the surface and the credential: never by a header. */
1168
+ const originOf = (request: ReachRequest | InvocationRequest, session: CallSession | undefined): CallOrigin =>
1169
+ // An agent surface (agent tools, MCP) or an agent session makes the call an agent's, whatever identity it was
1170
+ // given: `AgentTools.execute({ caller: { identity } })` with no agent session is still an agent's call, so the
1171
+ // handler's `ctx.origin` agrees with what consent and the tool groups treat as one (`agentCall`), and guards
1172
+ // that refuse agents (consent and business-approval decisions) hold for it.
1173
+ isAgentOrigin(request.surface, session)
1174
+ ? "agent"
1175
+ : // A call a MAKE module's code makes inside another call keeps that call's origin.
1176
+ request.identity !== undefined && "provenance" in request && request.provenance !== undefined
1177
+ ? request.provenance.origin
1178
+ : request.identity !== undefined && request.agentSession === undefined
1179
+ ? // A person's own call, deferred (an approval executing it), stays theirs.
1180
+ request.identity.kind === "user" && request.identity.origin === "person"
1181
+ ? "person"
1182
+ : "system"
1183
+ : "person"
1184
+
1185
+ /**
1186
+ * What deferring the call must keep (a business approval records it and executes the call with it): its
1187
+ * origin, the reference it was the agent's under, its credential's scope and its whole chain of authorities.
1188
+ */
1189
+ const provenanceOf = (
1190
+ request: InvocationRequest,
1191
+ origin: CallOrigin,
1192
+ session: CallSession | undefined,
1193
+ credential: ResolvedCall["credential"],
1194
+ chain: AuthorityChain,
1195
+ ): CallProvenance => {
1196
+ const agent = agentCall(request, origin, session)
1197
+ const reference =
1198
+ session?.agentSessionId ??
1199
+ (session?.id.startsWith("agent:") === true ? session.id.slice("agent:".length) : session?.id) ??
1200
+ `surface:${request.surface}`
1201
+ return {
1202
+ origin: agent ? "agent" : origin,
1203
+ ...(agent ? { agentSession: reference } : {}),
1204
+ // What an approval executes later rests on: never the call's own session (`deferrable`).
1205
+ authority: { scope: credential.scope === null ? null : [...credential.scope], chain: deferrable(chain) },
1206
+ // An agent run's call keeps its edit group: its changes, once approved, belong to the run like any other.
1207
+ ...(request.identity !== undefined && request.editGroup !== undefined
1208
+ ? { editGroup: request.editGroup }
1209
+ : {}),
1210
+ }
1211
+ }
1212
+
1213
+ /** Is this an agent's call (what consent holds, and disabled tool groups refuse)? */
1214
+ const agentCall = (
1215
+ request: ReachRequest | InvocationRequest,
1216
+ origin: CallOrigin,
1217
+ session: CallSession | undefined,
1218
+ ) => origin === "agent" || isAgentOrigin(request.surface, session)
1219
+
1220
+ /**
1221
+ * Is the action offered to this caller on this surface? Its exposure on the surface, and for an agent session's
1222
+ * credential on an API transport (a browser agent's WebMCP bearer over HTTP or RPC) also its agent exposure: what
1223
+ * the agent's tool list hides, the agent's own credential does not reach through another transport.
1224
+ */
1225
+ const offered = (contract: AnyAction, surface: Surface, session: CallSession | undefined) =>
1226
+ exposedOn(contract, surface) &&
1227
+ (session?.agent !== true || !API_SURFACES.has(surface) || contract.exposure.agent)
1228
+
1229
+ const toolGroupDisabled = (registered: RegisteredAction) =>
1230
+ `Agents may not call this action: its tool group ${registered.disabledForAgents} is disabled in this app`
1231
+
1232
+ /**
1233
+ * Does the action's policy deny `actor` whatever the input: a constant FALSE for records as they stand and as
1234
+ * the action would leave them (or, for an action that declares no entity, anything but a constant TRUE)?
1235
+ */
1236
+ const deniedFor = (actor: Actor, registered: RegisteredAction) =>
1237
+ Effect.gen(function* () {
1238
+ const primary = registered.writes ?? targetEntity(registered)
1239
+ const pred = yield* filterFor(actor, registered, primary)
1240
+ if (primary === undefined) return pred.kind !== "true"
1241
+ return pred.kind === "false" && (yield* filterFor(actor, registered, primary, "new")).kind === "false"
1242
+ })
1243
+
1244
+ const reach = (request: ReachRequest) =>
1245
+ Effect.gen(function* () {
1246
+ const { actor, credential, session } = yield* authenticateRequest(request)
1247
+ const origin = originOf(request, session)
1248
+ const agent = agentCall(request, origin, session)
1249
+ const actions: Array<string> = []
1250
+ const consider = (registered: RegisteredAction) =>
1251
+ Effect.gen(function* () {
1252
+ const name = registered.contract.name
1253
+ if (!scopeAllows(credential.scope, name, permissionActions)) return
1254
+ if (!offered(registered.contract, request.surface, session)) return
1255
+ if (agent && registered.disabledForAgents !== undefined) return
1256
+ // A policy that cannot be compiled denies the call; it hides the action too.
1257
+ const denied = yield* deniedFor(actor, registered).pipe(Effect.orElseSucceed(() => true))
1258
+ if (!denied) actions.push(name)
1259
+ })
1260
+ for (const registered of registry.actions.values()) yield* consider(registered)
1261
+ // The MAKE modules installed in the caller's organisation, at the version each runs now (one read: a
1262
+ // rollback shows at once), by the same checks (`invoke` looks them up by name and refuses another
1263
+ // organisation's). Never one named as an app action, and never another organisation's.
1264
+ if (Option.isSome(makeRuntime)) {
1265
+ for (const registered of yield* makeRuntime.value.actionsIn(actor.orgId)) {
1266
+ if (registry.actions.has(registered.contract.name)) continue
1267
+ if (registered.module.make?.orgId !== actor.orgId) continue
1268
+ yield* consider(registered)
1269
+ }
1270
+ }
1271
+ return { actor, origin, actions: actions.sort() } satisfies Reach
1272
+ }).pipe(Effect.withSpan("Invocation.reach", { attributes: { surface: request.surface } }))
1273
+
1274
+ const execute = (
1275
+ registered: RegisteredAction,
1276
+ actor: Actor,
1277
+ invocationId: string,
1278
+ input: unknown,
1279
+ origin: CallOrigin,
1280
+ context: AuditContext,
1281
+ asserted: Asserted,
1282
+ held: HeldCredential,
1283
+ ) =>
1284
+ Effect.gen(function* () {
1285
+ const name = registered.contract.name
1286
+ const events: Array<PendingEvent> = []
1287
+ // This attempt's deletes by `ctx.history.revert` (their write-log entries), and the group each record it
1288
+ // changed was reverted for: a run again after a conflict starts with none.
1289
+ const revertDeletes = new Set<string>()
1290
+ const revertGroups = new Map<string, { readonly conversationId: string; readonly messageId: string | null }>()
1291
+ // Work items and notifications the handler asks for are applied after its writes are checked.
1292
+ const items = workItems.buffer(registered.module.contract.name, actor.orgId, asserted)
1293
+ const notify = notifications.buffer(actor.orgId)
1294
+ // External effects the handler schedules: recorded with the kernel's writes, delivered after commit.
1295
+ const effects = effectBuffer(actor, registered, invocationId, context.idempotencyKey, asserted)
1296
+ // The sharing operations for this actor; only the kernel's own sharing module may find a record's managers.
1297
+ const sharingApi = sharing.forActor(actor, registered.module.role)
1298
+ const { managersOf: _managers, askManagers: _ask, ...publicSharing } = sharingApi
1299
+ // The role the handler runs as: its module's, or the kernel's own for a kernel module's handlers.
1300
+ const handlerRole =
1301
+ registered.kernel && !(Option.isSome(kernelHandlers) && kernelHandlers.value.find(registered.module, name))
1302
+ ? undefined
1303
+ : registered.module.role
1304
+ const moduleName = registered.module.contract.name
1305
+ const progress = Option.isSome(progressService)
1306
+ ? progressService.value.buffer(actor, moduleName, invocationId)
1307
+ : undefined
1308
+ // A module's events are declared in its manifest and checked here (the telemetry module relays clients'
1309
+ // declared `client.*` events); they are queued once the call commits.
1310
+ const track = (event: TrackEvent) =>
1311
+ Effect.gen(function* () {
1312
+ const decoded = yield* Schema.decodeUnknownEffect(TrackEventSchema)(event).pipe(
1313
+ Effect.mapError(
1314
+ () => new InvalidInput({ message: "An analytics event is an event name and properties" }),
1315
+ ),
1316
+ )
1317
+ if (Option.isNone(analytics)) return
1318
+ const prepared = yield* analytics.value.prepare(moduleName, actor, decoded)
1319
+ if (prepared !== null && actor.userId !== SYSTEM_ACTOR) context.events.push(prepared)
1320
+ })
1321
+ // The handler's own statements wait while a helper switches the connection's role (db-tx.md, guarantee 2).
1322
+ const gate = handlerGate(sql)
1323
+ const ungated: HandlerContext = {
1324
+ actor,
1325
+ invocationId,
1326
+ sql,
1327
+ queryView: (id, limit) => readOwnView(sql, registered.module, id, limit),
1328
+ // A module emits only the events its manifest declares, encoded by the declared payload schema: never
1329
+ // another module's (which would start that module's triggers as if it had emitted them).
1330
+ emit: (event, payload) => {
1331
+ const declared = (Object.values(registered.module.contract.events) as ReadonlyArray<AnyEvent>).find(
1332
+ (e) => e.type === event.type,
1333
+ )
1334
+ return declared === undefined
1335
+ ? Effect.die(
1336
+ new Error(`Module ${moduleName} emitted ${event.type}, an event its manifest does not declare`),
1337
+ )
1338
+ : Effect.sync(() => void events.push({ event: declared, payload }))
1339
+ },
1340
+ origin,
1341
+ authority: recordOf(asserted),
1342
+ workItems: items.api,
1343
+ notify: notify.api,
1344
+ settings: Option.isSome(settingsService) ? settingsService.value.api : { get: () => missing("Settings") },
1345
+ flags: Option.isSome(flagsService) ? flagsService.value.api(actor) : { isEnabled: () => missing("Flags") },
1346
+ sharing: registered.module === sharingModule ? sharingApi : publicSharing,
1347
+ files: Option.isSome(filesService)
1348
+ ? filesService.value.forHandler(actor, registered.module.contract.name, handlerRole, invocationId)
1349
+ : { attach: () => missing("Files"), list: () => missing("Files") },
1350
+ ingestion: Option.isSome(ingestionService)
1351
+ ? ingestionService.value.forHandler(
1352
+ actor,
1353
+ registered.module.contract.name,
1354
+ handlerRole,
1355
+ invocationId,
1356
+ asserted,
1357
+ )
1358
+ : {
1359
+ submit: () => missing("Ingestion"),
1360
+ current: () => missing("Ingestion"),
1361
+ basis: () => missing("Ingestion"),
1362
+ collect: () => missing("Ingestion"),
1363
+ collection: () => missing("Ingestion"),
1364
+ datasets: {
1365
+ stage: () => missing("Ingestion"),
1366
+ rows: () => missing("Ingestion"),
1367
+ query: () => missing("Ingestion"),
1368
+ list: () => missing("Ingestion"),
1369
+ drop: () => missing("Ingestion"),
1370
+ },
1371
+ runs: {
1372
+ open: () => missing("Ingestion"),
1373
+ claim: () => missing("Ingestion"),
1374
+ complete: () => missing("Ingestion"),
1375
+ report: () => missing("Ingestion"),
1376
+ inventory: () => missing("Ingestion"),
1377
+ finish: () => missing("Ingestion"),
1378
+ },
1379
+ },
1380
+ progress: progress?.api ?? {
1381
+ start: () => Effect.succeed(`pt_${crypto.randomUUID()}`),
1382
+ update: () => Effect.void,
1383
+ complete: () => Effect.void,
1384
+ fail: () => Effect.void,
1385
+ },
1386
+ analytics: { track },
1387
+ history: Option.isSome(versioning)
1388
+ ? versioning.value.api(sql, registered.module, actor, name, {
1389
+ deleted: (writeId) => void revertDeletes.add(writeId),
1390
+ reverted: (record, group) => void revertGroups.set(record, group),
1391
+ })
1392
+ : {
1393
+ restore: () => Effect.fail(new InvalidInput({ message: "Record history is not available" })),
1394
+ revert: () => Effect.fail(new InvalidInput({ message: "Record history is not available" })),
1395
+ },
1396
+ connections: connectionsApi(
1397
+ actor,
1398
+ registered,
1399
+ effects,
1400
+ asserted,
1401
+ () => void (context.acted ??= "provider"),
1402
+ ),
1403
+ // Read as the owner's role under its row-level security, filtered by its read policy for the caller,
1404
+ // in one statement (the handler's role never changes between its own); the entity is the registered one
1405
+ // of that Cedar type, never the table the value passed names.
1406
+ references: {
1407
+ read: (entity, id) =>
1408
+ readReference(sql, registry, policy, actor, entity.cedarType, id) as Effect.Effect<any>,
1409
+ },
1410
+ }
1411
+ // Only the helpers that switch the connection's role (or assert on it as the kernel) are run exclusively. The
1412
+ // rest buffer until the handler returns (notify, progress, analytics), read through definer functions
1413
+ // (settings, flags), or read as the handler's own role or in one statement (queryView, references): they stay
1414
+ // outside the gate, so a handler that calls them while it reads a stream of its own never waits on it.
1415
+ const base: HandlerContext = {
1416
+ ...ungated,
1417
+ workItems: gate.api(ungated.workItems),
1418
+ sharing: gate.api(ungated.sharing),
1419
+ connections: gate.api(ungated.connections),
1420
+ files: gate.api(ungated.files),
1421
+ ingestion: gate.api({
1422
+ ...ungated.ingestion,
1423
+ runs: gate.api(ungated.ingestion.runs),
1424
+ datasets: gate.api(ungated.ingestion.datasets),
1425
+ }),
1426
+ history: gate.api(ungated.history),
1427
+ }
1428
+ // A read-only action changes nothing: its SQL runs in a read-only scope, and what the context would buffer to
1429
+ // apply after the handler (events, work items, notifications, progress, external effects) is refused, so a
1430
+ // read never leaves a side effect, nor one per retry of it (a read batch's reader retries lost answers).
1431
+ const readOnlyRefusal = (what: string) => () =>
1432
+ Effect.die(new Error(`${name} is read-only: it may not ${what}`))
1433
+ const ctx: HandlerContext = !registered.contract.hints.readOnly
1434
+ ? base
1435
+ : {
1436
+ ...base,
1437
+ emit: readOnlyRefusal("emit events"),
1438
+ workItems: {
1439
+ ...base.workItems,
1440
+ put: readOnlyRefusal("put work items"),
1441
+ close: readOnlyRefusal("close work items"),
1442
+ retitle: readOnlyRefusal("retitle work items"),
1443
+ },
1444
+ notify: { ...base.notify, send: readOnlyRefusal("send notifications") },
1445
+ progress: {
1446
+ start: readOnlyRefusal("start progress"),
1447
+ update: readOnlyRefusal("report progress"),
1448
+ complete: readOnlyRefusal("report progress"),
1449
+ fail: readOnlyRefusal("report progress"),
1450
+ },
1451
+ connections: { ...base.connections, schedule: readOnlyRefusal("schedule external effects") },
1452
+ }
1453
+ const denied = (e: unknown) =>
1454
+ forbidden(
1455
+ name,
1456
+ `The database refused a change the action is not authorised for: ${
1457
+ SqlError.isSqlError(e) && e.reason.cause instanceof Error ? e.reason.cause.message : String(e)
1458
+ }`,
1459
+ )
1460
+ // Execute as the module's runtime role: its own schema only, plain DML, under row-level security. An
1461
+ // action hinted read-only runs its handler in a read-only scope, so the hint surfaces publish holds.
1462
+ //
1463
+ // The handler bound when the registry was built. The kernel's own modules served by kernel services
1464
+ // (`KernelActionHandlers`: query, settings, flags) run the kernel's function, as the module's role. The
1465
+ // kernel's own modules defined with `defineKernelModule` are kernel code on the kernel's tables: they run
1466
+ // as the kernel's role, with the kernel's services, and authorise what they touch themselves. Every other
1467
+ // handler is module code and runs without the kernel's services.
1468
+ const kernelHandler = Option.isSome(kernelHandlers)
1469
+ ? kernelHandlers.value.find(registered.module, name)
1470
+ : undefined
1471
+ const kernelModule = kernelHandler === undefined && registered.kernel
1472
+ const call = Effect.suspend(() => registered.handler(input, ctx)) as Effect.Effect<
1473
+ unknown,
1474
+ ActionFailed | InvalidInput | Forbidden
1475
+ >
1476
+ const handler =
1477
+ kernelHandler !== undefined
1478
+ ? kernelHandler(input, ctx, {
1479
+ auditDetail: (detail) => Effect.sync(() => void (context.detail = detail)),
1480
+ asserted,
1481
+ credential: held,
1482
+ })
1483
+ : kernelModule
1484
+ ? Effect.provide(call, kernelContext).pipe(
1485
+ Effect.provideService(CallerCredential, held),
1486
+ Effect.provideService(CallerAuthority, asserted),
1487
+ // A kernel module's handler about to commit outside the call (MAKE's setup): it may have acted.
1488
+ Effect.provideService(CallActed, { mark: Effect.sync(() => void (context.acted ??= "setup")) }),
1489
+ )
1490
+ : asModuleCode(call)
1491
+ const run = kernelModule ? <A, E>(_: RegisteredAction, effect: Effect.Effect<A, E>) => effect : asModule
1492
+ // A kernel handler's unexpected failure is logged, never returned: its message may carry what the
1493
+ // kernel holds (a token, a secret), which the caller must not see.
1494
+ const unexpected = (defect: unknown) => capture(invocationId).pipe(Effect.andThen(unexpectedFailure(defect)))
1495
+ const unexpectedFailure = (defect: unknown) =>
1496
+ // A constraint conflict may name a record the caller cannot read: a fixed message, the detail logged.
1497
+ sqlStateOf(defect, CONSTRAINT_CONFLICTS) !== undefined
1498
+ ? Effect.logWarning(`${name} hit a constraint`, defect).pipe(
1499
+ Effect.as(new ActionFailed({ action: name, message: CONSTRAINT_CONFLICT_MESSAGE })),
1500
+ )
1501
+ : kernelModule
1502
+ ? Effect.logError(`The kernel's ${name} handler failed unexpectedly`, defect).pipe(
1503
+ Effect.as(
1504
+ new ActionFailed({
1505
+ action: name,
1506
+ message: `The action failed unexpectedly (invocation ${invocationId})`,
1507
+ }),
1508
+ ),
1509
+ )
1510
+ : Effect.succeed(new ActionFailed({ action: name, message: String(defect) }))
1511
+ const output = yield* run(
1512
+ registered,
1513
+ gate.around(registered.contract.hints.readOnly ? readOnly(sql, handler) : handler).pipe(
1514
+ Effect.mapError((e) => (refused(e) ? denied(e) : e)),
1515
+ // A lock conflict the database reported to a statement of the handler's (a deadlock, a serialisation
1516
+ // failure) aborted the call's transaction: it stays a defect, which the transaction's retry runs again
1517
+ // (`retryingConflicts`), rather than becoming the handler's failure.
1518
+ Effect.catchDefect((defect): Effect.Effect<never, ActionFailed | Forbidden> =>
1519
+ isLockConflictError(defect)
1520
+ ? Effect.die(defect)
1521
+ : refused(defect)
1522
+ ? Effect.fail(denied(defect))
1523
+ : Effect.flatMap(unexpected(defect), Effect.fail),
1524
+ ),
1525
+ ),
1526
+ )
1527
+ const kernelWrites = Effect.all([items.apply, notify.apply, progress?.apply ?? Effect.void, effects.apply], {
1528
+ discard: true,
1529
+ }).pipe(Effect.mapError((e) => new ActionFailed({ action: name, message: e.message })))
1530
+ return {
1531
+ output,
1532
+ events,
1533
+ kernelWrites,
1534
+ effectIds: effects.pending.map((p) => p.id),
1535
+ revertDeletes,
1536
+ revertGroups,
1537
+ }
1538
+ })
1539
+
1540
+ /** Run `effect` outside the current transaction: on its own connection, committed on its own. */
1541
+ const outsideTransaction = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
1542
+ Effect.updateContext(
1543
+ effect,
1544
+ (context: Context.Context<R>) => Context.omit(sql.transactionService)(context) as never,
1545
+ )
1546
+ /** Run `effect` in a kernel transaction of its own (a database failure of the transaction is a defect). */
1547
+ const inTransaction = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
1548
+ sql.withTransaction(effect).pipe(
1549
+ Effect.catchIf(
1550
+ (e): e is SqlError.SqlError => SqlError.isSqlError(e),
1551
+ (e) => Effect.die(e),
1552
+ ),
1553
+ )
1554
+
1555
+ /**
1556
+ * Execute a MAKE module's action (`make/Execute.ts`): its code in the sandbox, its statements on a session of
1557
+ * its own runtime role, and everything the call leaves (its rows, its idempotency claim and receipt, its audit
1558
+ * record, its events and its one-time consent's use) committed once, in that session's transaction. It runs
1559
+ * inside the kernel transaction that holds the call's authority (asserted, its links locked, its consent
1560
+ * locked), which commits after it; its other kernel statements run outside that one, each on its own (a setting
1561
+ * is read in a transaction of its own), and the expiry check and the guard (`InvocationRequest.guard`) are held
1562
+ * from just before its commit until it is answered. `nested`: called by another MAKE call's code (it runs only
1563
+ * if an interpreter is free at once). `taken`: the idempotency key is another call's, answered as a replay.
1564
+ */
1565
+ const executeMakeAction = (
1566
+ registered: RegisteredAction,
1567
+ actor: Actor,
1568
+ context: AuditContext,
1569
+ decoded: unknown,
1570
+ encoded: unknown,
1571
+ key: string | undefined,
1572
+ provenance: {
1573
+ readonly origin: CallOrigin
1574
+ readonly session: CallSession | undefined
1575
+ /** Where the call came from, for its receipt (with a key only). */
1576
+ readonly receipt?: ReceiptProvenance | undefined
1577
+ },
1578
+ options: { readonly nested: boolean; readonly guard: Effect.Effect<void, Forbidden> | undefined },
1579
+ /** What the call acts under: the read-only calls its code makes act under it too (Authority). */
1580
+ acting: AuthorityRecord,
1581
+ /**
1582
+ * The call's authority, asserted in the kernel transaction that encloses the module's (its links held until
1583
+ * that one commits), and the one-time consents it uses up, recorded in the module's transaction.
1584
+ */
1585
+ held: { readonly asserted: Asserted; readonly consumes: ReadonlyArray<string> },
1586
+ ) =>
1587
+ Effect.gen(function* () {
1588
+ const runtime = Option.getOrThrow(makeRuntime)
1589
+ const module = registered.module
1590
+ const contract = registered.contract
1591
+ const name = contract.name
1592
+ const session = yield* runtime.session(module)
1593
+ const events: Array<PendingEvent> = []
1594
+ const identity: ExecutionIdentity =
1595
+ actor.userId === SYSTEM_ACTOR
1596
+ ? { kind: "system", orgId: actor.orgId, ...(acting.scope === null ? {} : { scope: [...acting.scope] }) }
1597
+ : { kind: "user", userId: actor.userId, orgId: actor.orgId, authority: acting }
1598
+ const failedWith = (e: InvocationError) =>
1599
+ e._tag === "Forbidden"
1600
+ ? e
1601
+ : new ActionFailed({ action: name, message: `${e._tag}: ${"message" in e ? e.message : ""}` })
1602
+ const encodeOutput = (value: unknown) =>
1603
+ asModuleCode(Schema.encodeUnknownEffect(contract.output as Schema.Codec<unknown, unknown>)(value))
1604
+ let finished: InvocationResult | undefined
1605
+ const outcome = yield* executeMake({
1606
+ module,
1607
+ action: contract,
1608
+ actor,
1609
+ origin: provenance.origin,
1610
+ invocationId: context.invocationId,
1611
+ input: decoded,
1612
+ encodedInput: encoded,
1613
+ session,
1614
+ kernel: sql,
1615
+ autonomous: outsideTransaction,
1616
+ filterFor: (entity, row) => filterFor(actor, registered, entity, row),
1617
+ references: runtime.referencesOf(module),
1618
+ emit: (event, payload) => Effect.sync(() => void events.push({ event, payload })),
1619
+ // Another module's read-only action, through this same path, as the caller and with the call's own
1620
+ // provenance (its origin and agent session), in a read-only transaction of its own: it writes nothing, so
1621
+ // whether this call then commits changes nothing of it. Never a kernel module's action (governance:
1622
+ // approvals, consent, MAKE itself, sharing, settings ...), nor one that needs the person's consent.
1623
+ call: (action, input) =>
1624
+ Effect.gen(function* () {
1625
+ const target = registry.actions.get(action) ?? (yield* runtime.lookup(action))
1626
+ if (target === undefined) return yield* forbidden(name, `No action ${action}`)
1627
+ if (isKernelProvided(target.module) || target.kernel) {
1628
+ return yield* forbidden(name, `${action} is the kernel's; a module's code cannot call it`)
1629
+ }
1630
+ if (!target.contract.hints.readOnly) {
1631
+ return yield* forbidden(name, `${action} writes; a module's code calls only read-only actions`)
1632
+ }
1633
+ if (target.contract.consent) {
1634
+ return yield* forbidden(name, `${action} needs the person's consent; a module's code cannot call it`)
1635
+ }
1636
+ const called = yield* outsideTransaction(
1637
+ invoke({ action, input: { encoded: input }, surface: "internal", identity, provenance }),
1638
+ ).pipe(Effect.mapError(failedWith))
1639
+ return called.encoded
1640
+ }),
1641
+ // A setting, for the caller, read as the module's runtime role (as a built-in handler reads it), in a
1642
+ // kernel transaction of its own with the call's invocation context.
1643
+ setting: (key) =>
1644
+ Option.isNone(settingsService)
1645
+ ? Effect.fail(new ActionFailed({ action: name, message: "This app has no settings" }))
1646
+ : inTransaction(
1647
+ Effect.gen(function* () {
1648
+ yield* sql`INSERT INTO eloxiv.invocation_context (actor, org, action)
1649
+ VALUES (${actor.userId}, ${actor.orgId}, ${name})`.pipe(Effect.orDie)
1650
+ yield* sql.unsafe(`SET LOCAL ROLE ${quoteIdent(module.role)}`).pipe(Effect.orDie)
1651
+ const value = yield* settingsService.value.api.get(key)
1652
+ yield* sql.unsafe(`RESET ROLE`).pipe(Effect.orDie)
1653
+ yield* sql`DELETE FROM eloxiv.invocation_context WHERE xid = pg_current_xact_id()`.pipe(
1654
+ Effect.orDie,
1655
+ )
1656
+ return value
1657
+ }),
1658
+ ),
1659
+ nested: options.nested,
1660
+ // The guard (an agent run's cancellation) holds what it reads from just before the commit until the
1661
+ // commit is answered, in a kernel transaction: a failure of it rolls the call back.
1662
+ // Before the module's commit, the check at commit (Authority.confirm): the call's links that expire still
1663
+ // hold by the clock and its session is not revoked (their rows are held since the assertion, by the
1664
+ // enclosing kernel transaction, and the revocation's lock from here to that transaction's commit).
1665
+ atCommit: (commit) =>
1666
+ inTransaction(
1667
+ authority.confirm(held.asserted).pipe(
1668
+ Effect.andThen(options.guard ?? Effect.void),
1669
+ // From here the module's transaction commits: a failure now may come after it took effect.
1670
+ Effect.andThen(Effect.sync(() => void (context.acted ??= "committing"))),
1671
+ Effect.andThen(commit),
1672
+ ),
1673
+ ),
1674
+ commit: {
1675
+ idempotency: key === undefined ? undefined : { key, requestHash: context.inputHash },
1676
+ consumes: held.consumes,
1677
+ finish: (result) =>
1678
+ Effect.gen(function* () {
1679
+ const completion = result.completion
1680
+ // Best effort: the kernel, not the handler, reports what was affected.
1681
+ const output =
1682
+ contract.bestEffort && completion !== undefined
1683
+ ? { ...(result.output as object), ...completion }
1684
+ : result.output
1685
+ const encodedOutput = yield* encodeOutput(output).pipe(
1686
+ Effect.mapError(
1687
+ (e) => new ActionFailed({ action: name, message: `The output does not encode: ${String(e)}` }),
1688
+ ),
1689
+ )
1690
+ const named = valuesIn(encodedOutput)
1691
+ // Its events are written by the module's commit (`make_finish`), which then adds to this receipt a
1692
+ // reference to every outbox row the invocation committed (migration 0235), as an ordinary call's.
1693
+ const receipt: InvocationReceipt = {
1694
+ version: RECEIPT_VERSION,
1695
+ action: name,
1696
+ invocationId: context.invocationId,
1697
+ outcome: "succeeded",
1698
+ targets: targetIds(registered, decoded) ?? [],
1699
+ created: result.created
1700
+ .filter((r) => r.entity === registered.writes?.cedarType && named.has(r.pk))
1701
+ .map((r) => r.pk),
1702
+ ...(isNoOp(encodedOutput) ? { noop: encodedOutput } : {}),
1703
+ completion: contract.bestEffort ? (completion ?? null) : null,
1704
+ ...(provenance.receipt === undefined ? {} : { provenance: provenance.receipt }),
1705
+ }
1706
+ const encodedEvents: Array<{ type: string; payload: unknown }> = []
1707
+ for (const { event, payload } of events) {
1708
+ const encodedPayload = yield* asModuleCode(
1709
+ Schema.encodeUnknownEffect(event.payload as Schema.Codec<unknown, unknown>)(payload),
1710
+ ).pipe(Effect.mapError((e) => new ActionFailed({ action: name, message: String(e) })))
1711
+ encodedEvents.push({ type: event.type, payload: encodedPayload })
1712
+ }
1713
+ finished = {
1714
+ invocationId: context.invocationId,
1715
+ replayed: false,
1716
+ output,
1717
+ envelope: { kind: "output", output },
1718
+ encoded: { kind: "output", output: encodedOutput },
1719
+ }
1720
+ return {
1721
+ surface: context.surface,
1722
+ inputHash: context.inputHash,
1723
+ idempotencyKey: key ?? null,
1724
+ completion: completion ?? null,
1725
+ receipt: key === undefined ? null : receipt,
1726
+ receiptFormat: RECEIPT_FORMAT,
1727
+ events: encodedEvents,
1728
+ }
1729
+ }),
1730
+ },
1731
+ })
1732
+ if (outcome.kind === "taken") return { kind: "taken" } as const
1733
+ return { kind: "done", result: finished! } as const
1734
+ })
1735
+
1736
+ const body = (request: InvocationRequest, context: AuditContext) =>
1737
+ Effect.gen(function* () {
1738
+ const registered =
1739
+ registry.actions.get(request.action) ??
1740
+ (Option.isSome(makeRuntime) ? yield* makeRuntime.value.lookup(request.action) : undefined)
1741
+ if (!registered)
1742
+ return yield* new UnknownAction({ action: request.action, message: `No action ${request.action}` })
1743
+ const contract = registered.contract
1744
+ if (!contract.hints.readOnly) yield* checkClientVersion(contract.name, request)
1745
+
1746
+ // Normalise input to both forms; hash the canonical encoded form.
1747
+ // The action's schemas are the module's: module code, like its handler. Every problem of the input is
1748
+ // reported at once, so a caller (an agent above all) fixes them in one retry rather than one per retry.
1749
+ const decodeInput = (value: unknown) =>
1750
+ asModuleCode(
1751
+ Schema.decodeUnknownEffect(contract.input as Schema.Codec<unknown, unknown>)(value, { errors: "all" }),
1752
+ )
1753
+ const encodeInput = (value: unknown) =>
1754
+ asModuleCode(Schema.encodeUnknownEffect(contract.input as Schema.Codec<unknown, unknown>)(value))
1755
+ const invalid = (e: unknown) => new InvalidInput({ message: String(e) })
1756
+ const decoded =
1757
+ "decoded" in request.input
1758
+ ? request.input.decoded
1759
+ : yield* decodeInput(request.input.encoded).pipe(Effect.mapError(invalid))
1760
+ const encoded = yield* encodeInput(decoded).pipe(Effect.mapError(invalid))
1761
+ context.inputHash = yield* hashOf(encoded)
1762
+
1763
+ // 1. Identity: credentials from a surface, or an internal caller's execution identity (resolved now).
1764
+ const authenticate = authenticateRequest(request)
1765
+ // An execution identity names who the call acts as even when resolving it is refused (a requester who
1766
+ // left the organisation): the audit record says whose call was refused.
1767
+ if (request.identity !== undefined) {
1768
+ context.actor = {
1769
+ userId: request.identity.kind === "user" ? request.identity.userId : SYSTEM_ACTOR,
1770
+ orgId: request.identity.orgId,
1771
+ email: "",
1772
+ roles: [],
1773
+ groups: [],
1774
+ permissions: [],
1775
+ }
1776
+ }
1777
+ const authenticated = yield* authenticate
1778
+ const { actor, credential } = authenticated
1779
+ const session =
1780
+ request.identity !== undefined && request.provenance !== undefined
1781
+ ? request.provenance.session
1782
+ : authenticated.session
1783
+ context.actor = actor
1784
+ // Deferred or indirect work acts only while every authority it depends on holds (asserted again, with the
1785
+ // rows locked, inside the call's transaction): refused here before any stage records anything.
1786
+ const recorded = chainOf(request, credential)
1787
+ // Recurring work (a schedule's run) may not rest on a one-time consent.
1788
+ const recurringWork =
1789
+ request.identity?.kind === "user" &&
1790
+ typeof request.identity.authority === "object" &&
1791
+ request.identity.authority.recurring === true
1792
+ yield* authority.check({ chain: recorded, who: actor, scope: credential.scope, recurring: recurringWork })
1793
+ const chain: AuthorityChain = recorded === "unrecorded" ? [] : recorded
1794
+ // A MAKE module is installed for the organisation that made and approved it, and serves only its members.
1795
+ const make = registered.module.make
1796
+ if (make !== undefined && make.orgId !== actor.orgId) {
1797
+ return yield* forbidden(contract.name, "This module is not installed in your organisation")
1798
+ }
1799
+ // Where the call comes from, decided by the kernel: never by a header.
1800
+ const origin = originOf(request, session)
1801
+ context.origin = origin
1802
+ context.lineage = lineageOf(request, origin, credential, chain, undefined)
1803
+ // A machine credential's scope narrows what it may call; it never widens the policy.
1804
+ if (!scopeAllows(credential.scope, contract.name, permissionActions)) {
1805
+ return yield* forbidden(contract.name, "The credential is not scoped to this action")
1806
+ }
1807
+ // A surface the action is not offered on (its exposure) does not run it, whoever calls.
1808
+ if (!exposedOn(contract, request.surface)) {
1809
+ return yield* forbidden(contract.name, `This action is not offered on the ${request.surface} surface`)
1810
+ }
1811
+ // An agent session's credential reaches only what the agent surface offers, on whichever API transport.
1812
+ if (!offered(contract, request.surface, session)) {
1813
+ return yield* forbidden(contract.name, "This action is not offered to agents")
1814
+ }
1815
+ // An agent tool group the app disabled: no agent reaches its actions, on any surface.
1816
+ if (agentCall(request, origin, session) && registered.disabledForAgents !== undefined) {
1817
+ return yield* forbidden(contract.name, toolGroupDisabled(registered))
1818
+ }
1819
+
1820
+ // 2. Policy: a constant FALSE (for records as they stand and as the action would leave them) denies
1821
+ // before anything runs.
1822
+ const denies = (current: Actor) => deniedFor(current, registered)
1823
+ if (yield* denies(actor)) return yield* forbidden(contract.name, "Policy denies this action")
1824
+
1825
+ // 3. Consent or business approval. Without the consent module (allowed only for the kernel-provided
1826
+ // scheduler's actions), an agent's call that needs consent cannot be held for the person: it is refused.
1827
+ if (contract.consent && !consentInstalled && agentCall(request, origin, session)) {
1828
+ return yield* forbidden(
1829
+ contract.name,
1830
+ "An agent's call to this action needs the person's consent, and this app has no consent module",
1831
+ )
1832
+ }
1833
+ // A sequenced call (sync's push) never reaches a MAKE action: its writes commit in its module's own
1834
+ // transaction, not the kernel's one the sequence advances in.
1835
+ if (request.sequence !== undefined && make !== undefined) {
1836
+ return yield* forbidden(contract.name, "A MAKE action cannot be written through sync")
1837
+ }
1838
+ // A replay commits nothing but its own record: it never reaches a stage that holds calls.
1839
+ const replayOnly = request.sequence?.kind === "replay"
1840
+ // What would make the call fail anyway is refused before it is held (an approved call's execution is
1841
+ // checked by its handler).
1842
+ const precheck = Option.isSome(prechecks) ? prechecks.value.checks.get(contract.name) : undefined
1843
+ const executingApproved = request.identity !== undefined && request.approval !== undefined
1844
+ if (precheck !== undefined && !replayOnly && !executingApproved) yield* precheck(actor, decoded)
1845
+ const approval = replayOnly
1846
+ ? ({ _tag: "Approved" } as const)
1847
+ : yield* approvals.check({
1848
+ actor,
1849
+ action: contract.name,
1850
+ title: contract.title,
1851
+ input: encoded,
1852
+ inputHash: context.inputHash,
1853
+ surface: request.surface,
1854
+ session,
1855
+ idempotencyKey: request.idempotencyKey,
1856
+ consent: contract.consent,
1857
+ consentEachCall: contract.consentEachCall,
1858
+ provenance: provenanceOf(request, origin, session, credential, chain),
1859
+ // A request it records is created under the call's whole chain, the person's session included,
1860
+ // asserted in the transaction that records it; what it records (`provenance`) drops the session.
1861
+ held: { chain, who: actor, scope: credential.scope, recurring: recurringWork },
1862
+ approval: request.identity !== undefined ? request.approval : undefined,
1863
+ })
1864
+ if (approval._tag === "Pending") {
1865
+ return yield* new ApprovalRequired({
1866
+ action: contract.name,
1867
+ approvalId: approval.approvalId,
1868
+ message: approval.reason,
1869
+ })
1870
+ }
1871
+ if (approval._tag === "ConsentPending") {
1872
+ return yield* new ConsentRequired({
1873
+ action: contract.name,
1874
+ consentId: approval.consentId,
1875
+ message: approval.reason,
1876
+ })
1877
+ }
1878
+ if (approval._tag === "Refused") return yield* forbidden(contract.name, approval.reason)
1879
+ // What the call acts under: its chain, and the consent that let an agent's call through (Authority). A
1880
+ // one-time consent it runs under is used up as it commits (`consume`, after its idempotency claim).
1881
+ const basis = approval._tag === "Approved" ? approval.consent : undefined
1882
+ const consents = basis?.request === undefined ? [] : [basis.request]
1883
+ const acting = extend(
1884
+ chain.filter((link) => !(link.kind === "consent-request" && consents.includes(link.id))),
1885
+ basis?.permission === undefined ? [] : [{ kind: "consent-permission", id: basis.permission }],
1886
+ )
1887
+ context.lineage = lineageOf(request, origin, credential, acting, basis)
1888
+
1889
+ const encodeOutput = (value: unknown) =>
1890
+ asModuleCode(Schema.encodeUnknownEffect(contract.output as Schema.Codec<unknown, unknown>)(value))
1891
+ const key = request.idempotencyKey
1892
+ // An insert a client may predict (its optimistic effect): the record's key is derived from the key the
1893
+ // caller named, or a fresh one, for this actor, on every surface, so the client's prediction and the
1894
+ // handler arrive at the same record and no caller ever chooses a record's key outright.
1895
+ const keyed = withRecordKey(registered, decoded, actor)
1896
+ if (!keyed.ok) return yield* new InvalidInput({ message: keyed.message })
1897
+ const input = keyed.input
1898
+
1899
+ // A MAKE action (see `executeMakeAction`): its writes commit in its module's own transaction, inside the
1900
+ // kernel transaction that holds its authority. A top-level call is admitted within its organisation's bounds
1901
+ // before it takes any connection or interpreter; a nested one runs within its caller's.
1902
+ if (make !== undefined) {
1903
+ const guard = request.identity !== undefined ? request.guard : undefined
1904
+ const nested = request.identity !== undefined && request.provenance !== undefined
1905
+ // The call's authority, held by a kernel transaction that encloses the module's: asserted (its links
1906
+ // locked FOR SHARE, in the global order, before anything else of the call), its one-time consent used up
1907
+ // (locked FOR UPDATE here, its use recorded in the module's transaction, so it commits with the call), its
1908
+ // clock read again before the module's commit; this transaction commits after the module's, so a
1909
+ // revocation waits for the call, or is seen by it. A key another call holds rolls it back (nothing used).
1910
+ // A lock conflict that aborted it before the module's commit runs it again (after the module committed,
1911
+ // nothing in this transaction can conflict: it only commits).
1912
+ const taken = { _tag: "MakeKeyTaken" } as const
1913
+ const run = retryingConflicts(
1914
+ sql.withTransaction(
1915
+ Effect.gen(function* () {
1916
+ // A run again after a conflict rolled the last one back: it has not begun committing.
1917
+ if (context.acted === "committing") context.acted = undefined
1918
+ let asserted = yield* authority.assert({
1919
+ chain: acting,
1920
+ who: actor,
1921
+ scope: credential.scope,
1922
+ recurring: recurringWork,
1923
+ })
1924
+ // A cancelled run's call never starts (and the guard is held again over the commit).
1925
+ if (guard !== undefined) yield* guard
1926
+ if (consents.length > 0) {
1927
+ asserted = yield* authority.consume(asserted, consents, {
1928
+ invocationId: context.invocationId,
1929
+ recordedBy: "make",
1930
+ })
1931
+ }
1932
+ // The module's version, held (shared) until this transaction commits, which is after the module's:
1933
+ // a version change waits for the call, and a call the change overtook while it was admitted or
1934
+ // waited runs nothing of the version it looked up. A nested call never waits for it.
1935
+ const runtime = Option.getOrThrow(makeRuntime)
1936
+ const current = yield* runtime.holdVersion(registered.module.contract.name, { wait: !nested })
1937
+ if (current === VERSION_BUSY) {
1938
+ return yield* new ActionFailed({
1939
+ action: contract.name,
1940
+ message: `${registered.module.contract.name} is changing version; try again shortly`,
1941
+ })
1942
+ }
1943
+ if (current?.make?.hash !== make.hash || current.make.orgId !== make.orgId) {
1944
+ return yield* new ActionFailed({
1945
+ action: contract.name,
1946
+ message: `${registered.module.contract.name} changed version while this call waited; call it again`,
1947
+ })
1948
+ }
1949
+ const executed = yield* executeMakeAction(
1950
+ registered,
1951
+ actor,
1952
+ context,
1953
+ decoded,
1954
+ encoded,
1955
+ key,
1956
+ {
1957
+ origin,
1958
+ session,
1959
+ receipt:
1960
+ key === undefined ? undefined : provenanceFor(request, context.invocationId, key, origin),
1961
+ },
1962
+ { nested, guard },
1963
+ { scope: credential.scope === null ? null : [...credential.scope], chain: acting },
1964
+ { asserted, consumes: consents },
1965
+ )
1966
+ if (executed.kind === "taken") return yield* Effect.fail(taken)
1967
+ return executed
1968
+ }),
1969
+ ),
1970
+ ).pipe(
1971
+ Effect.catchIf(
1972
+ (e): e is typeof taken => e === taken,
1973
+ () => Effect.succeed({ kind: "taken" } as const),
1974
+ ),
1975
+ Effect.catchIf(
1976
+ (e): e is SqlError.SqlError => SqlError.isSqlError(e),
1977
+ (e) => Effect.die(e),
1978
+ ),
1979
+ )
1980
+ const executed = nested
1981
+ ? yield* run
1982
+ : yield* Option.getOrThrow(makeRuntime).admit(registered.module, actor, contract.name, run)
1983
+ if (executed.kind === "done") return executed.result
1984
+ // The key is another call's (which has committed): answered below with its receipt.
1985
+ }
1986
+
1987
+ // 4-7. Idempotency, execute, record checks, audit and outbox in one transaction (a MAKE draft, preview or view
1988
+ // step, which runs untrusted code in the sandbox, admitted first, before its transaction takes a connection:
1989
+ // see `MakeRuntime.admitLifecycle`).
1990
+ const admitted = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1991
+ Option.isSome(makeRuntime) &&
1992
+ isKernelProvided(registered.module) &&
1993
+ (contract.name === "make.draft" || contract.name === "make.preview" || contract.name === "make.renderView")
1994
+ ? makeRuntime.value.admitLifecycle(actor, contract.name, effect)
1995
+ : effect
1996
+ // A lock conflict the database resolved by aborting this transaction (it rolled back whole) runs it again.
1997
+ return yield* admitted(
1998
+ retryingConflicts(
1999
+ sql.withTransaction(
2000
+ Effect.gen(function* () {
2001
+ // A run again after a conflict rolled the last one back: it has not begun committing.
2002
+ if (context.acted === "committing") context.acted = undefined
2003
+ // Authority: every link of the call's chain (and the person's membership) holds, its row locked,
2004
+ // before the call reads or writes any protected data (and before its invocation context is set:
2005
+ // consent links are read as that module). The capability it returns is what the handler runs with.
2006
+ // Links first, then the rows they protect (the lock order: the run's row the guard holds included).
2007
+ let asserted = yield* authority.assert({
2008
+ chain: acting,
2009
+ who: actor,
2010
+ scope: credential.scope,
2011
+ recurring: recurringWork,
2012
+ })
2013
+ if (request.identity !== undefined && request.guard !== undefined) yield* request.guard
2014
+ if (request.sequence?.kind === "next") yield* request.sequence.advance
2015
+ // The context row-level security reads: who acts, where, for which action (not forgeable by modules).
2016
+ const group = request.identity !== undefined ? (request.editGroup ?? null) : null
2017
+ const setContext = sql`INSERT INTO eloxiv.invocation_context
2018
+ (actor, org, action, agent_run, agent_conversation, agent_message, namespace)
2019
+ VALUES (${actor.userId}, ${actor.orgId}, ${contract.name}, ${group?.runId ?? null},
2020
+ ${group?.conversationId ?? null}, ${group?.messageId ?? null},
2021
+ ${registered.module.contract.cedarNamespace})
2022
+ ON CONFLICT (xid) DO UPDATE SET actor = EXCLUDED.actor, org = EXCLUDED.org, action = EXCLUDED.action,
2023
+ agent_run = EXCLUDED.agent_run, agent_conversation = EXCLUDED.agent_conversation,
2024
+ agent_message = EXCLUDED.agent_message, namespace = EXCLUDED.namespace`.pipe(Effect.orDie)
2025
+ yield* setContext
2026
+ const clearContext = Effect.all([
2027
+ sql`DELETE FROM eloxiv.invocation_context WHERE xid = pg_current_xact_id()`,
2028
+ sql`DELETE FROM eloxiv.invocation_target WHERE xid = pg_current_xact_id()`,
2029
+ ]).pipe(Effect.asVoid, Effect.orDie)
2030
+ if (key !== undefined) {
2031
+ const claimed = yield* sql<{ claimed: number }>`
2032
+ INSERT INTO eloxiv.idempotency_key (org_id, actor_user_id, action, key, request_hash, invocation_id)
2033
+ VALUES (${actor.orgId}, ${actor.userId}, ${contract.name}, ${key}, ${context.inputHash}, ${context.invocationId})
2034
+ ON CONFLICT DO NOTHING RETURNING 1 AS claimed`.pipe(Effect.orDie)
2035
+ if (claimed.length === 0) {
2036
+ const [previous] = yield* sql<{
2037
+ requestHash: string
2038
+ receipt: InvocationReceipt | null
2039
+ receiptFormat: number
2040
+ }>`
2041
+ SELECT request_hash AS "requestHash", receipt, receipt_format AS "receiptFormat"
2042
+ FROM eloxiv.idempotency_key
2043
+ WHERE org_id = ${actor.orgId} AND actor_user_id = ${actor.userId} AND action = ${contract.name} AND key = ${key}`.pipe(
2044
+ Effect.orDie,
2045
+ )
2046
+ if (!previous || previous.requestHash !== context.inputHash) {
2047
+ return yield* new IdempotencyConflict({
2048
+ key,
2049
+ message: "The idempotency key was used with a different request",
2050
+ })
2051
+ }
2052
+ if (previous.receipt === null || previous.receiptFormat !== RECEIPT_FORMAT) {
2053
+ return yield* new IdempotencyConflict({
2054
+ key,
2055
+ message: "The idempotency key's receipt was stored in an older format; use a new key",
2056
+ })
2057
+ }
2058
+ // This call may have waited on the first execution's claim: authenticate again (the same user, still
2059
+ // a member of the same organisation) and re-check the action's policy immediately before release.
2060
+ const { actor: current, credential: currentCredential } = yield* authenticate
2061
+ if (!scopeAllows(currentCredential.scope, contract.name, permissionActions)) {
2062
+ return yield* forbidden(contract.name, "The credential is not scoped to this action")
2063
+ }
2064
+ if (current.userId !== actor.userId || current.orgId !== actor.orgId) {
2065
+ return yield* forbidden(contract.name, "The caller's identity changed")
2066
+ }
2067
+ if (yield* denies(current)) return yield* forbidden(contract.name, "Policy denies this action")
2068
+ // A deferred call's credentials still hold, and are held until this replay is released.
2069
+ // A replay returns the receipt, never the output: see `InvocationReceipt` for what it may hold.
2070
+ const replay: ReplayEnvelope = { kind: "replay", receipt: previous.receipt }
2071
+ yield* writeAudit(context, "replayed", undefined, previous.receipt.completion ?? undefined)
2072
+ yield* clearContext
2073
+ yield* authority.confirm(asserted)
2074
+ return {
2075
+ invocationId: context.invocationId,
2076
+ replayed: true,
2077
+ output: undefined,
2078
+ envelope: replay,
2079
+ encoded: replay,
2080
+ }
2081
+ }
2082
+ }
2083
+
2084
+ if (replayOnly) {
2085
+ return yield* new IdempotencyConflict({
2086
+ key: key ?? "",
2087
+ message: "The call was already answered and left no receipt to replay",
2088
+ })
2089
+ }
2090
+ if (make !== undefined) {
2091
+ // A MAKE action never runs here: its call ran (and committed) above, or its key is another's.
2092
+ return yield* new IdempotencyConflict({
2093
+ key: key ?? "",
2094
+ message: "The idempotency key is in use; try again",
2095
+ })
2096
+ }
2097
+ // The call runs (it is not a replay): the one-time consent it runs under is used up with it, and the
2098
+ // context is set again (the consent module's tables are written as that module).
2099
+ if (consents.length > 0) {
2100
+ asserted = yield* authority.consume(asserted, consents, {
2101
+ invocationId: context.invocationId,
2102
+ recordedBy: "this transaction",
2103
+ })
2104
+ yield* setContext
2105
+ }
2106
+ const capability = asserted
2107
+ const executed = yield* Effect.gen(function* () {
2108
+ const targets = yield* authoriseTargets(actor, registered, input)
2109
+ // Still holding by the clock now, after any wait for the targets (the rows are held since the
2110
+ // assertion).
2111
+ yield* authority.recheck(capability)
2112
+ const ran = yield* execute(
2113
+ registered,
2114
+ actor,
2115
+ context.invocationId,
2116
+ input,
2117
+ origin,
2118
+ context,
2119
+ capability,
2120
+ {
2121
+ kind: credential.kind,
2122
+ id: credential.id,
2123
+ session: session?.id ?? null,
2124
+ },
2125
+ )
2126
+ const checked = yield* authoriseWrites(actor, registered, targets, ran.revertDeletes)
2127
+ context.changes = changesOf(checked.log)
2128
+ // Counted while the session still acts as the caller: row-level security reads with it.
2129
+ const written = yield* writtenOf(actor, registered, checked.log)
2130
+ // Record history (the Versioning contract): a version per changed record of a history entity.
2131
+ if (Option.isSome(versioning) && versioning.value.byTable.size > 0) {
2132
+ yield* versioning.value.record(sql, checked.log, {
2133
+ orgId: actor.orgId,
2134
+ actorUserId: actor.userId,
2135
+ action: contract.name,
2136
+ invocationId: context.invocationId,
2137
+ editGroup: group,
2138
+ revertGroups: ran.revertGroups,
2139
+ })
2140
+ }
2141
+ // The kernel's own writes for the handler (work items, notifications), as the system actor.
2142
+ yield* ran.kernelWrites
2143
+ // Work-item titles copied from records this call wrote follow them.
2144
+ yield* workItems.followRecords(registered.module.contract.name, actor.orgId, checked.log)
2145
+ return {
2146
+ output: ran.output,
2147
+ events: ran.events,
2148
+ ...checked,
2149
+ requested: targets?.requested,
2150
+ effectIds: ran.effectIds,
2151
+ written,
2152
+ }
2153
+ })
2154
+ const { events, created, completion, written } = executed
2155
+ // Best effort: the kernel, not the handler, reports what was affected; an untargeted write that
2156
+ // reports what it wrote, likewise.
2157
+ const output =
2158
+ contract.bestEffort && completion !== undefined
2159
+ ? { ...(executed.output as object), ...completion }
2160
+ : contract.reportsWritten && written !== undefined
2161
+ ? { ...(executed.output as object), written }
2162
+ : executed.output
2163
+ // An output that does not match the action's contract fails the call, which rolls back whole: its
2164
+ // writes, its events and the effects it scheduled. Why it does not match is logged, never returned
2165
+ // (the output may hold what the handler read).
2166
+ const encodedOutput = yield* encodeOutput(output).pipe(
2167
+ Effect.catch((e) =>
2168
+ Effect.logError(`The output of ${contract.name} does not match its contract`, e).pipe(
2169
+ Effect.andThen(
2170
+ Effect.fail(
2171
+ new ActionFailed({
2172
+ action: contract.name,
2173
+ message: "The action's output does not match its contract; nothing it did was kept",
2174
+ }),
2175
+ ),
2176
+ ),
2177
+ ),
2178
+ ),
2179
+ )
2180
+
2181
+ yield* writeAudit(context, "succeeded", undefined, completion)
2182
+ // The events, in the call's transaction.
2183
+ for (const { event, payload } of events) {
2184
+ const encodedPayload = yield* asModuleCode(
2185
+ Schema.encodeUnknownEffect(event.payload as Schema.Codec<unknown, unknown>)(payload),
2186
+ ).pipe(Effect.orDie)
2187
+ yield* outbox.publish({
2188
+ invocationId: context.invocationId,
2189
+ type: event.type,
2190
+ module: registered.module.contract.name,
2191
+ orgId: actor.orgId,
2192
+ payload: encodedPayload,
2193
+ })
2194
+ }
2195
+ if (key !== undefined) {
2196
+ // The receipt names, by reference (never their payload), every event the call committed: those its
2197
+ // handler emitted and those the kernel published for it (a file's upload, a scheduled effect).
2198
+ const published: ReadonlyArray<ReceiptEventRef> = (yield* sql<{
2199
+ id: string
2200
+ type: string
2201
+ module: string
2202
+ }>`
2203
+ SELECT id::text AS id, type, module FROM eloxiv.outbox
2204
+ WHERE invocation_id = ${context.invocationId} ORDER BY seq`.pipe(Effect.orDie)).map((row) => ({
2205
+ specversion: "1.0" as const,
2206
+ id: row.id,
2207
+ source: `/modules/${row.module}`,
2208
+ type: row.type,
2209
+ }))
2210
+ // Only what the caller already had: the target ids it supplied; ids of records of the action's
2211
+ // entity this call inserted *and* its output named; best-effort counts (never which targets);
2212
+ // what an untargeted write wrote (counts); the events it committed and where it came from (ids).
2213
+ const named = valuesIn(encodedOutput)
2214
+ const receipt: InvocationReceipt = {
2215
+ version: RECEIPT_VERSION,
2216
+ action: contract.name,
2217
+ invocationId: context.invocationId,
2218
+ outcome: "succeeded",
2219
+ targets: executed.requested ?? [],
2220
+ created: created
2221
+ .filter((r) => r.entity === registered.writes?.cedarType && named.has(r.pk))
2222
+ .map((r) => r.pk),
2223
+ ...(executed.effectIds.length === 0 ? {} : { effects: executed.effectIds }),
2224
+ ...(isNoOp(encodedOutput) ? { noop: encodedOutput } : {}),
2225
+ completion: contract.bestEffort ? (completion ?? null) : null,
2226
+ events: published,
2227
+ provenance: provenanceFor(request, context.invocationId, key, origin),
2228
+ ...(written === undefined ? {} : { written }),
2229
+ }
2230
+ yield* sql`UPDATE eloxiv.idempotency_key
2231
+ SET receipt = ${JSON.stringify(receipt)}::jsonb, receipt_format = ${RECEIPT_FORMAT}
2232
+ WHERE org_id = ${actor.orgId} AND actor_user_id = ${actor.userId} AND action = ${contract.name} AND key = ${key}`.pipe(
2233
+ Effect.orDie,
2234
+ )
2235
+ }
2236
+ yield* clearContext
2237
+ // The check at commit, the transaction's last statement: the call's session and tokens still valid
2238
+ // by the clock, its session not revoked (Authority.confirm). Otherwise it commits nothing.
2239
+ yield* authority.confirm(capability)
2240
+ // From here the transaction commits: a failure now may come after the commit took effect.
2241
+ context.acted ??= "committing"
2242
+ return {
2243
+ invocationId: context.invocationId,
2244
+ replayed: false,
2245
+ output,
2246
+ envelope: { kind: "output", output },
2247
+ encoded: { kind: "output", output: encodedOutput },
2248
+ ...(executed.effectIds.length === 0 ? {} : { effects: executed.effectIds }),
2249
+ }
2250
+ }),
2251
+ ),
2252
+ ),
2253
+ )
2254
+ })
2255
+
2256
+ const invoke: InvocationShape["invoke"] = (request) =>
2257
+ Effect.gen(function* () {
2258
+ const started = Date.now()
2259
+ const context: AuditContext = {
2260
+ invocationId: crypto.randomUUID(),
2261
+ action: request.action,
2262
+ surface: request.surface,
2263
+ inputHash: yield* hashOf("decoded" in request.input ? request.input.decoded : request.input.encoded),
2264
+ idempotencyKey: request.idempotencyKey,
2265
+ actor: undefined,
2266
+ // The client address the kernel's HTTP layer determined (CookieGuard), for bounding anonymous refusals.
2267
+ address:
2268
+ request.identity === undefined ? (request.headers.get(CLIENT_ADDRESS_HEADER) ?? undefined) : undefined,
2269
+ events: [],
2270
+ }
2271
+ const exit = yield* Effect.exit(
2272
+ body(request, context).pipe(
2273
+ Effect.catchTag("SqlError", (e) => Effect.die(e)),
2274
+ Effect.tap((result) =>
2275
+ result.replayed
2276
+ ? Effect.void
2277
+ : invocationHooks.afterCommit({ action: request.action, idempotencyKey: request.idempotencyKey }),
2278
+ ),
2279
+ ),
2280
+ )
2281
+ // Telemetry: the span's attributes (ids and tags only), the call's metrics.
2282
+ const outcomeOf = Exit.isSuccess(exit)
2283
+ ? exit.value.replayed
2284
+ ? "replayed"
2285
+ : "succeeded"
2286
+ : Cause.hasInterruptsOnly(exit.cause)
2287
+ ? "interrupted"
2288
+ : "failed"
2289
+ const errorTag = Exit.isFailure(exit)
2290
+ ? Option.match(Cause.findErrorOption(exit.cause), {
2291
+ onNone: () => "Defect",
2292
+ onSome: (e) => (e as { readonly _tag: string })._tag,
2293
+ })
2294
+ : undefined
2295
+ // Declared values only: a name the caller sent that no module registered is `unknown`.
2296
+ const registered = registry.actions.get(request.action)
2297
+ const action = registered === undefined ? "unknown" : request.action
2298
+ yield* Effect.annotateCurrentSpan({
2299
+ "eloxiv.outcome": outcomeOf,
2300
+ ...(errorTag === undefined ? {} : { "eloxiv.error_tag": errorTag }),
2301
+ ...(context.origin === undefined ? {} : { "eloxiv.origin": context.origin }),
2302
+ "eloxiv.module": registered === undefined ? "unknown" : registered.module.contract.name,
2303
+ })
2304
+ const series = { action, surface: request.surface, outcome: outcomeOf }
2305
+ yield* Metric.update(Metric.withAttributes(invocationMetrics.calls, series), 1)
2306
+ yield* Metric.update(Metric.withAttributes(invocationMetrics.duration, series), Date.now() - started)
2307
+ if (Exit.isSuccess(exit)) {
2308
+ // Product analytics, now the call has committed: the kernel's own event for a person's or their
2309
+ // agent's call, and what the handler asked for. Consent is checked when they leave.
2310
+ if (analyticsOn && Option.isSome(analytics) && context.actor !== undefined && context.origin !== "system") {
2311
+ const actor = context.actor
2312
+ if (!exit.value.replayed && actor.userId !== SYSTEM_ACTOR) {
2313
+ const own = yield* analytics.value
2314
+ .prepare("eloxiv", actor, {
2315
+ event: ACTION_INVOKED_EVENT,
2316
+ properties: {
2317
+ action: request.action,
2318
+ surface: request.surface,
2319
+ origin: context.origin ?? "person",
2320
+ duration_ms: Date.now() - started,
2321
+ },
2322
+ })
2323
+ .pipe(Effect.orElseSucceed(() => null))
2324
+ if (own !== null) yield* analytics.value.enqueue(own)
2325
+ }
2326
+ for (const event of context.events) yield* analytics.value.enqueue(event)
2327
+ }
2328
+ return exit.value
2329
+ }
2330
+ if (Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause as Cause.Cause<never>)
2331
+ const failure = Cause.findErrorOption(exit.cause)
2332
+ if (Option.isNone(failure)) {
2333
+ // A defect outside the handler (the kernel's own code, the database): the caller and error telemetry get
2334
+ // its tag and the invocation's id only, and the kernel's log its cause under that id (a database refusal
2335
+ // such as a module role the kernel's role may no longer take), so an operator can find what failed.
2336
+ yield* Effect.logError(
2337
+ `The call of ${request.action} failed unexpectedly (invocation ${context.invocationId})`,
2338
+ exit.cause,
2339
+ )
2340
+ yield* capture(context.invocationId)
2341
+ }
2342
+ const found: InvocationError = Option.isSome(failure)
2343
+ ? failure.value
2344
+ : new ActionFailed({
2345
+ action: request.action,
2346
+ message: `The call failed unexpectedly (invocation ${context.invocationId})`,
2347
+ })
2348
+ // A failure says what the call may have done (C-011): nothing kept, or possibly something. The kernel decides
2349
+ // it from what it saw, whatever a handler's own `ActionFailed` said.
2350
+ const error: InvocationError =
2351
+ found._tag === "ActionFailed"
2352
+ ? new ActionFailed({
2353
+ action: found.action,
2354
+ message: found.message,
2355
+ effect: context.acted === undefined ? "none" : "unknown",
2356
+ })
2357
+ : found
2358
+ // The transaction (if any) has rolled back with any audit row it held: record the failure exactly once.
2359
+ const outcome: AuditOutcome =
2360
+ error._tag === "Forbidden" || error._tag === "Unauthenticated" || error._tag === "ClientOutdated"
2361
+ ? "denied"
2362
+ : error._tag === "ApprovalRequired" || error._tag === "ConsentRequired"
2363
+ ? "approval-required"
2364
+ : "failed"
2365
+ yield* writeAudit(context, outcome, error._tag)
2366
+ return yield* Effect.fail(error)
2367
+ }).pipe(
2368
+ Effect.withSpan("Invocation.invoke", {
2369
+ attributes: { "eloxiv.action": request.action, "eloxiv.surface": request.surface },
2370
+ }),
2371
+ )
2372
+
2373
+ const receiptFor = (asserted: Asserted, action: string, key: string) =>
2374
+ authority.bound(asserted, asserted.who).pipe(
2375
+ Effect.andThen(
2376
+ sql<{ receipt: InvocationReceipt | null }>`SELECT receipt FROM eloxiv.idempotency_key
2377
+ WHERE org_id = ${asserted.who.orgId} AND actor_user_id = ${asserted.who.userId} AND action = ${action}
2378
+ AND key = ${key} AND receipt IS NOT NULL`,
2379
+ ),
2380
+ Effect.map(([row]) => row?.receipt ?? null),
2381
+ Effect.orDie,
2382
+ )
2383
+
2384
+ return Invocation.of({ invoke, reach, receiptFor })
2385
+ }),
2386
+ )
2387
+ }