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,228 @@
1
+ import { MayuraError } from './errors.js';
2
+
3
+ // Media a model can see: images and PDFs, given to an agent with its input or returned by a tool. Media never travels
4
+ // inside JSON: it has its own channel, its own byte limits, and its bytes are never shown to hooks or events.
5
+
6
+ /** The media types Mayura accepts. Each is checked against the file's own leading bytes, not only its label. */
7
+ export const MEDIA_TYPES = Object.freeze(['image/png', 'image/jpeg', 'image/webp', 'image/gif', 'application/pdf'] as const);
8
+ export type MediaType = typeof MEDIA_TYPES[number];
9
+
10
+ /** An image or PDF: its bytes, or an HTTPS URL the model provider fetches itself. Create it with `media` or `mediaUrl`. */
11
+ export type Media =
12
+ | { readonly type: 'media'; readonly mediaType: MediaType; readonly data: Uint8Array; readonly name?: string }
13
+ | { readonly type: 'media'; readonly mediaType: MediaType; readonly url: string; readonly name?: string };
14
+
15
+ /** What hooks, events and logs see of a piece of media: never its bytes. */
16
+ export interface MediaSummary {
17
+ readonly mediaType: MediaType;
18
+ readonly source: 'bytes' | 'url';
19
+ /** The size of inline bytes; absent for a URL. */
20
+ readonly bytes?: number;
21
+ readonly name?: string;
22
+ }
23
+
24
+ /**
25
+ * Which media an agent accepts with its input, or a tool may return. Nothing is accepted unless it is declared.
26
+ * - `accept`: the media types allowed.
27
+ * - `maxItems`: how many at once (default 4, at most 32).
28
+ * - `maxBytes`: the largest single item, in bytes (default 10 MB, at most 64 MiB).
29
+ * - `urls`: HTTPS URL prefixes a URL source must start with, such as `'https://cdn.example.com/'`. Without it, only
30
+ * bytes are accepted. The model provider fetches the URL, so list only addresses you trust it to read.
31
+ */
32
+ export interface MediaPolicy {
33
+ readonly accept: readonly MediaType[];
34
+ readonly maxItems?: number;
35
+ readonly maxBytes?: number;
36
+ readonly urls?: readonly string[];
37
+ }
38
+ /** A policy with its defaults filled in. */
39
+ export interface ResolvedMediaPolicy {
40
+ readonly accept: readonly MediaType[];
41
+ readonly maxItems: number;
42
+ readonly maxBytes: number;
43
+ readonly urls: readonly string[];
44
+ }
45
+
46
+ const MAX_ITEM_BYTES = 67_108_864;
47
+ const nameText = /^[^\u0000-\u001f\u007f/\\]{1,255}$/u;
48
+
49
+ function isMediaType(value: unknown): value is MediaType { return (MEDIA_TYPES as readonly unknown[]).includes(value); }
50
+ const startsWith = (bytes: Uint8Array, prefix: readonly number[], at = 0): boolean =>
51
+ bytes.length >= at + prefix.length && prefix.every((byte, index) => bytes[at + index] === byte);
52
+ const ascii = (text: string): number[] => [...text].map(character => character.charCodeAt(0));
53
+
54
+ /** The media type the bytes really are, from their leading bytes; undefined when they are none of `MEDIA_TYPES`. */
55
+ export function sniffMediaType(bytes: Uint8Array): MediaType | undefined {
56
+ if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'image/png';
57
+ if (startsWith(bytes, [0xff, 0xd8, 0xff])) return 'image/jpeg';
58
+ if (startsWith(bytes, ascii('GIF87a')) || startsWith(bytes, ascii('GIF89a'))) return 'image/gif';
59
+ if (startsWith(bytes, ascii('RIFF')) && startsWith(bytes, ascii('WEBP'), 8)) return 'image/webp';
60
+ if (startsWith(bytes, ascii('%PDF-'))) return 'application/pdf';
61
+ return undefined;
62
+ }
63
+
64
+ function checkName(name: unknown): string | undefined {
65
+ if (name === undefined) return undefined;
66
+ if (typeof name !== 'string' || !nameText.test(name)) throw new MayuraError('INVALID_INPUT', 'A media name must be 1–255 characters, without slashes or control characters.');
67
+ return name;
68
+ }
69
+
70
+ /**
71
+ * Media from bytes. The bytes are copied, and must really be the given type: a PNG labelled `image/jpeg` is refused
72
+ * here rather than by the provider.
73
+ */
74
+ export function media(data: Uint8Array | ArrayBuffer, mediaType: MediaType, options: { readonly name?: string } = {}): Media {
75
+ const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
76
+ if (!(bytes instanceof Uint8Array)) throw new MayuraError('INVALID_INPUT', 'Media bytes must be a Uint8Array or ArrayBuffer.');
77
+ if (!isMediaType(mediaType)) throw new MayuraError('INVALID_INPUT', `Unsupported media type; use one of ${MEDIA_TYPES.join(', ')}.`);
78
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_ITEM_BYTES) throw new MayuraError('INVALID_INPUT', 'Media must hold between 1 byte and 64 MiB.');
79
+ const actual = sniffMediaType(bytes);
80
+ if (actual !== mediaType) {
81
+ throw new MayuraError('INVALID_INPUT', actual ? `These bytes are ${actual}, not ${mediaType}.` : `These bytes are not a ${mediaType} file.`);
82
+ }
83
+ const name = checkName(options.name);
84
+ return Object.freeze({ type: 'media', mediaType, data: bytes.slice(), ...(name === undefined ? {} : { name }) });
85
+ }
86
+
87
+ /** Media the model provider fetches from an HTTPS URL. The agent must list the URL's prefix in `media.urls`. */
88
+ export function mediaUrl(url: string, mediaType: MediaType, options: { readonly name?: string } = {}): Media {
89
+ if (!isMediaType(mediaType)) throw new MayuraError('INVALID_INPUT', `Unsupported media type; use one of ${MEDIA_TYPES.join(', ')}.`);
90
+ const href = checkUrl(url);
91
+ const name = checkName(options.name);
92
+ return Object.freeze({ type: 'media', mediaType, url: href, ...(name === undefined ? {} : { name }) });
93
+ }
94
+
95
+ /** Media from base64 text, as it arrives in JSON (for example over HTTP). */
96
+ export function mediaFromBase64(text: string, mediaType: MediaType, options: { readonly name?: string } = {}): Media {
97
+ return media(base64ToBytes(text), mediaType, options);
98
+ }
99
+
100
+ function checkUrl(url: unknown): string {
101
+ let parsed: URL;
102
+ try { parsed = new URL(typeof url === 'string' ? url : ''); } catch { throw new MayuraError('INVALID_INPUT', 'A media URL must be an absolute https:// URL.'); }
103
+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password || parsed.href.length > 2_048) {
104
+ throw new MayuraError('INVALID_INPUT', 'A media URL must be an https:// URL of at most 2,048 characters, without credentials.');
105
+ }
106
+ return parsed.href;
107
+ }
108
+
109
+ /** The summary hooks and events see. */
110
+ export function mediaSummary(item: Media): MediaSummary {
111
+ return Object.freeze({ mediaType: item.mediaType, source: 'data' in item ? 'bytes' as const : 'url' as const,
112
+ ...('data' in item ? { bytes: item.data.byteLength } : {}), ...(item.name === undefined ? {} : { name: item.name }) });
113
+ }
114
+
115
+ /** Validate a declared policy, filling in its defaults. `where` names it in the error, such as `Agent support`. */
116
+ export function mediaPolicy(value: MediaPolicy, where: string): ResolvedMediaPolicy {
117
+ const fail = (why: string): never => { throw new MayuraError('INVALID_CONFIG', `${where}: media ${why}`); };
118
+ if (!value || typeof value !== 'object') return fail('must be an object such as { accept: [\'image/png\'] }.');
119
+ const accept = value.accept;
120
+ if (!Array.isArray(accept) || accept.length === 0 || accept.some(type => !isMediaType(type)) || new Set(accept).size !== accept.length) {
121
+ return fail(`accept must list distinct media types from ${MEDIA_TYPES.join(', ')}.`);
122
+ }
123
+ const maxItems = value.maxItems ?? 4; const maxBytes = value.maxBytes ?? 10_000_000;
124
+ if (!Number.isSafeInteger(maxItems) || maxItems < 1 || maxItems > 32) fail('maxItems must be between 1 and 32.');
125
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_ITEM_BYTES) fail('maxBytes must be between 1 and 67,108,864.');
126
+ const urls = value.urls ?? [];
127
+ if (!Array.isArray(urls) || urls.length > 32) fail('urls must be a list of at most 32 https:// prefixes.');
128
+ for (const prefix of urls) {
129
+ let parsed: URL | undefined;
130
+ try { parsed = new URL(prefix); } catch { /* reported below */ }
131
+ // A prefix must end at a path boundary, so https://cdn.example.com cannot also admit https://cdn.example.com.evil.
132
+ if (!parsed || parsed.protocol !== 'https:' || parsed.username || parsed.password || parsed.search || parsed.hash || !prefix.endsWith('/') || parsed.href !== prefix) {
133
+ fail(`url prefix ${JSON.stringify(String(prefix).slice(0, 80))} must be a plain https:// URL ending in /.`);
134
+ }
135
+ }
136
+ return Object.freeze({ accept: Object.freeze([...accept]), maxItems, maxBytes, urls: Object.freeze([...urls]) });
137
+ }
138
+
139
+ /**
140
+ * Check media against a policy and a byte allowance, and copy it: the result holds private copies of the bytes, so
141
+ * a caller changing its array afterwards changes nothing. `code` is the error code for a refusal (`INVALID_INPUT` for
142
+ * what a caller sent, `INVALID_OUTPUT` for what a tool returned); `where` names the source in the message.
143
+ */
144
+ export function admitMedia(items: unknown, policy: ResolvedMediaPolicy | undefined, allowanceBytes: number,
145
+ code: 'INVALID_INPUT' | 'INVALID_OUTPUT', where: string): { readonly media: readonly Media[]; readonly bytes: number } {
146
+ const fail = (why: string): never => { throw new MayuraError(code, `${where}: ${why}`); };
147
+ if (!Array.isArray(items)) return fail('media must be a list.');
148
+ if (items.length === 0) return { media: Object.freeze([]), bytes: 0 };
149
+ if (!policy) return fail('media is not accepted here; declare which types are accepted with `media: { accept: [...] }`.');
150
+ if (items.length > policy.maxItems) fail(`at most ${policy.maxItems} media items are accepted, not ${items.length}.`);
151
+ const admitted: Media[] = []; let total = 0;
152
+ for (const [index, raw] of items.entries()) {
153
+ const item = raw as Partial<Record<'type' | 'mediaType' | 'data' | 'url' | 'name', unknown>> | null;
154
+ const label = `media ${index + 1}`;
155
+ if (!item || typeof item !== 'object' || item.type !== 'media' || !isMediaType(item.mediaType)) return fail(`${label} is not media; create it with media() or mediaUrl().`);
156
+ if (!policy.accept.includes(item.mediaType)) fail(`${label} is ${item.mediaType}, which is not accepted (accepted: ${policy.accept.join(', ')}).`);
157
+ let name: string | undefined;
158
+ try { name = checkName(item.name); } catch (error) { fail(`${label}: ${(error as Error).message}`); }
159
+ if (item.data !== undefined) {
160
+ if (!(item.data instanceof Uint8Array) || item.url !== undefined) return fail(`${label} must hold either bytes or a URL.`);
161
+ const bytes = item.data.slice(); // a private copy, taken before any check
162
+ if (bytes.byteLength === 0 || bytes.byteLength > policy.maxBytes) fail(`${label} is ${bytes.byteLength} bytes; the limit is ${policy.maxBytes}.`);
163
+ const actual = sniffMediaType(bytes);
164
+ if (actual !== item.mediaType) fail(actual ? `${label} is labelled ${item.mediaType} but its bytes are ${actual}.` : `${label} is labelled ${item.mediaType} but its bytes are not that type.`);
165
+ total += bytes.byteLength;
166
+ if (total > allowanceBytes) fail(`the media is ${total} bytes or more, above the ${allowanceBytes} bytes left under limits.maxMediaBytes.`);
167
+ admitted.push(Object.freeze({ type: 'media', mediaType: item.mediaType, data: bytes, ...(name === undefined ? {} : { name }) }));
168
+ } else {
169
+ let href = '';
170
+ try { href = checkUrl(item.url); } catch (error) { fail(`${label}: ${(error as Error).message}`); }
171
+ if (!policy.urls.some(prefix => href.startsWith(prefix))) {
172
+ fail(policy.urls.length === 0 ? `${label} is a URL, but no URL prefixes are allowed (media.urls); send the bytes instead.`
173
+ : `${label} is not under an allowed URL prefix (media.urls).`);
174
+ }
175
+ admitted.push(Object.freeze({ type: 'media', mediaType: item.mediaType, url: href, ...(name === undefined ? {} : { name }) }));
176
+ }
177
+ }
178
+ return { media: Object.freeze(admitted), bytes: total };
179
+ }
180
+
181
+ const resultMedia = new WeakMap<object, { readonly output: unknown; readonly media: readonly Media[] }>();
182
+ /**
183
+ * A tool result with media for the model to see, such as a screenshot: return `withMedia(output, [media(...)])` from
184
+ * the tool's `execute`. `output` is checked against the tool's output schema as usual; the tool must declare `media`.
185
+ */
186
+ export function withMedia<T>(output: T, items: readonly Media[]): T {
187
+ if (!Array.isArray(items)) throw new MayuraError('INVALID_OUTPUT', 'withMedia needs a list of media.');
188
+ const wrapper = Object.freeze({ '~mayuraMedia': true });
189
+ resultMedia.set(wrapper, Object.freeze({ output, media: Object.freeze([...items]) }));
190
+ return wrapper as unknown as T;
191
+ }
192
+ /** The output and media of a `withMedia` result, or undefined for an ordinary result. For tool brokers. */
193
+ export function readMediaResult(value: unknown): { readonly output: unknown; readonly media: readonly Media[] } | undefined {
194
+ return value && typeof value === 'object' ? resultMedia.get(value) : undefined;
195
+ }
196
+
197
+ /** Base64 of bytes, in browsers and Node.js alike. */
198
+ export function bytesToBase64(bytes: Uint8Array): string {
199
+ const buffer = (globalThis as { Buffer?: { from(data: Uint8Array): { toString(encoding: string): string } } }).Buffer;
200
+ if (buffer) return buffer.from(bytes).toString('base64');
201
+ let binary = '';
202
+ for (let index = 0; index < bytes.length; index += 32_768) binary += String.fromCharCode(...bytes.subarray(index, index + 32_768));
203
+ return btoa(binary);
204
+ }
205
+ /** Bytes of base64 text; refuses anything that is not canonical base64. */
206
+ export function base64ToBytes(text: string): Uint8Array {
207
+ if (typeof text !== 'string' || text.length === 0 || text.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/u.test(text)) {
208
+ throw new MayuraError('INVALID_INPUT', 'Media data must be base64 text.');
209
+ }
210
+ const binary = atob(text); const bytes = new Uint8Array(binary.length);
211
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
212
+ return bytes;
213
+ }
214
+ /**
215
+ * The most bytes the media of these messages adds to a provider request once encoded (base64, or a URL), with room
216
+ * for each item's wrapping. Adapters allow this on top of their JSON request limit.
217
+ */
218
+ export function encodedMediaBytes(messages: readonly object[]): number {
219
+ let total = 0;
220
+ for (const message of messages) for (const item of ('media' in message ? message.media as readonly Media[] | undefined : undefined) ?? []) {
221
+ total += ('data' in item ? Math.ceil(item.data.byteLength / 3) * 4 : item.url.length) + 512 + (item.name?.length ?? 0) * 2;
222
+ }
223
+ return total;
224
+ }
225
+ /** A `data:` URL of inline media, as several providers take images. */
226
+ export function mediaDataUrl(item: Media & { readonly data: Uint8Array }): string {
227
+ return `data:${item.mediaType};base64,${bytesToBase64(item.data)}`;
228
+ }
@@ -0,0 +1,129 @@
1
+ import { MayuraError } from './errors.js';
2
+ import { freezeJson, jsonValue, type JsonObject, type JsonValue } from './json.js';
3
+ import type { Schema } from './schema.js';
4
+ import { ModelProviderError, type ModelDefinitionCheck, type ModelFailureReason } from './contracts.js';
5
+
6
+ const nested = ['items', 'additionalItems', 'not', 'if', 'then', 'else', 'contains'] as const;
7
+ const lists = ['anyOf', 'allOf', 'oneOf', 'prefixItems'] as const;
8
+ const maps = ['$defs', 'definitions', 'properties', 'patternProperties'] as const;
9
+ const isObject = (value: JsonValue | undefined): value is JsonObject => !!value && typeof value === 'object' && !Array.isArray(value);
10
+ const describesObject = (node: JsonObject): boolean =>
11
+ node['type'] === 'object' || (Array.isArray(node['type']) && node['type'].includes('object')) || (node['type'] === undefined && isObject(node['properties']));
12
+
13
+ /** Visit every subschema of a JSON Schema, with its JSON Pointer. */
14
+ function walk(node: JsonObject, path: string, visit: (node: JsonObject, path: string) => void): void {
15
+ visit(node, path);
16
+ for (const key of nested) { const child = node[key]; if (isObject(child)) walk(child, `${path}/${key}`, visit); }
17
+ if (isObject(node['additionalProperties'])) walk(node['additionalProperties'], `${path}/additionalProperties`, visit);
18
+ for (const key of lists) { const children = node[key]; if (Array.isArray(children)) children.forEach((child, index) => { if (isObject(child)) walk(child, `${path}/${key}/${index}`, visit); }); }
19
+ for (const key of maps) {
20
+ const children = node[key];
21
+ if (isObject(children)) for (const [name, child] of Object.entries(children)) if (isObject(child)) walk(child, `${path}/${key}/${name.replaceAll('~', '~0').replaceAll('/', '~1')}`, visit);
22
+ }
23
+ }
24
+
25
+ /**
26
+ * The JSON Schema of the values a validator accepts, when the validator can describe itself through the Standard JSON
27
+ * Schema interface (`~standard.jsonSchema`, which Zod 4.2 and later implement). That is what a model has to produce:
28
+ * a tool's input, or an agent's output. The `$schema` dialect marker is removed, and an object that says nothing about
29
+ * other keys gets `additionalProperties: false`, because a model should never add keys the validator would drop.
30
+ * Returns undefined when the validator cannot describe itself, or its description is not plain bounded JSON.
31
+ */
32
+ export function jsonSchemaOf(schema: Schema): JsonObject | undefined {
33
+ let described: unknown;
34
+ try {
35
+ const standard = schema['~standard'] as { readonly jsonSchema?: { readonly input?: unknown } };
36
+ const generator = standard.jsonSchema?.input;
37
+ if (typeof generator !== 'function') return undefined;
38
+ described = generator.call(standard.jsonSchema, { target: 'draft-2020-12' });
39
+ // A plain copy: generators may attach non-enumerable metadata that is not JSON.
40
+ const copy = jsonValue(JSON.parse(JSON.stringify(described)) as unknown, { maxBytes: 262_144, maxDepth: 64 });
41
+ if (!isObject(copy)) return undefined;
42
+ delete copy['$schema'];
43
+ walk(copy, '', node => { if (describesObject(node) && node['additionalProperties'] === undefined) node['additionalProperties'] = false; });
44
+ return freezeJson(copy) as JsonObject;
45
+ } catch { return undefined; }
46
+ }
47
+
48
+ /**
49
+ * Check a JSON Schema against the strict rules model providers apply to tool inputs and structured output (OpenAI and
50
+ * Anthropic strict mode, and OpenAI-compatible servers): the root is an object, and every object lists all of its
51
+ * properties in `required` and sets `additionalProperties: false`. Returns a frozen copy to send; an object with no
52
+ * properties may leave out `properties` and `required`, which the copy states. Throws INVALID_CONFIG naming `subject`,
53
+ * the place in the schema and how to fix it.
54
+ */
55
+ export function strictJsonSchema(schema: unknown, subject: string): JsonObject {
56
+ let copy: JsonValue;
57
+ try { copy = jsonValue(schema, { maxBytes: 262_144, maxDepth: 64 }); }
58
+ catch { throw new MayuraError('INVALID_CONFIG', `${subject} is not a plain JSON Schema object.`); }
59
+ if (!isObject(copy) || copy['type'] !== 'object') throw new MayuraError('INVALID_CONFIG', `${subject} must be a JSON Schema whose root has type "object".`);
60
+ const at = (path: string): string => (path ? ` at ${path}` : '');
61
+ walk(copy, '', (node, path) => {
62
+ if (!describesObject(node)) return;
63
+ if (node['properties'] === undefined && node['required'] === undefined) node['properties'] = {};
64
+ const properties = node['properties'];
65
+ if (!isObject(properties)) throw new MayuraError('INVALID_CONFIG', `${subject}: "properties"${at(path)} must be an object.`);
66
+ if (node['required'] === undefined && Object.keys(properties).length === 0) node['required'] = [];
67
+ // Generators leave `required` out when nothing is required; then every property is optional.
68
+ const required = node['required'] ?? [];
69
+ if (!Array.isArray(required) || required.some(key => typeof key !== 'string') || new Set(required).size !== required.length) {
70
+ throw new MayuraError('INVALID_CONFIG', `${subject}: "required"${at(path)} must list property names once each.`);
71
+ }
72
+ const optional = Object.keys(properties).find(key => !required.includes(key));
73
+ if (optional !== undefined) {
74
+ throw new MayuraError('INVALID_CONFIG', `${subject}: property "${optional}"${at(path)} is optional, but model providers require every property. Make it nullable instead (with Zod, .nullable() rather than .optional() or .default()).`);
75
+ }
76
+ const unknown = required.find(key => !Object.hasOwn(properties, key as string));
77
+ if (unknown !== undefined) throw new MayuraError('INVALID_CONFIG', `${subject}: "required"${at(path)} names "${String(unknown)}", which is not a property.`);
78
+ if (node['additionalProperties'] !== false) {
79
+ throw new MayuraError('INVALID_CONFIG', `${subject}: the object${at(path)} must set additionalProperties to false; model providers accept no open objects, records or maps.`);
80
+ }
81
+ });
82
+ return freezeJson(copy) as JsonObject;
83
+ }
84
+
85
+ /**
86
+ * The failure for a provider's HTTP error status: 401 and 403 are credentials or model access, 402 and 429 a rate limit
87
+ * or quota, 408 and 5xx the provider being unavailable, and any other status a rejected request. `costMicros` is usage
88
+ * the provider confirmed before the failure, if any.
89
+ */
90
+ export function providerHttpFailure(status: number, costMicros?: number): ModelProviderError {
91
+ const reason: ModelFailureReason = status === 401 || status === 403 ? 'authentication' : status === 402 || status === 429 ? 'rate_limited'
92
+ : status === 408 || (status >= 500 && status <= 599) ? 'unavailable' : 'rejected';
93
+ const httpStatus = Number.isSafeInteger(status) && status >= 100 && status <= 599 ? status : undefined;
94
+ return new ModelProviderError(reason, { ...(httpStatus === undefined ? {} : { httpStatus }), ...(costMicros === undefined ? {} : { costMicros }) });
95
+ }
96
+
97
+ /**
98
+ * `ModelAdapter.checkDefinition` for a provider with strict schemas: every tool needs an input schema and the agent an
99
+ * output schema (unless the adapter was given its own, `fixedOutput`), and each must follow the strict rules.
100
+ */
101
+ export function checkStrictDefinition(definition: ModelDefinitionCheck, fixedOutput?: JsonObject): void {
102
+ for (const tool of definition.tools) {
103
+ if (tool.inputJsonSchema === undefined) {
104
+ throw new MayuraError('INVALID_CONFIG', `Tool "${tool.id}" has no inputJsonSchema, and its input validator cannot describe itself. Give the tool an inputJsonSchema.`);
105
+ }
106
+ strictJsonSchema(tool.inputJsonSchema, `Tool "${tool.id}" input schema`);
107
+ }
108
+ if (fixedOutput !== undefined) return;
109
+ if (definition.outputJsonSchema === undefined) {
110
+ throw new MayuraError('INVALID_CONFIG', 'There is no output JSON Schema: the output validator cannot describe itself. Give outputJsonSchema to defineAgent or to the model adapter.');
111
+ }
112
+ strictJsonSchema(definition.outputJsonSchema, 'The output schema');
113
+ }
114
+
115
+ /**
116
+ * The names a provider sees for tools: each Mayura tool id made safe for provider function names (letters, digits,
117
+ * `_` and `-`, at most 64 characters), so `orders.list` becomes `orders_list` and the model can match the names in
118
+ * the instructions. Two ids that sanitize alike get `_2`, `_3`, ... so every name is unique. The map is id -> name.
119
+ */
120
+ export function modelToolNames(ids: readonly string[]): ReadonlyMap<string, string> {
121
+ const names = new Map<string, string>(); const taken = new Set<string>();
122
+ for (const id of ids) {
123
+ const base = (id.replace(/[^A-Za-z0-9_-]/gu, '_') || 'tool').slice(0, 64);
124
+ let name = base;
125
+ for (let suffix = 2; taken.has(name); suffix++) name = `${base.slice(0, 64 - String(suffix).length - 1)}_${suffix}`;
126
+ taken.add(name); names.set(id, name);
127
+ }
128
+ return names;
129
+ }
@@ -91,7 +91,7 @@ function request(events, serviceName, serviceVersion) {
91
91
  const attributes = [attribute('service.name', serviceName)];
92
92
  if (serviceVersion)
93
93
  attributes.push(attribute('service.version', serviceVersion));
94
- return { resourceLogs: [{ resource: { attributes }, scopeLogs: [{ scope: { name: '@mayura/observability', version: '0.1.0-dev.0' }, logRecords: events.map(record) }] }] };
94
+ return { resourceLogs: [{ resource: { attributes }, scopeLogs: [{ scope: { name: '@mayura/observability', version: '1.0.0-rc.2' }, logRecords: events.map(record) }] }] };
95
95
  }
