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,4 +1,4 @@
1
- import type { JsonObject } from '@mayura/core';
1
+ import { MayuraError, type ErrorCode, type JsonObject } from '@mayura/core';
2
2
 
3
3
  /** An append-only event whose sequence and time are assigned by the store. */
4
4
  export interface StoredEventInput { readonly type: string; readonly data: JsonObject }
@@ -55,15 +55,39 @@ export interface AggregateStore {
55
55
  close(): Promise<void>;
56
56
  }
57
57
 
58
+ /** The exact storage condition behind a `StorageError`; its `code` is the general `ErrorCode` this maps to. */
58
59
  export type StorageErrorCode =
59
60
  | 'INVALID_INPUT' | 'CONFLICT' | 'NOT_FOUND' | 'STORAGE_UNAVAILABLE'
60
61
  | 'STORE_CLOSED' | 'STORE_NOT_INITIALIZED' | 'QUEUE_FULL' | 'STALE_CLAIM' | 'LIMIT_EXCEEDED'
61
62
  | 'SCHEDULED_WRITER_REQUIRED';
62
63
 
63
- /** Stable errors intentionally omit driver messages, SQL and connection credentials. */
64
- export class StorageError extends Error {
65
- override readonly name = 'StorageError';
66
- constructor(readonly code: StorageErrorCode, message: string) { super(message); }
64
+ /**
65
+ * The general code of each storage condition: a closed store is unavailable, a store used before `initialize()` is a
66
+ * configuration error, a full queue is a limit, and a lost claim or a run owned by its scheduled writer is a conflict.
67
+ */
68
+ const generalCodes: Readonly<Record<StorageErrorCode, ErrorCode>> = Object.freeze({
69
+ INVALID_INPUT: 'INVALID_INPUT', CONFLICT: 'CONFLICT', NOT_FOUND: 'NOT_FOUND', STORAGE_UNAVAILABLE: 'STORAGE_UNAVAILABLE',
70
+ STORE_CLOSED: 'STORAGE_UNAVAILABLE', STORE_NOT_INITIALIZED: 'INVALID_CONFIG', QUEUE_FULL: 'LIMIT_EXCEEDED',
71
+ STALE_CLAIM: 'CONFLICT', LIMIT_EXCEEDED: 'LIMIT_EXCEEDED', SCHEDULED_WRITER_REQUIRED: 'CONFLICT',
72
+ });
73
+
74
+ /**
75
+ * A storage failure. It is a `MayuraError`, so one `catch` handles storage and workflow failures alike: `code` is the
76
+ * general code every Mayura API uses (`CONFLICT`, `NOT_FOUND`, `LIMIT_EXCEEDED`, ...) and `storageCode` names the exact
77
+ * storage condition (for example `STALE_CLAIM` behind `CONFLICT`). Messages never contain driver text, SQL or
78
+ * connection credentials.
79
+ */
80
+ export class StorageError extends MayuraError {
81
+ readonly storageCode: StorageErrorCode;
82
+ constructor(code: StorageErrorCode, message: string) {
83
+ super(Object.hasOwn(generalCodes, code) ? generalCodes[code] : 'STORAGE_UNAVAILABLE', message);
84
+ this.storageCode = Object.hasOwn(generalCodes, code) ? code : 'STORAGE_UNAVAILABLE';
85
+ }
86
+ }
87
+
88
+ /** Whether `error` is a storage failure with this exact storage condition. */
89
+ export function isStorageError(error: unknown, code: StorageErrorCode): error is StorageError {
90
+ return error instanceof StorageError && error.storageCode === code;
67
91
  }
68
92
 
69
93
  export function storageError(error: unknown): StorageError {
@@ -14,4 +14,6 @@ export * from './workflow-format5.js';
14
14
  export * from './workflow-saga-format1.js';
15
15
  export * from './workflow-loop-format1.js';
16
16
  export * from './submission-journal.js';
17
+ export * from './run-records.js';
17
18
  export * from './memory-contracts.js';
19
+ export { schemaDigest } from './schema-digest.js';
@@ -301,7 +301,7 @@ export function memoryIndexResult(method: MemoryIndexMethod, value: unknown, com
301
301
  return snapshot(({ records: integer(result['records']), edges: integer(result['edges']), sequence: integer(result['sequence']) }));
302
302
  }
303
303
  }
304
- } catch (error) { if (error instanceof StorageError && error.code !== 'INVALID_INPUT') throw error; return corrupt(); }
304
+ } catch (error) { if (error instanceof StorageError && error.storageCode !== 'INVALID_INPUT') throw error; return corrupt(); }
305
305
  return corrupt();
306
306
  }
307
307
 
