eve 0.16.0 → 0.16.1

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 (67) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/src/channel/compiled-channel.d.ts +2 -0
  3. package/dist/src/channel/cors.d.ts +43 -0
  4. package/dist/src/channel/cors.js +1 -0
  5. package/dist/src/cli/dev/tui/agent-info-probe.d.ts +16 -0
  6. package/dist/src/cli/dev/tui/agent-info-probe.js +1 -0
  7. package/dist/src/cli/dev/tui/mcp-connection-status.d.ts +19 -0
  8. package/dist/src/cli/dev/tui/mcp-connection-status.js +1 -0
  9. package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
  10. package/dist/src/cli/dev/tui/remote-connection-probe.js +1 -1
  11. package/dist/src/cli/dev/tui/runner.d.ts +4 -0
  12. package/dist/src/cli/dev/tui/runner.js +1 -1
  13. package/dist/src/cli/dev/tui/setup-commands.d.ts +1 -0
  14. package/dist/src/cli/dev/tui/setup-commands.js +1 -1
  15. package/dist/src/cli/dev/tui/setup-panel.js +1 -1
  16. package/dist/src/cli/dev/tui/tui.js +1 -1
  17. package/dist/src/compiler/manifest.d.ts +8 -2
  18. package/dist/src/compiler/manifest.js +1 -1
  19. package/dist/src/compiler/normalize-channel.js +1 -1
  20. package/dist/src/context/providers/connection-key.d.ts +9 -0
  21. package/dist/src/context/providers/connection-key.js +1 -0
  22. package/dist/src/context/providers/connection.d.ts +1 -9
  23. package/dist/src/context/providers/connection.js +1 -1
  24. package/dist/src/harness/input-requests.d.ts +1 -0
  25. package/dist/src/harness/input-requests.js +1 -1
  26. package/dist/src/harness/tool-loop.js +1 -1
  27. package/dist/src/internal/application/package.js +1 -1
  28. package/dist/src/internal/nitro/host/channel-routes.d.ts +2 -0
  29. package/dist/src/internal/nitro/host/channel-routes.js +5 -3
  30. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  31. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  32. package/dist/src/public/channels/eve.d.ts +31 -0
  33. package/dist/src/public/channels/eve.js +1 -1
  34. package/dist/src/public/channels/github/githubChannel.js +1 -1
  35. package/dist/src/public/channels/github/inbound-types.d.ts +189 -0
  36. package/dist/src/public/channels/github/inbound-types.js +1 -0
  37. package/dist/src/public/channels/github/inbound.d.ts +2 -190
  38. package/dist/src/public/channels/github/inbound.js +2 -2
  39. package/dist/src/public/channels/index.d.ts +1 -1
  40. package/dist/src/public/definitions/defineChannel.d.ts +10 -0
  41. package/dist/src/public/definitions/defineChannel.js +1 -1
  42. package/dist/src/runtime/connections/scoped-authorization.d.ts +9 -0
  43. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  44. package/dist/src/runtime/connections/types.d.ts +4 -4
  45. package/dist/src/runtime/framework-channels/index.js +1 -1
  46. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +1 -1
  47. package/dist/src/runtime/framework-tools/index.d.ts +1 -1
  48. package/dist/src/runtime/framework-tools/index.js +1 -1
  49. package/dist/src/runtime/framework-tools/skill.js +1 -1
  50. package/dist/src/runtime/resolve-channel.js +1 -1
  51. package/dist/src/runtime/types.d.ts +2 -0
  52. package/dist/src/setup/boxes/select-connections.js +1 -1
  53. package/dist/src/setup/cli/option-row.d.ts +2 -0
  54. package/dist/src/setup/cli/option-row.js +1 -1
  55. package/dist/src/setup/flows/connections.d.ts +1 -0
  56. package/dist/src/setup/flows/connections.js +2 -2
  57. package/dist/src/setup/scaffold/create/project.js +1 -1
  58. package/docs/channels/custom.mdx +19 -0
  59. package/docs/channels/eve.mdx +23 -0
  60. package/docs/concepts/sessions-runs-and-streaming.md +2 -0
  61. package/docs/connections/mcp.mdx +161 -19
  62. package/docs/connections/openapi.mdx +133 -36
  63. package/docs/connections/overview.mdx +4 -4
  64. package/docs/patterns/multi-tenant-approvals.md +4 -0
  65. package/docs/patterns/multi-tenant-auth.md +156 -37
  66. package/docs/tools/human-in-the-loop.md +3 -1
  67. package/package.json +1 -1
@@ -1,193 +1,6 @@
1
1
  import type { UserContent } from "ai";
2
- import { type JsonObject } from "#shared/json.js";
3
- /** GitHub conversation kinds represented by the channel state. */
4
- export type GitHubConversationKind = "issue" | "pull_request" | "review_thread";
5
- /** Stable repository identity normalized from webhook payloads. */
6
- export interface GitHubRepositoryRef {
7
- readonly fullName: string;
8
- readonly id: number;
9
- readonly name: string;
10
- readonly owner: string;
11
- readonly private: boolean;
12
- }
13
- /** GitHub actor metadata normalized from webhook payloads. */
14
- export interface GitHubUser {
15
- readonly htmlUrl: string | undefined;
16
- readonly id: number;
17
- readonly login: string;
18
- readonly type: string;
19
- readonly url: string | undefined;
20
- }
21
- /** Verified GitHub webhook delivery headers. */
22
- export interface GitHubDelivery {
23
- readonly event: string;
24
- readonly hookId: string | undefined;
25
- readonly id: string;
26
- }
27
- /** Channel-local conversation reference. */
28
- export interface GitHubConversationRef {
29
- readonly issueNumber: number | null;
30
- readonly kind: GitHubConversationKind;
31
- readonly pullRequestNumber: number | null;
32
- }
33
- /**
34
- * Normalized GitHub comment handed to the `onComment` hook. Covers issue and PR
35
- * timeline comments and inline review comments alike; `ctx.conversation.kind`
36
- * distinguishes them.
37
- */
38
- export interface GitHubComment {
39
- readonly author: GitHubUser | undefined;
40
- readonly body: string;
41
- readonly htmlUrl: string | undefined;
42
- readonly id: number;
43
- readonly raw: JsonObject;
44
- readonly url: string | undefined;
45
- }
46
- /** Normalized issue/PR timeline comment. */
47
- export interface GitHubIssueComment {
48
- readonly author: GitHubUser | undefined;
49
- readonly body: string;
50
- readonly htmlUrl: string | undefined;
51
- readonly id: number;
52
- readonly issueNumber: number;
53
- readonly pullRequestNumber: number | null;
54
- readonly raw: JsonObject;
55
- readonly url: string | undefined;
56
- }
57
- /** Normalized inline pull-request review comment. */
58
- export interface GitHubPullRequestReviewComment {
59
- readonly author: GitHubUser | undefined;
60
- readonly body: string;
61
- readonly htmlUrl: string | undefined;
62
- readonly id: number;
63
- readonly inReplyToId: number | null;
64
- readonly pullRequestNumber: number;
65
- readonly raw: JsonObject;
66
- readonly reviewThreadRootCommentId: number;
67
- readonly url: string | undefined;
68
- }
69
- /**
70
- * Common `issues` webhook actions, kept open to any action GitHub sends so
71
- * authors get autocomplete without losing forward compatibility.
72
- */
73
- export type GitHubIssueAction = "assigned" | "closed" | "edited" | "labeled" | "opened" | "reopened" | "unassigned" | "unlabeled" | (string & {});
74
- /** Common `pull_request` webhook actions, kept open to any action GitHub sends. */
75
- export type GitHubPullRequestAction = "closed" | "edited" | "labeled" | "opened" | "ready_for_review" | "reopened" | "synchronize" | "unlabeled" | (string & {});
76
- /** Normalized issue event payload. */
77
- export interface GitHubIssueEvent {
78
- readonly action: GitHubIssueAction;
79
- readonly issueNumber: number;
80
- readonly raw: JsonObject;
81
- }
82
- /** Normalized pull-request event payload. */
83
- export interface GitHubPullRequestEvent {
84
- readonly action: GitHubPullRequestAction;
85
- readonly headSha: string | null;
86
- readonly pullRequestNumber: number;
87
- readonly raw: JsonObject;
88
- }
89
- /** GitHub App identity attached to CI webhook payloads. */
90
- export interface GitHubAppRef {
91
- readonly slug: string | null;
92
- }
93
- /** Common fields normalized from GitHub CI webhook payloads. */
94
- export interface GitHubCiEvent {
95
- readonly action: string;
96
- readonly app: GitHubAppRef;
97
- readonly conclusion: string | null;
98
- readonly headSha: string | null;
99
- readonly pullRequests: readonly number[];
100
- readonly raw: JsonObject;
101
- readonly status: string | null;
102
- }
103
- /** Normalized `check_suite` webhook payload. */
104
- export interface GitHubCheckSuiteEvent extends GitHubCiEvent {
105
- readonly checkSuiteId: number;
106
- }
107
- /** Normalized `check_run` webhook payload. */
108
- export interface GitHubCheckRunEvent extends GitHubCiEvent {
109
- readonly checkRunId: number;
110
- }
111
- /** Normalized `workflow_run` webhook payload. */
112
- export interface GitHubWorkflowRunEvent extends GitHubCiEvent {
113
- readonly workflowRunId: number;
114
- }
115
- /** Normalized payload accepted by one of the GitHub CI event hooks. */
116
- export type GitHubCiPayload = GitHubCheckRunEvent | GitHubCheckSuiteEvent | GitHubWorkflowRunEvent;
117
- export interface GitHubPingEvent extends GitHubInboundEventBase {
118
- readonly kind: "ping";
119
- }
120
- export interface GitHubIssueCommentEvent extends GitHubInboundEventBase {
121
- readonly action: string;
122
- readonly baseRef: string | null;
123
- readonly baseSha: string | null;
124
- readonly comment: GitHubIssueComment;
125
- readonly conversation: GitHubConversationRef;
126
- readonly defaultBranch: string | null;
127
- readonly headRef: string | null;
128
- readonly headSha: string | null;
129
- readonly kind: "issue_comment";
130
- }
131
- export interface GitHubPullRequestReviewCommentEvent extends GitHubInboundEventBase {
132
- readonly action: string;
133
- readonly baseRef: string | null;
134
- readonly baseSha: string | null;
135
- readonly comment: GitHubPullRequestReviewComment;
136
- readonly conversation: GitHubConversationRef;
137
- readonly defaultBranch: string | null;
138
- readonly headRef: string | null;
139
- readonly headSha: string | null;
140
- readonly kind: "pull_request_review_comment";
141
- }
142
- export interface GitHubIssueWebhookEvent extends GitHubInboundEventBase {
143
- readonly action: string;
144
- readonly conversation: GitHubConversationRef;
145
- readonly issue: GitHubIssueEvent;
146
- readonly kind: "issues";
147
- }
148
- export interface GitHubPullRequestWebhookEvent extends GitHubInboundEventBase {
149
- readonly action: string;
150
- readonly baseRef: string | null;
151
- readonly baseSha: string | null;
152
- readonly conversation: GitHubConversationRef;
153
- readonly defaultBranch: string | null;
154
- readonly headRef: string | null;
155
- readonly headSha: string | null;
156
- readonly kind: "pull_request";
157
- readonly pullRequest: GitHubPullRequestEvent;
158
- }
159
- export interface GitHubCheckSuiteWebhookEvent extends GitHubInboundEventBase {
160
- readonly checkSuite: GitHubCheckSuiteEvent;
161
- readonly conversation: GitHubConversationRef;
162
- readonly kind: "check_suite";
163
- }
164
- export interface GitHubCheckRunWebhookEvent extends GitHubInboundEventBase {
165
- readonly checkRun: GitHubCheckRunEvent;
166
- readonly conversation: GitHubConversationRef;
167
- readonly kind: "check_run";
168
- }
169
- export interface GitHubWorkflowRunWebhookEvent extends GitHubInboundEventBase {
170
- readonly conversation: GitHubConversationRef;
171
- readonly kind: "workflow_run";
172
- readonly workflowRun: GitHubWorkflowRunEvent;
173
- }
174
- /** Parsed CI webhook envelopes consumed by the GitHub channel. */
175
- export type GitHubCiWebhookEvent = GitHubCheckRunWebhookEvent | GitHubCheckSuiteWebhookEvent | GitHubWorkflowRunWebhookEvent;
176
- interface GitHubInboundEventBase {
177
- readonly delivery: GitHubDelivery;
178
- readonly installationId: number | undefined;
179
- readonly raw: JsonObject;
180
- readonly repository: GitHubRepositoryRef;
181
- readonly sender: GitHubUser;
182
- }
183
- /** Parsed GitHub webhook event shape consumed by the channel. */
184
- export type GitHubInboundEvent = GitHubCheckRunWebhookEvent | GitHubCheckSuiteWebhookEvent | GitHubIssueCommentEvent | GitHubIssueWebhookEvent | GitHubPingEvent | GitHubPullRequestReviewCommentEvent | GitHubPullRequestWebhookEvent | GitHubWorkflowRunWebhookEvent;
185
- /** Parsed mention trigger for a bot-directed GitHub comment. */
186
- export interface GitHubCommentTrigger {
187
- readonly kind: "mention";
188
- readonly message: string;
189
- readonly token: string;
190
- }
2
+ import type { GitHubCommentTrigger, GitHubConversationKind, GitHubInboundEvent, GitHubRepositoryRef, GitHubUser } from "#public/channels/github/inbound-types.js";
3
+ export type { GitHubAppRef, GitHubCheckRunEvent, GitHubCheckRunWebhookEvent, GitHubCheckSuiteEvent, GitHubCheckSuiteWebhookEvent, GitHubCiEvent, GitHubCiPayload, GitHubCiWebhookEvent, GitHubComment, GitHubCommentTrigger, GitHubConversationKind, GitHubConversationRef, GitHubDelivery, GitHubInboundEvent, GitHubIssueAction, GitHubIssueComment, GitHubIssueCommentEvent, GitHubIssueEvent, GitHubIssueWebhookEvent, GitHubPullRequestAction, GitHubPullRequestEvent, GitHubPullRequestReviewComment, GitHubPullRequestReviewCommentEvent, GitHubPullRequestWebhookEvent, GitHubRepositoryRef, GitHubUser, GitHubWorkflowRunEvent, GitHubWorkflowRunWebhookEvent, } from "#public/channels/github/inbound-types.js";
191
4
  /** Builds the channel-local continuation token for a GitHub conversation. */
