eve 0.83.1 → 0.83.3
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.
- package/CHANGELOG.md +41 -0
- package/dist/src/channel/types.d.ts +3 -2
- package/dist/src/chunks/{use-eve-agent-ZY7NQ2VW.js → use-eve-agent-BE2_zd5q.js} +17 -12
- package/dist/src/chunks/{use-eve-agent-DnbG9c7c.js → use-eve-agent-e8a5vcFO.js} +17 -12
- package/dist/src/client/optimistic-message-submissions.d.ts +2 -3
- package/dist/src/client/optimistic-message-submissions.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/evals/assertions/run.js +1 -1
- package/dist/src/evals/runner/derive-run-facts.d.ts +13 -0
- package/dist/src/evals/runner/derive-run-facts.js +1 -1
- package/dist/src/evals/session.js +2 -2
- package/dist/src/evals/types.d.ts +1 -1
- package/dist/src/eve-channel/request.js +1 -1
- package/dist/src/execution/cancelled-model-call-batch.js +1 -1
- package/dist/src/execution/catalog/connection-auth.js +1 -1
- package/dist/src/execution/catalog/connection-entry.js +1 -1
- package/dist/src/execution/catalog/rank.js +1 -1
- package/dist/src/execution/connections/callback-route.d.ts +3 -2
- package/dist/src/execution/connections/callback-route.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/legacy-session/prepare-step.js +1 -1
- package/dist/src/execution/node-step.d.ts +1 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/sandbox/multiplexed-command.d.ts +9 -3
- package/dist/src/execution/sandbox/multiplexed-command.js +1 -1
- package/dist/src/execution/sandbox/read-file.js +1 -1
- package/dist/src/execution/session/handoff-steps.d.ts +1 -0
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/handoff.d.ts +1 -0
- package/dist/src/execution/session/handoff.js +1 -1
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session-event-stream.d.ts +6 -0
- package/dist/src/execution/session-event-stream.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/web-fetch/html.js +3 -4
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/extensions/git/extension/lib/gh-tool.d.ts +11 -2
- package/dist/src/extensions/git/extension/lib/gh-tool.js +1 -1
- package/dist/src/harness/attachment-staging.js +1 -1
- package/dist/src/harness/compaction/engine.js +2 -2
- package/dist/src/harness/compaction/over-limit-error.d.ts +7 -0
- package/dist/src/harness/compaction/over-limit-error.js +1 -0
- package/dist/src/harness/compaction/prompt.js +1 -1
- package/dist/src/harness/compaction/step.d.ts +16 -1
- package/dist/src/harness/compaction/step.js +1 -1
- package/dist/src/harness/emission.d.ts +8 -3
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/hitl/approvals.d.ts +2 -0
- package/dist/src/harness/hitl/approvals.js +1 -1
- package/dist/src/harness/hitl/delivery.d.ts +1 -0
- package/dist/src/harness/hitl/delivery.js +1 -1
- package/dist/src/harness/hitl/intake.js +1 -1
- package/dist/src/harness/model-call/call.d.ts +8 -2
- package/dist/src/harness/model-call/call.js +1 -1
- package/dist/src/harness/model-call/failure.d.ts +7 -0
- package/dist/src/harness/model-call/failure.js +1 -1
- package/dist/src/harness/model-call/request.d.ts +2 -1
- package/dist/src/harness/model-call/run.js +1 -1
- package/dist/src/harness/model-call/usage.js +1 -1
- package/dist/src/harness/session-machine/current.d.ts +8 -0
- package/dist/src/harness/session-machine/current.js +1 -1
- package/dist/src/harness/token-estimate.js +1 -1
- package/dist/src/harness/types.d.ts +6 -0
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/attachments/media-metadata.d.ts +0 -2
- package/dist/src/internal/attachments/media-metadata.js +1 -1
- package/dist/src/internal/attachments/read-media-metadata.d.ts +7 -0
- package/dist/src/internal/attachments/read-media-metadata.js +2 -0
- package/dist/src/internal/authored-asset-import-plugin.d.ts +11 -3
- package/dist/src/internal/authored-asset-import-plugin.js +1 -1
- package/dist/src/internal/authored-module-build-options.js +1 -1
- package/dist/src/internal/authored-module-graph.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +0 -1
- package/dist/src/internal/authored-module-loader.js +1 -1
- package/dist/src/internal/authored-package-boundary.d.ts +3 -0
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/input-text.d.ts +2 -1
- package/dist/src/internal/nitro/dev-client-address.d.ts +12 -0
- package/dist/src/internal/nitro/dev-client-address.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.d.ts +6 -3
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
- package/dist/src/internal/workflow-bundle/builder.js +2 -2
- package/dist/src/public/channels/auth.d.ts +14 -0
- package/dist/src/public/channels/auth.js +1 -1
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +6 -1
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +1 -1
- package/dist/src/public/channels/slack/reply-delivery.d.ts +1 -7
- package/dist/src/public/channels/slack/reply-delivery.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +2 -6
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/undelivered-reply.d.ts +30 -0
- package/dist/src/public/channels/undelivered-reply.js +1 -0
- package/dist/src/runtime/connections/authorization-complete-page.d.ts +14 -2
- package/dist/src/runtime/connections/authorization-complete-page.js +5 -5
- package/dist/src/runtime/connections/mcp-client.d.ts +5 -2
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/openapi-client.js +1 -1
- package/dist/src/runtime/connections/openapi-operations.d.ts +4 -0
- package/dist/src/runtime/connections/openapi-operations.js +1 -1
- package/dist/src/runtime/connections/openapi-schema.d.ts +19 -14
- package/dist/src/runtime/connections/openapi-schema.js +1 -1
- package/dist/src/runtime/local-dev-capability.d.ts +2 -2
- package/dist/src/runtime/local-dev-capability.js +1 -1
- package/dist/src/runtime/subagents/workflow.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/connection-types.d.ts +5 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tools/schema.d.ts +2 -0
- package/dist/src/tools/schema.js +1 -1
- package/dist/src/tools/signature.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/chat-sdk.mdx +1 -1
- package/docs/channels/custom.mdx +4 -0
- package/docs/channels/slack.mdx +3 -1
- package/docs/concepts/built-in-tools.md +1 -1
- package/docs/concepts/default-harness.md +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +1 -1
- package/docs/connections/mcp.mdx +1 -1
- package/docs/connections/openapi.mdx +1 -1
- package/docs/guides/auth-and-route-protection.md +4 -0
- package/docs/reference/cli.md +3 -1
- package/docs/reference/typescript-api.md +3 -1
- package/docs/tools/human-in-the-loop.md +3 -1
- package/docs/tools/tasks.md +2 -2
- package/package.json +6 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,46 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.83.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 3e96a14: An optimistic message no longer stays in the `submitted` state when its turn is cancelled or fails before the agent reads it. `EveAgentStore` now marks that message `failed`, so it keeps its own text, and later messages reconcile against their own submissions. A steered message the cancelled turn never read now also lets its `send()` settle. Thanks @brettcrane for reporting this in #3102.
|
|
8
|
+
- 8077f2d: With `otel({ traceChannelRequests: true })`, the `agent.channel.request` span now ends when the response body finishes, fails, or is cancelled, not when the route handler returns. Session stream requests no longer log `You can only call end() on a span once.` for `workflow.stream.read.connect`, and request spans now cover the full streaming time. Thanks @ahcarpenter for reporting this and proposing the fix in #4256.
|
|
9
|
+
- 54adf15: `chatSdkChannel` now reports failed final reply delivery with an error-id notice and a note to the model, avoids reposting streamed replies, and skips unchanged final edits after state restoration. Thanks @diegojohnsonl for reporting this in #4801.
|
|
10
|
+
- 4280d51: A hook that cancels the turn at `compaction.completed` no longer drops the compaction's summary call from the session's usage. `session.waiting` and session limits now count it.
|
|
11
|
+
- 181caed: Compaction no longer re-runs on every step when the current user message is most of the context window. After a compaction, eve keeps at most 20,000 tokens of the latest conversation word for word next to the summary, with tool results shortened to 2,000 characters; a current message larger than that keeps its start and end, and the cut-out middle is summarized. A compaction that cannot bring the history under the threshold now fails the session, without retrying the step, with an error that says to start a new session or send a smaller message.
|
|
12
|
+
- cea4eb0: Declare `next` as an optional peer dependency, so `eve/next` types resolve the app's own `next` in pnpm workspaces that install more than one `next` version. Thanks @laugharn for reporting this in #5341.
|
|
13
|
+
- 80db4b3: A session started before eve 0.57 now imports on its next message instead of failing with `IncompatibleStateLayoutError` for `eve.mode`. The import drops the framework context keys that those builds saved and the current build no longer defines. Thanks @sunlanchang for reporting this in #5213.
|
|
14
|
+
- 200d2d8: `localDev()` now refuses requests that a browser sends for another website: a non-loopback request host or `Origin`. A web page open in the developer's browser can no longer start sessions or run the agent's tools on an `eve dev` server, including through DNS rebinding. Frontends served from any loopback host and port still authenticate.
|
|
15
|
+
- 243a4a4: `localDev()` now refuses callers on other machines. Before, an `eve dev` server started with `--host 0.0.0.0` gave every LAN caller the `local-dev` principal, so they could run the agent and its local editing tools, which write to the project's `agent/` source. Callers on the same machine are unchanged, including the developer's own clients when `--host` names a LAN address.
|
|
16
|
+
- da515dc: OpenAPI `operations.allow` and `operations.block` now match an operation's `operationId` as written in the spec, as well as its generated tool name. Before, an `operationId` with characters such as `.` or `/` never matched, because eve compared the filter only against the sanitized tool name, so a blocked operation stayed callable.
|
|
17
|
+
- 9a55d23: OpenAPI connection tools no longer reject valid deeply nested input, such as a Notion page title. eve now keeps the spec's referenced schemas under `$defs` instead of copying them inline up to a depth limit, so validation applies at every depth and shared schemas no longer grow exponentially. Thanks @lildesert for reporting this with a minimal reproduction in #3267.
|
|
18
|
+
- b8b36a8: Preserve the original session output stream’s public encryption metadata during deployment handoffs, avoiding repeated run metadata and encryption-key lookups before later turns.
|
|
19
|
+
- 7cf27bb: Text a root session's model writes before `eve__task_wait` in the same step now posts as a reply. Before, Slack showed it only as the thread status, and Telegram, Teams, and other channels dropped it.
|
|
20
|
+
- f3e3140: Fixed a denial-of-service issue in `webFetch` with `format: "text"`: HTML text extraction now runs in linear time, so malformed pages, such as ones with unclosed `<script>` tags or stray `<` characters, can no longer block the event loop. Content after an unclosed `<script>`, `<style>`, `<noscript>`, or `<!--` is now dropped, as browsers do. Thanks @not2face for the report.
|
|
21
|
+
- de1b9aa: Workspace packages bundled from TypeScript source can now import their own files with `?raw` and other relative asset imports. Before, `eve build` failed with "resolves outside package root" when an agent imported such a package. `?raw` now also works for `.json` files and files without an extension, such as a `Dockerfile`.
|
|
22
|
+
|
|
23
|
+
## 0.83.2
|
|
24
|
+
|
|
25
|
+
### Patch Changes
|
|
26
|
+
|
|
27
|
+
- 8329939: A parent agent's message to a subagent no longer answers the subagent's pending tool approval or session-limit prompt. Before, a follow-up such as `approve` or `continue` settled the prompt as if the person had answered it. Now only a person's structured answer settles it: the parent's message is delivered as an ordinary message, so a pending approval resolves as `ignored` and a session-limit prompt keeps waiting for the person. Thanks @devon-seitz for reporting this in #5075.
|
|
28
|
+
- 084b2bf: When compaction runs partway through a turn, notices the framework sends again, such as the deferred tool catalog notice, now go before the turn's input instead of after the latest tool result, where the model read them as the newest message.
|
|
29
|
+
|
|
30
|
+
Thanks @hrayn3 for reporting this in #5198.
|
|
31
|
+
- c37d279: The connection sign-in page now says "Authorization not completed" instead of "Authorization complete" when the provider redirects back with an OAuth error, such as the person declining consent. Thanks @dretanacr for reporting this in #5105.
|
|
32
|
+
- 4853062: Connection tool calls now fail after 5 minutes without an answer, instead of holding the turn until it is cancelled. eve cancels the request and returns a tool error the agent can report, so a tool that takes longer than 5 minutes now fails. Thanks @dretanacr for reporting this in #4977.
|
|
33
|
+
- 697741e: Record the input the model sent to an agent tool in eval facts, so a subagent or remote agent call in `turn.toolCalls` no longer shows `input: {}` and `t.calledTool(name, { input })` can match it. Thanks @dretanacr for reporting this in #5063.
|
|
34
|
+
- 6447c36: Evals keep an input request pending after a `respond()` that answers only some of the open requests. `session.pendingInputRequests` still lists the unanswered ones, and `parked()` holds (and `succeeded()` fails) while the run waits on them. Thanks @elrumordelaluz for reporting this in #5157.
|
|
35
|
+
- 3b9ceef: An expired session is no longer reported as failed when writing its final `session.completed` event fails. Before, channels such as Slack posted a `session.failed` error after they had already handled `session.completed`. Thanks @bisak for reporting this in #5261.
|
|
36
|
+
- 3d7eb49: A session stream request that does not report the durable tail no longer looks it up. Default opens and client reconnects now check that the session exists with one run lookup, instead of a tail lookup that on the local world opens every chunk file. Unknown and expired sessions still answer 404 and 410 before the stream starts. Thanks @KingAmo for reporting this in #5016.
|
|
37
|
+
- 7d653ef: MCP connections now fall back to the highest mutually supported legacy protocol version when `server/discover` returns `-32022`. Thanks @zico-io for reporting this in #4406, and @bluepegasus123 for proposing the fallback.
|
|
38
|
+
- 9b24d70: PDFs that store their pages in compressed object streams, as phone scans and `pdf-lib` output usually do, now get a per-page token estimate instead of one based on file size. A multi-megabyte scan no longer requests compaction on the first step of a session. Thanks @DLME2024 for reporting this and suggesting the fix in #5090.
|
|
39
|
+
- 1a735c6: `git({ github })` and the deprecated `code({ github })` register their authenticated `gh` tool at session start again, as do dynamic tools built with `defineGhTool` from `eve/extensions/git/sandbox`. Thanks @seahiLin for reporting this in #4986.
|
|
40
|
+
- 653a257: Slack apps that set `onInputResponse` or `approvalChannel` no longer let a message typed in the thread answer an open question. Before, the typed message answered it without running `onInputResponse`, and the answer was the whole `<slack_message>` envelope. The message now reaches the agent as a new message instead.
|
|
41
|
+
- e14685b: On Vercel Sandbox, aborting a `sandbox.run()` or `sandbox.spawn()` command after it starts now kills it, and `run()` rejects instead of waiting, as the `abortSignal` option documents. Before, the command kept running until it exited by itself, including after a turn was cancelled. Thanks @voidhrithik for reporting this in #5301.
|
|
42
|
+
- 64b5d06: Workflow and step modules can now use `?raw` and other relative asset imports. Before, `eve build` failed with `UNLOADABLE_DEPENDENCY` when a module reachable from a workflow imported a file this way, even though the same import worked in a tool. Thanks @gmstevenson for reporting this in #5269.
|
|
43
|
+
|
|
3
44
|
## 0.83.1
|
|
4
45
|
|
|
5
46
|
### Patch Changes
|
|
@@ -577,8 +577,9 @@ export interface Runtime {
|
|
|
577
577
|
* parameter unchanged.
|
|
578
578
|
*
|
|
579
579
|
* A following read throws `SessionStrandedError` when the session's owner
|
|
580
|
-
* cannot execute here
|
|
581
|
-
* or
|
|
580
|
+
* cannot execute here, and rejects before returning when the session does
|
|
581
|
+
* not exist or its history has expired. A historical read (`follow: false`)
|
|
582
|
+
* never inspects or changes the session's lifecycle.
|
|
582
583
|
*/
|
|
583
584
|
getEventStream(sessionId: string, options?: GetEventStreamOptions): Promise<ReadableStream<MessageStreamEvent>>;
|
|
584
585
|
/**
|
|
@@ -3019,16 +3019,12 @@ var OptimisticMessageSubmissions = class {
|
|
|
3019
3019
|
return this.submit(input, pending?.eventStartIndex ?? 0, pending?.turnId);
|
|
3020
3020
|
}
|
|
3021
3021
|
apply(event) {
|
|
3022
|
-
|
|
3022
|
+
const settling = this.#settling(event);
|
|
3023
|
+
if (settling.length === 0) {
|
|
3023
3024
|
for (const projection of this.#projections) projection.append(event);
|
|
3024
3025
|
return;
|
|
3025
3026
|
}
|
|
3026
|
-
|
|
3027
|
-
if (matching.length === 0) {
|
|
3028
|
-
for (const projection of this.#projections) projection.append(event);
|
|
3029
|
-
return;
|
|
3030
|
-
}
|
|
3031
|
-
return this.#reconcile(matching, event, false);
|
|
3027
|
+
return this.#settle(settling, event, false);
|
|
3032
3028
|
}
|
|
3033
3029
|
correlate(submissionId, deliveryId, events) {
|
|
3034
3030
|
if (submissionId === void 0) return void 0;
|
|
@@ -3040,9 +3036,8 @@ var OptimisticMessageSubmissions = class {
|
|
|
3040
3036
|
const pending = this.#pending.find((candidate) => candidate.id === submissionId);
|
|
3041
3037
|
if (pending === void 0) return void 0;
|
|
3042
3038
|
for (const event of events.slice(pending.eventStartIndex)) {
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
if (matching.some((candidate) => candidate.id === submissionId)) return this.#reconcile(matching, event, true);
|
|
3039
|
+
const settling = this.#settling(event);
|
|
3040
|
+
if (settling.some((candidate) => candidate.id === submissionId)) return this.#settle(settling, event, true);
|
|
3046
3041
|
}
|
|
3047
3042
|
}
|
|
3048
3043
|
fail(error, submissionId) {
|
|
@@ -3063,12 +3058,22 @@ var OptimisticMessageSubmissions = class {
|
|
|
3063
3058
|
failAll(error) {
|
|
3064
3059
|
for (const pending of this.#pending) this.fail(error, pending.id);
|
|
3065
3060
|
}
|
|
3061
|
+
#settling(event) {
|
|
3062
|
+
if (event.type === "message.received") return this.#matching(event);
|
|
3063
|
+
if (event.type !== "turn.cancelled" && event.type !== "turn.failed") return [];
|
|
3064
|
+
const named = event.meta.deliveryIds ?? [];
|
|
3065
|
+
return this.#pending.filter((pending) => pending.deliveryId !== void 0 && named.includes(pending.deliveryId));
|
|
3066
|
+
}
|
|
3066
3067
|
#matching(event) {
|
|
3067
3068
|
return this.#pending.filter((pending) => pending.deliveryId === void 0 ? !pending.requiresDeliveryId : event.meta.deliveryIds?.includes(pending.deliveryId) === true);
|
|
3068
3069
|
}
|
|
3069
|
-
#
|
|
3070
|
+
#settle(submissions, event, alreadyProjected) {
|
|
3070
3071
|
const ids = submissions.map((pending) => pending.id);
|
|
3071
|
-
this.#withdraw(ids);
|
|
3072
|
+
if (event.type === "message.received") this.#withdraw(ids);
|
|
3073
|
+
else {
|
|
3074
|
+
const error = /* @__PURE__ */ new Error("The turn ended before the agent read the message.");
|
|
3075
|
+
for (const id of ids) this.fail(error, id);
|
|
3076
|
+
}
|
|
3072
3077
|
if (!alreadyProjected) for (const projection of this.#projections) projection.append(event);
|
|
3073
3078
|
return {
|
|
3074
3079
|
alreadyProjected,
|
|
@@ -3018,16 +3018,12 @@ var OptimisticMessageSubmissions = class {
|
|
|
3018
3018
|
return this.submit(input, pending?.eventStartIndex ?? 0, pending?.turnId);
|
|
3019
3019
|
}
|
|
3020
3020
|
apply(event) {
|
|
3021
|
-
|
|
3021
|
+
const settling = this.#settling(event);
|
|
3022
|
+
if (settling.length === 0) {
|
|
3022
3023
|
for (const projection of this.#projections) projection.append(event);
|
|
3023
3024
|
return;
|
|
3024
3025
|
}
|
|
3025
|
-
|
|
3026
|
-
if (matching.length === 0) {
|
|
3027
|
-
for (const projection of this.#projections) projection.append(event);
|
|
3028
|
-
return;
|
|
3029
|
-
}
|
|
3030
|
-
return this.#reconcile(matching, event, false);
|
|
3026
|
+
return this.#settle(settling, event, false);
|
|
3031
3027
|
}
|
|
3032
3028
|
correlate(submissionId, deliveryId, events) {
|
|
3033
3029
|
if (submissionId === void 0) return void 0;
|
|
@@ -3039,9 +3035,8 @@ var OptimisticMessageSubmissions = class {
|
|
|
3039
3035
|
const pending = this.#pending.find((candidate) => candidate.id === submissionId);
|
|
3040
3036
|
if (pending === void 0) return void 0;
|
|
3041
3037
|
for (const event of events.slice(pending.eventStartIndex)) {
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
if (matching.some((candidate) => candidate.id === submissionId)) return this.#reconcile(matching, event, true);
|
|
3038
|
+
const settling = this.#settling(event);
|
|
3039
|
+
if (settling.some((candidate) => candidate.id === submissionId)) return this.#settle(settling, event, true);
|
|
3045
3040
|
}
|
|
3046
3041
|
}
|
|
3047
3042
|
fail(error, submissionId) {
|
|
@@ -3062,12 +3057,22 @@ var OptimisticMessageSubmissions = class {
|
|
|
3062
3057
|
failAll(error) {
|
|
3063
3058
|
for (const pending of this.#pending) this.fail(error, pending.id);
|
|
3064
3059
|
}
|
|
3060
|
+
#settling(event) {
|
|
3061
|
+
if (event.type === "message.received") return this.#matching(event);
|
|
3062
|
+
if (event.type !== "turn.cancelled" && event.type !== "turn.failed") return [];
|
|
3063
|
+
const named = event.meta.deliveryIds ?? [];
|
|
3064
|
+
return this.#pending.filter((pending) => pending.deliveryId !== void 0 && named.includes(pending.deliveryId));
|
|
3065
|
+
}
|
|
3065
3066
|
#matching(event) {
|
|
3066
3067
|
return this.#pending.filter((pending) => pending.deliveryId === void 0 ? !pending.requiresDeliveryId : event.meta.deliveryIds?.includes(pending.deliveryId) === true);
|
|
3067
3068
|
}
|
|
3068
|
-
#
|
|
3069
|
+
#settle(submissions, event, alreadyProjected) {
|
|
3069
3070
|
const ids = submissions.map((pending) => pending.id);
|
|
3070
|
-
this.#withdraw(ids);
|
|
3071
|
+
if (event.type === "message.received") this.#withdraw(ids);
|
|
3072
|
+
else {
|
|
3073
|
+
const error = /* @__PURE__ */ new Error("The turn ended before the agent read the message.");
|
|
3074
|
+
for (const id of ids) this.fail(error, id);
|
|
3075
|
+
}
|
|
3071
3076
|
if (!alreadyProjected) for (const projection of this.#projections) projection.append(event);
|
|
3072
3077
|
return {
|
|
3073
3078
|
alreadyProjected,
|
|
@@ -3,9 +3,8 @@ import type { MessageStreamEvent } from "#protocol/message.js";
|
|
|
3
3
|
import type { SendTurnPayload } from "#client/types.js";
|
|
4
4
|
interface ReconciledSubmissions {
|
|
5
5
|
readonly alreadyProjected: boolean;
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
}>;
|
|
6
|
+
/** The event that settled the submissions: their `message.received`, or their turn's end. */
|
|
7
|
+
readonly event: MessageStreamEvent;
|
|
9
8
|
readonly ids: readonly string[];
|
|
10
9
|
}
|
|
11
10
|
/** Owns optimistic message projection and server-delivery reconciliation. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSubmissionId,summarizeUserContent}from"#client/eve-agent-store-helpers.js";var OptimisticMessageSubmissions=class{#e;#t;#n=[];constructor(e,t){this.#t=e,this.#e=t}reset(){this.#n=[]}submit(e,t,n){if(e.message===void 0)return;let r={createdAt:Date.now(),eventStartIndex:t,id:createSubmissionId(),message:summarizeUserContent(e.message),turnId:n,requiresDeliveryId:!0};if(this.#n=[...this.#n,r],this.#e)for(let e of this.#t)e.append({data:{createdAt:r.createdAt,message:r.message,submissionId:r.id,turnId:n},type:`client.message.submitted`});return r.id}resubmit(e,t){let n=this.#n.find(t=>t.id===e),r=t.message===void 0?void 0:summarizeUserContent(t.message);return n?.message===r?e:(n!==void 0&&this.#
|
|
1
|
+
import{createSubmissionId,summarizeUserContent}from"#client/eve-agent-store-helpers.js";var OptimisticMessageSubmissions=class{#e;#t;#n=[];constructor(e,t){this.#t=e,this.#e=t}reset(){this.#n=[]}submit(e,t,n){if(e.message===void 0)return;let r={createdAt:Date.now(),eventStartIndex:t,id:createSubmissionId(),message:summarizeUserContent(e.message),turnId:n,requiresDeliveryId:!0};if(this.#n=[...this.#n,r],this.#e)for(let e of this.#t)e.append({data:{createdAt:r.createdAt,message:r.message,submissionId:r.id,turnId:n},type:`client.message.submitted`});return r.id}resubmit(e,t){let n=this.#n.find(t=>t.id===e),r=t.message===void 0?void 0:summarizeUserContent(t.message);return n?.message===r?e:(n!==void 0&&this.#o([n.id]),this.submit(t,n?.eventStartIndex??0,n?.turnId))}apply(e){let t=this.#r(e);if(t.length===0){for(let t of this.#t)t.append(e);return}return this.#a(t,e,!1)}correlate(e,t,n){if(e===void 0)return;this.#n=this.#n.map(n=>n.id===e?{...n,deliveryId:t,requiresDeliveryId:t!==void 0}:n);let r=this.#n.find(t=>t.id===e);if(r!==void 0)for(let t of n.slice(r.eventStartIndex)){let n=this.#r(t);if(n.some(t=>t.id===e))return this.#a(n,t,!0)}}fail(e,t){let n=t===void 0?this.#n[0]:this.#n.find(e=>e.id===t);if(n!==void 0){this.#n=this.#n.filter(e=>e.id!==n.id);for(let t of this.#t)t.replace(e=>e.type===`client.message.submitted`&&e.data.submissionId===n.id,{data:{createdAt:n.createdAt,error:{message:e.message},message:n.message,submissionId:n.id,turnId:n.turnId},type:`client.message.failed`})}}failAll(e){for(let t of this.#n)this.fail(e,t.id)}#r(e){if(e.type===`message.received`)return this.#i(e);if(e.type!==`turn.cancelled`&&e.type!==`turn.failed`)return[];let t=e.meta.deliveryIds??[];return this.#n.filter(e=>e.deliveryId!==void 0&&t.includes(e.deliveryId))}#i(e){return this.#n.filter(t=>t.deliveryId===void 0?!t.requiresDeliveryId:e.meta.deliveryIds?.includes(t.deliveryId)===!0)}#a(e,t,n){let r=e.map(e=>e.id);if(t.type===`message.received`)this.#o(r);else{let e=Error(`The turn ended before the agent read the message.`);for(let t of r)this.fail(e,t)}if(!n)for(let e of this.#t)e.append(t);return{alreadyProjected:n,event:t,ids:r}}#o(e){let t=new Set(e);this.#n=this.#n.filter(e=>!t.has(e.id));for(let e of this.#t)e.remove(e=>e.type===`client.message.submitted`&&t.has(e.data.submissionId))}};export{OptimisticMessageSubmissions};
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"zod": "4.5.4",
|
|
62
62
|
"zod-validation-error": "5.0.0"
|
|
63
63
|
},
|
|
64
|
-
"scriptHash": "
|
|
64
|
+
"scriptHash": "ca0d1cac1d58bfe2accdeb13ad8bc14b51bd709a890983fbd3c4e53ed7309faf",
|
|
65
65
|
"toolVersions": {
|
|
66
66
|
"rolldown": "1.2.9",
|
|
67
67
|
"typescript": "7.0.2"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{I as n,K as r,M as i,N as a,St as o,Tt as s,U as c,c as l,dt as u,ft as d,gt as f,i as p,j as m,p as h,tt as g,ut as _,yt as v}from"../../_chunks/workflow/dist-C8k3N3BQ.js";import*as y from"#compiled/zod/index.js";import{z as b}from"#compiled/zod/index.js";let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function S(e){return(await x).getRandomValues(new Uint8Array(e))}async function C(e){let t=``;for(;t.length<e;){let n=await S(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function w(e){return await C(e)}async function ee(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function te(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await w(e);return{code_verifier:t,code_challenge:await ee(t)}}const T=`2026-07-28`,E=`2025-11-25`,ne=[T,E,`2025-06-18`,`2025-03-26`,`2024-11-05`],re=b.optional(b.record(b.string(),b.unknown())),ie=b.looseObject({name:b.string(),version:b.string(),title:b.optional(b.string())}),D=b.looseObject({_meta:b.optional(b.object({}).loose())}),O=D.extend({resultType:b.optional(b.string())}),ae=b.object({method:b.string(),params:b.optional(D)}),oe=b.object({applyDefaults:b.optional(b.boolean())}).loose(),se=b.looseObject({events:b.looseObject({listChanged:b.boolean().nullish()}).nullish(),experimental:b.optional(b.object({}).loose()),logging:b.optional(b.object({}).loose()),completions:b.optional(b.object({}).loose()),prompts:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),resources:b.optional(b.looseObject({subscribe:b.optional(b.boolean()),listChanged:b.optional(b.boolean())})),tools:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),elicitation:b.optional(oe)});b.object({elicitation:b.optional(oe)}).loose();const ce=O.extend({supportedVersions:b.array(b.string()),capabilities:se,instructions:b.optional(b.string()),ttlMs:b.optional(b.number()),cacheScope:b.optional(b.union([b.literal(`public`),b.literal(`private`)]))}),le=O.extend({protocolVersion:b.string(),capabilities:se,serverInfo:ie,instructions:b.optional(b.string())}),k=O.extend({nextCursor:b.optional(b.string())}),ue=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),inputSchema:b.looseObject({type:b.optional(b.unknown()),properties:b.optional(b.object({}).loose())}),outputSchema:b.optional(b.object({}).loose()),annotations:b.optional(b.object({title:b.optional(b.string()),readOnlyHint:b.optional(b.boolean()),destructiveHint:b.optional(b.boolean()),idempotentHint:b.optional(b.boolean()),openWorldHint:b.optional(b.boolean())}).loose()),_meta:re}).loose(),de=k.extend({tools:b.array(ue)}),fe=b.object({type:b.literal(`text`),text:b.string()}).loose(),pe=b.object({type:b.literal(`image`),data:b.base64(),mimeType:b.string()}).loose(),me=b.object({uri:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string()),size:b.optional(b.number())}).loose(),he=k.extend({resources:b.array(me)}),ge=b.object({uri:b.string(),name:b.optional(b.string()),title:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),_e=ge.extend({text:b.string()}),ve=ge.extend({blob:b.base64()}),ye=b.object({type:b.literal(`resource`),resource:b.union([_e,ve])}).loose(),be=b.object({type:b.literal(`resource_link`),uri:b.string(),name:b.string(),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),xe=b.object({type:b.string()}).loose().refine(e=>![`text`,`image`,`resource`,`resource_link`].includes(e.type),{message:`Known content types must match their schema`}),Se=O.extend({content:b.array(b.union([fe,pe,ye,be,xe])),structuredContent:b.optional(b.unknown()),isError:b.boolean().default(!1).optional()}),Ce=O.extend({content:b.never().optional(),structuredContent:b.json(),isError:b.boolean().default(!1).optional()}).transform(e=>({...e,content:[{type:`text`,text:JSON.stringify(e.structuredContent)}]})).pipe(Se),we=Se.or(Ce).or(O.extend({toolResult:b.unknown().nonoptional()})),Te=b.object({uriTemplate:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),Ee=O.extend({resourceTemplates:b.array(Te)}),De=O.extend({contents:b.array(b.union([_e,ve]))}),Oe=b.object({type:b.literal(`ref/prompt`),name:b.string()}).loose(),ke=b.object({type:b.literal(`ref/resource`),uri:b.string()}).loose(),Ae=b.object({name:b.string(),value:b.string()}).loose();D.extend({ref:b.union([Oe,ke]),argument:Ae,context:b.optional(b.object({arguments:b.record(b.string(),b.string())}).loose())});const je=O.extend({completion:b.object({values:b.array(b.string()).max(100),total:b.optional(b.number().int()),hasMore:b.optional(b.boolean())}).loose()}),Me=b.object({name:b.string(),description:b.optional(b.string()),required:b.optional(b.boolean())}).loose(),Ne=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),arguments:b.optional(b.array(Me))}).loose(),Pe=k.extend({prompts:b.array(Ne)}),Fe=b.object({role:b.union([b.literal(`user`),b.literal(`assistant`)]),content:b.union([fe,pe,ye,be])}).loose(),Ie=O.extend({description:b.optional(b.string()),messages:b.array(Fe)}),Le=D.extend({message:b.string(),requestedSchema:b.unknown()}),A=ae.extend({method:b.literal(`elicitation/create`),params:Le}),Re=O.extend({action:b.union([b.literal(`accept`),b.literal(`decline`),b.literal(`cancel`)]),content:b.optional(b.record(b.string(),b.unknown()))}),ze=b.object({jsonrpc:b.literal(`2.0`),id:b.union([b.string(),b.number().int()])}).merge(ae).strict(),Be=b.object({jsonrpc:b.literal(`2.0`),id:b.union([b.string(),b.number().int()]),result:O}).strict(),Ve=b.object({jsonrpc:b.literal(`2.0`),id:b.optional(b.union([b.string(),b.number().int()])),error:b.object({code:b.number().int(),message:b.string(),data:b.optional(b.unknown())})}).strict(),He=b.object({jsonrpc:b.literal(`2.0`)}).merge(b.object({method:b.string(),params:b.optional(D)})).strict(),Ue=b.union([ze,He,Be,Ve]);function j(e){return Ue.parse(e)}async function M(e){return j(await g({text:e}))}const We=`vercel.ai.error.AI_MCPClientError`,Ge=Symbol.for(We);var N=class extends e{constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[Ge]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,We)}};function Ke(){return`whsec_${h(crypto.getRandomValues(new Uint8Array(32)))}`}function qe(e){let t=e.slice(6);if(!e.startsWith(`whsec_`)||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new N({message:`Invalid MCP event signing secret`});let n=l(t);if(n.length<24||n.length>64)throw new N({message:`MCP event signing secrets must contain 24–64 random bytes`});return n}async function Je({headers:e,body:t,secret:n}){let r=e.get(`webhook-id`),i=e.get(`webhook-timestamp`),a=e.get(`webhook-signature`);if(!r||!i||!a||!/^\d+$/.test(i)||Math.abs(Date.now()/1e3-Number(i))>300)return!1;let o=await crypto.subtle.importKey(`raw`,new Uint8Array(qe(n)),{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]),s=new TextEncoder().encode(`${r}.${i}.`),c=new Uint8Array(s.length+t.length);c.set(s),c.set(t,s.length);for(let e of a.split(` `)){let[t,n]=e.split(`,`);if(t===`v1`&&n)try{if(await crypto.subtle.verify(`HMAC`,o,new Uint8Array(l(n)),c))return!0}catch{}}return!1}const Ye=b.union([b.boolean(),b.record(b.string(),b.unknown())]),Xe=b.looseObject({name:b.string().min(1),description:b.string().nullish(),delivery:b.array(b.enum([`webhook`,`poll`,`push`])).min(1),inputSchema:Ye,payloadSchema:Ye}),Ze=O.extend({events:b.array(Xe),nextCursor:b.string().nullish()}),Qe=O.extend({id:b.string().min(1),refreshBefore:b.iso.datetime({offset:!0}).nullable(),cursor:b.string().nullish().transform(e=>e??null),truncated:b.boolean()}),$e=b.looseObject({eventId:b.string().min(1),name:b.string().min(1),timestamp:b.iso.datetime({offset:!0}),data:b.record(b.string(),b.unknown()),cursor:b.string().nullish()}),et=b.discriminatedUnion(`type`,[b.looseObject({type:b.literal(`gap`),cursor:b.string()}),b.looseObject({type:b.literal(`terminated`),error:b.looseObject({code:b.number().int(),message:b.string(),data:b.unknown().nullish()})})]).transform(e=>e.type===`gap`?{...e,truncated:!0}:e),tt=`mcp_event_subscription`;function nt({request:e,store:t,validateArguments:n}){function r(){if(!t)throw new N({message:`Configure experimental_events.store to manage direct event subscriptions`});return t}async function i({id:e,key:t}){let n=r(),i=e===void 0?await n.get(t):await n.getById(e);if(!i)throw new N({message:`Unknown MCP event subscription: ${e??t}`});return i}async function a(t,n){let i=await e({request:{method:`events/subscribe`,params:{name:t.name,arguments:t.arguments,delivery:t.delivery,cursor:t.cursor,...t.ttlMs===void 0?{}:{ttlMs:t.ttlMs},...t.maxAgeMs===void 0?{}:{maxAgeMs:t.maxAgeMs}}},resultSchema:Qe,options:n});return await r().update(t.key,{id:i.id,refreshBefore:i.refreshBefore,cursor:i.cursor,truncated:i.truncated,status:`active`}),i}let o={list({params:t,options:n}={}){return e({request:{method:`events/list`,params:t},resultSchema:Ze,options:n})},async subscribe({name:e,arguments:t={},delivery:i,cursor:s=null,ttlMs:c,maxAgeMs:l,options:u}){let d=r(),f=new URL(i.url),p=i.allowInsecureLocalhost===!0&&f.protocol===`http:`&&(f.hostname===`127.0.0.1`||f.hostname===`[::1]`);if(f.protocol!==`https:`&&!p||f.username||f.password||f.hash)throw new N({message:`MCP event callback URLs must use HTTPS without credentials or fragments`});if(i.mode!==`webhook`)throw new N({message:`Only webhook event delivery is supported`});if(c!=null&&(!Number.isSafeInteger(c)||c<=0)||l!=null&&(!Number.isSafeInteger(l)||l<0))throw new N({message:`Invalid MCP event subscription lifetime or replay age`});let m,h=new Set,g;do{let t=await o.list({params:{cursor:m},options:u});if(g=t.events.find(t=>t.name===e),g)break;if(m=t.nextCursor??void 0,m!=null){if(h.has(m))throw new N({message:`Repeated MCP events pagination cursor`});h.add(m)}}while(m!=null);if(!g)throw new N({message:`Unknown MCP event: ${e}`});if(!g.delivery.includes(`webhook`))throw new N({message:`MCP event ${e} does not support webhook delivery`});await n?.({definition:g,arguments:t});let _=i.secret??Ke();qe(_);let v=crypto.randomUUID();f.searchParams.set(tt,v);let y={key:v,name:e,arguments:structuredClone(t),definition:g,delivery:{mode:`webhook`,url:f.href,secret:_},cursor:s,truncated:!1,ttlMs:c,maxAgeMs:l,status:`pending`};return await d.set(y),a(y,u)},async refresh(e){let t=await i(e);return await r().update(t.key,{status:`pending`}),a(t,e.options)},async unsubscribe(t){let n=await i(t);await e({request:{method:`events/unsubscribe`,params:{name:n.name,arguments:n.arguments,delivery:{mode:`webhook`,url:n.delivery.url}}},resultSchema:O,options:t.options}),await r().delete(n.key)}};return o}function rt(e){if(e!=null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`)throw Promise.resolve(e).catch(()=>{}),new N({message:`experimental_events.adapter.createAdapter() must return operations synchronously. Promise and thenable results are not supported.`});if(typeof e!=`object`||!e||!(`subscribe`in e)||typeof e.subscribe!=`function`||!(`getSubscription`in e)||typeof e.getSubscription!=`function`||!(`listSubscriptions`in e)||typeof e.listSubscriptions!=`function`||!(`unsubscribe`in e)||typeof e.unsubscribe!=`function`)throw new N({message:`experimental_events.adapter.createAdapter() must return an object implementing subscribe, getSubscription, listSubscriptions, and unsubscribe.`})}function it(e,t){return{list:t,subscribe:t=>e.subscribe(t),getSubscription:t=>e.getSubscription(t),listSubscriptions:t=>e.listSubscriptions(t),unsubscribe:t=>e.unsubscribe(t)}}const at=`2.0.73`,P=b.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:b.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),b.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),ot=b.object({access_token:b.string(),id_token:b.string().optional(),token_type:b.string(),expires_in:b.number().optional(),scope:b.string().optional(),refresh_token:b.string().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),st=b.looseObject({resource:b.string().url(),authorization_servers:b.array(P).optional(),jwks_uri:b.string().url().optional(),scopes_supported:b.array(b.string()).optional(),bearer_methods_supported:b.array(b.string()).optional(),resource_signing_alg_values_supported:b.array(b.string()).optional(),resource_name:b.string().optional(),resource_documentation:b.string().optional(),resource_policy_uri:b.string().url().optional(),resource_tos_uri:b.string().url().optional(),tls_client_certificate_bound_access_tokens:b.boolean().optional(),authorization_details_types_supported:b.array(b.string()).optional(),dpop_signing_alg_values_supported:b.array(b.string()).optional(),dpop_bound_access_tokens_required:b.boolean().optional()}),ct=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),code_challenge_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_signing_alg_values_supported:b.array(b.string()).optional()}),lt=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,userinfo_endpoint:P.optional(),jwks_uri:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),subject_types_supported:b.array(b.string()),id_token_signing_alg_values_supported:b.array(b.string()),claims_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional()}).merge(ct.pick({code_challenge_methods_supported:!0})),ut=b.object({client_id:b.string(),client_secret:b.string().optional(),client_id_issued_at:b.number().optional(),client_secret_expires_at:b.number().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),dt=b.object({redirect_uris:b.array(P),application_type:b.union([b.literal(`native`),b.literal(`web`)]).optional(),token_endpoint_auth_method:b.string().optional(),grant_types:b.array(b.string()).optional(),response_types:b.array(b.string()).optional(),client_name:b.string().optional(),client_uri:P.optional(),logo_uri:P.optional(),scope:b.string().optional(),contacts:b.array(b.string()).optional(),tos_uri:P.optional(),policy_uri:b.string().optional(),jwks_uri:P.optional(),jwks:b.any().optional(),software_id:b.string().optional(),software_version:b.string().optional(),software_statement:b.string().optional()}).strip(),ft=b.object({error:b.string(),error_description:b.string().optional(),error_uri:b.string().optional()}),pt=dt.merge(ut),mt=`vercel.ai.error.AI_MCPClientOAuthError`,ht=Symbol.for(mt);var F=class extends e{constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[ht]=!0}static isInstance(t){return e.hasMarker(t,mt)}},I=class extends F{static{this.errorCode=`server_error`}},L=class extends F{static{this.errorCode=`invalid_client`}},R=class extends F{static{this.errorCode=`invalid_grant`}},z=class extends F{static{this.errorCode=`unauthorized_client`}};const gt=`vercel.ai.error.AI_AuthorizationServerMismatchError`,_t=Symbol.for(gt);var vt=class extends F{static{this.errorCode=`authorization_server_mismatch`}constructor({message:e,cause:t}){super({name:`AuthorizationServerMismatchError`,message:e,cause:t}),this[_t]=!0}static isInstance(t){return e.hasMarker(t,gt)}};const yt={[I.errorCode]:I,[L.errorCode]:L,[R.errorCode]:R,[z.errorCode]:z};function bt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function B(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function xt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var V=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function H(e){return new URL(e).href}function U(e){let t=e.toLowerCase().replace(/\.+$/,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function W(e,{allowLoopback:t=!1}={}){if(!t||e.protocol!==`http:`&&e.protocol!==`https:`||!U(e.hostname))try{v(e.href)}catch(t){throw new F({message:`OAuth endpoint URL is not allowed: ${e.href}`,cause:t})}}function G(e){let t=new URL(e);return U(t.hostname)?t.origin:void 0}function St({callbackIssuer:e,expectedIssuer:t}){if(e!=null&&e!==t)throw new F({message:`OAuth authorization response issuer ${e} does not match expected issuer ${t}`})}function Ct(e,t){return{issuer:t?.issuer??String(e),authorizationServerUrl:H(e),tokenEndpoint:H(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function wt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Tt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Et(e){if(e?.authorization_server&&e.token_endpoint)return{issuer:e.issuer,authorizationServerUrl:H(e.authorization_server),tokenEndpoint:H(e.token_endpoint)}}async function K({provider:e,clientInformation:t,tokens:n}){let r=Et(n);if(r)return r;let i=await e.authorizationServerInformation?.();return i?{issuer:i.issuer,authorizationServerUrl:H(i.authorizationServerUrl),tokenEndpoint:H(i.tokenEndpoint)}:Et(t)}async function Dt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(Tt(t,n)),!0):!1}function Ot(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new F({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function q({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.issuer!=null&&t.issuer!=null&&e.issuer!==t.issuer||e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new vt({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function J(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=t.match(/(?:^|[,\s])resource_metadata="([^"]*)"/i),a=t.match(/(?:^|[,\s])scope="([^"]*)"/i)?.[1],o;try{o=i?new URL(i[1]):void 0}catch{}return{resourceMetadataUrl:o,scope:a}}function kt({scope:e,resourceMetadata:t,clientMetadata:n}){return e||t?.scopes_supported?.join(` `)||n.scope}function At(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Y(e,t,n=fetch,r){try{return await i({url:e.href,fetch:async(e,i)=>a({url:e,init:{...i,headers:new Headers(i?.headers).has(`MCP-Protocol-Version`)?t:void 0},fetch:n,trustedOrigin:r,redirect:`manual`}),headers:t,trustedOrigin:r,untrustedFirstHopHeaders:[`mcp-protocol-version`]})}catch(i){if(i instanceof TypeError)return t?Y(e,void 0,n,r):void 0;throw i}}async function jt(e,t,n=fetch,r){return await Y(e,{"MCP-Protocol-Version":t},n,r)}function Mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Nt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2026-07-28`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=At(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await jt(o,a,n,r?.trustedOrigin);return!r?.metadataUrl&&Mt(s,i.pathname)&&(s=await jt(new URL(`/.well-known/${t}`,i),a,n,r?.trustedOrigin)),s}async function Pt(e,t,n=fetch){let r=await Nt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl,trustedOrigin:new URL(e).origin});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return st.parse(await r.json())}function Ft(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o});let s=new URL(t.origin);return s.pathname=`${a}/.well-known/openid-configuration`,i.push({url:s,type:`oidc`,expectedIssuer:o}),i}function It(e,t){if(!(e.issuer===t||t===new URL(t).origin&&e.issuer===`${t}/`))throw new F({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Lt(e,{fetchFn:t=fetch,protocolVersion:n=T,trustedOrigin:r}={}){let i={"MCP-Protocol-Version":n},a=new URL(e).origin,o=Ft(e);if(o.some(({url:e})=>e.origin!==a))throw new F({message:`OAuth discovery URL changed authorization-server origin`});for(let{url:e,type:n,expectedIssuer:a}of o){let o=await Y(e,i,t,r);if(o){if(!o.ok){if(o.status>=400&&o.status<500)continue;throw Error(`HTTP ${o.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=ct.parse(await o.json());return It(e,a),e}{let t=lt.parse(await o.json());if(It(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Rt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await te(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,B(o)),{authorizationUrl:l,codeVerifier:d}}function zt(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Bt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Vt(i,a,n);return;case`client_secret_post`:Ht(i,a,r);return;case`none`:Ut(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Vt(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Ht(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Ut(e,t){t.set(`client_id`,e)}async function X(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ft.parse(await g({text:n}));return new(yt[e]||I)({message:t||``,cause:r})}catch(e){return new I({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Wt(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:c,fetchFn:l}){let u=`authorization_code`,d=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),f=G(e);if(W(d,{allowLoopback:d.origin===f}),t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),m=new URLSearchParams({grant_type:u,code:r,code_verifier:i,redirect_uri:String(o)});c?await c(p,m,e,t):Bt(zt(n,t?.token_endpoint_auth_methods_supported??[]),n,p,m),s&&m.set(`resource`,B(s));let h=await a({url:d,init:{method:`POST`,headers:p,body:m},fetch:l,trustedOrigin:f});if(!h.ok)throw await X(h);return ot.parse(await h.json())}async function Gt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:o,fetchFn:s}){let c=`refresh_token`,l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL(`/token`,e);let u=G(e);W(l,{allowLoopback:l.origin===u});let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:c,refresh_token:r});o?await o(d,f,e,t):Bt(zt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),i&&f.set(`resource`,B(i));let p=await a({url:l,init:{method:`POST`,headers:d,body:f},fetch:s,trustedOrigin:u});if(!p.ok)throw await X(p);return ot.parse({refresh_token:r,...await p.json()})}async function Kt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let o=G(e);W(i,{allowLoopback:i.origin===o});let s=n.application_type??qt(n.redirect_uris),c=await a({url:i,init:{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,application_type:s})},fetch:r,trustedOrigin:o});if(!c.ok)throw await X(c);return pt.parse(await c.json())}function qt(e){return e.every(e=>{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&U(t.hostname)||t.protocol!==`http:`&&t.protocol!==`https:`})?`native`:`web`}async function Z(e,t){let n={};try{return await Yt(e,t,n)}catch(r){if(r instanceof L||r instanceof z){if(t.authorizationCode!==void 0||!await e.isClientInformationDynamicallyRegistered?.())throw r;return await e.invalidateCredentials?.(`all`),await Yt(e,t)}if(r instanceof R&&n.tokens)return await e.invalidateCredentials?.(`tokens`,{tokens:n.tokens}),await Yt(e,t);throw r}}async function Jt(e,t,n){let r=bt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!xt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Yt(e,{serverUrl:t,authorizationCode:n,callbackState:r,callbackIssuer:i,scope:a,resourceMetadataUrl:o,fetchFn:s},c){let l,u,d,f;Ot(t,o);try{l=await Pt(t,{resourceMetadataUrl:o},s),l.authorization_servers&&l.authorization_servers.length>0&&(u=l.authorization_servers[0])}catch{}n!==void 0&&(d=await Promise.resolve(e.clientInformation()),d&&(f=await K({provider:e,clientInformation:d}))),u||=f?.authorizationServerUrl??t;let p=new URL(t),m=new URL(u),h=p.origin,g=m.origin,_=g===h||U(p.hostname)&&U(m.hostname)?g:void 0;_||W(new URL(u));let v=await Jt(t,e,l);await e.validateAuthorizationServerURL?.(t,u);let y=await Lt(u,{fetchFn:s,trustedOrigin:_}),b=Ct(u,y),x=e.clientMetadata,S=kt({scope:a,resourceMetadata:l,clientMetadata:x});if(n===void 0&&(d=await Promise.resolve(e.clientInformation())),d?.issuer!=null){let t=f??await K({provider:e,clientInformation:d});t&&q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b})}if(!d){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);d=Tt(await Kt(u,{metadata:y,clientMetadata:{...x,scope:S},fetchFn:s}),b),await e.saveClientInformation(d)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=f??await K({provider:e,clientInformation:d});if(!t)throw new F({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});St({callbackIssuer:i,expectedIssuer:t.issuer??y?.issuer??String(u)}),q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b});let a=await e.codeVerifier(),o=await Wt(u,{metadata:y,clientInformation:d,authorizationCode:n,codeVerifier:a,redirectUri:e.redirectUrl,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(wt(o,b)),`AUTHORIZED`}let C=await e.tokens();if(C?.refresh_token){let t=await K({provider:e,clientInformation:d,tokens:C});t?q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b}):await e.invalidateCredentials?.(`tokens`,{tokens:{...C}});try{if(t){c&&(c.tokens={...C});let t=await Gt(u,{metadata:y,clientInformation:d,refreshToken:C.refresh_token,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(wt(t,b)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof F)||e instanceof I))throw e}}let w=e.state?await e.state():void 0;w&&e.saveState&&await e.saveState(w);let{authorizationUrl:ee,codeVerifier:te}=await Rt(u,{metadata:y,clientInformation:d,state:w,redirectUrl:e.redirectUrl,scope:S,resource:v});if(!await Dt({provider:e,clientInformation:d,authorizationServerInformation:b}))throw new F({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(te),await e.redirectToAuthorization(ee),`REDIRECT`}function Xt(e){return e===void 0||e===`message`}var Zt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??`2025-11-25`};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return o(t,`ai-sdk/${at}`,n())}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async accessTokenChanged(e){let t=(await this.authProvider?.tokens())?.access_token;return t!=null&&e!==`Bearer ${t}`}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{try{let i=await this.commonHeaders({Accept:`text/event-stream`}),a=await this.fetchFn(this.url.href,{headers:i,signal:this.abortController?.signal,redirect:this.redirectMode});if(a.status===401&&this.authProvider&&!r){let{resourceMetadataUrl:e,scope:r}=J(a);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,r)!==`AUTHORIZED`){let e=new V;return this.onerror?.(e),t(e)}}catch(e){return this.onerror?.(e),t(e)}return n(!0)}if(!a.ok||!a.body){let e=`MCP SSE Transport Error: ${a.status} ${a.statusText}`;a.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new N({message:e});return this.onerror?.(n),t(n)}let o=a.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader(),c=async()=>{try{for(;;){let{done:t,value:n}=await o.read();if(t){if(this.abortController?.signal.aborted)return;throw this.connected?(this.connected=!1,new N({message:`MCP SSE Transport Error: Connection closed unexpectedly`})):new N({message:`MCP SSE Transport Error: Connection closed before endpoint event was received`})}let{event:r,data:i}=n;if(r===`endpoint`){if(this.endpoint)continue;let t=new URL(i,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,this.sseConnection?.close(),this.abortController?.abort(),new N({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Xt(r))try{let e=await M(i);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),t(e)}};this.sseConnection={close:()=>o.cancel()},c()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),t(e)}};n()})}async close(){this.connected=!1,this.endpoint=void 0,this.sseConnection?.close(),this.abortController?.abort(),this.onclose?.()}async send(e,t){if(t?.signal?.throwIfAborted(),!this.endpoint||!this.connected)throw new N({message:`MCP SSE Transport Error: Not connected`});let n=this.endpoint,r=this.abortController?.signal,i=t?.signal==null?r:r==null?t.signal:AbortSignal.any([r,t.signal]),a=async(r=!1)=>{try{let t=await this.commonHeaders({"Content-Type":`application/json`}),o={method:`POST`,headers:t,body:JSON.stringify(e),signal:i,redirect:this.redirectMode},s=await this.fetchFn(n.href,o);if(s.status===401&&this.authProvider&&!r){if(await this.accessTokenChanged(new Headers(t).get(`authorization`)??void 0))return a(!0);let{resourceMetadataUrl:e,scope:n}=J(s);if(this.resourceMetadataUrl=e,await this.authorizeOnce(this.resourceMetadataUrl,n)!==`AUTHORIZED`)throw new V;return a(!0)}if(!s.ok){let e=await s.text().catch(()=>null);throw new N({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${s.status}): ${e}`,statusCode:s.status,url:n.href,responseBody:e??void 0})}}catch(e){throw t?.signal?.aborted||this.onerror?.(e),e}};await a()}};const Qt=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,$t=/^=\?base64\?.*\?=$/;function en(e){return[...e].every(e=>{let t=e.charCodeAt(0);return t===9||t>=32&&t<=126})&&e.trim()===e&&!$t.test(e)?e:`=?base64?${h(new TextEncoder().encode(e))}?=`}function tn(e){if(!c(e))return{success:!1,error:`inputSchema must be a JSON Schema object`};let t=[],n=new Set,r,i=(e,a,o)=>{if(r==null&&c(e)){if(`x-mcp-header`in e){if(!o||a.length===0){r=`x-mcp-header is not on a statically reachable property`;return}let i=e[`x-mcp-header`];if(typeof i!=`string`||!Qt.test(i)){r=`x-mcp-header must be a non-empty HTTP token`;return}let s=i.toLowerCase();if(n.has(s)){r=`x-mcp-header value "${i}" is not unique`;return}let c=e.type;if(c!==`boolean`&&c!==`integer`&&c!==`string`){r=`x-mcp-header can only annotate boolean, integer, or string properties`;return}n.add(s),t.push({headerName:i,path:a,valueType:c})}for(let[t,n]of Object.entries(e))if(t!==`x-mcp-header`){if(t===`properties`&&c(n))for(let[e,t]of Object.entries(n))i(t,[...a,e],o);else i(n,a,!1)}}};return i(e,[],!0),r==null?{success:!0,bindings:t}:{success:!1,error:r}}function nn(e,t){let n=e;for(let e of t){if(!c(n))return;n=n[e]}return n}function rn({bindings:e,args:t}){let n={};for(let r of e){let e=nn(t,r.path);if(e!=null){if(r.valueType===`string`&&typeof e!=`string`||r.valueType===`boolean`&&typeof e!=`boolean`||r.valueType===`integer`&&!Number.isSafeInteger(e))throw TypeError(`Tool argument "${r.path.join(`.`)}" does not match its x-mcp-header type`);n[`Mcp-Param-${r.headerName}`]=en(String(e))}}return n}function an(e){return e===void 0||e===`message`}var on=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.supportsProtocolVersionDiscovery=!0,this.supportsMcpToolParameterHeaders=!0,this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a??`2025-11-25`,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){if(this.protocolVersion=e,this.abortController){if(this.isModernProtocol()){this.inboundSseConnection?.close(),this.inboundSseConnection=void 0;return}this.sessionId&&this.startInboundSse()}}isModernProtocol(){return(this.protocolVersion??`2026-07-28`)===T}async commonHeaders({base:e,includeSessionId:t=!0}){let r={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??`2025-11-25`};if(!this.isModernProtocol()&&t&&this.sessionId&&(r[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(r.Authorization=`Bearer ${e.access_token}`)}return o(r,`ai-sdk/${at}`,n())}setSessionId(e){this.sessionId!==e&&(this.sessionId=e,this.onSessionIdChange?.(e))}applySessionIdFromResponse(e){if(this.isModernProtocol())return;let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){this.sessionId===e&&this.setSessionId(void 0),this.onSessionExpired?.(e)}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new N({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.protocolVersion!=null&&this.protocolVersion!==`2026-07-28`&&this.startInboundSse()}async close(e){this.inboundSseConnection?.close(),this.abortController?.abort();try{if(!this.isModernProtocol()&&this.sessionId&&this.terminateSessionOnClose&&this.abortController){e?.signal?.throwIfAborted();let t=await this.commonHeaders({base:{}});e?.signal?.throwIfAborted();let n=new AbortController,r=setTimeout(()=>n.abort(),5e3);await this.fetchFn(this.url.href,{method:`DELETE`,headers:t,signal:e?.signal??n.signal,redirect:this.redirectMode}).catch(()=>void 0).finally(()=>clearTimeout(r))}}catch{}this.onclose?.()}async send(e,t){t?.signal?.throwIfAborted();let n=this.abortController?.signal,r=t?.signal==null?n:n==null?t.signal:AbortSignal.any([n,t.signal]),i=async(n=!1)=>{try{let a=`method`in e&&e.method===`initialize`,o=a?void 0:this.sessionId,c={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...this.isModernProtocol()?t?.headers:{},...this.isModernProtocol()&&`method`in e&&`id`in e?this.getStandardRequestHeaders(e):{}},includeSessionId:!a}),body:JSON.stringify(e),signal:r,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c);if(this.applySessionIdFromResponse(l),l.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=J(l);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,t)!==`AUTHORIZED`)throw new V}catch(e){throw this.onerror?.(e),e}return i(!0)}if(l.status===202){!this.isModernProtocol()&&!this.inboundSseConnection&&this.startInboundSse();return}if(!l.ok){let t=await l.text().catch(()=>null);if(`id`in e&&t!=null){let n=await M(t).catch(()=>void 0);if(n!=null&&`error`in n){this.onmessage?.(n.id==null?{...n,id:e.id}:n);return}}let n=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${t}`;l.status===404&&(!this.isModernProtocol()&&o?(this.expireSessionId(o),n+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):this.isModernProtocol()||(n+=". This server does not support HTTP transport. Try using `sse` transport instead"));let r=new N({message:n,statusCode:l.status,url:this.url.href,responseBody:t??void 0});throw this.onerror?.(r),r}if(!(`id`in e))return;let u=l.headers.get(`content-type`)||``;if(u.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>j(e)):[j(e)];for(let e of t)this.onmessage?.(e);return}if(u.includes(`text/event-stream`)){if(!l.body){let e=new N({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:l.status,url:this.url.href});throw this.onerror?.(e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader();(async()=>{try{for(;;){let{done:t,value:n}=await e.read();if(t)return;let{event:r,data:i}=n;if(an(r))try{let e=await M(i);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e)}})().catch(e=>{t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)});return}let d=new N({message:`MCP HTTP Transport Error: Unexpected content type: ${u}`,statusCode:l.status,url:this.url.href});throw this.onerror?.(d),d}catch(e){throw t?.signal?.aborted||this.onerror?.(e),e}};await i()}getStandardRequestHeaders(e){let t={"Mcp-Method":e.method},n=e.params,r=e.method===`resources/read`?n?.uri:e.method===`tools/call`||e.method===`prompts/get`?n?.name:void 0;return typeof r==`string`&&(t[`Mcp-Name`]=en(r)),t}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){let{maxRetries:e}=this.reconnectionOptions;if(e>0&&this.inboundReconnectAttempts>=e){this.onerror?.(new N({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${e}) exceeded.`}));return}let t=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},t)}startInboundSse(e=!1,t){if(this.isModernProtocol()||this.inboundSseConnection)return;let n={close(){}};this.inboundSseConnection=n,this.openInboundSse(e,t).finally(()=>{this.inboundSseConnection===n&&(this.inboundSseConnection=void 0)}).catch(e=>{e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)})}async openInboundSse(e=!1,t){if(!this.isModernProtocol())try{let n=this.sessionId,r=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(r[`last-event-id`]=t);let i=await this.fetchFn(this.url.href,{method:`GET`,headers:r,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(i),i.status===401&&this.authProvider&&!e){let{resourceMetadataUrl:e,scope:n}=J(i);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,n)!==`AUTHORIZED`){let e=new V;this.onerror?.(e);return}}catch(e){this.onerror?.(e);return}return this.openInboundSse(!0,t)}if(i.status===405)return;if(!i.ok||!i.body){i.status===404&&n&&this.expireSessionId(n);let e=new N({message:`MCP HTTP Transport Error: GET SSE failed: ${i.status} ${i.statusText}`,statusCode:i.status,url:this.url.href});this.onerror?.(e);return}let a=i.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader(),o=async()=>{try{for(;;){let{done:e,value:t}=await a.read();if(e)return;let{event:n,data:r,id:i}=t;if(i&&(this.lastInboundEventId=i),an(n))try{let e=await M(r);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{a.cancel().catch(e=>{e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)})}},this.inboundReconnectAttempts=0;let c=this.inboundSseConnection;o().finally(()=>{this.inboundSseConnection===c&&(this.inboundSseConnection=void 0)}).catch(e=>{e instanceof Error&&e.name===`AbortError`||(this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function sn(e){switch(e.type){case`sse`:return new Zt(e);case`http`:return new on({...e,initialProtocolVersion:e.initialProtocolVersion??`2026-07-28`});default:throw new N({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function cn(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}const Q=`text/html;profile=mcp-app`,ln={extensions:{"io.modelcontextprotocol/ui":{mimeTypes:[Q]}}};function un(e){let n=e?.ui;return t(n)?n:void 0}const dn=y.array(y.unknown()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),fn=y.looseObject({connectDomains:dn,resourceDomains:dn,frameDomains:dn}),pn=y.looseObject({prefersBorder:y.boolean().optional().catch(void 0),csp:fn.optional().catch(void 0),permissions:y.record(y.string(),y.unknown()).optional().catch(void 0)});function mn(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=pn.safeParse(n);return r.success?r.data:void 0}function hn(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function gn(e){let t=un(e._meta),n=t?.resourceUri??e._meta?.[`ui/resourceUri`],r=hn(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function _n(e){let t=[],n=[];for(let r of e.tools){let e=gn(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function vn({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(l(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);let i=mn(n._meta);return{uri:e,mimeType:Q,html:r,meta:i}}async function yn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return vn({uri:t,resource:await e.readResource({uri:t,options:n})})}const bn=[-32020,-32021,-32022],xn=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function Sn(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function Cn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function wn(e){let t=Sn(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(N.isInstance(e)&&e.code!=null)return!1;let n=Cn(e);return n!=null&&xn.includes(n)}function Tn(e){if(e==null)return 0;if(!Number.isInteger(e))throw new N({message:`maxRetries must be an integer`});if(e<0)throw new N({message:`maxRetries must be >= 0`});return e}function En({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function Dn(e,t){return t==null?e:new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,a)},a=()=>{i(),r(t.reason)};if(t.aborted){a();return}t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{i(),n(e)}).catch(e=>{i(),r(e)})})}function On({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function kn(e){let t=new An(e);return await t.init(),t}var An=class{constructor({experimental_events:e,transport:t,name:n,clientName:r=n??`ai-sdk-mcp-client`,version:i=`1.0.0`,onUncaughtError:a,maxRetries:o,capabilities:s,initialInitializeResult:c,initializationOptions:l,protocolVersionDiscovery:u=!0}){if(this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:E,capabilities:{},serverInfo:this._serverInfo},this.protocolEra=`legacy`,this.protocolVersion=E,this.toolHeaderBindings=new Map,this.isClosed=!0,e?.adapter!==void 0&&(e.store!==void 0||e.validateArguments!==void 0))throw new N({message:`Configure experimental_events with either an adapter or a store, not both. Managed adapters own argument validation.`});if(e?.adapter!==void 0&&typeof e.adapter?.createAdapter!=`function`)throw new N({message:`experimental_events.adapter must implement createAdapter. Wrap bound operations with { createAdapter: () => operations }.`});let d=e?.adapter?.createAdapter({transport:cn(t)?{type:`custom`}:{type:t.type,url:t.url}});e?.adapter!==void 0&&rt(d),this.onUncaughtError=a,this.maxRetries=Tn(o),this.clientCapabilities=s??{},this.initialInitializeResult=c,this.initializationOptions=l,this.protocolVersionDiscovery=u,this.transport=cn(t)?t:sn(t),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new N({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:r,version:i};let f=nt({request:e=>this.request(e),store:e?.store,validateArguments:e?.validateArguments});this.experimental_events=d?it(d,f.list):f}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?En(this.initializationOptions):void 0,n=t==null?void 0:new AbortController,r=e==null?n?.signal:n==null?e:AbortSignal.any([e,n.signal]),i,a;t!=null&&(i=setTimeout(()=>{a=new N({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await Dn(this.transport.start(),r),this.initialInitializeResult){let e=le.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}if(this.protocolVersionDiscovery&&this.transport.supportsProtocolVersionDiscovery&&await this.tryProtocolDiscovery(r))return this;this.protocolEra=`legacy`,this.protocolVersion=E,this.setTransportProtocolVersion(this.protocolVersion);let e=await this.request({request:{method:`initialize`,params:{protocolVersion:E,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:le,options:{signal:r}});if(e===void 0)throw new N({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await Dn(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new N({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}async tryProtocolDiscovery(e){this.protocolEra=`modern`,this.protocolVersion=T,this.setTransportProtocolVersion(this.protocolVersion);try{let t=await this.request({request:{method:`server/discover`},resultSchema:ce,options:{signal:e,timeout:this.transport instanceof on?void 0:1e3}});return this.applyDiscoverResult(t),!0}catch(e){if(N.isInstance(e)&&e.code!=null&&bn.includes(e.code))throw e;return!1}}applyDiscoverResult(e){if(!e.supportedVersions.includes(this.protocolVersion))throw new N({message:`Server does not support the requested protocol version: ${this.protocolVersion}`});let t=e._meta?.[`io.modelcontextprotocol/serverInfo`];typeof t==`object`&&t&&`name`in t&&typeof t.name==`string`&&`version`in t&&typeof t.version==`string`&&(this._serverInfo=t),this.serverCapabilities=e.capabilities,this._serverInstructions=e.instructions,this._initializeResult={protocolVersion:this.protocolVersion,capabilities:e.capabilities,serverInfo:this._serverInfo,instructions:e.instructions}}setTransportProtocolVersion(e){this.transport.setProtocolVersion?this.transport.setProtocolVersion(e):this.transport.protocolVersion=e}applyInitializeResult(e){if(!ne.includes(e.protocolVersion))throw new N({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this.protocolEra=`legacy`,this.protocolVersion=e.protocolVersion,this._serverInfo=e.serverInfo,this._initializeResult=e,this.setTransportProtocolVersion(e.protocolVersion),this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}send(e,t){return t==null?this.transport.send(e):this.transport.send(e,t)}assertCapability(e){switch(e){case`initialize`:case`server/discover`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new N({message:`Server does not support completions`});break;case`events/list`:case`events/subscribe`:case`events/unsubscribe`:if(!this.serverCapabilities.events)throw new N({message:`Server does not support events`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new N({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new N({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new N({message:`Server does not support prompts`});break;default:throw new N({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new N({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:En(n),s=o==null?void 0:new AbortController,c=a==null?s?.signal:s==null?a:AbortSignal.any([a,s.signal]),l,u=this.requestMessageId++,d=this.protocolEra===`modern`?{...e,params:{...e.params,_meta:{...e.params?._meta,"io.modelcontextprotocol/protocolVersion":this.protocolVersion,"io.modelcontextprotocol/clientCapabilities":this.clientCapabilities,"io.modelcontextprotocol/clientInfo":this.clientInfo}}}:e,f={...d,jsonrpc:`2.0`,id:u},p=this.getToolRequestHeaders(d),m=()=>{i(new N({message:`Request was aborted`,cause:a?.reason}))},h=()=>{this.responseHandlers.delete(u),a?.removeEventListener(`abort`,_),l!=null&&clearTimeout(l)},g=e=>{h(),i(e)},_=()=>{h(),m()};this.responseHandlers.set(u,e=>{if(a?.aborted)return h(),m();if(e instanceof Error)return g(e);try{if(this.protocolEra===`modern`&&e.result.resultType==null)throw new N({message:`Modern MCP result is missing resultType`});if(e.result.resultType===`input_required`)throw new N({message:`Server requested additional input, but multi round-trip requests are not supported yet`});let n=t.parse(e.result);h(),r(n)}catch(e){let t=N.isInstance(e)?e:new N({message:`Failed to parse server response`,cause:e});g(t)}}),a?.addEventListener(`abort`,_,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new N({message:`Request timed out after ${o}ms`});s?.abort(e),g(e)},o));let v={...c==null?{}:{signal:c},...p==null?{}:{headers:p}};(Object.keys(v).length===0?this.send(f):this.send(f,v)).catch(e=>{g(e)})})}async listTools({params:e,options:t}={}){let n=await this.request({request:{method:`tools/list`,params:e},resultSchema:de,options:t});return this.prepareToolDefinitions(n,e?.cursor==null)}prepareToolDefinitions(e,t=!1){if(this.protocolEra!==`modern`||!this.transport.supportsMcpToolParameterHeaders)return e;t&&this.toolHeaderBindings.clear();let n=e.tools.filter(e=>{let t=tn(e.inputSchema);return t.success?(this.toolHeaderBindings.set(e.name,t.bindings),!0):(this.onError(new N({message:`Ignoring MCP tool "${e.name}": ${t.error}`})),!1)});return{...e,tools:n}}getToolRequestHeaders(e){if(this.protocolEra!==`modern`||e.method!==`tools/call`||typeof e.params?.name!=`string`)return;let t=this.toolHeaderBindings.get(e.params.name);if(t==null||t.length===0)return;let n=e.params.arguments;if(typeof n==`object`&&n&&!Array.isArray(n))try{return rn({bindings:t,args:n})}catch(t){throw new N({message:`Failed to create MCP headers for tool "${e.params.name}"`,cause:t})}}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():_({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:wn,createRetryError:({message:e,errors:t})=>new N({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:we,options:n})})}async listResourcesInternal({params:e,options:t}={}){return this.request({request:{method:`resources/list`,params:e},resultSchema:he,options:t})}async readResourceInternal({uri:e,options:t}){return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:De,options:t})}async listResourceTemplatesInternal({options:e}={}){return this.request({request:{method:`resources/templates/list`},resultSchema:Ee,options:e})}async listPromptsInternal({params:e,options:t}={}){return this.request({request:{method:`prompts/list`,params:e},resultSchema:Pe,options:t})}async getPromptInternal({name:e,args:t,options:n}){return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Ie,options:n})}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:je,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await Dn(this.send(n,t?.signal==null?void 0:{signal:t.signal}),t?.signal)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools(),n=[...t.tools];for(;t.nextCursor!=null;)t=await this.listTools({params:{cursor:t.nextCursor}}),n.push(...t.tools);return this.toolsFromDefinitions({...t,tools:n},{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){e=this.prepareToolDefinitions(e);let n=Object.create(null);for(let{name:i,title:a,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=a??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,i))continue;let u=this,d=t===`automatic`?void 0:t[i]?.outputSchema,p=gn({_meta:l}),h={clientName:this.clientInfo.name,toolName:i,...e==null?{}:{title:e},...c==null?{}:{annotations:{...c.title==null?{}:{title:c.title},...c.readOnlyHint==null?{}:{readOnlyHint:c.readOnlyHint},...c.destructiveHint==null?{}:{destructiveHint:c.destructiveHint},...c.idempotentHint==null?{}:{idempotentHint:c.idempotentHint},...c.openWorldHint==null?{}:{openWorldHint:c.openWorldHint}}},...p?.resourceUri==null?{}:{app:{...p,mimeType:Q}}},g=async(e,t)=>{t?.abortSignal?.throwIfAborted();let n=await u.callTool({name:i,arguments:e,options:{signal:t?.abortSignal}});return n.isError||d==null?n:u.extractStructuredContent(n,d,i)};n[i]={...t===`automatic`?m({description:o,title:e,metadata:h,inputSchema:r({...s,properties:s.properties??{},additionalProperties:!1}),execute:g,toModelOutput:On}):f({description:o,title:e,metadata:h,inputSchema:t[i].inputSchema,...d==null?{}:{outputSchema:d},execute:g,toModelOutput:On}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await d({value:e.structuredContent,schema:p(t)});if(!r.success)throw new N({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await u({text:r.text,schema:t});if(!e.success)throw new N({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new N({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==A)throw new N({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=A.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=Re.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new N({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){if(e.id==null){this.onError(new N({message:`Protocol error: Received a response without a message ID: ${JSON.stringify(e)}`}));return}let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new N({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new N({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};const jn=new TextEncoder;function $(e){if(typeof e!=`object`||!e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map($).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${$(t[e])}`).join(`,`)}}`}function Mn(e){return h(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function Nn(e){let t=await crypto.subtle.digest(`SHA-256`,jn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return Mn(new Uint8Array(t))}function Pn(e,t){return e!==t}const Fn=262144,In=b.object({type:b.literal(`verification`),challenge:b.string().min(1)});function Ln({store:e,validatePayload:t,onEvent:n,onGap:r,onTerminated:i,onError:a}){return async o=>{if(o.method!==`POST`)return new Response(null,{status:405,headers:{Allow:`POST`}});if(o.headers.get(`content-type`)?.split(`;`)[0].trim().toLowerCase()!==`application/json`)return new Response(null,{status:415});if(Number(o.headers.get(`content-length`))>Fn)return new Response(null,{status:413});try{let s=new URL(o.url).searchParams.get(tt),c=o.headers.get(`X-MCP-Subscription-Id`);if(!s||!c)return new Response(null,{status:401});let l=await e.get(s);if(!l||l.id!=null&&l.id!==c)return new Response(null,{status:401});let d=o.body?.getReader();if(!d)return new Response(null,{status:400});let f=[],p=0;try{for(;;){let{done:e,value:t}=await d.read();if(e)break;if(p+=t.byteLength,p>Fn)return await d.cancel(),new Response(null,{status:413});f.push(t)}}finally{d.releaseLock()}let m=new Uint8Array(p),h=0;for(let e of f)m.set(e,h),h+=e.length;if(!await Je({headers:o.headers,body:m,secret:l.delivery.secret}))return new Response(null,{status:401});let g=await u({text:new TextDecoder().decode(m)});if(!g.success)return new Response(null,{status:400});let _=g.value,v;if(typeof _==`object`&&_&&`type`in _){if(_.type===`verification`){let e=In.safeParse(_);return e.success?Response.json({challenge:e.data.challenge}):new Response(null,{status:400})}let e=et.safeParse(_);if(!e.success)return new Response(null,{status:400});v=e.data}if(l.id==null||l.status!==`active`&&v?.type!==`terminated`)return new Response(null,{status:503});let y={id:l.id,name:l.name,arguments:l.arguments,delivery:{mode:`webhook`,url:l.delivery.url},refreshBefore:l.refreshBefore??null};if(v){let t=o.headers.get(`webhook-id`);return v.type===`gap`?(await r?.({subscription:y,messageId:t,gap:v}),await e.update(l.key,{cursor:v.cursor,truncated:!0})):(await i?.({subscription:y,messageId:t,termination:v}),await e.delete(l.key)),new Response(null,{status:204})}if(l.refreshBefore!=null&&Date.parse(l.refreshBefore)<=Date.now())return new Response(null,{status:410});let b=$e.safeParse(_);if(!b.success||b.data.name!==l.name||b.data.eventId!==o.headers.get(`webhook-id`))return new Response(null,{status:400});try{await t?.({definition:l.definition,data:b.data.data})}catch(e){return a?.(e),new Response(null,{status:400})}return await n({subscription:y,event:b.data}),b.data.cursor!==void 0&&await e.update(l.key,{cursor:b.data.cursor}),new Response(null,{status:204})}catch(e){return a?.(e),new Response(null,{status:503})}}}export{vt as AuthorizationServerMismatchError,Re as ElicitResultSchema,A as ElicitationRequestSchema,N as MCPClientError,F as MCPClientOAuthError,Q as MCP_APP_MIME_TYPE,V as UnauthorizedError,Z as auth,kn as createMCPClient,kn as experimental_createMCPClient,Pn as detectMCPAppResourceDrift,Ln as experimental_createMCPEventWebhook,Nn as fingerprintMCPAppResource,ln as mcpAppClientCapabilities,yn as readMCPAppResource,_n as splitMCPAppTools,j as validateJSONRPCMessage};
|
|
1
|
+
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{I as n,K as r,M as i,N as a,St as o,Tt as s,U as c,c as l,dt as u,ft as d,gt as f,i as p,j as m,p as h,tt as g,ut as _,yt as v}from"../../_chunks/workflow/dist-C8k3N3BQ.js";import*as y from"#compiled/zod/index.js";import{z as b}from"#compiled/zod/index.js";let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function S(e){return(await x).getRandomValues(new Uint8Array(e))}async function C(e){let t=``;for(;t.length<e;){let n=await S(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function w(e){return await C(e)}async function ee(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function te(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await w(e);return{code_verifier:t,code_challenge:await ee(t)}}const T=`2026-07-28`,E=`2025-11-25`,ne=[T,E,`2025-06-18`,`2025-03-26`,`2024-11-05`],re=b.optional(b.record(b.string(),b.unknown())),ie=b.looseObject({name:b.string(),version:b.string(),title:b.optional(b.string())}),D=b.looseObject({_meta:b.optional(b.object({}).loose())}),O=D.extend({resultType:b.optional(b.string())}),ae=b.object({method:b.string(),params:b.optional(D)}),oe=b.object({applyDefaults:b.optional(b.boolean())}).loose(),se=b.looseObject({events:b.looseObject({listChanged:b.boolean().nullish()}).nullish(),experimental:b.optional(b.object({}).loose()),logging:b.optional(b.object({}).loose()),completions:b.optional(b.object({}).loose()),prompts:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),resources:b.optional(b.looseObject({subscribe:b.optional(b.boolean()),listChanged:b.optional(b.boolean())})),tools:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),elicitation:b.optional(oe)});b.object({elicitation:b.optional(oe)}).loose();const ce=O.extend({supportedVersions:b.array(b.string()),capabilities:se,instructions:b.optional(b.string()),ttlMs:b.optional(b.number()),cacheScope:b.optional(b.union([b.literal(`public`),b.literal(`private`)]))}),le=O.extend({protocolVersion:b.string(),capabilities:se,serverInfo:ie,instructions:b.optional(b.string())}),k=O.extend({nextCursor:b.optional(b.string())}),ue=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),inputSchema:b.looseObject({type:b.optional(b.unknown()),properties:b.optional(b.object({}).loose())}),outputSchema:b.optional(b.object({}).loose()),annotations:b.optional(b.object({title:b.optional(b.string()),readOnlyHint:b.optional(b.boolean()),destructiveHint:b.optional(b.boolean()),idempotentHint:b.optional(b.boolean()),openWorldHint:b.optional(b.boolean())}).loose()),_meta:re}).loose(),de=k.extend({tools:b.array(ue)}),fe=b.object({type:b.literal(`text`),text:b.string()}).loose(),pe=b.object({type:b.literal(`image`),data:b.base64(),mimeType:b.string()}).loose(),me=b.object({uri:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string()),size:b.optional(b.number())}).loose(),he=k.extend({resources:b.array(me)}),ge=b.object({uri:b.string(),name:b.optional(b.string()),title:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),_e=ge.extend({text:b.string()}),ve=ge.extend({blob:b.base64()}),ye=b.object({type:b.literal(`resource`),resource:b.union([_e,ve])}).loose(),be=b.object({type:b.literal(`resource_link`),uri:b.string(),name:b.string(),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),xe=b.object({type:b.string()}).loose().refine(e=>![`text`,`image`,`resource`,`resource_link`].includes(e.type),{message:`Known content types must match their schema`}),Se=O.extend({content:b.array(b.union([fe,pe,ye,be,xe])),structuredContent:b.optional(b.unknown()),isError:b.boolean().default(!1).optional()}),Ce=O.extend({content:b.never().optional(),structuredContent:b.json(),isError:b.boolean().default(!1).optional()}).transform(e=>({...e,content:[{type:`text`,text:JSON.stringify(e.structuredContent)}]})).pipe(Se),we=Se.or(Ce).or(O.extend({toolResult:b.unknown().nonoptional()})),Te=b.object({uriTemplate:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),Ee=O.extend({resourceTemplates:b.array(Te)}),De=O.extend({contents:b.array(b.union([_e,ve]))}),Oe=b.object({type:b.literal(`ref/prompt`),name:b.string()}).loose(),ke=b.object({type:b.literal(`ref/resource`),uri:b.string()}).loose(),Ae=b.object({name:b.string(),value:b.string()}).loose();D.extend({ref:b.union([Oe,ke]),argument:Ae,context:b.optional(b.object({arguments:b.record(b.string(),b.string())}).loose())});const je=O.extend({completion:b.object({values:b.array(b.string()).max(100),total:b.optional(b.number().int()),hasMore:b.optional(b.boolean())}).loose()}),Me=b.object({name:b.string(),description:b.optional(b.string()),required:b.optional(b.boolean())}).loose(),Ne=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),arguments:b.optional(b.array(Me))}).loose(),Pe=k.extend({prompts:b.array(Ne)}),Fe=b.object({role:b.union([b.literal(`user`),b.literal(`assistant`)]),content:b.union([fe,pe,ye,be])}).loose(),Ie=O.extend({description:b.optional(b.string()),messages:b.array(Fe)}),Le=D.extend({message:b.string(),requestedSchema:b.unknown()}),A=ae.extend({method:b.literal(`elicitation/create`),params:Le}),Re=O.extend({action:b.union([b.literal(`accept`),b.literal(`decline`),b.literal(`cancel`)]),content:b.optional(b.record(b.string(),b.unknown()))}),ze=b.object({jsonrpc:b.literal(`2.0`),id:b.union([b.string(),b.number().int()])}).merge(ae).strict(),Be=b.object({jsonrpc:b.literal(`2.0`),id:b.union([b.string(),b.number().int()]),result:O}).strict(),Ve=b.object({jsonrpc:b.literal(`2.0`),id:b.optional(b.union([b.string(),b.number().int()])),error:b.object({code:b.number().int(),message:b.string(),data:b.optional(b.unknown())})}).strict(),He=b.object({jsonrpc:b.literal(`2.0`)}).merge(b.object({method:b.string(),params:b.optional(D)})).strict(),Ue=b.union([ze,He,Be,Ve]);function j(e){return Ue.parse(e)}async function M(e){return j(await g({text:e}))}const We=`vercel.ai.error.AI_MCPClientError`,Ge=Symbol.for(We);var N=class extends e{constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[Ge]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,We)}};function Ke(){return`whsec_${h(crypto.getRandomValues(new Uint8Array(32)))}`}function qe(e){let t=e.slice(6);if(!e.startsWith(`whsec_`)||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new N({message:`Invalid MCP event signing secret`});let n=l(t);if(n.length<24||n.length>64)throw new N({message:`MCP event signing secrets must contain 24–64 random bytes`});return n}async function Je({headers:e,body:t,secret:n}){let r=e.get(`webhook-id`),i=e.get(`webhook-timestamp`),a=e.get(`webhook-signature`);if(!r||!i||!a||!/^\d+$/.test(i)||Math.abs(Date.now()/1e3-Number(i))>300)return!1;let o=await crypto.subtle.importKey(`raw`,new Uint8Array(qe(n)),{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]),s=new TextEncoder().encode(`${r}.${i}.`),c=new Uint8Array(s.length+t.length);c.set(s),c.set(t,s.length);for(let e of a.split(` `)){let[t,n]=e.split(`,`);if(t===`v1`&&n)try{if(await crypto.subtle.verify(`HMAC`,o,new Uint8Array(l(n)),c))return!0}catch{}}return!1}const Ye=b.union([b.boolean(),b.record(b.string(),b.unknown())]),Xe=b.looseObject({name:b.string().min(1),description:b.string().nullish(),delivery:b.array(b.enum([`webhook`,`poll`,`push`])).min(1),inputSchema:Ye,payloadSchema:Ye}),Ze=O.extend({events:b.array(Xe),nextCursor:b.string().nullish()}),Qe=O.extend({id:b.string().min(1),refreshBefore:b.iso.datetime({offset:!0}).nullable(),cursor:b.string().nullish().transform(e=>e??null),truncated:b.boolean()}),$e=b.looseObject({eventId:b.string().min(1),name:b.string().min(1),timestamp:b.iso.datetime({offset:!0}),data:b.record(b.string(),b.unknown()),cursor:b.string().nullish()}),et=b.discriminatedUnion(`type`,[b.looseObject({type:b.literal(`gap`),cursor:b.string()}),b.looseObject({type:b.literal(`terminated`),error:b.looseObject({code:b.number().int(),message:b.string(),data:b.unknown().nullish()})})]).transform(e=>e.type===`gap`?{...e,truncated:!0}:e),tt=`mcp_event_subscription`;function nt({request:e,store:t,validateArguments:n}){function r(){if(!t)throw new N({message:`Configure experimental_events.store to manage direct event subscriptions`});return t}async function i({id:e,key:t}){let n=r(),i=e===void 0?await n.get(t):await n.getById(e);if(!i)throw new N({message:`Unknown MCP event subscription: ${e??t}`});return i}async function a(t,n){let i=await e({request:{method:`events/subscribe`,params:{name:t.name,arguments:t.arguments,delivery:t.delivery,cursor:t.cursor,...t.ttlMs===void 0?{}:{ttlMs:t.ttlMs},...t.maxAgeMs===void 0?{}:{maxAgeMs:t.maxAgeMs}}},resultSchema:Qe,options:n});return await r().update(t.key,{id:i.id,refreshBefore:i.refreshBefore,cursor:i.cursor,truncated:i.truncated,status:`active`}),i}let o={list({params:t,options:n}={}){return e({request:{method:`events/list`,params:t},resultSchema:Ze,options:n})},async subscribe({name:e,arguments:t={},delivery:i,cursor:s=null,ttlMs:c,maxAgeMs:l,options:u}){let d=r(),f=new URL(i.url),p=i.allowInsecureLocalhost===!0&&f.protocol===`http:`&&(f.hostname===`127.0.0.1`||f.hostname===`[::1]`);if(f.protocol!==`https:`&&!p||f.username||f.password||f.hash)throw new N({message:`MCP event callback URLs must use HTTPS without credentials or fragments`});if(i.mode!==`webhook`)throw new N({message:`Only webhook event delivery is supported`});if(c!=null&&(!Number.isSafeInteger(c)||c<=0)||l!=null&&(!Number.isSafeInteger(l)||l<0))throw new N({message:`Invalid MCP event subscription lifetime or replay age`});let m,h=new Set,g;do{let t=await o.list({params:{cursor:m},options:u});if(g=t.events.find(t=>t.name===e),g)break;if(m=t.nextCursor??void 0,m!=null){if(h.has(m))throw new N({message:`Repeated MCP events pagination cursor`});h.add(m)}}while(m!=null);if(!g)throw new N({message:`Unknown MCP event: ${e}`});if(!g.delivery.includes(`webhook`))throw new N({message:`MCP event ${e} does not support webhook delivery`});await n?.({definition:g,arguments:t});let _=i.secret??Ke();qe(_);let v=crypto.randomUUID();f.searchParams.set(tt,v);let y={key:v,name:e,arguments:structuredClone(t),definition:g,delivery:{mode:`webhook`,url:f.href,secret:_},cursor:s,truncated:!1,ttlMs:c,maxAgeMs:l,status:`pending`};return await d.set(y),a(y,u)},async refresh(e){let t=await i(e);return await r().update(t.key,{status:`pending`}),a(t,e.options)},async unsubscribe(t){let n=await i(t);await e({request:{method:`events/unsubscribe`,params:{name:n.name,arguments:n.arguments,delivery:{mode:`webhook`,url:n.delivery.url}}},resultSchema:O,options:t.options}),await r().delete(n.key)}};return o}function rt(e){if(e!=null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`)throw Promise.resolve(e).catch(()=>{}),new N({message:`experimental_events.adapter.createAdapter() must return operations synchronously. Promise and thenable results are not supported.`});if(typeof e!=`object`||!e||!(`subscribe`in e)||typeof e.subscribe!=`function`||!(`getSubscription`in e)||typeof e.getSubscription!=`function`||!(`listSubscriptions`in e)||typeof e.listSubscriptions!=`function`||!(`unsubscribe`in e)||typeof e.unsubscribe!=`function`)throw new N({message:`experimental_events.adapter.createAdapter() must return an object implementing subscribe, getSubscription, listSubscriptions, and unsubscribe.`})}function it(e,t){return{list:t,subscribe:t=>e.subscribe(t),getSubscription:t=>e.getSubscription(t),listSubscriptions:t=>e.listSubscriptions(t),unsubscribe:t=>e.unsubscribe(t)}}const at=`2.0.73`,P=b.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:b.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),b.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),ot=b.object({access_token:b.string(),id_token:b.string().optional(),token_type:b.string(),expires_in:b.number().optional(),scope:b.string().optional(),refresh_token:b.string().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),st=b.looseObject({resource:b.string().url(),authorization_servers:b.array(P).optional(),jwks_uri:b.string().url().optional(),scopes_supported:b.array(b.string()).optional(),bearer_methods_supported:b.array(b.string()).optional(),resource_signing_alg_values_supported:b.array(b.string()).optional(),resource_name:b.string().optional(),resource_documentation:b.string().optional(),resource_policy_uri:b.string().url().optional(),resource_tos_uri:b.string().url().optional(),tls_client_certificate_bound_access_tokens:b.boolean().optional(),authorization_details_types_supported:b.array(b.string()).optional(),dpop_signing_alg_values_supported:b.array(b.string()).optional(),dpop_bound_access_tokens_required:b.boolean().optional()}),ct=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),code_challenge_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_signing_alg_values_supported:b.array(b.string()).optional()}),lt=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,userinfo_endpoint:P.optional(),jwks_uri:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),subject_types_supported:b.array(b.string()),id_token_signing_alg_values_supported:b.array(b.string()),claims_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional()}).merge(ct.pick({code_challenge_methods_supported:!0})),ut=b.object({client_id:b.string(),client_secret:b.string().optional(),client_id_issued_at:b.number().optional(),client_secret_expires_at:b.number().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),dt=b.object({redirect_uris:b.array(P),application_type:b.union([b.literal(`native`),b.literal(`web`)]).optional(),token_endpoint_auth_method:b.string().optional(),grant_types:b.array(b.string()).optional(),response_types:b.array(b.string()).optional(),client_name:b.string().optional(),client_uri:P.optional(),logo_uri:P.optional(),scope:b.string().optional(),contacts:b.array(b.string()).optional(),tos_uri:P.optional(),policy_uri:b.string().optional(),jwks_uri:P.optional(),jwks:b.any().optional(),software_id:b.string().optional(),software_version:b.string().optional(),software_statement:b.string().optional()}).strip(),ft=b.object({error:b.string(),error_description:b.string().optional(),error_uri:b.string().optional()}),pt=dt.merge(ut),mt=`vercel.ai.error.AI_MCPClientOAuthError`,ht=Symbol.for(mt);var F=class extends e{constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[ht]=!0}static isInstance(t){return e.hasMarker(t,mt)}},I=class extends F{static{this.errorCode=`server_error`}},L=class extends F{static{this.errorCode=`invalid_client`}},R=class extends F{static{this.errorCode=`invalid_grant`}},z=class extends F{static{this.errorCode=`unauthorized_client`}};const gt=`vercel.ai.error.AI_AuthorizationServerMismatchError`,_t=Symbol.for(gt);var vt=class extends F{static{this.errorCode=`authorization_server_mismatch`}constructor({message:e,cause:t}){super({name:`AuthorizationServerMismatchError`,message:e,cause:t}),this[_t]=!0}static isInstance(t){return e.hasMarker(t,gt)}};const yt={[I.errorCode]:I,[L.errorCode]:L,[R.errorCode]:R,[z.errorCode]:z};function bt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function B(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function xt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var V=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function H(e){return new URL(e).href}function U(e){let t=e.toLowerCase().replace(/\.+$/,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function W(e,{allowLoopback:t=!1}={}){if(!t||e.protocol!==`http:`&&e.protocol!==`https:`||!U(e.hostname))try{v(e.href)}catch(t){throw new F({message:`OAuth endpoint URL is not allowed: ${e.href}`,cause:t})}}function G(e){let t=new URL(e);return U(t.hostname)?t.origin:void 0}function St({callbackIssuer:e,expectedIssuer:t}){if(e!=null&&e!==t)throw new F({message:`OAuth authorization response issuer ${e} does not match expected issuer ${t}`})}function Ct(e,t){return{issuer:t?.issuer??String(e),authorizationServerUrl:H(e),tokenEndpoint:H(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function wt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Tt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Et(e){if(e?.authorization_server&&e.token_endpoint)return{issuer:e.issuer,authorizationServerUrl:H(e.authorization_server),tokenEndpoint:H(e.token_endpoint)}}async function K({provider:e,clientInformation:t,tokens:n}){let r=Et(n);if(r)return r;let i=await e.authorizationServerInformation?.();return i?{issuer:i.issuer,authorizationServerUrl:H(i.authorizationServerUrl),tokenEndpoint:H(i.tokenEndpoint)}:Et(t)}async function Dt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(Tt(t,n)),!0):!1}function Ot(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new F({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function q({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.issuer!=null&&t.issuer!=null&&e.issuer!==t.issuer||e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new vt({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function J(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=t.match(/(?:^|[,\s])resource_metadata="([^"]*)"/i),a=t.match(/(?:^|[,\s])scope="([^"]*)"/i)?.[1],o;try{o=i?new URL(i[1]):void 0}catch{}return{resourceMetadataUrl:o,scope:a}}function kt({scope:e,resourceMetadata:t,clientMetadata:n}){return e||t?.scopes_supported?.join(` `)||n.scope}function At(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Y(e,t,n=fetch,r){try{return await i({url:e.href,fetch:async(e,i)=>a({url:e,init:{...i,headers:new Headers(i?.headers).has(`MCP-Protocol-Version`)?t:void 0},fetch:n,trustedOrigin:r,redirect:`manual`}),headers:t,trustedOrigin:r,untrustedFirstHopHeaders:[`mcp-protocol-version`]})}catch(i){if(i instanceof TypeError)return t?Y(e,void 0,n,r):void 0;throw i}}async function jt(e,t,n=fetch,r){return await Y(e,{"MCP-Protocol-Version":t},n,r)}function Mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Nt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2026-07-28`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=At(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await jt(o,a,n,r?.trustedOrigin);return!r?.metadataUrl&&Mt(s,i.pathname)&&(s=await jt(new URL(`/.well-known/${t}`,i),a,n,r?.trustedOrigin)),s}async function Pt(e,t,n=fetch){let r=await Nt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl,trustedOrigin:new URL(e).origin});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return st.parse(await r.json())}function Ft(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o});let s=new URL(t.origin);return s.pathname=`${a}/.well-known/openid-configuration`,i.push({url:s,type:`oidc`,expectedIssuer:o}),i}function It(e,t){if(!(e.issuer===t||t===new URL(t).origin&&e.issuer===`${t}/`))throw new F({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Lt(e,{fetchFn:t=fetch,protocolVersion:n=T,trustedOrigin:r}={}){let i={"MCP-Protocol-Version":n},a=new URL(e).origin,o=Ft(e);if(o.some(({url:e})=>e.origin!==a))throw new F({message:`OAuth discovery URL changed authorization-server origin`});for(let{url:e,type:n,expectedIssuer:a}of o){let o=await Y(e,i,t,r);if(o){if(!o.ok){if(o.status>=400&&o.status<500)continue;throw Error(`HTTP ${o.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=ct.parse(await o.json());return It(e,a),e}{let t=lt.parse(await o.json());if(It(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Rt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await te(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,B(o)),{authorizationUrl:l,codeVerifier:d}}function zt(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Bt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Vt(i,a,n);return;case`client_secret_post`:Ht(i,a,r);return;case`none`:Ut(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Vt(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Ht(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Ut(e,t){t.set(`client_id`,e)}async function X(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ft.parse(await g({text:n}));return new(yt[e]||I)({message:t||``,cause:r})}catch(e){return new I({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Wt(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:c,fetchFn:l}){let u=`authorization_code`,d=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),f=G(e);if(W(d,{allowLoopback:d.origin===f}),t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),m=new URLSearchParams({grant_type:u,code:r,code_verifier:i,redirect_uri:String(o)});c?await c(p,m,e,t):Bt(zt(n,t?.token_endpoint_auth_methods_supported??[]),n,p,m),s&&m.set(`resource`,B(s));let h=await a({url:d,init:{method:`POST`,headers:p,body:m},fetch:l,trustedOrigin:f});if(!h.ok)throw await X(h);return ot.parse(await h.json())}async function Gt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:o,fetchFn:s}){let c=`refresh_token`,l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL(`/token`,e);let u=G(e);W(l,{allowLoopback:l.origin===u});let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:c,refresh_token:r});o?await o(d,f,e,t):Bt(zt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),i&&f.set(`resource`,B(i));let p=await a({url:l,init:{method:`POST`,headers:d,body:f},fetch:s,trustedOrigin:u});if(!p.ok)throw await X(p);return ot.parse({refresh_token:r,...await p.json()})}async function Kt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let o=G(e);W(i,{allowLoopback:i.origin===o});let s=n.application_type??qt(n.redirect_uris),c=await a({url:i,init:{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,application_type:s})},fetch:r,trustedOrigin:o});if(!c.ok)throw await X(c);return pt.parse(await c.json())}function qt(e){return e.every(e=>{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&U(t.hostname)||t.protocol!==`http:`&&t.protocol!==`https:`})?`native`:`web`}async function Z(e,t){let n={};try{return await Yt(e,t,n)}catch(r){if(r instanceof L||r instanceof z){if(t.authorizationCode!==void 0||!await e.isClientInformationDynamicallyRegistered?.())throw r;return await e.invalidateCredentials?.(`all`),await Yt(e,t)}if(r instanceof R&&n.tokens)return await e.invalidateCredentials?.(`tokens`,{tokens:n.tokens}),await Yt(e,t);throw r}}async function Jt(e,t,n){let r=bt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!xt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Yt(e,{serverUrl:t,authorizationCode:n,callbackState:r,callbackIssuer:i,scope:a,resourceMetadataUrl:o,fetchFn:s},c){let l,u,d,f;Ot(t,o);try{l=await Pt(t,{resourceMetadataUrl:o},s),l.authorization_servers&&l.authorization_servers.length>0&&(u=l.authorization_servers[0])}catch{}n!==void 0&&(d=await Promise.resolve(e.clientInformation()),d&&(f=await K({provider:e,clientInformation:d}))),u||=f?.authorizationServerUrl??t;let p=new URL(t),m=new URL(u),h=p.origin,g=m.origin,_=g===h||U(p.hostname)&&U(m.hostname)?g:void 0;_||W(new URL(u));let v=await Jt(t,e,l);await e.validateAuthorizationServerURL?.(t,u);let y=await Lt(u,{fetchFn:s,trustedOrigin:_}),b=Ct(u,y),x=e.clientMetadata,S=kt({scope:a,resourceMetadata:l,clientMetadata:x});if(n===void 0&&(d=await Promise.resolve(e.clientInformation())),d?.issuer!=null){let t=f??await K({provider:e,clientInformation:d});t&&q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b})}if(!d){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);d=Tt(await Kt(u,{metadata:y,clientMetadata:{...x,scope:S},fetchFn:s}),b),await e.saveClientInformation(d)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=f??await K({provider:e,clientInformation:d});if(!t)throw new F({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});St({callbackIssuer:i,expectedIssuer:t.issuer??y?.issuer??String(u)}),q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b});let a=await e.codeVerifier(),o=await Wt(u,{metadata:y,clientInformation:d,authorizationCode:n,codeVerifier:a,redirectUri:e.redirectUrl,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(wt(o,b)),`AUTHORIZED`}let C=await e.tokens();if(C?.refresh_token){let t=await K({provider:e,clientInformation:d,tokens:C});t?q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b}):await e.invalidateCredentials?.(`tokens`,{tokens:{...C}});try{if(t){c&&(c.tokens={...C});let t=await Gt(u,{metadata:y,clientInformation:d,refreshToken:C.refresh_token,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(wt(t,b)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof F)||e instanceof I))throw e}}let w=e.state?await e.state():void 0;w&&e.saveState&&await e.saveState(w);let{authorizationUrl:ee,codeVerifier:te}=await Rt(u,{metadata:y,clientInformation:d,state:w,redirectUrl:e.redirectUrl,scope:S,resource:v});if(!await Dt({provider:e,clientInformation:d,authorizationServerInformation:b}))throw new F({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(te),await e.redirectToAuthorization(ee),`REDIRECT`}function Xt(e){return e===void 0||e===`message`}var Zt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??`2025-11-25`};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return o(t,`ai-sdk/${at}`,n())}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async accessTokenChanged(e){let t=(await this.authProvider?.tokens())?.access_token;return t!=null&&e!==`Bearer ${t}`}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{try{let i=await this.commonHeaders({Accept:`text/event-stream`}),a=await this.fetchFn(this.url.href,{headers:i,signal:this.abortController?.signal,redirect:this.redirectMode});if(a.status===401&&this.authProvider&&!r){let{resourceMetadataUrl:e,scope:r}=J(a);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,r)!==`AUTHORIZED`){let e=new V;return this.onerror?.(e),t(e)}}catch(e){return this.onerror?.(e),t(e)}return n(!0)}if(!a.ok||!a.body){let e=`MCP SSE Transport Error: ${a.status} ${a.statusText}`;a.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new N({message:e});return this.onerror?.(n),t(n)}let o=a.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader(),c=async()=>{try{for(;;){let{done:t,value:n}=await o.read();if(t){if(this.abortController?.signal.aborted)return;throw this.connected?(this.connected=!1,new N({message:`MCP SSE Transport Error: Connection closed unexpectedly`})):new N({message:`MCP SSE Transport Error: Connection closed before endpoint event was received`})}let{event:r,data:i}=n;if(r===`endpoint`){if(this.endpoint)continue;let t=new URL(i,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,this.sseConnection?.close(),this.abortController?.abort(),new N({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Xt(r))try{let e=await M(i);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),t(e)}};this.sseConnection={close:()=>o.cancel()},c()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),t(e)}};n()})}async close(){this.connected=!1,this.endpoint=void 0,this.sseConnection?.close(),this.abortController?.abort(),this.onclose?.()}async send(e,t){if(t?.signal?.throwIfAborted(),!this.endpoint||!this.connected)throw new N({message:`MCP SSE Transport Error: Not connected`});let n=this.endpoint,r=this.abortController?.signal,i=t?.signal==null?r:r==null?t.signal:AbortSignal.any([r,t.signal]),a=async(r=!1)=>{try{let t=await this.commonHeaders({"Content-Type":`application/json`}),o={method:`POST`,headers:t,body:JSON.stringify(e),signal:i,redirect:this.redirectMode},s=await this.fetchFn(n.href,o);if(s.status===401&&this.authProvider&&!r){if(await this.accessTokenChanged(new Headers(t).get(`authorization`)??void 0))return a(!0);let{resourceMetadataUrl:e,scope:n}=J(s);if(this.resourceMetadataUrl=e,await this.authorizeOnce(this.resourceMetadataUrl,n)!==`AUTHORIZED`)throw new V;return a(!0)}if(!s.ok){let e=await s.text().catch(()=>null);throw new N({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${s.status}): ${e}`,statusCode:s.status,url:n.href,responseBody:e??void 0})}}catch(e){throw t?.signal?.aborted||this.onerror?.(e),e}};await a()}};const Qt=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,$t=/^=\?base64\?.*\?=$/;function en(e){return[...e].every(e=>{let t=e.charCodeAt(0);return t===9||t>=32&&t<=126})&&e.trim()===e&&!$t.test(e)?e:`=?base64?${h(new TextEncoder().encode(e))}?=`}function tn(e){if(!c(e))return{success:!1,error:`inputSchema must be a JSON Schema object`};let t=[],n=new Set,r,i=(e,a,o)=>{if(r==null&&c(e)){if(`x-mcp-header`in e){if(!o||a.length===0){r=`x-mcp-header is not on a statically reachable property`;return}let i=e[`x-mcp-header`];if(typeof i!=`string`||!Qt.test(i)){r=`x-mcp-header must be a non-empty HTTP token`;return}let s=i.toLowerCase();if(n.has(s)){r=`x-mcp-header value "${i}" is not unique`;return}let c=e.type;if(c!==`boolean`&&c!==`integer`&&c!==`string`){r=`x-mcp-header can only annotate boolean, integer, or string properties`;return}n.add(s),t.push({headerName:i,path:a,valueType:c})}for(let[t,n]of Object.entries(e))if(t!==`x-mcp-header`){if(t===`properties`&&c(n))for(let[e,t]of Object.entries(n))i(t,[...a,e],o);else i(n,a,!1)}}};return i(e,[],!0),r==null?{success:!0,bindings:t}:{success:!1,error:r}}function nn(e,t){let n=e;for(let e of t){if(!c(n))return;n=n[e]}return n}function rn({bindings:e,args:t}){let n={};for(let r of e){let e=nn(t,r.path);if(e!=null){if(r.valueType===`string`&&typeof e!=`string`||r.valueType===`boolean`&&typeof e!=`boolean`||r.valueType===`integer`&&!Number.isSafeInteger(e))throw TypeError(`Tool argument "${r.path.join(`.`)}" does not match its x-mcp-header type`);n[`Mcp-Param-${r.headerName}`]=en(String(e))}}return n}function an(e){return e===void 0||e===`message`}var on=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.supportsProtocolVersionDiscovery=!0,this.supportsMcpToolParameterHeaders=!0,this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a??`2025-11-25`,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){if(this.protocolVersion=e,this.abortController){if(this.isModernProtocol()){this.inboundSseConnection?.close(),this.inboundSseConnection=void 0;return}this.sessionId&&this.startInboundSse()}}isModernProtocol(){return(this.protocolVersion??`2026-07-28`)===T}async commonHeaders({base:e,includeSessionId:t=!0}){let r={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??`2025-11-25`};if(!this.isModernProtocol()&&t&&this.sessionId&&(r[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(r.Authorization=`Bearer ${e.access_token}`)}return o(r,`ai-sdk/${at}`,n())}setSessionId(e){this.sessionId!==e&&(this.sessionId=e,this.onSessionIdChange?.(e))}applySessionIdFromResponse(e){if(this.isModernProtocol())return;let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){this.sessionId===e&&this.setSessionId(void 0),this.onSessionExpired?.(e)}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new N({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.protocolVersion!=null&&this.protocolVersion!==`2026-07-28`&&this.startInboundSse()}async close(e){this.inboundSseConnection?.close(),this.abortController?.abort();try{if(!this.isModernProtocol()&&this.sessionId&&this.terminateSessionOnClose&&this.abortController){e?.signal?.throwIfAborted();let t=await this.commonHeaders({base:{}});e?.signal?.throwIfAborted();let n=new AbortController,r=setTimeout(()=>n.abort(),5e3);await this.fetchFn(this.url.href,{method:`DELETE`,headers:t,signal:e?.signal??n.signal,redirect:this.redirectMode}).catch(()=>void 0).finally(()=>clearTimeout(r))}}catch{}this.onclose?.()}async send(e,t){t?.signal?.throwIfAborted();let n=this.abortController?.signal,r=t?.signal==null?n:n==null?t.signal:AbortSignal.any([n,t.signal]),i=async(n=!1)=>{try{let a=`method`in e&&e.method===`initialize`,o=a?void 0:this.sessionId,c={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...this.isModernProtocol()?t?.headers:{},...this.isModernProtocol()&&`method`in e&&`id`in e?this.getStandardRequestHeaders(e):{}},includeSessionId:!a}),body:JSON.stringify(e),signal:r,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c);if(this.applySessionIdFromResponse(l),l.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=J(l);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,t)!==`AUTHORIZED`)throw new V}catch(e){throw this.onerror?.(e),e}return i(!0)}if(l.status===202){!this.isModernProtocol()&&!this.inboundSseConnection&&this.startInboundSse();return}if(!l.ok){let t=await l.text().catch(()=>null);if(`id`in e&&t!=null){let n=await M(t).catch(()=>void 0);if(n!=null&&`error`in n){this.onmessage?.(n.id==null?{...n,id:e.id}:n);return}}let n=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${t}`;l.status===404&&(!this.isModernProtocol()&&o?(this.expireSessionId(o),n+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):this.isModernProtocol()||(n+=". This server does not support HTTP transport. Try using `sse` transport instead"));let r=new N({message:n,statusCode:l.status,url:this.url.href,responseBody:t??void 0});throw this.onerror?.(r),r}if(!(`id`in e))return;let u=l.headers.get(`content-type`)||``;if(u.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>j(e)):[j(e)];for(let e of t)this.onmessage?.(e);return}if(u.includes(`text/event-stream`)){if(!l.body){let e=new N({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:l.status,url:this.url.href});throw this.onerror?.(e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader();(async()=>{try{for(;;){let{done:t,value:n}=await e.read();if(t)return;let{event:r,data:i}=n;if(an(r))try{let e=await M(i);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e)}})().catch(e=>{t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)});return}let d=new N({message:`MCP HTTP Transport Error: Unexpected content type: ${u}`,statusCode:l.status,url:this.url.href});throw this.onerror?.(d),d}catch(e){throw t?.signal?.aborted||this.onerror?.(e),e}};await i()}getStandardRequestHeaders(e){let t={"Mcp-Method":e.method},n=e.params,r=e.method===`resources/read`?n?.uri:e.method===`tools/call`||e.method===`prompts/get`?n?.name:void 0;return typeof r==`string`&&(t[`Mcp-Name`]=en(r)),t}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){let{maxRetries:e}=this.reconnectionOptions;if(e>0&&this.inboundReconnectAttempts>=e){this.onerror?.(new N({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${e}) exceeded.`}));return}let t=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},t)}startInboundSse(e=!1,t){if(this.isModernProtocol()||this.inboundSseConnection)return;let n={close(){}};this.inboundSseConnection=n,this.openInboundSse(e,t).finally(()=>{this.inboundSseConnection===n&&(this.inboundSseConnection=void 0)}).catch(e=>{e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)})}async openInboundSse(e=!1,t){if(!this.isModernProtocol())try{let n=this.sessionId,r=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(r[`last-event-id`]=t);let i=await this.fetchFn(this.url.href,{method:`GET`,headers:r,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(i),i.status===401&&this.authProvider&&!e){let{resourceMetadataUrl:e,scope:n}=J(i);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,n)!==`AUTHORIZED`){let e=new V;this.onerror?.(e);return}}catch(e){this.onerror?.(e);return}return this.openInboundSse(!0,t)}if(i.status===405)return;if(!i.ok||!i.body){i.status===404&&n&&this.expireSessionId(n);let e=new N({message:`MCP HTTP Transport Error: GET SSE failed: ${i.status} ${i.statusText}`,statusCode:i.status,url:this.url.href});this.onerror?.(e);return}let a=i.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader(),o=async()=>{try{for(;;){let{done:e,value:t}=await a.read();if(e)return;let{event:n,data:r,id:i}=t;if(i&&(this.lastInboundEventId=i),an(n))try{let e=await M(r);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{a.cancel().catch(e=>{e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)})}},this.inboundReconnectAttempts=0;let c=this.inboundSseConnection;o().finally(()=>{this.inboundSseConnection===c&&(this.inboundSseConnection=void 0)}).catch(e=>{e instanceof Error&&e.name===`AbortError`||(this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function sn(e){switch(e.type){case`sse`:return new Zt(e);case`http`:return new on({...e,initialProtocolVersion:e.initialProtocolVersion??`2026-07-28`});default:throw new N({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function cn(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}const Q=`text/html;profile=mcp-app`,ln={extensions:{"io.modelcontextprotocol/ui":{mimeTypes:[Q]}}};function un(e){let n=e?.ui;return t(n)?n:void 0}const dn=y.array(y.unknown()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),fn=y.looseObject({connectDomains:dn,resourceDomains:dn,frameDomains:dn}),pn=y.looseObject({prefersBorder:y.boolean().optional().catch(void 0),csp:fn.optional().catch(void 0),permissions:y.record(y.string(),y.unknown()).optional().catch(void 0)});function mn(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=pn.safeParse(n);return r.success?r.data:void 0}function hn(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function gn(e){let t=un(e._meta),n=t?.resourceUri??e._meta?.[`ui/resourceUri`],r=hn(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function _n(e){let t=[],n=[];for(let r of e.tools){let e=gn(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function vn({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(l(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);let i=mn(n._meta);return{uri:e,mimeType:Q,html:r,meta:i}}async function yn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return vn({uri:t,resource:await e.readResource({uri:t,options:n})})}const bn=[-32020,-32021,-32022],xn=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function Sn(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function Cn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function wn(e){let t=Sn(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(N.isInstance(e)&&e.code!=null)return!1;let n=Cn(e);return n!=null&&xn.includes(n)}function Tn(e){if(e==null)return 0;if(!Number.isInteger(e))throw new N({message:`maxRetries must be an integer`});if(e<0)throw new N({message:`maxRetries must be >= 0`});return e}function En({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function Dn(e,t){return t==null?e:new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,a)},a=()=>{i(),r(t.reason)};if(t.aborted){a();return}t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{i(),n(e)}).catch(e=>{i(),r(e)})})}function On({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function kn(e){let t=new An(e);return await t.init(),t}var An=class{constructor({experimental_events:e,transport:t,name:n,clientName:r=n??`ai-sdk-mcp-client`,version:i=`1.0.0`,onUncaughtError:a,maxRetries:o,capabilities:s,initialInitializeResult:c,initializationOptions:l,protocolVersionDiscovery:u=!0}){if(this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:E,capabilities:{},serverInfo:this._serverInfo},this.protocolEra=`legacy`,this.protocolVersion=E,this.toolHeaderBindings=new Map,this.isClosed=!0,e?.adapter!==void 0&&(e.store!==void 0||e.validateArguments!==void 0))throw new N({message:`Configure experimental_events with either an adapter or a store, not both. Managed adapters own argument validation.`});if(e?.adapter!==void 0&&typeof e.adapter?.createAdapter!=`function`)throw new N({message:`experimental_events.adapter must implement createAdapter. Wrap bound operations with { createAdapter: () => operations }.`});let d=e?.adapter?.createAdapter({transport:cn(t)?{type:`custom`}:{type:t.type,url:t.url}});e?.adapter!==void 0&&rt(d),this.onUncaughtError=a,this.maxRetries=Tn(o),this.clientCapabilities=s??{},this.initialInitializeResult=c,this.initializationOptions=l,this.protocolVersionDiscovery=u,this.transport=cn(t)?t:sn(t),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new N({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:r,version:i};let f=nt({request:e=>this.request(e),store:e?.store,validateArguments:e?.validateArguments});this.experimental_events=d?it(d,f.list):f}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?En(this.initializationOptions):void 0,n=t==null?void 0:new AbortController,r=e==null?n?.signal:n==null?e:AbortSignal.any([e,n.signal]),i,a;t!=null&&(i=setTimeout(()=>{a=new N({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await Dn(this.transport.start(),r),this.initialInitializeResult){let e=le.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}if(this.protocolVersionDiscovery&&this.transport.supportsProtocolVersionDiscovery&&await this.tryProtocolDiscovery(r))return this;this.protocolEra=`legacy`,this.protocolVersion===T&&(this.protocolVersion=E),this.setTransportProtocolVersion(this.protocolVersion);let e=await this.request({request:{method:`initialize`,params:{protocolVersion:this.protocolVersion,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:le,options:{signal:r}});if(e===void 0)throw new N({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await Dn(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new N({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}async tryProtocolDiscovery(e){this.protocolEra=`modern`,this.protocolVersion=T,this.setTransportProtocolVersion(this.protocolVersion);try{let t=await this.request({request:{method:`server/discover`},resultSchema:ce,options:{signal:e,timeout:this.transport instanceof on?void 0:1e3}});return this.applyDiscoverResult(t),!0}catch(e){if(N.isInstance(e)&&e.code!=null&&bn.includes(e.code)){if(e.code!==-32022||!Array.isArray(e.data?.supported))throw e;let t=e.data.supported,n=ne.find(e=>e!==T&&t.includes(e));if(n===void 0)throw e;return this.protocolVersion=n,!1}return!1}}applyDiscoverResult(e){if(!e.supportedVersions.includes(this.protocolVersion))throw new N({message:`Server does not support the requested protocol version: ${this.protocolVersion}`});let t=e._meta?.[`io.modelcontextprotocol/serverInfo`];typeof t==`object`&&t&&`name`in t&&typeof t.name==`string`&&`version`in t&&typeof t.version==`string`&&(this._serverInfo=t),this.serverCapabilities=e.capabilities,this._serverInstructions=e.instructions,this._initializeResult={protocolVersion:this.protocolVersion,capabilities:e.capabilities,serverInfo:this._serverInfo,instructions:e.instructions}}setTransportProtocolVersion(e){this.transport.setProtocolVersion?this.transport.setProtocolVersion(e):this.transport.protocolVersion=e}applyInitializeResult(e){if(!ne.includes(e.protocolVersion))throw new N({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this.protocolEra=`legacy`,this.protocolVersion=e.protocolVersion,this._serverInfo=e.serverInfo,this._initializeResult=e,this.setTransportProtocolVersion(e.protocolVersion),this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}send(e,t){return t==null?this.transport.send(e):this.transport.send(e,t)}assertCapability(e){switch(e){case`initialize`:case`server/discover`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new N({message:`Server does not support completions`});break;case`events/list`:case`events/subscribe`:case`events/unsubscribe`:if(!this.serverCapabilities.events)throw new N({message:`Server does not support events`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new N({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new N({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new N({message:`Server does not support prompts`});break;default:throw new N({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new N({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:En(n),s=o==null?void 0:new AbortController,c=a==null?s?.signal:s==null?a:AbortSignal.any([a,s.signal]),l,u=this.requestMessageId++,d=this.protocolEra===`modern`?{...e,params:{...e.params,_meta:{...e.params?._meta,"io.modelcontextprotocol/protocolVersion":this.protocolVersion,"io.modelcontextprotocol/clientCapabilities":this.clientCapabilities,"io.modelcontextprotocol/clientInfo":this.clientInfo}}}:e,f={...d,jsonrpc:`2.0`,id:u},p=this.getToolRequestHeaders(d),m=()=>{i(new N({message:`Request was aborted`,cause:a?.reason}))},h=()=>{this.responseHandlers.delete(u),a?.removeEventListener(`abort`,_),l!=null&&clearTimeout(l)},g=e=>{h(),i(e)},_=()=>{h(),m()};this.responseHandlers.set(u,e=>{if(a?.aborted)return h(),m();if(e instanceof Error)return g(e);try{if(this.protocolEra===`modern`&&e.result.resultType==null)throw new N({message:`Modern MCP result is missing resultType`});if(e.result.resultType===`input_required`)throw new N({message:`Server requested additional input, but multi round-trip requests are not supported yet`});let n=t.parse(e.result);h(),r(n)}catch(e){let t=N.isInstance(e)?e:new N({message:`Failed to parse server response`,cause:e});g(t)}}),a?.addEventListener(`abort`,_,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new N({message:`Request timed out after ${o}ms`});s?.abort(e),g(e)},o));let v={...c==null?{}:{signal:c},...p==null?{}:{headers:p}};(Object.keys(v).length===0?this.send(f):this.send(f,v)).catch(e=>{g(e)})})}async listTools({params:e,options:t}={}){let n=await this.request({request:{method:`tools/list`,params:e},resultSchema:de,options:t});return this.prepareToolDefinitions(n,e?.cursor==null)}prepareToolDefinitions(e,t=!1){if(this.protocolEra!==`modern`||!this.transport.supportsMcpToolParameterHeaders)return e;t&&this.toolHeaderBindings.clear();let n=e.tools.filter(e=>{let t=tn(e.inputSchema);return t.success?(this.toolHeaderBindings.set(e.name,t.bindings),!0):(this.onError(new N({message:`Ignoring MCP tool "${e.name}": ${t.error}`})),!1)});return{...e,tools:n}}getToolRequestHeaders(e){if(this.protocolEra!==`modern`||e.method!==`tools/call`||typeof e.params?.name!=`string`)return;let t=this.toolHeaderBindings.get(e.params.name);if(t==null||t.length===0)return;let n=e.params.arguments;if(typeof n==`object`&&n&&!Array.isArray(n))try{return rn({bindings:t,args:n})}catch(t){throw new N({message:`Failed to create MCP headers for tool "${e.params.name}"`,cause:t})}}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():_({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:wn,createRetryError:({message:e,errors:t})=>new N({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:we,options:n})})}async listResourcesInternal({params:e,options:t}={}){return this.request({request:{method:`resources/list`,params:e},resultSchema:he,options:t})}async readResourceInternal({uri:e,options:t}){return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:De,options:t})}async listResourceTemplatesInternal({options:e}={}){return this.request({request:{method:`resources/templates/list`},resultSchema:Ee,options:e})}async listPromptsInternal({params:e,options:t}={}){return this.request({request:{method:`prompts/list`,params:e},resultSchema:Pe,options:t})}async getPromptInternal({name:e,args:t,options:n}){return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Ie,options:n})}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:je,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await Dn(this.send(n,t?.signal==null?void 0:{signal:t.signal}),t?.signal)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools(),n=[...t.tools];for(;t.nextCursor!=null;)t=await this.listTools({params:{cursor:t.nextCursor}}),n.push(...t.tools);return this.toolsFromDefinitions({...t,tools:n},{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){e=this.prepareToolDefinitions(e);let n=Object.create(null);for(let{name:i,title:a,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=a??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,i))continue;let u=this,d=t===`automatic`?void 0:t[i]?.outputSchema,p=gn({_meta:l}),h={clientName:this.clientInfo.name,toolName:i,...e==null?{}:{title:e},...c==null?{}:{annotations:{...c.title==null?{}:{title:c.title},...c.readOnlyHint==null?{}:{readOnlyHint:c.readOnlyHint},...c.destructiveHint==null?{}:{destructiveHint:c.destructiveHint},...c.idempotentHint==null?{}:{idempotentHint:c.idempotentHint},...c.openWorldHint==null?{}:{openWorldHint:c.openWorldHint}}},...p?.resourceUri==null?{}:{app:{...p,mimeType:Q}}},g=async(e,t)=>{t?.abortSignal?.throwIfAborted();let n=await u.callTool({name:i,arguments:e,options:{signal:t?.abortSignal}});return n.isError||d==null?n:u.extractStructuredContent(n,d,i)};n[i]={...t===`automatic`?m({description:o,title:e,metadata:h,inputSchema:r({...s,properties:s.properties??{},additionalProperties:!1}),execute:g,toModelOutput:On}):f({description:o,title:e,metadata:h,inputSchema:t[i].inputSchema,...d==null?{}:{outputSchema:d},execute:g,toModelOutput:On}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await d({value:e.structuredContent,schema:p(t)});if(!r.success)throw new N({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await u({text:r.text,schema:t});if(!e.success)throw new N({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new N({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==A)throw new N({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=A.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=Re.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new N({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){if(e.id==null){this.onError(new N({message:`Protocol error: Received a response without a message ID: ${JSON.stringify(e)}`}));return}let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new N({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new N({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};const jn=new TextEncoder;function $(e){if(typeof e!=`object`||!e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map($).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${$(t[e])}`).join(`,`)}}`}function Mn(e){return h(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function Nn(e){let t=await crypto.subtle.digest(`SHA-256`,jn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return Mn(new Uint8Array(t))}function Pn(e,t){return e!==t}const Fn=262144,In=b.object({type:b.literal(`verification`),challenge:b.string().min(1)});function Ln({store:e,validatePayload:t,onEvent:n,onGap:r,onTerminated:i,onError:a}){return async o=>{if(o.method!==`POST`)return new Response(null,{status:405,headers:{Allow:`POST`}});if(o.headers.get(`content-type`)?.split(`;`)[0].trim().toLowerCase()!==`application/json`)return new Response(null,{status:415});if(Number(o.headers.get(`content-length`))>Fn)return new Response(null,{status:413});try{let s=new URL(o.url).searchParams.get(tt),c=o.headers.get(`X-MCP-Subscription-Id`);if(!s||!c)return new Response(null,{status:401});let l=await e.get(s);if(!l||l.id!=null&&l.id!==c)return new Response(null,{status:401});let d=o.body?.getReader();if(!d)return new Response(null,{status:400});let f=[],p=0;try{for(;;){let{done:e,value:t}=await d.read();if(e)break;if(p+=t.byteLength,p>Fn)return await d.cancel(),new Response(null,{status:413});f.push(t)}}finally{d.releaseLock()}let m=new Uint8Array(p),h=0;for(let e of f)m.set(e,h),h+=e.length;if(!await Je({headers:o.headers,body:m,secret:l.delivery.secret}))return new Response(null,{status:401});let g=await u({text:new TextDecoder().decode(m)});if(!g.success)return new Response(null,{status:400});let _=g.value,v;if(typeof _==`object`&&_&&`type`in _){if(_.type===`verification`){let e=In.safeParse(_);return e.success?Response.json({challenge:e.data.challenge}):new Response(null,{status:400})}let e=et.safeParse(_);if(!e.success)return new Response(null,{status:400});v=e.data}if(l.id==null||l.status!==`active`&&v?.type!==`terminated`)return new Response(null,{status:503});let y={id:l.id,name:l.name,arguments:l.arguments,delivery:{mode:`webhook`,url:l.delivery.url},refreshBefore:l.refreshBefore??null};if(v){let t=o.headers.get(`webhook-id`);return v.type===`gap`?(await r?.({subscription:y,messageId:t,gap:v}),await e.update(l.key,{cursor:v.cursor,truncated:!0})):(await i?.({subscription:y,messageId:t,termination:v}),await e.delete(l.key)),new Response(null,{status:204})}if(l.refreshBefore!=null&&Date.parse(l.refreshBefore)<=Date.now())return new Response(null,{status:410});let b=$e.safeParse(_);if(!b.success||b.data.name!==l.name||b.data.eventId!==o.headers.get(`webhook-id`))return new Response(null,{status:400});try{await t?.({definition:l.definition,data:b.data.data})}catch(e){return a?.(e),new Response(null,{status:400})}return await n({subscription:y,event:b.data}),b.data.cursor!==void 0&&await e.update(l.key,{cursor:b.data.cursor}),new Response(null,{status:204})}catch(e){return a?.(e),new Response(null,{status:503})}}}export{vt as AuthorizationServerMismatchError,Re as ElicitResultSchema,A as ElicitationRequestSchema,N as MCPClientError,F as MCPClientOAuthError,Q as MCP_APP_MIME_TYPE,V as UnauthorizedError,Z as auth,kn as createMCPClient,kn as experimental_createMCPClient,Pn as detectMCPAppResourceDrift,Ln as experimental_createMCPEventWebhook,Nn as fingerprintMCPAppResource,ln as mcpAppClientCapabilities,yn as readMCPAppResource,_n as splitMCPAppTools,j as validateJSONRPCMessage};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{deepEquals,eventMatches,subagentCallMatches,testRegExp,toolCallMatches}from"#evals/match.js";const PASS={score:1},fail=(e,t)=>({score:0,message:e,metadata:t});function succeeded(){return{name:`succeeded`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?fail(`run parked on
|
|
1
|
+
import{deepEquals,eventMatches,subagentCallMatches,testRegExp,toolCallMatches}from"#evals/match.js";const PASS={score:1},fail=(e,t)=>({score:0,message:e,metadata:t});function succeeded(){return{name:`succeeded`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?fail(`run parked on unanswered input request(s)`):PASS:t}}}function parked(){return{name:`parked`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?PASS:fail(`expected the run to park on HITL input; it ended "${e.status}" with no pending requests`):t}}}function messageIncludes(e){return{name:`messageIncludes(${String(e)})`,evaluate(t){let n=joinCompletedMessages(t.events);return(typeof e==`string`?n.includes(e):testRegExp(e,n))?PASS:fail(`assistant messages did not include ${String(e)}; got: ${truncate(n)}`)}}}function calledTool(e,t={}){return validateCount(t.count),{name:`calledTool(${e})`,evaluate(n){let r=n.derived.toolCalls.filter(t=>t.name===e),i=r.filter(e=>toolCallMatches(e,t));if(matchesCount(t.count,i.length))return{score:1,metadata:{matchingCalls:i.length}};let a=r.length>0?`observed ${e} calls: ${r.map(e=>truncate(JSON.stringify(e.input))).join(`, `)}`:`observed tools: [${n.derived.toolCalls.map(e=>e.name).join(`, `)}]`,o;return o=t.count===void 0?`expected a matching call to "${e}"`:typeof t.count==`number`?`expected exactly ${t.count} matching call(s), found ${i.length}`:`expected matching call count to satisfy the count predicate, found ${i.length}`,fail(`${o}; ${a}`)}}}function loadedSkill(e,t={}){return validateCount(t.count),{name:`loadedSkill(${e})`,evaluate(n){let r=n.derived.skillLoads.filter(t=>t.skill===e).filter(e=>toolCallMatches(e,t));if(matchesCount(t.count,r.length))return{score:1,metadata:{matchingLoads:r.length}};let i=n.derived.skillLoads.map(e=>e.skill).join(`, `);return fail(`expected ${describeCount(t.count)} matching load(s) of "${e}", found ${r.length}; observed skill loads: [${i}]`)}}}function notCalledTool(e){return{name:`notCalledTool(${e})`,evaluate(t){let n=t.derived.toolCalls.filter(t=>t.name===e).length;return n===0?PASS:fail(`"${e}" was called ${n} time(s)`)}}}function toolOrder(e){return{name:`toolOrder(${e.join(` → `)})`,evaluate(t){let n=requestedTools(t.events).map(e=>e.name),r=missingOrderedName(e,n);return r===void 0?PASS:fail(`missing "${r.name}" after [${e.slice(0,r.cursor).join(`, `)}]; observed request order: [${n.join(`, `)}]`)}}}function usedNoTools(){return{name:`usedNoTools`,evaluate(e){let t=e.derived.toolCallCount;return t===0?PASS:fail(`expected no tool calls, got ${t}`,{toolCallCount:t})}}}function maxToolCalls(e){return validateCount(e),{name:`maxToolCalls(${e})`,evaluate(t){let n=t.derived.toolCallCount;return n<=e?PASS:fail(`expected at most ${e} tool calls, got ${n}`,{maxAllowed:e,toolCallCount:n})}}}function noFailedActions(){return{name:`noFailedActions`,evaluate(e){let t=e.events.filter(e=>e.type===`action.result`&&(e.data.status===`failed`||e.data.result.isError===!0));if(t.length===0)return PASS;let n=t.map(formatFailedActionResult);return fail(`${t.length} failed action(s): ${n.join(`; `)}`,{failedActions:t.map(e=>({callId:e.data.result.callId,error:e.data.error,kind:e.data.result.kind,output:e.data.result.output,status:e.data.status}))})}}}function calledSubagent(e,t={}){return validateCount(t.count),{name:`calledSubagent(${e})`,evaluate(n){let r=n.derived.subagentCalls.filter(t=>t.name===e),i=r.filter(e=>subagentCallMatches(e,t));if(matchesCount(t.count,i.length))return{score:1,metadata:{matchingCalls:i.length}};if(r.length===0){let t=n.derived.subagentCalls.map(e=>e.name);return fail(`subagent "${e}" was never called; observed: [${t.join(`, `)}]`,{observedSubagentCalls:n.derived.subagentCalls})}return fail(`subagent "${e}" was called but ${i.length} call(s) matched the constraints`,{observedSubagentCalls:r})}}}function eventsSatisfy(e,t){return{name:`eventsSatisfy(${e})`,evaluate(n){return t(n.events)?PASS:fail(`event predicate "${e}" did not hold`)}}}function typedEvent(e){return validateCount(e.count),{name:`event(${e.type})`,evaluate(t){let n=t.events.filter(t=>eventMatches(t,e));if(matchesCount(e.count,n.length))return{score:1,metadata:{matchingEvents:n.length}};let r=describeCount(e.count);return fail(`expected ${r} matching ${e.type} event(s), found ${n.length}; observed: [${t.events.map(e=>e.type).join(`, `)}]`)}}}function notEvent(e){return{name:`notEvent(${e.type})`,evaluate(t){let n=t.events.filter(t=>eventMatches(t,e));return n.length===0?PASS:fail(`expected no matching ${e.type} events, found ${n.length}`)}}}function eventOrder(e){for(let t of e)validateCount(t.count);return{name:`eventOrder(${e.map(e=>e.type).join(` → `)})`,evaluate(t){let n=-1;for(let r of e){let e=t.events.flatMap((e,t)=>eventMatches(e,r)?[t]:[]);if(!matchesCount(r.count,e.length)){let t=describeCount(r.count);return fail(`expected ${t} matching ${r.type} event(s), found ${e.length}`)}let i=e[0];if(i===void 0||i<=n)return fail(`event group ${r.type} did not occur after the previous group`);n=e[e.length-1]??n}return PASS}}}function outputEquals(e){return{name:`outputEquals`,evaluate(t){return deepEquals(t.output,e)?PASS:fail(`output ${truncate(JSON.stringify(t.output))} does not equal expected ${truncate(JSON.stringify(e))}`)}}}function outputMatches(e){return{name:`outputMatches`,async evaluate(t){let n=await e[`~standard`].validate(t.output);if(!(`issues`in n)||n.issues===void 0)return PASS;let r=n.issues.map(e=>e.message).join(`; `);return fail(`output failed schema validation: ${r}`)}}}function joinCompletedMessages(e){let t=[];for(let n of e)n.type===`message.completed`&&t.push(n.data.message);return t.join(`
|
|
2
2
|
`)}function failureDetail(e,t){return t===void 0?e:`${e} (code: ${t})`}function formatFailedActionResult(e){let{result:t,status:n}=e.data;return[actionResultLabel(t),`callId=${t.callId}`,`status=${n}`,t.isError===!0?`isError=true`:void 0,e.data.error?.message===void 0?void 0:`error=${e.data.error.message}`,`output=${truncate(formatUnknown(t.output))}`].filter(e=>e!==void 0).join(` `)}function actionResultLabel(e){switch(e.kind){case`tool-result`:return`tool-result:${e.toolName}`;case`subagent-result`:return`subagent-result:${e.subagentName}`;case`load-skill-result`:return`load-skill-result:${e.name}`}}function runFailure(e){if(e.status===`failed`)return fail(failureDetail(`run failed`,e.derived.failureCode));let t=e.events.find(e=>e.type===`turn.failed`||e.type===`step.failed`);return t===void 0?void 0:fail(`${t.type} (${t.data.code}): ${t.data.message}`)}function truncate(e,t=200){return e===void 0?`undefined`:e.length<=t?e:`${e.slice(0,t)}…`}function formatUnknown(e){if(e!==void 0){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}}function matchesCount(e,t){return e===void 0?t>0:typeof e==`function`?e(t):t===e}function describeCount(e){return e===void 0?`at least one`:typeof e==`function`?`a count satisfying the predicate`:`exactly ${e}`}function validateCount(e){if(e!==void 0&&typeof e!=`function`&&(typeof e!=`number`||!Number.isInteger(e)||e<0))throw TypeError(`Assertion count must be a non-negative integer or predicate; received ${String(e)}.`)}function missingOrderedName(e,t){let n=0;for(let r of t)if(r===e[n]&&(n+=1),n===e.length)return;let r=e[n];return r===void 0?void 0:{cursor:n,name:r}}function requestedTools(e){let t=[],n=new Set,append=(e,r)=>{n.has(e)||(n.add(e),t.push({callId:e,name:r}))};for(let t of e)if(t.type===`actions.requested`)for(let e of t.data.actions)e.kind===`tool-call`&&append(e.callId,e.toolName);else if(t.type===`input.requested`)for(let e of t.data.requests){let{action:t}=e;t.kind===`tool-call`&&append(t.callId,t.toolName)}return t}export{calledSubagent,calledTool,eventOrder,eventsSatisfy,loadedSkill,maxToolCalls,messageIncludes,noFailedActions,notCalledTool,notEvent,outputEquals,outputMatches,parked,succeeded,toolOrder,typedEvent,usedNoTools};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { MessageStreamEvent } from "#protocol/message.js";
|
|
2
|
+
import type { InputRequest } from "#shared/input.js";
|
|
2
3
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
3
4
|
import type { EveEvalDerivedFacts } from "#evals/types.js";
|
|
4
5
|
/**
|
|
@@ -33,3 +34,15 @@ export declare function latestUsage(events: readonly MessageStreamEvent[]): {
|
|
|
33
34
|
* (execution errors, transport failures).
|
|
34
35
|
*/
|
|
35
36
|
export declare function createEmptyDerivedFacts(): EveEvalDerivedFacts;
|
|
37
|
+
/**
|
|
38
|
+
* Input requests the last started turn raised, or a child relayed, that nobody
|
|
39
|
+
* has answered yet. A partial answer settles only the requests it answers; the
|
|
40
|
+
* rest stay open.
|
|
41
|
+
*
|
|
42
|
+
* An eval may watch how a request ends outside the session (for example
|
|
43
|
+
* through `t.target`), so two kinds of open request don't count: the session's
|
|
44
|
+
* own requests from earlier turns, and answered ones whose responder still has
|
|
45
|
+
* to sign in. Relayed requests keep the child's `turnId`, so they never match
|
|
46
|
+
* the parent's turn and are kept by `callId`/`taskId` instead.
|
|
47
|
+
*/
|
|
48
|
+
export declare function openInputRequests(events: readonly MessageStreamEvent[]): InputRequest[];
|