eve 0.88.1 → 0.90.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 (102) hide show
  1. package/CHANGELOG.md +25 -11
  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/jwt-ecdsa.js +1 -1
  7. package/dist/src/channel/auth/jwt-hmac.js +1 -1
  8. package/dist/src/channel/auth/oidc.js +1 -1
  9. package/dist/src/channel/auth/result.d.ts +2 -3
  10. package/dist/src/channel/auth/result.js +1 -1
  11. package/dist/src/channel/channel-address.d.ts +1 -1
  12. package/dist/src/channel/channel-address.js +1 -1
  13. package/dist/src/channel/schedule.js +1 -1
  14. package/dist/src/chunks/{use-eve-agent-BExXjBv6.js → use-eve-agent-Bwloorf8.js} +96 -65
  15. package/dist/src/chunks/{use-eve-agent-C0KHCyb9.js → use-eve-agent-XCB0-tLX.js} +96 -65
  16. package/dist/src/cli/dev/environment.js +1 -1
  17. package/dist/src/cli/dev/tui/remote-connection-probe.js +1 -1
  18. package/dist/src/cli/dev/tui/remote-connection-types.d.ts +1 -0
  19. package/dist/src/cli/dev/tui/runner.js +2 -2
  20. package/dist/src/cli/dev/tui/status-line.d.ts +2 -2
  21. package/dist/src/cli/dev/tui/status-line.js +1 -1
  22. package/dist/src/client/agent-info-schema.d.ts +341 -326
  23. package/dist/src/client/agent-info-schema.js +1 -1
  24. package/dist/src/client/agent-info-types.d.ts +13 -10
  25. package/dist/src/client/client-error.d.ts +1 -1
  26. package/dist/src/client/client.d.ts +5 -3
  27. package/dist/src/client/client.js +1 -1
  28. package/dist/src/client/conversation.js +1 -1
  29. package/dist/src/client/transcript.d.ts +7 -4
  30. package/dist/src/client/transcript.js +1 -1
  31. package/dist/src/compiled/.vendor-stamp.json +1 -1
  32. package/dist/src/evals/target.js +1 -1
  33. package/dist/src/eve-channel/auth.d.ts +19 -0
  34. package/dist/src/eve-channel/auth.js +1 -0
  35. package/dist/src/eve-channel/index.d.ts +1 -0
  36. package/dist/src/eve-channel/index.js +1 -1
  37. package/dist/src/eve-channel/types.d.ts +23 -4
  38. package/dist/src/execution/catalog/connection-entry.js +1 -1
  39. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  40. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  41. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  42. package/dist/src/extensions/git/extension/extension.d.ts +12 -9
  43. package/dist/src/extensions/git/extension/extension.js +1 -1
  44. package/dist/src/extensions/git/extension/lib/gh-tool.d.ts +4 -12
  45. package/dist/src/extensions/git/extension/lib/gh-tool.js +1 -1
  46. package/dist/src/extensions/git/extension/lib/github-guidance.js +4 -4
  47. package/dist/src/extensions/git/extension/lib/github-shell-schema.d.ts +3 -5
  48. package/dist/src/extensions/git/extension/lib/github-shell-schema.js +1 -1
  49. package/dist/src/extensions/git/extension/lib/github-shell.d.ts +31 -21
  50. package/dist/src/extensions/git/extension/lib/github-shell.js +1 -1
  51. package/dist/src/extensions/git/extension/lib/signed-commit.js +1 -1
  52. package/dist/src/extensions/git/tools.d.ts +2 -10
  53. package/dist/src/internal/application/stamped-package-version.js +1 -1
  54. package/dist/src/internal/authored-module-graph.js +1 -1
  55. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +2 -2
  56. package/dist/src/protocol/routes.d.ts +7 -1
  57. package/dist/src/protocol/routes.js +1 -1
  58. package/dist/src/protocol/session-events/families/delivery.d.ts +3 -2
  59. package/dist/src/public/channels/github/githubChannel.js +1 -1
  60. package/dist/src/public/channels/github/state.d.ts +7 -0
  61. package/dist/src/public/channels/github/state.js +1 -1
  62. package/dist/src/public/channels/mcp.js +1 -1
  63. package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
  64. package/dist/src/public/connections/index.d.ts +1 -1
  65. package/dist/src/public/definitions/channel.js +1 -1
  66. package/dist/src/public/definitions/connections/tool-call.d.ts +2 -2
  67. package/dist/src/reactions/frame.js +1 -1
  68. package/dist/src/runtime/channels/registry.d.ts +2 -2
  69. package/dist/src/runtime/channels/registry.js +1 -1
  70. package/dist/src/runtime/connections/approval-scope.d.ts +9 -0
  71. package/dist/src/runtime/connections/approval-scope.js +1 -0
  72. package/dist/src/runtime/connections/mcp-client.d.ts +1 -1
  73. package/dist/src/runtime/connections/mcp-client.js +1 -1
  74. package/dist/src/runtime/connections/provided-arguments.js +1 -1
  75. package/dist/src/runtime/subagents/workflow.js +1 -1
  76. package/dist/src/setup/scaffold/create/project.js +1 -1
  77. package/dist/src/shared/agent-info-access.d.ts +5 -0
  78. package/dist/src/shared/agent-info-access.js +1 -0
  79. package/dist/src/shared/connection-types.d.ts +21 -4
  80. package/dist/src/shared/session-history.d.ts +4 -2
  81. package/dist/src/shared/session-history.js +1 -1
  82. package/dist/src/svelte/index.js +1 -1
  83. package/dist/src/svelte/use-eve-agent.js +1 -1
  84. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  85. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  86. package/dist/src/vue/index.js +1 -1
  87. package/dist/src/vue/use-eve-agent.js +1 -1
  88. package/docs/channels/custom.mdx +2 -0
  89. package/docs/channels/eve.mdx +5 -3
  90. package/docs/code-extension.mdx +17 -60
  91. package/docs/concepts/execution-model-and-durability.mdx +1 -1
  92. package/docs/concepts/sessions-runs-and-streaming.md +9 -3
  93. package/docs/connections/overview.mdx +30 -0
  94. package/docs/evals/targets.mdx +2 -0
  95. package/docs/evals/tool-stubs.mdx +4 -4
  96. package/docs/guides/auth-and-route-protection.md +16 -3
  97. package/docs/guides/client/overview.mdx +6 -2
  98. package/docs/guides/client/streaming.mdx +1 -1
  99. package/docs/guides/frontend/use-eve-agent.mdx +1 -1
  100. package/docs/guides/prepare-for-1-0.md +23 -1
  101. package/docs/tools/human-in-the-loop.md +1 -1
  102. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,19 +1,33 @@
