eve 0.89.0 → 0.91.0

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 (247) hide show
  1. package/CHANGELOG.md +39 -9
  2. package/dist/src/channel/adapter.d.ts +12 -3
  3. package/dist/src/channel/adapter.js +1 -1
  4. package/dist/src/channel/auth/definitions.d.ts +7 -20
  5. package/dist/src/channel/auth/definitions.js +1 -1
  6. package/dist/src/channel/auth/http-basic.js +1 -1
  7. package/dist/src/channel/auth/jwt-ecdsa.js +1 -1
  8. package/dist/src/channel/auth/jwt-hmac.js +1 -1
  9. package/dist/src/channel/auth/oidc.js +1 -1
  10. package/dist/src/channel/auth/result.d.ts +2 -3
  11. package/dist/src/channel/auth/result.js +1 -1
  12. package/dist/src/channel/channel-address.d.ts +1 -1
  13. package/dist/src/channel/channel-address.js +1 -1
  14. package/dist/src/channel/channel-operations.d.ts +1 -1
  15. package/dist/src/channel/schedule.js +1 -1
  16. package/dist/src/channel/types.d.ts +2 -0
  17. package/dist/src/chunks/{use-eve-agent-Bbl4H5aA.js → use-eve-agent-Bwloorf8.js} +77 -63
  18. package/dist/src/chunks/{use-eve-agent-CNpxgKEH.js → use-eve-agent-XCB0-tLX.js} +77 -63
  19. package/dist/src/cli/dev/environment.js +1 -1
  20. package/dist/src/cli/dev/tui/prompt-commands.d.ts +1 -1
  21. package/dist/src/cli/dev/tui/remote-connection-probe.js +1 -1
  22. package/dist/src/cli/dev/tui/remote-connection-types.d.ts +1 -0
  23. package/dist/src/cli/dev/tui/runner.js +2 -2
  24. package/dist/src/cli/dev/tui/status-line.d.ts +2 -2
  25. package/dist/src/cli/dev/tui/status-line.js +1 -1
  26. package/dist/src/client/agent-info-schema.d.ts +341 -326
  27. package/dist/src/client/agent-info-schema.js +1 -1
  28. package/dist/src/client/agent-info-types.d.ts +13 -10
  29. package/dist/src/client/client-error.d.ts +1 -1
  30. package/dist/src/client/client.d.ts +5 -3
  31. package/dist/src/client/client.js +1 -1
  32. package/dist/src/client/session.d.ts +1 -1
  33. package/dist/src/compiled/.vendor-stamp.json +1 -1
  34. package/dist/src/evals/target.js +1 -1
  35. package/dist/src/eve-channel/auth.d.ts +19 -0
  36. package/dist/src/eve-channel/auth.js +1 -0
  37. package/dist/src/eve-channel/index.d.ts +1 -0
  38. package/dist/src/eve-channel/index.js +1 -1
  39. package/dist/src/eve-channel/types.d.ts +23 -4
  40. package/dist/src/execution/catalog/connection-entry.js +1 -1
  41. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  42. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  43. package/dist/src/execution/proxied-deliver-step.js +1 -1
  44. package/dist/src/execution/sandbox/bash.js +2 -2
  45. package/dist/src/execution/session/active-turn.js +1 -1
  46. package/dist/src/execution/session/admission.d.ts +6 -0
  47. package/dist/src/execution/session/admission.js +1 -1
  48. package/dist/src/execution/session/delivery-facts.js +1 -1
  49. package/dist/src/execution/session/next-input.d.ts +2 -2
  50. package/dist/src/execution/session/next-input.js +1 -1
  51. package/dist/src/execution/session/program.js +1 -1
  52. package/dist/src/execution/session-inbox/inbox.d.ts +2 -2
  53. package/dist/src/execution/session-inbox/inbox.js +1 -1
  54. package/dist/src/execution/session-inbox/protocol.js +1 -1
  55. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  56. package/dist/src/harness/compaction/engine.js +2 -2
  57. package/dist/src/harness/current-messages.js +1 -1
  58. package/dist/src/harness/emission.d.ts +3 -0
  59. package/dist/src/harness/emission.js +1 -1
  60. package/dist/src/harness/facts.d.ts +5 -2
  61. package/dist/src/harness/facts.js +1 -1
  62. package/dist/src/harness/model-call/call.d.ts +7 -1
  63. package/dist/src/harness/model-call/call.js +3 -1
  64. package/dist/src/harness/provider-tool-history.d.ts +8 -0
  65. package/dist/src/harness/provider-tool-history.js +1 -1
  66. package/dist/src/harness/session-machine/transitions.d.ts +3 -2
  67. package/dist/src/harness/step/after-model.js +1 -1
  68. package/dist/src/harness/step/context.js +1 -1
  69. package/dist/src/harness/step/intake.js +1 -1
  70. package/dist/src/harness/step/prompt.js +1 -1
  71. package/dist/src/harness/tool-history-repair.d.ts +2 -0
  72. package/dist/src/harness/tool-history-repair.js +1 -1
  73. package/dist/src/harness/tool-loop.js +1 -1
  74. package/dist/src/internal/application/stamped-package-version.js +1 -1
  75. package/dist/src/internal/authored-module-graph.js +1 -1
  76. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +2 -2
  77. package/dist/src/protocol/routes.d.ts +7 -1
  78. package/dist/src/protocol/routes.js +1 -1
  79. package/dist/src/protocol/session-events/families/delivery.d.ts +5 -3
  80. package/dist/src/protocol/session-events/families/delivery.js +1 -1
  81. package/dist/src/protocol/session-projection/fold.js +1 -1
  82. package/dist/src/public/channels/discord/hitl.js +1 -1
  83. package/dist/src/public/channels/github/githubChannel.js +1 -1
  84. package/dist/src/public/channels/github/state.d.ts +7 -0
  85. package/dist/src/public/channels/github/state.js +1 -1
  86. package/dist/src/public/channels/mcp.js +1 -1
  87. package/dist/src/public/channels/slack/hitl.d.ts +2 -1
  88. package/dist/src/public/channels/slack/hitl.js +3 -3
  89. package/dist/src/public/channels/slack/interaction-cards.js +1 -1
  90. package/dist/src/public/channels/slack/request-card-render.js +1 -1
  91. package/dist/src/public/channels/teams/hitl.js +1 -1
  92. package/dist/src/public/channels/teams/verify.js +1 -1
  93. package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
  94. package/dist/src/public/connections/index.d.ts +1 -1
  95. package/dist/src/public/definitions/channel.js +1 -1
  96. package/dist/src/public/definitions/connections/tool-call.d.ts +2 -2
  97. package/dist/src/public/definitions/hook.d.ts +90 -7
  98. package/dist/src/public/definitions/hook.js +1 -1
  99. package/dist/src/public/hooks/index.d.ts +3 -2
  100. package/dist/src/reactions/continuation.d.ts +19 -0
  101. package/dist/src/reactions/continuation.js +1 -0
  102. package/dist/src/reactions/frame.js +1 -1
  103. package/dist/src/reactions/intents.d.ts +10 -4
  104. package/dist/src/reactions/intents.js +1 -1
  105. package/dist/src/reactions/kinds/hook.js +1 -1
  106. package/dist/src/reactions/runner.js +1 -1
  107. package/dist/src/reactions/state.d.ts +15 -2
  108. package/dist/src/reactions/state.js +1 -1
  109. package/dist/src/runtime/channels/registry.d.ts +2 -2
  110. package/dist/src/runtime/channels/registry.js +1 -1
  111. package/dist/src/runtime/connections/approval-scope.d.ts +9 -0
  112. package/dist/src/runtime/connections/approval-scope.js +1 -0
  113. package/dist/src/runtime/connections/mcp-client.d.ts +1 -1
  114. package/dist/src/runtime/connections/mcp-client.js +1 -1
  115. package/dist/src/runtime/connections/provided-arguments.js +1 -1
  116. package/dist/src/runtime/resolve-connection.js +1 -1
  117. package/dist/src/runtime/subagents/workflow.js +1 -1
  118. package/dist/src/setup/primitives/open-url.js +1 -1
  119. package/dist/src/setup/scaffold/create/project.js +1 -1
  120. package/dist/src/shared/agent-info-access.d.ts +5 -0
  121. package/dist/src/shared/agent-info-access.js +1 -0
  122. package/dist/src/shared/connection-types.d.ts +21 -4
  123. package/dist/src/shared/value-delta.d.ts +5 -4
  124. package/dist/src/shared/value-delta.js +1 -1
  125. package/dist/src/svelte/index.js +1 -1
  126. package/dist/src/svelte/use-eve-agent.js +1 -1
  127. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  128. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  129. package/dist/src/tools/provided/web-fetch.js +1 -1
  130. package/dist/src/vue/index.js +1 -1
  131. package/dist/src/vue/use-eve-agent.js +1 -1
  132. package/docs/agent-config.md +199 -222
  133. package/docs/channels/chat-sdk.mdx +60 -64
  134. package/docs/channels/custom.mdx +265 -280
  135. package/docs/channels/discord.mdx +176 -123
  136. package/docs/channels/eve.mdx +136 -204
  137. package/docs/channels/github.mdx +24 -22
  138. package/docs/channels/linear.mdx +30 -30
  139. package/docs/channels/linq.mdx +25 -13
  140. package/docs/channels/mcp.mdx +154 -116
  141. package/docs/channels/overview.mdx +31 -32
  142. package/docs/channels/photon.mdx +32 -56
  143. package/docs/channels/slack.mdx +538 -375
  144. package/docs/channels/teams.mdx +40 -26
  145. package/docs/channels/telegram.mdx +13 -13
  146. package/docs/channels/twilio.mdx +11 -11
  147. package/docs/code-extension.mdx +40 -42
  148. package/docs/concepts/built-in-tools.md +89 -57
  149. package/docs/concepts/context-control.md +20 -20
  150. package/docs/concepts/default-harness.md +20 -36
  151. package/docs/concepts/execution-model-and-durability.mdx +96 -160
  152. package/docs/concepts/project-structure.mdx +21 -14
  153. package/docs/concepts/security-model.md +27 -27
  154. package/docs/concepts/sessions-runs-and-streaming.md +184 -194
  155. package/docs/concepts/state.md +7 -15
  156. package/docs/connections/mcp.mdx +109 -93
  157. package/docs/connections/openapi.mdx +57 -59
  158. package/docs/connections/overview.mdx +205 -170
  159. package/docs/evals/assertions.mdx +36 -29
  160. package/docs/evals/cases.mdx +38 -42
  161. package/docs/evals/judge.mdx +21 -29
  162. package/docs/evals/overview.mdx +42 -38
  163. package/docs/evals/reporters.mdx +54 -27
  164. package/docs/evals/running.mdx +15 -8
  165. package/docs/evals/targets.mdx +17 -18
  166. package/docs/evals/tool-stubs.mdx +111 -97
  167. package/docs/experimental/dynamic-schedules.mdx +118 -63
  168. package/docs/extensions.md +58 -65
  169. package/docs/getting-started.mdx +4 -6
  170. package/docs/guides/auth-and-route-protection.md +100 -70
  171. package/docs/guides/client/continuations.mdx +23 -26
  172. package/docs/guides/client/messages.mdx +47 -66
  173. package/docs/guides/client/output-schema.mdx +8 -8
  174. package/docs/guides/client/overview.mdx +47 -41
  175. package/docs/guides/client/streaming.mdx +62 -71
  176. package/docs/guides/decide.md +24 -79
  177. package/docs/guides/deployment/meta.json +1 -1
  178. package/docs/guides/deployment/overview.md +27 -18
  179. package/docs/guides/deployment/self-hosted-operations.md +99 -0
  180. package/docs/guides/deployment/self-hosting.md +63 -80
  181. package/docs/guides/deployment/vercel.mdx +31 -27
  182. package/docs/guides/deployment/workflow-worlds.md +100 -0
  183. package/docs/guides/dev-tui.md +48 -41
  184. package/docs/guides/dynamic-capabilities.md +49 -50
  185. package/docs/guides/frontend/nextjs.mdx +2 -2
  186. package/docs/guides/frontend/nuxt.mdx +11 -11
  187. package/docs/guides/frontend/overview.mdx +1 -1
  188. package/docs/guides/frontend/sveltekit.mdx +11 -11
  189. package/docs/guides/frontend/tanstack.mdx +16 -16
  190. package/docs/guides/frontend/use-eve-agent-svelte.mdx +21 -21
  191. package/docs/guides/frontend/use-eve-agent-vue.mdx +22 -22
  192. package/docs/guides/frontend/use-eve-agent.mdx +25 -25
  193. package/docs/guides/hooks.md +152 -106
  194. package/docs/guides/instrumentation/agent-runs.mdx +26 -30
  195. package/docs/guides/instrumentation/instrumentation.mdx +49 -76
  196. package/docs/guides/instrumentation/meta.json +1 -1
  197. package/docs/guides/instrumentation/otel.mdx +113 -179
  198. package/docs/guides/prepare-for-1-0.md +23 -1
  199. package/docs/guides/remote-agents.md +125 -187
  200. package/docs/guides/self-modification.md +18 -18
  201. package/docs/guides/session-context.md +16 -16
  202. package/docs/install-integrations.mdx +26 -24
  203. package/docs/instructions.mdx +37 -42
  204. package/docs/memory/custom-provider.md +35 -41
  205. package/docs/memory/file.md +93 -76
  206. package/docs/memory/overview.mdx +145 -156
  207. package/docs/patterns/durable-cross-channel-notifications.md +15 -19
  208. package/docs/patterns/dynamic-scheduling.md +19 -23
  209. package/docs/patterns/multi-tenant-approvals.md +17 -22
  210. package/docs/patterns/multi-tenant-auth.md +43 -42
  211. package/docs/patterns/multi-tenant-memory.md +39 -36
  212. package/docs/patterns/voice-notes.md +3 -3
  213. package/docs/protocols/acp.md +13 -13
  214. package/docs/protocols/ucp.mdx +7 -7
  215. package/docs/reference/agent-files.md +6 -6
  216. package/docs/reference/cli.md +99 -98
  217. package/docs/reference/telemetry.md +1 -1
  218. package/docs/reference/typescript-api.md +52 -53
  219. package/docs/responsible-use.md +2 -2
  220. package/docs/sandbox/custom-providers.mdx +60 -56
  221. package/docs/sandbox/default.mdx +23 -24
  222. package/docs/sandbox/docker.mdx +16 -10
  223. package/docs/sandbox/index.mdx +93 -61
  224. package/docs/sandbox/just-bash.mdx +17 -11
  225. package/docs/sandbox/troubleshooting.mdx +29 -23
  226. package/docs/sandbox/vercel.mdx +45 -52
  227. package/docs/schedules.mdx +65 -54
  228. package/docs/skills.mdx +74 -49
  229. package/docs/subagents/index.mdx +97 -136
  230. package/docs/tools/human-in-the-loop.md +160 -90
  231. package/docs/tools/meta.json +1 -1
  232. package/docs/tools/overview.mdx +229 -237
  233. package/docs/tools/tasks.md +118 -117
  234. package/docs/tools/workflows.mdx +447 -543
  235. package/docs/tutorial/connect-a-warehouse.mdx +11 -13
  236. package/docs/tutorial/first-agent.mdx +14 -16
  237. package/docs/tutorial/guard-the-spend.mdx +6 -8
  238. package/docs/tutorial/how-it-runs.mdx +8 -8
  239. package/docs/tutorial/query-sample-data.mdx +8 -8
  240. package/docs/tutorial/remember-definitions.mdx +4 -4
  241. package/docs/tutorial/run-analysis.mdx +20 -22
  242. package/docs/tutorial/ship-it.mdx +19 -19
  243. package/docs/tutorial/team-playbooks.mdx +9 -9
  244. package/docs/use-cases.mdx +13 -11
  245. package/package.json +1 -1
  246. package/docs/guides/instrumentation/migration.md +0 -96
  247. package/docs/tools/tasks-upgrade.md +0 -218
