mayura 0.1.0-dev.0 → 1.0.0-rc.2

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 (578) hide show
  1. package/README.md +152 -35
  2. package/docs/README.md +82 -0
  3. package/docs/ai-agents.md +73 -0
  4. package/docs/cli/dev.md +111 -0
  5. package/docs/cli/init.md +192 -0
  6. package/docs/cli/operations.md +235 -0
  7. package/docs/cli/overview.md +129 -0
  8. package/docs/cli/run.md +182 -0
  9. package/docs/concepts/agent.md +197 -0
  10. package/docs/concepts/costs-and-budgets.md +177 -0
  11. package/docs/concepts/outcomes.md +154 -0
  12. package/docs/concepts/permissions.md +155 -0
  13. package/docs/concepts/runtime.md +172 -0
  14. package/docs/concepts/tools.md +202 -0
  15. package/docs/concepts/workflows.md +134 -0
  16. package/docs/guides/approvals-and-human-input.md +278 -0
  17. package/docs/guides/artifacts.md +123 -0
  18. package/docs/guides/child-agents.md +158 -0
  19. package/docs/guides/code-mode.md +233 -0
  20. package/docs/guides/deployment.md +644 -0
  21. package/docs/guides/durable-workflows.md +463 -0
  22. package/docs/guides/guardrails.md +205 -0
  23. package/docs/guides/helpers.md +176 -0
  24. package/docs/guides/lifecycle-hooks.md +187 -0
  25. package/docs/guides/mcp.md +123 -0
  26. package/docs/guides/memory-and-context.md +293 -0
  27. package/docs/guides/model-providers.md +371 -0
  28. package/docs/guides/model-routing.md +138 -0
  29. package/docs/guides/observability.md +238 -0
  30. package/docs/guides/operator-console.md +140 -0
  31. package/docs/guides/react.md +276 -0
  32. package/docs/guides/sagas-and-loops.md +212 -0
  33. package/docs/guides/server-and-client.md +559 -0
  34. package/docs/guides/skills.md +152 -0
  35. package/docs/guides/storage.md +251 -0
  36. package/docs/guides/streaming.md +146 -0
  37. package/docs/guides/terminal.md +166 -0
  38. package/docs/guides/testing.md +220 -0
  39. package/docs/guides/vision.md +155 -0
  40. package/docs/guides/webhooks.md +172 -0
  41. package/docs/guides/workflow-composition.md +141 -0
  42. package/docs/guides/workflow-operations.md +269 -0
  43. package/docs/installation.md +90 -0
  44. package/docs/introduction.md +74 -0
  45. package/docs/project/credits.md +78 -0
  46. package/docs/project/security.md +178 -0
  47. package/docs/project/support.md +91 -0
  48. package/docs/project/versioning.md +122 -0
  49. package/docs/quickstart.md +190 -0
  50. package/docs/reference/entry-points.md +146 -0
  51. package/lib/adapter-code-docker/dist/index.d.ts +8 -1
  52. package/lib/adapter-code-docker/dist/index.d.ts.map +1 -1
  53. package/lib/adapter-code-docker/dist/index.js +64 -67
  54. package/lib/adapter-code-docker/dist/index.js.map +1 -1
  55. package/lib/adapter-code-docker/dist/options.d.ts +15 -0
  56. package/lib/adapter-code-docker/dist/options.d.ts.map +1 -0
  57. package/lib/adapter-code-docker/dist/options.js +56 -0
  58. package/lib/adapter-code-docker/dist/options.js.map +1 -0
  59. package/lib/adapter-code-docker/image/Dockerfile +4 -2
  60. package/lib/adapter-code-docker/package.json +1 -1
  61. package/lib/adapter-code-docker/src/index.ts +63 -65
  62. package/lib/adapter-code-docker/src/options.ts +51 -0
  63. package/lib/adapter-code-quickjs/dist/index.d.ts +16 -4
  64. package/lib/adapter-code-quickjs/dist/index.d.ts.map +1 -1
  65. package/lib/adapter-code-quickjs/dist/index.js +94 -50
  66. package/lib/adapter-code-quickjs/dist/index.js.map +1 -1
  67. package/lib/adapter-code-quickjs/dist/worker-command.d.ts +27 -0
  68. package/lib/adapter-code-quickjs/dist/worker-command.d.ts.map +1 -0
  69. package/lib/adapter-code-quickjs/dist/worker-command.js +66 -0
  70. package/lib/adapter-code-quickjs/dist/worker-command.js.map +1 -0
  71. package/lib/adapter-code-quickjs/dist/worker.js +421 -104
  72. package/lib/adapter-code-quickjs/dist/worker.js.map +1 -1
  73. package/lib/adapter-code-quickjs/package.json +1 -1
  74. package/lib/adapter-code-quickjs/src/index.ts +88 -44
  75. package/lib/adapter-code-quickjs/src/worker-command.ts +68 -0
  76. package/lib/adapter-code-quickjs/src/worker.ts +315 -89
  77. package/lib/adapter-mcp/package.json +1 -1
  78. package/lib/artifacts/dist/contracts.d.ts +6 -2
  79. package/lib/artifacts/dist/contracts.d.ts.map +1 -1
  80. package/lib/artifacts/dist/contracts.js.map +1 -1
  81. package/lib/artifacts/dist/index.d.ts +1 -0
  82. package/lib/artifacts/dist/index.d.ts.map +1 -1
  83. package/lib/artifacts/dist/index.js +1 -0
  84. package/lib/artifacts/dist/index.js.map +1 -1
  85. package/lib/artifacts/dist/local-store.d.ts.map +1 -1
  86. package/lib/artifacts/dist/local-store.js +4 -7
  87. package/lib/artifacts/dist/local-store.js.map +1 -1
  88. package/lib/artifacts/dist/media.d.ts +11 -0
  89. package/lib/artifacts/dist/media.d.ts.map +1 -0
  90. package/lib/artifacts/dist/media.js +18 -0
  91. package/lib/artifacts/dist/media.js.map +1 -0
  92. package/lib/artifacts/package.json +1 -1
  93. package/lib/artifacts/src/contracts.ts +6 -2
  94. package/lib/artifacts/src/index.ts +1 -0
  95. package/lib/artifacts/src/local-store.ts +5 -7
  96. package/lib/artifacts/src/media.ts +20 -0
  97. package/lib/cli/dist/agent-guide.d.ts +10 -0
  98. package/lib/cli/dist/agent-guide.d.ts.map +1 -0
  99. package/lib/cli/dist/agent-guide.js +48 -0
  100. package/lib/cli/dist/agent-guide.js.map +1 -0
  101. package/lib/cli/dist/application.d.ts +24 -0
  102. package/lib/cli/dist/application.d.ts.map +1 -1
  103. package/lib/cli/dist/application.js +21 -0
  104. package/lib/cli/dist/application.js.map +1 -1
  105. package/lib/cli/dist/bin.js +26 -6
  106. package/lib/cli/dist/bin.js.map +1 -1
  107. package/lib/cli/dist/dev.d.ts.map +1 -1
  108. package/lib/cli/dist/dev.js +7 -1
  109. package/lib/cli/dist/dev.js.map +1 -1
  110. package/lib/cli/dist/index.d.ts +3 -3
  111. package/lib/cli/dist/index.d.ts.map +1 -1
  112. package/lib/cli/dist/index.js +19 -9
  113. package/lib/cli/dist/index.js.map +1 -1
  114. package/lib/cli/dist/interactive.d.ts.map +1 -1
  115. package/lib/cli/dist/interactive.js +52 -11
  116. package/lib/cli/dist/interactive.js.map +1 -1
  117. package/lib/cli/dist/operations.d.ts +25 -2
  118. package/lib/cli/dist/operations.d.ts.map +1 -1
  119. package/lib/cli/dist/operations.js +125 -12
  120. package/lib/cli/dist/operations.js.map +1 -1
  121. package/lib/cli/dist/output.d.ts.map +1 -1
  122. package/lib/cli/dist/output.js +3 -0
  123. package/lib/cli/dist/output.js.map +1 -1
  124. package/lib/cli/dist/providers.d.ts +34 -4
  125. package/lib/cli/dist/providers.d.ts.map +1 -1
  126. package/lib/cli/dist/providers.js +26 -5
  127. package/lib/cli/dist/providers.js.map +1 -1
  128. package/lib/cli/package.json +1 -1
  129. package/lib/cli/src/agent-guide.ts +47 -0
  130. package/lib/cli/src/application.ts +24 -0
  131. package/lib/cli/src/bin.ts +22 -5
  132. package/lib/cli/src/dev.ts +5 -1
  133. package/lib/cli/src/index.ts +18 -10
  134. package/lib/cli/src/interactive.ts +44 -12
  135. package/lib/cli/src/operations.ts +82 -12
  136. package/lib/cli/src/output.ts +3 -0
  137. package/lib/cli/src/providers.ts +45 -10
  138. package/lib/cli/starters/approval-workflow/dot-env.example +11 -0
  139. package/lib/cli/starters/approval-workflow/package.json +1 -2
  140. package/lib/cli/starters/approval-workflow/src/config.ts +25 -7
  141. package/lib/cli/starters/approval-workflow/src/intake.ts +1 -2
  142. package/lib/cli/starters/approval-workflow/src/model.ts +11 -4
  143. package/lib/cli/starters/approval-workflow/src/workflow.ts +1 -2
  144. package/lib/cli/starters/cli-agent/README.md +121 -0
  145. package/lib/cli/starters/cli-agent/dot-env.example +37 -0
  146. package/lib/cli/starters/cli-agent/dot-github/workflows/ci.yml +13 -0
  147. package/lib/cli/starters/cli-agent/dot-gitignore +10 -0
  148. package/lib/cli/starters/cli-agent/mayura.project.json +15 -0
  149. package/lib/cli/starters/cli-agent/package.json +28 -0
  150. package/lib/cli/starters/cli-agent/skills/release-notes/SKILL.md +18 -0
  151. package/lib/cli/starters/cli-agent/skills/release-notes/references/example.md +12 -0
  152. package/lib/cli/starters/cli-agent/src/assistant.ts +124 -0
  153. package/lib/cli/starters/cli-agent/src/cli.ts +72 -0
  154. package/lib/cli/starters/cli-agent/src/config.ts +117 -0
  155. package/lib/cli/starters/cli-agent/src/model.ts +34 -0
  156. package/lib/cli/starters/cli-agent/src/workspace.ts +170 -0
  157. package/lib/cli/starters/cli-agent/test/assistant.test.ts +205 -0
  158. package/lib/cli/starters/cli-agent/tsconfig.json +20 -0
  159. package/lib/cli/starters/event-automation/README.md +4 -3
  160. package/lib/cli/starters/event-automation/dot-env.example +11 -0
  161. package/lib/cli/starters/event-automation/package.json +1 -2
  162. package/lib/cli/starters/event-automation/src/config.ts +25 -7
  163. package/lib/cli/starters/event-automation/src/ingress.ts +3 -5
  164. package/lib/cli/starters/event-automation/src/model.ts +11 -4
  165. package/lib/cli/starters/event-automation/src/send-sample.ts +1 -1
  166. package/lib/cli/starters/event-automation/src/tracker/main.ts +1 -1
  167. package/lib/cli/starters/event-automation/src/tracker/mcp-server.ts +1 -1
  168. package/lib/cli/starters/event-automation/src/tracker/tickets.ts +1 -1
  169. package/lib/cli/starters/event-automation/src/tracker-tools.ts +1 -1
  170. package/lib/cli/starters/event-automation/src/triage.ts +15 -22
  171. package/lib/cli/starters/event-automation/src/workflows.ts +1 -1
  172. package/lib/cli/starters/event-automation/test/automation.test.ts +3 -3
  173. package/lib/cli/starters/research-team/README.md +2 -2
  174. package/lib/cli/starters/research-team/dot-env.example +11 -0
  175. package/lib/cli/starters/research-team/package.json +1 -2
  176. package/lib/cli/starters/research-team/src/config.ts +25 -7
  177. package/lib/cli/starters/research-team/src/desk.ts +1 -2
  178. package/lib/cli/starters/research-team/src/library/index.ts +1 -2
  179. package/lib/cli/starters/research-team/src/model.ts +11 -4
  180. package/lib/cli/starters/research-team/src/services.ts +1 -1
  181. package/lib/cli/starters/research-team/src/team.ts +1 -2
  182. package/lib/cli/starters/research-team/src/workflow.ts +45 -59
  183. package/lib/cli/starters/support-agent/dot-env.example +11 -0
  184. package/lib/cli/starters/support-agent/package.json +1 -2
  185. package/lib/cli/starters/support-agent/src/assistant.ts +5 -5
  186. package/lib/cli/starters/support-agent/src/config.ts +25 -7
  187. package/lib/cli/starters/support-agent/src/guardrails.ts +3 -1
  188. package/lib/cli/starters/support-agent/src/model.ts +11 -4
  189. package/lib/cli/starters/support-agent/src/returns.ts +1 -2
  190. package/lib/cli/starters/support-agent/test/support.test.ts +25 -1
  191. package/lib/cli/templates/basic-agent.ts +1 -2
  192. package/lib/cli/templates/capability-policy.ts +1 -2
  193. package/lib/cli/templates/code-mode-workflow.ts +1 -1
  194. package/lib/cli/templates/durable-approval.ts +1 -1
  195. package/lib/cli/templates/parallel-research.ts +1 -2
  196. package/lib/cli/templates/typed-tool-runner.ts +1 -2
  197. package/lib/client/dist/forms.d.ts.map +1 -1
  198. package/lib/client/dist/forms.js +3 -4
  199. package/lib/client/dist/forms.js.map +1 -1
  200. package/lib/client/dist/headless.d.ts +3 -1
  201. package/lib/client/dist/headless.d.ts.map +1 -1
  202. package/lib/client/dist/headless.js +10 -6
  203. package/lib/client/dist/headless.js.map +1 -1
  204. package/lib/client/dist/index.d.ts +95 -6
  205. package/lib/client/dist/index.d.ts.map +1 -1
  206. package/lib/client/dist/index.js +397 -124
  207. package/lib/client/dist/index.js.map +1 -1
  208. package/lib/client/dist/workflows.d.ts +1 -1
  209. package/lib/client/dist/workflows.d.ts.map +1 -1
  210. package/lib/client/dist/workflows.js +7 -6
  211. package/lib/client/dist/workflows.js.map +1 -1
  212. package/lib/client/package.json +1 -1
  213. package/lib/client/src/forms.ts +3 -4
  214. package/lib/client/src/headless.ts +13 -7
  215. package/lib/client/src/index.ts +344 -74
  216. package/lib/client/src/workflows.ts +8 -7
  217. package/lib/client-react/package.json +1 -1
  218. package/lib/code-mode/dist/index.d.ts +32 -1
  219. package/lib/code-mode/dist/index.d.ts.map +1 -1
  220. package/lib/code-mode/dist/index.js +289 -221
  221. package/lib/code-mode/dist/index.js.map +1 -1
  222. package/lib/code-mode/package.json +1 -1
  223. package/lib/code-mode/src/index.ts +288 -184
  224. package/lib/code-mode-workflows/package.json +1 -1
  225. package/lib/context/package.json +1 -1
  226. package/lib/core/dist/budget.d.ts.map +1 -1
  227. package/lib/core/dist/budget.js +17 -2
  228. package/lib/core/dist/budget.js.map +1 -1
  229. package/lib/core/dist/contracts.d.ts +57 -0
  230. package/lib/core/dist/contracts.d.ts.map +1 -1
  231. package/lib/core/dist/contracts.js +36 -0
  232. package/lib/core/dist/contracts.js.map +1 -1
  233. package/lib/core/dist/destination.d.ts +12 -0
  234. package/lib/core/dist/destination.d.ts.map +1 -0
  235. package/lib/core/dist/destination.js +37 -0
  236. package/lib/core/dist/destination.js.map +1 -0
  237. package/lib/core/dist/event-stream.d.ts +1 -1
  238. package/lib/core/dist/event-stream.d.ts.map +1 -1
  239. package/lib/core/dist/event-stream.js +7 -0
  240. package/lib/core/dist/event-stream.js.map +1 -1
  241. package/lib/core/dist/host.d.ts +3 -0
  242. package/lib/core/dist/host.d.ts.map +1 -1
  243. package/lib/core/dist/host.js +3 -0
  244. package/lib/core/dist/host.js.map +1 -1
  245. package/lib/core/dist/index.d.ts +2 -0
  246. package/lib/core/dist/index.d.ts.map +1 -1
  247. package/lib/core/dist/index.js +2 -0
  248. package/lib/core/dist/index.js.map +1 -1
  249. package/lib/core/dist/media.d.ts +98 -0
  250. package/lib/core/dist/media.d.ts.map +1 -0
  251. package/lib/core/dist/media.js +227 -0
  252. package/lib/core/dist/media.js.map +1 -0
  253. package/lib/core/dist/model-schema.d.ts +37 -0
  254. package/lib/core/dist/model-schema.d.ts.map +1 -0
  255. package/lib/core/dist/model-schema.js +154 -0
  256. package/lib/core/dist/model-schema.js.map +1 -0
  257. package/lib/core/package.json +1 -1
  258. package/lib/core/src/budget.ts +17 -2
  259. package/lib/core/src/contracts.ts +71 -3
  260. package/lib/core/src/destination.ts +33 -0
  261. package/lib/core/src/event-stream.ts +5 -1
  262. package/lib/core/src/host.ts +3 -0
  263. package/lib/core/src/index.ts +2 -0
  264. package/lib/core/src/media.ts +228 -0
  265. package/lib/core/src/model-schema.ts +129 -0
  266. package/lib/exporter-otlp/dist/otlp-http-json.js +1 -1
  267. package/lib/exporter-otlp/dist/otlp-http-json.js.map +1 -1
  268. package/lib/exporter-otlp/dist/signals.js +2 -2
  269. package/lib/exporter-otlp/dist/signals.js.map +1 -1
  270. package/lib/exporter-otlp/package.json +1 -1
  271. package/lib/exporter-otlp/src/otlp-http-json.ts +1 -1
  272. package/lib/exporter-otlp/src/signals.ts +2 -2
  273. package/lib/guardrails/package.json +1 -1
  274. package/lib/helpers/package.json +1 -1
  275. package/lib/memory/dist/index.js +1 -1
  276. package/lib/memory/dist/index.js.map +1 -1
  277. package/lib/memory/dist/native.d.ts.map +1 -1
  278. package/lib/memory/dist/native.js +4 -3
  279. package/lib/memory/dist/native.js.map +1 -1
  280. package/lib/memory/package.json +1 -1
  281. package/lib/memory/src/index.ts +1 -1
  282. package/lib/memory/src/native.ts +4 -3
  283. package/lib/memory-remote/package.json +1 -1
  284. package/lib/observability/package.json +1 -1
  285. package/lib/provider-anthropic/dist/index.d.ts +36 -3
  286. package/lib/provider-anthropic/dist/index.d.ts.map +1 -1
  287. package/lib/provider-anthropic/dist/index.js +128 -78
  288. package/lib/provider-anthropic/dist/index.js.map +1 -1
  289. package/lib/provider-anthropic/package.json +1 -1
  290. package/lib/provider-anthropic/src/index.ts +152 -76
  291. package/lib/provider-openai/dist/index.d.ts +71 -4
  292. package/lib/provider-openai/dist/index.d.ts.map +1 -1
  293. package/lib/provider-openai/dist/index.js +259 -96
  294. package/lib/provider-openai/dist/index.js.map +1 -1
  295. package/lib/provider-openai/package.json +1 -1
  296. package/lib/provider-openai/src/index.ts +282 -84
  297. package/lib/runtime/dist/agent.d.ts +18 -1
  298. package/lib/runtime/dist/agent.d.ts.map +1 -1
  299. package/lib/runtime/dist/agent.js +59 -3
  300. package/lib/runtime/dist/agent.js.map +1 -1
  301. package/lib/runtime/dist/composition.d.ts.map +1 -1
  302. package/lib/runtime/dist/composition.js +2 -1
  303. package/lib/runtime/dist/composition.js.map +1 -1
  304. package/lib/runtime/dist/hooks.d.ts +15 -3
  305. package/lib/runtime/dist/hooks.d.ts.map +1 -1
  306. package/lib/runtime/dist/hooks.js.map +1 -1
  307. package/lib/runtime/dist/index.d.ts +1 -1
  308. package/lib/runtime/dist/index.d.ts.map +1 -1
  309. package/lib/runtime/dist/index.js.map +1 -1
  310. package/lib/runtime/dist/response.d.ts +7 -1
  311. package/lib/runtime/dist/response.d.ts.map +1 -1
  312. package/lib/runtime/dist/response.js +23 -2
  313. package/lib/runtime/dist/response.js.map +1 -1
  314. package/lib/runtime/dist/router.d.ts +10 -3
  315. package/lib/runtime/dist/router.d.ts.map +1 -1
  316. package/lib/runtime/dist/router.js +45 -8
  317. package/lib/runtime/dist/router.js.map +1 -1
  318. package/lib/runtime/dist/runtime.d.ts +9 -1
  319. package/lib/runtime/dist/runtime.d.ts.map +1 -1
  320. package/lib/runtime/dist/runtime.js +50 -22
  321. package/lib/runtime/dist/runtime.js.map +1 -1
  322. package/lib/runtime/package.json +1 -1
  323. package/lib/runtime/src/agent.ts +69 -3
  324. package/lib/runtime/src/composition.ts +2 -1
  325. package/lib/runtime/src/hooks.ts +10 -4
  326. package/lib/runtime/src/index.ts +1 -1
  327. package/lib/runtime/src/response.ts +20 -2
  328. package/lib/runtime/src/router.ts +43 -10
  329. package/lib/runtime/src/runtime.ts +58 -27
  330. package/lib/sdk/dist/index.d.ts +9 -1
  331. package/lib/sdk/dist/index.d.ts.map +1 -1
  332. package/lib/sdk/dist/index.js +9 -1
  333. package/lib/sdk/dist/index.js.map +1 -1
  334. package/lib/sdk/package.json +1 -1
  335. package/lib/sdk/src/index.ts +9 -1
  336. package/lib/server/dist/index.d.ts +201 -3
  337. package/lib/server/dist/index.d.ts.map +1 -1
  338. package/lib/server/dist/index.js +701 -149
  339. package/lib/server/dist/index.js.map +1 -1
  340. package/lib/server/dist/inspector-bundle.d.ts +1 -1
  341. package/lib/server/dist/inspector-bundle.d.ts.map +1 -1
  342. package/lib/server/dist/inspector-bundle.js +4 -4
  343. package/lib/server/dist/inspector-bundle.js.map +1 -1
  344. package/lib/server/package.json +1 -1
  345. package/lib/server/src/index.ts +611 -135
  346. package/lib/server/src/inspector-bundle.ts +4 -4
  347. package/lib/server-node/dist/hardening.d.ts +1 -1
  348. package/lib/server-node/dist/hardening.d.ts.map +1 -1
  349. package/lib/server-node/dist/hardening.js +4 -2
  350. package/lib/server-node/dist/hardening.js.map +1 -1
  351. package/lib/server-node/dist/index.d.ts +2 -1
  352. package/lib/server-node/dist/index.d.ts.map +1 -1
  353. package/lib/server-node/dist/index.js.map +1 -1
  354. package/lib/server-node/dist/probe.js +2 -2
  355. package/lib/server-node/dist/probe.js.map +1 -1
  356. package/lib/server-node/dist/production.d.ts +8 -1
  357. package/lib/server-node/dist/production.d.ts.map +1 -1
  358. package/lib/server-node/dist/production.js +15 -2
  359. package/lib/server-node/dist/production.js.map +1 -1
  360. package/lib/server-node/package.json +1 -1
  361. package/lib/server-node/src/hardening.ts +5 -3
  362. package/lib/server-node/src/index.ts +2 -1
  363. package/lib/server-node/src/probe.ts +2 -2
  364. package/lib/server-node/src/production.ts +23 -3
  365. package/lib/skills/dist/index.d.ts +81 -0
  366. package/lib/skills/dist/index.d.ts.map +1 -0
  367. package/lib/skills/dist/index.js +311 -0
  368. package/lib/skills/dist/index.js.map +1 -0
  369. package/lib/skills/package.json +5 -0
  370. package/lib/skills/src/index.ts +260 -0
  371. package/lib/storage/dist/index.d.ts +1 -1
  372. package/lib/storage/dist/index.d.ts.map +1 -1
  373. package/lib/storage/dist/index.js.map +1 -1
  374. package/lib/storage/package.json +1 -1
  375. package/lib/storage/src/index.ts +1 -1
  376. package/lib/storage-contracts/dist/contracts.d.ts +12 -5
  377. package/lib/storage-contracts/dist/contracts.d.ts.map +1 -1
  378. package/lib/storage-contracts/dist/contracts.js +24 -6
  379. package/lib/storage-contracts/dist/contracts.js.map +1 -1
  380. package/lib/storage-contracts/dist/index.d.ts +2 -0
  381. package/lib/storage-contracts/dist/index.d.ts.map +1 -1
  382. package/lib/storage-contracts/dist/index.js +2 -0
  383. package/lib/storage-contracts/dist/index.js.map +1 -1
  384. package/lib/storage-contracts/dist/memory-contracts.js +1 -1
  385. package/lib/storage-contracts/dist/memory-contracts.js.map +1 -1
  386. package/lib/storage-contracts/dist/run-records.d.ts +100 -0
  387. package/lib/storage-contracts/dist/run-records.d.ts.map +1 -0
  388. package/lib/storage-contracts/dist/run-records.js +464 -0
  389. package/lib/storage-contracts/dist/run-records.js.map +1 -0
  390. package/lib/storage-contracts/dist/schema-digest.d.ts +17 -0
  391. package/lib/storage-contracts/dist/schema-digest.d.ts.map +1 -0
  392. package/lib/storage-contracts/dist/schema-digest.js +94 -0
  393. package/lib/storage-contracts/dist/schema-digest.js.map +1 -0
  394. package/lib/storage-contracts/dist/submission-journal.js +1 -1
  395. package/lib/storage-contracts/dist/submission-journal.js.map +1 -1
  396. package/lib/storage-contracts/dist/workflow-format5.d.ts +30 -2
  397. package/lib/storage-contracts/dist/workflow-format5.d.ts.map +1 -1
  398. package/lib/storage-contracts/dist/workflow-format5.js +57 -5
  399. package/lib/storage-contracts/dist/workflow-format5.js.map +1 -1
  400. package/lib/storage-contracts/package.json +1 -1
  401. package/lib/storage-contracts/src/contracts.ts +29 -5
  402. package/lib/storage-contracts/src/index.ts +2 -0
  403. package/lib/storage-contracts/src/memory-contracts.ts +1 -1
  404. package/lib/storage-contracts/src/run-records.ts +365 -0
  405. package/lib/storage-contracts/src/schema-digest.ts +71 -0
  406. package/lib/storage-contracts/src/submission-journal.ts +1 -1
  407. package/lib/storage-contracts/src/workflow-format5.ts +70 -6
  408. package/lib/storage-postgres/dist/index.d.ts +1 -1
  409. package/lib/storage-postgres/dist/index.d.ts.map +1 -1
  410. package/lib/storage-postgres/dist/index.js.map +1 -1
  411. package/lib/storage-postgres/dist/postgres.d.ts +15 -0
  412. package/lib/storage-postgres/dist/postgres.d.ts.map +1 -1
  413. package/lib/storage-postgres/dist/postgres.js +18 -7
  414. package/lib/storage-postgres/dist/postgres.js.map +1 -1
  415. package/lib/storage-postgres/package.json +1 -1
  416. package/lib/storage-postgres/src/index.ts +1 -1
  417. package/lib/storage-postgres/src/postgres.ts +34 -8
  418. package/lib/storage-sql/dist/aggregate-session.js +1 -1
  419. package/lib/storage-sql/dist/aggregate-session.js.map +1 -1
  420. package/lib/storage-sql/dist/scheduled-database.js +1 -1
  421. package/lib/storage-sql/dist/scheduled-database.js.map +1 -1
  422. package/lib/storage-sql/dist/workflow-tree-validation.js +1 -1
  423. package/lib/storage-sql/dist/workflow-tree-validation.js.map +1 -1
  424. package/lib/storage-sql/package.json +1 -1
  425. package/lib/storage-sql/src/aggregate-session.ts +1 -1
  426. package/lib/storage-sql/src/scheduled-database.ts +1 -1
  427. package/lib/storage-sql/src/workflow-tree-validation.ts +1 -1
  428. package/lib/storage-sqlite/dist/sqlite-database.js +4 -4
  429. package/lib/storage-sqlite/dist/sqlite-database.js.map +1 -1
  430. package/lib/storage-sqlite/dist/sqlite-worker.js +2 -2
  431. package/lib/storage-sqlite/dist/sqlite-worker.js.map +1 -1
  432. package/lib/storage-sqlite/dist/sqlite.js +1 -1
  433. package/lib/storage-sqlite/dist/sqlite.js.map +1 -1
  434. package/lib/storage-sqlite/package.json +1 -1
  435. package/lib/storage-sqlite/src/sqlite-database.ts +4 -4
  436. package/lib/storage-sqlite/src/sqlite-worker.ts +2 -2
  437. package/lib/storage-sqlite/src/sqlite.ts +1 -1
  438. package/lib/terminal/dist/index.d.ts +92 -0
  439. package/lib/terminal/dist/index.d.ts.map +1 -0
  440. package/lib/terminal/dist/index.js +397 -0
  441. package/lib/terminal/dist/index.js.map +1 -0
  442. package/lib/terminal/package.json +5 -0
  443. package/lib/terminal/src/index.ts +273 -0
  444. package/lib/testing/dist/index.d.ts +44 -1
  445. package/lib/testing/dist/index.d.ts.map +1 -1
  446. package/lib/testing/dist/index.js +63 -10
  447. package/lib/testing/dist/index.js.map +1 -1
  448. package/lib/testing/package.json +1 -1
  449. package/lib/testing/src/index.ts +83 -10
  450. package/lib/tools/dist/index.d.ts +32 -4
  451. package/lib/tools/dist/index.d.ts.map +1 -1
  452. package/lib/tools/dist/index.js +64 -11
  453. package/lib/tools/dist/index.js.map +1 -1
  454. package/lib/tools/package.json +1 -1
  455. package/lib/tools/src/index.ts +74 -13
  456. package/lib/workflows/dist/abandoned.d.ts +15 -0
  457. package/lib/workflows/dist/abandoned.d.ts.map +1 -0
  458. package/lib/workflows/dist/abandoned.js +33 -0
  459. package/lib/workflows/dist/abandoned.js.map +1 -0
  460. package/lib/workflows/dist/agent-step.d.ts +83 -0
  461. package/lib/workflows/dist/agent-step.d.ts.map +1 -0
  462. package/lib/workflows/dist/agent-step.js +161 -0
  463. package/lib/workflows/dist/agent-step.js.map +1 -0
  464. package/lib/workflows/dist/children-runtime.js +8 -8
  465. package/lib/workflows/dist/children-runtime.js.map +1 -1
  466. package/lib/workflows/dist/composite-fleet.js +2 -2
  467. package/lib/workflows/dist/composite-fleet.js.map +1 -1
  468. package/lib/workflows/dist/composite-host.d.ts.map +1 -1
  469. package/lib/workflows/dist/composite-host.js +26 -2
  470. package/lib/workflows/dist/composite-host.js.map +1 -1
  471. package/lib/workflows/dist/hook-relay.js +2 -2
  472. package/lib/workflows/dist/hook-relay.js.map +1 -1
  473. package/lib/workflows/dist/index.d.ts +1 -1
  474. package/lib/workflows/dist/index.d.ts.map +1 -1
  475. package/lib/workflows/dist/index.js.map +1 -1
  476. package/lib/workflows/dist/leadership.js +3 -3
  477. package/lib/workflows/dist/leadership.js.map +1 -1
  478. package/lib/workflows/dist/lifecycle-definition.d.ts +26 -4
  479. package/lib/workflows/dist/lifecycle-definition.d.ts.map +1 -1
  480. package/lib/workflows/dist/lifecycle-definition.js +31 -6
  481. package/lib/workflows/dist/lifecycle-definition.js.map +1 -1
  482. package/lib/workflows/dist/lifecycle-fleet.d.ts.map +1 -1
  483. package/lib/workflows/dist/lifecycle-fleet.js +9 -11
  484. package/lib/workflows/dist/lifecycle-fleet.js.map +1 -1
  485. package/lib/workflows/dist/lifecycle-host.d.ts.map +1 -1
  486. package/lib/workflows/dist/lifecycle-host.js +26 -2
  487. package/lib/workflows/dist/lifecycle-host.js.map +1 -1
  488. package/lib/workflows/dist/lifecycle-human-transport.d.ts +22 -2
  489. package/lib/workflows/dist/lifecycle-human-transport.d.ts.map +1 -1
  490. package/lib/workflows/dist/lifecycle-human-transport.js +115 -33
  491. package/lib/workflows/dist/lifecycle-human-transport.js.map +1 -1
  492. package/lib/workflows/dist/lifecycle-runtime.d.ts +62 -1
  493. package/lib/workflows/dist/lifecycle-runtime.d.ts.map +1 -1
  494. package/lib/workflows/dist/lifecycle-runtime.js +268 -64
  495. package/lib/workflows/dist/lifecycle-runtime.js.map +1 -1
  496. package/lib/workflows/dist/lifecycle.d.ts +6 -4
  497. package/lib/workflows/dist/lifecycle.d.ts.map +1 -1
  498. package/lib/workflows/dist/lifecycle.js +2 -0
  499. package/lib/workflows/dist/lifecycle.js.map +1 -1
  500. package/lib/workflows/dist/loop-runtime.d.ts.map +1 -1
  501. package/lib/workflows/dist/loop-runtime.js +38 -26
  502. package/lib/workflows/dist/loop-runtime.js.map +1 -1
  503. package/lib/workflows/dist/migration.d.ts +1 -1
  504. package/lib/workflows/dist/migration.d.ts.map +1 -1
  505. package/lib/workflows/dist/migration.js +3 -3
  506. package/lib/workflows/dist/migration.js.map +1 -1
  507. package/lib/workflows/dist/operator-transports.d.ts +24 -2
  508. package/lib/workflows/dist/operator-transports.d.ts.map +1 -1
  509. package/lib/workflows/dist/operator-transports.js +49 -3
  510. package/lib/workflows/dist/operator-transports.js.map +1 -1
  511. package/lib/workflows/dist/runtime.d.ts.map +1 -1
  512. package/lib/workflows/dist/runtime.js +34 -22
  513. package/lib/workflows/dist/runtime.js.map +1 -1
  514. package/lib/workflows/dist/saga-runtime.d.ts.map +1 -1
  515. package/lib/workflows/dist/saga-runtime.js +44 -30
  516. package/lib/workflows/dist/saga-runtime.js.map +1 -1
  517. package/lib/workflows/dist/scheduled-helpers.d.ts.map +1 -1
  518. package/lib/workflows/dist/scheduled-helpers.js +3 -3
  519. package/lib/workflows/dist/scheduled-helpers.js.map +1 -1
  520. package/lib/workflows/dist/storage-failure.d.ts +16 -0
  521. package/lib/workflows/dist/storage-failure.d.ts.map +1 -0
  522. package/lib/workflows/dist/storage-failure.js +38 -0
  523. package/lib/workflows/dist/storage-failure.js.map +1 -0
  524. package/lib/workflows/dist/sweep-position.d.ts +22 -0
  525. package/lib/workflows/dist/sweep-position.d.ts.map +1 -0
  526. package/lib/workflows/dist/sweep-position.js +45 -0
  527. package/lib/workflows/dist/sweep-position.js.map +1 -0
  528. package/lib/workflows/dist/traces.js +2 -2
  529. package/lib/workflows/dist/traces.js.map +1 -1
  530. package/lib/workflows/dist/worker.d.ts +31 -0
  531. package/lib/workflows/dist/worker.d.ts.map +1 -1
  532. package/lib/workflows/dist/worker.js +94 -0
  533. package/lib/workflows/dist/worker.js.map +1 -1
  534. package/lib/workflows/package.json +1 -1
  535. package/lib/workflows/src/abandoned.ts +32 -0
  536. package/lib/workflows/src/agent-step.ts +199 -0
  537. package/lib/workflows/src/children-runtime.ts +8 -8
  538. package/lib/workflows/src/composite-fleet.ts +2 -2
  539. package/lib/workflows/src/composite-host.ts +21 -3
  540. package/lib/workflows/src/hook-relay.ts +2 -2
  541. package/lib/workflows/src/index.ts +2 -1
  542. package/lib/workflows/src/leadership.ts +3 -3
  543. package/lib/workflows/src/lifecycle-definition.ts +50 -9
  544. package/lib/workflows/src/lifecycle-fleet.ts +7 -8
  545. package/lib/workflows/src/lifecycle-host.ts +21 -5
  546. package/lib/workflows/src/lifecycle-human-transport.ts +110 -26
  547. package/lib/workflows/src/lifecycle-runtime.ts +270 -60
  548. package/lib/workflows/src/lifecycle.ts +7 -0
  549. package/lib/workflows/src/loop-runtime.ts +34 -25
  550. package/lib/workflows/src/migration.ts +2 -2
  551. package/lib/workflows/src/operator-transports.ts +48 -4
  552. package/lib/workflows/src/runtime.ts +28 -22
  553. package/lib/workflows/src/saga-runtime.ts +38 -28
  554. package/lib/workflows/src/scheduled-helpers.ts +3 -3
  555. package/lib/workflows/src/storage-failure.ts +37 -0
  556. package/lib/workflows/src/sweep-position.ts +52 -0
  557. package/lib/workflows/src/traces.ts +2 -2
  558. package/lib/workflows/src/worker.ts +79 -1
  559. package/lib/workstream/dist/humans.d.ts +7 -3
  560. package/lib/workstream/dist/humans.d.ts.map +1 -1
  561. package/lib/workstream/dist/humans.js +13 -2
  562. package/lib/workstream/dist/humans.js.map +1 -1
  563. package/lib/workstream/dist/index.js +2 -2
  564. package/lib/workstream/dist/index.js.map +1 -1
  565. package/lib/workstream/dist/timers.js +2 -2
  566. package/lib/workstream/dist/timers.js.map +1 -1
  567. package/lib/workstream/dist/webhooks.d.ts +6 -2
  568. package/lib/workstream/dist/webhooks.d.ts.map +1 -1
  569. package/lib/workstream/dist/webhooks.js +17 -7
  570. package/lib/workstream/dist/webhooks.js.map +1 -1
  571. package/lib/workstream/package.json +1 -1
  572. package/lib/workstream/src/humans.ts +15 -5
  573. package/lib/workstream/src/index.ts +2 -2
  574. package/lib/workstream/src/timers.ts +2 -2
  575. package/lib/workstream/src/webhooks.ts +21 -8
  576. package/llms-full.txt +9766 -0
  577. package/llms.txt +92 -0
  578. package/package.json +18 -6
