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
@@ -4,8 +4,9 @@ import { lstat, mkdir, readdir, readFile, realpath, rename, stat, unlink, writeF
4
4
  import { basename, isAbsolute, parse, relative, resolve, sep } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { MayuraError, freezeJson, jsonValue, type JsonObject } from '@mayura/core';
7
+ import { agentGuide } from './agent-guide.js';
7
8
 
8
- export { approveWorkflow, cancelRun, cancelWorkflow, inspectHumanRequest, inspectHumanRequests, inspectRun, inspectServerHealth, inspectServerTools, inspectWorkflow, inspectWorkflows,
9
+ export { OperationalRequestError, approveWorkflow, cancelRun, cancelWorkflow, inspectHumanRequest, inspectHumanRequests, inspectRun, inspectServerHealth, inspectServerTools, inspectWorkflow, inspectWorkflows,
9
10
  holdWorkflowFleet, inspectWorkflowFleet, pauseWorkflow, releaseWorkflowFleet, respondHumanRequest, resumeWorkflow, signalWorkflow, sweepWorkflowFleet, waitForRun,
10
11
  type OperationalFleetHold, type OperationalFleetSweep, type OperationalFleetSweepOutcome,
11
12
  type OperationalClientOptions, type OperationalHealth, type OperationalHealthCheck, type OperationalHumanRequest,
@@ -33,22 +34,22 @@ const descriptions: Readonly<Record<TemplateName, string>> = Object.freeze({
33
34
 
34
35
  /** What a template's project installs: `mayura`, and the optional peers the parts it uses need. */
35
36
  const dependencies: Readonly<Record<TemplateName, readonly string[]>> = Object.freeze({
36
- 'typed-tool-runner': ['mayura', 'zod'],
37
- 'basic-agent': ['mayura', 'zod'],
38
- 'durable-approval': ['better-sqlite3', 'mayura', 'zod'],
39
- 'parallel-research': ['mayura', 'zod'],
37
+ 'typed-tool-runner': ['mayura'],
38
+ 'basic-agent': ['mayura'],
39
+ 'durable-approval': ['better-sqlite3', 'mayura'],
40
+ 'parallel-research': ['mayura'],
40
41
  'native-memory': ['better-sqlite3', 'mayura'],
41
42
  'guarded-streaming-app': ['mayura'],
42
43
  'code-mode-workflow': ['@jitl/quickjs-wasmfile-release-sync', 'better-sqlite3', 'mayura', 'quickjs-emscripten-core'],
43
- 'capability-policy': ['mayura', 'zod'],
44
+ 'capability-policy': ['mayura'],
44
45
  });
45
46
  /** Versions of the third-party packages generated projects install; kept equal to the workspace's (tested). */
46
47
  export const PEER_VERSIONS: Readonly<Record<string, string>> = Object.freeze({
47
- zod: '4.6.5', 'better-sqlite3': '13.0.3', pg: '8.23.0', '@jitl/quickjs-wasmfile-release-sync': '0.32.0', 'quickjs-emscripten-core': '0.32.0',
48
+ 'better-sqlite3': '13.0.3', pg: '8.23.0', '@jitl/quickjs-wasmfile-release-sync': '0.32.0', 'quickjs-emscripten-core': '0.32.0',
48
49
  });
49
50
 
50
51
  /** Complete multi-file projects: offline by default, one environment switch to a real provider or PostgreSQL. */
51
- export const STARTER_NAMES = Object.freeze(['approval-workflow', 'support-agent', 'research-team', 'event-automation'] as const);
52
+ export const STARTER_NAMES = Object.freeze(['approval-workflow', 'support-agent', 'research-team', 'event-automation', 'cli-agent'] as const);
52
53
  export type StarterName = typeof STARTER_NAMES[number];
53
54
 
54
55
  const starterDescriptions: Readonly<Record<StarterName, string>> = Object.freeze({
@@ -56,6 +57,7 @@ const starterDescriptions: Readonly<Record<StarterName, string>> = Object.freeze
56
57
  'support-agent': 'Customer support chat: a streaming agent with order tools scoped to the signed-in customer, per-customer native memory, PII redaction, a React chat UI and the operator console.',
57
58
  'research-team': 'Multi-agent research: a planner, parallel researchers over a source library and a writer as one durable workflow under a shared budget, with cited reports stored as content-addressed artifacts and optional OpenTelemetry traces.',
58
59
  'event-automation': 'Signed webhooks start durable workflows in which a triage agent acts through MCP tools under explicit capability grants; forged, stale and replayed deliveries are refused.',
60
+ 'cli-agent': 'Command-line assistant: chat or one-shot requests about the folder you run it in, with file tools confined to that folder, writes you confirm, skills and streaming replies.',
59
61
  });
60
62
 
61
63
  const id = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/u;
@@ -192,6 +194,9 @@ export async function planProject(template: TemplateName, directory: string): Pr
192
194
  }, include: ['src/**/*.ts'] }, null, 2)}\n`],
193
195
  ['mayura.project.json', projectManifest(name, template)], ['README.md', readme], ['src/index.ts', source],
194
196
  ]);
197
+ // Guidance for AI coding assistants: where the installed version's documentation is, and the rules they miss most.
198
+ files.set('AGENTS.md', agentGuide({ kind: 'template', scripts: (JSON.parse(files.get('package.json')!) as { scripts?: Record<string, string> }).scripts ?? {} }));
199
+ files.set('CLAUDE.md', '@AGENTS.md\n');
195
200
  const { changes, before } = await planChanges(target, files);
196
201
  const planDigest = digest(JSON.stringify({ template, directory: target, changes }));
197
202
  const plan = Object.freeze({ format: 'mayura.init-plan.v1' as const, template, directory: target, digest: planDigest, changes: Object.freeze(changes) });
@@ -271,6 +276,9 @@ export async function planStarter(starter: StarterName, directory: string): Prom
271
276
  files.set('package.json', await starterManifest(manifest, name));
272
277
  const catalog = validateProject(JSON.parse(project)); if (catalog.template !== starter) throw new MayuraError('INTEGRITY_VIOLATION', 'Starter project manifest names another starter.');
273
278
  files.set('mayura.project.json', `${JSON.stringify({ ...catalog, name }, null, 2)}\n`);
279
+ // Guidance for AI coding assistants, unless the starter brings its own.
280
+ if (!files.has('AGENTS.md')) files.set('AGENTS.md', agentGuide({ kind: 'starter', scripts: (JSON.parse(files.get('package.json')!) as { scripts?: Record<string, string> }).scripts ?? {} }));
281
+ if (!files.has('CLAUDE.md')) files.set('CLAUDE.md', '@AGENTS.md\n');
274
282
  const { changes, before } = await planChanges(target, files);
275
283
  const planDigest = digest(JSON.stringify({ starter, directory: target, changes }));
276
284
  const plan = Object.freeze({ format: 'mayura.init-plan.v1' as const, starter, directory: target, digest: planDigest, changes: Object.freeze(changes) });
@@ -382,5 +390,5 @@ export function templates(): readonly Readonly<{ name: TemplateName; description
382
390
  export function starters(): readonly Readonly<{ name: StarterName; description: string }>[] {
383
391
  return Object.freeze(STARTER_NAMES.map(name => Object.freeze({ name, description: starterDescriptions[name] })));
384
392
  }
385
- export { defineMayuraApplication, loadApplication, migrateApplication, runWorkerApplication, serveApplication, type MayuraApplication, type MayuraLifecycleEvent,
386
- type MayuraServerHandle, type MayuraWorkerHandle } from './application.js';
393
+ export { defineMayuraApplication, loadApplication, migrateApplication, runWorkerApplication, runWorkerOnce, serveApplication, type MayuraApplication, type MayuraLifecycleEvent,
394
+ type MayuraServerHandle, type MayuraWorkerHandle, type MayuraWorkerOnceReport } from './application.js';
@@ -4,7 +4,7 @@ import { relative, resolve } from 'node:path';
4
4
  import type { Readable, Writable } from 'node:stream';
5
5
  import { applyProjectPlan, planProject, planStarter, starters, templates, type InitPlan, type StarterInitPlan, type StarterName, type TemplateName } from './index.js';
6
6
  import { nextSteps, wrap, type Paint } from './output.js';
7
- import { azureEndpoint, dollarsToMicros, endpointProblem, modelPattern, PROVIDERS, providerIdPattern, validKey, writeProviderEnvironment, type ProviderChoice } from './providers.js';
7
+ import { azureEndpoint, cloudflareEndpoint, cloudflareProviderEndpoint, dollarsToMicros, endpointProblem, gatewayDialect, modelPattern, PROVIDERS, providerIdPattern, validKey, writeProviderEnvironment, type ProviderChoice } from './providers.js';
8
8
 
9
9
  /** The part of a description before its first colon or full stop: short enough for a menu hint. */
10
10
  const summary = (description: string): string => description.split(/[:.]/u)[0]!.trim();
@@ -21,7 +21,7 @@ export async function initWizard(p: Paint, io: WizardIo = {}, afterWrite?: Wizar
21
21
  prompts.intro(p.bold(' Create a Mayura project '), io);
22
22
 
23
23
  const kind = await prompts.select({ ...io, message: 'Start from', options: [
24
- { value: 'starter' as const, label: 'A starter', hint: 'a complete app: server, worker, operator console, tests' },
24
+ { value: 'starter' as const, label: 'A starter', hint: 'a complete project with tests: a server app or a command-line assistant' },
25
25
  { value: 'template' as const, label: 'A template', hint: 'one small, single-purpose example' },
26
26
  ] });
27
27
  if (prompts.isCancel(kind)) return cancelled();
@@ -42,9 +42,29 @@ export async function initWizard(p: Paint, io: WizardIo = {}, afterWrite?: Wizar
42
42
  providerLabel = details.label;
43
43
  // OpenAI-compatible: a preset endpoint, or the pieces of one.
44
44
  let compatible: ProviderChoice['compatible'];
45
+ // Cloudflare AI Gateway in front of OpenAI's or Anthropic's own API, used with Mayura's adapter for that provider.
46
+ let native: { readonly provider: 'openai' | 'anthropic'; readonly endpoint: string; readonly token?: string } | undefined;
45
47
  if (details.provider === 'compatible') {
46
- let endpoint = details.endpoint; let id = details.id;
47
- if (details.ask === 'azure') {
48
+ let endpoint = details.endpoint; let id = details.id; let gatewayToken: string | undefined;
49
+ if (details.ask === 'cloudflare') {
50
+ const account = await prompts.text({ ...io, message: 'Cloudflare account ID', placeholder: 'in the dashboard URL or Account home',
51
+ validate: value => /^[a-f0-9]{32}$/u.test(value ?? '') ? undefined : 'Enter the 32-character account ID.' });
52
+ if (prompts.isCancel(account)) return cancelled();
53
+ const gateway = await prompts.text({ ...io, message: 'Gateway name', placeholder: 'default', defaultValue: 'default',
54
+ validate: value => /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/u.test(value || 'default') ? undefined : 'Enter the gateway name from AI Gateway.' });
55
+ if (prompts.isCancel(gateway)) return cancelled();
56
+ const token = await prompts.password({ ...io, message: 'Gateway token (leave empty if the gateway is not authenticated)', mask: '•',
57
+ validate: value => !value || validKey(value) ? undefined : 'Paste the token: at least 8 visible characters, no spaces.' });
58
+ if (prompts.isCancel(token)) return cancelled();
59
+ const route = await prompts.select({ ...io, message: 'Which API through the gateway?', initialValue: 'unified' as const, options: [
60
+ { value: 'unified' as const, label: 'Unified (OpenAI-compatible)', hint: 'any provider, models named provider/model' },
61
+ { value: 'openai' as const, label: 'OpenAI Responses API', hint: 'OpenAI models, with the OpenAI adapter' },
62
+ { value: 'anthropic' as const, label: 'Anthropic Messages API', hint: 'Claude models, with the Anthropic adapter' },
63
+ ] });
64
+ if (prompts.isCancel(route)) return cancelled();
65
+ if (route !== 'unified') native = { provider: route, endpoint: cloudflareProviderEndpoint(account, gateway || 'default', route), ...(token ? { token } : {}) };
66
+ endpoint = cloudflareEndpoint(account, gateway || 'default'); gatewayToken = token || undefined;
67
+ } else if (details.ask === 'azure') {
48
68
  const resource = await prompts.text({ ...io, message: 'Azure OpenAI resource name', placeholder: 'the <resource> in https://<resource>.openai.azure.com',
49
69
  validate: value => /^[a-z0-9][a-z0-9-]{1,62}$/u.test(value ?? '') ? undefined : 'Enter the resource name: lower-case letters, digits and dashes.' });
50
70
  if (prompts.isCancel(resource)) return cancelled();
@@ -66,15 +86,26 @@ export async function initWizard(p: Paint, io: WizardIo = {}, afterWrite?: Wizar
66
86
  if (prompts.isCancel(named)) return cancelled();
67
87
  id = named || suggested;
68
88
  }
69
- compatible = { id, endpoint: endpoint!, auth: details.auth ?? 'bearer' };
89
+ if (!native) compatible = { id, endpoint: endpoint!, auth: details.auth ?? 'bearer', ...(details.dialect ? { dialect: details.dialect } : {}), ...(gatewayToken ? { gatewayToken } : {}) };
70
90
  }
71
- const model = await prompts.text({ ...io, message: `${details.label} model`, placeholder: details.defaultModel ?? 'the model id from your account',
72
- ...(details.defaultModel ? { defaultValue: details.defaultModel } : {}),
73
- validate: value => (value || details.defaultModel) && modelPattern.test(value || details.defaultModel!) ? undefined : 'Enter a model id, such as the one in your provider dashboard.' });
91
+ // Behind the gateway, the provider's own defaults apply (a Claude model for Anthropic, for example).
92
+ const target = native ? PROVIDERS.find(item => item.id === native.provider)! : details;
93
+ const defaultModel = target.defaultModel;
94
+ const model = await prompts.text({ ...io, message: `${target.label} model`,
95
+ placeholder: defaultModel ?? (details.ask === 'cloudflare' && !native ? 'provider/model, such as deepseek/deepseek-flash' : 'the model id from your account'),
96
+ ...(defaultModel ? { defaultValue: defaultModel } : {}),
97
+ validate: value => (value || defaultModel) && modelPattern.test(value || defaultModel!) ? undefined : 'Enter a model id, such as the one in your provider dashboard.' });
74
98
  if (prompts.isCancel(model)) return cancelled();
75
- // Masked, and written only to the project's .env: never printed, logged or put in the plan.
76
- const apiKey = await prompts.password({ ...io, message: `${details.label} API key`, mask: '•',
77
- validate: value => validKey(value) ? undefined : 'Paste the key: at least 8 visible characters, no spaces.' });
99
+ // Through a gateway, the model's provider sets the dialect (DeepSeek answers in JSON mode, for example).
100
+ if (details.ask === 'cloudflare' && compatible) {
101
+ const dialect = gatewayDialect(model || '');
102
+ compatible = { ...compatible, ...(dialect ? { dialect } : {}) };
103
+ }
104
+ // Masked, and written only to the project's .env: never printed, logged or put in the plan. A gateway with a
105
+ // token may keep the provider's key itself, so the key may be left empty there.
106
+ const keyOptional = details.ask === 'cloudflare' && (compatible?.gatewayToken !== undefined || native?.token !== undefined);
107
+ const apiKey = await prompts.password({ ...io, message: keyOptional ? `${native ? target.label : 'Provider'} API key (leave empty if the gateway stores it)` : `${target.label} API key`, mask: '•',
108
+ validate: value => (keyOptional && !value) || validKey(value) ? undefined : 'Paste the key: at least 8 visible characters, no spaces.' });
78
109
  if (prompts.isCancel(apiKey)) return cancelled();
79
110
  prompts.log.message(p.dim(wrap('Mayura accounts every call conservatively, so it needs your prices (from the provider\'s pricing page) and a spending cap.', 76, '')), io);
80
111
  const price = async (message: string, defaultValue?: string): Promise<number | symbol> => {
@@ -86,7 +117,8 @@ export async function initWizard(p: Paint, io: WizardIo = {}, afterWrite?: Wizar
86
117
  const output = await price('Output price, $ per million tokens'); if (typeof output === 'symbol') return cancelled();
87
118
  const call = await price('Most one model call may cost, $', '0.05'); if (typeof call === 'symbol') return cancelled();
88
119
  const run = await price('Most one agent run may cost, $', '0.50'); if (typeof run === 'symbol') return cancelled();
89
- provider = { provider: details.provider, apiKey, model: model || details.defaultModel!, ...(compatible ? { compatible } : {}),
120
+ provider = { provider: native?.provider ?? details.provider, apiKey, model: model || defaultModel!, ...(compatible ? { compatible } : {}),
121
+ ...(native ? { gateway: { endpoint: native.endpoint, ...(native.token ? { token: native.token } : {}) } } : {}),
90
122
  inputMicrosPerMillionTokens: input, outputMicrosPerMillionTokens: output, maxCallCostMicros: call, maxRunCostMicros: Math.max(run, call) };
91
123
  }
92
124
  }
@@ -36,11 +36,16 @@ export interface OperationalRun {
36
36
  readonly evidence: readonly OperationalRunReceipt[];
37
37
  }
38
38
  export type OperationalWorkflowFormat = 2 | 3 | 4 | 5;
39
- export type OperationalWorkflowNodeKind = 'tool' | 'join' | 'wait' | 'child' | 'human' | 'timer';
39
+ export type OperationalWorkflowNodeKind = 'tool' | 'join' | 'wait' | 'child' | 'human' | 'timer' | 'signal';
40
40
  export type OperationalWorkflowStatus = 'running' | 'waiting' | 'paused' | 'succeeded' | 'failed' | 'blocked' | 'cancelled' | 'outcome_unknown';
41
41
  export type OperationalWorkflowStepStatus = 'pending' | 'waiting' | 'approved' | 'dispatching' | 'succeeded' | 'failed' | 'blocked' | 'unknown' | 'skipped' | 'timed_out';
42
42
  export interface OperationalWorkflowNode { readonly id: string; readonly kind: OperationalWorkflowNodeKind; readonly dependsOn: readonly string[] }
43
- export interface OperationalWorkflowStep { readonly id: string; readonly kind: OperationalWorkflowNodeKind; readonly status: OperationalWorkflowStepStatus; readonly childRunId?: string }
43
+ /** A tool step waiting for approval: approve it with `digest` (`workflow-approve --digest`) before `expiresAtMs`. */
44
+ export interface OperationalWorkflowApproval { readonly digest: string; readonly expiresAtMs: number }
45
+ export interface OperationalWorkflowStep {
46
+ readonly id: string; readonly kind: OperationalWorkflowNodeKind; readonly status: OperationalWorkflowStepStatus; readonly childRunId?: string;
47
+ readonly approval?: OperationalWorkflowApproval;
48
+ }
44
49
  export interface OperationalWorkflow {
45
50
  readonly format: OperationalWorkflowFormat; readonly definitionId: string; readonly definitionVersion: string;
46
51
  readonly runId: string; readonly revision: number; readonly status: OperationalWorkflowStatus;
@@ -61,6 +66,55 @@ const workflowRunIdentifier = /^[a-f0-9]{64}$/u;
61
66
  const workflowNodeIdentifier = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
62
67
  const workflowVersion = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/u;
63
68
  function fail(): never { throw new MayuraError('INVALID_OUTPUT', 'The operational server returned an invalid response.'); }
69
+
70
+ /**
71
+ * A request the server refused. `code` is a stable Mayura error class; `serverCode` is the server's own precise code
72
+ * (for example `CAPABILITY_REQUIRED` or `WORKFLOW_CONFLICT`) when it sent one, and the message repeats the server's
73
+ * fixed explanation, checked to be short printable text so it is safe to print in a terminal.
74
+ */
75
+ export class OperationalRequestError extends MayuraError {
76
+ constructor(code: ConstructorParameters<typeof MayuraError>[0], message: string, readonly status: number, readonly serverCode: string | null,
77
+ readonly retryAfterMs: number | null, readonly capability: string | null, readonly currentRevision: number | null) { super(code, message); }
78
+ override toJSON(): ReturnType<MayuraError['toJSON']> & { readonly status: number; readonly serverCode: string | null } {
79
+ return { code: this.code, message: this.message, status: this.status, serverCode: this.serverCode,
80
+ ...(this.retryAfterMs === null ? {} : { retryAfterMs: this.retryAfterMs }), ...(this.capability === null ? {} : { capability: this.capability }),
81
+ ...(this.currentRevision === null ? {} : { currentRevision: this.currentRevision }) };
82
+ }
83
+ }
84
+ /** The stable class for an HTTP status; the server's own code travels next to it. */
85
+ function statusCode(status: number, serverCode: string | null): ConstructorParameters<typeof MayuraError>[0] {
86
+ if (serverCode === 'SUBMISSION_OUTCOME_UNKNOWN') return 'OUTCOME_UNKNOWN';
87
+ return status === 401 || status === 403 ? 'PERMISSION_DENIED' : status === 404 || status === 410 ? 'NOT_FOUND' : status === 409 || status === 412 ? 'CONFLICT'
88
+ : status === 408 ? 'TIMEOUT' : status === 413 || status === 429 ? 'LIMIT_EXCEEDED' : status === 400 || status === 415 ? 'INVALID_INPUT' : 'TOOL_FAILED';
89
+ }
90
+ /** Read at most 16 KiB of an error answer and keep only a well-formed Mayura code, message and hints. */
91
+ async function refusal(response: Response, signal: AbortSignal): Promise<OperationalRequestError> {
92
+ let code: string | null = null; let text: string | null = null; let retryAfterMs: number | null = null; let capability: string | null = null; let revision: number | null = null;
93
+ if (/^application\/json(?:\s*;|$)/iu.test(response.headers.get('content-type') ?? '') && response.body) {
94
+ const reader = response.body.getReader(); const chunks: Uint8Array[] = []; let size = 0; let complete = false;
95
+ try {
96
+ while (true) {
97
+ const next = await bounded(reader.read(), signal); if (next.done) { complete = true; break; }
98
+ size += next.value.byteLength; if (size > 16_384) break; chunks.push(next.value);
99
+ }
100
+ if (complete) {
101
+ const bytes = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
102
+ const error = (JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as { error?: Record<string, unknown> } | null)?.error;
103
+ if (error && typeof error === 'object' && typeof error['code'] === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/u.test(error['code'])) {
104
+ code = error['code'];
105
+ if (typeof error['message'] === 'string' && /^[\x20-\x7e]{1,1024}$/u.test(error['message'])) text = error['message'];
106
+ if (Number.isSafeInteger(error['retryAfterMs']) && (error['retryAfterMs'] as number) >= 0) retryAfterMs = error['retryAfterMs'] as number;
107
+ if (typeof error['capability'] === 'string' && capabilityIdentifier.test(error['capability'])) capability = error['capability'];
108
+ if (Number.isSafeInteger(error['currentRevision']) && (error['currentRevision'] as number) >= 1) revision = error['currentRevision'] as number;
109
+ }
110
+ }
111
+ } catch (error) { if (error instanceof MayuraError && error.code === 'TIMEOUT') throw error; /* Not a Mayura error body. */ }
112
+ finally { if (!complete) void reader.cancel().catch(() => {}); reader.releaseLock(); }
113
+ } else void response.body?.cancel().catch(() => {});
114
+ const message = code === null ? `The operational server refused the request (HTTP ${response.status}).`
115
+ : `The operational server refused the request (HTTP ${response.status} ${code})${text === null ? '.' : `: ${text}`}`;
116
+ return new OperationalRequestError(statusCode(response.status, code), message, response.status, code, retryAfterMs, capability, revision);
117
+ }
64
118
  function record(value: unknown): Record<string, unknown> {
65
119
  if (value === null || typeof value !== 'object' || Array.isArray(value) || ![null, Object.prototype].includes(Object.getPrototypeOf(value))) return fail();
66
120
  return value as Record<string, unknown>;
@@ -117,10 +171,7 @@ async function transport(options: OperationalClientOptions, path: string, accept
117
171
  throw new MayuraError('TOOL_FAILED', 'The operational server could not be reached.');
118
172
  }
119
173
  if (response.redirected || (response.url && new URL(response.url).origin !== base.origin)) { void response.body?.cancel().catch(() => {}); throw new MayuraError('PERMISSION_DENIED', 'Operational redirects are denied.'); }
120
- if (!accepted.includes(response.status)) { void response.body?.cancel().catch(() => {});
121
- const code = response.status === 401 || response.status === 403 ? 'PERMISSION_DENIED' : response.status === 404 ? 'NOT_FOUND'
122
- : response.status === 409 || response.status === 412 ? 'CONFLICT' : 'TOOL_FAILED';
123
- throw new MayuraError(code, 'Operational request was rejected.'); }
174
+ if (!accepted.includes(response.status)) throw await refusal(response, controller.signal);
124
175
  if (!/^application\/json(?:\s*;|$)/iu.test(response.headers.get('content-type') ?? '')) { void response.body?.cancel().catch(() => {}); return fail(); }
125
176
  const reader = response.body?.getReader(); if (!reader) return fail();
126
177
  const chunks: Uint8Array[] = []; let size = 0; let complete = false;
@@ -182,7 +233,7 @@ function workflow(value: unknown, expectedId: string): OperationalWorkflow {
182
233
  || !Array.isArray(item['nodes']) || item['nodes'].length < 1 || item['nodes'].length > 128
183
234
  || !Array.isArray(item['steps']) || item['steps'].length !== item['nodes'].length) return fail();
184
235
  const allowedKinds: Readonly<Record<OperationalWorkflowFormat, ReadonlySet<OperationalWorkflowNodeKind>>> = {
185
- 2: new Set(['tool', 'join']), 3: new Set(['tool', 'join', 'wait']), 4: new Set(['tool', 'join', 'child']), 5: new Set(['tool', 'join', 'human', 'timer']),
236
+ 2: new Set(['tool', 'join']), 3: new Set(['tool', 'join', 'wait']), 4: new Set(['tool', 'join', 'child']), 5: new Set(['tool', 'join', 'human', 'timer', 'signal']),
186
237
  };
187
238
  const nodes = new Map<string, OperationalWorkflowNode>(); let edges = 0;
188
239
  for (const raw of item['nodes']) {
@@ -204,20 +255,39 @@ function workflow(value: unknown, expectedId: string): OperationalWorkflow {
204
255
  const statuses = new Set<OperationalWorkflowStepStatus>(['pending', 'waiting', 'approved', 'dispatching', 'succeeded', 'failed', 'blocked', 'unknown', 'skipped', 'timed_out']);
205
256
  const steps = new Map<string, OperationalWorkflowStep>();
206
257
  for (const raw of item['steps']) {
207
- const source = record(raw); const keys = Object.keys(source); if (keys.some(key => !['id', 'kind', 'status', 'childRunId'].includes(key))
258
+ const source = record(raw); const keys = Object.keys(source); if (keys.some(key => !['id', 'kind', 'status', 'childRunId', 'approval'].includes(key))
208
259
  || !['id', 'kind', 'status'].every(key => Object.hasOwn(source, key))) return fail();
209
260
  const stepId = source['id']; const kind = source['kind'] as OperationalWorkflowNodeKind; const status = source['status'] as OperationalWorkflowStepStatus;
210
261
  const node = typeof stepId === 'string' ? nodes.get(stepId) : undefined; const childRunId = source['childRunId'];
211
262
  if (!node || steps.has(stepId as string) || kind !== node.kind || !statuses.has(status)
212
- || (kind === 'human' && !['pending', 'waiting', 'succeeded', 'timed_out', 'skipped'].includes(status))
213
- || (kind === 'timer' && !['pending', 'waiting', 'succeeded', 'skipped'].includes(status)) || (status === 'timed_out' && kind !== 'human')
214
- || (childRunId !== undefined && (kind !== 'child' || typeof childRunId !== 'string' || !workflowRunIdentifier.test(childRunId)))) return fail();
215
- steps.set(stepId as string, Object.freeze({ id: stepId as string, kind, status, ...(childRunId === undefined ? {} : { childRunId: childRunId as string }) }));
263
+ || ((kind === 'human' || kind === 'signal') && !['pending', 'waiting', 'succeeded', 'timed_out', 'skipped'].includes(status))
264
+ || (kind === 'timer' && !['pending', 'waiting', 'succeeded', 'skipped'].includes(status)) || (status === 'timed_out' && kind !== 'human' && kind !== 'signal')
265
+ || (childRunId !== undefined && (kind !== 'child' || typeof childRunId !== 'string' || !workflowRunIdentifier.test(childRunId)))
266
+ || (source['approval'] !== undefined && (kind !== 'tool' || status !== 'waiting'))) return fail();
267
+ const approval = source['approval'] === undefined ? undefined : pendingApproval(source['approval']);
268
+ steps.set(stepId as string, Object.freeze({ id: stepId as string, kind, status, ...(childRunId === undefined ? {} : { childRunId: childRunId as string }),
269
+ ...(approval === undefined ? {} : { approval }) }));
216
270
  }
217
271
  return Object.freeze({ format, definitionId, definitionVersion, runId: expectedId, revision: item['revision'] as number,
218
272
  status: item['status'] as OperationalWorkflowStatus, nodes: Object.freeze([...nodes.values()]), steps: Object.freeze([...steps.values()]) });
219
273
  }
220
274
 
275
+ /**
276
+ * A waiting tool step's pending approval, in the shape the server sends. Only the digest and expiry are kept: the exact
277
+ * tool call the host may attach (`subject`) is checked but not kept, so the CLI never prints approval data.
278
+ */
279
+ function pendingApproval(value: unknown): OperationalWorkflowApproval {
280
+ const approval = record(value); if (Object.keys(approval).some(key => !['digest', 'expiresAtMs', 'subject'].includes(key))) return fail();
281
+ const digest = approval['digest']; const expiresAtMs = approval['expiresAtMs'];
282
+ if (typeof digest !== 'string' || !/^[a-f0-9]{64}$/u.test(digest) || typeof expiresAtMs !== 'number' || !Number.isSafeInteger(expiresAtMs) || expiresAtMs <= 0) return fail();
283
+ if (approval['subject'] !== undefined) {
284
+ const subject = record(approval['subject']); exact(subject, ['toolId', 'toolVersion', 'input']);
285
+ const identifier = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/u;
286
+ if (typeof subject['toolId'] !== 'string' || !identifier.test(subject['toolId']) || typeof subject['toolVersion'] !== 'string' || !identifier.test(subject['toolVersion'])) return fail();
287
+ }
288
+ return Object.freeze({ digest, expiresAtMs });
289
+ }
290
+
221
291
  function workflowIndexEntry(value: unknown, settled = false): OperationalWorkflowIndexEntry {
222
292
  const item = record(value); exact(item, ['format', 'definitionId', 'definitionVersion', 'runId', 'revision', 'status', ...(settled ? ['settledAtMs'] : [])]);
223
293
  if (settled && (!Number.isSafeInteger(item['settledAtMs']) || (item['settledAtMs'] as number) < 0 || ['running', 'waiting', 'paused'].includes(String(item['status'])))) return fail();
@@ -200,6 +200,9 @@ export function help(p: Paint): string {
200
200
  row('workflow-list [--settled]', 'active runs, or finished and unresolved ones'),
201
201
  row('workflow-get, workflow-approve', ''), row('workflow-cancel, workflow-pause, workflow-resume, workflow-signal', ''),
202
202
  row('fleet-get, fleet-hold, fleet-release, fleet-sweep', ''), '',
203
+ p.bold('Options'),
204
+ row('--help, -h', 'show this help (also after any command)'), row('--version, -v', 'print the version'),
205
+ row('--json', 'always print JSON, even in a terminal'), '',
203
206
  p.dim('Output is readable in a terminal and JSON when piped; --json always prints JSON.'),
204
207
  ].map(line => line.trimEnd()).join('\n');
205
208
  }
@@ -9,14 +9,22 @@ export interface ProviderOption {
9
9
  readonly id: string; readonly label: string; readonly hint: string;
10
10
  /** What MAYURA_MODEL_PROVIDER becomes; undefined for offline. */
11
11
  readonly provider?: StarterProvider; readonly keyVariable?: string; readonly defaultModel?: string;
12
- /** OpenAI-compatible presets: a fixed endpoint, or `azure` / `other` to ask for it. */
13
- readonly endpoint?: string; readonly ask?: 'azure' | 'other'; readonly auth?: ProviderAuth;
12
+ /** OpenAI-compatible presets: a fixed endpoint, or `azure` / `cloudflare` / `other` to ask for it. */
13
+ readonly endpoint?: string; readonly ask?: 'azure' | 'cloudflare' | 'other'; readonly auth?: ProviderAuth;
14
+ /** The provider's dialect: JSON mode instead of JSON Schema output, and strict tool calls. */
15
+ readonly dialect?: ProviderDialect;
14
16
  }
17
+ /** How an OpenAI-compatible provider differs from OpenAI: see `output`, `strictTools` and `tokenLimitField` of openAICompatibleChat. */
18
+ export interface ProviderDialect { readonly output?: 'json_object'; readonly strictTools?: boolean; readonly tokenLimitField?: 'max_completion_tokens' }
19
+ /** DeepSeek offers JSON mode but not JSON Schema output, and strict tool calls on its beta endpoint. */
20
+ export const DEEPSEEK_DIALECT: ProviderDialect = Object.freeze({ output: 'json_object', strictTools: true });
21
+ /** OpenAI's models through a gateway: its newer models accept only `max_completion_tokens` for the output limit. */
22
+ export const OPENAI_CHAT_DIALECT: ProviderDialect = Object.freeze({ tokenLimitField: 'max_completion_tokens' });
15
23
 
16
- const compatible = (id: string, label: string, endpoint: string): ProviderOption =>
17
- ({ id, label, hint: 'OpenAI-compatible', provider: 'compatible', keyVariable: 'MAYURA_MODEL_API_KEY', endpoint, auth: 'bearer' });
24
+ const compatible = (id: string, label: string, endpoint: string, extra: Partial<ProviderOption> = {}): ProviderOption =>
25
+ ({ id, label, hint: 'OpenAI-compatible', provider: 'compatible', keyVariable: 'MAYURA_MODEL_API_KEY', endpoint, auth: 'bearer', ...extra });
18
26
  /**
19
- * Offline, the two native adapters, then OpenAI-compatible endpoints as documented in docs/how-to/model-providers.md.
27
+ * Offline, the two native adapters, then OpenAI-compatible endpoints as documented in docs/guides/model-providers.md.
20
28
  * Mayura has not qualified the compatible ones against live accounts; `pnpm providers:live-check` does that.
21
29
  */
22
30
  export const PROVIDERS: readonly ProviderOption[] = Object.freeze([
@@ -26,19 +34,28 @@ export const PROVIDERS: readonly ProviderOption[] = Object.freeze([
26
34
  compatible('groq', 'Groq', 'https://api.groq.com/openai/v1/chat/completions'),
27
35
  compatible('gemini', 'Google Gemini', 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions'),
28
36
  compatible('mistral', 'Mistral', 'https://api.mistral.ai/v1/chat/completions'),
29
- compatible('deepseek', 'DeepSeek', 'https://api.deepseek.com/chat/completions'),
37
+ compatible('deepseek', 'DeepSeek', 'https://api.deepseek.com/beta/chat/completions', { defaultModel: 'deepseek-flash', dialect: DEEPSEEK_DIALECT }),
30
38
  compatible('xai', 'xAI', 'https://api.x.ai/v1/chat/completions'),
31
39
  compatible('openrouter', 'OpenRouter', 'https://openrouter.ai/api/v1/chat/completions'),
32
40
  compatible('together', 'Together', 'https://api.together.xyz/v1/chat/completions'),
33
41
  compatible('fireworks', 'Fireworks', 'https://api.fireworks.ai/inference/v1/chat/completions'),
42
+ { id: 'cloudflare', label: 'Cloudflare AI Gateway', hint: 'OpenAI, Anthropic or any model through your gateway', provider: 'compatible', keyVariable: 'MAYURA_MODEL_API_KEY', ask: 'cloudflare', auth: 'bearer' },
34
43
  { id: 'azure', label: 'Azure OpenAI', hint: 'your resource and deployment', provider: 'compatible', keyVariable: 'MAYURA_MODEL_API_KEY', ask: 'azure', auth: 'api-key' },
35
44
  { id: 'other', label: 'Another OpenAI-compatible provider', hint: 'any HTTPS /chat/completions endpoint', provider: 'compatible', keyVariable: 'MAYURA_MODEL_API_KEY', ask: 'other', auth: 'bearer' },
36
45
  ]);
37
46
 
38
47
  export interface ProviderChoice {
48
+ /** The provider's key; empty only for a gateway that stores the key itself (then `gatewayToken` authenticates). */
39
49
  readonly provider: StarterProvider; readonly apiKey: string; readonly model: string;
40
- /** For `compatible`: the endpoint, a short id naming its adapter, and how it takes the key. */
41
- readonly compatible?: { readonly id: string; readonly endpoint: string; readonly auth: ProviderAuth };
50
+ /** For `compatible`: the endpoint, a short id naming its adapter, how it takes the key, and its dialect. */
51
+ readonly compatible?: { readonly id: string; readonly endpoint: string; readonly auth: ProviderAuth; readonly dialect?: ProviderDialect;
52
+ /** Cloudflare AI Gateway's token, for an authenticated gateway (sent as `cf-aig-authorization`). */
53
+ readonly gatewayToken?: string };
54
+ /**
55
+ * For `openai` and `anthropic` through a gateway (Cloudflare AI Gateway's provider endpoints): the full endpoint, and
56
+ * the gateway's token for an authenticated gateway. The key may then be empty when the gateway stores it.
57
+ */
58
+ readonly gateway?: { readonly endpoint: string; readonly token?: string };
42
59
  /** Micro-dollars per million tokens. */
43
60
  readonly inputMicrosPerMillionTokens: number; readonly outputMicrosPerMillionTokens: number;
44
61
  /** The most one model call, and one agent run, may cost, in micro-dollars. */
@@ -71,6 +88,19 @@ export function endpointProblem(value: string | undefined): string | undefined {
71
88
  }
72
89
  return undefined;
73
90
  }
91
+ /** Cloudflare AI Gateway's OpenAI-compatible endpoint for an account and gateway. Models are named `provider/model`. */
92
+ export function cloudflareEndpoint(accountId: string, gatewayId: string): string {
93
+ return `https://gateway.ai.cloudflare.com/v1/${encodeURIComponent(accountId)}/${encodeURIComponent(gatewayId)}/compat/chat/completions`;
94
+ }
95
+ /** Cloudflare AI Gateway's endpoint for a provider's own API: OpenAI's Responses API or Anthropic's Messages API. */
96
+ export function cloudflareProviderEndpoint(accountId: string, gatewayId: string, api: 'openai' | 'anthropic'): string {
97
+ const base = `https://gateway.ai.cloudflare.com/v1/${encodeURIComponent(accountId)}/${encodeURIComponent(gatewayId)}`;
98
+ return api === 'openai' ? `${base}/openai/responses` : `${base}/anthropic/v1/messages`;
99
+ }
100
+ /** The dialect of a model reached through a gateway, from its `provider/model` name. */
101
+ export const gatewayDialect = (model: string): ProviderDialect | undefined =>
102
+ /^deepseek\//iu.test(model) ? DEEPSEEK_DIALECT : /^openai\//iu.test(model) ? OPENAI_CHAT_DIALECT : undefined;
103
+
74
104
  /** The Azure OpenAI chat-completions URL for a resource, deployment and API version. */
