@makaio/framework 1.0.0-dev-1785409369816 → 1.0.0-dev-1786014320559

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 (508) hide show
  1. package/dist/.makaio-build.json +4 -3
  2. package/dist/{account-identity-DFx8pwKL.mjs → account-identity-DGpXd8h_.mjs} +1 -1
  3. package/dist/adapter-BkdJaOOG.mjs +1 -0
  4. package/dist/adapter-subsystem/index.d.mts +138 -6
  5. package/dist/adapter-subsystem/index.mjs +1 -1
  6. package/dist/adapters/acp-client/index.d.mts +105 -7
  7. package/dist/adapters/acp-client/index.mjs +2 -2
  8. package/dist/adapters/config/index.d.mts +1 -1
  9. package/dist/adapters/config/index.mjs +1 -1
  10. package/dist/adapters/index.d.mts +362 -801
  11. package/dist/adapters/index.mjs +6 -6
  12. package/dist/adapters/node.d.mts +1 -1
  13. package/dist/adapters/node.mjs +1 -1
  14. package/dist/adapters/stream-session/index.d.mts +28 -7
  15. package/dist/adapters/stream-session/index.mjs +1 -1
  16. package/dist/agent-namespace-D51PODFf.mjs +1 -0
  17. package/dist/{ajv-DD3SIL2i.mjs → ajv-L5fKxaia.mjs} +2 -2
  18. package/dist/artifact-k3veR4Yx.mjs +1 -0
  19. package/dist/attach-error-BSlc7JfL.mjs +1 -0
  20. package/dist/{auth-DGEdiHF6.mjs → auth-A1K_7q-8.mjs} +1 -1
  21. package/dist/authority-state-bootstrap-YwtEImIB.mjs +1 -0
  22. package/dist/automation-trigger-CuSdQwir.mjs +1 -0
  23. package/dist/await-trigger-ph1S0zVI.mjs +1 -0
  24. package/dist/bus/index.d.mts +19 -5
  25. package/dist/bus/index.mjs +1 -1
  26. package/dist/bus-BIj0_aG6.mjs +1 -0
  27. package/dist/bus-CqgrphNE.mjs +2 -0
  28. package/dist/{canonical-model-BAytQ4NV.mjs → canonical-model-DJASlL4m.mjs} +1 -1
  29. package/dist/{capabilities-BQEp34ir.mjs → capabilities-Bqckjh7G.mjs} +1 -1
  30. package/dist/{client-DbS847wW.mjs → client-BL5__WT0.mjs} +1 -1
  31. package/dist/clients/index.d.mts +2 -2
  32. package/dist/clients/index.mjs +1 -1
  33. package/dist/clients/managed-install.d.mts +1 -1
  34. package/dist/clients/managed-install.mjs +1 -1
  35. package/dist/{compression-74fFeBha.mjs → compression-BbttSqm8.mjs} +1 -1
  36. package/dist/{config-namespace-TVX-hG4I.mjs → config-namespace-CyzeLWSg.mjs} +1 -1
  37. package/dist/{context-resolution-DdyhpH4L.d.mts → context-resolution-CW0ya4QO.d.mts} +13 -13
  38. package/dist/contracts/adapter/index.d.mts +3 -3
  39. package/dist/contracts/adapter/index.mjs +1 -1
  40. package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
  41. package/dist/contracts/artifact/index.d.mts +3 -3
  42. package/dist/contracts/artifact/index.mjs +1 -1
  43. package/dist/contracts/auth/index.d.mts +2 -2
  44. package/dist/contracts/auth/index.mjs +1 -1
  45. package/dist/contracts/automation-trigger/index.d.mts +4 -0
  46. package/dist/contracts/automation-trigger/index.mjs +1 -0
  47. package/dist/contracts/canonical-model/index.d.mts +1 -1
  48. package/dist/contracts/canonical-model/index.mjs +1 -1
  49. package/dist/contracts/capabilities/index.d.mts +1 -1
  50. package/dist/contracts/capabilities/index.mjs +1 -1
  51. package/dist/contracts/client/index.d.mts +2 -2
  52. package/dist/contracts/client/index.mjs +1 -1
  53. package/dist/contracts/common/index.d.mts +1 -1
  54. package/dist/contracts/config/index.d.mts +1 -1
  55. package/dist/contracts/config/index.mjs +1 -1
  56. package/dist/contracts/extension/index.d.mts +6 -5
  57. package/dist/contracts/extension/index.mjs +1 -1
  58. package/dist/contracts/facet/index.d.mts +1 -1
  59. package/dist/contracts/facet/index.mjs +1 -1
  60. package/dist/contracts/harness/index.d.mts +1 -1
  61. package/dist/contracts/harness/index.mjs +1 -1
  62. package/dist/contracts/host/index.d.mts +1 -1
  63. package/dist/contracts/host/index.mjs +1 -1
  64. package/dist/contracts/index.d.mts +181 -120
  65. package/dist/contracts/index.mjs +1 -1
  66. package/dist/contracts/materialization/index.d.mts +3 -3
  67. package/dist/contracts/materialization/index.mjs +1 -1
  68. package/dist/contracts/model-registry/index.d.mts +1 -1
  69. package/dist/contracts/model-registry/index.mjs +1 -1
  70. package/dist/contracts/native-session-supervisor/index.d.mts +1 -1
  71. package/dist/contracts/native-session-supervisor/index.mjs +1 -1
  72. package/dist/contracts/platform/index.d.mts +1 -1
  73. package/dist/contracts/platform/index.mjs +1 -1
  74. package/dist/contracts/provider/index.d.mts +2 -2
  75. package/dist/contracts/provider/index.mjs +1 -1
  76. package/dist/contracts/reaction/index.d.mts +2 -0
  77. package/dist/contracts/reaction/index.mjs +1 -0
  78. package/dist/contracts/session/index.d.mts +3 -3
  79. package/dist/contracts/session/index.mjs +1 -1
  80. package/dist/contracts/shared/index.d.mts +3 -3
  81. package/dist/contracts/shared/index.mjs +1 -1
  82. package/dist/contracts/skill/index.d.mts +1 -1
  83. package/dist/contracts/skill/index.mjs +1 -1
  84. package/dist/contracts/telemetry/index.d.mts +1 -1
  85. package/dist/contracts/telemetry/index.mjs +1 -1
  86. package/dist/contracts/timeout/index.d.mts +1 -1
  87. package/dist/contracts/timeout/index.mjs +1 -1
  88. package/dist/contracts/toast/index.mjs +1 -1
  89. package/dist/contracts/variant/index.d.mts +1 -1
  90. package/dist/contracts/variant/index.mjs +1 -1
  91. package/dist/contracts/worker-node/index.d.mts +1 -1
  92. package/dist/contracts/worker-node/index.mjs +1 -1
  93. package/dist/contracts/workflow/index.d.mts +3 -3
  94. package/dist/contracts/workflow/index.mjs +1 -1
  95. package/dist/contribution-BH-wKsWI.d.mts +35 -0
  96. package/dist/core/index.d.mts +60 -1
  97. package/dist/core/index.mjs +1 -1
  98. package/dist/definition-BYgHlmMw.d.mts +375 -0
  99. package/dist/{definition-CJfiv8xm.mjs → definition-CDg-Jq1T.mjs} +1 -1
  100. package/dist/{detached-extension-handle-Ddfquy5_.mjs → detached-extension-handle-DKd17UB6.mjs} +1 -1
  101. package/dist/drizzle/0031_adapter_session_currency.sql +66 -0
  102. package/dist/drizzle/0032_native_session_ownership.sql +77 -0
  103. package/dist/drizzle/0033_m_msf3hu2s.sql +1 -0
  104. package/dist/drizzle/meta/_journal.json +21 -0
  105. package/dist/{execution-attempt-repository-DWXKY41_.d.mts → execution-attempt-repository-DFyAnchJ.d.mts} +1 -1
  106. package/dist/{execution-target-Cf645pDj.mjs → execution-target-ByNwZh5-.mjs} +1 -1
  107. package/dist/extension-DMdmj9gi.mjs +1 -0
  108. package/dist/extension-DUmibvMk.mjs +1 -0
  109. package/dist/extension-context-CqfddWXs.d.mts +295 -0
  110. package/dist/{extension-discovery-CQRdbVQ6.d.mts → extension-discovery-Fhps4icD.d.mts} +2 -0
  111. package/dist/{extension-namespace-Yu41YepM.mjs → extension-namespace-B554RmCp.mjs} +1 -1
  112. package/dist/extension-package-provenance-Dh_-Z-tE.mjs +1 -0
  113. package/dist/{filesystem-service-DlP2HfDg.mjs → filesystem-service-FAtd9gWH.mjs} +1 -1
  114. package/dist/framework-packages-D_2hBZ-p.mjs +1 -0
  115. package/dist/git/index.mjs +1 -1
  116. package/dist/{globby-1yCVCk8s.mjs → globby-BBLuT_vy.mjs} +1 -1
  117. package/dist/handlers-2yd00VEq.mjs +57 -0
  118. package/dist/{harness-DpwsFsE7.mjs → harness-KxbWGL4I.mjs} +1 -1
  119. package/dist/{hook-responses-Dh1PWXqJ.d.mts → hook-responses-CQZIv3L3.d.mts} +2 -293
  120. package/dist/{index-DCZ8BX9S.d.mts → index-3eUIRy7T.d.mts} +304 -74
  121. package/dist/{index-brqfk9JQ.d.mts → index-B4xdTT3c.d.mts} +6 -6
  122. package/dist/{index-4VfqCjl2.d.mts → index-B5op6AsV.d.mts} +49 -39
  123. package/dist/{index-CMgLxw14.d.mts → index-B6GOuxVy2.d.mts} +18 -18
  124. package/dist/index-BFhJe-Sb.d.mts +302 -0
  125. package/dist/{index-EjsSBQXy2.d.mts → index-BSQ30wYP.d.mts} +1 -1
  126. package/dist/{index-DlsHL9Jg.d.mts → index-BiAYXjgM.d.mts} +25 -25
  127. package/dist/{index-B9UW_vPM.d.mts → index-ByZi9bml.d.mts} +4967 -1509
  128. package/dist/{index-BVlXneHH.d.mts → index-C7HcDpHE.d.mts} +14 -10
  129. package/dist/{index-BskPjMet.d.mts → index-CB4aIUoF.d.mts} +16 -16
  130. package/dist/{index-cqLS1eFV.d.mts → index-CDusRXio.d.mts} +70 -71
  131. package/dist/{index-DnG-QFpG.d.mts → index-CSN_0sCo.d.mts} +18 -1
  132. package/dist/{index-BAXkicoQ.d.mts → index-C__EQfKa.d.mts} +1 -1
  133. package/dist/{index-CLvQsL6s2.d.mts → index-CqQYgsbB.d.mts} +1660 -218
  134. package/dist/{index-BNMnIe-j.d.mts → index-CwDiyJkJ.d.mts} +276 -705
  135. package/dist/{index-GHASUiem.d.mts → index-DBadVauL.d.mts} +1 -1
  136. package/dist/{index-gUhidukN.d.mts → index-DI7-tIL3.d.mts} +299 -2
  137. package/dist/index-DP3o_13U.d.mts +165 -0
  138. package/dist/{index-DSBT83c0.d.mts → index-DcYAAJ0V.d.mts} +24 -3
  139. package/dist/{index-D5Nb7IEP.d.mts → index-Dch_AxUg.d.mts} +77 -39
  140. package/dist/{index-D_ODXsBv.d.mts → index-DcqSUsX6.d.mts} +35 -79
  141. package/dist/{index-B0Kf_OWi.d.mts → index-DgOfgjx3.d.mts} +1 -1
  142. package/dist/{index-Ds5_rDEJ.d.mts → index-DwLRZscE.d.mts} +1 -12
  143. package/dist/{index-DkiTJM5p.d.mts → index-DxYDRoDE2.d.mts} +17 -3
  144. package/dist/{index-CRvpVIqA.d.mts → index-OsbtyMgx2.d.mts} +10 -1
  145. package/dist/{index-BaZeoZoS.d.mts → index-bIe_57cL.d.mts} +1 -1
  146. package/dist/{json-value-Brslhqbm.d.mts → json-value-C1RGgS0a.d.mts} +16 -1
  147. package/dist/{json-value-DmU8ibo_.mjs → json-value-D57aJhVn.mjs} +1 -1
  148. package/dist/kernel/cli/index.d.mts +2 -2
  149. package/dist/kernel/cli/index.mjs +1 -1
  150. package/dist/kernel/cli/register.d.mts +1 -1
  151. package/dist/kernel/cli/register.mjs +1 -1
  152. package/dist/kernel/cli/schemas.mjs +1 -1
  153. package/dist/kernel/extension/index.d.mts +1 -1
  154. package/dist/kernel/extension/index.mjs +1 -1
  155. package/dist/kernel/index.d.mts +9 -9
  156. package/dist/kernel/index.mjs +1 -1
  157. package/dist/kernel/namespace/index.d.mts +2 -2
  158. package/dist/kernel/namespace/index.mjs +1 -1
  159. package/dist/kernel/observability/index.d.mts +1 -1
  160. package/dist/kernel/observability/index.mjs +1 -1
  161. package/dist/kernel/providers/index.d.mts +1 -1
  162. package/dist/kernel/providers/index.mjs +1 -1
  163. package/dist/kernel/window/index.d.mts +1 -1
  164. package/dist/kernel/window/index.mjs +1 -1
  165. package/dist/{lib-C7-s68uf.mjs → lib-B_rJ6r0T.mjs} +1 -1
  166. package/dist/{lib-DErgth_E.mjs → lib-CnOAtohU.mjs} +1 -1
  167. package/dist/load-extensions-CW9uzNR5.mjs +1 -0
  168. package/dist/{load-extensions-BxsDB87B.d.mts → load-extensions-DUpaMQ7G.d.mts} +17 -13
  169. package/dist/{materialization-Jd198K3y.mjs → materialization-CcpCDhXh.mjs} +1 -1
  170. package/dist/mcp-http-server/index.mjs +1 -1
  171. package/dist/model-ZH3L1dPW.mjs +1 -0
  172. package/dist/{namespace-BqxtpNAn.mjs → namespace-B7bntOB8.mjs} +1 -1
  173. package/dist/{namespace-CWUDFGOy.mjs → namespace-BFqkUTJp.mjs} +1 -1
  174. package/dist/{namespace-CjjFvrIA2.d.mts → namespace-CAy4P5mW.d.mts} +29 -29
  175. package/dist/{namespace-B8uKAzWJ.mjs → namespace-CFjdyNXG.mjs} +1 -1
  176. package/dist/{namespace-DV-Hr9sZ.d.mts → namespace-ChnRTUG4.d.mts} +11 -1
  177. package/dist/namespace-CxrOLeeP.mjs +1 -0
  178. package/dist/{namespace-g_mbIZq_.d.mts → namespace-DSlfFhB1.d.mts} +410 -26
  179. package/dist/{namespace-CupOzbRv.d.mts → namespace-DwZwGXgF.d.mts} +24 -20
  180. package/dist/{namespace-TseEI3Pu.d.mts → namespace-Rge9mMI-.d.mts} +36 -28
  181. package/dist/{native-session-supervisor-DRx0MX-d.mjs → native-session-supervisor-fZYPUk0-.mjs} +1 -1
  182. package/dist/node/bus-server/index.d.mts +1 -1
  183. package/dist/node/bus-server/index.mjs +1 -1
  184. package/dist/node/bus-server/server-lifecycle.d.mts +1 -1
  185. package/dist/node/bus-server/server-lifecycle.mjs +1 -1
  186. package/dist/{orchestrator-shared-BHCv-l2O.d.mts → orchestrator-shared-B-KRW1Z0.d.mts} +1 -0
  187. package/dist/orchestrator-shared-CTCZc6Vl.mjs +1 -0
  188. package/dist/ownership-memory-handler-Bblp93YC.mjs +1 -0
  189. package/dist/{package-DWMxGfzK.d.mts → package-Bf3hyuzs.d.mts} +234 -84
  190. package/dist/package-CBdvjyyZ.mjs +1 -0
  191. package/dist/package-CddkNbZI.mjs +1 -0
  192. package/dist/package-ypz4rKvn.mjs +7 -0
  193. package/dist/package.json +1 -1
  194. package/dist/{profile-BTAI31Nt.mjs → profile-BtznZlq3.mjs} +1 -1
  195. package/dist/{provider-context-Dq53Cgzz.mjs → provider-context-BrLZYnDW.mjs} +1 -1
  196. package/dist/{provider-context-PZIQWcqQ.mjs → provider-context-Dh-VOOYF.mjs} +1 -1
  197. package/dist/reaction-BS0k4eNN.mjs +1 -0
  198. package/dist/{registry-wfF2uTty.mjs → registry-BO_bOoky.mjs} +2 -2
  199. package/dist/{resolved-DZgqql2Z.mjs → resolved-DMByz1_2.mjs} +1 -1
  200. package/dist/rules/index.d.mts +1 -1
  201. package/dist/rules/index.mjs +1 -1
  202. package/dist/rules/schemas.d.mts +1 -1
  203. package/dist/runtime-bun/index.mjs +1 -1
  204. package/dist/runtime-node/extension-discovery.d.mts +1 -1
  205. package/dist/runtime-node/extension-validation.d.mts +1 -1
  206. package/dist/runtime-node/extension-validation.mjs +1 -1
  207. package/dist/runtime-node/index.d.mts +4 -4
  208. package/dist/runtime-node/index.mjs +24 -24
  209. package/dist/runtime-node/makaio-config.d.mts +1 -1
  210. package/dist/runtime-node/makaio-config.mjs +1 -1
  211. package/dist/runtime-node/workflow-worker/index.d.mts +1 -1
  212. package/dist/runtime-node/workflow-worker/index.mjs +1 -1
  213. package/dist/runtime-node/workflow-worker/worker-entry.mjs +1 -1
  214. package/dist/{schema-Dd-e89MO.mjs → schema-DBG7Jq5_.mjs} +1 -1
  215. package/dist/{schema-DKUb4rkr.d.mts → schema-DKTzriEY.d.mts} +519 -9
  216. package/dist/{schemas-DrVg4aQQ.d.mts → schemas-9qeeHGBf.d.mts} +8 -8
  217. package/dist/{schemas-CRB2O5zo.mjs → schemas-BqD8LlQw.mjs} +1 -1
  218. package/dist/{schemas-DaHQzpgm.mjs → schemas-CsjN7cmM.mjs} +1 -1
  219. package/dist/schemas-DSkBOdx_.mjs +1 -0
  220. package/dist/schemas-DplrlAyR.mjs +1 -0
  221. package/dist/{schemas-DnYiAvfz.d.mts → schemas-VbB1FTxx.d.mts} +24 -20
  222. package/dist/scoped-bus-ClwTWqX8.mjs +1 -0
  223. package/dist/{selection-BNwTKEVT.mjs → selection-7Ku8DBnh.mjs} +1 -1
  224. package/dist/services/adapter-runtime/index.d.mts +3 -3
  225. package/dist/services/adapter-runtime/index.mjs +1 -1
  226. package/dist/services/adapter-runtime/namespace.d.mts +1 -1
  227. package/dist/services/adapter-runtime/schemas.d.mts +1 -1
  228. package/dist/services/adapter-subsystem/index.d.mts +4 -4
  229. package/dist/services/adapter-subsystem/index.mjs +1 -1
  230. package/dist/services/adapter-subsystem/namespace.d.mts +2 -2
  231. package/dist/services/adapter-subsystem/namespace.mjs +1 -1
  232. package/dist/services/agent-runtime/index.d.mts +2 -2
  233. package/dist/services/agent-runtime/namespace.d.mts +1 -1
  234. package/dist/services/agent-runtime/schemas.d.mts +1 -1
  235. package/dist/services/automation-trigger/index.d.mts +943 -0
  236. package/dist/services/automation-trigger/index.mjs +1 -0
  237. package/dist/services/capability/index.d.mts +1 -1
  238. package/dist/services/capability/index.mjs +1 -1
  239. package/dist/services/codebase/index.d.mts +2 -2
  240. package/dist/services/codebase/namespace.d.mts +1 -1
  241. package/dist/services/codebase/schemas.d.mts +1 -1
  242. package/dist/services/compression/index.d.mts +2 -2
  243. package/dist/services/compression/namespace.d.mts +1 -1
  244. package/dist/services/compression/schemas.d.mts +1 -1
  245. package/dist/services/context-rules/index.d.mts +4 -4
  246. package/dist/services/context-rules/index.mjs +1 -1
  247. package/dist/services/execution-target/index.d.mts +3 -3
  248. package/dist/services/execution-target/index.mjs +1 -1
  249. package/dist/services/execution-target/namespace.d.mts +1 -1
  250. package/dist/services/execution-target/namespace.mjs +1 -1
  251. package/dist/services/execution-target/schemas.d.mts +1 -1
  252. package/dist/services/execution-target/schemas.mjs +1 -1
  253. package/dist/services/filesystem/index.d.mts +1 -1
  254. package/dist/services/filesystem/index.mjs +1 -1
  255. package/dist/services/filesystem/namespace.d.mts +6 -6
  256. package/dist/services/filesystem/schemas.d.mts +3 -3
  257. package/dist/services/git/namespace.mjs +1 -1
  258. package/dist/services/git/schemas.mjs +1 -1
  259. package/dist/services/harness/index.mjs +1 -1
  260. package/dist/services/index.d.mts +459 -93
  261. package/dist/services/index.mjs +1 -1
  262. package/dist/services/log-import/browser.d.mts +2 -2
  263. package/dist/services/log-import/index.d.mts +3 -3
  264. package/dist/services/log-import/log-import.d.mts +1 -1
  265. package/dist/services/log-import/log-import.mjs +1 -1
  266. package/dist/services/log-import/namespace.mjs +1 -1
  267. package/dist/services/log-import/schemas.mjs +1 -1
  268. package/dist/services/materialization/index.d.mts +1 -1
  269. package/dist/services/materialization/index.mjs +1 -1
  270. package/dist/services/model-registry/index.d.mts +1 -1
  271. package/dist/services/model-registry/index.mjs +1 -1
  272. package/dist/services/preferences/index.d.mts +2 -2
  273. package/dist/services/preferences/schemas.d.mts +1 -1
  274. package/dist/services/preferences/storage-namespace.d.mts +2 -2
  275. package/dist/services/provider-context/index.d.mts +1 -1
  276. package/dist/services/provider-context/index.mjs +1 -1
  277. package/dist/services/provider-runtime/index.mjs +1 -1
  278. package/dist/services/session/handlers/index.d.mts +2 -2
  279. package/dist/services/session/handlers/index.mjs +1 -1
  280. package/dist/services/session/index.d.mts +10 -10
  281. package/dist/services/session/index.mjs +1 -1
  282. package/dist/services/session/messages/namespace.d.mts +1 -1
  283. package/dist/services/session/messages/namespace.mjs +1 -1
  284. package/dist/services/session/orchestrator-testing/index.d.mts +1 -1
  285. package/dist/services/session/orchestrator-testing/index.mjs +1 -1
  286. package/dist/services/session/session-events/namespace.d.mts +1 -1
  287. package/dist/services/session/session-events/namespace.mjs +1 -1
  288. package/dist/services/session/storage/namespace.d.mts +1 -1
  289. package/dist/services/session/storage/schema.d.mts +2 -2
  290. package/dist/services/session/storage/schema.mjs +1 -1
  291. package/dist/services/session/testing/index.d.mts +12 -4
  292. package/dist/services/session/testing/index.mjs +36 -4
  293. package/dist/services/session/testing/orchestrator-shared.d.mts +1 -1
  294. package/dist/services/session/testing/orchestrator-shared.mjs +1 -1
  295. package/dist/services/session/turns/namespace.d.mts +1 -1
  296. package/dist/services/session/turns/namespace.mjs +1 -1
  297. package/dist/services/session-editor/index.d.mts +1 -1
  298. package/dist/services/session-editor/index.mjs +1 -1
  299. package/dist/services/settings/index.d.mts +3 -3
  300. package/dist/services/settings/index.mjs +1 -1
  301. package/dist/services/settings/namespace.d.mts +8 -8
  302. package/dist/services/settings/namespace.mjs +1 -1
  303. package/dist/services/settings/storage/clients-namespace.d.mts +1 -1
  304. package/dist/services/settings/storage/clients-namespace.mjs +1 -1
  305. package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
  306. package/dist/services/settings/storage/index.d.mts +3 -3
  307. package/dist/services/settings/storage/index.mjs +1 -1
  308. package/dist/services/settings/storage/providers-namespace.d.mts +1 -1
  309. package/dist/services/settings/storage/providers-namespace.mjs +1 -1
  310. package/dist/services/subagent/index.d.mts +1 -1
  311. package/dist/services/subagent/index.mjs +1 -1
  312. package/dist/services/subagent-template/index.d.mts +2 -2
  313. package/dist/services/subagent-template/namespace.d.mts +1 -1
  314. package/dist/services/subagent-template/schemas.d.mts +1 -1
  315. package/dist/services/tool-approval/index.d.mts +1 -1
  316. package/dist/services/tool-approval/index.mjs +1 -1
  317. package/dist/services/tools/index.d.mts +1 -1
  318. package/dist/services/tools/index.mjs +1 -1
  319. package/dist/services/tray-menu/index.d.mts +3 -3
  320. package/dist/services/tray-menu/index.mjs +1 -1
  321. package/dist/services/tray-menu/namespace.d.mts +1 -1
  322. package/dist/services/tray-menu/schemas.d.mts +1 -1
  323. package/dist/services/turn/index.d.mts +1 -1
  324. package/dist/services/turn/namespace.d.mts +1 -1
  325. package/dist/services/workflow-transitions/index.d.mts +1 -1
  326. package/dist/services/workflow-transitions/index.mjs +1 -1
  327. package/dist/session-BMy2kRpX.mjs +90 -0
  328. package/dist/session-Cipx34j6.mjs +1 -0
  329. package/dist/{session-lineage-B_JW5LpF.d.mts → session-lineage-B_PVa1XN.d.mts} +1 -1
  330. package/dist/shared-BFVuCDPx.mjs +1 -0
  331. package/dist/{skill-BR6rkfLe.mjs → skill-C1D51nhh.mjs} +1 -1
  332. package/dist/{src-DD0v-nIj.mjs → src-xbmzokNe.mjs} +1 -1
  333. package/dist/storage/drizzle/client.d.mts +1 -1
  334. package/dist/storage/drizzle/client.mjs +1 -1
  335. package/dist/storage/drizzle/index.d.mts +42 -2
  336. package/dist/storage/drizzle/index.mjs +1 -1
  337. package/dist/storage/handlers/drizzle/index.d.mts +1 -1
  338. package/dist/storage/handlers/drizzle/index.mjs +1 -1
  339. package/dist/storage/handlers/index.d.mts +1 -1
  340. package/dist/storage/handlers/index.mjs +1 -1
  341. package/dist/tool-approval-service-BVgN9Q1r.mjs +1 -0
  342. package/dist/{tools-PdG9fO1M.mjs → tools-DxwHox1a.mjs} +1 -1
  343. package/dist/{transition-Du3MQzJV.d.mts → transition-BF1nevaC.d.mts} +7 -34
  344. package/dist/{types-DMLDHFR9.d.mts → types-BNjPhj_a.d.mts} +1 -1
  345. package/dist/{types-Dzrwa1GY.d.mts → types-CijlWGwb.d.mts} +2036 -618
  346. package/dist/types-ClpEaoAm.d.mts +2917 -0
  347. package/dist/{types-D7_kevBK.d.mts → types-xCdGghb2.d.mts} +1 -1
  348. package/dist/ui-hooks/index.d.mts +29 -2
  349. package/dist/ui-hooks/index.mjs +1 -1
  350. package/dist/ui-kernel/index.d.mts +2 -2
  351. package/dist/ui-kernel/pages/schemas.d.mts +1 -1
  352. package/dist/ui-views/index.d.mts +1 -1
  353. package/dist/utils/index.d.mts +77 -1
  354. package/dist/utils/index.mjs +2 -2
  355. package/dist/{version-CoCeMxDT.mjs → version-BfNnVAGr.mjs} +1 -1
  356. package/dist/{view-builder-DeFd-k7C.d.mts → view-builder-Bc9dx6jF.d.mts} +1 -1
  357. package/dist/{visibility-qhGWmpSJ.mjs → visibility-Dl1o2I01.mjs} +1 -1
  358. package/dist/{worker-node-Bl9_vqYi.mjs → worker-node-BDOYPEpi.mjs} +1 -1
  359. package/dist/{worker-node-DZTuT1DS.mjs → worker-node-DJ41Tr-F.mjs} +1 -1
  360. package/dist/workflow-Hzc5jlnV.mjs +1 -0
  361. package/dist/workflow-engine/execution-attempt-repository.d.mts +1 -1
  362. package/dist/workflow-engine/index.d.mts +114 -395
  363. package/dist/workflow-engine/index.mjs +1 -1
  364. package/dist/workflow-engine/package.d.mts +1 -1
  365. package/dist/workflow-engine/package.mjs +1 -1
  366. package/dist/workflow-engine/provider-operation.d.mts +1 -1
  367. package/dist/workflow-engine/testing/index.d.mts +2 -2
  368. package/dist/workflow-engine/testing/index.mjs +1 -1
  369. package/dist/workflow-engine/testing/sqlite.d.mts +1 -1
  370. package/dist/workflow-engine/testing/sqlite.mjs +27 -27
  371. package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
  372. package/dist/workflow-engine/workflow-trigger-binding-consumer.d.mts +46 -0
  373. package/dist/workflow-engine/workflow-trigger-binding-consumer.mjs +1 -0
  374. package/dist/{workflow-transitions-DSc45ixc.mjs → workflow-transitions-DM0fN_eP.mjs} +1 -1
  375. package/dist/workflow-worker-DARC7UZl.mjs +1 -0
  376. package/dist/zod-json-schema-BAGAFfCN.mjs +1 -0
  377. package/package.json +29 -1
  378. package/dist/adapter-D5c5LrPN.mjs +0 -1
  379. package/dist/artifact-DGiXqb11.mjs +0 -1
  380. package/dist/attach-error-C3tngg6J.mjs +0 -1
  381. package/dist/authority-state-bootstrap-GPL_tqaT.mjs +0 -1
  382. package/dist/await-trigger-I3lrepb8.mjs +0 -1
  383. package/dist/bus-B6SAjgOC.mjs +0 -2
  384. package/dist/bus-C2l3K74u.mjs +0 -1
  385. package/dist/extension-DCA4pYrY.mjs +0 -1
  386. package/dist/extension-hjOPs10e.mjs +0 -1
  387. package/dist/framework-packages-C3RWfJDk.mjs +0 -1
  388. package/dist/handlers-CfnLyLfE.mjs +0 -57
  389. package/dist/load-extensions-D0DfjYLC.mjs +0 -1
  390. package/dist/model-BGgVmRnN.mjs +0 -1
  391. package/dist/namespace-DJfUADSV.mjs +0 -1
  392. package/dist/orchestrator-shared-BxmHCPvx.mjs +0 -1
  393. package/dist/package-CNUPPcU1.mjs +0 -7
  394. package/dist/package-Dft_RItb.mjs +0 -1
  395. package/dist/schemas-Cm09dXL4.mjs +0 -1
  396. package/dist/scoped-bus-C9BdNwfM.mjs +0 -1
  397. package/dist/session-BOGCd18q.mjs +0 -1
  398. package/dist/session-BTFiDoGz.mjs +0 -76
  399. package/dist/shared-BQ0CHIVy.mjs +0 -1
  400. package/dist/tool-approval-service-kBA0fRzm.mjs +0 -1
  401. package/dist/types-CJ_QZ1yW.d.mts +0 -1487
  402. package/dist/workflow-BfDbgtIQ.mjs +0 -1
  403. package/dist/workflow-worker-BN9XPxQO.mjs +0 -1
  404. package/dist/{adapter-auth-runtime-DO-FVTXg.mjs → adapter-auth-runtime-D9Lnl7cc.mjs} +0 -0
  405. package/dist/{adapter-binding-DQchUtrK.d.mts → adapter-binding-B-FBoCys.d.mts} +0 -0
  406. package/dist/{attempt-record-codec-CqO1_XnE.mjs → attempt-record-codec-DaFLKR5C.mjs} +0 -0
  407. package/dist/{base-orchestrator-BilsQNW1.d.mts → base-orchestrator-D9u4NyiM.d.mts} +0 -0
  408. package/dist/{capability-service-BqiLlRGA.mjs → capability-service-CJHNkjvm.mjs} +0 -0
  409. package/dist/{client-B--e2qcU.d.mts → client-4ihewPUm.d.mts} +0 -0
  410. package/dist/{client-binary-version-verifier-taewmKTY.mjs → client-binary-version-verifier-DJajc_Ff.mjs} +0 -0
  411. package/dist/{client-binary-version-verifier-CgjM_vGF.d.mts → client-binary-version-verifier-jDDZ64Ah.d.mts} +0 -0
  412. package/dist/{clients-namespace-DfxjG2ZP.d.mts → clients-namespace-DFWuUawf.d.mts} +0 -0
  413. package/dist/{config-namespace-BCqvufbD.d.mts → config-namespace-D1kyZj0B.d.mts} +0 -0
  414. package/dist/{create-static-mount-bbQhTt6W.mjs → create-static-mount-9tnGpIeK.mjs} +0 -0
  415. package/dist/{cross-spawn-B57KZuns.mjs → cross-spawn-BIgueAqr.mjs} +0 -0
  416. package/dist/{cursor-storage-DIFK_9hg.mjs → cursor-storage-ROWfiTh1.mjs} +0 -0
  417. package/dist/{definition-gnKgXU91.d.mts → definition-DB-kKc0d.d.mts} +0 -0
  418. package/dist/{definitions-xrrY0wgz.mjs → definitions-CF6YmEhL.mjs} +0 -0
  419. package/dist/{descriptor-to-package-DvF08krT.mjs → descriptor-to-package-BecVCopf.mjs} +0 -0
  420. package/dist/{drizzle-z_0SiGY8.mjs → drizzle-CPv3vdTE.mjs} +0 -0
  421. package/dist/{esm-CltRnX8_.mjs → esm-CBFWM8u_.mjs} +0 -0
  422. package/dist/{event-CmVjR6Ib.mjs → event-DR8U9Efx.mjs} +0 -0
  423. package/dist/{facet-BCI00njh.mjs → facet-DVsW12iF.mjs} +0 -0
  424. package/dist/{filesystem-service-CQ9yVkSz.d.mts → filesystem-service-Cm2RHKBa.d.mts} +0 -0
  425. package/dist/{handler-Cbv9FqDO.mjs → handler-Bqlk-6BY.mjs} +0 -0
  426. package/dist/{host-Caq6ZfSJ.mjs → host-k5yoyKHg.mjs} +0 -0
  427. package/dist/{identity-D6guMtmi.mjs → identity-DC3Pk0ps.mjs} +0 -0
  428. package/dist/{index-dtsLKOID.d.mts → index-42UdYStR.d.mts} +0 -0
  429. package/dist/{index-DR40QWlw.d.mts → index-BJAB-BW_.d.mts} +0 -0
  430. package/dist/{index-Dm1nUxCF.d.mts → index-BJMezANn.d.mts} +0 -0
  431. package/dist/{index-CnMu8BQl.d.mts → index-BQprJNA_.d.mts} +0 -0
  432. package/dist/{index-Cv-o5Krs.d.mts → index-BRCrFirq.d.mts} +0 -0
  433. package/dist/{index-BVRQEpAg.d.mts → index-BRzHs7Bx.d.mts} +6 -6
  434. /package/dist/{index-DXN_L5D6.d.mts → index-BSbGB23v.d.mts} +0 -0
  435. /package/dist/{index-vA--0lOM.d.mts → index-BVcQcphK.d.mts} +0 -0
  436. /package/dist/{index-ye0oklfU.d.mts → index-BcvqDfcN.d.mts} +0 -0
  437. /package/dist/{index-CGZQVTid.d.mts → index-BeENojSx2.d.mts} +0 -0
  438. /package/dist/{index-DjgLchuQ.d.mts → index-Beo_Ik8-.d.mts} +0 -0
  439. /package/dist/{index-sS6KUlrx.d.mts → index-BgGe9WZz.d.mts} +0 -0
  440. /package/dist/{index-CWHfOz6d.d.mts → index-CK3f0bAL.d.mts} +0 -0
  441. /package/dist/{index-DZunhZec.d.mts → index-CQuRTeRa.d.mts} +0 -0
  442. /package/dist/{index-jTaAHsul.d.mts → index-CRmE88hi.d.mts} +0 -0
  443. /package/dist/{index-CjdRdsd0.d.mts → index-CvW9_SzR.d.mts} +0 -0
  444. /package/dist/{index-ByKi34v5.d.mts → index-CxSSdIZz.d.mts} +0 -0
  445. /package/dist/{index-vcSj12YQ.d.mts → index-E4SET1AA.d.mts} +0 -0
  446. /package/dist/{index-DN4NOCqN2.d.mts → index-Ol9RBB0W2.d.mts} +0 -0
  447. /package/dist/{index-BIdsFcQs2.d.mts → index-aoxdnhJ42.d.mts} +0 -0
  448. /package/dist/{index-SsBHjUqA.d.mts → index-nydhGvXa.d.mts} +0 -0
  449. /package/dist/{jsonl-transport-bQl3JwIu.mjs → jsonl-transport-Bp_6pB2a.mjs} +0 -0
  450. /package/dist/{lib-DOBXZmYX.mjs → lib-Bwdd2m81.mjs} +0 -0
  451. /package/dist/{model-registry-CmgcPDH3.mjs → model-registry-Y854mUml.mjs} +0 -0
  452. /package/dist/{model-registry-xyBKSye-.mjs → model-registry-yURX738J.mjs} +0 -0
  453. /package/dist/{modes-BheyN7SS.mjs → modes-DmUsjHdV.mjs} +0 -0
  454. /package/dist/{namespace-HO2J9sO8.mjs → namespace-B9FEGuEu.mjs} +0 -0
  455. /package/dist/{namespace-jDhZjw-i.d.mts → namespace-Bi3CmYQy.d.mts} +0 -0
  456. /package/dist/{namespace-GPA7zots.d.mts → namespace-BusZERU8.d.mts} +0 -0
  457. /package/dist/{namespace-BOkKoq34.d.mts → namespace-ByP1Iipi.d.mts} +0 -0
  458. /package/dist/{namespace-YytVKIgI.d.mts → namespace-C1D77w7U.d.mts} +0 -0
  459. /package/dist/{namespace-CErHuXtb.d.mts → namespace-C6CVEGH8.d.mts} +0 -0
  460. /package/dist/{namespace-C-9si-fV.mjs → namespace-CfIW0hpQ.mjs} +0 -0
  461. /package/dist/{namespace-YxU1xf-K.mjs → namespace-CkBbNFSU.mjs} +0 -0
  462. /package/dist/{namespace-DWCEo-9M.d.mts → namespace-DX1Ec15L.d.mts} +0 -0
  463. /package/dist/{namespace-CWGKCNZm.mjs → namespace-DbNWsPFY.mjs} +0 -0
  464. /package/dist/{namespace-Cv1RFP7n.d.mts → namespace-Dgg0uoe6.d.mts} +0 -0
  465. /package/dist/{namespace-tGRAod3o.d.mts → namespace-s2y_NFKf.d.mts} +0 -0
  466. /package/dist/{namespace-Blp4c8GK.d.mts → namespace-yREpGJgG.d.mts} +0 -0
  467. /package/dist/{out-CvjtANXN.mjs → out-DrhwCgqM.mjs} +0 -0
  468. /package/dist/{packages-DtEEP0Vt.mjs → packages-FBv3fAOR.mjs} +0 -0
  469. /package/dist/{packages-BZ6pzFIq.d.mts → packages-N3-2Kl-Y.d.mts} +0 -0
  470. /package/dist/{platform-Bv8llU9c.mjs → platform-BrsMv_S3.mjs} +0 -0
  471. /package/dist/{provider-operation-Cxoe2SUr.d.mts → provider-operation-DJ_TLZFf.d.mts} +0 -0
  472. /package/dist/{providers-Co5UszRH.mjs → providers-CCcn4Ndp.mjs} +0 -0
  473. /package/dist/{providers-namespace-DjFkmvBR.d.mts → providers-namespace-DeJBh6MP.d.mts} +0 -0
  474. /package/dist/{quick-lru-CrOpWwrf.mjs → quick-lru-uwB0hP-y.mjs} +0 -0
  475. /package/dist/{schema-introspection-DgWQCpwx.mjs → schema-introspection-C1wvklj9.mjs} +0 -0
  476. /package/dist/{schema-Db-y-09L.mjs → schema-jIapW8Kb.mjs} +0 -0
  477. /package/dist/{schemas-CR8hSqTy.d.mts → schemas-B7zo7Zcx.d.mts} +0 -0
  478. /package/dist/{schemas-CqRm0i9a.mjs → schemas-BNdiVBWh.mjs} +0 -0
  479. /package/dist/{schemas-B1NWNASS.d.mts → schemas-C-Bm6Oac.d.mts} +0 -0
  480. /package/dist/{schemas-BO7uOum6.d.mts → schemas-CD0wOQxx.d.mts} +0 -0
  481. /package/dist/{schemas-N6x2z7Lf.d.mts → schemas-CeUI2i5j.d.mts} +0 -0
  482. /package/dist/{schemas-CwbYk_kZ.d.mts → schemas-Cg-Kwp8c.d.mts} +0 -0
  483. /package/dist/{schemas-BtZqovRH.d.mts → schemas-Cv3rR9Sz.d.mts} +0 -0
  484. /package/dist/{schemas-tDf_WiC8.mjs → schemas-CvHFbzdy.mjs} +0 -0
  485. /package/dist/{schemas-BsVYZviy.d.mts → schemas-DZH9lpxs.d.mts} +0 -0
  486. /package/dist/{schemas-BGExwp3j.mjs → schemas-DgwEVUt-.mjs} +0 -0
  487. /package/dist/{schemas-Bfxskx_2.mjs → schemas-mLpOfMoN.mjs} +0 -0
  488. /package/dist/{schemas-CQyRBqD6.d.mts → schemas-qA279_j_.d.mts} +0 -0
  489. /package/dist/{schemas-miYxK_Z1.d.mts → schemas-sMoRnBdZ.d.mts} +0 -0
  490. /package/dist/{semver-DlM8znk4.mjs → semver-DTXuyLcK.mjs} +0 -0
  491. /package/dist/{server-lifecycle-Dsq56aqC.d.mts → server-lifecycle-C_8iKgat.d.mts} +0 -0
  492. /package/dist/{server-lifecycle-kmQ5PUDv.mjs → server-lifecycle-DKx_fWlq.mjs} +0 -0
  493. /package/dist/{shared-schemas-DXwyMCwZ.mjs → shared-schemas-aahW97QW.mjs} +0 -0
  494. /package/dist/{src-CCu8TwL6.mjs → src-DHqsl5Pg.mjs} +0 -0
  495. /package/dist/{storage-namespace-BSrv0vXR.mjs → storage-namespace-Dz2jsssp.mjs} +0 -0
  496. /package/dist/{storage-namespace-dfywhXR3.d.mts → storage-namespace-Tf3P5yJ5.d.mts} +0 -0
  497. /package/dist/{storage-namespace-definition-BvlX0QV_.d.mts → storage-namespace-definition-BsnYAPot.d.mts} +0 -0
  498. /package/dist/{storage-namespace-definition-CkMKt7-I.mjs → storage-namespace-definition-CDef0E20.mjs} +0 -0
  499. /package/dist/{supports-color-DUugCQsK.mjs → supports-color-i7OTnKcZ.mjs} +0 -0
  500. /package/dist/{telemetry-Pr3oP2rk.mjs → telemetry-BvCBUjFg.mjs} +0 -0
  501. /package/dist/{timeout-DWDhddRJ.mjs → timeout-B0nYjLc8.mjs} +0 -0
  502. /package/dist/{tray-menu-service-BBLa-Rcv.mjs → tray-menu-service-Deo6yyP8.mjs} +0 -0
  503. /package/dist/{types-BrcjaNPZ.d.mts → types-CNS55jvt.d.mts} +0 -0
  504. /package/dist/{types-b54n1o57.d.mts → types-Ce6LL25v.d.mts} +0 -0
  505. /package/dist/{ui-config-CyCdlns_.mjs → ui-config-BIyGzMNL.mjs} +0 -0
  506. /package/dist/{variant-krjlTdJt.mjs → variant-B4uWdxW7.mjs} +0 -0
  507. /package/dist/{window-registry-BDnZLPVx.d.mts → window-registry-BLtVx3Iw.d.mts} +0 -0
  508. /package/dist/{window-registry-I-imZHV_.mjs → window-registry-CoBJq3u4.mjs} +0 -0