192
5
  export declare function githubContinuationToken(input: {
193
6
  readonly conversationKind: GitHubConversationKind;
@@ -225,4 +38,3 @@ export declare function formatGitHubContextBlock(input: {
225
38
  }): string;
226
39
  /** Prepends a `<github_context>` block to the inbound turn message. */
227
40
  export declare function prependGitHubContext(message: string | UserContent, block: string): string | UserContent;
228
- export {};
@@ -1,2 +1,2 @@
1
- import{isObject}from"#shared/guards.js";import{parseJsonObject}from"#shared/json.js";function githubContinuationToken(e){return e.conversationKind===`issue`?`repo:${e.repositoryId}:issue:${requiredNumber(e.issueNumber,`issueNumber`)}`:e.conversationKind===`pull_request`?`repo:${e.repositoryId}:pull:${requiredNumber(e.pullRequestNumber,`pullRequestNumber`)}`:`repo:${e.repositoryId}:pull:${requiredNumber(e.pullRequestNumber,`pullRequestNumber`)}:review-comment:${requiredNumber(e.reviewThreadRootCommentId,`reviewThreadRootCommentId`)}`}function shouldDispatchGitHubComment(e){return isIgnoredGitHubComment(e.body,e.author,e.botName)?!1:extractGitHubCommentTrigger(e)!==null}function extractGitHubCommentTrigger(e){let t=e.botName?.trim();if(!t)return null;let n=RegExp(`@${escapeRegExp(t)}(?=$|[^A-Za-z0-9_-])`,`iu`).exec(e.body);if(n===null)return null;let r=n.index,i=r+n[0].length;return{kind:`mention`,message:`${e.body.slice(0,r)}${e.body.slice(i)}`.trim(),token:n[0]}}function parseGitHubWebhookEvent(e){let t=e.headers.get(`x-github-event`)??``,n=e.headers.get(`x-github-delivery`)??``;if(!t||!n)return null;let r=decodePayload(e.body,e.contentType),i=normalizeRepository(r.repository),a=normalizeUser(r.sender);if(i===null||a===void 0)return null;let o={delivery:{event:t,hookId:e.headers.get(`x-github-hook-id`)??void 0,id:n},installationId:readInstallationId(r.installation),raw:r,repository:i,sender:a};return t===`ping`?{...o,kind:`ping`}:t===`issue_comment`?parseIssueCommentEvent(o):t===`pull_request_review_comment`?parsePullRequestReviewCommentEvent(o):t===`issues`?parseIssueEvent(o):t===`pull_request`?parsePullRequestEvent(o):t===`check_suite`?parseCheckSuiteEvent(o):t===`check_run`?parseCheckRunEvent(o):t===`workflow_run`?parseWorkflowRunEvent(o):null}function formatGitHubContextBlock(e){return[`<github_context>`,`repository: ${e.repository.fullName}`,`repository_id: ${e.repository.id}`,...e.issueNumber!==void 0&&e.issueNumber!==null?[`issue_number: ${e.issueNumber}`]:[],...e.pullRequestNumber!==void 0&&e.pullRequestNumber!==null?[`pull_request_number: ${e.pullRequestNumber}`]:[],`sender: ${e.sender.login}`,`sender_type: ${e.sender.type}`,...e.commentUrl?[`comment_url: ${e.commentUrl}`]:[],...e.headSha?[`head_sha: ${e.headSha}`]:[],`delivery_id: ${e.deliveryId}`,`</github_context>`].join(`
2
- `)}function prependGitHubContext(e,t){return typeof e==`string`?e.length>0?`${t}\n\n${e}`:t:[{text:t,type:`text`},...e]}function parseIssueCommentEvent(n){let r=isObject(n.raw.issue)?n.raw.issue:null,i=isObject(n.raw.comment)?parseJsonObject(n.raw.comment):null,a=typeof r?.number==`number`?r.number:void 0;if(i===null||r===null||a===void 0)return null;let o=isObject(r.pull_request)?a:null,s=readAction(n.raw),c={author:normalizeUser(i.user),body:typeof i.body==`string`?i.body:``,htmlUrl:typeof i.html_url==`string`?i.html_url:void 0,id:typeof i.id==`number`?i.id:0,issueNumber:a,pullRequestNumber:o,raw:i,url:typeof i.url==`string`?i.url:void 0};return{...n,action:s,baseRef:null,baseSha:null,comment:c,conversation:{issueNumber:a,kind:o===null?`issue`:`pull_request`,pullRequestNumber:o},defaultBranch:null,headRef:null,headSha:null,kind:`issue_comment`}}function parsePullRequestReviewCommentEvent(n){let r=isObject(n.raw.comment)?parseJsonObject(n.raw.comment):null,i=isObject(n.raw.pull_request)?n.raw.pull_request:null,a=typeof i?.number==`number`?i.number:void 0;if(r===null||a===void 0)return null;let o=typeof r.id==`number`?r.id:0,s=typeof r.in_reply_to_id==`number`?r.in_reply_to_id:null,c={author:normalizeUser(r.user),body:typeof r.body==`string`?r.body:``,htmlUrl:typeof r.html_url==`string`?r.html_url:void 0,id:o,inReplyToId:s,pullRequestNumber:a,raw:r,reviewThreadRootCommentId:s??o,url:typeof r.url==`string`?r.url:void 0};return{...n,action:readAction(n.raw),baseRef:readPullRequestBaseRef(i),baseSha:readPullRequestBaseSha(i),comment:c,conversation:{issueNumber:null,kind:`review_thread`,pullRequestNumber:a},defaultBranch:readPullRequestDefaultBranch(i),headRef:readPullRequestHeadRef(i),headSha:readPullRequestHeadSha(i),kind:`pull_request_review_comment`}}function parseIssueEvent(n){let r=isObject(n.raw.issue)?n.raw.issue:null,i=typeof r?.number==`number`?r.number:void 0;return i===void 0?null:{...n,action:readAction(n.raw),conversation:{issueNumber:i,kind:`issue`,pullRequestNumber:null},issue:{action:readAction(n.raw),issueNumber:i,raw:parseJsonObject(r)},kind:`issues`}}function parsePullRequestEvent(n){let r=isObject(n.raw.pull_request)?n.raw.pull_request:null,i=typeof r?.number==`number`?r.number:void 0;return i===void 0?null:{...n,action:readAction(n.raw),baseRef:readPullRequestBaseRef(r),baseSha:readPullRequestBaseSha(r),conversation:{issueNumber:null,kind:`pull_request`,pullRequestNumber:i},defaultBranch:readPullRequestDefaultBranch(r),headRef:readPullRequestHeadRef(r),headSha:readPullRequestHeadSha(r),kind:`pull_request`,pullRequest:{action:readAction(n.raw),headSha:readPullRequestHeadSha(r),pullRequestNumber:i,raw:parseJsonObject(r)}}}function parseCheckSuiteEvent(e){let t=readEventObject(e.raw.check_suite);if(t===null)return null;let n=readId(t);if(n===null)return null;let r=normalizeCiEvent(e.raw,t,normalizeApp(t.app));return{...e,checkSuite:{...r,checkSuiteId:n},conversation:ciConversation(r.pullRequests),kind:`check_suite`}}function parseCheckRunEvent(e){let t=readEventObject(e.raw.check_run);if(t===null)return null;let n=readId(t);if(n===null)return null;let r=normalizeCiEvent(e.raw,t,normalizeApp(t.app));return{...e,checkRun:{...r,checkRunId:n},conversation:ciConversation(r.pullRequests),kind:`check_run`}}function parseWorkflowRunEvent(e){let t=readEventObject(e.raw.workflow_run);if(t===null)return null;let n=readId(t);if(n===null)return null;let r=normalizeCiEvent(e.raw,t,{slug:`github-actions`});return{...e,conversation:ciConversation(r.pullRequests),kind:`workflow_run`,workflowRun:{...r,workflowRunId:n}}}function normalizeCiEvent(e,t,n){return{action:readAction(e),app:n,conclusion:readNullableString(t.conclusion),headSha:readNullableString(t.head_sha),pullRequests:readPullRequestNumbers(t.pull_requests),raw:t,status:readNullableString(t.status)}}function readEventObject(n){return isObject(n)?parseJsonObject(n):null}function readId(e){return typeof e.id==`number`?e.id:null}function normalizeApp(t){return{slug:isObject(t)&&typeof t.slug==`string`?t.slug:null}}function readNullableString(e){return typeof e==`string`?e:null}function readPullRequestNumbers(t){return Array.isArray(t)?t.flatMap(t=>isObject(t)&&typeof t.number==`number`?[t.number]:[]):[]}function ciConversation(e){return{issueNumber:null,kind:`pull_request`,pullRequestNumber:e[0]??null}}function decodePayload(e,n){if(n?.includes(`application/x-www-form-urlencoded`)===!0){let n=new URLSearchParams(e).get(`payload`)??``;return parseJsonObject(JSON.parse(n))}return parseJsonObject(JSON.parse(e))}function normalizeRepository(t){if(!isObject(t))return null;let n=typeof t.full_name==`string`?t.full_name:``,[r=``,i=``]=n.split(`/`),a=isObject(t.owner)?t.owner:{},o=typeof a.login==`string`?a.login:r,s=typeof t.name==`string`?t.name:i,c=typeof t.id==`number`?t.id:0;return!o||!s?null:{fullName:n||`${o}/${s}`,id:c,name:s,owner:o,private:t.private===!0}}function normalizeUser(t){if(!isObject(t))return;let n=typeof t.login==`string`?t.login:``;if(n)return{htmlUrl:typeof t.html_url==`string`?t.html_url:void 0,id:typeof t.id==`number`?t.id:0,login:n,type:typeof t.type==`string`?t.type:`User`,url:typeof t.url==`string`?t.url:void 0}}function readInstallationId(t){if(isObject(t))return typeof t.id==`number`?t.id:void 0}function readAction(e){return typeof e.action==`string`?e.action:``}function readPullRequestHeadSha(t){let n=isObject(t?.head)?t.head:null;return typeof n?.sha==`string`?n.sha:null}function readPullRequestHeadRef(t){let n=isObject(t?.head)?t.head:null;return typeof n?.ref==`string`?n.ref:null}function readPullRequestBaseRef(t){let n=isObject(t?.base)?t.base:null;return typeof n?.ref==`string`?n.ref:null}function readPullRequestBaseSha(t){let n=isObject(t?.base)?t.base:null;return typeof n?.sha==`string`?n.sha:null}function readPullRequestDefaultBranch(t){let n=isObject(t?.base)?t.base:null,r=isObject(n?.repo)?n.repo:null;return typeof r?.default_branch==`string`?r.default_branch:null}function isIgnoredGitHubComment(e,t,n){if(e.includes(`<!-- eve:github:`))return!0;if(t===void 0)return!1;if(t.type===`Bot`)return!0;let r=n?`${n}[bot]`.toLowerCase():``;return r.length>0&&t.login.toLowerCase()===r}function requiredNumber(e,t){if(typeof e==`number`&&Number.isFinite(e))return e;throw Error(`githubContinuationToken requires ${t}.`)}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}export{extractGitHubCommentTrigger,formatGitHubContextBlock,githubContinuationToken,parseGitHubWebhookEvent,prependGitHubContext,shouldDispatchGitHubComment};
1
+ import{isObject}from"#shared/guards.js";import{parseJsonObject}from"#shared/json.js";function githubContinuationToken(e){return e.conversationKind===`issue`?`repo:${e.repositoryId}:issue:${requiredNumber(e.issueNumber,`issueNumber`)}`:e.conversationKind===`pull_request`?`repo:${e.repositoryId}:pull:${requiredNumber(e.pullRequestNumber,`pullRequestNumber`)}`:`repo:${e.repositoryId}:pull:${requiredNumber(e.pullRequestNumber,`pullRequestNumber`)}:review-comment:${requiredNumber(e.reviewThreadRootCommentId,`reviewThreadRootCommentId`)}`}function shouldDispatchGitHubComment(e){return isIgnoredGitHubComment(e.body,e.author,e.botName)?!1:extractGitHubCommentTrigger(e)!==null}function extractGitHubCommentTrigger(e){let t=e.botName?.trim();if(!t)return null;let n=RegExp(`@${escapeRegExp(t)}(?=$|[^A-Za-z0-9_-])`,`iu`).exec(e.body);if(n===null)return null;let r=n.index,i=r+n[0].length;return{kind:`mention`,message:`${e.body.slice(0,r)}${e.body.slice(i)}`.trim(),token:n[0]}}function parseGitHubWebhookEvent(e){let t=decodePayload(e.body,e.contentType),n=readHeader(e.headers,`x-github-event`)??inferGitHubWebhookEventName(t);if(n===null)return null;let r=normalizeRepository(t.repository),i=normalizeUser(t.sender);if(r===null||i===void 0)return null;let a={delivery:{event:n,hookId:readHeader(e.headers,`x-github-hook-id`)??readGitHubHookId(t),id:readHeader(e.headers,`x-github-delivery`)??inferGitHubDeliveryId(n,t)},installationId:readInstallationId(t.installation),raw:t,repository:r,sender:i};return n===`ping`?{...a,kind:`ping`}:n===`issue_comment`?parseIssueCommentEvent(a):n===`pull_request_review_comment`?parsePullRequestReviewCommentEvent(a):n===`issues`?parseIssueEvent(a):n===`pull_request`?parsePullRequestEvent(a):n===`check_suite`?parseCheckSuiteEvent(a):n===`check_run`?parseCheckRunEvent(a):n===`workflow_run`?parseWorkflowRunEvent(a):null}function inferGitHubWebhookEventName(t){return isObject(t.hook)&&typeof t.zen==`string`?`ping`:isObject(t.comment)&&isObject(t.issue)?`issue_comment`:isObject(t.comment)&&isObject(t.pull_request)?`pull_request_review_comment`:isObject(t.check_suite)?`check_suite`:isObject(t.check_run)?`check_run`:isObject(t.workflow_run)?`workflow_run`:isObject(t.issue)?`issues`:isObject(t.pull_request)&&!isObject(t.review)?`pull_request`:null}function inferGitHubDeliveryId(e,t){return`inferred:${e}:${readObjectNumber(t.comment,`id`)??readObjectNumber(t.issue,`id`)??readObjectNumber(t.issue,`number`)??readObjectNumber(t.pull_request,`id`)??readObjectNumber(t.pull_request,`number`)??readObjectNumber(t.check_suite,`id`)??readObjectNumber(t.check_run,`id`)??readObjectNumber(t.workflow_run,`id`)??readObjectNumber(t.hook,`id`)??`unknown`}:${readAction(t)||`unknown`}`}function readHeader(e,t){let n=e.get(t)?.trim();return n&&n.length>0?n:void 0}function formatGitHubContextBlock(e){return[`<github_context>`,`repository: ${e.repository.fullName}`,`repository_id: ${e.repository.id}`,...e.issueNumber!==void 0&&e.issueNumber!==null?[`issue_number: ${e.issueNumber}`]:[],...e.pullRequestNumber!==void 0&&e.pullRequestNumber!==null?[`pull_request_number: ${e.pullRequestNumber}`]:[],`sender: ${e.sender.login}`,`sender_type: ${e.sender.type}`,...e.commentUrl?[`comment_url: ${e.commentUrl}`]:[],...e.headSha?[`head_sha: ${e.headSha}`]:[],`delivery_id: ${e.deliveryId}`,`</github_context>`].join(`
2
+ `)}function prependGitHubContext(e,t){return typeof e==`string`?e.length>0?`${t}\n\n${e}`:t:[{text:t,type:`text`},...e]}function parseIssueCommentEvent(n){let r=isObject(n.raw.issue)?n.raw.issue:null,i=isObject(n.raw.comment)?parseJsonObject(n.raw.comment):null,a=typeof r?.number==`number`?r.number:void 0;if(i===null||r===null||a===void 0)return null;let o=isObject(r.pull_request)?a:null,s=readAction(n.raw),c={author:normalizeUser(i.user),body:typeof i.body==`string`?i.body:``,htmlUrl:typeof i.html_url==`string`?i.html_url:void 0,id:typeof i.id==`number`?i.id:0,issueNumber:a,pullRequestNumber:o,raw:i,url:typeof i.url==`string`?i.url:void 0};return{...n,action:s,baseRef:null,baseSha:null,comment:c,conversation:{issueNumber:a,kind:o===null?`issue`:`pull_request`,pullRequestNumber:o},defaultBranch:null,headRef:null,headSha:null,kind:`issue_comment`}}function parsePullRequestReviewCommentEvent(n){let r=isObject(n.raw.comment)?parseJsonObject(n.raw.comment):null,i=isObject(n.raw.pull_request)?n.raw.pull_request:null,a=typeof i?.number==`number`?i.number:void 0;if(r===null||a===void 0)return null;let o=typeof r.id==`number`?r.id:0,s=typeof r.in_reply_to_id==`number`?r.in_reply_to_id:null,c={author:normalizeUser(r.user),body:typeof r.body==`string`?r.body:``,htmlUrl:typeof r.html_url==`string`?r.html_url:void 0,id:o,inReplyToId:s,pullRequestNumber:a,raw:r,reviewThreadRootCommentId:s??o,url:typeof r.url==`string`?r.url:void 0};return{...n,action:readAction(n.raw),baseRef:readPullRequestBaseRef(i),baseSha:readPullRequestBaseSha(i),comment:c,conversation:{issueNumber:null,kind:`review_thread`,pullRequestNumber:a},defaultBranch:readPullRequestDefaultBranch(i),headRef:readPullRequestHeadRef(i),headSha:readPullRequestHeadSha(i),kind:`pull_request_review_comment`}}function parseIssueEvent(n){let r=isObject(n.raw.issue)?n.raw.issue:null,i=typeof r?.number==`number`?r.number:void 0;return i===void 0?null:{...n,action:readAction(n.raw),conversation:{issueNumber:i,kind:`issue`,pullRequestNumber:null},issue:{action:readAction(n.raw),issueNumber:i,raw:parseJsonObject(r)},kind:`issues`}}function parsePullRequestEvent(n){let r=isObject(n.raw.pull_request)?n.raw.pull_request:null,i=typeof r?.number==`number`?r.number:void 0;return i===void 0?null:{...n,action:readAction(n.raw),baseRef:readPullRequestBaseRef(r),baseSha:readPullRequestBaseSha(r),conversation:{issueNumber:null,kind:`pull_request`,pullRequestNumber:i},defaultBranch:readPullRequestDefaultBranch(r),headRef:readPullRequestHeadRef(r),headSha:readPullRequestHeadSha(r),kind:`pull_request`,pullRequest:{action:readAction(n.raw),headSha:readPullRequestHeadSha(r),pullRequestNumber:i,raw:parseJsonObject(r)}}}function parseCheckSuiteEvent(e){let t=readEventObject(e.raw.check_suite);if(t===null)return null;let n=readId(t);if(n===null)return null;let r=normalizeCiEvent(e.raw,t,normalizeApp(t.app));return{...e,checkSuite:{...r,checkSuiteId:n},conversation:ciConversation(r.pullRequests),kind:`check_suite`}}function parseCheckRunEvent(e){let t=readEventObject(e.raw.check_run);if(t===null)return null;let n=readId(t);if(n===null)return null;let r=normalizeCiEvent(e.raw,t,normalizeApp(t.app));return{...e,checkRun:{...r,checkRunId:n},conversation:ciConversation(r.pullRequests),kind:`check_run`}}function parseWorkflowRunEvent(e){let t=readEventObject(e.raw.workflow_run);if(t===null)return null;let n=readId(t);if(n===null)return null;let r=normalizeCiEvent(e.raw,t,{slug:`github-actions`});return{...e,conversation:ciConversation(r.pullRequests),kind:`workflow_run`,workflowRun:{...r,workflowRunId:n}}}function normalizeCiEvent(e,t,n){return{action:readAction(e),app:n,conclusion:readNullableString(t.conclusion),headSha:readNullableString(t.head_sha),pullRequests:readPullRequestNumbers(t.pull_requests),raw:t,status:readNullableString(t.status)}}function readEventObject(n){return isObject(n)?parseJsonObject(n):null}function readId(e){return typeof e.id==`number`?e.id:null}function readObjectNumber(t,n){return isObject(t)&&typeof t[n]==`number`?t[n]:null}function normalizeApp(t){return{slug:isObject(t)&&typeof t.slug==`string`?t.slug:null}}function readNullableString(e){return typeof e==`string`?e:null}function readPullRequestNumbers(t){return Array.isArray(t)?t.flatMap(t=>isObject(t)&&typeof t.number==`number`?[t.number]:[]):[]}function ciConversation(e){return{issueNumber:null,kind:`pull_request`,pullRequestNumber:e[0]??null}}function decodePayload(e,n){if(n?.includes(`application/x-www-form-urlencoded`)===!0){let n=new URLSearchParams(e).get(`payload`)??``;return parseJsonObject(JSON.parse(n))}return parseJsonObject(JSON.parse(e))}function normalizeRepository(t){if(!isObject(t))return null;let n=typeof t.full_name==`string`?t.full_name:``,[r=``,i=``]=n.split(`/`),a=isObject(t.owner)?t.owner:{},o=typeof a.login==`string`?a.login:r,s=typeof t.name==`string`?t.name:i,c=typeof t.id==`number`?t.id:0;return!o||!s?null:{fullName:n||`${o}/${s}`,id:c,name:s,owner:o,private:t.private===!0}}function normalizeUser(t){if(!isObject(t))return;let n=typeof t.login==`string`?t.login:``;if(n)return{htmlUrl:typeof t.html_url==`string`?t.html_url:void 0,id:typeof t.id==`number`?t.id:0,login:n,type:typeof t.type==`string`?t.type:`User`,url:typeof t.url==`string`?t.url:void 0}}function readInstallationId(t){if(isObject(t))return typeof t.id==`number`?t.id:void 0}function readGitHubHookId(e){if(typeof e.hook_id==`number`)return String(e.hook_id);if(typeof e.hook_id==`string`&&e.hook_id.length>0)return e.hook_id;let t=readObjectNumber(e.hook,`id`);return t===null?void 0:String(t)}function readAction(e){return typeof e.action==`string`?e.action:``}function readPullRequestHeadSha(t){let n=isObject(t?.head)?t.head:null;return typeof n?.sha==`string`?n.sha:null}function readPullRequestHeadRef(t){let n=isObject(t?.head)?t.head:null;return typeof n?.ref==`string`?n.ref:null}function readPullRequestBaseRef(t){let n=isObject(t?.base)?t.base:null;return typeof n?.ref==`string`?n.ref:null}function readPullRequestBaseSha(t){let n=isObject(t?.base)?t.base:null;return typeof n?.sha==`string`?n.sha:null}function readPullRequestDefaultBranch(t){let n=isObject(t?.base)?t.base:null,r=isObject(n?.repo)?n.repo:null;return typeof r?.default_branch==`string`?r.default_branch:null}function isIgnoredGitHubComment(e,t,n){if(e.includes(`<!-- eve:github:`))return!0;if(t===void 0)return!1;if(t.type===`Bot`)return!0;let r=n?`${n}[bot]`.toLowerCase():``;return r.length>0&&t.login.toLowerCase()===r}function requiredNumber(e,t){if(typeof e==`number`&&Number.isFinite(e))return e;throw Error(`githubContinuationToken requires ${t}.`)}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}export{extractGitHubCommentTrigger,formatGitHubContextBlock,githubContinuationToken,parseGitHubWebhookEvent,prependGitHubContext,shouldDispatchGitHubComment};
@@ -1,4 +1,4 @@
1
- export { defineChannel, GET, POST, PUT, PATCH, DELETE, WS, type Channel, type ChannelDefinition, type ChannelSessionOps, type ChannelEvents, type InferChannelMetadata, type Session, type SessionHandle, type RouteDefinition, type RouteHandlerArgs, type SendFn, type SendOptions, type SendPayload, type GetSessionFn, type HttpRouteDefinition, type WebSocketMessage, type WebSocketPeer, type WebSocketRouteDefinition, type WebSocketRouteHandler, type WebSocketRouteHooks, type WebSocketUpgradeRequest, type WebSocketUpgradeResult, } from "#public/definitions/defineChannel.js";
1
+ export { defineChannel, GET, POST, PUT, PATCH, DELETE, WS, type Channel, type ChannelCors, type ChannelCorsOptions, type ChannelDefinition, type ChannelSessionOps, type ChannelEvents, type InferChannelMetadata, type Session, type SessionHandle, type RouteDefinition, type RouteHandlerArgs, type SendFn, type SendOptions, type SendPayload, type GetSessionFn, type HttpRouteDefinition, type WebSocketMessage, type WebSocketPeer, type WebSocketRouteDefinition, type WebSocketRouteHandler, type WebSocketRouteHooks, type WebSocketUpgradeRequest, type WebSocketUpgradeResult, } from "#public/definitions/defineChannel.js";
2
2
  export { createWebSocketUpgradeServer, type WebSocketUpgradeServerBridge, } from "#channel/websocket-upgrade-server.js";
