@voltro/cli 0.33.0 → 0.34.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 (337) hide show
  1. package/CHANGELOG.md +1801 -0
  2. package/bin/nodeEnvironment.d.mts +30 -0
  3. package/bin/nodeEnvironment.mjs +158 -0
  4. package/bin/voltro.mjs +69 -5
  5. package/dist/addCommand-BNeoeSxe.js +124 -0
  6. package/dist/addCommand-aXSQveak.js +2 -0
  7. package/dist/agentsMd-BTchIZku.js +2 -0
  8. package/dist/agentsMd-mhQMF1bx.js +254 -0
  9. package/dist/apiBuild-BICVGnEC.js +2 -0
  10. package/dist/{apiBuild-h9VHtnlw.js → apiBuild-DZF_f0_I.js} +46 -46
  11. package/dist/appPort-B_HpJ_ck.js +48 -0
  12. package/dist/baselineCommand-C2ClWZN3.js +2 -0
  13. package/dist/baselineCommand-DIttzO8A.js +227 -0
  14. package/dist/bin.js +71 -28
  15. package/dist/build-CE7Ca9gm.js +711 -0
  16. package/dist/cacheCommand-DA4OH9xt.js +42 -0
  17. package/dist/capabilitiesCommand-nq_pz5xd.js +123 -0
  18. package/dist/checkCommand-Dv8r9tGO.js +231 -0
  19. package/dist/checkCommand-YZDmkAGd.js +2 -0
  20. package/dist/{cliArgs-qdZSElM3.js → cliArgs-D4p8n7EE.js} +12 -1
  21. package/dist/cliError-BmdYnghb.js +10 -0
  22. package/dist/cliOutput-D1tSBoRM.js +15 -0
  23. package/dist/{cliRuntime-Oh517vCV.js → cliRuntime-Dh7UDinH.js} +20 -20
  24. package/dist/cloudClient-DWL-Hw_T.js +67 -0
  25. package/dist/cloudCmd-Cvv5HGaZ.js +364 -0
  26. package/dist/clusterCmd-CNXKlcvD.js +54 -0
  27. package/dist/codegen-CYM3Zqrf.js +605 -0
  28. package/dist/codegen-ChBi_hVa.js +2 -0
  29. package/dist/codegenCommand-DC6w2tNZ.js +30 -0
  30. package/dist/codemodRunner-DRRqXR74.js +5243 -0
  31. package/dist/commandRunner-BLAEFLjp.js +47 -0
  32. package/dist/commands-gutsz-Ac.js +808 -0
  33. package/dist/connectionConfig-UFlIEiys.js +66 -0
  34. package/dist/dashboardCommand-3YG8p-UA.js +25 -0
  35. package/dist/dataCommand-qL0r7fPO.js +535 -0
  36. package/dist/dataProfile-dW-PsfLB.js +15 -0
  37. package/dist/{dbCommand-DTLKAfbA.js → dbCommand-B6X0FZbq.js} +551 -401
  38. package/dist/dbCommand-CpdKLeQq.js +2 -0
  39. package/dist/{dev-C_P8FLSx.js → dev-CerMd0mW.js} +3122 -3129
  40. package/dist/dev-CoG-ZPx8.js +3 -0
  41. package/dist/devActivity-Dx_3nnGv.js +100 -0
  42. package/dist/devActivity.js +1 -1
  43. package/dist/dialectDriver-CgXnDfec.js +39 -0
  44. package/dist/discover-C9XKJDco.js +25 -0
  45. package/dist/doctorCommand-BvqGBwNG.js +2 -0
  46. package/dist/{checkCommand-xGhRFFg2.js → doctorCommand-CnDXQxfa.js} +520 -1278
  47. package/dist/dormancyCommand-Dszo57d6.js +69 -0
  48. package/dist/e2eCmd-BRabZww-.js +147 -0
  49. package/dist/embeddingsCommand-C0sKVRo1.js +73 -0
  50. package/dist/envCommand-DPgdV1Bq.js +60 -0
  51. package/dist/evalCommand-6RUfPen4.js +118 -0
  52. package/dist/evolveCommand-DHpkgjgH.js +281 -0
  53. package/dist/fileTaxonomy-CJfgOllU.js +457 -0
  54. package/dist/frameworkTableAssembly-BGHmck-x.js +2 -0
  55. package/dist/{frameworkTableAssembly-BwIrO5nv.js → frameworkTableAssembly-DkkP6BgC.js} +184 -148
  56. package/dist/generateCommand-oibemh97.js +147 -0
  57. package/dist/index.d.ts +45 -0
  58. package/dist/index.js +4 -3
  59. package/dist/infoCommand-BJw9nLUR.js +60 -0
  60. package/dist/{inspect-BUUjt773.js → inspect-CBqFtAKA.js} +82 -40
  61. package/dist/inspect-C_T_WGvl.js +2 -0
  62. package/dist/inspectCmd-Bppy-GGw.js +224 -0
  63. package/dist/inspectFetch-Cm8_wVvp.js +151 -0
  64. package/dist/inspectMetrics-CfdKLh6t.js +72 -0
  65. package/dist/loadEnv-D9nEOClM.js +44 -0
  66. package/dist/logFileSink-C_D2wRN1.js +105 -0
  67. package/dist/logsCmd-CCca3KRZ.js +260 -0
  68. package/dist/manifestBuild-ChsKAhmn.js +2 -0
  69. package/dist/{manifestBuild-BLrVuSlM.js → manifestBuild-sxpwdKY1.js} +1 -1
  70. package/dist/metaCommands-7MJfZ5cf.js +196 -0
  71. package/dist/migrate-CBwOt_iV.js +83 -0
  72. package/dist/mssqlClusterPatch-_4cE_nun.js +44 -0
  73. package/dist/newCommand-COWOJ1_E.js +156 -0
  74. package/dist/nodeEnvironment-cGFAj1J8.js +28 -0
  75. package/dist/packageCommand-Cug_3Ogl.js +271 -0
  76. package/dist/pageConvention-cEiRxdab.js +5 -0
  77. package/dist/privacyCommand-C-Df56U_.js +146 -0
  78. package/dist/projectScaffold-DmzEKHib.js +2 -0
  79. package/dist/projectScaffold-LMMtaavR.js +814 -0
  80. package/dist/renderModeScan-D7J1B7Kw.js +105 -0
  81. package/dist/renderProfile-1OWWAAtx.js +81 -0
  82. package/dist/runtimeRegistry-DMeKfTHP.js +81 -0
  83. package/dist/runtimeTrace-CRxalXTs.js +91 -0
  84. package/dist/scheduleCmd--jksTrf6.js +69 -0
  85. package/dist/scheduleManifestCmd-D2x0CTTY.js +249 -0
  86. package/dist/schemaIr-UJybUUZW.js +103 -0
  87. package/dist/{sdkgen-C81QIkiL.js → sdkgen-CYJscZC7.js} +111 -209
  88. package/dist/seedRunner-TFHHiToI.js +329 -0
  89. package/dist/serveCommand-B_isw7q4.js +1647 -0
  90. package/dist/serveCommand-DOvbgRnQ.js +2 -0
  91. package/dist/serveEntry.js +5 -5
  92. package/dist/serverlessCommand-CfJZy6dS.js +482 -0
  93. package/dist/start-9LiUOfES.js +1087 -0
  94. package/dist/start-B-9Nsp-S.js +3 -0
  95. package/dist/startEntry.js +2 -2
  96. package/dist/staticCommand-Dr2M6tpU.js +304 -0
  97. package/dist/storageCommand-Co6NfLqN.js +42 -0
  98. package/dist/templates-De8IR5-c.js +102 -0
  99. package/dist/test-CI6iDsYc.js +115 -0
  100. package/dist/tracesCmd-CkEZQrtt.js +232 -0
  101. package/dist/tsconfigPaths-BWXBWgcl.js +107 -0
  102. package/dist/tsxLoader-EuXmSJ1K.js +51 -0
  103. package/dist/typecheckCommand-BlsWiCNq.js +61 -0
  104. package/dist/updateCommand-Bkptutss.js +585 -0
  105. package/dist/updateCommand-us1_hdIC.js +2 -0
  106. package/dist/{inspectMetrics-1xzTKAFx.js → webDev-CBYvPqQr.js} +975 -1559
  107. package/dist/webDev-Cg-fFiyd2.js +2 -0
  108. package/dist/webhookDiscovery-CrGAfhIG.js +2 -0
  109. package/dist/webhookDiscovery-D7VaeMlz.js +51 -0
  110. package/dist/webhooksCommand-CID96Rga.js +267 -0
  111. package/dist/workflowsCmd-D1VTmLMY.js +608 -0
  112. package/package.json +179 -17
  113. package/templates/AGENTS.core.md +58 -3
  114. package/templates/AGENTS.md +64 -7
  115. package/templates/agent-docs/_index.md +6 -4
  116. package/templates/agent-docs/_manifest.json +22 -5
  117. package/templates/agent-docs/ai.md +370 -0
  118. package/templates/agent-docs/authentication.md +265 -31
  119. package/templates/agent-docs/caching.md +6 -0
  120. package/templates/agent-docs/cli.md +794 -50
  121. package/templates/agent-docs/data.md +550 -11
  122. package/templates/agent-docs/database/migrations.md +174 -25
  123. package/templates/agent-docs/database/misc.md +156 -40
  124. package/templates/agent-docs/database/querying.md +19 -1
  125. package/templates/agent-docs/database/scaling.md +60 -0
  126. package/templates/agent-docs/database/schema.md +1 -0
  127. package/templates/agent-docs/database/seedsdialects.md +208 -19
  128. package/templates/agent-docs/database/transactions.md +68 -0
  129. package/templates/agent-docs/deployment.md +69 -3
  130. package/templates/agent-docs/introduction.md +87 -16
  131. package/templates/agent-docs/local-first-mobile.md +79 -4
  132. package/templates/agent-docs/multi-tenancy.md +95 -20
  133. package/templates/agent-docs/observability.md +58 -3
  134. package/templates/agent-docs/plugins/ai-flows.md +161 -2
  135. package/templates/agent-docs/plugins/analytics-postgres.md +1 -1
  136. package/templates/agent-docs/plugins/audit.md +37 -1
  137. package/templates/agent-docs/plugins/auth-social.md +143 -0
  138. package/templates/agent-docs/plugins/auth-workos.md +4 -2
  139. package/templates/agent-docs/plugins/auth.md +131 -6
  140. package/templates/agent-docs/plugins/billing.md +132 -15
  141. package/templates/agent-docs/plugins/cdc-out.md +46 -7
  142. package/templates/agent-docs/plugins/clickhouse.md +1 -1
  143. package/templates/agent-docs/plugins/duckdb.md +1 -1
  144. package/templates/agent-docs/plugins/flags.md +132 -0
  145. package/templates/agent-docs/plugins/governance.md +105 -7
  146. package/templates/agent-docs/plugins/multitenancy.md +9 -4
  147. package/templates/agent-docs/plugins/presence.md +13 -2
  148. package/templates/agent-docs/plugins/ratelimit.md +9 -0
  149. package/templates/agent-docs/plugins/search.md +157 -6
  150. package/templates/agent-docs/plugins/sso-saml.md +47 -8
  151. package/templates/agent-docs/plugins/webhooks.md +105 -0
  152. package/templates/agent-docs/plugins.md +150 -18
  153. package/templates/agent-docs/reference.md +60 -3
  154. package/templates/agent-docs/releases.md +1117 -0
  155. package/templates/agent-docs/routing.md +43 -25
  156. package/templates/agent-docs/scheduling.md +10 -0
  157. package/templates/agent-docs/schema-driven-ui.md +92 -12
  158. package/templates/agent-docs/security.md +426 -0
  159. package/templates/agent-docs/templates/apibackends.md +87 -18
  160. package/templates/agent-docs/templates/appshells.md +32 -14
  161. package/templates/agent-docs/templates/overview.md +13 -8
  162. package/templates/agent-docs/testing.md +211 -14
  163. package/templates/agent-docs/whats-new.md +1700 -104
  164. package/templates/agent-docs/workflows.md +130 -14
  165. package/templates/apps/api-ai/actions/summarize.action.ts +11 -0
  166. package/templates/apps/api-ai/package.json +8 -7
  167. package/templates/apps/api-auth/actions/me.action.ts +13 -0
  168. package/templates/apps/api-auth/package.json +9 -8
  169. package/templates/apps/api-backend/mutations/notes.create.mutation.ts +9 -0
  170. package/templates/apps/api-backend/package.json +12 -8
  171. package/templates/apps/api-backend/queries/notes.query.ts +30 -8
  172. package/templates/apps/api-backend-deactivation/actions/users.get.action.ts +14 -0
  173. package/templates/apps/api-backend-deactivation/mutations/users.create.mutation.ts +8 -0
  174. package/templates/apps/api-backend-deactivation/mutations/users.deactivate.mutation.ts +10 -0
  175. package/templates/apps/api-backend-deactivation/package.json +8 -7
  176. package/templates/apps/api-backend-mail/actions/sendWelcome.action.ts +17 -0
  177. package/templates/apps/api-backend-mail/mutations/notes.create.mutation.ts +9 -0
  178. package/templates/apps/api-backend-mail/package.json +9 -8
  179. package/templates/apps/api-backend-mail/queries/notes.query.ts +30 -8
  180. package/templates/apps/api-backend-mariadb/.env.example +14 -0
  181. package/templates/apps/api-backend-mariadb/mutations/notes.create.mutation.ts +9 -0
  182. package/templates/apps/api-backend-mariadb/package.json +10 -9
  183. package/templates/apps/api-backend-mariadb/queries/notes.query.ts +30 -8
  184. package/templates/apps/api-backend-sqlite/.env.example +14 -0
  185. package/templates/apps/api-backend-sqlite/mutations/notes.create.mutation.ts +9 -0
  186. package/templates/apps/api-backend-sqlite/package.json +9 -8
  187. package/templates/apps/api-backend-sqlite/queries/notes.query.ts +30 -8
  188. package/templates/apps/api-backend-storage/actions/uploadAvatar.action.ts +13 -0
  189. package/templates/apps/api-backend-storage/actions/uploadDocument.action.ts +12 -0
  190. package/templates/apps/api-backend-storage/mutations/notes.create.mutation.ts +9 -0
  191. package/templates/apps/api-backend-storage/package.json +9 -8
  192. package/templates/apps/api-backend-storage/queries/notes.query.ts +30 -8
  193. package/templates/apps/api-cms/actions/content.get.action.ts +7 -0
  194. package/templates/apps/api-cms/actions/content.types.action.ts +6 -0
  195. package/templates/apps/api-cms/actions/me.action.ts +13 -0
  196. package/templates/apps/api-cms/app.config.ts +19 -0
  197. package/templates/apps/api-cms/authz.ts +63 -0
  198. package/templates/apps/api-cms/mutations/content.publish.mutation.ts +10 -0
  199. package/templates/apps/api-cms/mutations/content.saveDraft.mutation.ts +10 -0
  200. package/templates/apps/api-cms/mutations/content.unpublish.mutation.ts +5 -0
  201. package/templates/apps/api-cms/package.json +11 -10
  202. package/templates/apps/api-cms/queries/content.list.query.ts +23 -7
  203. package/templates/apps/api-cms/tests/accessDecisions.test.ts +121 -0
  204. package/templates/apps/api-cms/tests/content.descriptors.test.ts +8 -4
  205. package/templates/apps/api-collab/mutations/documents.create.mutation.ts +8 -0
  206. package/templates/apps/api-collab/mutations/documents.setBody.mutation.ts +13 -0
  207. package/templates/apps/api-collab/package.json +9 -8
  208. package/templates/apps/api-collab/queries/documents.query.ts +19 -7
  209. package/templates/apps/api-data-advanced/package.json +9 -8
  210. package/templates/apps/api-data-advanced/queries/authors.withBooks.query.ts +12 -0
  211. package/templates/apps/api-data-advanced/queries/books.search.query.ts +9 -0
  212. package/templates/apps/api-durable/mutations/orders.approve.mutation.ts +17 -0
  213. package/templates/apps/api-durable/mutations/orders.place.mutation.ts +9 -0
  214. package/templates/apps/api-durable/package.json +9 -8
  215. package/templates/apps/api-feature-flags/actions/notes.export.action.ts +16 -0
  216. package/templates/apps/api-feature-flags/mutations/notes.create.mutation.ts +12 -0
  217. package/templates/apps/api-feature-flags/package.json +10 -9
  218. package/templates/apps/api-governance/README.md +30 -8
  219. package/templates/apps/api-governance/actions/profiles.get.action.server.ts +17 -1
  220. package/templates/apps/api-governance/actions/profiles.get.action.ts +29 -4
  221. package/templates/apps/api-governance/database/schema.ts +16 -4
  222. package/templates/apps/api-governance/mutations/profiles.create.mutation.ts +12 -0
  223. package/templates/apps/api-governance/package.json +9 -8
  224. package/templates/apps/api-kv/actions/sync.pull.action.ts +15 -0
  225. package/templates/apps/api-kv/actions/sync.reset.action.ts +13 -0
  226. package/templates/apps/api-kv/actions/sync.status.action.ts +7 -0
  227. package/templates/apps/api-kv/package.json +9 -8
  228. package/templates/apps/api-kv/queries/events.list.query.ts +19 -8
  229. package/templates/apps/api-moderation/mutations/comments.create.mutation.ts +11 -0
  230. package/templates/apps/api-moderation/mutations/posts.create.mutation.ts +13 -0
  231. package/templates/apps/api-moderation/package.json +9 -8
  232. package/templates/apps/api-observability/mutations/notes.create.mutation.ts +8 -0
  233. package/templates/apps/api-observability/package.json +9 -8
  234. package/templates/apps/api-observability/queries/notes.list.query.ts +13 -0
  235. package/templates/apps/api-ratelimit/mutations/notes.create.mutation.ts +14 -0
  236. package/templates/apps/api-ratelimit/package.json +9 -8
  237. package/templates/apps/api-rbac/package.json +9 -8
  238. package/templates/apps/api-rest/package.json +8 -7
  239. package/templates/apps/api-saas/mutations/projects.create.mutation.ts +13 -0
  240. package/templates/apps/api-saas/package.json +12 -11
  241. package/templates/apps/api-saas/queries/projects.list.query.ts +11 -0
  242. package/templates/apps/api-saas-starter/actions/me.action.ts +13 -0
  243. package/templates/apps/api-saas-starter/app.config.ts +19 -0
  244. package/templates/apps/api-saas-starter/authz.ts +75 -0
  245. package/templates/apps/api-saas-starter/mutations/invites.create.mutation.ts +10 -0
  246. package/templates/apps/api-saas-starter/mutations/projects.create.mutation.ts +9 -0
  247. package/templates/apps/api-saas-starter/package.json +15 -11
  248. package/templates/apps/api-saas-starter/queries/invites.list.query.ts +19 -8
  249. package/templates/apps/api-saas-starter/queries/projects.list.query.ts +18 -7
  250. package/templates/apps/api-saas-starter/tests/accessDecisions.test.ts +135 -0
  251. package/templates/apps/api-search/mutations/articles.create.mutation.ts +14 -0
  252. package/templates/apps/api-search/package.json +9 -8
  253. package/templates/apps/api-search/queries/articles.list.query.ts +21 -8
  254. package/templates/apps/api-status/README.md +10 -3
  255. package/templates/apps/api-status/app.config.ts +8 -3
  256. package/templates/apps/api-status/authz.ts +5 -3
  257. package/templates/apps/api-status/package.json +9 -8
  258. package/templates/apps/api-status/queries/components.list.query.ts +14 -6
  259. package/templates/apps/api-status/queries/incidents.live.query.ts +23 -10
  260. package/templates/apps/api-status/queries/updates.list.query.ts +16 -9
  261. package/templates/apps/api-status/tests/status.test.ts +9 -1
  262. package/templates/apps/api-versioning/actions/documents.asOf.action.ts +12 -0
  263. package/templates/apps/api-versioning/actions/documents.history.action.ts +13 -0
  264. package/templates/apps/api-versioning/mutations/documents.create.mutation.ts +9 -0
  265. package/templates/apps/api-versioning/mutations/documents.update.mutation.ts +12 -0
  266. package/templates/apps/api-versioning/package.json +9 -8
  267. package/templates/apps/api-webhooks/mutations/orders.fulfill.mutation.ts +16 -0
  268. package/templates/apps/api-webhooks/package.json +10 -9
  269. package/templates/apps/api-webhooks/queries/orders.list.query.ts +10 -0
  270. package/templates/apps/changelog/package.json +8 -6
  271. package/templates/apps/edge-functions/package.json +2 -2
  272. package/templates/apps/frontend-admin/package.json +10 -8
  273. package/templates/apps/frontend-admin/src/lib/admin.ts +20 -9
  274. package/templates/apps/frontend-admin/src/locales/de.ts +11 -1
  275. package/templates/apps/frontend-admin/src/locales/en.ts +13 -1
  276. package/templates/apps/frontend-admin/src/pages/admin/[entity]/page.tsx +65 -22
  277. package/templates/apps/frontend-admin/src/pages/admin/entity.test.tsx +130 -23
  278. package/templates/apps/frontend-admin/src/pages/admin/layout.tsx +3 -2
  279. package/templates/apps/frontend-admin/src/pages/admin/page.test.tsx +19 -2
  280. package/templates/apps/frontend-admin/src/pages/admin/page.tsx +9 -4
  281. package/templates/apps/frontend-app/app.config.ts +4 -3
  282. package/templates/apps/frontend-app/package.json +11 -8
  283. package/templates/apps/frontend-app/src/lib/api.ts +25 -0
  284. package/templates/apps/frontend-app/src/pages/page.test.tsx +130 -82
  285. package/templates/apps/frontend-app/src/pages/page.tsx +14 -18
  286. package/templates/apps/frontend-auth/package.json +10 -8
  287. package/templates/apps/frontend-blank/package.json +9 -7
  288. package/templates/apps/frontend-cms/package.json +11 -9
  289. package/templates/apps/frontend-collab/package.json +12 -9
  290. package/templates/apps/frontend-collab/src/pages/page.test.tsx +122 -78
  291. package/templates/apps/frontend-contact/package.json +9 -7
  292. package/templates/apps/frontend-dashboard/package.json +9 -7
  293. package/templates/apps/frontend-docs/package.json +9 -7
  294. package/templates/apps/frontend-i18n/package.json +8 -6
  295. package/templates/apps/frontend-landing/package.json +9 -7
  296. package/templates/apps/frontend-portal/package.json +10 -8
  297. package/templates/apps/frontend-saas/app.config.ts +10 -6
  298. package/templates/apps/frontend-saas/package.json +10 -8
  299. package/templates/apps/frontend-saas/src/lib/api.ts +27 -32
  300. package/templates/apps/frontend-saas/src/pages/dashboard/billing/page.tsx +7 -8
  301. package/templates/apps/frontend-saas/src/pages/dashboard/page.test.tsx +27 -3
  302. package/templates/apps/frontend-saas/src/pages/dashboard/page.tsx +4 -4
  303. package/templates/apps/frontend-saas/src/pages/dashboard/team/page.tsx +3 -4
  304. package/templates/apps/frontend-spa/package.json +9 -7
  305. package/templates/apps/frontend-ssr/package.json +9 -7
  306. package/templates/apps/frontend-ssr-api/package.json +10 -8
  307. package/templates/apps/frontend-static-blog/package.json +8 -6
  308. package/templates/apps/frontend-status/package.json +10 -8
  309. package/templates/apps/mobile-app/README.md +1 -0
  310. package/templates/apps/mobile-app/package.json +4 -2
  311. package/templates/apps/mobile-app/src/app/index.tsx +22 -12
  312. package/templates/apps/mobile-app/src/app/orders/[id].tsx +1 -1
  313. package/templates/apps/mobile-app/src/lib/api.ts +34 -0
  314. package/templates/apps/mobile-app/voltro.mobile.ts +4 -2
  315. package/templates/baselines/bare/.env.example +14 -0
  316. package/templates/baselines/bare/baseline.json +4 -4
  317. package/templates/baselines/compose/.env.example +14 -0
  318. package/templates/baselines/compose/README.md +1 -1
  319. package/templates/baselines/compose/baseline.json +5 -5
  320. package/templates/baselines/compose-mariadb/.env.example +14 -0
  321. package/templates/baselines/compose-mariadb/README.md +1 -1
  322. package/templates/baselines/compose-mariadb/baseline.json +5 -5
  323. package/templates/baselines/helm/.env.example +14 -0
  324. package/templates/baselines/helm/baseline.json +4 -4
  325. package/dist/apiBuild-C-x9YacA.js +0 -2
  326. package/dist/checkCommand-DRovTKza.js +0 -2
  327. package/dist/commands-CJfepbm4.js +0 -11541
  328. package/dist/dbCommand-b1gum4td.js +0 -2
  329. package/dist/dev-iiMtlkfs.js +0 -3
  330. package/dist/devActivity-BhIu6ncs.js +0 -159
  331. package/dist/frameworkTableAssembly-D-EebUQX.js +0 -2
  332. package/dist/inspect-mmBuRXmy.js +0 -2
  333. package/dist/manifestBuild-Dj8Jjoto.js +0 -2
  334. package/dist/seedRunner-Bqxgp7HZ.js +0 -230
  335. package/dist/serveCommand-DdaM4Hup.js +0 -1608
  336. package/dist/start-C0koT0UO.js +0 -1084
  337. /package/templates/apps/api-ai/actions/{summarize.action.server.tsx → summarize.action.server.ts} +0 -0