@@ -0,0 +1 @@
1
+ import{SessionStorageSubjects as e}from"./services/session/storage/namespace.mjs";import{n as t}from"./agent-namespace-D51PODFf.mjs";import{SessionOwnershipStorageSubjects as n,SessionStorageSetRequestSchema as r,SessionStorageUpdateSchema as i,SessionSubjects as a,resolveResumableAdapterSessionId as o}from"@makaio/framework/contracts";function s(){return{sessions:new Map,agents:new Map,claims:new Map}}function c(e,t){for(let[n,r]of e.claims)t(r)&&e.claims.delete(n)}function l(e,t){let n=e?.clientAccountId??null,r=t.clientAccountId??null;return!r||n===r?null:{previousClientAccountId:n,clientAccountId:r}}function u(e,t){let n=t.lastClientIdentityObservation;if(t.clientAccountId!==void 0&&!n)throw Error(`Session "${t.sessionId}" cannot persist clientAccountId without lastClientIdentityObservation`);if(t.clientAccountId!==void 0&&t.clientId===void 0)throw Error(`Session "${t.sessionId}" cannot persist clientAccountId without clientId`);if(n&&t.clientId!==void 0&&t.clientId!==n.clientId)throw Error(`Session "${t.sessionId}" cannot persist clientId "${t.clientId}" because lastClientIdentityObservation belongs to "${n.clientId}"`)}function d(e,t,n){let r=l(t,n);if(!r)return;let i=n.lastClientIdentityObservation;if(!i)return;let o={sessionId:n.sessionId,clientId:i.clientId,previousClientAccountId:r.previousClientAccountId,clientAccountId:r.clientAccountId,source:i.source,observedAt:i.observedAt,lastClientIdentityObservation:structuredClone(i)};queueMicrotask(()=>{Promise.resolve().then(()=>e.emit(a.clientAccount.changed,o)).catch(e=>{console.error(`[SessionStorage] Failed to emit session.clientAccount.changed:`,e)})})}function f(e){switch(e){case`fork`:return`fork`;case`subagent`:return`subagent`;case`compress`:return`compress`;case`root`:return;default:return}}function ee(e){switch(e.kind){case`root`:return{kind:`root`,parentAdapterSessionId:null,forkPointMessageId:null};case`fork`:return{kind:`fork`,parentAdapterSessionId:e.parentAdapterSessionId,forkPointMessageId:e.forkPointMessageId};case`subagent`:return{kind:`subagent`,parentAdapterSessionId:e.parentAdapterSessionId,forkPointMessageId:null};case`compress`:return{kind:`compress`,parentAdapterSessionId:e.parentAdapterSessionId,forkPointMessageId:null};default:return e.kind}}function p(){let e=0;return()=>{let t=Date.now();return e=t>e?t:e+1,e}}function m(e){return e.activation===`live`?`active`:`discovered`}const te=p();function ne(e,t){return e===`imported`||t===`imported`?`imported`:e===`tracking`||t===`tracking`?`tracking`:e??t??`discovered`}function h(e,t,n){n!==void 0&&(e[t]=n)}function re(e){return e.status===`closed`||e.status===`archived`||e.status===`active`&&e.isImported===!0}function g(e,t,n){if(!re(e)){if(n===`live`){e.status===`discovered`&&(e.status=`active`);return}t===`discovered`&&(e.status=`discovered`)}}function _(e,t,n){let r=e.startedAt??n,i=f(e.kind);return{sessionId:t,createdAt:r,lastActivityAt:r,agents:[],status:m(e),branchKind:i,adapterName:e.source,adapterSessionId:e.externalSessionId,adapterId:e.adapterId,clientId:e.clientId,isOrchestrated:!1,isImported:!0,title:e.title??void 0,targetWorkingDirectory:e.cwd??void 0,source:e.source,parentExternalSessionId:e.parentAdapterSessionId??void 0,logFilePath:e.logFilePath??void 0,discoveredAt:n,importStatus:e.importStatus??`discovered`,forkPointMessageId:e.forkPointMessageId??void 0,metadata:e.metadata,lastClientIdentityObservation:e.lastClientIdentityObservation,isSidechain:e.isSidechain,machineId:e.machineId??void 0}}function v(e,t,n){let r=ne(e.importStatus,t.importStatus);g(e,r,t.activation),e.isImported=!0,e.importStatus=r,e.adapterName??=t.source,e.adapterSessionId??=t.externalSessionId,e.source??=t.source,e.discoveredAt??=n}function y(e,t){t.logFilePath!==void 0&&t.logFilePath!==null&&(e.logFilePath??=t.logFilePath),t.cwd!==null&&(e.targetWorkingDirectory=t.cwd),t.title!==void 0&&t.title!==null&&(e.title=t.title),e.forkPointMessageId===void 0&&t.forkPointMessageId!==null&&(e.forkPointMessageId=t.forkPointMessageId),e.parentExternalSessionId===void 0&&t.parentAdapterSessionId!==null&&(e.parentExternalSessionId=t.parentAdapterSessionId);let n=f(t.kind);n!==void 0&&e.branchKind===void 0&&(e.branchKind=n),h(e,`adapterId`,t.adapterId),h(e,`clientId`,t.clientId),t.metadata!==void 0&&(e.metadata={...t.metadata,...e.metadata??{}}),h(e,`isSidechain`,t.isSidechain),h(e,`lastClientIdentityObservation`,t.lastClientIdentityObservation),t.machineId===null?e.machineId=void 0:t.machineId!==void 0&&(e.machineId??=t.machineId)}function b(e,t,n){t.startedAt!==void 0&&((n===void 0||e.createdAt===n)&&(e.createdAt=t.startedAt),(n===void 0||e.lastActivityAt===n)&&(e.lastActivityAt=t.startedAt))}function x(e,t,n){let r=e.discoveredAt;v(e,t,n),y(e,t),b(e,t,r)}function S(e,t){if(t.parentExternalSessionId===void 0)return;let n=t.source??t.adapterName,r=Array.from(e.values()).find(e=>e.adapterSessionId===t.parentExternalSessionId&&(e.source??e.adapterName)===n);r&&(t.parentSessionId=r.sessionId,t.rootSessionId=r.rootSessionId??r.sessionId)}function ie(e,t,n){if(n){e.emit(a.created,{sessionId:t.sessionId,parentSessionId:t.parentSessionId??null,branchKind:t.branchKind??null,createdAt:t.createdAt}).catch(e=>console.error(`[SessionStorage] Failed to emit session.created:`,e));return}e.emit(a.updated,{sessionId:t.sessionId,changedProperties:[`source`,`targetWorkingDirectory`,`title`]}).catch(e=>console.error(`[SessionStorage] Failed to emit session.updated:`,e))}function ae(e){let t=0,n=0,r=0;for(let i of e)i.importStatus===`imported`&&(t+=1),i.importStatus===`tracking`&&(n+=1),i.importStatus===`discovered`&&(r+=1);return{total:e.length,imported:t,tracking:n,discovered:r}}function C(e,t,n){return Array.from(e.values()).find(e=>e.adapterSessionId===n&&e.source===t)}function oe(e,t){let n=[];return t.cwd!==void 0&&(e.targetWorkingDirectory=t.cwd,n.push(`targetWorkingDirectory`)),t.logFilePath!==void 0&&(e.logFilePath=t.logFilePath,n.push(`logFilePath`)),t.machineId!==void 0&&(e.machineId=t.machineId??void 0,n.push(`machineId`)),n}function se(e,t,n){e.emit(a.importStatusChanged,{sessionId:t.sessionId,importStatus:n}).catch(e=>console.error(`[SessionStorage] Failed to emit session.importStatusChanged:`,e));let r=t.source??t.adapterName;n!==`imported`||t.adapterSessionId===void 0||r===void 0||e.emit(a.import.completed,{sessionId:t.sessionId,adapterSessionId:t.adapterSessionId,source:r}).catch(e=>console.error(`[SessionStorage] Failed to emit session.import.completed:`,e))}function ce(t,n){return t.on(e.rebindObserved,e=>{let r=e.payload,i=C(n,r.source,r.externalSessionId);if(!i){e.setResult({outcome:`not-found`});return}let o=oe(i,r);e.setResult({outcome:`rebound`,sessionId:i.sessionId}),o.length>0&&t.emit(a.updated,{sessionId:i.sessionId,changedProperties:o}).catch(e=>console.error(`[SessionStorage] Failed to emit session.updated:`,e))})}function le(t){let{bus:n,store:r,cloneSession:i,populateAgents:a}=t;return[n.on(e.importUpsert,e=>{let t=e.payload,i=C(r,t.source,t.externalSessionId),a=te(),o=i===void 0,s=i??_(t,crypto.randomUUID(),a);i?(x(i,t,a),i.parentExternalSessionId!==void 0&&i.parentSessionId===void 0&&S(r,i)):(r.set(s.sessionId,s),S(r,s)),ie(n,s,o),e.setResult({sessionId:s.sessionId,created:o})}),ce(n,r),n.on(e.getByLogFilePath,async e=>{let t=Array.from(r.values()).find(t=>t.logFilePath===e.payload.logFilePath);if(!t){e.setResult({session:null});return}let o=await a(n,t.sessionId);e.setResult({session:{...i(t),agents:o}})}),n.on(e.listImported,async e=>{let{source:t,importStatus:o}=e.payload,s=Array.from(r.values()).filter(e=>e.isImported===!0).filter(e=>t===void 0||e.source===t).filter(e=>o===void 0||e.importStatus===o).sort((e,t)=>t.createdAt-e.createdAt),c=await Promise.all(s.map(async e=>({...i(e),agents:await a(n,e.sessionId)})));e.setResult({sessions:c})}),n.on(e.countBySource,e=>{let t=Array.from(r.values()).filter(t=>t.isImported===!0&&t.source===e.payload.source);e.setResult(ae(t))}),n.on(e.updateImportStatus,e=>{let t=r.get(e.payload.sessionId),i=e.payload.importStatus;if(!t||t.importStatus===i){e.setResult({success:!1});return}t.importStatus=i,i===`imported`&&t.status===`discovered`&&(t.status=`active`),e.setResult({success:!0}),se(n,t,i)})]}function w(e,t){let n=t.expectIdentityOpenForLead;return n===void 0?!1:e.adapterName!==void 0||e.adapterId!==void 0?!0:(e.leadAgentId??null)!==n}async function T(e,n){let r=await e.requestOptional(t.listBySession,{sessionId:n});return r.handled?r.data.agents:[]}function E(e){return structuredClone(e)}function D(e,t,n){n!==void 0&&(e[t]=n)}function O(e,t,n){n!==void 0&&(e[t]=n??void 0)}function k(e,t){let n=e;return t.status!==`all`&&(n=n.filter(e=>e.status===t.status)),t.executionTargetId!==void 0&&(n=n.filter(e=>e.executionTargetId===t.executionTargetId)),n}function A(e,t){e.currentAdapterSessionId=t?.currentAdapterSessionId,e.currentAdapterSessionIdState=t?.currentAdapterSessionIdState??`inherited`,t!==null&&(e.leadAgentId=t.leadAgentId)}function j(e,t){D(e,`status`,t.status),D(e,`parentSessionId`,t.parentSessionId),D(e,`contextInheritance`,t.contextInheritance),D(e,`rootSessionId`,t.rootSessionId),D(e,`forkPointMessageId`,t.forkPointMessageId),D(e,`branchKind`,t.branchKind),D(e,`isOrchestrated`,t.isOrchestrated),D(e,`clientId`,t.clientId),D(e,`clientAccountId`,t.clientAccountId),D(e,`lastClientIdentityObservation`,t.lastClientIdentityObservation),D(e,`title`,t.title),D(e,`targetWorkingDirectory`,t.targetWorkingDirectory),D(e,`createdAt`,t.createdAt),D(e,`lastActivityAt`,t.lastActivityAt),D(e,`machineId`,t.machineId),t.identity!==void 0&&(e.adapterName=t.identity.adapterName,e.adapterId=t.identity.adapterId,D(e,`adapterSessionId`,t.identity.adapterSessionId)),O(e,`executionTargetId`,t.executionTargetId),O(e,`approvalPolicyOverride`,t.approvalPolicyOverride),O(e,`metadata`,t.metadata),t.spawningToolCallId===null?e.spawningToolCallId=void 0:t.spawningToolCallId!==void 0&&e.spawningToolCallId===void 0&&(e.spawningToolCallId=t.spawningToolCallId)}function M(t,n){return t.on(e.list,async e=>{let{status:r=`all`,limit:i,offset:a=0,includePreview:o=!1,executionTargetId:s}=e.payload,c=k(Array.from(n.values()),{status:r,executionTargetId:s});c.sort((e,t)=>t.lastActivityAt-e.lastActivityAt);let l=c.length;i!==void 0&&(c=c.slice(a,a+i));let u=await Promise.all(c.map(async e=>({...E(e),agents:await T(t,e.sessionId)}))),d=o?u.map(e=>({...e,preview:{messageCount:0,firstUserMessage:null}})):u;e.setResult({sessions:d,total:l})})}function N(t,n){return t.on(e.update,async e=>{let r=structuredClone(i.request.parse(e.payload)),a=n.get(r.sessionId);if(!a){e.setResult({success:!1,clientAccountChanged:!1});return}if(r.expectedStatus!==void 0&&!r.expectedStatus.includes(a.status)){e.setResult({success:!1,clientAccountChanged:!1});return}if(w(a,r)){e.setResult({success:!1,clientAccountChanged:!1});return}let o=E(a);u(o,{sessionId:a.sessionId,clientId:r.clientId??a.clientId,clientAccountId:r.clientAccountId??a.clientAccountId,lastClientIdentityObservation:r.lastClientIdentityObservation??a.lastClientIdentityObservation}),j(a,r),e.setResult({success:!0,clientAccountChanged:(o.clientAccountId??null)!==(a.clientAccountId??null)}),d(t,o,E(a))})}function P(t,n=s()){let i=n.sessions,a=[];return a.push(t.on(e.get,async e=>{let n=i.get(e.payload.sessionId);if(!n){e.setResult({session:null});return}let r=await T(t,e.payload.sessionId);e.setResult({session:{...E(n),agents:r}})})),a.push(t.on(e.set,async e=>{let{sessionId:n,session:a,ifAbsent:o}=r.parse(e.payload);if(o&&i.has(n)){e.setResult({success:!1,clientAccountChanged:!1});return}let s=structuredClone(a),c=i.get(n)??null,l=c?E(c):null;A(s,l),u(c,s),i.set(n,s),e.setResult({success:!0,clientAccountChanged:(l?.clientAccountId??null)!==(s.clientAccountId??null)}),d(t,l,E(s))})),a.push(t.on(e.delete,async e=>{let t=new Set;for(let[r,i]of n.agents)i.sessionId===e.payload.sessionId&&(t.add(r),n.agents.delete(r));c(n,n=>n.sessionId===e.payload.sessionId||t.has(n.agentId)),i.delete(e.payload.sessionId),e.setResult({success:!0}),await e.next()})),a.push(M(t,i)),a.push(t.on(e.getChildren,e=>{let{sessionId:t}=e.payload,n=Array.from(i.values()),r=n.filter(e=>e.parentSessionId===t),a=new Set(n.map(e=>e.parentSessionId).filter(e=>!!e)),o=r.map(e=>({sessionId:e.sessionId,title:e.title??null,forkPointMessageId:e.forkPointMessageId??null,branchKind:e.branchKind??null,messageCount:0,hasChildren:a.has(e.sessionId),spawningToolCallId:e.spawningToolCallId}));e.setResult({children:o})})),a.push(t.on(e.getStatusCounts,e=>{e.payload;let t=Array.from(i.values()),n=t.filter(e=>e.status===`active`).length,r=t.filter(e=>e.status===`closed`).length,a=t.filter(e=>e.status===`archived`).length,o=t.filter(e=>e.status===`discovered`).length;e.setResult({all:n+r+a+o,active:n,closed:r,archived:a,discovered:o})})),a.push(N(t,i)),a.push(F(t,i)),a.push(...le({bus:t,store:i,populateAgents:T,cloneSession:E})),()=>a.forEach(e=>e())}function F(n,r){return n.on(e.getByAdapterSessionId,async e=>{let{adapterSessionId:i,source:a,adapterName:o}=e.payload,s=Array.from(r.values()).filter(e=>e.adapterSessionId!==void 0&&e.adapterSessionId===i&&(a===void 0||e.source===a)&&(o===void 0||e.adapterName===o)),c=s[0];if(s.length!==1||c===void 0){e.setResult({session:null});return}let l=await n.requestOptional(t.listBySession,{sessionId:c.sessionId}),u=l.handled?l.data.agents:[];e.setResult({session:{...E(c),agents:u}})})}function I(e){return structuredClone(e)}function L(e,t){let{adapterId:n,adapterSessionId:r,cwd:i,model:a,allowedDirectories:o,providerConfigId:s}=t;return n===void 0&&r===void 0&&i===void 0&&a===void 0&&o===void 0&&s===void 0?!1:(n!==void 0&&(e.adapterId=n),r!==void 0&&(e.adapterSessionId=r),i!==void 0&&(e.cwd=i),a!==void 0&&(e.model=a),o!==void 0&&(e.allowedDirectories=o),s===null?delete e.providerConfigId:s!==void 0&&(e.providerConfigId=s),!0)}function R(e){return{status:e.status,adapterSessionId:e.adapterSessionId,currentAdapterSessionId:e.currentAdapterSessionId,currentAdapterSessionIdState:e.currentAdapterSessionIdState,revision:e.revision,currencyFence:e.currencyFence}}function z(e,t,n){let r=e.get(t),i=r===void 0?void 0:R(r);e.set(t,{...structuredClone(n),status:i?.status===`disposed`?`disposed`:n.status,adapterSessionId:i===void 0?n.adapterSessionId:i.adapterSessionId,currentAdapterSessionId:i?.currentAdapterSessionId,currentAdapterSessionIdState:i?.currentAdapterSessionIdState??`inherited`,revision:i?.revision??0,currencyFence:i?.currencyFence??0})}function B(e,t,n){let r=e.get(t);return r===void 0?!1:n(r)}function V(e,t,n,r){let i=e.get(t);return i===void 0?{success:!1,transitioned:!1}:i.status===`disposed`||r!==void 0&&!r.includes(i.status)?{success:!0,transitioned:!1}:(i.status=n,i.lastActivityAt=Date.now(),{success:!0,transitioned:!0})}function H(e,t){return c(e,e=>e.agentId===t),e.agents.delete(t)}function U(e,n=s()){let r=n.agents,i=[];return i.push(e.on(t.get,e=>{let t=r.get(e.payload.agentId);e.setResult({agent:t===void 0?null:I(t)})})),i.push(e.on(t.set,e=>{z(r,e.payload.agentId,e.payload.agent),e.setResult({success:!0})})),i.push(e.on(t.delete,e=>{e.setResult({success:H(n,e.payload.agentId)})})),i.push(e.on(t.listByAdapter,e=>{let{adapterName:t,status:n}=e.payload,i=Array.from(r.values()).filter(e=>e.adapterName===t);n&&n!==`all`&&(i=i.filter(e=>e.status===n)),e.setResult({agents:i.map(I)})})),i.push(e.on(t.listBySession,e=>{let t=Array.from(r.values()).filter(t=>t.sessionId===e.payload.sessionId);e.setResult({agents:t.map(I)})})),i.push(e.on(t.updateStatus,e=>{let{agentId:t,status:n,expectedStatus:i}=e.payload;e.setResult(V(r,t,n,i))})),i.push(e.on(t.updateActivity,e=>{let t=B(r,e.payload.agentId,t=>(t.lastActivityAt=e.payload.lastActivityAt,!0));e.setResult({success:t})})),i.push(e.on(t.updateRuntime,e=>{let{adapterId:t,adapterSessionId:n,cwd:i,model:a,allowedDirectories:o,providerConfigId:s}=e.payload,c=B(r,e.payload.agentId,e=>L(e,{adapterId:t,adapterSessionId:n,cwd:i,model:a,allowedDirectories:o,providerConfigId:s})?(e.lastActivityAt=Date.now(),!0):!1);e.setResult({success:c})})),()=>i.forEach(e=>e())}function W(e,t,n,r){for(let i of e.values())if(i.machineId===t&&i.adapterId===n&&i.providerSessionId===r)return i}function G(e,t){for(let n of e.values())if(n.claimToken===t)return n}function ue(e,t){let n=0;for(let r of e.values())r.agentId===t&&r.fence>n&&(n=r.fence);return n}function K(e,t,n){let r=e.agents.get(t)?.currencyFence??0;return 1+Math.max(n,r,ue(e.claims,t))}function q(e,t){let n=e.currentAdapterSessionIdState??`inherited`;if(n!==`inherited`)return{currentAdapterSessionId:e.currentAdapterSessionId,currentAdapterSessionIdState:n};let r=e.adapterSessionId??null;return r===t?{currentAdapterSessionId:void 0,currentAdapterSessionIdState:`inherited`}:r===null?{currentAdapterSessionId:void 0,currentAdapterSessionIdState:`moved`}:{currentAdapterSessionId:r,currentAdapterSessionIdState:`confirmed`}}function de(e,t){if(t===`confirmed`!=(e!==null))throw Error(`Currency pairing invariant violated: confirmed ↔ id !== null (state="${t}", id=${e===null?`null`:`present`})`)}function J(e){return{adapterSessionId:e.adapterSessionId??null,currentAdapterSessionId:e.currentAdapterSessionId??null,currentAdapterSessionIdState:e.currentAdapterSessionIdState??`inherited`}}function Y(e,t,n){let r=e.sessions.get(t.sessionId);if(r===void 0)return{kind:`refused`,result:{outcome:`not-found`,missing:`session`}};let i=r.leadAgentId??null,a=t.designateLead;if(a===void 0)return{kind:`ok`,leadDesignated:!1,previousLeadAgentId:i};let o=a.clear===!0,s=o?null:n.agentId;if(!o&&n.status===`disposed`)return{kind:`refused`,result:{outcome:`agent-disposed`}};if(!o&&i===n.agentId)return{kind:`ok`,leadDesignated:!1,previousLeadAgentId:i};if(i!==a.expectedLeadAgentId)return{kind:`conflict`,currentLeadAgentId:i};if(r.leadAgentId=s??void 0,!o){let e=q(n,r.adapterSessionId??null);r.currentAdapterSessionId=e.currentAdapterSessionId,r.currentAdapterSessionIdState=e.currentAdapterSessionIdState}return{kind:`ok`,leadDesignated:!0,previousLeadAgentId:i}}function X(e,t,n){if(!e.sessions.has(t.sessionId))return{kind:`refused`,result:{outcome:`not-found`,missing:`session`}};let r=e.agents.get(t.agentId);if(r===void 0||r.sessionId!==t.sessionId)return{kind:`refused`,result:{outcome:`not-found`,missing:`agent`}};if(r.status===`disposed`)return{kind:`refused`,result:{outcome:`agent-disposed`}};let i=G(e.claims,t.claimToken);if(i!==void 0&&i.claimId!==n?.claimId)throw Error(`UNIQUE constraint failed: adapter_session_claims.claim_token (uniq_adapter_session_claims_token): "${t.claimToken}" is already in use`);return{kind:`ok`,agent:r}}function Z(e,t,n){return{outcome:e,claim:t===null?null:structuredClone(t),leadDesignated:n.leadDesignated,previousLeadAgentId:n.previousLeadAgentId}}function fe(e,t){let n=X(e,t);if(n.kind===`refused`)return n.result;let r=Date.now(),i=crypto.randomUUID(),a={claimId:i,machineId:t.machineId,adapterId:t.adapterId,adapterName:t.adapterName,providerSessionId:t.providerSessionId,sessionId:t.sessionId,agentId:t.agentId,claimToken:t.claimToken,fence:K(e,t.agentId,0),status:`held`,claimedAt:r,updatedAt:r};e.claims.set(i,structuredClone(a));let o=Y(e,t,n.agent);return o.kind===`ok`?Z(`claimed`,a,o):(e.claims.delete(i),o.kind===`conflict`?{outcome:`lead-conflict`,currentLeadAgentId:o.currentLeadAgentId}:o.result)}function pe(e,t,n){let r=X(e,t,n);if(r.kind===`refused`)return r.result;let i=Date.now(),a={...n,claimToken:t.claimToken,fence:K(e,t.agentId,n.fence),agentId:t.agentId,sessionId:t.sessionId,adapterName:t.adapterName,status:`held`,claimedAt:i,updatedAt:i};e.claims.set(n.claimId,structuredClone(a));let o=Y(e,t,r.agent);return o.kind===`ok`?Z(`claimed`,a,o):(e.claims.set(n.claimId,structuredClone(n)),o.kind===`conflict`?{outcome:`lead-conflict`,currentLeadAgentId:o.currentLeadAgentId}:o.result)}function me(e,t,n){if(n.status!==`held`)return{outcome:`already-claimed`,holder:structuredClone(n)};let r=X(e,t,n);if(r.kind===`refused`)return r.result;let i=Y(e,t,r.agent);return i.kind===`conflict`?{outcome:`lead-conflict`,currentLeadAgentId:i.currentLeadAgentId}:i.kind===`refused`?i.result:Z(`idempotent`,n,i)}function he(e,t){let n=e.agents.get(t.agentId);if(n===void 0||n.sessionId!==t.sessionId)return{outcome:`not-found`,missing:`agent`};if(n.status===`disposed`&&t.designateLead?.clear!==!0)return{outcome:`agent-disposed`};let r=Y(e,t,n);return r.kind===`conflict`?{outcome:`lead-conflict`,currentLeadAgentId:r.currentLeadAgentId}:r.kind===`refused`?r.result:Z(`claimed`,null,r)}function ge(e,t){let{providerSessionId:n}=t;if(n===null)return he(e,t);let r={...t,providerSessionId:n},i=W(e.claims,r.machineId,r.adapterId,n);return i===void 0?fe(e,r):i.claimToken===r.claimToken?i.agentId===r.agentId&&i.sessionId===r.sessionId?me(e,r,i):{outcome:`already-claimed`,holder:structuredClone(i)}:r.supersedes?.claimToken===i.claimToken||e.agents.get(i.agentId)?.status===`disposed`?pe(e,r,i):{outcome:`already-claimed`,holder:structuredClone(i)}}function _e(e,t,n){let{agentId:r,claimToken:i,fence:a,expectedRevision:o,target:s}=n,c=t.revision??0,l=t.currencyFence??0;if(t.status===`disposed`)return{outcome:`agent-disposed`};let u=G(e.claims,i);if(u===void 0||u.agentId!==r||u.sessionId!==t.sessionId||u.status!==`held`||u.fence!==a)return{outcome:`not-owner`};if(a<l)return{outcome:`superseded`,currentFence:l};let d=J(t);if(d.currentAdapterSessionId===s.currentAdapterSessionId&&d.currentAdapterSessionIdState===s.currentAdapterSessionIdState&&l===a)return{outcome:`idempotent`,revision:c,currency:d,sessionSnapshotUpdated:!1};if(c!==o)return{outcome:`currency-changed`,revision:c,currency:d}}function Q(e,t,n){let r=_e(e,t,n);if(r!==void 0)return r;let{agentId:i,fence:a,expectedRevision:o,target:s}=n;de(s.currentAdapterSessionId,s.currentAdapterSessionIdState);let c=t.adapterSessionId??null;t.currentAdapterSessionId=s.currentAdapterSessionId??void 0,t.currentAdapterSessionIdState=s.currentAdapterSessionIdState,t.currencyFence=a,t.revision=o+1,t.lastActivityAt=Date.now();let l=e.sessions.get(t.sessionId),u=!1;if(l!==void 0&&l.leadAgentId===i){let e=q(t,l.adapterSessionId??null);l.currentAdapterSessionId=e.currentAdapterSessionId,l.currentAdapterSessionIdState=e.currentAdapterSessionIdState,u=!0}return{outcome:`settled`,revision:o+1,currency:{adapterSessionId:c,...s},sessionSnapshotUpdated:u}}function ve(e,t,n){let r=G(e.claims,t);if(!(r===void 0||r.claimId===n))throw Error(`UNIQUE constraint failed: adapter_session_claims.claim_token (uniq_adapter_session_claims_token): "${t}" is already in use`)}function ye(e,t,n){let{machineId:r,adapterId:i,agentId:a}=t,o=W(e.claims,r,i,n),s,c;if(o!==void 0&&o.agentId===a&&o.status===`held`)s=o,c=()=>{};else if(o!==void 0&&e.agents.get(o.agentId)?.status!==`disposed`)return{outcome:`already-claimed`,holder:structuredClone(o)};else{let l=Date.now(),u=o?.claimId??crypto.randomUUID();ve(e,t.movement.claimToken,u),s={claimId:u,machineId:r,adapterId:i,adapterName:t.adapterName,providerSessionId:n,sessionId:t.sessionId,agentId:a,claimToken:t.movement.claimToken,fence:K(e,a,o?.fence??0),status:`held`,claimedAt:l,updatedAt:l},e.claims.set(u,structuredClone(s)),c=o===void 0?()=>{e.claims.delete(u)}:()=>{e.claims.set(u,structuredClone(o))}}let l=t.movement.kind===`confirmed`?Array.from(e.claims.values()).filter(e=>e.agentId===a&&e.status===`held`&&e.claimId!==s.claimId):[];for(let t of l)e.claims.delete(t.claimId);return{generation:s,releasedProviderSessionIds:l.map(e=>e.providerSessionId),rollback:()=>{for(let t of l)e.claims.set(t.claimId,structuredClone(t));c()}}}function be(e,t){if(e.kind===`confirmed`)return{providerSessionId:e.providerSessionId,currency:{currentAdapterSessionId:e.providerSessionId,currentAdapterSessionIdState:`confirmed`}};let n=o(J(t));return n===null?null:{providerSessionId:n,currency:{currentAdapterSessionId:null,currentAdapterSessionIdState:`moved`}}}function xe(e,t){return e.on(n.read,e=>{let{agentId:n}=e.payload,r=t.agents.get(n);if(r===void 0){e.setResult({ownership:null});return}let i=Array.from(t.claims.values()).filter(e=>e.agentId===n).sort((e,t)=>e.fence-t.fence||e.claimId.localeCompare(t.claimId));e.setResult({ownership:{agentId:n,sessionId:r.sessionId,currency:J(r),revision:r.revision??0,currencyFence:r.currencyFence??0,claims:i.map(e=>structuredClone(e))}})})}function Se(e,t){return e.on(n.settleCurrency,e=>{let n=t.agents.get(e.payload.agentId);if(n===void 0){e.setResult({outcome:`not-found`});return}e.setResult(Q(t,n,e.payload))})}function Ce(e,t){return e.on(n.settleMovement,e=>{let n=e.payload,r=t.agents.get(n.agentId);if(r===void 0||r.sessionId!==n.sessionId){e.setResult({outcome:`not-found`});return}if(r.status===`disposed`){e.setResult({outcome:`agent-disposed`});return}let i=be(n.movement,r);if(i===null){e.setResult({outcome:`idempotent`,revision:r.revision??0,currency:J(r),sessionSnapshotUpdated:!1,claim:null});return}let a=ye(t,n,i.providerSessionId);if(!(`generation`in a)){e.setResult(a);return}let o=Q(t,r,{agentId:n.agentId,claimToken:a.generation.claimToken,fence:a.generation.fence,expectedRevision:n.expectedRevision,target:i.currency});if(o.outcome!==`settled`){a.rollback(),e.setResult(o.outcome===`idempotent`?{...o,claim:structuredClone(a.generation)}:o);return}e.setResult({outcome:`settled`,revision:o.revision,currency:o.currency,sessionSnapshotUpdated:o.sessionSnapshotUpdated,releasedProviderSessionIds:a.releasedProviderSessionIds,claim:structuredClone(a.generation)})})}function $(e,t){return e.on(n.releaseAgentClaims,e=>{let{agentId:n,claimToken:r,disposition:i}=e.payload,a=Array.from(t.claims.values()).filter(e=>e.agentId===n&&(r===void 0||e.claimToken===r));if(i===`released`){for(let e of a)t.claims.delete(e.claimId);e.setResult({releasedProviderSessionIds:a.map(e=>e.providerSessionId),markedClaims:[],claimTokenNotFound:r!==void 0&&a.length===0});return}let o=Date.now(),s=a.map(e=>{let n={...e,status:i,updatedAt:o};return t.claims.set(e.claimId,structuredClone(n)),n});e.setResult({releasedProviderSessionIds:[],markedClaims:s,claimTokenNotFound:r!==void 0&&a.length===0})})}function we(e,t){return e.on(n.release,e=>{let{agentId:n,claimToken:r,disposition:i}=e.payload,a=G(t.claims,r);if(a===void 0){e.setResult({outcome:`not-found`});return}if(a.agentId!==n){e.setResult({outcome:`not-owner`,holder:structuredClone(a)});return}if(i===`released`){t.claims.delete(a.claimId),e.setResult({outcome:`released`});return}let o={...a,status:i,updatedAt:Date.now()};t.claims.set(a.claimId,structuredClone(o)),e.setResult({outcome:`marked`,claim:structuredClone(o)})})}function Te(e,t){return e.on(n.listClaims,e=>{let{machineId:n,adapterId:r,providerSessionId:i,statuses:a}=e.payload,o=Array.from(t.claims.values()).filter(e=>e.machineId===n&&(r===void 0||e.adapterId===r)&&(i===void 0||e.providerSessionId===i)&&(a===void 0||a.includes(e.status)));o.sort((e,t)=>e.claimedAt-t.claimedAt||e.claimId.localeCompare(t.claimId)),e.setResult({claims:o.map(e=>structuredClone(e))})})}function Ee(e,t=s()){let r=[xe(e,t),e.on(n.claim,e=>{e.setResult(ge(t,e.payload))}),Se(e,t),Ce(e,t),we(e,t),$(e,t),Te(e,t)];return()=>{for(let e=r.length-1;e>=0;--e)r[e]?.()}}export{m as a,ee as c,s as d,w as i,u as l,U as n,p as o,P as r,f as s,Ee as t,d as u};
@@ -1,10 +1,11 @@
1
- import { l as ProviderOperationOwnershipRecord, o as ProviderOperationClaimDecision, s as ProviderOperationMutationDecision } from "./provider-operation-Cxoe2SUr.mjs";
2
- import { A as RecoverableAttemptRecord, C as ProvisioningClaimDecision, D as RecordProviderOperationUncertaintyInput, E as RecordInfrastructureFailureInput, M as TakeOverProviderOperationInput, O as RecordProvisionerIncarnationLostInput, S as ProvisioningAbsenceDecision, T as RecordAllocationTerminatedInput, a as BeginProvisioningInput, b as PendingAttemptAbandonmentDecision, f as ExecutionAttemptOutcomeDecision, h as ExecutionAttemptRepository, i as AllocationTerminationDecision, j as RenewProviderOperationClaimInput, k as RecordProvisioningAbsentInput, n as AllocationRefEvolution, o as DiscoveredAllocationDecision, p as ExecutionAttemptRecord, r as AllocationRefEvolutionDecision, t as AllocationRecordingDecision, v as HandoffProviderOperationInput, w as RecordAllocationInput, x as ProvisionerIncarnationLossDecision, y as InfrastructureFailureDecision } from "./execution-attempt-repository-DWXKY41_.mjs";
1
+ import { l as ProviderOperationOwnershipRecord, o as ProviderOperationClaimDecision, s as ProviderOperationMutationDecision } from "./provider-operation-DJ_TLZFf.mjs";
2
+ import { A as RecoverableAttemptRecord, C as ProvisioningClaimDecision, D as RecordProviderOperationUncertaintyInput, E as RecordInfrastructureFailureInput, M as TakeOverProviderOperationInput, O as RecordProvisionerIncarnationLostInput, S as ProvisioningAbsenceDecision, T as RecordAllocationTerminatedInput, a as BeginProvisioningInput, b as PendingAttemptAbandonmentDecision, f as ExecutionAttemptOutcomeDecision, h as ExecutionAttemptRepository, i as AllocationTerminationDecision, j as RenewProviderOperationClaimInput, k as RecordProvisioningAbsentInput, n as AllocationRefEvolution, o as DiscoveredAllocationDecision, p as ExecutionAttemptRecord, r as AllocationRefEvolutionDecision, t as AllocationRecordingDecision, v as HandoffProviderOperationInput, w as RecordAllocationInput, x as ProvisionerIncarnationLossDecision, y as InfrastructureFailureDecision } from "./execution-attempt-repository-DFyAnchJ.mjs";
3
3
  import { IMakaioBus } from "@makaio/framework/bus";