3
3
  import type { Channel } from "#public/definitions/defineChannel.js";
4
4
  /**
@@ -1,5 +1,6 @@
1
1
  import type { FetchFileResult } from "#channel/adapter.js";
2
2
  import { CHANNEL_SENTINEL } from "#channel/compiled-channel.js";
3
+ import { type ChannelCors, type ChannelCorsOptions } from "#channel/cors.js";
3
4
  import type { TypedReceiveTarget } from "#channel/receive-target.js";
4
5
  import type { SessionAuthContext } from "#channel/types.js";
5
6
  import type { HandleMessageStreamEvent } from "#protocol/message.js";
@@ -8,6 +9,7 @@ import type { RouteDefinition, SendFn } from "#channel/routes.js";
8
9
  import type { Session, SessionHandle } from "#channel/session.js";
9
10
  declare const CHANNEL_METADATA_TYPE: unique symbol;
10
11
  export type { Session, SessionHandle } from "#channel/session.js";
12
+ export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";
11
13
  export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";
12
14
  export type { HttpRouteDefinition, RouteDefinition, RouteHandlerArgs, SendFn, SendOptions, SendPayload, GetSessionFn, WebSocketMessage, WebSocketPeer, WebSocketRouteDefinition, WebSocketRouteHandler, WebSocketRouteHooks, WebSocketUpgradeRequest, WebSocketUpgradeResult, } from "#channel/routes.js";
13
15
  type EventData<T extends HandleMessageStreamEvent["type"]> = Extract<HandleMessageStreamEvent, {
@@ -74,6 +76,13 @@ export interface ReceiveInput<TReceiveTarget = Record<string, unknown>> {
74
76
  */