package/CHANGELOG.md CHANGED
@@ -1,14 +1,44 @@
1
- # eve 0.89.0
1
+ # eve 0.91.0
2
2
 
3
- Released 2026-10-29 · [Compare with 0.88.1](https://github.com/vercel/eve/compare/eve%400.88.1...eve%400.89.0)
3
+ Released 2026-10-30 · [Compare with 0.90.0](https://github.com/vercel/eve/compare/eve%400.90.0...eve%400.91.0)
4
4
 
5
5
  ## Breaking Changes
6
6
 
7
- - Client `messages` now show only the session's current conversation, so messages from before a clear no longer appear.
8
- `messages` and `transcriptOf()` follow each turn's `follows` and a completed context change's `selects`, as `conversation(view)` does, and leave out turns outside the conversation. The session `view` still holds every retained turn. ([#5597](https://github.com/vercel/eve/pull/5597))
9
- - The `gh` tool takes an optional `repository` instead of `permissions`, runs any `gh` or `git` subcommand, and leaves every access decision to `github.authorize`.
10
- `github.principalType` is now required and decides what `authorize` receives: `{ argv, auth, owner, repository, token }` for `"app"`, and `{ argv, auth, repository, token }` for `"user"`, where `repository` may be `null`. eve no longer matches `--repo` and other explicit targets against the declared repository or limits `git` to `fetch`, `ls-remote`, `pull`, and `push`; check `argv` in `authorize` if your policy depends on them. ([#5595](https://github.com/vercel/eve/pull/5595))
11
- - `history` passed to `send()`, `create()`, or the eve channel's `onMessage` now rejects an entry with a field other than `id`, `role`, or `text` instead of dropping it.
12
- `InvalidSessionHistoryError` names the entry and its unknown fields. Map stored messages to `{ id, role, text }` before passing them, so fields a later release accepts never change what an existing caller sends. ([#5597](https://github.com/vercel/eve/pull/5597))
7
+ - `session.clear()` now cancels a running turn and every working task before it clears history, instead of waiting for the turn to finish.
8
+ Previously a clear sent while a turn waited on tasks didn't run until the tasks finished, and never ran if one hung. Tasks a clear stops end with `task.ended` `outcome: "cancelled"`, and no task result the cleared conversation hadn't read reaches the next turn. ([#5619](https://github.com/vercel/eve/pull/5619))
13
9
 
14
- For an upgrade across multiple releases, review each version between the installed and target versions in the [target version's changelog](https://raw.githubusercontent.com/vercel/eve/refs/tags/eve%400.89.0/packages/eve/CHANGELOG.md).
10
+ ## Features
11
+
12
+ - Hooks can start a session's next turn with `ctx.continue()` from `turn.settled` and `*` handlers.
13
+ Other handlers don't receive it. It continues a completed turn, or a turn the same hook cancelled, and hooks that continue one turn share its next turn. It takes `MessageContent` with `session.send()`'s `context` and an optional `auth`, returns `{ queued }` synchronously, and yields to any other turn, cancel, clear, or reset that comes first. `delivery.admitted` records `source: { channel, hook }`. ([#5555](https://github.com/vercel/eve/pull/5555))
14
+
15
+ ## Bug Fixes
16
+
17
+ - The `bash` tool now keeps only the last 50 KiB of each output stream while a command runs, so a verbose command no longer holds its whole stdout and stderr in memory.
18
+ Very large output no longer fails with `Cannot create a string longer than 0x1fffffe8 characters`. Output past the limit is noted as `earlier output omitted`, as it already was for commands left running.
19
+ Thanks @mrud for reporting this in #5651. ([#5653](https://github.com/vercel/eve/pull/5653))
20
+ - HTTP Basic auth now compares the username and password in constant time on every request, so response timing no longer reveals whether the username matched. ([#5521](https://github.com/vercel/eve/pull/5521))
21
+ - Anthropic agents no longer fail with a 400 when the model calls a server tool, such as `web_search` or programmatic `code_execution`, beside a local tool.
22
+ Anthropic runs that server tool after the local results arrive and returns its result at the start of the next response, so the next request must end on those local results. Until that result arrives, eve now holds a message that steers the turn for one model step, holds changed catalog or skill announcements, sends an empty-response retry's note as a system instruction, and keeps compaction from separating the deferred result from its call or adding a resumption message after the local results. When the result can no longer arrive, because the turn was cancelled, failed, or retried, or a new turn starts, eve answers the server call as one whose outcome is unknown, so the model reads the new message right away.
23
+ Thanks @jam3gw for reporting this in #4890. ([#4891](https://github.com/vercel/eve/pull/4891))
24
+ - A Discord `display: "select"` request with an option `id` longer than 100 characters now fails with a clear error instead of posting a select whose truncated value came back as an id the request never offered, which dropped or mismatched the user's choice. ([#5533](https://github.com/vercel/eve/pull/5533))
25
+ - Sessions now fail controls their eve version does not support, so the control's delivery settles `failed` instead of never settling. ([#5622](https://github.com/vercel/eve/pull/5622))
26
+ - A provider tool result that arrives in the response after its call, such as an Anthropic tool search the model started beside a local tool, now settles the call the earlier step introduced.
27
+ Previously eve published that call a second time, so with the session-event checker on (`eve dev`, `eve eval`, or `EVE_CHECK_SESSION_EVENTS=1`) the step failed with `introduced-twice`, and without it the session log recorded one call introduced twice. ([#5648](https://github.com/vercel/eve/pull/5648))
28
+ - A turn cancellation raised while the model is being resolved now cancels the turn instead of failing the session with `MODEL_SELECTION_FAILED`, even when it arrives before the turn's abort signal fires.
29
+ Thanks @burn2delete for reporting this and proposing the fix in #4273. ([#4274](https://github.com/vercel/eve/pull/4274))
30
+ - Session steps now return only the session projection rows they changed, instead of every row of each changed table, so a step's stored output no longer grows with the calls and parts the turn already settled.
31
+ Thanks @mrud for reporting this in #5635. ([#5642](https://github.com/vercel/eve/pull/5642))
32
+ - Slack approval and question cards now show their prompt, tool input, and answer as literal text.
33
+ A model-written `<!channel>` or `<url|label>` in a prompt or tool input no longer notifies the channel or hides a link's real destination from the approver. `Card(...)` rendering is unchanged. ([#5517](https://github.com/vercel/eve/pull/5517))
34
+ - A connection in `agent/connections/*.ts` now keeps an `approval` written as `{ request, response, prompt }`, so its tools ask for approval and run its `response` policy.
35
+ Previously only the function form was kept and the object form was dropped, so the connection's tools ran without asking anyone. A malformed `approval` now fails resolution instead of being ignored. ([#5632](https://github.com/vercel/eve/pull/5632))
36
+ - Teams approval and question cards now show the prompt, tool input, and answer as literal text.
37
+ A model-written `[docs](https://evil.example)` no longer renders as a link whose label hides its destination. The cards use `RichTextBlock` text runs, and the message text is sent as plain text. ([#5529](https://github.com/vercel/eve/pull/5529))
38
+ - Teams inbound verification now accepts only RS256-signed Bot Connector tokens, as Microsoft documents, instead of using the algorithm named in the token header. ([#5530](https://github.com/vercel/eve/pull/5530))
39
+ - `ctx.turn.input` keeps the turn's input after the turn pauses for an approval, a question, a sign-in, or a budget answer.
40
+ Dynamic values no longer see empty input after the pause, including `auto()` if its per-turn memo was invalidated. ([#5628](https://github.com/vercel/eve/pull/5628))
41
+ - `web_fetch` now rejects a `timeout` of zero or less as invalid tool input, instead of throwing an opaque `RangeError` or aborting the request immediately. ([#5532](https://github.com/vercel/eve/pull/5532))
42
+ - `eve` setup now opens browser URLs on Windows through `rundll32` instead of `cmd /c start`, so `&` or `|` in a URL is no longer interpreted by the shell. ([#5522](https://github.com/vercel/eve/pull/5522))
43
+
44
+ For an upgrade across multiple releases, review each version between the installed and target versions in the [target version's changelog](https://raw.githubusercontent.com/vercel/eve/refs/tags/eve%400.91.0/packages/eve/CHANGELOG.md).
@@ -91,9 +91,10 @@ export type ChannelAdapter<TCtx extends ChannelAdapterContext<any> = ChannelAdap
91
91
  */
92
92
  readonly kind: string;
93
93
  /**
94
- * Initial state shape. Auto-serialized at step boundaries via JSON
95
- * snapshot. On rehydration, the runtime restores the serialized state
96
- * and re-attaches the adapter's behavior functions from the registry.
94
+ * Initial state shape. Auto-serialized at step boundaries. On rehydration,
95
+ * the runtime restores top-level seed fields missing from the serialized
96
+ * state (see {@link seedChannelState}) and re-attaches the adapter's
97
+ * behavior functions from the registry.
97
98
  */
98
99
  readonly state?: Record<string, unknown>;
99
100
  /**
@@ -149,6 +150,14 @@ export declare function defaultDeliverResult(payload: Pick<ChannelDelivery, "mes
149
150
  * Returns the durable kind for an adapter.
150
151
  */
151
152
  export declare function getAdapterKind(adapter: ChannelAdapter): string;
153
+ /**
154
+ * Builds `channel.state` from an adapter's seed and the session's own state,
155
+ * at creation and at every step boundary. Keys present in `state` win, even
156
+ * when `undefined`; keys absent from it take a fresh copy of the seed value,
157
+ * so mutating a nested default never reaches the shared seed. Seeds must be
158
+ * plain JSON-like data (`structuredClone`).
159
+ */
160
+ export declare function seedChannelState(seed: Record<string, unknown> | undefined, state: Record<string, unknown> | undefined): Record<string, unknown>;
152
161
  /**
153
162
  * Calls an adapter's event handler for a given event. Adapters perform side
154
163
  * effects rather than transforming events.
@@ -1 +1 @@
1
- import{attachClientContext,readClientContext}from"#internal/client-context.js";import{attachInputText,readInputText}from"#internal/input-text.js";import{createLogger}from"#internal/logging.js";const log=createLogger(`channel.adapter`);function defaultDeliverResult(e){if(e.message!==void 0)return attachClientContext(attachInputText({answers:e.answers,message:e.message,context:e.context,outputSchema:e.outputSchema},readInputText(e)),readClientContext(e));if(e.answers!==void 0&&e.answers.length>0)return attachClientContext({answers:e.answers,context:e.context,outputSchema:e.outputSchema},readClientContext(e));if(e.context!==void 0&&e.context.length>0||(readClientContext(e)?.length??0)>0)return attachClientContext({context:e.context,outputSchema:e.outputSchema},readClientContext(e));if(e.outputSchema!==void 0)return{outputSchema:e.outputSchema}}function getAdapterKind(e){return e.kind}async function callAdapterEventHandler(e,t,n){let r=`facts`in t?`committed`:t.type,i=e[r];if(i!==void 0)try{await i(t,n)}catch(t){log.error(`adapter event handler threw — event swallowed`,{adapterKind:getAdapterKind(e),eventType:r,error:t})}}export{callAdapterEventHandler,defaultDeliverResult,getAdapterKind};
1
+ import{attachClientContext,readClientContext}from"#internal/client-context.js";import{attachInputText,readInputText}from"#internal/input-text.js";import{createLogger}from"#internal/logging.js";const log=createLogger(`channel.adapter`);function defaultDeliverResult(e){if(e.message!==void 0)return attachClientContext(attachInputText({answers:e.answers,message:e.message,context:e.context,outputSchema:e.outputSchema},readInputText(e)),readClientContext(e));if(e.answers!==void 0&&e.answers.length>0)return attachClientContext({answers:e.answers,context:e.context,outputSchema:e.outputSchema},readClientContext(e));if(e.context!==void 0&&e.context.length>0||(readClientContext(e)?.length??0)>0)return attachClientContext({context:e.context,outputSchema:e.outputSchema},readClientContext(e));if(e.outputSchema!==void 0)return{outputSchema:e.outputSchema}}function getAdapterKind(e){return e.kind}function seedChannelState(e,t){return{...structuredClone(e),...t}}async function callAdapterEventHandler(e,t,n){let r=`facts`in t?`committed`:t.type,i=e[r];if(i!==void 0)try{await i(t,n)}catch(t){log.error(`adapter event handler threw — event swallowed`,{adapterKind:getAdapterKind(e),eventType:r,error:t})}}export{callAdapterEventHandler,defaultDeliverResult,getAdapterKind,seedChannelState};
@@ -218,13 +218,8 @@ export declare class ForbiddenError extends Error {
218
218
  readonly response: Response;
219
219
  constructor(opts?: AuthErrorOptions);
220
220
  }
221
- export interface AuthResult extends SessionAuthContext {
222
- /**
223
- * Set to true to let this authenticated caller create sessions with tool stubs.
224
- * Callers without this permission cannot supply stubs.
225
- */
226
- readonly allowToolStubs?: boolean;
227
- }
221
+ /** Verified identity returned by a shared HTTP authenticator. */
222
+ export type AuthResult = SessionAuthContext;
228
223
  /**
229
224
  * Route auth callback. Returned value semantics inside {@link routeAuth}:
230
225
  *
@@ -236,7 +231,7 @@ export interface AuthResult extends SessionAuthContext {
236
231
  * {@link UnauthenticatedError} or {@link ForbiddenError}. To accept anonymous
237
232
  * traffic, include {@link none} as the final entry.
238
233
  */
239
- export type AuthFn<TEvent = Request> = (event: TEvent) => AuthResult | null | undefined | Promise<AuthResult | null | undefined>;
234
+ export type AuthFn<TEvent = Request, TResult extends AuthResult = AuthResult> = (event: TEvent) => TResult | null | undefined | Promise<TResult | null | undefined>;
240
235
  /**
241
236
  * OAuth protected-resource metadata attached to an inbound auth policy.
242
237
  * `issuer` is shorthand for a single authorization server.
@@ -286,7 +281,7 @@ export declare function oauthResource(auth: AuthFn<Request> | readonly AuthFn<Re
286
281
  * );
287
282
  * ```
288
283
  */
289
- export declare function withAuthChallenges<TEvent>(fn: AuthFn<TEvent>, challenges: readonly UnauthorizedChallenge[]): AuthFn<TEvent>;
284
+ export declare function withAuthChallenges<TEvent, TResult extends AuthResult = AuthResult>(fn: AuthFn<TEvent, TResult>, challenges: readonly UnauthorizedChallenge[]): AuthFn<TEvent, TResult>;
290
285
  /**
291
286
  * Walks an `AuthFn` (or array) in order against `request`. The first entry
292
287
  * returning a {@link SessionAuthContext} wins; entries returning `null` or
@@ -300,7 +295,7 @@ export declare function withAuthChallenges<TEvent>(fn: AuthFn<TEvent>, challenge
300
295
  * a custom `defineChannel` route handler) should call `routeAuth` rather than
301
296
  * re-implement the walk.
302
297
  */
303
- export declare function routeAuth(request: Request, auth: AuthFn<Request> | readonly AuthFn<Request>[]): Promise<AuthResult | Response>;
298
+ export declare function routeAuth<TResult extends AuthResult = AuthResult>(request: Request, auth: AuthFn<Request, TResult> | readonly AuthFn<Request, TResult>[]): Promise<TResult | Response>;
304
299
  /**
305
300
  * Returns an {@link AuthFn} for scaffolded apps that makes unfinished
306
301
  * production auth fail as an intentional 401 rather than an internal route
@@ -469,16 +464,8 @@ export interface VercelSubjectInput {
469
464
  * not exposed in `sub`. See Vercel's OIDC reference for the token anatomy.
470
465
  */
471
466
  export declare function vercelSubject(input: VercelSubjectInput): string;
472
- export interface VercelOidcOptions extends Omit<VerifyVercelOidcOptions, "subjects"> {
473
- /**
474
- * Additional token subjects allowed to authenticate.
475
- * To allow stubs, use { subject, allowToolStubs: true } for that subject.
476
- */
477
- readonly subjects?: readonly (string | {
478
- readonly subject: string;
479
- readonly allowToolStubs?: boolean;
480
- })[];
481
- }
467
+ /** Verification options for the Vercel OIDC route authenticator. */
468
+ export type VercelOidcOptions = VerifyVercelOidcOptions;
482
469
  /**
483
470
  * Returns an HTTP route auth callback backed by Vercel OIDC. See
484
471
  * {@link verifyVercelOidc} for the always-on current-project bypass and how
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{areTokenClaimMatchersSatisfied}from"#channel/auth/token-claims.js";import{decodeJwt}from"#compiled/jose/index.js";import{ANONYMOUS_SESSION_AUTH_CONTEXT}from"#channel/principal-identity.js";import{isEveDevEnvironment,isLocalDevelopmentServer}from"#internal/application/dev-environment.js";import{isLocalMachineAddress,readTrustedDevelopmentPeer}from"#internal/nitro/dev-client-address.js";import{authenticateHttpBasicStrategy}from"#channel/auth/http-basic.js";import{authenticateJwtEcdsaStrategy}from"#channel/auth/jwt-ecdsa.js";import{authenticateJwtHmacStrategy}from"#channel/auth/jwt-hmac.js";import{authenticateOidcStrategy}from"#channel/auth/oidc.js";import{resolveVercelOidcCurrentProject}from"#channel/auth/vercel-oidc-project.js";import{createRuntimeSessionAuthContext}from"#channel/auth/types.js";import{isVercelOidcIssuer}from"#shared/vercel-project.js";import{createRuntimeIpAllowList,isRuntimeIpAllowed}from"#channel/ip-allow-list.js";import{isLoopbackHostname}from"#shared/network-address.js";const vercelOidcLog=createLogger(`auth.vercel-oidc`);function verifyHttpBasic(e,t){if(e===null)return{ok:!1};let n=authenticateHttpBasicStrategy({authorization:e,strategy:{kind:`http-basic`,password:t.password,username:t.username}});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function verifyJwtHmac(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-hmac`,secret:t.secret,claims:t.claims,subjects:t.subjects},r=await authenticateJwtHmacStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyJwtEcdsa(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-ecdsa`,publicKey:t.publicKey,claims:t.claims,subjects:t.subjects},r=await authenticateJwtEcdsaStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyOidc(e,t){let n=await runOidcVerification(e,{...t,acceptCurrentVercelProject:!1,currentVercelProject:void 0});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function runOidcVerification(e,t){if(e===null||e.length===0)return{kind:`not-authenticated`};let n={acceptCurrentVercelProject:t.acceptCurrentVercelProject,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,discoveryUrl:t.discoveryUrl??`${t.issuer.replace(/\/$/,``)}/.well-known/openid-configuration`,issuer:t.issuer,kind:`oidc`,claims:t.claims,subjects:t.subjects},r=t.currentVercelProject===void 0?n:{...n,currentVercelProject:t.currentVercelProject};return await authenticateOidcStrategy({strategy:r,token:e})}function extractBearerToken(e){if(e===null)return null;let t=/^Bearer\s+(.+)$/i.exec(e)?.[1]?.trim();return t===void 0||t.length===0?null:t}function createIpAllowList(e){return createRuntimeIpAllowList(e)}function isIpAllowed(e,t){return e!==null&&isRuntimeIpAllowed(e,t)}function createUnauthorizedResponse(e={}){let t=e.status??401,n=e.code??(t===403?`forbidden`:`unauthorized`),r=e.message??(t===403?`Forbidden.`:`Authorization is required for this route.`),i=e.challenges??[],a=new Headers({"cache-control":`no-store`});for(let e of i)a.append(`www-authenticate`,formatChallenge(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function formatChallenge(e){if(e.parameters===void 0||Object.keys(e.parameters).length===0)return e.scheme;let t=Object.entries(e.parameters).map(([e,t])=>`${e}="${escapeAuthChallengeParameter(t)}"`).join(`, `);return`${e.scheme} ${t}`}function escapeAuthChallengeParameter(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function isValidOAuthIdentifierUrl(e){try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`&&isLoopbackHostname(t.hostname))&&t.username.length===0&&t.password.length===0&&t.search.length===0&&t.hash.length===0}catch{return!1}}function isValidMetadataPath(e){if(!e.startsWith(`/`)||e.startsWith(`//`))return!1;let t=new URL(e,`https://eve.invalid`);return t.origin===`https://eve.invalid`&&t.search.length===0&&t.hash.length===0}var UnauthenticatedError=class extends Error{response;constructor(e={}){super(e.message??`Authorization is required for this route.`),this.name=`UnauthenticatedError`,this.response=createUnauthorizedResponse({...e,status:401})}},ForbiddenError=class extends Error{response;constructor(e={}){super(e.message??`Forbidden.`),this.name=`ForbiddenError`,this.response=createUnauthorizedResponse({...e,status:403})}};const OAUTH_RESOURCE_SYMBOL=Symbol.for(`eve.channels.auth.oauthResource`);function oauthResource(e,t){let n=t.issuer===void 0?t.authorizationServers:[t.issuer];if(n.length===0||n.some(e=>!isValidOAuthIdentifierUrl(e)))throw Error(`oauthResource requires at least one HTTPS authorization server URL (HTTP is allowed only on loopback).`);if(t.resource!==void 0&&!isValidOAuthIdentifierUrl(t.resource))throw Error(`oauthResource resource must be an HTTPS URL without credentials, query, or fragment (HTTP is allowed only on loopback).`);if(t.metadataPath!==void 0&&!isValidMetadataPath(t.metadataPath))throw Error(`oauthResource metadataPath must be an absolute path without a host, query, or fragment.`);let r=Array.isArray(e)?e:[e],composed=async e=>{for(let t of r){let n=await t(e);if(n)return n}return null},i=collectDeclaredChallenges(r),a=withAuthChallenges(composed,i.length>0?i:[{scheme:`Bearer`}]);return Object.defineProperty(a,OAUTH_RESOURCE_SYMBOL,{enumerable:!1,value:t}),a}function readOAuthResourceOptions(e){if(!Array.isArray(e))return e[OAUTH_RESOURCE_SYMBOL]}const AUTH_CHALLENGES_SYMBOL=Symbol.for(`eve.channels.auth.challenges`);function withAuthChallenges(e,t){let wrapped=t=>e(t);return Object.defineProperty(wrapped,AUTH_CHALLENGES_SYMBOL,{value:t}),wrapped}function getDeclaredChallenges(e){return e[AUTH_CHALLENGES_SYMBOL]}function collectDeclaredChallenges(e){let t=new Set,n=[];for(let r of e)for(let e of getDeclaredChallenges(r)??[]){let r=formatChallenge(e);t.has(r)||(t.add(r),n.push(e))}return n}async function routeAuth(e,t){let n=Array.isArray(t)?t:[t];try{for(let t of n){let n=await t(e);if(n)return n}}catch(e){if(typeof e==`object`&&e&&`response`in e&&e.response instanceof Response)return e.response;throw e}let r=collectDeclaredChallenges(n);return createUnauthorizedResponse({challenges:r.length>0?addInvalidBearerTokenError(e,r):[{scheme:`Bearer`}]})}function addInvalidBearerTokenError(e,t){let n=e.headers.get(`authorization`);return n===null||!/^Bearer(?:\s|$)/i.test(n.trim())||!t.some(e=>e.scheme===`Bearer`)?t:t.map(e=>e.scheme!==`Bearer`||e.parameters?.error!==void 0?e:{...e,parameters:{...e.parameters,error:`invalid_token`}})}function placeholderAuth(){return()=>{if(process.env.VERCEL_ENV!==`production`)return null;throw new UnauthenticatedError({code:`eve_production_auth_not_configured`,message:`Production auth is not configured. Replace placeholderAuth() in agent/channels/eve.ts with your app's auth provider.`})}}function none(){return()=>ANONYMOUS_SESSION_AUTH_CONTEXT}function localDev(){return e=>isLocalDevelopmentServer()&&!isCrossSiteBrowserRequest(e)&&!isFromRemotePeer(e)?LOCAL_DEV_SESSION_AUTH_CONTEXT:null}function isCrossSiteBrowserRequest(e){if(!isLocalMachineAddress(new URL(e.url).hostname))return!0;let t=e.headers.get(`origin`);if(t===null)return!1;let n=URL.parse(t)?.hostname;return n===void 0||!isLocalMachineAddress(n)}function isFromRemotePeer(e){return readTrustedDevelopmentPeer(e.headers)===`remote`}const LOCAL_DEV_SESSION_AUTH_CONTEXT={attributes:{},authenticator:`local-dev`,principalId:`local-dev`,principalType:`local-dev`};async function verifyVercelOidc(e,t={}){if(e===null||e.length===0)return{ok:!1};let n=decodeUnverifiedJwtClaims(e);if(n===null)return vercelOidcLog.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!isVercelOidcIssuer(n.issuer))return vercelOidcLog.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return vercelOidcLog.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};if(!n.audiences.some(e=>e.startsWith(`https://vercel.com/`)))return vercelOidcLog.debug(`Rejected token whose audience is not a Vercel audience.`,{audiences:n.audiences,issuer:n.issuer}),{ok:!1};let r=resolveCurrentVercelProject(t),i=await runOidcVerification(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,currentVercelProject:r,issuer:n.issuer,subjects:t.subjects??[]});return i.kind===`authenticated`?(vercelOidcLog.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:i.principal.principalType,subject:i.principal.subject}),{ok:!0,sessionAuth:createRuntimeSessionAuthContext(i.principal)}):(vercelOidcLog.debug(`Rejected Vercel OIDC token after verification.`,{audiences:n.audiences,issuer:n.issuer,reason:i.kind,subjectsConfigured:(t.subjects??[]).length>0,detail:i.kind===`misconfigured`?i.message:void 0}),{ok:!1})}function resolveCurrentVercelProject(e){if(e.currentVercelProject!==void 0)return e.currentVercelProject;let t=process.env.VERCEL_PROJECT_ID?.trim();if(t===void 0||t.length===0)return;let n=process.env.VERCEL_TARGET_ENV?.trim()||process.env.VERCEL_ENV?.trim();return n===void 0||n.length===0?{projectId:t}:{environment:n,projectId:t}}function vercelSubject(e){assertVercelSubjectSegment(`teamSlug`,e.teamSlug),assertVercelSubjectSegment(`projectName`,e.projectName);let t=e.environment??`production`;if(t!==`production`&&t!==`preview`&&t!==`development`&&t!==`*`)throw Error(`vercelSubject: invalid environment ${JSON.stringify(t)}; expected "production", "preview", "development", or "*".`);return`owner:${e.teamSlug}:project:${e.projectName}:environment:${t}`}function assertVercelSubjectSegment(e,t){if(t.length===0)throw Error(`vercelSubject: ${e} must be a non-empty string.`);if(t.includes(`*`)||t.includes(`:`))throw Error(`vercelSubject: ${e} ${JSON.stringify(t)} may not contain ${t.includes(`:`)?`':'`:`'*'`}. Hand-write the subject string when wildcards are intentional.`)}function vercelOidc(e={}){let{subjects:t,...n}=e,r={...n,subjects:t?.map(e=>typeof e==`string`?e:e.subject)};return withAuthChallenges(async n=>{let i=extractBearerToken(n.headers.get(`authorization`)),a=e.currentVercelProject??(i!==null&&isLocalDevelopmentVercelOidc()?await resolveVercelOidcCurrentProject(n):void 0),o=await verifyVercelOidc(i,a===void 0?r:{...r,currentVercelProject:a});if(!o.ok)return null;let s=o.sessionAuth;return(s.principalType===`service`||s.principalType===`runtime`)&&t?.some(e=>typeof e!=`string`&&e.allowToolStubs===!0&&areTokenClaimMatchersSatisfied({sub:s.subject},{subjects:[e.subject]}))?{...s,allowToolStubs:!0}:s},[{scheme:`Bearer`}])}function isLocalDevelopmentVercelOidc(){return process.env.VERCEL_ENV===`development`?!0:process.env.VERCEL_ENV===`preview`||process.env.VERCEL_ENV===`production`?!1:isEveDevEnvironment()}function httpBasic(e,t){return withAuthChallenges(t=>{let n=verifyHttpBasic(t.headers.get(`authorization`),e);return n.ok?n.sessionAuth:null},[{parameters:{realm:t?.realm??`eve`,charset:`UTF-8`},scheme:`Basic`}])}function jwtHmac(e){return withAuthChallenges(async t=>{let n=await verifyJwtHmac(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function jwtEcdsa(e){return withAuthChallenges(async t=>{let n=await verifyJwtEcdsa(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function oidc(e){return withAuthChallenges(async t=>{let n=await verifyOidc(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function decodeUnverifiedJwtClaims(e){let t;try{t=decodeJwt(e)}catch{return null}return typeof t.iss!=`string`||t.iss.length===0?null:{audiences:typeof t.aud==`string`?[t.aud]:Array.isArray(t.aud)?t.aud.filter(e=>typeof e==`string`):[],issuer:t.iss}}export{ForbiddenError,UnauthenticatedError,createIpAllowList,createUnauthorizedResponse,escapeAuthChallengeParameter,extractBearerToken,httpBasic,isIpAllowed,jwtEcdsa,jwtHmac,localDev,none,oauthResource,oidc,placeholderAuth,readOAuthResourceOptions,routeAuth,vercelOidc,vercelSubject,verifyHttpBasic,verifyJwtEcdsa,verifyJwtHmac,verifyOidc,verifyVercelOidc,withAuthChallenges};
1
+ import{createLogger}from"#internal/logging.js";import{decodeJwt}from"#compiled/jose/index.js";import{ANONYMOUS_SESSION_AUTH_CONTEXT}from"#channel/principal-identity.js";import{isEveDevEnvironment,isLocalDevelopmentServer}from"#internal/application/dev-environment.js";import{isLocalMachineAddress,readTrustedDevelopmentPeer}from"#internal/nitro/dev-client-address.js";import{authenticateHttpBasicStrategy}from"#channel/auth/http-basic.js";import{authenticateJwtEcdsaStrategy}from"#channel/auth/jwt-ecdsa.js";import{authenticateJwtHmacStrategy}from"#channel/auth/jwt-hmac.js";import{authenticateOidcStrategy}from"#channel/auth/oidc.js";import{resolveVercelOidcCurrentProject}from"#channel/auth/vercel-oidc-project.js";import{createRuntimeSessionAuthContext}from"#channel/auth/types.js";import{isVercelOidcIssuer}from"#shared/vercel-project.js";import{createRuntimeIpAllowList,isRuntimeIpAllowed}from"#channel/ip-allow-list.js";import{isLoopbackHostname}from"#shared/network-address.js";const vercelOidcLog=createLogger(`auth.vercel-oidc`);function verifyHttpBasic(e,t){if(e===null)return{ok:!1};let n=authenticateHttpBasicStrategy({authorization:e,strategy:{kind:`http-basic`,password:t.password,username:t.username}});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function verifyJwtHmac(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-hmac`,secret:t.secret,claims:t.claims,subjects:t.subjects},r=await authenticateJwtHmacStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyJwtEcdsa(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-ecdsa`,publicKey:t.publicKey,claims:t.claims,subjects:t.subjects},r=await authenticateJwtEcdsaStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyOidc(e,t){let n=await runOidcVerification(e,{...t,acceptCurrentVercelProject:!1,currentVercelProject:void 0});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function runOidcVerification(e,t){if(e===null||e.length===0)return{kind:`not-authenticated`};let n={acceptCurrentVercelProject:t.acceptCurrentVercelProject,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,discoveryUrl:t.discoveryUrl??`${t.issuer.replace(/\/$/,``)}/.well-known/openid-configuration`,issuer:t.issuer,kind:`oidc`,claims:t.claims,subjects:t.subjects},r=t.currentVercelProject===void 0?n:{...n,currentVercelProject:t.currentVercelProject};return await authenticateOidcStrategy({strategy:r,token:e})}function extractBearerToken(e){if(e===null)return null;let t=/^Bearer\s+(.+)$/i.exec(e)?.[1]?.trim();return t===void 0||t.length===0?null:t}function createIpAllowList(e){return createRuntimeIpAllowList(e)}function isIpAllowed(e,t){return e!==null&&isRuntimeIpAllowed(e,t)}function createUnauthorizedResponse(e={}){let t=e.status??401,n=e.code??(t===403?`forbidden`:`unauthorized`),r=e.message??(t===403?`Forbidden.`:`Authorization is required for this route.`),i=e.challenges??[],a=new Headers({"cache-control":`no-store`});for(let e of i)a.append(`www-authenticate`,formatChallenge(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function formatChallenge(e){if(e.parameters===void 0||Object.keys(e.parameters).length===0)return e.scheme;let t=Object.entries(e.parameters).map(([e,t])=>`${e}="${escapeAuthChallengeParameter(t)}"`).join(`, `);return`${e.scheme} ${t}`}function escapeAuthChallengeParameter(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function isValidOAuthIdentifierUrl(e){try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`&&isLoopbackHostname(t.hostname))&&t.username.length===0&&t.password.length===0&&t.search.length===0&&t.hash.length===0}catch{return!1}}function isValidMetadataPath(e){if(!e.startsWith(`/`)||e.startsWith(`//`))return!1;let t=new URL(e,`https://eve.invalid`);return t.origin===`https://eve.invalid`&&t.search.length===0&&t.hash.length===0}var UnauthenticatedError=class extends Error{response;constructor(e={}){super(e.message??`Authorization is required for this route.`),this.name=`UnauthenticatedError`,this.response=createUnauthorizedResponse({...e,status:401})}},ForbiddenError=class extends Error{response;constructor(e={}){super(e.message??`Forbidden.`),this.name=`ForbiddenError`,this.response=createUnauthorizedResponse({...e,status:403})}};const OAUTH_RESOURCE_SYMBOL=Symbol.for(`eve.channels.auth.oauthResource`);function oauthResource(e,t){let n=t.issuer===void 0?t.authorizationServers:[t.issuer];if(n.length===0||n.some(e=>!isValidOAuthIdentifierUrl(e)))throw Error(`oauthResource requires at least one HTTPS authorization server URL (HTTP is allowed only on loopback).`);if(t.resource!==void 0&&!isValidOAuthIdentifierUrl(t.resource))throw Error(`oauthResource resource must be an HTTPS URL without credentials, query, or fragment (HTTP is allowed only on loopback).`);if(t.metadataPath!==void 0&&!isValidMetadataPath(t.metadataPath))throw Error(`oauthResource metadataPath must be an absolute path without a host, query, or fragment.`);let r=Array.isArray(e)?e:[e],composed=async e=>{for(let t of r){let n=await t(e);if(n)return n}return null},i=collectDeclaredChallenges(r),a=withAuthChallenges(composed,i.length>0?i:[{scheme:`Bearer`}]);return Object.defineProperty(a,OAUTH_RESOURCE_SYMBOL,{enumerable:!1,value:t}),a}function readOAuthResourceOptions(e){if(!Array.isArray(e))return e[OAUTH_RESOURCE_SYMBOL]}const AUTH_CHALLENGES_SYMBOL=Symbol.for(`eve.channels.auth.challenges`);function withAuthChallenges(e,t){let wrapped=t=>e(t);return Object.defineProperty(wrapped,AUTH_CHALLENGES_SYMBOL,{value:t}),wrapped}function getDeclaredChallenges(e){return e[AUTH_CHALLENGES_SYMBOL]}function collectDeclaredChallenges(e){let t=new Set,n=[];for(let r of e)for(let e of getDeclaredChallenges(r)??[]){let r=formatChallenge(e);t.has(r)||(t.add(r),n.push(e))}return n}async function routeAuth(e,t){let n=Array.isArray(t)?t:[t];try{for(let t of n){let n=await t(e);if(n)return n}}catch(e){if(typeof e==`object`&&e&&`response`in e&&e.response instanceof Response)return e.response;throw e}let r=collectDeclaredChallenges(n);return createUnauthorizedResponse({challenges:r.length>0?addInvalidBearerTokenError(e,r):[{scheme:`Bearer`}]})}function addInvalidBearerTokenError(e,t){let n=e.headers.get(`authorization`);return n===null||!/^Bearer(?:\s|$)/i.test(n.trim())||!t.some(e=>e.scheme===`Bearer`)?t:t.map(e=>e.scheme!==`Bearer`||e.parameters?.error!==void 0?e:{...e,parameters:{...e.parameters,error:`invalid_token`}})}function placeholderAuth(){return()=>{if(process.env.VERCEL_ENV!==`production`)return null;throw new UnauthenticatedError({code:`eve_production_auth_not_configured`,message:`Production auth is not configured. Replace placeholderAuth() in agent/channels/eve.ts with your app's auth provider.`})}}function none(){return()=>ANONYMOUS_SESSION_AUTH_CONTEXT}const LOCAL_DEV_AUTH_SYMBOL=Symbol.for(`eve.channels.auth.localDev`);function localDev(){let authenticate=e=>isLocalDevelopmentServer()&&!isCrossSiteBrowserRequest(e)&&!isFromRemotePeer(e)?LOCAL_DEV_SESSION_AUTH_CONTEXT:null;return Object.defineProperty(authenticate,LOCAL_DEV_AUTH_SYMBOL,{value:!0}),authenticate}function isLocalDevAuth(e){return e[LOCAL_DEV_AUTH_SYMBOL]===!0}function isCrossSiteBrowserRequest(e){if(!isLocalMachineAddress(new URL(e.url).hostname))return!0;let t=e.headers.get(`origin`);if(t===null)return!1;let n=URL.parse(t)?.hostname;return n===void 0||!isLocalMachineAddress(n)}function isFromRemotePeer(e){return readTrustedDevelopmentPeer(e.headers)===`remote`}const LOCAL_DEV_SESSION_AUTH_CONTEXT={attributes:{},authenticator:`local-dev`,principalId:`local-dev`,principalType:`local-dev`};async function verifyVercelOidc(e,t={}){if(e===null||e.length===0)return{ok:!1};let n=decodeUnverifiedJwtClaims(e);if(n===null)return vercelOidcLog.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!isVercelOidcIssuer(n.issuer))return vercelOidcLog.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return vercelOidcLog.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};if(!n.audiences.some(e=>e.startsWith(`https://vercel.com/`)))return vercelOidcLog.debug(`Rejected token whose audience is not a Vercel audience.`,{audiences:n.audiences,issuer:n.issuer}),{ok:!1};let r=resolveCurrentVercelProject(t),i=await runOidcVerification(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,currentVercelProject:r,issuer:n.issuer,subjects:t.subjects??[]});return i.kind===`authenticated`?(vercelOidcLog.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:i.principal.principalType,subject:i.principal.subject}),{ok:!0,sessionAuth:createRuntimeSessionAuthContext(i.principal)}):(vercelOidcLog.debug(`Rejected Vercel OIDC token after verification.`,{audiences:n.audiences,issuer:n.issuer,reason:i.kind,subjectsConfigured:(t.subjects??[]).length>0,detail:i.kind===`misconfigured`?i.message:void 0}),{ok:!1})}function resolveCurrentVercelProject(e){if(e.currentVercelProject!==void 0)return e.currentVercelProject;let t=process.env.VERCEL_PROJECT_ID?.trim();if(t===void 0||t.length===0)return;let n=process.env.VERCEL_TARGET_ENV?.trim()||process.env.VERCEL_ENV?.trim();return n===void 0||n.length===0?{projectId:t}:{environment:n,projectId:t}}function vercelSubject(e){assertVercelSubjectSegment(`teamSlug`,e.teamSlug),assertVercelSubjectSegment(`projectName`,e.projectName);let t=e.environment??`production`;if(t!==`production`&&t!==`preview`&&t!==`development`&&t!==`*`)throw Error(`vercelSubject: invalid environment ${JSON.stringify(t)}; expected "production", "preview", "development", or "*".`);return`owner:${e.teamSlug}:project:${e.projectName}:environment:${t}`}function assertVercelSubjectSegment(e,t){if(t.length===0)throw Error(`vercelSubject: ${e} must be a non-empty string.`);if(t.includes(`*`)||t.includes(`:`))throw Error(`vercelSubject: ${e} ${JSON.stringify(t)} may not contain ${t.includes(`:`)?`':'`:`'*'`}. Hand-write the subject string when wildcards are intentional.`)}function vercelOidc(e={}){if(e.subjects?.some(e=>typeof e!=`string`))throw TypeError(`vercelOidc: every subjects entry must be a string. For entries such as { subject, allowToolStubs: true }, use eveVercelOidc from "eve/channels/eve".`);return withAuthChallenges(async t=>{let n=extractBearerToken(t.headers.get(`authorization`)),r=e.currentVercelProject??(n!==null&&isLocalDevelopmentVercelOidc()?await resolveVercelOidcCurrentProject(t):void 0),i=await verifyVercelOidc(n,r===void 0?e:{...e,currentVercelProject:r});return i.ok?i.sessionAuth:null},[{scheme:`Bearer`}])}function isLocalDevelopmentVercelOidc(){return process.env.VERCEL_ENV===`development`?!0:process.env.VERCEL_ENV===`preview`||process.env.VERCEL_ENV===`production`?!1:isEveDevEnvironment()}function httpBasic(e,t){return withAuthChallenges(t=>{let n=verifyHttpBasic(t.headers.get(`authorization`),e);return n.ok?n.sessionAuth:null},[{parameters:{realm:t?.realm??`eve`,charset:`UTF-8`},scheme:`Basic`}])}function jwtHmac(e){return withAuthChallenges(async t=>{let n=await verifyJwtHmac(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function jwtEcdsa(e){return withAuthChallenges(async t=>{let n=await verifyJwtEcdsa(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function oidc(e){return withAuthChallenges(async t=>{let n=await verifyOidc(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function decodeUnverifiedJwtClaims(e){let t;try{t=decodeJwt(e)}catch{return null}return typeof t.iss!=`string`||t.iss.length===0?null:{audiences:typeof t.aud==`string`?[t.aud]:Array.isArray(t.aud)?t.aud.filter(e=>typeof e==`string`):[],issuer:t.iss}}export{ForbiddenError,UnauthenticatedError,createIpAllowList,createUnauthorizedResponse,escapeAuthChallengeParameter,extractBearerToken,httpBasic,isIpAllowed,isLocalDevAuth,jwtEcdsa,jwtHmac,localDev,none,oauthResource,oidc,placeholderAuth,readOAuthResourceOptions,routeAuth,vercelOidc,vercelSubject,verifyHttpBasic,verifyJwtEcdsa,verifyJwtHmac,verifyOidc,verifyVercelOidc,withAuthChallenges};
@@ -1 +1 @@
1
- import{createHash,timingSafeEqual}from"node:crypto";function authenticateHttpBasicStrategy(e){let t=parseBasicAuthorizationHeader(e.authorization);return t===null||normalizeCredential(t.username)!==normalizeCredential(e.strategy.username)||!timingSafeStringEquals(normalizeCredential(t.password),normalizeCredential(e.strategy.password))?{kind:`not-authenticated`}:{kind:`authenticated`,principal:{attributes:Object.freeze({}),authenticator:`http-basic`,claims:Object.freeze({}),principalId:e.strategy.username,principalType:`user`}}}function parseBasicAuthorizationHeader(e){let t=/^Basic\s+(.+)$/i.exec(e);if(t===null)return null;let n=t[1];if(n===void 0)return null;let r;try{r=Buffer.from(n,`base64`).toString(`utf8`)}catch{return null}let i=r.indexOf(`:`);return i===-1?null:{password:r.slice(i+1),username:r.slice(0,i)}}function normalizeCredential(e){return e.normalize(`NFC`)}function timingSafeStringEquals(e,t){return timingSafeEqual(hashString(e),hashString(t))}function hashString(e){return createHash(`sha256`).update(e,`utf8`).digest()}export{authenticateHttpBasicStrategy};
1
+ import{createHash,timingSafeEqual}from"node:crypto";function authenticateHttpBasicStrategy(e){let t=parseBasicAuthorizationHeader(e.authorization);if(t===null)return{kind:`not-authenticated`};let n=timingSafeStringEquals(normalizeCredential(t.username),normalizeCredential(e.strategy.username)),r=timingSafeStringEquals(normalizeCredential(t.password),normalizeCredential(e.strategy.password));return!n||!r?{kind:`not-authenticated`}:{kind:`authenticated`,principal:{attributes:Object.freeze({}),authenticator:`http-basic`,claims:Object.freeze({}),principalId:e.strategy.username,principalType:`user`}}}function parseBasicAuthorizationHeader(e){let t=/^Basic\s+(.+)$/i.exec(e);if(t===null)return null;let n=t[1];if(n===void 0)return null;let r;try{r=Buffer.from(n,`base64`).toString(`utf8`)}catch{return null}let i=r.indexOf(`:`);return i===-1?null:{password:r.slice(i+1),username:r.slice(0,i)}}function normalizeCredential(e){return e.normalize(`NFC`)}function timingSafeStringEquals(e,t){return timingSafeEqual(hashString(e),hashString(t))}function hashString(e){return createHash(`sha256`).update(e,`utf8`).digest()}export{authenticateHttpBasicStrategy};
@@ -1 +1 @@
1
- import{areTokenClaimMatchersSatisfied,createJwtAuthenticatedCallerPrincipal}from"#channel/auth/token-claims.js";import{importJWK,importSPKI,jwtVerify}from"#compiled/jose/index.js";const importedJwtPublicKeyCache=new Map;async function authenticateJwtEcdsaStrategy(e){let t;try{t=await getImportedJwtPublicKey(e.strategy)}catch(e){return{kind:`misconfigured`,message:`Failed to import JWT ECDSA public key. ${e instanceof Error?e.message:`Unknown key import failure.`}`}}try{let n=await jwtVerify(e.token,t,{algorithms:[e.strategy.algorithm],audience:[...e.strategy.audiences],clockTolerance:e.strategy.clockSkewSeconds,issuer:e.strategy.issuer});return typeof n.payload.sub!=`string`||n.payload.sub.length===0?{kind:`not-authenticated`}:areTokenClaimMatchersSatisfied(n.payload,e.strategy)?{kind:`authenticated`,principal:createJwtAuthenticatedCallerPrincipal({authenticator:`jwt-ecdsa`,payload:n.payload,principalType:`service`})}:{kind:`caller-not-allowed`}}catch{return{kind:`not-authenticated`}}}async function getImportedJwtPublicKey(e){let t=`${e.algorithm}:${e.publicKey}`,n=importedJwtPublicKeyCache.get(t);if(n!==void 0)return await n;let r=importJwtPublicKey(e.publicKey,e.algorithm).catch(e=>{throw importedJwtPublicKeyCache.delete(t),e});return importedJwtPublicKeyCache.set(t,r),await r}async function importJwtPublicKey(e,t){let n=e.trim();return n.startsWith(`{`)?await importJWK(JSON.parse(n),t):await importSPKI(n,t)}export{authenticateJwtEcdsaStrategy};
1
+ import{importJWK,importSPKI,jwtVerify}from"#compiled/jose/index.js";import{areTokenClaimMatchersSatisfied,createJwtAuthenticatedCallerPrincipal}from"#channel/auth/token-claims.js";const importedJwtPublicKeyCache=new Map;async function authenticateJwtEcdsaStrategy(e){let t;try{t=await getImportedJwtPublicKey(e.strategy)}catch(e){return{kind:`misconfigured`,message:`Failed to import JWT ECDSA public key. ${e instanceof Error?e.message:`Unknown key import failure.`}`}}try{let n=await jwtVerify(e.token,t,{algorithms:[e.strategy.algorithm],audience:[...e.strategy.audiences],clockTolerance:e.strategy.clockSkewSeconds,issuer:e.strategy.issuer});return typeof n.payload.sub!=`string`||n.payload.sub.length===0?{kind:`not-authenticated`}:areTokenClaimMatchersSatisfied(n.payload,e.strategy)?{kind:`authenticated`,principal:createJwtAuthenticatedCallerPrincipal({authenticator:`jwt-ecdsa`,payload:n.payload,principalType:`service`})}:{kind:`caller-not-allowed`}}catch{return{kind:`not-authenticated`}}}async function getImportedJwtPublicKey(e){let t=`${e.algorithm}:${e.publicKey}`,n=importedJwtPublicKeyCache.get(t);if(n!==void 0)return await n;let r=importJwtPublicKey(e.publicKey,e.algorithm).catch(e=>{throw importedJwtPublicKeyCache.delete(t),e});return importedJwtPublicKeyCache.set(t,r),await r}async function importJwtPublicKey(e,t){let n=e.trim();return n.startsWith(`{`)?await importJWK(JSON.parse(n),t):await importSPKI(n,t)}export{authenticateJwtEcdsaStrategy};
@@ -1 +1 @@
1
- import{createSecretKey}from"node:crypto";import{areTokenClaimMatchersSatisfied,createJwtAuthenticatedCallerPrincipal}from"#channel/auth/token-claims.js";import{jwtVerify}from"#compiled/jose/index.js";async function authenticateJwtHmacStrategy(e){try{let t=await jwtVerify(e.token,createSecretKey(Buffer.from(e.strategy.secret,`utf8`)),{algorithms:[e.strategy.algorithm],audience:[...e.strategy.audiences],clockTolerance:e.strategy.clockSkewSeconds,issuer:e.strategy.issuer});return typeof t.payload.sub!=`string`||t.payload.sub.length===0?{kind:`not-authenticated`}:areTokenClaimMatchersSatisfied(t.payload,e.strategy)?{kind:`authenticated`,principal:createJwtAuthenticatedCallerPrincipal({authenticator:`jwt-hmac`,payload:t.payload,principalType:`service`})}:{kind:`caller-not-allowed`}}catch{return{kind:`not-authenticated`}}}export{authenticateJwtHmacStrategy};
1
+ import{createSecretKey}from"node:crypto";import{jwtVerify}from"#compiled/jose/index.js";import{areTokenClaimMatchersSatisfied,createJwtAuthenticatedCallerPrincipal}from"#channel/auth/token-claims.js";async function authenticateJwtHmacStrategy(e){try{let t=await jwtVerify(e.token,createSecretKey(Buffer.from(e.strategy.secret,`utf8`)),{algorithms:[e.strategy.algorithm],audience:[...e.strategy.audiences],clockTolerance:e.strategy.clockSkewSeconds,issuer:e.strategy.issuer});return typeof t.payload.sub!=`string`||t.payload.sub.length===0?{kind:`not-authenticated`}:areTokenClaimMatchersSatisfied(t.payload,e.strategy)?{kind:`authenticated`,principal:createJwtAuthenticatedCallerPrincipal({authenticator:`jwt-hmac`,payload:t.payload,principalType:`service`})}:{kind:`caller-not-allowed`}}catch{return{kind:`not-authenticated`}}}export{authenticateJwtHmacStrategy};
@@ -1 +1 @@
1
- import{areTokenClaimMatchersSatisfied,createJwtAuthenticatedCallerPrincipal}from"#channel/auth/token-claims.js";import{createRemoteJWKSet,jwtVerify}from"#compiled/jose/index.js";import{isVercelOidcIssuer}from"#shared/vercel-project.js";import{z}from"#compiled/zod/index.js";const oidcDiscoveryDocumentSchema=z.object({issuer:z.string().optional(),jwks_uri:z.string().url()}).passthrough(),oidcDiscoveryDocumentCache=new Map,oidcJwksCache=new Map;async function authenticateOidcStrategy(e){let t;try{t=await getOidcRemoteJwks(e.strategy)}catch(e){return{kind:`misconfigured`,message:`Failed to load OIDC discovery metadata. ${e instanceof Error?e.message:`Unknown discovery failure.`}`}}try{let n=await jwtVerify(e.token,t,{audience:[...e.strategy.audiences],clockTolerance:e.strategy.clockSkewSeconds,issuer:e.strategy.issuer});if(e.strategy.acceptCurrentVercelProject&&isVercelOidcIssuer(e.strategy.issuer)&&n.payload.external_sub!==void 0)return typeof n.payload.external_sub!=`string`||n.payload.external_sub.length===0||!currentVercelProjectMatches({payload:n.payload,strategy:e.strategy})||!currentVercelEnvironmentMatches({payload:n.payload,strategy:e.strategy})?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:createJwtAuthenticatedCallerPrincipal({authenticator:`oidc`,issuerClaims:[`external_iss`,`connector_id`],payload:n.payload,principalType:`user`,subjectClaim:`external_sub`})};if(e.strategy.acceptCurrentVercelProject&&isVercelOidcIssuer(e.strategy.issuer)&&n.payload.user_id!==void 0){if(typeof n.payload.user_id!=`string`||n.payload.user_id.length===0||n.payload.environment!==`development`||!currentVercelProjectMatches({payload:n.payload,strategy:e.strategy}))return{kind:`caller-not-allowed`};if(currentVercelEnvironmentMatches({payload:n.payload,strategy:e.strategy}))return{kind:`authenticated`,principal:createJwtAuthenticatedCallerPrincipal({authenticator:`oidc`,payload:n.payload,principalType:`user`,subjectClaim:`user_id`})}}if(typeof n.payload.sub!=`string`||n.payload.sub.length===0)return{kind:`not-authenticated`};let r=e.strategy.acceptCurrentVercelProject&&isCurrentVercelProjectToken({issuer:e.strategy.issuer,payload:n.payload,strategy:e.strategy}),i=r&&isCurrentVercelEnvironmentToken({payload:n.payload,strategy:e.strategy});return!r&&!areTokenClaimMatchersSatisfied(n.payload,e.strategy)?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:createJwtAuthenticatedCallerPrincipal({authenticator:`oidc`,payload:n.payload,principalType:i?`runtime`:`service`})}}catch{return{kind:`not-authenticated`}}}async function getOidcRemoteJwks(e){let t=await getOidcDiscoveryDocument(e.discoveryUrl),n=oidcJwksCache.get(t.jwks_uri);if(n!==void 0)return n;let r=createRemoteJWKSet(new URL(t.jwks_uri));return oidcJwksCache.set(t.jwks_uri,r),r}async function getOidcDiscoveryDocument(e){let t=oidcDiscoveryDocumentCache.get(e);if(t!==void 0)return await t;let n=fetch(e,{headers:{accept:`application/json`}}).then(async e=>{if(!e.ok)throw Error(`Discovery route returned HTTP ${e.status}.`);return oidcDiscoveryDocumentSchema.parse(await e.json())}).catch(t=>{throw oidcDiscoveryDocumentCache.delete(e),t});return oidcDiscoveryDocumentCache.set(e,n),await n}function isCurrentVercelProjectToken(e){if(!isVercelOidcIssuer(e.issuer))return!1;let t=e.strategy.currentVercelProject;return t!==void 0&&typeof e.payload.project_id==`string`&&e.payload.project_id===t.projectId}function currentVercelProjectMatches(e){let t=e.strategy.currentVercelProject;return t!==void 0&&typeof e.payload.project_id==`string`&&e.payload.project_id===t.projectId}function isCurrentVercelEnvironmentToken(e){let t=e.strategy.currentVercelProject?.environment;return t===void 0||t.length===0?!1:typeof e.payload.environment==`string`&&e.payload.environment===t}function currentVercelEnvironmentMatches(e){let t=e.strategy.currentVercelProject?.environment;return t===void 0||t.length===0?!1:typeof e.payload.environment==`string`&&e.payload.environment===t}export{authenticateOidcStrategy};
1
+ import{createRemoteJWKSet,jwtVerify}from"#compiled/jose/index.js";import{isVercelOidcIssuer}from"#shared/vercel-project.js";import{areTokenClaimMatchersSatisfied,createJwtAuthenticatedCallerPrincipal}from"#channel/auth/token-claims.js";import{z}from"#compiled/zod/index.js";const oidcDiscoveryDocumentSchema=z.object({issuer:z.string().optional(),jwks_uri:z.string().url()}).passthrough(),oidcDiscoveryDocumentCache=new Map,oidcJwksCache=new Map;async function authenticateOidcStrategy(e){let t;try{t=await getOidcRemoteJwks(e.strategy)}catch(e){return{kind:`misconfigured`,message:`Failed to load OIDC discovery metadata. ${e instanceof Error?e.message:`Unknown discovery failure.`}`}}try{let n=await jwtVerify(e.token,t,{audience:[...e.strategy.audiences],clockTolerance:e.strategy.clockSkewSeconds,issuer:e.strategy.issuer});if(e.strategy.acceptCurrentVercelProject&&isVercelOidcIssuer(e.strategy.issuer)&&n.payload.external_sub!==void 0)return typeof n.payload.external_sub!=`string`||n.payload.external_sub.length===0||!currentVercelProjectMatches({payload:n.payload,strategy:e.strategy})||!currentVercelEnvironmentMatches({payload:n.payload,strategy:e.strategy})?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:createJwtAuthenticatedCallerPrincipal({authenticator:`oidc`,issuerClaims:[`external_iss`,`connector_id`],payload:n.payload,principalType:`user`,subjectClaim:`external_sub`})};if(e.strategy.acceptCurrentVercelProject&&isVercelOidcIssuer(e.strategy.issuer)&&n.payload.user_id!==void 0){if(typeof n.payload.user_id!=`string`||n.payload.user_id.length===0||n.payload.environment!==`development`||!currentVercelProjectMatches({payload:n.payload,strategy:e.strategy}))return{kind:`caller-not-allowed`};if(currentVercelEnvironmentMatches({payload:n.payload,strategy:e.strategy}))return{kind:`authenticated`,principal:createJwtAuthenticatedCallerPrincipal({authenticator:`oidc`,payload:n.payload,principalType:`user`,subjectClaim:`user_id`})}}if(typeof n.payload.sub!=`string`||n.payload.sub.length===0)return{kind:`not-authenticated`};let r=e.strategy.acceptCurrentVercelProject&&isCurrentVercelProjectToken({issuer:e.strategy.issuer,payload:n.payload,strategy:e.strategy}),i=r&&isCurrentVercelEnvironmentToken({payload:n.payload,strategy:e.strategy});return!r&&!areTokenClaimMatchersSatisfied(n.payload,e.strategy)?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:createJwtAuthenticatedCallerPrincipal({authenticator:`oidc`,payload:n.payload,principalType:i?`runtime`:`service`})}}catch{return{kind:`not-authenticated`}}}async function getOidcRemoteJwks(e){let t=await getOidcDiscoveryDocument(e.discoveryUrl),n=oidcJwksCache.get(t.jwks_uri);if(n!==void 0)return n;let r=createRemoteJWKSet(new URL(t.jwks_uri));return oidcJwksCache.set(t.jwks_uri,r),r}async function getOidcDiscoveryDocument(e){let t=oidcDiscoveryDocumentCache.get(e);if(t!==void 0)return await t;let n=fetch(e,{headers:{accept:`application/json`}}).then(async e=>{if(!e.ok)throw Error(`Discovery route returned HTTP ${e.status}.`);return oidcDiscoveryDocumentSchema.parse(await e.json())}).catch(t=>{throw oidcDiscoveryDocumentCache.delete(e),t});return oidcDiscoveryDocumentCache.set(e,n),await n}function isCurrentVercelProjectToken(e){if(!isVercelOidcIssuer(e.issuer))return!1;let t=e.strategy.currentVercelProject;return t!==void 0&&typeof e.payload.project_id==`string`&&e.payload.project_id===t.projectId}function currentVercelProjectMatches(e){let t=e.strategy.currentVercelProject;return t!==void 0&&typeof e.payload.project_id==`string`&&e.payload.project_id===t.projectId}function isCurrentVercelEnvironmentToken(e){let t=e.strategy.currentVercelProject?.environment;return t===void 0||t.length===0?!1:typeof e.payload.environment==`string`&&e.payload.environment===t}function currentVercelEnvironmentMatches(e){let t=e.strategy.currentVercelProject?.environment;return t===void 0||t.length===0?!1:typeof e.payload.environment==`string`&&e.payload.environment===t}export{authenticateOidcStrategy};
@@ -1,4 +1,3 @@
1
1
  import type { SessionAuthContext } from "#channel/types.js";
2
- import type { AuthResult } from "#public/channels/auth.js";
3
- /** Do not save this request's stub permission or forward it to another agent. */
4
- export declare function sessionAuthFromResult(result: AuthResult): SessionAuthContext;
2
+ /** Persist and forward identity only, never a channel's request-local permission extensions. */
3
+ export declare function sessionAuthFromResult(result: SessionAuthContext): SessionAuthContext;
@@ -1 +1 @@
1
- function sessionAuthFromResult(e){let{allowToolStubs:t,...n}=e;return n}export{sessionAuthFromResult};
1
+ const IDENTITY_KEYS=Object.keys({attributes:!0,authenticator:!0,issuer:!0,principalId:!0,principalType:!0,subject:!0});function sessionAuthFromResult(e){let t={};for(let n of IDENTITY_KEYS)e[n]!==void 0&&(t[n]=e[n]);return t}export{sessionAuthFromResult};
@@ -1,6 +1,6 @@
1
1
  import type { MessageContent } from "#shared/message-content.js";
2
2
  import type { Delivery } from "#shared/delivery.js";
3
- import type { ChannelAdapter } from "#channel/adapter.js";
3
+ import { type ChannelAdapter } from "#channel/adapter.js";
4
4
  import { type ChannelDeliverySource } from "#channel/delivery-metadata.js";
5
5
  import type { SendPayload } from "#channel/routes.js";
6
6
  import { type Session } from "#channel/session.js";
@@ -1 +1 @@
1
- import{createSession,sessionCallbackToTurnCaller}from"#channel/session.js";import{commandDelivery}from"#channel/delivery.js";import{validateDeliveryIdempotencyKey}from"#channel/delivery-idempotency.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{normalizeSendInput,serializeFilePartsInMessage}from"#channel/send-input.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{SessionStrandedError,describeStrandedSession}from"#channel/session-stranded-error.js";import{DEFAULT_TURN_POLICY,controlCommand}from"#channel/types.js";import{isReservedSessionCommandToken}from"#execution/session-inbox/address.js";import{validateSessionHistory}from"#shared/session-history.js";function createChannelAddress(e){let t=e.metadata??{},n=`${e.channelName}:${e.continuationToken}`;if(isReservedSessionCommandToken(n))throw Error(`Channel address "${n}" uses eve's reserved session namespace.`);return{continuationToken:e.continuationToken,async deliver(r,i){validateDeliveryIdempotencyKey(i.idempotencyKey);let a=createChannelDeliveryMetadata({channelKind:`channel:${e.channelName}`,channelName:e.channelName,...t}),o=withValidatedHistory(normalizeSendInput(r)),s=sessionCallbackToTurnCaller(i.callback),c={idempotencyKey:i.idempotencyKey,auth:i.auth,delivery:a,kind:`send`,payload:{...o,message:serializeFilePartsInMessage(o.message)},requestId:t.requestId,turnPolicy:o.message===void 0?void 0:i.turnPolicy??e.turnPolicy??DEFAULT_TURN_POLICY},l=s===void 0?c:{...c,caller:s},u=i.state,d=u===void 0?e.adapter:{...e.adapter,state:{...e.adapter.state,...u}},f={idempotencyKey:i.idempotencyKey,adapter:d,auth:i.auth,capabilities:{requestInput:!0},callback:i.callback,channelName:e.channelName,continuationConflictCommand:l,continuationToken:n,delivery:a,initiatorAuth:i.initiatorAuth,input:{context:o.context,history:o.history,message:serializeFilePartsInMessage(o.message)??``,outputSchema:o.outputSchema,state:o.state},requestId:t.requestId,title:i.title},p=await e.runtime.dispatchContinuation({command:l,continuationToken:n,successor:f});if(p.status===`accepted`)return commandDelivery(e.runtime,p,a.deliveryId);if(p.retryable===!0)throw new SessionNotActiveError({retryable:!0});if(o.answers&&o.answers.length>0)throw new SessionNotActiveError;let m=await e.runtime.createSession(f);return commandDelivery(e.runtime,{status:`accepted`,sessionId:m.sessionId},a.deliveryId)},async create(r){let i=validateSessionHistory(r.history),toSession=n=>createSession(n,e.runtime,{...t,turnPolicy:e.turnPolicy}),a;try{a=await e.runtime.resolveContinuation(n,{runnable:!0})}catch(e){throw SessionStrandedError.is(e)?new SessionStrandedError(e.owner,describeStrandedSession(e.owner,`Call end() on the address, then create() again to start a session from your history.`)):e}if(a!==void 0)return{created:!1,session:toSession(a.sessionId)};let o=r.state,s=await e.runtime.createSession({adapter:o===void 0?e.adapter:{...e.adapter,state:{...e.adapter.state,...o}},auth:r.auth,capabilities:{requestInput:!0},channelName:e.channelName,continuationToken:n,initiatorAuth:r.initiatorAuth,input:i===void 0?{}:{history:i},requestId:t.requestId,title:r.title}),c=await waitForContinuationOwner(e.runtime,n,s.sessionId);return{created:c.sessionId===s.sessionId,session:toSession(c.sessionId)}},async send(e,t){return await this.deliver({message:e},t)},async respond(e,t){if(e===void 0||e.length===0)throw Error(`respond() requires at least one answer.`);return await this.deliver({answers:e},t)},async cancel(t){let r=controlCommand({kind:`cancel`,turnId:t?.turnId},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId)},async compact(t){let r=controlCommand({kind:`compact`},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId)},async clear(t){let r=controlCommand({kind:`clear`},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId)},async end(t){let r=controlCommand({kind:`reset`,reason:t?.reason},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId,{follow:!1})},async resolveSession(){let r=await e.runtime.resolveContinuation(n);return r===void 0?void 0:createSession(r.sessionId,e.runtime,{...t,turnPolicy:e.turnPolicy})}}}function createChannelAddressFn(e){return t=>createChannelAddress({...e,continuationToken:t})}function withValidatedHistory(e){let{history:t,...n}=e,r=validateSessionHistory(t);return r===void 0?n:{...n,history:r}}const CREATE_CLAIM_TIMEOUT_MS=15e3;async function waitForContinuationOwner(e,t,n){let r=Date.now()+CREATE_CLAIM_TIMEOUT_MS;for(let i=25;;i=Math.min(i*2,500)){let a=await e.resolveContinuation(t);if(a!==void 0)return a;if(Date.now()+i>r)throw Error(`create() started session "${n}" for "${t}", but no session claimed the address within ${CREATE_CLAIM_TIMEOUT_MS/1e3}s. Call resolveSession() on the address to find its owner once one does.`);await new Promise(e=>setTimeout(e,i))}}export{createChannelAddress,createChannelAddressFn};
1
+ import{createSession,sessionCallbackToTurnCaller}from"#channel/session.js";import{commandDelivery}from"#channel/delivery.js";import{seedChannelState}from"#channel/adapter.js";import{validateDeliveryIdempotencyKey}from"#channel/delivery-idempotency.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{normalizeSendInput,serializeFilePartsInMessage}from"#channel/send-input.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{SessionStrandedError,describeStrandedSession}from"#channel/session-stranded-error.js";import{DEFAULT_TURN_POLICY,controlCommand}from"#channel/types.js";import{isReservedSessionCommandToken}from"#execution/session-inbox/address.js";import{validateSessionHistory}from"#shared/session-history.js";function createChannelAddress(e){let t=e.metadata??{},n=`${e.channelName}:${e.continuationToken}`;if(isReservedSessionCommandToken(n))throw Error(`Channel address "${n}" uses eve's reserved session namespace.`);return{continuationToken:e.continuationToken,async deliver(r,i){validateDeliveryIdempotencyKey(i.idempotencyKey);let a=createChannelDeliveryMetadata({channelKind:`channel:${e.channelName}`,channelName:e.channelName,...t}),o=withValidatedHistory(normalizeSendInput(r)),s=sessionCallbackToTurnCaller(i.callback),c={idempotencyKey:i.idempotencyKey,auth:i.auth,delivery:a,kind:`send`,payload:{...o,message:serializeFilePartsInMessage(o.message)},requestId:t.requestId,turnPolicy:o.message===void 0?void 0:i.turnPolicy??e.turnPolicy??DEFAULT_TURN_POLICY},l=s===void 0?c:{...c,caller:s},u=i.state,d={...e.adapter,state:seedChannelState(e.adapter.state,u)},f={idempotencyKey:i.idempotencyKey,adapter:d,auth:i.auth,capabilities:{requestInput:!0},callback:i.callback,channelName:e.channelName,continuationConflictCommand:l,continuationToken:n,delivery:a,initiatorAuth:i.initiatorAuth,input:{context:o.context,history:o.history,message:serializeFilePartsInMessage(o.message)??``,outputSchema:o.outputSchema,state:o.state},requestId:t.requestId,title:i.title},p=await e.runtime.dispatchContinuation({command:l,continuationToken:n,successor:f});if(p.status===`accepted`)return commandDelivery(e.runtime,p,a.deliveryId);if(p.retryable===!0)throw new SessionNotActiveError({retryable:!0});if(o.answers&&o.answers.length>0)throw new SessionNotActiveError;let m=await e.runtime.createSession(f);return commandDelivery(e.runtime,{status:`accepted`,sessionId:m.sessionId},a.deliveryId)},async create(r){let i=validateSessionHistory(r.history),toSession=n=>createSession(n,e.runtime,{...t,turnPolicy:e.turnPolicy}),a;try{a=await e.runtime.resolveContinuation(n,{runnable:!0})}catch(e){throw SessionStrandedError.is(e)?new SessionStrandedError(e.owner,describeStrandedSession(e.owner,`Call end() on the address, then create() again to start a session from your history.`)):e}if(a!==void 0)return{created:!1,session:toSession(a.sessionId)};let o=r.state,s=await e.runtime.createSession({adapter:{...e.adapter,state:seedChannelState(e.adapter.state,o)},auth:r.auth,capabilities:{requestInput:!0},channelName:e.channelName,continuationToken:n,initiatorAuth:r.initiatorAuth,input:i===void 0?{}:{history:i},requestId:t.requestId,title:r.title}),c=await waitForContinuationOwner(e.runtime,n,s.sessionId);return{created:c.sessionId===s.sessionId,session:toSession(c.sessionId)}},async send(e,t){return await this.deliver({message:e},t)},async respond(e,t){if(e===void 0||e.length===0)throw Error(`respond() requires at least one answer.`);return await this.deliver({answers:e},t)},async cancel(t){let r=controlCommand({kind:`cancel`,turnId:t?.turnId},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId)},async compact(t){let r=controlCommand({kind:`compact`},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId)},async clear(t){let r=controlCommand({kind:`clear`},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId)},async end(t){let r=controlCommand({kind:`reset`,reason:t?.reason},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId,{follow:!1})},async resolveSession(){let r=await e.runtime.resolveContinuation(n);return r===void 0?void 0:createSession(r.sessionId,e.runtime,{...t,turnPolicy:e.turnPolicy})}}}function createChannelAddressFn(e){return t=>createChannelAddress({...e,continuationToken:t})}function withValidatedHistory(e){let{history:t,...n}=e,r=validateSessionHistory(t);return r===void 0?n:{...n,history:r}}const CREATE_CLAIM_TIMEOUT_MS=15e3;async function waitForContinuationOwner(e,t,n){let r=Date.now()+CREATE_CLAIM_TIMEOUT_MS;for(let i=25;;i=Math.min(i*2,500)){let a=await e.resolveContinuation(t);if(a!==void 0)return a;if(Date.now()+i>r)throw Error(`create() started session "${n}" for "${t}", but no session claimed the address within ${CREATE_CLAIM_TIMEOUT_MS/1e3}s. Call resolveSession() on the address to find its owner once one does.`);await new Promise(e=>setTimeout(e,i))}}export{createChannelAddress,createChannelAddressFn};
@@ -53,7 +53,7 @@ export interface ChannelSource<TState = undefined> {
53
53
  } & SessionControlOptions): Promise<Delivery>;
54
54
  /** Queues context compaction without creating a session. */
55
55
  compact(options?: SessionControlOptions): Promise<Delivery>;
56
- /** Clears model-message history without creating a session. */
56
+ /** Cancels a running turn and every working task, then clears model-message history in place. */
57
57
  clear(options?: SessionControlOptions): Promise<Delivery>;
58
58
  /** Retires the current owner without creating a replacement. */
59
59
  end(options?: {
@@ -1 +1 @@
1
- import{createHash,randomUUID}from"node:crypto";import{commandDelivery}from"#channel/delivery.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{scheduleDisplayName}from"#runtime/schedules/record.js";import{SCHEDULE_APP_AUTH,SCHEDULE_APP_AUTH as SCHEDULE_APP_AUTH$1}from"#channel/schedule-auth.js";import{createCrossChannelToFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,OccurrenceIdKey,ScheduleIdKey,ScheduleInstanceKey}from"#context/keys.js";import{expectFunction}from"#internal/authored-module.js";import{parseSchedulePayload,validateSchedulePayload}from"#runtime/schedules/payload.js";const SCHEDULE_ADAPTER_KIND=`schedule`,SCHEDULE_ADAPTER={kind:SCHEDULE_ADAPTER_KIND};var ScheduleDispatcher=class{runtime;channels;constructor(e){this.runtime=e.runtime,this.channels=e.channels}async trigger(e){let t=new ContextContainer;return t.set(ScheduleIdKey,e.scheduleId),await contextStorage.run(t,()=>this.triggerInScope(e))}async triggerCollection(e){let{envelope:t}=parseSchedulePayload(e.payload,{application:e.payload.eve.application,collection:e.collectionId}),{definition:n}=e,r={...e.occurrence,displayName:scheduleDisplayName(e.occurrence.name)},i=n.preparePayload===void 0?await validateSchedulePayload(n.inputSchema,t.payload):t.payload;await e.verifyDelivery?.();let a=await n.auth({principal:t.principal,payload:i,occurrence:r});if(a===null)throw Error(`Scheduled execution is no longer authorized.`);if(a.principalId!==t.principal.principalId||a.principalType!==t.principal.type||a.authenticator!==t.principal.authenticator||a.issuer!==t.principal.issuer||a.subject!==t.principal.subject)throw Error(`Scheduled execution auth must resolve the schedule creator.`);let o=a,s=new ContextContainer;s.set(ScheduleIdKey,e.collectionId),s.set(AuthKey,o),s.set(OccurrenceIdKey,r.executionId),s.set(ScheduleInstanceKey,r.name);let scheduledToken=(e,t)=>t===void 0?`eve-scheduled-send:${randomUUID()}`:`eve-scheduled-send:${createHash(`sha256`).update(JSON.stringify([r.scheduleId,e,t])).digest(`hex`)}`,freshRun=e=>({...e,auth:o,initiatorAuth:o,capabilities:{requestInput:!1},continuationToken:scheduledToken(e.continuationToken,e.idempotencyKey),continuationConflictCommand:e.idempotencyKey===void 0?void 0:e.continuationConflictCommand});return await contextStorage.run(s,async()=>{let e={...this.runtime,resolveContinuation:async()=>void 0,dispatchContinuation:async e=>{let{command:t}=e;if(t.kind!==`send`)throw Error(`Scheduled channel receive can only start a fresh session.`);return t.idempotencyKey===void 0?{status:`session_not_active`}:await this.runtime.dispatchContinuation({command:t,continuationToken:scheduledToken(e.continuationToken,t.idempotencyKey),successor:e.successor&&freshRun(e.successor)})},createSession:async e=>await this.runtime.createSession(freshRun(e))},{args:t,sessions:a,waitUntilTasks:s}=this.createHandlerContext(e);return await n.run({payload:i,occurrence:r,auth:o,to:(e,n)=>({send:(r,i)=>t.to(e,n).send(r,{...i,auth:o})}),waitUntil:t.waitUntil}),await Promise.all(s),{sessions:a,waitUntilTasks:s}})}async triggerInScope(e){let{args:t,sessions:n,waitUntilTasks:r}=this.createHandlerContext();if(e.run)await e.run(t);else if(e.markdown!==void 0)n.push(await this.runMarkdown(e.markdown));else throw Error(`Schedule "${e.scheduleId}" has neither "run" nor "markdown" — at least one must be set.`);return{sessions:n,waitUntilTasks:r}}createHandlerContext(e=this.runtime){let t=[],n=[],r=createCrossChannelToFn(e,toCrossChannelTargets(this.channels));return{args:{appAuth:SCHEDULE_APP_AUTH$1,to(e,n){let i=r(e,n);return{async send(e,n){let r=await i.send(e,n);return t.push(r),r}}},waitUntil(e){n.push(e)}},sessions:t,waitUntilTasks:n}}async runMarkdown(e){let t=createChannelDeliveryMetadata({channelKind:`schedule`,channelName:`schedule`}),n=await this.runtime.createSession({delivery:t,adapter:SCHEDULE_ADAPTER,auth:SCHEDULE_APP_AUTH$1,input:{message:e}});return commandDelivery(this.runtime,{status:`accepted`,sessionId:n.sessionId},t.deliveryId)}};function expectScheduleRun(e,t,n){let r=e;if(typeof r!=`object`||!r)throw Error(`Schedule export "${n??`default`}" from "${t}" must be an object.`);return expectFunction(r.run,`Expected the schedule export "${n??`default`}" from "${t}" to export a \`run\` handler function.`)}export{SCHEDULE_ADAPTER,SCHEDULE_ADAPTER_KIND,SCHEDULE_APP_AUTH,ScheduleDispatcher,expectScheduleRun};
1
+ import{createHash,randomUUID}from"node:crypto";import{commandDelivery}from"#channel/delivery.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{scheduleDisplayName}from"#runtime/schedules/record.js";import{SCHEDULE_APP_AUTH,SCHEDULE_APP_AUTH as SCHEDULE_APP_AUTH$1}from"#channel/schedule-auth.js";import{createCrossChannelToFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,OccurrenceIdKey,ScheduleIdKey,ScheduleInstanceKey}from"#context/keys.js";import{expectFunction}from"#internal/authored-module.js";import{parseSchedulePayload,validateSchedulePayload}from"#runtime/schedules/payload.js";const SCHEDULE_ADAPTER_KIND=`schedule`,SCHEDULE_ADAPTER={kind:SCHEDULE_ADAPTER_KIND};var ScheduleDispatcher=class{runtime;channels;constructor(e){this.runtime=e.runtime,this.channels=e.channels}async trigger(e){let t=new ContextContainer;return t.set(ScheduleIdKey,e.scheduleId),await contextStorage.run(t,()=>this.triggerInScope(e))}async triggerCollection(e){let{envelope:t}=parseSchedulePayload(e.payload,{application:e.payload.eve.application,collection:e.collectionId}),{definition:n}=e,r={...e.occurrence,displayName:scheduleDisplayName(e.occurrence.name)},i=n.preparePayload===void 0?await validateSchedulePayload(n.inputSchema,t.payload):t.payload;await e.verifyDelivery?.();let a=await n.auth({principal:t.principal,payload:i,occurrence:r});if(a===null)throw Error(`Scheduled execution is no longer authorized.`);if(a.principalId!==t.principal.principalId||a.principalType!==t.principal.type||a.authenticator!==t.principal.authenticator||a.issuer!==t.principal.issuer||a.subject!==t.principal.subject)throw Error(`Scheduled execution auth must resolve the schedule creator.`);let o=a,s=new ContextContainer;s.set(ScheduleIdKey,e.collectionId),s.set(AuthKey,o),s.set(OccurrenceIdKey,r.executionId),s.set(ScheduleInstanceKey,r.name);let scheduledToken=(e,t)=>t===void 0?`eve-scheduled-send:${randomUUID()}`:`eve-scheduled-send:${createHash(`sha256`).update(JSON.stringify([r.scheduleId,e,t])).digest(`hex`)}`,freshRun=e=>({...e,auth:o,initiatorAuth:o,capabilities:{requestInput:!1},continuationToken:scheduledToken(e.continuationToken,e.idempotencyKey),continuationConflictCommand:e.idempotencyKey===void 0?void 0:e.continuationConflictCommand});return await contextStorage.run(s,async()=>{let e={...this.runtime,resolveContinuation:async()=>void 0,dispatchContinuation:async e=>{let{command:t}=e;if(t.kind!==`send`)throw Error(`Scheduled channel receive can only start a fresh session.`);return t.idempotencyKey===void 0?{status:`session_not_active`}:await this.runtime.dispatchContinuation({command:t,continuationToken:scheduledToken(e.continuationToken,t.idempotencyKey),successor:e.successor&&freshRun(e.successor)})},createSession:async e=>await this.runtime.createSession(freshRun(e))},{args:t,sessions:a,waitUntilTasks:s}=this.createHandlerContext(e);return await n.run({payload:i,occurrence:r,auth:o,to:(e,n)=>({send:(r,i)=>t.to(e,n).send(r,{...i,auth:o})}),waitUntil:t.waitUntil}),await Promise.all(s),{sessions:a,waitUntilTasks:s}})}async triggerInScope(e){let{args:t,sessions:n,waitUntilTasks:r}=this.createHandlerContext();if(e.run)await e.run(t);else if(e.markdown!==void 0)n.push(await this.runMarkdown(e.markdown));else throw Error(`Schedule "${e.scheduleId}" has neither "run" nor "markdown" — at least one must be set.`);return{sessions:n,waitUntilTasks:r}}createHandlerContext(e=this.runtime){let t=[],n=[],r=createCrossChannelToFn(e,toCrossChannelTargets(this.channels),{acceptedDeploymentId:process.env.VERCEL_DEPLOYMENT_ID?.trim()||void 0});return{args:{appAuth:SCHEDULE_APP_AUTH$1,to(e,n){let i=r(e,n);return{async send(e,n){let r=await i.send(e,n);return t.push(r),r}}},waitUntil(e){n.push(e)}},sessions:t,waitUntilTasks:n}}async runMarkdown(e){let t=createChannelDeliveryMetadata({channelKind:`schedule`,channelName:`schedule`}),n=await this.runtime.createSession({delivery:t,adapter:SCHEDULE_ADAPTER,auth:SCHEDULE_APP_AUTH$1,input:{message:e}});return commandDelivery(this.runtime,{status:`accepted`,sessionId:n.sessionId},t.deliveryId)}};function expectScheduleRun(e,t,n){let r=e;if(typeof r!=`object`||!r)throw Error(`Schedule export "${n??`default`}" from "${t}" must be an object.`);return expectFunction(r.run,`Expected the schedule export "${n??`default`}" from "${t}" to export a \`run\` handler function.`)}export{SCHEDULE_ADAPTER,SCHEDULE_ADAPTER_KIND,SCHEDULE_APP_AUTH,ScheduleDispatcher,expectScheduleRun};
@@ -103,6 +103,8 @@ export interface ChannelDeliveryMetadata {
103
103
  readonly channelKind: string;
104
104
  readonly channelName: string;
105
105
  readonly deliveryId: string;
106
+ /** The hook whose `ctx.continue()` made the delivery, recorded on its `delivery.admitted`. */
107
+ readonly hook?: string;
106
108
  readonly requestId?: string;
107
109
  readonly requestTraceContext?: SessionTraceSeed;
108
110
  }