4
4
  import * as _$_makaio_contracts0 from "@makaio/framework/contracts";
5
- import { IWorkflowRunner, IWorkflowTriggerTypeRegistry, LoopGateHandler, MakaioNodeExtension, StationHandler, StepRunnerBusAuth, StepRunnerPlatformDefaults, WorkerMaterializationSpec, WorkflowDefinition, WorkflowExecution, WorkflowRunContext, WorkflowRunResult } from "@makaio/framework/contracts";
5
+ import { IWorkflowRunner, LoopGateHandler, MakaioNodeExtension, StationHandler, StepRunnerBusAuth, StepRunnerPlatformDefaults, WorkerMaterializationSpec, WorkflowDefinition, WorkflowExecution, WorkflowRunContext, WorkflowRunResult } from "@makaio/framework/contracts";
6
6
  import { BaseService } from "@makaio/framework/service-base";
7
7
  import { MakaioDatabase } from "@makaio/framework/storage/drizzle";
8
+ import { AutomationTriggerBindingRuntime } from "@makaio/framework/services/automation-trigger";
8
9
 
9
10
  //#region subsystems/workflow-engine/src/storage/handler.d.ts
10
11
  /**
@@ -413,7 +414,6 @@ declare class WorkflowExecutor extends BaseService {
413
414
  private readonly workflowRunner?;
414
415
  private readonly executionAttemptAuthority?;
415
416
  private readonly materializationSpecResolvers;
416
- private triggerTypeRegistry?;
417
417
  /**
418
418
  * Create a new workflow executor.
419
419
  * @param bus - The message bus for communication
@@ -422,19 +422,6 @@ declare class WorkflowExecutor extends BaseService {
422
422
  * @param executionAttemptAuthority - Optional Authority for WorkerNode dispatch runners
423
423
  */