75
77
  export interface ChannelDefinition<TState = undefined, TCtx = void, TReceiveTarget = Record<string, unknown>, TMetadata extends Record<string, unknown> = Record<string, unknown>> {
76
78
  readonly state?: TState;
79
+ /**
80
+ * CORS policy for this channel's HTTP routes. `true` enables H3/Nitro's
81
+ * permissive defaults (`origin`, methods, request headers, and exposed
82
+ * headers all `"*"`); `false` or omission leaves CORS untouched. Pass an
83
+ * object for a serializable subset of H3/Nitro CORS options.
84
+ */
85
+ readonly cors?: ChannelCors;
77
86
  /**
78
87
  * Builds the per-step channel context handed to `events` and `deliver`.
79
88
  * Receives the live {@link SessionHandle}, so a factory can close over it to
@@ -129,6 +138,7 @@ export interface Channel<TState = undefined, TReceiveTarget = Record<string, unk
129
138
  readonly __kind: typeof CHANNEL_SENTINEL;
130
139
  readonly [CHANNEL_METADATA_TYPE]?: TMetadata;
131
140
  readonly routes: readonly RouteDefinition<TState>[];
141
+ readonly cors?: ChannelCorsOptions;
132
142
  readonly receive?: (input: ReceiveInput<TReceiveTarget>, args: {
133
143
  send: SendFn<TState>;
134
144
  }) => Promise<Session>;
@@ -1 +1 @@
1
- import{CHANNEL_SENTINEL}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{HTTP_ADAPTER_KIND}from"#channel/http.js";import{DELETE,GET,PATCH,POST,PUT,WS}from"#channel/routes.js";function defineChannel(t){let n=buildAdapter(t);return{__kind:CHANNEL_SENTINEL,routes:t.routes,adapter:n,receive:t.receive}}function buildAdapter(e){let i=e.state!=null,a=e.context!=null,o=e.fetchFile!==void 0,s=e.metadata,c=i||a||s!==void 0,l={},u=!1,d=[`turn.started`,`actions.requested`,`action.result`,`message.completed`,`message.appended`,`reasoning.appended`,`reasoning.completed`,`input.requested`,`turn.failed`,`turn.completed`,`session.failed`,`session.completed`,`session.waiting`,`authorization.required`,`authorization.completed`],f=e.events;for(let e of d){let t=f?.[e];t&&(u=!0,l[e]=(r,i)=>{let a={...i,continuationToken:i.session?.continuationToken??``,setContinuationToken:e=>i.session?.setContinuationToken(e)};return e===`session.failed`?t(r,a):t(r,a,buildCallbackContext())})}return!c&&!u&&!o?{kind:e.kindHint??HTTP_ADAPTER_KIND}:{kind:e.kindHint??`defineChannel`,state:i?{...e.state}:{},fetchFile:e.fetchFile,instrumentation:s===void 0?void 0:{metadata(e){return s(e)}},createAdapterContext(t){let n=t.state,r=t.session;return{...a?e.context(n,r):{},state:n,ctx:t.ctx,session:r}},deliver(e){return defaultDeliverResult(e)},...l}}export{DELETE,GET,PATCH,POST,PUT,WS,defineChannel};
1
+ import{CHANNEL_SENTINEL}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{normalizeChannelCors}from"#channel/cors.js";import{HTTP_ADAPTER_KIND}from"#channel/http.js";import{DELETE,GET,PATCH,POST,PUT,WS}from"#channel/routes.js";function defineChannel(t){let n=buildAdapter(t),i=normalizeChannelCors(t.cors);return{__kind:CHANNEL_SENTINEL,routes:t.routes,adapter:n,cors:i,receive:t.receive}}function buildAdapter(e){let r=e.state!=null,a=e.context!=null,o=e.fetchFile!==void 0,s=e.metadata,c=r||a||s!==void 0,l={},u=!1,d=[`turn.started`,`actions.requested`,`action.result`,`message.completed`,`message.appended`,`reasoning.appended`,`reasoning.completed`,`input.requested`,`turn.failed`,`turn.completed`,`session.failed`,`session.completed`,`session.waiting`,`authorization.required`,`authorization.completed`],f=e.events;for(let e of d){let t=f?.[e];t&&(u=!0,l[e]=(r,i)=>{let a={...i,continuationToken:i.session?.continuationToken??``,setContinuationToken:e=>i.session?.setContinuationToken(e)};return e===`session.failed`?t(r,a):t(r,a,buildCallbackContext())})}return!c&&!u&&!o?{kind:e.kindHint??HTTP_ADAPTER_KIND}:{kind:e.kindHint??`defineChannel`,state:r?{...e.state}:{},fetchFile:e.fetchFile,instrumentation:s===void 0?void 0:{metadata(e){return s(e)}},createAdapterContext(t){let n=t.state,r=t.session;return{...a?e.context(n,r):{},state:n,ctx:t.ctx,session:r}},deliver(e){return defaultDeliverResult(e)},...l}}export{DELETE,GET,PATCH,POST,PUT,WS,defineChannel};
@@ -78,6 +78,15 @@ export declare function completeScopedAuthorization(input: ScopedAuthorization):
78
78
  * callers can fall through to rethrowing the original `Required` error.
79
79
  */
80
80
  export declare function startScopedAuthorization(input: ScopedAuthorization): Promise<AuthorizationSignal | undefined>;
81
+ /**
82
+ * Vercel Connect accepts local HTTP callback URLs only when their hostname is
83
+ * literally `localhost`. Other authorization providers keep the framework's
84
+ * original callback URL so their registered redirect URI remains unchanged.
85
+ */
86
+ export declare function resolveAuthorizationCallbackUrl(input: {
87
+ readonly authorization: Readonly<AuthorizationDefinition>;
88
+ readonly callbackUrl: string;
89
+ }): string;
81
90
  /**
82
91
  * Resolves the user-facing `displayName` onto a challenge before it is
83
92
  * surfaced on `authorization.required`.
@@ -1 +1 @@
1
- import{contextStorage,loadContext}from"#context/container.js";import{getAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{evictCachedToken,readCachedToken,writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";async function resolveScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore(),o=resolveConnectionPrincipal(n,r,a);if(a===void 0)return await r.getToken({connection:i,principal:o});let u=principalKey(o),d=readCachedToken(a,n,u);if(d!==void 0)return d;let f=await r.getToken({connection:i,principal:o});return writeCachedToken(a,n,u,f),f}async function evictScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore();if(a===void 0)return;let s;try{s=resolveConnectionPrincipal(n,r,a),evictCachedToken(a,n,principalKey(s))}catch{return}try{await r.evict?.({connection:i,principal:s})}catch{}}async function completeScopedAuthorization(e){let{scope:r,authorization:i,connection:o}=e;if(!supportsInteractiveAuthorization(i))return!1;let s=getAuthorizationResult(r);if(s===void 0)return!1;let u=i,d=loadContext(),f=resolveConnectionPrincipal(r,u,d),p=await u.completeAuthorization({callbackUrl:s.hookUrl,connection:o,principal:f,resume:s.resume,callback:s.callback});return writeCachedToken(d,r,principalKey(f),p),!0}async function startScopedAuthorization(e){let{scope:t,authorization:n,connection:o}=e;if(!supportsInteractiveAuthorization(n))return;let s=getHookUrl(t);if(s===void 0)return;let c=n,l=resolveConnectionPrincipal(t,c),{challenge:u,resume:d}=await c.startAuthorization({callbackUrl:s,connection:o,principal:l});return requestAuthorization([{challenge:stampChallengeDisplayName(u,n),hookUrl:s,name:t,resume:d}])}function stampChallengeDisplayName(e,t){let n=t.displayName??e.displayName;return n===e.displayName?e:{...e,displayName:n}}export{completeScopedAuthorization,evictScopedToken,resolveScopedToken,stampChallengeDisplayName,startScopedAuthorization};
1
+ import{contextStorage,loadContext}from"#context/container.js";import{getAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{evictCachedToken,readCachedToken,writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";const LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES=new Set([`127.0.0.1`,`[::1]`]);async function resolveScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore(),o=resolveConnectionPrincipal(n,r,a);if(a===void 0)return await r.getToken({connection:i,principal:o});let u=principalKey(o),d=readCachedToken(a,n,u);if(d!==void 0)return d;let f=await r.getToken({connection:i,principal:o});return writeCachedToken(a,n,u,f),f}async function evictScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore();if(a===void 0)return;let s;try{s=resolveConnectionPrincipal(n,r,a),evictCachedToken(a,n,principalKey(s))}catch{return}try{await r.evict?.({connection:i,principal:s})}catch{}}async function completeScopedAuthorization(e){let{scope:r,authorization:i,connection:o}=e;if(!supportsInteractiveAuthorization(i))return!1;let s=getAuthorizationResult(r);if(s===void 0)return!1;let u=i,d=loadContext(),f=resolveConnectionPrincipal(r,u,d),p=await u.completeAuthorization({callbackUrl:s.hookUrl,connection:o,principal:f,resume:s.resume,callback:s.callback});return writeCachedToken(d,r,principalKey(f),p),!0}async function startScopedAuthorization(e){let{scope:t,authorization:n,connection:o}=e;if(!supportsInteractiveAuthorization(n))return;let s=getHookUrl(t);if(s===void 0)return;let c=n,l=resolveConnectionPrincipal(t,c),u=resolveAuthorizationCallbackUrl({authorization:n,callbackUrl:s}),{challenge:d,resume:f}=await c.startAuthorization({callbackUrl:u,connection:o,principal:l});return requestAuthorization([{challenge:stampChallengeDisplayName(d,n),hookUrl:u,name:t,resume:f}])}function resolveAuthorizationCallbackUrl(e){if(e.authorization.vercelConnect===void 0)return e.callbackUrl;let t;try{t=new URL(e.callbackUrl)}catch{return e.callbackUrl}return t.protocol!==`http:`||!LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES.has(t.hostname)?e.callbackUrl:(t.hostname=`localhost`,t.toString())}function stampChallengeDisplayName(e,t){let n=t.displayName??e.displayName;return n===e.displayName?e:{...e,displayName:n}}export{completeScopedAuthorization,evictScopedToken,resolveAuthorizationCallbackUrl,resolveScopedToken,stampChallengeDisplayName,startScopedAuthorization};
@@ -200,10 +200,10 @@ interface AuthorizationDefinitionBase {
200
200
  * that surfaces connector identifiers in build output, or the Vercel
201
201
  * dashboard rendering deep links to a connector's settings page.
202
202
  *
203
- * The runtime token-fetch path ignores this field; it is purely
204
- * provider attribution. Authors writing their own `getToken`
205
- * callbacks (raw bearer tokens, custom callbacks) should leave it
206
- * unset.
203
+ * The runtime uses this marker for Connect-specific authorization behavior,
204
+ * including its local callback URL contract. Authors writing their own
205
+ * `getToken` callbacks (raw bearer tokens, custom callbacks) should leave
206
+ * it unset.
207
207
  *
208
208
  * `connector` carries whatever value the author passed to
209
209
  * `connect()`: a UID like `"oauth/mcp-linear-app"` or opaque
@@ -1 +1 @@
1
- import{localDev,vercelOidc}from"#public/channels/auth.js";import{isHttpRouteDefinition}from"#channel/routes.js";import{eveChannel}from"#public/channels/eve.js";import{getConnectionCallbackChannelDefinitions,getConnectionCallbackChannelNames}from"#runtime/connections/callback-route.js";import{getSessionCallbackChannelDefinitions,getSessionCallbackChannelNames}from"#runtime/session-callback-route.js";function getFrameworkChannelDefinitions(){let r=eveChannel({auth:[vercelOidc(),localDev()]}),i=[];for(let e of r.routes)isHttpRouteDefinition(e)&&i.push({name:`eve`,method:e.method.toUpperCase(),urlPath:e.path,fetch:async(t,n)=>e.handler(t,n),handler:e.handler,adapter:r.adapter,logicalPath:`framework://channels/${e.path}`,sourceId:`eve:framework:${e.method.toLowerCase()}-${e.path}`,sourceKind:`module`});return i.push(...getConnectionCallbackChannelDefinitions(),...getSessionCallbackChannelDefinitions()),i}function getAllFrameworkChannelNames(){return new Set([`eve`,...getConnectionCallbackChannelNames(),...getSessionCallbackChannelNames()])}export{getAllFrameworkChannelNames,getFrameworkChannelDefinitions};
1
+ import{localDev,vercelOidc}from"#public/channels/auth.js";import{isHttpRouteDefinition}from"#channel/routes.js";import{eveChannel}from"#public/channels/eve.js";import{getConnectionCallbackChannelDefinitions,getConnectionCallbackChannelNames}from"#runtime/connections/callback-route.js";import{getSessionCallbackChannelDefinitions,getSessionCallbackChannelNames}from"#runtime/session-callback-route.js";function getFrameworkChannelDefinitions(){let r=eveChannel({auth:[vercelOidc(),localDev()]}),i=[];for(let e of r.routes)isHttpRouteDefinition(e)&&i.push({name:`eve`,method:e.method.toUpperCase(),urlPath:e.path,cors:r.cors,fetch:async(t,n)=>e.handler(t,n),handler:e.handler,adapter:r.adapter,logicalPath:`framework://channels/${e.path}`,sourceId:`eve:framework:${e.method.toLowerCase()}-${e.path}`,sourceKind:`module`});return i.push(...getConnectionCallbackChannelDefinitions(),...getSessionCallbackChannelDefinitions()),i}function getAllFrameworkChannelNames(){return new Set([`eve`,...getConnectionCallbackChannelNames(),...getSessionCallbackChannelNames()])}export{getAllFrameworkChannelNames,getFrameworkChannelDefinitions};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{getAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_OUTPUT_SCHEMA={items:{additionalProperties:!1,properties:{connection:{type:`string`},description:{type:`string`},error:{type:`string`},inputSchema:{type:`object`},needsAuthorization:{type:`boolean`},outputSchema:{type:`object`},qualifiedName:{type:`string`},tool:{type:`string`}},required:[`connection`,`description`],type:`object`},type:`array`},ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e){let n=loadContext(),r=new Set;for(let t of e.getConnections()){let i=getAuthorizationResult(t.connectionName);if(!i)continue;let a=await resolveInteractiveAuth(e,t.connectionName);if(!a)continue;let o=resolveConnectionPrincipal(t.connectionName,a),c=await a.completeAuthorization({callbackUrl:i.hookUrl,connection:{url:t.url??``},principal:o,resume:i.resume,callback:i.callback});writeCachedToken(n,t.connectionName,principalKey(o),c),r.add(t.connectionName)}return r}async function executeConnectionSearch(e){let n=loadContext(),i=n.get(ConnectionRegistryKey);if(i===void 0)return[];let s=await completePendingAuthorizations(i),l=e.limit??10,u=tokenize(e.keywords),d=[],f=[],m=e.connection!==void 0&&e.connection!==``?i.getConnections().filter(t=>t.connectionName===e.connection):i.getConnections(),h=[];for(let e of m){let t;try{t=await i.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(s.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),f.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(i,e.connectionName);if(t){let n=getHookUrl(e.connectionName);if(n){let r=resolveConnectionPrincipal(e.connectionName,t);try{let{challenge:i,resume:a}=await t.startAuthorization({callbackUrl:n,connection:{url:e.url??``},principal:r});h.push({name:e.connectionName,challenge:stampChallengeDisplayName(i,t),hookUrl:n,resume:a})}catch(t){logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:t instanceof Error?t:Error(String(t))})}}}f.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),f.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let n=t instanceof Error?t.message:`unknown error`;logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:t instanceof Error?t:Error(n)}),f.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${n}`});continue}for(let n of t){let t=scoreMatch(u,n);t>0&&d.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(h.length>0)return requestAuthorization(h);d.sort((e,t)=>t.score-e.score);let g=d.slice(0,l).map(e=>e.item);if(g.length>0){let e=[...g,...f],t=n.get(ConnectionSearchResultsKey)??[],r=new Map(t.map(e=>[e.qualifiedName,e]));for(let e of g)e.qualifiedName&&r.set(e.qualifiedName,e);return n.set(ConnectionSearchResultsKey,[...r.values()]),e}return m.map(e=>f.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function extractDiscoveredTools(e){let t=new Map;for(let n of e){if(n.role!==`tool`)continue;let e=n.content;for(let n of e){if(n.type!==`tool-result`||n.toolName!==`connection_search`)continue;let e=n.output;if(e==null)continue;let r=typeof e==`object`&&`type`in e&&`value`in e?e.value:e;if(Array.isArray(r))for(let e of r)e.tool&&e.qualifiedName&&t.set(e.qualifiedName,e)}}return[...t.values()]}function createConnectionSearchEvents(){return{"step.started":async(e,n)=>{let a=loadContext().get(ConnectionRegistryKey);if(!a||a.getConnections().length===0)return null;let l=a.getConnections().map(e=>e.connectionName),u=extractDiscoveredTools(n.messages),p=loadContext().get(ConnectionSearchResultsKey)??[],h=new Map;for(let e of p)e.qualifiedName&&h.set(e.qualifiedName,e);for(let e of u)e.qualifiedName&&h.set(e.qualifiedName,e);let g=[...h.values()],_={};_.connection_search={description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${l.join(`, `)}.`,inputSchema:{type:`object`,additionalProperties:!1,properties:{keywords:{description:`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`,type:`string`},connection:{description:`Optional: limit search to a specific connection name.`,type:`string`},limit:{description:`Max results to return. Default 10.`,type:`number`}},required:[`keywords`]},async execute(e){return executeConnectionSearch(e)},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA};for(let e of g){let n=e.connection,l=e.tool,u=a.getConnectionApproval(n);_[qualifiedConnectionToolName(n,l)]={description:e.description,inputSchema:e.inputSchema??{type:`object`},approval:u,outputSchema:e.outputSchema,async execute(e){let a=loadContext().get(ConnectionRegistryKey),u=a.getConnections().find(e=>e.connectionName===n),p=await resolveInteractiveAuth(a,n),m=!1;if(p){let e=getAuthorizationResult(n);if(e){m=!0;let r=loadContext(),i=resolveConnectionPrincipal(n,p),a=await p.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:u?.url??``},principal:i,resume:e.resume,callback:e.callback});writeCachedToken(r,n,principalKey(i),a)}}try{return await a.getClient(n).executeTool(l,e)}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!p)throw e;if(m)throw new ConnectionAuthorizationFailedError(n,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${n}" rejected the token immediately after authorization.`});let t=getHookUrl(n);if(!t)throw e;let r=resolveConnectionPrincipal(n,p),{challenge:a,resume:s}=await p.startAuthorization({callbackUrl:t,connection:{url:u?.url??``},principal:r});return requestAuthorization([{name:n,challenge:stampChallengeDisplayName(a,p),hookUrl:t,resume:s}])}}}}return _}}}function createConnectionSearchResolver(){let e=createConnectionSearchEvents();return{slug:`connection`,eventNames:Object.keys(e),events:e,sourceId:`eve:connection-search-dynamic`,sourceKind:`module`,logicalPath:`eve:framework/connection-search-dynamic`}}export{createConnectionSearchEvents,createConnectionSearchResolver,extractDiscoveredTools};
1
+ import{createLogger}from"#internal/logging.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{getAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{resolveAuthorizationCallbackUrl,stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_OUTPUT_SCHEMA={items:{additionalProperties:!1,properties:{connection:{type:`string`},description:{type:`string`},error:{type:`string`},inputSchema:{type:`object`},needsAuthorization:{type:`boolean`},outputSchema:{type:`object`},qualifiedName:{type:`string`},tool:{type:`string`}},required:[`connection`,`description`],type:`object`},type:`array`},ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e){let n=loadContext(),r=new Set;for(let t of e.getConnections()){let i=getAuthorizationResult(t.connectionName);if(!i)continue;let a=await resolveInteractiveAuth(e,t.connectionName);if(!a)continue;let o=resolveConnectionPrincipal(t.connectionName,a),c=await a.completeAuthorization({callbackUrl:i.hookUrl,connection:{url:t.url??``},principal:o,resume:i.resume,callback:i.callback});writeCachedToken(n,t.connectionName,principalKey(o),c),r.add(t.connectionName)}return r}async function executeConnectionSearch(e){let n=loadContext(),i=n.get(ConnectionRegistryKey);if(i===void 0)return[];let s=await completePendingAuthorizations(i),l=e.limit??10,u=tokenize(e.keywords),d=[],f=[],m=e.connection!==void 0&&e.connection!==``?i.getConnections().filter(t=>t.connectionName===e.connection):i.getConnections(),h=[];for(let e of m){let t;try{t=await i.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(s.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),f.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(i,e.connectionName);if(t){let n=getHookUrl(e.connectionName);if(n){let r=resolveConnectionPrincipal(e.connectionName,t),i=resolveAuthorizationCallbackUrl({authorization:t,callbackUrl:n});try{let{challenge:n,resume:a}=await t.startAuthorization({callbackUrl:i,connection:{url:e.url??``},principal:r});h.push({name:e.connectionName,challenge:stampChallengeDisplayName(n,t),hookUrl:i,resume:a})}catch(t){logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:t instanceof Error?t:Error(String(t))})}}}f.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),f.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let n=t instanceof Error?t.message:`unknown error`;logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:t instanceof Error?t:Error(n)}),f.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${n}`});continue}for(let n of t){let t=scoreMatch(u,n);t>0&&d.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(h.length>0)return requestAuthorization(h);d.sort((e,t)=>t.score-e.score);let g=d.slice(0,l).map(e=>e.item);if(g.length>0){let e=[...g,...f],t=n.get(ConnectionSearchResultsKey)??[],r=new Map(t.map(e=>[e.qualifiedName,e]));for(let e of g)e.qualifiedName&&r.set(e.qualifiedName,e);return n.set(ConnectionSearchResultsKey,[...r.values()]),e}return m.map(e=>f.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function extractDiscoveredTools(e){let t=new Map;for(let n of e){if(n.role!==`tool`)continue;let e=n.content;for(let n of e){if(n.type!==`tool-result`||n.toolName!==`connection_search`)continue;let e=n.output;if(e==null)continue;let r=typeof e==`object`&&`type`in e&&`value`in e?e.value:e;if(Array.isArray(r))for(let e of r)e.tool&&e.qualifiedName&&t.set(e.qualifiedName,e)}}return[...t.values()]}function createConnectionSearchEvents(){return{"step.started":async(e,n)=>{let a=loadContext().get(ConnectionRegistryKey);if(!a||a.getConnections().length===0)return null;let l=a.getConnections().map(e=>e.connectionName),u=extractDiscoveredTools(n.messages),p=loadContext().get(ConnectionSearchResultsKey)??[],h=new Map;for(let e of p)e.qualifiedName&&h.set(e.qualifiedName,e);for(let e of u)e.qualifiedName&&h.set(e.qualifiedName,e);let g=[...h.values()],_={};_.connection_search={description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${l.join(`, `)}.`,inputSchema:{type:`object`,additionalProperties:!1,properties:{keywords:{description:`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`,type:`string`},connection:{description:`Optional: limit search to a specific connection name.`,type:`string`},limit:{description:`Max results to return. Default 10.`,type:`number`}},required:[`keywords`]},async execute(e){return executeConnectionSearch(e)},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA};for(let e of g){let n=e.connection,l=e.tool,u=a.getConnectionApproval(n);_[qualifiedConnectionToolName(n,l)]={description:e.description,inputSchema:e.inputSchema??{type:`object`},approval:u,outputSchema:e.outputSchema,async execute(e){let a=loadContext().get(ConnectionRegistryKey),u=a.getConnections().find(e=>e.connectionName===n),p=await resolveInteractiveAuth(a,n),m=!1;if(p){let e=getAuthorizationResult(n);if(e){m=!0;let r=loadContext(),i=resolveConnectionPrincipal(n,p),a=await p.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:u?.url??``},principal:i,resume:e.resume,callback:e.callback});writeCachedToken(r,n,principalKey(i),a)}}try{return await a.getClient(n).executeTool(l,e)}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!p)throw e;if(m)throw new ConnectionAuthorizationFailedError(n,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${n}" rejected the token immediately after authorization.`});let t=getHookUrl(n);if(!t)throw e;let r=resolveConnectionPrincipal(n,p),a=resolveAuthorizationCallbackUrl({authorization:p,callbackUrl:t}),{challenge:s,resume:l}=await p.startAuthorization({callbackUrl:a,connection:{url:u?.url??``},principal:r});return requestAuthorization([{name:n,challenge:stampChallengeDisplayName(s,p),hookUrl:a,resume:l}])}}}}return _}}}function createConnectionSearchResolver(){let e=createConnectionSearchEvents();return{slug:`connection`,eventNames:Object.keys(e),events:e,sourceId:`eve:connection-search-dynamic`,sourceKind:`module`,logicalPath:`eve:framework/connection-search-dynamic`}}export{createConnectionSearchEvents,createConnectionSearchResolver,extractDiscoveredTools};
@@ -1,4 +1,4 @@
1
- export { ConnectionRegistryKey } from "#context/providers/connection.js";
1
+ export { ConnectionRegistryKey } from "#context/providers/connection-key.js";
2
2
  export type { ReadFileStamp, ReadFileState } from "#runtime/framework-tools/file-state.js";
3
3
  export { ReadFileStateKey } from "#runtime/framework-tools/file-state.js";
4
4
  export type { TodoItem, TodoState } from "#runtime/framework-tools/todo.js";
@@ -1 +1 @@
1
- import{ConnectionRegistryKey}from"#context/providers/connection.js";import{ReadFileStateKey}from"#runtime/framework-tools/file-state.js";import{TODO_TOOL_DEFINITION,TodoStateKey}from"#runtime/framework-tools/todo.js";import{ASK_QUESTION_TOOL_DEFINITION}from"#runtime/framework-tools/ask-question.js";import{WEB_SEARCH_TOOL_DEFINITION}from"#runtime/framework-tools/web-search.js";import{BASH_TOOL_DEFINITION}from"#runtime/framework-tools/bash.js";import{GLOB_TOOL_DEFINITION}from"#runtime/framework-tools/glob.js";import{GREP_TOOL_DEFINITION}from"#runtime/framework-tools/grep.js";import{READ_FILE_TOOL_DEFINITION}from"#runtime/framework-tools/read-file.js";import{SKILL_TOOL_DEFINITION}from"#runtime/framework-tools/skill.js";import{WEB_FETCH_TOOL_DEFINITION}from"#runtime/framework-tools/web-fetch.js";import{WRITE_FILE_TOOL_DEFINITION}from"#runtime/framework-tools/write-file.js";const ALL_FRAMEWORK_TOOLS=[ASK_QUESTION_TOOL_DEFINITION,BASH_TOOL_DEFINITION,GLOB_TOOL_DEFINITION,GREP_TOOL_DEFINITION,READ_FILE_TOOL_DEFINITION,WRITE_FILE_TOOL_DEFINITION,TODO_TOOL_DEFINITION,WEB_FETCH_TOOL_DEFINITION,WEB_SEARCH_TOOL_DEFINITION,SKILL_TOOL_DEFINITION];function getFrameworkToolDefinitions(e){return ALL_FRAMEWORK_TOOLS}function getAllFrameworkToolNames(){return new Set(ALL_FRAMEWORK_TOOLS.map(e=>e.name))}export{ConnectionRegistryKey,ReadFileStateKey,TodoStateKey,getAllFrameworkToolNames,getFrameworkToolDefinitions};
1
+ import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{ReadFileStateKey}from"#runtime/framework-tools/file-state.js";import{TODO_TOOL_DEFINITION,TodoStateKey}from"#runtime/framework-tools/todo.js";import{ASK_QUESTION_TOOL_DEFINITION}from"#runtime/framework-tools/ask-question.js";import{WEB_SEARCH_TOOL_DEFINITION}from"#runtime/framework-tools/web-search.js";import{BASH_TOOL_DEFINITION}from"#runtime/framework-tools/bash.js";import{GLOB_TOOL_DEFINITION}from"#runtime/framework-tools/glob.js";import{GREP_TOOL_DEFINITION}from"#runtime/framework-tools/grep.js";import{READ_FILE_TOOL_DEFINITION}from"#runtime/framework-tools/read-file.js";import{SKILL_TOOL_DEFINITION}from"#runtime/framework-tools/skill.js";import{WEB_FETCH_TOOL_DEFINITION}from"#runtime/framework-tools/web-fetch.js";import{WRITE_FILE_TOOL_DEFINITION}from"#runtime/framework-tools/write-file.js";const ALL_FRAMEWORK_TOOLS=[ASK_QUESTION_TOOL_DEFINITION,BASH_TOOL_DEFINITION,GLOB_TOOL_DEFINITION,GREP_TOOL_DEFINITION,READ_FILE_TOOL_DEFINITION,WRITE_FILE_TOOL_DEFINITION,TODO_TOOL_DEFINITION,WEB_FETCH_TOOL_DEFINITION,WEB_SEARCH_TOOL_DEFINITION,SKILL_TOOL_DEFINITION];function getFrameworkToolDefinitions(e){return ALL_FRAMEWORK_TOOLS}function getAllFrameworkToolNames(){return new Set(ALL_FRAMEWORK_TOOLS.map(e=>e.name))}export{ConnectionRegistryKey,ReadFileStateKey,TodoStateKey,getAllFrameworkToolNames,getFrameworkToolDefinitions};
@@ -1 +1 @@
1
- import{DynamicSkillManifestKey,SandboxKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{loadSkillFromSandbox}from"#runtime/skills/sandbox-access.js";async function executeLoadSkillTool(e){let r=loadContext(),i=r.get(SandboxKey);if(i===void 0)throw Error(`The load_skill tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let{skill:a}=e;return await loadSkillFromSandbox(i,a,availableSkillNames(r))}function availableSkillNames(t){let n=Object.values(t.get(DynamicSkillManifestKey)??{}).flat().map(e=>e.name);return[...new Set(n)].sort()}const SKILL_OUTPUT_SCHEMA={type:`string`},SKILL_TOOL_DEFINITION={description:[`Load the full instructions for one available skill by name or id.`,`Use this tool when the request clearly matches a listed skill description or when the user explicitly asks for that skill.`,`Loading adds the skill instructions to the current turn.`,`Choose the "skill" value from the Available skills block.`].join(` `),execute:e=>executeLoadSkillTool(e),inputSchema:{additionalProperties:!1,properties:{skill:{description:`Available skill name or id.`,type:`string`}},required:[`skill`],type:`object`},logicalPath:`eve:framework/load-skill`,name:`load_skill`,outputSchema:SKILL_OUTPUT_SCHEMA,sourceId:`eve:load-skill-tool`,sourceKind:`module`};export{SKILL_OUTPUT_SCHEMA,SKILL_TOOL_DEFINITION};
1
+ import{DynamicSkillManifestKey,SandboxKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{loadSkillFromSandbox}from"#runtime/skills/sandbox-access.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";async function executeLoadSkillTool(e){let r=loadContext(),i=r.get(SandboxKey);if(i===void 0)throw Error(`The load_skill tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let{skill:a}=e,o=availableSkillNames(r);try{return await loadSkillFromSandbox(i,a,o)}catch(e){let t=r.get(ConnectionRegistryKey)?.getConnectionNames().find(e=>e.toLowerCase()===a.toLowerCase());if(t===void 0||o.includes(a))throw e;let n=e instanceof Error?e.message:String(e);throw Error(`${n} "${t}" is an installed connection, not a skill. Use connection_search with connection "${t}" to find its tools.`,{cause:e})}}function availableSkillNames(t){let n=Object.values(t.get(DynamicSkillManifestKey)??{}).flat().map(e=>e.name);return[...new Set(n)].sort()}const SKILL_OUTPUT_SCHEMA={type:`string`},SKILL_TOOL_DEFINITION={description:[`Load the full instructions for one available skill by name or id.`,`Use this tool when the request clearly matches a listed skill description or when the user explicitly asks for that skill.`,`This is not for MCP connections; use connection_search to access an installed connection.`,`Loading adds the skill instructions to the current turn.`,`Choose the "skill" value from the Available skills block.`].join(` `),execute:e=>executeLoadSkillTool(e),inputSchema:{additionalProperties:!1,properties:{skill:{description:`Available skill name or id.`,type:`string`}},required:[`skill`],type:`object`},logicalPath:`eve:framework/load-skill`,name:`load_skill`,outputSchema:SKILL_OUTPUT_SCHEMA,sourceId:`eve:load-skill-tool`,sourceKind:`module`};export{SKILL_OUTPUT_SCHEMA,SKILL_TOOL_DEFINITION};
@@ -1 +1 @@
1
- import{setChannelInstrumentationKind}from"#channel/compiled-channel.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeChannelDefinition}from"#internal/authored-definition/channel.js";import{ResolveAgentError,createResolvedModuleSourceRef,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{HTTP_ADAPTER_KIND}from"#channel/http.js";import{isHttpRouteDefinition,isWebSocketRouteDefinition}from"#channel/routes.js";async function resolveChannelDefinition(r,i,a){try{let t=normalizeChannelDefinition(await loadResolvedModuleExport({definition:r,kindLabel:`channel`,moduleMap:i,nodeId:a}),`Expected the channel export "${r.exportName??`default`}" from "${r.logicalPath}" to match the public eve shape.`),n=createResolvedModuleSourceRef({exportName:r.exportName,logicalPath:r.logicalPath,sourceId:r.sourceId}),o=t.routes.find(e=>e.method.toUpperCase()===r.method.toUpperCase()&&e.path===r.urlPath),s=`channel:${r.name}`;setChannelInstrumentationKind(t,s);let c=t.adapter;c&&c.kind!==HTTP_ADAPTER_KIND&&(c.kind=s);let l=resolveHttpRoute(r,o),u=resolveWebSocketRoute(r,o);return{name:r.name,method:r.method,urlPath:r.urlPath,fetch:async(e,t)=>l?l.handler(e,t):Response.json({error:`No matching route handler.`,ok:!1},{status:404}),handler:l?.handler,websocket:u?.handler,receive:t.receive,definition:t,adapter:c,...n}}catch(e){throw e instanceof ResolveAgentError?e:new ResolveAgentError(`Failed to attach the channel definition from "${r.logicalPath}": ${toErrorMessage(e)}`,{logicalPath:r.logicalPath,sourceId:r.sourceId})}}function resolveHttpRoute(e,t){if(!(t===void 0||e.method===`WEBSOCKET`||!isHttpRouteDefinition(t)))return t}function resolveWebSocketRoute(e,t){if(!(t===void 0||e.method!==`WEBSOCKET`||!isWebSocketRouteDefinition(t)))return t}export{resolveChannelDefinition};
1
+ import{setChannelInstrumentationKind}from"#channel/compiled-channel.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeChannelDefinition}from"#internal/authored-definition/channel.js";import{ResolveAgentError,createResolvedModuleSourceRef,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{HTTP_ADAPTER_KIND}from"#channel/http.js";import{isHttpRouteDefinition,isWebSocketRouteDefinition}from"#channel/routes.js";async function resolveChannelDefinition(r,i,a){try{let t=normalizeChannelDefinition(await loadResolvedModuleExport({definition:r,kindLabel:`channel`,moduleMap:i,nodeId:a}),`Expected the channel export "${r.exportName??`default`}" from "${r.logicalPath}" to match the public eve shape.`),n=createResolvedModuleSourceRef({exportName:r.exportName,logicalPath:r.logicalPath,sourceId:r.sourceId}),o=t.routes.find(e=>e.method.toUpperCase()===r.method.toUpperCase()&&e.path===r.urlPath),s=`channel:${r.name}`;setChannelInstrumentationKind(t,s);let c=t.adapter;c&&c.kind!==HTTP_ADAPTER_KIND&&(c.kind=s);let l=resolveHttpRoute(r,o),u=resolveWebSocketRoute(r,o);return{name:r.name,method:r.method,urlPath:r.urlPath,cors:r.cors,fetch:async(e,t)=>l?l.handler(e,t):Response.json({error:`No matching route handler.`,ok:!1},{status:404}),handler:l?.handler,websocket:u?.handler,receive:t.receive,definition:t,adapter:c,...n}}catch(e){throw e instanceof ResolveAgentError?e:new ResolveAgentError(`Failed to attach the channel definition from "${r.logicalPath}": ${toErrorMessage(e)}`,{logicalPath:r.logicalPath,sourceId:r.sourceId})}}function resolveHttpRoute(e,t){if(!(t===void 0||e.method===`WEBSOCKET`||!isHttpRouteDefinition(t)))return t}function resolveWebSocketRoute(e,t){if(!(t===void 0||e.method!==`WEBSOCKET`||!isWebSocketRouteDefinition(t)))return t}export{resolveChannelDefinition};
@@ -1,6 +1,7 @@
1
1
  import type { FlexibleSchema } from "ai";
2
2
  import type { ChannelAdapter } from "#channel/adapter.js";
3
3
  import type { CompiledChannel } from "#channel/compiled-channel.js";
4
+ import type { NormalizedChannelCorsOptions } from "#channel/cors.js";
4
5
  import type { HeadersValue } from "#client/types.js";
5
6
  import type { DiscoverDiagnosticsSummary } from "#discover/diagnostics.js";
6
7
  import type { ChannelRouteMethod, RouteContext } from "#public/definitions/channel.js";
@@ -190,6 +191,7 @@ export interface ResolvedChannelDefinition extends ResolvedModuleSourceRef {
190
191
  readonly name: string;
191
192
  readonly method: ChannelRouteMethod;
192
193
  readonly adapter?: ChannelAdapter;
194
+ readonly cors?: NormalizedChannelCorsOptions;
193
195
  readonly urlPath: string;
194
196
  readonly fetch: (req: Request, ctx: RouteContext) => Promise<Response>;
195
197
  /**
@@ -1 +1 @@
1
- import{select,text}from"../ask.js";import{CONNECTION_CATALOG,CUSTOM_CONNECTION_SLUG,SUPPORTED_PROTOCOLS,catalogSlugs,effectiveProtocols,getCatalogEntry,isValidConnectionSlug}from"#setup/scaffold/index.js";import{connectorServiceForEntry}from"#setup/scaffold/connections/catalog.js";const CONNECT_REQUIRES_VERCEL=`Authenticates through Vercel Connect, which needs a Vercel project. Re-run and choose to deploy to Vercel.`,PROTOCOL_LABELS={mcp:`MCP`,openapi:`OpenAPI`};function buildCatalogOptions(e){return CONNECTION_CATALOG.map(t=>{let n=e[t.slug];return n===void 0?{value:t.slug,label:t.label,hint:t.hint}:{value:t.slug,label:t.label,hint:t.hint,disabled:!0,disabledReason:n}})}function unknownSlugError(e){return Error(`Unknown connection "${e}". Known: ${catalogSlugs().join(`, `)}, or pass a custom name with a definition.`)}function assertSupportedProtocols(e,t){if(e.length===0)throw Error(`No supported protocol for "${t}". Supported: ${SUPPORTED_PROTOCOLS.join(`, `)}.`)}async function resolveProtocolInteractive(t,n,r){let i=effectiveProtocols(n);return assertSupportedProtocols(i,r),i.length===1?i[0]:t.ask(select({key:`protocol:${r}`,message:`Protocol for ${r}`,options:i.map(e=>({id:e,value:e,label:PROTOCOL_LABELS[e]}))}))}function resolveProtocolHeadless(e,t){let n=effectiveProtocols(e);if(assertSupportedProtocols(n,t),n.length>1)throw Error(`Connection "${t}" supports multiple protocols (${n.join(`, `)}). Pass --protocol to choose one.`);return n[0]}function deriveProvision(e,t){if(e.auth?.kind!==`connect`)return{kind:`none`};let n=connectorServiceForEntry({mcp:e.mcp,auth:e.auth});return n===void 0?{kind:`connect-manual`}:t?{kind:`command-hint`,service:n}:{kind:`connect`,service:n}}async function promptCustomSlug(e){return e.ask(text({key:`connection-name`,message:`Connection name`,placeholder:`mycorp`,validate:e=>{let t=e.trim();return t.length===0?`A name is required.`:isValidConnectionSlug(t)?null:`Start with a lowercase letter; use only lowercase letters, digits, and hyphens (max 64 characters).`}}))}async function planCustomInteractive(e,n){let r=await resolveProtocolInteractive(e,void 0,n),i=await e.ask(text({key:`description:${n}`,message:`Description for ${n}`,placeholder:`What this connection exposes`}));if(r===`mcp`){let a={slug:n,description:i,protocols:[`mcp`],mcp:{url:(await e.ask(text({key:`mcp-url:${n}`,message:`MCP server URL for ${n}`,placeholder:`https://mcp.example.com/sse`,validate:e=>e.trim().length===0?`A URL is required.`:null}))).trim()},auth:{kind:`connect`,connector:n}};return{slug:n,protocol:r,entry:a,provision:deriveProvision(a,!1)}}let a=await e.ask(text({key:`openapi-spec:${n}`,message:`OpenAPI spec URL for ${n}`,placeholder:`https://api.example.com/openapi.json`,validate:e=>e.trim().length===0?`A spec URL is required.`:null})),o=await e.ask(text({key:`openapi-base-url:${n}`,message:`Base URL for ${n} (optional)`,placeholder:`https://api.example.com`})),s={slug:n,description:i,protocols:[`openapi`],openapi:o.trim().length>0?{spec:a.trim(),baseUrl:o.trim()}:{spec:a.trim()},auth:{kind:`connect`,connector:n}};return{slug:n,protocol:r,entry:s,provision:deriveProvision(s,!1)}}async function planSelectionInteractive(e,t){if(t===CUSTOM_CONNECTION_SLUG)return planCustomInteractive(e,(await promptCustomSlug(e)).trim());let n=getCatalogEntry(t);if(n!==void 0)return{slug:t,protocol:await resolveProtocolInteractive(e,n.protocols,t),entry:n,provision:deriveProvision(n,!1)};if(!isValidConnectionSlug(t))throw unknownSlugError(t);return planCustomInteractive(e,t)}function planPresetHeadless(e){if(e===CUSTOM_CONNECTION_SLUG)throw Error(`Custom connection requires interactive input or a preset definition.`);let t=getCatalogEntry(e);if(t!==void 0)return{slug:e,protocol:resolveProtocolHeadless(t.protocols,e),entry:t,provision:deriveProvision(t,!0)};throw isValidConnectionSlug(e)?Error(`Custom connection "${e}" requires interactive input or a preset definition.`):unknownSlugError(e)}function selectConnections(e){return{id:`select-connections`,async gather(){let t=e.headless??!1,n=e.presetConnections??[];if(t)return n.map(e=>planPresetHeadless(e));let r;if(n.length>0)r=[...n];else{let t=buildCatalogOptions({}).map(e=>({id:String(e.value),value:String(e.value),label:e.label,hint:e.hint,disabled:e.disabled,disabledReason:e.disabledReason}));r=await e.asker.askMany({key:`connection`,message:`What should your agent connect to?`,options:t})}let i=[];for(let t of r)i.push(await planSelectionInteractive(e.asker,t));return i},async perform({input:e}){return e},apply(e,t){return{...e,connectionSelection:t}}}}export{CONNECT_REQUIRES_VERCEL,buildCatalogOptions,selectConnections};
1
+ import{select,text}from"../ask.js";import{CONNECTION_CATALOG,CUSTOM_CONNECTION_SLUG,SUPPORTED_PROTOCOLS,catalogSlugs,effectiveProtocols,getCatalogEntry,isValidConnectionSlug}from"#setup/scaffold/index.js";import{connectorServiceForEntry}from"#setup/scaffold/connections/catalog.js";const CONNECT_REQUIRES_VERCEL=`Authenticates through Vercel Connect, which needs a Vercel project. Re-run and choose to deploy to Vercel.`,PROTOCOL_LABELS={mcp:`MCP`,openapi:`OpenAPI`};function buildCatalogOptions(e){return CONNECTION_CATALOG.map(t=>{let n=e[t.slug];return n===void 0?{value:t.slug,label:t.label,hint:t.hint}:{value:t.slug,label:t.label,hint:t.hint,disabled:!0,disabledReason:n}})}function unknownSlugError(e){return Error(`Unknown connection "${e}". Known: ${catalogSlugs().join(`, `)}, or pass a custom name with a definition.`)}function assertSupportedProtocols(e,t){if(e.length===0)throw Error(`No supported protocol for "${t}". Supported: ${SUPPORTED_PROTOCOLS.join(`, `)}.`)}async function resolveProtocolInteractive(t,n,r){let i=effectiveProtocols(n);return assertSupportedProtocols(i,r),i.length===1?i[0]:t.ask(select({key:`protocol:${r}`,message:`Protocol for ${r}`,options:i.map(e=>({id:e,value:e,label:PROTOCOL_LABELS[e]}))}))}function resolveProtocolHeadless(e,t){let n=effectiveProtocols(e);if(assertSupportedProtocols(n,t),n.length>1)throw Error(`Connection "${t}" supports multiple protocols (${n.join(`, `)}). Pass --protocol to choose one.`);return n[0]}function deriveProvision(e,t){if(e.auth?.kind!==`connect`)return{kind:`none`};let n=connectorServiceForEntry({mcp:e.mcp,auth:e.auth});return n===void 0?{kind:`connect-manual`}:t?{kind:`command-hint`,service:n}:{kind:`connect`,service:n}}async function promptCustomSlug(e){return e.ask(text({key:`connection-name`,message:`Connection name`,placeholder:`mycorp`,validate:e=>{let t=e.trim();return t.length===0?`A name is required.`:isValidConnectionSlug(t)?null:`Start with a lowercase letter; use only lowercase letters, digits, and hyphens (max 64 characters).`}}))}async function planCustomInteractive(e,n){let r=await resolveProtocolInteractive(e,void 0,n),i=await e.ask(text({key:`description:${n}`,message:`Description for ${n}`,placeholder:`What this connection exposes`}));if(r===`mcp`){let a={slug:n,description:i,protocols:[`mcp`],mcp:{url:(await e.ask(text({key:`mcp-url:${n}`,message:`MCP server URL for ${n}`,placeholder:`https://mcp.example.com/mcp`,validate:e=>e.trim().length===0?`A URL is required.`:null}))).trim()},auth:{kind:`connect`,connector:n}};return{slug:n,protocol:r,entry:a,provision:deriveProvision(a,!1)}}let a=await e.ask(text({key:`openapi-spec:${n}`,message:`OpenAPI spec URL for ${n}`,placeholder:`https://api.example.com/openapi.json`,validate:e=>e.trim().length===0?`A spec URL is required.`:null})),o=await e.ask(text({key:`openapi-base-url:${n}`,message:`Base URL for ${n} (optional)`,placeholder:`https://api.example.com`})),s={slug:n,description:i,protocols:[`openapi`],openapi:o.trim().length>0?{spec:a.trim(),baseUrl:o.trim()}:{spec:a.trim()},auth:{kind:`connect`,connector:n}};return{slug:n,protocol:r,entry:s,provision:deriveProvision(s,!1)}}async function planSelectionInteractive(e,t){if(t===CUSTOM_CONNECTION_SLUG)return planCustomInteractive(e,(await promptCustomSlug(e)).trim());let n=getCatalogEntry(t);if(n!==void 0)return{slug:t,protocol:await resolveProtocolInteractive(e,n.protocols,t),entry:n,provision:deriveProvision(n,!1)};if(!isValidConnectionSlug(t))throw unknownSlugError(t);return planCustomInteractive(e,t)}function planPresetHeadless(e){if(e===CUSTOM_CONNECTION_SLUG)throw Error(`Custom connection requires interactive input or a preset definition.`);let t=getCatalogEntry(e);if(t!==void 0)return{slug:e,protocol:resolveProtocolHeadless(t.protocols,e),entry:t,provision:deriveProvision(t,!0)};throw isValidConnectionSlug(e)?Error(`Custom connection "${e}" requires interactive input or a preset definition.`):unknownSlugError(e)}function selectConnections(e){return{id:`select-connections`,async gather(){let t=e.headless??!1,n=e.presetConnections??[];if(t)return n.map(e=>planPresetHeadless(e));let r;if(n.length>0)r=[...n];else{let t=buildCatalogOptions({}).map(e=>({id:String(e.value),value:String(e.value),label:e.label,hint:e.hint,disabled:e.disabled,disabledReason:e.disabledReason}));r=await e.asker.askMany({key:`connection`,message:`What should your agent connect to?`,options:t})}let i=[];for(let t of r)i.push(await planSelectionInteractive(e.asker,t));return i},async perform({input:e}){return e},apply(e,t){return{...e,connectionSelection:t}}}}export{CONNECT_REQUIRES_VERCEL,buildCatalogOptions,selectConnections};
@@ -30,6 +30,8 @@ export interface RowGlyphs {
30
30
  placeholder: string;
31
31
  /** Separator before an inline hint. */
32
32
  dot: string;
33
+ /** Attention marker for an unavailable option with actionable guidance. */
34
+ warning: string;
33
35
  }
