eve 0.6.0-beta.9 → 0.7.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 (650) hide show
  1. package/CHANGELOG.md +281 -0
  2. package/README.md +9 -6
  3. package/dist/docs/public/README.md +17 -12
  4. package/dist/docs/public/agent-config.md +10 -10
  5. package/dist/docs/public/channels/custom.mdx +4 -4
  6. package/dist/docs/public/channels/discord.mdx +1 -1
  7. package/dist/docs/public/channels/eve.mdx +10 -10
  8. package/dist/docs/public/channels/github.mdx +1 -1
  9. package/dist/docs/public/channels/overview.mdx +21 -15
  10. package/dist/docs/public/channels/slack.mdx +16 -4
  11. package/dist/docs/public/channels/teams.mdx +1 -1
  12. package/dist/docs/public/channels/telegram.mdx +1 -1
  13. package/dist/docs/public/channels/twilio.mdx +1 -1
  14. package/dist/docs/public/{advanced → concepts}/context-control.md +3 -3
  15. package/dist/docs/public/{advanced → concepts}/default-harness.md +5 -5
  16. package/dist/docs/public/{advanced → concepts}/execution-model-and-durability.md +3 -1
  17. package/dist/docs/public/concepts/meta.json +10 -0
  18. package/dist/docs/public/{advanced → concepts}/security-model.md +3 -3
  19. package/dist/docs/public/{advanced → concepts}/sessions-runs-and-streaming.md +7 -7
  20. package/dist/docs/public/connections.mdx +6 -4
  21. package/dist/docs/public/evals/assertions.mdx +108 -0
  22. package/dist/docs/public/evals/cases.mdx +143 -0
  23. package/dist/docs/public/evals/judge.mdx +94 -0
  24. package/dist/docs/public/evals/meta.json +4 -0
  25. package/dist/docs/public/evals/overview.mdx +118 -0
  26. package/dist/docs/public/evals/reporters.mdx +62 -0
  27. package/dist/docs/public/evals/running.mdx +63 -0
  28. package/dist/docs/public/evals/targets.mdx +54 -0
  29. package/dist/docs/public/getting-started.mdx +38 -33
  30. package/dist/docs/public/{advanced → guides}/auth-and-route-protection.md +5 -3
  31. package/dist/docs/public/{client → guides/client}/continuations.mdx +2 -2
  32. package/dist/docs/public/{client → guides/client}/messages.mdx +1 -1
  33. package/dist/docs/public/{client → guides/client}/meta.json +1 -1
  34. package/dist/docs/public/{client → guides/client}/output-schema.mdx +2 -2
  35. package/dist/docs/public/{client → guides/client}/overview.mdx +5 -5
  36. package/dist/docs/public/{client → guides/client}/streaming.mdx +1 -1
  37. package/dist/docs/public/{advanced → guides}/deployment.md +9 -1
  38. package/dist/docs/public/guides/dev-tui.md +50 -0
  39. package/dist/docs/public/{advanced → guides}/dynamic-capabilities.md +1 -1
  40. package/dist/docs/public/{advanced → guides}/dynamic-workflows.md +1 -1
  41. package/dist/docs/public/{frontend → guides/frontend}/nextjs.mdx +16 -7
  42. package/dist/docs/public/{frontend → guides/frontend}/nuxt.mdx +7 -7
  43. package/dist/docs/public/{frontend → guides/frontend}/overview.mdx +6 -6
  44. package/dist/docs/public/{frontend → guides/frontend}/sveltekit.mdx +5 -5
  45. package/dist/docs/public/{frontend → guides/frontend}/use-eve-agent-svelte.mdx +2 -2
  46. package/dist/docs/public/{frontend → guides/frontend}/use-eve-agent-vue.mdx +2 -2
  47. package/dist/docs/public/{advanced → guides}/hooks.md +2 -2
  48. package/dist/docs/public/{advanced → guides}/instrumentation.md +3 -1
  49. package/dist/docs/public/{advanced → guides}/meta.json +8 -12
  50. package/dist/docs/public/{advanced → guides}/session-context.md +3 -3
  51. package/dist/docs/public/{advanced → guides}/state.md +1 -1
  52. package/dist/docs/public/instructions.mdx +2 -2
  53. package/dist/docs/public/introduction.md +5 -2
  54. package/dist/docs/public/meta.json +4 -3
  55. package/dist/docs/public/reference/cli.md +35 -19
  56. package/dist/docs/public/reference/meta.json +1 -1
  57. package/dist/docs/public/reference/project-layout.md +5 -1
  58. package/dist/docs/public/reference/typescript-api.md +27 -23
  59. package/dist/docs/public/sandbox.mdx +1 -1
  60. package/dist/docs/public/schedules.mdx +2 -2
  61. package/dist/docs/public/skills.mdx +3 -3
  62. package/dist/docs/public/subagents.mdx +3 -3
  63. package/dist/docs/public/tools.mdx +4 -8
  64. package/dist/docs/public/tutorial/connect-a-warehouse.mdx +3 -3
  65. package/dist/docs/public/tutorial/first-agent.mdx +6 -3
  66. package/dist/docs/public/tutorial/guard-the-spend.mdx +1 -1
  67. package/dist/docs/public/tutorial/how-it-runs.mdx +2 -2
  68. package/dist/docs/public/tutorial/meta.json +1 -1
  69. package/dist/docs/public/tutorial/query-sample-data.mdx +1 -1
  70. package/dist/docs/public/tutorial/remember-definitions.mdx +3 -3
  71. package/dist/docs/public/tutorial/run-analysis.mdx +1 -1
  72. package/dist/docs/public/tutorial/ship-it.mdx +4 -4
  73. package/dist/docs/public/tutorial/team-playbooks.mdx +3 -3
  74. package/dist/src/chunks/{use-eve-agent-DCZbkLG7.js → use-eve-agent-DErQj5hs.js} +125 -37
  75. package/dist/src/chunks/{use-eve-agent-DoheC4_o.js → use-eve-agent-DoR8C4i6.js} +125 -37
  76. package/dist/src/cli/banner.d.ts +7 -0
  77. package/dist/src/cli/banner.js +1 -0
  78. package/dist/src/cli/commands/channel-add-conflicts.d.ts +1 -1
  79. package/dist/src/cli/commands/channels.d.ts +9 -6
  80. package/dist/src/cli/commands/channels.js +1 -1
  81. package/dist/src/cli/commands/deploy.d.ts +21 -0
  82. package/dist/src/cli/commands/deploy.js +1 -0
  83. package/dist/src/cli/commands/init-git.d.ts +15 -0
  84. package/dist/src/cli/commands/init-git.js +1 -0
  85. package/dist/src/cli/commands/init.d.ts +29 -0
  86. package/dist/src/cli/commands/init.js +1 -0
  87. package/dist/src/cli/commands/link.d.ts +21 -0
  88. package/dist/src/cli/commands/link.js +1 -0
  89. package/dist/src/cli/commands/preconditions.d.ts +7 -0
  90. package/dist/src/cli/commands/preconditions.js +1 -0
  91. package/dist/src/cli/commands/register-project-commands.d.ts +12 -0
  92. package/dist/src/cli/commands/register-project-commands.js +1 -0
  93. package/dist/src/cli/dev/tui/agent-header.d.ts +15 -9
  94. package/dist/src/cli/dev/tui/agent-header.js +1 -1
  95. package/dist/src/cli/dev/tui/blocks.d.ts +1 -1
  96. package/dist/src/cli/dev/tui/blocks.js +3 -2
  97. package/dist/src/cli/dev/tui/command-typeahead.d.ts +47 -0
  98. package/dist/src/cli/dev/tui/command-typeahead.js +1 -0
  99. package/dist/src/cli/dev/tui/dev-rebuild-status.d.ts +21 -0
  100. package/dist/src/cli/dev/tui/dev-rebuild-status.js +1 -0
  101. package/dist/src/cli/dev/tui/errors.d.ts +18 -0
  102. package/dist/src/cli/dev/tui/errors.js +1 -1
  103. package/dist/src/cli/dev/tui/prompt-command-handler.d.ts +14 -0
  104. package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -0
  105. package/dist/src/cli/dev/tui/prompt-commands.d.ts +54 -0
  106. package/dist/src/cli/dev/tui/prompt-commands.js +2 -0
  107. package/dist/src/cli/dev/tui/runner.d.ts +64 -7
  108. package/dist/src/cli/dev/tui/runner.js +1 -1
  109. package/dist/src/cli/dev/tui/setup-commands.d.ts +48 -0
  110. package/dist/src/cli/dev/tui/setup-commands.js +2 -0
  111. package/dist/src/cli/dev/tui/setup-flow.d.ts +35 -0
  112. package/dist/src/cli/dev/tui/setup-issues.d.ts +40 -0
  113. package/dist/src/cli/dev/tui/setup-issues.js +1 -0
  114. package/dist/src/cli/dev/tui/setup-panel.d.ts +103 -0
  115. package/dist/src/cli/dev/tui/setup-panel.js +1 -0
  116. package/dist/src/cli/dev/tui/status-line.d.ts +25 -0
  117. package/dist/src/cli/dev/tui/status-line.js +1 -0
  118. package/dist/src/cli/dev/tui/stream-format.d.ts +16 -1
  119. package/dist/src/cli/dev/tui/stream-format.js +1 -1
  120. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +32 -3
  121. package/dist/src/cli/dev/tui/terminal-renderer.js +5 -2
  122. package/dist/src/cli/dev/tui/test/index.d.ts +3 -1
  123. package/dist/src/cli/dev/tui/test/index.js +1 -1
  124. package/dist/src/cli/dev/tui/test/mock-terminal.d.ts +1 -0
  125. package/dist/src/cli/dev/tui/test/mock-terminal.js +1 -1
  126. package/dist/src/cli/dev/tui/theme.d.ts +10 -0
  127. package/dist/src/cli/dev/tui/theme.js +1 -1
  128. package/dist/src/cli/dev/tui/tui-prompter.d.ts +20 -0
  129. package/dist/src/cli/dev/tui/tui-prompter.js +1 -0
  130. package/dist/src/cli/dev/tui/tui.d.ts +6 -8
  131. package/dist/src/cli/dev/tui/tui.js +1 -1
  132. package/dist/src/cli/dev/tui/types.d.ts +4 -3
  133. package/dist/src/cli/dev/tui/vercel-status.d.ts +47 -0
  134. package/dist/src/cli/dev/tui/vercel-status.js +1 -0
  135. package/dist/src/cli/run.d.ts +9 -18
  136. package/dist/src/cli/run.js +2 -2
  137. package/dist/src/client/client.d.ts +8 -0
  138. package/dist/src/client/client.js +1 -1
  139. package/dist/src/client/file-parts.d.ts +18 -0
  140. package/dist/src/client/file-parts.js +1 -0
  141. package/dist/src/client/index.d.ts +3 -2
  142. package/dist/src/client/index.js +1 -1
  143. package/dist/src/client/message-response.js +1 -1
  144. package/dist/src/client/open-stream.d.ts +6 -0
  145. package/dist/src/client/open-stream.js +1 -1
  146. package/dist/src/client/session-utils.d.ts +5 -0
  147. package/dist/src/client/session-utils.js +1 -1
  148. package/dist/src/client/session.js +1 -1
  149. package/dist/src/client/types.d.ts +9 -2
  150. package/dist/src/compiled/.vendor-stamp.json +8 -8
  151. package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +56 -31
  152. package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
  153. package/dist/src/compiled/@ai-sdk/google/index.js +1 -1
  154. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  155. package/dist/src/compiled/@ai-sdk/openai/index.d.ts +16 -9
  156. package/dist/src/compiled/@ai-sdk/openai/index.js +2 -2
  157. package/dist/src/compiled/@ai-sdk/otel/index.js +2 -2
  158. package/dist/src/compiled/@vercel/sandbox/index.js +1 -1
  159. package/dist/src/compiled/@workflow/core/capabilities.d.ts +19 -1
  160. package/dist/src/compiled/@workflow/core/class-serialization.d.ts +32 -0
  161. package/dist/src/compiled/@workflow/core/create-hook.d.ts +37 -0
  162. package/dist/src/compiled/@workflow/core/global.d.ts +11 -1
  163. package/dist/src/compiled/@workflow/core/index.js +2 -2
  164. package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +4 -2
  165. package/dist/src/compiled/@workflow/core/runtime/start.d.ts +6 -0
  166. package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +15 -2
  167. package/dist/src/compiled/@workflow/core/runtime/wait-continuation.d.ts +84 -0
  168. package/dist/src/compiled/@workflow/core/runtime/wait-until.d.ts +18 -0
  169. package/dist/src/compiled/@workflow/core/runtime.d.ts +3 -1
  170. package/dist/src/compiled/@workflow/core/runtime.js +28 -28
  171. package/dist/src/compiled/@workflow/core/serialization/types.d.ts +21 -0
  172. package/dist/src/compiled/@workflow/core/serialization.d.ts +113 -6
  173. package/dist/src/compiled/@workflow/core/symbols.d.ts +2 -0
  174. package/dist/src/compiled/@workflow/core/util.d.ts +0 -5
  175. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  176. package/dist/src/compiled/@workflow/core/workflow/attribute-dispatcher.d.ts +6 -0
  177. package/dist/src/compiled/@workflow/core/workflow/set-attributes.d.ts +3 -4
  178. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  179. package/dist/src/compiled/@workflow/world/events.d.ts +48 -0
  180. package/dist/src/compiled/@workflow/world/index.d.ts +3 -3
  181. package/dist/src/compiled/@workflow/world/queue.d.ts +31 -2
  182. package/dist/src/compiled/@workflow/world/runs.d.ts +2 -0
  183. package/dist/src/compiled/@workflow/world/spec-version.d.ts +2 -1
  184. package/dist/src/compiled/_chunks/workflow/attribute-changes-DGVGRGfw.js +59 -0
  185. package/dist/src/compiled/_chunks/workflow/{dist-gEXVSMPU.js → dist-CkMRLaRV.js} +1 -1
  186. package/dist/src/compiled/_chunks/workflow/functions-DuPjIvMH.js +1 -0
  187. package/dist/src/compiled/_chunks/workflow/resume-hook-DMSadN9o.js +1 -0
  188. package/dist/src/compiled/_chunks/workflow/run-BRdn7zy_.js +1 -0
  189. package/dist/src/compiled/_chunks/workflow/sleep-CpXfoXLF.js +1 -0
  190. package/dist/src/compiled/just-bash/index.d.ts +4 -4
  191. package/dist/src/compiler/artifacts.js +1 -1
  192. package/dist/src/compiler/manifest.d.ts +8 -8
  193. package/dist/src/compiler/normalize-agent-config.js +1 -1
  194. package/dist/src/compiler/normalize-channel.d.ts +2 -1
  195. package/dist/src/compiler/normalize-channel.js +1 -1
  196. package/dist/src/compiler/normalize-connection.d.ts +2 -1
  197. package/dist/src/compiler/normalize-connection.js +1 -1
  198. package/dist/src/compiler/normalize-helpers.d.ts +5 -0
  199. package/dist/src/compiler/normalize-helpers.js +1 -1
  200. package/dist/src/compiler/normalize-instructions.d.ts +3 -2
  201. package/dist/src/compiler/normalize-instructions.js +1 -1
  202. package/dist/src/compiler/normalize-manifest.js +2 -2
  203. package/dist/src/compiler/normalize-sandbox.d.ts +2 -1
  204. package/dist/src/compiler/normalize-sandbox.js +1 -1
  205. package/dist/src/compiler/normalize-schedule.d.ts +2 -1
  206. package/dist/src/compiler/normalize-schedule.js +1 -1
  207. package/dist/src/compiler/normalize-skill.d.ts +2 -1
  208. package/dist/src/compiler/normalize-skill.js +1 -1
  209. package/dist/src/compiler/normalize-subagent.d.ts +4 -1
  210. package/dist/src/compiler/normalize-subagent.js +1 -1
  211. package/dist/src/compiler/normalize-tool.d.ts +2 -1
  212. package/dist/src/compiler/normalize-tool.js +1 -1
  213. package/dist/src/compiler/workspace-resources.js +1 -1
  214. package/dist/src/context/node.d.ts +1 -1
  215. package/dist/src/evals/assertions/collector.d.ts +43 -0
  216. package/dist/src/evals/assertions/collector.js +1 -0
  217. package/dist/src/evals/assertions/run.d.ts +72 -0
  218. package/dist/src/evals/assertions/run.js +2 -0
  219. package/dist/src/evals/autoevals-client.js +2 -0
  220. package/dist/src/evals/cli/eval-client.d.ts +22 -0
  221. package/dist/src/evals/cli/eval-client.js +1 -0
  222. package/dist/src/evals/cli/eval.d.ts +8 -5
  223. package/dist/src/evals/cli/eval.js +1 -1
  224. package/dist/src/evals/context.d.ts +19 -0
  225. package/dist/src/evals/context.js +1 -0
  226. package/dist/src/evals/define-eval-config.d.ts +16 -0
  227. package/dist/src/evals/define-eval-config.js +1 -0
  228. package/dist/src/evals/define-eval.d.ts +20 -0
  229. package/dist/src/evals/define-eval.js +1 -0
  230. package/dist/src/evals/expect/index.d.ts +25 -0
  231. package/dist/src/evals/expect/index.js +1 -0
  232. package/dist/src/evals/index.d.ts +6 -2
  233. package/dist/src/evals/index.js +1 -1
  234. package/dist/src/evals/judge.d.ts +20 -0
  235. package/dist/src/evals/judge.js +1 -0
  236. package/dist/src/evals/{checks/match.d.ts → match.d.ts} +17 -18
  237. package/dist/src/evals/match.js +1 -0
  238. package/dist/src/evals/reporters/index.d.ts +1 -0
  239. package/dist/src/evals/reporters/index.js +1 -1
  240. package/dist/src/evals/requirements.d.ts +3 -0
  241. package/dist/src/evals/requirements.js +1 -0
  242. package/dist/src/evals/runner/artifacts.d.ts +7 -6
  243. package/dist/src/evals/runner/artifacts.js +3 -3
  244. package/dist/src/evals/runner/discover.d.ts +31 -10
  245. package/dist/src/evals/runner/discover.js +1 -1
  246. package/dist/src/evals/runner/execute-eval.d.ts +25 -0
  247. package/dist/src/evals/runner/execute-eval.js +1 -0
  248. package/dist/src/evals/runner/execute-task.d.ts +31 -0
  249. package/dist/src/evals/runner/execute-task.js +1 -0
  250. package/dist/src/evals/runner/reporters/braintrust.d.ts +7 -5
  251. package/dist/src/evals/runner/reporters/braintrust.js +2 -2
  252. package/dist/src/evals/runner/reporters/console.d.ts +4 -4
  253. package/dist/src/evals/runner/reporters/console.js +1 -1
  254. package/dist/src/evals/runner/reporters/junit.d.ts +10 -0
  255. package/dist/src/evals/runner/reporters/junit.js +4 -0
  256. package/dist/src/evals/runner/reporters/types.d.ts +14 -8
  257. package/dist/src/evals/runner/run-evals.d.ts +38 -0
  258. package/dist/src/evals/runner/run-evals.js +1 -0
  259. package/dist/src/evals/runner/verdict.d.ts +10 -15
  260. package/dist/src/evals/runner/verdict.js +1 -1
  261. package/dist/src/evals/session.d.ts +52 -0
  262. package/dist/src/evals/session.js +1 -0
  263. package/dist/src/evals/target.d.ts +23 -0
  264. package/dist/src/evals/target.js +1 -0
  265. package/dist/src/evals/types.d.ts +294 -219
  266. package/dist/src/execution/compaction.d.ts +14 -0
  267. package/dist/src/execution/compaction.js +1 -0
  268. package/dist/src/execution/delegated-parent-notification.js +1 -1
  269. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  270. package/dist/src/execution/node-step.js +1 -1
  271. package/dist/src/execution/sandbox/bash-tool.d.ts +6 -6
  272. package/dist/src/execution/sandbox/bash-tool.js +1 -1
  273. package/dist/src/execution/sandbox/bindings/local.js +1 -1
  274. package/dist/src/execution/sandbox/bindings/vercel.d.ts +2 -6
  275. package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
  276. package/dist/src/execution/sandbox/glob-tool.js +3 -3
  277. package/dist/src/execution/sandbox/grep-tool.js +3 -3
  278. package/dist/src/execution/sandbox/read-file-tool.js +1 -1
  279. package/dist/src/execution/subagent-adapter.js +1 -1
  280. package/dist/src/execution/tool-auth.js +1 -1
  281. package/dist/src/execution/turn-workflow.js +1 -1
  282. package/dist/src/execution/workflow-runtime.d.ts +2 -2
  283. package/dist/src/execution/workflow-runtime.js +1 -1
  284. package/dist/src/execution/workflow-steps.js +1 -1
  285. package/dist/src/harness/action-result-helpers.js +1 -1
  286. package/dist/src/harness/authorization.d.ts +26 -0
  287. package/dist/src/harness/authorization.js +1 -1
  288. package/dist/src/harness/code-mode-lifecycle.js +1 -1
  289. package/dist/src/harness/emission.d.ts +12 -5
  290. package/dist/src/harness/emission.js +1 -1
  291. package/dist/src/harness/model-call-error.d.ts +35 -6
  292. package/dist/src/harness/model-call-error.js +1 -1
  293. package/dist/src/harness/step-hooks.d.ts +10 -4
  294. package/dist/src/harness/step-hooks.js +1 -1
  295. package/dist/src/harness/tool-loop.js +1 -1
  296. package/dist/src/harness/tools.d.ts +4 -6
  297. package/dist/src/harness/tools.js +1 -1
  298. package/dist/src/harness/turn-tag-state.d.ts +4 -0
  299. package/dist/src/harness/turn-tag-state.js +1 -1
  300. package/dist/src/harness/types.d.ts +4 -15
  301. package/dist/src/internal/application/cache-metadata.js +1 -1
  302. package/dist/src/internal/application/compiled-artifacts.js +1 -1
  303. package/dist/src/internal/application/package.js +1 -1
  304. package/dist/src/internal/application/paths.js +1 -1
  305. package/dist/src/internal/authored-definition/schema-backed.js +1 -1
  306. package/dist/src/internal/authored-module-loader.d.ts +4 -1
  307. package/dist/src/internal/authored-module-loader.js +2 -2
  308. package/dist/src/internal/authored-module-map-loader.js +1 -1
  309. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  310. package/dist/src/internal/nitro/host/build-application.js +1 -1
  311. package/dist/src/internal/nitro/host/build-vercel-agent-summary.js +1 -1
  312. package/dist/src/internal/nitro/host/configure-nitro-routes.js +3 -3
  313. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  314. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  315. package/dist/src/internal/nitro/host/dev-watcher-log.d.ts +37 -0
  316. package/dist/src/internal/nitro/host/dev-watcher-log.js +1 -0
  317. package/dist/src/internal/nitro/host/ports.d.ts +8 -0
  318. package/dist/src/internal/nitro/host/ports.js +1 -0
  319. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  320. package/dist/src/internal/nitro/host/server-external-packages.d.ts +1 -1
  321. package/dist/src/internal/nitro/host/server-external-packages.js +1 -1
  322. package/dist/src/internal/nitro/host/start-development-server.js +1 -1
  323. package/dist/src/internal/nitro/host/start-production-server.js +1 -1
  324. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.d.ts +5 -0
  325. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js +1 -0
  326. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +31 -2
  327. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  328. package/dist/src/internal/nitro/routes/agent-info/load-agent-info-data.d.ts +13 -0
  329. package/dist/src/internal/nitro/routes/agent-info/load-agent-info-data.js +1 -1
  330. package/dist/src/internal/nitro/routes/info.d.ts +2 -2
  331. package/dist/src/internal/nitro/routes/info.js +1 -1
  332. package/dist/src/internal/workflow/queue-namespace.d.ts +5 -0
  333. package/dist/src/internal/workflow/queue-namespace.js +1 -0
  334. package/dist/src/internal/workflow-bundle/builder-support.js +2 -2
  335. package/dist/src/internal/workflow-bundle/builder.js +3 -5
  336. package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
  337. package/dist/src/internal/workflow-bundle/workflow-builders.d.ts +1 -1
  338. package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
  339. package/dist/src/node_modules/.pnpm/@clack_core@1.3.1/node_modules/@clack/core/dist/index.js +4 -4
  340. package/dist/src/protocol/message.d.ts +15 -0
  341. package/dist/src/protocol/message.js +2 -2
  342. package/dist/src/public/channels/slack/api.d.ts +8 -0
  343. package/dist/src/public/channels/slack/api.js +1 -1
  344. package/dist/src/public/channels/slack/connections.d.ts +26 -18
  345. package/dist/src/public/channels/slack/connections.js +1 -1
  346. package/dist/src/public/channels/slack/defaults.d.ts +5 -2
  347. package/dist/src/public/channels/slack/defaults.js +1 -1
  348. package/dist/src/public/channels/slack/index.d.ts +1 -1
  349. package/dist/src/public/channels/slack/slackChannel.d.ts +65 -5
  350. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  351. package/dist/src/public/channels/teams/defaults.js +1 -1
  352. package/dist/src/public/connections/errors.d.ts +8 -0
  353. package/dist/src/public/definitions/tool.d.ts +0 -33
  354. package/dist/src/public/next/index.d.ts +7 -1
  355. package/dist/src/public/next/index.js +1 -1
  356. package/dist/src/public/next/server.d.ts +1 -0
  357. package/dist/src/public/next/server.js +1 -1
  358. package/dist/src/public/nuxt/dev-server.js +1 -1
  359. package/dist/src/public/sveltekit/dev-server.js +1 -1
  360. package/dist/src/public/sveltekit/index.d.ts +1 -1
  361. package/dist/src/public/tools/defaults.d.ts +2 -4
  362. package/dist/src/public/tools/defaults.js +1 -1
  363. package/dist/src/public/tools/define-bash-tool.d.ts +3 -3
  364. package/dist/src/public/tools/define-bash-tool.js +1 -1
  365. package/dist/src/public/tools/define-read-file-tool.d.ts +0 -6
  366. package/dist/src/public/tools/define-read-file-tool.js +1 -1
  367. package/dist/src/public/tools/index.d.ts +2 -2
  368. package/dist/src/public/tools/index.js +1 -1
  369. package/dist/src/public/tools/internal.js +1 -1
  370. package/dist/src/runtime/actions/types.d.ts +11 -11
  371. package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
  372. package/dist/src/runtime/agent/mock-model-fixtures.js +3 -2
  373. package/dist/src/runtime/agent/mock-model-skill-selection.js +3 -4
  374. package/dist/src/runtime/connections/callback-route.js +1 -1
  375. package/dist/src/runtime/connections/mcp-client.js +1 -1
  376. package/dist/src/runtime/connections/scoped-authorization.d.ts +21 -5
  377. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  378. package/dist/src/runtime/connections/types.d.ts +33 -0
  379. package/dist/src/runtime/connections/validate-authorization.js +1 -1
  380. package/dist/src/runtime/framework-tools/bash.d.ts +3 -3
  381. package/dist/src/runtime/framework-tools/bash.js +1 -1
  382. package/dist/src/runtime/framework-tools/connection-search-dynamic.d.ts +1 -1
  383. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +1 -1
  384. package/dist/src/runtime/framework-tools/file-state.d.ts +3 -3
  385. package/dist/src/runtime/framework-tools/index.js +1 -1
  386. package/dist/src/runtime/framework-tools/read-file.js +2 -2
  387. package/dist/src/runtime/framework-tools/todo.d.ts +7 -0
  388. package/dist/src/runtime/framework-tools/todo.js +2 -2
  389. package/dist/src/runtime/governance/auth/http-basic.js +1 -1
  390. package/dist/src/runtime/input/types.d.ts +1 -1
  391. package/dist/src/runtime/resolve-tool.d.ts +2 -2
  392. package/dist/src/runtime/resolve-tool.js +1 -1
  393. package/dist/src/runtime/sandbox/keys.js +1 -1
  394. package/dist/src/runtime/session-callback-route.js +1 -1
  395. package/dist/src/runtime/types.d.ts +1 -7
  396. package/dist/src/services/dev-client/client-options.d.ts +8 -0
  397. package/dist/src/services/dev-client/client-options.js +1 -0
  398. package/dist/src/services/dev-client/runtime-artifacts.d.ts +13 -0
  399. package/dist/src/services/dev-client/runtime-artifacts.js +1 -0
  400. package/dist/src/services/dev-client.d.ts +13 -46
  401. package/dist/src/services/dev-client.js +1 -1
  402. package/dist/src/setup/ask.d.ts +205 -0
  403. package/dist/src/setup/ask.js +1 -0
  404. package/dist/src/setup/boxes/add-channels.d.ts +100 -16
  405. package/dist/src/setup/boxes/add-channels.js +2 -1
  406. package/dist/src/setup/boxes/add-connections.d.ts +13 -23
  407. package/dist/src/setup/boxes/add-connections.js +1 -1
  408. package/dist/src/setup/boxes/apply-ai-gateway-credential.d.ts +2 -2
  409. package/dist/src/setup/boxes/apply-ai-gateway-credential.js +1 -1
  410. package/dist/src/setup/boxes/deploy-project.d.ts +46 -14
  411. package/dist/src/setup/boxes/deploy-project.js +1 -1
  412. package/dist/src/setup/boxes/detect-ai-gateway.d.ts +10 -3
  413. package/dist/src/setup/boxes/detect-ai-gateway.js +1 -1
  414. package/dist/src/setup/boxes/link-project.d.ts +3 -3
  415. package/dist/src/setup/boxes/link-project.js +1 -1
  416. package/dist/src/setup/boxes/one-shot-next-steps.d.ts +18 -0
  417. package/dist/src/setup/boxes/one-shot-next-steps.js +2 -0
  418. package/dist/src/setup/boxes/preflight.d.ts +14 -6
  419. package/dist/src/setup/boxes/preflight.js +1 -1
  420. package/dist/src/setup/boxes/resolve-provisioning.d.ts +36 -8
  421. package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
  422. package/dist/src/setup/boxes/resolve-target.d.ts +25 -8
  423. package/dist/src/setup/boxes/resolve-target.js +1 -1
  424. package/dist/src/setup/boxes/scaffold.d.ts +12 -6
  425. package/dist/src/setup/boxes/scaffold.js +1 -1
  426. package/dist/src/setup/boxes/select-channels.d.ts +38 -9
  427. package/dist/src/setup/boxes/select-channels.js +1 -1
  428. package/dist/src/setup/boxes/select-chat.d.ts +15 -11
  429. package/dist/src/setup/boxes/select-chat.js +1 -1
  430. package/dist/src/setup/boxes/select-connections.d.ts +30 -0
  431. package/dist/src/setup/boxes/select-connections.js +1 -0
  432. package/dist/src/setup/boxes/select-model.d.ts +18 -14
  433. package/dist/src/setup/boxes/select-model.js +1 -1
  434. package/dist/src/setup/boxes/select-setup-mode.d.ts +32 -0
  435. package/dist/src/setup/boxes/select-setup-mode.js +1 -0
  436. package/dist/src/setup/channel-add-conflicts.d.ts +28 -0
  437. package/dist/src/setup/channel-add-conflicts.js +1 -0
  438. package/dist/src/setup/cli/channel-setup-prompter.d.ts +23 -0
  439. package/dist/src/setup/cli/channel-setup-prompter.js +1 -0
  440. package/dist/src/setup/cli/connection-add-prompter.d.ts +8 -0
  441. package/dist/src/setup/cli/connection-add-prompter.js +1 -0
  442. package/dist/src/setup/{scaffold/cli → cli}/index.d.ts +4 -3
  443. package/dist/src/setup/cli/index.js +1 -0
  444. package/dist/src/setup/{scaffold/cli → cli}/prompt-ui.d.ts +39 -15
  445. package/dist/src/setup/cli/prompt-ui.js +5 -0
  446. package/dist/src/setup/{scaffold/cli → cli}/rail-log.d.ts +2 -0
  447. package/dist/src/setup/{scaffold/cli → cli}/rail-log.js +2 -2
  448. package/dist/src/setup/{scaffold/cli → cli}/select-component.d.ts +18 -3
  449. package/dist/src/setup/cli/select-component.js +1 -0
  450. package/dist/src/setup/cli/select-option-codec.d.ts +12 -0
  451. package/dist/src/setup/cli/select-option-codec.js +1 -0
  452. package/dist/src/setup/{scaffold/cli → cli}/select-state.d.ts +13 -1
  453. package/dist/src/setup/cli/select-state.js +1 -0
  454. package/dist/src/setup/cli/whimsy.d.ts +16 -0
  455. package/dist/src/setup/cli/whimsy.js +1 -0
  456. package/dist/src/setup/{scaffold/steps/setup-connection.d.ts → connection-connector.d.ts} +3 -2
  457. package/dist/src/setup/connection-connector.js +1 -0
  458. package/dist/src/setup/flows/channels.d.ts +43 -0
  459. package/dist/src/setup/flows/channels.js +1 -0
  460. package/dist/src/setup/flows/deploy.d.ts +40 -0
  461. package/dist/src/setup/flows/deploy.js +1 -0
  462. package/dist/src/setup/flows/in-project.d.ts +16 -0
  463. package/dist/src/setup/flows/in-project.js +1 -0
  464. package/dist/src/setup/flows/link.d.ts +43 -0
  465. package/dist/src/setup/flows/link.js +1 -0
  466. package/dist/src/setup/flows/model.d.ts +112 -0
  467. package/dist/src/setup/flows/model.js +1 -0
  468. package/dist/src/setup/flows/vercel.d.ts +31 -0
  469. package/dist/src/setup/flows/vercel.js +2 -0
  470. package/dist/src/setup/gateway-models.js +1 -1
  471. package/dist/src/setup/headless.d.ts +1 -1
  472. package/dist/src/setup/index.d.ts +10 -4
  473. package/dist/src/setup/index.js +1 -1
  474. package/dist/src/setup/onboarding.d.ts +7 -4
  475. package/dist/src/setup/onboarding.js +1 -1
  476. package/dist/src/setup/package-manager.d.ts +27 -0
  477. package/dist/src/setup/package-manager.js +1 -0
  478. package/dist/src/setup/primitives/index.d.ts +3 -0
  479. package/dist/src/setup/primitives/index.js +1 -0
  480. package/dist/src/setup/primitives/pm/bun.d.ts +10 -0
  481. package/dist/src/setup/primitives/pm/bun.js +1 -0
  482. package/dist/src/setup/primitives/pm/index.d.ts +11 -0
  483. package/dist/src/setup/primitives/pm/index.js +1 -0
  484. package/dist/src/setup/primitives/pm/npm.d.ts +10 -0
  485. package/dist/src/setup/primitives/pm/npm.js +1 -0
  486. package/dist/src/setup/primitives/pm/pnpm.d.ts +27 -0
  487. package/dist/src/setup/primitives/pm/pnpm.js +8 -0
  488. package/dist/src/setup/primitives/pm/run.d.ts +23 -0
  489. package/dist/src/setup/primitives/pm/run.js +1 -0
  490. package/dist/src/setup/primitives/pm/shared.d.ts +8 -0
  491. package/dist/src/setup/primitives/pm/shared.js +1 -0
  492. package/dist/src/setup/primitives/pm/types.d.ts +37 -0
  493. package/dist/src/setup/primitives/pm/types.js +1 -0
  494. package/dist/src/setup/primitives/pm/yarn.d.ts +10 -0
  495. package/dist/src/setup/primitives/pm/yarn.js +1 -0
  496. package/dist/src/setup/primitives/run-pnpm.d.ts +1 -0
  497. package/dist/src/setup/primitives/run-pnpm.js +1 -0
  498. package/dist/src/setup/{scaffold/primitives → primitives}/run-vercel.d.ts +7 -0
  499. package/dist/src/setup/primitives/run-vercel.js +1 -0
  500. package/dist/src/setup/project-name.d.ts +4 -0
  501. package/dist/src/setup/project-name.js +1 -0
  502. package/dist/src/setup/project-resolution.d.ts +54 -0
  503. package/dist/src/setup/project-resolution.js +1 -0
  504. package/dist/src/setup/prompter.d.ts +52 -4
  505. package/dist/src/setup/prompter.js +1 -1
  506. package/dist/src/setup/quit-guard.d.ts +1 -1
  507. package/dist/src/setup/run-vercel-link.d.ts +1 -1
  508. package/dist/src/setup/run-vercel-link.js +1 -1
  509. package/dist/src/setup/runner.d.ts +5 -4
  510. package/dist/src/setup/runner.js +1 -1
  511. package/dist/src/setup/scaffold/channels-catalog.d.ts +3 -3
  512. package/dist/src/setup/scaffold/channels-catalog.js +1 -1
  513. package/dist/src/setup/scaffold/create/add-to-project.d.ts +26 -0
  514. package/dist/src/setup/scaffold/create/add-to-project.js +1 -0
  515. package/dist/src/setup/scaffold/create/project.d.ts +54 -0
  516. package/dist/src/setup/scaffold/create/project.js +80 -0
  517. package/dist/src/setup/scaffold/index.d.ts +4 -4
  518. package/dist/src/setup/scaffold/index.js +1 -1
  519. package/dist/src/setup/scaffold/{channels.d.ts → update/channels.d.ts} +11 -0
  520. package/dist/src/setup/scaffold/update/channels.js +7 -0
  521. package/dist/src/setup/scaffold/{connections.d.ts → update/connections.d.ts} +1 -1
  522. package/dist/src/setup/scaffold/update/connections.js +21 -0
  523. package/dist/src/setup/scaffold/version-tokens.d.ts +11 -0
  524. package/dist/src/setup/scaffold/version-tokens.js +1 -0
  525. package/dist/src/setup/{scaffold/steps/setup-slackbot.d.ts → slackbot.d.ts} +24 -20
  526. package/dist/src/setup/slackbot.js +1 -0
  527. package/dist/src/setup/state.d.ts +62 -15
  528. package/dist/src/setup/state.js +1 -1
  529. package/dist/src/setup/step.d.ts +9 -18
  530. package/dist/src/setup/vercel-project.d.ts +15 -8
  531. package/dist/src/setup/vercel-project.js +1 -1
  532. package/dist/src/shared/agent-definition.d.ts +5 -3
  533. package/dist/src/shared/default-agent-model.d.ts +5 -0
  534. package/dist/src/shared/default-agent-model.js +1 -0
  535. package/dist/src/source-change/apply-model-name.d.ts +25 -0
  536. package/dist/src/source-change/apply-model-name.js +2 -0
  537. package/dist/src/source-change/static-source-change.d.ts +36 -0
  538. package/dist/src/source-change/static-source-change.js +1 -0
  539. package/dist/src/svelte/index.js +1 -1
  540. package/dist/src/svelte/use-eve-agent.js +1 -1
  541. package/dist/src/vue/index.js +1 -1
  542. package/dist/src/vue/use-eve-agent.js +1 -1
  543. package/package.json +22 -42
  544. package/dist/docs/evals-v2-plan.md +0 -939
  545. package/dist/docs/public/advanced/dev-tui.md +0 -52
  546. package/dist/docs/public/advanced/evals.md +0 -158
  547. package/dist/docs/public/reference/faqs.md +0 -48
  548. package/dist/src/cli/commands/setup.d.ts +0 -55
  549. package/dist/src/cli/commands/setup.js +0 -1
  550. package/dist/src/cli/dev/repl/input-requests.d.ts +0 -38
  551. package/dist/src/cli/dev/repl/input-requests.js +0 -1
  552. package/dist/src/cli/dev/repl/input.d.ts +0 -19
  553. package/dist/src/cli/dev/repl/input.js +0 -1
  554. package/dist/src/cli/dev/repl/repl.d.ts +0 -62
  555. package/dist/src/cli/dev/repl/repl.js +0 -2
  556. package/dist/src/cli/dev/repl/terminal.d.ts +0 -21
  557. package/dist/src/cli/dev/repl/terminal.js +0 -5
  558. package/dist/src/compiled/_chunks/workflow/resume-hook-0Zk0zSvq.js +0 -12
  559. package/dist/src/compiled/_chunks/workflow/sleep-DXZr2BgM.js +0 -1
  560. package/dist/src/compiled/_chunks/workflow/symbols-BWCAoPHE.js +0 -48
  561. package/dist/src/evals/checks/checks.d.ts +0 -66
  562. package/dist/src/evals/checks/checks.js +0 -2
  563. package/dist/src/evals/checks/index.d.ts +0 -21
  564. package/dist/src/evals/checks/index.js +0 -1
  565. package/dist/src/evals/checks/match.js +0 -1
  566. package/dist/src/evals/define-eval-suite.d.ts +0 -18
  567. package/dist/src/evals/define-eval-suite.js +0 -1
  568. package/dist/src/evals/runner/execute-case.d.ts +0 -23
  569. package/dist/src/evals/runner/execute-case.js +0 -1
  570. package/dist/src/evals/runner/execute-suite.d.ts +0 -24
  571. package/dist/src/evals/runner/execute-suite.js +0 -1
  572. package/dist/src/evals/scorers/autoevals-client.js +0 -2
  573. package/dist/src/evals/scorers/autoevals.d.ts +0 -58
  574. package/dist/src/evals/scorers/autoevals.js +0 -1
  575. package/dist/src/evals/scorers/json.d.ts +0 -10
  576. package/dist/src/evals/scorers/json.js +0 -1
  577. package/dist/src/evals/scorers/model-marker.d.ts +0 -12
  578. package/dist/src/evals/scorers/model-marker.js +0 -1
  579. package/dist/src/evals/scorers/run.d.ts +0 -24
  580. package/dist/src/evals/scorers/run.js +0 -1
  581. package/dist/src/evals/scorers/sql.d.ts +0 -9
  582. package/dist/src/evals/scorers/sql.js +0 -1
  583. package/dist/src/evals/scorers/text.d.ts +0 -18
  584. package/dist/src/evals/scorers/text.js +0 -1
  585. package/dist/src/evals/scores/index.d.ts +0 -72
  586. package/dist/src/evals/scores/index.js +0 -1
  587. package/dist/src/execution/tool-compaction.d.ts +0 -9
  588. package/dist/src/execution/tool-compaction.js +0 -1
  589. package/dist/src/services/dev-client/stream.d.ts +0 -5
  590. package/dist/src/services/dev-client/stream.js +0 -1
  591. package/dist/src/services/dev-client/url.d.ts +0 -11
  592. package/dist/src/services/dev-client/url.js +0 -1
  593. package/dist/src/setup/channel-setup-prompter.d.ts +0 -8
  594. package/dist/src/setup/channel-setup-prompter.js +0 -1
  595. package/dist/src/setup/scaffold/channels.js +0 -7
  596. package/dist/src/setup/scaffold/cli/channel-add-prompter.d.ts +0 -12
  597. package/dist/src/setup/scaffold/cli/channel-add-prompter.js +0 -1
  598. package/dist/src/setup/scaffold/cli/channel-setup-prompter.d.ts +0 -56
  599. package/dist/src/setup/scaffold/cli/connection-add-prompter.d.ts +0 -44
  600. package/dist/src/setup/scaffold/cli/connection-add-prompter.js +0 -1
  601. package/dist/src/setup/scaffold/cli/index.js +0 -1
  602. package/dist/src/setup/scaffold/cli/prompt-ui.js +0 -5
  603. package/dist/src/setup/scaffold/cli/select-component.js +0 -1
  604. package/dist/src/setup/scaffold/cli/select-state.js +0 -1
  605. package/dist/src/setup/scaffold/connections.js +0 -21
  606. package/dist/src/setup/scaffold/pnpm-workspace.d.ts +0 -3
  607. package/dist/src/setup/scaffold/pnpm-workspace.js +0 -11
  608. package/dist/src/setup/scaffold/primitives/detect-deployment.d.ts +0 -13
  609. package/dist/src/setup/scaffold/primitives/detect-deployment.js +0 -1
  610. package/dist/src/setup/scaffold/primitives/index.d.ts +0 -3
  611. package/dist/src/setup/scaffold/primitives/index.js +0 -1
  612. package/dist/src/setup/scaffold/primitives/pnpm-invocation.d.ts +0 -12
  613. package/dist/src/setup/scaffold/primitives/pnpm-invocation.js +0 -1
  614. package/dist/src/setup/scaffold/primitives/run-pnpm.d.ts +0 -17
  615. package/dist/src/setup/scaffold/primitives/run-pnpm.js +0 -1
  616. package/dist/src/setup/scaffold/primitives/run-vercel.js +0 -1
  617. package/dist/src/setup/scaffold/project.d.ts +0 -21
  618. package/dist/src/setup/scaffold/project.js +0 -80
  619. package/dist/src/setup/scaffold/steps/deploy-to-vercel.d.ts +0 -17
  620. package/dist/src/setup/scaffold/steps/deploy-to-vercel.js +0 -1
  621. package/dist/src/setup/scaffold/steps/index.d.ts +0 -4
  622. package/dist/src/setup/scaffold/steps/index.js +0 -1
  623. package/dist/src/setup/scaffold/steps/project-resolution.d.ts +0 -19
  624. package/dist/src/setup/scaffold/steps/project-resolution.js +0 -1
  625. package/dist/src/setup/scaffold/steps/run-add-connection.d.ts +0 -40
  626. package/dist/src/setup/scaffold/steps/run-add-connection.js +0 -1
  627. package/dist/src/setup/scaffold/steps/run-add-to-agent.d.ts +0 -81
  628. package/dist/src/setup/scaffold/steps/run-add-to-agent.js +0 -2
  629. package/dist/src/setup/scaffold/steps/setup-connection.js +0 -1
  630. package/dist/src/setup/scaffold/steps/setup-slackbot.js +0 -1
  631. /package/dist/docs/public/{frontend → guides/frontend}/meta.json +0 -0
  632. /package/dist/docs/public/{advanced → guides}/remote-agents.md +0 -0
  633. /package/dist/src/{setup/scaffold/cli/channel-setup-prompter.js → cli/dev/tui/setup-flow.js} +0 -0
  634. /package/dist/src/evals/{scorers/autoevals-client.d.ts → autoevals-client.d.ts} +0 -0
  635. /package/dist/src/setup/{scaffold/cli → cli}/command-output.d.ts +0 -0
  636. /package/dist/src/setup/{scaffold/cli → cli}/command-output.js +0 -0
  637. /package/dist/src/setup/{scaffold/human-action.d.ts → human-action.d.ts} +0 -0
  638. /package/dist/src/setup/{scaffold/human-action.js → human-action.js} +0 -0
  639. /package/dist/src/setup/{scaffold/primitives → primitives}/process-output.d.ts +0 -0
  640. /package/dist/src/setup/{scaffold/primitives → primitives}/process-output.js +0 -0
  641. /package/dist/src/setup/scaffold/{web-template.d.ts → create/web-template.d.ts} +0 -0
  642. /package/dist/src/setup/scaffold/{web-template.js → create/web-template.js} +0 -0
  643. /package/dist/src/setup/scaffold/{module-files.d.ts → update/module-files.d.ts} +0 -0
  644. /package/dist/src/setup/scaffold/{module-files.js → update/module-files.js} +0 -0
  645. /package/dist/src/setup/scaffold/{package-json.d.ts → update/package-json.d.ts} +0 -0
  646. /package/dist/src/setup/scaffold/{package-json.js → update/package-json.js} +0 -0
  647. /package/dist/src/setup/scaffold/{primitives → update}/update-connection-connector.d.ts +0 -0
  648. /package/dist/src/setup/scaffold/{primitives → update}/update-connection-connector.js +0 -0
  649. /package/dist/src/setup/scaffold/{primitives → update}/update-slack-channel.d.ts +0 -0
  650. /package/dist/src/setup/scaffold/{primitives → update}/update-slack-channel.js +0 -0