424
424
  constructor(bus: IMakaioBus, config?: Partial<ExecutorConfig>, workflowRunner?: IWorkflowRunner, executionAttemptAuthority?: ExecutionAttemptAuthority);
425
- /**
426
- * Set the trigger type registry for listTriggerTypes support.
427
- * @param registry - Trigger type registry instance
428
- */
429
- setTriggerTypeRegistry(registry: IWorkflowTriggerTypeRegistry): void;
430
- /**
431
- * Retrieve the registry set via {@link setTriggerTypeRegistry}.
432
- *
433
- * The composition root calls this after boot to wire
434
- * `setWorkflowTriggerTypeRegistry` from `@makaio/kernel`.
435
- * @returns The trigger type registry, or `undefined` if not yet set.
436
- */
437
- getTriggerTypeRegistry(): IWorkflowTriggerTypeRegistry | undefined;
438
425
  /**
439
426
  * Register a host resolver used to freeze workspace materialization before a
440
427
  * path-backed execution is persisted.
@@ -580,87 +567,241 @@ declare class WorkflowExecutor extends BaseService {
580
567
  private dispatchPausedExecutionResume;
581
568
  }
582
569
  //#endregion
583
- //#region subsystems/workflow-engine/src/cron-trigger-evaluator.d.ts
570
+ //#region subsystems/workflow-engine/src/workflow-trigger-reconciler.d.ts
584
571
  /**
585
- * Schedules and fires cron triggers for workflows on `'main-dev-machine'` role machines.
572
+ * Keeps declarative workflow triggers subscribed to the automation trigger
573
+ * binding runtime.
586
574
  *
587
- * On `init`, loads all workflow definitions with `cron` triggers and schedules
588
- * them via croner. Subscribes to workflow CRUD events to keep the schedule
589
- * index live.
575
+ * The reconciler is the workflow engine's only consumer of automation triggers.
576
+ * It owns no trigger sources and no timers: every persisted
577
+ * {@link WorkflowAutomationTriggerBinding} becomes one listener on the shared
578
+ * runtime, and the runtime decides how many live sources that requires.
590
579
  *
591
- * Each cron trigger fires `WorkflowSubjects.start` with the workflow ID and
592
- * a `triggerPayload` containing the scheduled fire time.
580
+ * Four invariants define it:
593
581
  *
594
- * ## Role partitioning
595
- *
596
- * Only machines with role `'main-dev-machine'` should run this evaluator.
597
- * Server-role machines rely on the relay-side `CronEvaluator` for routing.
598
- * @example
599
- * ```typescript
600
- * if (machineRole === 'main-dev-machine') {
601
- * const evaluator = new CronTriggerEvaluator(bus);
602
- * await evaluator.init();
603
- * // ...on shutdown:
604
- * evaluator.destroy();
605
- * }
606
- * ```
582
+ * 1. **Storage is the source of truth.** Reconciliation always reads the
583
+ * persisted definitions. Workflow CRUD events and
584
+ * `automation-triggers.changed` events are refresh *signals*, never the state
585
+ * itself, which is why an extension re-enable restores a binding with no
586
+ * workflow CRUD event of its own.
587
+ * 2. **Stable consumer keys.** A consumer is identified by `workflowId` plus the
588
+ * binding's index in the definition's `triggers` array, so a refresh replaces
589
+ * exactly the consumer it belongs to and leaves that workflow's other
590
+ * bindings untouched.
591
+ * 3. **Acquire, designate, release.** Every refresh of a live consumer subscribes
592
+ * the replacement **before** releasing the previous handle, so a source both
593
+ * bindings share is never torn down and re-activated, and a failed acquisition
594
+ * cannot leave a gap. Re-acquiring an unchanged binding is deliberately not
595
+ * special-cased: canonical sharing means it joins the activation it already
596
+ * holds, so the refresh is churn-free by construction. Because the overlap
597
+ * leaves two listeners of the same consumer briefly attached, exactly one of
598
+ * them is *designated* — see {@link ConsumerRecord} — so one event still
599
+ * produces exactly one workflow start. Which one is designated during the
600
+ * overlap follows from whether the replacement resolves to the activation its
601
+ * predecessor's handle already holds, not from timing: a replacement that
602
+ * shares its predecessor's activation
603
+ * stays undesignated until it is live (the outgoing listener is already on
604
+ * that activation and covers every event), while a replacement targeting a
605
+ * *different* activation is designated **before** `subscribe` — its new source
606
+ * may emit from inside `activate`, and the outgoing listener cannot cover an
607
+ * event of an activation it is not attached to. Either way designation moves
608
+ * strictly **before** the previous handle is released, so the release — whose
609
+ * extension-owned cleanup may take arbitrarily long — can never leave a window
610
+ * in which the outgoing listener is already detached while the incoming one is
611
+ * not yet allowed to start. One residual window remains, and is theoretical
612
+ * rather than reachable through storage: for a *changed* binding, events the
613
+ * outgoing source emits between the early designation and the completed
614
+ * acquisition are dropped. They belong to the binding the definition just
615
+ * replaced, so dropping them is the intended reading of a changed binding; if
616
+ * the acquisition then fails, `keep-last-good` restores that designation and
617
+ * the outgoing listener resumes starting the workflow.
618
+ * Acquiring the replacement through {@link AutomationTriggerBindingRuntime}'s
619
+ * `subscribe`/`detach` pair rather than a single combined swap is what makes
620
+ * that ordering expressible, and it is also what lets a refresh survive a
621
+ * runtime restart: the previous handle is released against the runtime that
622
+ * issued it, while the replacement is acquired from the one resolved now.
623
+ * 4. **Availability is probed, not tracked.** The reconciler keeps no record of
624
+ * which trigger kinds are currently registered. A kind that has gone away
625
+ * surfaces as a failed acquisition during the refresh that the registry's
626
+ * `changed` event triggers, and the consumer is dropped there — which is also
627
+ * what guarantees no executable closure survives a deregistration. Probing is
628
+ * scoped by the exact old/new kind union the event carries: only bindings
629
+ * whose registration may have changed are re-acquired. Owner prefixes are
630
+ * deliberately not used as identity because owner names may overlap.
607
631
  */