34
36
  /** Canonical unicode glyphs; the CLI prompts render with these. */
35
37
  export declare const UNICODE_ROW_GLYPHS: RowGlyphs;
@@ -1 +1 @@
1
- const UNICODE_ROW_GLYPHS={pointer:`▷`,selectedPointer:`▶`,success:`✓`,placeholder:`◦`,dot:`·`};function resolveOptionRowState(e,t){if(Number(e.disabled===!0)+Number(e.completed===!0)+Number(e.locked===!0)>1)throw Error(`An option row cannot combine disabled, completed, or locked states.`);if(e.disabled===!0){let t={kind:`disabled`};return e.disabledReason!==void 0&&(t.reason=e.disabledReason),e.disabledReasonTone!==void 0&&(t.reasonTone=e.disabledReasonTone),t}if(e.completed===!0)return{kind:`completed`};if(e.locked===!0){let t={kind:`locked`};return e.lockedReason!==void 0&&(t.reason=e.lockedReason),t}return{kind:`available`,checked:t}}function parenthetical(e){return e===void 0?``:` (${e})`}function unfocusedGlyph(e){return e.placeholder?e.colors.dim(e.glyphs.placeholder):` `}function disabledLabel(e,t,n){let r=parenthetical(t.reason);return t.reasonTone===`warning`?`${n.dim(e)}${n.yellow(r)}`:n.dim(`${e}${r}`)}function optionRowPresentation(e){let{colors:t,glyphs:n,state:r}=e;switch(r.kind){case`available`:return e.isCursor?{glyph:n.selectedPointer,label:e.label}:{glyph:r.checked?t.green(n.success):unfocusedGlyph(e),label:e.accent===`warning`?t.yellow(e.label):e.label};case`completed`:return{glyph:e.isCursor?t.dim(n.pointer):t.green(n.success),label:t.dim(e.label)};case`disabled`:return{glyph:e.isCursor?t.dim(n.pointer):unfocusedGlyph(e),label:disabledLabel(e.label,r,t)};case`locked`:return{glyph:t.dim(t.green(n.success)),label:t.dim(`${e.label}${parenthetical(r.reason)}`)}}return r}function renderCursorRow(e,t,n,r){if(!t)return` ${e}`;let i=r===`warning`?n.yellow:n.blue;return n.inverse(i(` ${e} `))}function renderOptionRowContinuation(e){return` ${e}`}function renderOptionRow(e){let{colors:t,glyphs:n}=e,{glyph:r,label:i}=optionRowPresentation(e),a=e.isCursor&&e.state.kind===`available`,o=e.hint;e.isCursor&&e.focusHint!==void 0&&(o=e.focusHint);let s=``;if(o!==void 0){let r=Math.max(0,(e.hintPadding??0)+1-Number(a));s=t.dim(`${` `.repeat(r)}${n.dot} ${o}`)}return`${renderCursorRow(`${r} ${i}`,a,t,e.accent)}${s}`}export{UNICODE_ROW_GLYPHS,renderCursorRow,renderOptionRow,renderOptionRowContinuation,resolveOptionRowState};
1
+ const UNICODE_ROW_GLYPHS={pointer:`▷`,selectedPointer:`▶`,success:`✓`,placeholder:`◦`,dot:`·`,warning:`⚠`};function resolveOptionRowState(e,t){if(Number(e.disabled===!0)+Number(e.completed===!0)+Number(e.locked===!0)>1)throw Error(`An option row cannot combine disabled, completed, or locked states.`);if(e.disabled===!0){let t={kind:`disabled`};return e.disabledReason!==void 0&&(t.reason=e.disabledReason),e.disabledReasonTone!==void 0&&(t.reasonTone=e.disabledReasonTone),t}if(e.completed===!0)return{kind:`completed`};if(e.locked===!0){let t={kind:`locked`};return e.lockedReason!==void 0&&(t.reason=e.lockedReason),t}return{kind:`available`,checked:t}}function parenthetical(e){return e===void 0?``:` (${e})`}function unfocusedGlyph(e){return e.placeholder?e.colors.dim(e.glyphs.placeholder):` `}function disabledLabel(e,t,n,r){if(t.reasonTone===`warning`){let i=t.reason===void 0?``:` ${r.warning} ${t.reason}`;return`${n.dim(e)}${n.yellow(i)}`}let i=parenthetical(t.reason);return n.dim(`${e}${i}`)}function optionRowPresentation(e){let{colors:t,glyphs:n,state:r}=e;switch(r.kind){case`available`:return e.isCursor?{glyph:n.selectedPointer,label:e.label}:{glyph:r.checked?t.green(n.success):unfocusedGlyph(e),label:e.accent===`warning`?t.yellow(e.label):e.label};case`completed`:return{glyph:e.isCursor?t.dim(n.pointer):t.green(n.success),label:t.dim(e.label)};case`disabled`:return{glyph:e.isCursor?t.dim(n.pointer):unfocusedGlyph(e),label:disabledLabel(e.label,r,t,n)};case`locked`:return{glyph:t.dim(t.green(n.success)),label:t.dim(`${e.label}${parenthetical(r.reason)}`)}}return r}function renderCursorRow(e,t,n,r){if(!t)return` ${e}`;let i=r===`warning`?n.yellow:n.blue;return n.inverse(i(` ${e} `))}function renderOptionRowContinuation(e){return` ${e}`}function renderOptionRow(e){let{colors:t,glyphs:n}=e,{glyph:r,label:i}=optionRowPresentation(e),a=e.isCursor&&e.state.kind===`available`,o=e.hint;e.isCursor&&e.focusHint!==void 0&&(o=e.focusHint);let s=``;if(o!==void 0){let r=Math.max(0,(e.hintPadding??0)+1-Number(a));s=t.dim(`${` `.repeat(r)}${n.dot} ${o}`)}return`${renderCursorRow(`${r} ${i}`,a,t,e.accent)}${s}`}export{UNICODE_ROW_GLYPHS,renderCursorRow,renderOptionRow,renderOptionRowContinuation,resolveOptionRowState};
@@ -32,5 +32,6 @@ export declare function runConnectionsFlow(input: {
32
32
  appRoot: string;
33
33
  prompter: Prompter;
34
34
  signal?: AbortSignal;
35
+ disabledConnectionReasons?: Readonly<Record<string, string>>;
35
36
  deps?: Partial<ConnectionsFlowDeps>;
36
37
  }): Promise<ConnectionsFlowResult>;
