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 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sHAAsH;AACtH,sGAAsG;AACtG,+GAA+G;AAC/G,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,cAAc,E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EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC;QAC9L,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;IACzD,CAAC;SAAM,IAAI,OAAO,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;QAC1C,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,MAAwB,CAAC,CAAC;QACvD,qHAAqH;QACrH,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAC3F,CAAC;;QACI,MAAM,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,OAAO,KAAK,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC;IACpE,OAAO,OAAO,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAChD,CAAC","sourcesContent":["// Terminal front ends for agents: an interactive chat (`runTerminalChat`) and one-shot commands whose flags come from\n// the agent's input (`runAgentCommand`). A person at the terminal can confirm actions before they run\n// (`confirmBeforeRunning`) and answer the agent's questions (`askPersonTool`); with nobody there, both refuse.\nimport { readFile, stat } from 'node:fs/promises';\nimport { basename } from 'node:path';\nimport type { Readable, Writable } from 'node:stream';\nimport { MayuraError, media, publicError, sniffMediaType, type InferInput, type InferOutput, type JsonObject, type JsonValue, type Media, type Schema } from '@mayura/core';\nimport type { AgentDefinition, Runtime } from '@mayura/runtime';\nimport { defineTool, ToolRefusal, withPreflight, type AnyTool } from '@mayura/tools';\n\n/** Someone at the terminal, for the run currently in a chat turn or command. */\ninterface Person {\n confirm(title: string, detail: string): Promise<boolean>;\n ask(question: string): Promise<string | undefined>;\n}\n// Tools find the person for their run by the run id the runtime passes them; a run with nobody registered is refused.\nconst people = new Map<string, Person>();\n\n/**\n * The same tool, but a person at the terminal sees its input and confirms before it runs. Declining, or running with\n * nobody at a terminal (for example on a server), refuses the call before any effect.\n */\nexport function confirmBeforeRunning<T extends AnyTool>(tool: T, options: { readonly describe?: (input: InferOutput<T['input']>) => string;\n readonly waitMs?: number } = {}): T {\n return withPreflight(tool, async (input, context) => {\n const person = people.get(context.runId);\n if (!person) throw new ToolRefusal(`${tool.id} needs a person to confirm it, and nobody is available.`);\n const detail = options.describe ? options.describe(input) : JSON.stringify(input, null, 2);\n if (!await person.confirm(`Allow ${tool.id}?`, detail)) throw new ToolRefusal(`The person declined ${tool.id}.`);\n }, { extraTimeoutMs: options.waitMs ?? 600_000, description: `${tool.description} (A person confirms each call.)` });\n}\n\nconst questionInput: Schema<{ question: string }> = { '~standard': { version: 1, vendor: 'mayura-terminal', validate: value => {\n const record = value as Record<string, unknown> | null;\n return record && typeof record === 'object' && !Array.isArray(record) && Object.keys(record).length === 1 && typeof record['question'] === 'string'\n && record['question'].length > 0 && record['question'].length <= 2_000 ? { value: { question: record['question'] } } : { issues: [{ message: 'Expected { question }.' }] };\n} } } as Schema<{ question: string }>;\nconst anyOutput: Schema<JsonValue> = { '~standard': { version: 1, vendor: 'mayura-terminal', validate: value => ({ value: value as JsonValue }) } } as Schema<JsonValue>;\n/** A tool the agent calls to ask the person at the terminal a question. Grant `tool:person.ask` and `person:ask`. */\nexport const askPersonTool = defineTool({ id: 'person.ask', version: '1', effects: 'none', capabilities: ['person:ask'], costMicros: 0, timeoutMs: 600_000,\n description: 'Ask the person you are working with a question, when you cannot continue without their answer. Ask one clear question at a time.',\n input: questionInput, output: anyOutput,\n inputJsonSchema: { type: 'object', additionalProperties: false, required: ['question'], properties: { question: { type: 'string', description: 'The question to ask.' } } },\n execute: async ({ question }, context) => {\n const person = people.get(context.runId); if (!person) throw new ToolRefusal('Nobody is available to answer questions.');\n const answer = await person.ask(question); if (answer === undefined) throw new ToolRefusal('The person did not answer.');\n return { answer };\n } });\n\n/** Plain text for a person from an agent's output: a string, or its reply/message/text/answer field, or JSON. */\nexport function outputText(output: unknown): string {\n if (typeof output === 'string') return output;\n if (output && typeof output === 'object' && !Array.isArray(output)) {\n for (const field of ['reply', 'message', 'text', 'answer', 'content', 'response']) {\n const value = (output as Record<string, unknown>)[field]; if (typeof value === 'string') return value;\n }\n }\n return JSON.stringify(output, null, 2);\n}\nconst dollars = (micros: number): string => `$${(micros / 1_000_000).toFixed(micros < 10_000 ? 6 : 4)}`;\nconst spent = (runtime: Runtime, handle: Parameters<Runtime['inspect']>[0]): number => {\n try { const value = runtime.inspect(handle).budget.spentMicros; return typeof value === 'number' ? value : Number(value) || 0; } catch { return 0; }\n};\n\nexport interface ChatTurn { readonly role: 'person' | 'agent'; readonly text: string }\n\n/**\n * The default chat input: the message alone for the first turn, and afterwards the last 20 turns as a transcript\n * followed by the new message, so an agent that takes text remembers the conversation.\n */\nexport function chatTranscript(message: string, history: readonly ChatTurn[]): string {\n if (history.length === 0) return message;\n const earlier = history.slice(-20).map(turn => `${turn.role === 'person' ? 'Person' : 'You'}: ${turn.text}`).join('\\n');\n return `The conversation so far:\\n${earlier}\\n\\nThe person's new message:\\n${message}`;\n}\n\n/** Whether a streamed preview differs from the final answer, which then has to be shown in full. */\nconst differs = (streamed: string, final: string): boolean => streamed.trim() !== final.trim();\nexport interface TerminalChatOptions<I extends Schema, O extends Schema> {\n readonly agent: AgentDefinition<I, O>;\n readonly runtime: Runtime;\n /**\n * The agent's input for a message; `history` holds the earlier turns. The default (`chatTranscript`) passes the\n * message text, with the recent conversation before it after the first turn.\n */\n readonly toInput?: (message: string, history: readonly ChatTurn[]) => InferInput<I>;\n /** What to show for the agent's output; the default is `outputText`. */\n readonly toText?: (output: InferOutput<O>) => string;\n readonly title?: string;\n /** Streams to prompt on; the process's terminal by default. */\n readonly io?: { readonly input?: Readable; readonly output?: Writable };\n}\n\n/** Run an interactive chat with an agent until the person types /exit (or presses Ctrl+C at the prompt). */\nexport async function runTerminalChat<I extends Schema, O extends Schema>(options: TerminalChatOptions<I, O>): Promise<{ readonly turns: number; readonly spentMicros: number }> {\n const prompts = await import('@clack/prompts'); const io = options.io ?? {}; const out = io.output ?? process.stdout;\n const toText = options.toText ?? (value => outputText(value)); const toInput = options.toInput ?? ((message: string, earlier: readonly ChatTurn[]) => chatTranscript(message, earlier) as InferInput<I>);\n const history: ChatTurn[] = []; let turns = 0; let total = 0;\n prompts.intro(options.title ?? ` ${options.agent.id} `, io);\n prompts.log.message('Type a message. /help lists commands.', io);\n for (;;) {\n const message = await prompts.text({ ...io, message: 'You', placeholder: 'Ask something, or /exit' });\n if (prompts.isCancel(message) || message.trim() === '/exit' || message.trim() === '/quit') break;\n const text = message.trim(); if (!text) continue;\n if (text === '/help') { prompts.log.message('/clear forget the conversation\\n/cost spend so far\\n/exit leave', io); continue; }\n if (text === '/clear') { history.length = 0; prompts.log.success('Started a new conversation.', io); continue; }\n if (text === '/cost') { prompts.log.message(`Spent ${dollars(total)} over ${turns} turn${turns === 1 ? '' : 's'}.`, io); continue; }\n let handle: ReturnType<Runtime['submit']>;\n try { handle = options.runtime.submit(options.agent, { input: toInput(text, history) }); }\n catch (error) { const failure = publicError(error, 'INVALID_INPUT'); prompts.log.error(`${failure.message} (${failure.code})`, io); continue; }\n const spinner = prompts.spinner(io.output ? { output: io.output } : {}); let spinning = true; let streamed = false; let preview = ''; let withheld = false; spinner.start('Thinking');\n const pause = (): void => { if (spinning) { spinner.stop(); spinning = false; } };\n const resume = (label: string): void => { if (!spinning && !streamed) { spinner.start(label); spinning = true; } };\n people.set(handle.id, {\n confirm: async (title, detail) => { pause(); prompts.note(detail, title, io); const answer = await prompts.confirm({ ...io, message: 'Allow it?', initialValue: false });\n resume('Working'); return !prompts.isCancel(answer) && answer === true; },\n ask: async question => { pause(); const answer = await prompts.text({ ...io, message: question }); resume('Thinking');\n return prompts.isCancel(answer) ? undefined : answer; },\n });\n const watching = (async () => {\n for await (const event of handle.observe()) {\n if (event.type === 'tool.started' && !streamed) { if (spinning) spinner.message(`Using ${String(event.metadata['toolId'])}`); }\n else if (event.type === 'output.delta') {\n if (!streamed) { pause(); streamed = true; out.write('\\n'); }\n const text = String(event.metadata['text'] ?? ''); preview += text; out.write(text);\n } else if (event.type === 'output.withheld') withheld = true;\n }\n })().catch(() => {});\n const outcome = await handle.result(); await watching; people.delete(handle.id); pause();\n const cost = spent(options.runtime, handle); total += cost; turns += 1;\n if (streamed) out.write('\\n\\n');\n if (outcome.status === 'succeeded') {\n const reply = toText(outcome.output as InferOutput<O>);\n if (!streamed) prompts.log.message(reply, { ...io, symbol: '◆' });\n // A guard stopped the stream, or the output schema changed the answer (for example redacted it): show the final\n // answer, which is the one that counts.\n else if (withheld || differs(preview, reply)) prompts.log.message(reply, { ...io, symbol: '◆' });\n if (cost > 0) prompts.log.message(`${dollars(cost)} this turn`, io);\n history.push({ role: 'person', text }, { role: 'agent', text: reply });\n } else prompts.log.error(`${outcome.error.message} (${outcome.status})`, io);\n }\n prompts.outro(turns > 0 ? `${turns} turn${turns === 1 ? '' : 's'}, ${dollars(total)} spent.` : 'Bye.', io);\n return { turns, spentMicros: total };\n}\n\nexport interface AgentCommandOptions<I extends Schema, O extends Schema> {\n readonly agent: AgentDefinition<I, O>;\n readonly runtime: Runtime;\n /** The command's name in its help; the default is the agent id. */\n readonly name?: string;\n /** Arguments after the command; the default is `process.argv.slice(2)`. */\n readonly argv?: readonly string[];\n /**\n * The agent input's JSON Schema: its top-level properties become flags, and `--help` lists them. The default is the\n * agent's own input schema, when its validator can describe itself (Zod 4.2 and later).\n */\n readonly inputJsonSchema?: JsonObject;\n readonly toText?: (output: InferOutput<O>) => string;\n readonly io?: { readonly stdin?: Readable & { isTTY?: boolean }; readonly stdout?: Writable & { isTTY?: boolean }; readonly stderr?: Writable };\n}\n\ntype Property = { readonly type?: string; readonly description?: string };\n/** Usage text for a command: flags from the schema, or free text; `attachments` when the agent accepts media. */\nexport function agentCommandHelp(name: string, schema?: JsonObject, options: { readonly attachments?: boolean } = {}): string {\n const properties = (schema?.['properties'] ?? {}) as Record<string, Property>; const required = new Set((schema?.['required'] ?? []) as string[]);\n const flags = Object.entries(properties).filter(([, property]) => ['string', 'number', 'integer', 'boolean'].includes(String(property.type)));\n return [\n `Usage: ${name} ${flags.length ? '[options]' : '<text>'}`, '',\n ...(flags.length ? ['Options:', ...flags.map(([key, property]) => ` --${key}${property.type === 'boolean' ? '' : ` <${property.type}>`}${required.has(key) ? ' (required)' : ''}${property.description ? ` ${property.description}` : ''}`), ''] : []),\n 'Input:', ' --input <json> the whole input as JSON', ' --input-file <path> read it from a JSON file', ' (or pipe text to stdin)',\n ...(options.attachments ? [' --attach <path> attach an image or PDF for the agent to see (repeatable)'] : []), '',\n 'Output:', ' --json print {\"status\", \"output\", \"spentMicros\"}', ' --help, -h show this help',\n ].join('\\n');\n}\n\n/** Parse the command line into the agent's input. */\nexport async function parseAgentCommand(argv: readonly string[], schema?: JsonObject, stdin?: Readable & { isTTY?: boolean },\n options: { readonly attachments?: boolean } = {}):\n Promise<{ readonly help: boolean; readonly json: boolean; readonly input: unknown; readonly media: readonly Media[] }> {\n const properties = (schema?.['properties'] ?? {}) as Record<string, Property>; const values: Record<string, JsonValue> = {}; const words: string[] = [];\n let json = false; let help = false; let whole: unknown; let hasWhole = false; const attached: Media[] = [];\n const fail = (message: string): never => { throw new MayuraError('INVALID_INPUT', message); };\n for (let index = 0; index < argv.length; index++) {\n const argument = argv[index]!;\n if (argument === '--help' || argument === '-h') { help = true; continue; }\n if (argument === '--json') { json = true; continue; }\n // An input field named `attach` keeps its flag; otherwise --attach adds an image or PDF.\n if (argument === '--attach' && !properties['attach']) {\n if (!options.attachments) fail('This command does not take attachments.');\n const path = argv[++index]; if (path === undefined) fail('--attach needs a file path.');\n let bytes: Uint8Array | undefined;\n try { if ((await stat(path!)).size > 67_108_864) fail(`${path} is larger than 64 MiB.`); bytes = await readFile(path!); }\n catch (error) { if (error instanceof MayuraError) throw error; fail(`Could not read ${path}.`); }\n const mediaType = sniffMediaType(bytes!);\n if (!mediaType) fail(`${path} is not a PNG, JPEG, WebP, GIF or PDF file.`);\n attached.push(media(bytes!, mediaType!, { name: basename(path!) }));\n continue;\n }\n if (argument === '--input' || argument === '--input-file') {\n const value = argv[++index]; if (value === undefined) fail(`${argument} needs a value.`);\n try { whole = JSON.parse(argument === '--input' ? value! : await readFile(value!, 'utf8')); } catch { fail(`${argument} must be valid JSON.`); }\n hasWhole = true; continue;\n }\n if (argument.startsWith('--')) {\n const raw = argument.slice(2); const negated = raw.startsWith('no-') && properties[raw.slice(3)]?.type === 'boolean';\n const key = negated ? raw.slice(3) : raw; const property = properties[key]; if (!property) fail(`Unknown option ${argument}. Run with --help.`);\n if (property!.type === 'boolean') { values[key] = !negated; continue; }\n const value = argv[++index]; if (value === undefined) fail(`${argument} needs a value.`);\n if (property!.type === 'number' || property!.type === 'integer') {\n const number = Number(value); if (!Number.isFinite(number) || (property!.type === 'integer' && !Number.isInteger(number))) fail(`${argument} must be a ${property!.type}.`);\n values[key] = number;\n } else values[key] = value!;\n continue;\n }\n words.push(argument);\n }\n const files = Object.freeze(attached);\n if (help) return { help, json, input: undefined, media: files };\n if (hasWhole) { if (Object.keys(values).length || words.length) fail('Use --input on its own.'); return { help, json, input: whole, media: files }; }\n if (Object.keys(values).length) { if (words.length) fail(`Unexpected ${words[0]}; pass values with their --option.`); return { help, json, input: values, media: files }; }\n if (words.length) return { help, json, input: words.join(' '), media: files };\n if (stdin && !stdin.isTTY) {\n const chunks: Buffer[] = []; let size = 0;\n for await (const chunk of stdin) { const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)); size += bytes.byteLength; if (size > 1_048_576) fail('Standard input is larger than 1 MiB.'); chunks.push(bytes); }\n const text = Buffer.concat(chunks).toString('utf8').trim(); if (text) return { help, json, input: text, media: files };\n }\n return fail('No input. Pass text, options, --input or pipe it in; run with --help.');\n}\n\n/** Run an agent once from the command line. Returns the exit code: 0 when it succeeded, 1 otherwise. */\nexport async function runAgentCommand<I extends Schema, O extends Schema>(options: AgentCommandOptions<I, O>): Promise<number> {\n const io = options.io ?? {}; const stdout = io.stdout ?? process.stdout; const stderr = io.stderr ?? process.stderr;\n const name = options.name ?? options.agent.id; const toText = options.toText ?? (value => outputText(value));\n // Flags come from the given schema, or from the agent's own input when its validator can describe itself.\n const schema = options.inputJsonSchema ?? options.agent.inputJsonSchema;\n let parsed: Awaited<ReturnType<typeof parseAgentCommand>>;\n // An agent that accepts media takes --attach <file>.\n const attachments = options.agent.media !== undefined;\n try { parsed = await parseAgentCommand(options.argv ?? process.argv.slice(2), schema, io.stdin ?? process.stdin, { attachments }); }\n catch (error) { stderr.write(`${publicError(error, 'INVALID_INPUT').message}\\n`); return 1; }\n if (parsed.help) { stdout.write(`${agentCommandHelp(name, schema, { attachments })}\\n`); return 0; }\n const human = !parsed.json && stdout.isTTY === true; let handle: ReturnType<Runtime['submit']>;\n try { handle = options.runtime.submit(options.agent, { input: parsed.input as InferInput<I>, ...(parsed.media.length > 0 ? { media: parsed.media } : {}) }); }\n catch (error) { const failure = publicError(error, 'INVALID_INPUT'); stderr.write(parsed.json ? `${JSON.stringify({ status: 'failed', error: failure })}\\n` : `${failure.message}\\n`); return 1; }\n // Confirmations and questions need someone at a terminal; piped or scheduled runs refuse them.\n const stdinTTY = (io.stdin ?? process.stdin).isTTY === true;\n if (stdinTTY) {\n const prompts = await import('@clack/prompts');\n people.set(handle.id, {\n confirm: async (title, detail) => { prompts.note(detail, title); const answer = await prompts.confirm({ message: 'Allow it?', initialValue: false }); return !prompts.isCancel(answer) && answer === true; },\n ask: async question => { const answer = await prompts.text({ message: question }); return prompts.isCancel(answer) ? undefined : answer; },\n });\n }\n let streamed = false; let preview = '';\n const watching = (async () => {\n for await (const event of handle.observe()) {\n if (human && event.type === 'output.delta') { const text = String(event.metadata['text'] ?? ''); streamed = true; preview += text; stdout.write(text); }\n else if (human && event.type === 'tool.started') stderr.write(`· ${String(event.metadata['toolId'])}\\n`);\n }\n })().catch(() => {});\n const outcome = await handle.result(); await watching; people.delete(handle.id);\n const cost = spent(options.runtime, handle);\n if (parsed.json) {\n const document = outcome.status === 'succeeded' ? { status: outcome.status, output: outcome.output, spentMicros: cost } : { status: outcome.status, error: outcome.error, spentMicros: cost };\n stdout.write(`${JSON.stringify(document, null, 2)}\\n`);\n } else if (outcome.status === 'succeeded') {\n const reply = toText(outcome.output as InferOutput<O>);\n // The streamed text is a preview: when the final answer differs (a guard or the output schema changed it), print it.\n stdout.write(!streamed ? `${reply}\\n` : differs(preview, reply) ? `\\n${reply}\\n` : '\\n');\n }\n else stderr.write(`${outcome.error.message} (${outcome.status})\\n`);\n return outcome.status === 'succeeded' ? 0 : 1;\n}\n"]}
@@ -0,0 +1,5 @@
1
+ {
2
+ "type": "module",
3
+ "version": "1.0.0-rc.2",
4
+ "private": true
5
+ }
@@ -0,0 +1,273 @@
1
+ // Terminal front ends for agents: an interactive chat (`runTerminalChat`) and one-shot commands whose flags come from
2
+ // the agent's input (`runAgentCommand`). A person at the terminal can confirm actions before they run
3
+ // (`confirmBeforeRunning`) and answer the agent's questions (`askPersonTool`); with nobody there, both refuse.
4
+ import { readFile, stat } from 'node:fs/promises';
5
+ import { basename } from 'node:path';
6
+ import type { Readable, Writable } from 'node:stream';
7
+ import { MayuraError, media, publicError, sniffMediaType, type InferInput, type InferOutput, type JsonObject, type JsonValue, type Media, type Schema } from '@mayura/core';
8
+ import type { AgentDefinition, Runtime } from '@mayura/runtime';
9
+ import { defineTool, ToolRefusal, withPreflight, type AnyTool } from '@mayura/tools';
10
+
11
+ /** Someone at the terminal, for the run currently in a chat turn or command. */
12
+ interface Person {
13
+ confirm(title: string, detail: string): Promise<boolean>;
14
+ ask(question: string): Promise<string | undefined>;
15
+ }
16
+ // Tools find the person for their run by the run id the runtime passes them; a run with nobody registered is refused.
17
+ const people = new Map<string, Person>();
18
+
19
+ /**
20
+ * The same tool, but a person at the terminal sees its input and confirms before it runs. Declining, or running with
21
+ * nobody at a terminal (for example on a server), refuses the call before any effect.
22
+ */
23
+ export function confirmBeforeRunning<T extends AnyTool>(tool: T, options: { readonly describe?: (input: InferOutput<T['input']>) => string;
24
+ readonly waitMs?: number } = {}): T {
25
+ return withPreflight(tool, async (input, context) => {
26
+ const person = people.get(context.runId);
27
+ if (!person) throw new ToolRefusal(`${tool.id} needs a person to confirm it, and nobody is available.`);
28
+ const detail = options.describe ? options.describe(input) : JSON.stringify(input, null, 2);
29
+ if (!await person.confirm(`Allow ${tool.id}?`, detail)) throw new ToolRefusal(`The person declined ${tool.id}.`);
30
+ }, { extraTimeoutMs: options.waitMs ?? 600_000, description: `${tool.description} (A person confirms each call.)` });
31
+ }
32
+
33
+ const questionInput: Schema<{ question: string }> = { '~standard': { version: 1, vendor: 'mayura-terminal', validate: value => {
34
+ const record = value as Record<string, unknown> | null;
35
+ return record && typeof record === 'object' && !Array.isArray(record) && Object.keys(record).length === 1 && typeof record['question'] === 'string'
36
+ && record['question'].length > 0 && record['question'].length <= 2_000 ? { value: { question: record['question'] } } : { issues: [{ message: 'Expected { question }.' }] };
37
+ } } } as Schema<{ question: string }>;
38
+ const anyOutput: Schema<JsonValue> = { '~standard': { version: 1, vendor: 'mayura-terminal', validate: value => ({ value: value as JsonValue }) } } as Schema<JsonValue>;
39
+ /** A tool the agent calls to ask the person at the terminal a question. Grant `tool:person.ask` and `person:ask`. */
40
+ export const askPersonTool = defineTool({ id: 'person.ask', version: '1', effects: 'none', capabilities: ['person:ask'], costMicros: 0, timeoutMs: 600_000,
41
+ description: 'Ask the person you are working with a question, when you cannot continue without their answer. Ask one clear question at a time.',
42
+ input: questionInput, output: anyOutput,
43
+ inputJsonSchema: { type: 'object', additionalProperties: false, required: ['question'], properties: { question: { type: 'string', description: 'The question to ask.' } } },
44
+ execute: async ({ question }, context) => {
45
+ const person = people.get(context.runId); if (!person) throw new ToolRefusal('Nobody is available to answer questions.');
46
+ const answer = await person.ask(question); if (answer === undefined) throw new ToolRefusal('The person did not answer.');
47
+ return { answer };
48
+ } });
49
+
50
+ /** Plain text for a person from an agent's output: a string, or its reply/message/text/answer field, or JSON. */
51
+ export function outputText(output: unknown): string {
52
+ if (typeof output === 'string') return output;
53
+ if (output && typeof output === 'object' && !Array.isArray(output)) {
54
+ for (const field of ['reply', 'message', 'text', 'answer', 'content', 'response']) {
55
+ const value = (output as Record<string, unknown>)[field]; if (typeof value === 'string') return value;
56
+ }
57
+ }
58
+ return JSON.stringify(output, null, 2);
59
+ }
60
+ const dollars = (micros: number): string => `$${(micros / 1_000_000).toFixed(micros < 10_000 ? 6 : 4)}`;
61
+ const spent = (runtime: Runtime, handle: Parameters<Runtime['inspect']>[0]): number => {
62
+ try { const value = runtime.inspect(handle).budget.spentMicros; return typeof value === 'number' ? value : Number(value) || 0; } catch { return 0; }
63
+ };
64
+
65
+ export interface ChatTurn { readonly role: 'person' | 'agent'; readonly text: string }
66
+
67
+ /**
68
+ * The default chat input: the message alone for the first turn, and afterwards the last 20 turns as a transcript
69
+ * followed by the new message, so an agent that takes text remembers the conversation.
70
+ */
71
+ export function chatTranscript(message: string, history: readonly ChatTurn[]): string {
72
+ if (history.length === 0) return message;
73
+ const earlier = history.slice(-20).map(turn => `${turn.role === 'person' ? 'Person' : 'You'}: ${turn.text}`).join('\n');
74
+ return `The conversation so far:\n${earlier}\n\nThe person's new message:\n${message}`;
75
+ }
76
+
77
+ /** Whether a streamed preview differs from the final answer, which then has to be shown in full. */
78
+ const differs = (streamed: string, final: string): boolean => streamed.trim() !== final.trim();
79
+ export interface TerminalChatOptions<I extends Schema, O extends Schema> {
80
+ readonly agent: AgentDefinition<I, O>;
81
+ readonly runtime: Runtime;
82
+ /**
83
+ * The agent's input for a message; `history` holds the earlier turns. The default (`chatTranscript`) passes the
84
+ * message text, with the recent conversation before it after the first turn.
85
+ */
86
+ readonly toInput?: (message: string, history: readonly ChatTurn[]) => InferInput<I>;
87
+ /** What to show for the agent's output; the default is `outputText`. */
88
+ readonly toText?: (output: InferOutput<O>) => string;
89
+ readonly title?: string;
90
+ /** Streams to prompt on; the process's terminal by default. */
91
+ readonly io?: { readonly input?: Readable; readonly output?: Writable };
92
+ }
93
+
94
+ /** Run an interactive chat with an agent until the person types /exit (or presses Ctrl+C at the prompt). */
95
+ export async function runTerminalChat<I extends Schema, O extends Schema>(options: TerminalChatOptions<I, O>): Promise<{ readonly turns: number; readonly spentMicros: number }> {
96
+ const prompts = await import('@clack/prompts'); const io = options.io ?? {}; const out = io.output ?? process.stdout;
97
+ const toText = options.toText ?? (value => outputText(value)); const toInput = options.toInput ?? ((message: string, earlier: readonly ChatTurn[]) => chatTranscript(message, earlier) as InferInput<I>);
98
+ const history: ChatTurn[] = []; let turns = 0; let total = 0;
99
+ prompts.intro(options.title ?? ` ${options.agent.id} `, io);
100
+ prompts.log.message('Type a message. /help lists commands.', io);
101
+ for (;;) {
102
+ const message = await prompts.text({ ...io, message: 'You', placeholder: 'Ask something, or /exit' });
103
+ if (prompts.isCancel(message) || message.trim() === '/exit' || message.trim() === '/quit') break;
104
+ const text = message.trim(); if (!text) continue;
105
+ if (text === '/help') { prompts.log.message('/clear forget the conversation\n/cost spend so far\n/exit leave', io); continue; }
106
+ if (text === '/clear') { history.length = 0; prompts.log.success('Started a new conversation.', io); continue; }
107
+ if (text === '/cost') { prompts.log.message(`Spent ${dollars(total)} over ${turns} turn${turns === 1 ? '' : 's'}.`, io); continue; }
108
+ let handle: ReturnType<Runtime['submit']>;
109
+ try { handle = options.runtime.submit(options.agent, { input: toInput(text, history) }); }
110
+ catch (error) { const failure = publicError(error, 'INVALID_INPUT'); prompts.log.error(`${failure.message} (${failure.code})`, io); continue; }
111
+ const spinner = prompts.spinner(io.output ? { output: io.output } : {}); let spinning = true; let streamed = false; let preview = ''; let withheld = false; spinner.start('Thinking');
112
+ const pause = (): void => { if (spinning) { spinner.stop(); spinning = false; } };
113
+ const resume = (label: string): void => { if (!spinning && !streamed) { spinner.start(label); spinning = true; } };
114
+ people.set(handle.id, {
115
+ confirm: async (title, detail) => { pause(); prompts.note(detail, title, io); const answer = await prompts.confirm({ ...io, message: 'Allow it?', initialValue: false });
116
+ resume('Working'); return !prompts.isCancel(answer) && answer === true; },
117
+ ask: async question => { pause(); const answer = await prompts.text({ ...io, message: question }); resume('Thinking');
118
+ return prompts.isCancel(answer) ? undefined : answer; },
119
+ });
120
+ const watching = (async () => {
121
+ for await (const event of handle.observe()) {
122
+ if (event.type === 'tool.started' && !streamed) { if (spinning) spinner.message(`Using ${String(event.metadata['toolId'])}`); }
123
+ else if (event.type === 'output.delta') {
124
+ if (!streamed) { pause(); streamed = true; out.write('\n'); }
125
+ const text = String(event.metadata['text'] ?? ''); preview += text; out.write(text);
126
+ } else if (event.type === 'output.withheld') withheld = true;
127
+ }
128
+ })().catch(() => {});
129
+ const outcome = await handle.result(); await watching; people.delete(handle.id); pause();
130
+ const cost = spent(options.runtime, handle); total += cost; turns += 1;
131
+ if (streamed) out.write('\n\n');
132
+ if (outcome.status === 'succeeded') {
133
+ const reply = toText(outcome.output as InferOutput<O>);
134
+ if (!streamed) prompts.log.message(reply, { ...io, symbol: '◆' });
135
+ // A guard stopped the stream, or the output schema changed the answer (for example redacted it): show the final
136
+ // answer, which is the one that counts.
137
+ else if (withheld || differs(preview, reply)) prompts.log.message(reply, { ...io, symbol: '◆' });
138
+ if (cost > 0) prompts.log.message(`${dollars(cost)} this turn`, io);
139
+ history.push({ role: 'person', text }, { role: 'agent', text: reply });
140
+ } else prompts.log.error(`${outcome.error.message} (${outcome.status})`, io);
141
+ }
142
+ prompts.outro(turns > 0 ? `${turns} turn${turns === 1 ? '' : 's'}, ${dollars(total)} spent.` : 'Bye.', io);
143
+ return { turns, spentMicros: total };
144
+ }
145
+
146
+ export interface AgentCommandOptions<I extends Schema, O extends Schema> {
147
+ readonly agent: AgentDefinition<I, O>;
148
+ readonly runtime: Runtime;
149
+ /** The command's name in its help; the default is the agent id. */
150
+ readonly name?: string;
151
+ /** Arguments after the command; the default is `process.argv.slice(2)`. */
152
+ readonly argv?: readonly string[];
153
+ /**
154
+ * The agent input's JSON Schema: its top-level properties become flags, and `--help` lists them. The default is the
155
+ * agent's own input schema, when its validator can describe itself (Zod 4.2 and later).
156
+ */
157
+ readonly inputJsonSchema?: JsonObject;
158
+ readonly toText?: (output: InferOutput<O>) => string;
159
+ readonly io?: { readonly stdin?: Readable & { isTTY?: boolean }; readonly stdout?: Writable & { isTTY?: boolean }; readonly stderr?: Writable };
160
+ }
161
+
162
+ type Property = { readonly type?: string; readonly description?: string };
163
+ /** Usage text for a command: flags from the schema, or free text; `attachments` when the agent accepts media. */
164
+ export function agentCommandHelp(name: string, schema?: JsonObject, options: { readonly attachments?: boolean } = {}): string {
165
+ const properties = (schema?.['properties'] ?? {}) as Record<string, Property>; const required = new Set((schema?.['required'] ?? []) as string[]);
166
+ const flags = Object.entries(properties).filter(([, property]) => ['string', 'number', 'integer', 'boolean'].includes(String(property.type)));
167
+ return [
168
+ `Usage: ${name} ${flags.length ? '[options]' : '<text>'}`, '',
169
+ ...(flags.length ? ['Options:', ...flags.map(([key, property]) => ` --${key}${property.type === 'boolean' ? '' : ` <${property.type}>`}${required.has(key) ? ' (required)' : ''}${property.description ? ` ${property.description}` : ''}`), ''] : []),
170
+ 'Input:', ' --input <json> the whole input as JSON', ' --input-file <path> read it from a JSON file', ' (or pipe text to stdin)',
171
+ ...(options.attachments ? [' --attach <path> attach an image or PDF for the agent to see (repeatable)'] : []), '',
172
+ 'Output:', ' --json print {"status", "output", "spentMicros"}', ' --help, -h show this help',
173
+ ].join('\n');
174
+ }
175
+
176
+ /** Parse the command line into the agent's input. */
177
+ export async function parseAgentCommand(argv: readonly string[], schema?: JsonObject, stdin?: Readable & { isTTY?: boolean },
178
+ options: { readonly attachments?: boolean } = {}):
179
+ Promise<{ readonly help: boolean; readonly json: boolean; readonly input: unknown; readonly media: readonly Media[] }> {
180
+ const properties = (schema?.['properties'] ?? {}) as Record<string, Property>; const values: Record<string, JsonValue> = {}; const words: string[] = [];
181
+ let json = false; let help = false; let whole: unknown; let hasWhole = false; const attached: Media[] = [];
182
+ const fail = (message: string): never => { throw new MayuraError('INVALID_INPUT', message); };
183
+ for (let index = 0; index < argv.length; index++) {
184
+ const argument = argv[index]!;
185
+ if (argument === '--help' || argument === '-h') { help = true; continue; }
186
+ if (argument === '--json') { json = true; continue; }
187
+ // An input field named `attach` keeps its flag; otherwise --attach adds an image or PDF.
188
+ if (argument === '--attach' && !properties['attach']) {
189
+ if (!options.attachments) fail('This command does not take attachments.');
190
+ const path = argv[++index]; if (path === undefined) fail('--attach needs a file path.');
191
+ let bytes: Uint8Array | undefined;
192
+ try { if ((await stat(path!)).size > 67_108_864) fail(`${path} is larger than 64 MiB.`); bytes = await readFile(path!); }
193
+ catch (error) { if (error instanceof MayuraError) throw error; fail(`Could not read ${path}.`); }
194
+ const mediaType = sniffMediaType(bytes!);
195
+ if (!mediaType) fail(`${path} is not a PNG, JPEG, WebP, GIF or PDF file.`);
196
+ attached.push(media(bytes!, mediaType!, { name: basename(path!) }));
197
+ continue;
198
+ }
199
+ if (argument === '--input' || argument === '--input-file') {
200
+ const value = argv[++index]; if (value === undefined) fail(`${argument} needs a value.`);
201
+ try { whole = JSON.parse(argument === '--input' ? value! : await readFile(value!, 'utf8')); } catch { fail(`${argument} must be valid JSON.`); }
202
+ hasWhole = true; continue;
203
+ }
204
+ if (argument.startsWith('--')) {
205
+ const raw = argument.slice(2); const negated = raw.startsWith('no-') && properties[raw.slice(3)]?.type === 'boolean';
206
+ const key = negated ? raw.slice(3) : raw; const property = properties[key]; if (!property) fail(`Unknown option ${argument}. Run with --help.`);
207
+ if (property!.type === 'boolean') { values[key] = !negated; continue; }
208
+ const value = argv[++index]; if (value === undefined) fail(`${argument} needs a value.`);
209
+ if (property!.type === 'number' || property!.type === 'integer') {
210
+ const number = Number(value); if (!Number.isFinite(number) || (property!.type === 'integer' && !Number.isInteger(number))) fail(`${argument} must be a ${property!.type}.`);
211
+ values[key] = number;
212
+ } else values[key] = value!;
213
+ continue;
214
+ }
215
+ words.push(argument);
216
+ }
217
+ const files = Object.freeze(attached);
218
+ if (help) return { help, json, input: undefined, media: files };
219
+ if (hasWhole) { if (Object.keys(values).length || words.length) fail('Use --input on its own.'); return { help, json, input: whole, media: files }; }
220
+ if (Object.keys(values).length) { if (words.length) fail(`Unexpected ${words[0]}; pass values with their --option.`); return { help, json, input: values, media: files }; }
221
+ if (words.length) return { help, json, input: words.join(' '), media: files };
222
+ if (stdin && !stdin.isTTY) {
223
+ const chunks: Buffer[] = []; let size = 0;
224
+ for await (const chunk of stdin) { const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)); size += bytes.byteLength; if (size > 1_048_576) fail('Standard input is larger than 1 MiB.'); chunks.push(bytes); }
225
+ const text = Buffer.concat(chunks).toString('utf8').trim(); if (text) return { help, json, input: text, media: files };
226
+ }
227
+ return fail('No input. Pass text, options, --input or pipe it in; run with --help.');
228
+ }
229
+
230
+ /** Run an agent once from the command line. Returns the exit code: 0 when it succeeded, 1 otherwise. */
231
+ export async function runAgentCommand<I extends Schema, O extends Schema>(options: AgentCommandOptions<I, O>): Promise<number> {
232
+ const io = options.io ?? {}; const stdout = io.stdout ?? process.stdout; const stderr = io.stderr ?? process.stderr;
233
+ const name = options.name ?? options.agent.id; const toText = options.toText ?? (value => outputText(value));
234
+ // Flags come from the given schema, or from the agent's own input when its validator can describe itself.
235
+ const schema = options.inputJsonSchema ?? options.agent.inputJsonSchema;
236
+ let parsed: Awaited<ReturnType<typeof parseAgentCommand>>;
237
+ // An agent that accepts media takes --attach <file>.
238
+ const attachments = options.agent.media !== undefined;
239
+ try { parsed = await parseAgentCommand(options.argv ?? process.argv.slice(2), schema, io.stdin ?? process.stdin, { attachments }); }
240
+ catch (error) { stderr.write(`${publicError(error, 'INVALID_INPUT').message}\n`); return 1; }
241
+ if (parsed.help) { stdout.write(`${agentCommandHelp(name, schema, { attachments })}\n`); return 0; }
242
+ const human = !parsed.json && stdout.isTTY === true; let handle: ReturnType<Runtime['submit']>;
243
+ try { handle = options.runtime.submit(options.agent, { input: parsed.input as InferInput<I>, ...(parsed.media.length > 0 ? { media: parsed.media } : {}) }); }
244
+ catch (error) { const failure = publicError(error, 'INVALID_INPUT'); stderr.write(parsed.json ? `${JSON.stringify({ status: 'failed', error: failure })}\n` : `${failure.message}\n`); return 1; }
245
+ // Confirmations and questions need someone at a terminal; piped or scheduled runs refuse them.
246
+ const stdinTTY = (io.stdin ?? process.stdin).isTTY === true;
247
+ if (stdinTTY) {
248
+ const prompts = await import('@clack/prompts');
249
+ people.set(handle.id, {
250
+ confirm: async (title, detail) => { prompts.note(detail, title); const answer = await prompts.confirm({ message: 'Allow it?', initialValue: false }); return !prompts.isCancel(answer) && answer === true; },
251
+ ask: async question => { const answer = await prompts.text({ message: question }); return prompts.isCancel(answer) ? undefined : answer; },
252
+ });
253
+ }
254
+ let streamed = false; let preview = '';
255
+ const watching = (async () => {
256
+ for await (const event of handle.observe()) {
257
+ if (human && event.type === 'output.delta') { const text = String(event.metadata['text'] ?? ''); streamed = true; preview += text; stdout.write(text); }
258
+ else if (human && event.type === 'tool.started') stderr.write(`· ${String(event.metadata['toolId'])}\n`);
259
+ }
260
+ })().catch(() => {});
261
+ const outcome = await handle.result(); await watching; people.delete(handle.id);
262
+ const cost = spent(options.runtime, handle);
263
+ if (parsed.json) {
264
+ const document = outcome.status === 'succeeded' ? { status: outcome.status, output: outcome.output, spentMicros: cost } : { status: outcome.status, error: outcome.error, spentMicros: cost };
265
+ stdout.write(`${JSON.stringify(document, null, 2)}\n`);
266
+ } else if (outcome.status === 'succeeded') {
267
+ const reply = toText(outcome.output as InferOutput<O>);
268
+ // The streamed text is a preview: when the final answer differs (a guard or the output schema changed it), print it.
269
+ stdout.write(!streamed ? `${reply}\n` : differs(preview, reply) ? `\n${reply}\n` : '\n');
270
+ }
271
+ else stderr.write(`${outcome.error.message} (${outcome.status})\n`);
272
+ return outcome.status === 'succeeded' ? 0 : 1;
273
+ }
@@ -1,10 +1,53 @@
1
- import { type ModelAdapter, type ModelRequest, type ModelResponse } from '../../core/dist/index.js';
1
+ import { type ExecutionReceipt, type Media, type ModelAdapter, type ModelMediaCapability, type ModelRequest, type ModelResponse, type Outcome, type Scope } from '../../core/dist/index.js';
2
+ import { type AnyTool, type ToolOutput } from '../../tools/dist/index.js';
2
3
  /**
3
4
  * Deterministic test-only model. It never performs inference or network requests.
4
5
  * Each call consumes a scripted response; exhaustion is an error, not a fabricated answer.
6
+ *
7
+ * It also streams, for agents with a stream policy: a final answer arrives as `output.delta` pieces of its JSON text
8
+ * (`streamChunk` characters each, 16 by default), then the complete response, exactly as a provider adapter streams.
9
+ *
10
+ * It can "see" every media type and URLs, so agents that accept images or PDFs can be tested; a scripted step receives
11
+ * the request with its `media`. Pass `media: false` to test a model that cannot see.
5
12
  */
