eve 0.15.4 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/src/chunks/{use-eve-agent-8X2UMr8q.js → use-eve-agent-BEOUv37s.js} +70 -0
- package/dist/src/chunks/{use-eve-agent-9ZNiSFMb.js → use-eve-agent-C25KOe9i.js} +70 -0
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/dev/tui/agent-header.js +1 -1
- package/dist/src/cli/dev/tui/blocks.js +8 -8
- package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.d.ts +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +10 -3
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +9 -1
- package/dist/src/cli/dev/tui/setup-commands.js +2 -2
- package/dist/src/cli/dev/tui/setup-flow.d.ts +8 -1
- package/dist/src/cli/dev/tui/setup-issues.d.ts +2 -14
- package/dist/src/cli/dev/tui/setup-issues.js +1 -1
- package/dist/src/cli/dev/tui/setup-panel.d.ts +14 -8
- package/dist/src/cli/dev/tui/setup-panel.js +3 -3
- package/dist/src/cli/dev/tui/terminal-renderer.js +6 -6
- package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
- package/dist/src/cli/dev/tui/tui.d.ts +2 -3
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/cli/dev/ui-options.d.ts +21 -0
- package/dist/src/cli/dev/ui-options.js +1 -0
- package/dist/src/cli/run.d.ts +6 -42
- package/dist/src/cli/run.js +2 -2
- package/dist/src/client/authorization-message-parts.d.ts +4 -0
- package/dist/src/client/authorization-message-parts.js +1 -0
- package/dist/src/client/index.d.ts +2 -2
- package/dist/src/client/message-reducer-types.d.ts +40 -1
- package/dist/src/client/message-reducer.d.ts +3 -5
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +71 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/harness/emission.d.ts +3 -3
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/stream-actions.d.ts +17 -0
- package/dist/src/harness/stream-actions.js +1 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +1 -0
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/host/start-development-server.d.ts +8 -0
- package/dist/src/internal/nitro/host/start-development-server.js +2 -2
- package/dist/src/internal/nitro/host.d.ts +1 -1
- package/dist/src/internal/nitro/host.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/dev-runtime-artifacts.d.ts +0 -3
- package/dist/src/internal/nitro/routes/dev-runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/routes/info.js +1 -1
- package/dist/src/internal/vercel/project-link.d.ts +10 -0
- package/dist/src/internal/vercel/project-link.js +1 -0
- package/dist/src/protocol/message.d.ts +14 -10
- package/dist/src/public/channels/auth.d.ts +26 -13
- package/dist/src/public/channels/auth.js +1 -1
- package/dist/src/react/index.d.ts +1 -1
- package/dist/src/runtime/agent/mock-model-adapter.d.ts +3 -2
- package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
- package/dist/src/runtime/connections/principal.d.ts +2 -0
- package/dist/src/runtime/connections/principal.js +1 -1
- package/dist/src/runtime/connections/types.d.ts +4 -1
- package/dist/src/runtime/framework-channels/index.d.ts +1 -6
- package/dist/src/runtime/framework-channels/index.js +1 -1
- package/dist/src/runtime/governance/auth/oidc.js +1 -1
- package/dist/src/runtime/governance/auth/types.d.ts +14 -10
- package/dist/src/runtime/governance/auth/vercel-oidc-project.d.ts +12 -0
- package/dist/src/runtime/governance/auth/vercel-oidc-project.js +1 -0
- package/dist/src/services/dev-client/client-options.d.ts +5 -0
- package/dist/src/services/dev-client/client-options.js +1 -1
- package/dist/src/services/dev-client/request-headers.d.ts +8 -0
- package/dist/src/services/dev-client/request-headers.js +1 -1
- package/dist/src/services/dev-client/runtime-artifacts.d.ts +1 -0
- package/dist/src/services/dev-client/runtime-artifacts.js +1 -1
- package/dist/src/services/dev-client.d.ts +8 -0
- package/dist/src/services/dev-client.js +1 -1
- package/dist/src/setup/boxes/add-connections.d.ts +10 -8
- package/dist/src/setup/boxes/add-connections.js +1 -1
- package/dist/src/setup/boxes/resolve-provisioning.d.ts +1 -0
- package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
- package/dist/src/setup/cli/channel-setup-prompter.d.ts +9 -2
- package/dist/src/setup/cli/channel-setup-prompter.js +1 -1
- package/dist/src/setup/cli/index.d.ts +1 -1
- package/dist/src/setup/cli/prompt-ui.d.ts +2 -0
- package/dist/src/setup/cli/select-state.js +1 -1
- package/dist/src/setup/connection-connector.d.ts +26 -52
- package/dist/src/setup/connection-connector.js +2 -1
- package/dist/src/setup/flows/channels.js +1 -1
- package/dist/src/setup/flows/connections.d.ts +36 -0
- package/dist/src/setup/flows/connections.js +3 -0
- package/dist/src/setup/flows/link.d.ts +1 -0
- package/dist/src/setup/flows/link.js +1 -1
- package/dist/src/setup/project-resolution.d.ts +2 -8
- package/dist/src/setup/project-resolution.js +1 -1
- package/dist/src/setup/prompter.d.ts +2 -0
- package/dist/src/setup/scaffold/connections/catalog.d.ts +10 -5
- package/dist/src/setup/scaffold/connections/catalog.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +11 -11
- package/dist/src/setup/scaffold/create/web-template.d.ts +2 -2
- package/dist/src/setup/scaffold/create/web-template.js +107 -3
- package/dist/src/setup/scaffold/index.d.ts +1 -1
- package/dist/src/setup/scaffold/index.js +1 -1
- package/dist/src/setup/scaffold/update/connections.d.ts +6 -0
- package/dist/src/setup/scaffold/update/connections.js +3 -3
- package/dist/src/svelte/index.d.ts +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.d.ts +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/eve.mdx +3 -3
- package/docs/concepts/sessions-runs-and-streaming.md +1 -1
- package/docs/guides/auth-and-route-protection.md +5 -5
- package/docs/guides/dev-tui.md +11 -4
- package/docs/guides/frontend/nextjs.mdx +2 -2
- package/docs/guides/frontend/nuxt.mdx +2 -2
- package/docs/guides/frontend/overview.mdx +34 -4
- package/docs/guides/frontend/sveltekit.mdx +2 -2
- package/docs/reference/cli.md +3 -1
- package/docs/tutorial/ship-it.mdx +1 -1
- package/docs/tutorial/team-playbooks.mdx +1 -1
- package/package.json +2 -2
- package/dist/src/internal/nitro/host/dev-rebuild-registry.d.ts +0 -5
- package/dist/src/internal/nitro/host/dev-rebuild-registry.js +0 -1
|
@@ -9,8 +9,8 @@ export { ClientSession } from "#client/session.js";
|
|
|
9
9
|
export type { EveAgentStoreCallbacks, EveAgentStoreInit, EveAgentStoreSnapshot, EveAgentStoreStatus, PrepareSend, } from "#client/eve-agent-store.js";
|
|
10
10
|
export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, ClientAuth, ClientOptions, ClientRedirectPolicy, HeadersValue, HealthResult, MessageResult, SendTurnInput, SendTurnPayload, SessionState, StreamOptions, TokenValue, } from "#client/types.js";
|
|
11
11
|
export type { EveAgentReducer, EveAgentReducerEvent, ClientInputRespondedEvent, ClientMessageFailedEvent, ClientMessageSubmittedEvent, } from "#client/reducer.js";
|
|
12
|
-
export type { EveMessageData, EveDynamicToolPart, EveMessageInputRequest, EveMessage, EveMessageMetadata, EveMessagePart, EveMessageToolMetadata, } from "#client/message-reducer.js";
|
|
13
|
-
export type { ActionResultStreamEvent, ActionsRequestedStreamEvent, AssistantStepFinishReason, CompactionCompletedStreamEvent, CompactionRequestedStreamEvent, AuthorizationCompletedStreamEvent, ConnectionAuthorizationOutcome, AuthorizationRequiredStreamEvent, HandleMessageStreamEvent, InputRequestedStreamEvent, MessageAppendedStreamEvent, MessageCompletedStreamEvent, MessageReceivedStreamEvent, ReasoningAppendedStreamEvent, ReasoningCompletedStreamEvent, ResultCompletedStreamEvent, SessionCompletedStreamEvent, SessionFailedStreamEvent, SessionStartedStreamEvent, SessionWaitingStreamEvent, StepCompletedStreamEvent, StepFailedStreamEvent, StepStartedStreamEvent, SubagentCalledStreamEvent, SubagentChildEventStreamEvent, SubagentCompletedStreamEvent, SubagentStartedStreamEvent, TurnCompletedStreamEvent, TurnFailedStreamEvent, TurnStartedStreamEvent, TurnFailureStreamEvent, } from "#protocol/message.js";
|
|
12
|
+
export type { EveAuthorizationChallenge, EveAuthorizationOutcome, EveAuthorizationPart, EveMessageData, EveDynamicToolPart, EveMessageInputRequest, EveMessage, EveMessageMetadata, EveMessagePart, EveMessageToolMetadata, } from "#client/message-reducer.js";
|
|
13
|
+
export type { ActionResultStreamEvent, ActionsRequestedStreamEvent, AssistantStepFinishReason, AuthorizationOutcome, CompactionCompletedStreamEvent, CompactionRequestedStreamEvent, AuthorizationCompletedStreamEvent, ConnectionAuthorizationOutcome, AuthorizationRequiredStreamEvent, HandleMessageStreamEvent, InputRequestedStreamEvent, MessageAppendedStreamEvent, MessageCompletedStreamEvent, MessageReceivedStreamEvent, ReasoningAppendedStreamEvent, ReasoningCompletedStreamEvent, ResultCompletedStreamEvent, SessionCompletedStreamEvent, SessionFailedStreamEvent, SessionStartedStreamEvent, SessionWaitingStreamEvent, StepCompletedStreamEvent, StepFailedStreamEvent, StepStartedStreamEvent, SubagentCalledStreamEvent, SubagentChildEventStreamEvent, SubagentCompletedStreamEvent, SubagentStartedStreamEvent, TurnCompletedStreamEvent, TurnFailedStreamEvent, TurnStartedStreamEvent, TurnFailureStreamEvent, } from "#protocol/message.js";
|
|
14
14
|
export { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";
|
|
15
15
|
export type { InputOption, InputRequest, InputResponse } from "#runtime/input/types.js";
|
|
16
16
|
export { inputOptionSchema, inputRequestSchema, inputResponseSchema, isInputRequest, isInputResponse, } from "#runtime/input/types.js";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { InputResponse } from "#runtime/input/types.js";
|
|
2
|
+
import type { AuthorizationOutcome } from "#protocol/message.js";
|
|
2
3
|
/**
|
|
3
4
|
* UIMessage-compatible eve message projection for chat and agent UIs.
|
|
4
5
|
*/
|
|
@@ -52,7 +53,45 @@ export type EveMessagePart = {
|
|
|
52
53
|
readonly type: "reasoning";
|
|
53
54
|
} | {
|
|
54
55
|
readonly type: "step-start";
|
|
55
|
-
} | EveDynamicToolPart;
|
|
56
|
+
} | EveAuthorizationPart | EveDynamicToolPart;
|
|
57
|
+
/**
|
|
58
|
+
* User-facing authorization challenge projected from an
|
|
59
|
+
* `authorization.required` stream event. These fields are safe to render in a
|
|
60
|
+
* browser UI; the model-facing tool output never receives the URL or code.
|
|
61
|
+
*/
|
|
62
|
+
export interface EveAuthorizationChallenge {
|
|
63
|
+
readonly displayName?: string;
|
|
64
|
+
readonly expiresAt?: string;
|
|
65
|
+
readonly instructions?: string;
|
|
66
|
+
readonly url?: string;
|
|
67
|
+
readonly userCode?: string;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Outcome of a completed user authorization flow.
|
|
71
|
+
*/
|
|
72
|
+
export type EveAuthorizationOutcome = AuthorizationOutcome;
|
|
73
|
+
/**
|
|
74
|
+
* An authorization prompt or result. The default reducer projects
|
|
75
|
+
* `authorization.required` into a pending part so browser chat UIs can render a
|
|
76
|
+
* sign-in affordance, then updates it when `authorization.completed` arrives.
|
|
77
|
+
*/
|
|
78
|
+
export type EveAuthorizationPart = {
|
|
79
|
+
readonly authorization?: EveAuthorizationChallenge;
|
|
80
|
+
readonly description: string;
|
|
81
|
+
readonly displayName: string;
|
|
82
|
+
readonly name: string;
|
|
83
|
+
readonly stepIndex: number;
|
|
84
|
+
readonly turnId: string;
|
|
85
|
+
readonly type: "authorization";
|
|
86
|
+
} & ({
|
|
87
|
+
readonly outcome?: never;
|
|
88
|
+
readonly reason?: never;
|
|
89
|
+
readonly state: "required";
|
|
90
|
+
} | {
|
|
91
|
+
readonly outcome: EveAuthorizationOutcome;
|
|
92
|
+
readonly reason?: string;
|
|
93
|
+
readonly state: "completed";
|
|
94
|
+
});
|
|
56
95
|
/**
|
|
57
96
|
* A tool-call part of an assistant message, following the AI SDK `dynamic-tool`
|
|
58
97
|
* convention. `state` advances through the lifecycle: `"input-streaming"` and
|
|
@@ -1,14 +1,12 @@
|
|
|
1
1
|
import type { EveAgentReducer } from "#client/reducer.js";
|
|
2
2
|
import type { EveMessageData } from "#client/message-reducer-types.js";
|
|
3
|
-
export type { EveMessageData, EveDynamicToolPart, EveMessageInputRequest, EveMessage, EveMessageMetadata, EveMessagePart, EveMessageToolMetadata, } from "#client/message-reducer-types.js";
|
|
3
|
+
export type { EveAuthorizationChallenge, EveAuthorizationOutcome, EveAuthorizationPart, EveMessageData, EveDynamicToolPart, EveMessageInputRequest, EveMessage, EveMessageMetadata, EveMessagePart, EveMessageToolMetadata, } from "#client/message-reducer-types.js";
|
|
4
4
|
/**
|
|
5
5
|
* Creates a UIMessage-compatible eve reducer for chat and agent UIs.
|
|
6
6
|
*
|
|
7
7
|
* The returned projection keeps eve-owned types while following the AI SDK
|
|
8
8
|
* `messages[].parts[]` rendering convention used by AI Elements. It projects
|
|
9
|
-
* text, reasoning, tool calls, tool results, tool approvals,
|
|
10
|
-
*
|
|
11
|
-
* custom reducers through the reducer event contract until eve has a dedicated
|
|
12
|
-
* message-part shape for authorization UI.
|
|
9
|
+
* text, reasoning, tool calls, tool results, tool approvals, submitted HITL
|
|
10
|
+
* responses, and authorization prompts.
|
|
13
11
|
*/
|
|
14
12
|
export declare function defaultMessageReducer(): EveAgentReducer<EveMessageData>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function defaultMessageReducer(){return{initial(){return{messages:[]}},reduce(e,t){return reduceMessageData(e,t)}}}function reduceMessageData(e,
|
|
1
|
+
import{createAuthorizationCompletedPart,createAuthorizationRequiredPart}from"#client/authorization-message-parts.js";function defaultMessageReducer(){return{initial(){return{messages:[]}},reduce(e,t){return reduceMessageData(e,t)}}}function reduceMessageData(e,n){switch(n.type){case`client.message.submitted`:return upsertMessage(e,{id:optimisticUserMessageId(n.data.submissionId),metadata:{optimistic:!0,status:`submitted`},parts:[{type:`text`,text:n.data.message}],role:`user`});case`client.message.failed`:return upsertMessage(e,{id:optimisticUserMessageId(n.data.submissionId),metadata:{optimistic:!0,status:`failed`},parts:[{type:`text`,text:n.data.message}],role:`user`});case`client.input.responded`:{let t=e;for(let e of n.data.responses)t=respondToInputRequest(t,e);return t}case`message.received`:return upsertMessage(e,{id:`${n.data.turnId}:user`,metadata:{status:`complete`,turnId:n.data.turnId},parts:[{type:`text`,text:n.data.message,state:`done`}],role:`user`});case`step.started`:return updateAssistantMessage(e,n.data.turnId,e=>ensureStepStartPart(e,n.data.stepIndex));case`reasoning.appended`:return updateAssistantMessage(e,n.data.turnId,e=>upsertPart(ensureStepStartPart(e,n.data.stepIndex),{state:`streaming`,stepIndex:n.data.stepIndex,text:n.data.reasoningSoFar,type:`reasoning`}));case`reasoning.completed`:return updateAssistantMessage(e,n.data.turnId,e=>upsertPart(ensureStepStartPart(e,n.data.stepIndex),{state:`done`,stepIndex:n.data.stepIndex,text:n.data.reasoning,type:`reasoning`}));case`actions.requested`:{let t=e;for(let e of n.data.actions){let r=normalizeActionRequest(e);t=updateAssistantMessage(t,n.data.turnId,t=>upsertPart(ensureStepStartPart(t,n.data.stepIndex),{input:`input`in e?e.input:void 0,state:`input-available`,stepIndex:n.data.stepIndex,toolCallId:e.callId,toolMetadata:createToolMetadata(r),toolName:r.toolName,type:`dynamic-tool`}))}return t}case`input.requested`:{let t=e;for(let e of n.data.requests){let r=normalizeActionRequest(e.action);t=updateAssistantMessage(t,n.data.turnId,t=>upsertPart(ensureStepStartPart(t,n.data.stepIndex),{approval:{id:e.requestId},input:e.action.input,state:`approval-requested`,stepIndex:n.data.stepIndex,toolCallId:e.action.callId,toolMetadata:createToolMetadata(r,{inputRequest:toMessageInputRequest(e)}),toolName:r.toolName,type:`dynamic-tool`}))}return t}case`action.result`:{let t=normalizeActionResult(n.data.result),r=findToolPart(e,n.data.result.callId),i=n.data.error?.code===`TOOL_EXECUTION_DENIED`,a=n.data.status===`failed`&&!i,o=r?.approval?.id??n.data.result.callId,s=mergeToolMetadata(r?.toolMetadata,createToolMetadata(t)),c={input:r?.input,stepIndex:n.data.stepIndex,toolCallId:n.data.result.callId,toolMetadata:s,toolName:r?.toolName??t.toolName,type:`dynamic-tool`},l;return l=i?{...c,approval:{approved:!1,id:o,reason:n.data.error?.message},state:`output-denied`}:a?{...c,approval:approvedApproval(r),errorText:n.data.error?.message??stringifyUnknown(n.data.result.output),state:`output-error`}:{...c,approval:approvedApproval(r),output:n.data.result.output,state:`output-available`},r===void 0?updateAssistantMessage(e,n.data.turnId,e=>upsertPart(ensureStepStartPart(e,n.data.stepIndex),l)):updateToolPart(e,n.data.result.callId,l)}case`authorization.required`:return updateAssistantMessage(e,n.data.turnId,e=>upsertPart(ensureStepStartPart(e,n.data.stepIndex),createAuthorizationRequiredPart(n)));case`authorization.completed`:return completeAuthorization(e,n);case`message.appended`:return updateAssistantMessage(e,n.data.turnId,e=>upsertPart(ensureStepStartPart(e,n.data.stepIndex),{state:`streaming`,stepIndex:n.data.stepIndex,text:n.data.messageSoFar,type:`text`}));case`message.completed`:return updateAssistantMessage(e,n.data.turnId,e=>n.data.message===null?removeTextPart(e,n.data.stepIndex):upsertPart(ensureStepStartPart(e,n.data.stepIndex),{state:`done`,stepIndex:n.data.stepIndex,text:n.data.message,type:`text`}));case`result.completed`:return updateAssistantMetadata(e,n.data.turnId,{result:n.data.result});case`turn.completed`:return updateAssistantMetadata(e,n.data.turnId,{status:`complete`});case`turn.failed`:case`session.failed`:return e;default:return e}}function respondToInputRequest(e,t){let n=findToolPartByApprovalId(e,t.requestId);if(!n)return e;let r={id:t.requestId};return t.text!==void 0&&(r.reason=t.text),updateToolPart(e,n.toolCallId,{approval:r,input:n.input,state:`approval-responded`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:mergeToolMetadata(n.toolMetadata,{eve:{inputResponse:t,kind:n.toolMetadata?.eve?.kind??`unknown`,name:n.toolMetadata?.eve?.name??n.toolName}}),toolName:n.toolName,type:`dynamic-tool`})}function updateAssistantMessage(e,t,n){return upsertMessage(e,n(e.messages.find(e=>e.role===`assistant`&&e.metadata?.turnId===t)??createAssistantMessage(t)))}function updateAssistantMetadata(e,t,n){return updateAssistantMessage(e,t,e=>({...e,metadata:{...e.metadata,...n}}))}function createAssistantMessage(e){return{id:`${e}:assistant`,metadata:{status:`streaming`,turnId:e},parts:[],role:`assistant`}}function ensureStepStartPart(e,t){let n=e.parts.filter(e=>e.type===`step-start`).length;if(n>t)return e;let r=t-n+1;return{...e,parts:[...e.parts,...Array.from({length:r},()=>({type:`step-start`}))]}}function upsertPart(e,t){let n=e.parts.findIndex(e=>partKey(e)===partKey(t)),r=n===-1?[...e.parts,t]:[...e.parts.slice(0,n),t,...e.parts.slice(n+1)];return{...e,metadata:{...e.metadata,status:t.type===`text`&&t.state===`done`?`complete`:`streaming`},parts:r}}function removeTextPart(e,t){let n=e.parts.filter(e=>e.type!==`text`||e.stepIndex!==t);return n.length===e.parts.length?e:{...e,metadata:{...e.metadata,status:`complete`},parts:n}}function updateToolPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`dynamic-tool`&&e.toolCallId===t));return r?upsertMessage(e,upsertPart(r,n)):e}function completeAuthorization(t,n){let r=findLatestPendingAuthorizationPart(t,n.data.name),i=createAuthorizationCompletedPart(n,r);return r===void 0?updateAssistantMessage(t,n.data.turnId,e=>upsertPart(ensureStepStartPart(e,n.data.stepIndex),i)):updateAuthorizationPart(t,r,i)}function updateAuthorizationPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e===t));return r?upsertMessage(e,upsertPart(r,n)):e}function findToolPart(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.toolCallId===t)return e}function findLatestPendingAuthorizationPart(e,t){for(let n=e.messages.length-1;n>=0;--n){let r=e.messages[n];if(r?.role===`assistant`)for(let e=r.parts.length-1;e>=0;--e){let n=r.parts[e];if(n?.type===`authorization`&&n.state===`required`&&n.name===t)return n}}}function findToolPartByApprovalId(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.approval?.id===t)return e}function partKey(e){switch(e.type){case`text`:return`text:${e.stepIndex??0}`;case`reasoning`:return`reasoning:${e.stepIndex??0}`;case`step-start`:return`step-start`;case`authorization`:return`authorization:${e.turnId}:${e.stepIndex}:${e.name}`;case`dynamic-tool`:return`dynamic-tool:${e.toolCallId}`}}function upsertMessage(e,t){let n=e.messages.findIndex(e=>e.id===t.id);return n===-1?{messages:[...e.messages,t]}:{messages:[...e.messages.slice(0,n),t,...e.messages.slice(n+1)]}}function toMessageInputRequest(e){return{allowFreeform:e.allowFreeform,display:e.display,options:e.options,prompt:e.prompt,requestId:e.requestId}}function createToolMetadata(e,t){return{eve:{inputRequest:t?.inputRequest,kind:e.kind,name:e.name}}}function mergeToolMetadata(e,t){let n=t.eve?.kind??e?.eve?.kind??`unknown`,r=t.eve?.name??e?.eve?.name??`unknown`;return{eve:{...e?.eve,...t.eve,inputRequest:t.eve?.inputRequest??e?.eve?.inputRequest,inputResponse:t.eve?.inputResponse??e?.eve?.inputResponse,kind:n,name:r}}}function approvedApproval(e){if(e?.approval?.id)return{approved:!0,id:e.approval.id,isAutomatic:e.approval.isAutomatic,reason:e.approval.reason}}function normalizeActionRequest(e){switch(e.kind){case`load-skill`:return{kind:`load-skill`,name:`load_skill`,toolName:`eve:load-skill`};case`tool-call`:return{kind:`tool-call`,name:e.toolName,toolName:e.toolName};case`subagent-call`:return{kind:`subagent-call`,name:e.subagentName,toolName:`eve:subagent:${e.subagentName}`};case`remote-agent-call`:return{kind:`subagent-call`,name:e.remoteAgentName,toolName:`eve:subagent:${e.remoteAgentName}`}}}function normalizeActionResult(e){switch(e.kind){case`load-skill-result`:return{kind:`load-skill`,name:e.name??`load_skill`,toolName:`eve:load-skill`};case`tool-result`:return{kind:`tool-call`,name:e.toolName,toolName:e.toolName};case`subagent-result`:return{kind:`subagent-call`,name:e.subagentName,toolName:`eve:subagent:${e.subagentName}`}}}function optimisticUserMessageId(e){return`optimistic:${e}:user`}function stringifyUnknown(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return`Action failed.`}}export{defaultMessageReducer};
|
|
@@ -273,6 +273,37 @@ type MCPTransportConfig = {
|
|
|
273
273
|
* @default 'error'
|
|
274
274
|
*/
|
|
275
275
|
redirect?: 'follow' | 'error';
|
|
276
|
+
/**
|
|
277
|
+
* Initial MCP session id to send with resumed Streamable HTTP requests after
|
|
278
|
+
* initialization.
|
|
279
|
+
* Only used by the HTTP transport.
|
|
280
|
+
*/
|
|
281
|
+
initialSessionId?: string;
|
|
282
|
+
/**
|
|
283
|
+
* Initial MCP protocol version to send before initialize negotiates one.
|
|
284
|
+
* Only used by the HTTP transport.
|
|
285
|
+
*/
|
|
286
|
+
initialProtocolVersion?: string;
|
|
287
|
+
/**
|
|
288
|
+
* Called when the Streamable HTTP server creates, changes, or clears the MCP
|
|
289
|
+
* session id.
|
|
290
|
+
* Only used by the HTTP transport.
|
|
291
|
+
*/
|
|
292
|
+
onSessionIdChange?: (sessionId: string | undefined) => void;
|
|
293
|
+
/**
|
|
294
|
+
* Called when a Streamable HTTP request returns 404 for an existing MCP
|
|
295
|
+
* session id. The transport clears the session id before reporting the
|
|
296
|
+
* underlying HTTP error.
|
|
297
|
+
* Only used by the HTTP transport.
|
|
298
|
+
*/
|
|
299
|
+
onSessionExpired?: (sessionId: string) => void;
|
|
300
|
+
/**
|
|
301
|
+
* Whether close() should send DELETE for the current MCP session id.
|
|
302
|
+
* Set to false when the application intends to reattach to the session later.
|
|
303
|
+
* Only used by the HTTP transport.
|
|
304
|
+
* @default true
|
|
305
|
+
*/
|
|
306
|
+
terminateSessionOnClose?: boolean;
|
|
276
307
|
/**
|
|
277
308
|
* Optional custom fetch implementation to use for HTTP requests.
|
|
278
309
|
* Useful for runtimes that need a request-local fetch.
|
|
@@ -337,6 +368,34 @@ declare const ClientCapabilitiesSchema: z.ZodObject<{
|
|
|
337
368
|
}, z.core.$loose>>;
|
|
338
369
|
}, z.core.$loose>;
|
|
339
370
|
type ClientCapabilities = z.infer<typeof ClientCapabilitiesSchema>;
|
|
371
|
+
declare const InitializeResultSchema: z.ZodObject<{
|
|
372
|
+
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
373
|
+
protocolVersion: z.ZodString;
|
|
374
|
+
capabilities: z.ZodObject<{
|
|
375
|
+
experimental: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
376
|
+
logging: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
377
|
+
prompts: z.ZodOptional<z.ZodObject<{
|
|
378
|
+
listChanged: z.ZodOptional<z.ZodBoolean>;
|
|
379
|
+
}, z.core.$loose>>;
|
|
380
|
+
resources: z.ZodOptional<z.ZodObject<{
|
|
381
|
+
subscribe: z.ZodOptional<z.ZodBoolean>;
|
|
382
|
+
listChanged: z.ZodOptional<z.ZodBoolean>;
|
|
383
|
+
}, z.core.$loose>>;
|
|
384
|
+
tools: z.ZodOptional<z.ZodObject<{
|
|
385
|
+
listChanged: z.ZodOptional<z.ZodBoolean>;
|
|
386
|
+
}, z.core.$loose>>;
|
|
387
|
+
elicitation: z.ZodOptional<z.ZodObject<{
|
|
388
|
+
applyDefaults: z.ZodOptional<z.ZodBoolean>;
|
|
389
|
+
}, z.core.$loose>>;
|
|
390
|
+
}, z.core.$loose>;
|
|
391
|
+
serverInfo: z.ZodObject<{
|
|
392
|
+
name: z.ZodString;
|
|
393
|
+
version: z.ZodString;
|
|
394
|
+
title: z.ZodOptional<z.ZodString>;
|
|
395
|
+
}, z.core.$loose>;
|
|
396
|
+
instructions: z.ZodOptional<z.ZodString>;
|
|
397
|
+
}, z.core.$loose>;
|
|
398
|
+
type InitializeResult = z.infer<typeof InitializeResultSchema>;
|
|
340
399
|
type PaginatedRequest = Request & {
|
|
341
400
|
params?: BaseParams & {
|
|
342
401
|
cursor?: string;
|
|
@@ -513,6 +572,12 @@ interface MCPClientConfig {
|
|
|
513
572
|
transport: MCPTransportConfig | MCPTransport;
|
|
514
573
|
/** Optional callback for uncaught errors */
|
|
515
574
|
onUncaughtError?: (error: unknown) => void;
|
|
575
|
+
/**
|
|
576
|
+
* Initialize result from a previous MCP session. When provided, the client
|
|
577
|
+
* starts the transport and reuses this metadata without sending a new
|
|
578
|
+
* initialize request.
|
|
579
|
+
*/
|
|
580
|
+
initialInitializeResult?: InitializeResult;
|
|
516
581
|
/** Optional client name, defaults to 'ai-sdk-mcp-client' */
|
|
517
582
|
clientName?: string;
|
|
518
583
|
/**
|
|
@@ -537,6 +602,11 @@ interface MCPClient {
|
|
|
537
602
|
* @see https://modelcontextprotocol.io/specification/2025-11-25/schema#implementation
|
|
538
603
|
*/
|
|
539
604
|
readonly serverInfo: Configuration;
|
|
605
|
+
/**
|
|
606
|
+
* The full initialize result used by this client, either from the server
|
|
607
|
+
* during initialization or from `initialInitializeResult`.
|
|
608
|
+
*/
|
|
609
|
+
readonly initializeResult: InitializeResult;
|
|
540
610
|
/**
|
|
541
611
|
* Optional instructions provided by the server during the initialize handshake.
|
|
542
612
|
*
|
|
@@ -651,4 +721,4 @@ declare function readMCPAppResource({ client, uri, options, }: {
|
|
|
651
721
|
options?: RequestOptions;
|
|
652
722
|
}): Promise<MCPAppResource>;
|
|
653
723
|
|
|
654
|
-
export { type CallToolResult, type Configuration, type ElicitResult, ElicitResultSchema, type ElicitationRequest, ElicitationRequestSchema, type JSONRPCError, type JSONRPCMessage, type JSONRPCNotification, type JSONRPCRequest, type JSONRPCResponse, type ListToolsResult, type MCPAppResource, type MCPAppResourceCSP, type MCPAppResourceMeta, type MCPClient, type ClientCapabilities as MCPClientCapabilities, type MCPClientConfig, type MCPTransport, MCP_APP_MIME_TYPE, type McpProviderMetadata, type OAuthAuthorizationServerInformation, type OAuthClientInformation, type OAuthClientMetadata, type OAuthClientProvider, type OAuthTokens, UnauthorizedError, auth, createMCPClient, type MCPClient as experimental_MCPClient, type ClientCapabilities as experimental_MCPClientCapabilities, type MCPClientConfig as experimental_MCPClientConfig, createMCPClient as experimental_createMCPClient, mcpAppClientCapabilities, readMCPAppResource, splitMCPAppTools };
|
|
724
|
+
export { type CallToolResult, type Configuration, type ElicitResult, ElicitResultSchema, type ElicitationRequest, ElicitationRequestSchema, type InitializeResult, type JSONRPCError, type JSONRPCMessage, type JSONRPCNotification, type JSONRPCRequest, type JSONRPCResponse, type ListToolsResult, type MCPAppResource, type MCPAppResourceCSP, type MCPAppResourceMeta, type MCPClient, type ClientCapabilities as MCPClientCapabilities, type MCPClientConfig, type MCPTransport, MCP_APP_MIME_TYPE, type McpProviderMetadata, type OAuthAuthorizationServerInformation, type OAuthClientInformation, type OAuthClientMetadata, type OAuthClientProvider, type OAuthTokens, UnauthorizedError, auth, createMCPClient, type MCPClient as experimental_MCPClient, type ClientCapabilities as experimental_MCPClientCapabilities, type MCPClientConfig as experimental_MCPClientConfig, createMCPClient as experimental_createMCPClient, mcpAppClientCapabilities, readMCPAppResource, splitMCPAppTools };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{$ as n,I as r,J as i,K as a,S as o,U as s,W as c,_t as l,at as u,bt as d,dt as f,ft as p,ht as m,i as ee,it as h,k as te,lt as g,mt as ne,n as re,ot as _,pt as v,rt as ie,ut as y,vt as b,y as ae}from"../../_chunks/workflow/dist-D7CzPkf8.js";const oe={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var se;se||={};let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ce(e){return(await x).getRandomValues(new Uint8Array(e))}async function le(e){let t=``;for(;t.length<e;){let n=await ce(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function ue(e){return await le(e)}async function de(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 fe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ue(e);return{code_verifier:t,code_challenge:await de(t)}}var pe=`vercel.ai.error.AI_MCPClientError`,me=Symbol.for(pe),he,ge,S=class extends (ge=e,he=me,ge){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[he]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,pe)}},C=`2025-11-25`,_e=[C,`2025-06-18`,`2025-03-26`,`2024-11-05`],ve=v(ne(m(),b())),ye=y({name:m(),version:m(),title:v(m())}),w=y({_meta:v(p({}).loose())}),T=w,be=p({method:m(),params:v(w)}),xe=p({applyDefaults:v(_())}).loose(),Se=y({experimental:v(p({}).loose()),logging:v(p({}).loose()),prompts:v(y({listChanged:v(_())})),resources:v(y({subscribe:v(_()),listChanged:v(_())})),tools:v(y({listChanged:v(_())})),elicitation:v(xe)});p({elicitation:v(xe)}).loose();var Ce=T.extend({protocolVersion:m(),capabilities:Se,serverInfo:ye,instructions:v(m())}),E=T.extend({nextCursor:v(m())}),we=p({name:m(),title:v(m()),description:v(m()),inputSchema:p({type:g(`object`),properties:v(p({}).loose())}).loose(),outputSchema:v(p({}).loose()),annotations:v(p({title:v(m())}).loose()),_meta:ve}).loose(),Te=E.extend({tools:h(we)}),D=p({type:g(`text`),text:m()}).loose(),O=p({type:g(`image`),data:u(),mimeType:m()}).loose(),Ee=p({uri:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m()),size:v(f())}).loose(),De=E.extend({resources:h(Ee)}),k=p({uri:m(),name:v(m()),title:v(m()),mimeType:v(m())}).loose(),A=k.extend({text:m()}),j=k.extend({blob:u()}),M=p({type:g(`resource`),resource:l([A,j])}).loose(),Oe=p({type:g(`resource_link`),uri:m(),name:m(),description:v(m()),mimeType:v(m())}).loose(),ke=T.extend({content:h(l([D,O,M,Oe])),structuredContent:v(b()),isError:_().default(!1).optional()}).or(T.extend({toolResult:b()})),Ae=p({uriTemplate:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m())}).loose(),je=T.extend({resourceTemplates:h(Ae)}),Me=T.extend({contents:h(l([A,j]))}),Ne=p({name:m(),description:v(m()),required:v(_())}).loose(),Pe=p({name:m(),title:v(m()),description:v(m()),arguments:v(h(Ne))}).loose(),Fe=E.extend({prompts:h(Pe)}),Ie=p({role:l([g(`user`),g(`assistant`)]),content:l([D,O,M,Oe])}).loose(),Le=T.extend({description:v(m()),messages:h(Ie)}),Re=w.extend({message:m(),requestedSchema:b()}),N=be.extend({method:g(`elicitation/create`),params:Re}),ze=T.extend({action:l([g(`accept`),g(`decline`),g(`cancel`)]),content:v(ne(m(),b()))}),P=`2.0`,Be=p({jsonrpc:g(P),id:l([m(),f().int()])}).merge(be).strict(),Ve=p({jsonrpc:g(P),id:l([m(),f().int()]),result:T}).strict(),He=p({jsonrpc:g(P),id:l([m(),f().int()]),error:p({code:f().int(),message:m(),data:v(b())})}).strict(),F=l([Be,p({jsonrpc:g(P)}).merge(p({method:m(),params:v(w)})).strict(),Ve,He]);async function I(e){return F.parse(await r({text:e}))}var Ue=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,L=m().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:oe.custom,message:`URL must be parseable`,fatal:!0}),d}).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`}),We=p({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:f().optional(),scope:m().optional(),refresh_token:m().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Ge=p({resource:m().url(),authorization_servers:h(L).optional(),jwks_uri:m().url().optional(),scopes_supported:h(m()).optional(),bearer_methods_supported:h(m()).optional(),resource_signing_alg_values_supported:h(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:_().optional(),authorization_details_types_supported:h(m()).optional(),dpop_signing_alg_values_supported:h(m()).optional(),dpop_bound_access_tokens_required:_().optional()}).passthrough(),R=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),code_challenge_methods_supported:h(m()),token_endpoint_auth_methods_supported:h(m()).optional(),token_endpoint_auth_signing_alg_values_supported:h(m()).optional()}).passthrough(),Ke=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,userinfo_endpoint:L.optional(),jwks_uri:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),subject_types_supported:h(m()),id_token_signing_alg_values_supported:h(m()),claims_supported:h(m()).optional(),token_endpoint_auth_methods_supported:h(m()).optional()}).passthrough().merge(R.pick({code_challenge_methods_supported:!0})),qe=p({client_id:m(),client_secret:m().optional(),client_id_issued_at:f().optional(),client_secret_expires_at:f().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Je=p({redirect_uris:h(L),token_endpoint_auth_method:m().optional(),grant_types:h(m()).optional(),response_types:h(m()).optional(),client_name:m().optional(),client_uri:L.optional(),logo_uri:L.optional(),scope:m().optional(),contacts:h(m()).optional(),tos_uri:L.optional(),policy_uri:m().optional(),jwks_uri:L.optional(),jwks:ie().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),Ye=p({error:m(),error_description:m().optional(),error_uri:m().optional()}),Xe=Je.merge(qe),Ze=`vercel.ai.error.AI_MCPClientOAuthError`,Qe=Symbol.for(Ze),$e,et,z=class extends (et=e,$e=Qe,et){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[$e]=!0}static isInstance(t){return e.hasMarker(t,Ze)}},B=class extends z{};B.errorCode=`server_error`;var V=class extends z{};V.errorCode=`invalid_client`;var H=class extends z{};H.errorCode=`invalid_grant`;var U=class extends z{};U.errorCode=`unauthorized_client`;var tt={[B.errorCode]:B,[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U};function nt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function W(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function rt({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 G=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function K(e){return new URL(e).href}function it(e,t){return{authorizationServerUrl:K(e),tokenEndpoint:K(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function at(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ot(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function st(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:K(e.authorization_server),tokenEndpoint:K(e.token_endpoint)}}async function ct({provider:e,clientInformation:t,tokens:n}){let r=st(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:K(i.authorizationServerUrl),tokenEndpoint:K(i.tokenEndpoint)}:st(t)}async function lt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(ot(t,n)),!0):!1}function ut(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new z({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function dt({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new z({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function q(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(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function ft(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function pt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function ht(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=ft(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await pt(o,a,n);return!r?.metadataUrl&&mt(s,i.pathname)&&(s=await pt(new URL(`/.well-known/${t}`,i),a,n)),s}async function gt(e,t,n=fetch){let r=await ht(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});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 Ge.parse(await r.json())}function _t(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}`;return 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}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function vt(e,t){if(e.issuer!==t)throw new z({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function yt(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=_t(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=R.parse(await i.json());return vt(e,a),e}else{let t=Ke.parse(await i.json());if(vt(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 bt(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 fe(),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`,W(o)),{authorizationUrl:l,codeVerifier:d}}function xt(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 St(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Ct(i,a,n);return;case`client_secret_post`:wt(i,a,r);return;case`none`:Tt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Ct(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 wt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Tt(e,t){t.set(`client_id`,e)}async function Y(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:i}=Ye.parse(await r({text:n}));return new(tt[e]||B)({message:t||``,cause:i})}catch(e){return new B({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Et(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):St(xt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,W(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Y(p);return We.parse(await p.json())}async function Dt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):St(xt(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,W(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Y(d);return We.parse({refresh_token:r,...await d.json()})}async function Ot(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 a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Y(a);return Xe.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof V||n instanceof U)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof H)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function kt(e,t,n){let r=nt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!rt({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 Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;ut(t,a);try{s=await gt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await kt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await yt(c,{fetchFn:o}),d=it(c,u),f=await Promise.resolve(e.clientInformation());if(!f){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`);f=ot(await Ot(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o}),d),await e.saveClientInformation(f)}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=await ct({provider:e,clientInformation:f});if(!t)throw new z({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await Et(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await ct({provider:e,clientInformation:f,tokens:p});t?dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Dt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof z)||e instanceof B))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:ee,codeVerifier:h}=await bt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await lt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new z({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(ee),`REDIRECT`}function At(e){return e===void 0||e===`message`}var jt=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??C};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return i(t,`ai-sdk/${Ue}`,o())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let r=async(i=!1)=>{var a,o,s,c;try{let c=await this.commonHeaders({Accept:`text/event-stream`}),l=await this.fetchFn(this.url.href,{headers:c,signal:this.abortController?.signal,redirect:this.redirectMode});if(l.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;return(a=this.onerror)==null||a.call(this,e),t(e)}}catch(e){return(o=this.onerror)==null||o.call(this,e),t(e)}return r(!0)}if(!l.ok||!l.body){let e=`MCP SSE Transport Error: ${l.status} ${l.statusText}`;l.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new S({message:e});return(s=this.onerror)==null||s.call(this,n),t(n)}let u=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),d=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await u.read();if(t){if(this.connected)throw this.connected=!1,new S({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new S({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(At(s))try{let e=await I(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new S({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>u.cancel()},d()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(c=this.onerror)==null||c.call(this,e),t(e)}};r()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new S({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new S({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}};function Mt(e){return e===void 0||e===`message`}var Nt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){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.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??C};if(this.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return i(t,`ai-sdk/${Ue}`,o())}authorizeOnce(e){return this.authProvider?(this.authPromise||=X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new S({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(r=!1)=>{var i,a,o,s,c,l;try{let l={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},u=await this.fetchFn(this.url.href,l),d=u.headers.get(`mcp-session-id`);if(d&&(this.sessionId=d),u.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(u);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new G}catch(e){throw(i=this.onerror)==null||i.call(this,e),e}return t(!0)}if(u.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!u.ok){let e=await u.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${u.status}): ${e}`;u.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new S({message:t,statusCode:u.status,url:this.url.href,responseBody:e??void 0});throw(a=this.onerror)==null||a.call(this,n),n}if(!(`id`in e))return;let f=u.headers.get(`content-type`)||``;if(f.includes(`application/json`)){let e=await u.json(),t=Array.isArray(e)?e.map(e=>F.parse(e)):[F.parse(e)];for(let e of t)(o=this.onmessage)==null||o.call(this,e);return}if(f.includes(`text/event-stream`)){if(!u.body){let e=new S({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:u.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,e),e}let e=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(Mt(a))try{let e=await I(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new S({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let p=new S({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`,statusCode:u.status,url:this.url.href});throw(c=this.onerror)==null||c.call(this,p),p}catch(e){throw(l=this.onerror)==null||l.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new S({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var r,i,a,o;try{let o=await this.commonHeaders({Accept:`text/event-stream`});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode}),c=s.headers.get(`mcp-session-id`);if(c&&(this.sessionId=c),s.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(s);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new G;(r=this.onerror)==null||r.call(this,e);return}}catch(e){(i=this.onerror)==null||i.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){let e=new S({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(a=this.onerror)==null||a.call(this,e);return}let l=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),u=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await l.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),Mt(i))try{let t=await I(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new S({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>l.cancel()},this.inboundReconnectAttempts=0,u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Pt(e){switch(e.type){case`sse`:return new jt(e);case`http`:return new Nt(e);default:throw new S({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Ft(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var It=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,Lt=`ui/resourceUri`,Rt={extensions:{[It]:{mimeTypes:[Q]}}};function zt(e){let n=e?.ui;return t(n)?n:void 0}function Bt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Vt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Ht(e){let t=zt(e._meta),n=t?.resourceUri??e._meta?.[Lt],r=Vt(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 Ut(e){let t=[],n=[];for(let r of e.tools){let e=Ht(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 Wt({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(ee(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Bt(n._meta)}}async function Gt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Wt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Kt=`1.0.0`;function qt({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 $(e){let t=new Jt(e);return await t.init(),t}var Jt=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Kt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},Ft(e)?this.transport=e:this.transport=Pt(e),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 S({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:C,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Ce});if(e===void 0)throw new S({message:`Server sent invalid initialize result`});if(!_e.includes(e.protocolVersion))throw new S({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new S({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new S({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new S({message:`Server does not support prompts`});break;default:throw new S({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new S({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new S({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new S({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:Te,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:ke,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:De,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Me,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:je,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Fe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Le,options:n})}catch(e){throw e}}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=i??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let u=this,d=t===`automatic`?void 0:t[r]?.outputSchema,f=Ht({_meta:l}),p={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...f?.resourceUri==null?{}:{app:{...f,mimeType:Q}}},m=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await u.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||d==null?i:u.extractStructuredContent(i,d,r)};n[r]={...t===`automatic`?ae({description:o,title:e,metadata:p,inputSchema:te({...s,properties:s.properties??{},additionalProperties:!1}),execute:m,toModelOutput:qt}):a({description:o,title:e,metadata:p,inputSchema:t[r].inputSchema,...d==null?{}:{outputSchema:d},execute:m,toModelOutput:qt}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await c({value:e.structuredContent,schema:re(t)});if(!r.success)throw new S({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 s({text:r.text,schema:t});if(!e.success)throw new S({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new S({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})}onElicitationRequest(e,t){if(e!==N)throw new S({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=N.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=ze.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 S({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new S({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new S({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{ze as ElicitResultSchema,N as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,G as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Rt as mcpAppClientCapabilities,Gt as readMCPAppResource,Ut as splitMCPAppTools};
|
|
1
|
+
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{$ as n,I as r,J as i,K as a,S as o,U as s,W as c,_t as l,at as u,bt as d,dt as f,ft as p,ht as m,i as ee,it as h,k as te,lt as g,mt as ne,n as re,ot as _,pt as v,rt as ie,ut as y,vt as b,y as ae}from"../../_chunks/workflow/dist-D7CzPkf8.js";const oe={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var se;se||={};let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ce(e){return(await x).getRandomValues(new Uint8Array(e))}async function le(e){let t=``;for(;t.length<e;){let n=await ce(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function ue(e){return await le(e)}async function de(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 fe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ue(e);return{code_verifier:t,code_challenge:await de(t)}}var pe=`vercel.ai.error.AI_MCPClientError`,me=Symbol.for(pe),he,ge,S=class extends (ge=e,he=me,ge){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[he]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,pe)}},C=`2025-11-25`,_e=[C,`2025-06-18`,`2025-03-26`,`2024-11-05`],ve=v(ne(m(),b())),ye=y({name:m(),version:m(),title:v(m())}),w=y({_meta:v(p({}).loose())}),T=w,be=p({method:m(),params:v(w)}),xe=p({applyDefaults:v(_())}).loose(),Se=y({experimental:v(p({}).loose()),logging:v(p({}).loose()),prompts:v(y({listChanged:v(_())})),resources:v(y({subscribe:v(_()),listChanged:v(_())})),tools:v(y({listChanged:v(_())})),elicitation:v(xe)});p({elicitation:v(xe)}).loose();var E=T.extend({protocolVersion:m(),capabilities:Se,serverInfo:ye,instructions:v(m())}),D=T.extend({nextCursor:v(m())}),Ce=p({name:m(),title:v(m()),description:v(m()),inputSchema:p({type:g(`object`),properties:v(p({}).loose())}).loose(),outputSchema:v(p({}).loose()),annotations:v(p({title:v(m())}).loose()),_meta:ve}).loose(),we=D.extend({tools:h(Ce)}),O=p({type:g(`text`),text:m()}).loose(),k=p({type:g(`image`),data:u(),mimeType:m()}).loose(),Te=p({uri:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m()),size:v(f())}).loose(),Ee=D.extend({resources:h(Te)}),A=p({uri:m(),name:v(m()),title:v(m()),mimeType:v(m())}).loose(),j=A.extend({text:m()}),M=A.extend({blob:u()}),De=p({type:g(`resource`),resource:l([j,M])}).loose(),Oe=p({type:g(`resource_link`),uri:m(),name:m(),description:v(m()),mimeType:v(m())}).loose(),ke=T.extend({content:h(l([O,k,De,Oe])),structuredContent:v(b()),isError:_().default(!1).optional()}).or(T.extend({toolResult:b()})),Ae=p({uriTemplate:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m())}).loose(),je=T.extend({resourceTemplates:h(Ae)}),Me=T.extend({contents:h(l([j,M]))}),Ne=p({name:m(),description:v(m()),required:v(_())}).loose(),Pe=p({name:m(),title:v(m()),description:v(m()),arguments:v(h(Ne))}).loose(),Fe=D.extend({prompts:h(Pe)}),Ie=p({role:l([g(`user`),g(`assistant`)]),content:l([O,k,De,Oe])}).loose(),Le=T.extend({description:v(m()),messages:h(Ie)}),Re=w.extend({message:m(),requestedSchema:b()}),N=be.extend({method:g(`elicitation/create`),params:Re}),ze=T.extend({action:l([g(`accept`),g(`decline`),g(`cancel`)]),content:v(ne(m(),b()))}),P=`2.0`,Be=p({jsonrpc:g(P),id:l([m(),f().int()])}).merge(be).strict(),Ve=p({jsonrpc:g(P),id:l([m(),f().int()]),result:T}).strict(),He=p({jsonrpc:g(P),id:l([m(),f().int()]),error:p({code:f().int(),message:m(),data:v(b())})}).strict(),F=l([Be,p({jsonrpc:g(P)}).merge(p({method:m(),params:v(w)})).strict(),Ve,He]);async function I(e){return F.parse(await r({text:e}))}var Ue=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,L=m().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:oe.custom,message:`URL must be parseable`,fatal:!0}),d}).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`}),We=p({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:f().optional(),scope:m().optional(),refresh_token:m().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Ge=p({resource:m().url(),authorization_servers:h(L).optional(),jwks_uri:m().url().optional(),scopes_supported:h(m()).optional(),bearer_methods_supported:h(m()).optional(),resource_signing_alg_values_supported:h(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:_().optional(),authorization_details_types_supported:h(m()).optional(),dpop_signing_alg_values_supported:h(m()).optional(),dpop_bound_access_tokens_required:_().optional()}).passthrough(),R=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),code_challenge_methods_supported:h(m()),token_endpoint_auth_methods_supported:h(m()).optional(),token_endpoint_auth_signing_alg_values_supported:h(m()).optional()}).passthrough(),Ke=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,userinfo_endpoint:L.optional(),jwks_uri:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),subject_types_supported:h(m()),id_token_signing_alg_values_supported:h(m()),claims_supported:h(m()).optional(),token_endpoint_auth_methods_supported:h(m()).optional()}).passthrough().merge(R.pick({code_challenge_methods_supported:!0})),qe=p({client_id:m(),client_secret:m().optional(),client_id_issued_at:f().optional(),client_secret_expires_at:f().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Je=p({redirect_uris:h(L),token_endpoint_auth_method:m().optional(),grant_types:h(m()).optional(),response_types:h(m()).optional(),client_name:m().optional(),client_uri:L.optional(),logo_uri:L.optional(),scope:m().optional(),contacts:h(m()).optional(),tos_uri:L.optional(),policy_uri:m().optional(),jwks_uri:L.optional(),jwks:ie().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),Ye=p({error:m(),error_description:m().optional(),error_uri:m().optional()}),Xe=Je.merge(qe),Ze=`vercel.ai.error.AI_MCPClientOAuthError`,Qe=Symbol.for(Ze),$e,et,z=class extends (et=e,$e=Qe,et){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[$e]=!0}static isInstance(t){return e.hasMarker(t,Ze)}},B=class extends z{};B.errorCode=`server_error`;var V=class extends z{};V.errorCode=`invalid_client`;var H=class extends z{};H.errorCode=`invalid_grant`;var U=class extends z{};U.errorCode=`unauthorized_client`;var tt={[B.errorCode]:B,[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U};function nt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function W(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function rt({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 G=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function K(e){return new URL(e).href}function it(e,t){return{authorizationServerUrl:K(e),tokenEndpoint:K(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function at(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ot(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function st(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:K(e.authorization_server),tokenEndpoint:K(e.token_endpoint)}}async function ct({provider:e,clientInformation:t,tokens:n}){let r=st(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:K(i.authorizationServerUrl),tokenEndpoint:K(i.tokenEndpoint)}:st(t)}async function lt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(ot(t,n)),!0):!1}function ut(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new z({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function dt({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new z({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function q(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(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function ft(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function pt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function ht(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=ft(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await pt(o,a,n);return!r?.metadataUrl&&mt(s,i.pathname)&&(s=await pt(new URL(`/.well-known/${t}`,i),a,n)),s}async function gt(e,t,n=fetch){let r=await ht(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});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 Ge.parse(await r.json())}function _t(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}`;return 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}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function vt(e,t){if(e.issuer!==t)throw new z({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function yt(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=_t(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=R.parse(await i.json());return vt(e,a),e}else{let t=Ke.parse(await i.json());if(vt(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 bt(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 fe(),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`,W(o)),{authorizationUrl:l,codeVerifier:d}}function xt(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 St(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Ct(i,a,n);return;case`client_secret_post`:wt(i,a,r);return;case`none`:Tt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Ct(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 wt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Tt(e,t){t.set(`client_id`,e)}async function Y(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:i}=Ye.parse(await r({text:n}));return new(tt[e]||B)({message:t||``,cause:i})}catch(e){return new B({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Et(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):St(xt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,W(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Y(p);return We.parse(await p.json())}async function Dt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):St(xt(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,W(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Y(d);return We.parse({refresh_token:r,...await d.json()})}async function Ot(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 a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Y(a);return Xe.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof V||n instanceof U)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof H)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function kt(e,t,n){let r=nt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!rt({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 Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;ut(t,a);try{s=await gt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await kt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await yt(c,{fetchFn:o}),d=it(c,u),f=await Promise.resolve(e.clientInformation());if(!f){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`);f=ot(await Ot(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o}),d),await e.saveClientInformation(f)}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=await ct({provider:e,clientInformation:f});if(!t)throw new z({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await Et(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await ct({provider:e,clientInformation:f,tokens:p});t?dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Dt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof z)||e instanceof B))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:ee,codeVerifier:h}=await bt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await lt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new z({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(ee),`REDIRECT`}function At(e){return e===void 0||e===`message`}var jt=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??C};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return i(t,`ai-sdk/${Ue}`,o())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let r=async(i=!1)=>{var a,o,s,c;try{let c=await this.commonHeaders({Accept:`text/event-stream`}),l=await this.fetchFn(this.url.href,{headers:c,signal:this.abortController?.signal,redirect:this.redirectMode});if(l.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;return(a=this.onerror)==null||a.call(this,e),t(e)}}catch(e){return(o=this.onerror)==null||o.call(this,e),t(e)}return r(!0)}if(!l.ok||!l.body){let e=`MCP SSE Transport Error: ${l.status} ${l.statusText}`;l.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new S({message:e});return(s=this.onerror)==null||s.call(this,n),t(n)}let u=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),d=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await u.read();if(t){if(this.connected)throw this.connected=!1,new S({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new S({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(At(s))try{let e=await I(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new S({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>u.cancel()},d()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(c=this.onerror)==null||c.call(this,e),t(e)}};r()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new S({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new S({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}};function Mt(e){return e===void 0||e===`message`}var Nt=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.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,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??C};if(t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return i(n,`ai-sdk/${Ue}`,o())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e){return this.authProvider?(this.authPromise||=X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new S({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.terminateSessionOnClose&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({base:{}});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(r=!1)=>{var i,a,o,s,c,l;try{let l=`method`in e&&e.method===`initialize`,u=l?void 0:this.sessionId,d={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`},includeSessionId:!l}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},f=await this.fetchFn(this.url.href,d);if(this.applySessionIdFromResponse(f),f.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(f);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new G}catch(e){throw(i=this.onerror)==null||i.call(this,e),e}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){let e=await f.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${e}`;f.status===404&&(u?(this.expireSessionId(u),t+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new S({message:t,statusCode:f.status,url:this.url.href,responseBody:e??void 0});throw(a=this.onerror)==null||a.call(this,n),n}if(!(`id`in e))return;let p=f.headers.get(`content-type`)||``;if(p.includes(`application/json`)){let e=await f.json(),t=Array.isArray(e)?e.map(e=>F.parse(e)):[F.parse(e)];for(let e of t)(o=this.onmessage)==null||o.call(this,e);return}if(p.includes(`text/event-stream`)){if(!f.body){let e=new S({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:f.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,e),e}let e=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(Mt(a))try{let e=await I(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new S({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let m=new S({message:`MCP HTTP Transport Error: Unexpected content type: ${p}`,statusCode:f.status,url:this.url.href});throw(c=this.onerror)==null||c.call(this,m),m}catch(e){throw(l=this.onerror)==null||l.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new S({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var r,i,a,o;try{let o=this.sessionId,s=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(s[`last-event-id`]=t);let c=await this.fetchFn(this.url.href,{method:`GET`,headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(c),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(c);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new G;(r=this.onerror)==null||r.call(this,e);return}}catch(e){(i=this.onerror)==null||i.call(this,e);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){c.status===404&&o&&this.expireSessionId(o);let e=new S({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`,statusCode:c.status,url:this.url.href});(a=this.onerror)==null||a.call(this,e);return}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),u=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await l.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),Mt(i))try{let t=await I(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new S({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>l.cancel()},this.inboundReconnectAttempts=0,u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Pt(e){switch(e.type){case`sse`:return new jt(e);case`http`:return new Nt(e);default:throw new S({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Ft(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var It=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,Lt=`ui/resourceUri`,Rt={extensions:{[It]:{mimeTypes:[Q]}}};function zt(e){let n=e?.ui;return t(n)?n:void 0}function Bt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Vt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Ht(e){let t=zt(e._meta),n=t?.resourceUri??e._meta?.[Lt],r=Vt(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 Ut(e){let t=[],n=[];for(let r of e.tools){let e=Ht(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 Wt({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(ee(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Bt(n._meta)}}async function Gt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Wt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Kt=`1.0.0`;function qt({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 $(e){let t=new Jt(e);return await t.init(),t}var Jt=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Kt,onUncaughtError:i,capabilities:a,initialInitializeResult:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:C,capabilities:{},serverInfo:this._serverInfo},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},this.initialInitializeResult=o,Ft(e)?this.transport=e:this.transport=Pt(e),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 S({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){try{if(await this.transport.start(),this.isClosed=!1,this.initialInitializeResult){let e=E.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}let e=await this.request({request:{method:`initialize`,params:{protocolVersion:C,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:E});if(e===void 0)throw new S({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}applyInitializeResult(e){if(!_e.includes(e.protocolVersion))throw new S({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this._initializeResult=e,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new S({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new S({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new S({message:`Server does not support prompts`});break;default:throw new S({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new S({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new S({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new S({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:we,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:ke,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Ee,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Me,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:je,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Fe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Le,options:n})}catch(e){throw e}}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=i??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let u=this,d=t===`automatic`?void 0:t[r]?.outputSchema,f=Ht({_meta:l}),p={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...f?.resourceUri==null?{}:{app:{...f,mimeType:Q}}},m=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await u.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||d==null?i:u.extractStructuredContent(i,d,r)};n[r]={...t===`automatic`?ae({description:o,title:e,metadata:p,inputSchema:te({...s,properties:s.properties??{},additionalProperties:!1}),execute:m,toModelOutput:qt}):a({description:o,title:e,metadata:p,inputSchema:t[r].inputSchema,...d==null?{}:{outputSchema:d},execute:m,toModelOutput:qt}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await c({value:e.structuredContent,schema:re(t)});if(!r.success)throw new S({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 s({text:r.text,schema:t});if(!e.success)throw new S({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new S({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})}onElicitationRequest(e,t){if(e!==N)throw new S({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=N.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=ze.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 S({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new S({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new S({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{ze as ElicitResultSchema,N as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,G as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Rt as mcpAppClientCapabilities,Gt as readMCPAppResource,Ut as splitMCPAppTools};
|
|
@@ -109,9 +109,9 @@ interface StreamActionEmissionOptions {
|
|
|
109
109
|
* Consumes the AI SDK `fullStream` and emits real-time text and reasoning
|
|
110
110
|
* events.
|
|
111
111
|
*
|
|
112
|
-
* Emits local
|
|
113
|
-
*
|
|
114
|
-
*
|
|
112
|
+
* Emits local tool events in source order. Provider calls that arrive in one
|
|
113
|
+
* stream batch into one request event before their first result. A result
|
|
114
|
+
* without a streamed call resumes a call from an earlier step.
|
|
115
115
|
*/
|
|
116
116
|
export declare function emitStreamContent(emitFn: HarnessEmitFn, state: HarnessEmissionState, fullStream: AsyncIterable<TextStreamPart<ToolSet>>, options?: StreamActionEmissionOptions): Promise<EmittedStreamContent>;
|
|
117
117
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toError}from"#shared/errors.js";import{createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{createRuntimeActionRequestFromToolCall,resolveToolCallInputObject}from"#harness/runtime-actions.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";const HARNESS_EMISSION_STATE_KEY=`eve.harness.emission`,DEFAULT_EMISSION_STATE={sessionStarted:!1,sequence:0,stepIndex:0,turnId:``};function getHarnessEmissionState(e){return e?.[HARNESS_EMISSION_STATE_KEY]??DEFAULT_EMISSION_STATE}function isHarnessBetweenTurns(e){return getHarnessEmissionState(e.state).turnId===``}function setHarnessEmissionState(e,t){return{...e,state:{...e.state,[HARNESS_EMISSION_STATE_KEY]:t}}}async function emitTurnPreamble(e,t,n,r){let i=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r})),await e(createTurnStartedEvent({sequence:n.sequence,turnId:i})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:i})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:i}}async function emitStepStarted(e,t,n){await e(createStepStartedEvent({sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),n)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId})),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(a,o,s,c){let l=``,u=``,d=`stop`,f,p=new Set,m=new Set,h=new Set,g=new Set,_=[],
|
|
1
|
+
import{toError}from"#shared/errors.js";import{createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{createRuntimeActionRequestFromToolCall,resolveToolCallInputObject}from"#harness/runtime-actions.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";const HARNESS_EMISSION_STATE_KEY=`eve.harness.emission`,DEFAULT_EMISSION_STATE={sessionStarted:!1,sequence:0,stepIndex:0,turnId:``};function getHarnessEmissionState(e){return e?.[HARNESS_EMISSION_STATE_KEY]??DEFAULT_EMISSION_STATE}function isHarnessBetweenTurns(e){return getHarnessEmissionState(e.state).turnId===``}function setHarnessEmissionState(e,t){return{...e,state:{...e.state,[HARNESS_EMISSION_STATE_KEY]:t}}}async function emitTurnPreamble(e,t,n,r){let i=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r})),await e(createTurnStartedEvent({sequence:n.sequence,turnId:i})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:i})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:i}}async function emitStepStarted(e,t,n){await e(createStepStartedEvent({sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),n)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId})),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(a,o,s,c){let l=``,u=``,d=`stop`,f,p=new Set,m=new Set,h=new Set,g=new Set,_=createProviderStreamActionBatch({emitFn:a,state:o}),v=new Set,y=[],b=[],flushCurrentMessage=async()=>{u.length!==0&&(await a(createMessageCompletedEvent({finishReason:`tool-calls`,message:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),u=``)},emitActionRequest=async e=>{m.has(e.callId)||(u.trim().length>0&&await flushCurrentMessage(),m.add(e.callId),await a(createActionsRequestedEvent({actions:[e],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},collectProviderToolCall=async e=>{g.has(e.toolCallId)||(g.add(e.toolCallId),!m.has(e.toolCallId)&&(m.add(e.toolCallId),u.trim().length>0&&await flushCurrentMessage(),_.observe({callId:e.toolCallId,input:resolveToolCallInputObject(e.input,{callId:e.toolCallId,toolName:e.toolName}),kind:`tool-call`,toolName:e.toolName})))},emitActionResult=async e=>{h.has(e.callId)||(h.add(e.callId),await a(createActionResultEvent({result:e,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},emitToolCall=async e=>{if(!(c===void 0||e.invalid===!0||c.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:c.tools}))}catch(e){if(e instanceof TypeError)return;throw e}};for await(let t of s)if(f===void 0)switch(t.type){case`reasoning-delta`:await _.flush(),l+=t.text,await a(createReasoningAppendedEvent({reasoningDelta:t.text,reasoningSoFar:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`text-delta`:await _.flush(),l.trim().length>0&&(await a(createReasoningCompletedEvent({reasoning:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),l=``),u+=t.text,await a(createMessageAppendedEvent({messageDelta:t.text,messageSoFar:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`tool-call`:{let e=t;p.add(e.toolCallId),e.providerExecuted===!0?await collectProviderToolCall(e):(await _.flush(),await emitToolCall(e));break}case`tool-result`:{let e=t;if(e.preliminary===!0)break;if(e.providerExecuted===!0){await collectProviderToolCall({input:`input`in e?e.input:void 0,toolCallId:e.toolCallId,toolName:e.toolName}),await _.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(e));break}if(p.has(t.toolCallId)){if(isInlineAuthorizationToolResult(e))break;m.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(e)),v.add(t.toolCallId));break}if(await _.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(e)){v.add(t.toolCallId),y.push(e);break}await emitActionResult(createRuntimeToolResultFromStepResult(e)),v.add(t.toolCallId);let n=e.output;b.push({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n??null}});break}case`tool-error`:{let n=t;n.providerExecuted===!0?(await collectProviderToolCall(n),await _.flush(),await emitActionResult(createRuntimeToolResultFromValue({callId:n.toolCallId,isError:!0,output:toError(n.error),toolName:n.toolName}))):m.has(n.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromValue({callId:n.toolCallId,isError:!0,output:toError(n.error),toolName:n.toolName})),v.add(n.toolCallId));break}case`finish-step`:d=normalizeAssistantStepFinishReason(t.finishReason),await _.flush();break;case`error`:f=toError(t.error);break;default:break}if(await _.flush(),f!==void 0)throw f;return l.trim().length>0&&await a(createReasoningCompletedEvent({reasoning:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),d!==`tool-calls`&&hasEmptyDeliverySentinel(u)?await a(createMessageCompletedEvent({finishReason:d,message:null,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})):u.trim().length>0&&await a(createMessageCompletedEvent({finishReason:d,message:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{emittedActionCallIds:m,handledInlineToolResultCallIds:v,inlineAuthorizationResults:y,inlineToolResultParts:b}}function isInlineAuthorizationToolResult(e){if(isPendingAuthorizationToolOutput(e.output))return!0;let t=contextStorage.getStore();if(t===void 0)return!1;let n=readToolInterrupt(t,e.toolCallId);return n!==void 0&&isAuthorizationSignal(n)}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
|
|
2
|
+
import type { HarnessEmitFn } from "#harness/types.js";
|
|
3
|
+
interface ActionEventCoordinates {
|
|
4
|
+
readonly sequence: number;
|
|
5
|
+
readonly stepIndex: number;
|
|
6
|
+
readonly turnId: string;
|
|
7
|
+
}
|
|
8
|
+
interface ProviderStreamActionBatch {
|
|
9
|
+
flush(): Promise<void>;
|
|
10
|
+
observe(action: RuntimeToolCallActionRequest): void;
|
|
11
|
+
}
|
|
12
|
+
/** Batches provider-managed calls that arrive in one streamed model response. */
|
|
13
|
+
export declare function createProviderStreamActionBatch(input: {
|
|
14
|
+
readonly emitFn: HarnessEmitFn;
|
|
15
|
+
readonly state: ActionEventCoordinates;
|
|
16
|
+
}): ProviderStreamActionBatch;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createActionsRequestedEvent}from"#protocol/message.js";function createProviderStreamActionBatch(t){let n=new Map,r=Promise.resolve(),i,a,o,emitPendingActions=async()=>{if(n.size===0)return;let r=[...n.values()];n.clear(),await t.emitFn(createActionsRequestedEvent({actions:r,sequence:t.state.sequence,stepIndex:t.state.stepIndex,turnId:t.state.turnId}))},scheduleFlush=()=>{if(a!==void 0)return;let e,t=new Promise(t=>{e=t});o=e,a=setTimeout(()=>{a=void 0,o=void 0,e?.()},0),r=r.then(()=>t).then(emitPendingActions).catch(e=>{i??=e})};return{observe(e){n.set(e.callId,e),scheduleFlush()},async flush(){if(a!==void 0){clearTimeout(a),a=void 0;let e=o;o=void 0,e?.()}if(await r,i!==void 0)throw i;await emitPendingActions()}}}export{createProviderStreamActionBatch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.16.0`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,
|
|
1
|
+
import{EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH}from"#protocol/routes.js";import{resolvePackageRoot,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,join,relative}from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{isVercelBuildEnvironment}from"#internal/application/paths.js";import{normalizeEsmImportSpecifier,stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{computeChannelRouteRegistrations,registerChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";function includesApplicationRoutes(e){return e===`all`||e===`app`}function includesWorkflowBundles(e){return includesWorkflowRoute(e)}function includesWorkflowRoute(e){return e===`all`||e===`flow`}function registerHandler(e,t){let n=`#eve-route-handler/${t.method??`ALL`} ${t.route}`,r=stringifyEsmImportSpecifier(t.handlerPath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import handler from ${r};`,`export default handler;`].join(`
|
|
2
2
|
`)}function resolveNitroWorkflowBuildDirectory(e){return join(e.options.buildDir,`workflow`)}function createRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function addWorkflowFileHandler(e,t){let n=join(resolveNitroWorkflowBuildDirectory(e),`${t.bundleName}-handler.mjs`),r=dirname(n),i=createRelativeImportSpecifier(r,t.bundlePath),a=(t.directHandlers??[]).map(e=>{let t=createRelativeImportSpecifier(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await mkdir(r,{recursive:!0}),await writeFile(n,buildWorkflowFileHandlerSource({bundlePath:i,directHandlers:a,runtimeImportSpecifier:t.runtimeImportSpecifier})),e.options.handlers.push({handler:n,route:t.route})}function buildWorkflowFileHandlerSource(e){let t=[`// Generated by eve. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__eveWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);t.push(`import { getWorld as __eveGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __eveWorkflowWorld = await __eveGetWorkflowWorld();`,` if (typeof __eveWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __eveWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[eve] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
|
|
3
3
|
`)}function addFrameworkVirtualHandler(e,t){let n=`#eve-route${t.route}`,r=stringifyEsmImportSpecifier(t.modulePath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import { ${t.handlerExport} } from ${r};`,`export default async (event) => ${t.handlerExport}(${t.args}, event.req);`].join(`
|
|
4
|
-
`)}async function configureNitroRoutes(o,s,c){if(includesWorkflowBundles(c.surface)){let e=resolvePackageRoot(),t=new WorkflowBundleBuilder({agentName:s.compileResult.manifest.config.name,appRoot:s.appRoot,compiledArtifactsBootstrapPath:s.compiledArtifacts.bootstrapPath,outDir:s.workflowBuildDir,rootDir:e,watch:o.options.dev}),n=Promise.resolve(),buildWorkflowArtifacts=async()=>{await t.build({nitroStepOutfile:includesWorkflowRoute(c.surface)?join(resolveNitroWorkflowBuildDirectory(o),`steps.mjs`):void 0,nitroWorkflowOutfile:o.options.dev&&includesWorkflowRoute(c.surface)?join(resolveNitroWorkflowBuildDirectory(o),`workflows.mjs`):void 0})},syncWorkflowArtifacts=async()=>{let e=n.then(buildWorkflowArtifacts);n=e.catch(()=>{}),await e},r=!0;await syncWorkflowArtifacts(),o.hooks.hook(`build:before`,async()=>{if(r){r=!1;return}await syncWorkflowArtifacts()}),o.options.dev&&o.hooks.hook(`dev:reload`,async()=>{await syncWorkflowArtifacts()})}let l=createNitroArtifactsConfig({appRoot:s.appRoot,dev:o.options.dev});if(includesApplicationRoutes(c.surface)){registerHandler(o,{handlerPath:resolvePackageSourceFilePath(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`});for(let e of[`GET`,`HEAD`])registerHandler(o,{handlerPath:resolvePackageSourceFilePath(`src/internal/nitro/routes/health.ts`),method:e,route:EVE_HEALTH_ROUTE_PATH});addFrameworkVirtualHandler(o,{args:JSON.stringify({...l,mode:o.options.dev?`development`:`production`}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/info.ts`),route:EVE_INFO_ROUTE_PATH}),registerChannelVirtualHandlers(o,{artifactsConfig:l,registrations:computeChannelRouteRegistrations(s)}),o.options.dev&&(addFrameworkVirtualHandler(o,{args:JSON.stringify({appRoot:l.appRoot}),handlerExport:`handleDevRuntimeArtifactsRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-runtime-artifacts.ts`),route:EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}),addFrameworkVirtualHandler(o,{args:JSON.stringify({appRoot:l.appRoot}),handlerExport:`
|
|
4
|
+
`)}async function configureNitroRoutes(o,s,c){if(includesWorkflowBundles(c.surface)){let e=resolvePackageRoot(),t=new WorkflowBundleBuilder({agentName:s.compileResult.manifest.config.name,appRoot:s.appRoot,compiledArtifactsBootstrapPath:s.compiledArtifacts.bootstrapPath,outDir:s.workflowBuildDir,rootDir:e,watch:o.options.dev}),n=Promise.resolve(),buildWorkflowArtifacts=async()=>{await t.build({nitroStepOutfile:includesWorkflowRoute(c.surface)?join(resolveNitroWorkflowBuildDirectory(o),`steps.mjs`):void 0,nitroWorkflowOutfile:o.options.dev&&includesWorkflowRoute(c.surface)?join(resolveNitroWorkflowBuildDirectory(o),`workflows.mjs`):void 0})},syncWorkflowArtifacts=async()=>{let e=n.then(buildWorkflowArtifacts);n=e.catch(()=>{}),await e},r=!0;await syncWorkflowArtifacts(),o.hooks.hook(`build:before`,async()=>{if(r){r=!1;return}await syncWorkflowArtifacts()}),o.options.dev&&o.hooks.hook(`dev:reload`,async()=>{await syncWorkflowArtifacts()})}let l=createNitroArtifactsConfig({appRoot:s.appRoot,dev:o.options.dev});if(includesApplicationRoutes(c.surface)){registerHandler(o,{handlerPath:resolvePackageSourceFilePath(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`});for(let e of[`GET`,`HEAD`])registerHandler(o,{handlerPath:resolvePackageSourceFilePath(`src/internal/nitro/routes/health.ts`),method:e,route:EVE_HEALTH_ROUTE_PATH});addFrameworkVirtualHandler(o,{args:JSON.stringify({...l,mode:o.options.dev?`development`:`production`}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/info.ts`),route:EVE_INFO_ROUTE_PATH}),registerChannelVirtualHandlers(o,{artifactsConfig:l,registrations:computeChannelRouteRegistrations(s)}),o.options.dev&&(addFrameworkVirtualHandler(o,{args:JSON.stringify({appRoot:l.appRoot}),handlerExport:`handleDevRuntimeArtifactsRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-runtime-artifacts.ts`),route:EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}),addFrameworkVirtualHandler(o,{args:JSON.stringify({appRoot:l.appRoot}),handlerExport:`handleDevScheduleDispatchRequest`,method:`POST`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-schedule-dispatch.ts`),route:EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN}))}let u=resolveNitroWorkflowBuildDirectory(o),d=includesWorkflowRoute(c.surface)?o.options.dev?join(u,`workflows.mjs`):join(s.workflowBuildDir,`workflows.mjs`):void 0,f=s.compileResult.manifest.config.experimental?.workflow?.world!==void 0,p=(o.options.dev||!isVercelBuildEnvironment()&&f)&&d!==void 0?[{bundlePath:d,queuePrefix:deriveEveWorkflowQueuePrefix(s.compileResult.manifest.config.name)}]:[],m=p.length>0?normalizeEsmImportSpecifier(resolveWorkflowModulePath(`workflow/runtime`)):void 0;d&&await addWorkflowFileHandler(o,{bundleName:`workflows`,bundlePath:d,directHandlers:p,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:m}),o.routing.sync()}export{configureNitroRoutes};
|