1
- # eve 0.88.1
1
+ # eve 0.90.0
2
2
 
3
- Released 2026-10-29 · [Compare with 0.88.0](https://github.com/vercel/eve/compare/eve%400.88.0...eve%400.88.1)
3
+ Released 2026-10-29 · [Compare with 0.89.0](https://github.com/vercel/eve/compare/eve%400.89.0...eve%400.90.0)
4
+
5
+ ## Breaking Changes
6
+
7
+ - `GET /eve/v1/info` now serves only operator principals and returns 403 to end users.
8
+ The route answers `service` and `runtime` principals and callers a configured `localDev()` admits, and returns `403` with code `info_forbidden` to everyone else. To give another credential access, return `principalType: "service"` from its `AuthFn`, or `allowAgentInfo: true` from an `EveAuthFn`; `allowAgentInfo: false` denies a caller that would otherwise qualify. The payload stays at version 5 with every field, and `client.info()` now ignores unknown fields and reads unknown enum strings as `"unrecognized"`, so handle that value when switching on fields such as `mode` or `sourceKind`. `kind` discriminants stay closed, so a new variant needs a version bump. ([#5542](https://github.com/vercel/eve/pull/5542))
9
+ - Tool-stub grants on Vercel OIDC subjects move from `vercelOidc` to the new `eveVercelOidc` helper in `eve/channels/eve`.
10
+ `vercelOidc` and `AuthResult` from `eve/channels/auth` now carry identity only. Rename grant-bearing `vercelOidc` calls to `eveVercelOidc`; the options are unchanged. `vercelOidc` now throws when a `subjects` entry is not a string. Type custom callbacks that return `allowToolStubs` as `EveAuthFn` from `eve/channels/eve`. ([#5542](https://github.com/vercel/eve/pull/5542))
4
11
 
5
12
  ## Features
6
13
 
7
- - Approval spans now record who approved or denied the call as `agent.approval.responder.type` and `agent.approval.responder.id`, an approved call's tool span records its approver as `agent.tool.approver.type` and `agent.tool.approver.id`, and the `interaction.settled` instrumentation event carries the same `responder`.
8
- An approved call runs as the requester, so until now traces showed only the requester and an audit had to read the session stream to find the approver. The responder's id follows the same rule as the turn's principal ids: it is recorded only when the trace policy records both inputs and outputs and the conversation is public or running in development. ([#5596](https://github.com/vercel/eve/pull/5596))
9
- - The MCP channel's `agent_get` now returns an optional `statusMessage` while an invocation is `working`.
10
- It names the tool call that is running, using the tool's activity label when it has one, so MCP clients can show progress instead of a bare `working`. ([#5314](https://github.com/vercel/eve/pull/5314))
14
+ - A connection's `headers` and `toolCall.providedArguments` callbacks now receive `ctx.approval.responder` while an approved tool call runs, so an MCP or OpenAPI server can act for the person who approved it.
15
+ As in a `defineTool` tool, `ctx.approval.responder.getToken(provider)` resolves the approver's token without starting a sign-in. The call still runs as the requester, and its `auth` token stays the requester's. `ctx.approval` is absent for calls that needed no approval and while eve lists the connection's tools. ([#5605](https://github.com/vercel/eve/pull/5605))
11
16
 
12
17
  ## Bug Fixes
13
18
 
14
- - Release notes now list breaking changes first and use plain headings, one paragraph per change, and a single compare link.
15
- A `minor` changeset always appears under Breaking Changes, so breaking changes merged with an internal PR title are no longer left out. The 0.86.0 and 0.87.0 notes now include the two breaking changes they missed. ([#5588](https://github.com/vercel/eve/pull/5588))
16
- - Upgrade `undici` to `8.12.3` for the security fixes published in `8.12.2`.
17
- A TLS 1.2 server that renegotiates to a certificate for another host now fails the `web_fetch` request instead of crashing the process. Thanks @pedro757 for reporting this in #5589. ([#5591](https://github.com/vercel/eve/pull/5591))
19
+ - `eve build` no longer fails with `Cannot access '<name>' before initialization` while evaluating authored modules whose shared bundle chunks import each other.
20
+ Compile now keeps top-level evaluation in source order. Thanks @blaesild for reporting this and pinpointing the fix in #5514. ([#5516](https://github.com/vercel/eve/pull/5516))
21
+ - Resumed sessions now fill in top-level channel `state` fields that a later deploy added to the `defineChannel` seed (or to a built-in channel's state), instead of leaving them `undefined`.
22
+ This runs at every step boundary, so a seed field a session deletes from `channel.state` comes back at the next step. Set the field to `null` (or `undefined`) to clear it instead. ([#5549](https://github.com/vercel/eve/pull/5549))
23
+ - A connection tool call with an approval policy now runs once the sign-in it stopped for completes, instead of failing as if its connection had changed.
24
+ Thanks @exbald for reporting #5564. ([#5570](https://github.com/vercel/eve/pull/5570))
25
+ - A connection tool call no longer fails with `Instance type "null" is invalid` when the model omits an argument whose schema declares a `null` default it does not allow, such as Pydantic's `{ "type": "string", "default": null }` for `x: str = None`. eve fills schema defaults once, when the call runs, instead of filling them before approval and rejecting them on the second check. ([#5510](https://github.com/vercel/eve/pull/5510))
26
+ - The GitHub channel now applies the state a later webhook brings to an existing session, so a turn after a push (or a comment after a push) checks out the new PR head instead of the old one, and reacts to the comment that triggered it.
27
+ Thanks @blicksky for reporting this in #1554, and @haydenbleasel for reporting the reaction symptom. ([#4874](https://github.com/vercel/eve/pull/4874))
28
+ - Messages a schedule sends with `to()` on Vercel now carry the deployment that ran the schedule, so an idle session they continue hands off to the new deployment like one a route reaches.
29
+ Thanks @dohooo for reporting this in #5598. ([#5599](https://github.com/vercel/eve/pull/5599))
30
+ - `eve dev --agent <name>` in an agent workspace now uses the model connection saved by `/login`.
31
+ Previously the dev host looked for it under the member directory, so a Vercel account sign-in failed every model call with "The model connection is unavailable". Thanks @cnaccio for reporting this in #5505. ([#5506](https://github.com/vercel/eve/pull/5506))
18
32
 
19
- 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.88.1/packages/eve/CHANGELOG.md).
33
+ 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.90.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{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};
@@ -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};