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
@@ -0,0 +1,170 @@
1
+ import { existsSync, realpathSync } from 'node:fs';
2
+ import { lstat, mkdir, open, readdir, realpath, stat } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { defineTool, type AnyTool, z } from 'mayura';
5
+ import { confirmBeforeRunning } from 'mayura/terminal';
6
+
7
+ // The assistant's file tools, confined to one folder (the workspace). This is the whole safety story of the tools, so
8
+ // it is written to be read:
9
+ // - Paths are relative to the workspace. Absolute paths, `..` that leaves it, and symbolic links that lead out of it are
10
+ // refused, by checking the real path on disk, not just the text.
11
+ // - Secrets and machinery are never read, listed or written: `.env` files, `.git` and `node_modules`.
12
+ // - Everything is bounded: file sizes, listing sizes and search work.
13
+ // - Writing is the only tool that changes anything, and a person at the terminal confirms every write first
14
+ // (`confirmBeforeRunning`). With nobody at a terminal (piped, scripted), writes are refused.
15
+ // Tools answer ordinary problems ("no such file") with a result the model can read, instead of throwing: a failed
16
+ // tool call would end the turn.
17
+
18
+ const MAX_READ_BYTES = 64 * 1_024;
19
+ const MAX_WRITE_BYTES = 256 * 1_024;
20
+ const MAX_ENTRIES = 200;
21
+ const MAX_MATCHES = 50;
22
+ const MAX_SEARCHED_FILES = 2_000;
23
+ const MAX_SEARCHED_BYTES = 256 * 1_024;
24
+
25
+ /** A path segment the assistant never touches. */
26
+ const off = (segment: string): boolean => segment === '.git' || segment === 'node_modules' || /^\.env(?:\..*)?$/iu.test(segment);
27
+
28
+ export type Resolved = { readonly ok: true; readonly absolute: string; readonly path: string } | { readonly ok: false; readonly reason: string };
29
+
30
+ /** Where a workspace-relative path points, or why it is refused. `forWrite` allows a file (and folders) that do not exist yet. */
31
+ export async function resolveInWorkspace(root: string, requested: string, forWrite = false): Promise<Resolved> {
32
+ const text = requested.trim().replaceAll('\\', '/');
33
+ if (!text || isAbsolute(text) || /^[A-Za-z]:/u.test(text)) return { ok: false, reason: 'Use a path relative to the workspace folder.' };
34
+ const absolute = resolve(root, text);
35
+ const path = relative(root, absolute).split(sep).join('/') || '.';
36
+ if (path === '..' || path.startsWith('../')) return { ok: false, reason: 'That path is outside the workspace folder.' };
37
+ if (path.split('/').some(off)) return { ok: false, reason: 'The assistant does not open .env files, .git or node_modules.' };
38
+ // The real location must still be inside the workspace: a symbolic link must not lead out of it.
39
+ let existing = absolute;
40
+ while (!existsSync(existing)) { if (!forWrite) return { ok: false, reason: `There is no ${path} in the workspace.` }; existing = dirname(existing); }
41
+ // Both sides are resolved the same way, so a root named through a link or a Windows short name (C:\PROGRA~1, which
42
+ // only some realpath functions expand) is compared as the folder it really is.
43
+ const real = await realpath(existing); const inside = relative(await realpath(root), real);
44
+ if (inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside)) return { ok: false, reason: 'That path leads outside the workspace folder.' };
45
+ return { ok: true, absolute, path };
46
+ }
47
+
48
+ /** Read at most `limit` bytes of a file; `null` when it is not UTF-8 text. */
49
+ async function readText(absolute: string, limit: number): Promise<{ readonly text: string; readonly truncated: boolean } | null> {
50
+ const handle = await open(absolute, 'r');
51
+ try {
52
+ const buffer = Buffer.alloc(limit + 1); const { bytesRead } = await handle.read(buffer, 0, limit + 1, 0);
53
+ const bytes = buffer.subarray(0, Math.min(bytesRead, limit));
54
+ if (bytes.includes(0)) return null;
55
+ // A cut may split a character at the end; decode leniently there, but refuse text that is not UTF-8 elsewhere.
56
+ const text = new TextDecoder('utf-8', { fatal: bytesRead <= limit }).decode(bytes);
57
+ return { text, truncated: bytesRead > limit };
58
+ } catch { return null; } finally { await handle.close(); }
59
+ }
60
+
61
+ const relativePath = z.string().min(1).max(512).describe('A path relative to the workspace folder, such as "src" or "README.md". Use "." for the folder itself.');
62
+
63
+ export function workspaceTools(workspace: string): { readonly tools: readonly AnyTool[]; readonly permissions: readonly string[] } {
64
+ const root = realpathSync(workspace);
65
+
66
+ const list = defineTool({
67
+ id: 'files.list', version: '1', effects: 'read', capabilities: [],
68
+ description: 'List the files and folders in a folder of the workspace, with file sizes. Start with "." to see the top level.',
69
+ input: z.strictObject({ path: relativePath }),
70
+ output: z.union([
71
+ z.strictObject({ found: z.literal(true), path: z.string(), entries: z.array(z.strictObject({ name: z.string(), kind: z.enum(['file', 'folder']), bytes: z.number().int().nullable() })), truncated: z.boolean() }),
72
+ z.strictObject({ found: z.literal(false), path: z.string(), reason: z.string() }),
73
+ ]),
74
+ execute: async ({ path }) => {
75
+ const target = await resolveInWorkspace(root, path);
76
+ if (!target.ok) return { found: false as const, path, reason: target.reason };
77
+ if (!(await stat(target.absolute)).isDirectory()) return { found: false as const, path: target.path, reason: `${target.path} is a file, not a folder; read it instead.` };
78
+ const names = (await readdir(target.absolute, { withFileTypes: true })).filter(entry => !off(entry.name)).sort((a, b) => a.name.localeCompare(b.name));
79
+ const entries = [];
80
+ for (const entry of names.slice(0, MAX_ENTRIES)) {
81
+ const details = await lstat(join(target.absolute, entry.name));
82
+ entries.push({ name: entry.name, kind: details.isDirectory() ? 'folder' as const : 'file' as const, bytes: details.isFile() ? details.size : null });
83
+ }
84
+ return { found: true as const, path: target.path, entries, truncated: names.length > MAX_ENTRIES };
85
+ },
86
+ });
87
+
88
+ const read = defineTool({
89
+ id: 'files.read', version: '1', effects: 'read', capabilities: [],
90
+ description: `Read a text file in the workspace (up to ${MAX_READ_BYTES / 1_024} KiB; longer files are cut and marked truncated).`,
91
+ input: z.strictObject({ path: relativePath }),
92
+ output: z.union([
93
+ z.strictObject({ found: z.literal(true), path: z.string(), content: z.string(), truncated: z.boolean() }),
94
+ z.strictObject({ found: z.literal(false), path: z.string(), reason: z.string() }),
95
+ ]),
96
+ execute: async ({ path }) => {
97
+ const target = await resolveInWorkspace(root, path);
98
+ if (!target.ok) return { found: false as const, path, reason: target.reason };
99
+ if (!(await stat(target.absolute)).isFile()) return { found: false as const, path: target.path, reason: `${target.path} is a folder; list it instead.` };
100
+ const content = await readText(target.absolute, MAX_READ_BYTES);
101
+ if (!content) return { found: false as const, path: target.path, reason: `${target.path} is not a text file.` };
102
+ return { found: true as const, path: target.path, content: content.text, truncated: content.truncated };
103
+ },
104
+ });
105
+
106
+ const search = defineTool({
107
+ id: 'files.search', version: '1', effects: 'read', capabilities: [],
108
+ description: `Find lines containing some text (case-insensitive) in the workspace's text files. Returns up to ${MAX_MATCHES} matches with file and line number.`,
109
+ input: z.strictObject({ query: z.string().min(1).max(200).describe('The text to look for.') }),
110
+ output: z.strictObject({ query: z.string(), matches: z.array(z.strictObject({ path: z.string(), line: z.number().int(), text: z.string() })), truncated: z.boolean(), filesSearched: z.number().int() }),
111
+ execute: async ({ query }, context) => {
112
+ const needle = query.toLowerCase(); const matches: { path: string; line: number; text: string }[] = [];
113
+ let filesSearched = 0; let truncated = false;
114
+ // Breadth-first over the workspace, never following links and skipping what the assistant may not open.
115
+ const pending = [root];
116
+ while (pending.length && !truncated) {
117
+ if (context.signal.aborted) break;
118
+ const folder = pending.shift()!;
119
+ for (const entry of (await readdir(folder, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
120
+ if (off(entry.name) || entry.isSymbolicLink()) continue;
121
+ const absolute = join(folder, entry.name);
122
+ if (entry.isDirectory()) { pending.push(absolute); continue; }
123
+ if (!entry.isFile()) continue;
124
+ if (++filesSearched > MAX_SEARCHED_FILES) { truncated = true; break; }
125
+ const content = await readText(absolute, MAX_SEARCHED_BYTES); if (!content) continue;
126
+ const lines = content.text.split(/\r?\n/u);
127
+ for (let index = 0; index < lines.length; index++) {
128
+ if (!lines[index]!.toLowerCase().includes(needle)) continue;
129
+ if (matches.length === MAX_MATCHES) { truncated = true; break; }
130
+ matches.push({ path: relative(root, absolute).split(sep).join('/'), line: index + 1, text: lines[index]!.trim().slice(0, 300) });
131
+ }
132
+ if (truncated) break;
133
+ }
134
+ }
135
+ return { query, matches, truncated, filesSearched: Math.min(filesSearched, MAX_SEARCHED_FILES) };
136
+ },
137
+ });
138
+
139
+ const write = defineTool({
140
+ id: 'files.write', version: '1', effects: 'write', capabilities: ['files:write'],
141
+ description: 'Create or replace a text file in the workspace with the given content. Only when the person asks for it.',
142
+ input: z.strictObject({ path: relativePath, content: z.string().max(MAX_WRITE_BYTES).describe('The complete new content of the file.') }),
143
+ output: z.union([
144
+ z.strictObject({ written: z.literal(true), path: z.string(), bytes: z.number().int(), created: z.boolean() }),
145
+ z.strictObject({ written: z.literal(false), path: z.string(), reason: z.string() }),
146
+ ]),
147
+ execute: async ({ path, content }) => {
148
+ const target = await resolveInWorkspace(root, path, true);
149
+ if (!target.ok) return { written: false as const, path, reason: target.reason };
150
+ const created = !existsSync(target.absolute);
151
+ if (!created && !(await stat(target.absolute)).isFile()) return { written: false as const, path: target.path, reason: `${target.path} is a folder.` };
152
+ await mkdir(dirname(target.absolute), { recursive: true });
153
+ const handle = await open(target.absolute, 'w');
154
+ try { await handle.writeFile(content, 'utf8'); } finally { await handle.close(); }
155
+ return { written: true as const, path: target.path, bytes: Buffer.byteLength(content), created };
156
+ },
157
+ });
158
+
159
+ // What the person sees before they allow a write: the file, whether it is new, and the start of the new content.
160
+ const confirmedWrite = confirmBeforeRunning(write, {
161
+ describe: ({ path, content }) => {
162
+ const lines = content.split(/\r?\n/u); const shown = lines.slice(0, 20).join('\n');
163
+ const exists = existsSync(resolve(root, path.replaceAll('\\', '/')));
164
+ return `${exists ? 'Replace' : 'Create'} ${path} (${Buffer.byteLength(content)} bytes)\n\n${shown}${lines.length > 20 ? `\n… ${lines.length - 20} more lines` : ''}`;
165
+ },
166
+ });
167
+
168
+ const tools = [list, read, search, confirmedWrite];
169
+ return { tools, permissions: ['tool:files.list', 'tool:files.read', 'tool:files.search', 'tool:files.write', 'files:write', 'effect:read', 'effect:write'] };
170
+ }
@@ -0,0 +1,205 @@
1
+ import assert from 'node:assert/strict';
2
+ import { existsSync, realpathSync } from 'node:fs';
3
+ import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { PassThrough, Writable } from 'node:stream';
7
+ import { after, before, describe, it } from 'node:test';
8
+ import { createRuntime, defineAgent } from 'mayura';
9
+ import { runAgentCommand } from 'mayura/terminal';
10
+ import { scriptedModel, testImage } from 'mayura/testing';
11
+ import { anthropicMessages } from 'mayura/provider-anthropic';
12
+ import { openAICompatibleChat, openAIResponses } from 'mayura/provider-openai';
13
+ import { createSkillSet, loadSkills } from 'mayura/skills';
14
+ import { assistantInput, assistantOutput, workspaceAssistant } from '../src/assistant.js';
15
+ import { main } from '../src/cli.js';
16
+ import { bundledSkills, loadConfig } from '../src/config.js';
17
+ import { resolveInWorkspace } from '../src/workspace.js';
18
+ import { selectModel } from '../src/model.js';
19
+
20
+ // Everything runs offline, on the rule-based stand-in model, in a temporary workspace folder.
21
+
22
+ let workspace: string; let outside: string;
23
+ before(async () => {
24
+ workspace = await mkdtemp(join(tmpdir(), 'assistant-workspace-'));
25
+ outside = await mkdtemp(join(tmpdir(), 'assistant-outside-'));
26
+ await mkdir(join(workspace, 'src')); await mkdir(join(workspace, 'node_modules', 'dep'), { recursive: true });
27
+ await writeFile(join(workspace, 'README.md'), '# Demo\n\nA small project.\n');
28
+ await writeFile(join(workspace, 'src', 'index.ts'), 'export const answer = 42; // TODO: explain the answer\n');
29
+ await writeFile(join(workspace, '.env'), 'SECRET_TOKEN=do-not-show-me\n');
30
+ await writeFile(join(workspace, 'node_modules', 'dep', 'index.js'), '// TODO inside a dependency\n');
31
+ await writeFile(join(outside, 'private.txt'), 'outside the workspace\n');
32
+ });
33
+ after(async () => { await rm(workspace, { recursive: true, force: true }); await rm(outside, { recursive: true, force: true }); });
34
+
35
+ const env = (): Record<string, string> => ({ ASSISTANT_ROOT: workspace });
36
+ /** Run `assistant <argv>` with captured output and a non-terminal stdin, as a script would. */
37
+ async function ask(...argv: string[]): Promise<{ code: number; out: string; err: string }> {
38
+ let out = ''; let err = '';
39
+ const stdout = Object.assign(new Writable({ write(chunk, _encoding, done) { out += String(chunk); done(); } }), { isTTY: false });
40
+ const stderr = new Writable({ write(chunk, _encoding, done) { err += String(chunk); done(); } });
41
+ const stdin = Object.assign(new PassThrough(), { isTTY: false }); stdin.end();
42
+ const code = await main(argv, { env: env(), io: { stdin, stdout, stderr } });
43
+ return { code, out, err };
44
+ }
45
+
46
+ describe('one-shot requests', () => {
47
+ it('list, read and search the workspace', async () => {
48
+ const listed = await ask('list', 'files');
49
+ assert.equal(listed.code, 0); assert.match(listed.out, /README\.md \(\d+ bytes\)/u); assert.match(listed.out, /src\//u);
50
+ assert.doesNotMatch(listed.out, /node_modules|\.env/u, 'secrets and dependencies are not listed');
51
+ assert.match((await ask('read', 'README.md')).out, /A small project\./u);
52
+ const found = await ask('search', 'TODO');
53
+ assert.match(found.out, /src\/index\.ts:1/u);
54
+ assert.doesNotMatch(found.out, /dependency/u, 'node_modules is not searched');
55
+ const json = JSON.parse((await ask('--json', 'read', 'src/index.ts')).out) as { status: string; output: { reply: string }; spentMicros: number };
56
+ assert.equal(json.status, 'succeeded'); assert.match(json.output.reply, /answer = 42/u); assert.equal(json.spentMicros, 0);
57
+ });
58
+
59
+ it('resolve a workspace named through a link or a short name as the folder it is (found by CI)', async () => {
60
+ // Windows runners name the temporary folder with an 8.3 short name, which realpathSync keeps and realpath expands.
61
+ const short = 'C:\\PROGRA~1';
62
+ if (process.platform === 'win32' && existsSync(short) && realpathSync(short) !== realpathSync.native(short)) {
63
+ assert.deepEqual(await resolveInWorkspace(short, '.'), { ok: true, absolute: short, path: '.' });
64
+ }
65
+ const link = join(outside, 'linked-workspace'); let linked = true;
66
+ try { await symlink(workspace, link, 'junction'); } catch { linked = false; }
67
+ if (linked) {
68
+ try {
69
+ assert.equal((await resolveInWorkspace(link, 'README.md')).ok, true);
70
+ assert.equal((await resolveInWorkspace(link, '../private.txt')).ok, false);
71
+ } finally { await rm(link, { recursive: true, force: true }); }
72
+ }
73
+ });
74
+
75
+ it('never leave the workspace or open secrets, even through a link', async () => {
76
+ assert.match((await ask('read', '../private.txt')).out, /outside the workspace folder/u);
77
+ const secret = await ask('read', '.env');
78
+ assert.match(secret.out, /does not open \.env files/u); assert.doesNotMatch(secret.out, /do-not-show-me/u);
79
+ assert.match((await ask('read', join(outside, 'private.txt'))).out, /relative to the workspace/u);
80
+ // A link inside the workspace that points out of it is refused too (skipped where links need extra rights).
81
+ let linked = true;
82
+ try { await symlink(outside, join(workspace, 'escape'), 'junction'); } catch { linked = false; }
83
+ if (linked) {
84
+ const escaped = await ask('read', 'escape/private.txt');
85
+ assert.match(escaped.out, /leads outside the workspace folder/u); assert.doesNotMatch(escaped.out, /outside the workspace\n/u);
86
+ await rm(join(workspace, 'escape'), { recursive: true, force: true });
87
+ }
88
+ });
89
+
90
+ it('refuse to write without a person at the terminal to confirm', async () => {
91
+ const refused = await ask('write', 'notes.txt:', 'hello');
92
+ assert.equal(refused.code, 1); assert.match(refused.err, /files\.write needs a person to confirm it/u);
93
+ assert.equal(existsSync(join(workspace, 'notes.txt')), false);
94
+ });
95
+
96
+ it('load a skill when a task matches it', async () => {
97
+ const answer = await ask('how', 'do', 'I', 'write', 'release', 'notes?');
98
+ assert.equal(answer.code, 0); assert.match(answer.out, /From the release-notes skill/u); assert.match(answer.out, /\*\*Breaking\*\*/u);
99
+ });
100
+
101
+ it('print help, and explain a bad setting instead of a stack trace', async () => {
102
+ assert.match((await ask('--help')).out, /assistant chat {11}chat with the assistant/u);
103
+ let err = '';
104
+ const code = await main(['list', 'files'], { env: { ASSISTANT_ROOT: join(workspace, 'missing') },
105
+ io: { stderr: new Writable({ write(chunk, _encoding, done) { err += String(chunk); done(); } }) } });
106
+ assert.equal(code, 1); assert.match(err, /ASSISTANT_ROOT must be an existing folder/u);
107
+ });
108
+ });
109
+
110
+ /** A fake terminal for the chat: keystrokes are typed only once the expected prompt is on screen. */
111
+ function terminal() {
112
+ const input = new PassThrough(); let raw = '';
113
+ const output = Object.assign(new Writable({ write(chunk, _encoding, done) { raw += String(chunk); done(); } }), { columns: 100, rows: 40 });
114
+ const screen = (): string => raw.replace(/\u001b\[[0-9;?]*[A-Za-z]/gu, '');
115
+ const count = (text: string): number => screen().split(text).length - 1;
116
+ const waitFor = async (predicate: () => boolean, label: string): Promise<void> => {
117
+ const deadline = Date.now() + 10_000;
118
+ while (!predicate()) { if (Date.now() > deadline) throw new Error(`Timed out waiting for ${label}.\n${screen().slice(-1_500)}`); await new Promise(resolve => setTimeout(resolve, 10)); }
119
+ };
120
+ const type = async (keys: string): Promise<void> => { for (const key of keys) { input.write(key); await new Promise(resolve => setTimeout(resolve, 2)); } };
121
+ // The prompt symbol is ◆, or * where the terminal cannot show Unicode.
122
+ const prompts = (): number => screen().match(/[◆*] {2}You/gu)?.length ?? 0;
123
+ const say = async (n: number, text: string): Promise<void> => { await waitFor(() => prompts() >= n, `prompt ${n}`); await type(`${text}\r`); };
124
+ return { input, output, screen, count, waitFor, type, say };
125
+ }
126
+
127
+ describe('chat', () => {
128
+ it('writes a file only after the person allows it, and shows what it will write', async () => {
129
+ const t = terminal();
130
+ const chat = main(['chat'], { env: env(), io: { input: t.input, output: t.output } });
131
+ await t.say(1, 'write todo.md: buy milk');
132
+ await t.waitFor(() => t.screen().includes('Allow it?'), 'first confirmation');
133
+ assert.match(t.screen(), /Create todo\.md \(9 bytes\)/u); assert.match(t.screen(), /buy milk/u);
134
+ await t.type('\r'); // the default answer is No
135
+ await t.waitFor(() => t.screen().includes('The person declined files.write.'), 'refusal');
136
+ assert.equal(existsSync(join(workspace, 'todo.md')), false);
137
+ await t.say(2, 'write todo.md: buy milk');
138
+ await t.waitFor(() => t.count('Allow it?') >= 2, 'second confirmation');
139
+ await t.type('\u001b[D\r'); // left arrow: Yes
140
+ await t.waitFor(() => t.screen().includes('Created todo.md (9 bytes).'), 'written');
141
+ assert.equal(await readFile(join(workspace, 'todo.md'), 'utf8'), 'buy milk\n');
142
+ await t.say(3, '/exit');
143
+ assert.equal(await chat, 0);
144
+ await rm(join(workspace, 'todo.md'));
145
+ });
146
+ });
147
+
148
+ describe('real model providers', () => {
149
+ it('accept every tool schema and the output schema', async () => {
150
+ // defineAgent asks each adapter to check the agent's schemas against its provider's rules; nothing is sent.
151
+ const skills = await loadSkills(bundledSkills);
152
+ const pricing = { inputMicrosPerMillionTokens: 1, outputMicrosPerMillionTokens: 1 };
153
+ const adapters = [openAIResponses({ apiKey: 'unused', model: 'unused', maxCostMicros: 1, pricing }),
154
+ anthropicMessages({ apiKey: 'unused', model: 'unused', maxCostMicros: 1, pricing }),
155
+ openAICompatibleChat({ endpoint: 'https://api.example.com/v1/chat/completions', remote: { id: 'example' }, apiKey: 'unused', model: 'unused', maxCostMicros: 1, pricing })];
156
+ for (const model of adapters) {
157
+ const { agent } = workspaceAssistant({ root: workspace, skills, model: { provider: 'offline' }, modelOverride: model });
158
+ assert.ok(agent.outputJsonSchema, `${model.id} receives the output schema`);
159
+ assert.doesNotThrow(() => defineAgent({ id: 'check', version: '1', instructions: 'x', input: assistantInput, output: assistantOutput, tools: agent.tools, model }));
160
+ }
161
+ });
162
+ });
163
+
164
+ describe('attachments', () => {
165
+ it('send attached images to a model that can see, and are refused offline', async () => {
166
+ const png = join(outside, 'shot.png'); await writeFile(png, (testImage() as { data: Uint8Array }).data);
167
+ const offline = await ask('--attach', png, 'what is this?');
168
+ assert.equal(offline.code, 1); assert.match(offline.err, /does not take attachments/u);
169
+ let seen: readonly { readonly mediaType: string; readonly name?: string }[] = [];
170
+ const model = scriptedModel([request => {
171
+ const first = request.messages[0]; seen = first && first.role === 'user' ? first.media ?? [] : [];
172
+ return { type: 'final', output: { reply: 'A single pixel.' }, usage: { costMicros: 0 } };
173
+ }]);
174
+ const { agent, permissions } = workspaceAssistant({ root: workspace, skills: createSkillSet([]), model: { provider: 'offline' }, modelOverride: model });
175
+ const runtime = createRuntime({ profile: 'ephemeral', permissions: { allow: permissions } });
176
+ let out = '';
177
+ const stdout = Object.assign(new Writable({ write(chunk, _encoding, done) { out += String(chunk); done(); } }), { isTTY: false });
178
+ const stdin = Object.assign(new PassThrough(), { isTTY: false }); stdin.end();
179
+ try {
180
+ assert.equal(await runAgentCommand({ agent, runtime, name: 'assistant', argv: ['--attach', png, 'what is this?'], io: { stdin, stdout, stderr: new Writable({ write(_c, _e, done) { done(); } }) } }), 0);
181
+ } finally { await runtime.close(); }
182
+ assert.match(out, /A single pixel\./u);
183
+ assert.deepEqual(seen.map(item => [item.mediaType, item.name]), [['image/png', 'shot.png']]);
184
+ });
185
+ });
186
+
187
+ describe('configuration', () => {
188
+ it('runs offline in the current folder by default, and needs a key, prices and caps for a real model', async () => {
189
+ const config = await loadConfig({}, workspace);
190
+ assert.equal(config.root, workspace); assert.deepEqual(config.model, { provider: 'offline' }); assert.equal(config.skillsDirectory, bundledSkills);
191
+ await assert.rejects(loadConfig({ MAYURA_MODEL_PROVIDER: 'anthropic' }, workspace), /ANTHROPIC_API_KEY/u);
192
+ await assert.rejects(loadConfig({ MAYURA_MODEL_PROVIDER: 'compatible', MAYURA_MODEL_API_KEY: 'k' }, workspace), /MAYURA_MODEL_ENDPOINT/u);
193
+ const paid = await loadConfig({ MAYURA_MODEL_PROVIDER: 'openai', OPENAI_API_KEY: 'k', MAYURA_MODEL: 'm', MAYURA_MODEL_INPUT_MICROS_PER_MILLION_TOKENS: '1',
194
+ MAYURA_MODEL_OUTPUT_MICROS_PER_MILLION_TOKENS: '1', MAYURA_MODEL_MAX_CALL_COST_MICROS: '10', MAYURA_MAX_RUN_COST_MICROS: '100' }, workspace);
195
+ assert.equal(paid.model.provider, 'openai'); assert.equal(paid.maxRunCostMicros, 100);
196
+ // Anthropic through Cloudflare AI Gateway, with the key held by the gateway: an endpoint and token, no key.
197
+ const gateway = await loadConfig({ MAYURA_MODEL_PROVIDER: 'anthropic', MAYURA_MODEL: 'claude-sonnet-5',
198
+ MAYURA_MODEL_ENDPOINT: 'https://gateway.ai.cloudflare.com/v1/account/default/anthropic/v1/messages', MAYURA_MODEL_GATEWAY_TOKEN: 'fixture-gateway-token',
199
+ MAYURA_MODEL_INPUT_MICROS_PER_MILLION_TOKENS: '1', MAYURA_MODEL_OUTPUT_MICROS_PER_MILLION_TOKENS: '1', MAYURA_MODEL_MAX_CALL_COST_MICROS: '10', MAYURA_MAX_RUN_COST_MICROS: '100' }, workspace);
200
+ assert.equal(gateway.model.provider, 'anthropic');
201
+ assert.equal(selectModel(gateway.model, scriptedModel([])).id, 'anthropic.messages');
202
+ await assert.rejects(loadConfig({ MAYURA_MODEL_PROVIDER: 'anthropic', MAYURA_MODEL: 'claude-sonnet-5', MAYURA_MODEL_GATEWAY_TOKEN: 'fixture-gateway-token',
203
+ MAYURA_MODEL_INPUT_MICROS_PER_MILLION_TOKENS: '1', MAYURA_MODEL_OUTPUT_MICROS_PER_MILLION_TOKENS: '1', MAYURA_MODEL_MAX_CALL_COST_MICROS: '10' }, workspace), /ANTHROPIC_API_KEY/u);
204
+ });
205
+ });
@@ -0,0 +1,20 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2023",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
7
+ "strict": true,
8
+ "noUncheckedIndexedAccess": true,
9
+ "exactOptionalPropertyTypes": true,
10
+ "noUnusedLocals": true,
11
+ "noUnusedParameters": true,
12
+ "verbatimModuleSyntax": true,
13
+ "skipLibCheck": false,
14
+ "sourceMap": true,
15
+ "rootDir": ".",
16
+ "outDir": "dist",
17
+ "types": ["node"]
18
+ },
19
+ "include": ["src/**/*.ts", "test/**/*.ts"]
20
+ }
@@ -127,9 +127,10 @@ from `.env`. The image builds from the npm registry, so it needs published Mayur
127
127
 
128
128
  ## Know the limits
129
129
 
130
- - If the triage agent stops part-way (a refused tool, a model error, a timeout, a crash), the tracker may already have
131
- some of its labels or comments, so the intake run ends `outcome_unknown` and is never re-run automatically. Check the
132
- ticket and reconcile it by hand. The console's run list shows active runs only; open a finished run by its id (the
130
+ - If the triage agent fails part-way (a refused tool, a model error), every tracker call it made has a known result:
131
+ the intake run ends `failed`, and labels or comments it already added stay on the ticket. If a call's result is
132
+ unknown (the tracker did not answer, a timeout, a crash mid-call), the run ends `outcome_unknown`. Neither is re-run
133
+ automatically; check the ticket and reconcile it by hand. The console's run list shows active runs only; open a finished run by its id (the
133
134
  ingress returns it to the tracker in its 202 response) with `GET /v1/workflow-runs/<run id>` (or `client.workflow(runId)`).
134
135
  - A delivery whose dispatch failed part-way is answered `500 unconfirmed` and stays that way; the tracker's retries
135
136
  will not start it. A delivery that was being dispatched when a server process died is answered `503 in_progress`
@@ -41,6 +41,17 @@ MAYURA_MODEL_PROVIDER=offline
41
41
  # MAYURA_MODEL_PROVIDER_ID=groq
42
42
  # MAYURA_MODEL_AUTH=bearer
43
43
  # MAYURA_MODEL_API_KEY=
44
+ # DeepSeek answers in JSON mode and has strict tools on https://api.deepseek.com/beta/chat/completions:
45
+ # MAYURA_MODEL_OUTPUT=json_object
46
+ # MAYURA_MODEL_STRICT_TOOLS=true
47
+ # OpenAI's newer models (directly or as openai/... through a gateway) take only max_completion_tokens:
48
+ # MAYURA_MODEL_TOKEN_LIMIT_FIELD=max_completion_tokens
49
+ # OpenAI or Anthropic through a gateway: MAYURA_MODEL_PROVIDER=openai or anthropic, MAYURA_MODEL_ENDPOINT set to its
50
+ # endpoint (for Cloudflare, https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/openai/responses or
51
+ # .../anthropic/v1/messages) and MAYURA_MODEL_GATEWAY_TOKEN; the provider key may then stay in the gateway.
52
+ # Cloudflare AI Gateway: https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/compat/chat/completions, models named
53
+ # provider/model, and the gateway token of an authenticated gateway (the API key may stay in the gateway):
54
+ # MAYURA_MODEL_GATEWAY_TOKEN=
44
55
  # MAYURA_MODEL=
45
56
  # Prices in micro-dollars per million tokens, and the most one call and one triage run may cost.
46
57
  # MAYURA_MODEL_INPUT_MICROS_PER_MILLION_TOKENS=
@@ -22,8 +22,7 @@
22
22
  "dependencies": {
23
23
  "better-sqlite3": "13.0.3",
24
24
  "mayura": "workspace:*",
25
- "pg": "8.23.0",
26
- "zod": "4.6.5"
25
+ "pg": "8.23.0"
27
26
  },
28
27
  "devDependencies": {
29
28
  "@types/node": "24.13.6",
@@ -1,6 +1,6 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { validatedEnvironment } from 'mayura/helpers';
3
- import { z } from 'zod';
3
+ import { z } from 'mayura';
4
4
 
5
5
  // Every setting comes from the environment and is validated once at startup. Nothing is discovered implicitly:
6
6
  // no config files, no default credentials, and no provider is contacted unless MAYURA_MODEL_PROVIDER says so.
@@ -36,6 +36,13 @@ const schema = z.object({
36
36
  compatibleId: z.string().regex(/^[a-z0-9][a-z0-9-]{0,39}$/u, 'Use a short lower-case id such as groq.').optional(),
37
37
  compatibleAuth: z.enum(['bearer', 'api-key']).default('bearer'),
38
38
  compatibleApiKey: z.string().min(1).optional(),
39
+ // How the provider differs from OpenAI: JSON mode instead of JSON Schema output (DeepSeek), strict tool calls, and
40
+ // a Cloudflare AI Gateway token (sent as cf-aig-authorization; with keys stored in the gateway, no API key is needed).
41
+ compatibleOutput: z.enum(['json_schema', 'json_object']).default('json_schema'),
42
+ compatibleStrictTools: z.enum(['true', 'false']).default('false'),
43
+ // The field for the output-token limit: OpenAI's newer models (also through a gateway) take only max_completion_tokens.
44
+ compatibleTokenLimitField: z.enum(['max_tokens', 'max_completion_tokens']).optional(),
45
+ gatewayToken: z.string().min(1).optional(),
39
46
  modelName: z.string().min(1).max(128).optional(),
40
47
  inputMicrosPerMillionTokens: micros.optional(),
41
48
  outputMicrosPerMillionTokens: micros.optional(),
@@ -45,10 +52,14 @@ const schema = z.object({
45
52
 
46
53
  export type ModelSettings =
47
54
  | { readonly provider: 'offline' }
48
- | { readonly provider: 'openai' | 'anthropic'; readonly apiKey: string; readonly name: string; readonly maxCallCostMicros: number;
55
+ // OpenAI or Anthropic directly, or through a gateway: its endpoint (MAYURA_MODEL_ENDPOINT) and token.
56
+ | { readonly provider: 'openai' | 'anthropic'; readonly apiKey: string | undefined; readonly name: string; readonly maxCallCostMicros: number;
57
+ readonly endpoint: string | undefined; readonly gatewayToken: string | undefined;
49
58
  readonly pricing: { readonly inputMicrosPerMillionTokens: number; readonly outputMicrosPerMillionTokens: number } }
50
- | { readonly provider: 'compatible'; readonly apiKey: string; readonly name: string; readonly maxCallCostMicros: number;
59
+ | { readonly provider: 'compatible'; readonly apiKey: string | undefined; readonly name: string; readonly maxCallCostMicros: number;
51
60
  readonly endpoint: string; readonly providerId: string; readonly auth: 'bearer' | 'api-key';
61
+ readonly output: 'json_schema' | 'json_object'; readonly strictTools: boolean; readonly gatewayToken: string | undefined;
62
+ readonly tokenLimitField: 'max_tokens' | 'max_completion_tokens' | undefined;
52
63
  readonly pricing: { readonly inputMicrosPerMillionTokens: number; readonly outputMicrosPerMillionTokens: number } };
53
64
 
54
65
  export interface Config {
@@ -88,7 +99,8 @@ export async function loadConfig(source: Readonly<Record<string, string | undefi
88
99
  webhookSecret: 'WEBHOOK_SECRET', webhookPort: 'WEBHOOK_PORT', trackerUrl: 'TRACKER_MCP_URL', trackerToken: 'TRACKER_MCP_TOKEN',
89
100
  oncallAssignee: 'ONCALL_ASSIGNEE',
90
101
  modelProvider: 'MAYURA_MODEL_PROVIDER', openaiApiKey: 'OPENAI_API_KEY', anthropicApiKey: 'ANTHROPIC_API_KEY',
91
- compatibleEndpoint: 'MAYURA_MODEL_ENDPOINT', compatibleId: 'MAYURA_MODEL_PROVIDER_ID', compatibleAuth: 'MAYURA_MODEL_AUTH', compatibleApiKey: 'MAYURA_MODEL_API_KEY', modelName: 'MAYURA_MODEL',
102
+ compatibleEndpoint: 'MAYURA_MODEL_ENDPOINT', compatibleId: 'MAYURA_MODEL_PROVIDER_ID', compatibleAuth: 'MAYURA_MODEL_AUTH', compatibleApiKey: 'MAYURA_MODEL_API_KEY',
103
+ compatibleOutput: 'MAYURA_MODEL_OUTPUT', compatibleStrictTools: 'MAYURA_MODEL_STRICT_TOOLS', compatibleTokenLimitField: 'MAYURA_MODEL_TOKEN_LIMIT_FIELD', gatewayToken: 'MAYURA_MODEL_GATEWAY_TOKEN', modelName: 'MAYURA_MODEL',
92
104
  inputMicrosPerMillionTokens: 'MAYURA_MODEL_INPUT_MICROS_PER_MILLION_TOKENS', outputMicrosPerMillionTokens: 'MAYURA_MODEL_OUTPUT_MICROS_PER_MILLION_TOKENS',
93
105
  maxCallCostMicros: 'MAYURA_MODEL_MAX_CALL_COST_MICROS', maxRunCostMicros: 'MAYURA_MAX_RUN_COST_MICROS',
94
106
  },
@@ -127,12 +139,18 @@ function modelSettings(value: z.infer<typeof schema>): ModelSettings {
127
139
  if (value.modelProvider === 'compatible' && (!value.compatibleEndpoint || !value.compatibleId)) {
128
140
  throw new Error('MAYURA_MODEL_PROVIDER=compatible requires MAYURA_MODEL_ENDPOINT (the https://.../chat/completions URL) and MAYURA_MODEL_PROVIDER_ID (such as groq).');
129
141
  }
130
- if (!apiKey || !value.modelName || value.inputMicrosPerMillionTokens === undefined || value.outputMicrosPerMillionTokens === undefined || value.maxCallCostMicros === 0) {
142
+ // A gateway with a token may hold the provider key itself: the compatible endpoint, or OpenAI's or Anthropic's through
143
+ // a gateway endpoint.
144
+ const gatewayOnly = value.gatewayToken !== undefined && (value.modelProvider === 'compatible' || value.compatibleEndpoint !== undefined);
145
+ if ((!apiKey && !gatewayOnly) || !value.modelName || value.inputMicrosPerMillionTokens === undefined || value.outputMicrosPerMillionTokens === undefined || value.maxCallCostMicros === 0) {
131
146
  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.`);
132
147
  }
133
148
  if (value.maxRunCostMicros < value.maxCallCostMicros) throw new Error('MAYURA_MAX_RUN_COST_MICROS must cover at least one model call.');
134
149
  const pricing = { inputMicrosPerMillionTokens: value.inputMicrosPerMillionTokens, outputMicrosPerMillionTokens: value.outputMicrosPerMillionTokens };
135
150
  if (value.modelProvider === 'compatible') return { provider: 'compatible', apiKey, name: value.modelName, maxCallCostMicros: value.maxCallCostMicros,
136
- endpoint: value.compatibleEndpoint!, providerId: value.compatibleId!, auth: value.compatibleAuth, pricing };
137
- return { provider: value.modelProvider, apiKey, name: value.modelName, maxCallCostMicros: value.maxCallCostMicros, pricing };
151
+ endpoint: value.compatibleEndpoint!, providerId: value.compatibleId!, auth: value.compatibleAuth, pricing,
152
+ output: value.compatibleOutput, strictTools: value.compatibleStrictTools === 'true', gatewayToken: value.gatewayToken,
153
+ tokenLimitField: value.compatibleTokenLimitField };
154
+ return { provider: value.modelProvider, apiKey, name: value.modelName, maxCallCostMicros: value.maxCallCostMicros, pricing,
155
+ endpoint: value.compatibleEndpoint, gatewayToken: value.gatewayToken };
138
156
  }
@@ -1,11 +1,9 @@
1
- import { createHash } from 'node:crypto';
2
1
  import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
3
2
  import type { AddressInfo } from 'node:net';
4
3
  import { MayuraError } from 'mayura/core';
5
4
  import { StorageError } from 'mayura/storage-contracts';
6
5
  import { createWebhookRuntime, defineWebhookTrigger } from 'mayura/workstream/webhooks';
7
6
  import type { Config } from './config.js';
8
- import { jsonSchema } from './model.js';
9
7
  import type { Services } from './services.js';
10
8
  import { webhookHeaders } from './signing.js';
11
9
  import { ticketCreated } from './triage.js';
@@ -15,8 +13,6 @@ const maxBodyBytes = 65_536;
15
13
  const maxInFlight = 32;
16
14
  /** Deliveries signed more than five minutes before or after our clock are refused, so a captured request goes stale. */
17
15
  const replayWindowMs = 300_000;
18
- // Pins the payload schema into every stored delivery: a schema change is a new trigger version, never a silent reinterpretation.
19
- const schemaDigest = createHash('sha256').update(JSON.stringify(jsonSchema(ticketCreated))).digest('hex');
20
16
 
21
17
  export interface WebhookIngress { readonly url: string; isAccepting(): boolean; close(): Promise<void> }
22
18
 
@@ -35,7 +31,9 @@ export async function startWebhookIngress(config: Config, services: Services): P
35
31
  resolveSecret: async () => new Uint8Array(secret),
36
32
  });
37
33
  const trigger = defineWebhookTrigger({
38
- id: 'tickets.created', version: '1', secretId: 'tracker-webhook', schemaId: 'tickets.created.v1', schemaDigest, input: ticketCreated,
34
+ id: 'tickets.created', version: '1', secretId: 'tracker-webhook', schemaId: 'tickets.created.v1', input: ticketCreated,
35
+ // No schemaDigest: Mayura derives it from `ticketCreated` and pins it into every stored delivery, so a schema change
36
+ // is a new trigger version, never a silent reinterpretation.
39
37
  // Runs once per new delivery, after verification. `commandId` is stable for the delivery, so the intake run is
40
38
  // idempotent on it too: even a dispatch retried after a crash finds the run it already started.
41
39
  dispatch: async (event, { deliveryId, commandId }) => {
@@ -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,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { readFile } from 'node:fs/promises';
3
3
  import { parseArgs } from 'node:util';
4
- import { z } from 'zod';
4
+ import { z } from 'mayura';
5
5
  import { sendDelivery } from './signing.js';
6
6
  import { sampleNames, ticketCreatedEvent, type SampleName } from './tracker/samples.js';
7
7
 
@@ -1,4 +1,4 @@
1
- import { z } from 'zod';
1
+ import { z } from 'mayura';
2
2
  import { startTrackerMcpServer } from './mcp-server.js';
3
3
  import { sampleTickets } from './samples.js';
4
4
  import { memoryTracker } from './tickets.js';
@@ -1,7 +1,7 @@
1
1
  import { createHash, timingSafeEqual } from 'node:crypto';
2
2
  import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
3
3
  import type { AddressInfo } from 'node:net';
4
- import { z } from 'zod';
4
+ import { z } from 'mayura';
5
5
  import { assignee, label, TicketNotFound, ticketId, type TicketTracker } from './tickets.js';
6
6
 
7
7
  /**
@@ -1,4 +1,4 @@
1
- import { z } from 'zod';
1
+ import { z } from 'mayura';
2
2
 
3
3
  // The ticket tracker's own model. In a real deployment this lives in your tracker (Jira, Linear, Zendesk, GitHub
4
4
  // Issues...) and Mayura reaches it only through that tracker's MCP server. The in-memory tracker below backs the
@@ -1,5 +1,5 @@
1
1
  import { defineMcpTool, type McpClient } from 'mayura/adapter-mcp';
2
- import { z } from 'zod';
2
+ import { z } from 'mayura';
3
3
  import { jsonSchema } from './model.js';
4
4
  import { assignee, label, ticketId } from './tracker/tickets.js';
5
5