@@ -0,0 +1,1647 @@
1
+ import { t as e } from "./nodeEnvironment-cGFAj1J8.js";
2
+ import { t } from "./frameworkInspectState-CX2250XB.js";
3
+ import { r as n, t as r } from "./appModuleLoader-C9r9mxZt.js";
4
+ import { n as i, t as a } from "./startupRunner-DPGFchOa.js";
5
+ import { $ as o, $t as s, A as c, At as l, B as u, Bt as d, C as ee, Ct as f, D as te, Dt as p, E as ne, Et as re, F as ie, G as ae, Gt as oe, H as m, Ht as se, It as ce, J as le, Jt as ue, K as de, Kt as fe, L as pe, Lt as h, M as g, Mt as _, N as me, O as he, Ot as ge, P as _e, Pt as ve, Q as ye, Qt as be, R as xe, Rt as Se, S as v, St as Ce, T as we, Tt as Te, U as Ee, Ut as De, V as Oe, Vt as ke, W as Ae, Wt as y, X as je, Xt as Me, Y as b, Yt as Ne, Z as x, Zt as Pe, _ as Fe, _t as Ie, an as Le, at as Re, b as ze, bt as Be, c as Ve, cn as S, ct as He, dn as C, dt as Ue, en as We, et as Ge, f as Ke, fn as qe, ft as Je, g as Ye, gt as Xe, h as Ze, ht as Qe, i as $e, in as et, it as tt, j as nt, jt as w, k as rt, kt as it, ln as T, lt as at, m as ot, mt as st, nn as ct, nt as lt, o as E, on as ut, ot as dt, p as ft, pt, q as mt, qt as D, r as ht, rn as gt, rt as _t, st as O, t as k, tn as vt, tt as A, u as yt, un as bt, ut as xt, v as St, vt as Ct, w as wt, wt as Tt, x as Et, xt as Dt, y as Ot, yt as kt, z as At, zt as jt } from "./dev-CerMd0mW.js";
6
+ import { n as Mt } from "./cliArgs-D4p8n7EE.js";
7
+ import { r as Nt } from "./appPort-B_HpJ_ck.js";
8
+ import { at as Pt, nt as j, st as M } from "./webDev-CBYvPqQr.js";
9
+ import { r as N } from "./dialectDriver-CgXnDfec.js";
10
+ import { n as Ft } from "./connectionConfig-UFlIEiys.js";
11
+ import { c as It, n as Lt, o as Rt } from "./seedRunner-TFHHiToI.js";
12
+ import { C as zt, S as Bt, _ as Vt, g as P, m as Ht, r as Ut, v as Wt } from "./frameworkTableAssembly-DkkP6BgC.js";
13
+ import { S as Gt, c as Kt, n as F, p as qt, s as Jt, x as Yt } from "./fileConventions-Cof68_BL.js";
14
+ import { h as Xt, o as Zt } from "./inspect-CBqFtAKA.js";
15
+ import { n as Qt } from "./mssqlClusterPatch-_4cE_nun.js";
16
+ import { i as $t, n as en, r as tn, t as nn } from "./webhookDiscovery-D7VaeMlz.js";
17
+ import { t as rn } from "./inspectMetrics-CfdKLh6t.js";
18
+ import { r as an, u as on } from "./apiBuild-DZF_f0_I.js";
19
+ import { t as sn } from "./bootTiming-BdyP9nYw.js";
20
+ import { t as cn } from "./dataProfile-dW-PsfLB.js";
21
+ import { basename as ln, join as un } from "node:path";
22
+ import { existsSync as dn } from "node:fs";
23
+ import { pathToFileURL as fn } from "node:url";
24
+ import { createLogger as I } from "@voltro/logger";
25
+ import { AuthMiddleware as pn, ConnectionInfoMiddleware as mn, actionToRpc as L, anonymousSubject as hn, isWireReachable as gn, mutationToRpc as _n, queryToRpc as R, streamToRpc as vn, workflowCancelDescriptor as z, workflowDomainEventsQueryDescriptor as yn, workflowEventDeliveriesQueryDescriptor as B, workflowResumeDescriptor as V, workflowRunEventsQueryDescriptor as H, workflowRunQueryDescriptor as bn, workflowRunStepsQueryDescriptor as xn, workflowRunsQueryDescriptor as Sn, workflowSignalDescriptor as Cn, workflowUpdateDescriptor as wn } from "@voltro/protocol";
26
+ import { Cause as Tn, Effect as U, Layer as W, ManagedRuntime as En } from "effect";
27
+ import { SqlClient as Dn } from "@effect/sql";
28
+ import { declaredSnapshot as On, describeOutcome as kn, pendingFileMigrationIds as An, runPlannedMigrations as jn } from "@voltro/database/sql";
29
+ import { RpcGroup as Mn } from "@effect/rpc";
30
+ import { allRegisteredTables as Nn, and as G, connectionIdentity as Pn, ensureTableRegistered as Fn, eq as K, or as In } from "@voltro/database";
31
+ import { AggregateRegistry as Ln, CostRegistry as Rn, DORMANCY_WAKEUP_TENANT as zn, Dispatcher as q, ExpectationRegistry as Bn, ExperimentRegistry as Vn, apiKeyManagementRoutes as Hn, attachAnalyticsMirror as Un, attachExpectations as Wn, attachExperiments as Gn, attachFinops as Kn, awaitServerListening as qn, bindMutation as J, bindStream as Jn, bindSubscription as Y, buildTracingLayer as Yn, cancelWakeup as Xn, compileCron as Zn, dataStoreApiKeyStore as Qn, formatServerOnlyLeaks as $n, formatUnresolvedSources as er, frameworkApiKeyStrategy as tr, installPolicyGuardResolver as nr, loadResourceTuples as rr, makeActionRunner as ir, makeAdvisoryLockCoordinator as ar, makeApiKeyService as or, makeApiKeyUsageBuffer as sr, makeApiKeyUsageFlusher as cr, makeAsyncKv as lr, makeAuthMiddlewareLayers as ur, makeCoordinatedScheduler as dr, makeEffectStoreLayer as fr, makeLazyWorkflowFacade as pr, makeMutationOutputCodec as mr, makeMutationRunner as hr, makeOneShotQueryRunner as gr, makeQueryDescriptorProducer as _r, makeQueryFinalizer as vr, makeQueryReauthorizer as yr, makeQuerySubscriber as br, makeSchemaRegistry as xr, makeWorkflowFacade as X, makeWorkflowFacadeWithCallerContext as Sr, makeWorkflowLayers as Cr, noopKv as wr, onProcessShutdown as Tr, recordSubscriptionDelivery as Er, recordWorkflowRun as Z, registerWakeup as Dr, resolveSecretsBackend as Or, runProvidedEffect as kr, setSecretsBackend as Ar, setSystemStoreHandle as jr, setTupleSource as Mr, singleCoordinator as Nr, startRpcServer as Pr, startScheduler as Fr, stripForbiddenForWire as Ir, unresolvedSources as Lr, workflowToRpc as Rr, wrapStoreWithBootCodec as zr } from "@voltro/runtime";
32
+ import { appStorageProvider as Br, fromNodeReadable as Vr, getObjectStream as Hr, putObjectStream as Ur, toNodeReadable as Wr } from "@voltro/plugin-storage";
33
+ import { isEnvContract as Gr } from "@voltro/env";
34
+ import { assertProductionSessionSecret as Kr } from "@voltro/protocol/session";
35
+ import { createHash as qr, timingSafeEqual as Jr } from "node:crypto";
36
+ import { buildDeliverWebhookExecute as Yr, buildWebhooksService as Xr, defaultIncomingPath as Zr, deliverWebhookWorkflow as Qr, makeDeferredEmitHandler as $r, mountIncomingWebhook as ei } from "@voltro/plugin-webhooks";
37
+ import { getAuthSessionStrategy as ti } from "@voltro/plugin-auth";
38
+ import { registerEmailTemplates as ni } from "@voltro/plugin-mail";
39
+ import { channelFor as ri, getBroadcastPlugin as ii } from "@voltro/plugin-broadcast";
40
+ import { packBundle as ai, runExport as oi, runImport as si, storageBlobSink as ci, storageRefsBlobSource as li, unpackBundle as ui, unpackBundleToDir as di } from "@voltro/data-transfer";
41
+ //#region src/dbPoolReport.ts
42
+ var fi = (e, t, n = [], r = 0) => {
43
+ let i = n.length, a = 1 + Math.max(0, r), o = e === void 0 ? void 0 : e * a + i, s = o !== void 0 && t !== void 0 ? o * t : void 0, c = i === 0 ? " No connections outside the pool in this process." : ` PLUS ${i} outside the pool (${n.map((e) => e.reason).join("; ")}) — those do not come out of the pool budget, they come out of the DATABASE's.`, l = r > 0 ? ` This process opens ${a} pools of that size — 1 primary + ${r} read replica(s) (DB_REPLICA_URLS), each with its own DB_MAX_CONNECTIONS.` : "";
44
+ if (e === void 0) return "db pool: max per replica UNSET (DB_MAX_CONNECTIONS) — each replica opens the driver's default pool, so the fleet total is that default × replicas. Set DB_MAX_CONNECTIONS so the total stays under your database's connection limit; the pool scales with replicaCount and the database does not." + l + c + pi;
45
+ let u = (r > 0 ? `max × ${a}` : "max") + (i === 0 ? "" : ` + ${i}`), d = r === 0 ? i === 0 ? "" : ` + ${i} = ${o}` : ` → ${u} = ${o} per pod`, ee = r === 0 && i === 0 ? "max" : `(${u})`;
46
+ return `db pool: max=${e} per replica (DB_MAX_CONNECTIONS)` + d + (s === void 0 ? ` — the fleet opens up to ${ee} × replicas connections. Check that against your database's limit before raising replicaCount.` : ` × ${t} replicas = up to ${s} connections. Check that against your database's limit.`) + l + c + pi;
47
+ }, pi = " A rolling update runs BOTH generations at once, so budget for (replicas + surge), not replicas — a surge pod that cannot get a connection crashloops, and a rollout that never completes cannot free the connections it is waiting for.", mi = (e = process.env) => {
48
+ let t = e.REPLICA_COUNT;
49
+ if (t === void 0 || t === "") return;
50
+ let n = Number(t);
51
+ return Number.isInteger(n) && n > 0 ? n : void 0;
52
+ }, hi = "/_voltro/admin/import", gi = "/_voltro/admin/export", Q = (e, t) => ({
53
+ status: e,
54
+ contentType: "application/json; charset=utf-8",
55
+ body: JSON.stringify(t)
56
+ }), _i = (e) => {
57
+ let t = e.authorization ?? e.Authorization, n = t ? /^Bearer\s+(.+)$/i.exec(t) : null;
58
+ return n ? n[1] : null;
59
+ }, vi = (e, t) => Jr(qr("sha256").update(e).digest(), qr("sha256").update(t).digest()), yi = (e, t) => {
60
+ if (e.method.toUpperCase() !== "POST") return Q(405, { error: "method not allowed" });
61
+ if (!t || t.length < 16) return Q(503, { error: "data transfer misconfigured (no/weak secret)" });
62
+ let n = _i(e.headers);
63
+ return !n || !vi(n, t) ? Q(401, { error: "unauthorized" }) : null;
64
+ }, bi = I({ scope: "voltro:admin-import" }), xi = "VBUNDLE2", Si = async function* (e) {
65
+ yield e;
66
+ }, Ci = (e) => async (t) => {
67
+ let n = yi(t, e.secret);
68
+ if (n) return n;
69
+ let r = t.headers["x-import-mode"], i = t.headers["x-import-on-conflict"], a = t.headers["x-import-atomic"] === "1" || t.headers["x-import-atomic"] === "true", o = t.headers["x-import-force"] === "1" || t.headers["x-import-force"] === "true", s = t.rawBody.byteLength >= 8 && Buffer.from(t.rawBody.subarray(0, 8)).toString("latin1") === xi, c, l;
70
+ if (s) c = Si(t.rawBody), l = "upload";
71
+ else {
72
+ let n;
73
+ try {
74
+ n = JSON.parse(Buffer.from(t.rawBody).toString("utf8") || "{}");
75
+ } catch {
76
+ return Q(400, { error: "body must be a packed bundle archive or { bundleKey } JSON" });
77
+ }
78
+ if (typeof n.bundleKey != "string" || !n.bundleKey) return Q(400, { error: "body.bundleKey (string) is required for the storage transport" });
79
+ if (!e.openArchive) return Q(501, { error: "storage transport not configured on this instance" });
80
+ c = e.openArchive(n.bundleKey), l = "storage";
81
+ }
82
+ let u = await import("node:os"), d = await import("node:fs/promises"), ee = await import("node:path"), f = await d.mkdtemp(ee.join(u.tmpdir(), "voltro-admin-import-"));
83
+ try {
84
+ e.assetSink ? await ui(c, {
85
+ dir: f,
86
+ blobs: e.assetSink
87
+ }) : await di(c, f);
88
+ let t = await U.runPromiseExit(si({
89
+ store: e.store,
90
+ bundleDir: f,
91
+ ...r ? { mode: r } : {},
92
+ ...i ? { onConflict: i } : {},
93
+ ...a ? { atomic: a } : {},
94
+ ...e.snapshot ? { targetSnapshot: e.snapshot } : {},
95
+ force: o,
96
+ onWarn: (e) => bi.warn("admin.import", { message: e }),
97
+ ...e.assetSink ? { assetsAlreadyRestored: !0 } : {}
98
+ }));
99
+ if (t._tag === "Failure") {
100
+ let e = t.cause._tag === "Fail" ? t.cause.error : void 0;
101
+ if (e && e._tag === "SchemaDriftError") {
102
+ let t = e;
103
+ return bi.warn("admin.import refused (schema drift)", {
104
+ transport: l,
105
+ bundle: t.bundleFingerprint.slice(0, 16),
106
+ target: t.targetFingerprint.slice(0, 16)
107
+ }), Q(409, {
108
+ error: "schema drift",
109
+ bundleFingerprint: t.bundleFingerprint,
110
+ targetFingerprint: t.targetFingerprint,
111
+ diff: t.diff,
112
+ hint: "re-export against the current schema, or resend with x-import-force: 1"
113
+ });
114
+ }
115
+ throw Error(String(e?.message ?? e ?? "import failed"));
116
+ }
117
+ let n = t.value, s = n.tables.reduce((e, t) => e + t.rowCount, 0);
118
+ return bi.info("admin.import", {
119
+ transport: l,
120
+ tables: n.tables.length,
121
+ rows: s,
122
+ mode: r ?? "upsert",
123
+ atomic: a
124
+ }), Q(200, {
125
+ tables: n.tables.length,
126
+ rows: s,
127
+ transport: l
128
+ });
129
+ } catch (e) {
130
+ return bi.warn("admin.import failed", {
131
+ transport: l,
132
+ error: e?.message ?? String(e)
133
+ }), Q(500, {
134
+ error: "import failed",
135
+ message: e?.message ?? String(e)
136
+ });
137
+ } finally {
138
+ await d.rm(f, {
139
+ recursive: !0,
140
+ force: !0
141
+ });
142
+ }
143
+ }, wi = I({ scope: "voltro:admin-export" }), Ti = async (e) => {
144
+ let t = [];
145
+ for await (let n of e) t.push(Buffer.from(n));
146
+ return new Uint8Array(Buffer.concat(t));
147
+ }, Ei = (e) => typeof e.tenant == "string" && e.tenant ? {
148
+ kind: "tenant",
149
+ tenantId: e.tenant
150
+ } : Array.isArray(e.tables) && e.tables.length ? {
151
+ kind: "tables",
152
+ tables: e.tables.filter((e) => typeof e == "string")
153
+ } : { kind: "all" }, Di = (e) => async (t) => {
154
+ let n = yi(t, e.secret);
155
+ if (n) return n;
156
+ let r;
157
+ try {
158
+ r = JSON.parse(Buffer.from(t.rawBody).toString("utf8") || "{}");
159
+ } catch {
160
+ return Q(400, { error: "body must be JSON: { profile?, tenant?, tables?, consistency?, compression?, bundleKey? }" });
161
+ }
162
+ let i = {};
163
+ if (typeof r.profile == "string" && r.profile) {
164
+ if (!e.loadProfile) return Q(501, { error: "server-side profiles not configured on this instance" });
165
+ try {
166
+ i = await e.loadProfile(r.profile);
167
+ } catch (e) {
168
+ return Q(400, {
169
+ error: `profile '${r.profile}' could not be loaded`,
170
+ message: e?.message ?? String(e)
171
+ });
172
+ }
173
+ }
174
+ let a = r.consistency === "snapshot" ? "snapshot" : i.consistency ?? "live", o = (typeof r.compression == "string" ? r.compression : void 0) ?? i.compression, s = i.scope ?? Ei(r), c = typeof r.bundleKey == "string" && r.bundleKey.length > 0, l = r.assets === !0 && e.assetSource ? { blobs: e.assetSource } : {}, u = await import("node:os"), d = await import("node:fs/promises"), ee = await import("node:path"), f = await d.mkdtemp(ee.join(u.tmpdir(), "voltro-admin-export-"));
175
+ try {
176
+ let t = await U.runPromise(oi({
177
+ store: e.store,
178
+ snapshot: e.snapshot,
179
+ dialect: e.dialect,
180
+ outDir: f,
181
+ ...i.subset ? { subset: i.subset } : {
182
+ scope: s,
183
+ ...e.tenantTables && e.tenantTables.length > 0 ? { tenantTables: e.tenantTables } : {}
184
+ },
185
+ consistency: a,
186
+ ...o ? { compression: o } : {},
187
+ ...i.masking ? { masking: i.masking } : {}
188
+ })), n = t.tables.reduce((e, t) => e + t.rowCount, 0), u = t.masking?.transformed.length ?? 0;
189
+ if (c) {
190
+ if (!e.putArchive) return Q(501, { error: "storage transport not configured on this instance" });
191
+ let i = r.bundleKey;
192
+ return await e.putArchive(i, () => ai({
193
+ dir: f,
194
+ ...l
195
+ })), wi.info("admin.export", {
196
+ transport: "storage",
197
+ tables: t.tables.length,
198
+ rows: n,
199
+ masked: u,
200
+ bundleKey: i
201
+ }), Q(200, {
202
+ bundleKey: i,
203
+ tables: t.tables.length,
204
+ rows: n,
205
+ masked: u,
206
+ transport: "storage"
207
+ });
208
+ }
209
+ let d = await Ti(ai({
210
+ dir: f,
211
+ ...l
212
+ }));
213
+ return wi.info("admin.export", {
214
+ transport: "download",
215
+ tables: t.tables.length,
216
+ rows: n,
217
+ masked: u,
218
+ bytes: d.byteLength
219
+ }), {
220
+ status: 200,
221
+ contentType: "application/octet-stream",
222
+ body: d,
223
+ headers: {
224
+ "x-export-tables": String(t.tables.length),
225
+ "x-export-rows": String(n),
226
+ "x-export-masked": String(u)
227
+ }
228
+ };
229
+ } catch (e) {
230
+ return wi.warn("admin.export failed", { error: e?.message ?? String(e) }), Q(500, {
231
+ error: "export failed",
232
+ message: e?.message ?? String(e)
233
+ });
234
+ } finally {
235
+ await d.rm(f, {
236
+ recursive: !0,
237
+ force: !0
238
+ });
239
+ }
240
+ }, Oi = (e, t, n = {}) => (async function* () {
241
+ let r = await Wr((await U.runPromise(Hr(e, t).pipe(U.timeout(n.openTimeout ?? "30 seconds")))).stream), i = n.stallMs ?? 12e4, a, o = () => {
242
+ a && clearTimeout(a), a = setTimeout(() => r.destroy(/* @__PURE__ */ Error(`storage read stalled for ${i}ms reading '${t}'`)), i);
243
+ };
244
+ try {
245
+ o();
246
+ for await (let e of r) o(), yield e instanceof Uint8Array ? e : new Uint8Array(e);
247
+ } finally {
248
+ a && clearTimeout(a), r.destroy();
249
+ }
250
+ })(), ki = {
251
+ get: async () => void 0,
252
+ set: async () => {},
253
+ setWithTags: async () => {},
254
+ remove: async () => !1,
255
+ has: async () => !1,
256
+ clear: async () => {},
257
+ invalidateTag: async () => 0,
258
+ wrap: async (e, t, n) => n()
259
+ }, Ai = async (e) => {
260
+ _(e.appProcedures ?? e.discovered, {
261
+ defaultDeny: e.security?.defaultDeny ?? !0,
262
+ commandHint: "`voltro serve`"
263
+ }), jr({
264
+ dataStore: e.store,
265
+ schemaRegistry: e.schemaRegistry
266
+ });
267
+ let t = (e.discovered.budgets?.length ?? 0) > 0, n, r = new q({
268
+ store: e.store,
269
+ ...e.snapshotCache ? { cache: e.snapshotCache } : {},
270
+ ...t ? { recordCost: (e) => n?.record(e) } : {},
271
+ recordDelivery: (e) => Er({
272
+ label: e.label,
273
+ kind: e.kind,
274
+ durationMs: e.durationMs,
275
+ rowCount: e.rowCount
276
+ })
277
+ }), i = e.cache ?? ki, a = e.kv ?? wr, o, ee = () => void 0, f, te, p, ne, ie, ae, oe, se = Se({
278
+ store: e.store,
279
+ warn: (e, t) => {
280
+ process.stderr.write(`[workflow] ${e} ${JSON.stringify(t)}\n`);
281
+ }
282
+ }), ce = se.remember, de = se.resolve, fe = jt({
283
+ authority: e.authority,
284
+ getStore: () => e.store
285
+ }), h = (e.discovered.workflows?.length ?? 0) > 0 ? pr(() => o) : void 0, he = (e.discovered.workflows?.length ?? 0) > 0 || (e.discovered.eventTriggers?.length ?? 0) > 0, ge = he || (e.discovered.workflowWorkers?.length ?? 0) > 0 || e.scheduleCoordination === "cluster", _e = e.tenantIsolation === "namespace", ve = (e.log ?? I({ scope: "voltro:serve" })).child("webhooks"), ye, be, v = e.discovered.webhooks;
286
+ if (v && v.outgoing.length > 0 && e.workflowEngineLayer !== void 0) {
287
+ e.workflowEngineLayer;
288
+ let t = vt({
289
+ store: e.store,
290
+ schemaRegistry: e.schemaRegistry,
291
+ cache: i,
292
+ kv: a
293
+ }), n = v.outgoing.map((e) => e.descriptor);
294
+ be = Qr.toLayer(Yr(t, { events: n })), ye = Xr(t, async (e) => {
295
+ let t = p;
296
+ if (t === void 0) {
297
+ ve.error("webhook delivery skipped — the workflow runtime was never built. This is a framework defect, not a configuration problem: report it with your engine setting. Deliveries are NOT queued and will not be retried.", {
298
+ deliveryId: e.deliveryId,
299
+ targetId: e.targetId
300
+ });
301
+ return;
302
+ }
303
+ t.runPromise(Qr.execute(e)).catch((t) => {
304
+ ve.error("deliverWebhook workflow crashed", {
305
+ deliveryId: e.deliveryId,
306
+ targetId: e.targetId
307
+ }, t);
308
+ });
309
+ }, { events: n });
310
+ }
311
+ let Ce = /* @__PURE__ */ new Map();
312
+ if (v) for (let e of v.incoming) {
313
+ let t = e.descriptor.path ?? Zr(e.descriptor.id), n = `VOLTRO_WEBHOOK_SECRET_${e.descriptor.id.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`, r = ei(e.descriptor, {
314
+ resolveSecret: async () => process.env[n] ?? null,
315
+ resolveWorkflows: () => h === void 0 ? void 0 : Sr(h, {
316
+ traceId: `incoming:${e.descriptor.id}`,
317
+ source: `incoming:${e.descriptor.id}`
318
+ }),
319
+ log: (e) => {
320
+ let t = {
321
+ webhookId: e.webhookId,
322
+ status: e.status,
323
+ signatureOk: String(e.signatureOk),
324
+ idempotency: e.idempotency,
325
+ durationMs: e.durationMs
326
+ };
327
+ e.status >= 500 ? ve.error("incoming delivery failed", t) : e.status >= 400 ? ve.warn("incoming delivery rejected", t) : ve.info("incoming delivery handled", t);
328
+ }
329
+ });
330
+ Ce.set(t, { handle: r });
331
+ }
332
+ nr(), Mr((t) => rr(e.store, t.subjectId, t.resourceType, t.resourceId));
333
+ let we = [], Ee = [...e.discovered.outboxHandlers ?? [], ...en((v?.outgoing.length ?? 0) + (v?.incoming.length ?? 0) + (v?.providers.length ?? 0), []) ? [{
334
+ file: "<framework>/webhooks",
335
+ id: "voltro-webhook-emit",
336
+ definition: $r(() => ye)
337
+ }] : []], Ne = Ee.length > 0 ? De({
338
+ handlers: Ee,
339
+ store: e.store,
340
+ log: (e.log ?? I({ scope: "voltro:serve" })).child("outbox"),
341
+ onChange: (t) => e.store.onChange((e) => t({
342
+ table: e.table,
343
+ op: e.op
344
+ })),
345
+ onShutdown: (e) => {
346
+ we.push(e);
347
+ }
348
+ }) : void 0, x = ke({
349
+ definitions: (e.discovered.connections ?? []).map((e) => e.definition),
350
+ store: e.store,
351
+ publicUrl: d(e.port ?? 4e3),
352
+ log: (e.log ?? I({ scope: "voltro:serve" })).child("connections")
353
+ });
354
+ rt({
355
+ events: e.discovered.events ?? [],
356
+ rpcTags: [
357
+ ...e.discovered.queries.map((e) => e.descriptor.name),
358
+ ...e.discovered.mutations.map((e) => e.descriptor.name),
359
+ ...e.discovered.actions.map((e) => e.descriptor.name),
360
+ ...(e.discovered.streams ?? []).map((e) => e.descriptor.name)
361
+ ]
362
+ });
363
+ let Pe = (e.log ?? I({ scope: "voltro:serve" })).child("events"), Ie = e.broadcastNamespace ?? Ze(e.plugins, void 0), Le = Ye(e.plugins, Ie, Pe), ze = e.membership?.instanceId ?? process.env.POD_NAME ?? process.env.HOSTNAME ?? `serve-${process.pid}`, Ve = e.membership ?? Fe(e.plugins, {
364
+ instanceId: ze,
365
+ namespace: Ie,
366
+ meta: { mode: "serve" },
367
+ logger: Pe
368
+ }), S = c({
369
+ events: e.discovered.events ?? [],
370
+ origin: ze,
371
+ ...Le.publishRemote === void 0 ? {} : { publishRemote: Le.publishRemote }
372
+ }), He = (e.discovered.events ?? []).length > 0 ? await Le.attach(S.bus) : null, C = We({
373
+ store: e.store,
374
+ schemaRegistry: e.schemaRegistry,
375
+ cache: i,
376
+ kv: a,
377
+ ...ye === void 0 ? {} : { webhooksService: ye },
378
+ ...h === void 0 ? {} : { workflowsProxy: h },
379
+ eventTriggers: e.discovered.eventTriggers ?? [],
380
+ namespaceIsolationOn: _e,
381
+ ...Ne === void 0 ? {} : { outbox: { nudge: Ne.nudge } },
382
+ ...x.active ? { connections: { registry: x.registry } } : {},
383
+ eventBus: S.bus
384
+ }), Ge = W.succeed(Ln, Dt), Ke = W.succeed(Bn, Qe), qe = W.succeed(Rn, st), Je = W.succeed(Vn, Xe), $e = (t, n) => {
385
+ let r = t.pipe(U.provide(fr(n)));
386
+ return (e.baseLayer ? r.pipe(U.provide(e.baseLayer)) : r).pipe(U.provide(Ge)).pipe(U.provide(Ke)).pipe(U.provide(qe)).pipe(U.provide(Je));
387
+ }, et = (e, t) => kr($e(e, t)), w = rn(), T = Ae(e.plugins ?? [], w), at = pe({
388
+ plugins: e.plugins ?? [],
389
+ metrics: w,
390
+ log: e.log ?? I({ scope: "voltro:serve" })
391
+ }), ot = m(e.plugins ?? [], w), ct = hr({
392
+ store: e.store,
393
+ recordMetric: (e) => {
394
+ w.record(e);
395
+ },
396
+ ...T.mutation === void 0 ? {} : { interceptor: T.mutation },
397
+ buildContext: (e, t, n) => C(e, t, n),
398
+ runEffect: et,
399
+ undoCapture: b()
400
+ }), lt = le();
401
+ {
402
+ let t = je();
403
+ t !== void 0 && (e.log ?? I({ scope: "voltro:serve" })).info(t);
404
+ }
405
+ let E = mt({
406
+ store: e.store,
407
+ ...e.approvals === void 0 ? {} : { defaultExpiryMs: e.approvals.defaultExpiryMs }
408
+ }), ut = ir({
409
+ buildContext: (e) => C(e),
410
+ runEffect: et,
411
+ recordMetric: (e) => {
412
+ w.record(e);
413
+ },
414
+ ...T.action === void 0 ? {} : { interceptor: T.action }
415
+ }), ft = vr({
416
+ tenantScopedTables: e.tenantScopedTables,
417
+ softDeleteScopedTables: e.softDeleteScopedTables
418
+ }), pt = {
419
+ buildContext: (e) => C(e),
420
+ finalize: (e, t) => ft(e, t.subject),
421
+ provideEffect: $e,
422
+ ...T.query === void 0 ? {} : { interceptor: T.query }
423
+ }, D = _r(pt), ht = gr({
424
+ ...pt,
425
+ queryRows: (t, n) => e.store.query(t).then((e) => Ir(t.table, e, n.subject))
426
+ }), gt = br({
427
+ ...pt,
428
+ subscribeDescriptor: (e, t, n) => r.subscribe(e, t, n),
429
+ subscribeComputed: (e, t, n) => r.subscribeComputed(e, t, n)
430
+ }), k = (e) => e.filter((e) => gn(e.descriptor)), A = {};
431
+ for (let t of [
432
+ ...k(e.discovered.queries),
433
+ ...lt.queries,
434
+ ...E.queries,
435
+ ...x.queries
436
+ ]) A[t.descriptor.name] = (e) => Y(D(t, e), r, `subscription.${t.descriptor.name}`, void 0, void 0, yr(t, e));
437
+ for (let t of [
438
+ ...k(e.discovered.mutations),
439
+ ...lt.mutations,
440
+ ...E.mutations,
441
+ ...x.mutations
442
+ ]) {
443
+ let n = mr(t.descriptor.output);
444
+ A[t.descriptor.name] = (r) => J(async (e, n) => ct(t, e, n), r, `mutation.${t.descriptor.name}`, n, e.idempotency, t.descriptor.error);
445
+ }
446
+ for (let t of [...k(e.discovered.actions), ...x.actions]) {
447
+ let n = mr(t.descriptor.output);
448
+ A[t.descriptor.name] = (r) => J(async (e, n) => ut(t, e, n), r, `action.${t.descriptor.name}`, n, e.idempotency, t.descriptor.error);
449
+ }
450
+ let yt = () => `public-${Math.random().toString(36).slice(2, 10)}`, xt = [
451
+ ...e.discovered.queries.filter((e) => e.descriptor.publicApi !== void 0).map((e) => ({
452
+ descriptor: e.descriptor,
453
+ invoke: (t, n) => ht(e, t, {
454
+ subject: n.subject,
455
+ traceId: yt()
456
+ }),
457
+ subscribe: (t, n, r) => gt(e, t, {
458
+ subject: n.subject,
459
+ traceId: yt()
460
+ }, r)
461
+ })),
462
+ ...e.discovered.mutations.filter((e) => e.descriptor.publicApi !== void 0).map((e) => ({
463
+ descriptor: e.descriptor,
464
+ invoke: (t, n) => ct(e, t, {
465
+ subject: n.subject,
466
+ traceId: yt()
467
+ })
468
+ })),
469
+ ...e.discovered.actions.filter((e) => e.descriptor.publicApi !== void 0).map((e) => ({
470
+ descriptor: e.descriptor,
471
+ invoke: (t, n) => ut(e, t, {
472
+ subject: n.subject,
473
+ traceId: yt()
474
+ })
475
+ }))
476
+ ], St = {
477
+ candidates: l({
478
+ queries: e.discovered.queries,
479
+ mutations: e.discovered.mutations,
480
+ actions: e.discovered.actions,
481
+ descriptorOf: (e) => e.descriptor,
482
+ runQuery: (e, t, n) => Promise.resolve(ht(e, t, n)),
483
+ runMutation: (e, t, n) => Promise.resolve(ct(e, t, n)),
484
+ runAction: (e, t, n) => Promise.resolve(ut(e, t, n))
485
+ }),
486
+ policy: e.agents?.tools ?? {},
487
+ mcpEnabled: e.agents?.mcp === !0,
488
+ resolveSubject: (t) => e.resolveSubject(t, -1).then((e) => e.subject)
489
+ }, Ct = ue({
490
+ ...e.restRoutes === void 0 ? {} : { restRoutes: e.restRoutes },
491
+ publicApiEntries: xt,
492
+ store: e.store,
493
+ resolveSubject: (t) => e.resolveSubject(t, -1).then((e) => e.subject),
494
+ ...e.idempotency === void 0 ? {} : { idempotency: e.idempotency },
495
+ log: e.log ?? I({ scope: "voltro:serve" })
496
+ }), wt = e.dataTransferSecret ?? process.env.VOLTRO_DATA_TRANSFER_SECRET, Tt = wt && wt.length >= 16 ? [{
497
+ method: "POST",
498
+ path: hi,
499
+ handle: Ci({
500
+ secret: wt,
501
+ store: e.store,
502
+ ...e.dataTransferSnapshot ? { snapshot: e.dataTransferSnapshot } : {},
503
+ assetSink: ci(Br()),
504
+ openArchive: (e) => Oi(Br(), e)
505
+ })
506
+ }, {
507
+ method: "POST",
508
+ path: gi,
509
+ handle: Di({
510
+ secret: wt,
511
+ store: e.store,
512
+ snapshot: e.dataTransferSnapshot ?? { tables: [] },
513
+ dialect: e.dataTransferDialect ?? "memory",
514
+ tenantTables: [...e.tenantScopedTables],
515
+ loadProfile: cn,
516
+ assetSource: li(Br(), e.store),
517
+ putArchive: async (e, t) => {
518
+ let { Readable: n } = await import("node:stream"), r = Br(), i = Vr("storage", () => n.from(t()));
519
+ await U.runPromise(Ur(r, e, i, { contentType: "application/octet-stream" }));
520
+ }
521
+ })
522
+ }] : [], Et = [
523
+ ...e.httpRoutes ?? [],
524
+ ...Ct.httpRoutes,
525
+ ...Tt,
526
+ ...x.httpRoutes
527
+ ];
528
+ Object.assign(A, S.handlers);
529
+ for (let t of k(e.discovered.streams ?? [])) A[t.descriptor.name] = (n) => Jn((r) => {
530
+ let i = C(r), a = t.executor(n, i);
531
+ if (U.isEffect(a)) {
532
+ let t = a.pipe(U.provide(fr(i.store)));
533
+ return (e.baseLayer ? t.pipe(U.provide(e.baseLayer)) : t).pipe(U.provide(Ge)).pipe(U.provide(Ke)).pipe(U.provide(qe)).pipe(U.provide(Je));
534
+ }
535
+ return typeof a == "object" && a && typeof a.then == "function" ? U.promise(() => a) : a;
536
+ }, `stream.${t.descriptor.name}`);
537
+ for (let t of e.discovered.workflows ?? []) A[t.definition.name] = (e) => J(async (e, n) => {
538
+ let r = n;
539
+ return Sr(h, {
540
+ subject: r.subject,
541
+ traceId: r.traceId,
542
+ source: "workflow-rpc"
543
+ }).start(t.definition.name, e);
544
+ }, e, `workflow.${t.definition.name}`);
545
+ he && (A[bn.name] = (e) => Y(D({
546
+ descriptor: bn,
547
+ executor: (e) => {
548
+ let t = e.id;
549
+ return {
550
+ table: "_voltro_workflow_runs",
551
+ order: [{
552
+ column: "startedAt",
553
+ direction: "desc"
554
+ }],
555
+ predicate: In(K("id", t), K("executionId", t)),
556
+ take: 1,
557
+ skip: void 0,
558
+ projection: void 0
559
+ };
560
+ }
561
+ }, e), r, `subscription.${bn.name}`), A[Sn.name] = (e) => Y(D({
562
+ descriptor: Sn,
563
+ executor: (e) => {
564
+ let t = e, n = [...t.tag === void 0 ? [] : [K("tag", t.tag)], ...t.status === void 0 ? [] : [K("status", t.status)]], r = Number.isFinite(t.limit) && t.limit !== void 0 ? Math.min(Math.max(Math.floor(t.limit), 1), 500) : 100;
565
+ return {
566
+ table: "_voltro_workflow_runs",
567
+ order: [{
568
+ column: "startedAt",
569
+ direction: "desc"
570
+ }],
571
+ predicate: n.length === 0 ? void 0 : n.length === 1 ? n[0] : G(...n),
572
+ take: r,
573
+ skip: void 0,
574
+ projection: void 0
575
+ };
576
+ }
577
+ }, e), r, `subscription.${Sn.name}`), A[xn.name] = (e) => Y(D({
578
+ descriptor: xn,
579
+ executor: (e) => {
580
+ let t = e.runId;
581
+ return {
582
+ table: "_voltro_workflow_run_steps",
583
+ order: [{
584
+ column: "startedAt",
585
+ direction: "asc"
586
+ }],
587
+ predicate: K("runId", t),
588
+ take: 1e3,
589
+ skip: void 0,
590
+ projection: void 0
591
+ };
592
+ }
593
+ }, e), r, `subscription.${xn.name}`), A[H.name] = (e) => Y(D({
594
+ descriptor: H,
595
+ executor: (e) => {
596
+ let t = e.runId;
597
+ return {
598
+ table: "_voltro_workflow_run_events",
599
+ order: [{
600
+ column: "occurredAt",
601
+ direction: "asc"
602
+ }],
603
+ predicate: K("runId", t),
604
+ take: 1e3,
605
+ skip: void 0,
606
+ projection: void 0
607
+ };
608
+ }
609
+ }, e), r, `subscription.${H.name}`), A[yn.name] = (e) => Y(D({
610
+ descriptor: yn,
611
+ executor: (e) => {
612
+ let t = e;
613
+ return {
614
+ table: "_voltro_workflow_events",
615
+ order: [{
616
+ column: "occurredAt",
617
+ direction: "desc"
618
+ }],
619
+ predicate: t.name === void 0 ? void 0 : K("name", t.name),
620
+ take: Math.max(1, Math.min(500, t.limit ?? 100)),
621
+ skip: void 0,
622
+ projection: void 0
623
+ };
624
+ }
625
+ }, e), r, `subscription.${yn.name}`), A[B.name] = (e) => Y(D({
626
+ descriptor: B,
627
+ executor: (e) => {
628
+ let t = e.eventId;
629
+ return {
630
+ table: "_voltro_workflow_event_deliveries",
631
+ order: [{
632
+ column: "createdAt",
633
+ direction: "asc"
634
+ }],
635
+ predicate: K("eventId", t),
636
+ take: 500,
637
+ skip: void 0,
638
+ projection: void 0
639
+ };
640
+ }
641
+ }, e), r, `subscription.${B.name}`), A[z.name] = (t) => J(async (t, n) => {
642
+ let r = t;
643
+ return await s(e.store, n.subject, { executionId: r.executionId }), await h.cancel(r.workflowName, r.executionId), await Ft(r.workflowName, r.executionId, "workflow.cancel"), { ok: !0 };
644
+ }, t, `action.${z.name}`), A[V.name] = (t) => J(async (t, n) => {
645
+ let r = t;
646
+ return await s(e.store, n.subject, { executionId: r.executionId }), await h.resume(r.workflowName, r.executionId), { ok: !0 };
647
+ }, t, `action.${V.name}`), A[Cn.name] = (t) => J(async (t, n) => {
648
+ let r = t;
649
+ return await s(e.store, n.subject, { id: r.id }), h.signal({ id: r.id }, r.signalName, r.payload);
650
+ }, t, `action.${Cn.name}`), A[wn.name] = (t) => J(async (t, n) => {
651
+ let r = t;
652
+ return await s(e.store, n.subject, { id: r.id }), h.update({ id: r.id }, r.updateName, r.payload, r.timeoutMs === void 0 ? void 0 : { timeoutMs: r.timeoutMs });
653
+ }, t, `action.${wn.name}`));
654
+ let Ot = [
655
+ ...k(e.discovered.queries).map((e) => R(e.descriptor)),
656
+ ...k(e.discovered.mutations).map((e) => _n(e.descriptor)),
657
+ ...k(e.discovered.actions).map((e) => L(e.descriptor)),
658
+ ...lt.queries.map((e) => R(e.descriptor)),
659
+ ...lt.mutations.map((e) => _n(e.descriptor)),
660
+ ...E.queries.map((e) => R(e.descriptor)),
661
+ ...E.mutations.map((e) => _n(e.descriptor)),
662
+ ...x.queries.map((e) => R(e.descriptor)),
663
+ ...x.mutations.map((e) => _n(e.descriptor)),
664
+ ...x.actions.map((e) => L(e.descriptor)),
665
+ ...k(e.discovered.streams ?? []).map((e) => vn(e.descriptor)),
666
+ ...S.rpcs,
667
+ ...(e.discovered.workflows ?? []).map((e) => Rr(e.definition)),
668
+ ...he ? [
669
+ R(bn),
670
+ R(Sn),
671
+ R(xn),
672
+ R(H),
673
+ R(yn),
674
+ R(B),
675
+ L(z),
676
+ L(V),
677
+ L(Cn),
678
+ L(wn)
679
+ ] : []
680
+ ], kt = Mn.make(...Ot).middleware(pn).middleware(mn), Mt = ur({ resolveSubject: ({ headers: t, clientId: n }) => e.resolveSubject(t, n) }), Nt = e.dormancyTenantId ?? zn, Pt = e.dormancy === "sleep" ? {
681
+ register: (t, n, r) => Dr(e.store, {
682
+ tenantId: r ?? Nt,
683
+ kind: "workflow",
684
+ refId: t,
685
+ wakeAt: n
686
+ }),
687
+ cancel: (t, n) => Xn(e.store, {
688
+ tenantId: n ?? Nt,
689
+ kind: "workflow",
690
+ refId: t
691
+ }).then(() => {})
692
+ } : void 0, j = ge ? await import("@voltro/workflow") : void 0, M = j?.makeWorkflowRunRecorder({
693
+ store: e.store,
694
+ ...Pt === void 0 ? {} : { wakeups: Pt }
695
+ }), N = async (t, n) => {
696
+ await j.closeWorkflowChildrenForParent({
697
+ store: e.store,
698
+ parentExecutionId: t,
699
+ parentStatus: n,
700
+ recorder: M,
701
+ log: { warn: (e, t) => {
702
+ process.stderr.write(`[workflow] ${e} ${t ? JSON.stringify(t) : ""}\n`);
703
+ } },
704
+ interruptChild: async (t, n) => {
705
+ let r = (e.discovered.workflows ?? []).find((e) => e.definition.name === t);
706
+ if (!r) throw Error(`Unknown child workflow: ${t}`);
707
+ if (!p) throw Error("Workflow runtime is not ready");
708
+ await p.runPromise(r.definition.interrupt(n));
709
+ }
710
+ });
711
+ }, Ft = async (t, n, r) => {
712
+ let i = (await e.store.query({
713
+ table: "_voltro_workflow_runs",
714
+ order: [],
715
+ predicate: K("executionId", n),
716
+ projection: void 0,
717
+ skip: void 0,
718
+ take: 1
719
+ }))[0];
720
+ if (i === void 0) return;
721
+ let a = await e.store.update("_voltro_workflow_runs", i.id, {
722
+ status: "cancelled",
723
+ cancelled: !0,
724
+ completedAt: /* @__PURE__ */ new Date()
725
+ }), o = i.subject?.tenantId ?? void 0;
726
+ a && await M.recordEvent({
727
+ runId: i.id,
728
+ eventType: "run-cancelled",
729
+ payload: {
730
+ reason: r,
731
+ workflowName: t,
732
+ executionId: n,
733
+ ...o == null ? {} : { tenantId: o }
734
+ }
735
+ }), a && await N(n, "cancelled");
736
+ }, It = [
737
+ ...Cr(e.discovered.workflows ?? [], {
738
+ buildContext: (t, n) => e.buildContextForWorkflow?.(t, n) ?? C({
739
+ subject: t.subject,
740
+ traceId: t.traceId
741
+ }, e.store, void 0, `workflow:${n.workflowName}`, { parentExecutionId: n.executionId }),
742
+ resolveStartContext: de,
743
+ ...fe === void 0 ? {} : { resolveAuthority: fe }
744
+ }, (t, n, r) => {
745
+ let i = j.getWorkflowVersionMetadata(t.definition);
746
+ return j.wrapWorkflowExecuteWithRunRecording({
747
+ name: t.definition.name,
748
+ store: e.store,
749
+ subject: r.subject,
750
+ source: r.source ?? null,
751
+ traceId: r.traceId,
752
+ workflowVersion: i.version,
753
+ workflowCompatibleVersions: i.compatibleWith,
754
+ workflowPatches: i.patches,
755
+ parentExecutionId: r?.parentExecutionId ?? null,
756
+ parentClosePolicy: r?.parentClosePolicy ?? null,
757
+ onParentClose: ({ executionId: e, status: t }) => N(e, t),
758
+ ...tt(t.definition),
759
+ onTerminal: async ({ executionId: e }) => {
760
+ await te?.gate.release(e);
761
+ },
762
+ recorder: M,
763
+ pluginWorkflowStepLayer: ot,
764
+ recordRun: Z
765
+ }, n);
766
+ }),
767
+ ...e.discovered.workflowWorkers ?? [],
768
+ ...be === void 0 ? [] : [be]
769
+ ], Lt = [...(e.discovered.workflows ?? []).map((e) => e.definition.name).filter(Boolean), ...be === void 0 ? [] : ["voltro.deliverWebhook"]], Rt = It.length > 0 ? W.mergeAll(...It) : W.empty;
770
+ if (((e.discovered.workflows?.length ?? 0) > 0 || (e.discovered.workflowWorkers?.length ?? 0) > 0 || e.scheduleCoordination === "cluster" || be !== void 0) && e.workflowEngineLayer !== void 0) {
771
+ let t = Rt.pipe(W.provideMerge(e.workflowEngineLayer));
772
+ p = En.make(e.baseLayer === void 0 ? t : t.pipe(W.provideMerge(e.baseLayer))), await p.runPromise(U.void), (e.log ?? I({ scope: "voltro:serve" })).child("workflow").info(`workflow runtime ready — ${Lt.length} entity type(s) registered`, { entities: Lt });
773
+ let n = await import("@voltro/workflow/cluster"), r = (e) => p.runPromise(n.redriveFailedRun(e)), i = (e) => p.runPromise(n.resumeRunFromStep(e));
774
+ ae = await bt({
775
+ provider: ii(e.plugins ?? [])?.broadcast?.provider,
776
+ crossReplica: ii(e.plugins ?? [])?.broadcast?.crossReplica ?? !1,
777
+ namespace: Ie,
778
+ replicaId: crypto.randomUUID(),
779
+ pollStorage: () => p.runPromise(n.pollWorkflowStorage),
780
+ log: (e.log ?? I({ scope: "voltro:serve" })).child("workflow")
781
+ }), ne = async (t) => {
782
+ let n = await At({
783
+ store: e.store,
784
+ workflows: e.discovered.workflows ?? [],
785
+ runRedrive: r
786
+ }, t.runId);
787
+ return n.statusReset && await M.recordEvent({
788
+ runId: t.runId,
789
+ eventType: "run-redriven",
790
+ payload: {
791
+ reason: "inspect.redrive",
792
+ activitiesReset: n.outcome.activitiesReset
793
+ }
794
+ }), {
795
+ redriven: n.outcome.redriven,
796
+ activitiesReset: n.outcome.activitiesReset,
797
+ reason: n.outcome.reason
798
+ };
799
+ }, ie = async (t) => {
800
+ let n = await u({
801
+ store: e.store,
802
+ workflows: e.discovered.workflows ?? [],
803
+ runResume: i
804
+ }, t.runId, t.step);
805
+ return n.statusReset && await M.recordEvent({
806
+ runId: t.runId,
807
+ eventType: "run-redriven",
808
+ payload: {
809
+ reason: "inspect.resume-from-step",
810
+ step: n.stepName,
811
+ activitiesReset: n.outcome.activitiesReset
812
+ }
813
+ }), {
814
+ redriven: n.outcome.redriven,
815
+ stepName: n.stepName,
816
+ activitiesReset: n.outcome.activitiesReset,
817
+ reason: n.outcome.reason
818
+ };
819
+ };
820
+ let a = dr({
821
+ coordinator: (e.scheduleCoordination ?? "single") === "advisoryLock" ? ar(e.store, e.scheduleReplicaId ?? `pid-${process.pid}`) : Nr,
822
+ replicaId: e.scheduleReplicaId ?? `pid-${process.pid}`
823
+ }), s = {
824
+ info: (e, t) => {
825
+ process.stdout.write(`[flow-control] ${e} ${t ? JSON.stringify(t) : ""}\n`);
826
+ },
827
+ warn: (e, t) => {
828
+ process.stderr.write(`[flow-control] ${e} ${t ? JSON.stringify(t) : ""}\n`);
829
+ },
830
+ error: (e, t) => {
831
+ process.stderr.write(`[flow-control] ERROR ${e} ${t ? JSON.stringify(t) : ""}\n`);
832
+ }
833
+ }, c, l = () => {
834
+ if (c !== void 0) return c;
835
+ if (!(o === void 0 || M === void 0)) return c = g({
836
+ store: e.store,
837
+ log: F,
838
+ workflows: e.discovered.workflows ?? [],
839
+ workflowsProxy: o,
840
+ workflowRuntime: p,
841
+ workflowRunRecorder: M,
842
+ closeChildrenForParent: N
843
+ }), c;
844
+ };
845
+ ee = l, te = Ue({
846
+ store: e.store,
847
+ onChange: (t) => e.store.onChange((e) => t({
848
+ table: e.table,
849
+ op: e.op
850
+ })),
851
+ ...e.scheduling === void 0 ? {} : {
852
+ disarmWhenIdle: e.scheduling.disarmWhenIdle,
853
+ drainIntervalMs: e.scheduling.admissionDrainMs,
854
+ cancelSweepIntervalMs: e.scheduling.cancelSweepMs,
855
+ stalenessSweepIntervalMs: e.scheduling.stalenessSweepMs
856
+ },
857
+ workflows: e.discovered.workflows ?? [],
858
+ facade: () => o,
859
+ cancelRunWithReason: l,
860
+ recordRunEvent: () => M?.recordEvent,
861
+ ...e.workflowStaleness === void 0 ? {} : { staleness: e.workflowStaleness },
862
+ scheduleCoordinated: a,
863
+ onAbandoned: async (t) => {
864
+ await _t({
865
+ workflows: e.discovered.workflows ?? [],
866
+ facade: () => o,
867
+ log: s,
868
+ ...t
869
+ });
870
+ },
871
+ log: s
872
+ });
873
+ let d = te;
874
+ d !== void 0 && Tr(() => d.stop()), f = O({
875
+ store: e.store,
876
+ onChange: (t) => e.store.onChange((e) => t({
877
+ table: e.table,
878
+ op: e.op
879
+ })),
880
+ ...e.scheduling === void 0 ? {} : {
881
+ disarmWhenIdle: e.scheduling.disarmWhenIdle,
882
+ tickIntervalMs: e.scheduling.inferenceTickMs
883
+ },
884
+ enabled: (e.discovered.workflows?.length ?? 0) > 0,
885
+ resumeSignal: () => p === void 0 || j === void 0 ? void 0 : async ({ executionId: t, workflowName: n, signalName: r, payload: i }) => {
886
+ await p.runPromise(j.completeSuspendingSignal({
887
+ store: e.store,
888
+ target: dt(t, n),
889
+ signalName: r,
890
+ payload: i
891
+ }));
892
+ },
893
+ runEffect: (e) => p.runPromise(e),
894
+ scheduleCoordinated: a,
895
+ log: s
896
+ });
897
+ let re = f;
898
+ re !== void 0 && Tr(() => re.stop()), o = (e.discovered.workflows?.length ?? 0) > 0 ? X({
899
+ workflows: e.discovered.workflows ?? [],
900
+ runEffect: (e) => p.runPromise(e),
901
+ onEnqueue: () => ae?.publishWake(),
902
+ ...d === void 0 ? {} : {
903
+ admitStart: d.gate.admitStart,
904
+ startPayloadSchema: d.gate.startPayloadSchema
905
+ },
906
+ rememberStartContext: ce,
907
+ signal: async (t, n, r) => {
908
+ let i = await j.sendWorkflowSignal({
909
+ store: e.store,
910
+ recorder: M,
911
+ target: t,
912
+ signalName: n,
913
+ payload: r
914
+ });
915
+ return await p.runPromise(j.completeSuspendingSignal({
916
+ store: e.store,
917
+ target: t,
918
+ signalName: n,
919
+ payload: r
920
+ })).catch(() => {}), i;
921
+ },
922
+ update: (t, n, r, i) => j.sendWorkflowUpdate({
923
+ store: e.store,
924
+ recorder: M,
925
+ target: t,
926
+ updateName: n,
927
+ payload: r,
928
+ ...i === void 0 ? {} : { options: i }
929
+ }),
930
+ listRuns: (t) => xe(e.store, t),
931
+ retry: (t, n) => Oe({
932
+ store: e.store,
933
+ workflows: e.discovered.workflows ?? [],
934
+ runPromise: (e) => p.runPromise(e)
935
+ }, t, n),
936
+ redrive: (t) => At({
937
+ store: e.store,
938
+ workflows: e.discovered.workflows ?? [],
939
+ runRedrive: r
940
+ }, t).then((e) => e.outcome)
941
+ }) : void 0;
942
+ }
943
+ let zt = W.mergeAll(kt.toLayer(A), Mt), Bt = Me(A, e.discovered.queries.map((e) => e.descriptor.name), he), Vt = W.mergeAll(kt.toLayer(Bt), Mt), P = e.observability, Ht = await Yn({
944
+ ...e.appName === void 0 ? {} : { serviceName: e.appName },
945
+ ...P && P.spanProcessors.length > 0 ? { extraSpanProcessors: P.spanProcessors } : {},
946
+ ...P && P.metricReaders.length > 0 ? { extraMetricReaders: P.metricReaders } : {},
947
+ ...P && Object.keys(P.resourceAttributes).length > 0 ? { resourceAttributes: P.resourceAttributes } : {},
948
+ ...P && P.sampler !== void 0 ? { sampler: P.sampler } : {}
949
+ }), Ut = !1, Wt = e.store.ping ? () => e.store.ping().then(() => !0).catch(() => !1) : void 0, { server: Gt, shutdown: Kt } = Pr({
950
+ group: kt,
951
+ handlersLayer: zt,
952
+ httpHandlersLayer: Vt,
953
+ port: e.port ?? 4e3,
954
+ ...e.host === void 0 ? {} : { host: e.host },
955
+ path: e.path ?? "/ws",
956
+ tracerLayer: Ht.layer,
957
+ security: it(e),
958
+ ...at,
959
+ healthCheck: {
960
+ isReady: () => Ut,
961
+ ...Wt ? { ping: Wt } : {}
962
+ },
963
+ ...Et.length > 0 ? { httpRoutes: Et } : {},
964
+ ...e.getStore === void 0 ? {} : { getStore: e.getStore },
965
+ ...Ce.size > 0 ? { webhookRoutes: Ce } : {},
966
+ ...e.inspectRoute === void 0 ? {} : { inspectRoute: e.inspectRoute }
967
+ });
968
+ if (await qn(Gt), (e.discovered.schedules?.length ?? 0) > 0) {
969
+ let t = (e.scheduleCoordination ?? "single") === "advisoryLock" ? ar(e.store, e.scheduleReplicaId ?? `pid-${process.pid}`) : Nr;
970
+ oe = await Fr(e.discovered.schedules ?? [], {
971
+ store: e.store,
972
+ coordinator: t,
973
+ defaultTrigger: e.scheduleDefaultTrigger ?? "self",
974
+ replicaId: e.scheduleReplicaId ?? `pid-${process.pid}`,
975
+ armSelf: e.scheduleArmSelf ?? !0,
976
+ dormancy: e.dormancy ?? "always-on",
977
+ ...e.dormancyTenantId === void 0 ? {} : { dormancyTenantId: e.dormancyTenantId },
978
+ buildContext: ({ traceId: t, scheduleName: n, subject: r }) => C({
979
+ subject: r,
980
+ traceId: t
981
+ }, e.store, void 0, `schedule:${n}`),
982
+ log: {
983
+ info: (e, t) => {
984
+ process.stdout.write(`[schedule] ${e} ${t ? JSON.stringify(t) : ""}\n`);
985
+ },
986
+ warn: (e, t) => {
987
+ process.stderr.write(`[schedule] ${e} ${t ? JSON.stringify(t) : ""}\n`);
988
+ },
989
+ error: (e, t) => {
990
+ process.stderr.write(`[schedule] ERROR ${e} ${t ? JSON.stringify(t) : ""}\n`);
991
+ },
992
+ debug: () => {}
993
+ },
994
+ ...e.scheduleFireInterceptor === void 0 ? {} : { interceptFire: e.scheduleFireInterceptor },
995
+ ...e.onScheduleRunEvent === void 0 ? {} : { onRunEvent: e.onScheduleRunEvent }
996
+ }), e.onSchedulerReady?.(oe);
997
+ }
998
+ let F = e.log ?? I({ scope: "voltro:serve" }), qt, Jt;
999
+ if ((e.discovered.subscribers?.length ?? 0) > 0 && (qt = y(e.discovered.subscribers ?? [], e.store, F.child("subscribe"), e.schemaRegistry, S.bus)), (e.discovered.reactions?.length ?? 0) > 0) {
1000
+ let t = F.child("reaction"), n = async (n, r) => {
1001
+ if (n.kind === "workflow") {
1002
+ if (h === void 0) {
1003
+ t.warn("reaction workflow act skipped — no workflow engine in this app", { workflow: n.workflow });
1004
+ return;
1005
+ }
1006
+ let e = n.payload === void 0 ? r.new ?? r.old ?? {} : n.payload(r);
1007
+ await Sr(h, {
1008
+ traceId: `reaction:${n.workflow}`,
1009
+ source: `reaction:${n.workflow}`
1010
+ }).start(n.workflow, e);
1011
+ return;
1012
+ }
1013
+ await re(n.agent, r, {
1014
+ findAgentSend: (t) => e.discovered.actions.find((e) => e.descriptor.name === `${t}.send`),
1015
+ runAction: (e, t, n) => Promise.resolve(ut(e, t, n)),
1016
+ makeSubject: (e) => hn(e),
1017
+ now: () => Date.now(),
1018
+ log: t
1019
+ });
1020
+ }, r = async (n, r) => {
1021
+ try {
1022
+ let { requireAiBudget: t } = await import("@voltro/ai");
1023
+ return (await U.runPromise(U.either(t(e.store, {
1024
+ tenantId: n,
1025
+ limitUsd: r
1026
+ }))))._tag === "Right";
1027
+ } catch (e) {
1028
+ return t.warn("reaction budget check failed — refusing the act", { tenantId: n }, e), !1;
1029
+ }
1030
+ }, i = Re(e.store, { onError: (e) => t.warn("reaction: rate-slot claim failed; refusing the act", { cause: String(e) }) });
1031
+ Jt = Te(e.discovered.reactions ?? [], e.store, {
1032
+ runAct: n,
1033
+ checkBudget: r,
1034
+ claimRateSlot: (e) => i.claim(e)
1035
+ }, t);
1036
+ }
1037
+ let Yt;
1038
+ (e.discovered.aggregates?.length ?? 0) > 0 && (Yt = await Be({
1039
+ discovered: e.discovered.aggregates ?? [],
1040
+ store: e.store,
1041
+ log: F.child("aggregate"),
1042
+ ...e.analytics === void 0 ? {} : { analytics: e.analytics },
1043
+ ...e.aggregateStorage === void 0 ? {} : { storage: e.aggregateStorage },
1044
+ ...e.aggregateCoordinator === void 0 ? {} : { coordinator: e.aggregateCoordinator }
1045
+ }), Ge = W.succeed(Ln, Yt.registry));
1046
+ let Xt;
1047
+ (e.discovered.expectations?.length ?? 0) > 0 && (Xt = Wn({
1048
+ discovered: e.discovered.expectations ?? [],
1049
+ store: e.store,
1050
+ log: F.child("expectation")
1051
+ }), Ke = W.succeed(Bn, Xt.registry)), (e.discovered.budgets?.length ?? 0) > 0 && (n = Kn({
1052
+ discovered: e.discovered.budgets ?? [],
1053
+ log: F.child("finops")
1054
+ }), qe = W.succeed(Rn, n.registry));
1055
+ let Zt;
1056
+ return (e.discovered.experiments?.length ?? 0) > 0 && (Zt = Gn({
1057
+ discovered: e.discovered.experiments ?? [],
1058
+ store: e.store,
1059
+ log: F.child("experiment")
1060
+ }), Je = W.succeed(Vn, Zt.registry)), Ut = !0, e.bootTiming?.mark("ready"), {
1061
+ dispatcher: r,
1062
+ server: Gt,
1063
+ scheduler: oe,
1064
+ eventsSnapshot: nt(S.bus, S.declared),
1065
+ membersSnapshot: () => ({
1066
+ members: Ve.membership.list(),
1067
+ capturedAt: Date.now()
1068
+ }),
1069
+ agentTools: () => St,
1070
+ rpcMetrics: () => w,
1071
+ webhooksService: () => ye,
1072
+ runCanceller: () => ee(),
1073
+ flowControlHealth: () => te?.cancelHealth(),
1074
+ inferenceHealth: () => f?.health(),
1075
+ workflowWriteActions: () => h === void 0 || M === void 0 ? void 0 : me({
1076
+ store: e.store,
1077
+ log: F,
1078
+ workflows: e.discovered.workflows ?? [],
1079
+ workflowsProxy: o,
1080
+ workflowRuntime: p,
1081
+ workflowRunRecorder: M,
1082
+ closeChildrenForParent: N
1083
+ }),
1084
+ redriveWorkflowRun: (e) => ne ? ne(e) : Promise.reject(/* @__PURE__ */ Error("redrive: this app registers no workflows")),
1085
+ resumeWorkflowRunFromStep: (e) => ie ? ie(e) : Promise.reject(/* @__PURE__ */ Error("resume-from-step: this app registers no workflows")),
1086
+ close: async () => {
1087
+ Ut = !1;
1088
+ for (let e of we) try {
1089
+ await e();
1090
+ } catch (e) {
1091
+ F.warn("serve: teardown step failed", {}, e);
1092
+ }
1093
+ await He?.detach(), await Ve.detach(), Yt?.detach(), Xt?.detach(), n?.detach(), Zt?.detach(), Jt?.(), qt?.(), await oe?.shutdown(), r.close(), await ae?.detach(), await p?.dispose(), await new Promise((e) => Gt.close(() => e())), await Kt();
1094
+ }
1095
+ };
1096
+ }, $ = I({ scope: "voltro:serve" }), ji = (e, t, n) => (e === "production" || e === "staging") && t !== "memory" && n !== "0", Mi = Mt, Ni = async (e) => {
1097
+ let t = on(process.cwd());
1098
+ if (dn(t)) {
1099
+ let n;
1100
+ try {
1101
+ let e = await import(fn(t).href);
1102
+ typeof e.runServe == "function" ? n = e.runServe : $.warn("serve bundle has no runServe export — using the standard serve path");
1103
+ } catch (e) {
1104
+ $.warn("serve bundle failed to load — using the standard serve path", {}, e);
1105
+ }
1106
+ if (n) return $.info("serve: booting from the precompiled serve bundle"), n(e);
1107
+ }
1108
+ return Pi(e);
1109
+ }, Pi = async (s) => {
1110
+ let c = sn();
1111
+ e("serve");
1112
+ try {
1113
+ Kr();
1114
+ } catch (e) {
1115
+ throw j(e instanceof Error ? e.message : String(e));
1116
+ }
1117
+ let l = process.cwd(), u = await Ve(l), d = Nt({
1118
+ kind: "api",
1119
+ configPort: u?.port,
1120
+ env: process.env,
1121
+ flagPort: Mi(s, "--port")
1122
+ });
1123
+ for (let e of d.warnings) $.warn(e);
1124
+ let re = d.port;
1125
+ Ar(Or(u?.secrets)), await M({
1126
+ rawEnv: u?.env,
1127
+ appType: "api",
1128
+ root: l,
1129
+ log: $,
1130
+ generateTypes: !1
1131
+ }), c.mark("config");
1132
+ let m = (process.env.DB_DIALECT ?? u?.store ?? "memory").toLowerCase(), le = (m === "mariadb" || m === "postgres" || m === "mssql") && (process.env.CDC ?? "1") !== "0", ue = m === "mariadb" ? "mariadb" : m === "mssql" ? "mssql" : void 0, pe = an(l);
1133
+ if (!r() && dn(pe)) try {
1134
+ let e = await import(fn(pe).href);
1135
+ if (e.modules) {
1136
+ let t = {};
1137
+ for (let [n, r] of Object.entries(e.modules)) t[un(l, n)] = r;
1138
+ n(t), $.info("precompiled api bundle loaded", { modules: Object.keys(t).length });
1139
+ }
1140
+ } catch (e) {
1141
+ $.warn("precompiled api bundle failed to load — falling back to source", {}, e);
1142
+ }
1143
+ let g = await Ke(l), _ = await yt(g, { cdc: le && ue !== void 0 }), me = w(_);
1144
+ {
1145
+ let e = /* @__PURE__ */ new Set([
1146
+ ..._.queries.filter((e) => e.descriptor.overridesPlugin === !0).map((e) => e.descriptor.name),
1147
+ ..._.mutations.filter((e) => e.descriptor.overridesPlugin === !0).map((e) => e.descriptor.name),
1148
+ ..._.actions.filter((e) => e.descriptor.overridesPlugin === !0).map((e) => e.descriptor.name)
1149
+ ]);
1150
+ Bt(zt(u?.plugins ?? []), [
1151
+ ..._.queries.map((e) => e.descriptor.name),
1152
+ ..._.mutations.map((e) => e.descriptor.name),
1153
+ ..._.actions.map((e) => e.descriptor.name),
1154
+ ..._.streams.map((e) => e.descriptor.name)
1155
+ ], e);
1156
+ let t = h(_.serverOnlyLeaks, ce(process.env, "strict"), $n, "`voltro serve`");
1157
+ if (t.action === "fail") throw j(t.message ?? "");
1158
+ t.action === "warn" && $.warn(t.message ?? "");
1159
+ }
1160
+ let xe = g.filter((e) => nn.test(e)), Se = xe.length > 0 ? await tn(xe, $.child("webhooks")) : {
1161
+ outgoing: [],
1162
+ incoming: [],
1163
+ providers: []
1164
+ }, Te = $t(_.events), De = Se.outgoing.length + Se.incoming.length + Se.providers.length + Te.length === 0 ? void 0 : {
1165
+ ...Se,
1166
+ outgoing: [...Se.outgoing, ...Te]
1167
+ }, Oe = Ut({
1168
+ mix: _.featureMix,
1169
+ plugins: u?.plugins ?? [],
1170
+ cdc: le && ue !== void 0,
1171
+ ...ue ? { cdcDialect: ue } : {}
1172
+ }), ke = u?.analytics !== void 0 && u.analytics.kind !== "noop" && m !== "memory" ? (await N(m)).makeSqlLayer(E()) : void 0, Ae = await fe({
1173
+ spec: u?.analytics,
1174
+ sqlLayer: ke,
1175
+ log: $
1176
+ }), y = (() => {
1177
+ let e = new Set(_.tables.map((e) => e.tableName)), t = [..._.tables];
1178
+ for (let n of [...Oe, ...Ae.tables]) e.has(n.tableName) || (e.add(n.tableName), t.push(n));
1179
+ return t;
1180
+ })();
1181
+ for (let e of y) Fn(e);
1182
+ {
1183
+ let e = er(Lr(_.queries.map((e) => ({
1184
+ name: e.descriptor.name,
1185
+ source: e.descriptor.source
1186
+ })), new Set(y.flatMap((e) => {
1187
+ let t = e.tableName;
1188
+ return t === void 0 ? [] : [t];
1189
+ }))));
1190
+ e !== void 0 && $.warn(e);
1191
+ }
1192
+ let je = (process.env.NODE_ENV ?? "").toLowerCase();
1193
+ if (ji(je, m, process.env.VOLTRO_AUTO_MIGRATE)) {
1194
+ let e = (await N(m)).makeSqlLayer(E()), t = await U.runPromise(Dn.SqlClient.pipe(U.flatMap((e) => An(e, l)), U.provide(e), U.catchAll(() => U.succeed([]))));
1195
+ t.length > 0 && ($.error(`serve: refusing to boot — ${t.length} pending file-based migration(s) have never run against this database. They perform the changes a schema diff cannot infer (data moves, backfills, table splits), so the declarative fingerprint check below cannot see them and would have let this process serve un-migrated data.`, { pending: t }), $.error("Run them from your pre-deploy job — `voltro db migrate .` (schema + files) or `voltro db files .` (files alone) — or set VOLTRO_AUTO_MIGRATE=0 to bypass every boot schema check. `voltro serve` never applies them itself: a rolling deploy would start N replicas and each would try."), process.exit(1));
1196
+ let n = await U.runPromise(Dn.SqlClient.pipe(U.flatMap((e) => jn(e, y, {
1197
+ appliedBy: `serve:${je}`,
1198
+ environment: "prod",
1199
+ dialectId: m
1200
+ })), U.provide(e)));
1201
+ n.kind === "prod-mismatch" && ($.error(kn(n, m)), $.error("serve: refusing to boot — apply the schema first (voltro db apply in a pre-deploy step), or set VOLTRO_AUTO_MIGRATE=0 to bypass this check."), process.exit(1)), $.info(kn(n, m));
1202
+ }
1203
+ await Rt({
1204
+ dialectId: m,
1205
+ tables: y,
1206
+ mode: It(u?.reactiveTriggers),
1207
+ makeLayer: async () => (await N(m)).makeSqlLayer(E()),
1208
+ log: {
1209
+ info: (e, t) => $.info(e, t ?? {}),
1210
+ warn: (e, t) => $.warn(e, t ?? {})
1211
+ }
1212
+ });
1213
+ let Me = xr(y);
1214
+ c.mark("discover");
1215
+ let b = await $e(u, void 0), Re = zr(b, m);
1216
+ for (let e of ut({
1217
+ dialect: String(u?.store ?? process.env.DB_DIALECT ?? "postgres"),
1218
+ changeStrategy: (process.env.CDC ?? "1") === "0" ? "inline" : "cdc",
1219
+ dbUrl: process.env.DB_URL,
1220
+ crossReplicaBus: ii(u?.plugins ?? [])?.broadcast.crossReplica === !0,
1221
+ tables: _.tables.map((e) => ({
1222
+ tableName: e.tableName,
1223
+ isReactive: e.isReactive === !0
1224
+ })),
1225
+ querySources: _.queries.flatMap((e) => {
1226
+ let t = e.descriptor.source;
1227
+ return t === void 0 ? [] : typeof t == "string" ? [t] : [...t];
1228
+ })
1229
+ })) e.level === "warn" ? $.warn(e.message) : $.info(e.message);
1230
+ {
1231
+ let e = Le(et({
1232
+ tables: Nn().map((e) => ({ tableName: e.tableName })),
1233
+ queries: _.queries.map((e) => ({
1234
+ name: e.descriptor.name,
1235
+ source: e.descriptor.source
1236
+ }))
1237
+ }));
1238
+ e !== void 0 && $.warn(e);
1239
+ }
1240
+ u?.cache && !process.env.CACHE_BACKEND && (process.env.CACHE_BACKEND = u.cache), u?.cacheRedisUrl && !process.env.CACHE_REDIS_URL && (process.env.CACHE_REDIS_URL = u.cacheRedisUrl), u?.cacheRedisDriver && !process.env.CACHE_REDIS_DRIVER && (process.env.CACHE_REDIS_DRIVER = u.cacheRedisDriver), u?.cacheKeyPrefix && !process.env.CACHE_KEY_PREFIX && (process.env.CACHE_KEY_PREFIX = u.cacheKeyPrefix);
1241
+ let { service: Be, invalidationBus: Ue, snapshotCache: We, cache: Ye, semantic: Xe, evictSource: Qe, backend: tt, stats: nt, dispose: rt } = await gt({
1242
+ env: process.env,
1243
+ semantic: u?.cacheSemantic ?? !1
1244
+ });
1245
+ Xe !== void 0 && $.info("semantic cache enabled — reactive eviction on live writes"), $.info(`cache backend resolved: ${tt}` + (tt === "redis" ? ` (driver ${process.env.CACHE_REDIS_DRIVER ?? "resp"})` : " — in-process, not cross-instance")), b.onChange((e) => {
1246
+ if (U.runFork(Ue.publish(e.table)), Qe !== void 0) {
1247
+ let t = (e.new ?? e.old)?.id;
1248
+ Qe({
1249
+ table: e.table,
1250
+ op: e.op,
1251
+ ...t === void 0 ? {} : { id: t }
1252
+ });
1253
+ }
1254
+ }), u?.kv && !process.env.KV_BACKEND && (process.env.KV_BACKEND = u.kv), u?.kvRedisUrl && !process.env.KV_REDIS_URL && (process.env.KV_REDIS_URL = u.kvRedisUrl), u?.kvKeyPrefix && !process.env.KV_KEY_PREFIX && (process.env.KV_KEY_PREFIX = u.kvKeyPrefix);
1255
+ let { kv: st, service: dt } = await lr({ store: b });
1256
+ $.info(fi(Ft(), mi(), m === "postgres" && (process.env.CDC ?? "1") !== "0" ? [{ reason: "CDC LISTEN consumer" }] : [], t.replicationSnapshot()?.replicaCount ?? 0)), c.mark("store");
1257
+ let mt = Un({
1258
+ store: b,
1259
+ sink: Ae.sink,
1260
+ log: $
1261
+ }), _t = ct({
1262
+ store: b,
1263
+ dialect: m,
1264
+ log: { info: (e) => $.info(e) }
1265
+ }), O = u?.plugins ?? [], vt = process.env.POD_NAME ?? process.env.HOSTNAME ?? `serve-${process.pid}`, bt, Dt;
1266
+ m !== "memory" && (bt = En.make((await N(m)).makeSqlLayer(E())), Dt = await bt.runPromise(Dn.SqlClient));
1267
+ let At = [
1268
+ "postgres",
1269
+ "mariadb",
1270
+ "mysql",
1271
+ "mssql"
1272
+ ].includes(m) ? ar(b, vt, $) : Nr, jt = pt(u?.scheduling), Mt = dr({
1273
+ maxIdleIntervalMs: jt.pollCeilingMs,
1274
+ coordinator: At,
1275
+ replicaId: vt,
1276
+ log: $
1277
+ }), en = [], on = process.env.POD_NAME ?? process.env.HOSTNAME ?? `serve-${process.pid}`, cn = ii(u?.plugins ?? [])?.broadcast?.provider, I = Ze(u?.plugins, u?.name ?? ln(l));
1278
+ {
1279
+ let e = ot(u?.plugins, u?.name ?? ln(l));
1280
+ e !== void 0 && $.warn(e);
1281
+ }
1282
+ let pn = Fe(u?.plugins, {
1283
+ instanceId: on,
1284
+ namespace: I,
1285
+ meta: { mode: "serve" },
1286
+ logger: $
1287
+ }), mn = {
1288
+ ...Dt ? { sql: Dt } : {},
1289
+ instanceId: on,
1290
+ membership: pn.membership,
1291
+ ...cn === void 0 ? {} : { broadcast: cn },
1292
+ broadcastChannels: { presence: ri(I, "presence") },
1293
+ scheduleCoordinated: (e, t, n) => {
1294
+ let r = Mt(e, t, n);
1295
+ return en.push(r), r;
1296
+ }
1297
+ };
1298
+ for (let e of O) e.bindDataStore?.(b, mn);
1299
+ he({
1300
+ store: b,
1301
+ ...te(),
1302
+ log: $
1303
+ });
1304
+ let L = O.filter((e) => typeof e.onChangeEvent == "function");
1305
+ if (L.length > 0) {
1306
+ let e = b.changeScope ?? "local";
1307
+ b.onChange((t) => {
1308
+ let n = ge(t, e);
1309
+ for (let e of L) U.runFork(e.onChangeEvent(n).pipe(U.catchAllCause((t) => U.sync(() => $.warn(`plugin ${e.name} onChangeEvent failed`, { error: Tn.pretty(t) })))));
1310
+ });
1311
+ }
1312
+ let hn = ae({
1313
+ plugins: O,
1314
+ appName: u?.name ?? "voltro-api",
1315
+ appType: "api",
1316
+ voltroVersion: process.env.npm_package_version ?? "0.0.0",
1317
+ log: $
1318
+ });
1319
+ O.length && await hn.activate(), c.mark("plugins");
1320
+ let gn = await hn.gatherObservability(), _n = {
1321
+ info: (e, t) => process.stdout.write(`[broadcast] ${e} ${t ? JSON.stringify(t) : ""}\n`),
1322
+ warn: (e, t) => process.stderr.write(`[broadcast] ${e} ${t ? JSON.stringify(t) : ""}\n`),
1323
+ debug: () => {}
1324
+ }, R, vn = await ft(b, u, m, I, _n, (e, t) => {
1325
+ R?.refreshAll(`broadcast gap: missed ${t} change(s) from ${e}`);
1326
+ }), z = u?.apiKeys, yn = (typeof z == "object" ? z.prefix : void 0) ?? "voltro_", B = z ? Qn(b) : void 0, V = B ? sr({ flush: cr(B) }) : void 0;
1327
+ V && Tr(() => V.shutdown());
1328
+ let H = B ? or(B, {
1329
+ prefix: yn,
1330
+ ...V ? { usage: V } : {}
1331
+ }) : void 0, bn = H ? [tr(H, { prefix: yn })] : [], xn = ht([...u?.auth?.strategies ?? [], ...bn], ti(u?.plugins ?? []), u?.auth?.anonymousTenantRequired ?? !1, u?.auth, () => Re), Sn = [...u?.restRoutes ?? [], ...H ? Hn(H, (typeof z == "object" ? z.managementPath : void 0) ?? "/v1/api-keys") : []], Cn = Ne(u?.idempotency, b), wn = O.map((e) => e.services).filter((e) => e !== void 0), Mn = W.mergeAll(be({
1332
+ analyticsLayer: Ae.layer,
1333
+ cacheService: Be,
1334
+ kvService: dt,
1335
+ ...Xe === void 0 ? {} : { semanticCache: Xe },
1336
+ pluginServices: wn,
1337
+ userLayers: u?.layers ?? []
1338
+ }), Pe(u?.http ?? {})), G = await Ge({
1339
+ files: g,
1340
+ store: b,
1341
+ log: $,
1342
+ seedPolicy: "report",
1343
+ seedPattern: Yt,
1344
+ loadSeedFiles: Lt,
1345
+ startupPattern: Gt,
1346
+ loadStartupFiles: a,
1347
+ runStartups: i,
1348
+ emailPattern: A,
1349
+ loadEmailFiles: lt,
1350
+ registerEmailTemplates: ni
1351
+ });
1352
+ (G.startupCount > 0 || G.emailCount > 0) && $.info("boot lifecycle", {
1353
+ startups: G.startupCount,
1354
+ emailTemplates: G.emailCount
1355
+ }), G.startups !== void 0 && Tr(async () => {
1356
+ await G.startups.stop();
1357
+ });
1358
+ let K = o({
1359
+ schedules: _.schedules,
1360
+ seeds: G.seeds,
1361
+ store: b,
1362
+ log: $.child("seeds")
1363
+ }), In = u?.scheduling ?? {}, Ln = In.trigger ?? "self", Rn = /* @__PURE__ */ new Set([
1364
+ "postgres",
1365
+ "mysql",
1366
+ "mariadb",
1367
+ "mssql"
1368
+ ]), zn = In.coordination ?? (Rn.has(m) ? "advisoryLock" : "single"), q = zn === "cluster" && Rn.has(m), Bn = q ? "cluster" : zn === "advisoryLock" && Rn.has(m) ? "advisoryLock" : "single";
1369
+ zn === "cluster" && !q && $.warn("scheduling.coordination=cluster needs a sql-backed store except sqlite — falling back to single"), zn === "advisoryLock" && !Rn.has(m) && $.warn("scheduling.coordination=advisoryLock needs a SQL store (the claim-row gate) — falling back to single");
1370
+ let Vn, Wn = _.workflows.length > 0 || _.workflowWorkers.length > 0 || _.eventTriggers.length > 0 || (De?.outgoing.length ?? 0) > 0 || q, Gn;
1371
+ if (Wn) {
1372
+ if (m === "mssql") {
1373
+ let e = await Qt(process.cwd());
1374
+ e && $.warn(e);
1375
+ }
1376
+ let [{ WorkflowEngine: e }, { makeClusterCronLayer: t, workflowEngineLayer: n, resolveRunnerStorage: r, resolveFailoverTuning: i }] = await Promise.all([import("@effect/workflow"), import("@voltro/workflow/cluster")]), a = q ? K.filter((e) => (e.trigger ?? Ln) === "self").map((e) => t({
1377
+ name: e.name,
1378
+ cron: Zn(e),
1379
+ execute: async () => {
1380
+ await Vn?.fireFromCluster(e.name);
1381
+ }
1382
+ })) : [];
1383
+ Gn = m === "memory" ? e.layerMemory : await (async () => {
1384
+ let e = await N(m), t = r({ sqliteFamily: e.id === "sqlite" || e.id === "turso" });
1385
+ return $.info(`workflow engine: cluster-${t}, dialect=${e.id}` + (t === "memory" ? " — single-process durable replay, no cross-pod shard handoff" + (e.id !== "sqlite" && e.id !== "turso" ? " (VOLTRO_WORKFLOW_RUNNER_STORAGE=memory: SqlRunnerStorage/cluster_runners + GET_LOCK skipped)" : "") : "")), n({
1386
+ sqlClientLayer: e.makeSqlLayer(E()),
1387
+ runnerStorage: t,
1388
+ dialectId: e.id,
1389
+ ...process.env.VOLTRO_WORKFLOW_RUNNER_PORT ? { runnerListenPort: Number(process.env.VOLTRO_WORKFLOW_RUNNER_PORT) } : {},
1390
+ ...i(),
1391
+ ...a.length > 0 ? { extraShardingLayers: a } : {}
1392
+ });
1393
+ })();
1394
+ }
1395
+ let Kn = Ee(O, rn()), qn = g.filter((e) => /\.subscribe\.tsx?$/.test(e)), J = qn.length > 0 ? await oe(qn, $) : [], Jn = g.filter((e) => /\.reaction\.tsx?$/.test(e)), Y = Jn.length > 0 ? await p(Jn, $) : [], Yn = g.filter((e) => qt.test(e)), Xn = Yn.length > 0 ? await se(Yn, $) : [], nr = g.filter((e) => /\.aggregate\.tsx?$/.test(e)), rr = nr.length > 0 ? await Ce(nr, $) : [], ir = f();
1396
+ if (rr.length > 0 && m !== "memory") try {
1397
+ ir = Tt((await N(m)).makeSqlLayer(E()));
1398
+ } catch (e) {
1399
+ $.warn("aggregate: SQL storage init failed — falling back to in-process", { err: String(e) });
1400
+ }
1401
+ let ur = m === "memory" ? Nr : ar(b, `aggregate@${process.pid}`, $), fr = g.filter((e) => Jt.test(e)), pr = fr.length > 0 ? await Ct(fr, $) : [], mr = g.filter((e) => F.test(e)), hr = mr.length > 0 ? await Ie(mr, $) : [], gr = g.filter((e) => Kt.test(e)), _r = gr.length > 0 ? await kt(gr, $) : [], vr = [], yr = [], br = g.filter((e) => Ht.test(e));
1402
+ if (br.length > 0) {
1403
+ let e = $.child("agent"), t = g.filter((e) => P.test(e));
1404
+ t.length > 0 && await Wt(t, e);
1405
+ let n = await Vt(br, e);
1406
+ for (let e of n.agents) for (let t of x(e)) (t.kind === "action" ? vr : yr).push({
1407
+ file: t.file,
1408
+ descriptor: t.descriptor,
1409
+ executor: t.executor
1410
+ });
1411
+ n.agents.length > 0 && e.info("synthesized agent routes", { agents: n.agents.map((e) => e.descriptor.name) });
1412
+ }
1413
+ c.mark("workflow");
1414
+ let X = () => {
1415
+ let e = Z.workflowWriteActions();
1416
+ if (e === void 0) throw Error("workflow actions: this app registers no workflows");
1417
+ return e;
1418
+ }, Sr = Pn({
1419
+ dialect: m,
1420
+ ...E()
1421
+ }), Cr = m === "memory" ? void 0 : (await N(m)).makeSqlLayer(E()), wr = async () => ye({
1422
+ sqlLayer: Cr,
1423
+ declared: y,
1424
+ log: $
1425
+ }), Er = {
1426
+ kind: "api",
1427
+ meta: {
1428
+ name: u?.name ?? "voltro-api",
1429
+ voltroVersion: k,
1430
+ port: re,
1431
+ mode: "start",
1432
+ store: m,
1433
+ cdc: le ? "on" : "off",
1434
+ ...Sr === void 0 ? {} : { databaseId: Sr }
1435
+ },
1436
+ rpc: S(_, l),
1437
+ workflows: T(_, l),
1438
+ migrations: wr,
1439
+ events: () => Z.eventsSnapshot(),
1440
+ agentTools: () => Z.agentTools(),
1441
+ invariantChecks: () => ({
1442
+ mode: "serve",
1443
+ accessGate: me,
1444
+ config: u,
1445
+ serverOnlyLeaks: _.serverOnlyLeaks,
1446
+ migrations: wr
1447
+ }),
1448
+ members: () => Z.membersSnapshot(),
1449
+ inspectFireSchedule: async ({ name: e, trigger: t }) => {
1450
+ if (!Vn) throw Error("scheduler not started — this app registers no self-triggered schedules (all schedules are trigger:'external', or there are none).");
1451
+ return { runId: await Vn.fireNow(e, t) ?? null };
1452
+ },
1453
+ ...De === void 0 ? {} : { webhooks: () => ne({
1454
+ store: b,
1455
+ discoveredWebhooks: De
1456
+ }) },
1457
+ plugins: () => ({
1458
+ plugins: hn.snapshot(),
1459
+ capturedAt: Date.now()
1460
+ }),
1461
+ env: () => Pt(u?.name ?? ln(l), {
1462
+ ...u?.env !== void 0 && Gr(u.env) ? { contract: u.env } : {},
1463
+ plugins: u?.plugins ?? []
1464
+ }),
1465
+ dataCache: () => Ot({
1466
+ stats: nt,
1467
+ backendKind: tt
1468
+ }),
1469
+ subscriptions: () => ze(() => R),
1470
+ inspectTables: () => _e(_.tables),
1471
+ inspectRows: ie({
1472
+ store: b,
1473
+ tables: _.tables,
1474
+ mask: !0
1475
+ }),
1476
+ metrics: (e) => Z.rpcMetrics().snapshot(e),
1477
+ cluster: () => St({
1478
+ store: b,
1479
+ dialect: m,
1480
+ useClusterCron: q,
1481
+ scheduleCoordChoice: zn
1482
+ }),
1483
+ inspectSchedules: () => wt({
1484
+ schedules: K,
1485
+ defaultTrigger: Ln,
1486
+ coordination: Bn
1487
+ }),
1488
+ inspectScheduleRuns: (e) => ee(b, e),
1489
+ ...v(b, {
1490
+ controls: xt(_.workflows ?? []),
1491
+ active: (_.workflows?.length ?? 0) > 0,
1492
+ cancellation: () => Z.flowControlHealth()
1493
+ }),
1494
+ webhookActions: Et(() => Z.webhooksService()),
1495
+ inspectStartWorkflow: (e) => X().inspectStartWorkflow(e),
1496
+ inspectCancelWorkflowRun: (e) => X().inspectCancelWorkflowRun(e),
1497
+ inspectSuspendWorkflowRun: (e) => X().inspectSuspendWorkflowRun(e),
1498
+ inspectResumeWorkflowRun: (e) => X().inspectResumeWorkflowRun(e),
1499
+ inspectDiscardWorkflowRun: (e) => X().inspectDiscardWorkflowRun(e),
1500
+ inspectRetryWorkflowRun: (e) => X().inspectRetryWorkflowRun(e),
1501
+ inspectSignalWorkflowRun: (e) => X().inspectSignalWorkflowRun(e),
1502
+ inspectUpdateWorkflowRun: (e) => X().inspectUpdateWorkflowRun(e),
1503
+ inspectInferences: (e) => He({
1504
+ store: b,
1505
+ active: (_.workflows?.length ?? 0) > 0,
1506
+ dispatcher: () => Z.inferenceHealth()
1507
+ }, e.limit === void 0 ? {} : { limit: e.limit }),
1508
+ ...at({
1509
+ store: b,
1510
+ cancelRun: async (e) => await Z.runCanceller()?.(e) ?? !1,
1511
+ retryRun: async (e) => X().inspectRetryWorkflowRun({ runId: e }),
1512
+ redriveRun: async (e) => Z.redriveWorkflowRun({ runId: e }),
1513
+ log: $
1514
+ }),
1515
+ inspectRedriveWorkflowRun: (e) => Z.redriveWorkflowRun(e),
1516
+ inspectResumeWorkflowRunFromStep: (e) => Z.resumeWorkflowRunFromStep(e)
1517
+ }, Z = await Ai({
1518
+ bootTiming: c,
1519
+ broadcastNamespace: I,
1520
+ scheduling: (() => {
1521
+ let e = jt;
1522
+ return {
1523
+ admissionDrainMs: e.admissionDrainMs,
1524
+ inferenceTickMs: e.inferenceTickMs,
1525
+ cancelSweepMs: e.cancelSweepMs,
1526
+ stalenessSweepMs: e.stalenessSweepMs,
1527
+ disarmWhenIdle: Je({
1528
+ changeScope: b.changeScope,
1529
+ broadcastAttached: vn !== void 0
1530
+ })
1531
+ };
1532
+ })(),
1533
+ ...u?.workflows?.staleness === void 0 ? {} : { workflowStaleness: u.workflows.staleness },
1534
+ membership: {
1535
+ ...pn,
1536
+ instanceId: on
1537
+ },
1538
+ security: {
1539
+ defaultDeny: ve(u),
1540
+ ...it(u)
1541
+ },
1542
+ approvals: { defaultExpiryMs: de(u) },
1543
+ ...u?.plugins === void 0 ? {} : { plugins: u.plugins },
1544
+ ...Cn ? { idempotency: Cn } : {},
1545
+ restRoutes: Sn,
1546
+ appProcedures: me,
1547
+ discovered: {
1548
+ queries: [..._.queries, ...yr],
1549
+ mutations: _.mutations,
1550
+ actions: [..._.actions, ...vr],
1551
+ streams: _.streams,
1552
+ events: _.events,
1553
+ workflows: _.workflows,
1554
+ workflowWorkers: _.workflowWorkers,
1555
+ eventTriggers: _.eventTriggers,
1556
+ schedules: K,
1557
+ subscribers: J,
1558
+ outboxHandlers: Xn,
1559
+ connections: _.connections,
1560
+ reactions: Y,
1561
+ aggregates: rr,
1562
+ expectations: pr,
1563
+ budgets: hr,
1564
+ experiments: _r,
1565
+ ...De === void 0 ? {} : { webhooks: De }
1566
+ },
1567
+ log: $,
1568
+ analytics: Ae.sink,
1569
+ aggregateStorage: ir,
1570
+ aggregateCoordinator: ur,
1571
+ store: b,
1572
+ kv: st,
1573
+ cache: Ye,
1574
+ snapshotCache: We,
1575
+ schemaRegistry: Me,
1576
+ tenantScopedTables: _.tenantScopedTables,
1577
+ softDeleteScopedTables: _.softDeleteScopedTables,
1578
+ dataTransferSnapshot: On(y),
1579
+ dataTransferDialect: m,
1580
+ tenantIsolation: (process.env.VOLTRO_TENANT_ISOLATION ?? u?.tenancy?.isolation) === "namespace" ? "namespace" : "shared-schema",
1581
+ resolveSubject: (e, t) => xn({
1582
+ headers: e,
1583
+ clientId: t
1584
+ }),
1585
+ ...u?.auth === void 0 ? {} : { authority: u.auth },
1586
+ ...u?.agents === void 0 ? {} : { agents: u.agents },
1587
+ httpRoutes: O.flatMap((e) => e.httpRoutes ?? []),
1588
+ getStore: () => Re,
1589
+ ...Mn ? { baseLayer: Mn } : {},
1590
+ ...Gn === void 0 ? {} : { workflowEngineLayer: Gn },
1591
+ scheduleDefaultTrigger: Ln,
1592
+ scheduleCoordination: Bn,
1593
+ scheduleArmSelf: !q,
1594
+ dormancy: process.env.VOLTRO_DORMANCY === "sleep" || process.env.VOLTRO_DORMANCY === "always-on" ? process.env.VOLTRO_DORMANCY : u?.dormancy ?? "always-on",
1595
+ scheduleReplicaId: process.env.HOSTNAME ?? `pid-${process.pid}`,
1596
+ ...Kn === void 0 ? {} : { scheduleFireInterceptor: Kn },
1597
+ onSchedulerReady: (e) => {
1598
+ Vn = e;
1599
+ },
1600
+ inspectRoute: { handle: async (e, t, n, r) => await we(e, Er, t, {
1601
+ method: n,
1602
+ ...r === void 0 ? {} : { body: r }
1603
+ }) || ((n === "GET" ? await Zt(e, Er, t, { method: n }) : null) ?? Xt(e, Er, t, {
1604
+ method: n,
1605
+ ...r === void 0 ? {} : { body: r }
1606
+ }) ?? {
1607
+ status: 404,
1608
+ contentType: "application/json",
1609
+ body: JSON.stringify({ error: "not an inspect route" })
1610
+ }) },
1611
+ ...u?.name === void 0 ? {} : { appName: u.name },
1612
+ observability: gn,
1613
+ port: re,
1614
+ ...u?.transport?.wsPath ? { path: u.transport.wsPath } : {}
1615
+ });
1616
+ return R = Z.dispatcher, qe(C([
1617
+ _.queries,
1618
+ _.mutations,
1619
+ _.actions,
1620
+ _.streams
1621
+ ]), (e) => {
1622
+ $.warn(e);
1623
+ }), $.info(`API listening on :${re}`, {
1624
+ dialect: m,
1625
+ queries: _.queries.length,
1626
+ mutations: _.mutations.length,
1627
+ actions: _.actions.length,
1628
+ streams: _.streams.length,
1629
+ workflows: _.workflows.length,
1630
+ workflowWorkers: _.workflowWorkers.length,
1631
+ schedules: K.length,
1632
+ scheduleCoordination: Bn
1633
+ }), c.finish($), Tr(async () => {
1634
+ for (let e of en) e.stop();
1635
+ _t.stop(), rt(), bt?.dispose();
1636
+ try {
1637
+ await hn.deactivate(), await vn?.close(), await D({
1638
+ mirror: mt,
1639
+ log: $
1640
+ }), await Ae.dispose(), await Z.close(), await b.close?.();
1641
+ } catch (e) {
1642
+ console.error("serve: shutdown step failed, exiting anyway:", e);
1643
+ }
1644
+ }), await new Promise(() => {}), 0;
1645
+ };
1646
+ //#endregion
1647
+ export { Ni as n, ji as r, Pi as t };