@@ -1,6 +1,7 @@
1
1
  import { Budget, MayuraError, assertPositiveInteger, freezeJson, jsonValue, validate,
2
2
  type ExecutionReceipt, type JsonObject, type JsonValue, type Permissions, type Scope } from '@mayura/core';
3
3
  import { invokeTool } from '@mayura/tools';
4
+ import { abandoned, dispatchedAt } from './abandoned.js';
4
5
  import { createWorkflowDrainGate, type WorkflowDrainOptions, type WorkflowDrainReport } from './drain.js';
5
6
  import { StorageError, assertWorkflowLifecycleStateMatchesManifest, initialWorkflowLifecycleState,
6
7
  mergeWorkflowReceipt, workflowLifecycleOutputs, workflowLifecycleState,
@@ -10,6 +11,7 @@ import { charged, digest, resolveBinding, type Binding } from './definition.js';
10
11
  import { assertWorkflowLifecycle, lifecycleManifest, type AnyWorkflowLifecycle,
11
12
  type WorkflowLifecycleNode } from './lifecycle-definition.js';
12
13
  import type { VerifiedHuman } from './runtime.js';
14
+ import { createSubmission, workflowStorageFailure } from './storage-failure.js';
13
15
  import { assertMigrationAllowed, assertWorkflowMigration, migrationCommand, migrationEvent, nodeEvidence, nodeFingerprint, planWorkflowMigration,
14
16
  type MigrationBlocker, type MigrationCommand, type WorkflowMigration, type WorkflowMigrationResult } from './migration.js';
15
17
  export type { WorkflowMigrationResult } from './migration.js';
@@ -38,6 +40,22 @@ export interface WorkflowLifecycleHumanRequest {
38
40
  readonly deadlineAtMs: number | null;
39
41
  }
40
42
 
43
+ /**
44
+ * A signal for a waiting (or not yet started) `signal` step. `signalId` makes delivery idempotent: the same id with the
45
+ * same payload is accepted once and every repeat returns the run unchanged; the same id with another payload, or a
46
+ * second signal for a step that already has one, is refused with CONFLICT.
47
+ */
48
+ export interface WorkflowLifecycleSignalCommand {
49
+ readonly id: string;
50
+ /** The signal node's `name` (its id unless it names one). */
51
+ readonly name: string;
52
+ /** 1–128 letters, digits, `.`, `_`, `/` or `-`, starting with a letter or digit. */
53
+ readonly signalId: string;
54
+ readonly payload: unknown;
55
+ /** Who sent it, recorded in the run's event log. */
56
+ readonly actorId?: string;
57
+ }
58
+
41
59
  /** What an operator approves: the exact tool call the approval digest binds, reconstructed and digest-verified. */
42
60
  export interface WorkflowLifecycleApprovalRequest {
43
61
  readonly runId: string;
@@ -51,6 +69,18 @@ export interface WorkflowLifecycleApprovalRequest {
51
69
  readonly expiresAtMs: number;
52
70
  }
53
71
 
72
+ /**
73
+ * Runtime settings a run may have been started with (same scope as the runtime). Defaults match the runtime's own.
74
+ * A run started under a listed policy continues under exactly those settings; it never gains the current ones.
75
+ */
76
+ export interface WorkflowLifecyclePolicy {
77
+ readonly permissions: Permissions;
78
+ readonly policyVersion: string;
79
+ readonly maxCostMicros: number;
80
+ readonly maxOutputBytes?: number;
81
+ readonly approvalTtlMs?: number;
82
+ }
83
+
54
84
  export interface WorkflowLifecycleRuntimeOptions {
55
85
  readonly store: AggregateStore;
56
86
  readonly scope: Scope;
@@ -59,6 +89,11 @@ export interface WorkflowLifecycleRuntimeOptions {
59
89
  readonly maxCostMicros: number;
60
90
  readonly approvalTtlMs?: number;
61
91
  readonly maxOutputBytes?: number;
92
+ /**
93
+ * Settings of earlier deployments (at most 16). Runs started under one of them continue under it instead of
94
+ * failing with CONFLICT; new runs always use the current settings, and `migrate` moves a run onto them.
95
+ */
96
+ readonly previousPolicies?: readonly WorkflowLifecyclePolicy[];
62
97
  readonly callbackTimeoutMs?: number;
63
98
  readonly maxPendingCallbacks?: number;
64
99
  /** Trusted synchronized clock; never accepted from workflow input. */
@@ -84,6 +119,11 @@ export interface WorkflowLifecycleRuntime {
84
119
  readonly requestDigest: string; readonly commandId: string; readonly credential: unknown; readonly value: unknown }): Promise<WorkflowLifecycleSnapshot>;
85
120
  respondVerified(definition: AnyWorkflowLifecycle, command: { readonly id: string; readonly nodeId: string;
86
121
  readonly requestDigest: string; readonly commandId: string; readonly actor: WorkflowLifecycleVerifiedActor; readonly value: unknown }): Promise<WorkflowLifecycleSnapshot>;
122
+ /**
123
+ * Deliver a signal to the run's `signal` step named `command.name`. The payload is validated with the step's
124
+ * `payload` schema (INVALID_INPUT otherwise). The run continues on its next `runUntilSettled`, as after a response.
125
+ */
126
+ signal(definition: AnyWorkflowLifecycle, command: WorkflowLifecycleSignalCommand): Promise<WorkflowLifecycleSnapshot>;
87
127
  pause(id: string): Promise<WorkflowLifecycleSnapshot>;
88
128
  resume(id: string): Promise<WorkflowLifecycleSnapshot>;
89
129
  /**
@@ -104,6 +144,7 @@ const terminalStepStatuses = new Set(['succeeded', 'failed', 'blocked', 'unknown
104
144
  const satisfiedStepStatuses = new Set(['succeeded', 'bypassed']);
105
145
  const hashPattern = /^[a-f0-9]{64}$/;
106
146
  const nodePattern = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/;
147
+ const signalPattern = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
107
148
 
108
149
  async function bounded<T>(operation: () => Promise<T>, timeoutMs: number): Promise<T> {
109
150
  let timer: ReturnType<typeof setTimeout> | undefined;
@@ -116,10 +157,7 @@ async function bounded<T>(operation: () => Promise<T>, timeoutMs: number): Promi
116
157
 
117
158
  async function storageCall<T>(operation: () => Promise<T>): Promise<T> {
118
159
  try { return await operation(); }
119
- catch (error) {
120
- if (error instanceof StorageError && error.code === 'CONFLICT') throw new StorageError('CONFLICT', 'Workflow lifecycle storage version changed.');
121
- throw new MayuraError('STORAGE_UNAVAILABLE', 'Workflow lifecycle storage is unavailable; reconcile uncertain actions before retrying.');
122
- }
160
+ catch (error) { throw workflowStorageFailure(error, 'workflow lifecycle run'); }
123
161
  }
124
162
 
125
163
  function stateFrom(record: StoredRecord): State {
@@ -139,7 +177,7 @@ function receipt(previous: ExecutionReceipt | null, incoming: ExecutionReceipt):
139
177
 
140
178
  function nextWake(state: State): number | null {
141
179
  const deadlines = Object.values(state.steps).flatMap(step => step.kind === 'timer' && step.status === 'waiting' && step.fireAtMs !== null
142
- ? [step.fireAtMs] : step.kind === 'human' && step.status === 'waiting' && step.deadlineAtMs !== null
180
+ ? [step.fireAtMs] : (step.kind === 'human' || step.kind === 'signal') && step.status === 'waiting' && step.deadlineAtMs !== null
143
181
  ? [step.deadlineAtMs] : step.kind === 'tool' && step.status === 'waiting' && step.approval !== null ? [step.approval.expiresAt] : []);
144
182
  return deadlines.length === 0 ? null : Math.min(...deadlines);
145
183
  }
@@ -161,6 +199,62 @@ function exactDigest(value: JsonValue): string {
161
199
  return value;
162
200
  }
163
201
 
202
+ /** @internal A validated policy with its defaults applied. */
203
+ export interface WorkflowPolicySettings {
204
+ readonly permissions: Permissions; readonly policyVersion: string; readonly maxCostMicros: number;
205
+ readonly maxOutputBytes: number; readonly approvalTtlMs: number;
206
+ }
207
+
208
+ /**
209
+ * @internal The runtime's own settings first, then each previous policy, validated and defaulted alike, so index `n`
210
+ * means the same settings to every runtime built from one options object.
211
+ */
212
+ export function workflowPolicySettings(options: WorkflowLifecyclePolicy & { readonly previousPolicies?: readonly WorkflowLifecyclePolicy[] }): readonly WorkflowPolicySettings[] {
213
+ const previous: unknown = options.previousPolicies ?? [];
214
+ if (!Array.isArray(previous) || previous.length > 16) throw new MayuraError('INVALID_CONFIG', 'previousPolicies must list at most 16 policies.');
215
+ return Object.freeze([options, ...previous as unknown[]].map(value => {
216
+ if (value === null || typeof value !== 'object') throw new MayuraError('INVALID_CONFIG', 'Each previous policy must be an explicit settings object.');
217
+ const policy = value as WorkflowLifecyclePolicy;
218
+ if (typeof policy.policyVersion !== 'string' || policy.policyVersion.length < 1 || policy.policyVersion.length > 128) {
219
+ throw new MayuraError('INVALID_CONFIG', 'Workflow lifecycle policy version is required.');
220
+ }
221
+ if (!Array.isArray(policy.permissions?.allow) || policy.permissions.allow.length > 4_096
222
+ || policy.permissions.allow.some(grant => typeof grant !== 'string' || grant.length < 1 || grant.length > 256)) {
223
+ throw new MayuraError('INVALID_CONFIG', 'Workflow lifecycle permissions must be bounded explicit grants.');
224
+ }
225
+ if (!Number.isSafeInteger(policy.maxCostMicros) || policy.maxCostMicros < 0) throw new MayuraError('INVALID_CONFIG', 'A bounded lifecycle cost is required.');
226
+ const maxOutputBytes = policy.maxOutputBytes ?? 1_048_576; const approvalTtlMs = policy.approvalTtlMs ?? 3_600_000;
227
+ assertPositiveInteger(approvalTtlMs, 'approvalTtlMs'); assertPositiveInteger(maxOutputBytes, 'maxOutputBytes');
228
+ return Object.freeze({ permissions: Object.freeze({ allow: Object.freeze([...policy.permissions.allow]) }),
229
+ policyVersion: policy.policyVersion, maxCostMicros: policy.maxCostMicros, maxOutputBytes, approvalTtlMs });
230
+ }));
231
+ }
232
+
233
+ /** @internal The digest a run records for its settings; each runtime kind has its own domain tag. */
234
+ export function workflowPolicyDigest(tag: string, scope: Scope, settings: WorkflowPolicySettings): string {
235
+ return digest(tag, { scope, permissions: [...settings.permissions.allow].sort(), policyVersion: settings.policyVersion,
236
+ maxCostMicros: settings.maxCostMicros, maxOutputBytes: settings.maxOutputBytes, approvalTtlMs: settings.approvalTtlMs });
237
+ }
238
+
239
+ /** @internal */
240
+ export function unknownWorkflowPolicy(): MayuraError {
241
+ return new MayuraError('CONFLICT', 'This run was started under different runtime settings (permissions, policyVersion or limits). '
242
+ + 'List those settings in previousPolicies to let it continue, or migrate it.');
243
+ }
244
+
245
+ type LifecycleSubmission = Parameters<WorkflowLifecycleRuntime['submit']>;
246
+ const pinnedSubmissions = new WeakMap<WorkflowLifecycleRuntime, (policy: number, ...submission: LifecycleSubmission) => Promise<WorkflowLifecycleSnapshot>>();
247
+
248
+ /**
249
+ * @internal Submit under the runtime's policy at `policy` (0: current, n: `previousPolicies[n - 1]`), so the later
250
+ * children of a pinned saga or loop keep the parent's settings instead of gaining the current ones.
251
+ */
252
+ export function submitWorkflowLifecycleUnder(runtime: WorkflowLifecycleRuntime, policy: number, ...submission: LifecycleSubmission): Promise<WorkflowLifecycleSnapshot> {
253
+ const submit = pinnedSubmissions.get(runtime);
254
+ if (!submit) throw new MayuraError('INVALID_CONFIG', 'A genuine workflow lifecycle runtime is required.');
255
+ return submit(policy, ...submission);
256
+ }
257
+
164
258
  /** Conservative durable lifecycle driver. Waiting nodes never retain a callback, worker, or timer handle. */
165
259
  export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntimeOptions): WorkflowLifecycleRuntime {
166
260
  const store = options.store;
@@ -168,18 +262,9 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
168
262
  if ([scope.principalId, scope.projectId, options.policyVersion].some(value => typeof value !== 'string' || value.length < 1 || value.length > 128)) {
169
263
  throw new MayuraError('INVALID_CONFIG', 'Workflow lifecycle scope and policy version are required.');
170
264
  }
171
- if (!Array.isArray(options.permissions?.allow) || options.permissions.allow.length > 4_096
172
- || options.permissions.allow.some(grant => typeof grant !== 'string' || grant.length < 1 || grant.length > 256)) {
173
- throw new MayuraError('INVALID_CONFIG', 'Workflow lifecycle permissions must be bounded explicit grants.');
174
- }
175
- if (!Number.isSafeInteger(options.maxCostMicros) || options.maxCostMicros < 0) throw new MayuraError('INVALID_CONFIG', 'A bounded lifecycle cost is required.');
176
- const permissions = Object.freeze({ allow: Object.freeze([...options.permissions.allow]) });
177
- const maxCostMicros = options.maxCostMicros;
178
- const approvalTtlMs = options.approvalTtlMs ?? 3_600_000;
179
- const maxOutputBytes = options.maxOutputBytes ?? 1_048_576;
265
+ const settings = workflowPolicySettings(options);
180
266
  const callbackTimeoutMs = options.callbackTimeoutMs ?? 30_000;
181
267
  const maxPendingCallbacks = options.maxPendingCallbacks ?? 32;
182
- assertPositiveInteger(approvalTtlMs, 'approvalTtlMs'); assertPositiveInteger(maxOutputBytes, 'maxOutputBytes');
183
268
  assertPositiveInteger(callbackTimeoutMs, 'callbackTimeoutMs');
184
269
  assertPositiveInteger(maxPendingCallbacks, 'maxPendingCallbacks');
185
270
  if (maxPendingCallbacks > 128) throw new MayuraError('INVALID_CONFIG', 'maxPendingCallbacks must not exceed 128.');
@@ -201,8 +286,12 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
201
286
  return value;
202
287
  };
203
288
  const scopeKey = digest('mayura:scope:v1', scope);
204
- const policy = digest('mayura:workflow-lifecycle-policy:v1', { scope, permissions: [...permissions.allow].sort(),
205
- policyVersion: options.policyVersion, maxCostMicros, maxOutputBytes, approvalTtlMs });
289
+ type Pinned = WorkflowPolicySettings & { readonly digest: string };
290
+ const policies: readonly Pinned[] = settings.map(entry =>
291
+ Object.freeze({ ...entry, digest: workflowPolicyDigest('mayura:workflow-lifecycle-policy:v1', scope, entry) }));
292
+ const currentPolicy = policies[0]!; const policy = currentPolicy.digest; const maxCostMicros = currentPolicy.maxCostMicros;
293
+ /** The settings a stored run was started with; undefined when they are neither current nor listed. */
294
+ const pinnedTo = (state: State): Pinned | undefined => policies.find(entry => entry.digest === state.policy);
206
295
  const active = new Map<string, AbortController>(); let closed = false; const gate = createWorkflowDrainGate();
207
296
  const ensureOpen = (): void => { if (closed) throw new MayuraError('CANCELLED', 'Workflow lifecycle runtime is closed.'); };
208
297
  const load = async (id: string, allowClosed = false): Promise<StoredRecord> => {
@@ -222,7 +311,7 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
222
311
  const record = await load(id, allowClosed); const state = stateFrom(record);
223
312
  if (!transition(state)) return record;
224
313
  try { return await save(record, state, type, data); }
225
- catch (error) { if (!(error instanceof StorageError) || error.code !== 'CONFLICT') throw error; }
314
+ catch (error) { if (!(error instanceof StorageError) || error.storageCode !== 'CONFLICT') throw error; }
226
315
  }
227
316
  throw new MayuraError('CONFLICT', 'Workflow lifecycle contention exceeded the bounded retry limit.');
228
317
  };
@@ -236,8 +325,9 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
236
325
  return Object.freeze(human);
237
326
  } catch { throw new MayuraError('PERMISSION_DENIED', 'Human identity verification failed.'); }