75
105
  export function azureEndpoint(resource: string, deployment: string, apiVersion: string): string {
76
106
  return `https://${resource}.openai.azure.com/openai/deployments/${encodeURIComponent(deployment)}/chat/completions?api-version=${encodeURIComponent(apiVersion)}`;
@@ -83,9 +113,14 @@ export function providerEnvironment(choice: ProviderChoice): string {
83
113
  '# Written by mayura init for local development. It holds your API key: keep it private and never commit it',
84
114
  '# (.gitignore excludes it). Production reads these settings from its own environment instead.',
85
115
  `MAYURA_MODEL_PROVIDER=${choice.provider}`,
116
+ ...(choice.gateway ? [`MAYURA_MODEL_ENDPOINT=${choice.gateway.endpoint}`, ...(choice.gateway.token ? [`MAYURA_MODEL_GATEWAY_TOKEN=${choice.gateway.token}`] : [])] : []),
86
117
  ...(choice.compatible ? [`MAYURA_MODEL_PROVIDER_ID=${choice.compatible.id}`, `MAYURA_MODEL_ENDPOINT=${choice.compatible.endpoint}`,
87
- `MAYURA_MODEL_AUTH=${choice.compatible.auth}`] : []),
88
- `${keyVariable}=${choice.apiKey}`,
118
+ `MAYURA_MODEL_AUTH=${choice.compatible.auth}`,
119
+ ...(choice.compatible.dialect?.output ? [`MAYURA_MODEL_OUTPUT=${choice.compatible.dialect.output}`] : []),
120
+ ...(choice.compatible.dialect?.strictTools ? ['MAYURA_MODEL_STRICT_TOOLS=true'] : []),
121
+ ...(choice.compatible.dialect?.tokenLimitField ? [`MAYURA_MODEL_TOKEN_LIMIT_FIELD=${choice.compatible.dialect.tokenLimitField}`] : []),
122
+ ...(choice.compatible.gatewayToken ? [`MAYURA_MODEL_GATEWAY_TOKEN=${choice.compatible.gatewayToken}`] : [])] : []),
123
+ ...(choice.apiKey ? [`${keyVariable}=${choice.apiKey}`] : []),
89
124
  `MAYURA_MODEL=${choice.model}`,