6
13
  export declare function scriptedModel(responses: readonly (ModelResponse | ((request: ModelRequest) => ModelResponse | Promise<ModelResponse>))[], options?: {
7
14
  readonly id?: string;
8
15
  readonly maxCostMicros?: number;
16
+ readonly streamChunk?: number;
17
+ readonly media?: ModelMediaCapability | false;
9
18
  }): ModelAdapter;
19
+ /** A real 1×1 PNG, for tests of agents and tools that take or return images. */
20
+ export declare function testImage(options?: {
21
+ readonly name?: string;
22
+ }): Media;
23
+ /** A minimal one-page PDF, for tests of agents and tools that take or return documents. */
24
+ export declare function testPdf(options?: {
25
+ readonly name?: string;
26
+ }): Media;
27
+ /** The grants a tool needs to run: `tool:<id>`, each of its capabilities, and its effect (unless it has none). */
28
+ export declare function toolGrants(tool: AnyTool): readonly string[];
29
+ export interface TestToolOptions {
30
+ /** What the call is allowed; the default is exactly what the tool needs (`toolGrants`). */
31
+ readonly permissions?: readonly string[];
32
+ readonly scope?: Scope;
33
+ /** The budget for the call, in micros; the default is the tool's own `costMicros`. */
34
+ readonly budgetMicros?: number;
35
+ readonly signal?: AbortSignal;
36
+ readonly runId?: string;
37
+ readonly callId?: string;
38
+ }
39
+ export interface TestToolResult<T extends AnyTool> {
40
+ /** The outcome, exactly as a run would see it: checked input, the tool's effect and cost rules, checked output. */
41
+ readonly outcome: Outcome<ToolOutput<T>>;
42
+ /** What the call was charged: known cost, and cost still unresolved (an uncertain call keeps its reservation). */
43
+ readonly spentMicros: number;
44
+ readonly reservedMicros: number;
45
+ /** The execution record Mayura keeps for the call, when it started. */
46
+ readonly receipt: ExecutionReceipt | undefined;
47
+ }
48
+ /**
49
+ * Run one tool through Mayura's broker, as an agent's call would, without an agent, model or runtime: permissions,
50
+ * input and output validation, guards, timeout, cost and the `outcome_unknown` rules all apply. For unit tests.
51
+ */
52
+ export declare function testTool<T extends AnyTool>(tool: T, input: unknown, options?: TestToolOptions): Promise<TestToolResult<T>>;
10
53
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,KAAK,YAAY,EAAE,KAAK,YAAY,EAAE,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAEhH;;;GAGG;AACH,wBAAgB,aAAa,CAC3B,SAAS,EAAE,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,OAAO,EAAE,YAAY,KAAK,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,EAC3G,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,GACtE,YAAY,CAgBd"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,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,CAAC;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;IAC9B,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,cAAc,CAAC,CAAC,SAAS,OAAO;IAC/C,mHAAmH;IACnH,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IACzC,kHAAkH;IAClH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,uEAAuE;IACvE,QAAQ,CAAC,OAAO,EAAE,gBAAgB,GAAG,SAAS,CAAC;CAChD;AAED;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,CAAC,SAAS,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,GAAE,eAAoB,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAWpI"}
@@ -1,24 +1,77 @@
1
- import { MayuraError, jsonValue } from '../../core/dist/index.js';
1
+ import { Budget, MayuraError, MEDIA_TYPES, jsonValue, mediaFromBase64 } from '../../core/dist/index.js';
2
+ import { invokeTool } from '../../tools/dist/index.js';
2
3
  /**
3
4
  * Deterministic test-only model. It never performs inference or network requests.
4
5
  * Each call consumes a scripted response; exhaustion is an error, not a fabricated answer.
6
+ *
7
+ * It also streams, for agents with a stream policy: a final answer arrives as `output.delta` pieces of its JSON text
8
+ * (`streamChunk` characters each, 16 by default), then the complete response, exactly as a provider adapter streams.
9
+ *
10
+ * It can "see" every media type and URLs, so agents that accept images or PDFs can be tested; a scripted step receives
11
+ * the request with its `media`. Pass `media: false` to test a model that cannot see.
5
12
  */