238
327
  };
328
+ // Bound to the run's own policy, so an approval issued before an upgrade stays valid for the run it was issued to.
239
329
  const approvalCandidate = (node: Extract<WorkflowLifecycleNode, { kind: 'tool' }>, input: JsonValue,
240
- runId: string, expiresAt: number | null): string => digest('mayura:approval:v1', { runId, nodeId: node.id,
330
+ runId: string, expiresAt: number | null, policy: string): string => digest('mayura:approval:v1', { runId, nodeId: node.id,
241
331
  tool: node.tool.id, toolVersion: node.tool.version, input, policy, expiresAt });
242
332
 
243
333
  const schedulable = (state: State): boolean => state.status !== 'paused' && state.status !== 'cancelled';
@@ -250,12 +340,19 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
250
340
  step.actorId = null; step.deadlineAtMs = null;
251
341
  } else if (step.kind === 'timer') {
252
342
  step.status = 'skipped'; step.output = null; step.fireAtMs = null; step.firedAtMs = null;
343
+ } else if (step.kind === 'signal') {
344
+ step.status = 'skipped'; clearSignal(step); step.deadlineAtMs = null;
253
345
  } else step.status = 'skipped';
254
346
  return true;
255
347
  };
348
+ // A signal kept for a step that never runs is dropped with it.
349
+ const clearSignal = (step: Extract<WorkflowLifecycleStep, { kind: 'signal' }>): void => {
350
+ step.output = null; step.signalId = null; step.payloadDigest = null; step.receivedAtMs = null;
351
+ };
256
352
 