@@ -1,3 +1,3 @@
1
- import{t as e}from"../../_chunks/workflow/src-B54rYDvB.js";import{convertDataContentToBase64String as t}from"ai";var n=e();function r(e){let t=e.toLowerCase();for(let[e,n]of[[`google.vertex`,`gcp.vertex_ai`],[`google.generative-ai`,`gcp.gemini`],[`google-vertex`,`gcp.vertex_ai`],[`amazon-bedrock`,`aws.bedrock`],[`azure-openai`,`azure.ai.openai`],[`anthropic`,`anthropic`],[`openai`,`openai`],[`azure`,`azure.ai.inference`],[`google`,`gcp.gemini`],[`mistral`,`mistral_ai`],[`cohere`,`cohere`],[`bedrock`,`aws.bedrock`],[`groq`,`groq`],[`deepseek`,`deepseek`],[`perplexity`,`perplexity`],[`xai`,`x_ai`]])if(t===e||t.startsWith(e+`.`)||t.startsWith(e+`-`))return n;return e}function i(e){return{"ai.generateText":`invoke_agent`,"ai.streamText":`invoke_agent`,"ai.generateObject":`invoke_agent`,"ai.streamObject":`invoke_agent`,"ai.embed":`embeddings`,"ai.embedMany":`embeddings`,"ai.rerank":`rerank`}[e]??e}function a(e){return typeof e==`string`?[{type:`text`,content:e}]:Array.isArray(e)?e.map(e=>({type:`text`,content:e.content})):[{type:`text`,content:e.content}]}function o(e){switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})(),i;if(r instanceof Uint8Array)i=t(r);else if(typeof r==`string`){if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r};i=r}else if(r instanceof URL)return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()};else i=String(r);return{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:i}}case`tool-approval-response`:return{type:`tool_approval_response`,approval_id:e.approvalId,approved:e.approved,reason:e.reason};case`custom`:return{type:`custom`,kind:e.kind};case`reasoning-file`:return{type:String(e.type)};default:return{type:String(e.type)}}}function s(e){return!e||e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`image`}function c(e){return e.filter(e=>e.role!==`system`).map(e=>{if(e.role===`system`)return{role:`system`,parts:[{type:`text`,content:e.content}]};let t=e.content.map(o);return{role:e.role,parts:t}})}function l({prompt:e,messages:t}){let n=[];if(typeof e==`string`)n.push({role:`user`,parts:[{type:`text`,content:e}]});else if(Array.isArray(e))for(let t of e){let e=u(t);e&&n.push(e)}if(t)for(let e of t){let t=u(e);t&&n.push(t)}return n}function u(e){if(e.role!==`system`){if(e.role===`user`)return typeof e.content==`string`?{role:`user`,parts:[{type:`text`,content:e.content}]}:{role:`user`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`image`:{let n=e.image;return n instanceof URL?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n.toString()}:typeof n==`string`?n.startsWith(`http://`)||n.startsWith(`https://`)?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:t(n)}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})();return r instanceof URL?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()}:typeof r==`string`?r.startsWith(`http://`)||r.startsWith(`https://`)?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:t(r)}}default:return{type:String(e.type)}}})};if(e.role===`assistant`)return typeof e.content==`string`?{role:`assistant`,parts:[{type:`text`,content:e.content}]}:{role:`assistant`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}default:return{type:String(e.type)}}})};if(e.role===`tool`)return{role:`tool`,parts:e.content.map(e=>{if(e.type===`tool-result`){let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}return{type:String(e.type)}})}}}function d({text:e,reasoning:t,toolCalls:n,files:r,finishReason:i}){let a=[];if(t)for(let e of t)`text`in e&&e.text&&a.push({type:`reasoning`,content:e.text});if(e!=null&&e.length>0&&a.push({type:`text`,content:e}),n)for(let e of n)a.push({type:`tool_call`,id:e.toolCallId,name:e.toolName,arguments:e.input});if(r)for(let e of r)a.push({type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType,content:e.base64});return[{role:`assistant`,parts:a,finish_reason:p(i)}]}function f({objectText:e,finishReason:t}){return[{role:`assistant`,parts:[{type:`text`,content:e}],finish_reason:p(t)}]}function p(e){return{stop:`stop`,length:`length`,"content-filter":`content_filter`,"tool-calls":`tool_call`,error:`error`,other:`stop`,unknown:`stop`}[e]??e}function m(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function h(e){return e?.isEnabled!==!1}function g(e,t){if(!h(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var _={usage:!1,providerMetadata:!1,embedding:!1,reranking:!1,runtimeContext:!1,headers:!1,toolChoice:!1,schema:!1};function v(e){return{..._,usage:e.usage??!1,providerMetadata:e.providerMetadata??!1,embedding:e.embedding??!1,reranking:e.reranking??!1,runtimeContext:e.runtimeContext??!1,headers:e.headers??!1,toolChoice:e.toolChoice??!1,schema:e.schema??!1}}function y(e){let t={};for(let[n,r]of Object.entries(e??{}))b(t,`ai.settings.context.${n}`,r);return t}function b(e,t,n){if(n!=null){if(Array.isArray(n)||typeof n!=`object`){e[t]=n;return}for(let[r,i]of Object.entries(n))b(e,`${t}.${r}`,i)}}function x(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!=null).map(([e,t])=>[`ai.request.headers.${e}`,t]))}function S(e){return{"ai.usage.inputTokenDetails.noCacheTokens":e.inputTokenDetails?.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":e.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.outputTokenDetails?.reasoningTokens}}function C(e,t,n){let r={};for(let[i,a]of Object.entries(n))!t[i]||a==null||Object.assign(r,g(e,a));return r}var w=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`gen_ai`),this.supplementalAttributes=v(e),this.enrichSpan=e.enrichSpan}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}getSpanAttributes({attributes:e,spanType:t,operationId:n,callId:r,runtimeContext:i}){let a;try{a=this.enrichSpan?.call(this,{spanType:t,operationId:n,callId:r,runtimeContext:i})}catch{a=void 0}return{...a,...e}}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e),i=r?.inferenceContext??r?.stepContext;return i==null?t():n.context.with(i,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=e.runtimeContext,d=C(t,this.supplementalAttributes,{runtimeContext:y(u),headers:x(e.headers)}),f=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.stop_sequences":e.stopSequences,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.instructions?{input:()=>JSON.stringify(a(e.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:void 0,messages:e.messages}))},...d}),p=`${c} ${e.modelId}`,m=this.tracer.startSpan(p,{attributes:this.getSpanAttributes({attributes:f,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:u}),kind:n.SpanKind.INTERNAL}),h=n.trace.setSpan(n.context.active(),m);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:m,rootContext:h,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:u,baseSupplementalAttributes:d})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=C(t,this.supplementalAttributes,{headers:x(e.headers)}),d=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.system?{input:()=>JSON.stringify(a(e.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:e.prompt,messages:e.messages}))},...u,...C(t,this.supplementalAttributes,{schema:{"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}})}),f=`${c} ${e.modelId}`,p=this.tracer.startSpan(f,{attributes:this.getSpanAttributes({attributes:d,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.INTERNAL}),m=n.trace.setSpan(n.context.active(),p);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:p,rootContext:m,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:u})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>e.promptMessages?JSON.stringify(c(e.promptMessages)):void 0},...t.baseSupplementalAttributes}),o=`chat ${e.modelId}`;t.inferenceSpan=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),t.inferenceContext=n.trace.setSpan(t.rootContext,t.inferenceSpan)}onObjectStepFinish(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(f({objectText:e.objectText,finishReason:e.finishReason}))}catch{return e.objectText}}},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=C(t,this.supplementalAttributes,{headers:x(e.headers)}),o=e.value,s=e.operationId===`ai.embedMany`,c=g(t,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...C(t,this.supplementalAttributes,{embedding:s?{"ai.values":{input:()=>o.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(o)}}})}),l=`embeddings ${e.modelId}`,u=this.tracer.startSpan(l,{attributes:this.getSpanAttributes({attributes:c,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),d=n.trace.setSpan(n.context.active(),u);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:u,rootContext:d,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t;t.runtimeContext=e.runtimeContext;let i=g(r,{"gen_ai.operation.name":`agent_step`,...t.baseSupplementalAttributes,...C(r,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)}}})});t.stepSpan=this.tracer.startSpan(`step ${e.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:i,spanType:`step`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onLanguageModelCallStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>{let t=l({prompt:void 0,messages:e.messages});return t.length>0?JSON.stringify(t):void 0}},"gen_ai.tool.definitions":{input:()=>e.tools?JSON.stringify(e.tools):void 0}});t.inferenceSpan=this.tracer.startSpan(`chat ${e.modelId}`,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.stepContext),t.inferenceContext=n.trace.setSpan(t.stepContext,t.inferenceSpan)}onLanguageModelCallEnd(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.responseId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)||void 0,reasoning:e.content.filter(e=>e.type===`reasoning`),toolCalls:e.content.filter(e=>e.type===`tool-call`),files:e.content.filter(e=>e.type===`file`).map(e=>e.file),finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{usage:S(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=g(r,{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":i.toolName,"gen_ai.tool.call.id":i.toolCallId,"gen_ai.tool.type":`function`,"gen_ai.tool.call.arguments":{input:()=>JSON.stringify(i.input)}}),o=`execute_tool ${i.toolName}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`tool`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.stepContext),c=n.trace.setSpan(t.stepContext,s);t.toolSpans.set(i.toolCallId,{span:s,context:c})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(g(i,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else m(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepFinish(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId===`ai.embed`||t.operationId===`ai.embedMany`){this.onEmbedOperationEnd(e);return}if(t.operationId===`ai.rerank`){this.onRerankOperationEnd(e);return}if(t.operationId===`ai.generateObject`||t.operationId===`ai.streamObject`){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e)}}onGenerateEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.text??void 0,reasoning:e.finalStep.reasoning,toolCalls:e.toolCalls,files:e.files,finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.finalStep.providerMetadata?JSON.stringify(e.finalStep.providerMetadata):void 0},usage:S(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onObjectOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>e.object==null?void 0:JSON.stringify(f({objectText:JSON.stringify(e.object),finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.embedMany`;t.rootSpan.setAttributes(g(n,{"gen_ai.usage.input_tokens":e.usage.tokens,...C(n,this.supplementalAttributes,{embedding:r?{"ai.embeddings":{output:()=>e.embedding.map(e=>JSON.stringify(e))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}}})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...C(i,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>e.values.map(e=>JSON.stringify(e))}}})}),o=`embeddings ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`embedding`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),c=n.trace.setSpan(t.rootContext,s);t.embedSpans.set(e.embedCallId,{span:s,context:c})}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.embedSpans.get(e.embedCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t;r.setAttributes(g(i,{"gen_ai.usage.input_tokens":e.usage.tokens,...C(i,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>e.embeddings.map(e=>JSON.stringify(e))}}})})),r.end(),t.embedSpans.delete(e.embedCallId)}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=C(t,this.supplementalAttributes,{headers:x(e.headers)}),o=g(t,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...C(t,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),s=`rerank ${e.modelId}`,c=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:o,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId))}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...C(i,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),o=`rerank ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`reranking`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext);t.rerankSpan={span:s,context:n.trace.setSpan(t.rootContext,s)}}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:n}=t.rerankSpan,{telemetry:r}=t;n.setAttributes(C(r,this.supplementalAttributes,{reranking:{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(e=>JSON.stringify(e))}}})),n.end(),t.rerankSpan=void 0}onAbort(e){let t=this.getCallState(e.callId);if(t?.rootSpan){for(let{span:e}of t.toolSpans.values())e.end();t.toolSpans.clear(),t.inferenceSpan&&(t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0),t.stepSpan&&(t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0);for(let{span:e}of t.embedSpans.values())e.end();t.embedSpans.clear(),t.rerankSpan&&=(t.rerankSpan.span.end(),void 0),t.rootSpan.end(),this.cleanupCallState(e.callId)}}onError(e){let t=e;if(!t?.callId)return;let n=this.getCallState(t.callId);if(!n?.rootSpan)return;let r=t.error??e;for(let{span:e}of n.toolSpans.values())m(e,r),e.end();n.toolSpans.clear(),n.inferenceSpan&&(m(n.inferenceSpan,r),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0),n.stepSpan&&(m(n.stepSpan,r),n.stepSpan.end(),n.stepSpan=void 0,n.stepContext=void 0);for(let{span:e}of n.embedSpans.values())m(e,r),e.end();n.embedSpans.clear(),n.rerankSpan&&=(m(n.rerankSpan.span,r),n.rerankSpan.span.end(),void 0),m(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(t.callId)}};function T({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId==null?``:` ${t.functionId}`}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function E({model:e,settings:t,headers:n,context:r}){return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,n])=>(e[`ai.settings.${t}`]=n,e),{}),...y(r),...Object.entries(n??{}).reduce((e,[t,n])=>(n!==void 0&&(e[`ai.request.headers.${t}`]=n),e),{})}}function D(e){return JSON.stringify(e.map(e=>({...e,content:typeof e.content==`string`?e.content:e.content.map(e=>e.type===`file`?{...e,data:O(e.data)}:e)})))}function O(e){switch(e.type){case`data`:return e.data instanceof Uint8Array?t(e.data):e.data;case`url`:return e.url.toString();case`reference`:return e.reference;case`text`:return e.text}}function k(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function A(e){return e?.isEnabled!==!1}function j(e,t){if(!A(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var M=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`ai`)}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e)?.stepContext;return r==null?t():n.context.with(r,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:e.runtimeContext}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt":{input:()=>JSON.stringify({system:e.instructions,messages:e.messages})}}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.prompt":{input:()=>JSON.stringify({system:e.system,prompt:e.prompt,messages:e.messages})},"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamObject`?`ai.streamObject.doStream`:`ai.generateObject.doGenerate`,a=j(r,{...T({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.prompt.messages":{input:()=>e.promptMessages?D(e.promptMessages):void 0},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onObjectStepFinish(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.object":{output:()=>{try{return JSON.stringify(JSON.parse(e.objectText))}catch{return e.objectText}}},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens})),e.msToFirstChunk!=null&&(t.stepSpan.addEvent(`ai.stream.firstChunk`,{"ai.stream.msToFirstChunk":e.msToFirstChunk}),t.stepSpan.setAttributes({"ai.stream.msToFirstChunk":e.msToFirstChunk})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=e.value,o=e.operationId===`ai.embedMany`,s=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,...o?{"ai.values":{input:()=>a.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(a)}}}),c=this.tracer.startSpan(e.operationId,{attributes:s}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamText`?`ai.streamText.doStream`:`ai.generateText.doGenerate`,a=j(r,{...T({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt.messages":{input:()=>e.promptMessages?D(e.promptMessages):void 0},"ai.prompt.tools":{input:()=>e.stepTools?.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=j(r,{...T({operationId:`ai.toolCall`,telemetry:r}),"ai.toolCall.name":i.toolName,"ai.toolCall.id":i.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(i.input)}}),o=this.tracer.startSpan(`ai.toolCall`,{attributes:a},t.stepContext),s=n.trace.setSpan(t.stepContext,o);t.toolSpans.set(i.toolCallId,{span:o,context:s})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(j(i,{"ai.toolCall.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else k(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepFinish(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.streamText`;t.stepSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.text":{output:()=>e.text??void 0},"ai.response.reasoning":{output:()=>e.reasoning.length>0?e.reasoning.filter(e=>`text`in e).map(e=>e.text).join(`
2
- `):void 0},"ai.response.toolCalls":{output:()=>e.toolCalls.length>0?JSON.stringify(e.toolCalls.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,input:e.input}))):void 0},"ai.response.files":{output:()=>e.files.length>0?JSON.stringify(e.files.map(e=>({type:`file`,mediaType:e.mediaType,data:e.base64}))):void 0},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.response.msToFirstChunk":r?e.performance.timeToFirstOutputMs:void 0,"ai.response.msToFinish":r?e.performance.responseTimeMs:void 0,"ai.response.avgOutputTokensPerSecond":r?e.performance.effectiveOutputTokensPerSecond:void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.noCacheTokens":e.usage.inputTokenDetails?.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":e.usage.inputTokenDetails?.cacheWriteTokens,"ai.usage.outputTokenDetails.textTokens":e.usage.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens})),r&&e.performance.timeToFirstOutputMs!=null&&t.stepSpan.addEvent(`ai.stream.firstChunk`,{"ai.response.msToFirstChunk":e.performance.timeToFirstOutputMs}),r&&t.stepSpan.addEvent(`ai.stream.finish`,{"ai.response.msToFinish":e.performance.responseTimeMs,"ai.response.avgOutputTokensPerSecond":e.performance.effectiveOutputTokensPerSecond}),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId===`ai.embed`||t.operationId===`ai.embedMany`){this.onEmbedOperationEnd(e);return}if(t.operationId===`ai.rerank`){this.onRerankOperationEnd(e);return}if(t.operationId===`ai.generateObject`||t.operationId===`ai.streamObject`){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e)}}onGenerateEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.text":{output:()=>e.text??void 0},"ai.response.reasoning":{output:()=>e.finalStep.reasoning.length>0?e.finalStep.reasoning.filter(e=>`text`in e).map(e=>e.text).join(`
1
+ import{t as e}from"../../_chunks/workflow/src-B54rYDvB.js";import{convertDataContentToBase64String as t}from"ai";var n=e();function r(e){let t=e.toLowerCase();for(let[e,n]of[[`google.vertex`,`gcp.vertex_ai`],[`google.generative-ai`,`gcp.gemini`],[`google-vertex`,`gcp.vertex_ai`],[`amazon-bedrock`,`aws.bedrock`],[`azure-openai`,`azure.ai.openai`],[`anthropic`,`anthropic`],[`openai`,`openai`],[`azure`,`azure.ai.inference`],[`google`,`gcp.gemini`],[`mistral`,`mistral_ai`],[`cohere`,`cohere`],[`bedrock`,`aws.bedrock`],[`groq`,`groq`],[`deepseek`,`deepseek`],[`perplexity`,`perplexity`],[`xai`,`x_ai`]])if(t===e||t.startsWith(e+`.`)||t.startsWith(e+`-`))return n;return e}function i(e){return{"ai.generateText":`invoke_agent`,"ai.streamText":`invoke_agent`,"ai.generateObject":`invoke_agent`,"ai.streamObject":`invoke_agent`,"ai.embed":`embeddings`,"ai.embedMany":`embeddings`,"ai.rerank":`rerank`}[e]??e}function a(e){return typeof e==`string`?[{type:`text`,content:e}]:Array.isArray(e)?e.map(e=>({type:`text`,content:e.content})):[{type:`text`,content:e.content}]}function o(e){switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})(),i;if(r instanceof Uint8Array)i=t(r);else if(typeof r==`string`){if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r};i=r}else if(r instanceof URL)return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()};else i=String(r);return{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:i}}case`tool-approval-response`:return{type:`tool_approval_response`,approval_id:e.approvalId,approved:e.approved,reason:e.reason};case`custom`:return{type:`custom`,kind:e.kind};case`reasoning-file`:return{type:String(e.type)};default:return{type:String(e.type)}}}function s(e){return!e||e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`image`}function c(e){return e.filter(e=>e.role!==`system`).map(e=>{if(e.role===`system`)return{role:`system`,parts:[{type:`text`,content:e.content}]};let t=e.content.map(o);return{role:e.role,parts:t}})}function l({prompt:e,messages:t}){let n=[];if(typeof e==`string`)n.push({role:`user`,parts:[{type:`text`,content:e}]});else if(Array.isArray(e))for(let t of e){let e=u(t);e&&n.push(e)}if(t)for(let e of t){let t=u(e);t&&n.push(t)}return n}function u(e){if(e.role!==`system`){if(e.role===`user`)return typeof e.content==`string`?{role:`user`,parts:[{type:`text`,content:e.content}]}:{role:`user`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`image`:{let n=e.image;return n instanceof URL?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n.toString()}:typeof n==`string`?n.startsWith(`http://`)||n.startsWith(`https://`)?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:t(n)}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})();return r instanceof URL?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()}:typeof r==`string`?r.startsWith(`http://`)||r.startsWith(`https://`)?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:t(r)}}default:return{type:String(e.type)}}})};if(e.role===`assistant`)return typeof e.content==`string`?{role:`assistant`,parts:[{type:`text`,content:e.content}]}:{role:`assistant`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}default:return{type:String(e.type)}}})};if(e.role===`tool`)return{role:`tool`,parts:e.content.map(e=>{if(e.type===`tool-result`){let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}return{type:String(e.type)}})}}}function d({text:e,reasoning:t,toolCalls:n,files:r,finishReason:i}){let a=[];if(t)for(let e of t)`text`in e&&e.text&&a.push({type:`reasoning`,content:e.text});if(e!=null&&e.length>0&&a.push({type:`text`,content:e}),n)for(let e of n)a.push({type:`tool_call`,id:e.toolCallId,name:e.toolName,arguments:e.input});if(r)for(let e of r)a.push({type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType,content:e.base64});return[{role:`assistant`,parts:a,finish_reason:p(i)}]}function f({objectText:e,finishReason:t}){return[{role:`assistant`,parts:[{type:`text`,content:e}],finish_reason:p(t)}]}function p(e){return{stop:`stop`,length:`length`,"content-filter":`content_filter`,"tool-calls":`tool_call`,error:`error`,other:`stop`,unknown:`stop`}[e]??e}function m(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function h(e){return e?.isEnabled!==!1}function g(e,t){if(!h(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var _={usage:!1,providerMetadata:!1,embedding:!1,reranking:!1,runtimeContext:!1,headers:!1,toolChoice:!1,schema:!1};function v(e){return{..._,usage:e.usage??!1,providerMetadata:e.providerMetadata??!1,embedding:e.embedding??!1,reranking:e.reranking??!1,runtimeContext:e.runtimeContext??!1,headers:e.headers??!1,toolChoice:e.toolChoice??!1,schema:e.schema??!1}}function y(e){let t={};for(let[n,r]of Object.entries(e??{}))b(t,`ai.settings.context.${n}`,r);return t}function b(e,t,n){if(n!=null){if(Array.isArray(n)||typeof n!=`object`){e[t]=n;return}for(let[r,i]of Object.entries(n))b(e,`${t}.${r}`,i)}}function x(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!=null).map(([e,t])=>[`ai.request.headers.${e}`,t]))}function S(e){return{"ai.usage.inputTokenDetails.noCacheTokens":e.inputTokenDetails?.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":e.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.outputTokenDetails?.reasoningTokens}}function C(e,t,n){let r={};for(let[i,a]of Object.entries(n))!t[i]||a==null||Object.assign(r,g(e,a));return r}var w=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`gen_ai`),this.supplementalAttributes=v(e),this.enrichSpan=e.enrichSpan}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}getSpanAttributes({attributes:e,spanType:t,operationId:n,callId:r,runtimeContext:i}){let a;try{a=this.enrichSpan?.call(this,{spanType:t,operationId:n,callId:r,runtimeContext:i})}catch{a=void 0}return{...a,...e}}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e),i=r?.inferenceContext??r?.stepContext;return i==null?t():n.context.with(i,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=e.runtimeContext,d=C(t,this.supplementalAttributes,{runtimeContext:y(u),headers:x(e.headers)}),f=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.stop_sequences":e.stopSequences,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.instructions?{input:()=>JSON.stringify(a(e.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:void 0,messages:e.messages}))},...d}),p=`${c} ${e.modelId}`,m=this.tracer.startSpan(p,{attributes:this.getSpanAttributes({attributes:f,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:u}),kind:n.SpanKind.INTERNAL}),h=n.trace.setSpan(n.context.active(),m);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:m,rootContext:h,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:u,baseSupplementalAttributes:d})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=C(t,this.supplementalAttributes,{headers:x(e.headers)}),d=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.system?{input:()=>JSON.stringify(a(e.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:e.prompt,messages:e.messages}))},...u,...C(t,this.supplementalAttributes,{schema:{"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}})}),f=`${c} ${e.modelId}`,p=this.tracer.startSpan(f,{attributes:this.getSpanAttributes({attributes:d,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.INTERNAL}),m=n.trace.setSpan(n.context.active(),p);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:p,rootContext:m,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:u})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>e.promptMessages?JSON.stringify(c(e.promptMessages)):void 0},...t.baseSupplementalAttributes}),o=`chat ${e.modelId}`;t.inferenceSpan=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),t.inferenceContext=n.trace.setSpan(t.rootContext,t.inferenceSpan)}onObjectStepEnd(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(f({objectText:e.objectText,finishReason:e.finishReason}))}catch{return e.objectText}}},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=C(t,this.supplementalAttributes,{headers:x(e.headers)}),o=e.value,s=e.operationId===`ai.embedMany`,c=g(t,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...C(t,this.supplementalAttributes,{embedding:s?{"ai.values":{input:()=>o.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(o)}}})}),l=`embeddings ${e.modelId}`,u=this.tracer.startSpan(l,{attributes:this.getSpanAttributes({attributes:c,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),d=n.trace.setSpan(n.context.active(),u);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:u,rootContext:d,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t;t.runtimeContext=e.runtimeContext;let i=g(r,{"gen_ai.operation.name":`agent_step`,...t.baseSupplementalAttributes,...C(r,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)}}})});t.stepSpan=this.tracer.startSpan(`step ${e.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:i,spanType:`step`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onLanguageModelCallStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>{let t=l({prompt:void 0,messages:e.messages});return t.length>0?JSON.stringify(t):void 0}},"gen_ai.tool.definitions":{input:()=>e.tools?JSON.stringify(e.tools):void 0}});t.inferenceSpan=this.tracer.startSpan(`chat ${e.modelId}`,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.stepContext),t.inferenceContext=n.trace.setSpan(t.stepContext,t.inferenceSpan)}onLanguageModelCallEnd(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.responseId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)||void 0,reasoning:e.content.filter(e=>e.type===`reasoning`),toolCalls:e.content.filter(e=>e.type===`tool-call`),files:e.content.filter(e=>e.type===`file`).map(e=>e.file),finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{usage:S(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=g(r,{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":i.toolName,"gen_ai.tool.call.id":i.toolCallId,"gen_ai.tool.type":`function`,"gen_ai.tool.call.arguments":{input:()=>JSON.stringify(i.input)}}),o=`execute_tool ${i.toolName}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`tool`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.stepContext),c=n.trace.setSpan(t.stepContext,s);t.toolSpans.set(i.toolCallId,{span:s,context:c})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(g(i,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else m(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onStepFinish(e){this.onStepEnd(e)}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId===`ai.embed`||t.operationId===`ai.embedMany`){this.onEmbedOperationEnd(e);return}if(t.operationId===`ai.rerank`){this.onRerankOperationEnd(e);return}if(t.operationId===`ai.generateObject`||t.operationId===`ai.streamObject`){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e)}}onGenerateEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.text??void 0,reasoning:e.finalStep.reasoning,toolCalls:e.toolCalls,files:e.files,finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.finalStep.providerMetadata?JSON.stringify(e.finalStep.providerMetadata):void 0},usage:S(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onObjectOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>e.object==null?void 0:JSON.stringify(f({objectText:JSON.stringify(e.object),finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.embedMany`;t.rootSpan.setAttributes(g(n,{"gen_ai.usage.input_tokens":e.usage.tokens,...C(n,this.supplementalAttributes,{embedding:r?{"ai.embeddings":{output:()=>e.embedding.map(e=>JSON.stringify(e))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}}})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...C(i,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>e.values.map(e=>JSON.stringify(e))}}})}),o=`embeddings ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`embedding`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),c=n.trace.setSpan(t.rootContext,s);t.embedSpans.set(e.embedCallId,{span:s,context:c})}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.embedSpans.get(e.embedCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t;r.setAttributes(g(i,{"gen_ai.usage.input_tokens":e.usage.tokens,...C(i,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>e.embeddings.map(e=>JSON.stringify(e))}}})})),r.end(),t.embedSpans.delete(e.embedCallId)}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=C(t,this.supplementalAttributes,{headers:x(e.headers)}),o=g(t,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...C(t,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),s=`rerank ${e.modelId}`,c=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:o,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId))}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...C(i,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),o=`rerank ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`reranking`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext);t.rerankSpan={span:s,context:n.trace.setSpan(t.rootContext,s)}}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:n}=t.rerankSpan,{telemetry:r}=t;n.setAttributes(C(r,this.supplementalAttributes,{reranking:{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(e=>JSON.stringify(e))}}})),n.end(),t.rerankSpan=void 0}onAbort(e){let t=this.getCallState(e.callId);if(t?.rootSpan){for(let{span:e}of t.toolSpans.values())e.end();t.toolSpans.clear(),t.inferenceSpan&&(t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0),t.stepSpan&&(t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0);for(let{span:e}of t.embedSpans.values())e.end();t.embedSpans.clear(),t.rerankSpan&&=(t.rerankSpan.span.end(),void 0),t.rootSpan.end(),this.cleanupCallState(e.callId)}}onError(e){let t=e;if(!t?.callId)return;let n=this.getCallState(t.callId);if(!n?.rootSpan)return;let r=t.error??e;for(let{span:e}of n.toolSpans.values())m(e,r),e.end();n.toolSpans.clear(),n.inferenceSpan&&(m(n.inferenceSpan,r),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0),n.stepSpan&&(m(n.stepSpan,r),n.stepSpan.end(),n.stepSpan=void 0,n.stepContext=void 0);for(let{span:e}of n.embedSpans.values())m(e,r),e.end();n.embedSpans.clear(),n.rerankSpan&&=(m(n.rerankSpan.span,r),n.rerankSpan.span.end(),void 0),m(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(t.callId)}};function T({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId==null?``:` ${t.functionId}`}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function E({model:e,settings:t,headers:n,context:r}){return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,n])=>(e[`ai.settings.${t}`]=n,e),{}),...y(r),...Object.entries(n??{}).reduce((e,[t,n])=>(n!==void 0&&(e[`ai.request.headers.${t}`]=n),e),{})}}function D(e){return JSON.stringify(e.map(e=>({...e,content:typeof e.content==`string`?e.content:e.content.map(e=>e.type===`file`?{...e,data:O(e.data)}:e)})))}function O(e){switch(e.type){case`data`:return e.data instanceof Uint8Array?t(e.data):e.data;case`url`:return e.url.toString();case`reference`:return e.reference;case`text`:return e.text}}function k(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function A(e){return e?.isEnabled!==!1}function j(e,t){if(!A(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var M=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`ai`)}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e)?.stepContext;return r==null?t():n.context.with(r,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:e.runtimeContext}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt":{input:()=>JSON.stringify({system:e.instructions,messages:e.messages})}}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.prompt":{input:()=>JSON.stringify({system:e.system,prompt:e.prompt,messages:e.messages})},"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamObject`?`ai.streamObject.doStream`:`ai.generateObject.doGenerate`,a=j(r,{...T({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.prompt.messages":{input:()=>e.promptMessages?D(e.promptMessages):void 0},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onObjectStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.object":{output:()=>{try{return JSON.stringify(JSON.parse(e.objectText))}catch{return e.objectText}}},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens})),e.msToFirstChunk!=null&&(t.stepSpan.addEvent(`ai.stream.firstChunk`,{"ai.stream.msToFirstChunk":e.msToFirstChunk}),t.stepSpan.setAttributes({"ai.stream.msToFirstChunk":e.msToFirstChunk})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=e.value,o=e.operationId===`ai.embedMany`,s=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,...o?{"ai.values":{input:()=>a.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(a)}}}),c=this.tracer.startSpan(e.operationId,{attributes:s}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamText`?`ai.streamText.doStream`:`ai.generateText.doGenerate`,a=j(r,{...T({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt.messages":{input:()=>e.promptMessages?D(e.promptMessages):void 0},"ai.prompt.tools":{input:()=>e.stepTools?.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=j(r,{...T({operationId:`ai.toolCall`,telemetry:r}),"ai.toolCall.name":i.toolName,"ai.toolCall.id":i.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(i.input)}}),o=this.tracer.startSpan(`ai.toolCall`,{attributes:a},t.stepContext),s=n.trace.setSpan(t.stepContext,o);t.toolSpans.set(i.toolCallId,{span:o,context:s})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(j(i,{"ai.toolCall.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else k(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.streamText`;t.stepSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.text":{output:()=>e.text??void 0},"ai.response.reasoning":{output:()=>e.reasoning.length>0?e.reasoning.filter(e=>`text`in e).map(e=>e.text).join(`
2
+ `):void 0},"ai.response.toolCalls":{output:()=>e.toolCalls.length>0?JSON.stringify(e.toolCalls.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,input:e.input}))):void 0},"ai.response.files":{output:()=>e.files.length>0?JSON.stringify(e.files.map(e=>({type:`file`,mediaType:e.mediaType,data:e.base64}))):void 0},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.response.msToFirstChunk":r?e.performance.timeToFirstOutputMs:void 0,"ai.response.msToFinish":r?e.performance.responseTimeMs:void 0,"ai.response.avgOutputTokensPerSecond":r?e.performance.effectiveOutputTokensPerSecond:void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.noCacheTokens":e.usage.inputTokenDetails?.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":e.usage.inputTokenDetails?.cacheWriteTokens,"ai.usage.outputTokenDetails.textTokens":e.usage.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens})),r&&e.performance.timeToFirstOutputMs!=null&&t.stepSpan.addEvent(`ai.stream.firstChunk`,{"ai.response.msToFirstChunk":e.performance.timeToFirstOutputMs}),r&&t.stepSpan.addEvent(`ai.stream.finish`,{"ai.response.msToFinish":e.performance.responseTimeMs,"ai.response.avgOutputTokensPerSecond":e.performance.effectiveOutputTokensPerSecond}),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onStepFinish(e){this.onStepEnd(e)}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId===`ai.embed`||t.operationId===`ai.embedMany`){this.onEmbedOperationEnd(e);return}if(t.operationId===`ai.rerank`){this.onRerankOperationEnd(e);return}if(t.operationId===`ai.generateObject`||t.operationId===`ai.streamObject`){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e)}}onGenerateEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.text":{output:()=>e.text??void 0},"ai.response.reasoning":{output:()=>e.finalStep.reasoning.length>0?e.finalStep.reasoning.filter(e=>`text`in e).map(e=>e.text).join(`
3
3
  `):void 0},"ai.response.toolCalls":{output:()=>e.toolCalls.length>0?JSON.stringify(e.toolCalls.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,input:e.input}))):void 0},"ai.response.files":{output:()=>e.files.length>0?JSON.stringify(e.files.map(e=>({type:`file`,mediaType:e.mediaType,data:e.base64}))):void 0},"ai.response.providerMetadata":e.finalStep.providerMetadata?JSON.stringify(e.finalStep.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.noCacheTokens":e.usage.inputTokenDetails?.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":e.usage.inputTokenDetails?.cacheWriteTokens,"ai.usage.outputTokenDetails.textTokens":e.usage.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onObjectOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.object":{output:()=>e.object==null?void 0:JSON.stringify(e.object)},"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.embedMany`;t.rootSpan.setAttributes(j(n,{...r?{"ai.embeddings":{output:()=>e.embedding.map(e=>JSON.stringify(e))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}},"ai.usage.tokens":e.usage.tokens})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=j(r,{...T({operationId:e.operationId,telemetry:r}),...t.baseTelemetryAttributes,"ai.values":{input:()=>e.values.map(e=>JSON.stringify(e))}}),a=this.tracer.startSpan(e.operationId,{attributes:i},t.rootContext),o=n.trace.setSpan(t.rootContext,a);t.embedSpans.set(e.embedCallId,{span:a,context:o})}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.embedSpans.get(e.embedCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t;r.setAttributes(j(i,{"ai.embeddings":{output:()=>e.embeddings.map(e=>JSON.stringify(e))},"ai.usage.tokens":e.usage.tokens})),r.end(),t.embedSpans.delete(e.embedCallId)}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId))}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=j(r,{...T({operationId:e.operationId,telemetry:r}),...t.baseTelemetryAttributes,"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}),a=this.tracer.startSpan(e.operationId,{attributes:i},t.rootContext);t.rerankSpan={span:a,context:n.trace.setSpan(t.rootContext,a)}}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:n}=t.rerankSpan,{telemetry:r}=t;n.setAttributes(j(r,{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(e=>JSON.stringify(e))}})),n.end(),t.rerankSpan=void 0}onAbort(e){let t=this.getCallState(e.callId);if(t?.rootSpan){for(let{span:e}of t.toolSpans.values())e.end();t.toolSpans.clear(),t.stepSpan&&(t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0);for(let{span:e}of t.embedSpans.values())e.end();t.embedSpans.clear(),t.rerankSpan&&=(t.rerankSpan.span.end(),void 0),t.rootSpan.end(),this.cleanupCallState(e.callId)}}onError(e){let t=e;if(!t?.callId)return;let n=this.getCallState(t.callId);if(!n?.rootSpan)return;let r=t.error??e;n.stepSpan&&(k(n.stepSpan,r),n.stepSpan.end());for(let{span:e}of n.embedSpans.values())k(e,r),e.end();n.embedSpans.clear(),n.rerankSpan&&=(k(n.rerankSpan.span,r),n.rerankSpan.span.end(),void 0),k(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(t.callId)}};export{M as LegacyOpenTelemetry,w as OpenTelemetry};
@@ -105,4 +105,4 @@ ${e.message}`),t?new f.VercelOidcTokenError(t):e}return n}function m(){let e=(0,
105
105
  `);super(t,{cause:e}),this.name=`LocalOidcContextError`}},yr=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,`Please make sure OIDC is set up for your project`,`╰▶ Docs: https://vercel.com/docs/oidc`].join(`
106
106
  `);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function br(e){try{return wr(await(0,er.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!mr())throw process.env.VERCEL_URL?new yr(t):new vr(t);return await hr(e)}}async function xr(e){return Sr(e??{})||await br({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function Sr(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const Cr=s.object({exp:s.number().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:s.number().optional().describe(`Issued at timestamp`),owner_id:s.string(),project_id:s.string()});function wr(e){try{let t=Cr.parse(or(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const Tr={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function Er(e){if(typeof e==`number`)return e;if(e in Tr)return Tr[e];throw Error(`Unknown signal name: ${String(e)}`)}var Dr=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await xr();return this._client=new nr({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[t](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[i](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=await t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal});return new Or({client:t,sessionId:this.sessionId,cmd:n.json.command,exitCode:n.json.command.exitCode})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:Er(e??`SIGTERM`),abortSignal:t?.abortSignal})}},Or=class e extends Dr{constructor(e){super({...e}),this.exitCode=e.exitCode}static[t](e){return{...Dr[t](e),exitCode:e.exitCode}}static[i](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,output:t.output})}async wait(){return this}};function kr(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){Ar(i);let t=e;for(yield t;t.pagination.next!==null;)Ar(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)Ar(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function Ar(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var jr=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await xr();return this._client=new nr({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[t](e){return{snapshot:e.snapshot}}static[i](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await xr(e),n=new nr({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return kr(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await xr(e),n=new nr({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return kr(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await xr(t),r=new nr({teamId:n.teamId,token:n.token});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function Mr(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?zn(t):void 0}}var Nr=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await xr();return this._client=new nr({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[t](e){return{session:e.session,routes:e.routes}}static[i](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=Mr(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new Dr({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=async e=>{if(!(!i.stdout&&!i.stderr))try{for await(let t of e.logs({signal:i.signal}))t.stream===`stdout`?i.stdout?.write(t.data):t.stream===`stderr`&&i.stderr?.write(t.data)}catch(e){if(i.signal?.aborted)return;throw e}};if(a){let e=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,timeout:i.timeoutMs,signal:i.signal}),t=new Dr({client:r,sessionId:this.session.id,cmd:e.command}),[n]=await Promise.all([e.finished,o(t)]);return new Or({client:r,sessionId:this.session.id,cmd:n,exitCode:n.exitCode??0})}let s=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,timeout:i.timeoutMs,signal:i.signal}),c=new Dr({client:r,sessionId:this.session.id,cmd:s.json.command});return o(c).catch(e=>{i.signal?.aborted||(i.stderr??i.stdout)?.emit(`error`,e)}),c}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:In(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=f(t.cwd??``,t.path);return n?.mkdirRecursive&&await v(d(e),{recursive:!0}),await _(i,p(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=Mr(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=Mr((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=Mr((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=Mr(n.json.session),new jr({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:Pr,S_IFREG:Fr,S_IFDIR:Ir,S_IFLNK:Lr,S_IFBLK:Rr,S_IFCHR:zr,S_IFIFO:Br,S_IFSOCK:Vr}=y;function $(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function Hr(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var Ur=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&Pr)===Fr}isDirectory(){return(this.mode&Pr)===Ir}isBlockDevice(){return(this.mode&Pr)===Rr}isCharacterDevice(){return(this.mode&Pr)===zr}isSymbolicLink(){return(this.mode&Pr)===Lr}isFIFO(){return(this.mode&Pr)===Br}isSocket(){return(this.mode&Pr)===Vr}},Wr=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function Gr(e){let t=e.trim().split(`|`);return new Ur(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function Kr(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw $(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new Wr(r,Jr[i]??1,t)}const qr=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,Jr={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var Yr=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=Hr(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw $(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw $(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`scandir`,e):$(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
107
107
  `).filter(Boolean).map(t=>Kr(t,e))}let n=await this.sandbox.runCommand(`ls`,[`-1`,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`scandir`,e):$(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
108
- `).filter(Boolean)}async stat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-L`,`-c`,qr,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`stat`,e):$(`EACCES`,t.trim(),`stat`,e)}return Gr(await n.stdout())}async lstat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-c`,qr,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`lstat`,e):$(`EACCES`,t.trim(),`lstat`,e)}return Gr(await n.stdout())}async unlink(e,t){"use step";let n=await this.sandbox.runCommand(`rm`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`unlink`,e):$(`EACCES`,t.trim(),`unlink`,e)}}async rm(e,t){"use step";let n=[];t?.recursive&&n.push(`-r`),t?.force&&n.push(`-f`),n.push(e);let r=await this.sandbox.runCommand(`rm`,n,{signal:t?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`rm`,e):$(`EACCES`,t.trim(),`rm`,e)}}async rmdir(e,t){"use step";let n=await this.sandbox.runCommand(`rmdir`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`rmdir`,e):t.includes(`not empty`)?$(`ENOTEMPTY`,`directory not empty`,`rmdir`,e):$(`EACCES`,t.trim(),`rmdir`,e)}}async rename(e,t,n){"use step";let r=await this.sandbox.runCommand(`mv`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`rename`,e):$(`EACCES`,t.trim(),`rename`,e)}}async copyFile(e,t,n){"use step";let r=await this.sandbox.runCommand(`cp`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`copyfile`,e):$(`EACCES`,t.trim(),`copyfile`,e)}}async access(e,t){"use step";if((await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode!==0)throw $(`ENOENT`,`no such file or directory`,`access`,e)}async exists(e,t){return(await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode===0}async chmod(e,t,n){"use step";let r=typeof t==`number`?t.toString(8):t,i=await this.sandbox.runCommand(`chmod`,[r,e],{signal:n?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`chmod`,e):$(`EACCES`,t.trim(),`chmod`,e)}}async chown(e,t,n,r){"use step";let i=await this.sandbox.runCommand(`chown`,[`${t}:${n}`,e],{signal:r?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`chown`,e):$(`EACCES`,t.trim(),`chown`,e)}}async symlink(e,t,n){"use step";let r=await this.sandbox.runCommand(`ln`,[`-s`,e,t],{signal:n?.signal});if(r.exitCode!==0){let e=await r.stderr();throw e.includes(`File exists`)?$(`EEXIST`,`file already exists`,`symlink`,t):$(`EACCES`,e.trim(),`symlink`,t)}}async readlink(e,t){"use step";let n=await this.sandbox.runCommand(`readlink`,[e],{signal:t?.signal});if(n.exitCode!==0)throw(await n.stderr()).includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`readlink`,e):$(`EINVAL`,`invalid argument`,`readlink`,e);return(await n.stdout()).trim()}async realpath(e,t){"use step";let n=await this.sandbox.runCommand(`realpath`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`realpath`,e):$(`EACCES`,t.trim(),`realpath`,e)}return(await n.stdout()).trim()}async truncate(e,t,n){"use step";let r=await this.sandbox.runCommand(`truncate`,[`-s`,String(t??0),e],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`truncate`,e):$(`EACCES`,t.trim(),`truncate`,e)}}async mkdtemp(e,t){"use step";let n=await this.sandbox.runCommand(`mktemp`,[`-d`,`${e}XXXXXX`],{signal:t?.signal});if(n.exitCode!==0)throw $(`EACCES`,(await n.stderr()).trim(),`mkdtemp`,e);return(await n.stdout()).trim()}};function Xr(e){return e instanceof b&&e.response.status===410}function Zr(e){return e instanceof b&&e.response.status===404}function Qr(e){return e instanceof b&&e.response.status===410&&e.json?.error?.code===`snapshot_not_found`}function $r(e){return e instanceof b&&e.response.status===422&&e.json?.error?.code===`sandbox_stopping`}function ei(e){return e instanceof b&&e.response.status===422&&e.json?.error?.code===`sandbox_snapshotting`}var ti=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await xr();return this._client=new nr({teamId:e.teamId,token:e.token}),this._client}get name(){return this.sandbox.name}get routes(){return this.currentSession().routes}get persistent(){return this.sandbox.persistent}get region(){return this.sandbox.region}get vcpus(){return this.sandbox.vcpus}get memory(){return this.sandbox.memory}get runtime(){return this.sandbox.runtime}get totalEgressBytes(){return this.sandbox.totalEgressBytes}get totalIngressBytes(){return this.sandbox.totalIngressBytes}get totalActiveCpuDurationMs(){return this.sandbox.totalActiveCpuDurationMs}get totalDurationMs(){return this.sandbox.totalDurationMs}get updatedAt(){return new Date(this.sandbox.updatedAt)}get statusUpdatedAt(){return this.sandbox.statusUpdatedAt?new Date(this.sandbox.statusUpdatedAt):void 0}get createdAt(){return new Date(this.sandbox.createdAt)}get interactivePort(){return this.currentSession().interactivePort}get status(){return this.currentSession().status}get timeout(){return this.sandbox.timeout}get tags(){return this.sandbox.tags}get networkPolicy(){return this.sandbox.networkPolicy?zn(this.sandbox.networkPolicy):void 0}get sourceSnapshotId(){return this.currentSession().sourceSnapshotId}get currentSnapshotId(){return this.sandbox.currentSnapshotId}get snapshotExpiration(){return this.sandbox.snapshotExpiration}get keepLastSnapshots(){return this.sandbox.keepLastSnapshots}get activeCpuUsageMs(){return this.currentSession().activeCpuUsageMs}get networkTransfer(){return this.currentSession().networkTransfer}static async list(e){"use step";let t=await xr(e),n=new nr({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSandboxes({...t,...e,...r!==void 0&&{cursor:r}})).json;return kr(await r(e?.cursor),{itemsKey:`sandboxes`,fetchNext:r,signal:e?.signal})}static[t](e){return{metadata:e.session?._sessionSnapshot,routes:e.session?.routes??[],sandboxMetadata:e.sandbox,projectId:e.projectId}}static[i](t){let n=new e({sandbox:t.sandboxMetadata,routes:t.routes,projectId:t.projectId});return t.metadata&&(n.session=new Nr({routes:t.routes,snapshot:t.metadata})),n}static async create(e){"use step";let t=await xr(e),n=new nr({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=Bn(e),i=await n.createSandbox({source:e?.source,projectId:t.projectId,ports:e?.ports??[],timeout:e?.timeout,resources:e?.resources,runtime:e&&`runtime`in e?e?.runtime:void 0,networkPolicy:e?.networkPolicy,env:e?.env,tags:e?.tags,snapshotExpiration:e?.snapshotExpiration,keepLastSnapshots:e?.keepLastSnapshots,signal:e?.signal,name:e?.name,persistent:e?.persistent,...r});return new ni({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e?.onResume})}static async fork(t){"use step";let{sourceSandbox:n,...r}=t,i=t,a=await e.get({token:i.token,projectId:i.projectId,teamId:i.teamId,fetch:t.fetch,signal:t.signal,...Bn(t),name:n,resume:!1}),o=a.routes.filter(e=>e.port!==a.interactivePort).map(e=>e.port),s={...a.vcpus!==void 0&&{resources:{vcpus:a.vcpus}},...a.timeout!==void 0&&{timeout:a.timeout},...a.networkPolicy!==void 0&&{networkPolicy:a.networkPolicy},...a.tags!==void 0&&{tags:a.tags},...o.length>0&&{ports:o},persistent:a.persistent,...a.snapshotExpiration!==void 0&&{snapshotExpiration:a.snapshotExpiration},...a.keepLastSnapshots!==void 0&&{keepLastSnapshots:a.keepLastSnapshots}},c=a.currentSnapshotId;return c?e.create({...s,...r,source:{type:`snapshot`,snapshotId:c}}):e.create({...s,...a.runtime!==void 0&&{runtime:a.runtime},...r})}static async get(t){"use step";let n=await xr(t),r=new nr({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=Bn(t),a=await r.getSandbox({name:t.name,projectId:n.projectId,resume:t.resume,signal:t.signal,...i}),o=new e({client:r,session:a.json.session,sandbox:a.json.sandbox,routes:a.json.routes,projectId:n.projectId,onResume:t.onResume});return a.json.resumed&&t.onResume&&await t.onResume(o),o}static async getOrCreate(t){"use step";if(!t?.name){let n=await e.create(t);return t?.onCreate&&await t.onCreate(n),n}try{return await e.get(t)}catch(n){if(Zr(n)){let n=await e.create(t);return t.onCreate&&await t.onCreate(n),n}if(Qr(n)){let n=await xr(t),r=new nr({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=Bn(t);try{await r.deleteSandbox({name:t.name,projectId:n.projectId,signal:t.signal,...i})}catch(e){if(!Zr(e))throw e}let a=await e.create(t);return t.onCreate&&await t.onCreate(a),a}throw n}}constructor({client:e,routes:t,session:n,sandbox:r,projectId:i,onResume:a}){this._client=null,this.resumePromise=null,this._client=e??null,n&&(this.session=new Nr({client:e,routes:t,session:n})),this.sandbox=r,this.projectId=i??``,this.onResume=a,this.fs=new Yr(this)}currentSession(){if(!this.session)throw Error(`No active session. Run a command or call resume first.`);return this.session}async resume(e){return this.resumePromise||=this.doResume(e).finally(()=>{this.resumePromise=null}),this.resumePromise}async doResume(e){let t=await this.ensureClient(),n=await t.getSandbox({name:this.sandbox.name,projectId:this.projectId,resume:!0,signal:e});this.session=new Nr({client:t,routes:n.json.routes,session:n.json.session}),this.onResume&&n.json.resumed&&await this.onResume(this)}async waitForStopAndResume(e){"use step";let t=await this.ensureClient(),n=this.session.status;for(;n===`stopping`||n===`snapshotting`;){await h(500,void 0,{signal:e});let r=await t.getSession({sessionId:this.session.sessionId,signal:e});this.session=new Nr({client:t,routes:r.json.routes,session:r.json.session}),n=r.json.session.status}await this.resume(e)}async withResume(e,t){this.session||await this.resume(t);try{return await e()}catch(n){if(Xr(n))return await this.resume(t),e();if($r(n)||ei(n))return await this.waitForStopAndResume(t),e();throw n}}async runCommand(e,t,n){"use step";let r=typeof e==`string`?n?.signal:e.signal;return this.withResume(()=>this.session.runCommand(e,t,n),r)}async getCommand(e,t){"use step";return this.withResume(()=>this.session.getCommand(e,t),t?.signal)}async mkDir(e,t){"use step";return this.withResume(()=>this.session.mkDir(e,t),t?.signal)}async readFile(e,t){"use step";return this.withResume(()=>this.session.readFile(e,t),t?.signal)}async readFileToBuffer(e,t){"use step";return this.withResume(()=>this.session.readFileToBuffer(e,t),t?.signal)}async downloadFile(e,t,n){"use step";return this.withResume(()=>this.session.downloadFile(e,t,n),n?.signal)}async writeFiles(e,t){"use step";return this.withResume(()=>this.session.writeFiles(e,t),t?.signal)}domain(e){return this.currentSession().domain(e)}async stop(e){"use step";if(!this.session)throw Error(`No active session to stop.`);let{session:t,sandbox:n,snapshot:r}=await this.session.stop(e);return n&&(this.sandbox=n),Object.assign(t,{snapshot:r})}async updateNetworkPolicy(e,t){"use step";return await this.withResume(()=>this.session.update({networkPolicy:e},t),t?.signal),this.session.networkPolicy}async extendTimeout(e,t){"use step";return this.withResume(()=>this.session.extendTimeout(e,t),t?.signal)}async snapshot(e){"use step";return this.withResume(()=>this.session.snapshot(e),e?.signal)}async update(e,t){"use step";let n=await this.ensureClient(),r;e.resources?.vcpus&&(r={vcpus:e.resources.vcpus,memory:e.resources.vcpus*2048});let i=await n.updateSandbox({name:this.sandbox.name,projectId:this.projectId,persistent:e.persistent,resources:r,timeout:e.timeout,networkPolicy:e.networkPolicy,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,signal:t?.signal});if(this.sandbox=i.json.sandbox,e.ports!==void 0&&i.json.routes&&this.session?.updateRoutes(i.json.routes),e.networkPolicy)try{return await this.session?.update({networkPolicy:e.networkPolicy},t)}catch(e){if(Xr(e)||$r(e))return;throw e}}async delete(e){"use step";await(await this.ensureClient()).deleteSandbox({name:this.sandbox.name,projectId:this.projectId,signal:e?.signal})}async listSessions(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSessions({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return kr(await n(e?.cursor),{itemsKey:`sessions`,fetchNext:n,signal:e?.signal})}async listSnapshots(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSnapshots({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return kr(await n(e?.cursor),{itemsKey:`snapshots`,fetchNext:n,signal:e?.signal})}},ni=class extends ti{async[Symbol.asyncDispose](){await this.stop()}};const ri=new TextEncoder,ii=new TextDecoder;function ai(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function oi(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function si(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function ci(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:ii.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=ii.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return si(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}const li=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),ui=(e,t)=>e.name===t;function di(e){return parseInt(e.name.slice(4),10)}function fi(e,t){if(di(e.hash)!==t)throw li(`SHA-${t}`,`algorithm.hash`)}function pi(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function mi(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function hi(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!ui(e.algorithm,`HMAC`))throw li(`HMAC`);fi(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!ui(e.algorithm,`RSASSA-PKCS1-v1_5`))throw li(`RSASSA-PKCS1-v1_5`);fi(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!ui(e.algorithm,`RSA-PSS`))throw li(`RSA-PSS`);fi(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!ui(e.algorithm,`Ed25519`))throw li(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!ui(e.algorithm,t))throw li(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!ui(e.algorithm,`ECDSA`))throw li(`ECDSA`);let n=pi(t);if(e.algorithm.namedCurve!==n)throw li(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}mi(e,n)}function gi(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const _i=(e,...t)=>gi(`Key must be `,e,...t),vi=(e,t,...n)=>gi(`Key for the ${e} algorithm must be `,t,...n);var yi=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},bi=class extends yi{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},xi=class extends yi{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},Si=class extends yi{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},Ci=class extends yi{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},wi=class extends yi{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},Ti=class extends yi{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},Ei=class extends yi{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},Di=class extends yi{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},Oi=class extends yi{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},ki=class extends yi{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},Ai=class extends yi{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};const ji=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Mi=e=>e?.[Symbol.toStringTag]===`KeyObject`,Ni=e=>ji(e)||Mi(e);function Pi(e,t,n){try{return ci(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}const Fi=e=>typeof e==`object`&&!!e;function Ii(e){if(!Fi(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Li(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const Ri=e=>Ii(e)&&typeof e.kty==`string`,zi=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),Bi=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,Vi=e=>e.kty===`oct`&&typeof e.k==`string`;function Hi(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Ui(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new Ci(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Wi(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(_i(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return hi(t,e,n),t}async function Gi(e,t,n,r){let i=await Wi(e,t,`verify`);Hi(e,i);let a=Ui(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const Ki=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function qi(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new Ci(Ki)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new Ci(Ki)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new Ci(Ki)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new Ci(Ki)}break;default:throw new Ci(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function Ji(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=qi(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const Yi=`given KeyObject instance cannot be used for this algorithm`;let Xi;const Zi=async(e,t,n,r=!1)=>{Xi||=new WeakMap;let i=Xi.get(e);if(i?.[n])return i[n];let a=await Ji({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:Xi.set(e,{[n]:a}),a},Qi=(e,t)=>{Xi||=new WeakMap;let n=Xi.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(Yi)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(Yi);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(Yi);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(Yi)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(Yi);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(Yi);return n?n[t]=a:Xi.set(e,{[t]:a}),a};async function $i(e,t){if(e instanceof Uint8Array||ji(e))return e;if(Mi(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return Qi(e,t)}catch(e){if(e instanceof TypeError)throw e}return Zi(e,e.export({format:`jwk`}),t)}if(Ri(e))return e.k?ci(e.k):Zi(e,e,t,!0);throw Error(`unreachable`)}async function ea(e,t,n){if(!Ii(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return ci(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new Ci(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return Ji({...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return Ji({...e,ext:r});case`EC`:case`OKP`:return Ji({...e,alg:t,ext:r});default:throw new Ci(`Unsupported "kty" (Key Type) Parameter value`)}}function ta(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new Ci(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}function na(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}const ra=e=>e?.[Symbol.toStringTag],ia=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`;break}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):r=n;break;case e.startsWith(`PBES2`):r=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):r=`wrapKey`;break;case n===`decrypt`:r=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`;break}if(r&&t.key_ops?.includes?.(r)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},aa=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(Ri(t)){if(Vi(t)&&ia(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!Ni(t))throw TypeError(vi(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${ra(t)} instances for symmetric algorithms must be of type "secret"`)}},oa=(e,t,n)=>{if(Ri(t))switch(n){case`decrypt`:case`sign`:if(zi(t)&&ia(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(Bi(t)&&ia(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!Ni(t))throw TypeError(vi(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${ra(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${ra(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${ra(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${ra(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${ra(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function sa(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:aa(e,t,n);break;default:oa(e,t,n)}}async function ca(e,t,n){if(!Ii(e))throw new wi(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new wi(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new wi(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new wi(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new wi(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!Ii(e.header))throw new wi(`JWS Unprotected Header incorrect type`);let r={};if(e.protected)try{let t=ci(e.protected);r=JSON.parse(ii.decode(t))}catch{throw new wi(`JWS Protected Header is invalid`)}if(!Li(r,e.header))throw new wi(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...r,...e.header},a=ta(wi,new Map([[`b64`,!0]]),n?.crit,r,i),o=!0;if(a.has(`b64`)&&(o=r.b64,typeof o!=`boolean`))throw new wi(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new wi(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=n&&na(`algorithms`,n.algorithms);if(c&&!c.has(s))throw new Si(`"alg" (Algorithm) Header Parameter value not allowed`);if(o){if(typeof e.payload!=`string`)throw new wi(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new wi(`JWS Payload must be a string or an Uint8Array instance`);let l=!1;typeof t==`function`&&(t=await t(r,e),l=!0),sa(s,t,`verify`);let u=ai(e.protected===void 0?new Uint8Array:oi(e.protected),oi(`.`),typeof e.payload==`string`?o?oi(e.payload):ri.encode(e.payload):e.payload),d=Pi(e.signature,`signature`,wi),f=await $i(t,s);if(!await Gi(s,f,d,u))throw new Ai;let p;p=o?Pi(e.payload,`payload`,wi):typeof e.payload==`string`?ri.encode(e.payload):e.payload;let m={payload:p};return e.protected!==void 0&&(m.protectedHeader=r),e.header!==void 0&&(m.unprotectedHeader=e.header),l?{...m,key:f}:m}async function la(e,t,n){if(e instanceof Uint8Array&&(e=ii.decode(e)),typeof e!=`string`)throw new wi(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new wi(`Invalid Compact JWS`);let s=await ca({payload:i,protected:r,signature:a},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t==`function`?{...c,key:s.key}:c}const ua=e=>Math.floor(e.getTime()/1e3),da=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function fa(e){let t=da.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*3600);break;case`day`:case`days`:case`d`:i=Math.round(n*86400);break;case`week`:case`weeks`:case`w`:i=Math.round(n*604800);break;default:i=Math.round(n*31557600);break}return t[1]===`-`||t[4]===`ago`?-i:i}const pa=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,ma=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function ha(e,t,n={}){let r;try{r=JSON.parse(ii.decode(t))}catch{}if(!Ii(r))throw new Ti(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i&&(typeof e.typ!=`string`||pa(e.typ)!==pa(i)))throw new bi(`unexpected "typ" JWT header value`,r,`typ`,`check_failed`);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!(e in r))throw new bi(`missing required "${e}" claim`,r,e,`missing`);if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new bi(`unexpected "iss" claim value`,r,`iss`,`check_failed`);if(s&&r.sub!==s)throw new bi(`unexpected "sub" claim value`,r,`sub`,`check_failed`);if(c&&!ma(r.aud,typeof c==`string`?[c]:c))throw new bi(`unexpected "aud" claim value`,r,`aud`,`check_failed`);let d;switch(typeof n.clockTolerance){case`string`:d=fa(n.clockTolerance);break;case`number`:d=n.clockTolerance;break;case`undefined`:d=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:f}=n,p=ua(f||new Date);if((r.iat!==void 0||l)&&typeof r.iat!=`number`)throw new bi(`"iat" claim must be a number`,r,`iat`,`invalid`);if(r.nbf!==void 0){if(typeof r.nbf!=`number`)throw new bi(`"nbf" claim must be a number`,r,`nbf`,`invalid`);if(r.nbf>p+d)throw new bi(`"nbf" claim timestamp check failed`,r,`nbf`,`check_failed`)}if(r.exp!==void 0){if(typeof r.exp!=`number`)throw new bi(`"exp" claim must be a number`,r,`exp`,`invalid`);if(r.exp<=p-d)throw new xi(`"exp" claim timestamp check failed`,r,`exp`,`check_failed`)}if(l){let e=p-r.iat,t=typeof l==`number`?l:fa(l);if(e-d>t)throw new xi(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,`check_failed`);if(e<0-d)throw new bi(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,`check_failed`)}return r}async function ga(e,t,n){let r=await la(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new Ti(`JWTs MUST NOT use unencoded payload`);let i={payload:ha(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}function _a(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new Ci(`Unsupported "alg" value for a JSON Web Key Set`)}}function va(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(ya)}function ya(e){return Ii(e)}var ba=class{#e;#t=new WeakMap;constructor(e){if(!va(e))throw new Ei(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=_a(n),a=this.#e.keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),t&&(typeof e.alg==`string`||i===`AKP`)&&(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`;break}return t}),{0:o,length:s}=a;if(s===0)throw new Di;if(s!==1){let e=new Oi,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await xa(t,e,n)}catch{}},e}return xa(this.#t,o,n)}};async function xa(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await ea({...t,ext:!0},n);if(e instanceof Uint8Array||e.type!==`public`)throw new Ei(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function Sa(e){let t=new ba(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}function Ca(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let wa;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(wa=`jose/v6.2.3`);const Ta=Symbol();async function Ea(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new ki:e});if(i.status!==200)throw new yi(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new yi(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const Da=Symbol();function Oa(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!Ii(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Ii))}var ka=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3,this.#n=typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4,this.#r=typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5,this.#o=new Headers(t?.headers),wa&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,wa),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=t?.[Ta],t?.[Da]!==void 0&&(this.#l=t?.[Da],Oa(t?.[Da],this.#r)&&(this.#i=this.#l.uat,this.#c=Sa(this.#l.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i==`number`?Date.now()<this.#i+this.#n:!1}fresh(){return typeof this.#i==`number`?Date.now()<this.#i+this.#r:!1}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof Di&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&Ca()&&(this.#a=void 0),this.#a||=Ea(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=Sa(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now(),this.#a=void 0}).catch(e=>{throw this.#a=void 0,e}),await this.#a}};function Aa(e,t){let n=new ka(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}function ja(e){if(typeof e!=`string`)throw new Ti(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Ti(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Ti(`Invalid JWT`);if(!t)throw new Ti(`JWTs must contain a payload`);let r;try{r=ci(t)}catch{throw new Ti(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(ii.decode(r))}catch{throw new Ti(`Failed to parse the decoded payload as JSON`)}if(!Ii(i))throw new Ti(`Invalid JWT Claims Set`);return i}const Ma=`vercel-forwarded-host`,Na=`vercel-forwarded-scheme`,Pa=`vercel-forwarded-port`,Fa=`vercel-forwarded-path`,Ia=`vercel-sandbox-oidc-token`,La=new Map;function Ra(e,t=za){return async function(n){let r=new Headers(n.headers),i=r.get(Ma),a=r.get(Na),o=r.get(Pa),s=r.get(Fa),c=r.get(Ia);if(r.delete(Ma),r.delete(Na),r.delete(Pa),r.delete(Fa),r.delete(Ia),!i||!a||!o||!s||!c)return t(n,Error(`Missing required proxy headers`));let l;try{l=new Request(Ba(a,i,o,s),{method:n.method,body:n.body,headers:r,duplex:`half`})}catch{return t(new Request(n,{headers:r}),Error(`Invalid proxied request URL`))}l.headers.set(`host`,i);try{let t=Va(new URL(n.url),s),r=await Wa(c,t),i=Ua(t.host,r);return e(l,i)}catch(e){return t(l,e instanceof Error?e:Error(`Invalid OIDC token`))}}}function za(){return new Response(`Forbidden`,{status:403})}function Ba(e,t,n,r){let i=`${e}://${t}:${n}`;return r===`/`?i:`${i}${r}`}function Va(e,t){let n=Ha(new URL(t,e.origin).pathname),r=new URL(e);return r.pathname=Ha(r.pathname),n!==`/`&&r.pathname.endsWith(n)&&(r.pathname=Ha(r.pathname.slice(0,-n.length))),r}function Ha(e){return e.replace(/\/+$/,``)||`/`}function Ua(e,t){let n=qa(t,`team_id`),r=qa(t,`project_id`),i=qa(t,`sandbox_id`),a=qa(t,`sandbox_name`)??i;if(!n||!r||!i||!a)throw Error(`Missing required claims in OIDC token`);return{host:e,teamId:n,projectId:r,sandboxId:i,sandboxName:a}}async function Wa(e,t){let n=qa(ja(e),`iss`);if(!n)throw Error(`Missing OIDC issuer`);let r;try{r=new URL(n)}catch{throw Error(`Invalid OIDC issuer`)}if(r.protocol!==`https:`||r.hostname!==`oidc.vercel.com`)throw Error(`Invalid OIDC issuer`);let{payload:i}=await ga(e,Ka(n),{audience:Ga(t),algorithms:[`RS256`],clockTolerance:60,issuer:n});return i}function Ga(e){let t=Ha(e.pathname);return t===`/`?e.origin:e.origin+t}function Ka(e){let t=La.get(e);if(t)return t;let n=Aa(new URL(`${e.replace(/\/$/,``)}/.well-known/jwks`));return La.set(e,n),n}function qa(e,t){let n=e[t];if(typeof n==`string`&&n)return n}export{b as APIError,Dr as Command,Or as CommandFinished,Yr as FileSystem,ti as Sandbox,Nr as Session,jr as Snapshot,x as StreamError,Ra as defineSandboxProxy,Gn as n,Zn as t};
108
+ `).filter(Boolean)}async stat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-L`,`-c`,qr,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`stat`,e):$(`EACCES`,t.trim(),`stat`,e)}return Gr(await n.stdout())}async lstat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-c`,qr,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`lstat`,e):$(`EACCES`,t.trim(),`lstat`,e)}return Gr(await n.stdout())}async unlink(e,t){"use step";let n=await this.sandbox.runCommand(`rm`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`unlink`,e):$(`EACCES`,t.trim(),`unlink`,e)}}async rm(e,t){"use step";let n=[];t?.recursive&&n.push(`-r`),t?.force&&n.push(`-f`),n.push(e);let r=await this.sandbox.runCommand(`rm`,n,{signal:t?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`rm`,e):$(`EACCES`,t.trim(),`rm`,e)}}async rmdir(e,t){"use step";let n=await this.sandbox.runCommand(`rmdir`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`rmdir`,e):t.includes(`not empty`)?$(`ENOTEMPTY`,`directory not empty`,`rmdir`,e):$(`EACCES`,t.trim(),`rmdir`,e)}}async rename(e,t,n){"use step";let r=await this.sandbox.runCommand(`mv`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`rename`,e):$(`EACCES`,t.trim(),`rename`,e)}}async copyFile(e,t,n){"use step";let r=await this.sandbox.runCommand(`cp`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`copyfile`,e):$(`EACCES`,t.trim(),`copyfile`,e)}}async access(e,t){"use step";if((await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode!==0)throw $(`ENOENT`,`no such file or directory`,`access`,e)}async exists(e,t){return(await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode===0}async chmod(e,t,n){"use step";let r=typeof t==`number`?t.toString(8):t,i=await this.sandbox.runCommand(`chmod`,[r,e],{signal:n?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`chmod`,e):$(`EACCES`,t.trim(),`chmod`,e)}}async chown(e,t,n,r){"use step";let i=await this.sandbox.runCommand(`chown`,[`${t}:${n}`,e],{signal:r?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`chown`,e):$(`EACCES`,t.trim(),`chown`,e)}}async symlink(e,t,n){"use step";let r=await this.sandbox.runCommand(`ln`,[`-s`,e,t],{signal:n?.signal});if(r.exitCode!==0){let e=await r.stderr();throw e.includes(`File exists`)?$(`EEXIST`,`file already exists`,`symlink`,t):$(`EACCES`,e.trim(),`symlink`,t)}}async readlink(e,t){"use step";let n=await this.sandbox.runCommand(`readlink`,[e],{signal:t?.signal});if(n.exitCode!==0)throw(await n.stderr()).includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`readlink`,e):$(`EINVAL`,`invalid argument`,`readlink`,e);return(await n.stdout()).trim()}async realpath(e,t){"use step";let n=await this.sandbox.runCommand(`realpath`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`realpath`,e):$(`EACCES`,t.trim(),`realpath`,e)}return(await n.stdout()).trim()}async truncate(e,t,n){"use step";let r=await this.sandbox.runCommand(`truncate`,[`-s`,String(t??0),e],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?$(`ENOENT`,`no such file or directory`,`truncate`,e):$(`EACCES`,t.trim(),`truncate`,e)}}async mkdtemp(e,t){"use step";let n=await this.sandbox.runCommand(`mktemp`,[`-d`,`${e}XXXXXX`],{signal:t?.signal});if(n.exitCode!==0)throw $(`EACCES`,(await n.stderr()).trim(),`mkdtemp`,e);return(await n.stdout()).trim()}};function Xr(e){return e instanceof b&&e.response.status===410}function Zr(e){return e instanceof b&&e.response.status===404}function Qr(e){return e instanceof b&&e.response.status===410&&e.json?.error?.code===`snapshot_not_found`}function $r(e){return e instanceof b&&e.response.status===422&&e.json?.error?.code===`sandbox_stopping`}function ei(e){return e instanceof b&&e.response.status===422&&e.json?.error?.code===`sandbox_snapshotting`}var ti=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await xr();return this._client=new nr({teamId:e.teamId,token:e.token}),this._client}get name(){return this.sandbox.name}get routes(){return this.currentSession().routes}get persistent(){return this.sandbox.persistent}get region(){return this.sandbox.region}get vcpus(){return this.sandbox.vcpus}get memory(){return this.sandbox.memory}get runtime(){return this.sandbox.runtime}get totalEgressBytes(){return this.sandbox.totalEgressBytes}get totalIngressBytes(){return this.sandbox.totalIngressBytes}get totalActiveCpuDurationMs(){return this.sandbox.totalActiveCpuDurationMs}get totalDurationMs(){return this.sandbox.totalDurationMs}get updatedAt(){return new Date(this.sandbox.updatedAt)}get statusUpdatedAt(){return this.sandbox.statusUpdatedAt?new Date(this.sandbox.statusUpdatedAt):void 0}get createdAt(){return new Date(this.sandbox.createdAt)}get interactivePort(){return this.currentSession().interactivePort}get status(){return this.currentSession().status}get timeout(){return this.sandbox.timeout}get tags(){return this.sandbox.tags}get networkPolicy(){return this.sandbox.networkPolicy?zn(this.sandbox.networkPolicy):void 0}get sourceSnapshotId(){return this.currentSession().sourceSnapshotId}get currentSnapshotId(){return this.sandbox.currentSnapshotId}get snapshotExpiration(){return this.sandbox.snapshotExpiration}get keepLastSnapshots(){return this.sandbox.keepLastSnapshots}get activeCpuUsageMs(){return this.currentSession().activeCpuUsageMs}get networkTransfer(){return this.currentSession().networkTransfer}static async list(e){"use step";let t=await xr(e),n=new nr({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSandboxes({...t,...e,...r!==void 0&&{cursor:r}})).json;return kr(await r(e?.cursor),{itemsKey:`sandboxes`,fetchNext:r,signal:e?.signal})}static[t](e){return{metadata:e.session?._sessionSnapshot,routes:e.session?.routes??[],sandboxMetadata:e.sandbox,projectId:e.projectId}}static[i](t){let n=new e({sandbox:t.sandboxMetadata,routes:t.routes,projectId:t.projectId});return t.metadata&&(n.session=new Nr({routes:t.routes,snapshot:t.metadata})),n}static async create(e){"use step";let t=await xr(e),n=new nr({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=Bn(e),i=await n.createSandbox({source:e?.source,projectId:t.projectId,ports:e?.ports??[],timeout:e?.timeout,resources:e?.resources,runtime:e&&`runtime`in e?e?.runtime:void 0,networkPolicy:e?.networkPolicy,env:e?.env,tags:e?.tags,snapshotExpiration:e?.snapshotExpiration,keepLastSnapshots:e?.keepLastSnapshots,signal:e?.signal,name:e?.name,persistent:e?.persistent,...r});return new ni({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e?.onResume})}static async fork(t){"use step";let{sourceSandbox:n,...r}=t,i=t,a=await e.get({token:i.token,projectId:i.projectId,teamId:i.teamId,fetch:t.fetch,signal:t.signal,...Bn(t),name:n,resume:!1}),o=a.routes.filter(e=>e.port!==a.interactivePort).map(e=>e.port),s={...a.vcpus!==void 0&&{resources:{vcpus:a.vcpus}},...a.timeout!==void 0&&{timeout:a.timeout},...a.networkPolicy!==void 0&&{networkPolicy:a.networkPolicy},...a.tags!==void 0&&{tags:a.tags},...o.length>0&&{ports:o},persistent:a.persistent,...a.snapshotExpiration!==void 0&&{snapshotExpiration:a.snapshotExpiration},...a.keepLastSnapshots!==void 0&&{keepLastSnapshots:a.keepLastSnapshots}},c=a.currentSnapshotId;return c?e.create({...s,...r,source:{type:`snapshot`,snapshotId:c}}):e.create({...s,...a.runtime!==void 0&&{runtime:a.runtime},...r})}static async get(t){"use step";let n=await xr(t),r=new nr({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=Bn(t),a=await r.getSandbox({name:t.name,projectId:n.projectId,resume:t.resume,signal:t.signal,...i}),o=new e({client:r,session:a.json.session,sandbox:a.json.sandbox,routes:a.json.routes,projectId:n.projectId,onResume:t.onResume});return a.json.resumed&&t.onResume&&await t.onResume(o),o}static async getOrCreate(t){"use step";if(!t?.name){let n=await e.create(t);return t?.onCreate&&await t.onCreate(n),n}try{return await e.get(t)}catch(n){if(Zr(n)){let n=await e.create(t);return t.onCreate&&await t.onCreate(n),n}if(Qr(n)){let n=await xr(t),r=new nr({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=Bn(t);try{await r.deleteSandbox({name:t.name,projectId:n.projectId,signal:t.signal,...i})}catch(e){if(!Zr(e))throw e}let a=await e.create(t);return t.onCreate&&await t.onCreate(a),a}throw n}}constructor({client:e,routes:t,session:n,sandbox:r,projectId:i,onResume:a}){this._client=null,this.resumePromise=null,this._client=e??null,n&&(this.session=new Nr({client:e,routes:t,session:n})),this.sandbox=r,this.projectId=i??``,this.onResume=a,this.fs=new Yr(this)}currentSession(){if(!this.session)throw Error(`No active session. Run a command or call resume first.`);return this.session}async resume(e){return this.resumePromise||=this.doResume(e).finally(()=>{this.resumePromise=null}),this.resumePromise}async doResume(e){let t=await this.ensureClient(),n=await t.getSandbox({name:this.sandbox.name,projectId:this.projectId,resume:!0,signal:e});this.session=new Nr({client:t,routes:n.json.routes,session:n.json.session}),this.onResume&&n.json.resumed&&await this.onResume(this)}async waitForStopAndResume(e){"use step";let t=await this.ensureClient(),n=this.session.status;for(;n===`stopping`||n===`snapshotting`;){await h(500,void 0,{signal:e});let r=await t.getSession({sessionId:this.session.sessionId,signal:e});this.session=new Nr({client:t,routes:r.json.routes,session:r.json.session}),n=r.json.session.status}await this.resume(e)}async withResume(e,t){this.session||await this.resume(t);try{return await e()}catch(n){if(Xr(n))return await this.resume(t),e();if($r(n)||ei(n))return await this.waitForStopAndResume(t),e();throw n}}async runCommand(e,t,n){"use step";let r=typeof e==`string`?n?.signal:e.signal;return this.withResume(()=>this.session.runCommand(e,t,n),r)}async getCommand(e,t){"use step";return this.withResume(()=>this.session.getCommand(e,t),t?.signal)}async mkDir(e,t){"use step";return this.withResume(()=>this.session.mkDir(e,t),t?.signal)}async readFile(e,t){"use step";return this.withResume(()=>this.session.readFile(e,t),t?.signal)}async readFileToBuffer(e,t){"use step";return this.withResume(()=>this.session.readFileToBuffer(e,t),t?.signal)}async downloadFile(e,t,n){"use step";return this.withResume(()=>this.session.downloadFile(e,t,n),n?.signal)}async writeFiles(e,t){"use step";return this.withResume(()=>this.session.writeFiles(e,t),t?.signal)}domain(e){return this.currentSession().domain(e)}async stop(e){"use step";if(!this.session)throw Error(`No active session to stop.`);let{session:t,sandbox:n,snapshot:r}=await this.session.stop(e);return n&&(this.sandbox=n),Object.assign(t,{snapshot:r})}async updateNetworkPolicy(e,t){"use step";return await this.withResume(()=>this.session.update({networkPolicy:e},t),t?.signal),this.session.networkPolicy}async extendTimeout(e,t){"use step";return this.withResume(()=>this.session.extendTimeout(e,t),t?.signal)}async snapshot(e){"use step";return this.withResume(()=>this.session.snapshot(e),e?.signal)}async update(e,t){"use step";let n=await this.ensureClient(),r;e.resources?.vcpus&&(r={vcpus:e.resources.vcpus,memory:e.resources.vcpus*2048});let i=await n.updateSandbox({name:this.sandbox.name,projectId:this.projectId,persistent:e.persistent,resources:r,timeout:e.timeout,networkPolicy:e.networkPolicy,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,signal:t?.signal});if(this.sandbox=i.json.sandbox,e.ports!==void 0&&i.json.routes&&this.session?.updateRoutes(i.json.routes),e.networkPolicy)try{return await this.session?.update({networkPolicy:e.networkPolicy},t)}catch(e){if(Xr(e)||$r(e))return;throw e}}async delete(e){"use step";await(await this.ensureClient()).deleteSandbox({name:this.sandbox.name,projectId:this.projectId,signal:e?.signal})}async listSessions(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSessions({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return kr(await n(e?.cursor),{itemsKey:`sessions`,fetchNext:n,signal:e?.signal})}async listSnapshots(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSnapshots({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return kr(await n(e?.cursor),{itemsKey:`snapshots`,fetchNext:n,signal:e?.signal})}},ni=class extends ti{async[Symbol.asyncDispose](){await this.stop()}};const ri=new TextEncoder,ii=new TextDecoder;function ai(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function oi(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function si(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function ci(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:ii.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=ii.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return si(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var li=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},ui=class extends li{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},di=class extends li{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},fi=class extends li{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},pi=class extends li{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},mi=class extends li{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},hi=class extends li{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},gi=class extends li{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},_i=class extends li{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},vi=class extends li{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},yi=class extends li{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},bi=class extends li{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};const xi=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),Si=(e,t)=>e.name===t;function Ci(e){return parseInt(e.name.slice(4),10)}function wi(e,t){if(Ci(e.hash)!==t)throw xi(`SHA-${t}`,`algorithm.hash`)}function Ti(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function Ei(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Di(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!Si(e.algorithm,`HMAC`))throw xi(`HMAC`);wi(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!Si(e.algorithm,`RSASSA-PKCS1-v1_5`))throw xi(`RSASSA-PKCS1-v1_5`);wi(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!Si(e.algorithm,`RSA-PSS`))throw xi(`RSA-PSS`);wi(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!Si(e.algorithm,`Ed25519`))throw xi(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!Si(e.algorithm,t))throw xi(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!Si(e.algorithm,`ECDSA`))throw xi(`ECDSA`);let n=Ti(t);if(e.algorithm.namedCurve!==n)throw xi(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}Ei(e,n)}function Oi(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const ki=(e,...t)=>Oi(`Key must be `,e,...t),Ai=(e,t,...n)=>Oi(`Key for the ${e} algorithm must be `,t,...n);function ji(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Mi(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new pi(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ni(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(ki(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return Di(t,e,n),t}async function Pi(e,t,n,r){let i=await Ni(e,t,`verify`);ji(e,i);let a=Mi(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}function Fi(e,t,n){try{return ci(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}const Ii=e=>typeof e==`object`&&!!e;function Li(e){if(!Ii(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Ri(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const zi=e=>Li(e)&&typeof e.kty==`string`,Bi=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),Vi=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,Hi=e=>e.kty===`oct`&&typeof e.k==`string`,Ui=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Wi=e=>e?.[Symbol.toStringTag]===`KeyObject`,Gi=e=>Ui(e)||Wi(e),Ki=e=>e?.[Symbol.toStringTag],qi=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`;break}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):r=n;break;case e.startsWith(`PBES2`):r=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):r=`wrapKey`;break;case n===`decrypt`:r=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`;break}if(r&&t.key_ops?.includes?.(r)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},Ji=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(zi(t)){if(Hi(t)&&qi(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!Gi(t))throw TypeError(Ai(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${Ki(t)} instances for symmetric algorithms must be of type "secret"`)}},Yi=(e,t,n)=>{if(zi(t))switch(n){case`decrypt`:case`sign`:if(Bi(t)&&qi(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(Vi(t)&&qi(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!Gi(t))throw TypeError(Ai(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${Ki(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${Ki(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${Ki(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${Ki(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${Ki(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Xi(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:Ji(e,t,n);break;default:Yi(e,t,n)}}function Zi(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new pi(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}function Qi(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}const $i=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function ea(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new pi($i)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new pi($i)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new pi($i)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new pi($i)}break;default:throw new pi(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function ta(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=ea(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const na=`given KeyObject instance cannot be used for this algorithm`;let ra;const ia=async(e,t,n,r=!1)=>{ra||=new WeakMap;let i=ra.get(e);if(i?.[n])return i[n];let a=await ta({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:ra.set(e,{[n]:a}),a},aa=(e,t)=>{ra||=new WeakMap;let n=ra.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(na)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(na);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(na);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(na)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(na);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(na);return n?n[t]=a:ra.set(e,{[t]:a}),a};async function oa(e,t){if(e instanceof Uint8Array||Ui(e))return e;if(Wi(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return aa(e,t)}catch(e){if(e instanceof TypeError)throw e}return ia(e,e.export({format:`jwk`}),t)}if(zi(e))return e.k?ci(e.k):ia(e,e,t,!0);throw Error(`unreachable`)}async function sa(e,t,n){if(!Li(e))throw new mi(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new mi(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new mi(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new mi(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new mi(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!Li(e.header))throw new mi(`JWS Unprotected Header incorrect type`);let r={};if(e.protected)try{let t=ci(e.protected);r=JSON.parse(ii.decode(t))}catch{throw new mi(`JWS Protected Header is invalid`)}if(!Ri(r,e.header))throw new mi(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...r,...e.header},a=Zi(mi,new Map([[`b64`,!0]]),n?.crit,r,i),o=!0;if(a.has(`b64`)&&(o=r.b64,typeof o!=`boolean`))throw new mi(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new mi(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=n&&Qi(`algorithms`,n.algorithms);if(c&&!c.has(s))throw new fi(`"alg" (Algorithm) Header Parameter value not allowed`);if(o){if(typeof e.payload!=`string`)throw new mi(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new mi(`JWS Payload must be a string or an Uint8Array instance`);let l=!1;typeof t==`function`&&(t=await t(r,e),l=!0),Xi(s,t,`verify`);let u=ai(e.protected===void 0?new Uint8Array:oi(e.protected),oi(`.`),typeof e.payload==`string`?o?oi(e.payload):ri.encode(e.payload):e.payload),d=Fi(e.signature,`signature`,mi),f=await oa(t,s);if(!await Pi(s,f,d,u))throw new bi;let p;p=o?Fi(e.payload,`payload`,mi):typeof e.payload==`string`?ri.encode(e.payload):e.payload;let m={payload:p};return e.protected!==void 0&&(m.protectedHeader=r),e.header!==void 0&&(m.unprotectedHeader=e.header),l?{...m,key:f}:m}async function ca(e,t,n){if(e instanceof Uint8Array&&(e=ii.decode(e)),typeof e!=`string`)throw new mi(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new mi(`Invalid Compact JWS`);let s=await sa({payload:i,protected:r,signature:a},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t==`function`?{...c,key:s.key}:c}const la=e=>Math.floor(e.getTime()/1e3),ua=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function da(e){let t=ua.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*3600);break;case`day`:case`days`:case`d`:i=Math.round(n*86400);break;case`week`:case`weeks`:case`w`:i=Math.round(n*604800);break;default:i=Math.round(n*31557600);break}return t[1]===`-`||t[4]===`ago`?-i:i}const fa=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,pa=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function ma(e,t,n={}){let r;try{r=JSON.parse(ii.decode(t))}catch{}if(!Li(r))throw new hi(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i&&(typeof e.typ!=`string`||fa(e.typ)!==fa(i)))throw new ui(`unexpected "typ" JWT header value`,r,`typ`,`check_failed`);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!(e in r))throw new ui(`missing required "${e}" claim`,r,e,`missing`);if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new ui(`unexpected "iss" claim value`,r,`iss`,`check_failed`);if(s&&r.sub!==s)throw new ui(`unexpected "sub" claim value`,r,`sub`,`check_failed`);if(c&&!pa(r.aud,typeof c==`string`?[c]:c))throw new ui(`unexpected "aud" claim value`,r,`aud`,`check_failed`);let d;switch(typeof n.clockTolerance){case`string`:d=da(n.clockTolerance);break;case`number`:d=n.clockTolerance;break;case`undefined`:d=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:f}=n,p=la(f||new Date);if((r.iat!==void 0||l)&&typeof r.iat!=`number`)throw new ui(`"iat" claim must be a number`,r,`iat`,`invalid`);if(r.nbf!==void 0){if(typeof r.nbf!=`number`)throw new ui(`"nbf" claim must be a number`,r,`nbf`,`invalid`);if(r.nbf>p+d)throw new ui(`"nbf" claim timestamp check failed`,r,`nbf`,`check_failed`)}if(r.exp!==void 0){if(typeof r.exp!=`number`)throw new ui(`"exp" claim must be a number`,r,`exp`,`invalid`);if(r.exp<=p-d)throw new di(`"exp" claim timestamp check failed`,r,`exp`,`check_failed`)}if(l){let e=p-r.iat,t=typeof l==`number`?l:da(l);if(e-d>t)throw new di(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,`check_failed`);if(e<0-d)throw new ui(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,`check_failed`)}return r}async function ha(e,t,n){let r=await ca(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new hi(`JWTs MUST NOT use unencoded payload`);let i={payload:ma(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}async function ga(e,t,n){if(!Li(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return ci(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new pi(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return ta({...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return ta({...e,ext:r});case`EC`:case`OKP`:return ta({...e,alg:t,ext:r});default:throw new pi(`Unsupported "kty" (Key Type) Parameter value`)}}function _a(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new pi(`Unsupported "alg" value for a JSON Web Key Set`)}}function va(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(ya)}function ya(e){return Li(e)}var ba=class{#e;#t=new WeakMap;constructor(e){if(!va(e))throw new gi(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=_a(n),a=this.#e.keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),t&&(typeof e.alg==`string`||i===`AKP`)&&(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`;break}return t}),{0:o,length:s}=a;if(s===0)throw new _i;if(s!==1){let e=new vi,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await xa(t,e,n)}catch{}},e}return xa(this.#t,o,n)}};async function xa(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await ga({...t,ext:!0},n);if(e instanceof Uint8Array||e.type!==`public`)throw new gi(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function Sa(e){let t=new ba(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}function Ca(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let wa;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(wa=`jose/v6.2.3`);const Ta=Symbol();async function Ea(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new yi:e});if(i.status!==200)throw new li(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new li(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const Da=Symbol();function Oa(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!Li(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Li))}var ka=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3,this.#n=typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4,this.#r=typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5,this.#o=new Headers(t?.headers),wa&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,wa),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=t?.[Ta],t?.[Da]!==void 0&&(this.#l=t?.[Da],Oa(t?.[Da],this.#r)&&(this.#i=this.#l.uat,this.#c=Sa(this.#l.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i==`number`?Date.now()<this.#i+this.#n:!1}fresh(){return typeof this.#i==`number`?Date.now()<this.#i+this.#r:!1}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof _i&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&Ca()&&(this.#a=void 0),this.#a||=Ea(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=Sa(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now(),this.#a=void 0}).catch(e=>{throw this.#a=void 0,e}),await this.#a}};function Aa(e,t){let n=new ka(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}function ja(e){if(typeof e!=`string`)throw new hi(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new hi(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new hi(`Invalid JWT`);if(!t)throw new hi(`JWTs must contain a payload`);let r;try{r=ci(t)}catch{throw new hi(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(ii.decode(r))}catch{throw new hi(`Failed to parse the decoded payload as JSON`)}if(!Li(i))throw new hi(`Invalid JWT Claims Set`);return i}const Ma=`vercel-forwarded-host`,Na=`vercel-forwarded-scheme`,Pa=`vercel-forwarded-port`,Fa=`vercel-forwarded-path`,Ia=`vercel-sandbox-oidc-token`,La=new Map;function Ra(e,t=za){return async function(n){let r=new Headers(n.headers),i=r.get(Ma),a=r.get(Na),o=r.get(Pa),s=r.get(Fa),c=r.get(Ia);if(r.delete(Ma),r.delete(Na),r.delete(Pa),r.delete(Fa),r.delete(Ia),!i||!a||!o||!s||!c)return t(n,Error(`Missing required proxy headers`));let l;try{l=new Request(Ba(a,i,o,s),{method:n.method,body:n.body,headers:r,duplex:`half`})}catch{return t(new Request(n,{headers:r}),Error(`Invalid proxied request URL`))}l.headers.set(`host`,i);try{let t=Va(new URL(n.url),s),r=await Wa(c,t),i=Ua(t.host,r);return e(l,i)}catch(e){return t(l,e instanceof Error?e:Error(`Invalid OIDC token`))}}}function za(){return new Response(`Forbidden`,{status:403})}function Ba(e,t,n,r){let i=`${e}://${t}:${n}`;return r===`/`?i:`${i}${r}`}function Va(e,t){let n=Ha(new URL(t,e.origin).pathname),r=new URL(e);return r.pathname=Ha(r.pathname),n!==`/`&&r.pathname.endsWith(n)&&(r.pathname=Ha(r.pathname.slice(0,-n.length))),r}function Ha(e){return e.replace(/\/+$/,``)||`/`}function Ua(e,t){let n=qa(t,`team_id`),r=qa(t,`project_id`),i=qa(t,`sandbox_id`),a=qa(t,`sandbox_name`)??i;if(!n||!r||!i||!a)throw Error(`Missing required claims in OIDC token`);return{host:e,teamId:n,projectId:r,sandboxId:i,sandboxName:a}}async function Wa(e,t){let n=qa(ja(e),`iss`);if(!n)throw Error(`Missing OIDC issuer`);let r;try{r=new URL(n)}catch{throw Error(`Invalid OIDC issuer`)}if(r.protocol!==`https:`||r.hostname!==`oidc.vercel.com`)throw Error(`Invalid OIDC issuer`);let{payload:i}=await ha(e,Ka(n),{audience:Ga(t),algorithms:[`RS256`],clockTolerance:60,issuer:n});return i}function Ga(e){let t=Ha(e.pathname);return t===`/`?e.origin:e.origin+t}function Ka(e){let t=La.get(e);if(t)return t;let n=Aa(new URL(`${e.replace(/\/$/,``)}/.well-known/jwks`));return La.set(e,n),n}function qa(e,t){let n=e[t];if(typeof n==`string`&&n)return n}export{b as APIError,Dr as Command,Or as CommandFinished,Yr as FileSystem,ti as Sandbox,Nr as Session,jr as Snapshot,x as StreamError,Ra as defineSandboxProxy,Gn as n,Zn as t};
@@ -15,11 +15,19 @@
15
15
  * `@workflow/core` version that supports it
16
16
  * 3. The `getRunCapabilities()` function will automatically include it
17
17
  *
18
+ * ## Adding a new non-format capability
19
+ *
20
+ * Some capabilities aren't serialization format prefixes — e.g.
21
+ * byte-stream wire framing is an envelope around chunks rather than
22
+ * a content format. For those, add a boolean field to `RunCapabilities`
23
+ * and an entry in `CAPABILITY_VERSION_TABLE` below.
24
+ *
18
25
  * ## History
19
26
  *
20
27
  * - `encr` (AES-256-GCM encryption): added in `4.2.0-beta.64`
21
28
  * Commit: 7618ac36 "Wire AES-GCM encryption into serialization layer (#1251)"
22
29
  * https://github.com/vercel/workflow/commit/7618ac36
30
+ * - `framedByteStreams` (wire-level chunk framing for byte streams): added in `5.0.0-beta.15`
23
31
  */
24
32
  import { type SerializationFormatType } from './serialization.js';
25
33
  /**
@@ -32,6 +40,15 @@ export interface RunCapabilities {
32
40
  * if encryption is supported, etc.
33
41
  */
34
42
  supportedFormats: ReadonlySet<SerializationFormatType>;
43
+ /**
44
+ * Whether the target run can decode wire-framed byte streams. When true,
45
+ * byte streams (`type: 'bytes'` ReadableStreams passed across boundaries)
46
+ * are wrapped in a length-prefixed frame envelope on the wire so the
47
+ * reader can identify chunk boundaries — which enables auto-reconnect
48
+ * on transient stream errors. When false, byte streams are written as
49
+ * raw bytes (the legacy format) for compatibility with older runs.
50
+ */
51
+ framedByteStreams: boolean;
35
52
  }
36
53
  /**
37
54
  * Look up what serialization capabilities a workflow run supports based on
@@ -39,7 +56,8 @@ export interface RunCapabilities {
39
56
  *
40
57
  * When the version is `undefined`, not a string, or not a valid semver string
41
58
  * (e.g. very old runs that predate the field, or corrupted metadata),
42
- * we assume the most conservative capabilities (baseline formats only).
59
+ * we assume the most conservative capabilities (baseline formats only,
60
+ * non-format capabilities all `false`).
43
61
  */
44
62
  export declare function getRunCapabilities(workflowCoreVersion: string | undefined): RunCapabilities;
45
63
  //# sourceMappingURL=capabilities.d.ts.map
@@ -18,6 +18,38 @@
18
18
  * when serializing instances (e.g., step return values).
19
19
  */
20
20
  export declare function registerSerializationClass(classId: string, cls: Function): void;
21
+ /**
22
+ * Stable, well-known registry id for the SDK's `Run` class.
23
+ *
24
+ * The SWC plugin auto-registers `Run` under a *path-derived* id (e.g.
25
+ * `class//./node_modules/@workflow/core/dist/runtime/run//Run`), which
26
+ * varies with the app's dependency layout and bundler. Host-side code
27
+ * that needs to construct `Run` instances inside the workflow VM (e.g.
28
+ * the hook event consumer resolving `hook.getConflict()`) cannot know
29
+ * that id statically, so the workflow-mode `create-hook` module also
30
+ * aliases the bundle's `Run` under this stable id at evaluation time.
31
+ *
32
+ * The `workflow` pseudo-path cannot collide with plugin-derived ids,
33
+ * which always use real relative module paths (`./…` / `../…`).
34
+ */
35
+ export declare const RUN_CLASS_ID = "class//workflow//Run";
36
+ /**
37
+ * Register an additional registry id for a class without touching its
38
+ * `classId` property.
39
+ *
40
+ * Unlike {@link registerSerializationClass}, this is safe to call for a
41
+ * class the SWC plugin has already registered: the plugin's inlined IIFE
42
+ * defines `classId` as non-configurable, so a second `defineProperty`
43
+ * would throw. Aliasing only adds a registry entry — the class keeps
44
+ * serializing under its primary (path-derived) id, while lookups succeed
45
+ * under both.
46
+ *
47
+ * Registration is per-global by construction: evaluated inside the
48
+ * workflow VM it registers the VM's compiled class on the VM's registry;
49
+ * evaluated on the host it registers the host class on the host's
50
+ * registry. Each context resolves its own correct variant.
51
+ */
52
+ export declare function aliasSerializationClass(classId: string, cls: Function, global?: Record<string, any>): void;
21
53
  /**
22
54
  * Find a registered class constructor by ID (used during deserialization)
23
55
  *
@@ -1,3 +1,4 @@
1
+ import type { Run } from './runtime/run.js';
1
2
  import type { Serializable } from './schemas.js';
2
3
  /**
3
4
  * An object that can be awaited to receive a value.
@@ -24,6 +25,42 @@ export interface Hook<T = any> extends AsyncIterable<T>, Thenable<T> {
24
25
  * The token used to identify this hook.
25
26
  */
26
27
  token: string;
28
+ /**
29
+ * Returns a promise that resolves with the conflicting {@link Run} if
30
+ * another active hook already owns this hook's token, or `null` once
31
+ * the hook has been registered and is ready to receive payloads.
32
+ *
33
+ * Calling `createHook()` alone does not register the hook — registration
34
+ * only happens when the workflow suspends. Awaiting `getConflict()`
35
+ * suspends the workflow to commit the hook registration, so it can be
36
+ * used to claim the token (and detect token conflicts early) without
37
+ * waiting for payload data.
38
+ *
39
+ * When a conflict is detected, the resolved `Run` is the run that
40
+ * currently owns the token. The workflow can decide how to handle the
41
+ * duplicate in code: return or log `conflict.runId`, inspect
42
+ * `await conflict.status`, await `conflict.returnValue`, or cancel the
43
+ * owner with `await conflict.cancel()` and continue in the current run.
44
+ *
45
+ * Note that awaiting the hook's payload (`await hook`) when the token is
46
+ * already owned by another active hook still rejects with
47
+ * `HookConflictError`. In the rare case where the conflicting run cannot
48
+ * be identified (a `hook_conflict` event persisted by an old world that
49
+ * did not record the owning run's ID), `getConflict()` also rejects with
50
+ * `HookConflictError` rather than resolving with an incomplete value.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * using hook = createHook({ token: `order:${orderId}` });
55
+ * const conflict = await hook.getConflict();
56
+ * if (conflict) {
57
+ * // another run already owns this token
58
+ * return { dedupedTo: conflict.runId };
59
+ * }
60
+ * // token is now claimed, without waiting for payload data
61
+ * ```
62
+ */
63
+ getConflict(): Promise<Run<unknown> | null>;
27
64
  /**
28
65
  * Disposes the hook, releasing its token for reuse by other workflows.
29
66
  *