@@ -0,0 +1,365 @@
1
+ import { jsonValue, MayuraError, type JsonObject, type JsonValue, type RunEvent } from '@mayura/core';
2
+ import { StorageError, type AggregateStore, type StoredRecord } from './contracts.js';
3
+ import { workflowHashMaterial } from './workflow-format2.js';
4
+
5
+ export type RunRecordStatus = 'running' | 'succeeded' | 'failed' | 'blocked' | 'cancelled' | 'outcome_unknown';
6
+ /** Structurally matches `RunRecordView` in mayura/server. */
7
+ export interface RunRecordView {
8
+ readonly runId: string; readonly agentId: string; readonly replicaId: string; readonly status: RunRecordStatus;
9
+ readonly leaseExpiresAtMs: number; readonly cancelRequested: boolean; readonly lastSequence: number;
10
+ readonly snapshot: JsonObject; readonly outcome?: JsonObject;
11
+ }
12
+ export type RunRecordClaim = { readonly status: 'claimed' }
13
+ | { readonly status: 'existing'; readonly digest: string; readonly runId: string | null; readonly claimedAtMs: number };
14
+ /** Structurally matches `AgentServerOptions.runRecords`; the server package does not depend on storage. */
15
+ export interface RunRecords {
16
+ claim(input: { readonly owner: string; readonly key: string; readonly digest: string; readonly replicaId: string; readonly nowMs: number; readonly signal?: AbortSignal }): Promise<RunRecordClaim>;
17
+ release(input: { readonly owner: string; readonly key: string; readonly replicaId: string; readonly signal?: AbortSignal }): Promise<void>;
18
+ start(input: { readonly owner: string; readonly key: string; readonly runId: string; readonly agentId: string; readonly replicaId: string;
19
+ readonly leaseExpiresAtMs: number; readonly snapshot: JsonObject; readonly signal?: AbortSignal }): Promise<void>;
20
+ update(input: { readonly owner: string; readonly runId: string; readonly replicaId: string; readonly events: readonly RunEvent[]; readonly snapshot: JsonObject;
21
+ readonly leaseExpiresAtMs: number; readonly outcome?: JsonObject; readonly signal?: AbortSignal })
22
+ : Promise<{ readonly status: 'written'; readonly cancelRequested: boolean } | { readonly status: 'lost' }>;
23
+ read(input: { readonly owner: string; readonly runId: string; readonly signal?: AbortSignal }): Promise<RunRecordView | null>;
24
+ events(input: { readonly owner: string; readonly runId: string; readonly after: number; readonly limit: number; readonly signal?: AbortSignal }): Promise<readonly RunEvent[]>;
25
+ requestCancel(input: { readonly owner: string; readonly runId: string; readonly signal?: AbortSignal }): Promise<RunRecordView | null>;
26
+ abandon(input: { readonly owner: string; readonly runId: string; readonly nowMs: number; readonly signal?: AbortSignal }): Promise<RunRecordView | null>;
27
+ }
28
+ export interface AggregateRunRecordOptions {
29
+ /** Most events kept per run (default 2,048, at least 16). Later events are summarized by one `events.gap` before `run.completed`. */
30
+ readonly maxEvents?: number;
31
+ }
32
+
33
+ const encoder = new TextEncoder();
34
+ async function sha256(domain: string, value: unknown): Promise<string> {
35
+ const bytes = await crypto.subtle.digest('SHA-256', encoder.encode(workflowHashMaterial(domain, value)));
36
+ return [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, '0')).join('');
37
+ }
38
+ async function digestText(text: string): Promise<string> {
39
+ const bytes = await crypto.subtle.digest('SHA-256', encoder.encode(text));
40
+ return [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, '0')).join('');
41
+ }
42
+ const runIdPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
43
+ const identifier = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
44
+ const replicaPattern = /^[A-Za-z0-9._:-]{1,128}$/;
45
+ const statuses = new Set<RunRecordStatus>(['running', 'succeeded', 'failed', 'blocked', 'cancelled', 'outcome_unknown']);
46
+ const eventTypes = new Set(['run.started', 'model.started', 'model.completed', 'tool.started', 'tool.completed', 'hook.started', 'hook.completed',
47
+ 'step.started', 'step.completed', 'delegate.started', 'delegate.completed', 'run.completed', 'events.gap', 'output.delta', 'output.withheld']);
48
+ /** Outcomes up to this size live in the run record; larger ones in chunk events of a companion aggregate. */
49
+ const inlineOutcomeBytes = 262_144; const maxOutcomeBytes = 16_777_216; const chunkChars = 16_384; const chunksPerWrite = 16;
50
+ /** One record write carries at most this much event data, well inside the store's one-MiB transaction bound. */
51
+ const maxBatchBytes = 786_432; const maxGaps = 64;
52
+
53
+ interface RunState {
54
+ readonly format: 1; readonly kind: 'run'; readonly runId: string; readonly agentId: string; readonly replicaId: string; readonly status: RunRecordStatus;
55
+ readonly leaseExpiresAtMs: number; readonly cancelRequested: boolean; readonly snapshot: JsonObject;
56
+ /** Run sequence of the last event received, stored or not. */
57
+ readonly lastSequence: number;
58
+ /** Aggregate events written; each holds one run event, and a gap event stands for several sequences. */
59
+ readonly stored: number; readonly gaps: readonly (readonly [number, number])[];
60
+ /** First run sequence not stored because the event bound was reached; summarized as a gap when the run ends. */
61
+ readonly truncatedFrom: number | null;
62
+ readonly outcome: JsonObject | null; readonly outcomeRef: { readonly bytes: number; readonly digest: string } | null;
63
+ }
64
+ interface ClaimState {
65
+ readonly format: 1; readonly kind: 'claim'; readonly digest: string; readonly runId: string | null; readonly claimedAtMs: number;
66
+ readonly replicaId: string; readonly released: boolean;
67
+ }
68
+ function integrity(): never { throw new MayuraError('STORAGE_UNAVAILABLE', 'Stored run record failed integrity validation.'); }
69
+ function invalid(message: string): never { throw new MayuraError('INVALID_INPUT', message); }
70
+ function owner(value: unknown): string { if (typeof value !== 'string' || value.length < 1 || value.length > 4_096) invalid('A run record requires a bounded owner.'); return value; }
71
+ function runId(value: unknown): string { if (typeof value !== 'string' || !runIdPattern.test(value)) invalid('A run record requires a run id.'); return value; }
72
+ function replica(value: unknown): string { if (typeof value !== 'string' || !replicaPattern.test(value)) invalid('A run record requires a replica id.'); return value; }
73
+ function time(value: unknown): number { if (!Number.isSafeInteger(value) || (value as number) < 0) invalid('A run record time must be a nonnegative integer.'); return value as number; }
74
+ function snapshotOf(value: unknown, id: string): JsonObject {
75
+ let copy: JsonValue; try { copy = jsonValue(value, { maxBytes: 786_432 }); } catch { return invalid('A run snapshot must be bounded JSON.'); }
76
+ if (copy === null || typeof copy !== 'object' || Array.isArray(copy) || copy['id'] !== id || !statuses.has(copy['status'] as RunRecordStatus)
77
+ || Object.keys(copy).some(key => !['id', 'status', 'budget', 'evidence'].includes(key))) invalid('A run snapshot has an unexpected shape.');
78
+ return copy;
79
+ }
80
+ function claimState(record: StoredRecord): ClaimState {
81
+ const state = record.state;
82
+ if (state['format'] !== 1 || state['kind'] !== 'claim' || typeof state['digest'] !== 'string' || !/^[a-f0-9]{64}$/.test(state['digest'])
83
+ || (state['runId'] !== null && (typeof state['runId'] !== 'string' || !runIdPattern.test(state['runId'])))
84
+ || !Number.isSafeInteger(state['claimedAtMs']) || typeof state['replicaId'] !== 'string' || typeof state['released'] !== 'boolean') integrity();
85
+ return state as unknown as ClaimState;
86
+ }
87
+ function runState(record: StoredRecord, id: string): RunState {
88
+ const state = record.state; const gaps = state['gaps']; const ref = state['outcomeRef'];
89
+ if (state['format'] !== 1 || state['kind'] !== 'run' || state['runId'] !== id || typeof state['agentId'] !== 'string' || typeof state['replicaId'] !== 'string'
90
+ || !statuses.has(state['status'] as RunRecordStatus) || !Number.isSafeInteger(state['leaseExpiresAtMs']) || typeof state['cancelRequested'] !== 'boolean'
91
+ || state['snapshot'] === null || typeof state['snapshot'] !== 'object' || Array.isArray(state['snapshot'])
92
+ || !Number.isSafeInteger(state['lastSequence']) || !Number.isSafeInteger(state['stored']) || !Array.isArray(gaps) || gaps.length > maxGaps + 1
93
+ || gaps.some(gap => !Array.isArray(gap) || gap.length !== 2 || !Number.isSafeInteger(gap[0]) || !Number.isSafeInteger(gap[1]))
94
+ || (state['truncatedFrom'] !== null && !Number.isSafeInteger(state['truncatedFrom']))
95
+ || (state['outcome'] !== null && (typeof state['outcome'] !== 'object' || Array.isArray(state['outcome'])))
96
+ || (ref !== null && (typeof ref !== 'object' || Array.isArray(ref) || !Number.isSafeInteger(ref['bytes']) || typeof ref['digest'] !== 'string'))
97
+ || ((state['status'] === 'running') !== (state['outcome'] === null && ref === null))) integrity();
98
+ return state as unknown as RunState;
99
+ }
100
+ function eventData(event: RunEvent): JsonObject {
101
+ return { sequence: event.sequence, timestamp: event.timestamp, metadata: event.metadata as JsonObject };
102
+ }
103
+
104
+ /**
105
+ * Durable agent run records for `AgentServerOptions.runRecords`, on any aggregate store (SQLite or PostgreSQL). Every
106
+ * owner's records live under a scope derived from it, so one caller can never read another's runs. Records are
107
+ * permanent, like submission claims: each keeps the run's snapshot, at most `maxEvents` content-free metadata events
108
+ * and its outcome.
109
+ */
110
+ export function createAggregateRunRecords(store: AggregateStore, options: AggregateRunRecordOptions = {}): RunRecords {
111
+ if (!store || typeof store.create !== 'function' || typeof store.update !== 'function' || typeof store.events !== 'function')
112
+ throw new MayuraError('INVALID_CONFIG', 'Run records require an aggregate store.');
113
+ const maxEvents = options.maxEvents ?? 2_048;
114
+ if (!Number.isSafeInteger(maxEvents) || maxEvents < 16 || maxEvents > 65_536) throw new MayuraError('INVALID_CONFIG', 'maxEvents must be an integer from 16 to 65,536.');
115
+ let definitionHash: Promise<string> | undefined;
116
+ const format = (): Promise<string> => (definitionHash ??= sha256('mayura:run-records-format:v1', {}));
117
+ const scopeOf = (value: string): Promise<string> => sha256('mayura:run-records-scope:v1', { owner: value });
118
+ const claimId = (value: string, key: string): Promise<string> => sha256('mayura:run-records-claim:v1', { owner: value, key });
119
+ /** Compare-and-set with a bounded number of fresh attempts: concurrent writers are cancel requests and abandonment. */
120
+ const retrying = async <T>(signal: AbortSignal | undefined, attempt: () => Promise<T>): Promise<T> => {
121
+ for (let tries = 0; ; tries++) {
122
+ signal?.throwIfAborted();
123
+ try { return await attempt(); } catch (error) { if (!(error instanceof StorageError) || error.code !== 'CONFLICT' || tries >= 8) throw error; }
124
+ }
125
+ };
126
+ const readRun = async (scope: string, id: string): Promise<{ record: StoredRecord; state: RunState } | null> => {
127
+ const record = await store.read(scope, `run:${id}`); return record ? { record, state: runState(record, id) } : null;
128
+ };
129
+ const outcomeOf = async (scope: string, state: RunState): Promise<JsonObject | undefined> => {
130
+ if (state.outcome) return state.outcome;
131
+ if (!state.outcomeRef) return undefined;
132
+ const id = `outcome:${state.runId}`; let text = ''; let after = 0;
133
+ for (;;) {
134
+ const page = await store.events(scope, id, after);
135
+ for (const event of page) { const chunk = event.data['text']; if (typeof chunk !== 'string') integrity(); text += chunk; after = event.sequence; }
136
+ if (page.length < 1_000) break;
137
+ }
138
+ if (encoder.encode(text).byteLength !== state.outcomeRef.bytes || await digestText(text) !== state.outcomeRef.digest) integrity();
139
+ let parsed: unknown; try { parsed = JSON.parse(text); } catch { return integrity(); }
140
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) integrity();
141
+ return parsed as JsonObject;
142
+ };
143
+ const view = async (scope: string, state: RunState): Promise<RunRecordView> => {
144
+ const outcome = await outcomeOf(scope, state);
145
+ return Object.freeze({ runId: state.runId, agentId: state.agentId, replicaId: state.replicaId, status: state.status, leaseExpiresAtMs: state.leaseExpiresAtMs,
146
+ cancelRequested: state.cancelRequested, lastSequence: state.lastSequence, snapshot: state.snapshot, ...(outcome ? { outcome } : {}) });
147
+ };
148
+ /** Store a large outcome as ordered chunk events of its own aggregate; a retried write continues where it stopped. */
149
+ const storeOutcome = async (scope: string, id: string, text: string): Promise<{ bytes: number; digest: string }> => {
150
+ const bytes = encoder.encode(text).byteLength; const digest = await digestText(text); const hash = await format();
151
+ const chunks: string[] = []; for (let index = 0; index < text.length; index += chunkChars) chunks.push(text.slice(index, index + chunkChars));
152
+ const aggregate = `outcome:${id}`; let record = await store.read(scope, aggregate);
153
+ if (!record) {
154
+ const created = await store.create({ scope, id: aggregate, idempotencyKey: aggregate, definitionHash: hash, state: { format: 1, digest, written: Math.min(chunks.length, chunksPerWrite) },
155
+ events: chunks.slice(0, chunksPerWrite).map(chunk => ({ type: 'outcome.chunk', data: { text: chunk } })) });
156
+ record = created.record;
157
+ }
158
+ // An earlier, interrupted attempt for a different outcome cannot be completed with this one.
159
+ if (record.state['digest'] !== digest || !Number.isSafeInteger(record.state['written'])) integrity();
160
+ while ((record.state['written'] as number) < chunks.length) {
161
+ const written = record.state['written'] as number; const next = chunks.slice(written, written + chunksPerWrite);
162
+ record = await store.update({ scope, id: aggregate, expectedVersion: record.version, state: { format: 1, digest, written: written + next.length },
163
+ events: next.map(chunk => ({ type: 'outcome.chunk', data: { text: chunk } })) });
164
+ }
165
+ return { bytes, digest };
166
+ };
167
+
168
+ return Object.freeze<RunRecords>({
169
+ async claim(input) {
170
+ const who = owner(input?.owner); replica(input.replicaId); time(input.nowMs);
171
+ if (typeof input.key !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(input.key) || typeof input.digest !== 'string' || !/^[a-f0-9]{64}$/.test(input.digest))
172
+ invalid('A submission claim requires a bounded key and a request digest.');
173
+ input.signal?.throwIfAborted();
174
+ const scope = await scopeOf(who); const id = await claimId(who, input.key);
175
+ const fresh = { format: 1, kind: 'claim', digest: input.digest, runId: null, claimedAtMs: input.nowMs, replicaId: input.replicaId, released: false };
176
+ return retrying(input.signal, async () => {
177
+ const existing = await store.read(scope, id);
178
+ if (!existing) {
179
+ try {
180
+ const created = await store.create({ scope, id, idempotencyKey: id, definitionHash: await format(), state: fresh, events: [{ type: 'submission.claimed', data: {} }] });
181
+ if (created.created) return { status: 'claimed' as const };
182
+ } catch (error) { if (!(error instanceof StorageError) || error.code !== 'CONFLICT') throw error; }
183
+ const winner = claimState((await store.read(scope, id)) ?? integrity());
184
+ return { status: 'existing' as const, digest: winner.digest, runId: winner.runId, claimedAtMs: winner.claimedAtMs };
185
+ }
186
+ const state = claimState(existing);
187
+ if (state.released) {
188
+ // A claim given back before its run started: the next claimant takes it over atomically.
189
+ await store.update({ scope, id, expectedVersion: existing.version, state: fresh, events: [{ type: 'submission.claimed', data: {} }] });
190
+ return { status: 'claimed' as const };
191
+ }
192
+ return { status: 'existing' as const, digest: state.digest, runId: state.runId, claimedAtMs: state.claimedAtMs };
193
+ });
194
+ },
195
+ async release(input) {
196
+ const who = owner(input?.owner); replica(input.replicaId);
197
+ if (typeof input.key !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(input.key)) invalid('A submission release requires its key.');
198
+ const scope = await scopeOf(who); const id = await claimId(who, input.key);
199
+ await retrying(input.signal, async () => {
200
+ const existing = await store.read(scope, id); if (!existing) return;
201
+ const state = claimState(existing);
202
+ // Only the claimant may give back a claim, and only before its run was bound.
203
+ if (state.replicaId !== input.replicaId || state.runId !== null || state.released) return;
204
+ await store.update({ scope, id, expectedVersion: existing.version, state: { ...state, released: true }, events: [{ type: 'submission.released', data: {} }] });
205
+ });
206
+ },
207
+ async start(input) {
208
+ const who = owner(input?.owner); const id = runId(input.runId); replica(input.replicaId); time(input.leaseExpiresAtMs);
209
+ if (typeof input.agentId !== 'string' || !identifier.test(input.agentId)) invalid('A run record requires an agent id.');
210
+ if (typeof input.key !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(input.key)) invalid('A run record requires its submission key.');
211
+ const snapshot = snapshotOf(input.snapshot, id); input.signal?.throwIfAborted();
212
+ const scope = await scopeOf(who); const hash = await format();
213
+ const state: RunState = { format: 1, kind: 'run', runId: id, agentId: input.agentId, replicaId: input.replicaId, status: 'running',
214
+ leaseExpiresAtMs: input.leaseExpiresAtMs, cancelRequested: false, snapshot: { ...snapshot, status: 'running' }, lastSequence: 0, stored: 0, gaps: [],
215
+ truncatedFrom: null, outcome: null, outcomeRef: null };
216
+ const created = await store.create({ scope, id: `run:${id}`, idempotencyKey: `run:${id}`, definitionHash: hash, state: state as unknown as JsonObject, events: [] });
217
+ if (!created.created && (created.record.state['replicaId'] !== input.replicaId || created.record.state['kind'] !== 'run')) integrity();
218
+ // Bind the submission key to the run, so every replica can replay it.
219
+ const claim = await claimId(who, input.key);
220
+ await retrying(input.signal, async () => {
221
+ const existing = await store.read(scope, claim); if (!existing) integrity();
222
+ const current = claimState(existing);
223
+ if (current.runId === id) return;
224
+ if (current.runId !== null || current.replicaId !== input.replicaId || current.released) integrity();
225
+ await store.update({ scope, id: claim, expectedVersion: existing.version, state: { ...current, runId: id }, events: [{ type: 'submission.started', data: {} }] });
226
+ });
227
+ },
228
+ async update(input) {
229
+ const who = owner(input?.owner); const id = runId(input.runId); replica(input.replicaId); time(input.leaseExpiresAtMs);
230
+ const snapshot = snapshotOf(input.snapshot, id);
231
+ if (!Array.isArray(input.events) || input.events.length > 1_000) invalid('A run record update carries at most 1,000 events.');
232
+ let outcomeText: string | undefined;
233
+ if (input.outcome !== undefined) {
234
+ try { outcomeText = JSON.stringify(jsonValue(input.outcome, { maxBytes: maxOutcomeBytes })); } catch { invalid('A run outcome must be JSON of at most 16 MiB.'); }
235
+ if (!statuses.has(input.outcome['status'] as RunRecordStatus) || input.outcome['status'] === 'running') invalid('A run outcome needs a final status.');
236
+ }
237
+ input.signal?.throwIfAborted();
238
+ const scope = await scopeOf(who);
239
+ // Events are written in batches that fit one transaction; the outcome goes with the last batch.
240
+ let remaining = [...input.events]; let cancelRequested = false;
241
+ do {
242
+ let bytes = 0; let count = 0;
243
+ while (count < remaining.length) {
244
+ bytes += encoder.encode(JSON.stringify(eventData(remaining[count]!))).byteLength + 64;
245
+ if (count > 0 && bytes > maxBatchBytes) break; count++;
246
+ }
247
+ const batch = remaining.slice(0, count); remaining = remaining.slice(count); const final = remaining.length === 0 && outcomeText !== undefined;
248
+ const ref = final && encoder.encode(outcomeText!).byteLength > inlineOutcomeBytes ? await storeOutcome(scope, id, outcomeText!) : null;
249
+ const result = await retrying(input.signal, async () => {
250
+ const current = await readRun(scope, id);
251
+ if (!current) integrity();
252
+ if (current.state.replicaId !== input.replicaId || current.state.status !== 'running') return 'lost' as const;
253
+ let { lastSequence, stored, truncatedFrom } = current.state; const gaps = current.state.gaps.map(gap => [gap[0], gap[1]] as [number, number]);
254
+ const appended: { type: string; data: JsonObject }[] = [];
255
+ const keep = (event: RunEvent): void => { appended.push({ type: event.type, data: eventData(event) }); stored++; };
256
+ for (const event of batch) {
257
+ const gap = event?.type === 'events.gap';
258
+ if (!event || event.runId !== id || !eventTypes.has(event.type) || !Number.isSafeInteger(event.sequence) || typeof event.timestamp !== 'string' || event.timestamp.length > 64
259
+ || event.metadata === null || typeof event.metadata !== 'object' || (gap ? event.metadata['from'] !== lastSequence + 1 || event.metadata['to'] !== event.sequence || event.sequence <= lastSequence
260
+ : event.sequence !== lastSequence + 1)) invalid('Run events must continue the recorded sequence.');
261
+ let size = 0; try { size = encoder.encode(JSON.stringify(jsonValue(event.metadata, { maxBytes: 16_384 }))).byteLength; } catch { size = Infinity; }
262
+ const from = gap ? event.metadata['from'] as number : event.sequence;
263
+ // Two slots stay free for the closing gap and run.completed, so a truncated history still ends truthfully.
264
+ const room = truncatedFrom === null && size <= 16_384 && stored < maxEvents - 2 && (!gap || gaps.length < maxGaps);
265
+ if (event.type === 'run.completed' && truncatedFrom !== null) {
266
+ if (truncatedFrom <= event.sequence - 1) {
267
+ gaps.push([truncatedFrom, event.sequence - 1]);
268
+ keep({ runId: id, sequence: event.sequence - 1, timestamp: event.timestamp, type: 'events.gap', metadata: { from: truncatedFrom, to: event.sequence - 1 } });
269
+ }
270
+ truncatedFrom = null; keep(event);
271
+ } else if (room || (event.type === 'run.completed' && stored < maxEvents)) { if (gap) gaps.push([from, event.sequence]); keep(event); }
272
+ else if (truncatedFrom === null) truncatedFrom = from;
273
+ lastSequence = event.sequence;
274
+ }
275
+ let status: RunRecordStatus = 'running'; let outcome: JsonObject | null = null;
276
+ if (final) {
277
+ status = input.outcome!['status'] as RunRecordStatus;
278
+ // A history that never reached run.completed still ends with a gap for what was not kept.
279
+ if (truncatedFrom !== null && truncatedFrom <= lastSequence) {
280
+ gaps.push([truncatedFrom, lastSequence]);
281
+ keep({ runId: id, sequence: lastSequence, timestamp: new Date().toISOString(), type: 'events.gap', metadata: { from: truncatedFrom, to: lastSequence } });
282
+ truncatedFrom = null;
283
+ }
284
+ if (!ref) outcome = JSON.parse(outcomeText!) as JsonObject;
285
+ }
286
+ const state: RunState = { ...current.state, leaseExpiresAtMs: input.leaseExpiresAtMs, snapshot: { ...snapshot, status: final ? status : 'running' },
287
+ lastSequence, stored, gaps, truncatedFrom, status, outcome, outcomeRef: final ? ref : null };
288
+ await store.update({ scope, id: `run:${id}`, expectedVersion: current.record.version, state: state as unknown as JsonObject, events: appended });
289
+ return current.state.cancelRequested;
290
+ });
291
+ if (result === 'lost') return { status: 'lost' as const };
292
+ cancelRequested = result;
293
+ } while (remaining.length > 0);
294
+ return { status: 'written' as const, cancelRequested };
295
+ },
296
+ async read(input) {
297
+ const scope = await scopeOf(owner(input?.owner)); const id = runId(input.runId); input.signal?.throwIfAborted();
298
+ const current = await readRun(scope, id); return current ? view(scope, current.state) : null;
299
+ },
300
+ async events(input) {
301
+ const scope = await scopeOf(owner(input?.owner)); const id = runId(input.runId);
302
+ if (!Number.isSafeInteger(input.after) || input.after < 0 || !Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 1_000) invalid('Event reads need a cursor and a limit from 1 to 1,000.');
303
+ input.signal?.throwIfAborted();
304
+ const current = await readRun(scope, id); if (!current) return [];
305
+ // Map the run sequence to the aggregate position: each stored gap stands for (to - from + 1) sequences in one slot.
306
+ let shift = 0; let position: number | undefined;
307
+ for (const [from, to] of current.state.gaps) {
308
+ if (to <= input.after) shift += to - from;
309
+ else if (from <= input.after) { position = from - 1 - shift; break; }
310
+ else break;
311
+ }
312
+ position = Math.min(position ?? input.after - shift, current.state.stored);
313
+ const page = await store.events(scope, `run:${id}`, position);
314
+ const result: RunEvent[] = [];
315
+ for (const stored of page.slice(0, input.limit)) {
316
+ const data = stored.data; const sequence = data['sequence']; const metadata = data['metadata'];
317
+ if (!Number.isSafeInteger(sequence) || typeof data['timestamp'] !== 'string' || metadata === null || typeof metadata !== 'object' || Array.isArray(metadata)
318
+ || !eventTypes.has(stored.type)) integrity();
319
+ let item: RunEvent = Object.freeze({ runId: id, sequence: sequence as number, timestamp: data['timestamp'], type: stored.type as RunEvent['type'],
320
+ metadata: Object.freeze({ ...(metadata as Record<string, string | number | boolean>) }) });
321
+ // A reader that stopped inside a gap sees the rest of that gap from its own position.
322
+ if (result.length === 0 && item.type === 'events.gap' && (item.metadata['from'] as number) <= input.after) {
323
+ if (item.sequence <= input.after) continue;
324
+ item = Object.freeze({ ...item, metadata: Object.freeze({ from: input.after + 1, to: item.sequence }) });
325
+ }
326
+ if (item.sequence <= input.after) continue;
327
+ result.push(item);
328
+ }
329
+ return Object.freeze(result);
330
+ },
331
+ async requestCancel(input) {
332
+ const scope = await scopeOf(owner(input?.owner)); const id = runId(input.runId);
333
+ return retrying(input.signal, async () => {
334
+ const current = await readRun(scope, id); if (!current) return null;
335
+ if (current.state.status !== 'running' || current.state.cancelRequested) return view(scope, current.state);
336
+ const state = { ...current.state, cancelRequested: true };
337
+ await store.update({ scope, id: `run:${id}`, expectedVersion: current.record.version, state: state as unknown as JsonObject, events: [] });
338
+ return view(scope, state);
339
+ });
340
+ },
341
+ async abandon(input) {
342
+ const scope = await scopeOf(owner(input?.owner)); const id = runId(input.runId); const now = time(input.nowMs);
343
+ return retrying(input.signal, async () => {
344
+ const current = await readRun(scope, id); if (!current) return null;
345
+ if (current.state.status !== 'running' || current.state.leaseExpiresAtMs >= now) return view(scope, current.state);
346
+ // The owner stopped renewing: nobody can say what its run did, so the record ends as outcome_unknown.
347
+ const evidence = current.state.snapshot['evidence'] ?? [];
348
+ const outcome: JsonObject = { status: 'outcome_unknown', error: { code: 'OUTCOME_UNKNOWN',
349
+ message: 'The server replica running this run stopped before recording its outcome. Effects it started may or may not have happened.' }, evidence };
350
+ const timestamp = new Date().toISOString(); const gaps = current.state.gaps.map(gap => [gap[0], gap[1]] as [number, number]);
351
+ const appended: { type: string; data: JsonObject }[] = []; let { lastSequence, truncatedFrom } = current.state;
352
+ if (truncatedFrom !== null && truncatedFrom <= lastSequence) {
353
+ gaps.push([truncatedFrom, lastSequence]);
354
+ appended.push({ type: 'events.gap', data: { sequence: lastSequence, timestamp, metadata: { from: truncatedFrom, to: lastSequence } } }); truncatedFrom = null;
355
+ }
356
+ lastSequence += 1;
357
+ appended.push({ type: 'run.completed', data: { sequence: lastSequence, timestamp, metadata: { status: 'outcome_unknown' } } });
358
+ const state: RunState = { ...current.state, status: 'outcome_unknown', snapshot: { ...current.state.snapshot, status: 'outcome_unknown' }, outcome, outcomeRef: null,
359
+ gaps, truncatedFrom, lastSequence, stored: current.state.stored + appended.length };
360
+ await store.update({ scope, id: `run:${id}`, expectedVersion: current.record.version, state: state as unknown as JsonObject, events: appended });
361
+ return view(scope, state);
362
+ });
363
+ },
364
+ });
365
+ }
@@ -0,0 +1,71 @@
1
+ import { jsonSchemaOf, jsonValue, MayuraError, type JsonObject, type Schema } from '@mayura/core';
2
+ import { workflowHashMaterial } from './workflow-format2.js';
3
+
4
+ const rounds = new Uint32Array([
5
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
6
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
7
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
8
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
9
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
10
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
11
+ ]);
12
+
13
+ /**
14
+ * @internal Synchronous SHA-256 (FIPS 180-4) of UTF-8 text, as lowercase hex. This package runs without Node types or
15
+ * WebCrypto, and definitions are built synchronously; tests check it against node:crypto.
16
+ */
17
+ export function sha256Hex(text: string): string {
18
+ const message = new TextEncoder().encode(text);
19
+ const length = Math.ceil((message.length + 9) / 64) * 64;
20
+ const padded = new Uint8Array(length); padded.set(message); padded[message.length] = 0x80;
21
+ const view = new DataView(padded.buffer);
22
+ view.setUint32(length - 8, Math.floor(message.length / 0x20000000)); view.setUint32(length - 4, (message.length << 3) >>> 0);
23
+ const state = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
24
+ const words = new Uint32Array(64);
25
+ const rotate = (value: number, bits: number): number => (value >>> bits) | (value << (32 - bits));
26
+ for (let offset = 0; offset < length; offset += 64) {
27
+ for (let index = 0; index < 16; index++) words[index] = view.getUint32(offset + index * 4);
28
+ for (let index = 16; index < 64; index++) {
29
+ const low = words[index - 15]!; const high = words[index - 2]!;
30
+ const s0 = rotate(low, 7) ^ rotate(low, 18) ^ (low >>> 3); const s1 = rotate(high, 17) ^ rotate(high, 19) ^ (high >>> 10);
31
+ words[index] = (words[index - 16]! + s0 + words[index - 7]! + s1) >>> 0;
32
+ }
33
+ let [a, b, c, d, e, f, g, h] = state as unknown as [number, number, number, number, number, number, number, number];
34
+ for (let index = 0; index < 64; index++) {
35
+ const t1 = (h + (rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25)) + ((e & f) ^ (~e & g)) + rounds[index]! + words[index]!) >>> 0;
36
+ const t2 = ((rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
37
+ h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;
38
+ }
39
+ state[0] = (state[0]! + a) >>> 0; state[1] = (state[1]! + b) >>> 0; state[2] = (state[2]! + c) >>> 0; state[3] = (state[3]! + d) >>> 0;
40
+ state[4] = (state[4]! + e) >>> 0; state[5] = (state[5]! + f) >>> 0; state[6] = (state[6]! + g) >>> 0; state[7] = (state[7]! + h) >>> 0;
41
+ }
42
+ return [...state].map(word => word.toString(16).padStart(8, '0')).join('');
43
+ }
44
+
45
+ /**
46
+ * The SHA-256 digest (64 lowercase hex characters) that pins a schema into durable records, such as the response a
47
+ * human request accepts or the body a webhook trigger admits. Pass a validator that can describe itself as JSON Schema
48
+ * (Zod 4.2 and later can), or the JSON Schema object itself. The digest covers canonical JSON, so key order does not
49
+ * change it. A validator that cannot describe itself is refused with INVALID_CONFIG.
50
+ *
51
+ * A derived digest follows the JSON Schema the validator produces: if a library upgrade changes that JSON Schema, the
52
+ * digest (and a definition that contains it) changes too, like any other definition change.
53
+ */
54
+ export function schemaDigest(schema: Schema | JsonObject): string {
55
+ let described: JsonObject | undefined;
56
+ if (schema !== null && typeof schema === 'object' && '~standard' in schema) {
57
+ described = jsonSchemaOf(schema as Schema);
58
+ if (described === undefined) {
59
+ throw new MayuraError('INVALID_CONFIG', 'This validator cannot describe itself as JSON Schema, so its schema digest cannot be derived. '
60
+ + 'Pass its JSON Schema object to schemaDigest, or give the 64-hex schemaDigest explicitly.');
61
+ }
62
+ } else {
63
+ let copy: unknown;
64
+ try { copy = jsonValue(schema, { maxBytes: 262_144, maxDepth: 64 }); } catch { copy = undefined; }
65
+ if (copy === null || typeof copy !== 'object' || Array.isArray(copy)) {
66
+ throw new MayuraError('INVALID_CONFIG', 'schemaDigest needs a validator or a JSON Schema object of at most 256 KiB.');
67
+ }
68
+ described = copy as JsonObject;
69
+ }
70
+ return sha256Hex(workflowHashMaterial('mayura:schema-digest:v1', described));
71
+ }
@@ -43,7 +43,7 @@ export function createAggregateSubmissionJournal(store: AggregateStore): Submiss
43
43
  const created = await store.create({ scope, id, idempotencyKey: id, definitionHash: await sha256('mayura:submission-journal-format:v1', {}),
44
44
  state: { format: 1, digest: input.digest }, events: [{ type: 'submission.claimed', data: {} }] });
45
45
  if (created.created) return { status: 'claimed' as const };
46
- } catch (error) { if (!(error instanceof StorageError) || error.code !== 'CONFLICT') throw error; }
46
+ } catch (error) { if (!(error instanceof StorageError) || error.storageCode !== 'CONFLICT') throw error; }
47
47
  return existing();
48
48
  },
49
49
  });