90
125
  `MAYURA_MODEL_INPUT_MICROS_PER_MILLION_TOKENS=${choice.inputMicrosPerMillionTokens}`,
91
126
  `MAYURA_MODEL_OUTPUT_MICROS_PER_MILLION_TOKENS=${choice.outputMicrosPerMillionTokens}`,
@@ -29,6 +29,17 @@ MAYURA_MODEL_PROVIDER=offline
29
29
  # MAYURA_MODEL_PROVIDER_ID=groq
30
30
  # MAYURA_MODEL_AUTH=bearer
31
31
  # MAYURA_MODEL_API_KEY=
32
+ # DeepSeek answers in JSON mode and has strict tools on https://api.deepseek.com/beta/chat/completions:
33
+ # MAYURA_MODEL_OUTPUT=json_object
34
+ # MAYURA_MODEL_STRICT_TOOLS=true
35
+ # OpenAI's newer models (directly or as openai/... through a gateway) take only max_completion_tokens:
36
+ # MAYURA_MODEL_TOKEN_LIMIT_FIELD=max_completion_tokens
37
+ # OpenAI or Anthropic through a gateway: MAYURA_MODEL_PROVIDER=openai or anthropic, MAYURA_MODEL_ENDPOINT set to its
38
+ # endpoint (for Cloudflare, https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/openai/responses or
39
+ # .../anthropic/v1/messages) and MAYURA_MODEL_GATEWAY_TOKEN; the provider key may then stay in the gateway.
40
+ # Cloudflare AI Gateway: https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/compat/chat/completions, models named
41
+ # provider/model, and the gateway token of an authenticated gateway (the API key may stay in the gateway):
42
+ # MAYURA_MODEL_GATEWAY_TOKEN=
32
43
  # MAYURA_MODEL=