257
353
  const bypass = (step: WorkflowLifecycleStep): boolean => {
258
354
  if (step.status !== 'pending') return false;
355
+ if (step.kind === 'signal') clearSignal(step);
259
356
  step.status = 'bypassed'; return true;
260
357
  };
261
358
  /** Whether a `when` binding holds: it resolves to something other than `null` or `false`. */
@@ -269,10 +366,28 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
269
366
 
270
367
  async function executeNode(id: string, definition: AnyWorkflowLifecycle, node: WorkflowLifecycleNode, claimRetries = 0): Promise<void> {
271
368
  const record = await load(id); const state = stateFrom(record); const step = state.steps[node.id];
272
- if (!step || step.kind !== node.kind || state.policy !== policy || !schedulable(state)) return;
369
+ // Every limit and grant below comes from the run's own policy, never from the current one.
370
+ const run = pinnedTo(state);
371
+ if (!step || step.kind !== node.kind || !run || !schedulable(state)) return;
372
+ const { permissions, maxOutputBytes, approvalTtlMs } = run;
273
373
  // A pause or cancellation may commit after this read; every scheduling transition rechecks the latest state.
274
374
  const advance = (transition: (current: State) => boolean, type: string, data: JsonObject): Promise<StoredRecord> =>
275
375
  mutate(id, current => schedulable(current) && transition(current), type, data);
376
+ // A dispatching step that no call in this process owns may belong to a process that stopped (killed, or frozen
377
+ // past its limit). Once the tool's timeout and a margin have passed since the dispatch, no live process can still
378
+ // settle it, so it is settled as recoverAbandoned would: unknown, or blocked when a receipt shows it succeeded. The
379
+ // effect is never run again.
380
+ if (node.kind === 'tool' && step.kind === 'tool' && step.status === 'dispatching') {
381
+ if (active.has(`${id}/${node.id}`)) return;
382
+ const dispatchedAtMs = await storageCall(() => dispatchedAt(store, scopeKey, id, 'lifecycle.step.dispatching', node.id));
383
+ if (!abandoned(dispatchedAtMs, node.tool.timeoutMs, now())) return;
384
+ await advance(current => {
385
+ const target = current.steps[node.id];
386
+ if (!target || target.kind !== 'tool' || target.status !== 'dispatching' || active.has(`${id}/${node.id}`)) return false;
387
+ target.status = target.receipt?.execution === 'succeeded' ? 'blocked' : 'unknown'; current.status = 'running'; return true;
388
+ }, 'lifecycle.step.abandoned', { nodeId: node.id });
389
+ return;
390
+ }
276
391
  const dependencies = (node.dependsOn ?? []).map(key => state.steps[key]!);
277
392
  if (dependencies.some(item => terminalStepStatuses.has(item.status) && !satisfiedStepStatuses.has(item.status))) {
278
393
  await advance(current => skip(current.steps[node.id]!), 'lifecycle.step.skipped', { nodeId: node.id }); return;
@@ -317,6 +432,38 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
317
432
  return;
318
433
  }
319
434
 
435
+ if (node.kind === 'signal') {
436
+ if (step.kind !== 'signal' || !['pending', 'waiting'].includes(step.status)) return;
437
+ if (step.status === 'waiting') {
438
+ const observedAtMs = now();
439
+ if (step.deadlineAtMs === null || observedAtMs < step.deadlineAtMs) return;
440
+ await advance(current => {
441
+ const target = current.steps[node.id];
442
+ if (!target || target.kind !== 'signal' || target.status !== 'waiting' || target.deadlineAtMs === null || observedAtMs < target.deadlineAtMs) return false;
443
+ target.status = 'timed_out'; current.status = 'running'; return true;
444
+ }, 'lifecycle.signal.timed_out', { nodeId: node.id, observedAtMs });
445
+ return;
446
+ }
447
+ let deadlineAtMs: number | null = null;
448
+ try { if (node.deadlineAtMs) deadlineAtMs = exactTimestamp(resolveBinding(node.deadlineAtMs, state.input, outputs(state))); }
449
+ catch { await advance(current => skip(current.steps[node.id]!), 'lifecycle.signal.invalid', { nodeId: node.id }); return; }
450
+ const observedAtMs = now();
451
+ // A signal kept from before the step started counts if it arrived before the deadline.
452
+ const decide = (target: Extract<WorkflowLifecycleStep, { kind: 'signal' }>): 'succeeded' | 'timed_out' | 'waiting' =>
453
+ target.signalId !== null ? (deadlineAtMs === null || target.receivedAtMs! < deadlineAtMs ? 'succeeded' : 'timed_out')
454
+ : deadlineAtMs !== null && observedAtMs >= deadlineAtMs ? 'timed_out' : 'waiting';
455
+ const next = decide(step);
456
+ await advance(current => {
457
+ const target = current.steps[node.id];
458
+ // A signal delivered since the read changes the decision: leave it to the next wave.
459
+ if (!target || target.kind !== 'signal' || target.status !== 'pending' || decide(target) !== next) return false;
460
+ target.deadlineAtMs = deadlineAtMs; target.status = next;
461
+ if (next === 'timed_out') clearSignal(target);
462
+ current.status = next === 'waiting' ? 'waiting' : 'running'; return true;
463
+ }, next === 'succeeded' ? 'lifecycle.signal.received' : `lifecycle.signal.${next}`, { nodeId: node.id });
464
+ return;
465
+ }
466
+
320
467
  if (node.kind === 'timer') {
321
468
  if (step.kind !== 'timer' || !['pending', 'waiting'].includes(step.status)) return;
322
469
  let fireAtMs: number;
@@ -349,7 +496,7 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
349
496
  if (node.kind === 'join') {
350
497
  step.output = dependencies.map(item => item.output); step.status = 'succeeded';
351
498
  try { await save(record, state, 'lifecycle.step.completed', { nodeId: node.id }); }
352
- catch (error) { if (!(error instanceof StorageError) || error.code !== 'CONFLICT') throw error; }
499
+ catch (error) { if (!(error instanceof StorageError) || error.storageCode !== 'CONFLICT') throw error; }
353
500
  return;
354
501
  }
355
502
  if (step.kind !== 'tool') return;
@@ -358,7 +505,7 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
358
505
  if (required.some(grant => !permissions.allow.includes(grant))) {
359
506
  step.status = 'blocked';
360
507
  try { await save(record, state, 'lifecycle.step.blocked', { nodeId: node.id, code: 'PERMISSION_DENIED' }); }
361
- catch (error) { if (!(error instanceof StorageError) || error.code !== 'CONFLICT') throw error; }
508
+ catch (error) { if (!(error instanceof StorageError) || error.storageCode !== 'CONFLICT') throw error; }
362
509
  return;
363
510
  }
364
511
  let input: JsonValue;
@@ -367,16 +514,16 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
367
514
  catch {
368
515
  step.status = 'failed';
369
516
  try { await save(record, state, 'lifecycle.step.failed', { nodeId: node.id, code: 'INVALID_INPUT' }); }
370
- catch (error) { if (!(error instanceof StorageError) || error.code !== 'CONFLICT') throw error; }
517
+ catch (error) { if (!(error instanceof StorageError) || error.storageCode !== 'CONFLICT') throw error; }
371
518
  return;
372
519
  }
373
520
  const observedAtMs = now(); const previousExpiry = step.approval?.expiresAt ?? 0;
374
521
  const reviewExpiry = node.approval ? (previousExpiry > observedAtMs ? previousExpiry : observedAtMs + approvalTtlMs) : null;
375
- const candidateHash = approvalCandidate(node, input, id, reviewExpiry);
522
+ const candidateHash = approvalCandidate(node, input, id, reviewExpiry, run.digest);
376
523
  if (node.approval && (step.status !== 'approved' || step.approval?.digest !== candidateHash || step.approval.expiresAt <= observedAtMs)) {
377
524
  step.status = 'waiting'; step.approval = { digest: candidateHash, expiresAt: reviewExpiry!, humanId: null }; state.status = 'waiting';
378
525
  try { await save(record, state, 'lifecycle.approval.requested', { nodeId: node.id, digest: candidateHash }); }
379
- catch (error) { if (!(error instanceof StorageError) || error.code !== 'CONFLICT') throw error; }
526
+ catch (error) { if (!(error instanceof StorageError) || error.storageCode !== 'CONFLICT') throw error; }
380
527
  return;
381
528
  }
382
529
  const affordable = (current: State): boolean => node.tool.costMicros <= current.maxCostMicros - current.spentMicros - current.reservedMicros;
@@ -394,7 +541,7 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
394
541
  state.reservedMicros += node.tool.costMicros; state.status = 'running';
395
542
  try { await save(record, state, 'lifecycle.step.dispatching', { nodeId: node.id, callId: step.callId }); }
396
543
  catch (error) {
397
- if (error instanceof StorageError && error.code === 'CONFLICT' && claimRetries < 32) return executeNode(id, definition, node, claimRetries + 1);
544
+ if (error instanceof StorageError && error.storageCode === 'CONFLICT' && claimRetries < 32) return executeNode(id, definition, node, claimRetries + 1);
398
545
  throw error;
399
546
  }
400
547
  const controller = new AbortController(); const activeKey = `${id}/${node.id}`; active.set(activeKey, controller);
@@ -404,9 +551,9 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
404
551
  budget: new Budget(node.tool.costMicros, 1), maxOutputBytes,
405
552
  beforeDispatch: async processed => {
406
553
  const current = stateFrom(await load(id)); const target = current.steps[node.id];
407
- if (!target || target.kind !== 'tool' || current.status !== 'running' || current.policy !== policy
554
+ if (!target || target.kind !== 'tool' || current.status !== 'running' || current.policy !== run.digest
408
555
  || target.status !== 'dispatching' || approvalCandidate(node, processed, id,
409
- node.approval ? target.approval!.expiresAt : null) !== candidateHash) throw new MayuraError('CONFLICT', 'Lifecycle dispatch candidate is no longer authorized.');
556
+ node.approval ? target.approval!.expiresAt : null, run.digest) !== candidateHash) throw new MayuraError('CONFLICT', 'Lifecycle dispatch candidate is no longer authorized.');
410
557
  if (node.approval && target.approval!.expiresAt <= now()) throw new MayuraError('PERMISSION_DENIED', 'Approval expired before dispatch.');
411
558
  },
412
559
  onExecutionReceipt: async (evidence, settlement) => {
@@ -450,13 +597,20 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
450
597
  return { requestDigest, deadlineAtMs, context, subjectDigest };
451
598
  };
452
599
 
453
- const verifyDefinition = (definition: AnyWorkflowLifecycle, record: StoredRecord, state: State): void => {
600
+ /** Checks the pinned definition and returns the settings the run was started with. */
601
+ function verifyDefinition(definition: AnyWorkflowLifecycle, record: StoredRecord, state: State): Pinned;
602
+ function verifyDefinition(definition: AnyWorkflowLifecycle, record: StoredRecord, state: State, anyPolicy: true): Pinned | undefined;
603
+ function verifyDefinition(definition: AnyWorkflowLifecycle, record: StoredRecord, state: State, anyPolicy = false): Pinned | undefined {
454
604
  assertWorkflowLifecycle(definition);
455
- if (record.definitionHash !== definition.digest || state.definition !== definition.digest || state.policy !== policy
456
- || state.maxCostMicros !== maxCostMicros) throw new MayuraError('CONFLICT', 'Lifecycle definition or policy changed; explicit migration/review is required.');
605
+ if (record.definitionHash !== definition.digest || state.definition !== definition.digest) {
606
+ throw new MayuraError('CONFLICT', 'Lifecycle definition changed; explicit migration/review is required.');
607
+ }
608
+ const run = pinnedTo(state);
609
+ if (run ? state.maxCostMicros !== run.maxCostMicros : !anyPolicy) throw unknownWorkflowPolicy();
457
610
  try { assertWorkflowLifecycleStateMatchesManifest(state, lifecycleManifest(definition)); }
458
611
  catch { throw new MayuraError('CONFLICT', 'Stored lifecycle steps do not match the pinned definition.'); }
459
- };
612
+ return run;
613
+ }
460
614
 
461
615
  const respondAs = async (definition: AnyWorkflowLifecycle, command: { readonly id: string; readonly nodeId: string;
462
616
  readonly requestDigest: string; readonly commandId: string; readonly value: unknown }, actor: WorkflowLifecycleVerifiedActor): Promise<WorkflowLifecycleSnapshot> => {
@@ -470,14 +624,14 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
470
624
  }
471
625
  const node = definition.nodes.find(candidate => candidate.id === command.nodeId);
472
626
  if (!node || node.kind !== 'human') throw new MayuraError('INVALID_INPUT', 'Human response node is not part of the lifecycle definition.');
473
- const before = await load(command.id); verifyDefinition(definition, before, stateFrom(before));
474
- const value = jsonValue(await controlled(() => validate(node.request.response, command.value, 'input')), { maxBytes: maxOutputBytes });
627
+ const before = await load(command.id); const run = verifyDefinition(definition, before, stateFrom(before));
628
+ const value = jsonValue(await controlled(() => validate(node.request.response, command.value, 'input')), { maxBytes: run.maxOutputBytes });
475
629
  const responseDigest = digest('mayura:human-response:v1', { requestDigest: command.requestDigest,
476
630
  commandId: command.commandId, actorId: actor.id, value });
477
631
  const observedAtMs = now();
478
632
  return publicSnapshot(await mutate(command.id, state => {
479
633
  const step = state.steps[command.nodeId];
480
- if (!step || step.kind !== 'human' || state.policy !== policy || step.requestDigest !== command.requestDigest) {
634
+ if (!step || step.kind !== 'human' || state.policy !== run.digest || step.requestDigest !== command.requestDigest) {
481
635
  throw new MayuraError('CONFLICT', 'Human request is stale or mismatched.');
482
636
  }
483
637
  if (step.status === 'succeeded') {
@@ -493,21 +647,24 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
493
647
  responseDigest, actorId: actor.id }));
494
648
  };
495
649
 
496
- return Object.freeze<WorkflowLifecycleRuntime>({
650
+ const submitUnder = async (under: Pinned, definition: AnyWorkflowLifecycle, command: LifecycleSubmission[1]): Promise<WorkflowLifecycleSnapshot> => {
651
+ ensureOpen(); assertWorkflowLifecycle(definition);
652
+ if (typeof command.idempotencyKey !== 'string' || command.idempotencyKey.length < 1 || command.idempotencyKey.length > 128) {
653
+ throw new MayuraError('INVALID_INPUT', 'A bounded lifecycle submission key is required.');
654
+ }
655
+ const inputSnapshot = freezeJson(jsonValue(command.input, { maxBytes: under.maxOutputBytes }));
656
+ const input = jsonValue(await controlled(() => validate(definition.input, inputSnapshot, 'input')), { maxBytes: under.maxOutputBytes });
657
+ const state = initialWorkflowLifecycleState(lifecycleManifest(definition), input, definition.digest, under.digest, under.maxCostMicros);
658
+ const id = digest('mayura:workflow-lifecycle-run-id:v1', { scope: scopeKey, submissionKey: command.idempotencyKey });
659
+ const created = await createSubmission(() => store.create({ scope: scopeKey, id, idempotencyKey: `lifecycle:${command.idempotencyKey}`,
660
+ definitionHash: definition.digest, state: jsonValue(state) as JsonObject, events: [{ type: 'lifecycle.run.created', data: {} }] }), 'workflow lifecycle run');
661
+ verifyDefinition(definition, created.record, stateFrom(created.record)); return publicSnapshot(created.record);
662
+ };
663
+
664
+ const runtime = Object.freeze<WorkflowLifecycleRuntime>({
497
665
  profile: 'lifecycle-v1',
498
- submit: async (definition, command) => {
499
- ensureOpen(); assertWorkflowLifecycle(definition);
500
- if (typeof command.idempotencyKey !== 'string' || command.idempotencyKey.length < 1 || command.idempotencyKey.length > 128) {
501
- throw new MayuraError('INVALID_INPUT', 'A bounded lifecycle submission key is required.');
502
- }
503
- const inputSnapshot = freezeJson(jsonValue(command.input, { maxBytes: maxOutputBytes }));
504
- const input = jsonValue(await controlled(() => validate(definition.input, inputSnapshot, 'input')), { maxBytes: maxOutputBytes });
505
- const state = initialWorkflowLifecycleState(lifecycleManifest(definition), input, definition.digest, policy, maxCostMicros);
506
- const id = digest('mayura:workflow-lifecycle-run-id:v1', { scope: scopeKey, submissionKey: command.idempotencyKey });
507
- const created = await storageCall(() => store.create({ scope: scopeKey, id, idempotencyKey: `lifecycle:${command.idempotencyKey}`,
508
- definitionHash: definition.digest, state: jsonValue(state) as JsonObject, events: [{ type: 'lifecycle.run.created', data: {} }] }));
509
- verifyDefinition(definition, created.record, stateFrom(created.record)); return publicSnapshot(created.record);
510
- },
666
+ // New runs always use the current settings.
667
+ submit: (definition, command) => submitUnder(currentPolicy, definition, command),
511
668
  inspect: async id => publicSnapshot(await load(id)),
512
669
  humanRequest: async (definition, id, nodeId) => {
513
670
  ensureOpen(); assertWorkflowLifecycle(definition);
@@ -526,15 +683,15 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
526
683
  approvalRequest: async (definition, id, nodeId) => {
527
684
  ensureOpen(); assertWorkflowLifecycle(definition);
528
685
  if (!nodePattern.test(nodeId)) throw new MayuraError('INVALID_INPUT', 'A lifecycle tool node ID is required.');
529
- const record = await load(id); const state = stateFrom(record); verifyDefinition(definition, record, state);
686
+ const record = await load(id); const state = stateFrom(record); const run = verifyDefinition(definition, record, state);
530
687
  const node = definition.nodes.find(candidate => candidate.id === nodeId);
531
688
  const step = state.steps[nodeId];
532
689
  if (!node || node.kind !== 'tool' || !step || step.kind !== 'tool') throw new MayuraError('NOT_FOUND', 'Lifecycle tool node was not found.');
533
690
  if (!node.approval || !step.approval || (step.status !== 'waiting' && step.status !== 'approved')) return undefined;
534
691
  // Rebuild the input exactly as preparation did; it must reproduce the persisted digest, or the evidence is refused.
535
692
  const input = jsonValue(await controlled(() => validate(node.tool.input, resolveBinding(node.input, state.input, outputs(state)), 'input'),
536
- node.tool.timeoutMs), { maxBytes: maxOutputBytes });
537
- if (approvalCandidate(node, input, id, step.approval.expiresAt) !== step.approval.digest) {
693
+ node.tool.timeoutMs), { maxBytes: run.maxOutputBytes });
694
+ if (approvalCandidate(node, input, id, step.approval.expiresAt, run.digest) !== step.approval.digest) {
538
695
  throw new MayuraError('CONFLICT', 'Persisted approval evidence does not match its definition.');
539
696
  }
540
697
  return freezeJson(jsonValue({ runId: id, nodeId, status: step.status, toolId: node.tool.id, toolVersion: node.tool.version, input,
@@ -549,18 +706,18 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
549
706
  // Each wave holds one drain admission until its effects and receipts settle.
550
707
  const release = gate.enter(); if (!release) return publicSnapshot(before);
551
708
  try { await Promise.all(definition.nodes.map(node => executeNode(id, definition, node))); } finally { release(); }
552
- let after = await load(id); const next = stateFrom(after); verifyDefinition(definition, after, next);
709
+ let after = await load(id); const next = stateFrom(after); const run = verifyDefinition(definition, after, next);
553
710
  const steps = Object.values(next.steps);
554
711
  if (!schedulable(next)) return publicSnapshot(after);
555
712
  if (steps.every(step => terminalStepStatuses.has(step.status))) {
556
713
  if (steps.every(step => satisfiedStepStatuses.has(step.status))) {
557
714
  try { next.output = jsonValue(await controlled(() => validate(definition.output,
558
- resolveBinding(definition.result, next.input, outputs(next)), 'output')), { maxBytes: maxOutputBytes }); next.status = 'succeeded'; }
715
+ resolveBinding(definition.result, next.input, outputs(next)), 'output')), { maxBytes: run.maxOutputBytes }); next.status = 'succeeded'; }
559
716
  catch { next.status = 'failed'; }
560
717
  } else next.status = steps.some(step => step.status === 'unknown') ? 'outcome_unknown'
561
718
  : steps.some(step => step.status === 'blocked') ? 'blocked' : 'failed';
562
719
  try { after = await save(after, next, 'lifecycle.run.completed', { status: next.status }); }
563
- catch (error) { if (!(error instanceof StorageError) || error.code !== 'CONFLICT') throw error; after = await load(id); }
720
+ catch (error) { if (!(error instanceof StorageError) || error.storageCode !== 'CONFLICT') throw error; after = await load(id); }
564
721
  return publicSnapshot(after);
565
722
  }
566
723
  if (after.version === before.version) {
@@ -568,7 +725,7 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
568
725
  if (waiting && next.status !== 'waiting') {
569
726
  next.status = 'waiting';
570
727
  try { after = await save(after, next, 'lifecycle.run.waiting'); }
571
- catch (error) { if (!(error instanceof StorageError) || error.code !== 'CONFLICT') throw error; after = await load(id); }
728
+ catch (error) { if (!(error instanceof StorageError) || error.storageCode !== 'CONFLICT') throw error; after = await load(id); }
572
729
  }
573
730
  return publicSnapshot(after);
574
731
  }
@@ -583,7 +740,8 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
583
740
  const human = await checkedHuman(command.credential, true); const observedAtMs = now();
584
741
  return publicSnapshot(await mutate(command.id, state => {
585
742
  const step = state.steps[command.nodeId];
586
- if (!step || step.kind !== 'tool' || state.policy !== policy || !step.approval || step.approval.digest !== command.digest) {
743
+ // The digest binds the run's own policy; a run under an unlisted policy has nothing approvable.
744
+ if (!step || step.kind !== 'tool' || !pinnedTo(state) || !step.approval || step.approval.digest !== command.digest) {
587
745
  throw new MayuraError('CONFLICT', 'Approval request is stale, expired or mismatched.');
588
746
  }
589
747
  if (step.status !== 'waiting' && step.approval.humanId === human.id) return false;
@@ -602,6 +760,48 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
602
760
  return respondAs(definition, command, { id: human.id, projectId: human.projectId });
603
761
  },
604
762
  respondVerified: (definition, command) => respondAs(definition, command, command.actor),
763
+ signal: async (definition, command) => {
764
+ ensureOpen(); assertWorkflowLifecycle(definition);
765
+ if (!command || typeof command.id !== 'string' || !hashPattern.test(command.id) || typeof command.name !== 'string' || !signalPattern.test(command.name)
766
+ || typeof command.signalId !== 'string' || !signalPattern.test(command.signalId)
767
+ || (command.actorId !== undefined && (typeof command.actorId !== 'string' || command.actorId.length < 1 || command.actorId.length > 256))) {
768
+ throw new MayuraError('INVALID_INPUT', 'A signal needs a run id, a signal name and a signal id (1–128 letters, digits, ".", "_", "/" or "-").');
769
+ }
770
+ const node = definition.nodes.find(candidate => candidate.kind === 'signal' && candidate.name === command.name);
771
+ if (!node || node.kind !== 'signal') throw new MayuraError('NOT_FOUND', `This workflow has no signal step named "${command.name}".`);
772
+ const before = await load(command.id); const run = verifyDefinition(definition, before, stateFrom(before));
773
+ let payload: JsonValue;
774
+ try { payload = jsonValue(await controlled(() => validate(node.payload, command.payload, 'input')), { maxBytes: run.maxOutputBytes }); }
775
+ catch (error) {
776
+ if (error instanceof MayuraError && ['TIMEOUT', 'LIMIT_EXCEEDED'].includes(error.code)) throw error;
777
+ throw new MayuraError('INVALID_INPUT', `The payload of signal "${command.name}" does not match the step's payload schema.`);
778
+ }
779
+ const payloadDigest = digest('mayura:workflow-signal:v1', { runId: command.id, nodeId: node.id, signalId: command.signalId, payload });
780
+ const receivedAtMs = now();
781
+ return publicSnapshot(await mutate(command.id, state => {
782
+ const step = state.steps[node.id];
783
+ if (!step || step.kind !== 'signal') throw new MayuraError('CONFLICT', 'Stored lifecycle steps do not match the pinned definition.');
784
+ if (step.signalId !== null) {
785
+ // Idempotent on the signal id: the same signal again changes nothing.
786
+ if (step.signalId === command.signalId && step.payloadDigest === payloadDigest) return false;
787
+ throw new MayuraError('CONFLICT', step.signalId === command.signalId
788
+ ? `Signal "${command.signalId}" was already delivered with a different payload.`
789
+ : `Signal step "${node.id}" already received signal "${step.signalId}"; a signal step accepts one signal.`);
790
+ }
791
+ if (finalRunStatuses.has(state.status)) throw new MayuraError('CONFLICT', `The run is ${state.status}; it no longer accepts signals.`);
792
+ if (step.status !== 'pending' && step.status !== 'waiting') {
793
+ throw new MayuraError('CONFLICT', `Signal step "${node.id}" is ${step.status}; it no longer accepts signals.`);
794
+ }
795
+ if (step.status === 'waiting' && step.deadlineAtMs !== null && receivedAtMs >= step.deadlineAtMs) {
796
+ throw new MayuraError('CONFLICT', `Signal step "${node.id}" passed its deadline; it no longer accepts signals.`);
797
+ }
798
+ step.signalId = command.signalId; step.payloadDigest = payloadDigest; step.receivedAtMs = receivedAtMs; step.output = payload;
799
+ // A step that has not started keeps the signal until it starts.
800
+ if (step.status === 'waiting') { step.status = 'succeeded'; if (state.status !== 'paused') state.status = 'running'; }
801
+ return true;
802
+ }, 'lifecycle.signal.delivered', { nodeId: node.id, signalId: command.signalId, payloadDigest,
803
+ ...(command.actorId === undefined ? {} : { actorId: command.actorId }) }));
804
+ },
605
805
  pause: async id => publicSnapshot(await mutate(id, state => {
606
806
  if (state.status === 'paused') return false;
607
807
  if (finalRunStatuses.has(state.status)) throw new MayuraError('CONFLICT', 'A terminal lifecycle workflow cannot be paused.');
@@ -613,12 +813,14 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
613
813
  migrate: async (migration, command) => {
614
814
  ensureOpen(); assertWorkflowMigration(migration); assertWorkflowLifecycle(migration.from); assertWorkflowLifecycle(migration.to);
615
815
  const { id, actorId, commandId, dryRun = false } = migrationCommand(command);
616
- const record = await load(id); const state = stateFrom(record); verifyDefinition(migration.from, record, state);
816
+ // A reviewed migration is the explicit way to move a run onto the current settings, whichever it started under.
817
+ const record = await load(id); const state = stateFrom(record); verifyDefinition(migration.from, record, state, true);
617
818
  const nodes = (definition: AnyWorkflowLifecycle) => lifecycleManifest(definition).graph.map(node =>
618
819
  ({ id: node.id, kind: node.kind, dependsOn: node.dependsOn, fingerprint: nodeFingerprint(node as unknown as Record<string, unknown>),
619
820
  ...(nodeEvidence(node) ? { evidence: nodeEvidence(node)! } : {}) }));
620
821
  const preconditions: MigrationBlocker[] = [];
621
822
  if (state.status !== 'paused') preconditions.push({ node: '*', reason: `The run is ${state.status}; pause it before migrating.` });
823
+ if (state.spentMicros > maxCostMicros) preconditions.push({ node: '*', reason: 'The run already spent more than the current maxCostMicros.' });
622
824
  const plan = planWorkflowMigration({ migration, format: 'lifecycle-v1', runId: id, fromDigest: migration.from.digest, toDigest: migration.to.digest,
623
825
  from: nodes(migration.from), to: nodes(migration.to), steps: Object.entries(state.steps).map(([step, value]) => ({ id: step, status: value.status })), preconditions });
624
826
  if (dryRun) return freezeJson(jsonValue({ plan })) as unknown as WorkflowMigrationResult<WorkflowLifecycleSnapshot>;
@@ -627,9 +829,11 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
627
829
  const steps: Record<string, WorkflowLifecycleStep> = {};
628
830
  for (const entry of plan.entries) {
629
831
  if (!entry.target) continue;
630
- steps[entry.target] = entry.action === 'keep' || entry.action === 'accept' ? state.steps[entry.source!]! : fresh.steps[entry.target]!;
832
+ const source = entry.source === undefined ? undefined : state.steps[entry.source];
833
+ steps[entry.target] = entry.action === 'keep' || entry.action === 'accept'
834
+ || (entry.action === 'update' && source?.kind === 'signal' && fresh.steps[entry.target]!.kind === 'signal') ? source! : fresh.steps[entry.target]!;
631
835
  }
632
- const next: State = { ...state, definition: migration.to.digest,
836
+ const next: State = { ...state, definition: migration.to.digest, policy, maxCostMicros,
633
837
  steps: Object.fromEntries(migration.to.nodes.map(node => [node.id, steps[node.id]!])) };
634
838
  // Released holds: only carried tool steps keep reserved cost.
635
839
  next.reservedMicros = Object.values(next.steps).reduce((sum, step) => sum + (step.kind === 'tool' ? step.costReserved : 0), 0);
@@ -670,4 +874,10 @@ export function createWorkflowLifecycleRuntime(options: WorkflowLifecycleRuntime
670
874
  close: () => { closed = true; for (const controller of active.values()) controller.abort(); },
671
875
  drain: options => gate.drain(options, () => { closed = true; for (const controller of active.values()) controller.abort(); }),
672
876
  });
877
+ pinnedSubmissions.set(runtime, (index, definition, command) => {
878
+ const under = policies[index];
879
+ if (!Number.isSafeInteger(index) || !under) throw new MayuraError('INVALID_INPUT', 'The requested lifecycle policy is not configured.');
880
+ return submitUnder(under, definition, command);
881
+ });
882
+ return runtime;
673
883
  }