@@ -1,3 +1,3 @@
1
- import{interactiveAsker}from"../ask.js";import{detectDeployment,isProjectResolved,projectResolutionFromDeployment}from"../project-resolution.js";import{snapshotSetupState}from"../state.js";import{WizardCancelledError}from"../step.js";import{withSpinner}from"../with-spinner.js";import{getVercelAuthStatus,vercelAuthBlockerReason}from"../vercel-project.js";import{selectConnections}from"../boxes/select-connections.js";import{addConnections}from"../boxes/add-connections.js";import{runInteractive}from"../runner.js";import{inProjectSetupState,prompterSink}from"./in-project.js";import{runLinkFlow}from"./link.js";import{CONNECTION_CATALOG,ensureConnectionDependencies,listAuthoredConnections}from"#setup/scaffold/index.js";import{detectPackageManager}from"#setup/package-manager.js";import{toErrorMessage}from"#shared/errors.js";import{createPromptCommandOutput,withPhase}from"#setup/cli/index.js";import{runPackageManagerInstall}from"#setup/primitives/pm/run.js";const CONNECTIONS_PROMPT_MESSAGE=`Select an MCP server to add to your agent through Vercel Connect`,CONNECT_CONNECTIONS=CONNECTION_CATALOG.filter(e=>e.auth.kind===`connect`);function connectionRows(e,t){let n=vercelAuthBlockerReason(t),r=CONNECT_CONNECTIONS.map(t=>{let r={value:t.slug,label:t.label};return e.has(t.slug)?{...r,completed:!0,focusHint:`Already added`}:n===void 0?{...r,hint:t.hint}:{...r,disabled:!0,disabledReason:n,disabledReasonTone:`warning`}});return r.push({value:`done`,label:`Done`,trailingAction:!0}),r}async function pickConnection(e,t,n){let r=connectionRows(t,n),i={message:CONNECTIONS_PROMPT_MESSAGE,options:r,hintLayout:`inline`,search:!0,placeholder:`type to search MCP servers`};r.some(e=>e.value!==`done`&&e.disabled!==!0&&e.completed!==!0)||(i.initialValue=`done`);try{return await e.select(i)}catch(e){if(e instanceof WizardCancelledError)return;throw e}}async function runConnectionsFlow(a){let{appRoot:o,prompter:s,signal:c}=a,l={detectDeployment,detectPackageManager,ensureConnectionDependencies,getVercelAuthStatus,listAuthoredConnections,runLinkFlow,runPackageManagerInstall,...a.deps},[u,d,f]=await withSpinner(s,`Checking the project…`,()=>Promise.all([l.detectDeployment(o,{signal:c}),l.listAuthoredConnections(o),l.getVercelAuthStatus(o,{signal:c})]));c?.throwIfAborted();let p=inProjectSetupState(o,projectResolutionFromDeployment(u)),m=new Set(d),h=await pickConnection(s,m,f);if(h===void 0)return{kind:`cancelled`};if(h===`done`||m.has(h))return{kind:`done`,addedConnections:[]};try{if(!isProjectResolved(p.project)){if((await l.runLinkFlow({appRoot:o,prompter:s,signal:c,projectSelection:`create-or-link`,teamSelectMessage:()=>`You need to link to a project to use Vercel Connect.
1
+ import{interactiveAsker}from"../ask.js";import{detectDeployment,isProjectResolved,projectResolutionFromDeployment}from"../project-resolution.js";import{snapshotSetupState}from"../state.js";import{WizardCancelledError}from"../step.js";import{withSpinner}from"../with-spinner.js";import{getVercelAuthStatus,vercelAuthBlockerReason}from"../vercel-project.js";import{selectConnections}from"../boxes/select-connections.js";import{addConnections}from"../boxes/add-connections.js";import{runInteractive}from"../runner.js";import{inProjectSetupState,prompterSink}from"./in-project.js";import{runLinkFlow}from"./link.js";import{CONNECTION_CATALOG,ensureConnectionDependencies,listAuthoredConnections}from"#setup/scaffold/index.js";import{detectPackageManager}from"#setup/package-manager.js";import{toErrorMessage}from"#shared/errors.js";import{createPromptCommandOutput,withPhase}from"#setup/cli/index.js";import{runPackageManagerInstall}from"#setup/primitives/pm/run.js";const CONNECTIONS_PROMPT_MESSAGE=`Select an MCP server to add to your agent through Vercel Connect`,CONNECT_CONNECTIONS=CONNECTION_CATALOG.filter(e=>e.auth.kind===`connect`);function connectionRows(e,t,n){let r=vercelAuthBlockerReason(t),i=CONNECT_CONNECTIONS.map(t=>{let i={value:t.slug,label:t.label};if(e.has(t.slug))return{...i,completed:!0,focusHint:`Already added`};let a=n[t.slug];return a===void 0?r===void 0?{...i,hint:t.hint}:{...i,disabled:!0,disabledReason:r,disabledReasonTone:`warning`}:{...i,disabled:!0,disabledReason:a,disabledReasonTone:`warning`}});return i.push({value:`done`,label:`Done`,trailingAction:!0}),i}async function pickConnection(e,t,n,r){let i=connectionRows(t,n,r),o={message:CONNECTIONS_PROMPT_MESSAGE,options:i,hintLayout:`inline`,search:!0,placeholder:`type to search MCP servers`};i.some(e=>e.value!==`done`&&e.disabled!==!0&&e.completed!==!0)||(o.initialValue=`done`);try{return await e.select(o)}catch(e){if(e instanceof WizardCancelledError)return;throw e}}async function runConnectionsFlow(s){let{appRoot:c,prompter:l,signal:u}=s,d={detectDeployment,detectPackageManager,ensureConnectionDependencies,getVercelAuthStatus,listAuthoredConnections,runLinkFlow,runPackageManagerInstall,...s.deps},[f,p,m]=await withSpinner(l,`Checking the project…`,()=>Promise.all([d.detectDeployment(c,{signal:u}),d.listAuthoredConnections(c),d.getVercelAuthStatus(c,{signal:u})]));u?.throwIfAborted();let h=inProjectSetupState(c,projectResolutionFromDeployment(f)),g=new Set(p),_=await pickConnection(l,g,m,s.disabledConnectionReasons??{});if(_===void 0)return{kind:`cancelled`};if(_===`done`||g.has(_))return{kind:`done`,addedConnections:[]};try{if(!isProjectResolved(h.project)){if((await d.runLinkFlow({appRoot:c,prompter:l,signal:u,projectSelection:`create-or-link`,teamSelectMessage:()=>`You need to link to a project to use Vercel Connect.
2
2
 
3
- Select your team`})).kind===`cancelled`)return{kind:`cancelled`};let e=projectResolutionFromDeployment(await withSpinner(s,`Checking the project…`,()=>l.detectDeployment(o,{signal:c})));if(!isProjectResolved(e))throw Error(`Project link was not found after linking.`);p={...p,project:e}}let t=await l.detectPackageManager(o);if(await l.ensureConnectionDependencies({projectRoot:o}),!await withPhase(s.log,`Installing connection dependencies (${t.kind} install)...`,()=>l.runPackageManagerInstall(t.kind,o,{onOutput:createPromptCommandOutput(s.log),signal:c})))throw Error(`Dependency installation failed. Run \`${t.kind} install\`.`);if((await runInteractive([selectConnections({asker:interactiveAsker(s),presetConnections:[h]}),addConnections({prompter:s,signal:c,deps:l.addConnections})],p,prompterSink(s),{snapshot:snapshotSetupState,signal:c})).kind!==`done`)return{kind:`cancelled`};if(!new Set(await l.listAuthoredConnections(o)).has(h))throw Error(`Connection "${h}" was not added.`);return{kind:`done`,addedConnections:[h]}}catch(e){return e instanceof WizardCancelledError?{kind:`cancelled`}:{kind:`failed`,addedConnections:new Set(await l.listAuthoredConnections(o)).has(h)?[h]:[],message:toErrorMessage(e)}}}export{CONNECTIONS_PROMPT_MESSAGE,runConnectionsFlow};
3
+ Select your team`})).kind===`cancelled`)return{kind:`cancelled`};let e=projectResolutionFromDeployment(await withSpinner(l,`Checking the project…`,()=>d.detectDeployment(c,{signal:u})));if(!isProjectResolved(e))throw Error(`Project link was not found after linking.`);h={...h,project:e}}let t=await d.detectPackageManager(c);if(await d.ensureConnectionDependencies({projectRoot:c}),!await withPhase(l.log,`Installing connection dependencies (${t.kind} install)...`,()=>d.runPackageManagerInstall(t.kind,c,{onOutput:createPromptCommandOutput(l.log),signal:u})))throw Error(`Dependency installation failed. Run \`${t.kind} install\`.`);if((await runInteractive([selectConnections({asker:interactiveAsker(l),presetConnections:[_]}),addConnections({prompter:l,signal:u,deps:d.addConnections})],h,prompterSink(l),{snapshot:snapshotSetupState,signal:u})).kind!==`done`)return{kind:`cancelled`};if(!new Set(await d.listAuthoredConnections(c)).has(_))throw Error(`Connection "${_}" was not added.`);return{kind:`done`,addedConnections:[_]}}catch(e){return e instanceof WizardCancelledError?{kind:`cancelled`}:{kind:`failed`,addedConnections:new Set(await d.listAuthoredConnections(c)).has(_)?[_]:[],message:toErrorMessage(e)}}}export{CONNECTIONS_PROMPT_MESSAGE,runConnectionsFlow};
@@ -1,4 +1,4 @@
1
- import{pinnedNodeEngineMajor}from"../../node-engine.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{basename,join,resolve}from"node:path";import{mkdir,readdir,stat}from"node:fs/promises";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),DEFAULT_AI_PACKAGE_VERSION=`^7.0.0`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.16.0`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
1
+ import{pinnedNodeEngineMajor}from"../../node-engine.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{basename,join,resolve}from"node:path";import{mkdir,readdir,stat}from"node:fs/promises";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),DEFAULT_AI_PACKAGE_VERSION=`^7.0.0`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.16.1`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
2
2
 
3
3
  export default defineAgent({
4
4
  model: "__EVE_INIT_MODEL__",
@@ -55,6 +55,25 @@ Declare routes with the `POST()` and `GET()` helpers. Each route handler receive
55
55
 
56
56
  Event handlers like `"message.completed"` are declared under the `events` key. They receive `(eventData, channel, ctx)`, where `eventData` is the event payload, `channel` carries platform handles and session continuation operations, and `ctx` is the eve `SessionContext`. Every channel kind shares this signature. The one exception is `session.failed`, which receives only `(eventData, channel)` with no `ctx`.
57
57
 
58
+ ## CORS
59
+
60
+ Custom HTTP channels leave CORS untouched unless you opt in. Pass `cors: true`
61
+ for permissive browser access with preflight handling, or pass a serializable
62
+ CORS options object to narrow origins, methods, and headers:
63
+
64
+ ```ts
65
+ import { defineChannel, POST } from "eve/channels";
66
+
67
+ export default defineChannel({
68
+ cors: {
69
+ origin: ["https://app.example.com"],
70
+ methods: ["POST"],
71
+ allowHeaders: ["authorization", "content-type"],
72
+ },
73
+ routes: [POST("/message", async () => new Response("ok"))],
74
+ });
75
+ ```
76
+
58
77
  ## WebSocket routes
59
78
 
60
79
  Use `WS()` when a custom channel needs a WebSocket endpoint. The route handler runs once per upgrade request and returns lifecycle hooks for that connection: