eve 0.83.1 → 0.83.2
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 +21 -0
- package/dist/src/channel/types.d.ts +3 -2
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/evals/assertions/run.js +1 -1
- package/dist/src/evals/runner/derive-run-facts.d.ts +13 -0
- package/dist/src/evals/runner/derive-run-facts.js +1 -1
- package/dist/src/evals/session.js +2 -2
- package/dist/src/evals/types.d.ts +1 -1
- package/dist/src/eve-channel/request.js +1 -1
- package/dist/src/execution/catalog/connection-entry.js +1 -1
- package/dist/src/execution/connections/callback-route.d.ts +3 -2
- package/dist/src/execution/connections/callback-route.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/node-step.d.ts +1 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/sandbox/multiplexed-command.d.ts +9 -3
- package/dist/src/execution/sandbox/multiplexed-command.js +1 -1
- package/dist/src/execution/sandbox/read-file.js +1 -1
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session-event-stream.d.ts +6 -0
- package/dist/src/execution/session-event-stream.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/extensions/git/extension/lib/gh-tool.d.ts +11 -2
- package/dist/src/extensions/git/extension/lib/gh-tool.js +1 -1
- package/dist/src/harness/attachment-staging.js +1 -1
- package/dist/src/harness/compaction/step.d.ts +7 -1
- package/dist/src/harness/compaction/step.js +1 -1
- package/dist/src/harness/hitl/approvals.d.ts +2 -0
- package/dist/src/harness/hitl/approvals.js +1 -1
- package/dist/src/harness/hitl/delivery.d.ts +1 -0
- package/dist/src/harness/hitl/delivery.js +1 -1
- package/dist/src/harness/hitl/intake.js +1 -1
- package/dist/src/harness/model-call/call.d.ts +2 -0
- package/dist/src/harness/model-call/call.js +1 -1
- package/dist/src/harness/model-call/request.d.ts +2 -1
- package/dist/src/harness/token-estimate.js +1 -1
- package/dist/src/harness/types.d.ts +6 -0
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/attachments/media-metadata.d.ts +0 -2
- package/dist/src/internal/attachments/media-metadata.js +1 -1
- package/dist/src/internal/attachments/read-media-metadata.d.ts +7 -0
- package/dist/src/internal/attachments/read-media-metadata.js +2 -0
- package/dist/src/internal/authored-asset-import-plugin.d.ts +7 -0
- package/dist/src/internal/authored-asset-import-plugin.js +1 -1
- package/dist/src/internal/authored-module-build-options.js +1 -1
- package/dist/src/internal/authored-module-graph.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +0 -1
- package/dist/src/internal/authored-module-loader.js +1 -1
- package/dist/src/internal/authored-package-boundary.d.ts +3 -0
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/input-text.d.ts +2 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/workflow-bundle/builder.js +2 -2
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/runtime/connections/authorization-complete-page.d.ts +14 -2
- package/dist/src/runtime/connections/authorization-complete-page.js +5 -5
- package/dist/src/runtime/subagents/workflow.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/docs/channels/custom.mdx +4 -0
- package/docs/channels/slack.mdx +2 -0
- package/docs/concepts/built-in-tools.md +1 -1
- package/docs/connections/mcp.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +3 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.83.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 8329939: A parent agent's message to a subagent no longer answers the subagent's pending tool approval or session-limit prompt. Before, a follow-up such as `approve` or `continue` settled the prompt as if the person had answered it. Now only a person's structured answer settles it: the parent's message is delivered as an ordinary message, so a pending approval resolves as `ignored` and a session-limit prompt keeps waiting for the person. Thanks @devon-seitz for reporting this in #5075.
|
|
8
|
+
- 084b2bf: When compaction runs partway through a turn, notices the framework sends again, such as the deferred tool catalog notice, now go before the turn's input instead of after the latest tool result, where the model read them as the newest message.
|
|
9
|
+
|
|
10
|
+
Thanks @hrayn3 for reporting this in #5198.
|
|
11
|
+
- c37d279: The connection sign-in page now says "Authorization not completed" instead of "Authorization complete" when the provider redirects back with an OAuth error, such as the person declining consent. Thanks @dretanacr for reporting this in #5105.
|
|
12
|
+
- 4853062: Connection tool calls now fail after 5 minutes without an answer, instead of holding the turn until it is cancelled. eve cancels the request and returns a tool error the agent can report, so a tool that takes longer than 5 minutes now fails. Thanks @dretanacr for reporting this in #4977.
|
|
13
|
+
- 697741e: Record the input the model sent to an agent tool in eval facts, so a subagent or remote agent call in `turn.toolCalls` no longer shows `input: {}` and `t.calledTool(name, { input })` can match it. Thanks @dretanacr for reporting this in #5063.
|
|
14
|
+
- 6447c36: Evals keep an input request pending after a `respond()` that answers only some of the open requests. `session.pendingInputRequests` still lists the unanswered ones, and `parked()` holds (and `succeeded()` fails) while the run waits on them. Thanks @elrumordelaluz for reporting this in #5157.
|
|
15
|
+
- 3b9ceef: An expired session is no longer reported as failed when writing its final `session.completed` event fails. Before, channels such as Slack posted a `session.failed` error after they had already handled `session.completed`. Thanks @bisak for reporting this in #5261.
|
|
16
|
+
- 3d7eb49: A session stream request that does not report the durable tail no longer looks it up. Default opens and client reconnects now check that the session exists with one run lookup, instead of a tail lookup that on the local world opens every chunk file. Unknown and expired sessions still answer 404 and 410 before the stream starts. Thanks @KingAmo for reporting this in #5016.
|
|
17
|
+
- 7d653ef: MCP connections now fall back to the highest mutually supported legacy protocol version when `server/discover` returns `-32022`. Thanks @zico-io for reporting this in #4406, and @bluepegasus123 for proposing the fallback.
|
|
18
|
+
- 9b24d70: PDFs that store their pages in compressed object streams, as phone scans and `pdf-lib` output usually do, now get a per-page token estimate instead of one based on file size. A multi-megabyte scan no longer requests compaction on the first step of a session. Thanks @DLME2024 for reporting this and suggesting the fix in #5090.
|
|
19
|
+
- 1a735c6: `git({ github })` and the deprecated `code({ github })` register their authenticated `gh` tool at session start again, as do dynamic tools built with `defineGhTool` from `eve/extensions/git/sandbox`. Thanks @seahiLin for reporting this in #4986.
|
|
20
|
+
- 653a257: Slack apps that set `onInputResponse` or `approvalChannel` no longer let a message typed in the thread answer an open question. Before, the typed message answered it without running `onInputResponse`, and the answer was the whole `<slack_message>` envelope. The message now reaches the agent as a new message instead.
|
|
21
|
+
- e14685b: On Vercel Sandbox, aborting a `sandbox.run()` or `sandbox.spawn()` command after it starts now kills it, and `run()` rejects instead of waiting, as the `abortSignal` option documents. Before, the command kept running until it exited by itself, including after a turn was cancelled. Thanks @voidhrithik for reporting this in #5301.
|
|
22
|
+
- 64b5d06: Workflow and step modules can now use `?raw` and other relative asset imports. Before, `eve build` failed with `UNLOADABLE_DEPENDENCY` when a module reachable from a workflow imported a file this way, even though the same import worked in a tool. Thanks @gmstevenson for reporting this in #5269.
|
|
23
|
+
|
|
3
24
|
## 0.83.1
|
|
4
25
|
|
|
5
26
|
### Patch Changes
|
|
@@ -577,8 +577,9 @@ export interface Runtime {
|
|
|
577
577
|
* parameter unchanged.
|
|
578
578
|
*
|
|
579
579
|
* A following read throws `SessionStrandedError` when the session's owner
|
|
580
|
-
* cannot execute here
|
|
581
|
-
* or
|
|
580
|
+
* cannot execute here, and rejects before returning when the session does
|
|
581
|
+
* not exist or its history has expired. A historical read (`follow: false`)
|
|
582
|
+
* never inspects or changes the session's lifecycle.
|
|
582
583
|
*/
|
|
583
584
|
getEventStream(sessionId: string, options?: GetEventStreamOptions): Promise<ReadableStream<MessageStreamEvent>>;
|
|
584
585
|
/**
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"zod": "4.5.4",
|
|
62
62
|
"zod-validation-error": "5.0.0"
|
|
63
63
|
},
|
|
64
|
-
"scriptHash": "
|
|
64
|
+
"scriptHash": "b350dbbe6a6621651989fdd64f1028d7339f90c15bb60f8fa0afc90e97d33db3",
|
|
65
65
|
"toolVersions": {
|
|
66
66
|
"rolldown": "1.2.9",
|
|
67
67
|
"typescript": "7.0.2"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{I as n,K as r,M as i,N as a,St as o,Tt as s,U as c,c as l,dt as u,ft as d,gt as f,i as p,j as m,p as h,tt as g,ut as _,yt as v}from"../../_chunks/workflow/dist-C8k3N3BQ.js";import*as y from"#compiled/zod/index.js";import{z as b}from"#compiled/zod/index.js";let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function S(e){return(await x).getRandomValues(new Uint8Array(e))}async function C(e){let t=``;for(;t.length<e;){let n=await S(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function w(e){return await C(e)}async function ee(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function te(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await w(e);return{code_verifier:t,code_challenge:await ee(t)}}const T=`2026-07-28`,E=`2025-11-25`,ne=[T,E,`2025-06-18`,`2025-03-26`,`2024-11-05`],re=b.optional(b.record(b.string(),b.unknown())),ie=b.looseObject({name:b.string(),version:b.string(),title:b.optional(b.string())}),D=b.looseObject({_meta:b.optional(b.object({}).loose())}),O=D.extend({resultType:b.optional(b.string())}),ae=b.object({method:b.string(),params:b.optional(D)}),oe=b.object({applyDefaults:b.optional(b.boolean())}).loose(),se=b.looseObject({events:b.looseObject({listChanged:b.boolean().nullish()}).nullish(),experimental:b.optional(b.object({}).loose()),logging:b.optional(b.object({}).loose()),completions:b.optional(b.object({}).loose()),prompts:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),resources:b.optional(b.looseObject({subscribe:b.optional(b.boolean()),listChanged:b.optional(b.boolean())})),tools:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),elicitation:b.optional(oe)});b.object({elicitation:b.optional(oe)}).loose();const ce=O.extend({supportedVersions:b.array(b.string()),capabilities:se,instructions:b.optional(b.string()),ttlMs:b.optional(b.number()),cacheScope:b.optional(b.union([b.literal(`public`),b.literal(`private`)]))}),le=O.extend({protocolVersion:b.string(),capabilities:se,serverInfo:ie,instructions:b.optional(b.string())}),k=O.extend({nextCursor:b.optional(b.string())}),ue=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),inputSchema:b.looseObject({type:b.optional(b.unknown()),properties:b.optional(b.object({}).loose())}),outputSchema:b.optional(b.object({}).loose()),annotations:b.optional(b.object({title:b.optional(b.string()),readOnlyHint:b.optional(b.boolean()),destructiveHint:b.optional(b.boolean()),idempotentHint:b.optional(b.boolean()),openWorldHint:b.optional(b.boolean())}).loose()),_meta:re}).loose(),de=k.extend({tools:b.array(ue)}),fe=b.object({type:b.literal(`text`),text:b.string()}).loose(),pe=b.object({type:b.literal(`image`),data:b.base64(),mimeType:b.string()}).loose(),me=b.object({uri:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string()),size:b.optional(b.number())}).loose(),he=k.extend({resources:b.array(me)}),ge=b.object({uri:b.string(),name:b.optional(b.string()),title:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),_e=ge.extend({text:b.string()}),ve=ge.extend({blob:b.base64()}),ye=b.object({type:b.literal(`resource`),resource:b.union([_e,ve])}).loose(),be=b.object({type:b.literal(`resource_link`),uri:b.string(),name:b.string(),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),xe=b.object({type:b.string()}).loose().refine(e=>![`text`,`image`,`resource`,`resource_link`].includes(e.type),{message:`Known content types must match their schema`}),Se=O.extend({content:b.array(b.union([fe,pe,ye,be,xe])),structuredContent:b.optional(b.unknown()),isError:b.boolean().default(!1).optional()}),Ce=O.extend({content:b.never().optional(),structuredContent:b.json(),isError:b.boolean().default(!1).optional()}).transform(e=>({...e,content:[{type:`text`,text:JSON.stringify(e.structuredContent)}]})).pipe(Se),we=Se.or(Ce).or(O.extend({toolResult:b.unknown().nonoptional()})),Te=b.object({uriTemplate:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),Ee=O.extend({resourceTemplates:b.array(Te)}),De=O.extend({contents:b.array(b.union([_e,ve]))}),Oe=b.object({type:b.literal(`ref/prompt`),name:b.string()}).loose(),ke=b.object({type:b.literal(`ref/resource`),uri:b.string()}).loose(),Ae=b.object({name:b.string(),value:b.string()}).loose();D.extend({ref:b.union([Oe,ke]),argument:Ae,context:b.optional(b.object({arguments:b.record(b.string(),b.string())}).loose())});const je=O.extend({completion:b.object({values:b.array(b.string()).max(100),total:b.optional(b.number().int()),hasMore:b.optional(b.boolean())}).loose()}),Me=b.object({name:b.string(),description:b.optional(b.string()),required:b.optional(b.boolean())}).loose(),Ne=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),arguments:b.optional(b.array(Me))}).loose(),Pe=k.extend({prompts:b.array(Ne)}),Fe=b.object({role:b.union([b.literal(`user`),b.literal(`assistant`)]),content:b.union([fe,pe,ye,be])}).loose(),Ie=O.extend({description:b.optional(b.string()),messages:b.array(Fe)}),Le=D.extend({message:b.string(),requestedSchema:b.unknown()}),A=ae.extend({method:b.literal(`elicitation/create`),params:Le}),Re=O.extend({action:b.union([b.literal(`accept`),b.literal(`decline`),b.literal(`cancel`)]),content:b.optional(b.record(b.string(),b.unknown()))}),ze=b.object({jsonrpc:b.literal(`2.0`),id:b.union([b.string(),b.number().int()])}).merge(ae).strict(),Be=b.object({jsonrpc:b.literal(`2.0`),id:b.union([b.string(),b.number().int()]),result:O}).strict(),Ve=b.object({jsonrpc:b.literal(`2.0`),id:b.optional(b.union([b.string(),b.number().int()])),error:b.object({code:b.number().int(),message:b.string(),data:b.optional(b.unknown())})}).strict(),He=b.object({jsonrpc:b.literal(`2.0`)}).merge(b.object({method:b.string(),params:b.optional(D)})).strict(),Ue=b.union([ze,He,Be,Ve]);function j(e){return Ue.parse(e)}async function M(e){return j(await g({text:e}))}const We=`vercel.ai.error.AI_MCPClientError`,Ge=Symbol.for(We);var N=class extends e{constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[Ge]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,We)}};function Ke(){return`whsec_${h(crypto.getRandomValues(new Uint8Array(32)))}`}function qe(e){let t=e.slice(6);if(!e.startsWith(`whsec_`)||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new N({message:`Invalid MCP event signing secret`});let n=l(t);if(n.length<24||n.length>64)throw new N({message:`MCP event signing secrets must contain 24–64 random bytes`});return n}async function Je({headers:e,body:t,secret:n}){let r=e.get(`webhook-id`),i=e.get(`webhook-timestamp`),a=e.get(`webhook-signature`);if(!r||!i||!a||!/^\d+$/.test(i)||Math.abs(Date.now()/1e3-Number(i))>300)return!1;let o=await crypto.subtle.importKey(`raw`,new Uint8Array(qe(n)),{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]),s=new TextEncoder().encode(`${r}.${i}.`),c=new Uint8Array(s.length+t.length);c.set(s),c.set(t,s.length);for(let e of a.split(` `)){let[t,n]=e.split(`,`);if(t===`v1`&&n)try{if(await crypto.subtle.verify(`HMAC`,o,new Uint8Array(l(n)),c))return!0}catch{}}return!1}const Ye=b.union([b.boolean(),b.record(b.string(),b.unknown())]),Xe=b.looseObject({name:b.string().min(1),description:b.string().nullish(),delivery:b.array(b.enum([`webhook`,`poll`,`push`])).min(1),inputSchema:Ye,payloadSchema:Ye}),Ze=O.extend({events:b.array(Xe),nextCursor:b.string().nullish()}),Qe=O.extend({id:b.string().min(1),refreshBefore:b.iso.datetime({offset:!0}).nullable(),cursor:b.string().nullish().transform(e=>e??null),truncated:b.boolean()}),$e=b.looseObject({eventId:b.string().min(1),name:b.string().min(1),timestamp:b.iso.datetime({offset:!0}),data:b.record(b.string(),b.unknown()),cursor:b.string().nullish()}),et=b.discriminatedUnion(`type`,[b.looseObject({type:b.literal(`gap`),cursor:b.string()}),b.looseObject({type:b.literal(`terminated`),error:b.looseObject({code:b.number().int(),message:b.string(),data:b.unknown().nullish()})})]).transform(e=>e.type===`gap`?{...e,truncated:!0}:e),tt=`mcp_event_subscription`;function nt({request:e,store:t,validateArguments:n}){function r(){if(!t)throw new N({message:`Configure experimental_events.store to manage direct event subscriptions`});return t}async function i({id:e,key:t}){let n=r(),i=e===void 0?await n.get(t):await n.getById(e);if(!i)throw new N({message:`Unknown MCP event subscription: ${e??t}`});return i}async function a(t,n){let i=await e({request:{method:`events/subscribe`,params:{name:t.name,arguments:t.arguments,delivery:t.delivery,cursor:t.cursor,...t.ttlMs===void 0?{}:{ttlMs:t.ttlMs},...t.maxAgeMs===void 0?{}:{maxAgeMs:t.maxAgeMs}}},resultSchema:Qe,options:n});return await r().update(t.key,{id:i.id,refreshBefore:i.refreshBefore,cursor:i.cursor,truncated:i.truncated,status:`active`}),i}let o={list({params:t,options:n}={}){return e({request:{method:`events/list`,params:t},resultSchema:Ze,options:n})},async subscribe({name:e,arguments:t={},delivery:i,cursor:s=null,ttlMs:c,maxAgeMs:l,options:u}){let d=r(),f=new URL(i.url),p=i.allowInsecureLocalhost===!0&&f.protocol===`http:`&&(f.hostname===`127.0.0.1`||f.hostname===`[::1]`);if(f.protocol!==`https:`&&!p||f.username||f.password||f.hash)throw new N({message:`MCP event callback URLs must use HTTPS without credentials or fragments`});if(i.mode!==`webhook`)throw new N({message:`Only webhook event delivery is supported`});if(c!=null&&(!Number.isSafeInteger(c)||c<=0)||l!=null&&(!Number.isSafeInteger(l)||l<0))throw new N({message:`Invalid MCP event subscription lifetime or replay age`});let m,h=new Set,g;do{let t=await o.list({params:{cursor:m},options:u});if(g=t.events.find(t=>t.name===e),g)break;if(m=t.nextCursor??void 0,m!=null){if(h.has(m))throw new N({message:`Repeated MCP events pagination cursor`});h.add(m)}}while(m!=null);if(!g)throw new N({message:`Unknown MCP event: ${e}`});if(!g.delivery.includes(`webhook`))throw new N({message:`MCP event ${e} does not support webhook delivery`});await n?.({definition:g,arguments:t});let _=i.secret??Ke();qe(_);let v=crypto.randomUUID();f.searchParams.set(tt,v);let y={key:v,name:e,arguments:structuredClone(t),definition:g,delivery:{mode:`webhook`,url:f.href,secret:_},cursor:s,truncated:!1,ttlMs:c,maxAgeMs:l,status:`pending`};return await d.set(y),a(y,u)},async refresh(e){let t=await i(e);return await r().update(t.key,{status:`pending`}),a(t,e.options)},async unsubscribe(t){let n=await i(t);await e({request:{method:`events/unsubscribe`,params:{name:n.name,arguments:n.arguments,delivery:{mode:`webhook`,url:n.delivery.url}}},resultSchema:O,options:t.options}),await r().delete(n.key)}};return o}function rt(e){if(e!=null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`)throw Promise.resolve(e).catch(()=>{}),new N({message:`experimental_events.adapter.createAdapter() must return operations synchronously. Promise and thenable results are not supported.`});if(typeof e!=`object`||!e||!(`subscribe`in e)||typeof e.subscribe!=`function`||!(`getSubscription`in e)||typeof e.getSubscription!=`function`||!(`listSubscriptions`in e)||typeof e.listSubscriptions!=`function`||!(`unsubscribe`in e)||typeof e.unsubscribe!=`function`)throw new N({message:`experimental_events.adapter.createAdapter() must return an object implementing subscribe, getSubscription, listSubscriptions, and unsubscribe.`})}function it(e,t){return{list:t,subscribe:t=>e.subscribe(t),getSubscription:t=>e.getSubscription(t),listSubscriptions:t=>e.listSubscriptions(t),unsubscribe:t=>e.unsubscribe(t)}}const at=`2.0.73`,P=b.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:b.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),b.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),ot=b.object({access_token:b.string(),id_token:b.string().optional(),token_type:b.string(),expires_in:b.number().optional(),scope:b.string().optional(),refresh_token:b.string().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),st=b.looseObject({resource:b.string().url(),authorization_servers:b.array(P).optional(),jwks_uri:b.string().url().optional(),scopes_supported:b.array(b.string()).optional(),bearer_methods_supported:b.array(b.string()).optional(),resource_signing_alg_values_supported:b.array(b.string()).optional(),resource_name:b.string().optional(),resource_documentation:b.string().optional(),resource_policy_uri:b.string().url().optional(),resource_tos_uri:b.string().url().optional(),tls_client_certificate_bound_access_tokens:b.boolean().optional(),authorization_details_types_supported:b.array(b.string()).optional(),dpop_signing_alg_values_supported:b.array(b.string()).optional(),dpop_bound_access_tokens_required:b.boolean().optional()}),ct=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),code_challenge_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_signing_alg_values_supported:b.array(b.string()).optional()}),lt=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,userinfo_endpoint:P.optional(),jwks_uri:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),subject_types_supported:b.array(b.string()),id_token_signing_alg_values_supported:b.array(b.string()),claims_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional()}).merge(ct.pick({code_challenge_methods_supported:!0})),ut=b.object({client_id:b.string(),client_secret:b.string().optional(),client_id_issued_at:b.number().optional(),client_secret_expires_at:b.number().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),dt=b.object({redirect_uris:b.array(P),application_type:b.union([b.literal(`native`),b.literal(`web`)]).optional(),token_endpoint_auth_method:b.string().optional(),grant_types:b.array(b.string()).optional(),response_types:b.array(b.string()).optional(),client_name:b.string().optional(),client_uri:P.optional(),logo_uri:P.optional(),scope:b.string().optional(),contacts:b.array(b.string()).optional(),tos_uri:P.optional(),policy_uri:b.string().optional(),jwks_uri:P.optional(),jwks:b.any().optional(),software_id:b.string().optional(),software_version:b.string().optional(),software_statement:b.string().optional()}).strip(),ft=b.object({error:b.string(),error_description:b.string().optional(),error_uri:b.string().optional()}),pt=dt.merge(ut),mt=`vercel.ai.error.AI_MCPClientOAuthError`,ht=Symbol.for(mt);var F=class extends e{constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[ht]=!0}static isInstance(t){return e.hasMarker(t,mt)}},I=class extends F{static{this.errorCode=`server_error`}},L=class extends F{static{this.errorCode=`invalid_client`}},R=class extends F{static{this.errorCode=`invalid_grant`}},z=class extends F{static{this.errorCode=`unauthorized_client`}};const gt=`vercel.ai.error.AI_AuthorizationServerMismatchError`,_t=Symbol.for(gt);var vt=class extends F{static{this.errorCode=`authorization_server_mismatch`}constructor({message:e,cause:t}){super({name:`AuthorizationServerMismatchError`,message:e,cause:t}),this[_t]=!0}static isInstance(t){return e.hasMarker(t,gt)}};const yt={[I.errorCode]:I,[L.errorCode]:L,[R.errorCode]:R,[z.errorCode]:z};function bt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function B(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function xt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var V=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function H(e){return new URL(e).href}function U(e){let t=e.toLowerCase().replace(/\.+$/,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function W(e,{allowLoopback:t=!1}={}){if(!t||e.protocol!==`http:`&&e.protocol!==`https:`||!U(e.hostname))try{v(e.href)}catch(t){throw new F({message:`OAuth endpoint URL is not allowed: ${e.href}`,cause:t})}}function G(e){let t=new URL(e);return U(t.hostname)?t.origin:void 0}function St({callbackIssuer:e,expectedIssuer:t}){if(e!=null&&e!==t)throw new F({message:`OAuth authorization response issuer ${e} does not match expected issuer ${t}`})}function Ct(e,t){return{issuer:t?.issuer??String(e),authorizationServerUrl:H(e),tokenEndpoint:H(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function wt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Tt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Et(e){if(e?.authorization_server&&e.token_endpoint)return{issuer:e.issuer,authorizationServerUrl:H(e.authorization_server),tokenEndpoint:H(e.token_endpoint)}}async function K({provider:e,clientInformation:t,tokens:n}){let r=Et(n);if(r)return r;let i=await e.authorizationServerInformation?.();return i?{issuer:i.issuer,authorizationServerUrl:H(i.authorizationServerUrl),tokenEndpoint:H(i.tokenEndpoint)}:Et(t)}async function Dt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(Tt(t,n)),!0):!1}function Ot(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new F({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function q({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.issuer!=null&&t.issuer!=null&&e.issuer!==t.issuer||e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new vt({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function J(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=t.match(/(?:^|[,\s])resource_metadata="([^"]*)"/i),a=t.match(/(?:^|[,\s])scope="([^"]*)"/i)?.[1],o;try{o=i?new URL(i[1]):void 0}catch{}return{resourceMetadataUrl:o,scope:a}}function kt({scope:e,resourceMetadata:t,clientMetadata:n}){return e||t?.scopes_supported?.join(` `)||n.scope}function At(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Y(e,t,n=fetch,r){try{return await i({url:e.href,fetch:async(e,i)=>a({url:e,init:{...i,headers:new Headers(i?.headers).has(`MCP-Protocol-Version`)?t:void 0},fetch:n,trustedOrigin:r,redirect:`manual`}),headers:t,trustedOrigin:r,untrustedFirstHopHeaders:[`mcp-protocol-version`]})}catch(i){if(i instanceof TypeError)return t?Y(e,void 0,n,r):void 0;throw i}}async function jt(e,t,n=fetch,r){return await Y(e,{"MCP-Protocol-Version":t},n,r)}function Mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Nt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2026-07-28`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=At(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await jt(o,a,n,r?.trustedOrigin);return!r?.metadataUrl&&Mt(s,i.pathname)&&(s=await jt(new URL(`/.well-known/${t}`,i),a,n,r?.trustedOrigin)),s}async function Pt(e,t,n=fetch){let r=await Nt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl,trustedOrigin:new URL(e).origin});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return st.parse(await r.json())}function Ft(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o});let s=new URL(t.origin);return s.pathname=`${a}/.well-known/openid-configuration`,i.push({url:s,type:`oidc`,expectedIssuer:o}),i}function It(e,t){if(!(e.issuer===t||t===new URL(t).origin&&e.issuer===`${t}/`))throw new F({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Lt(e,{fetchFn:t=fetch,protocolVersion:n=T,trustedOrigin:r}={}){let i={"MCP-Protocol-Version":n},a=new URL(e).origin,o=Ft(e);if(o.some(({url:e})=>e.origin!==a))throw new F({message:`OAuth discovery URL changed authorization-server origin`});for(let{url:e,type:n,expectedIssuer:a}of o){let o=await Y(e,i,t,r);if(o){if(!o.ok){if(o.status>=400&&o.status<500)continue;throw Error(`HTTP ${o.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=ct.parse(await o.json());return It(e,a),e}{let t=lt.parse(await o.json());if(It(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Rt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await te(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,B(o)),{authorizationUrl:l,codeVerifier:d}}function zt(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Bt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Vt(i,a,n);return;case`client_secret_post`:Ht(i,a,r);return;case`none`:Ut(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Vt(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Ht(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Ut(e,t){t.set(`client_id`,e)}async function X(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ft.parse(await g({text:n}));return new(yt[e]||I)({message:t||``,cause:r})}catch(e){return new I({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Wt(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:c,fetchFn:l}){let u=`authorization_code`,d=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),f=G(e);if(W(d,{allowLoopback:d.origin===f}),t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),m=new URLSearchParams({grant_type:u,code:r,code_verifier:i,redirect_uri:String(o)});c?await c(p,m,e,t):Bt(zt(n,t?.token_endpoint_auth_methods_supported??[]),n,p,m),s&&m.set(`resource`,B(s));let h=await a({url:d,init:{method:`POST`,headers:p,body:m},fetch:l,trustedOrigin:f});if(!h.ok)throw await X(h);return ot.parse(await h.json())}async function Gt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:o,fetchFn:s}){let c=`refresh_token`,l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL(`/token`,e);let u=G(e);W(l,{allowLoopback:l.origin===u});let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:c,refresh_token:r});o?await o(d,f,e,t):Bt(zt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),i&&f.set(`resource`,B(i));let p=await a({url:l,init:{method:`POST`,headers:d,body:f},fetch:s,trustedOrigin:u});if(!p.ok)throw await X(p);return ot.parse({refresh_token:r,...await p.json()})}async function Kt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let o=G(e);W(i,{allowLoopback:i.origin===o});let s=n.application_type??qt(n.redirect_uris),c=await a({url:i,init:{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,application_type:s})},fetch:r,trustedOrigin:o});if(!c.ok)throw await X(c);return pt.parse(await c.json())}function qt(e){return e.every(e=>{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&U(t.hostname)||t.protocol!==`http:`&&t.protocol!==`https:`})?`native`:`web`}async function Z(e,t){let n={};try{return await Yt(e,t,n)}catch(r){if(r instanceof L||r instanceof z){if(t.authorizationCode!==void 0||!await e.isClientInformationDynamicallyRegistered?.())throw r;return await e.invalidateCredentials?.(`all`),await Yt(e,t)}if(r instanceof R&&n.tokens)return await e.invalidateCredentials?.(`tokens`,{tokens:n.tokens}),await Yt(e,t);throw r}}async function Jt(e,t,n){let r=bt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!xt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Yt(e,{serverUrl:t,authorizationCode:n,callbackState:r,callbackIssuer:i,scope:a,resourceMetadataUrl:o,fetchFn:s},c){let l,u,d,f;Ot(t,o);try{l=await Pt(t,{resourceMetadataUrl:o},s),l.authorization_servers&&l.authorization_servers.length>0&&(u=l.authorization_servers[0])}catch{}n!==void 0&&(d=await Promise.resolve(e.clientInformation()),d&&(f=await K({provider:e,clientInformation:d}))),u||=f?.authorizationServerUrl??t;let p=new URL(t),m=new URL(u),h=p.origin,g=m.origin,_=g===h||U(p.hostname)&&U(m.hostname)?g:void 0;_||W(new URL(u));let v=await Jt(t,e,l);await e.validateAuthorizationServerURL?.(t,u);let y=await Lt(u,{fetchFn:s,trustedOrigin:_}),b=Ct(u,y),x=e.clientMetadata,S=kt({scope:a,resourceMetadata:l,clientMetadata:x});if(n===void 0&&(d=await Promise.resolve(e.clientInformation())),d?.issuer!=null){let t=f??await K({provider:e,clientInformation:d});t&&q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b})}if(!d){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);d=Tt(await Kt(u,{metadata:y,clientMetadata:{...x,scope:S},fetchFn:s}),b),await e.saveClientInformation(d)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=f??await K({provider:e,clientInformation:d});if(!t)throw new F({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});St({callbackIssuer:i,expectedIssuer:t.issuer??y?.issuer??String(u)}),q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b});let a=await e.codeVerifier(),o=await Wt(u,{metadata:y,clientInformation:d,authorizationCode:n,codeVerifier:a,redirectUri:e.redirectUrl,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(wt(o,b)),`AUTHORIZED`}let C=await e.tokens();if(C?.refresh_token){let t=await K({provider:e,clientInformation:d,tokens:C});t?q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b}):await e.invalidateCredentials?.(`tokens`,{tokens:{...C}});try{if(t){c&&(c.tokens={...C});let t=await Gt(u,{metadata:y,clientInformation:d,refreshToken:C.refresh_token,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(wt(t,b)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof F)||e instanceof I))throw e}}let w=e.state?await e.state():void 0;w&&e.saveState&&await e.saveState(w);let{authorizationUrl:ee,codeVerifier:te}=await Rt(u,{metadata:y,clientInformation:d,state:w,redirectUrl:e.redirectUrl,scope:S,resource:v});if(!await Dt({provider:e,clientInformation:d,authorizationServerInformation:b}))throw new F({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(te),await e.redirectToAuthorization(ee),`REDIRECT`}function Xt(e){return e===void 0||e===`message`}var Zt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??`2025-11-25`};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return o(t,`ai-sdk/${at}`,n())}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async accessTokenChanged(e){let t=(await this.authProvider?.tokens())?.access_token;return t!=null&&e!==`Bearer ${t}`}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{try{let i=await this.commonHeaders({Accept:`text/event-stream`}),a=await this.fetchFn(this.url.href,{headers:i,signal:this.abortController?.signal,redirect:this.redirectMode});if(a.status===401&&this.authProvider&&!r){let{resourceMetadataUrl:e,scope:r}=J(a);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,r)!==`AUTHORIZED`){let e=new V;return this.onerror?.(e),t(e)}}catch(e){return this.onerror?.(e),t(e)}return n(!0)}if(!a.ok||!a.body){let e=`MCP SSE Transport Error: ${a.status} ${a.statusText}`;a.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new N({message:e});return this.onerror?.(n),t(n)}let o=a.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader(),c=async()=>{try{for(;;){let{done:t,value:n}=await o.read();if(t){if(this.abortController?.signal.aborted)return;throw this.connected?(this.connected=!1,new N({message:`MCP SSE Transport Error: Connection closed unexpectedly`})):new N({message:`MCP SSE Transport Error: Connection closed before endpoint event was received`})}let{event:r,data:i}=n;if(r===`endpoint`){if(this.endpoint)continue;let t=new URL(i,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,this.sseConnection?.close(),this.abortController?.abort(),new N({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Xt(r))try{let e=await M(i);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),t(e)}};this.sseConnection={close:()=>o.cancel()},c()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),t(e)}};n()})}async close(){this.connected=!1,this.endpoint=void 0,this.sseConnection?.close(),this.abortController?.abort(),this.onclose?.()}async send(e,t){if(t?.signal?.throwIfAborted(),!this.endpoint||!this.connected)throw new N({message:`MCP SSE Transport Error: Not connected`});let n=this.endpoint,r=this.abortController?.signal,i=t?.signal==null?r:r==null?t.signal:AbortSignal.any([r,t.signal]),a=async(r=!1)=>{try{let t=await this.commonHeaders({"Content-Type":`application/json`}),o={method:`POST`,headers:t,body:JSON.stringify(e),signal:i,redirect:this.redirectMode},s=await this.fetchFn(n.href,o);if(s.status===401&&this.authProvider&&!r){if(await this.accessTokenChanged(new Headers(t).get(`authorization`)??void 0))return a(!0);let{resourceMetadataUrl:e,scope:n}=J(s);if(this.resourceMetadataUrl=e,await this.authorizeOnce(this.resourceMetadataUrl,n)!==`AUTHORIZED`)throw new V;return a(!0)}if(!s.ok){let e=await s.text().catch(()=>null);throw new N({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${s.status}): ${e}`,statusCode:s.status,url:n.href,responseBody:e??void 0})}}catch(e){throw t?.signal?.aborted||this.onerror?.(e),e}};await a()}};const Qt=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,$t=/^=\?base64\?.*\?=$/;function en(e){return[...e].every(e=>{let t=e.charCodeAt(0);return t===9||t>=32&&t<=126})&&e.trim()===e&&!$t.test(e)?e:`=?base64?${h(new TextEncoder().encode(e))}?=`}function tn(e){if(!c(e))return{success:!1,error:`inputSchema must be a JSON Schema object`};let t=[],n=new Set,r,i=(e,a,o)=>{if(r==null&&c(e)){if(`x-mcp-header`in e){if(!o||a.length===0){r=`x-mcp-header is not on a statically reachable property`;return}let i=e[`x-mcp-header`];if(typeof i!=`string`||!Qt.test(i)){r=`x-mcp-header must be a non-empty HTTP token`;return}let s=i.toLowerCase();if(n.has(s)){r=`x-mcp-header value "${i}" is not unique`;return}let c=e.type;if(c!==`boolean`&&c!==`integer`&&c!==`string`){r=`x-mcp-header can only annotate boolean, integer, or string properties`;return}n.add(s),t.push({headerName:i,path:a,valueType:c})}for(let[t,n]of Object.entries(e))if(t!==`x-mcp-header`){if(t===`properties`&&c(n))for(let[e,t]of Object.entries(n))i(t,[...a,e],o);else i(n,a,!1)}}};return i(e,[],!0),r==null?{success:!0,bindings:t}:{success:!1,error:r}}function nn(e,t){let n=e;for(let e of t){if(!c(n))return;n=n[e]}return n}function rn({bindings:e,args:t}){let n={};for(let r of e){let e=nn(t,r.path);if(e!=null){if(r.valueType===`string`&&typeof e!=`string`||r.valueType===`boolean`&&typeof e!=`boolean`||r.valueType===`integer`&&!Number.isSafeInteger(e))throw TypeError(`Tool argument "${r.path.join(`.`)}" does not match its x-mcp-header type`);n[`Mcp-Param-${r.headerName}`]=en(String(e))}}return n}function an(e){return e===void 0||e===`message`}var on=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.supportsProtocolVersionDiscovery=!0,this.supportsMcpToolParameterHeaders=!0,this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a??`2025-11-25`,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){if(this.protocolVersion=e,this.abortController){if(this.isModernProtocol()){this.inboundSseConnection?.close(),this.inboundSseConnection=void 0;return}this.sessionId&&this.startInboundSse()}}isModernProtocol(){return(this.protocolVersion??`2026-07-28`)===T}async commonHeaders({base:e,includeSessionId:t=!0}){let r={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??`2025-11-25`};if(!this.isModernProtocol()&&t&&this.sessionId&&(r[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(r.Authorization=`Bearer ${e.access_token}`)}return o(r,`ai-sdk/${at}`,n())}setSessionId(e){this.sessionId!==e&&(this.sessionId=e,this.onSessionIdChange?.(e))}applySessionIdFromResponse(e){if(this.isModernProtocol())return;let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){this.sessionId===e&&this.setSessionId(void 0),this.onSessionExpired?.(e)}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new N({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.protocolVersion!=null&&this.protocolVersion!==`2026-07-28`&&this.startInboundSse()}async close(e){this.inboundSseConnection?.close(),this.abortController?.abort();try{if(!this.isModernProtocol()&&this.sessionId&&this.terminateSessionOnClose&&this.abortController){e?.signal?.throwIfAborted();let t=await this.commonHeaders({base:{}});e?.signal?.throwIfAborted();let n=new AbortController,r=setTimeout(()=>n.abort(),5e3);await this.fetchFn(this.url.href,{method:`DELETE`,headers:t,signal:e?.signal??n.signal,redirect:this.redirectMode}).catch(()=>void 0).finally(()=>clearTimeout(r))}}catch{}this.onclose?.()}async send(e,t){t?.signal?.throwIfAborted();let n=this.abortController?.signal,r=t?.signal==null?n:n==null?t.signal:AbortSignal.any([n,t.signal]),i=async(n=!1)=>{try{let a=`method`in e&&e.method===`initialize`,o=a?void 0:this.sessionId,c={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...this.isModernProtocol()?t?.headers:{},...this.isModernProtocol()&&`method`in e&&`id`in e?this.getStandardRequestHeaders(e):{}},includeSessionId:!a}),body:JSON.stringify(e),signal:r,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c);if(this.applySessionIdFromResponse(l),l.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=J(l);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,t)!==`AUTHORIZED`)throw new V}catch(e){throw this.onerror?.(e),e}return i(!0)}if(l.status===202){!this.isModernProtocol()&&!this.inboundSseConnection&&this.startInboundSse();return}if(!l.ok){let t=await l.text().catch(()=>null);if(`id`in e&&t!=null){let n=await M(t).catch(()=>void 0);if(n!=null&&`error`in n){this.onmessage?.(n.id==null?{...n,id:e.id}:n);return}}let n=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${t}`;l.status===404&&(!this.isModernProtocol()&&o?(this.expireSessionId(o),n+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):this.isModernProtocol()||(n+=". This server does not support HTTP transport. Try using `sse` transport instead"));let r=new N({message:n,statusCode:l.status,url:this.url.href,responseBody:t??void 0});throw this.onerror?.(r),r}if(!(`id`in e))return;let u=l.headers.get(`content-type`)||``;if(u.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>j(e)):[j(e)];for(let e of t)this.onmessage?.(e);return}if(u.includes(`text/event-stream`)){if(!l.body){let e=new N({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:l.status,url:this.url.href});throw this.onerror?.(e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader();(async()=>{try{for(;;){let{done:t,value:n}=await e.read();if(t)return;let{event:r,data:i}=n;if(an(r))try{let e=await M(i);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e)}})().catch(e=>{t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)});return}let d=new N({message:`MCP HTTP Transport Error: Unexpected content type: ${u}`,statusCode:l.status,url:this.url.href});throw this.onerror?.(d),d}catch(e){throw t?.signal?.aborted||this.onerror?.(e),e}};await i()}getStandardRequestHeaders(e){let t={"Mcp-Method":e.method},n=e.params,r=e.method===`resources/read`?n?.uri:e.method===`tools/call`||e.method===`prompts/get`?n?.name:void 0;return typeof r==`string`&&(t[`Mcp-Name`]=en(r)),t}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){let{maxRetries:e}=this.reconnectionOptions;if(e>0&&this.inboundReconnectAttempts>=e){this.onerror?.(new N({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${e}) exceeded.`}));return}let t=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},t)}startInboundSse(e=!1,t){if(this.isModernProtocol()||this.inboundSseConnection)return;let n={close(){}};this.inboundSseConnection=n,this.openInboundSse(e,t).finally(()=>{this.inboundSseConnection===n&&(this.inboundSseConnection=void 0)}).catch(e=>{e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)})}async openInboundSse(e=!1,t){if(!this.isModernProtocol())try{let n=this.sessionId,r=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(r[`last-event-id`]=t);let i=await this.fetchFn(this.url.href,{method:`GET`,headers:r,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(i),i.status===401&&this.authProvider&&!e){let{resourceMetadataUrl:e,scope:n}=J(i);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,n)!==`AUTHORIZED`){let e=new V;this.onerror?.(e);return}}catch(e){this.onerror?.(e);return}return this.openInboundSse(!0,t)}if(i.status===405)return;if(!i.ok||!i.body){i.status===404&&n&&this.expireSessionId(n);let e=new N({message:`MCP HTTP Transport Error: GET SSE failed: ${i.status} ${i.statusText}`,statusCode:i.status,url:this.url.href});this.onerror?.(e);return}let a=i.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader(),o=async()=>{try{for(;;){let{done:e,value:t}=await a.read();if(e)return;let{event:n,data:r,id:i}=t;if(i&&(this.lastInboundEventId=i),an(n))try{let e=await M(r);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{a.cancel().catch(e=>{e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)})}},this.inboundReconnectAttempts=0;let c=this.inboundSseConnection;o().finally(()=>{this.inboundSseConnection===c&&(this.inboundSseConnection=void 0)}).catch(e=>{e instanceof Error&&e.name===`AbortError`||(this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function sn(e){switch(e.type){case`sse`:return new Zt(e);case`http`:return new on({...e,initialProtocolVersion:e.initialProtocolVersion??`2026-07-28`});default:throw new N({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function cn(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}const Q=`text/html;profile=mcp-app`,ln={extensions:{"io.modelcontextprotocol/ui":{mimeTypes:[Q]}}};function un(e){let n=e?.ui;return t(n)?n:void 0}const dn=y.array(y.unknown()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),fn=y.looseObject({connectDomains:dn,resourceDomains:dn,frameDomains:dn}),pn=y.looseObject({prefersBorder:y.boolean().optional().catch(void 0),csp:fn.optional().catch(void 0),permissions:y.record(y.string(),y.unknown()).optional().catch(void 0)});function mn(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=pn.safeParse(n);return r.success?r.data:void 0}function hn(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function gn(e){let t=un(e._meta),n=t?.resourceUri??e._meta?.[`ui/resourceUri`],r=hn(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function _n(e){let t=[],n=[];for(let r of e.tools){let e=gn(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function vn({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(l(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);let i=mn(n._meta);return{uri:e,mimeType:Q,html:r,meta:i}}async function yn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return vn({uri:t,resource:await e.readResource({uri:t,options:n})})}const bn=[-32020,-32021,-32022],xn=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function Sn(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function Cn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function wn(e){let t=Sn(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(N.isInstance(e)&&e.code!=null)return!1;let n=Cn(e);return n!=null&&xn.includes(n)}function Tn(e){if(e==null)return 0;if(!Number.isInteger(e))throw new N({message:`maxRetries must be an integer`});if(e<0)throw new N({message:`maxRetries must be >= 0`});return e}function En({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function Dn(e,t){return t==null?e:new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,a)},a=()=>{i(),r(t.reason)};if(t.aborted){a();return}t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{i(),n(e)}).catch(e=>{i(),r(e)})})}function On({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function kn(e){let t=new An(e);return await t.init(),t}var An=class{constructor({experimental_events:e,transport:t,name:n,clientName:r=n??`ai-sdk-mcp-client`,version:i=`1.0.0`,onUncaughtError:a,maxRetries:o,capabilities:s,initialInitializeResult:c,initializationOptions:l,protocolVersionDiscovery:u=!0}){if(this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:E,capabilities:{},serverInfo:this._serverInfo},this.protocolEra=`legacy`,this.protocolVersion=E,this.toolHeaderBindings=new Map,this.isClosed=!0,e?.adapter!==void 0&&(e.store!==void 0||e.validateArguments!==void 0))throw new N({message:`Configure experimental_events with either an adapter or a store, not both. Managed adapters own argument validation.`});if(e?.adapter!==void 0&&typeof e.adapter?.createAdapter!=`function`)throw new N({message:`experimental_events.adapter must implement createAdapter. Wrap bound operations with { createAdapter: () => operations }.`});let d=e?.adapter?.createAdapter({transport:cn(t)?{type:`custom`}:{type:t.type,url:t.url}});e?.adapter!==void 0&&rt(d),this.onUncaughtError=a,this.maxRetries=Tn(o),this.clientCapabilities=s??{},this.initialInitializeResult=c,this.initializationOptions=l,this.protocolVersionDiscovery=u,this.transport=cn(t)?t:sn(t),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new N({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:r,version:i};let f=nt({request:e=>this.request(e),store:e?.store,validateArguments:e?.validateArguments});this.experimental_events=d?it(d,f.list):f}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?En(this.initializationOptions):void 0,n=t==null?void 0:new AbortController,r=e==null?n?.signal:n==null?e:AbortSignal.any([e,n.signal]),i,a;t!=null&&(i=setTimeout(()=>{a=new N({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await Dn(this.transport.start(),r),this.initialInitializeResult){let e=le.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}if(this.protocolVersionDiscovery&&this.transport.supportsProtocolVersionDiscovery&&await this.tryProtocolDiscovery(r))return this;this.protocolEra=`legacy`,this.protocolVersion=E,this.setTransportProtocolVersion(this.protocolVersion);let e=await this.request({request:{method:`initialize`,params:{protocolVersion:E,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:le,options:{signal:r}});if(e===void 0)throw new N({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await Dn(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new N({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}async tryProtocolDiscovery(e){this.protocolEra=`modern`,this.protocolVersion=T,this.setTransportProtocolVersion(this.protocolVersion);try{let t=await this.request({request:{method:`server/discover`},resultSchema:ce,options:{signal:e,timeout:this.transport instanceof on?void 0:1e3}});return this.applyDiscoverResult(t),!0}catch(e){if(N.isInstance(e)&&e.code!=null&&bn.includes(e.code))throw e;return!1}}applyDiscoverResult(e){if(!e.supportedVersions.includes(this.protocolVersion))throw new N({message:`Server does not support the requested protocol version: ${this.protocolVersion}`});let t=e._meta?.[`io.modelcontextprotocol/serverInfo`];typeof t==`object`&&t&&`name`in t&&typeof t.name==`string`&&`version`in t&&typeof t.version==`string`&&(this._serverInfo=t),this.serverCapabilities=e.capabilities,this._serverInstructions=e.instructions,this._initializeResult={protocolVersion:this.protocolVersion,capabilities:e.capabilities,serverInfo:this._serverInfo,instructions:e.instructions}}setTransportProtocolVersion(e){this.transport.setProtocolVersion?this.transport.setProtocolVersion(e):this.transport.protocolVersion=e}applyInitializeResult(e){if(!ne.includes(e.protocolVersion))throw new N({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this.protocolEra=`legacy`,this.protocolVersion=e.protocolVersion,this._serverInfo=e.serverInfo,this._initializeResult=e,this.setTransportProtocolVersion(e.protocolVersion),this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}send(e,t){return t==null?this.transport.send(e):this.transport.send(e,t)}assertCapability(e){switch(e){case`initialize`:case`server/discover`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new N({message:`Server does not support completions`});break;case`events/list`:case`events/subscribe`:case`events/unsubscribe`:if(!this.serverCapabilities.events)throw new N({message:`Server does not support events`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new N({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new N({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new N({message:`Server does not support prompts`});break;default:throw new N({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new N({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:En(n),s=o==null?void 0:new AbortController,c=a==null?s?.signal:s==null?a:AbortSignal.any([a,s.signal]),l,u=this.requestMessageId++,d=this.protocolEra===`modern`?{...e,params:{...e.params,_meta:{...e.params?._meta,"io.modelcontextprotocol/protocolVersion":this.protocolVersion,"io.modelcontextprotocol/clientCapabilities":this.clientCapabilities,"io.modelcontextprotocol/clientInfo":this.clientInfo}}}:e,f={...d,jsonrpc:`2.0`,id:u},p=this.getToolRequestHeaders(d),m=()=>{i(new N({message:`Request was aborted`,cause:a?.reason}))},h=()=>{this.responseHandlers.delete(u),a?.removeEventListener(`abort`,_),l!=null&&clearTimeout(l)},g=e=>{h(),i(e)},_=()=>{h(),m()};this.responseHandlers.set(u,e=>{if(a?.aborted)return h(),m();if(e instanceof Error)return g(e);try{if(this.protocolEra===`modern`&&e.result.resultType==null)throw new N({message:`Modern MCP result is missing resultType`});if(e.result.resultType===`input_required`)throw new N({message:`Server requested additional input, but multi round-trip requests are not supported yet`});let n=t.parse(e.result);h(),r(n)}catch(e){let t=N.isInstance(e)?e:new N({message:`Failed to parse server response`,cause:e});g(t)}}),a?.addEventListener(`abort`,_,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new N({message:`Request timed out after ${o}ms`});s?.abort(e),g(e)},o));let v={...c==null?{}:{signal:c},...p==null?{}:{headers:p}};(Object.keys(v).length===0?this.send(f):this.send(f,v)).catch(e=>{g(e)})})}async listTools({params:e,options:t}={}){let n=await this.request({request:{method:`tools/list`,params:e},resultSchema:de,options:t});return this.prepareToolDefinitions(n,e?.cursor==null)}prepareToolDefinitions(e,t=!1){if(this.protocolEra!==`modern`||!this.transport.supportsMcpToolParameterHeaders)return e;t&&this.toolHeaderBindings.clear();let n=e.tools.filter(e=>{let t=tn(e.inputSchema);return t.success?(this.toolHeaderBindings.set(e.name,t.bindings),!0):(this.onError(new N({message:`Ignoring MCP tool "${e.name}": ${t.error}`})),!1)});return{...e,tools:n}}getToolRequestHeaders(e){if(this.protocolEra!==`modern`||e.method!==`tools/call`||typeof e.params?.name!=`string`)return;let t=this.toolHeaderBindings.get(e.params.name);if(t==null||t.length===0)return;let n=e.params.arguments;if(typeof n==`object`&&n&&!Array.isArray(n))try{return rn({bindings:t,args:n})}catch(t){throw new N({message:`Failed to create MCP headers for tool "${e.params.name}"`,cause:t})}}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():_({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:wn,createRetryError:({message:e,errors:t})=>new N({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:we,options:n})})}async listResourcesInternal({params:e,options:t}={}){return this.request({request:{method:`resources/list`,params:e},resultSchema:he,options:t})}async readResourceInternal({uri:e,options:t}){return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:De,options:t})}async listResourceTemplatesInternal({options:e}={}){return this.request({request:{method:`resources/templates/list`},resultSchema:Ee,options:e})}async listPromptsInternal({params:e,options:t}={}){return this.request({request:{method:`prompts/list`,params:e},resultSchema:Pe,options:t})}async getPromptInternal({name:e,args:t,options:n}){return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Ie,options:n})}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:je,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await Dn(this.send(n,t?.signal==null?void 0:{signal:t.signal}),t?.signal)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools(),n=[...t.tools];for(;t.nextCursor!=null;)t=await this.listTools({params:{cursor:t.nextCursor}}),n.push(...t.tools);return this.toolsFromDefinitions({...t,tools:n},{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){e=this.prepareToolDefinitions(e);let n=Object.create(null);for(let{name:i,title:a,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=a??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,i))continue;let u=this,d=t===`automatic`?void 0:t[i]?.outputSchema,p=gn({_meta:l}),h={clientName:this.clientInfo.name,toolName:i,...e==null?{}:{title:e},...c==null?{}:{annotations:{...c.title==null?{}:{title:c.title},...c.readOnlyHint==null?{}:{readOnlyHint:c.readOnlyHint},...c.destructiveHint==null?{}:{destructiveHint:c.destructiveHint},...c.idempotentHint==null?{}:{idempotentHint:c.idempotentHint},...c.openWorldHint==null?{}:{openWorldHint:c.openWorldHint}}},...p?.resourceUri==null?{}:{app:{...p,mimeType:Q}}},g=async(e,t)=>{t?.abortSignal?.throwIfAborted();let n=await u.callTool({name:i,arguments:e,options:{signal:t?.abortSignal}});return n.isError||d==null?n:u.extractStructuredContent(n,d,i)};n[i]={...t===`automatic`?m({description:o,title:e,metadata:h,inputSchema:r({...s,properties:s.properties??{},additionalProperties:!1}),execute:g,toModelOutput:On}):f({description:o,title:e,metadata:h,inputSchema:t[i].inputSchema,...d==null?{}:{outputSchema:d},execute:g,toModelOutput:On}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await d({value:e.structuredContent,schema:p(t)});if(!r.success)throw new N({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await u({text:r.text,schema:t});if(!e.success)throw new N({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new N({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==A)throw new N({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=A.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=Re.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new N({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){if(e.id==null){this.onError(new N({message:`Protocol error: Received a response without a message ID: ${JSON.stringify(e)}`}));return}let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new N({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new N({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};const jn=new TextEncoder;function $(e){if(typeof e!=`object`||!e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map($).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${$(t[e])}`).join(`,`)}}`}function Mn(e){return h(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function Nn(e){let t=await crypto.subtle.digest(`SHA-256`,jn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return Mn(new Uint8Array(t))}function Pn(e,t){return e!==t}const Fn=262144,In=b.object({type:b.literal(`verification`),challenge:b.string().min(1)});function Ln({store:e,validatePayload:t,onEvent:n,onGap:r,onTerminated:i,onError:a}){return async o=>{if(o.method!==`POST`)return new Response(null,{status:405,headers:{Allow:`POST`}});if(o.headers.get(`content-type`)?.split(`;`)[0].trim().toLowerCase()!==`application/json`)return new Response(null,{status:415});if(Number(o.headers.get(`content-length`))>Fn)return new Response(null,{status:413});try{let s=new URL(o.url).searchParams.get(tt),c=o.headers.get(`X-MCP-Subscription-Id`);if(!s||!c)return new Response(null,{status:401});let l=await e.get(s);if(!l||l.id!=null&&l.id!==c)return new Response(null,{status:401});let d=o.body?.getReader();if(!d)return new Response(null,{status:400});let f=[],p=0;try{for(;;){let{done:e,value:t}=await d.read();if(e)break;if(p+=t.byteLength,p>Fn)return await d.cancel(),new Response(null,{status:413});f.push(t)}}finally{d.releaseLock()}let m=new Uint8Array(p),h=0;for(let e of f)m.set(e,h),h+=e.length;if(!await Je({headers:o.headers,body:m,secret:l.delivery.secret}))return new Response(null,{status:401});let g=await u({text:new TextDecoder().decode(m)});if(!g.success)return new Response(null,{status:400});let _=g.value,v;if(typeof _==`object`&&_&&`type`in _){if(_.type===`verification`){let e=In.safeParse(_);return e.success?Response.json({challenge:e.data.challenge}):new Response(null,{status:400})}let e=et.safeParse(_);if(!e.success)return new Response(null,{status:400});v=e.data}if(l.id==null||l.status!==`active`&&v?.type!==`terminated`)return new Response(null,{status:503});let y={id:l.id,name:l.name,arguments:l.arguments,delivery:{mode:`webhook`,url:l.delivery.url},refreshBefore:l.refreshBefore??null};if(v){let t=o.headers.get(`webhook-id`);return v.type===`gap`?(await r?.({subscription:y,messageId:t,gap:v}),await e.update(l.key,{cursor:v.cursor,truncated:!0})):(await i?.({subscription:y,messageId:t,termination:v}),await e.delete(l.key)),new Response(null,{status:204})}if(l.refreshBefore!=null&&Date.parse(l.refreshBefore)<=Date.now())return new Response(null,{status:410});let b=$e.safeParse(_);if(!b.success||b.data.name!==l.name||b.data.eventId!==o.headers.get(`webhook-id`))return new Response(null,{status:400});try{await t?.({definition:l.definition,data:b.data.data})}catch(e){return a?.(e),new Response(null,{status:400})}return await n({subscription:y,event:b.data}),b.data.cursor!==void 0&&await e.update(l.key,{cursor:b.data.cursor}),new Response(null,{status:204})}catch(e){return a?.(e),new Response(null,{status:503})}}}export{vt as AuthorizationServerMismatchError,Re as ElicitResultSchema,A as ElicitationRequestSchema,N as MCPClientError,F as MCPClientOAuthError,Q as MCP_APP_MIME_TYPE,V as UnauthorizedError,Z as auth,kn as createMCPClient,kn as experimental_createMCPClient,Pn as detectMCPAppResourceDrift,Ln as experimental_createMCPEventWebhook,Nn as fingerprintMCPAppResource,ln as mcpAppClientCapabilities,yn as readMCPAppResource,_n as splitMCPAppTools,j as validateJSONRPCMessage};
|
|
1
|
+
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{I as n,K as r,M as i,N as a,St as o,Tt as s,U as c,c as l,dt as u,ft as d,gt as f,i as p,j as m,p as h,tt as g,ut as _,yt as v}from"../../_chunks/workflow/dist-C8k3N3BQ.js";import*as y from"#compiled/zod/index.js";import{z as b}from"#compiled/zod/index.js";let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function S(e){return(await x).getRandomValues(new Uint8Array(e))}async function C(e){let t=``;for(;t.length<e;){let n=await S(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function w(e){return await C(e)}async function ee(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function te(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await w(e);return{code_verifier:t,code_challenge:await ee(t)}}const T=`2026-07-28`,E=`2025-11-25`,ne=[T,E,`2025-06-18`,`2025-03-26`,`2024-11-05`],re=b.optional(b.record(b.string(),b.unknown())),ie=b.looseObject({name:b.string(),version:b.string(),title:b.optional(b.string())}),D=b.looseObject({_meta:b.optional(b.object({}).loose())}),O=D.extend({resultType:b.optional(b.string())}),ae=b.object({method:b.string(),params:b.optional(D)}),oe=b.object({applyDefaults:b.optional(b.boolean())}).loose(),se=b.looseObject({events:b.looseObject({listChanged:b.boolean().nullish()}).nullish(),experimental:b.optional(b.object({}).loose()),logging:b.optional(b.object({}).loose()),completions:b.optional(b.object({}).loose()),prompts:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),resources:b.optional(b.looseObject({subscribe:b.optional(b.boolean()),listChanged:b.optional(b.boolean())})),tools:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),elicitation:b.optional(oe)});b.object({elicitation:b.optional(oe)}).loose();const ce=O.extend({supportedVersions:b.array(b.string()),capabilities:se,instructions:b.optional(b.string()),ttlMs:b.optional(b.number()),cacheScope:b.optional(b.union([b.literal(`public`),b.literal(`private`)]))}),le=O.extend({protocolVersion:b.string(),capabilities:se,serverInfo:ie,instructions:b.optional(b.string())}),k=O.extend({nextCursor:b.optional(b.string())}),ue=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),inputSchema:b.looseObject({type:b.optional(b.unknown()),properties:b.optional(b.object({}).loose())}),outputSchema:b.optional(b.object({}).loose()),annotations:b.optional(b.object({title:b.optional(b.string()),readOnlyHint:b.optional(b.boolean()),destructiveHint:b.optional(b.boolean()),idempotentHint:b.optional(b.boolean()),openWorldHint:b.optional(b.boolean())}).loose()),_meta:re}).loose(),de=k.extend({tools:b.array(ue)}),fe=b.object({type:b.literal(`text`),text:b.string()}).loose(),pe=b.object({type:b.literal(`image`),data:b.base64(),mimeType:b.string()}).loose(),me=b.object({uri:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string()),size:b.optional(b.number())}).loose(),he=k.extend({resources:b.array(me)}),ge=b.object({uri:b.string(),name:b.optional(b.string()),title:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),_e=ge.extend({text:b.string()}),ve=ge.extend({blob:b.base64()}),ye=b.object({type:b.literal(`resource`),resource:b.union([_e,ve])}).loose(),be=b.object({type:b.literal(`resource_link`),uri:b.string(),name:b.string(),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),xe=b.object({type:b.string()}).loose().refine(e=>![`text`,`image`,`resource`,`resource_link`].includes(e.type),{message:`Known content types must match their schema`}),Se=O.extend({content:b.array(b.union([fe,pe,ye,be,xe])),structuredContent:b.optional(b.unknown()),isError:b.boolean().default(!1).optional()}),Ce=O.extend({content:b.never().optional(),structuredContent:b.json(),isError:b.boolean().default(!1).optional()}).transform(e=>({...e,content:[{type:`text`,text:JSON.stringify(e.structuredContent)}]})).pipe(Se),we=Se.or(Ce).or(O.extend({toolResult:b.unknown().nonoptional()})),Te=b.object({uriTemplate:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),Ee=O.extend({resourceTemplates:b.array(Te)}),De=O.extend({contents:b.array(b.union([_e,ve]))}),Oe=b.object({type:b.literal(`ref/prompt`),name:b.string()}).loose(),ke=b.object({type:b.literal(`ref/resource`),uri:b.string()}).loose(),Ae=b.object({name:b.string(),value:b.string()}).loose();D.extend({ref:b.union([Oe,ke]),argument:Ae,context:b.optional(b.object({arguments:b.record(b.string(),b.string())}).loose())});const je=O.extend({completion:b.object({values:b.array(b.string()).max(100),total:b.optional(b.number().int()),hasMore:b.optional(b.boolean())}).loose()}),Me=b.object({name:b.string(),description:b.optional(b.string()),required:b.optional(b.boolean())}).loose(),Ne=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),arguments:b.optional(b.array(Me))}).loose(),Pe=k.extend({prompts:b.array(Ne)}),Fe=b.object({role:b.union([b.literal(`user`),b.literal(`assistant`)]),content:b.union([fe,pe,ye,be])}).loose(),Ie=O.extend({description:b.optional(b.string()),messages:b.array(Fe)}),Le=D.extend({message:b.string(),requestedSchema:b.unknown()}),A=ae.extend({method:b.literal(`elicitation/create`),params:Le}),Re=O.extend({action:b.union([b.literal(`accept`),b.literal(`decline`),b.literal(`cancel`)]),content:b.optional(b.record(b.string(),b.unknown()))}),ze=b.object({jsonrpc:b.literal(`2.0`),id:b.union([b.string(),b.number().int()])}).merge(ae).strict(),Be=b.object({jsonrpc:b.literal(`2.0`),id:b.union([b.string(),b.number().int()]),result:O}).strict(),Ve=b.object({jsonrpc:b.literal(`2.0`),id:b.optional(b.union([b.string(),b.number().int()])),error:b.object({code:b.number().int(),message:b.string(),data:b.optional(b.unknown())})}).strict(),He=b.object({jsonrpc:b.literal(`2.0`)}).merge(b.object({method:b.string(),params:b.optional(D)})).strict(),Ue=b.union([ze,He,Be,Ve]);function j(e){return Ue.parse(e)}async function M(e){return j(await g({text:e}))}const We=`vercel.ai.error.AI_MCPClientError`,Ge=Symbol.for(We);var N=class extends e{constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[Ge]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,We)}};function Ke(){return`whsec_${h(crypto.getRandomValues(new Uint8Array(32)))}`}function qe(e){let t=e.slice(6);if(!e.startsWith(`whsec_`)||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new N({message:`Invalid MCP event signing secret`});let n=l(t);if(n.length<24||n.length>64)throw new N({message:`MCP event signing secrets must contain 24–64 random bytes`});return n}async function Je({headers:e,body:t,secret:n}){let r=e.get(`webhook-id`),i=e.get(`webhook-timestamp`),a=e.get(`webhook-signature`);if(!r||!i||!a||!/^\d+$/.test(i)||Math.abs(Date.now()/1e3-Number(i))>300)return!1;let o=await crypto.subtle.importKey(`raw`,new Uint8Array(qe(n)),{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]),s=new TextEncoder().encode(`${r}.${i}.`),c=new Uint8Array(s.length+t.length);c.set(s),c.set(t,s.length);for(let e of a.split(` `)){let[t,n]=e.split(`,`);if(t===`v1`&&n)try{if(await crypto.subtle.verify(`HMAC`,o,new Uint8Array(l(n)),c))return!0}catch{}}return!1}const Ye=b.union([b.boolean(),b.record(b.string(),b.unknown())]),Xe=b.looseObject({name:b.string().min(1),description:b.string().nullish(),delivery:b.array(b.enum([`webhook`,`poll`,`push`])).min(1),inputSchema:Ye,payloadSchema:Ye}),Ze=O.extend({events:b.array(Xe),nextCursor:b.string().nullish()}),Qe=O.extend({id:b.string().min(1),refreshBefore:b.iso.datetime({offset:!0}).nullable(),cursor:b.string().nullish().transform(e=>e??null),truncated:b.boolean()}),$e=b.looseObject({eventId:b.string().min(1),name:b.string().min(1),timestamp:b.iso.datetime({offset:!0}),data:b.record(b.string(),b.unknown()),cursor:b.string().nullish()}),et=b.discriminatedUnion(`type`,[b.looseObject({type:b.literal(`gap`),cursor:b.string()}),b.looseObject({type:b.literal(`terminated`),error:b.looseObject({code:b.number().int(),message:b.string(),data:b.unknown().nullish()})})]).transform(e=>e.type===`gap`?{...e,truncated:!0}:e),tt=`mcp_event_subscription`;function nt({request:e,store:t,validateArguments:n}){function r(){if(!t)throw new N({message:`Configure experimental_events.store to manage direct event subscriptions`});return t}async function i({id:e,key:t}){let n=r(),i=e===void 0?await n.get(t):await n.getById(e);if(!i)throw new N({message:`Unknown MCP event subscription: ${e??t}`});return i}async function a(t,n){let i=await e({request:{method:`events/subscribe`,params:{name:t.name,arguments:t.arguments,delivery:t.delivery,cursor:t.cursor,...t.ttlMs===void 0?{}:{ttlMs:t.ttlMs},...t.maxAgeMs===void 0?{}:{maxAgeMs:t.maxAgeMs}}},resultSchema:Qe,options:n});return await r().update(t.key,{id:i.id,refreshBefore:i.refreshBefore,cursor:i.cursor,truncated:i.truncated,status:`active`}),i}let o={list({params:t,options:n}={}){return e({request:{method:`events/list`,params:t},resultSchema:Ze,options:n})},async subscribe({name:e,arguments:t={},delivery:i,cursor:s=null,ttlMs:c,maxAgeMs:l,options:u}){let d=r(),f=new URL(i.url),p=i.allowInsecureLocalhost===!0&&f.protocol===`http:`&&(f.hostname===`127.0.0.1`||f.hostname===`[::1]`);if(f.protocol!==`https:`&&!p||f.username||f.password||f.hash)throw new N({message:`MCP event callback URLs must use HTTPS without credentials or fragments`});if(i.mode!==`webhook`)throw new N({message:`Only webhook event delivery is supported`});if(c!=null&&(!Number.isSafeInteger(c)||c<=0)||l!=null&&(!Number.isSafeInteger(l)||l<0))throw new N({message:`Invalid MCP event subscription lifetime or replay age`});let m,h=new Set,g;do{let t=await o.list({params:{cursor:m},options:u});if(g=t.events.find(t=>t.name===e),g)break;if(m=t.nextCursor??void 0,m!=null){if(h.has(m))throw new N({message:`Repeated MCP events pagination cursor`});h.add(m)}}while(m!=null);if(!g)throw new N({message:`Unknown MCP event: ${e}`});if(!g.delivery.includes(`webhook`))throw new N({message:`MCP event ${e} does not support webhook delivery`});await n?.({definition:g,arguments:t});let _=i.secret??Ke();qe(_);let v=crypto.randomUUID();f.searchParams.set(tt,v);let y={key:v,name:e,arguments:structuredClone(t),definition:g,delivery:{mode:`webhook`,url:f.href,secret:_},cursor:s,truncated:!1,ttlMs:c,maxAgeMs:l,status:`pending`};return await d.set(y),a(y,u)},async refresh(e){let t=await i(e);return await r().update(t.key,{status:`pending`}),a(t,e.options)},async unsubscribe(t){let n=await i(t);await e({request:{method:`events/unsubscribe`,params:{name:n.name,arguments:n.arguments,delivery:{mode:`webhook`,url:n.delivery.url}}},resultSchema:O,options:t.options}),await r().delete(n.key)}};return o}function rt(e){if(e!=null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`)throw Promise.resolve(e).catch(()=>{}),new N({message:`experimental_events.adapter.createAdapter() must return operations synchronously. Promise and thenable results are not supported.`});if(typeof e!=`object`||!e||!(`subscribe`in e)||typeof e.subscribe!=`function`||!(`getSubscription`in e)||typeof e.getSubscription!=`function`||!(`listSubscriptions`in e)||typeof e.listSubscriptions!=`function`||!(`unsubscribe`in e)||typeof e.unsubscribe!=`function`)throw new N({message:`experimental_events.adapter.createAdapter() must return an object implementing subscribe, getSubscription, listSubscriptions, and unsubscribe.`})}function it(e,t){return{list:t,subscribe:t=>e.subscribe(t),getSubscription:t=>e.getSubscription(t),listSubscriptions:t=>e.listSubscriptions(t),unsubscribe:t=>e.unsubscribe(t)}}const at=`2.0.73`,P=b.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:b.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),b.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),ot=b.object({access_token:b.string(),id_token:b.string().optional(),token_type:b.string(),expires_in:b.number().optional(),scope:b.string().optional(),refresh_token:b.string().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),st=b.looseObject({resource:b.string().url(),authorization_servers:b.array(P).optional(),jwks_uri:b.string().url().optional(),scopes_supported:b.array(b.string()).optional(),bearer_methods_supported:b.array(b.string()).optional(),resource_signing_alg_values_supported:b.array(b.string()).optional(),resource_name:b.string().optional(),resource_documentation:b.string().optional(),resource_policy_uri:b.string().url().optional(),resource_tos_uri:b.string().url().optional(),tls_client_certificate_bound_access_tokens:b.boolean().optional(),authorization_details_types_supported:b.array(b.string()).optional(),dpop_signing_alg_values_supported:b.array(b.string()).optional(),dpop_bound_access_tokens_required:b.boolean().optional()}),ct=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),code_challenge_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_signing_alg_values_supported:b.array(b.string()).optional()}),lt=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,userinfo_endpoint:P.optional(),jwks_uri:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),subject_types_supported:b.array(b.string()),id_token_signing_alg_values_supported:b.array(b.string()),claims_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional()}).merge(ct.pick({code_challenge_methods_supported:!0})),ut=b.object({client_id:b.string(),client_secret:b.string().optional(),client_id_issued_at:b.number().optional(),client_secret_expires_at:b.number().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),dt=b.object({redirect_uris:b.array(P),application_type:b.union([b.literal(`native`),b.literal(`web`)]).optional(),token_endpoint_auth_method:b.string().optional(),grant_types:b.array(b.string()).optional(),response_types:b.array(b.string()).optional(),client_name:b.string().optional(),client_uri:P.optional(),logo_uri:P.optional(),scope:b.string().optional(),contacts:b.array(b.string()).optional(),tos_uri:P.optional(),policy_uri:b.string().optional(),jwks_uri:P.optional(),jwks:b.any().optional(),software_id:b.string().optional(),software_version:b.string().optional(),software_statement:b.string().optional()}).strip(),ft=b.object({error:b.string(),error_description:b.string().optional(),error_uri:b.string().optional()}),pt=dt.merge(ut),mt=`vercel.ai.error.AI_MCPClientOAuthError`,ht=Symbol.for(mt);var F=class extends e{constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[ht]=!0}static isInstance(t){return e.hasMarker(t,mt)}},I=class extends F{static{this.errorCode=`server_error`}},L=class extends F{static{this.errorCode=`invalid_client`}},R=class extends F{static{this.errorCode=`invalid_grant`}},z=class extends F{static{this.errorCode=`unauthorized_client`}};const gt=`vercel.ai.error.AI_AuthorizationServerMismatchError`,_t=Symbol.for(gt);var vt=class extends F{static{this.errorCode=`authorization_server_mismatch`}constructor({message:e,cause:t}){super({name:`AuthorizationServerMismatchError`,message:e,cause:t}),this[_t]=!0}static isInstance(t){return e.hasMarker(t,gt)}};const yt={[I.errorCode]:I,[L.errorCode]:L,[R.errorCode]:R,[z.errorCode]:z};function bt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function B(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function xt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var V=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function H(e){return new URL(e).href}function U(e){let t=e.toLowerCase().replace(/\.+$/,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function W(e,{allowLoopback:t=!1}={}){if(!t||e.protocol!==`http:`&&e.protocol!==`https:`||!U(e.hostname))try{v(e.href)}catch(t){throw new F({message:`OAuth endpoint URL is not allowed: ${e.href}`,cause:t})}}function G(e){let t=new URL(e);return U(t.hostname)?t.origin:void 0}function St({callbackIssuer:e,expectedIssuer:t}){if(e!=null&&e!==t)throw new F({message:`OAuth authorization response issuer ${e} does not match expected issuer ${t}`})}function Ct(e,t){return{issuer:t?.issuer??String(e),authorizationServerUrl:H(e),tokenEndpoint:H(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function wt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Tt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Et(e){if(e?.authorization_server&&e.token_endpoint)return{issuer:e.issuer,authorizationServerUrl:H(e.authorization_server),tokenEndpoint:H(e.token_endpoint)}}async function K({provider:e,clientInformation:t,tokens:n}){let r=Et(n);if(r)return r;let i=await e.authorizationServerInformation?.();return i?{issuer:i.issuer,authorizationServerUrl:H(i.authorizationServerUrl),tokenEndpoint:H(i.tokenEndpoint)}:Et(t)}async function Dt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(Tt(t,n)),!0):!1}function Ot(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new F({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function q({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.issuer!=null&&t.issuer!=null&&e.issuer!==t.issuer||e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new vt({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function J(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=t.match(/(?:^|[,\s])resource_metadata="([^"]*)"/i),a=t.match(/(?:^|[,\s])scope="([^"]*)"/i)?.[1],o;try{o=i?new URL(i[1]):void 0}catch{}return{resourceMetadataUrl:o,scope:a}}function kt({scope:e,resourceMetadata:t,clientMetadata:n}){return e||t?.scopes_supported?.join(` `)||n.scope}function At(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Y(e,t,n=fetch,r){try{return await i({url:e.href,fetch:async(e,i)=>a({url:e,init:{...i,headers:new Headers(i?.headers).has(`MCP-Protocol-Version`)?t:void 0},fetch:n,trustedOrigin:r,redirect:`manual`}),headers:t,trustedOrigin:r,untrustedFirstHopHeaders:[`mcp-protocol-version`]})}catch(i){if(i instanceof TypeError)return t?Y(e,void 0,n,r):void 0;throw i}}async function jt(e,t,n=fetch,r){return await Y(e,{"MCP-Protocol-Version":t},n,r)}function Mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Nt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2026-07-28`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=At(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await jt(o,a,n,r?.trustedOrigin);return!r?.metadataUrl&&Mt(s,i.pathname)&&(s=await jt(new URL(`/.well-known/${t}`,i),a,n,r?.trustedOrigin)),s}async function Pt(e,t,n=fetch){let r=await Nt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl,trustedOrigin:new URL(e).origin});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return st.parse(await r.json())}function Ft(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o});let s=new URL(t.origin);return s.pathname=`${a}/.well-known/openid-configuration`,i.push({url:s,type:`oidc`,expectedIssuer:o}),i}function It(e,t){if(!(e.issuer===t||t===new URL(t).origin&&e.issuer===`${t}/`))throw new F({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Lt(e,{fetchFn:t=fetch,protocolVersion:n=T,trustedOrigin:r}={}){let i={"MCP-Protocol-Version":n},a=new URL(e).origin,o=Ft(e);if(o.some(({url:e})=>e.origin!==a))throw new F({message:`OAuth discovery URL changed authorization-server origin`});for(let{url:e,type:n,expectedIssuer:a}of o){let o=await Y(e,i,t,r);if(o){if(!o.ok){if(o.status>=400&&o.status<500)continue;throw Error(`HTTP ${o.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=ct.parse(await o.json());return It(e,a),e}{let t=lt.parse(await o.json());if(It(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Rt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await te(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,B(o)),{authorizationUrl:l,codeVerifier:d}}function zt(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Bt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Vt(i,a,n);return;case`client_secret_post`:Ht(i,a,r);return;case`none`:Ut(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Vt(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Ht(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Ut(e,t){t.set(`client_id`,e)}async function X(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ft.parse(await g({text:n}));return new(yt[e]||I)({message:t||``,cause:r})}catch(e){return new I({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Wt(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:c,fetchFn:l}){let u=`authorization_code`,d=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),f=G(e);if(W(d,{allowLoopback:d.origin===f}),t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),m=new URLSearchParams({grant_type:u,code:r,code_verifier:i,redirect_uri:String(o)});c?await c(p,m,e,t):Bt(zt(n,t?.token_endpoint_auth_methods_supported??[]),n,p,m),s&&m.set(`resource`,B(s));let h=await a({url:d,init:{method:`POST`,headers:p,body:m},fetch:l,trustedOrigin:f});if(!h.ok)throw await X(h);return ot.parse(await h.json())}async function Gt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:o,fetchFn:s}){let c=`refresh_token`,l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL(`/token`,e);let u=G(e);W(l,{allowLoopback:l.origin===u});let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:c,refresh_token:r});o?await o(d,f,e,t):Bt(zt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),i&&f.set(`resource`,B(i));let p=await a({url:l,init:{method:`POST`,headers:d,body:f},fetch:s,trustedOrigin:u});if(!p.ok)throw await X(p);return ot.parse({refresh_token:r,...await p.json()})}async function Kt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let o=G(e);W(i,{allowLoopback:i.origin===o});let s=n.application_type??qt(n.redirect_uris),c=await a({url:i,init:{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,application_type:s})},fetch:r,trustedOrigin:o});if(!c.ok)throw await X(c);return pt.parse(await c.json())}function qt(e){return e.every(e=>{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&U(t.hostname)||t.protocol!==`http:`&&t.protocol!==`https:`})?`native`:`web`}async function Z(e,t){let n={};try{return await Yt(e,t,n)}catch(r){if(r instanceof L||r instanceof z){if(t.authorizationCode!==void 0||!await e.isClientInformationDynamicallyRegistered?.())throw r;return await e.invalidateCredentials?.(`all`),await Yt(e,t)}if(r instanceof R&&n.tokens)return await e.invalidateCredentials?.(`tokens`,{tokens:n.tokens}),await Yt(e,t);throw r}}async function Jt(e,t,n){let r=bt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!xt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Yt(e,{serverUrl:t,authorizationCode:n,callbackState:r,callbackIssuer:i,scope:a,resourceMetadataUrl:o,fetchFn:s},c){let l,u,d,f;Ot(t,o);try{l=await Pt(t,{resourceMetadataUrl:o},s),l.authorization_servers&&l.authorization_servers.length>0&&(u=l.authorization_servers[0])}catch{}n!==void 0&&(d=await Promise.resolve(e.clientInformation()),d&&(f=await K({provider:e,clientInformation:d}))),u||=f?.authorizationServerUrl??t;let p=new URL(t),m=new URL(u),h=p.origin,g=m.origin,_=g===h||U(p.hostname)&&U(m.hostname)?g:void 0;_||W(new URL(u));let v=await Jt(t,e,l);await e.validateAuthorizationServerURL?.(t,u);let y=await Lt(u,{fetchFn:s,trustedOrigin:_}),b=Ct(u,y),x=e.clientMetadata,S=kt({scope:a,resourceMetadata:l,clientMetadata:x});if(n===void 0&&(d=await Promise.resolve(e.clientInformation())),d?.issuer!=null){let t=f??await K({provider:e,clientInformation:d});t&&q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b})}if(!d){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);d=Tt(await Kt(u,{metadata:y,clientMetadata:{...x,scope:S},fetchFn:s}),b),await e.saveClientInformation(d)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=f??await K({provider:e,clientInformation:d});if(!t)throw new F({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});St({callbackIssuer:i,expectedIssuer:t.issuer??y?.issuer??String(u)}),q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b});let a=await e.codeVerifier(),o=await Wt(u,{metadata:y,clientInformation:d,authorizationCode:n,codeVerifier:a,redirectUri:e.redirectUrl,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(wt(o,b)),`AUTHORIZED`}let C=await e.tokens();if(C?.refresh_token){let t=await K({provider:e,clientInformation:d,tokens:C});t?q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:b}):await e.invalidateCredentials?.(`tokens`,{tokens:{...C}});try{if(t){c&&(c.tokens={...C});let t=await Gt(u,{metadata:y,clientInformation:d,refreshToken:C.refresh_token,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(wt(t,b)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof F)||e instanceof I))throw e}}let w=e.state?await e.state():void 0;w&&e.saveState&&await e.saveState(w);let{authorizationUrl:ee,codeVerifier:te}=await Rt(u,{metadata:y,clientInformation:d,state:w,redirectUrl:e.redirectUrl,scope:S,resource:v});if(!await Dt({provider:e,clientInformation:d,authorizationServerInformation:b}))throw new F({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(te),await e.redirectToAuthorization(ee),`REDIRECT`}function Xt(e){return e===void 0||e===`message`}var Zt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??`2025-11-25`};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return o(t,`ai-sdk/${at}`,n())}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async accessTokenChanged(e){let t=(await this.authProvider?.tokens())?.access_token;return t!=null&&e!==`Bearer ${t}`}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{try{let i=await this.commonHeaders({Accept:`text/event-stream`}),a=await this.fetchFn(this.url.href,{headers:i,signal:this.abortController?.signal,redirect:this.redirectMode});if(a.status===401&&this.authProvider&&!r){let{resourceMetadataUrl:e,scope:r}=J(a);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,r)!==`AUTHORIZED`){let e=new V;return this.onerror?.(e),t(e)}}catch(e){return this.onerror?.(e),t(e)}return n(!0)}if(!a.ok||!a.body){let e=`MCP SSE Transport Error: ${a.status} ${a.statusText}`;a.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new N({message:e});return this.onerror?.(n),t(n)}let o=a.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader(),c=async()=>{try{for(;;){let{done:t,value:n}=await o.read();if(t){if(this.abortController?.signal.aborted)return;throw this.connected?(this.connected=!1,new N({message:`MCP SSE Transport Error: Connection closed unexpectedly`})):new N({message:`MCP SSE Transport Error: Connection closed before endpoint event was received`})}let{event:r,data:i}=n;if(r===`endpoint`){if(this.endpoint)continue;let t=new URL(i,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,this.sseConnection?.close(),this.abortController?.abort(),new N({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Xt(r))try{let e=await M(i);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),t(e)}};this.sseConnection={close:()=>o.cancel()},c()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),t(e)}};n()})}async close(){this.connected=!1,this.endpoint=void 0,this.sseConnection?.close(),this.abortController?.abort(),this.onclose?.()}async send(e,t){if(t?.signal?.throwIfAborted(),!this.endpoint||!this.connected)throw new N({message:`MCP SSE Transport Error: Not connected`});let n=this.endpoint,r=this.abortController?.signal,i=t?.signal==null?r:r==null?t.signal:AbortSignal.any([r,t.signal]),a=async(r=!1)=>{try{let t=await this.commonHeaders({"Content-Type":`application/json`}),o={method:`POST`,headers:t,body:JSON.stringify(e),signal:i,redirect:this.redirectMode},s=await this.fetchFn(n.href,o);if(s.status===401&&this.authProvider&&!r){if(await this.accessTokenChanged(new Headers(t).get(`authorization`)??void 0))return a(!0);let{resourceMetadataUrl:e,scope:n}=J(s);if(this.resourceMetadataUrl=e,await this.authorizeOnce(this.resourceMetadataUrl,n)!==`AUTHORIZED`)throw new V;return a(!0)}if(!s.ok){let e=await s.text().catch(()=>null);throw new N({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${s.status}): ${e}`,statusCode:s.status,url:n.href,responseBody:e??void 0})}}catch(e){throw t?.signal?.aborted||this.onerror?.(e),e}};await a()}};const Qt=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,$t=/^=\?base64\?.*\?=$/;function en(e){return[...e].every(e=>{let t=e.charCodeAt(0);return t===9||t>=32&&t<=126})&&e.trim()===e&&!$t.test(e)?e:`=?base64?${h(new TextEncoder().encode(e))}?=`}function tn(e){if(!c(e))return{success:!1,error:`inputSchema must be a JSON Schema object`};let t=[],n=new Set,r,i=(e,a,o)=>{if(r==null&&c(e)){if(`x-mcp-header`in e){if(!o||a.length===0){r=`x-mcp-header is not on a statically reachable property`;return}let i=e[`x-mcp-header`];if(typeof i!=`string`||!Qt.test(i)){r=`x-mcp-header must be a non-empty HTTP token`;return}let s=i.toLowerCase();if(n.has(s)){r=`x-mcp-header value "${i}" is not unique`;return}let c=e.type;if(c!==`boolean`&&c!==`integer`&&c!==`string`){r=`x-mcp-header can only annotate boolean, integer, or string properties`;return}n.add(s),t.push({headerName:i,path:a,valueType:c})}for(let[t,n]of Object.entries(e))if(t!==`x-mcp-header`){if(t===`properties`&&c(n))for(let[e,t]of Object.entries(n))i(t,[...a,e],o);else i(n,a,!1)}}};return i(e,[],!0),r==null?{success:!0,bindings:t}:{success:!1,error:r}}function nn(e,t){let n=e;for(let e of t){if(!c(n))return;n=n[e]}return n}function rn({bindings:e,args:t}){let n={};for(let r of e){let e=nn(t,r.path);if(e!=null){if(r.valueType===`string`&&typeof e!=`string`||r.valueType===`boolean`&&typeof e!=`boolean`||r.valueType===`integer`&&!Number.isSafeInteger(e))throw TypeError(`Tool argument "${r.path.join(`.`)}" does not match its x-mcp-header type`);n[`Mcp-Param-${r.headerName}`]=en(String(e))}}return n}function an(e){return e===void 0||e===`message`}var on=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.supportsProtocolVersionDiscovery=!0,this.supportsMcpToolParameterHeaders=!0,this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a??`2025-11-25`,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){if(this.protocolVersion=e,this.abortController){if(this.isModernProtocol()){this.inboundSseConnection?.close(),this.inboundSseConnection=void 0;return}this.sessionId&&this.startInboundSse()}}isModernProtocol(){return(this.protocolVersion??`2026-07-28`)===T}async commonHeaders({base:e,includeSessionId:t=!0}){let r={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??`2025-11-25`};if(!this.isModernProtocol()&&t&&this.sessionId&&(r[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(r.Authorization=`Bearer ${e.access_token}`)}return o(r,`ai-sdk/${at}`,n())}setSessionId(e){this.sessionId!==e&&(this.sessionId=e,this.onSessionIdChange?.(e))}applySessionIdFromResponse(e){if(this.isModernProtocol())return;let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){this.sessionId===e&&this.setSessionId(void 0),this.onSessionExpired?.(e)}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new N({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.protocolVersion!=null&&this.protocolVersion!==`2026-07-28`&&this.startInboundSse()}async close(e){this.inboundSseConnection?.close(),this.abortController?.abort();try{if(!this.isModernProtocol()&&this.sessionId&&this.terminateSessionOnClose&&this.abortController){e?.signal?.throwIfAborted();let t=await this.commonHeaders({base:{}});e?.signal?.throwIfAborted();let n=new AbortController,r=setTimeout(()=>n.abort(),5e3);await this.fetchFn(this.url.href,{method:`DELETE`,headers:t,signal:e?.signal??n.signal,redirect:this.redirectMode}).catch(()=>void 0).finally(()=>clearTimeout(r))}}catch{}this.onclose?.()}async send(e,t){t?.signal?.throwIfAborted();let n=this.abortController?.signal,r=t?.signal==null?n:n==null?t.signal:AbortSignal.any([n,t.signal]),i=async(n=!1)=>{try{let a=`method`in e&&e.method===`initialize`,o=a?void 0:this.sessionId,c={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...this.isModernProtocol()?t?.headers:{},...this.isModernProtocol()&&`method`in e&&`id`in e?this.getStandardRequestHeaders(e):{}},includeSessionId:!a}),body:JSON.stringify(e),signal:r,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c);if(this.applySessionIdFromResponse(l),l.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=J(l);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,t)!==`AUTHORIZED`)throw new V}catch(e){throw this.onerror?.(e),e}return i(!0)}if(l.status===202){!this.isModernProtocol()&&!this.inboundSseConnection&&this.startInboundSse();return}if(!l.ok){let t=await l.text().catch(()=>null);if(`id`in e&&t!=null){let n=await M(t).catch(()=>void 0);if(n!=null&&`error`in n){this.onmessage?.(n.id==null?{...n,id:e.id}:n);return}}let n=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${t}`;l.status===404&&(!this.isModernProtocol()&&o?(this.expireSessionId(o),n+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):this.isModernProtocol()||(n+=". This server does not support HTTP transport. Try using `sse` transport instead"));let r=new N({message:n,statusCode:l.status,url:this.url.href,responseBody:t??void 0});throw this.onerror?.(r),r}if(!(`id`in e))return;let u=l.headers.get(`content-type`)||``;if(u.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>j(e)):[j(e)];for(let e of t)this.onmessage?.(e);return}if(u.includes(`text/event-stream`)){if(!l.body){let e=new N({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:l.status,url:this.url.href});throw this.onerror?.(e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader();(async()=>{try{for(;;){let{done:t,value:n}=await e.read();if(t)return;let{event:r,data:i}=n;if(an(r))try{let e=await M(i);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e)}})().catch(e=>{t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)});return}let d=new N({message:`MCP HTTP Transport Error: Unexpected content type: ${u}`,statusCode:l.status,url:this.url.href});throw this.onerror?.(d),d}catch(e){throw t?.signal?.aborted||this.onerror?.(e),e}};await i()}getStandardRequestHeaders(e){let t={"Mcp-Method":e.method},n=e.params,r=e.method===`resources/read`?n?.uri:e.method===`tools/call`||e.method===`prompts/get`?n?.name:void 0;return typeof r==`string`&&(t[`Mcp-Name`]=en(r)),t}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){let{maxRetries:e}=this.reconnectionOptions;if(e>0&&this.inboundReconnectAttempts>=e){this.onerror?.(new N({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${e}) exceeded.`}));return}let t=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},t)}startInboundSse(e=!1,t){if(this.isModernProtocol()||this.inboundSseConnection)return;let n={close(){}};this.inboundSseConnection=n,this.openInboundSse(e,t).finally(()=>{this.inboundSseConnection===n&&(this.inboundSseConnection=void 0)}).catch(e=>{e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)})}async openInboundSse(e=!1,t){if(!this.isModernProtocol())try{let n=this.sessionId,r=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(r[`last-event-id`]=t);let i=await this.fetchFn(this.url.href,{method:`GET`,headers:r,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(i),i.status===401&&this.authProvider&&!e){let{resourceMetadataUrl:e,scope:n}=J(i);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,n)!==`AUTHORIZED`){let e=new V;this.onerror?.(e);return}}catch(e){this.onerror?.(e);return}return this.openInboundSse(!0,t)}if(i.status===405)return;if(!i.ok||!i.body){i.status===404&&n&&this.expireSessionId(n);let e=new N({message:`MCP HTTP Transport Error: GET SSE failed: ${i.status} ${i.statusText}`,statusCode:i.status,url:this.url.href});this.onerror?.(e);return}let a=i.body.pipeThrough(new TextDecoderStream).pipeThrough(new s).getReader(),o=async()=>{try{for(;;){let{done:e,value:t}=await a.read();if(e)return;let{event:n,data:r,id:i}=t;if(i&&(this.lastInboundEventId=i),an(n))try{let e=await M(r);this.onmessage?.(e)}catch(e){let t=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});this.onerror?.(t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{a.cancel().catch(e=>{e instanceof Error&&e.name===`AbortError`||this.onerror?.(e)})}},this.inboundReconnectAttempts=0;let c=this.inboundSseConnection;o().finally(()=>{this.inboundSseConnection===c&&(this.inboundSseConnection=void 0)}).catch(e=>{e instanceof Error&&e.name===`AbortError`||(this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;this.onerror?.(e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function sn(e){switch(e.type){case`sse`:return new Zt(e);case`http`:return new on({...e,initialProtocolVersion:e.initialProtocolVersion??`2026-07-28`});default:throw new N({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function cn(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}const Q=`text/html;profile=mcp-app`,ln={extensions:{"io.modelcontextprotocol/ui":{mimeTypes:[Q]}}};function un(e){let n=e?.ui;return t(n)?n:void 0}const dn=y.array(y.unknown()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),fn=y.looseObject({connectDomains:dn,resourceDomains:dn,frameDomains:dn}),pn=y.looseObject({prefersBorder:y.boolean().optional().catch(void 0),csp:fn.optional().catch(void 0),permissions:y.record(y.string(),y.unknown()).optional().catch(void 0)});function mn(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=pn.safeParse(n);return r.success?r.data:void 0}function hn(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function gn(e){let t=un(e._meta),n=t?.resourceUri??e._meta?.[`ui/resourceUri`],r=hn(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function _n(e){let t=[],n=[];for(let r of e.tools){let e=gn(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function vn({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(l(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);let i=mn(n._meta);return{uri:e,mimeType:Q,html:r,meta:i}}async function yn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return vn({uri:t,resource:await e.readResource({uri:t,options:n})})}const bn=[-32020,-32021,-32022],xn=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function Sn(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function Cn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function wn(e){let t=Sn(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(N.isInstance(e)&&e.code!=null)return!1;let n=Cn(e);return n!=null&&xn.includes(n)}function Tn(e){if(e==null)return 0;if(!Number.isInteger(e))throw new N({message:`maxRetries must be an integer`});if(e<0)throw new N({message:`maxRetries must be >= 0`});return e}function En({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function Dn(e,t){return t==null?e:new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,a)},a=()=>{i(),r(t.reason)};if(t.aborted){a();return}t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{i(),n(e)}).catch(e=>{i(),r(e)})})}function On({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function kn(e){let t=new An(e);return await t.init(),t}var An=class{constructor({experimental_events:e,transport:t,name:n,clientName:r=n??`ai-sdk-mcp-client`,version:i=`1.0.0`,onUncaughtError:a,maxRetries:o,capabilities:s,initialInitializeResult:c,initializationOptions:l,protocolVersionDiscovery:u=!0}){if(this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:E,capabilities:{},serverInfo:this._serverInfo},this.protocolEra=`legacy`,this.protocolVersion=E,this.toolHeaderBindings=new Map,this.isClosed=!0,e?.adapter!==void 0&&(e.store!==void 0||e.validateArguments!==void 0))throw new N({message:`Configure experimental_events with either an adapter or a store, not both. Managed adapters own argument validation.`});if(e?.adapter!==void 0&&typeof e.adapter?.createAdapter!=`function`)throw new N({message:`experimental_events.adapter must implement createAdapter. Wrap bound operations with { createAdapter: () => operations }.`});let d=e?.adapter?.createAdapter({transport:cn(t)?{type:`custom`}:{type:t.type,url:t.url}});e?.adapter!==void 0&&rt(d),this.onUncaughtError=a,this.maxRetries=Tn(o),this.clientCapabilities=s??{},this.initialInitializeResult=c,this.initializationOptions=l,this.protocolVersionDiscovery=u,this.transport=cn(t)?t:sn(t),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new N({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:r,version:i};let f=nt({request:e=>this.request(e),store:e?.store,validateArguments:e?.validateArguments});this.experimental_events=d?it(d,f.list):f}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?En(this.initializationOptions):void 0,n=t==null?void 0:new AbortController,r=e==null?n?.signal:n==null?e:AbortSignal.any([e,n.signal]),i,a;t!=null&&(i=setTimeout(()=>{a=new N({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await Dn(this.transport.start(),r),this.initialInitializeResult){let e=le.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}if(this.protocolVersionDiscovery&&this.transport.supportsProtocolVersionDiscovery&&await this.tryProtocolDiscovery(r))return this;this.protocolEra=`legacy`,this.protocolVersion===T&&(this.protocolVersion=E),this.setTransportProtocolVersion(this.protocolVersion);let e=await this.request({request:{method:`initialize`,params:{protocolVersion:this.protocolVersion,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:le,options:{signal:r}});if(e===void 0)throw new N({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await Dn(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new N({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}async tryProtocolDiscovery(e){this.protocolEra=`modern`,this.protocolVersion=T,this.setTransportProtocolVersion(this.protocolVersion);try{let t=await this.request({request:{method:`server/discover`},resultSchema:ce,options:{signal:e,timeout:this.transport instanceof on?void 0:1e3}});return this.applyDiscoverResult(t),!0}catch(e){if(N.isInstance(e)&&e.code!=null&&bn.includes(e.code)){if(e.code!==-32022||!Array.isArray(e.data?.supported))throw e;let t=e.data.supported,n=ne.find(e=>e!==T&&t.includes(e));if(n===void 0)throw e;return this.protocolVersion=n,!1}return!1}}applyDiscoverResult(e){if(!e.supportedVersions.includes(this.protocolVersion))throw new N({message:`Server does not support the requested protocol version: ${this.protocolVersion}`});let t=e._meta?.[`io.modelcontextprotocol/serverInfo`];typeof t==`object`&&t&&`name`in t&&typeof t.name==`string`&&`version`in t&&typeof t.version==`string`&&(this._serverInfo=t),this.serverCapabilities=e.capabilities,this._serverInstructions=e.instructions,this._initializeResult={protocolVersion:this.protocolVersion,capabilities:e.capabilities,serverInfo:this._serverInfo,instructions:e.instructions}}setTransportProtocolVersion(e){this.transport.setProtocolVersion?this.transport.setProtocolVersion(e):this.transport.protocolVersion=e}applyInitializeResult(e){if(!ne.includes(e.protocolVersion))throw new N({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this.protocolEra=`legacy`,this.protocolVersion=e.protocolVersion,this._serverInfo=e.serverInfo,this._initializeResult=e,this.setTransportProtocolVersion(e.protocolVersion),this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}send(e,t){return t==null?this.transport.send(e):this.transport.send(e,t)}assertCapability(e){switch(e){case`initialize`:case`server/discover`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new N({message:`Server does not support completions`});break;case`events/list`:case`events/subscribe`:case`events/unsubscribe`:if(!this.serverCapabilities.events)throw new N({message:`Server does not support events`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new N({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new N({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new N({message:`Server does not support prompts`});break;default:throw new N({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new N({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:En(n),s=o==null?void 0:new AbortController,c=a==null?s?.signal:s==null?a:AbortSignal.any([a,s.signal]),l,u=this.requestMessageId++,d=this.protocolEra===`modern`?{...e,params:{...e.params,_meta:{...e.params?._meta,"io.modelcontextprotocol/protocolVersion":this.protocolVersion,"io.modelcontextprotocol/clientCapabilities":this.clientCapabilities,"io.modelcontextprotocol/clientInfo":this.clientInfo}}}:e,f={...d,jsonrpc:`2.0`,id:u},p=this.getToolRequestHeaders(d),m=()=>{i(new N({message:`Request was aborted`,cause:a?.reason}))},h=()=>{this.responseHandlers.delete(u),a?.removeEventListener(`abort`,_),l!=null&&clearTimeout(l)},g=e=>{h(),i(e)},_=()=>{h(),m()};this.responseHandlers.set(u,e=>{if(a?.aborted)return h(),m();if(e instanceof Error)return g(e);try{if(this.protocolEra===`modern`&&e.result.resultType==null)throw new N({message:`Modern MCP result is missing resultType`});if(e.result.resultType===`input_required`)throw new N({message:`Server requested additional input, but multi round-trip requests are not supported yet`});let n=t.parse(e.result);h(),r(n)}catch(e){let t=N.isInstance(e)?e:new N({message:`Failed to parse server response`,cause:e});g(t)}}),a?.addEventListener(`abort`,_,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new N({message:`Request timed out after ${o}ms`});s?.abort(e),g(e)},o));let v={...c==null?{}:{signal:c},...p==null?{}:{headers:p}};(Object.keys(v).length===0?this.send(f):this.send(f,v)).catch(e=>{g(e)})})}async listTools({params:e,options:t}={}){let n=await this.request({request:{method:`tools/list`,params:e},resultSchema:de,options:t});return this.prepareToolDefinitions(n,e?.cursor==null)}prepareToolDefinitions(e,t=!1){if(this.protocolEra!==`modern`||!this.transport.supportsMcpToolParameterHeaders)return e;t&&this.toolHeaderBindings.clear();let n=e.tools.filter(e=>{let t=tn(e.inputSchema);return t.success?(this.toolHeaderBindings.set(e.name,t.bindings),!0):(this.onError(new N({message:`Ignoring MCP tool "${e.name}": ${t.error}`})),!1)});return{...e,tools:n}}getToolRequestHeaders(e){if(this.protocolEra!==`modern`||e.method!==`tools/call`||typeof e.params?.name!=`string`)return;let t=this.toolHeaderBindings.get(e.params.name);if(t==null||t.length===0)return;let n=e.params.arguments;if(typeof n==`object`&&n&&!Array.isArray(n))try{return rn({bindings:t,args:n})}catch(t){throw new N({message:`Failed to create MCP headers for tool "${e.params.name}"`,cause:t})}}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():_({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:wn,createRetryError:({message:e,errors:t})=>new N({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:we,options:n})})}async listResourcesInternal({params:e,options:t}={}){return this.request({request:{method:`resources/list`,params:e},resultSchema:he,options:t})}async readResourceInternal({uri:e,options:t}){return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:De,options:t})}async listResourceTemplatesInternal({options:e}={}){return this.request({request:{method:`resources/templates/list`},resultSchema:Ee,options:e})}async listPromptsInternal({params:e,options:t}={}){return this.request({request:{method:`prompts/list`,params:e},resultSchema:Pe,options:t})}async getPromptInternal({name:e,args:t,options:n}){return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Ie,options:n})}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:je,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await Dn(this.send(n,t?.signal==null?void 0:{signal:t.signal}),t?.signal)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools(),n=[...t.tools];for(;t.nextCursor!=null;)t=await this.listTools({params:{cursor:t.nextCursor}}),n.push(...t.tools);return this.toolsFromDefinitions({...t,tools:n},{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){e=this.prepareToolDefinitions(e);let n=Object.create(null);for(let{name:i,title:a,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=a??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,i))continue;let u=this,d=t===`automatic`?void 0:t[i]?.outputSchema,p=gn({_meta:l}),h={clientName:this.clientInfo.name,toolName:i,...e==null?{}:{title:e},...c==null?{}:{annotations:{...c.title==null?{}:{title:c.title},...c.readOnlyHint==null?{}:{readOnlyHint:c.readOnlyHint},...c.destructiveHint==null?{}:{destructiveHint:c.destructiveHint},...c.idempotentHint==null?{}:{idempotentHint:c.idempotentHint},...c.openWorldHint==null?{}:{openWorldHint:c.openWorldHint}}},...p?.resourceUri==null?{}:{app:{...p,mimeType:Q}}},g=async(e,t)=>{t?.abortSignal?.throwIfAborted();let n=await u.callTool({name:i,arguments:e,options:{signal:t?.abortSignal}});return n.isError||d==null?n:u.extractStructuredContent(n,d,i)};n[i]={...t===`automatic`?m({description:o,title:e,metadata:h,inputSchema:r({...s,properties:s.properties??{},additionalProperties:!1}),execute:g,toModelOutput:On}):f({description:o,title:e,metadata:h,inputSchema:t[i].inputSchema,...d==null?{}:{outputSchema:d},execute:g,toModelOutput:On}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await d({value:e.structuredContent,schema:p(t)});if(!r.success)throw new N({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await u({text:r.text,schema:t});if(!e.success)throw new N({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new N({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==A)throw new N({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=A.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=Re.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new N({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){if(e.id==null){this.onError(new N({message:`Protocol error: Received a response without a message ID: ${JSON.stringify(e)}`}));return}let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new N({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new N({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};const jn=new TextEncoder;function $(e){if(typeof e!=`object`||!e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map($).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${$(t[e])}`).join(`,`)}}`}function Mn(e){return h(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function Nn(e){let t=await crypto.subtle.digest(`SHA-256`,jn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return Mn(new Uint8Array(t))}function Pn(e,t){return e!==t}const Fn=262144,In=b.object({type:b.literal(`verification`),challenge:b.string().min(1)});function Ln({store:e,validatePayload:t,onEvent:n,onGap:r,onTerminated:i,onError:a}){return async o=>{if(o.method!==`POST`)return new Response(null,{status:405,headers:{Allow:`POST`}});if(o.headers.get(`content-type`)?.split(`;`)[0].trim().toLowerCase()!==`application/json`)return new Response(null,{status:415});if(Number(o.headers.get(`content-length`))>Fn)return new Response(null,{status:413});try{let s=new URL(o.url).searchParams.get(tt),c=o.headers.get(`X-MCP-Subscription-Id`);if(!s||!c)return new Response(null,{status:401});let l=await e.get(s);if(!l||l.id!=null&&l.id!==c)return new Response(null,{status:401});let d=o.body?.getReader();if(!d)return new Response(null,{status:400});let f=[],p=0;try{for(;;){let{done:e,value:t}=await d.read();if(e)break;if(p+=t.byteLength,p>Fn)return await d.cancel(),new Response(null,{status:413});f.push(t)}}finally{d.releaseLock()}let m=new Uint8Array(p),h=0;for(let e of f)m.set(e,h),h+=e.length;if(!await Je({headers:o.headers,body:m,secret:l.delivery.secret}))return new Response(null,{status:401});let g=await u({text:new TextDecoder().decode(m)});if(!g.success)return new Response(null,{status:400});let _=g.value,v;if(typeof _==`object`&&_&&`type`in _){if(_.type===`verification`){let e=In.safeParse(_);return e.success?Response.json({challenge:e.data.challenge}):new Response(null,{status:400})}let e=et.safeParse(_);if(!e.success)return new Response(null,{status:400});v=e.data}if(l.id==null||l.status!==`active`&&v?.type!==`terminated`)return new Response(null,{status:503});let y={id:l.id,name:l.name,arguments:l.arguments,delivery:{mode:`webhook`,url:l.delivery.url},refreshBefore:l.refreshBefore??null};if(v){let t=o.headers.get(`webhook-id`);return v.type===`gap`?(await r?.({subscription:y,messageId:t,gap:v}),await e.update(l.key,{cursor:v.cursor,truncated:!0})):(await i?.({subscription:y,messageId:t,termination:v}),await e.delete(l.key)),new Response(null,{status:204})}if(l.refreshBefore!=null&&Date.parse(l.refreshBefore)<=Date.now())return new Response(null,{status:410});let b=$e.safeParse(_);if(!b.success||b.data.name!==l.name||b.data.eventId!==o.headers.get(`webhook-id`))return new Response(null,{status:400});try{await t?.({definition:l.definition,data:b.data.data})}catch(e){return a?.(e),new Response(null,{status:400})}return await n({subscription:y,event:b.data}),b.data.cursor!==void 0&&await e.update(l.key,{cursor:b.data.cursor}),new Response(null,{status:204})}catch(e){return a?.(e),new Response(null,{status:503})}}}export{vt as AuthorizationServerMismatchError,Re as ElicitResultSchema,A as ElicitationRequestSchema,N as MCPClientError,F as MCPClientOAuthError,Q as MCP_APP_MIME_TYPE,V as UnauthorizedError,Z as auth,kn as createMCPClient,kn as experimental_createMCPClient,Pn as detectMCPAppResourceDrift,Ln as experimental_createMCPEventWebhook,Nn as fingerprintMCPAppResource,ln as mcpAppClientCapabilities,yn as readMCPAppResource,_n as splitMCPAppTools,j as validateJSONRPCMessage};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{deepEquals,eventMatches,subagentCallMatches,testRegExp,toolCallMatches}from"#evals/match.js";const PASS={score:1},fail=(e,t)=>({score:0,message:e,metadata:t});function succeeded(){return{name:`succeeded`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?fail(`run parked on
|
|
1
|
+
import{deepEquals,eventMatches,subagentCallMatches,testRegExp,toolCallMatches}from"#evals/match.js";const PASS={score:1},fail=(e,t)=>({score:0,message:e,metadata:t});function succeeded(){return{name:`succeeded`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?fail(`run parked on unanswered input request(s)`):PASS:t}}}function parked(){return{name:`parked`,evaluate(e){let t=runFailure(e);return t===void 0?e.derived.parked?PASS:fail(`expected the run to park on HITL input; it ended "${e.status}" with no pending requests`):t}}}function messageIncludes(e){return{name:`messageIncludes(${String(e)})`,evaluate(t){let n=joinCompletedMessages(t.events);return(typeof e==`string`?n.includes(e):testRegExp(e,n))?PASS:fail(`assistant messages did not include ${String(e)}; got: ${truncate(n)}`)}}}function calledTool(e,t={}){return validateCount(t.count),{name:`calledTool(${e})`,evaluate(n){let r=n.derived.toolCalls.filter(t=>t.name===e),i=r.filter(e=>toolCallMatches(e,t));if(matchesCount(t.count,i.length))return{score:1,metadata:{matchingCalls:i.length}};let a=r.length>0?`observed ${e} calls: ${r.map(e=>truncate(JSON.stringify(e.input))).join(`, `)}`:`observed tools: [${n.derived.toolCalls.map(e=>e.name).join(`, `)}]`,o;return o=t.count===void 0?`expected a matching call to "${e}"`:typeof t.count==`number`?`expected exactly ${t.count} matching call(s), found ${i.length}`:`expected matching call count to satisfy the count predicate, found ${i.length}`,fail(`${o}; ${a}`)}}}function loadedSkill(e,t={}){return validateCount(t.count),{name:`loadedSkill(${e})`,evaluate(n){let r=n.derived.skillLoads.filter(t=>t.skill===e).filter(e=>toolCallMatches(e,t));if(matchesCount(t.count,r.length))return{score:1,metadata:{matchingLoads:r.length}};let i=n.derived.skillLoads.map(e=>e.skill).join(`, `);return fail(`expected ${describeCount(t.count)} matching load(s) of "${e}", found ${r.length}; observed skill loads: [${i}]`)}}}function notCalledTool(e){return{name:`notCalledTool(${e})`,evaluate(t){let n=t.derived.toolCalls.filter(t=>t.name===e).length;return n===0?PASS:fail(`"${e}" was called ${n} time(s)`)}}}function toolOrder(e){return{name:`toolOrder(${e.join(` → `)})`,evaluate(t){let n=requestedTools(t.events).map(e=>e.name),r=missingOrderedName(e,n);return r===void 0?PASS:fail(`missing "${r.name}" after [${e.slice(0,r.cursor).join(`, `)}]; observed request order: [${n.join(`, `)}]`)}}}function usedNoTools(){return{name:`usedNoTools`,evaluate(e){let t=e.derived.toolCallCount;return t===0?PASS:fail(`expected no tool calls, got ${t}`,{toolCallCount:t})}}}function maxToolCalls(e){return validateCount(e),{name:`maxToolCalls(${e})`,evaluate(t){let n=t.derived.toolCallCount;return n<=e?PASS:fail(`expected at most ${e} tool calls, got ${n}`,{maxAllowed:e,toolCallCount:n})}}}function noFailedActions(){return{name:`noFailedActions`,evaluate(e){let t=e.events.filter(e=>e.type===`action.result`&&(e.data.status===`failed`||e.data.result.isError===!0));if(t.length===0)return PASS;let n=t.map(formatFailedActionResult);return fail(`${t.length} failed action(s): ${n.join(`; `)}`,{failedActions:t.map(e=>({callId:e.data.result.callId,error:e.data.error,kind:e.data.result.kind,output:e.data.result.output,status:e.data.status}))})}}}function calledSubagent(e,t={}){return validateCount(t.count),{name:`calledSubagent(${e})`,evaluate(n){let r=n.derived.subagentCalls.filter(t=>t.name===e),i=r.filter(e=>subagentCallMatches(e,t));if(matchesCount(t.count,i.length))return{score:1,metadata:{matchingCalls:i.length}};if(r.length===0){let t=n.derived.subagentCalls.map(e=>e.name);return fail(`subagent "${e}" was never called; observed: [${t.join(`, `)}]`,{observedSubagentCalls:n.derived.subagentCalls})}return fail(`subagent "${e}" was called but ${i.length} call(s) matched the constraints`,{observedSubagentCalls:r})}}}function eventsSatisfy(e,t){return{name:`eventsSatisfy(${e})`,evaluate(n){return t(n.events)?PASS:fail(`event predicate "${e}" did not hold`)}}}function typedEvent(e){return validateCount(e.count),{name:`event(${e.type})`,evaluate(t){let n=t.events.filter(t=>eventMatches(t,e));if(matchesCount(e.count,n.length))return{score:1,metadata:{matchingEvents:n.length}};let r=describeCount(e.count);return fail(`expected ${r} matching ${e.type} event(s), found ${n.length}; observed: [${t.events.map(e=>e.type).join(`, `)}]`)}}}function notEvent(e){return{name:`notEvent(${e.type})`,evaluate(t){let n=t.events.filter(t=>eventMatches(t,e));return n.length===0?PASS:fail(`expected no matching ${e.type} events, found ${n.length}`)}}}function eventOrder(e){for(let t of e)validateCount(t.count);return{name:`eventOrder(${e.map(e=>e.type).join(` → `)})`,evaluate(t){let n=-1;for(let r of e){let e=t.events.flatMap((e,t)=>eventMatches(e,r)?[t]:[]);if(!matchesCount(r.count,e.length)){let t=describeCount(r.count);return fail(`expected ${t} matching ${r.type} event(s), found ${e.length}`)}let i=e[0];if(i===void 0||i<=n)return fail(`event group ${r.type} did not occur after the previous group`);n=e[e.length-1]??n}return PASS}}}function outputEquals(e){return{name:`outputEquals`,evaluate(t){return deepEquals(t.output,e)?PASS:fail(`output ${truncate(JSON.stringify(t.output))} does not equal expected ${truncate(JSON.stringify(e))}`)}}}function outputMatches(e){return{name:`outputMatches`,async evaluate(t){let n=await e[`~standard`].validate(t.output);if(!(`issues`in n)||n.issues===void 0)return PASS;let r=n.issues.map(e=>e.message).join(`; `);return fail(`output failed schema validation: ${r}`)}}}function joinCompletedMessages(e){let t=[];for(let n of e)n.type===`message.completed`&&t.push(n.data.message);return t.join(`
|
|
2
2
|
`)}function failureDetail(e,t){return t===void 0?e:`${e} (code: ${t})`}function formatFailedActionResult(e){let{result:t,status:n}=e.data;return[actionResultLabel(t),`callId=${t.callId}`,`status=${n}`,t.isError===!0?`isError=true`:void 0,e.data.error?.message===void 0?void 0:`error=${e.data.error.message}`,`output=${truncate(formatUnknown(t.output))}`].filter(e=>e!==void 0).join(` `)}function actionResultLabel(e){switch(e.kind){case`tool-result`:return`tool-result:${e.toolName}`;case`subagent-result`:return`subagent-result:${e.subagentName}`;case`load-skill-result`:return`load-skill-result:${e.name}`}}function runFailure(e){if(e.status===`failed`)return fail(failureDetail(`run failed`,e.derived.failureCode));let t=e.events.find(e=>e.type===`turn.failed`||e.type===`step.failed`);return t===void 0?void 0:fail(`${t.type} (${t.data.code}): ${t.data.message}`)}function truncate(e,t=200){return e===void 0?`undefined`:e.length<=t?e:`${e.slice(0,t)}…`}function formatUnknown(e){if(e!==void 0){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}}function matchesCount(e,t){return e===void 0?t>0:typeof e==`function`?e(t):t===e}function describeCount(e){return e===void 0?`at least one`:typeof e==`function`?`a count satisfying the predicate`:`exactly ${e}`}function validateCount(e){if(e!==void 0&&typeof e!=`function`&&(typeof e!=`number`||!Number.isInteger(e)||e<0))throw TypeError(`Assertion count must be a non-negative integer or predicate; received ${String(e)}.`)}function missingOrderedName(e,t){let n=0;for(let r of t)if(r===e[n]&&(n+=1),n===e.length)return;let r=e[n];return r===void 0?void 0:{cursor:n,name:r}}function requestedTools(e){let t=[],n=new Set,append=(e,r)=>{n.has(e)||(n.add(e),t.push({callId:e,name:r}))};for(let t of e)if(t.type===`actions.requested`)for(let e of t.data.actions)e.kind===`tool-call`&&append(e.callId,e.toolName);else if(t.type===`input.requested`)for(let e of t.data.requests){let{action:t}=e;t.kind===`tool-call`&&append(t.callId,t.toolName)}return t}export{calledSubagent,calledTool,eventOrder,eventsSatisfy,loadedSkill,maxToolCalls,messageIncludes,noFailedActions,notCalledTool,notEvent,outputEquals,outputMatches,parked,succeeded,toolOrder,typedEvent,usedNoTools};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { MessageStreamEvent } from "#protocol/message.js";
|
|
2
|
+
import type { InputRequest } from "#shared/input.js";
|
|
2
3
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
3
4
|
import type { EveEvalDerivedFacts } from "#evals/types.js";
|
|
4
5
|
/**
|
|
@@ -33,3 +34,15 @@ export declare function latestUsage(events: readonly MessageStreamEvent[]): {
|
|
|
33
34
|
* (execution errors, transport failures).
|
|
34
35
|
*/
|
|
35
36
|
export declare function createEmptyDerivedFacts(): EveEvalDerivedFacts;
|
|
37
|
+
/**
|
|
38
|
+
* Input requests the last started turn raised, or a child relayed, that nobody
|
|
39
|
+
* has answered yet. A partial answer settles only the requests it answers; the
|
|
40
|
+
* rest stay open.
|
|
41
|
+
*
|
|
42
|
+
* An eval may watch how a request ends outside the session (for example
|
|
43
|
+
* through `t.target`), so two kinds of open request don't count: the session's
|
|
44
|
+
* own requests from earlier turns, and answered ones whose responder still has
|
|
45
|
+
* to sign in. Relayed requests keep the child's `turnId`, so they never match
|
|
46
|
+
* the parent's turn and are kept by `callId`/`taskId` instead.
|
|
47
|
+
*/
|
|
48
|
+
export declare function openInputRequests(events: readonly MessageStreamEvent[]): InputRequest[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const PARKING_EVENT_TYPES=new Set([`turn.waiting`,`turn.completed`,`session.waiting`,`session.completed`]);function deriveRunFacts(e,t){let n=t?.sessionId,r=[],i=new Map,a=new Map,o=[],s=new Map,c=[],l=[],u=-1,d=0,f=0,p=new Set,m,ensureToolCall=(e,t,a)=>{let o=i.get(e);if(o!==void 0)return o;let s={name:t,input:a,output:void 0,status:`pending`,turnIndex:Math.max(u,0),sessionId:n};return r.push(s),i.set(e,s),s};for(let t of e)switch(t.type){case`turn.started`:u+=1;break;case`actions.requested`:for(let e of t.data.actions)e.kind===`tool-call`?ensureToolCall(e.callId,e.toolName,e.input):e.kind===`load-skill`&&a.set(e.callId,{output:void 0,sessionId:n,skill:e.name,status:`pending`,turnIndex:Math.max(u,0)});break;case`action.result`:{let{result:e,status:n}=t.data
|
|
1
|
+
import{foldSession,initialSessionProjection,openInputs}from"#protocol/session-projection.js";const PARKING_EVENT_TYPES=new Set([`turn.waiting`,`turn.completed`,`session.waiting`,`session.completed`]);function deriveRunFacts(e,t){let n=t?.sessionId,r=[],i=new Map,a=new Map,o=[],s=new Map,c=[],l=[],u=-1,d=0,f=0,p=new Set,m,ensureToolCall=(e,t,a)=>{let o=i.get(e);if(o!==void 0)return o;let s={name:t,input:a,output:void 0,status:`pending`,turnIndex:Math.max(u,0),sessionId:n};return r.push(s),i.set(e,s),s};for(let t of e)switch(t.type){case`turn.started`:u+=1;break;case`actions.requested`:for(let e of t.data.actions)e.kind===`tool-call`?ensureToolCall(e.callId,e.toolName,e.input):e.kind===`subagent-call`||e.kind===`remote-agent-call`?ensureToolCall(e.callId,e.name,e.input):e.kind===`load-skill`&&a.set(e.callId,{output:void 0,sessionId:n,skill:e.name,status:`pending`,turnIndex:Math.max(u,0)});break;case`action.result`:{let{result:e,status:n}=t.data,r=e.kind===`tool-result`?ensureToolCall(e.callId,e.toolName,{}):e.kind===`subagent-result`?i.get(e.callId):void 0;r!==void 0&&(r.output=e.output,r.status=n);let o=e.kind===`load-skill-result`?a.get(e.callId):void 0;o!==void 0&&(o.output=e.output,o.status=n);break}case`task.started`:{let{callId:e,kind:n,name:r,taskId:i}=t.data;if(n!==`agent`)break;o.push({callId:e,name:r,taskId:i,turnIndex:Math.max(u,0)});break}case`task.settled`:s.set(t.data.callId,t.data);break;case`agent.started`:c.push(t.data);break;case`input.requested`:l.push(...t.data.requests);for(let e of t.data.requests)ensureToolCall(e.action.callId,e.action.toolName,e.action.input);break;case`message.completed`:t.data.finishReason!==`tool-calls`&&(d+=1);break;case`reasoning.completed`:f+=1;break;case`step.started`:p.add(t.data.modelId);break;case`session.failed`:m=t.data.code}let h=deriveSubagentCalls({agentCalls:o,agentSessions:c,sessionId:n,settledTaskCalls:s});return{toolCalls:r,toolCallCount:r.length,skillLoads:[...a.values()],subagentCalls:h,subagentCallCount:h.length,inputRequests:l,parked:endedParkedOnInput(e),messageCount:d,reasoningBlockCount:f,models:[...p],usage:latestUsage(e)?.usage,failureCode:m}}function latestUsage(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0)switch(n.type){case`session.waiting`:case`turn.waiting`:case`session.failed`:return{usage:n.data.usage,at:Date.parse(n.meta.at)};case`session.completed`:return{usage:n.data?.usage,at:Date.parse(n.meta.at)}}}}function deriveSubagentCalls(e){let t=new Map;for(let n of e.agentSessions)n.taskId!==void 0&&t.set(n.taskId,n);return e.agentCalls.map(n=>{let r=t.get(n.taskId),i=e.settledTaskCalls.get(n.callId);return{callId:n.callId,childSessionId:r?.sessionId,name:n.name,output:i?.output,remoteUrl:r?.remote?.url,sessionId:e.sessionId,status:i?.status??`working`,turnIndex:n.turnIndex}})}function createEmptyDerivedFacts(){return{toolCalls:[],toolCallCount:0,skillLoads:[],subagentCalls:[],subagentCallCount:0,inputRequests:[],parked:!1,messageCount:0,reasoningBlockCount:0,models:[]}}function openInputRequests(e){let t=initialSessionProjection(),n;for(let r of e)t=foldSession(t,r),r.type===`turn.started`&&(n=r.data.turnId);let r=new Set(Object.values(t.candidates).filter(e=>e.outcome===`pending`).map(e=>e.requestId));return openInputs(t).filter(e=>n===void 0||e.turnId===n||e.callId!==void 0||e.taskId!==void 0).filter(e=>!r.has(e.request.requestId)).map(e=>e.request)}function endedParkedOnInput(e){let t=e.at(-1);return t!==void 0&&PARKING_EVENT_TYPES.has(t.type)&&openInputRequests(e).length>0}export{createEmptyDerivedFacts,deriveRunFacts,latestUsage,openInputRequests};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{basename}from"node:path";import{TurnSegment,summarizeTurnEvents}from"#client/session-utils.js";import{isTurnFailureEvent}from"#protocol/message.js";import{getMessageResponseReceipt}from"#client/message-response.js";import{createTextWithFileContent}from"#client/file-parts.js";import{extractCompletedResult}from"#client/output-schema.js";import{inputRequestMatches,matchesValue,toolCallMatches}from"#evals/match.js";import"#evals/assertions/collector.js";import{assertReportedToolName}from"#evals/reported-tool-name.js";import{createOutputAssertions,createScopedAssertions}from"#evals/assertions/scoped.js";import{EvalRequirementFailed}from"#evals/control-flow.js";import{deriveRunFacts}from"#evals/runner/derive-run-facts.js";import{formatEvalTranscript,inferMediaType}from"#evals/session-content.js";var EveEvalTurnFailedError=class extends Error{event;turn;constructor(e){let t=e.events.find(isTurnFailureEvent),n=t===void 0?`turn ended with status "${e.status}"`:`${t.type}: ${t.data.code} ${t.data.message}`.trim();super(`Eval turn failed: ${n}`),this.name=`EveEvalTurnFailedError`,this.event=t,this.turn=e}},EvalSessionDriver=class{#e;#t;#n=``;#r;#i;#a=[];#o=[];#s=[];#c;#l;#u=[];#d=new Set;#f;#p=!1;#m=[];constructor(e){this.#i=e.collector,this.#l=e.onSessionStart,this.#c=e.primary,this.#e=e.session,this.#t=e.onTurn,this.#r=e.signal,Object.assign(this,createScopedAssertions(this.#i,{timing:`snapshot`,select:()=>this.#y()}),createOutputAssertions(this.#i,{timing:`snapshot`,select:()=>this.#y()}))}get events(){return this.#a}get transcript(){return formatEvalTranscript(this.#a)}get lastInput(){return this.#n}get lastTurn(){return this.#f}get pendingInputRequests(){return this.#m}get sessionId(){return this.#e.state.sessionId}get state(){return this.#e.state}async cancel(){return await this.#e.cancel()}async compact(){if((await this.#e.compact()).status!==`accepted`)throw Error(`compact() found no active session for "${this.sessionId}".`);return await this.readTurn()}agent(e){let t=this.#e.agent(e),n=this.#r;return{name:t.name,sessionId:t.sessionId,stream:(e={})=>t.stream({...e,signal:e.signal??n}),taskId:t.taskId}}async cleanup(e){await this.#e.reset({reason:`Eval timed out`,signal:e})}requireInputRequest(e={}){this.#m.length===0&&this.#b(`requireInputRequest`,`expected one pending input request, but the last turn did not park`);let t=this.#m.filter(t=>inputRequestMatches(t,e));return(this.#m.length!==1||t.length!==1)&&this.#b(`requireInputRequest`,`expected exactly one pending input request matching ${formatInputRequestFilter(e)}, found ${t.length} match(es) across ${this.#m.length} pending request(s)`),this.#i.recordOutcome({name:`requireInputRequest`,outcome:{score:1}}),t[0]}async respond(e,t={}){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await(await this.#h({...t,inputResponses:e})).result()}async startRespond(e,t={}){if(e.length===0)throw Error(`startRespond() requires input responses.`);return await this.#h({...t,inputResponses:e})}async respondAll(e){let t=this.#m;if(t.length===0)throw Error(`respondAll() requires at least one pending input request.`);for(let n of t)assertRequestHasOption(n,e);return await this.respond(t.map(t=>({optionId:e,requestId:t.requestId})))}async send(e,t={}){return await(await this.#h({turnPolicy:`queue`,...t,message:e})).result()}async start(e,t={}){return await this.#h({turnPolicy:`queue`,...t,message:e})}async#h(e){let{inputResponses:t,message:n,...r}=attachSignal(e,this.#r),i=t===void 0?await this.#e.send(n,r):await this.#e.respond(t,r);return this.recordSend(t===void 0?`message`:`respond`,getMessageResponseReceipt(i)),this.consume(i,n)}recordSend(e,t){t!==void 0&&this.#s.push({kind:e,...t})}consume(e,t){let n=this.sessionId;return new EvalLiveTurn({events:e,observe:e=>this.#g(n,e),record:(e,r)=>(t!==void 0&&(this.#n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
|
-
`)),this.#v(n,e,r)),session:this,sessionId:n})}async sendFile(e,t,n){let r=await readFile(t),i=createTextWithFileContent({bytes:r,filename:basename(t),mediaType:n??inferMediaType(t),text:e});return await this.send(i)}async readTurn(e){return await this.watchTurn(e).result()}watchTurn(e){return this.consume(this.#e.stream({signal:this.#r,startIndex:e?.startIndex}))}snapshot(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],primary:this.#c,sessionId:e,state:this.#e.state,traceContexts:[...this.#u],clock:{receivedAt:[...this.#o],sends:[...this.#s]}}}#g(e,t){if(t.type!==`session.started`&&t.type!==`turn.started`)return;let n=t.data.trace;if(n===void 0)return;let r=`${n.traceId}:${n.spanId}`;this.#d.has(r)||(this.#d.add(r),this.#u.push(n),!this.#p&&(this.#p=!0,this.#l?.({primary:this.#c,sessionId:e,startedAt:t.meta.at,traceContext:n})))}#_(e){this.#a.push(...e.events),this.#o.push(...e.receivedAt),this.#m=e.status===`waiting`?
|
|
1
|
+
import{readFile}from"node:fs/promises";import{basename}from"node:path";import{TurnSegment,summarizeTurnEvents}from"#client/session-utils.js";import{isTurnFailureEvent}from"#protocol/message.js";import{getMessageResponseReceipt}from"#client/message-response.js";import{createTextWithFileContent}from"#client/file-parts.js";import{extractCompletedResult}from"#client/output-schema.js";import{inputRequestMatches,matchesValue,toolCallMatches}from"#evals/match.js";import"#evals/assertions/collector.js";import{assertReportedToolName}from"#evals/reported-tool-name.js";import{createOutputAssertions,createScopedAssertions}from"#evals/assertions/scoped.js";import{EvalRequirementFailed}from"#evals/control-flow.js";import{deriveRunFacts,openInputRequests}from"#evals/runner/derive-run-facts.js";import{formatEvalTranscript,inferMediaType}from"#evals/session-content.js";var EveEvalTurnFailedError=class extends Error{event;turn;constructor(e){let t=e.events.find(isTurnFailureEvent),n=t===void 0?`turn ended with status "${e.status}"`:`${t.type}: ${t.data.code} ${t.data.message}`.trim();super(`Eval turn failed: ${n}`),this.name=`EveEvalTurnFailedError`,this.event=t,this.turn=e}},EvalSessionDriver=class{#e;#t;#n=``;#r;#i;#a=[];#o=[];#s=[];#c;#l;#u=[];#d=new Set;#f;#p=!1;#m=[];constructor(e){this.#i=e.collector,this.#l=e.onSessionStart,this.#c=e.primary,this.#e=e.session,this.#t=e.onTurn,this.#r=e.signal,Object.assign(this,createScopedAssertions(this.#i,{timing:`snapshot`,select:()=>this.#y()}),createOutputAssertions(this.#i,{timing:`snapshot`,select:()=>this.#y()}))}get events(){return this.#a}get transcript(){return formatEvalTranscript(this.#a)}get lastInput(){return this.#n}get lastTurn(){return this.#f}get pendingInputRequests(){return this.#m}get sessionId(){return this.#e.state.sessionId}get state(){return this.#e.state}async cancel(){return await this.#e.cancel()}async compact(){if((await this.#e.compact()).status!==`accepted`)throw Error(`compact() found no active session for "${this.sessionId}".`);return await this.readTurn()}agent(e){let t=this.#e.agent(e),n=this.#r;return{name:t.name,sessionId:t.sessionId,stream:(e={})=>t.stream({...e,signal:e.signal??n}),taskId:t.taskId}}async cleanup(e){await this.#e.reset({reason:`Eval timed out`,signal:e})}requireInputRequest(e={}){this.#m.length===0&&this.#b(`requireInputRequest`,`expected one pending input request, but the last turn did not park`);let t=this.#m.filter(t=>inputRequestMatches(t,e));return(this.#m.length!==1||t.length!==1)&&this.#b(`requireInputRequest`,`expected exactly one pending input request matching ${formatInputRequestFilter(e)}, found ${t.length} match(es) across ${this.#m.length} pending request(s)`),this.#i.recordOutcome({name:`requireInputRequest`,outcome:{score:1}}),t[0]}async respond(e,t={}){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await(await this.#h({...t,inputResponses:e})).result()}async startRespond(e,t={}){if(e.length===0)throw Error(`startRespond() requires input responses.`);return await this.#h({...t,inputResponses:e})}async respondAll(e){let t=this.#m;if(t.length===0)throw Error(`respondAll() requires at least one pending input request.`);for(let n of t)assertRequestHasOption(n,e);return await this.respond(t.map(t=>({optionId:e,requestId:t.requestId})))}async send(e,t={}){return await(await this.#h({turnPolicy:`queue`,...t,message:e})).result()}async start(e,t={}){return await this.#h({turnPolicy:`queue`,...t,message:e})}async#h(e){let{inputResponses:t,message:n,...r}=attachSignal(e,this.#r),i=t===void 0?await this.#e.send(n,r):await this.#e.respond(t,r);return this.recordSend(t===void 0?`message`:`respond`,getMessageResponseReceipt(i)),this.consume(i,n)}recordSend(e,t){t!==void 0&&this.#s.push({kind:e,...t})}consume(e,t){let n=this.sessionId;return new EvalLiveTurn({events:e,observe:e=>this.#g(n,e),record:(e,r)=>(t!==void 0&&(this.#n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
|
+
`)),this.#v(n,e,r)),session:this,sessionId:n})}async sendFile(e,t,n){let r=await readFile(t),i=createTextWithFileContent({bytes:r,filename:basename(t),mediaType:n??inferMediaType(t),text:e});return await this.send(i)}async readTurn(e){return await this.watchTurn(e).result()}watchTurn(e){return this.consume(this.#e.stream({signal:this.#r,startIndex:e?.startIndex}))}snapshot(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],primary:this.#c,sessionId:e,state:this.#e.state,traceContexts:[...this.#u],clock:{receivedAt:[...this.#o],sends:[...this.#s]}}}#g(e,t){if(t.type!==`session.started`&&t.type!==`turn.started`)return;let n=t.data.trace;if(n===void 0)return;let r=`${n.traceId}:${n.spanId}`;this.#d.has(r)||(this.#d.add(r),this.#u.push(n),!this.#p&&(this.#p=!0,this.#l?.({primary:this.#c,sessionId:e,startedAt:t.meta.at,traceContext:n})))}#_(e){this.#a.push(...e.events),this.#o.push(...e.receivedAt),this.#m=e.status===`waiting`?openInputRequests(this.#a):[];let t=deriveRunFacts(e.events,{sessionId:e.sessionId}),n={...t,parked:t.parked||this.#m.length>0},r=new EvalTurn({collector:this.#i,data:e.data,derived:n,events:e.events,inputRequests:e.inputRequests,message:e.message,session:this,sessionId:e.sessionId,status:e.status,toolCalls:n.toolCalls});return this.#f=r,this.#t(this),r}#v(e,t,n){let r=summarizeTurnEvents(t);return this.#_({data:extractCompletedResult(t),events:t,inputRequests:r.inputRequests,message:r.message,receivedAt:n,sessionId:e,status:r.status})}#y(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],output:outputOf(this.#f),status:this.#f?.status??`completed`}}#b(e,t){throw this.#i.recordOutcome({name:e,outcome:{score:0,message:t}}),new EvalRequirementFailed}},EvalLiveTurn=class{session;sessionId;#e;#t=[];#n=[];#r=new Set;#i;constructor(e){this.session=e.session,this.sessionId=e.sessionId,this.#e=this.#a(e.events,e.observe,e.record),this.#e.catch(()=>{})}get events(){return this.#t}async cancel(){return await this.session.cancel()}async result(){return await this.#e}async waitForEvent(e,t){let matches=n=>n.type===e&&(t?.data===void 0||matchesValue(t.data,`data`in n?n.data:void 0)),n=this.#t.find(matches);if(n!==void 0)return n;if(this.#i!==void 0)throw this.#i;return await new Promise((e,t)=>{let n={matches,reject:t,resolve:t=>e(t)};this.#r.add(n)})}async#a(e,t,n){try{let r=!1,i=new TurnSegment;for await(let n of e){this.#t.push(n),this.#n.push(Date.now());let e=i.observe(n);if(t(n),this.#o(n),isTurnFailureEvent(n)&&this.#s(Error(`Session ${this.sessionId} failed before the expected event (${n.type}).`)),e){r=!0,this.#s(Error(`Session ${this.sessionId} reached ${n.type} before the expected event.`));break}}if(!r)throw Error(`Stream for session "${this.sessionId}" closed before a turn boundary.`);return n(this.#t,this.#n)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.#s(t),e}}#o(e){for(let t of this.#r)t.matches(e)&&(this.#r.delete(t),t.resolve(e))}#s(e){if(this.#i===void 0){this.#i=e;for(let t of this.#r)t.reject(e);this.#r.clear()}}},EvalTurn=class{data;events;inputRequests;message;session;sessionId;status;toolCalls;#e;#t;constructor(e){this.data=e.data,this.events=e.events,this.inputRequests=e.inputRequests,this.message=e.message,this.sessionId=e.sessionId,this.session=e.session,this.status=e.status,this.toolCalls=e.toolCalls,this.#e=e.collector,this.#t=e.derived,Object.assign(this,createScopedAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}),createOutputAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}))}expectOk(){if(this.status!==`failed`)return this;throw new EveEvalTurnFailedError(this)}requireToolCall(e,t={}){assertReportedToolName(e,this.#e.tools);let n=this.toolCalls.filter(n=>n.name===e&&toolCallMatches(n,t));return n.length!==1&&inputRequirementFailed(this.#e,`requireToolCall`,`expected exactly one matching "${e}" tool call in this turn, found ${n.length}; observed [${this.toolCalls.map(e=>e.name).join(`, `)}]`),this.#e.recordOutcome({name:`requireToolCall`,outcome:{score:1}}),n[0]}#n(){return{derived:this.#t,events:this.events,output:outputOf(this),status:this.status}}};function attachSignal(e,t){return t===void 0?e:e.signal===void 0?{...e,signal:t}:e}function formatInputRequestFilter(e){return JSON.stringify(e)}function inputRequirementFailed(e,t,n){throw e.recordOutcome({name:t,outcome:{score:0,message:n}}),new EvalRequirementFailed}function outputOf(e){return e===void 0?null:e.data===void 0?e.message??null:e.data}function assertRequestHasOption(e,t){if(e.options===void 0||e.options.length===0)throw Error(`Input request "${e.requestId}" has no selectable options.`);if(!e.options.some(e=>e.id===t))throw Error(`Input request "${e.requestId}" does not offer option "${t}".`)}export{EvalSessionDriver,EveEvalTurnFailedError};
|
|
@@ -324,7 +324,7 @@ interface EveEvalSessionDriver {
|
|
|
324
324
|
* this to a judge's `on` option to grade the complete conversation.
|
|
325
325
|
*/
|
|
326
326
|
readonly transcript: string;
|
|
327
|
-
/** Input requests
|
|
327
|
+
/** Input requests still open when the last turn parked, including ones raised before a partial `respond()`. */
|
|
328
328
|
readonly pendingInputRequests: readonly InputRequest[];
|
|
329
329
|
/** Serializable cursor for resuming this session. */
|
|
330
330
|
readonly state: ClientSessionState;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{isInputResponse}from"#shared/input.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_LEASE_ENDED_CONTROL,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,splitLegacyTaskFields}from"#execution/legacy-remote-agent/protocol.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation}from"#public/channels/upload-policy.js";import{strandedSessionResponse}from"#eve-channel/support.js";import{parseToolStubs}from"#tool-stubs/rules.js";import{parseSessionCallback}from"#channel/session-callback.js";import{isExpiredWorkflowRunError,isMissingWorkflowRunError}from"#internal/workflow/is-inactive-workflow-run-error.js";import{REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,readRemoteAgentProtocolVersion}from"#protocol/remote-agent-protocol.js";import{parseTurnPolicyField}from"#eve-channel/turn-policy-request.js";import{validateMessageFreeCreate}from"#eve-channel/create-request.js";async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){let t=splitLegacyTaskFields(e),{payload:n}=t;if(n.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let r=parseMessageField(n.message);if(r instanceof Response)return r;let i=parseClientContextField(n.clientContext);if(i instanceof Response)return i;let a=parseCallbackField(n.callback);if(a instanceof Response)return a;let o=a===void 0?void 0:parseProtocolVersionField(n.protocolVersion);if(o instanceof Response)return o;let s=parseCapabilitiesField(n.capabilities);if(s instanceof Response)return s;let c=parseOutputSchemaField(n.outputSchema);if(c instanceof Response)return c;let l=validateMessageFreeCreate({callback:a,hasClientContext:n.clientContext!==void 0,hasMessageField:`message`in n,message:r,outputSchema:c});if(l!==void 0)return l;let u=n.operationId;if(u!==void 0&&(typeof u!=`string`||!u))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let d={callback:a,capabilities:s,context:i,outputSchema:c};if(n.stubs!==void 0)try{d.stubs=parseToolStubs(n.stubs)}catch(e){return Response.json({ok:!1,error:e instanceof Error?e.message:`Invalid tool stubs.`},{status:400})}return r!==void 0&&(d.message=r),typeof u==`string`&&(d.operationId=u),o!==void 0&&(d.protocolVersion=o),o===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION&&(d.legacyRemoteAgentCaller=t.taskId===void 0?{}:{taskId:t.taskId}),d}function parseSessionMessageBody(e){let{payload:t}=splitLegacyTaskFields(e);if(Object.hasOwn(t,`stubs`))return Response.json({ok:!1,error:`Tool stubs are fixed at session creation.`},{status:400});let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=parseMessageField(t.message);if(r instanceof Response)return r;let i=parseCallbackField(t.callback);if(i instanceof Response)return i;let a=parseInputResponses$1(t.inputResponses);if(a instanceof Response)return a;let o=parseClientContextField(t.clientContext);if(o instanceof Response)return o;let s=parseOutputSchemaField(t.outputSchema);if(s instanceof Response)return s;let c=parseTurnPolicyField(t.turnPolicy);return c instanceof Response?c:r===void 0&&a===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):r!==void 0&&a!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{callback:i,message:r,inputResponses:a,context:o,outputSchema:s,turnPolicy:c}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400}):typeof r==`string`?{turnId:r}:{}}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseFollow(e),i=!r||parseIncludeTailIndex(e);try{let a=t.getEventStream({follow:r,startIndex:n});a.catch(()=>{});let o;try{o=await t.getStreamTailIndex()}catch(e){throw a.then(e=>e.cancel()).catch(()=>{}),e}let s=await a,c=new URL(e.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY)===EVE_STREAM_CONTROL_VERSION?EVE_STREAM_CONTROL_VERSION:void 0,l=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return i&&l.set(EVE_STREAM_TAIL_INDEX_HEADER,String(o)),new Response(serializeAsNdjson(s,e.signal,i?streamEventLimit(n,o):void 0,c!==void 0),{headers:l})}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;if(isExpiredWorkflowRunError(e))return Response.json({code:`session_expired`,error:`Session history is no longer available.`,ok:!1},{headers:{"cache-control":`no-store`},status:410});let n=isMissingWorkflowRunError(e);return Response.json({error:n?`Session not found.`:`Session stream unavailable.`,ok:!1},{status:n?404:503})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseProtocolVersionField(e){if(e!==void 0&&typeof e!=`number`)return Response.json({error:`Expected 'protocolVersion' to be a number.`,ok:!1},{status:400});let t=readRemoteAgentProtocolVersion(e);return t===REMOTE_AGENT_PROTOCOL_VERSION||t===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION?t:Response.json({code:REMOTE_AGENT_PROTOCOL_MISMATCH,error:`This deployment speaks eve remote agent protocol ${String(REMOTE_AGENT_PROTOCOL_VERSION)}, but the caller speaks protocol ${String(t)}. Upgrade both deployments to the same eve release.`,ok:!1,protocolVersion:REMOTE_AGENT_PROTOCOL_VERSION},{status:409})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?e:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e:Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function parseIncludeTailIndex(e){let t=new URL(e.url).searchParams.get(`includeTailIndex`);return t===`1`||t===`true`}function parseFollow(e){let t=new URL(e.url).searchParams.get(`follow`);return t!==`0`&&t!==`false`}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number(t);return!/^-?\d+$/.test(t)||!Number.isSafeInteger(n)?Response.json({error:`Expected startIndex to be an integer.`,ok:!1},{status:400}):n}function streamEventLimit(e,t){if(t===void 0)return;let n=e===void 0?0:e<0?Math.max(0,t+1+e):e;return Math.max(0,t-n+1)}function serializeAsNdjson(e,t,n,r=!1){let i=new TextEncoder,a=0,o,s,clearTimers=()=>{clearTimeout(o),clearTimeout(s),o=void 0,s=void 0},scheduleHeartbeat=e=>{clearTimeout(o),o=setTimeout(()=>{try{e.enqueue(i.encode(`
|
|
1
|
+
import{isInputResponse}from"#shared/input.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_LEASE_ENDED_CONTROL,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,splitLegacyTaskFields}from"#execution/legacy-remote-agent/protocol.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation}from"#public/channels/upload-policy.js";import{strandedSessionResponse}from"#eve-channel/support.js";import{parseToolStubs}from"#tool-stubs/rules.js";import{parseSessionCallback}from"#channel/session-callback.js";import{isExpiredWorkflowRunError,isMissingWorkflowRunError}from"#internal/workflow/is-inactive-workflow-run-error.js";import{REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,readRemoteAgentProtocolVersion}from"#protocol/remote-agent-protocol.js";import{parseTurnPolicyField}from"#eve-channel/turn-policy-request.js";import{validateMessageFreeCreate}from"#eve-channel/create-request.js";async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){let t=splitLegacyTaskFields(e),{payload:n}=t;if(n.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let r=parseMessageField(n.message);if(r instanceof Response)return r;let i=parseClientContextField(n.clientContext);if(i instanceof Response)return i;let a=parseCallbackField(n.callback);if(a instanceof Response)return a;let o=a===void 0?void 0:parseProtocolVersionField(n.protocolVersion);if(o instanceof Response)return o;let s=parseCapabilitiesField(n.capabilities);if(s instanceof Response)return s;let c=parseOutputSchemaField(n.outputSchema);if(c instanceof Response)return c;let l=validateMessageFreeCreate({callback:a,hasClientContext:n.clientContext!==void 0,hasMessageField:`message`in n,message:r,outputSchema:c});if(l!==void 0)return l;let u=n.operationId;if(u!==void 0&&(typeof u!=`string`||!u))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let d={callback:a,capabilities:s,context:i,outputSchema:c};if(n.stubs!==void 0)try{d.stubs=parseToolStubs(n.stubs)}catch(e){return Response.json({ok:!1,error:e instanceof Error?e.message:`Invalid tool stubs.`},{status:400})}return r!==void 0&&(d.message=r),typeof u==`string`&&(d.operationId=u),o!==void 0&&(d.protocolVersion=o),o===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION&&(d.legacyRemoteAgentCaller=t.taskId===void 0?{}:{taskId:t.taskId}),d}function parseSessionMessageBody(e){let{payload:t}=splitLegacyTaskFields(e);if(Object.hasOwn(t,`stubs`))return Response.json({ok:!1,error:`Tool stubs are fixed at session creation.`},{status:400});let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=parseMessageField(t.message);if(r instanceof Response)return r;let i=parseCallbackField(t.callback);if(i instanceof Response)return i;let a=parseInputResponses$1(t.inputResponses);if(a instanceof Response)return a;let o=parseClientContextField(t.clientContext);if(o instanceof Response)return o;let s=parseOutputSchemaField(t.outputSchema);if(s instanceof Response)return s;let c=parseTurnPolicyField(t.turnPolicy);return c instanceof Response?c:r===void 0&&a===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):r!==void 0&&a!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{callback:i,message:r,inputResponses:a,context:o,outputSchema:s,turnPolicy:c}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400}):typeof r==`string`?{turnId:r}:{}}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseFollow(e),i=!r||parseIncludeTailIndex(e);try{let a=t.getEventStream({follow:r,startIndex:n});a.catch(()=>{});let o;if(i)try{o=await t.getStreamTailIndex()}catch(e){throw a.then(e=>e.cancel()).catch(()=>{}),e}let s=await a,c=new URL(e.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY)===EVE_STREAM_CONTROL_VERSION?EVE_STREAM_CONTROL_VERSION:void 0,l=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return o!==void 0&&l.set(EVE_STREAM_TAIL_INDEX_HEADER,String(o)),new Response(serializeAsNdjson(s,e.signal,o===void 0?void 0:streamEventLimit(n,o),c!==void 0),{headers:l})}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;if(isExpiredWorkflowRunError(e))return Response.json({code:`session_expired`,error:`Session history is no longer available.`,ok:!1},{headers:{"cache-control":`no-store`},status:410});let n=isMissingWorkflowRunError(e);return Response.json({error:n?`Session not found.`:`Session stream unavailable.`,ok:!1},{status:n?404:503})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseProtocolVersionField(e){if(e!==void 0&&typeof e!=`number`)return Response.json({error:`Expected 'protocolVersion' to be a number.`,ok:!1},{status:400});let t=readRemoteAgentProtocolVersion(e);return t===REMOTE_AGENT_PROTOCOL_VERSION||t===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION?t:Response.json({code:REMOTE_AGENT_PROTOCOL_MISMATCH,error:`This deployment speaks eve remote agent protocol ${String(REMOTE_AGENT_PROTOCOL_VERSION)}, but the caller speaks protocol ${String(t)}. Upgrade both deployments to the same eve release.`,ok:!1,protocolVersion:REMOTE_AGENT_PROTOCOL_VERSION},{status:409})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?e:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e:Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function parseIncludeTailIndex(e){let t=new URL(e.url).searchParams.get(`includeTailIndex`);return t===`1`||t===`true`}function parseFollow(e){let t=new URL(e.url).searchParams.get(`follow`);return t!==`0`&&t!==`false`}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number(t);return!/^-?\d+$/.test(t)||!Number.isSafeInteger(n)?Response.json({error:`Expected startIndex to be an integer.`,ok:!1},{status:400}):n}function streamEventLimit(e,t){if(t===void 0)return;let n=e===void 0?0:e<0?Math.max(0,t+1+e):e;return Math.max(0,t-n+1)}function serializeAsNdjson(e,t,n,r=!1){let i=new TextEncoder,a=0,o,s,clearTimers=()=>{clearTimeout(o),clearTimeout(s),o=void 0,s=void 0},scheduleHeartbeat=e=>{clearTimeout(o),o=setTimeout(()=>{try{e.enqueue(i.encode(`
|
|
2
2
|
`)),scheduleHeartbeat(e)}catch{clearTimers()}},1e4)},startLease=e=>{scheduleHeartbeat(e),s=setTimeout(()=>{clearTimers();try{e.enqueue(i.encode(`${JSON.stringify(EVE_STREAM_LEASE_ENDED_CONTROL)}\n`)),e.terminate()}catch{}},6e4)},c=new TransformStream({start(e){e.enqueue(i.encode(`
|
|
3
3
|
`)),n===0?e.terminate():r&&startLease(e)},transform(e,t){t.enqueue(i.encode(`${JSON.stringify(e)}\n`)),a+=1,a===n?(clearTimers(),t.terminate()):r&&scheduleHeartbeat(t)},flush(){clearTimers()}});return e.pipeTo(c.writable,{signal:t}).catch(()=>{}).finally(clearTimers),c.readable}export{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId};
|