33
44
  # Prices in micro-dollars per million tokens, and the most one call and one run may cost.
34
45
  # MAYURA_MODEL_INPUT_MICROS_PER_MILLION_TOKENS=
@@ -20,8 +20,7 @@
20
20
  "dependencies": {
21
21
  "better-sqlite3": "13.0.3",
22
22
  "mayura": "workspace:*",
23
- "pg": "8.23.0",
24
- "zod": "4.6.5"
23
+ "pg": "8.23.0"
25
24
  },
26
25
  "devDependencies": {
27
26
  "@types/node": "24.13.6",
@@ -1,5 +1,5 @@
1
1
  import { validatedEnvironment } from 'mayura/helpers';
2
- import { z } from 'zod';
2
+ import { z } from 'mayura';
3
3
 
4
4
  // Every setting comes from the environment and is validated once at startup. Nothing is discovered implicitly:
5
5
  // no config files, no default credentials, and no provider is contacted unless MAYURA_MODEL_PROVIDER says so.
@@ -29,6 +29,13 @@ const schema = z.object({
29
29
  compatibleId: z.string().regex(/^[a-z0-9][a-z0-9-]{0,39}$/u, 'Use a short lower-case id such as groq.').optional(),
30
30
  compatibleAuth: z.enum(['bearer', 'api-key']).default('bearer'),
31
31
  compatibleApiKey: z.string().min(1).optional(),
32
+ // How the provider differs from OpenAI: JSON mode instead of JSON Schema output (DeepSeek), strict tool calls, and
33
+ // a Cloudflare AI Gateway token (sent as cf-aig-authorization; with keys stored in the gateway, no API key is needed).
34
+ compatibleOutput: z.enum(['json_schema', 'json_object']).default('json_schema'),
35
+ compatibleStrictTools: z.enum(['true', 'false']).default('false'),
36
+ // The field for the output-token limit: OpenAI's newer models (also through a gateway) take only max_completion_tokens.
37
+ compatibleTokenLimitField: z.enum(['max_tokens', 'max_completion_tokens']).optional(),
38
+ gatewayToken: z.string().min(1).optional(),
32
39
  modelName: z.string().min(1).max(128).optional(),
33
40
  inputMicrosPerMillionTokens: micros.optional(),
34
41
  outputMicrosPerMillionTokens: micros.optional(),
@@ -39,10 +46,14 @@ const schema = z.object({
39
46
 
40
47
  export type ModelSettings =
41
48
  | { readonly provider: 'offline' }
42
- | { readonly provider: 'openai' | 'anthropic'; readonly apiKey: string; readonly name: string; readonly maxCallCostMicros: number;
49
+ // OpenAI or Anthropic directly, or through a gateway: its endpoint (MAYURA_MODEL_ENDPOINT) and token.
50
+ | { readonly provider: 'openai' | 'anthropic'; readonly apiKey: string | undefined; readonly name: string; readonly maxCallCostMicros: number;
51
+ readonly endpoint: string | undefined; readonly gatewayToken: string | undefined;
43
52
  readonly pricing: { readonly inputMicrosPerMillionTokens: number; readonly outputMicrosPerMillionTokens: number } }
44
- | { readonly provider: 'compatible'; readonly apiKey: string; readonly name: string; readonly maxCallCostMicros: number;
53
+ | { readonly provider: 'compatible'; readonly apiKey: string | undefined; readonly name: string; readonly maxCallCostMicros: number;
45
54
  readonly endpoint: string; readonly providerId: string; readonly auth: 'bearer' | 'api-key';
55
+ readonly output: 'json_schema' | 'json_object'; readonly strictTools: boolean; readonly gatewayToken: string | undefined;
56
+ readonly tokenLimitField: 'max_tokens' | 'max_completion_tokens' | undefined;
46
57
  readonly pricing: { readonly inputMicrosPerMillionTokens: number; readonly outputMicrosPerMillionTokens: number } };
47
58
 
48
59
  export interface Config {
@@ -67,7 +78,8 @@ export async function loadConfig(source: Readonly<Record<string, string | undefi
67
78
  port: 'PORT', bind: 'MAYURA_BIND', publicOrigin: 'MAYURA_PUBLIC_ORIGIN', allowedOrigins: 'MAYURA_ALLOWED_ORIGINS',
68
79
  operatorTokens: 'MAYURA_OPERATOR_TOKEN_SHA256', intakeTokens: 'MAYURA_INTAKE_TOKEN_SHA256',
69
80
  modelProvider: 'MAYURA_MODEL_PROVIDER', openaiApiKey: 'OPENAI_API_KEY', anthropicApiKey: 'ANTHROPIC_API_KEY',
70
- compatibleEndpoint: 'MAYURA_MODEL_ENDPOINT', compatibleId: 'MAYURA_MODEL_PROVIDER_ID', compatibleAuth: 'MAYURA_MODEL_AUTH', compatibleApiKey: 'MAYURA_MODEL_API_KEY', modelName: 'MAYURA_MODEL',
81
+ compatibleEndpoint: 'MAYURA_MODEL_ENDPOINT', compatibleId: 'MAYURA_MODEL_PROVIDER_ID', compatibleAuth: 'MAYURA_MODEL_AUTH', compatibleApiKey: 'MAYURA_MODEL_API_KEY',
82
+ compatibleOutput: 'MAYURA_MODEL_OUTPUT', compatibleStrictTools: 'MAYURA_MODEL_STRICT_TOOLS', compatibleTokenLimitField: 'MAYURA_MODEL_TOKEN_LIMIT_FIELD', gatewayToken: 'MAYURA_MODEL_GATEWAY_TOKEN', modelName: 'MAYURA_MODEL',
71
83
  inputMicrosPerMillionTokens: 'MAYURA_MODEL_INPUT_MICROS_PER_MILLION_TOKENS', outputMicrosPerMillionTokens: 'MAYURA_MODEL_OUTPUT_MICROS_PER_MILLION_TOKENS',
72
84
  maxCallCostMicros: 'MAYURA_MODEL_MAX_CALL_COST_MICROS', maxRunCostMicros: 'MAYURA_MAX_RUN_COST_MICROS', refundLimitCents: 'REFUND_LIMIT_CENTS',
73
85
  },
@@ -96,12 +108,18 @@ function modelSettings(value: z.infer<typeof schema>): ModelSettings {
96
108
  if (value.modelProvider === 'compatible' && (!value.compatibleEndpoint || !value.compatibleId)) {
97
109
  throw new Error('MAYURA_MODEL_PROVIDER=compatible requires MAYURA_MODEL_ENDPOINT (the https://.../chat/completions URL) and MAYURA_MODEL_PROVIDER_ID (such as groq).');
98
110
  }
99
- if (!apiKey || !value.modelName || value.inputMicrosPerMillionTokens === undefined || value.outputMicrosPerMillionTokens === undefined || value.maxCallCostMicros === 0) {
111
+ // A gateway with a token may hold the provider key itself: the compatible endpoint, or OpenAI's or Anthropic's through
112
+ // a gateway endpoint.
113
+ const gatewayOnly = value.gatewayToken !== undefined && (value.modelProvider === 'compatible' || value.compatibleEndpoint !== undefined);
114
+ if ((!apiKey && !gatewayOnly) || !value.modelName || value.inputMicrosPerMillionTokens === undefined || value.outputMicrosPerMillionTokens === undefined || value.maxCallCostMicros === 0) {
100
115
  throw new Error(`MAYURA_MODEL_PROVIDER=${value.modelProvider} requires ${keyName}, MAYURA_MODEL, both MAYURA_MODEL_*_MICROS_PER_MILLION_TOKENS prices and MAYURA_MODEL_MAX_CALL_COST_MICROS.`);
101
116
  }
102
117
  if (value.maxRunCostMicros < value.maxCallCostMicros) throw new Error('MAYURA_MAX_RUN_COST_MICROS must cover at least one model call.');
103
118
  const pricing = { inputMicrosPerMillionTokens: value.inputMicrosPerMillionTokens, outputMicrosPerMillionTokens: value.outputMicrosPerMillionTokens };
104
119
  if (value.modelProvider === 'compatible') return { provider: 'compatible', apiKey, name: value.modelName, maxCallCostMicros: value.maxCallCostMicros,
105
- endpoint: value.compatibleEndpoint!, providerId: value.compatibleId!, auth: value.compatibleAuth, pricing };
106
- return { provider: value.modelProvider, apiKey, name: value.modelName, maxCallCostMicros: value.maxCallCostMicros, pricing };
120
+ endpoint: value.compatibleEndpoint!, providerId: value.compatibleId!, auth: value.compatibleAuth, pricing,
121
+ output: value.compatibleOutput, strictTools: value.compatibleStrictTools === 'true', gatewayToken: value.gatewayToken,
122
+ tokenLimitField: value.compatibleTokenLimitField };
123
+ return { provider: value.modelProvider, apiKey, name: value.modelName, maxCallCostMicros: value.maxCallCostMicros, pricing,
124
+ endpoint: value.compatibleEndpoint, gatewayToken: value.gatewayToken };
107
125
  }
@@ -1,6 +1,5 @@
1
1
  import type { ModelAdapter, ModelRequest, ModelResponse } from 'mayura/core';
2
- import { defineAgent, defineTool } from 'mayura';
3
- import { z } from 'zod';
2
+ import { defineAgent, defineTool, z } from 'mayura';
4
3
  import type { ModelSettings } from './config.js';
5
4
  import { jsonSchema, selectModel } from './model.js';
6
5
  import { refundRequest, type RefundRequest } from './workflow.js';
@@ -1,7 +1,7 @@
1
1
  import type { JsonObject, ModelAdapter } from 'mayura/core';
2
2
  import { anthropicMessages } from 'mayura/provider-anthropic';
3
3
  import { openAICompatibleChat, openAIResponses } from 'mayura/provider-openai';
4
- import { z } from 'zod';
4
+ import { z } from 'mayura';
5
5
  import type { ModelSettings } from './config.js';
6
6
 
7
7
  /**
@@ -12,12 +12,19 @@ import type { ModelSettings } from './config.js';
12
12
  */
13
13
  export function selectModel(settings: ModelSettings, agent: { readonly outputJsonSchema: JsonObject; readonly offline: ModelAdapter }): ModelAdapter {
14
14
  if (settings.provider === 'offline') return agent.offline;
15
- const options = { apiKey: settings.apiKey, model: settings.name, outputJsonSchema: agent.outputJsonSchema,
15
+ const options = { model: settings.name, outputJsonSchema: agent.outputJsonSchema,
16
16
  maxCostMicros: settings.maxCallCostMicros, pricing: settings.pricing, timeoutMs: 30_000 };
17
17
  if (settings.provider === 'compatible') {
18
- return openAICompatibleChat({ ...options, endpoint: settings.endpoint, remote: { id: settings.providerId, auth: settings.auth } });
18
+ return openAICompatibleChat({ ...options, ...(settings.apiKey ? { apiKey: settings.apiKey } : {}), endpoint: settings.endpoint,
19
+ remote: { id: settings.providerId, auth: settings.auth }, output: settings.output, strictTools: settings.strictTools,
20
+ ...(settings.tokenLimitField ? { tokenLimitField: settings.tokenLimitField } : {}),
21
+ ...(settings.gatewayToken ? { headers: { 'cf-aig-authorization': `Bearer ${settings.gatewayToken}` } } : {}) });
19
22
  }
20
- return settings.provider === 'openai' ? openAIResponses(options) : anthropicMessages(options);
23
+ // Directly, or through a gateway (MAYURA_MODEL_ENDPOINT, with MAYURA_MODEL_GATEWAY_TOKEN; the key may stay in the gateway).
24
+ const headers = settings.gatewayToken ? { 'cf-aig-authorization': `Bearer ${settings.gatewayToken}` } : undefined;
25
+ const via = { ...(settings.endpoint ? { endpoint: settings.endpoint } : {}), ...(headers ? { headers } : {}) };
26
+ const credentials = settings.apiKey ? { apiKey: settings.apiKey, ...via } : { endpoint: settings.endpoint!, headers: headers! };
27
+ return settings.provider === 'openai' ? openAIResponses({ ...options, ...credentials }) : anthropicMessages({ ...options, ...credentials });
21
28
  }
22
29
 
23
30
  /** Runtimes must allow each model explicitly, as `model:<adapter id>`. */
@@ -1,7 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { defineTool } from 'mayura';
2
+ import { defineTool, z } from 'mayura';
3
3
  import { defineWorkflowLifecycle, defineWorkflowMigration } from 'mayura/workflows/lifecycle';
4
- import { z } from 'zod';
5
4
 
6
5
  const identifier = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/u);
7
6