608
- declare class CronTriggerEvaluator {
632
+ declare class WorkflowTriggerReconciler {
609
633
  private readonly bus;
634
+ private readonly resolveRuntime;
635
+ /** Live consumers: workflow id → trigger index → subscription record. */
636
+ private readonly consumers;
637
+ /** Bus subscription cleanups registered by {@link init}. */
610
638
  private readonly cleanupFns;
639
+ /** Records whether a completed initialization is currently live. */
611
640
  private initialized;
641
+ /** Shared in-flight initialization, cleared after success or rollback. */
642
+ private initialization;
612
643
  /**
613
- * Active cron jobs keyed by `{workflowId}:{triggerIndex}`.
644
+ * FIFO reconciliation lane.
645
+ *
646
+ * Refresh signals arrive concurrently — a CRUD event can land while a registry
647
+ * change is still acquiring — and reconciliation is asynchronous because
648
+ * activation is. Serializing every mutation keeps the consumer index and the
649
+ * runtime's reference counts consistent.
614
650
  */
615
- private readonly jobs;
651
+ private readonly lane;
616
652
  /**
617
- * @param bus - The shared bus instance
653
+ * Registry `changed` events whose reconciliation is still pending.
654
+ *
655
+ * A registry change identifies the exact union of one owner's old and new
656
+ * batches, and a contributor replay emits one such event per owner within a
657
+ * single turn. Collecting the events here and flushing on a trailing microtask
658
+ * turns that burst into one pass over the union of their kinds — one storage
659
+ * read instead of one per event. Retaining the complete payload also keeps the
660
+ * owner and revision visible in reconciliation diagnostics.
661
+ *
662
+ * Non-empty exactly while a flush is scheduled, which is also what lets
663
+ * {@link teardown} cancel a pending flush by clearing it.
618
664
  */
619
- constructor(bus: IMakaioBus);
665
+ private readonly pendingChanges;
620
666
  /**
621
- * Initialize the evaluator.
667
+ * @param bus - Shared runtime bus.
668
+ * @param resolveRuntime - Resolves the currently live binding runtime.
669
+ * Consulted per reconciliation rather than captured, so a runtime that
670
+ * restarts is picked up by the next refresh instead of leaving the engine
671
+ * holding a dead reference.
672
+ */
673
+ constructor(bus: IMakaioBus, resolveRuntime: () => AutomationTriggerBindingRuntime | undefined);
674
+ /**
675
+ * Subscribes to refresh signals and reconciles the persisted definitions.
622
676
  *
623
- * Idempotent: calling `init()` on an already-initialized evaluator is a no-op.
677
+ * Idempotent across concurrent and completed calls. A failure while loading
678
+ * the persisted definitions rolls back the signal subscriptions so a later
679
+ * attempt can initialize from a clean state.
680
+ * @returns Resolves once the initial reconciliation has settled.
681
+ * @throws When the persisted definitions cannot be loaded.
624
682
  */
625
683
  init(): Promise<void>;
626
684
  /**
627
- * Destroy the evaluator, stopping all cron jobs and removing all subscriptions.
685
+ * Clears the matching completed initialization attempt.
686
+ * @param initialization - Initialization attempt whose completion is being cleared.
687
+ */
688
+ private clearInitialization;
689
+ /**
690
+ * Performs one initialization attempt after {@link init} has made it exclusive.
691
+ * @returns Resolves once the initial reconciliation has settled.
692
+ * @throws When the persisted definitions cannot be loaded.
693
+ */
694
+ private initialize;
695
+ /**
696
+ * Detaches every consumer subscription and stops listening for refreshes.
697
+ *
698
+ * Idempotent, and safe to call on a reconciler that never initialized.
699
+ * @returns Resolves once every detach has settled.
700
+ */
701
+ destroy(): Promise<void>;
702
+ /**
703
+ * Number of live consumer subscriptions across all workflows.
628
704
  *
629
- * Idempotent: calling `destroy()` on a non-initialized evaluator is a no-op.
705
+ * Consumer count, not activation count: two workflows sharing one source
706
+ * report two consumers.
707
+ * @returns Count of live consumers.
630
708
  */
631
- destroy(): void;
632
- activeJobCount(): number;
709
+ activeConsumerCount(): number;
633
710
  /**
634
- * Load all existing workflow definitions and schedule their cron triggers.
711
+ * Runs one refresh signal detached from the bus handler that raised it.
712
+ *
713
+ * Bus handlers must not be delayed by reconciliation, and a reconciliation that
714
+ * fails must not surface as a failure of the emitter that signalled it — so the
715
+ * work is detached and its failure logged here, in the one place every signal
716
+ * passes through.
717
+ * @param describe - What was being reconciled, used in the failure log.
718
+ * @param operation - Reconciliation to run.
719
+ */
720
+ private onSignal;
721
+ /**
722
+ * Records one registry `changed` event and schedules the coalesced pass.
723
+ *
724
+ * The flush runs on a trailing microtask, so every kind named within the turn
725
+ * that raised the first event is reconciled by one pass — see
726
+ * {@link pendingChanges}.
727
+ * @param change - Exact changed-kind scope plus owner/revision diagnostics.
728
+ */
729
+ private scheduleRegistryReconcile;
730
+ /**
731
+ * Reconciles the persisted workflow definitions and forgets consumers whose
732
+ * workflow no longer exists.
733
+ * @param onFailure - Policy applied when a consumer cannot be acquired.
734
+ * @param kinds - When given, restricts reconciliation to the exact trigger
735
+ * kinds whose registration may have changed; a workflow declaring none of
736
+ * them is left untouched. Omitted at startup, where every binding still has
737
+ * to be acquired.
738
+ * @returns Resolves once every workflow in scope has been reconciled.
739
+ * @throws When the persisted definitions cannot be listed.
635
740
  */
636
- private loadExistingTriggers;
741
+ private reconcileStored;
637
742
  /**
638
- * Schedule all `cron` triggers found in a workflow definition.
639
- * @param workflow - Workflow definition to schedule
743
+ * Reconciles one workflow against storage after a CRUD event named it.
744
+ *
745
+ * The event supplies identity only. The definition is re-read inside the lane,
746
+ * so what is applied is the workflow as it stands when the refresh actually
747
+ * runs — which is also why a deletion needs no separate signal path: a workflow
748
+ * storage no longer holds is simply forgotten.
749
+ * @param workflowId - Workflow named by the event.
750
+ * @returns Resolves once the refresh has settled.
751
+ * @throws When the definition cannot be read.
640
752
  */
641
- private scheduleWorkflow;
753
+ private refreshDefinition;
642
754
  /**
643
- * Stop and remove all cron jobs for a given workflow.
644
- * @param workflowId - Workflow identifier to unschedule
755
+ * Brings one workflow's consumers in line with its definition. Lane-internal.
756
+ * @param workflow - Definition to apply.
757
+ * @param onFailure - Policy applied when a consumer cannot be acquired.
758
+ * @param kinds - When given, only consumers whose binding has an exact kind in
759
+ * this changed set are refreshed. Bindings outside the scope keep the
760
+ * subscriptions they hold — nothing about them changed.
761
+ * @returns Resolves once every consumer of this workflow in scope has settled.
645
762
  */
646
- private unscheduleWorkflow;
763
+ private applyDefinitionWithinLane;
647
764
  /**
648
- * Stop and remove a single cron job by key.
649
- * @param key - Job key (`{workflowId}:{triggerIndex}`)
765
+ * Acquires or replaces one consumer subscription. Lane-internal.
766
+ * @param runtime - Live binding runtime.
767
+ * @param workflowId - Workflow owning this consumer.
768
+ * @param triggerIndex - Position of the binding in the definition.
769
+ * @param next - Prepared consumer record to install.
770
+ * @param consumers - Mutable consumer index of this workflow.
771
+ * @param onFailure - Policy applied when the acquisition fails.
772
+ * @returns Resolves once the consumer has settled.
650
773
  */
651
- private stopJob;
774
+ private refreshConsumerWithinLane;
652
775
  /**
653
- * Stop all active cron jobs and clear the jobs map.
776
+ * Releases every consumer of one workflow. Lane-internal.
777
+ * @param workflowId - Workflow to forget.
778
+ * @returns Resolves once every detach has settled.
654
779
  */
655
- private stopAllJobs;
780
+ private forgetWorkflowWithinLane;
656
781
  /**
657
- * Fire a cron trigger by requesting workflow start.
782
+ * Builds the listener that turns one trigger event into a workflow start.
783
+ *
784
+ * The listener first checks that its own record is still the designated one for
785
+ * this consumer key, so a listener that has been superseded or dropped can
786
+ * neither double-start a workflow during a refresh overlap nor start one after
787
+ * its trigger type went away. Consumer-owned filters run next, then the payload
788
+ * is projected onto the `triggerPayload` contract.
658
789
  *
659
- * Errors are logged but not propagated — cron jobs are fire-and-forget.
660
- * @param workflowId - Workflow to start
661
- * @param triggerIndex - Index of the trigger that fired
790
+ * Every failure is logged against this consumer's identity and swallowed: a
791
+ * listener rejection would otherwise surface as a failure of the unrelated
792
+ * source that emitted the event.
793
+ * @param workflowId - Workflow to start on a match.
794
+ * @param triggerIndex - Consumer position, used in diagnostics.
795
+ * @param record - Consumer record this listener belongs to.
796
+ * @returns Listener to attach to the binding runtime.
797
+ */
798
+ private createListener;
799
+ /**
800
+ * Removes signal subscriptions, cancels a pending coalesced pass, and releases
801
+ * every consumer.
802
+ * @returns Resolves once every detach has settled.
662
803
  */
663
- private fireTrigger;
804
+ private teardown;
664
805
  }
665
806
  //#endregion
666
807
  //#region subsystems/workflow-engine/src/workflow-engine-service.d.ts
@@ -707,17 +848,29 @@ interface WorkflowEngineServiceOptions {
707
848
  executionAttemptAuthority?: ExecutionAttemptAuthority;
708
849
  /** Host-owned resolvers that create portable specs for path-backed starts. */
709
850
  workflowMaterializationSpecResolvers?: readonly WorkflowMaterializationSpecResolver[];
851
+ /**
852
+ * Resolves the host-owned automation trigger binding runtime.
853
+ *
854
+ * Declarative workflow triggers are consumer subscriptions on that runtime, so
855
+ * this is the seam through which the engine reaches trigger sources it does not
856
+ * own. Resolved per reconciliation rather than captured, so a runtime that
857
+ * restarts is picked up by the next refresh.
858
+ *
859
+ * When omitted — or when the resolver returns `undefined` — the engine runs
860
+ * without declarative triggers: direct `WorkflowSubjects.start` requests still
861
+ * work, which is the invocation-only mode a workflow with `triggers: []` uses.
862
+ */
863
+ automationTriggerBindingRuntime?: () => AutomationTriggerBindingRuntime | undefined;
710
864
  }
711
865
  /**
712
866
  * Workflow engine package service.
713
867
  *
714
- * Owns the boot lifecycle for the workflow executor and trigger evaluators so
868
+ * Owns the boot lifecycle for the workflow executor and the trigger reconciler so
715
869
  * stored triggers become active during normal runtime package startup.
716
870
  */
717
871
  declare class WorkflowEngineService extends BaseService {
718
872
  private readonly workflowExecutor;
719
- private readonly busEventTriggerEvaluator;
720
- private readonly cronTriggerEvaluator;
873
+ private readonly triggerReconcilerInstance;
721
874
  private readonly attemptAuthority;
722
875
  private readonly workspaceRootResolvers;
723
876
  /**
@@ -757,20 +910,10 @@ declare class WorkflowEngineService extends BaseService {
757
910
  */
758
911
  acceptAuthorityRunnerResult(executionId: string, result: Parameters<WorkflowExecutor['acceptAuthorityRunnerResult']>[1]): ReturnType<WorkflowExecutor['acceptAuthorityRunnerResult']>;
759
912
  /**
760
- * Cron evaluator owned by this package service.
761
- * @returns Cron trigger evaluator instance.
913
+ * Declarative trigger reconciler owned by this package service.
914
+ * @returns Workflow trigger reconciler instance.
762
915
  */
763
- get cronTriggers(): CronTriggerEvaluator;
764
- /**
765
- * Set the trigger type registry used by executor request handlers.
766
- * @param registry - Trigger type registry instance.
767
- */
768
- setTriggerTypeRegistry(registry: IWorkflowTriggerTypeRegistry): void;
769
- /**
770
- * Retrieve the executor trigger type registry.
771
- * @returns Trigger type registry, or `undefined` when none is set.
772
- */
773
- getTriggerTypeRegistry(): IWorkflowTriggerTypeRegistry | undefined;
916
+ get triggerReconciler(): WorkflowTriggerReconciler;
774
917
  /**
775
918
  * Register a host resolver used to freeze a path-backed workflow's workspace
776
919
  * reference before the durable run context is written.
@@ -791,7 +934,7 @@ declare class WorkflowEngineService extends BaseService {
791
934
  */
792
935
  resolveWorkspaceRoot(workspaceId: string): Promise<string | undefined>;
793
936
  /**
794
- * Initialize executor handlers before trigger evaluators can fire starts.
937
+ * Initialize executor handlers before the trigger reconciler can fire starts.
795
938
  * @returns Promise that resolves once all child services are initialized.
796
939
  */
797
940
  protected onInit(): Promise<void>;
@@ -812,6 +955,13 @@ declare const WorkflowEngineToken: _$_makaio_contracts0.ExtensionToken<WorkflowE
812
955
  * service, wires Drizzle storage handlers, and forwards the provided options
813
956
  * to the executor so that composition roots can inject a workflow-level runner
814
957
  * or executor configuration (e.g. busUrl, busAuth, platformDefaults).
958
+ *
959
+ * Declarative triggers are reached through the automation trigger binding
960
+ * runtime, resolved lazily from the extension context. The dependency on that
961
+ * runtime is declared **optional**: it orders startup so the runtime is present
962
+ * by the time the engine reconciles stored triggers, without making the runtime
963
+ * undisableable while the engine is active. A host that runs without it keeps
964
+ * invocation-mode workflow starts.
815
965
  * @param options - Optional workflow runner and executor config overrides.
816
966
  * @returns A `MakaioNodeExtension` manifest for the workflow engine subsystem.
817
967
  */
@@ -824,4 +974,4 @@ declare function createWorkflowEnginePackage(options?: WorkflowEngineServiceOpti
824
974
  */
825
975
  declare const workflowEnginePackage: MakaioNodeExtension<IMakaioBus>;
826
976
  //#endregion
827
- export { WorkflowEngineServiceOptions as a, WorkflowMaterializationSpecResolution as c, registerDrizzleWorkflowStorage as d, WorkflowEngineService as i, WorkflowMaterializationSpecResolver as l, createWorkflowEnginePackage as n, WorkflowExecutor as o, workflowEnginePackage as r, ExecutionAttemptAuthority as s, WorkflowEngineToken as t, WorkflowWorkspaceRootResolver as u };
977
+ export { WorkflowEngineServiceOptions as a, ExecutionAttemptAuthority as c, WorkflowWorkspaceRootResolver as d, registerDrizzleWorkflowStorage as f, WorkflowEngineService as i, WorkflowMaterializationSpecResolution as l, createWorkflowEnginePackage as n, WorkflowTriggerReconciler as o, workflowEnginePackage as r, WorkflowExecutor as s, WorkflowEngineToken as t, WorkflowMaterializationSpecResolver as u };
@@ -0,0 +1 @@
1
+ import{z as e}from"zod";import{SerialLane as t,canonicalStringify as n,deepFreeze as r}from"@makaio/framework/utils";import{createNamespaceWildcardSubject as i,splitSubjectKey as a}from"@makaio/framework/core";import{matchesSubscription as o}from"@makaio/framework/bus";import{AutomationTriggerLocalNameSchema as s,AutomationTriggerSubjects as c,BUS_EVENT_AUTOMATION_TRIGGER_KIND as l,CRON_AUTOMATION_TRIGGER_KIND as u,CronAutomationTriggerParamsSchema as d,JsonRecordSchema as f,JsonValueSchema as p,createAutomationTriggerDescriptor as m,defineAutomationTrigger as h,dep as g,extensionToken as _,toAutomationTriggerType as v}from"@makaio/framework/contracts";import{BaseService as ee}from"@makaio/framework/service-base";var y=class extends ee{typesByOwner=new Map;typesByKind=new Map;revision=0;mutations=new t;catalog;constructor(e){super(e)}onInit(){this.registerHandler(c.list,e=>{e.setResult({triggers:[...this.list()]})})}onDestroy(){this.typesByOwner=new Map,this.typesByKind=new Map}register(e,t){return this.mutations.run(()=>this.registerWithinLane(e,t))}async registerWithinLane(e,t){let n=this.validateBatch(e,t),r=this.typesByOwner.get(e);if(n.length===0&&r===void 0)return;let i=new Map(this.typesByOwner);n.length===0?i.delete(e):i.set(e,n),this.typesByOwner=i,this.typesByKind=b(this.typesByKind,r??[],n),this.revision+=1;let a=n.length>0?`registered`:`deregistered`,o=Array.from(new Set([...(r??[]).map(({type:e})=>e.kind),...n.map(({type:e})=>e.kind)]));await this.bus.emit(c.changed,{owner:e,revision:this.revision,kinds:o,reason:a}).catch(e=>{console.error(`[AutomationTriggerRegistry] Failed to emit automation-triggers.changed:`,e)})}deregister(e){return this.mutations.run(()=>this.registerWithinLane(e,[]))}resolveRegistration(e){let t=this.typesByKind.get(e);if(t!==void 0)return{owner:t.owner,type:t.type}}list(){let e=this.typesByKind;if(this.catalog?.source===e)return this.catalog.value;let t=Object.freeze(Array.from(e.values(),({descriptor:e})=>e));return this.catalog={source:e,value:t},t}validateBatch(e,t){let n=`${e}.`,i=new Set,a=new Set(this.typesByOwner.get(e)?.map(e=>e.type.kind)),o=[];for(let c of t){let t=c.kind.startsWith(n)?c.kind.slice(n.length):void 0;if(t===void 0||!s.safeParse(t).success)throw Error(`Automation trigger kind '${c.kind}' must be namespaced by owner '${n}'`);if(i.has(c.kind))throw Error(`Duplicate automation trigger kind '${c.kind}' in batch from '${e}'`);if(this.typesByKind.has(c.kind)&&!a.has(c.kind))throw Error(`Automation trigger kind '${c.kind}' is already registered; owner '${e}' cannot claim it`);i.add(c.kind);let l={kind:c.kind,label:c.label,description:c.description,categories:[...c.categories],paramsSchema:c.paramsSchema,eventSchema:c.eventSchema,activate:c.activate},u=r(m(Object.isFrozen(c)?c:l));o.push({owner:e,type:l,descriptor:u})}return o}};function b(e,t,n){let r=new Map(e);for(let e of t)r.delete(e.type.kind);for(let e of n)r.set(e.type.kind,e);return r}function x(e){return JSON.parse(n(e))}function S(e,t){return`${e}:${n(t)}`}const C=`[AutomationTriggerBindingRuntime]`;var w=class{resolver;bindings=new Map;records=new WeakMap;lane=new t;subscriptionCounter=0;closed=!1;constructor(e){this.resolver=e}async subscribe(e,t){let n=this.prepareBinding(e);if(n===void 0)throw Error(`Automation trigger kind '${e.kind}' is not registered`);return n.subscribe(t)}prepareBinding(e){let t=this.resolver.resolveRegistration(e.kind);if(t===void 0)return;let n=T(t.type,e),r={kind:e.kind,owner:t.owner,type:t.type,params:n,bindingKey:S(e.kind,n)};return{bindingKey:r.bindingKey,workflowCompatible:m(t.type).workflowCompatible,subscribe:e=>this.subscribePrepared(r,e)}}async subscribePrepared(e,t){let{entry:n,subscriptionId:r,retired:i}=await this.lane.run(()=>this.admitWithinLane(e,t));i!==void 0&&await this.runCleanup(i);try{await n.activated}catch(e){throw await this.lane.run(async()=>{this.retireWithinLane(n)}),e}return this.lane.run(async()=>{if(this.bindings.get(n.bindingKey)!==n||!n.listeners.has(r))throw Error(`Automation trigger acquisition for '${n.bindingKey}' was retired before it completed`);return this.issueHandle({bindingKey:n.bindingKey,subscriptionId:r})})}resolveBindingKey(e){return this.prepareBinding(e)?.bindingKey}stopOwner(e){return this.retireMatching(t=>t.owner===e)}stopKind(e){return this.retireMatching(t=>t.kind===e)}destroy(){return this.close()}close(){return this.retireMatching(()=>!0,()=>{this.closed=!0})}async admitWithinLane(e,t){if(this.closed)throw Error(`Automation trigger binding runtime is closed; cannot activate '${e.kind}'`);let n=this.resolver.resolveRegistration(e.kind);if(n===void 0)throw Error(`Automation trigger kind '${e.kind}' is not registered`);if(n.owner!==e.owner||n.type!==e.type)throw Error(`Automation trigger registration for '${e.kind}' changed after binding preparation`);this.subscriptionCounter+=1;let r=`s${this.subscriptionCounter}`,i=this.bindings.get(e.bindingKey);if(i?.type===n.type)return i.listeners.set(r,t),{entry:i,subscriptionId:r};let a=i===void 0?void 0:this.retireWithinLane(i),o=Promise.withResolvers(),s={bindingKey:e.bindingKey,kind:e.kind,owner:n.owner,type:n.type,controller:new AbortController,listeners:new Map([[r,t]]),activated:o.promise};return this.bindings.set(e.bindingKey,s),s.activated.catch(()=>void 0),this.startActivation(s,n.type,e.params,o),{entry:s,subscriptionId:r,...a===void 0?{}:{retired:a}}}async startActivation(e,t,n,r){try{r.resolve(await t.activate(this.createContext(e),n))}catch(e){r.reject(e)}}async release(e){let t=await this.lane.run(()=>this.releaseWithinLane(e));t!==void 0&&await this.runCleanup(t)}async releaseWithinLane(e){let t=this.records.get(e);if(t===void 0)throw Error(`${C} subscription handle was not issued by this runtime`);let n=this.bindings.get(t.bindingKey);if(n!==void 0&&n.listeners.delete(t.subscriptionId)&&!(n.listeners.size>0))return this.retireWithinLane(n)}async retireMatching(e,t){let n=await this.lane.run(async()=>{t?.();let n=[];for(let t of Array.from(this.bindings.values())){if(!e(t))continue;let r=this.retireWithinLane(t);r!==void 0&&n.push(r)}return n});await Promise.all(n.map(e=>this.runCleanup(e)))}retireWithinLane(e){if(this.bindings.get(e.bindingKey)===e)return this.bindings.delete(e.bindingKey),e.listeners.clear(),e.controller.abort(),e}async runCleanup(e){let t;try{t=await e.activated}catch{return}try{await t()}catch(t){console.error(`${C} cleanup failed for '${e.bindingKey}':`,t)}}issueHandle(e){let t={bindingKey:e.bindingKey,detach:()=>this.release(t)};return this.records.set(t,e),t}createContext(e){return{bindingKey:e.bindingKey,signal:e.controller.signal,emit:(t,n)=>this.dispatch(e,t,n?.correlationId)}}async dispatch(e,t,n){if(this.bindings.get(e.bindingKey)!==e)return;let r;try{let n=e.type.eventSchema.parse(t);r=e.type.eventSchema===p||e.type.eventSchema===f?n:p.parse(n)}catch(t){throw console.error(`${C} rejected invalid payload from '${e.kind}':`,t),t}let i={kind:e.kind,payload:r,observedAt:Date.now(),...n===void 0?{}:{correlationId:n}},a=Array.from(e.listeners.values()),o=await Promise.allSettled(a.map(async e=>e(i)));for(let t of o)t.status===`rejected`&&console.error(`${C} listener failed for '${e.kind}':`,t.reason)}};function T(e,t){let n=e.paramsSchema.parse(t.params);return x(f.parse(n))}const E=_(`automation-trigger-registry`),D=_(`automation-trigger-runtime`),te={name:E.name,displayName:`Automation Trigger Registry`,version:`0.1.0`,critical:!0,create:e=>new y(e.bus)},O={name:D.name,displayName:`Automation Trigger Binding Runtime`,version:`0.1.0`,critical:!0,create:e=>new w({resolveRegistration:t=>e.getService(E)?.resolveRegistration(t)})};function k(e){return Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)}function A(e,t){return e.y===t.y&&e.m===t.m&&e.d===t.d&&e.h===t.h&&e.i===t.i&&e.s===t.s}function j(e,t){let n=new Date(Date.parse(e));if(isNaN(n))throw Error(`Invalid ISO8601 passed to timezone parser.`);let r=e.substring(9);return r.includes(`Z`)||r.includes(`+`)||r.includes(`-`)?F(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):F(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}function M(e,t,n){return N(j(e,t),n)}function N(e,t){let n=new Date(k(e)),r=P(n,e.tz),i=k(e)-k(r),a=new Date(n.getTime()+i),o=P(a,e.tz);if(A(o,e)){let t=new Date(a.getTime()-36e5);return A(P(t,e.tz),e)?t:a}let s=new Date(a.getTime()+k(e)-k(o));if(A(P(s,e.tz),e))return s;if(t)throw Error(`Invalid date passed to fromTZ()`);return a.getTime()>s.getTime()?a:s}function P(e,t){let n,r;try{n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`,hour12:!1}),r=n.formatToParts(e)}catch(e){let n=e instanceof Error?e.message:String(e);throw RangeError(`toTZ: Invalid timezone '${t}' or date. Please provide a valid IANA timezone (e.g., 'America/New_York', 'Europe/Stockholm'). Original error: ${n}`)}let i={year:0,month:0,day:0,hour:0,minute:0,second:0};for(let e of r)(e.type===`year`||e.type===`month`||e.type===`day`||e.type===`hour`||e.type===`minute`||e.type===`second`)&&(i[e.type]=parseInt(e.value,10));if(isNaN(i.year)||isNaN(i.month)||isNaN(i.day)||isNaN(i.hour)||isNaN(i.minute)||isNaN(i.second))throw Error(`toTZ: Failed to parse all date components from timezone '${t}'. This may indicate an invalid date or timezone configuration. Parsed components: ${JSON.stringify(i)}`);return i.hour===24&&(i.hour=0),{y:i.year,m:i.month,d:i.day,h:i.hour,i:i.minute,s:i.second,tz:t}}function F(e,t,n,r,i,a,o){return{y:e,m:t,d:n,h:r,i,s:a,tz:o}}var I=[1,2,4,8,16],L=class{pattern;timezone;mode;alternativeWeekdays;sloppyRanges;second;minute;hour;day;month;dayOfWeek;year;lastDayOfMonth;lastWeekday;nearestWeekdays;starDOM;starDOW;starYear;useAndLogic;constructor(e,t,n){this.pattern=e,this.timezone=t,this.mode=n?.mode??`auto`,this.alternativeWeekdays=n?.alternativeWeekdays??!1,this.sloppyRanges=n?.sloppyRanges??!1,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.year=Array(1e4).fill(0),this.lastDayOfMonth=!1,this.lastWeekday=!1,this.nearestWeekdays=Array(31).fill(0),this.starDOM=!1,this.starDOW=!1,this.starYear=!1,this.useAndLogic=!1,this.parse()}parse(){if(!(typeof this.pattern==`string`||this.pattern instanceof String))throw TypeError(`CronPattern: Pattern has to be of type string.`);this.pattern.indexOf(`@`)>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let e=this.pattern.match(/\S+/g)||[``],t=e.length;if(e.length<5||e.length>7)throw TypeError(`CronPattern: invalid configuration format ('`+this.pattern+`'), exactly five, six, or seven space separated parts are required.`);if(this.mode!==`auto`){let e;switch(this.mode){case`5-part`:e=5;break;case`6-part`:e=6;break;case`7-part`:e=7;break;case`5-or-6-parts`:e=[5,6];break;case`6-or-7-parts`:e=[6,7];break;default:e=0}if(!(Array.isArray(e)?e.includes(t):t===e)){let n=Array.isArray(e)?e.join(` or `):e.toString();throw TypeError(`CronPattern: mode '${this.mode}' requires exactly ${n} parts, but pattern '${this.pattern}' has ${t} parts.`)}}if(e.length===5&&e.unshift(`0`),e.length===6&&e.push(`*`),e[3].toUpperCase()===`LW`?(this.lastWeekday=!0,e[3]=``):e[3].toUpperCase().indexOf(`L`)>=0&&(e[3]=e[3].replace(/L/gi,``),this.lastDayOfMonth=!0),e[3]==`*`&&(this.starDOM=!0),e[6]==`*`&&(this.starYear=!0),e[4].length>=3&&(e[4]=this.replaceAlphaMonths(e[4])),e[5].length>=3&&(e[5]=this.alternativeWeekdays?this.replaceAlphaDaysQuartz(e[5]):this.replaceAlphaDays(e[5])),e[5].startsWith(`+`)&&(this.useAndLogic=!0,e[5]=e[5].substring(1),e[5]===``))throw TypeError(`CronPattern: Day-of-week field cannot be empty after '+' modifier.`);switch(e[5]==`*`&&(this.starDOW=!0),this.pattern.indexOf(`?`)>=0&&(e[0]=e[0].replace(/\?/g,`*`),e[1]=e[1].replace(/\?/g,`*`),e[2]=e[2].replace(/\?/g,`*`),e[3]=e[3].replace(/\?/g,`*`),e[4]=e[4].replace(/\?/g,`*`),e[5]=e[5].replace(/\?/g,`*`),e[6]&&=e[6].replace(/\?/g,`*`)),this.mode){case`5-part`:e[0]=`0`,e[6]=`*`;break;case`6-part`:e[6]=`*`;break;case`5-or-6-parts`:e[6]=`*`;break;case`6-or-7-parts`:break;case`7-part`:case`auto`:break}this.throwAtIllegalCharacters(e),this.partToArray(`second`,e[0],0,1),this.partToArray(`minute`,e[1],0,1),this.partToArray(`hour`,e[2],0,1),this.partToArray(`day`,e[3],-1,1),this.partToArray(`month`,e[4],-1,1);let n=this.alternativeWeekdays?-1:0;this.partToArray(`dayOfWeek`,e[5],n,63),this.partToArray(`year`,e[6],0,1),!this.alternativeWeekdays&&this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(e,t,n,r){let i=this[e],a=e===`day`&&this.lastDayOfMonth,o=e===`day`&&this.lastWeekday;if(t===``&&!a&&!o)throw TypeError(`CronPattern: configuration entry `+e+` (`+t+`) is empty, check for trailing spaces.`);if(t===`*`)return i.fill(r);let s=t.split(`,`);if(s.length>1)for(let t=0;t<s.length;t++)this.partToArray(e,s[t],n,r);else t.indexOf(`-`)!==-1&&t.indexOf(`/`)!==-1?this.handleRangeWithStepping(t,e,n,r):t.indexOf(`-`)===-1?t.indexOf(`/`)===-1?t!==``&&this.handleNumber(t,e,n,r):this.handleStepping(t,e,n,r):this.handleRange(t,e,n,r)}throwAtIllegalCharacters(e){for(let t=0;t<e.length;t++)if((t===3?/[^/*0-9,\-WwLl]+/:t===5?/[^/*0-9,\-#Ll]+/:/[^/*0-9,\-]+/).test(e[t]))throw TypeError(`CronPattern: configuration entry `+t+` (`+e[t]+`) contains illegal characters.`)}handleNumber(e,t,n,r){let i=this.extractNth(e,t),a=e.toUpperCase().includes(`W`);if(t!==`day`&&a)throw TypeError(`CronPattern: Nearest weekday modifier (W) only allowed in day-of-month.`);a&&(t=`nearestWeekdays`);let o=parseInt(i[0],10)+n;if(isNaN(o))throw TypeError(`CronPattern: `+t+` is not a number: '`+e+`'`);this.setPart(t,o,i[1]||r)}setPart(e,t,n){if(!Object.prototype.hasOwnProperty.call(this,e))throw TypeError(`CronPattern: Invalid part specified: `+e);if(e===`dayOfWeek`){if(t===7&&(t=0),t<0||t>6)throw RangeError(`CronPattern: Invalid value for dayOfWeek: `+t);this.setNthWeekdayOfMonth(t,n);return}if(e===`second`||e===`minute`){if(t<0||t>=60)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`hour`){if(t<0||t>=24)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`day`||e===`nearestWeekdays`){if(t<0||t>=31)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`month`){if(t<0||t>=12)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`year`&&(t<1||t>=1e4))throw RangeError(`CronPattern: Invalid value for `+e+`: `+t+` (supported range: 1-9999)`);this[e][t]=n}validateNotNaN(e,t){if(isNaN(e))throw TypeError(t)}validateRange(e,t,n,r,i){if(e>t)throw TypeError(`CronPattern: From value is larger than to value: '`+i+`'`);if(n!==void 0){if(n===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(n>this[r].length)throw TypeError(`CronPattern: Syntax error, steps cannot be greater than maximum value of part (`+this[r].length+`)`)}}handleRangeWithStepping(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in ranges with stepping.`);let i=this.extractNth(e,t),a=i[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(a===null)throw TypeError(`CronPattern: Syntax error, illegal range with stepping: '`+e+`'`);let[,o,s,c]=a,l=parseInt(o,10)+n,u=parseInt(s,10)+n,d=parseInt(c,10);this.validateNotNaN(l,`CronPattern: Syntax error, illegal lower range (NaN)`),this.validateNotNaN(u,`CronPattern: Syntax error, illegal upper range (NaN)`),this.validateNotNaN(d,`CronPattern: Syntax error, illegal stepping: (NaN)`),this.validateRange(l,u,d,t,e);for(let e=l;e<=u;e+=d)this.setPart(t,e,i[1]||r)}extractNth(e,t){let n=e,r;if(n.includes(`#`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: nth (#) only allowed in day-of-week field`);r=n.split(`#`)[1],n=n.split(`#`)[0]}else if(n.toUpperCase().endsWith(`L`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: L modifier only allowed in day-of-week field (use L alone for day-of-month)`);r=`L`,n=n.slice(0,-1)}return[n,r]}handleRange(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in a range.`);let i=this.extractNth(e,t),a=i[0].split(`-`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal range: '`+e+`'`);let o=parseInt(a[0],10)+n,s=parseInt(a[1],10)+n;this.validateNotNaN(o,`CronPattern: Syntax error, illegal lower range (NaN)`),this.validateNotNaN(s,`CronPattern: Syntax error, illegal upper range (NaN)`),this.validateRange(o,s,void 0,t,e);for(let e=o;e<=s;e++)this.setPart(t,e,i[1]||r)}handleStepping(e,t,n,r){if(e.toUpperCase().includes(`W`))throw TypeError(`CronPattern: Syntax error, W is not allowed in parts with stepping.`);let i=this.extractNth(e,t),a=i[0].split(`/`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal stepping: '`+e+`'`);if(this.sloppyRanges)a[0]===``&&(a[0]=`*`);else{if(a[0]===``)throw TypeError(`CronPattern: Syntax error, stepping with missing prefix ('`+e+`') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.`);if(a[0]!==`*`)throw TypeError(`CronPattern: Syntax error, stepping with numeric prefix ('`+e+`') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.`)}let o=0;a[0]!==`*`&&(o=parseInt(a[0],10)+n);let s=parseInt(a[1],10);this.validateNotNaN(s,`CronPattern: Syntax error, illegal stepping: (NaN)`),this.validateRange(0,this[t].length-1,s,t,e);for(let e=o;e<this[t].length;e+=s)this.setPart(t,e,i[1]||r)}replaceAlphaDays(e){return e.replace(/-sun/gi,`-7`).replace(/sun/gi,`0`).replace(/mon/gi,`1`).replace(/tue/gi,`2`).replace(/wed/gi,`3`).replace(/thu/gi,`4`).replace(/fri/gi,`5`).replace(/sat/gi,`6`)}replaceAlphaDaysQuartz(e){return e.replace(/sun/gi,`1`).replace(/mon/gi,`2`).replace(/tue/gi,`3`).replace(/wed/gi,`4`).replace(/thu/gi,`5`).replace(/fri/gi,`6`).replace(/sat/gi,`7`)}replaceAlphaMonths(e){return e.replace(/jan/gi,`1`).replace(/feb/gi,`2`).replace(/mar/gi,`3`).replace(/apr/gi,`4`).replace(/may/gi,`5`).replace(/jun/gi,`6`).replace(/jul/gi,`7`).replace(/aug/gi,`8`).replace(/sep/gi,`9`).replace(/oct/gi,`10`).replace(/nov/gi,`11`).replace(/dec/gi,`12`)}handleNicknames(e){let t=e.trim().toLowerCase();if(t===`@yearly`||t===`@annually`)return`0 0 1 1 *`;if(t===`@monthly`)return`0 0 1 * *`;if(t===`@weekly`)return`0 0 * * 0`;if(t===`@daily`||t===`@midnight`)return`0 0 * * *`;if(t===`@hourly`)return`0 * * * *`;if(t===`@reboot`)throw TypeError(`CronPattern: @reboot is not supported in this environment. This is an event-based trigger that requires system startup detection.`);return e}setNthWeekdayOfMonth(e,t){if(typeof t!=`number`&&t.toUpperCase()===`L`)this.dayOfWeek[e]=this.dayOfWeek[e]|32;else if(t===63)this.dayOfWeek[e]=63;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|I[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},R=[31,28,31,30,31,30,31,31,30,31,30,31],z=[[`month`,`year`,0],[`day`,`month`,-1],[`hour`,`day`,0],[`minute`,`hour`,0],[`second`,`minute`,0]],B=class e{tz;ms;second;minute;hour;day;month;year;constructor(t,n){if(this.tz=n,t&&t instanceof Date)if(!isNaN(t))this.fromDate(t);else throw TypeError(`CronDate: Invalid date passed to CronDate constructor`);else if(t==null)this.fromDate(new Date);else if(t&&typeof t==`string`)this.fromString(t);else if(t instanceof e)this.fromCronDate(t);else throw TypeError(`CronDate: Invalid type (`+typeof t+`) passed to CronDate constructor`)}getLastDayOfMonth(e,t){return t===1?new Date(Date.UTC(e,t+1,0)).getUTCDate():R[t]}getLastWeekday(e,t){let n=this.getLastDayOfMonth(e,t),r=new Date(Date.UTC(e,t,n)).getUTCDay();return r===0?n-2:r===6?n-1:n}getNearestWeekday(e,t,n){let r=this.getLastDayOfMonth(e,t);if(n>r)return-1;let i=new Date(Date.UTC(e,t,n)).getUTCDay();return i===0?n===r?n-2:n+1:i===6?n===1?n+2:n-1:n}isNthWeekdayOfMonth(e,t,n,r){let i=new Date(Date.UTC(e,t,n)).getUTCDay(),a=0;for(let r=1;r<=n;r++)new Date(Date.UTC(e,t,r)).getUTCDay()===i&&a++;if(r&63&&I[a-1]&r)return!0;if(r&32){let r=this.getLastDayOfMonth(e,t);for(let a=n+1;a<=r;a++)if(new Date(Date.UTC(e,t,a)).getUTCDay()===i)return!1;return!0}return!1}fromDate(e){if(this.tz!==void 0)if(typeof this.tz==`number`)this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes()+this.tz,this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),this.apply();else try{let t=P(e,this.tz);this.ms=e.getMilliseconds(),this.second=t.s,this.minute=t.i,this.hour=t.h,this.day=t.d,this.month=t.m-1,this.year=t.y}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`CronDate: Failed to convert date to timezone '${this.tz}'. This may happen with invalid timezone names or dates. Original error: ${t}`)}else this.ms=e.getMilliseconds(),this.second=e.getSeconds(),this.minute=e.getMinutes(),this.hour=e.getHours(),this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear()}fromCronDate(e){this.tz=e.tz,this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.ms=e.ms}apply(){if(this.month>11||this.month<0||this.day>R[this.month]||this.day<1||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let e=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes(),this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),!0}else return!1}fromString(e){if(typeof this.tz==`number`){let t=M(e);this.ms=t.getUTCMilliseconds(),this.second=t.getUTCSeconds(),this.minute=t.getUTCMinutes(),this.hour=t.getUTCHours(),this.day=t.getUTCDate(),this.month=t.getUTCMonth(),this.year=t.getUTCFullYear(),this.apply()}else return this.fromDate(M(e,this.tz))}findNext(e,t,n,r){return this._findMatch(e,t,n,r,1)}_findMatch(e,t,n,r,i){let a=this[t],o;n.lastDayOfMonth&&(o=this.getLastDayOfMonth(this.year,this.month));let s=!n.starDOW&&t==`day`?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0,c=this[t]+r,l=i===1?e=>e<n[t].length:e=>e>=0;for(let u=c;l(u);u+=i){let i=n[t][u];if(t===`day`&&!i){for(let e=0;e<n.nearestWeekdays.length;e++)if(n.nearestWeekdays[e]){let t=this.getNearestWeekday(this.year,this.month,e-r);if(t===-1)continue;if(t===u-r){i=1;break}}}if(t===`day`&&n.lastWeekday){let e=this.getLastWeekday(this.year,this.month);u-r===e&&(i=1)}if(t===`day`&&n.lastDayOfMonth&&u-r==o&&(i=1),t===`day`&&!n.starDOW){let t=n.dayOfWeek[(s+(u-r-1))%7];if(t&&t&63)t=+!!this.isNthWeekdayOfMonth(this.year,this.month,u-r,t);else if(t)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${t}`);n.useAndLogic?i&&=t:!e.domAndDow&&!n.starDOM?i||=t:i&&=t}if(i)return this[t]=u-r,a===this[t]?1:2}return 3}recurse(e,t,n){if(n===0&&!e.starYear){if(this.year>=0&&this.year<e.year.length&&e.year[this.year]===0){let t=-1;for(let n=this.year+1;n<e.year.length&&n<1e4;n++)if(e.year[n]===1){t=n;break}if(t===-1)return null;this.year=t,this.month=0,this.day=1,this.hour=0,this.minute=0,this.second=0,this.ms=0}if(this.year>=1e4)return null}let r=this.findNext(t,z[n][0],e,z[n][2]);if(r>1){let i=n+1;for(;i<z.length;)this[z[i][0]]=-z[i][2],i++;if(r===3){if(this[z[n][1]]++,this[z[n][0]]=-z[n][2],this.apply(),n===0&&!e.starYear){for(;this.year>=0&&this.year<e.year.length&&e.year[this.year]===0&&this.year<1e4;)this.year++;if(this.year>=1e4||this.year>=e.year.length)return null}return this.recurse(e,t,0)}else if(this.apply())return this.recurse(e,t,n-1)}return n+=1,n>=z.length?this:(e.starYear?this.year>=3e3:this.year>=1e4)?null:this.recurse(e,t,n)}increment(e,t,n){return this.second+=t.interval!==void 0&&t.interval>1&&n?t.interval:1,this.ms=0,this.apply(),this.recurse(e,t,0)}decrement(e,t){return this.second-=t.interval!==void 0&&t.interval>1?t.interval:1,this.ms=0,this.apply(),this.recurseBackward(e,t,0,0)}recurseBackward(e,t,n,r=0){if(r>1e4)return null;if(n===0&&!e.starYear){if(this.year>=0&&this.year<e.year.length&&e.year[this.year]===0){let t=-1;for(let n=this.year-1;n>=0;n--)if(e.year[n]===1){t=n;break}if(t===-1)return null;this.year=t,this.month=11,this.day=31,this.hour=23,this.minute=59,this.second=59,this.ms=0}if(this.year<0)return null}let i=this.findPrevious(t,z[n][0],e,z[n][2]);if(i>1){let a=n+1;for(;a<z.length;){let t=z[a][0],n=z[a][2],r=this.getMaxPatternValue(t,e,n);this[t]=r,a++}if(i===3){if(this[z[n][1]]--,n===0){let e=this.getLastDayOfMonth(this.year,this.month);this.day>e&&(this.day=e)}if(n===1)if(this.day<=0)this.day=1;else{let e=this.year,t=this.month;for(;t<0;)t+=12,e--;for(;t>11;)t-=12,e++;let n=t===1?new Date(Date.UTC(e,t+1,0)).getUTCDate():R[t];this.day>n&&(this.day=n)}this.apply();let i=z[n][0],a=z[n][2],o=this.getMaxPatternValue(i,e,a);if(i===`day`){let e=this.getLastDayOfMonth(this.year,this.month);this[i]=Math.min(o,e)}else this[i]=o;if(this.apply(),n===0){let t=z[1][2],n=this.getMaxPatternValue(`day`,e,t),r=this.getLastDayOfMonth(this.year,this.month),i=Math.min(n,r);i!==this.day&&(this.day=i,this.hour=this.getMaxPatternValue(`hour`,e,z[2][2]),this.minute=this.getMaxPatternValue(`minute`,e,z[3][2]),this.second=this.getMaxPatternValue(`second`,e,z[4][2]))}if(n===0&&!e.starYear){for(;this.year>=0&&this.year<e.year.length&&e.year[this.year]===0;)this.year--;if(this.year<0)return null}return this.recurseBackward(e,t,0,r+1)}else if(this.apply())return this.recurseBackward(e,t,n-1,r+1)}return n+=1,n>=z.length?this:this.year<0?null:this.recurseBackward(e,t,n,r+1)}getMaxPatternValue(e,t,n){if(e===`day`&&t.lastDayOfMonth||e===`day`&&!t.starDOW)return this.getLastDayOfMonth(this.year,this.month);for(let r=t[e].length-1;r>=0;r--)if(t[e][r])return r-n;return t[e].length-1-n}findPrevious(e,t,n,r){return this._findMatch(e,t,n,r,-1)}getDate(e){return e||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz==`number`?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):N(F(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}match(e,t){if(!e.starYear&&(this.year<0||this.year>=e.year.length||e.year[this.year]===0))return!1;for(let n=0;n<z.length;n++){let r=z[n][0],i=z[n][2],a=this[r];if(a+i<0||a+i>=e[r].length)return!1;let o=e[r][a+i];if(r===`day`){if(!o){for(let t=0;t<e.nearestWeekdays.length;t++)if(e.nearestWeekdays[t]){let e=this.getNearestWeekday(this.year,this.month,t-i);if(e!==-1&&e===a){o=1;break}}}if(e.lastWeekday&&a===this.getLastWeekday(this.year,this.month)&&(o=1),e.lastDayOfMonth&&a===this.getLastDayOfMonth(this.year,this.month)&&(o=1),!e.starDOW){let n=new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay(),r=e.dayOfWeek[(n+(a-1))%7];r&&r&63&&(r=+!!this.isNthWeekdayOfMonth(this.year,this.month,a,r)),e.useAndLogic?o&&=r:!t.domAndDow&&!e.starDOM?o||=r:o&&=r}}if(!o)return!1}return!0}};function ne(e){if(e===void 0&&(e={}),delete e.name,e.legacyMode!==void 0&&e.domAndDow===void 0?e.domAndDow=!e.legacyMode:e.domAndDow===void 0&&(e.domAndDow=!1),e.legacyMode=!e.domAndDow,e.paused=e.paused===void 0?!1:e.paused,e.maxRuns=e.maxRuns===void 0?1/0:e.maxRuns,e.catch=e.catch===void 0?!1:e.catch,e.interval=e.interval===void 0?0:parseInt(e.interval.toString(),10),e.utcOffset=e.utcOffset===void 0?void 0:parseInt(e.utcOffset.toString(),10),e.dayOffset=e.dayOffset===void 0?0:parseInt(e.dayOffset.toString(),10),e.unref=e.unref===void 0?!1:e.unref,e.mode=e.mode===void 0?`auto`:e.mode,e.alternativeWeekdays=e.alternativeWeekdays===void 0?!1:e.alternativeWeekdays,e.sloppyRanges=e.sloppyRanges===void 0?!1:e.sloppyRanges,![`auto`,`5-part`,`6-part`,`7-part`,`5-or-6-parts`,`6-or-7-parts`].includes(e.mode))throw Error(`CronOptions: mode must be one of 'auto', '5-part', '6-part', '7-part', '5-or-6-parts', or '6-or-7-parts'.`);if(e.startAt&&=new B(e.startAt,e.timezone),e.stopAt&&=new B(e.stopAt,e.timezone),e.interval!==null){if(isNaN(e.interval))throw Error(`CronOptions: Supplied value for interval is not a number`);if(e.interval<0)throw Error(`CronOptions: Supplied value for interval can not be negative`)}if(e.utcOffset!==void 0){if(isNaN(e.utcOffset))throw Error(`CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.`);if(e.utcOffset<-870||e.utcOffset>870)throw Error(`CronOptions: utcOffset out of bounds.`);if(e.utcOffset!==void 0&&e.timezone)throw Error(`CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.`)}if(e.unref!==!0&&e.unref!==!1)throw Error(`CronOptions: Unref should be either true, false or undefined(false).`);if(e.dayOffset!==void 0&&e.dayOffset!==0&&isNaN(e.dayOffset))throw Error(`CronOptions: Invalid value passed for dayOffset, should be a number representing days to offset.`);return e}function V(e){return Object.prototype.toString.call(e)===`[object Function]`||typeof e==`function`||e instanceof Function}function re(e){return V(e)}function H(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var U=30*1e3,W=[],G=class{name;options;_states;fn;getTz(){return this.options.timezone||this.options.utcOffset}applyDayOffset(e){if(this.options.dayOffset!==void 0&&this.options.dayOffset!==0){let t=this.options.dayOffset*24*60*60*1e3;return new Date(e.getTime()+t)}return e}constructor(e,t,n){let r,i;if(V(t))i=t;else if(typeof t==`object`)r=t;else if(t!==void 0)throw Error(`Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).`);if(V(n))i=n;else if(typeof n==`object`)r=n;else if(n!==void 0)throw Error(`Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).`);if(this.name=r?.name,this.options=ne(r),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:r?r.maxRuns:void 0,paused:r?r.paused:!1,pattern:new L(`* * * * *`,void 0,{mode:`auto`})},e&&(e instanceof Date||typeof e==`string`&&e.indexOf(`:`)>0)?this._states.once=new B(e,this.getTz()):this._states.pattern=new L(e,this.options.timezone,{mode:this.options.mode,alternativeWeekdays:this.options.alternativeWeekdays,sloppyRanges:this.options.sloppyRanges}),this.name){if(W.find(e=>e.name===this.name))throw Error(`Cron: Tried to initialize new named job '`+this.name+`', but name already taken.`);W.push(this)}return i!==void 0&&re(i)&&(this.fn=i,this.schedule()),this}nextRun(e){let t=this._next(e);return t?this.applyDayOffset(t.getDate(!1)):null}nextRuns(e,t){this._states.maxRuns!==void 0&&e>this._states.maxRuns&&(e=this._states.maxRuns);let n=t||this._states.currentRun||void 0;return this._enumerateRuns(e,n,`next`)}previousRuns(e,t){return this._enumerateRuns(e,t||void 0,`previous`)}_enumerateRuns(e,t,n){let r=[],i=t?new B(t,this.getTz()):null,a=n===`next`?this._next:this._previous;for(;e--;){let e=a.call(this,i);if(!e)break;let t=e.getDate(!1);r.push(this.applyDayOffset(t)),i=e}return r}match(e){if(this._states.once){let t=new B(e,this.getTz());t.ms=0;let n=new B(this._states.once,this.getTz());return n.ms=0,t.getTime()===n.getTime()}let t=new B(e,this.getTz());return t.ms=0,t.match(this._states.pattern,this.options)}getPattern(){if(!this._states.once)return this._states.pattern?this._states.pattern.pattern:void 0}getOnce(){return this._states.once?this._states.once.getDate():null}isRunning(){let e=this.nextRun(this._states.currentRun),t=!this._states.paused,n=this.fn!==void 0,r=!this._states.kill;return t&&n&&r&&e!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(e){let t=this._next(e);return t?e instanceof B||e instanceof Date?t.getTime()-e.getTime():t.getTime()-new B(e).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let e=W.indexOf(this);e>=0&&W.splice(e,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(e){if(e&&this.fn)throw Error(`Cron: It is not allowed to schedule two functions using the same Croner instance.`);e&&(this.fn=e);let t=this.msToNext(),n=this.nextRun(this._states.currentRun);return t==null||isNaN(t)||n===null?this:(t>U&&(t=U),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&H(this._states.currentTimeout),this)}async _trigger(e){this._states.blocking=!0,this._states.currentRun=new B(void 0,this.getTz());try{if(this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(e){if(V(this.options.catch))try{this.options.catch(e,this)}catch{}}else this.fn!==void 0&&await this.fn(this,this.options.context)}finally{this._states.previousRun=new B(e,this.getTz()),this._states.blocking=!1}}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(e){let t=new Date,n=!this._states.paused&&t.getTime()>=e.getTime(),r=this._states.blocking&&this.options.protect;n&&!r?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):n&&r&&V(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(e){let t=!!(e||this._states.currentRun),n=!1;!e&&this.options.startAt&&this.options.interval&&([e,t]=this._calculatePreviousRun(e,t),n=!e),e=new B(e,this.getTz()),this.options.startAt&&e&&e.getTime()<this.options.startAt.getTime()&&(e=this.options.startAt);let r=this._states.once||new B(e,this.getTz());return!n&&r!==this._states.once&&(r=r.increment(this._states.pattern,this.options,t)),this._states.once&&this._states.once.getTime()<=e.getTime()||r===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&r.getTime()>=this.options.stopAt.getTime()?null:r}_previous(e){let t=new B(e,this.getTz());this.options.stopAt&&t.getTime()>this.options.stopAt.getTime()&&(t=this.options.stopAt);let n=new B(t,this.getTz());return this._states.once?this._states.once.getTime()<t.getTime()?this._states.once:null:(n=n.decrement(this._states.pattern,this.options),n===null||this.options.startAt&&n.getTime()<this.options.startAt.getTime()?null:n)}_calculatePreviousRun(e,t){let n=new B(void 0,this.getTz()),r=e;if(this.options.startAt.getTime()<=n.getTime()){r=this.options.startAt;let e=r.getTime()+this.options.interval*1e3;for(;e<=n.getTime();)r=new B(r,this.getTz()).increment(this._states.pattern,this.options,!0),e=r.getTime()+this.options.interval*1e3;t=!0}return r===null&&(r=void 0),[r,t]}};const K=_(`automation-cron-scheduler`);function q(e){try{new G(e.schedule,{timezone:e.timezone,paused:!0}).nextRun()}catch(t){throw Error(`Invalid cron schedule '${e.schedule}' in timezone '${e.timezone}' for binding '${e.bindingKey}'`,{cause:t})}}const J=`[BusEventAutomationTrigger]`,Y=e.object({subject:e.string().regex(/^[^.]+\.[\s\S]+$/,`Bus-event subject must be '<namespace>.<subject>' with both segments non-empty.`)});function X(e){return v(h({kind:l,label:`Bus Event`,description:`Fires when a matching event is emitted on the Makaio bus.`,categories:[`Bus`],paramsSchema:Y,eventSchema:f,activate:async(t,n)=>{let r=a(n.subject);if(r===void 0)throw Error(`Bus-event parameter schema admitted an unobservable subject: '${n.subject}'`);return e.on(i(r.namespace),e=>{if(e.isRequest||!o(e.subject,n.subject))return;let r=f.safeParse(e.payload);if(!r.success){console.warn(`${J} skipped non-object JSON payload on '${e.subject}':`,r.error);return}let{correlationId:i}=e;t.emit(r.data,i===void 0?void 0:{correlationId:i}).catch(t=>{console.error(`${J} emit failed for '${e.subject}':`,t)})},{handlerKind:`event`})}}))}function Z(e){return[X(e)]}const ie=e.object({scheduledFor:e.number().finite()});function Q(e){return v(h({kind:u,label:`Schedule`,description:`Fires on a cron schedule in a fixed timezone.`,categories:[`Schedule`],paramsSchema:d,eventSchema:ie,activate:async(t,n)=>{let r=e();if(!r)throw Error(`Automation trigger '${u}' requires the '${K.name}' service; no cron scheduler provider is registered.`);return r.schedule({bindingKey:t.bindingKey,schedule:n.schedule,timezone:n.timezone,emit:e=>t.emit(e)})}}))}const $=`makaio`,ae={name:$,displayName:`Makaio Built-in Automation Triggers`,version:`0.1.0`,dependencies:[g(K.name,void 0,!0)],critical:!0,automationTriggers:{createAutomationTriggers:e=>[...Z(e.bus),Q(()=>e.getService(K))]}};export{X as a,G as c,O as d,te as f,y as g,S as h,Z as i,D as l,x as m,ae as n,K as o,w as p,Q as r,q as s,$ as t,E as u};