96
96
  async function abortable(operation, signal) {
97
97
  if (signal.aborted) {
@@ -1 +1 @@
1
- {"version":3,"file":"otlp-http-json.js","sourceRoot":"","sources":["../src/otlp-http-json.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,SAAS,EAAE,WAAW,EAAkD,MAAM,cAAc,CAAC;AAC7H,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAGjE,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,EAAE,eAAe,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,EAAE,CAAC,CAAC;AAC9H,MAAM,UAAU,GAAG,qCAAqC,CAAC;AACzD,MAAM,UAAU,GAAG,sCAAsC,CAAC;AAC1D,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,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EAAE,QAAQ,CAAC,CAAC;gBAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;YAAC,CAAC;QACrF,CAAC;QAAC,MAAM,CAAC;YACP,KAAK,CAAC,gBAAgB,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;YACvC,IAAI,QAAQ,EAAE,CAAC;gBAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;gBAAC,MAAM,IAAI,WAAW,CAAC,SAAS,EAAE,iCAAiC,CAAC,CAAC;YAAC,CAAC;YACjH,IAAI,OAAO,CAAC,MAAM,CAAC,OAAO,IAAI,MAAM,EAAE,CAAC;gBAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBAAC,MAAM,IAAI,WAAW,CAAC,WAAW,EAAE,qCAAqC,CAAC,CAAC;YAAC,CAAC;YAChJ,KAAK,CAAC,gBAAgB,CAAC,CAAC;YAAC,OAAO,MAAM,EAAE,CAAC;QAC3C,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAC;YAAC,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YAAC,MAAM,GAAG,SAAS,CAAC;YAAC,QAAQ,GAAG,KAAK,CAAC;QAChH,CAAC;IACH,CAAC,CAAC;IACF,MAAM,KAAK,GAAG,GAAS,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAAC,MAAM,GAAG,IAAI,CAAC;QAAC,MAAM,EAAE,KAAK,EAAE,CAAC;IAAC,CAAC,CAAC,CAAC,CAAC;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import { assertPositiveInteger, jsonValue, MayuraError, type JsonObject, type JsonValue, type RunEvent } from '@mayura/core';\nimport { snapshotRunEventMetadata } from '@mayura/observability';\nimport type { ExactCount, OtlpHttpJsonLogExporter, OtlpHttpJsonLogExporterOptions, OtlpLogExporterMetrics, OtlpLogExporterSnapshot } from './contracts.js';\n\nconst defaults = Object.freeze({ timeoutMs: 5_000, maxBatchSize: 256, maxRequestBytes: 1_048_576, maxResponseBytes: 65_536 });\nconst headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;\nconst stableName = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;\nconst blockedHeaders = new Set(['connection', 'content-length', 'content-type', 'cookie', 'host', 'set-cookie', 'transfer-encoding']);\nconst metricNames = ['batchesAttempted', 'recordsAttempted', 'recordsAccepted', 'recordsDropped', 'partialResponses', 'failedRequests', 'timedOutRequests', 'cancelledRequests', 'requestBytes', 'responseBytes'] as const;\ntype Metric = typeof metricNames[number];\n\nconst failed = (): never => { throw new MayuraError('TOOL_FAILED', 'The telemetry export failed. Inspect authorized local diagnostics.'); };\nfunction exact(value: bigint): ExactCount { return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : value.toString(); }\nfunction object(value: JsonValue | undefined): JsonObject {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return failed();\n return value;\n}\nfunction stable(value: unknown): string {\n if (typeof value !== 'string' || !stableName.test(value)) throw new MayuraError('INVALID_CONFIG', 'Exporter names must be bounded stable identifiers.');\n return value;\n}\nfunction endpoint(value: unknown, allowInsecureLoopback: boolean): string {\n try {\n if (typeof value !== 'string' || value.length > 2_048) throw new Error();\n const url = new URL(value);\n const loopback = ['127.0.0.1', '[::1]'].includes(url.hostname);\n if ((url.protocol !== 'https:' && !(allowInsecureLoopback && url.protocol === 'http:' && loopback))\n || url.username || url.password || url.search || url.hash || !url.pathname.endsWith('/v1/logs')) throw new Error();\n return url.href;\n } catch { throw new MayuraError('INVALID_CONFIG', 'OTLP logs require an explicit HTTPS endpoint ending in /v1/logs.'); }\n}\nfunction headers(value: OtlpHttpJsonLogExporterOptions['headers']): Readonly<Record<string, string>> {\n try {\n if (value === undefined) return Object.freeze({ 'Content-Type': 'application/json' });\n const descriptors = Object.getOwnPropertyDescriptors(value);\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error();\n const result: Record<string, string> = { 'Content-Type': 'application/json' };\n const seen = new Set(['content-type']);\n if (Object.getOwnPropertySymbols(value).length > 0 || Object.keys(descriptors).length > 32) throw new Error();\n for (const [key, descriptor] of Object.entries(descriptors)) {\n const normalized = key.toLowerCase();\n if (!descriptor.enumerable || !('value' in descriptor) || !headerName.test(key) || blockedHeaders.has(normalized) || seen.has(normalized)\n || typeof descriptor.value !== 'string' || descriptor.value.length > 4_096 || /[\\r\\n\\0]/.test(descriptor.value)) throw new Error();\n seen.add(normalized);\n result[key] = descriptor.value;\n }\n return Object.freeze(result);\n } catch { throw new MayuraError('INVALID_CONFIG', 'Exporter headers must be bounded explicit HTTP fields.'); }\n}\n\nfunction anyValue(value: string | number | boolean): JsonObject {\n if (typeof value === 'string') return { stringValue: value };\n if (typeof value === 'boolean') return { boolValue: value };\n return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };\n}\nfunction attribute(key: string, value: string | number | boolean): JsonObject { return { key, value: anyValue(value) }; }\nfunction severity(event: RunEvent): readonly [number, string] {\n if (event.type === 'events.gap') return [13, 'WARN'];\n if (event.type !== 'run.completed' && event.type !== 'tool.completed' && event.type !== 'hook.completed' && event.type !== 'delegate.completed') return [9, 'INFO'];\n const status = event.metadata['status'];\n if (status === 'failed' || status === 'outcome_unknown') return [17, 'ERROR'];\n if (status === 'blocked' || status === 'cancelled') return [13, 'WARN'];\n return [9, 'INFO'];\n}\nfunction record(event: RunEvent): JsonObject {\n const [severityNumber, severityText] = severity(event);\n const attributes = [attribute('mayura.run.id', event.runId), attribute('mayura.event.sequence', event.sequence)];\n for (const [key, value] of Object.entries(event.metadata)) attributes.push(attribute(`mayura.${key}`, value));\n return {\n timeUnixNano: (BigInt(Date.parse(event.timestamp)) * 1_000_000n).toString(),\n severityNumber, severityText, body: { stringValue: event.type }, attributes,\n };\n}\nfunction request(events: readonly RunEvent[], serviceName: string, serviceVersion?: string): JsonObject {\n const attributes = [attribute('service.name', serviceName)];\n if (serviceVersion) attributes.push(attribute('service.version', serviceVersion));\n return { resourceLogs: [{ resource: { attributes }, scopeLogs: [{ scope: { name: '@mayura/observability', version: '0.1.0-dev.0' }, logRecords: events.map(record) }] }] };\n}\n\nasync function abortable<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) { void operation.catch(() => undefined); throw signal.reason; }\n let listener: (() => void) | undefined;\n try {\n return await Promise.race([operation, new Promise<never>((_, reject) => {\n listener = () => reject(signal.reason); signal.addEventListener('abort', listener, { once: true });\n if (signal.aborted) listener();\n })]);\n } finally { if (listener) signal.removeEventListener('abort', listener); }\n}\nasync function responsePayload(response: Response, limit: number, signal: AbortSignal, charge: (bytes: number) => void): Promise<JsonObject> {\n if (response.status !== 200 || response.redirected) { void response.body?.cancel().catch(() => undefined); return failed(); }\n if (!response.body) return {};\n const length = response.headers.get('content-length');\n if (length !== null && (!/^\\d+$/.test(length) || Number(length) > limit)) { void response.body.cancel().catch(() => undefined); return failed(); }\n const reader = response.body.getReader(); const chunks: Uint8Array[] = []; let size = 0;\n try {\n for (;;) {\n const item = await abortable(reader.read(), signal);\n if (item.done) break;\n size += item.value.byteLength; charge(item.value.byteLength);\n if (size > limit) return failed();\n chunks.push(item.value);\n }\n if (size === 0) return {};\n if (!/^application\\/json(?:\\s*;|$)/iu.test(response.headers.get('content-type') ?? '')) return failed();\n const bytes = new Uint8Array(size); let offset = 0;\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }\n return object(jsonValue(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)), { maxBytes: limit, maxDepth: 8, maxNodes: 1_024 }));\n } finally { void reader.cancel().catch(() => undefined); reader.releaseLock(); }\n}\nfunction rejectedRecords(payload: JsonObject, sent: number): number {\n const partial = payload['partialSuccess'];\n if (partial === undefined) return 0;\n const value = object(partial)['rejectedLogRecords'];\n if (value === undefined) return 0;\n const text = typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : value;\n if (typeof text !== 'string' || !/^\\d{1,20}$/.test(text)) return failed();\n const rejected = BigInt(text);\n if (rejected > BigInt(sent)) return failed();\n return Number(rejected);\n}\n\n/** Explicit OTLP/HTTP JSON log export with bounded metadata-only delivery and no retries. */\nexport function createOtlpHttpJsonLogExporter(options: OtlpHttpJsonLogExporterOptions): OtlpHttpJsonLogExporter {\n let config: typeof defaults; let destination: string; let serviceName: string; let serviceVersion: string | undefined;\n let transport: typeof globalThis.fetch; let fixedHeaders: Readonly<Record<string, string>>;\n try {\n const allowInsecureLoopback = options.allowInsecureLoopback ?? false;\n if (typeof allowInsecureLoopback !== 'boolean') throw new Error();\n config = Object.freeze(Object.fromEntries(Object.entries(defaults).map(([key, fallback]) => [key, options[key as keyof typeof defaults] ?? fallback]))) as typeof defaults;\n for (const [key, value] of Object.entries(config)) assertPositiveInteger(value, key);\n if (config.timeoutMs > 2_147_483_647 || config.maxBatchSize > 256 || config.maxRequestBytes > 16_777_216 || config.maxResponseBytes > 1_048_576) throw new Error();\n destination = endpoint(options.endpoint, allowInsecureLoopback); serviceName = stable(options.serviceName);\n serviceVersion = options.serviceVersion === undefined ? undefined : stable(options.serviceVersion);\n fixedHeaders = headers(options.headers); transport = options.fetch ?? globalThis.fetch;\n if (typeof transport !== 'function') throw new Error();\n } catch (error) {\n if (error instanceof MayuraError) throw error;\n throw new MayuraError('INVALID_CONFIG', 'OTLP exporter configuration must contain supported explicit bounds and transport.');\n }\n const metrics = Object.fromEntries(metricNames.map(key => [key, 0n])) as Record<Metric, bigint>;\n const count = (key: Metric, amount = 1): void => { metrics[key] += BigInt(amount); };\n let closed = false; let inFlight = false; let active: AbortController | undefined;\n const inspect = (): OtlpLogExporterSnapshot => Object.freeze({ state: closed ? 'closed' : 'active', inFlight,\n metrics: Object.freeze(Object.fromEntries(metricNames.map(key => [key, exact(metrics[key])]))) as unknown as OtlpLogExporterMetrics,\n });\n const sink = async (rawEvents: readonly RunEvent[], context: { readonly signal: AbortSignal }): Promise<void> => {\n if (closed) throw new MayuraError('CONFLICT', 'The telemetry exporter is closed.');\n if (inFlight) throw new MayuraError('CONFLICT', 'The telemetry exporter already has an active request.');\n if (!Array.isArray(rawEvents) || rawEvents.length === 0 || rawEvents.length > config.maxBatchSize || !(context.signal instanceof AbortSignal)) {\n if (Array.isArray(rawEvents)) count('recordsDropped', rawEvents.length);\n throw new MayuraError('INVALID_INPUT', 'Telemetry batches require admitted events, a signal and supported bounds.');\n }\n count('batchesAttempted'); count('recordsAttempted', rawEvents.length);\n let events: readonly RunEvent[]; let body: string;\n try {\n events = Object.freeze(rawEvents.map(value => snapshotRunEventMetadata(value)));\n body = JSON.stringify(jsonValue(request(events, serviceName, serviceVersion), { maxBytes: config.maxRequestBytes, maxDepth: 12, maxNodes: 32_768 }));\n const bytes = new TextEncoder().encode(body).byteLength;\n if (bytes > config.maxRequestBytes) throw new Error();\n count('requestBytes', bytes);\n } catch {\n count('recordsDropped', rawEvents.length); throw new MayuraError('INVALID_INPUT', 'Telemetry batches require admitted events within the configured request bound.');\n }\n const controller = new AbortController(); active = controller; inFlight = true; let timedOut = false;\n const timer = setTimeout(() => { timedOut = true; controller.abort(); }, config.timeoutMs);\n const relay = (): void => { controller.abort(); };\n context.signal.addEventListener('abort', relay, { once: true }); if (context.signal.aborted) relay();\n try {\n if (controller.signal.aborted) throw controller.signal.reason;\n const response = await abortable(Promise.resolve(transport(destination, {\n method: 'POST', headers: fixedHeaders, body, signal: controller.signal, redirect: 'error', credentials: 'omit', cache: 'no-store',\n })), controller.signal);\n const payload = await responsePayload(response, config.maxResponseBytes, controller.signal, bytes => count('responseBytes', bytes));\n const rejected = rejectedRecords(payload, events.length);\n count('recordsAccepted', events.length - rejected);\n if (rejected > 0) { count('recordsDropped', rejected); count('partialResponses'); }\n } catch {\n count('recordsDropped', events.length);\n if (timedOut) { count('timedOutRequests'); throw new MayuraError('TIMEOUT', 'The telemetry export timed out.'); }\n if (context.signal.aborted || closed) { count('cancelledRequests'); throw new MayuraError('CANCELLED', 'The telemetry export was cancelled.'); }\n count('failedRequests'); return failed();\n } finally {\n clearTimeout(timer); context.signal.removeEventListener('abort', relay); active = undefined; inFlight = false;\n }\n };\n const close = (): void => { if (!closed) { closed = true; active?.abort(); } };\n return Object.freeze({ sink, inspect, close });\n}\n"]}
1
+ {"version":3,"file":"otlp-http-json.js","sourceRoot":"","sources":["../src/otlp-http-json.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,SAAS,EAAE,WAAW,EAAkD,MAAM,cAAc,CAAC;AAC7H,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAGjE,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,EAAE,eAAe,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,EAAE,CAAC,CAAC;AAC9H,MAAM,UAAU,GAAG,qCAAqC,CAAC;AACzD,MAAM,UAAU,GAAG,sCAAsC,CAAC;AAC1D,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,mBAAmB,CAAC,CAAC,CAAC;AACtI,MAAM,WAAW,GAAG,CAAC,kBAAkB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,cAAc,EAAE,eAAe,CAAU,CAAC;AAG3N,MAAM,MAAM,GAAG,GAAU,EAAE,GAAG,MAAM,IAAI,WAAW,CAAC,aAAa,EAAE,oEAAoE,CAAC,CAAC,CAAC,CAAC,CAAC;AAC5I,SAAS,KAAK,CAAC,KAAa,IAAgB,OAAO,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,gBAAgB,C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BAAC,MAAM,IAAI,WAAW,CAAC,WAAW,EAAE,qCAAqC,CAAC,CAAC;YAAC,CAAC;YAChJ,KAAK,CAAC,gBAAgB,CAAC,CAAC;YAAC,OAAO,MAAM,EAAE,CAAC;QAC3C,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAC;YAAC,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YAAC,MAAM,GAAG,SAAS,CAAC;YAAC,QAAQ,GAAG,KAAK,CAAC;QAChH,CAAC;IACH,CAAC,CAAC;IACF,MAAM,KAAK,GAAG,GAAS,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAAC,MAAM,GAAG,IAAI,CAAC;QAAC,MAAM,EAAE,KAAK,EAAE,CAAC;IAAC,CAAC,CAAC,CAAC,CAAC;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import { assertPositiveInteger, jsonValue, MayuraError, type JsonObject, type JsonValue, type RunEvent } from '@mayura/core';\nimport { snapshotRunEventMetadata } from '@mayura/observability';\nimport type { ExactCount, OtlpHttpJsonLogExporter, OtlpHttpJsonLogExporterOptions, OtlpLogExporterMetrics, OtlpLogExporterSnapshot } from './contracts.js';\n\nconst defaults = Object.freeze({ timeoutMs: 5_000, maxBatchSize: 256, maxRequestBytes: 1_048_576, maxResponseBytes: 65_536 });\nconst headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;\nconst stableName = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;\nconst blockedHeaders = new Set(['connection', 'content-length', 'content-type', 'cookie', 'host', 'set-cookie', 'transfer-encoding']);\nconst metricNames = ['batchesAttempted', 'recordsAttempted', 'recordsAccepted', 'recordsDropped', 'partialResponses', 'failedRequests', 'timedOutRequests', 'cancelledRequests', 'requestBytes', 'responseBytes'] as const;\ntype Metric = typeof metricNames[number];\n\nconst failed = (): never => { throw new MayuraError('TOOL_FAILED', 'The telemetry export failed. Inspect authorized local diagnostics.'); };\nfunction exact(value: bigint): ExactCount { return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : value.toString(); }\nfunction object(value: JsonValue | undefined): JsonObject {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return failed();\n return value;\n}\nfunction stable(value: unknown): string {\n if (typeof value !== 'string' || !stableName.test(value)) throw new MayuraError('INVALID_CONFIG', 'Exporter names must be bounded stable identifiers.');\n return value;\n}\nfunction endpoint(value: unknown, allowInsecureLoopback: boolean): string {\n try {\n if (typeof value !== 'string' || value.length > 2_048) throw new Error();\n const url = new URL(value);\n const loopback = ['127.0.0.1', '[::1]'].includes(url.hostname);\n if ((url.protocol !== 'https:' && !(allowInsecureLoopback && url.protocol === 'http:' && loopback))\n || url.username || url.password || url.search || url.hash || !url.pathname.endsWith('/v1/logs')) throw new Error();\n return url.href;\n } catch { throw new MayuraError('INVALID_CONFIG', 'OTLP logs require an explicit HTTPS endpoint ending in /v1/logs.'); }\n}\nfunction headers(value: OtlpHttpJsonLogExporterOptions['headers']): Readonly<Record<string, string>> {\n try {\n if (value === undefined) return Object.freeze({ 'Content-Type': 'application/json' });\n const descriptors = Object.getOwnPropertyDescriptors(value);\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error();\n const result: Record<string, string> = { 'Content-Type': 'application/json' };\n const seen = new Set(['content-type']);\n if (Object.getOwnPropertySymbols(value).length > 0 || Object.keys(descriptors).length > 32) throw new Error();\n for (const [key, descriptor] of Object.entries(descriptors)) {\n const normalized = key.toLowerCase();\n if (!descriptor.enumerable || !('value' in descriptor) || !headerName.test(key) || blockedHeaders.has(normalized) || seen.has(normalized)\n || typeof descriptor.value !== 'string' || descriptor.value.length > 4_096 || /[\\r\\n\\0]/.test(descriptor.value)) throw new Error();\n seen.add(normalized);\n result[key] = descriptor.value;\n }\n return Object.freeze(result);\n } catch { throw new MayuraError('INVALID_CONFIG', 'Exporter headers must be bounded explicit HTTP fields.'); }\n}\n\nfunction anyValue(value: string | number | boolean): JsonObject {\n if (typeof value === 'string') return { stringValue: value };\n if (typeof value === 'boolean') return { boolValue: value };\n return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };\n}\nfunction attribute(key: string, value: string | number | boolean): JsonObject { return { key, value: anyValue(value) }; }\nfunction severity(event: RunEvent): readonly [number, string] {\n if (event.type === 'events.gap') return [13, 'WARN'];\n if (event.type !== 'run.completed' && event.type !== 'tool.completed' && event.type !== 'hook.completed' && event.type !== 'delegate.completed') return [9, 'INFO'];\n const status = event.metadata['status'];\n if (status === 'failed' || status === 'outcome_unknown') return [17, 'ERROR'];\n if (status === 'blocked' || status === 'cancelled') return [13, 'WARN'];\n return [9, 'INFO'];\n}\nfunction record(event: RunEvent): JsonObject {\n const [severityNumber, severityText] = severity(event);\n const attributes = [attribute('mayura.run.id', event.runId), attribute('mayura.event.sequence', event.sequence)];\n for (const [key, value] of Object.entries(event.metadata)) attributes.push(attribute(`mayura.${key}`, value));\n return {\n timeUnixNano: (BigInt(Date.parse(event.timestamp)) * 1_000_000n).toString(),\n severityNumber, severityText, body: { stringValue: event.type }, attributes,\n };\n}\nfunction request(events: readonly RunEvent[], serviceName: string, serviceVersion?: string): JsonObject {\n const attributes = [attribute('service.name', serviceName)];\n if (serviceVersion) attributes.push(attribute('service.version', serviceVersion));\n return { resourceLogs: [{ resource: { attributes }, scopeLogs: [{ scope: { name: '@mayura/observability', version: '1.0.0-rc.2' }, logRecords: events.map(record) }] }] };\n}\n\nasync function abortable<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) { void operation.catch(() => undefined); throw signal.reason; }\n let listener: (() => void) | undefined;\n try {\n return await Promise.race([operation, new Promise<never>((_, reject) => {\n listener = () => reject(signal.reason); signal.addEventListener('abort', listener, { once: true });\n if (signal.aborted) listener();\n })]);\n } finally { if (listener) signal.removeEventListener('abort', listener); }\n}\nasync function responsePayload(response: Response, limit: number, signal: AbortSignal, charge: (bytes: number) => void): Promise<JsonObject> {\n if (response.status !== 200 || response.redirected) { void response.body?.cancel().catch(() => undefined); return failed(); }\n if (!response.body) return {};\n const length = response.headers.get('content-length');\n if (length !== null && (!/^\\d+$/.test(length) || Number(length) > limit)) { void response.body.cancel().catch(() => undefined); return failed(); }\n const reader = response.body.getReader(); const chunks: Uint8Array[] = []; let size = 0;\n try {\n for (;;) {\n const item = await abortable(reader.read(), signal);\n if (item.done) break;\n size += item.value.byteLength; charge(item.value.byteLength);\n if (size > limit) return failed();\n chunks.push(item.value);\n }\n if (size === 0) return {};\n if (!/^application\\/json(?:\\s*;|$)/iu.test(response.headers.get('content-type') ?? '')) return failed();\n const bytes = new Uint8Array(size); let offset = 0;\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }\n return object(jsonValue(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)), { maxBytes: limit, maxDepth: 8, maxNodes: 1_024 }));\n } finally { void reader.cancel().catch(() => undefined); reader.releaseLock(); }\n}\nfunction rejectedRecords(payload: JsonObject, sent: number): number {\n const partial = payload['partialSuccess'];\n if (partial === undefined) return 0;\n const value = object(partial)['rejectedLogRecords'];\n if (value === undefined) return 0;\n const text = typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : value;\n if (typeof text !== 'string' || !/^\\d{1,20}$/.test(text)) return failed();\n const rejected = BigInt(text);\n if (rejected > BigInt(sent)) return failed();\n return Number(rejected);\n}\n\n/** Explicit OTLP/HTTP JSON log export with bounded metadata-only delivery and no retries. */\nexport function createOtlpHttpJsonLogExporter(options: OtlpHttpJsonLogExporterOptions): OtlpHttpJsonLogExporter {\n let config: typeof defaults; let destination: string; let serviceName: string; let serviceVersion: string | undefined;\n let transport: typeof globalThis.fetch; let fixedHeaders: Readonly<Record<string, string>>;\n try {\n const allowInsecureLoopback = options.allowInsecureLoopback ?? false;\n if (typeof allowInsecureLoopback !== 'boolean') throw new Error();\n config = Object.freeze(Object.fromEntries(Object.entries(defaults).map(([key, fallback]) => [key, options[key as keyof typeof defaults] ?? fallback]))) as typeof defaults;\n for (const [key, value] of Object.entries(config)) assertPositiveInteger(value, key);\n if (config.timeoutMs > 2_147_483_647 || config.maxBatchSize > 256 || config.maxRequestBytes > 16_777_216 || config.maxResponseBytes > 1_048_576) throw new Error();\n destination = endpoint(options.endpoint, allowInsecureLoopback); serviceName = stable(options.serviceName);\n serviceVersion = options.serviceVersion === undefined ? undefined : stable(options.serviceVersion);\n fixedHeaders = headers(options.headers); transport = options.fetch ?? globalThis.fetch;\n if (typeof transport !== 'function') throw new Error();\n } catch (error) {\n if (error instanceof MayuraError) throw error;\n throw new MayuraError('INVALID_CONFIG', 'OTLP exporter configuration must contain supported explicit bounds and transport.');\n }\n const metrics = Object.fromEntries(metricNames.map(key => [key, 0n])) as Record<Metric, bigint>;\n const count = (key: Metric, amount = 1): void => { metrics[key] += BigInt(amount); };\n let closed = false; let inFlight = false; let active: AbortController | undefined;\n const inspect = (): OtlpLogExporterSnapshot => Object.freeze({ state: closed ? 'closed' : 'active', inFlight,\n metrics: Object.freeze(Object.fromEntries(metricNames.map(key => [key, exact(metrics[key])]))) as unknown as OtlpLogExporterMetrics,\n });\n const sink = async (rawEvents: readonly RunEvent[], context: { readonly signal: AbortSignal }): Promise<void> => {\n if (closed) throw new MayuraError('CONFLICT', 'The telemetry exporter is closed.');\n if (inFlight) throw new MayuraError('CONFLICT', 'The telemetry exporter already has an active request.');\n if (!Array.isArray(rawEvents) || rawEvents.length === 0 || rawEvents.length > config.maxBatchSize || !(context.signal instanceof AbortSignal)) {\n if (Array.isArray(rawEvents)) count('recordsDropped', rawEvents.length);\n throw new MayuraError('INVALID_INPUT', 'Telemetry batches require admitted events, a signal and supported bounds.');\n }\n count('batchesAttempted'); count('recordsAttempted', rawEvents.length);\n let events: readonly RunEvent[]; let body: string;\n try {\n events = Object.freeze(rawEvents.map(value => snapshotRunEventMetadata(value)));\n body = JSON.stringify(jsonValue(request(events, serviceName, serviceVersion), { maxBytes: config.maxRequestBytes, maxDepth: 12, maxNodes: 32_768 }));\n const bytes = new TextEncoder().encode(body).byteLength;\n if (bytes > config.maxRequestBytes) throw new Error();\n count('requestBytes', bytes);\n } catch {\n count('recordsDropped', rawEvents.length); throw new MayuraError('INVALID_INPUT', 'Telemetry batches require admitted events within the configured request bound.');\n }\n const controller = new AbortController(); active = controller; inFlight = true; let timedOut = false;\n const timer = setTimeout(() => { timedOut = true; controller.abort(); }, config.timeoutMs);\n const relay = (): void => { controller.abort(); };\n context.signal.addEventListener('abort', relay, { once: true }); if (context.signal.aborted) relay();\n try {\n if (controller.signal.aborted) throw controller.signal.reason;\n const response = await abortable(Promise.resolve(transport(destination, {\n method: 'POST', headers: fixedHeaders, body, signal: controller.signal, redirect: 'error', credentials: 'omit', cache: 'no-store',\n })), controller.signal);\n const payload = await responsePayload(response, config.maxResponseBytes, controller.signal, bytes => count('responseBytes', bytes));\n const rejected = rejectedRecords(payload, events.length);\n count('recordsAccepted', events.length - rejected);\n if (rejected > 0) { count('recordsDropped', rejected); count('partialResponses'); }\n } catch {\n count('recordsDropped', events.length);\n if (timedOut) { count('timedOutRequests'); throw new MayuraError('TIMEOUT', 'The telemetry export timed out.'); }\n if (context.signal.aborted || closed) { count('cancelledRequests'); throw new MayuraError('CANCELLED', 'The telemetry export was cancelled.'); }\n count('failedRequests'); return failed();\n } finally {\n clearTimeout(timer); context.signal.removeEventListener('abort', relay); active = undefined; inFlight = false;\n }\n };\n const close = (): void => { if (!closed) { closed = true; active?.abort(); } };\n return Object.freeze({ sink, inspect, close });\n}\n"]}
@@ -127,7 +127,7 @@ function point(value) {
127
127
  }
128
128
  function resource(serviceName, serviceVersion) { return { attributes: attributes({ 'service.name': serviceName, 'service.version': serviceVersion }) }; }
129
129
  function traceRequest(records, serviceName, serviceVersion) {
130
- return { resourceSpans: [{ resource: resource(serviceName, serviceVersion), scopeSpans: [{ scope: { name: '@mayura/observability', version: '0.1.0-dev.0' }, spans: records.map(span) }] }] };
130
+ return { resourceSpans: [{ resource: resource(serviceName, serviceVersion), scopeSpans: [{ scope: { name: '@mayura/observability', version: '1.0.0-rc.2' }, spans: records.map(span) }] }] };
131
131
  }
132
132
  function metricRequest(records, serviceName, serviceVersion) {
133
133
  const grouped = new Map();
@@ -144,7 +144,7 @@ function metricRequest(records, serviceName, serviceVersion) {
144
144
  ...(first.kind === 'gauge' ? { gauge: { dataPoints: items.map(item => item.data) } }
145
145
  : { sum: { dataPoints: items.map(item => item.data), aggregationTemporality: 2, isMonotonic: first.monotonic } }) };
146
146
  });
147
- return { resourceMetrics: [{ resource: resource(serviceName, serviceVersion), scopeMetrics: [{ scope: { name: '@mayura/observability', version: '0.1.0-dev.0' }, metrics: encoded }] }] };
147
+ return { resourceMetrics: [{ resource: resource(serviceName, serviceVersion), scopeMetrics: [{ scope: { name: '@mayura/observability', version: '1.0.0-rc.2' }, metrics: encoded }] }] };
148
148
  }
149
149
  async function abortable(operation, signal) {
150
150
  if (signal.aborted) {