6
13
  export function scriptedModel(responses, options = {}) {
7
14
  const steps = [...responses];
8
15
  let position = 0;
16
+ const chunk = options.streamChunk ?? 16;
17
+ if (!Number.isSafeInteger(chunk) || chunk < 1)
18
+ throw new MayuraError('INVALID_CONFIG', 'streamChunk must be a positive integer.');
19
+ const next = async (request) => {
20
+ request.signal.throwIfAborted();
21
+ const response = steps[position++];
22
+ if (!response)
23
+ throw new MayuraError('MODEL_FAILED', 'The test model script is exhausted.');
24
+ const result = typeof response === 'function' ? await response(request) : response;
25
+ // Copy snapshots so a runtime cannot mutate a later test's scripted response.
26
+ return jsonValue(result);
27
+ };
9
28
  return Object.freeze({
10
29
  id: options.id ?? 'scripted',
11
- capabilities: Object.freeze({ tools: true, structuredOutput: true }),
30
+ capabilities: Object.freeze({ tools: true, structuredOutput: true,
31
+ ...(options.media === false ? {} : { media: options.media ?? Object.freeze({ types: MEDIA_TYPES, urls: true }) }) }),
12
32
  maxCostMicros: options.maxCostMicros ?? 0,
13
- async generate(request) {
14
- request.signal.throwIfAborted();
15
- const response = steps[position++];
16
- if (!response)
17
- throw new MayuraError('MODEL_FAILED', 'The test model script is exhausted.');
18
- const result = typeof response === 'function' ? await response(request) : response;
19
- // Copy snapshots so a runtime cannot mutate a later test's scripted response.
20
- return jsonValue(result);
33
+ generate: next,
34
+ async *stream(request) {
35
+ const response = await next(request);
36
+ if (response.type === 'final') {
37
+ const text = JSON.stringify(response.output);
38
+ for (let index = 0; index < text.length; index += chunk) {
39
+ request.signal.throwIfAborted();
40
+ yield { type: 'output.delta', text: text.slice(index, index + chunk) };
41
+ }
42
+ }
43
+ yield { type: 'response', response };
21
44
  },
22
45
  });
23
46
  }
47
+ /** A real 1×1 PNG, for tests of agents and tools that take or return images. */
48
+ export function testImage(options = {}) {
49
+ return mediaFromBase64('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'image/png', options);
50
+ }
51
+ /** A minimal one-page PDF, for tests of agents and tools that take or return documents. */
52
+ export function testPdf(options = {}) {
53
+ const text = ['%PDF-1.4', '1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj', '2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj',
54
+ '3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 72 72]>>endobj', 'trailer<</Root 1 0 R>>', '%%EOF', ''].join('\n');
55
+ return mediaFromBase64(btoa(text), 'application/pdf', options);
56
+ }
57
+ /** The grants a tool needs to run: `tool:<id>`, each of its capabilities, and its effect (unless it has none). */
58
+ export function toolGrants(tool) {
59
+ return [`tool:${tool.id}`, ...tool.capabilities, ...(tool.effects === 'none' ? [] : [`effect:${tool.effects}`])];
60
+ }
61
+ /**
62
+ * Run one tool through Mayura's broker, as an agent's call would, without an agent, model or runtime: permissions,
63
+ * input and output validation, guards, timeout, cost and the `outcome_unknown` rules all apply. For unit tests.
64
+ */
65
+ export async function testTool(tool, input, options = {}) {
66
+ const budget = new Budget(options.budgetMicros ?? tool.costMicros, 1);
67
+ let receipt;
68
+ const outcome = await invokeTool(tool, input, {
69
+ runId: options.runId ?? 'test-run', callId: options.callId ?? 'test-call',
70
+ scope: options.scope ?? { principalId: 'test', projectId: 'test' }, signal: options.signal ?? new AbortController().signal,
71
+ permissions: { allow: [...(options.permissions ?? toolGrants(tool))] }, budget,
72
+ onExecutionReceipt: async (evidence) => { receipt = evidence; },
73
+ });
74
+ const snapshot = budget.snapshot();
75
+ return { outcome, spentMicros: Number(snapshot.spentMicros), reservedMicros: snapshot.reservedMicros, receipt: outcome.receipt ?? receipt };
76
+ }
24
77
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAA4D,MAAM,cAAc,CAAC;AAEhH;;;GAGG;AACH,MAAM,UAAU,aAAa,CAC3B,SAA2G,EAC3G,OAAO,GAA8D,EAAE;IAEvE,MAAM,KAAK,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC;IAC7B,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,EAAE,EAAE,OAAO,CAAC,EAAE,IAAI,UAAU;QAC5B,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC;QACpE,aAAa,EAAE,OAAO,CAAC,aAAa,IAAI,CAAC;QACzC,KAAK,CAAC,QAAQ,CAAC,OAAqB;YAClC,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;YAChC,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;YACnC,IAAI,CAAC,QAAQ;gBAAE,MAAM,IAAI,WAAW,CAAC,cAAc,EAAE,qCAAqC,CAAC,CAAC;YAC5F,MAAM,MAAM,GAAG,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;YACnF,8EAA8E;YAC9E,OAAO,SAAS,CAAC,MAAM,CAA6B,CAAC;QACvD,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MayuraError, jsonValue, type ModelAdapter, type ModelRequest, type ModelResponse } from '@mayura/core';\n\n/**\n * Deterministic test-only model. It never performs inference or network requests.\n * Each call consumes a scripted response; exhaustion is an error, not a fabricated answer.\n */\nexport function scriptedModel(\n responses: readonly (ModelResponse | ((request: ModelRequest) => ModelResponse | Promise<ModelResponse>))[],\n options: { readonly id?: string; readonly maxCostMicros?: number } = {},\n): ModelAdapter {\n const steps = [...responses];\n let position = 0;\n return Object.freeze({\n id: options.id ?? 'scripted',\n capabilities: Object.freeze({ tools: true, structuredOutput: true }),\n maxCostMicros: options.maxCostMicros ?? 0,\n async generate(request: ModelRequest): Promise<ModelResponse> {\n request.signal.throwIfAborted();\n const response = steps[position++];\n if (!response) throw new MayuraError('MODEL_FAILED', 'The test model script is exhausted.');\n const result = typeof response === 'function' ? await response(request) : response;\n // Copy snapshots so a runtime cannot mutate a later test's scripted response.\n return jsonValue(result) as unknown as ModelResponse;\n },\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,SAAS,EAAE,eAAe,EAA2K,MAAM,cAAc,CAAC;AACrQ,OAAO,EAAE,UAAU,EAAiC,MAAM,eAAe,CAAC;AAE1E;;;;;;;;;GASG;AACH,MAAM,UAAU,aAAa,CAC3B,SAA2G,EAC3G,OAAO,GAA4I,EAAE;IAErJ,MAAM,KAAK,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC;IAC7B,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,IAAI,EAAE,CAAC;IACxC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC;QAAE,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,yCAAyC,CAAC,CAAC;IAClI,MAAM,IAAI,GAAG,KAAK,EAAE,OAAqB,EAA0B,EAAE;QACnE,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;QAChC,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;QACnC,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,WAAW,CAAC,cAAc,EAAE,qCAAqC,CAAC,CAAC;QAC5F,MAAM,MAAM,GAAG,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;QACnF,8EAA8E;QAC9E,OAAO,SAAS,CAAC,MAAM,CAA6B,CAAC;IACvD,CAAC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,EAAE,EAAE,OAAO,CA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AC,OAAO,CAAC,WAAW,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,MAAM;QAC9E,kBAAkB,EAAE,KAAK,EAAC,QAAQ,EAAC,EAAE,GAAG,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC;KAC9D,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;IACnC,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,cAAc,EAAE,QAAQ,CAAC,cAAc,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,OAAO,EAAE,CAAC;AAC9I,CAAC","sourcesContent":["import { Budget, MayuraError, MEDIA_TYPES, jsonValue, mediaFromBase64, type ExecutionReceipt, type Media, type ModelAdapter, type ModelMediaCapability, type ModelRequest, type ModelResponse, type ModelStreamEvent, type Outcome, type Scope } from '@mayura/core';\nimport { invokeTool, type AnyTool, type ToolOutput } from '@mayura/tools';\n\n/**\n * Deterministic test-only model. It never performs inference or network requests.\n * Each call consumes a scripted response; exhaustion is an error, not a fabricated answer.\n *\n * It also streams, for agents with a stream policy: a final answer arrives as `output.delta` pieces of its JSON text\n * (`streamChunk` characters each, 16 by default), then the complete response, exactly as a provider adapter streams.\n *\n * It can \"see\" every media type and URLs, so agents that accept images or PDFs can be tested; a scripted step receives\n * the request with its `media`. Pass `media: false` to test a model that cannot see.\n */\nexport function scriptedModel(\n responses: readonly (ModelResponse | ((request: ModelRequest) => ModelResponse | Promise<ModelResponse>))[],\n options: { readonly id?: string; readonly maxCostMicros?: number; readonly streamChunk?: number; readonly media?: ModelMediaCapability | false } = {},\n): ModelAdapter {\n const steps = [...responses];\n let position = 0;\n const chunk = options.streamChunk ?? 16;\n if (!Number.isSafeInteger(chunk) || chunk < 1) throw new MayuraError('INVALID_CONFIG', 'streamChunk must be a positive integer.');\n const next = async (request: ModelRequest): Promise<ModelResponse> => {\n request.signal.throwIfAborted();\n const response = steps[position++];\n if (!response) throw new MayuraError('MODEL_FAILED', 'The test model script is exhausted.');\n const result = typeof response === 'function' ? await response(request) : response;\n // Copy snapshots so a runtime cannot mutate a later test's scripted response.\n return jsonValue(result) as unknown as ModelResponse;\n };\n return Object.freeze({\n id: options.id ?? 'scripted',\n capabilities: Object.freeze({ tools: true, structuredOutput: true,\n ...(options.media === false ? {} : { media: options.media ?? Object.freeze({ types: MEDIA_TYPES, urls: true }) }) }),\n maxCostMicros: options.maxCostMicros ?? 0,\n generate: next,\n async *stream(request: ModelRequest): AsyncIterable<ModelStreamEvent> {\n const response = await next(request);\n if (response.type === 'final') {\n const text = JSON.stringify(response.output);\n for (let index = 0; index < text.length; index += chunk) { request.signal.throwIfAborted(); yield { type: 'output.delta', text: text.slice(index, index + chunk) }; }\n }\n yield { type: 'response', response };\n },\n });\n}\n\n/** A real 1×1 PNG, for tests of agents and tools that take or return images. */\nexport function testImage(options: { readonly name?: string } = {}): Media {\n return mediaFromBase64('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'image/png', options);\n}\n/** A minimal one-page PDF, for tests of agents and tools that take or return documents. */\nexport function testPdf(options: { readonly name?: string } = {}): Media {\n const text = ['%PDF-1.4', '1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj', '2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj',\n '3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 72 72]>>endobj', 'trailer<</Root 1 0 R>>', '%%EOF', ''].join('\\n');\n return mediaFromBase64(btoa(text), 'application/pdf', options);\n}\n\n/** The grants a tool needs to run: `tool:<id>`, each of its capabilities, and its effect (unless it has none). */\nexport function toolGrants(tool: AnyTool): readonly string[] {\n return [`tool:${tool.id}`, ...tool.capabilities, ...(tool.effects === 'none' ? [] : [`effect:${tool.effects}`])];\n}\n\nexport interface TestToolOptions {\n /** What the call is allowed; the default is exactly what the tool needs (`toolGrants`). */\n readonly permissions?: readonly string[];\n readonly scope?: Scope;\n /** The budget for the call, in micros; the default is the tool's own `costMicros`. */\n readonly budgetMicros?: number;\n readonly signal?: AbortSignal;\n readonly runId?: string;\n readonly callId?: string;\n}\n\nexport interface TestToolResult<T extends AnyTool> {\n /** The outcome, exactly as a run would see it: checked input, the tool's effect and cost rules, checked output. */\n readonly outcome: Outcome<ToolOutput<T>>;\n /** What the call was charged: known cost, and cost still unresolved (an uncertain call keeps its reservation). */\n readonly spentMicros: number;\n readonly reservedMicros: number;\n /** The execution record Mayura keeps for the call, when it started. */\n readonly receipt: ExecutionReceipt | undefined;\n}\n\n/**\n * Run one tool through Mayura's broker, as an agent's call would, without an agent, model or runtime: permissions,\n * input and output validation, guards, timeout, cost and the `outcome_unknown` rules all apply. For unit tests.\n */\nexport async function testTool<T extends AnyTool>(tool: T, input: unknown, options: TestToolOptions = {}): Promise<TestToolResult<T>> {\n const budget = new Budget(options.budgetMicros ?? tool.costMicros, 1);\n let receipt: ExecutionReceipt | undefined;\n const outcome = await invokeTool(tool, input, {\n runId: options.runId ?? 'test-run', callId: options.callId ?? 'test-call',\n scope: options.scope ?? { principalId: 'test', projectId: 'test' }, signal: options.signal ?? new AbortController().signal,\n permissions: { allow: [...(options.permissions ?? toolGrants(tool))] }, budget,\n onExecutionReceipt: async evidence => { receipt = evidence; },\n });\n const snapshot = budget.snapshot();\n return { outcome, spentMicros: Number(snapshot.spentMicros), reservedMicros: snapshot.reservedMicros, receipt: outcome.receipt ?? receipt };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "type": "module",
3
- "version": "0.1.0-dev.0",
3
+ "version": "1.0.0-rc.2",
4
4
  "private": true
5
5
  }