@gram-ai/elements 1.15.0 → 1.16.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/LICENSE +661 -0
- package/dist/elements.cjs +20 -20
- package/dist/elements.css +1 -1
- package/dist/elements.js +3163 -2946
- package/dist/index-BqoFmyxX.cjs +60 -0
- package/dist/{index-cubKOZsm.js → index-CVZt-xeH.js} +5760 -5494
- package/dist/server.cjs +14 -16
- package/dist/server.js +1375 -1256
- package/package.json +13 -16
- package/dist/components/assistant-ui/d3-renderer.d.ts +0 -5
- package/dist/index-Bq3DSKiX.cjs +0 -60
package/dist/server.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./index-Bq3DSKiX.cjs");var ar=e=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,{...n.description?{description:n.description}:void 0,inputSchema:t.jsonSchema(n.parameters)}]));let Oe;Oe=globalThis.crypto;async function ir(e){return(await Oe).getRandomValues(new Uint8Array(e))}async function lr(e){const r="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",n=Math.pow(2,8)-Math.pow(2,8)%r.length;let o="";for(;o.length<e;){const s=await ir(e-o.length);for(const a of s)a<n&&(o+=r[a%r.length])}return o}async function cr(e){return await lr(e)}async function ur(e){const r=await(await Oe).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function pr(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const r=await cr(e),n=await ur(r);return{code_verifier:r,code_challenge:n}}var dr="AI_MCPClientError",tt=`vercel.ai.error.${dr}`,hr=Symbol.for(tt),Ve,Be,R=class extends(Be=t.AISDKError,Ve=hr,Be){constructor({name:e="MCPClientError",message:r,cause:n,data:o,code:s}){super({name:e,message:r,cause:n}),this[Ve]=!0,this.data=o,this.code=s}static isInstance(e){return t.AISDKError.hasMarker(e,tt)}},Y="2025-06-18",gr=[Y,"2025-03-26","2024-11-05"],mr=t.looseObject({name:t.string(),version:t.string()}),ye=t.looseObject({_meta:t.optional(t.object({}).loose())}),z=ye,rt=t.object({method:t.string(),params:t.optional(ye)}),nt=t.object({applyDefaults:t.optional(t.boolean())}).loose(),fr=t.looseObject({experimental:t.optional(t.object({}).loose()),logging:t.optional(t.object({}).loose()),prompts:t.optional(t.looseObject({listChanged:t.optional(t.boolean())})),resources:t.optional(t.looseObject({subscribe:t.optional(t.boolean()),listChanged:t.optional(t.boolean())})),tools:t.optional(t.looseObject({listChanged:t.optional(t.boolean())})),elicitation:t.optional(nt)});t.object({elicitation:t.optional(nt)}).loose();var _r=z.extend({protocolVersion:t.string(),capabilities:fr,serverInfo:mr,instructions:t.optional(t.string())}),Ae=z.extend({nextCursor:t.optional(t.string())}),vr=t.object({name:t.string(),description:t.optional(t.string()),inputSchema:t.object({type:t.literal("object"),properties:t.optional(t.object({}).loose())}).loose()}).loose(),yr=Ae.extend({tools:t.array(vr)}),ot=t.object({type:t.literal("text"),text:t.string()}).loose(),st=t.object({type:t.literal("image"),data:t.base64(),mimeType:t.string()}).loose(),br=t.object({uri:t.string(),name:t.string(),title:t.optional(t.string()),description:t.optional(t.string()),mimeType:t.optional(t.string()),size:t.optional(t.number())}).loose(),wr=Ae.extend({resources:t.array(br)}),at=t.object({uri:t.string(),name:t.optional(t.string()),title:t.optional(t.string()),mimeType:t.optional(t.string())}).loose(),it=at.extend({text:t.string()}),lt=at.extend({blob:t.base64()}),ct=t.object({type:t.literal("resource"),resource:t.union([it,lt])}).loose(),kr=z.extend({content:t.array(t.union([ot,st,ct])),isError:t.boolean().default(!1).optional()}).or(z.extend({toolResult:t.unknown()})),Sr=t.object({uriTemplate:t.string(),name:t.string(),title:t.optional(t.string()),description:t.optional(t.string()),mimeType:t.optional(t.string())}).loose(),Tr=z.extend({resourceTemplates:t.array(Sr)}),Rr=z.extend({contents:t.array(t.union([it,lt]))}),Er=t.object({name:t.string(),description:t.optional(t.string()),required:t.optional(t.boolean())}).loose(),Cr=t.object({name:t.string(),title:t.optional(t.string()),description:t.optional(t.string()),arguments:t.optional(t.array(Er))}).loose(),xr=Ae.extend({prompts:t.array(Cr)}),Ir=t.object({role:t.union([t.literal("user"),t.literal("assistant")]),content:t.union([ot,st,ct])}).loose(),Pr=z.extend({description:t.optional(t.string()),messages:t.array(Ir)}),jr=ye.extend({message:t.string(),requestedSchema:t.unknown()}),Je=rt.extend({method:t.literal("elicitation/create"),params:jr}),Or=z.extend({action:t.union([t.literal("accept"),t.literal("decline"),t.literal("cancel")]),content:t.optional(t.record(t.string(),t.unknown()))}),be="2.0",Ar=t.object({jsonrpc:t.literal(be),id:t.union([t.string(),t.number().int()])}).merge(rt).strict(),Ur=t.object({jsonrpc:t.literal(be),id:t.union([t.string(),t.number().int()]),result:z}).strict(),$r=t.object({jsonrpc:t.literal(be),id:t.union([t.string(),t.number().int()]),error:t.object({code:t.number().int(),message:t.string(),data:t.optional(t.unknown())})}).strict(),Mr=t.object({jsonrpc:t.literal(be)}).merge(t.object({method:t.string(),params:t.optional(ye)})).strict(),ee=t.union([Ar,Mr,Ur,$r]),ut=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",pt=t.object({access_token:t.string(),id_token:t.string().optional(),token_type:t.string(),expires_in:t.number().optional(),scope:t.string().optional(),refresh_token:t.string().optional()}).strip(),D=t.string().url().superRefine((e,r)=>{if(!URL.canParse(e))return r.addIssue({code:t.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),t.NEVER}).refine(e=>{const r=new URL(e);return r.protocol!=="javascript:"&&r.protocol!=="data:"&&r.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Nr=t.object({resource:t.string().url(),authorization_servers:t.array(D).optional(),jwks_uri:t.string().url().optional(),scopes_supported:t.array(t.string()).optional(),bearer_methods_supported:t.array(t.string()).optional(),resource_signing_alg_values_supported:t.array(t.string()).optional(),resource_name:t.string().optional(),resource_documentation:t.string().optional(),resource_policy_uri:t.string().url().optional(),resource_tos_uri:t.string().url().optional(),tls_client_certificate_bound_access_tokens:t.boolean().optional(),authorization_details_types_supported:t.array(t.string()).optional(),dpop_signing_alg_values_supported:t.array(t.string()).optional(),dpop_bound_access_tokens_required:t.boolean().optional()}).passthrough(),dt=t.object({issuer:t.string(),authorization_endpoint:D,token_endpoint:D,registration_endpoint:D.optional(),scopes_supported:t.array(t.string()).optional(),response_types_supported:t.array(t.string()),grant_types_supported:t.array(t.string()).optional(),code_challenge_methods_supported:t.array(t.string()),token_endpoint_auth_methods_supported:t.array(t.string()).optional(),token_endpoint_auth_signing_alg_values_supported:t.array(t.string()).optional()}).passthrough(),Dr=t.object({issuer:t.string(),authorization_endpoint:D,token_endpoint:D,userinfo_endpoint:D.optional(),jwks_uri:D,registration_endpoint:D.optional(),scopes_supported:t.array(t.string()).optional(),response_types_supported:t.array(t.string()),grant_types_supported:t.array(t.string()).optional(),subject_types_supported:t.array(t.string()),id_token_signing_alg_values_supported:t.array(t.string()),claims_supported:t.array(t.string()).optional(),token_endpoint_auth_methods_supported:t.array(t.string()).optional()}).passthrough(),Hr=Dr.merge(dt.pick({code_challenge_methods_supported:!0})),qr=t.object({client_id:t.string(),client_secret:t.string().optional(),client_id_issued_at:t.number().optional(),client_secret_expires_at:t.number().optional()}).strip(),Lr=t.object({redirect_uris:t.array(D),token_endpoint_auth_method:t.string().optional(),grant_types:t.array(t.string()).optional(),response_types:t.array(t.string()).optional(),client_name:t.string().optional(),client_uri:D.optional(),logo_uri:D.optional(),scope:t.string().optional(),contacts:t.array(t.string()).optional(),tos_uri:D.optional(),policy_uri:t.string().optional(),jwks_uri:D.optional(),jwks:t.any().optional(),software_id:t.string().optional(),software_version:t.string().optional(),software_statement:t.string().optional()}).strip(),Vr=t.object({error:t.string(),error_description:t.string().optional(),error_uri:t.string().optional()}),Br=Lr.merge(qr),Jr="AI_MCPClientOAuthError",ht=`vercel.ai.error.${Jr}`,zr=Symbol.for(ht),ze,We,se=class extends(We=t.AISDKError,ze=zr,We){constructor({name:e="MCPClientOAuthError",message:r,cause:n}){super({name:e,message:r,cause:n}),this[ze]=!0}static isInstance(e){return t.AISDKError.hasMarker(e,ht)}},X=class extends se{};X.errorCode="server_error";var ue=class extends se{};ue.errorCode="invalid_client";var pe=class extends se{};pe.errorCode="invalid_grant";var de=class extends se{};de.errorCode="unauthorized_client";var Wr={[X.errorCode]:X,[ue.errorCode]:ue,[pe.errorCode]:pe,[de.errorCode]:de};function Gr(e){const r=typeof e=="string"?new URL(e):new URL(e.href);return r.hash="",r}function Kr({requestedResource:e,configuredResource:r}){const n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof r=="string"?new URL(r):new URL(r.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;const s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return s.startsWith(a)}var he=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function ge(e){var r;const n=(r=e.headers.get("www-authenticate"))!=null?r:e.headers.get("WWW-Authenticate");if(!n)return;const[o,s]=n.split(" ");if(o.toLowerCase()!=="bearer"||!s)return;const a=/resource_metadata="([^"]*)"/,l=n.match(a);if(l)try{return new URL(l[1])}catch{return}}function Fr(e,r="",n={}){return r.endsWith("/")&&(r=r.slice(0,-1)),n.prependPathname?`${r}/.well-known/${e}`:`/.well-known/${e}${r}`}async function Ue(e,r,n=fetch){try{return await n(e,{headers:r})}catch(o){if(o instanceof TypeError)return r?Ue(e,void 0,n):void 0;throw o}}async function Ge(e,r,n=fetch){return await Ue(e,{"MCP-Protocol-Version":r},n)}function Zr(e,r){return!e||e.status>=400&&e.status<500&&r!=="/"}async function Xr(e,r,n,o){var s,a;const l=new URL(e),c=(s=o?.protocolVersion)!=null?s:Y;let i;if(o?.metadataUrl)i=new URL(o.metadataUrl);else{const d=Fr(r,l.pathname);i=new URL(d,(a=o?.metadataServerUrl)!=null?a:l),i.search=l.search}let u=await Ge(i,c,n);if(!o?.metadataUrl&&Zr(u,l.pathname)){const d=new URL(`/.well-known/${r}`,l);u=await Ge(d,c,n)}return u}async function Yr(e,r,n=fetch){const o=await Xr(e,"oauth-protected-resource",n,{protocolVersion:r?.protocolVersion,metadataUrl:r?.resourceMetadataUrl});if(!o||o.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Nr.parse(await o.json())}function Qr(e){const r=typeof e=="string"?new URL(e):e,n=r.pathname!=="/",o=[];if(!n)return o.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",r.origin),type:"oidc"}),o;let s=r.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,r.origin),type:"oauth"}),o.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${s}`,r.origin),type:"oidc"}),o.push({url:new URL(`${s}/.well-known/openid-configuration`,r.origin),type:"oidc"}),o}async function en(e,{fetchFn:r=fetch,protocolVersion:n=Y}={}){var o;const s={"MCP-Protocol-Version":n},a=Qr(e);for(const{url:l,type:c}of a){const i=await Ue(l,s,r);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${l}`)}if(c==="oauth")return dt.parse(await i.json());{const u=Hr.parse(await i.json());if(!((o=u.code_challenge_methods_supported)!=null&&o.includes("S256")))throw new Error(`Incompatible OIDC provider at ${l}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function tn(e,{metadata:r,clientInformation:n,redirectUrl:o,scope:s,state:a,resource:l}){const c="code",i="S256";let u;if(r){if(u=new URL(r.authorization_endpoint),!r.response_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support response type ${c}`);if(!r.code_challenge_methods_supported||!r.code_challenge_methods_supported.includes(i))throw new Error(`Incompatible auth server: does not support code challenge method ${i}`)}else u=new URL("/authorize",e);const d=await pr(),m=d.code_verifier,h=d.code_challenge;return u.searchParams.set("response_type",c),u.searchParams.set("client_id",n.client_id),u.searchParams.set("code_challenge",h),u.searchParams.set("code_challenge_method",i),u.searchParams.set("redirect_uri",String(o)),a&&u.searchParams.set("state",a),s&&u.searchParams.set("scope",s),s?.includes("offline_access")&&u.searchParams.append("prompt","consent"),l&&u.searchParams.set("resource",l.href),{authorizationUrl:u,codeVerifier:m}}function gt(e,r){const n=e.client_secret!==void 0;return r.length===0?n?"client_secret_post":"none":n&&r.includes("client_secret_basic")?"client_secret_basic":n&&r.includes("client_secret_post")?"client_secret_post":r.includes("none")?"none":n?"client_secret_post":"none"}function mt(e,r,n,o){const{client_id:s,client_secret:a}=r;switch(e){case"client_secret_basic":rn(s,a,n);return;case"client_secret_post":nn(s,a,o);return;case"none":on(s,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function rn(e,r,n){if(!r)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${r}`);n.set("Authorization",`Basic ${o}`)}function nn(e,r,n){n.set("client_id",e),r&&n.set("client_secret",r)}function on(e,r){r.set("client_id",e)}async function $e(e){const r=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const o=Vr.parse(JSON.parse(n)),{error:s,error_description:a,error_uri:l}=o,c=Wr[s]||X;return new c({message:a||"",cause:l})}catch(o){const s=`${r?`HTTP ${r}: `:""}Invalid OAuth error response: ${o}. Raw body: ${n}`;return new X({message:s})}}async function sn(e,{metadata:r,clientInformation:n,authorizationCode:o,codeVerifier:s,redirectUri:a,resource:l,addClientAuthentication:c,fetchFn:i}){var u;const d="authorization_code",m=r?.token_endpoint?new URL(r.token_endpoint):new URL("/token",e);if(r?.grant_types_supported&&!r.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),f=new URLSearchParams({grant_type:d,code:o,code_verifier:s,redirect_uri:String(a)});if(c)c(h,f,e,r);else{const p=(u=r?.token_endpoint_auth_methods_supported)!=null?u:[],y=gt(n,p);mt(y,n,h,f)}l&&f.set("resource",l.href);const g=await(i??fetch)(m,{method:"POST",headers:h,body:f});if(!g.ok)throw await $e(g);return pt.parse(await g.json())}async function an(e,{metadata:r,clientInformation:n,refreshToken:o,resource:s,addClientAuthentication:a,fetchFn:l}){var c;const i="refresh_token";let u;if(r){if(u=new URL(r.token_endpoint),r.grant_types_supported&&!r.grant_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support grant type ${i}`)}else u=new URL("/token",e);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),m=new URLSearchParams({grant_type:i,refresh_token:o});if(a)a(d,m,e,r);else{const f=(c=r?.token_endpoint_auth_methods_supported)!=null?c:[],g=gt(n,f);mt(g,n,d,m)}s&&m.set("resource",s.href);const h=await(l??fetch)(u,{method:"POST",headers:d,body:m});if(!h.ok)throw await $e(h);return pt.parse({refresh_token:o,...await h.json()})}async function ln(e,{metadata:r,clientMetadata:n,fetchFn:o}){let s;if(r){if(!r.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(r.registration_endpoint)}else s=new URL("/register",e);const a=await(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok)throw await $e(a);return Br.parse(await a.json())}async function me(e,r){var n,o;try{return await Se(e,r)}catch(s){if(s instanceof ue||s instanceof de)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"all")),await Se(e,r);if(s instanceof pe)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"tokens")),await Se(e,r);throw s}}async function cn(e,r,n){const o=Gr(e);if(r.validateResourceURL)return await r.validateResourceURL(o,n?.resource);if(n){if(!Kr({requestedResource:o,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${o} (or origin)`);return new URL(n.resource)}}async function Se(e,{serverUrl:r,authorizationCode:n,scope:o,resourceMetadataUrl:s,fetchFn:a}){let l,c;try{l=await Yr(r,{resourceMetadataUrl:s},a),l.authorization_servers&&l.authorization_servers.length>0&&(c=l.authorization_servers[0])}catch{}c||(c=r);const i=await cn(r,e,l),u=await en(c,{fetchFn:a});let d=await Promise.resolve(e.clientInformation());if(!d){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const p=await ln(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(p),d=p}if(n!==void 0){const p=await e.codeVerifier(),y=await sn(c,{metadata:u,clientInformation:d,authorizationCode:n,codeVerifier:p,redirectUri:e.redirectUrl,resource:i,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(y),"AUTHORIZED"}const m=await e.tokens();if(m?.refresh_token)try{const p=await an(c,{metadata:u,clientInformation:d,refreshToken:m.refresh_token,resource:i,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(p),"AUTHORIZED"}catch(p){if(!(!(p instanceof se)||p instanceof X))throw p}const h=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:g}=await tn(c,{metadata:u,clientInformation:d,state:h,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:i});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(f),"REDIRECT"}var un=class{constructor({url:e,headers:r,authProvider:n}){this.connected=!1,this.url=new URL(e),this.headers=r,this.authProvider=n}async commonHeaders(e){const r={...this.headers,...e,"mcp-protocol-version":Y};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return t.withUserAgentSuffix(r,`ai-sdk/${ut}`,t.getRuntimeEnvironmentUserAgent())}async start(){return new Promise((e,r)=>{if(this.connected)return e();this.abortController=new AbortController;const n=async(o=!1)=>{var s,a,l,c,i;try{const u=await this.commonHeaders({Accept:"text/event-stream"}),d=await fetch(this.url.href,{headers:u,signal:(s=this.abortController)==null?void 0:s.signal});if(d.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=ge(d);try{if(await me(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const p=new he;return(a=this.onerror)==null||a.call(this,p),r(p)}}catch(g){return(l=this.onerror)==null||l.call(this,g),r(g)}return n(!0)}if(!d.ok||!d.body){let g=`MCP SSE Transport Error: ${d.status} ${d.statusText}`;d.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");const p=new R({message:g});return(c=this.onerror)==null||c.call(this,p),r(p)}const h=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).getReader(),f=async()=>{var g,p,y;try{for(;;){const{done:_,value:b}=await h.read();if(_){if(this.connected)throw this.connected=!1,new R({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:v,data:C}=b;if(v==="endpoint"){if(this.endpoint=new URL(C,this.url),this.endpoint.origin!==this.url.origin)throw new R({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(v==="message")try{const S=ee.parse(JSON.parse(C));(g=this.onmessage)==null||g.call(this,S)}catch(S){const I=new R({message:"MCP SSE Transport Error: Failed to parse message",cause:S});(p=this.onerror)==null||p.call(this,I)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(y=this.onerror)==null||y.call(this,_),r(_)}};this.sseConnection={close:()=>h.cancel()},f()}catch(u){if(u instanceof Error&&u.name==="AbortError")return;(i=this.onerror)==null||i.call(this,u),r(u)}};n()})}async close(){var e,r,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(r=this.abortController)==null||r.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new R({message:"MCP SSE Transport Error: Not connected"});const r=this.endpoint,n=async(o=!1)=>{var s,a,l,c,i;try{const d={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(s=this.abortController)==null?void 0:s.signal},m=await fetch(r,d);if(m.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=ge(m);try{if(await me(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new he;(a=this.onerror)==null||a.call(this,f);return}}catch(h){(l=this.onerror)==null||l.call(this,h);return}return n(!0)}if(!m.ok){const h=await m.text().catch(()=>null),f=new R({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${m.status}): ${h}`});(c=this.onerror)==null||c.call(this,f);return}}catch(u){(i=this.onerror)==null||i.call(this,u);return}};await n()}},pn=class{constructor({url:e,headers:r,authProvider:n}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=r,this.authProvider=n}async commonHeaders(e){const r={...this.headers,...e,"mcp-protocol-version":Y};if(this.sessionId&&(r["mcp-session-id"]=this.sessionId),this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return t.withUserAgentSuffix(r,`ai-sdk/${ut}`,t.getRuntimeEnvironmentUserAgent())}async start(){if(this.abortController)throw new R({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,r,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const o=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:o,signal:this.abortController.signal}).catch(()=>{})}}catch{}(r=this.abortController)==null||r.abort(),(n=this.onclose)==null||n.call(this)}async send(e){const r=async(n=!1)=>{var o,s,a,l,c,i,u;try{const m={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},h=await fetch(this.url,m),f=h.headers.get("mcp-session-id");if(f&&(this.sessionId=f),h.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ge(h);try{if(await me(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new he}catch(y){throw(s=this.onerror)==null||s.call(this,y),y}return r(!0)}if(h.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!h.ok){const y=await h.text().catch(()=>null);let _=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${y}`;h.status===404&&(_+=". This server does not support HTTP transport. Try using `sse` transport instead");const b=new R({message:_});throw(a=this.onerror)==null||a.call(this,b),b}const g=h.headers.get("content-type")||"";if(g.includes("application/json")){const y=await h.json(),_=Array.isArray(y)?y.map(b=>ee.parse(b)):[ee.parse(y)];for(const b of _)(l=this.onmessage)==null||l.call(this,b);return}if(g.includes("text/event-stream")){if(!h.body){const v=new R({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(c=this.onerror)==null||c.call(this,v),v}const _=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).getReader();(async()=>{var v,C,S;try{for(;;){const{done:I,value:P}=await _.read();if(I)return;const{event:U,data:q}=P;if(U==="message")try{const H=ee.parse(JSON.parse(q));(v=this.onmessage)==null||v.call(this,H)}catch(H){const L=new R({message:"MCP HTTP Transport Error: Failed to parse message",cause:H});(C=this.onerror)==null||C.call(this,L)}}}catch(I){if(I instanceof Error&&I.name==="AbortError")return;(S=this.onerror)==null||S.call(this,I)}})();return}const p=new R({message:`MCP HTTP Transport Error: Unexpected content type: ${g}`});throw(i=this.onerror)==null||i.call(this,p),p}catch(d){throw(u=this.onerror)==null||u.call(this,d),d}};await r()}getNextReconnectionDelay(e){const{initialReconnectionDelay:r,reconnectionDelayGrowFactor:n,maxReconnectionDelay:o}=this.reconnectionOptions;return Math.min(r*Math.pow(n,e),o)}scheduleInboundSseReconnection(){var e;const{maxRetries:r}=this.reconnectionOptions;if(r>0&&this.inboundReconnectAttempts>=r){(e=this.onerror)==null||e.call(this,new R({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${r}) exceeded.`}));return}const n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var o;(o=this.abortController)!=null&&o.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,r){var n,o,s,a,l,c;try{const i=await this.commonHeaders({Accept:"text/event-stream"});r&&(i["last-event-id"]=r);const u=await fetch(this.url.href,{method:"GET",headers:i,signal:(n=this.abortController)==null?void 0:n.signal}),d=u.headers.get("mcp-session-id");if(d&&(this.sessionId=d),u.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=ge(u);try{if(await me(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const p=new he;(o=this.onerror)==null||o.call(this,p);return}}catch(g){(s=this.onerror)==null||s.call(this,g);return}return this.openInboundSse(!0,r)}if(u.status===405)return;if(!u.ok||!u.body){const g=new R({message:`MCP HTTP Transport Error: GET SSE failed: ${u.status} ${u.statusText}`});(a=this.onerror)==null||a.call(this,g);return}const h=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).getReader(),f=async()=>{var g,p,y,_;try{for(;;){const{done:b,value:v}=await h.read();if(b)return;const{event:C,data:S,id:I}=v;if(I&&(this.lastInboundEventId=I),C==="message")try{const P=ee.parse(JSON.parse(S));(g=this.onmessage)==null||g.call(this,P)}catch(P){const U=new R({message:"MCP HTTP Transport Error: Failed to parse message",cause:P});(p=this.onerror)==null||p.call(this,U)}}}catch(b){if(b instanceof Error&&b.name==="AbortError")return;(y=this.onerror)==null||y.call(this,b),(_=this.abortController)!=null&&_.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>h.cancel()},this.inboundReconnectAttempts=0,f()}catch(i){if(i instanceof Error&&i.name==="AbortError")return;(l=this.onerror)==null||l.call(this,i),(c=this.abortController)!=null&&c.signal.aborted||this.scheduleInboundSseReconnection()}}};function dn(e){switch(e.type){case"sse":return new un(e);case"http":return new pn(e);default:throw new R({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function hn(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var gn="1.0.0";async function mn(e){const r=new fn(e);return await r.init(),r}var fn=class{constructor({transport:e,name:r="ai-sdk-mcp-client",version:n=gn,onUncaughtError:o,capabilities:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=o,this.clientCapabilities=s??{},hn(e)?this.transport=e:this.transport=dn(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=a=>this.onError(a),this.transport.onmessage=a=>{if("method"in a){"id"in a?this.onRequestMessage(a):this.onError(new R({message:"Unsupported message type"}));return}this.onResponse(a)},this.clientInfo={name:r,version:n}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:Y,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:_r});if(e===void 0)throw new R({message:"Server sent invalid initialize result"});if(!gr.includes(e.protocolVersion))throw new R({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new R({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new R({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new R({message:"Server does not support prompts"});break;default:throw new R({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:r,options:n}){return new Promise((o,s)=>{if(this.isClosed)return s(new R({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const a=n?.signal;a?.throwIfAborted();const l=this.requestMessageId++,c={...e,jsonrpc:"2.0",id:l},i=()=>{this.responseHandlers.delete(l)};this.responseHandlers.set(l,u=>{if(a?.aborted)return s(new R({message:"Request was aborted",cause:a.reason}));if(u instanceof Error)return s(u);try{const d=r.parse(u.result);o(d)}catch(d){const m=new R({message:"Failed to parse server response",cause:d});s(m)}}),this.transport.send(c).catch(u=>{i(),s(u)})})}async listTools({params:e,options:r}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:yr,options:r})}catch(n){throw n}}async callTool({name:e,args:r,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:r}},resultSchema:kr,options:{signal:n?.abortSignal}})}catch(o){throw o}}async listResourcesInternal({params:e,options:r}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:wr,options:r})}catch(n){throw n}}async readResourceInternal({uri:e,options:r}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:Rr,options:r})}catch(n){throw n}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:Tr,options:e})}catch(r){throw r}}async listPromptsInternal({params:e,options:r}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:xr,options:r})}catch(n){throw n}}async getPromptInternal({name:e,args:r,options:n}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:r}},resultSchema:Pr,options:n})}catch(o){throw o}}async notification(e){const r={...e,jsonrpc:"2.0"};await this.transport.send(r)}async tools({schemas:e="automatic"}={}){var r;const n={};try{const o=await this.listTools();for(const{name:s,description:a,inputSchema:l}of o.tools){if(e!=="automatic"&&!(s in e))continue;const c=this,i=async(d,m)=>{var h;return(h=m?.abortSignal)==null||h.throwIfAborted(),c.callTool({name:s,args:d,options:m})},u=e==="automatic"?t.dynamicTool({description:a,inputSchema:t.jsonSchema({...l,properties:(r=l.properties)!=null?r:{},additionalProperties:!1}),execute:i}):t.tool({description:a,inputSchema:e[s].inputSchema,execute:i});n[s]=u}return n}catch(o){throw o}}listResources({params:e,options:r}={}){return this.listResourcesInternal({params:e,options:r})}readResource({uri:e,options:r}){return this.readResourceInternal({uri:e,options:r})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}listPrompts({params:e,options:r}={}){return this.listPromptsInternal({params:e,options:r})}getPrompt({name:e,arguments:r,options:n}){return this.getPromptInternal({name:e,args:r,options:n})}onElicitationRequest(e,r){if(e!==Je)throw new R({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=r}async onRequestMessage(e){try{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}const r=Je.safeParse({method:e.method,params:e.params});if(!r.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${r.error.message}`,data:r.error.issues}});return}try{const n=await this.elicitationRequestHandler(r.data),o=Or.parse(n);await this.transport.send({jsonrpc:"2.0",id:e.id,result:o})}catch(n){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:n instanceof Error?n.message:"Failed to handle elicitation request"}}),this.onError(n)}}catch(r){this.onError(r)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new R({message:"Connection closed"});for(const r of this.responseHandlers.values())r(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const r=Number(e.id),n=this.responseHandlers.get(r);if(n===void 0)throw new R({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(r),n("result"in e?e:new R({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},_n=Object.defineProperty,vn=Object.defineProperties,yn=Object.getOwnPropertyDescriptors,Ke=Object.getOwnPropertySymbols,bn=Object.prototype.hasOwnProperty,wn=Object.prototype.propertyIsEnumerable,Fe=(e,r,n)=>r in e?_n(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n,E=(e,r)=>{for(var n in r||(r={}))bn.call(r,n)&&Fe(e,n,r[n]);if(Ke)for(var n of Ke(r))wn.call(r,n)&&Fe(e,n,r[n]);return e},fe=(e,r)=>vn(e,yn(r)),ft="vercel.ai.error",kn=Symbol.for(ft),_t,Sn=class vt extends Error{constructor({name:r,message:n,cause:o}){super(n),this[_t]=!0,this.name=r,this.cause=o}static isInstance(r){return vt.hasMarker(r,ft)}static hasMarker(r,n){const o=Symbol.for(n);return r!=null&&typeof r=="object"&&o in r&&typeof r[o]=="boolean"&&r[o]===!0}};_t=kn;var A=Sn,yt="AI_APICallError",bt=`vercel.ai.error.${yt}`,Tn=Symbol.for(bt),wt,B=class extends A{constructor({message:e,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:a,cause:l,isRetryable:c=o!=null&&(o===408||o===409||o===429||o>=500),data:i}){super({name:yt,message:e,cause:l}),this[wt]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=c,this.data=i}static isInstance(e){return A.hasMarker(e,bt)}};wt=Tn;var kt="AI_EmptyResponseBodyError",St=`vercel.ai.error.${kt}`,Rn=Symbol.for(St),Tt,En=class extends A{constructor({message:e="Empty response body"}={}){super({name:kt,message:e}),this[Tt]=!0}static isInstance(e){return A.hasMarker(e,St)}};Tt=Rn;function Rt(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Et="AI_InvalidArgumentError",Ct=`vercel.ai.error.${Et}`,Cn=Symbol.for(Ct),xt,It=class extends A{constructor({message:e,cause:r,argument:n}){super({name:Et,message:e,cause:r}),this[xt]=!0,this.argument=n}static isInstance(e){return A.hasMarker(e,Ct)}};xt=Cn;var Pt="AI_InvalidPromptError",jt=`vercel.ai.error.${Pt}`,xn=Symbol.for(jt),Ot,In=class extends A{constructor({prompt:e,message:r,cause:n}){super({name:Pt,message:`Invalid prompt: ${r}`,cause:n}),this[Ot]=!0,this.prompt=e}static isInstance(e){return A.hasMarker(e,jt)}};Ot=xn;var At="AI_InvalidResponseDataError",Ut=`vercel.ai.error.${At}`,Pn=Symbol.for(Ut),$t,Q=class extends A{constructor({data:e,message:r=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:At,message:r}),this[$t]=!0,this.data=e}static isInstance(e){return A.hasMarker(e,Ut)}};$t=Pn;var Mt="AI_JSONParseError",Nt=`vercel.ai.error.${Mt}`,jn=Symbol.for(Nt),Dt,_e=class extends A{constructor({text:e,cause:r}){super({name:Mt,message:`JSON parsing failed: Text: ${e}.
|
|
2
|
-
Error message: ${
|
|
3
|
-
Error message: ${
|
|
4
|
-
`;break;case"id":c=
|
|
5
|
-
`)?
|
|
6
|
-
`,o);let
|
|
7
|
-
`&&o++}}return[r,n]}var Hn=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(s){o=Nn({onEvent:a=>{s.enqueue(a)},onError(a){e==="terminate"?s.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function re(...e){return e.reduce((r,n)=>E(E({},r),n??{}),{})}function we(e){return Object.fromEntries([...e.headers])}var qn=({prefix:e,size:r=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const s=()=>{const a=n.length,l=new Array(r);for(let c=0;c<r;c++)l[c]=n[Math.random()*a|0];return l.join("")};if(e==null)return s;if(n.includes(o))throw new It({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${e}${o}${s()}`},V=qn();function xe(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Ln=["fetch failed","failed to fetch"];function Vn({error:e,url:r,requestBodyValues:n}){if(xe(e))return e;if(e instanceof TypeError&&Ln.includes(e.message.toLowerCase())){const o=e.cause;if(o!=null)return new B({message:`Cannot connect to API: ${o.message}`,cause:o,url:r,requestBodyValues:n,isRetryable:!0})}return e}function Bn(e){return Object.fromEntries(Object.entries(e).filter(([r,n])=>n!=null))}function Jn({apiKey:e,environmentVariableName:r,apiKeyParameterName:n="apiKey",description:o}){if(typeof e=="string")return e;if(e!=null)throw new le({message:`${o} API key must be a string.`});if(typeof process>"u")throw new le({message:`${o} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[r],e==null)throw new le({message:`${o} API key is missing. Pass it using the '${n}' parameter or the ${r} environment variable.`});if(typeof e!="string")throw new le({message:`${o} API key must be a string. The value of the ${r} environment variable is not a string.`});return e}var zn=/"__proto__"\s*:/,Wn=/"constructor"\s*:/;function Gn(e){const r=JSON.parse(e);return r===null||typeof r!="object"||zn.test(e)===!1&&Wn.test(e)===!1?r:Kn(r)}function Kn(e){let r=[e];for(;r.length;){const n=r;r=[];for(const o of n){if(Object.prototype.hasOwnProperty.call(o,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(o,"constructor")&&Object.prototype.hasOwnProperty.call(o.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const s in o){const a=o[s];a&&typeof a=="object"&&r.push(a)}}}return e}function Me(e){const{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return Gn(e)}finally{Error.stackTraceLimit=r}}var Ie=Symbol.for("vercel.ai.validator");function Fn(e){return{[Ie]:!0,validate:e}}function Zn(e){return typeof e=="object"&&e!==null&&Ie in e&&e[Ie]===!0&&"validate"in e}function Xn(e){return Zn(e)?e:Yn(e)}function Yn(e){return Fn(async r=>{const n=await e["~standard"].validate(r);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new te({value:r,cause:n.issues})}})}async function Qn({value:e,schema:r}){const n=await Yt({value:e,schema:r});if(!n.success)throw te.wrap({value:e,cause:n.error});return n.value}async function Yt({value:e,schema:r}){const n=Xn(r);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:te.wrap({value:e,cause:o.error}),rawValue:e}}catch(o){return{success:!1,error:te.wrap({value:e,cause:o}),rawValue:e}}}async function eo({text:e,schema:r}){try{const n=Me(e);return r==null?n:Qn({value:n,schema:r})}catch(n){throw _e.isInstance(n)||te.isInstance(n)?n:new _e({text:e,cause:n})}}async function Qt({text:e,schema:r}){try{const n=Me(e);return r==null?{success:!0,value:n,rawValue:n}:await Yt({value:n,schema:r})}catch(n){return{success:!1,error:_e.isInstance(n)?n:new _e({text:e,cause:n}),rawValue:void 0}}}function Re(e){try{return Me(e),!0}catch{return!1}}function to({stream:e,schema:r}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Hn).pipeThrough(new TransformStream({async transform({data:n},o){n!=="[DONE]"&&o.enqueue(await Qt({text:n,schema:r}))}}))}var ro=()=>globalThis.fetch,ne=async({url:e,headers:r,body:n,failedResponseHandler:o,successfulResponseHandler:s,abortSignal:a,fetch:l})=>no({url:e,headers:E({"Content-Type":"application/json"},r),body:{content:JSON.stringify(n),values:n},failedResponseHandler:o,successfulResponseHandler:s,abortSignal:a,fetch:l}),no=async({url:e,headers:r={},body:n,successfulResponseHandler:o,failedResponseHandler:s,abortSignal:a,fetch:l=ro()})=>{try{const c=await l(e,{method:"POST",headers:Bn(r),body:n.content,signal:a}),i=we(c);if(!c.ok){let u;try{u=await s({response:c,url:e,requestBodyValues:n.values})}catch(d){throw xe(d)||B.isInstance(d)?d:new B({message:"Failed to process error response",cause:d,statusCode:c.status,url:e,responseHeaders:i,requestBodyValues:n.values})}throw u.value}try{return await o({response:c,url:e,requestBodyValues:n.values})}catch(u){throw u instanceof Error&&(xe(u)||B.isInstance(u))?u:new B({message:"Failed to process successful response",cause:u,statusCode:c.status,url:e,responseHeaders:i,requestBodyValues:n.values})}}catch(c){throw Vn({error:c,url:e,requestBodyValues:n.values})}},oo=({errorSchema:e,errorToMessage:r,isRetryable:n})=>async({response:o,url:s,requestBodyValues:a})=>{const l=await o.text(),c=we(o);if(l.trim()==="")return{responseHeaders:c,value:new B({message:o.statusText,url:s,requestBodyValues:a,statusCode:o.status,responseHeaders:c,responseBody:l,isRetryable:n?.(o)})};try{const i=await eo({text:l,schema:e});return{responseHeaders:c,value:new B({message:r(i),url:s,requestBodyValues:a,statusCode:o.status,responseHeaders:c,responseBody:l,data:i,isRetryable:n?.(o,i)})}}catch{return{responseHeaders:c,value:new B({message:o.statusText,url:s,requestBodyValues:a,statusCode:o.status,responseHeaders:c,responseBody:l,isRetryable:n?.(o)})}}},er=e=>async({response:r})=>{const n=we(r);if(r.body==null)throw new En({});return{responseHeaders:n,value:to({stream:r.body,schema:e})}},Ne=e=>async({response:r,url:n,requestBodyValues:o})=>{const s=await r.text(),a=await Qt({text:s,schema:e}),l=we(r);if(!a.success)throw new B({message:"Invalid JSON response",cause:a.error,statusCode:r.status,responseHeaders:l,responseBody:s,url:n,requestBodyValues:o});return{responseHeaders:l,value:a.value,rawValue:a.rawValue}},{btoa:so}=globalThis;function ao(e){let r="";for(let n=0;n<e.length;n++)r+=String.fromCodePoint(e[n]);return so(r)}function io(e){return e?.replace(/\/$/,"")}function Ee(e){return e!=null}var tr=(e=>(e.Unknown="unknown",e.OpenAIResponsesV1="openai-responses-v1",e.XAIResponsesV1="xai-responses-v1",e.AnthropicClaudeV1="anthropic-claude-v1",e.GoogleGeminiV1="google-gemini-v1",e))(tr||{}),De=t.object({id:t.string().nullish(),format:t._enum$1(tr).nullish(),index:t.number().optional()}).loose(),lo=t.object({type:t.literal("reasoning.summary"),summary:t.string()}).extend(De.shape),co=t.object({type:t.literal("reasoning.encrypted"),data:t.string()}).extend(De.shape),uo=t.object({type:t.literal("reasoning.text"),text:t.string().nullish(),signature:t.string().nullish()}).extend(De.shape),He=t.union([lo,co,uo]),ce=t.union([He,t.unknown().transform(()=>null)]),qe=t.array(ce).transform(e=>e.filter(r=>!!r));t.union([t.object({delta:t.object({reasoning_details:t.array(ce)})}).transform(e=>e.delta.reasoning_details.filter(Ee)),t.object({message:t.object({reasoning_details:t.array(ce)})}).transform(e=>e.message.reasoning_details.filter(Ee)),t.object({text:t.string(),reasoning_details:t.array(ce)}).transform(e=>e.reasoning_details.filter(Ee))]);var ke=t.object({error:t.object({code:t.union([t.string(),t.number()]).nullable().optional().default(null),message:t.string(),type:t.string().nullable().optional().default(null),param:t.any().nullable().optional().default(null)}).passthrough()}).passthrough(),oe=oo({errorSchema:ke,errorToMessage:e=>e.error.message}),rr=t.object({type:t.literal("file"),file:t.object({hash:t.string(),name:t.string(),content:t.array(t.object({type:t.string(),text:t.string().optional()}).passthrough()).optional()}).passthrough()}),po=t.object({provider:t.string(),reasoning_details:t.array(He).optional(),annotations:t.array(rr).optional(),usage:t.object({promptTokens:t.number(),promptTokensDetails:t.object({cachedTokens:t.number()}).passthrough().optional(),completionTokens:t.number(),completionTokensDetails:t.object({reasoningTokens:t.number()}).passthrough().optional(),totalTokens:t.number(),cost:t.number().optional(),costDetails:t.object({upstreamInferenceCost:t.number()}).passthrough().optional()}).passthrough()}).passthrough(),Xe=t.object({openrouter:t.object({reasoning_details:t.array(He).optional(),annotations:t.array(rr).optional()}).optional()}).optional();function ve(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}function Le({url:e,protocols:r}){try{const n=new URL(e);return r.has(n.protocol)}catch{return!1}}function Pe({part:e,defaultMediaType:r}){var n,o;if(e.data instanceof Uint8Array){const a=ao(e.data);return`data:${(n=e.mediaType)!=null?n:r};base64,${a}`}const s=e.data.toString();return Le({url:s,protocols:new Set(["http:","https:"])})||s.startsWith("data:")?s:`data:${(o=e.mediaType)!=null?o:r};base64,${s}`}function Ye(e,r){var n;const o=e.match(/^data:([^;]+)/);return o&&(n=o[1])!=null?n:r}function je(e){const r=e.match(/^data:[^;]*;base64,(.+)$/);return r?r[1]:e}function ho(e){const r=Pe({part:e,defaultMediaType:"audio/mpeg"});if(Le({url:r,protocols:new Set(["http:","https:"])}))throw new Error(`Audio files cannot be provided as URLs.
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./index-BqoFmyxX.cjs"),cr=e=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,{...n.description?{description:n.description}:void 0,inputSchema:t.jsonSchema(n.parameters)}]));var ur=({prefix:e,size:r=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const s=()=>{const a=n.length,i=new Array(r);for(let c=0;c<r;c++)i[c]=n[Math.random()*a|0];return i.join("")};if(e==null)return s;if(n.includes(o))throw new t.InvalidArgumentError({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${e}${o}${s()}`};ur();function rt(e=globalThis){var r,n,o;return e.window?"runtime/browser":(r=e.navigator)!=null&&r.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(o=(n=e.process)==null?void 0:n.versions)!=null&&o.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function dr(e){if(e==null)return{};const r={};if(e instanceof Headers)e.forEach((n,o)=>{r[o.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,o]of e)o!=null&&(r[n.toLowerCase()]=o)}return r}function nt(e,...r){const n=new Headers(dr(e)),o=n.get("user-agent")||"";return n.set("user-agent",[o,...r].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var pr=Symbol.for("vercel.ai.validator");function hr(e){return{...e,type:"dynamic"}}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var mr=Symbol.for("vercel.ai.schema");function gr(e,{validate:r}={}){return{[mr]:!0,_type:void 0,[pr]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:r}}let Ae;Ae=globalThis.crypto;async function fr(e){return(await Ae).getRandomValues(new Uint8Array(e))}async function _r(e){const r="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const o=await fr(e);for(let s=0;s<e;s++){const a=o[s]%r.length;n+=r[a]}return n}async function vr(e){return await _r(e)}async function yr(e){const r=await(await Ae).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function br(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const r=await vr(e),n=await yr(r);return{code_verifier:r,code_challenge:n}}var wr="AI_MCPClientError",ot=`vercel.ai.error.${wr}`,kr=Symbol.for(ot),Be,Je,R=class extends(Je=t.AISDKError,Be=kr,Je){constructor({name:e="MCPClientError",message:r,cause:n,data:o,code:s}){super({name:e,message:r,cause:n}),this[Be]=!0,this.data=o,this.code=s}static isInstance(e){return t.AISDKError.hasMarker(e,ot)}},ee="2025-06-18",Sr=[ee,"2025-03-26","2024-11-05"],Tr=t.looseObject({name:t.string(),version:t.string()}),be=t.looseObject({_meta:t.optional(t.object({}).loose())}),J=be,st=t.object({method:t.string(),params:t.optional(be)}),at=t.object({applyDefaults:t.optional(t.boolean())}).loose(),Rr=t.looseObject({experimental:t.optional(t.object({}).loose()),logging:t.optional(t.object({}).loose()),prompts:t.optional(t.looseObject({listChanged:t.optional(t.boolean())})),resources:t.optional(t.looseObject({subscribe:t.optional(t.boolean()),listChanged:t.optional(t.boolean())})),tools:t.optional(t.looseObject({listChanged:t.optional(t.boolean())})),elicitation:t.optional(at)});t.object({elicitation:t.optional(at)}).loose();var Er=J.extend({protocolVersion:t.string(),capabilities:Rr,serverInfo:Tr,instructions:t.optional(t.string())}),Ue=J.extend({nextCursor:t.optional(t.string())}),Cr=t.object({name:t.string(),description:t.optional(t.string()),inputSchema:t.object({type:t.literal("object"),properties:t.optional(t.object({}).loose())}).loose()}).loose(),Ir=Ue.extend({tools:t.array(Cr)}),it=t.object({type:t.literal("text"),text:t.string()}).loose(),lt=t.object({type:t.literal("image"),data:t.base64(),mimeType:t.string()}).loose(),xr=t.object({uri:t.string(),name:t.string(),title:t.optional(t.string()),description:t.optional(t.string()),mimeType:t.optional(t.string()),size:t.optional(t.number())}).loose(),Or=Ue.extend({resources:t.array(xr)}),ct=t.object({uri:t.string(),name:t.optional(t.string()),title:t.optional(t.string()),mimeType:t.optional(t.string())}).loose(),ut=ct.extend({text:t.string()}),dt=ct.extend({blob:t.base64()}),pt=t.object({type:t.literal("resource"),resource:t.union([ut,dt])}).loose(),jr=J.extend({content:t.array(t.union([it,lt,pt])),isError:t.boolean().default(!1).optional()}).or(J.extend({toolResult:t.unknown()})),Pr=t.object({uriTemplate:t.string(),name:t.string(),title:t.optional(t.string()),description:t.optional(t.string()),mimeType:t.optional(t.string())}).loose(),Ar=J.extend({resourceTemplates:t.array(Pr)}),Ur=J.extend({contents:t.array(t.union([ut,dt]))}),$r=t.object({name:t.string(),description:t.optional(t.string()),required:t.optional(t.boolean())}).loose(),Mr=t.object({name:t.string(),title:t.optional(t.string()),description:t.optional(t.string()),arguments:t.optional(t.array($r))}).loose(),Nr=Ue.extend({prompts:t.array(Mr)}),Dr=t.object({role:t.union([t.literal("user"),t.literal("assistant")]),content:t.union([it,lt,pt])}).loose(),Hr=J.extend({description:t.optional(t.string()),messages:t.array(Dr)}),Lr=be.extend({message:t.string(),requestedSchema:t.unknown()}),ze=st.extend({method:t.literal("elicitation/create"),params:Lr}),qr=J.extend({action:t.union([t.literal("accept"),t.literal("decline"),t.literal("cancel")]),content:t.optional(t.record(t.string(),t.unknown()))}),we="2.0",Vr=t.object({jsonrpc:t.literal(we),id:t.union([t.string(),t.number().int()])}).merge(st).strict(),Br=t.object({jsonrpc:t.literal(we),id:t.union([t.string(),t.number().int()]),result:J}).strict(),Jr=t.object({jsonrpc:t.literal(we),id:t.union([t.string(),t.number().int()]),error:t.object({code:t.number().int(),message:t.string(),data:t.optional(t.unknown())})}).strict(),zr=t.object({jsonrpc:t.literal(we)}).merge(t.object({method:t.string(),params:t.optional(be)})).strict(),re=t.union([Vr,zr,Br,Jr]),ht=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",mt=t.object({access_token:t.string(),id_token:t.string().optional(),token_type:t.string(),expires_in:t.number().optional(),scope:t.string().optional(),refresh_token:t.string().optional()}).strip(),N=t.string().url().superRefine((e,r)=>{if(!URL.canParse(e))return r.addIssue({code:t.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),t.NEVER}).refine(e=>{const r=new URL(e);return r.protocol!=="javascript:"&&r.protocol!=="data:"&&r.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Gr=t.object({resource:t.string().url(),authorization_servers:t.array(N).optional(),jwks_uri:t.string().url().optional(),scopes_supported:t.array(t.string()).optional(),bearer_methods_supported:t.array(t.string()).optional(),resource_signing_alg_values_supported:t.array(t.string()).optional(),resource_name:t.string().optional(),resource_documentation:t.string().optional(),resource_policy_uri:t.string().url().optional(),resource_tos_uri:t.string().url().optional(),tls_client_certificate_bound_access_tokens:t.boolean().optional(),authorization_details_types_supported:t.array(t.string()).optional(),dpop_signing_alg_values_supported:t.array(t.string()).optional(),dpop_bound_access_tokens_required:t.boolean().optional()}).passthrough(),gt=t.object({issuer:t.string(),authorization_endpoint:N,token_endpoint:N,registration_endpoint:N.optional(),scopes_supported:t.array(t.string()).optional(),response_types_supported:t.array(t.string()),grant_types_supported:t.array(t.string()).optional(),code_challenge_methods_supported:t.array(t.string()),token_endpoint_auth_methods_supported:t.array(t.string()).optional(),token_endpoint_auth_signing_alg_values_supported:t.array(t.string()).optional()}).passthrough(),Wr=t.object({issuer:t.string(),authorization_endpoint:N,token_endpoint:N,userinfo_endpoint:N.optional(),jwks_uri:N,registration_endpoint:N.optional(),scopes_supported:t.array(t.string()).optional(),response_types_supported:t.array(t.string()),grant_types_supported:t.array(t.string()).optional(),subject_types_supported:t.array(t.string()),id_token_signing_alg_values_supported:t.array(t.string()),claims_supported:t.array(t.string()).optional(),token_endpoint_auth_methods_supported:t.array(t.string()).optional()}).passthrough(),Fr=Wr.merge(gt.pick({code_challenge_methods_supported:!0})),Kr=t.object({client_id:t.string(),client_secret:t.string().optional(),client_id_issued_at:t.number().optional(),client_secret_expires_at:t.number().optional()}).strip(),Zr=t.object({redirect_uris:t.array(N),token_endpoint_auth_method:t.string().optional(),grant_types:t.array(t.string()).optional(),response_types:t.array(t.string()).optional(),client_name:t.string().optional(),client_uri:N.optional(),logo_uri:N.optional(),scope:t.string().optional(),contacts:t.array(t.string()).optional(),tos_uri:N.optional(),policy_uri:t.string().optional(),jwks_uri:N.optional(),jwks:t.any().optional(),software_id:t.string().optional(),software_version:t.string().optional(),software_statement:t.string().optional()}).strip(),Xr=t.object({error:t.string(),error_description:t.string().optional(),error_uri:t.string().optional()}),Yr=Zr.merge(Kr),Qr="AI_MCPClientOAuthError",ft=`vercel.ai.error.${Qr}`,en=Symbol.for(ft),Ge,We,ie=class extends(We=t.AISDKError,Ge=en,We){constructor({name:e="MCPClientOAuthError",message:r,cause:n}){super({name:e,message:r,cause:n}),this[Ge]=!0}static isInstance(e){return t.AISDKError.hasMarker(e,ft)}},Q=class extends ie{};Q.errorCode="server_error";var de=class extends ie{};de.errorCode="invalid_client";var pe=class extends ie{};pe.errorCode="invalid_grant";var he=class extends ie{};he.errorCode="unauthorized_client";var tn={[Q.errorCode]:Q,[de.errorCode]:de,[pe.errorCode]:pe,[he.errorCode]:he};function rn(e){const r=typeof e=="string"?new URL(e):new URL(e.href);return r.hash="",r}function nn({requestedResource:e,configuredResource:r}){const n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof r=="string"?new URL(r):new URL(r.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;const s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return s.startsWith(a)}var me=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function ge(e){var r;const n=(r=e.headers.get("www-authenticate"))!=null?r:e.headers.get("WWW-Authenticate");if(!n)return;const[o,s]=n.split(" ");if(o.toLowerCase()!=="bearer"||!s)return;const a=/resource_metadata="([^"]*)"/,i=n.match(a);if(i)try{return new URL(i[1])}catch{return}}function on(e,r="",n={}){return r.endsWith("/")&&(r=r.slice(0,-1)),n.prependPathname?`${r}/.well-known/${e}`:`/.well-known/${e}${r}`}async function $e(e,r,n=fetch){try{return await n(e,{headers:r})}catch(o){if(o instanceof TypeError)return r?$e(e,void 0,n):void 0;throw o}}async function Fe(e,r,n=fetch){return await $e(e,{"MCP-Protocol-Version":r},n)}function sn(e,r){return!e||e.status>=400&&e.status<500&&r!=="/"}async function an(e,r,n,o){var s,a;const i=new URL(e),c=(s=o?.protocolVersion)!=null?s:ee;let l;if(o?.metadataUrl)l=new URL(o.metadataUrl);else{const p=on(r,i.pathname);l=new URL(p,(a=o?.metadataServerUrl)!=null?a:i),l.search=i.search}let u=await Fe(l,c,n);if(!o?.metadataUrl&&sn(u,i.pathname)){const p=new URL(`/.well-known/${r}`,i);u=await Fe(p,c,n)}return u}async function ln(e,r,n=fetch){const o=await an(e,"oauth-protected-resource",n,{protocolVersion:r?.protocolVersion,metadataUrl:r?.resourceMetadataUrl});if(!o||o.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Gr.parse(await o.json())}function cn(e){const r=typeof e=="string"?new URL(e):e,n=r.pathname!=="/",o=[];if(!n)return o.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",r.origin),type:"oidc"}),o;let s=r.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,r.origin),type:"oauth"}),o.push({url:new URL("/.well-known/oauth-authorization-server",r.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${s}`,r.origin),type:"oidc"}),o.push({url:new URL(`${s}/.well-known/openid-configuration`,r.origin),type:"oidc"}),o}async function un(e,{fetchFn:r=fetch,protocolVersion:n=ee}={}){var o;const s={"MCP-Protocol-Version":n},a=cn(e);for(const{url:i,type:c}of a){const l=await $e(i,s,r);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}if(c==="oauth")return gt.parse(await l.json());{const u=Fr.parse(await l.json());if(!((o=u.code_challenge_methods_supported)!=null&&o.includes("S256")))throw new Error(`Incompatible OIDC provider at ${i}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function dn(e,{metadata:r,clientInformation:n,redirectUrl:o,scope:s,state:a,resource:i}){const c="code",l="S256";let u;if(r){if(u=new URL(r.authorization_endpoint),!r.response_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support response type ${c}`);if(!r.code_challenge_methods_supported||!r.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else u=new URL("/authorize",e);const p=await br(),g=p.code_verifier,m=p.code_challenge;return u.searchParams.set("response_type",c),u.searchParams.set("client_id",n.client_id),u.searchParams.set("code_challenge",m),u.searchParams.set("code_challenge_method",l),u.searchParams.set("redirect_uri",String(o)),a&&u.searchParams.set("state",a),s&&u.searchParams.set("scope",s),s?.includes("offline_access")&&u.searchParams.append("prompt","consent"),i&&u.searchParams.set("resource",i.href),{authorizationUrl:u,codeVerifier:g}}function _t(e,r){const n=e.client_secret!==void 0;return r.length===0?n?"client_secret_post":"none":n&&r.includes("client_secret_basic")?"client_secret_basic":n&&r.includes("client_secret_post")?"client_secret_post":r.includes("none")?"none":n?"client_secret_post":"none"}function vt(e,r,n,o){const{client_id:s,client_secret:a}=r;switch(e){case"client_secret_basic":pn(s,a,n);return;case"client_secret_post":hn(s,a,o);return;case"none":mn(s,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function pn(e,r,n){if(!r)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${r}`);n.set("Authorization",`Basic ${o}`)}function hn(e,r,n){n.set("client_id",e),r&&n.set("client_secret",r)}function mn(e,r){r.set("client_id",e)}async function Me(e){const r=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const o=Xr.parse(JSON.parse(n)),{error:s,error_description:a,error_uri:i}=o,c=tn[s]||Q;return new c({message:a||"",cause:i})}catch(o){const s=`${r?`HTTP ${r}: `:""}Invalid OAuth error response: ${o}. Raw body: ${n}`;return new Q({message:s})}}async function gn(e,{metadata:r,clientInformation:n,authorizationCode:o,codeVerifier:s,redirectUri:a,resource:i,addClientAuthentication:c,fetchFn:l}){var u;const p="authorization_code",g=r?.token_endpoint?new URL(r.token_endpoint):new URL("/token",e);if(r?.grant_types_supported&&!r.grant_types_supported.includes(p))throw new Error(`Incompatible auth server: does not support grant type ${p}`);const m=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),_=new URLSearchParams({grant_type:p,code:o,code_verifier:s,redirect_uri:String(a)});if(c)c(m,_,e,r);else{const d=(u=r?.token_endpoint_auth_methods_supported)!=null?u:[],v=_t(n,d);vt(v,n,m,_)}i&&_.set("resource",i.href);const h=await(l??fetch)(g,{method:"POST",headers:m,body:_});if(!h.ok)throw await Me(h);return mt.parse(await h.json())}async function fn(e,{metadata:r,clientInformation:n,refreshToken:o,resource:s,addClientAuthentication:a,fetchFn:i}){var c;const l="refresh_token";let u;if(r){if(u=new URL(r.token_endpoint),r.grant_types_supported&&!r.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else u=new URL("/token",e);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),g=new URLSearchParams({grant_type:l,refresh_token:o});if(a)a(p,g,e,r);else{const _=(c=r?.token_endpoint_auth_methods_supported)!=null?c:[],h=_t(n,_);vt(h,n,p,g)}s&&g.set("resource",s.href);const m=await(i??fetch)(u,{method:"POST",headers:p,body:g});if(!m.ok)throw await Me(m);return mt.parse({refresh_token:o,...await m.json()})}async function _n(e,{metadata:r,clientMetadata:n,fetchFn:o}){let s;if(r){if(!r.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(r.registration_endpoint)}else s=new URL("/register",e);const a=await(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok)throw await Me(a);return Yr.parse(await a.json())}async function fe(e,r){var n,o;try{return await Te(e,r)}catch(s){if(s instanceof de||s instanceof he)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"all")),await Te(e,r);if(s instanceof pe)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"tokens")),await Te(e,r);throw s}}async function vn(e,r,n){const o=rn(e);if(r.validateResourceURL)return await r.validateResourceURL(o,n?.resource);if(n){if(!nn({requestedResource:o,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${o} (or origin)`);return new URL(n.resource)}}async function Te(e,{serverUrl:r,authorizationCode:n,scope:o,resourceMetadataUrl:s,fetchFn:a}){let i,c;try{i=await ln(r,{resourceMetadataUrl:s},a),i.authorization_servers&&i.authorization_servers.length>0&&(c=i.authorization_servers[0])}catch{}c||(c=r);const l=await vn(r,e,i),u=await un(c,{fetchFn:a});let p=await Promise.resolve(e.clientInformation());if(!p){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const d=await _n(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(d),p=d}if(n!==void 0){const d=await e.codeVerifier(),v=await gn(c,{metadata:u,clientInformation:p,authorizationCode:n,codeVerifier:d,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(v),"AUTHORIZED"}const g=await e.tokens();if(g?.refresh_token)try{const d=await fn(c,{metadata:u,clientInformation:p,refreshToken:g.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(d),"AUTHORIZED"}catch(d){if(!(!(d instanceof ie)||d instanceof Q))throw d}const m=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:h}=await dn(c,{metadata:u,clientInformation:p,state:m,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(_),"REDIRECT"}var yn=class{constructor({url:e,headers:r,authProvider:n}){this.connected=!1,this.url=new URL(e),this.headers=r,this.authProvider=n}async commonHeaders(e){const r={...this.headers,...e,"mcp-protocol-version":ee};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return nt(r,`ai-sdk/${ht}`,rt())}async start(){return new Promise((e,r)=>{if(this.connected)return e();this.abortController=new AbortController;const n=async(o=!1)=>{var s,a,i,c,l;try{const u=await this.commonHeaders({Accept:"text/event-stream"}),p=await fetch(this.url.href,{headers:u,signal:(s=this.abortController)==null?void 0:s.signal});if(p.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=ge(p);try{if(await fe(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new me;return(a=this.onerror)==null||a.call(this,d),r(d)}}catch(h){return(i=this.onerror)==null||i.call(this,h),r(h)}return n(!0)}if(!p.ok||!p.body){let h=`MCP SSE Transport Error: ${p.status} ${p.statusText}`;p.status===405&&(h+=". This server does not support SSE transport. Try using `http` transport instead");const d=new R({message:h});return(c=this.onerror)==null||c.call(this,d),r(d)}const m=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).getReader(),_=async()=>{var h,d,v;try{for(;;){const{done:y,value:k}=await m.read();if(y){if(this.connected)throw this.connected=!1,new R({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:b,data:w}=k;if(b==="endpoint"){if(this.endpoint=new URL(w,this.url),this.endpoint.origin!==this.url.origin)throw new R({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(b==="message")try{const O=re.parse(JSON.parse(w));(h=this.onmessage)==null||h.call(this,O)}catch(O){const I=new R({message:"MCP SSE Transport Error: Failed to parse message",cause:O});(d=this.onerror)==null||d.call(this,I)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(v=this.onerror)==null||v.call(this,y),r(y)}};this.sseConnection={close:()=>m.cancel()},_()}catch(u){if(u instanceof Error&&u.name==="AbortError")return;(l=this.onerror)==null||l.call(this,u),r(u)}};n()})}async close(){var e,r,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(r=this.abortController)==null||r.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new R({message:"MCP SSE Transport Error: Not connected"});const r=this.endpoint,n=async(o=!1)=>{var s,a,i,c,l;try{const p={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(s=this.abortController)==null?void 0:s.signal},g=await fetch(r,p);if(g.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=ge(g);try{if(await fe(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const _=new me;(a=this.onerror)==null||a.call(this,_);return}}catch(m){(i=this.onerror)==null||i.call(this,m);return}return n(!0)}if(!g.ok){const m=await g.text().catch(()=>null),_=new R({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${g.status}): ${m}`});(c=this.onerror)==null||c.call(this,_);return}}catch(u){(l=this.onerror)==null||l.call(this,u);return}};await n()}},bn=class{constructor({url:e,headers:r,authProvider:n}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=r,this.authProvider=n}async commonHeaders(e){const r={...this.headers,...e,"mcp-protocol-version":ee};if(this.sessionId&&(r["mcp-session-id"]=this.sessionId),this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return nt(r,`ai-sdk/${ht}`,rt())}async start(){if(this.abortController)throw new R({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,r,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const o=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:o,signal:this.abortController.signal}).catch(()=>{})}}catch{}(r=this.abortController)==null||r.abort(),(n=this.onclose)==null||n.call(this)}async send(e){const r=async(n=!1)=>{var o,s,a,i,c,l,u;try{const g={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},m=await fetch(this.url,g),_=m.headers.get("mcp-session-id");if(_&&(this.sessionId=_),m.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ge(m);try{if(await fe(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new me}catch(v){throw(s=this.onerror)==null||s.call(this,v),v}return r(!0)}if(m.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!m.ok){const v=await m.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${m.status}): ${v}`;m.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const k=new R({message:y});throw(a=this.onerror)==null||a.call(this,k),k}const h=m.headers.get("content-type")||"";if(h.includes("application/json")){const v=await m.json(),y=Array.isArray(v)?v.map(k=>re.parse(k)):[re.parse(v)];for(const k of y)(i=this.onmessage)==null||i.call(this,k);return}if(h.includes("text/event-stream")){if(!m.body){const b=new R({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(c=this.onerror)==null||c.call(this,b),b}const y=m.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).getReader();(async()=>{var b,w,O;try{for(;;){const{done:I,value:C}=await y.read();if(I)return;const{event:T,data:H}=C;if(T==="message")try{const D=re.parse(JSON.parse(H));(b=this.onmessage)==null||b.call(this,D)}catch(D){const L=new R({message:"MCP HTTP Transport Error: Failed to parse message",cause:D});(w=this.onerror)==null||w.call(this,L)}}}catch(I){if(I instanceof Error&&I.name==="AbortError")return;(O=this.onerror)==null||O.call(this,I)}})();return}const d=new R({message:`MCP HTTP Transport Error: Unexpected content type: ${h}`});throw(l=this.onerror)==null||l.call(this,d),d}catch(p){throw(u=this.onerror)==null||u.call(this,p),p}};await r()}getNextReconnectionDelay(e){const{initialReconnectionDelay:r,reconnectionDelayGrowFactor:n,maxReconnectionDelay:o}=this.reconnectionOptions;return Math.min(r*Math.pow(n,e),o)}scheduleInboundSseReconnection(){var e;const{maxRetries:r}=this.reconnectionOptions;if(r>0&&this.inboundReconnectAttempts>=r){(e=this.onerror)==null||e.call(this,new R({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${r}) exceeded.`}));return}const n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var o;(o=this.abortController)!=null&&o.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,r){var n,o,s,a,i,c;try{const l=await this.commonHeaders({Accept:"text/event-stream"});r&&(l["last-event-id"]=r);const u=await fetch(this.url.href,{method:"GET",headers:l,signal:(n=this.abortController)==null?void 0:n.signal}),p=u.headers.get("mcp-session-id");if(p&&(this.sessionId=p),u.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=ge(u);try{if(await fe(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new me;(o=this.onerror)==null||o.call(this,d);return}}catch(h){(s=this.onerror)==null||s.call(this,h);return}return this.openInboundSse(!0,r)}if(u.status===405)return;if(!u.ok||!u.body){const h=new R({message:`MCP HTTP Transport Error: GET SSE failed: ${u.status} ${u.statusText}`});(a=this.onerror)==null||a.call(this,h);return}const m=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).getReader(),_=async()=>{var h,d,v,y;try{for(;;){const{done:k,value:b}=await m.read();if(k)return;const{event:w,data:O,id:I}=b;if(I&&(this.lastInboundEventId=I),w==="message")try{const C=re.parse(JSON.parse(O));(h=this.onmessage)==null||h.call(this,C)}catch(C){const T=new R({message:"MCP HTTP Transport Error: Failed to parse message",cause:C});(d=this.onerror)==null||d.call(this,T)}}}catch(k){if(k instanceof Error&&k.name==="AbortError")return;(v=this.onerror)==null||v.call(this,k),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>m.cancel()},this.inboundReconnectAttempts=0,_()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(i=this.onerror)==null||i.call(this,l),(c=this.abortController)!=null&&c.signal.aborted||this.scheduleInboundSseReconnection()}}};function wn(e){switch(e.type){case"sse":return new yn(e);case"http":return new bn(e);default:throw new R({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function kn(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var Sn="1.0.0";async function Tn(e){const r=new Rn(e);return await r.init(),r}var Rn=class{constructor({transport:e,name:r="ai-sdk-mcp-client",version:n=Sn,onUncaughtError:o,capabilities:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=o,this.clientCapabilities=s??{},kn(e)?this.transport=e:this.transport=wn(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=a=>this.onError(a),this.transport.onmessage=a=>{if("method"in a){"id"in a?this.onRequestMessage(a):this.onError(new R({message:"Unsupported message type"}));return}this.onResponse(a)},this.clientInfo={name:r,version:n}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:ee,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Er});if(e===void 0)throw new R({message:"Server sent invalid initialize result"});if(!Sr.includes(e.protocolVersion))throw new R({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new R({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new R({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new R({message:"Server does not support prompts"});break;default:throw new R({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:r,options:n}){return new Promise((o,s)=>{if(this.isClosed)return s(new R({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const a=n?.signal;a?.throwIfAborted();const i=this.requestMessageId++,c={...e,jsonrpc:"2.0",id:i},l=()=>{this.responseHandlers.delete(i)};this.responseHandlers.set(i,u=>{if(a?.aborted)return s(new R({message:"Request was aborted",cause:a.reason}));if(u instanceof Error)return s(u);try{const p=r.parse(u.result);o(p)}catch(p){const g=new R({message:"Failed to parse server response",cause:p});s(g)}}),this.transport.send(c).catch(u=>{l(),s(u)})})}async listTools({params:e,options:r}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:Ir,options:r})}catch(n){throw n}}async callTool({name:e,args:r,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:r}},resultSchema:jr,options:{signal:n?.abortSignal}})}catch(o){throw o}}async listResourcesInternal({params:e,options:r}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:Or,options:r})}catch(n){throw n}}async readResourceInternal({uri:e,options:r}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:Ur,options:r})}catch(n){throw n}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:Ar,options:e})}catch(r){throw r}}async listPromptsInternal({params:e,options:r}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:Nr,options:r})}catch(n){throw n}}async getPromptInternal({name:e,args:r,options:n}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:r}},resultSchema:Hr,options:n})}catch(o){throw o}}async notification(e){const r={...e,jsonrpc:"2.0"};await this.transport.send(r)}async tools({schemas:e="automatic"}={}){var r;const n={};try{const o=await this.listTools();for(const{name:s,description:a,inputSchema:i}of o.tools){if(e!=="automatic"&&!(s in e))continue;const c=this,l=async(p,g)=>{var m;return(m=g?.abortSignal)==null||m.throwIfAborted(),c.callTool({name:s,args:p,options:g})},u=e==="automatic"?hr({description:a,inputSchema:gr({...i,properties:(r=i.properties)!=null?r:{},additionalProperties:!1}),execute:l}):{description:a,inputSchema:e[s].inputSchema,execute:l};n[s]=u}return n}catch(o){throw o}}listResources({params:e,options:r}={}){return this.listResourcesInternal({params:e,options:r})}readResource({uri:e,options:r}){return this.readResourceInternal({uri:e,options:r})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}listPrompts({params:e,options:r}={}){return this.listPromptsInternal({params:e,options:r})}getPrompt({name:e,arguments:r,options:n}){return this.getPromptInternal({name:e,args:r,options:n})}onElicitationRequest(e,r){if(e!==ze)throw new R({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=r}async onRequestMessage(e){try{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}const r=ze.safeParse({method:e.method,params:e.params});if(!r.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${r.error.message}`,data:r.error.issues}});return}try{const n=await this.elicitationRequestHandler(r.data),o=qr.parse(n);await this.transport.send({jsonrpc:"2.0",id:e.id,result:o})}catch(n){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:n instanceof Error?n.message:"Failed to handle elicitation request"}}),this.onError(n)}}catch(r){this.onError(r)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new R({message:"Connection closed"});for(const r of this.responseHandlers.values())r(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const r=Number(e.id),n=this.responseHandlers.get(r);if(n===void 0)throw new R({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(r),n("result"in e?e:new R({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},En=Object.defineProperty,Cn=Object.defineProperties,In=Object.getOwnPropertyDescriptors,Ke=Object.getOwnPropertySymbols,xn=Object.prototype.hasOwnProperty,On=Object.prototype.propertyIsEnumerable,Ze=(e,r,n)=>r in e?En(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n,E=(e,r)=>{for(var n in r||(r={}))xn.call(r,n)&&Ze(e,n,r[n]);if(Ke)for(var n of Ke(r))On.call(r,n)&&Ze(e,n,r[n]);return e},_e=(e,r)=>Cn(e,In(r)),yt="vercel.ai.error",jn=Symbol.for(yt),bt,Pn=class wt extends Error{constructor({name:r,message:n,cause:o}){super(n),this[bt]=!0,this.name=r,this.cause=o}static isInstance(r){return wt.hasMarker(r,yt)}static hasMarker(r,n){const o=Symbol.for(n);return r!=null&&typeof r=="object"&&o in r&&typeof r[o]=="boolean"&&r[o]===!0}};bt=jn;var U=Pn,kt="AI_APICallError",St=`vercel.ai.error.${kt}`,An=Symbol.for(St),Tt,V=class extends U{constructor({message:e,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:a,cause:i,isRetryable:c=o!=null&&(o===408||o===409||o===429||o>=500),data:l}){super({name:kt,message:e,cause:i}),this[Tt]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=c,this.data=l}static isInstance(e){return U.hasMarker(e,St)}};Tt=An;var Rt="AI_EmptyResponseBodyError",Et=`vercel.ai.error.${Rt}`,Un=Symbol.for(Et),Ct,$n=class extends U{constructor({message:e="Empty response body"}={}){super({name:Rt,message:e}),this[Ct]=!0}static isInstance(e){return U.hasMarker(e,Et)}};Ct=Un;function It(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var xt="AI_InvalidArgumentError",Ot=`vercel.ai.error.${xt}`,Mn=Symbol.for(Ot),jt,Pt=class extends U{constructor({message:e,cause:r,argument:n}){super({name:xt,message:e,cause:r}),this[jt]=!0,this.argument=n}static isInstance(e){return U.hasMarker(e,Ot)}};jt=Mn;var At="AI_InvalidPromptError",Ut=`vercel.ai.error.${At}`,Nn=Symbol.for(Ut),$t,Dn=class extends U{constructor({prompt:e,message:r,cause:n}){super({name:At,message:`Invalid prompt: ${r}`,cause:n}),this[$t]=!0,this.prompt=e}static isInstance(e){return U.hasMarker(e,Ut)}};$t=Nn;var Mt="AI_InvalidResponseDataError",Nt=`vercel.ai.error.${Mt}`,Hn=Symbol.for(Nt),Dt,te=class extends U{constructor({data:e,message:r=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Mt,message:r}),this[Dt]=!0,this.data=e}static isInstance(e){return U.hasMarker(e,Nt)}};Dt=Hn;var Ht="AI_JSONParseError",Lt=`vercel.ai.error.${Ht}`,Ln=Symbol.for(Lt),qt,ve=class extends U{constructor({text:e,cause:r}){super({name:Ht,message:`JSON parsing failed: Text: ${e}.
|
|
2
|
+
Error message: ${It(r)}`,cause:r}),this[qt]=!0,this.text=e}static isInstance(e){return U.hasMarker(e,Lt)}};qt=Ln;var Vt="AI_LoadAPIKeyError",Bt=`vercel.ai.error.${Vt}`,qn=Symbol.for(Bt),Jt,ce=class extends U{constructor({message:e}){super({name:Vt,message:e}),this[Jt]=!0}static isInstance(e){return U.hasMarker(e,Bt)}};Jt=qn;var zt="AI_NoContentGeneratedError",Gt=`vercel.ai.error.${zt}`,Vn=Symbol.for(Gt),Wt,Ft=class extends U{constructor({message:e="No content generated."}={}){super({name:zt,message:e}),this[Wt]=!0}static isInstance(e){return U.hasMarker(e,Gt)}};Wt=Vn;var Kt="AI_TypeValidationError",Zt=`vercel.ai.error.${Kt}`,Bn=Symbol.for(Zt),Xt,Jn=class Ie extends U{constructor({value:r,cause:n}){super({name:Kt,message:`Type validation failed: Value: ${JSON.stringify(r)}.
|
|
3
|
+
Error message: ${It(n)}`,cause:n}),this[Xt]=!0,this.value=r}static isInstance(r){return U.hasMarker(r,Zt)}static wrap({value:r,cause:n}){return Ie.isInstance(n)&&n.value===r?n:new Ie({value:r,cause:n})}};Xt=Bn;var ne=Jn,Yt="AI_UnsupportedFunctionalityError",Qt=`vercel.ai.error.${Yt}`,zn=Symbol.for(Qt),er,W=class extends U{constructor({functionality:e,message:r=`'${e}' functionality not supported.`}){super({name:Yt,message:r}),this[er]=!0,this.functionality=e}static isInstance(e){return U.hasMarker(e,Qt)}};er=zn;var Xe=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function Re(e){}function Gn(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:r=Re,onError:n=Re,onRetry:o=Re,onComment:s}=e;let a="",i=!0,c,l="",u="";function p(d){const v=i?d.replace(/^\xEF\xBB\xBF/,""):d,[y,k]=Wn(`${a}${v}`);for(const b of y)g(b);a=k,i=!1}function g(d){if(d===""){_();return}if(d.startsWith(":")){s&&s(d.slice(d.startsWith(": ")?2:1));return}const v=d.indexOf(":");if(v!==-1){const y=d.slice(0,v),k=d[v+1]===" "?2:1,b=d.slice(v+k);m(y,b,d);return}m(d,"",d)}function m(d,v,y){switch(d){case"event":u=v;break;case"data":l=`${l}${v}
|
|
4
|
+
`;break;case"id":c=v.includes("\0")?void 0:v;break;case"retry":/^\d+$/.test(v)?o(parseInt(v,10)):n(new Xe(`Invalid \`retry\` value: "${v}"`,{type:"invalid-retry",value:v,line:y}));break;default:n(new Xe(`Unknown field "${d.length>20?`${d.slice(0,20)}…`:d}"`,{type:"unknown-field",field:d,value:v,line:y}));break}}function _(){l.length>0&&r({id:c,event:u||void 0,data:l.endsWith(`
|
|
5
|
+
`)?l.slice(0,-1):l}),c=void 0,l="",u=""}function h(d={}){a&&d.consume&&g(a),i=!0,c=void 0,l="",u="",a=""}return{feed:p,reset:h}}function Wn(e){const r=[];let n="",o=0;for(;o<e.length;){const s=e.indexOf("\r",o),a=e.indexOf(`
|
|
6
|
+
`,o);let i=-1;if(s!==-1&&a!==-1?i=Math.min(s,a):s!==-1?i=s:a!==-1&&(i=a),i===-1){n=e.slice(o);break}else{const c=e.slice(o,i);r.push(c),o=i+1,e[o-1]==="\r"&&e[o]===`
|
|
7
|
+
`&&o++}}return[r,n]}var Fn=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(s){o=Gn({onEvent:a=>{s.enqueue(a)},onError(a){e==="terminate"?s.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function oe(...e){return e.reduce((r,n)=>E(E({},r),n??{}),{})}function ke(e){return Object.fromEntries([...e.headers])}var Kn=({prefix:e,size:r=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const s=()=>{const a=n.length,i=new Array(r);for(let c=0;c<r;c++)i[c]=n[Math.random()*a|0];return i.join("")};if(e==null)return s;if(n.includes(o))throw new Pt({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${e}${o}${s()}`},q=Kn();function xe(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Zn=["fetch failed","failed to fetch"];function Xn({error:e,url:r,requestBodyValues:n}){if(xe(e))return e;if(e instanceof TypeError&&Zn.includes(e.message.toLowerCase())){const o=e.cause;if(o!=null)return new V({message:`Cannot connect to API: ${o.message}`,cause:o,url:r,requestBodyValues:n,isRetryable:!0})}return e}function Yn(e){return Object.fromEntries(Object.entries(e).filter(([r,n])=>n!=null))}function Qn({apiKey:e,environmentVariableName:r,apiKeyParameterName:n="apiKey",description:o}){if(typeof e=="string")return e;if(e!=null)throw new ce({message:`${o} API key must be a string.`});if(typeof process>"u")throw new ce({message:`${o} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[r],e==null)throw new ce({message:`${o} API key is missing. Pass it using the '${n}' parameter or the ${r} environment variable.`});if(typeof e!="string")throw new ce({message:`${o} API key must be a string. The value of the ${r} environment variable is not a string.`});return e}var eo=/"__proto__"\s*:/,to=/"constructor"\s*:/;function ro(e){const r=JSON.parse(e);return r===null||typeof r!="object"||eo.test(e)===!1&&to.test(e)===!1?r:no(r)}function no(e){let r=[e];for(;r.length;){const n=r;r=[];for(const o of n){if(Object.prototype.hasOwnProperty.call(o,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(o,"constructor")&&Object.prototype.hasOwnProperty.call(o.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const s in o){const a=o[s];a&&typeof a=="object"&&r.push(a)}}}return e}function Ne(e){const{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return ro(e)}finally{Error.stackTraceLimit=r}}var Oe=Symbol.for("vercel.ai.validator");function oo(e){return{[Oe]:!0,validate:e}}function so(e){return typeof e=="object"&&e!==null&&Oe in e&&e[Oe]===!0&&"validate"in e}function ao(e){return so(e)?e:io(e)}function io(e){return oo(async r=>{const n=await e["~standard"].validate(r);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new ne({value:r,cause:n.issues})}})}async function lo({value:e,schema:r}){const n=await tr({value:e,schema:r});if(!n.success)throw ne.wrap({value:e,cause:n.error});return n.value}async function tr({value:e,schema:r}){const n=ao(r);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:ne.wrap({value:e,cause:o.error}),rawValue:e}}catch(o){return{success:!1,error:ne.wrap({value:e,cause:o}),rawValue:e}}}async function co({text:e,schema:r}){try{const n=Ne(e);return r==null?n:lo({value:n,schema:r})}catch(n){throw ve.isInstance(n)||ne.isInstance(n)?n:new ve({text:e,cause:n})}}async function rr({text:e,schema:r}){try{const n=Ne(e);return r==null?{success:!0,value:n,rawValue:n}:await tr({value:n,schema:r})}catch(n){return{success:!1,error:ve.isInstance(n)?n:new ve({text:e,cause:n}),rawValue:void 0}}}function Ee(e){try{return Ne(e),!0}catch{return!1}}function uo({stream:e,schema:r}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Fn).pipeThrough(new TransformStream({async transform({data:n},o){n!=="[DONE]"&&o.enqueue(await rr({text:n,schema:r}))}}))}var po=()=>globalThis.fetch,se=async({url:e,headers:r,body:n,failedResponseHandler:o,successfulResponseHandler:s,abortSignal:a,fetch:i})=>ho({url:e,headers:E({"Content-Type":"application/json"},r),body:{content:JSON.stringify(n),values:n},failedResponseHandler:o,successfulResponseHandler:s,abortSignal:a,fetch:i}),ho=async({url:e,headers:r={},body:n,successfulResponseHandler:o,failedResponseHandler:s,abortSignal:a,fetch:i=po()})=>{try{const c=await i(e,{method:"POST",headers:Yn(r),body:n.content,signal:a}),l=ke(c);if(!c.ok){let u;try{u=await s({response:c,url:e,requestBodyValues:n.values})}catch(p){throw xe(p)||V.isInstance(p)?p:new V({message:"Failed to process error response",cause:p,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw u.value}try{return await o({response:c,url:e,requestBodyValues:n.values})}catch(u){throw u instanceof Error&&(xe(u)||V.isInstance(u))?u:new V({message:"Failed to process successful response",cause:u,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(c){throw Xn({error:c,url:e,requestBodyValues:n.values})}},mo=({errorSchema:e,errorToMessage:r,isRetryable:n})=>async({response:o,url:s,requestBodyValues:a})=>{const i=await o.text(),c=ke(o);if(i.trim()==="")return{responseHeaders:c,value:new V({message:o.statusText,url:s,requestBodyValues:a,statusCode:o.status,responseHeaders:c,responseBody:i,isRetryable:n?.(o)})};try{const l=await co({text:i,schema:e});return{responseHeaders:c,value:new V({message:r(l),url:s,requestBodyValues:a,statusCode:o.status,responseHeaders:c,responseBody:i,data:l,isRetryable:n?.(o,l)})}}catch{return{responseHeaders:c,value:new V({message:o.statusText,url:s,requestBodyValues:a,statusCode:o.status,responseHeaders:c,responseBody:i,isRetryable:n?.(o)})}}},nr=e=>async({response:r})=>{const n=ke(r);if(r.body==null)throw new $n({});return{responseHeaders:n,value:uo({stream:r.body,schema:e})}},De=e=>async({response:r,url:n,requestBodyValues:o})=>{const s=await r.text(),a=await rr({text:s,schema:e}),i=ke(r);if(!a.success)throw new V({message:"Invalid JSON response",cause:a.error,statusCode:r.status,responseHeaders:i,responseBody:s,url:n,requestBodyValues:o});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}},{btoa:go}=globalThis;function fo(e){let r="";for(let n=0;n<e.length;n++)r+=String.fromCodePoint(e[n]);return go(r)}function _o(e){return e?.replace(/\/$/,"")}function Ce(e){return e!=null}var or=(e=>(e.Unknown="unknown",e.OpenAIResponsesV1="openai-responses-v1",e.XAIResponsesV1="xai-responses-v1",e.AnthropicClaudeV1="anthropic-claude-v1",e.GoogleGeminiV1="google-gemini-v1",e))(or||{}),He=t.object({id:t.string().nullish(),format:t._enum$1(or).nullish(),index:t.number().optional()}).loose(),vo=t.object({type:t.literal("reasoning.summary"),summary:t.string()}).extend(He.shape),yo=t.object({type:t.literal("reasoning.encrypted"),data:t.string()}).extend(He.shape),bo=t.object({type:t.literal("reasoning.text"),text:t.string().nullish(),signature:t.string().nullish()}).extend(He.shape),Le=t.union([vo,yo,bo]),ue=t.union([Le,t.unknown().transform(()=>null)]),qe=t.array(ue).transform(e=>e.filter(r=>!!r));t.union([t.object({delta:t.object({reasoning_details:t.array(ue)})}).transform(e=>e.delta.reasoning_details.filter(Ce)),t.object({message:t.object({reasoning_details:t.array(ue)})}).transform(e=>e.message.reasoning_details.filter(Ce)),t.object({text:t.string(),reasoning_details:t.array(ue)}).transform(e=>e.reasoning_details.filter(Ce))]);var Se=t.object({error:t.object({code:t.union([t.string(),t.number()]).nullable().optional().default(null),message:t.string(),type:t.string().nullable().optional().default(null),param:t.any().nullable().optional().default(null)}).passthrough()}).passthrough(),ae=mo({errorSchema:Se,errorToMessage:e=>e.error.message}),sr=t.object({type:t.literal("file"),file:t.object({hash:t.string(),name:t.string(),content:t.array(t.object({type:t.string(),text:t.string().optional()}).catchall(t.any())).optional()}).catchall(t.any())}).catchall(t.any()),wo=t.object({provider:t.string(),reasoning_details:t.array(Le).optional(),annotations:t.array(sr).optional(),usage:t.object({promptTokens:t.number(),promptTokensDetails:t.object({cachedTokens:t.number()}).catchall(t.any()).optional(),completionTokens:t.number(),completionTokensDetails:t.object({reasoningTokens:t.number()}).catchall(t.any()).optional(),totalTokens:t.number(),cost:t.number().optional(),costDetails:t.object({upstreamInferenceCost:t.number()}).catchall(t.any()).optional()}).catchall(t.any())}).catchall(t.any()),Ye=t.object({openrouter:t.object({reasoning_details:t.array(Le).optional(),annotations:t.array(sr).optional()}).optional()}).optional();function ye(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var ko=["wav","mp3","aiff","aac","ogg","flac","m4a","pcm16","pcm24"];function Ve({url:e,protocols:r}){try{const n=new URL(e);return r.has(n.protocol)}catch{return!1}}function je({part:e,defaultMediaType:r}){var n,o;if(e.data instanceof Uint8Array){const a=fo(e.data);return`data:${(n=e.mediaType)!=null?n:r};base64,${a}`}const s=e.data.toString();return Ve({url:s,protocols:new Set(["http:","https:"])})||s.startsWith("data:")?s:`data:${(o=e.mediaType)!=null?o:r};base64,${s}`}function Qe(e,r){var n;const o=e.match(/^data:([^;]+)/);return o&&(n=o[1])!=null?n:r}function Pe(e){const r=e.match(/^data:[^;]*;base64,(.+)$/);return r?r[1]:e}var So={mpeg:"mp3",mp3:"mp3","x-wav":"wav",wave:"wav",wav:"wav",ogg:"ogg",vorbis:"ogg",aac:"aac","x-aac":"aac",m4a:"m4a","x-m4a":"m4a",mp4:"m4a",aiff:"aiff","x-aiff":"aiff",flac:"flac","x-flac":"flac",pcm16:"pcm16",pcm24:"pcm24"};function To(e){const r=je({part:e,defaultMediaType:"audio/mpeg"});if(Ve({url:r,protocols:new Set(["http:","https:"])}))throw new Error(`Audio files cannot be provided as URLs.
|
|
8
8
|
|
|
9
9
|
OpenRouter requires audio to be base64-encoded. Please:
|
|
10
10
|
1. Download the audio file locally
|
|
@@ -13,19 +13,17 @@ OpenRouter requires audio to be base64-encoded. Please:
|
|
|
13
13
|
|
|
14
14
|
The AI SDK will automatically handle base64 encoding.
|
|
15
15
|
|
|
16
|
-
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);const n=
|
|
16
|
+
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);const n=Pe(r),o=e.mediaType||"audio/mpeg",s=o.replace("audio/",""),a=So[s];if(a===void 0){const i=ko.join(", ");throw new Error(`Unsupported audio format: "${o}"
|
|
17
17
|
|
|
18
|
-
OpenRouter
|
|
19
|
-
• For MP3: use "audio/mpeg" or "audio/mp3"
|
|
20
|
-
• For WAV: use "audio/wav" or "audio/x-wav"
|
|
18
|
+
OpenRouter supports the following audio formats: ${i}
|
|
21
19
|
|
|
22
|
-
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);return{data:n,format:s}}function W(e){var r,n,o;const s=e?.anthropic,a=e?.openrouter;return(o=(n=(r=a?.cacheControl)!=null?r:a?.cache_control)!=null?n:s?.cacheControl)!=null?o:s?.cache_control}function go(e){var r,n,o,s,a,l,c,i,u,d;const m=[];for(const{role:h,content:f,providerOptions:g}of e)switch(h){case"system":{m.push({role:"system",content:f,cache_control:W(g)});break}case"user":{if(f.length===1&&((r=f[0])==null?void 0:r.type)==="text"){const _=(n=W(g))!=null?n:W(f[0].providerOptions),b=_?[{type:"text",text:f[0].text,cache_control:_}]:f[0].text;m.push({role:"user",content:b});break}const p=W(g),y=f.map(_=>{var b,v,C,S,I,P,U;const q=(b=W(_.providerOptions))!=null?b:p;switch(_.type){case"text":return{type:"text",text:_.text,cache_control:q};case"file":{if((v=_.mediaType)!=null&&v.startsWith("image/"))return{type:"image_url",image_url:{url:Pe({part:_,defaultMediaType:"image/jpeg"})},cache_control:q};if((C=_.mediaType)!=null&&C.startsWith("audio/"))return{type:"input_audio",input_audio:ho(_),cache_control:q};const H=String((U=(P=(I=(S=_.providerOptions)==null?void 0:S.openrouter)==null?void 0:I.filename)!=null?P:_.filename)!=null?U:""),L=Pe({part:_,defaultMediaType:"application/pdf"});return Le({url:L,protocols:new Set(["http:","https:"])})?{type:"file",file:{filename:H,file_data:L}}:{type:"file",file:{filename:H,file_data:L},cache_control:q}}default:return{type:"text",text:"",cache_control:q}}});m.push({role:"user",content:y});break}case"assistant":{let p="",y="";const _=[],b=[];for(const P of f)switch(P.type){case"text":{p+=P.text;break}case"tool-call":{const U=(o=P.providerOptions)==null?void 0:o.openrouter;U?.reasoning_details&&Array.isArray(U.reasoning_details)&&b.push(...U.reasoning_details),_.push({id:P.toolCallId,type:"function",function:{name:P.toolName,arguments:JSON.stringify(P.input)}});break}case"reasoning":{y+=P.text;const U=Xe.safeParse(P.providerOptions);U.success&&((a=(s=U.data)==null?void 0:s.openrouter)!=null&&a.reasoning_details)&&b.push(...U.data.openrouter.reasoning_details);break}}const v=Xe.safeParse(g),C=v.success?(c=(l=v.data)==null?void 0:l.openrouter)==null?void 0:c.reasoning_details:void 0,S=v.success?(u=(i=v.data)==null?void 0:i.openrouter)==null?void 0:u.annotations:void 0,I=C&&Array.isArray(C)&&C.length>0?C:b.length>0?b:void 0;m.push({role:"assistant",content:p,tool_calls:_.length>0?_:void 0,reasoning:y||void 0,reasoning_details:I,annotations:S,cache_control:W(g)});break}case"tool":{for(const p of f){const y=mo(p);m.push({role:"tool",tool_call_id:p.toolCallId,content:y,cache_control:(d=W(g))!=null?d:W(p.providerOptions)})}break}}return m}function mo(e){return e.output.type==="text"?e.output.value:JSON.stringify(e.output.value)}t.union([t.literal("auto"),t.literal("none"),t.literal("required"),t.object({type:t.literal("function"),function:t.object({name:t.string()})})]);function fo(e){switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:e.toolName}};default:throw new It({argument:"toolChoice",message:`Invalid tool choice type: ${JSON.stringify(e)}`})}}var _o=t.object({type:t.literal("image_url"),image_url:t.object({url:t.string()}).passthrough()}).passthrough(),vo=t.union([_o,t.unknown().transform(()=>null)]),nr=t.array(vo).transform(e=>e.filter(r=>!!r)),or=t.object({id:t.string().optional(),model:t.string().optional(),provider:t.string().optional(),usage:t.object({prompt_tokens:t.number(),prompt_tokens_details:t.object({cached_tokens:t.number()}).passthrough().nullish(),completion_tokens:t.number(),completion_tokens_details:t.object({reasoning_tokens:t.number()}).passthrough().nullish(),total_tokens:t.number(),cost:t.number().optional(),cost_details:t.object({upstream_inference_cost:t.number().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),yo=t.union([or.extend({choices:t.array(t.object({message:t.object({role:t.literal("assistant"),content:t.string().nullable().optional(),reasoning:t.string().nullable().optional(),reasoning_details:qe.nullish(),images:nr.nullish(),tool_calls:t.array(t.object({id:t.string().optional().nullable(),type:t.literal("function"),function:t.object({name:t.string(),arguments:t.string()}).passthrough()}).passthrough()).optional(),annotations:t.array(t.union([t.object({type:t.literal("url_citation"),url_citation:t.object({end_index:t.number(),start_index:t.number(),title:t.string(),url:t.string(),content:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file_annotation"),file_annotation:t.object({file_id:t.string(),quote:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file"),file:t.object({hash:t.string(),name:t.string(),content:t.array(t.object({type:t.string(),text:t.string().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough(),index:t.number().nullish(),logprobs:t.object({content:t.array(t.object({token:t.string(),logprob:t.number(),top_logprobs:t.array(t.object({token:t.string(),logprob:t.number()}).passthrough())}).passthrough()).nullable()}).passthrough().nullable().optional(),finish_reason:t.string().optional().nullable()}).passthrough())}),ke.extend({user_id:t.string().optional()})]),bo=t.union([or.extend({choices:t.array(t.object({delta:t.object({role:t._enum$1(["assistant"]).optional(),content:t.string().nullish(),reasoning:t.string().nullish().optional(),reasoning_details:qe.nullish(),images:nr.nullish(),tool_calls:t.array(t.object({index:t.number().nullish(),id:t.string().nullish(),type:t.literal("function").optional(),function:t.object({name:t.string().nullish(),arguments:t.string().nullish()}).passthrough()}).passthrough()).nullish(),annotations:t.array(t.union([t.object({type:t.literal("url_citation"),url_citation:t.object({end_index:t.number(),start_index:t.number(),title:t.string(),url:t.string(),content:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file_annotation"),file_annotation:t.object({file_id:t.string(),quote:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file"),file:t.object({hash:t.string(),name:t.string(),content:t.array(t.object({type:t.string(),text:t.string().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough().nullish(),logprobs:t.object({content:t.array(t.object({token:t.string(),logprob:t.number(),top_logprobs:t.array(t.object({token:t.string(),logprob:t.number()}).passthrough())}).passthrough()).nullable()}).passthrough().nullish(),finish_reason:t.string().nullable().optional(),index:t.number().nullish()}).passthrough())}),ke]),wo=class{constructor(e,r,n){this.specificationVersion="v2",this.provider="openrouter",this.defaultObjectGenerationMode="tool",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.modelId=e,this.settings=r,this.config=n}getArgs({prompt:e,maxOutputTokens:r,temperature:n,topP:o,frequencyPenalty:s,presencePenalty:a,seed:l,stopSequences:c,responseFormat:i,topK:u,tools:d,toolChoice:m}){var h;const f=E(E({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===!0||typeof this.settings.logprobs=="number"?!0:void 0,top_logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:r,temperature:n,top_p:o,frequency_penalty:s,presence_penalty:a,seed:l,stop:c,response_format:i?.type==="json"?i.schema!=null?{type:"json_schema",json_schema:E({schema:i.schema,strict:!0,name:(h=i.name)!=null?h:"response"},i.description&&{description:i.description})}:{type:"json_object"}:void 0,top_k:u,messages:go(e),include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning,usage:this.settings.usage,plugins:this.settings.plugins,web_search_options:this.settings.web_search_options,provider:this.settings.provider,debug:this.settings.debug},this.config.extraBody),this.settings.extraBody);if(d&&d.length>0){const g=d.filter(p=>p.type==="function").map(p=>({type:"function",function:{name:p.name,description:p.description,parameters:p.inputSchema}}));return fe(E({},f),{tools:g,tool_choice:m?fo(m):void 0})}return f}async doGenerate(e){var r,n,o,s,a,l,c,i,u,d,m,h,f,g,p,y,_,b,v,C,S,I,P;const q=(e.providerOptions||{}).openrouter||{},H=E(E({},this.getArgs(e)),q),{value:L,responseHeaders:F}=await ne({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:re(this.config.headers(),e.headers),body:H,failedResponseHandler:oe,successfulResponseHandler:Ne(yo),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in L){const w=L.error;throw new B({message:w.message,url:this.config.url({path:"/chat/completions",modelId:this.modelId}),requestBodyValues:H,statusCode:200,responseHeaders:F,data:w})}const O=L,$=O.choices[0];if(!$)throw new zt({message:"No choice in response"});const K=O.usage?{inputTokens:(r=O.usage.prompt_tokens)!=null?r:0,outputTokens:(n=O.usage.completion_tokens)!=null?n:0,totalTokens:((o=O.usage.prompt_tokens)!=null?o:0)+((s=O.usage.completion_tokens)!=null?s:0),reasoningTokens:(l=(a=O.usage.completion_tokens_details)==null?void 0:a.reasoning_tokens)!=null?l:0,cachedInputTokens:(i=(c=O.usage.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?i:0}:{inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0},Z=(u=$.message.reasoning_details)!=null?u:[],ae=Z.length>0?Z.map(w=>{switch(w.type){case"reasoning.text":{if(w.text)return{type:"reasoning",text:w.text,providerMetadata:{openrouter:{reasoning_details:[w]}}};break}case"reasoning.summary":{if(w.summary)return{type:"reasoning",text:w.summary,providerMetadata:{openrouter:{reasoning_details:[w]}}};break}case"reasoning.encrypted":{if(w.data)return{type:"reasoning",text:"[REDACTED]",providerMetadata:{openrouter:{reasoning_details:[w]}}};break}}return null}).filter(w=>w!==null):$.message.reasoning?[{type:"reasoning",text:$.message.reasoning}]:[],J=[];if(J.push(...ae),$.message.content&&J.push({type:"text",text:$.message.content}),$.message.tool_calls)for(const w of $.message.tool_calls)J.push({type:"tool-call",toolCallId:(d=w.id)!=null?d:V(),toolName:w.function.name,input:w.function.arguments,providerMetadata:{openrouter:{reasoning_details:Z}}});if($.message.images)for(const w of $.message.images)J.push({type:"file",mediaType:Ye(w.image_url.url,"image/jpeg"),data:je(w.image_url.url)});if($.message.annotations)for(const w of $.message.annotations)w.type==="url_citation"&&J.push({type:"source",sourceType:"url",id:w.url_citation.url,url:w.url_citation.url,title:w.url_citation.title,providerMetadata:{openrouter:{content:w.url_citation.content||""}}});const x=(m=$.message.annotations)==null?void 0:m.filter(w=>w.type==="file");return{content:J,finishReason:ve($.finish_reason),usage:K,warnings:[],providerMetadata:{openrouter:po.parse({provider:(h=O.provider)!=null?h:"",reasoning_details:(f=$.message.reasoning_details)!=null?f:[],annotations:x&&x.length>0?x:void 0,usage:E(E(E({promptTokens:(g=K.inputTokens)!=null?g:0,completionTokens:(p=K.outputTokens)!=null?p:0,totalTokens:(y=K.totalTokens)!=null?y:0,cost:(_=O.usage)==null?void 0:_.cost},((v=(b=O.usage)==null?void 0:b.prompt_tokens_details)==null?void 0:v.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:O.usage.prompt_tokens_details.cached_tokens}}:{}),((S=(C=O.usage)==null?void 0:C.completion_tokens_details)==null?void 0:S.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:O.usage.completion_tokens_details.reasoning_tokens}}:{}),((P=(I=O.usage)==null?void 0:I.cost_details)==null?void 0:P.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:O.usage.cost_details.upstream_inference_cost}}:{})})},request:{body:H},response:{id:O.id,modelId:O.model,headers:F}}}async doStream(e){var r;const o=(e.providerOptions||{}).openrouter||{},s=E(E({},this.getArgs(e)),o),{value:a,responseHeaders:l}=await ne({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:re(this.config.headers(),e.headers),body:fe(E({},s),{stream:!0,stream_options:this.config.compatibility==="strict"?E({include_usage:!0},(r=this.settings.usage)!=null&&r.include?{include_usage:!0}:{}):void 0}),failedResponseHandler:oe,successfulResponseHandler:er(bo),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=[];let i="other";const u={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},d={},m=[];let h=!1,f=!1,g,p,y,_;return{stream:a.pipeThrough(new TransformStream({transform(b,v){var C,S,I,P,U,q,H,L,F,O,$,K,Z,ae,J;if(!b.success){i="error",v.enqueue({type:"error",error:b.error});return}const x=b.value;if("error"in x){i="error",v.enqueue({type:"error",error:x.error});return}if(x.provider&&(_=x.provider),x.id&&(y=x.id,v.enqueue({type:"response-metadata",id:x.id})),x.model&&v.enqueue({type:"response-metadata",modelId:x.model}),x.usage!=null){if(u.inputTokens=x.usage.prompt_tokens,u.outputTokens=x.usage.completion_tokens,u.totalTokens=x.usage.prompt_tokens+x.usage.completion_tokens,d.promptTokens=x.usage.prompt_tokens,x.usage.prompt_tokens_details){const T=(C=x.usage.prompt_tokens_details.cached_tokens)!=null?C:0;u.cachedInputTokens=T,d.promptTokensDetails={cachedTokens:T}}if(d.completionTokens=x.usage.completion_tokens,x.usage.completion_tokens_details){const T=(S=x.usage.completion_tokens_details.reasoning_tokens)!=null?S:0;u.reasoningTokens=T,d.completionTokensDetails={reasoningTokens:T}}d.cost=x.usage.cost,d.totalTokens=x.usage.total_tokens;const k=(I=x.usage.cost_details)==null?void 0:I.upstream_inference_cost;k!=null&&(d.costDetails={upstreamInferenceCost:k})}const w=x.choices[0];if(w?.finish_reason!=null&&(i=ve(w.finish_reason)),w?.delta==null)return;const M=w.delta,ie=(k,T)=>{f||(p=y||V(),v.enqueue({providerMetadata:T,type:"reasoning-start",id:p}),f=!0),v.enqueue({providerMetadata:T,type:"reasoning-delta",delta:k,id:p||V()})};if(M.reasoning_details&&M.reasoning_details.length>0){for(const T of M.reasoning_details)if(T.type==="reasoning.text"){const j=m[m.length-1];j?.type==="reasoning.text"?(j.text=(j.text||"")+(T.text||""),j.signature=j.signature||T.signature,j.format=j.format||T.format):m.push(E({},T))}else m.push(T);const k={openrouter:{reasoning_details:M.reasoning_details}};for(const T of M.reasoning_details)switch(T.type){case"reasoning.text":{T.text&&ie(T.text,k);break}case"reasoning.encrypted":{T.data&&ie("[REDACTED]",k);break}case"reasoning.summary":{T.summary&&ie(T.summary,k);break}}}else M.reasoning&&ie(M.reasoning);if(M.content&&(f&&!h&&(v.enqueue({type:"reasoning-end",id:p||V()}),f=!1),h||(g=y||V(),v.enqueue({type:"text-start",id:g}),h=!0),v.enqueue({type:"text-delta",delta:M.content,id:g||V()})),M.annotations)for(const k of M.annotations)k.type==="url_citation"&&v.enqueue({type:"source",sourceType:"url",id:k.url_citation.url,url:k.url_citation.url,title:k.url_citation.title,providerMetadata:{openrouter:{content:k.url_citation.content||""}}});if(M.tool_calls!=null)for(const k of M.tool_calls){const T=(P=k.index)!=null?P:c.length-1;if(c[T]==null){if(k.type!=="function")throw new Q({data:k,message:"Expected 'function' type."});if(k.id==null)throw new Q({data:k,message:"Expected 'id' to be a string."});if(((U=k.function)==null?void 0:U.name)==null)throw new Q({data:k,message:"Expected 'function.name' to be a string."});c[T]={id:k.id,type:"function",function:{name:k.function.name,arguments:(q=k.function.arguments)!=null?q:""},inputStarted:!1,sent:!1};const N=c[T];if(N==null)throw new Q({data:{index:T,toolCallsLength:c.length},message:`Tool call at index ${T} is missing after creation.`});((H=N.function)==null?void 0:H.name)!=null&&((L=N.function)==null?void 0:L.arguments)!=null&&Re(N.function.arguments)&&(N.inputStarted=!0,v.enqueue({type:"tool-input-start",id:N.id,toolName:N.function.name}),v.enqueue({type:"tool-input-delta",id:N.id,delta:N.function.arguments}),v.enqueue({type:"tool-input-end",id:N.id}),v.enqueue({type:"tool-call",toolCallId:N.id,toolName:N.function.name,input:N.function.arguments,providerMetadata:{openrouter:{reasoning_details:m}}}),N.sent=!0);continue}const j=c[T];if(j==null)throw new Q({data:{index:T,toolCallsLength:c.length,toolCallDelta:k},message:`Tool call at index ${T} is missing during merge.`});j.inputStarted||(j.inputStarted=!0,v.enqueue({type:"tool-input-start",id:j.id,toolName:j.function.name})),((F=k.function)==null?void 0:F.arguments)!=null&&(j.function.arguments+=($=(O=k.function)==null?void 0:O.arguments)!=null?$:""),v.enqueue({type:"tool-input-delta",id:j.id,delta:(K=k.function.arguments)!=null?K:""}),((Z=j.function)==null?void 0:Z.name)!=null&&((ae=j.function)==null?void 0:ae.arguments)!=null&&Re(j.function.arguments)&&(v.enqueue({type:"tool-call",toolCallId:(J=j.id)!=null?J:V(),toolName:j.function.name,input:j.function.arguments,providerMetadata:{openrouter:{reasoning_details:m}}}),j.sent=!0)}if(M.images!=null)for(const k of M.images)v.enqueue({type:"file",mediaType:Ye(k.image_url.url,"image/jpeg"),data:je(k.image_url.url)})},flush(b){var v;if(i==="tool-calls")for(const S of c)S&&!S.sent&&(b.enqueue({type:"tool-call",toolCallId:(v=S.id)!=null?v:V(),toolName:S.function.name,input:Re(S.function.arguments)?S.function.arguments:"{}",providerMetadata:{openrouter:{reasoning_details:m}}}),S.sent=!0);f&&b.enqueue({type:"reasoning-end",id:p||V()}),h&&b.enqueue({type:"text-end",id:g||V()});const C={usage:d};_!==void 0&&(C.provider=_),m.length>0&&(C.reasoning_details=m),b.enqueue({type:"finish",finishReason:i,usage:u,providerMetadata:{openrouter:C}})}})),warnings:[],request:{body:s},response:{headers:l}}}};function ko({prompt:e,inputFormat:r,user:n="user",assistant:o="assistant"}){if(e.length===1&&e[0]&&e[0].role==="user"&&e[0].content.length===1&&e[0].content[0]&&e[0].content[0].type==="text")return{prompt:e[0].content[0].text};let s="";e[0]&&e[0].role==="system"&&(s+=`${e[0].content}
|
|
20
|
+
Learn more: https://openrouter.ai/docs/features/multimodal/audio`)}return{data:n,format:a}}function G(e){var r,n,o;const s=e?.anthropic,a=e?.openrouter;return(o=(n=(r=a?.cacheControl)!=null?r:a?.cache_control)!=null?n:s?.cacheControl)!=null?o:s?.cache_control}function Ro(e){var r,n,o,s,a,i,c,l,u,p;const g=[];for(const{role:m,content:_,providerOptions:h}of e)switch(m){case"system":{g.push({role:"system",content:_,cache_control:G(h)});break}case"user":{if(_.length===1&&((r=_[0])==null?void 0:r.type)==="text"){const y=(n=G(h))!=null?n:G(_[0].providerOptions),k=y?[{type:"text",text:_[0].text,cache_control:y}]:_[0].text;g.push({role:"user",content:k});break}const d=G(h),v=_.map(y=>{var k,b,w,O,I,C,T;const H=(k=G(y.providerOptions))!=null?k:d;switch(y.type){case"text":return{type:"text",text:y.text,cache_control:H};case"file":{if((b=y.mediaType)!=null&&b.startsWith("image/"))return{type:"image_url",image_url:{url:je({part:y,defaultMediaType:"image/jpeg"})},cache_control:H};if((w=y.mediaType)!=null&&w.startsWith("audio/"))return{type:"input_audio",input_audio:To(y),cache_control:H};const D=String((T=(C=(I=(O=y.providerOptions)==null?void 0:O.openrouter)==null?void 0:I.filename)!=null?C:y.filename)!=null?T:""),L=je({part:y,defaultMediaType:"application/pdf"});return Ve({url:L,protocols:new Set(["http:","https:"])})?{type:"file",file:{filename:D,file_data:L}}:{type:"file",file:{filename:D,file_data:L},cache_control:H}}default:return{type:"text",text:"",cache_control:H}}});g.push({role:"user",content:v});break}case"assistant":{let d="",v="";const y=[],k=[];for(const C of _)switch(C.type){case"text":{d+=C.text;break}case"tool-call":{const T=(o=C.providerOptions)==null?void 0:o.openrouter;T?.reasoning_details&&Array.isArray(T.reasoning_details)&&k.push(...T.reasoning_details),y.push({id:C.toolCallId,type:"function",function:{name:C.toolName,arguments:JSON.stringify(C.input)}});break}case"reasoning":{v+=C.text;const T=Ye.safeParse(C.providerOptions);T.success&&((a=(s=T.data)==null?void 0:s.openrouter)!=null&&a.reasoning_details)&&k.push(...T.data.openrouter.reasoning_details);break}}const b=Ye.safeParse(h),w=b.success?(c=(i=b.data)==null?void 0:i.openrouter)==null?void 0:c.reasoning_details:void 0,O=b.success?(u=(l=b.data)==null?void 0:l.openrouter)==null?void 0:u.annotations:void 0,I=w&&Array.isArray(w)&&w.length>0?w:k.length>0?k:void 0;g.push({role:"assistant",content:d,tool_calls:y.length>0?y:void 0,reasoning:v||void 0,reasoning_details:I,annotations:O,cache_control:G(h)});break}case"tool":{for(const d of _){const v=Eo(d);g.push({role:"tool",tool_call_id:d.toolCallId,content:v,cache_control:(p=G(h))!=null?p:G(d.providerOptions)})}break}}return g}function Eo(e){return e.output.type==="text"?e.output.value:JSON.stringify(e.output.value)}t.union([t.literal("auto"),t.literal("none"),t.literal("required"),t.object({type:t.literal("function"),function:t.object({name:t.string()})})]);function Co(e){switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:e.toolName}};default:throw new Pt({argument:"toolChoice",message:`Invalid tool choice type: ${JSON.stringify(e)}`})}}var Io=t.object({type:t.literal("image_url"),image_url:t.object({url:t.string()}).passthrough()}).passthrough(),xo=t.union([Io,t.unknown().transform(()=>null)]),ar=t.array(xo).transform(e=>e.filter(r=>!!r)),ir=t.object({id:t.string().optional(),model:t.string().optional(),provider:t.string().optional(),usage:t.object({prompt_tokens:t.number(),prompt_tokens_details:t.object({cached_tokens:t.number()}).passthrough().nullish(),completion_tokens:t.number(),completion_tokens_details:t.object({reasoning_tokens:t.number()}).passthrough().nullish(),total_tokens:t.number(),cost:t.number().optional(),cost_details:t.object({upstream_inference_cost:t.number().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),Oo=t.union([ir.extend({choices:t.array(t.object({message:t.object({role:t.literal("assistant"),content:t.string().nullable().optional(),reasoning:t.string().nullable().optional(),reasoning_details:qe.nullish(),images:ar.nullish(),tool_calls:t.array(t.object({id:t.string().optional().nullable(),type:t.literal("function"),function:t.object({name:t.string(),arguments:t.string()}).passthrough()}).passthrough()).optional(),annotations:t.array(t.union([t.object({type:t.literal("url_citation"),url_citation:t.object({end_index:t.number(),start_index:t.number(),title:t.string(),url:t.string(),content:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file_annotation"),file_annotation:t.object({file_id:t.string(),quote:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file"),file:t.object({hash:t.string(),name:t.string(),content:t.array(t.object({type:t.string(),text:t.string().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough(),index:t.number().nullish(),logprobs:t.object({content:t.array(t.object({token:t.string(),logprob:t.number(),top_logprobs:t.array(t.object({token:t.string(),logprob:t.number()}).passthrough())}).passthrough()).nullable()}).passthrough().nullable().optional(),finish_reason:t.string().optional().nullable()}).passthrough())}),Se.extend({user_id:t.string().optional()})]),jo=t.union([ir.extend({choices:t.array(t.object({delta:t.object({role:t._enum$1(["assistant"]).optional(),content:t.string().nullish(),reasoning:t.string().nullish().optional(),reasoning_details:qe.nullish(),images:ar.nullish(),tool_calls:t.array(t.object({index:t.number().nullish(),id:t.string().nullish(),type:t.literal("function").optional(),function:t.object({name:t.string().nullish(),arguments:t.string().nullish()}).passthrough()}).passthrough()).nullish(),annotations:t.array(t.union([t.object({type:t.literal("url_citation"),url_citation:t.object({end_index:t.number(),start_index:t.number(),title:t.string(),url:t.string(),content:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file_annotation"),file_annotation:t.object({file_id:t.string(),quote:t.string().optional()}).passthrough()}).passthrough(),t.object({type:t.literal("file"),file:t.object({hash:t.string(),name:t.string(),content:t.array(t.object({type:t.string(),text:t.string().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough().nullish(),logprobs:t.object({content:t.array(t.object({token:t.string(),logprob:t.number(),top_logprobs:t.array(t.object({token:t.string(),logprob:t.number()}).passthrough())}).passthrough()).nullable()}).passthrough().nullish(),finish_reason:t.string().nullable().optional(),index:t.number().nullish()}).passthrough())}),Se]),Po=class{constructor(e,r,n){this.specificationVersion="v2",this.provider="openrouter",this.defaultObjectGenerationMode="tool",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.modelId=e,this.settings=r,this.config=n}getArgs({prompt:e,maxOutputTokens:r,temperature:n,topP:o,frequencyPenalty:s,presencePenalty:a,seed:i,stopSequences:c,responseFormat:l,topK:u,tools:p,toolChoice:g}){var m;const _=E(E({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===!0||typeof this.settings.logprobs=="number"?!0:void 0,top_logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:r,temperature:n,top_p:o,frequency_penalty:s,presence_penalty:a,seed:i,stop:c,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:E({schema:l.schema,strict:!0,name:(m=l.name)!=null?m:"response"},l.description&&{description:l.description})}:{type:"json_object"}:void 0,top_k:u,messages:Ro(e),include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning,usage:this.settings.usage,plugins:this.settings.plugins,web_search_options:this.settings.web_search_options,provider:this.settings.provider,debug:this.settings.debug},this.config.extraBody),this.settings.extraBody);if(p&&p.length>0){const h=p.filter(d=>d.type==="function").map(d=>({type:"function",function:{name:d.name,description:d.description,parameters:d.inputSchema}}));return _e(E({},_),{tools:h,tool_choice:g?Co(g):void 0})}return _}async doGenerate(e){var r,n,o,s,a,i,c,l,u,p,g,m,_,h,d,v,y,k,b,w,O,I,C;const H=(e.providerOptions||{}).openrouter||{},D=E(E({},this.getArgs(e)),H),{value:L,responseHeaders:Z}=await se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:oe(this.config.headers(),e.headers),body:D,failedResponseHandler:ae,successfulResponseHandler:De(Oo),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in L){const f=L.error;throw new V({message:f.message,url:this.config.url({path:"/chat/completions",modelId:this.modelId}),requestBodyValues:D,statusCode:200,responseHeaders:Z,data:f})}const P=L,A=P.choices[0];if(!A)throw new Ft({message:"No choice in response"});const F=P.usage?{inputTokens:(r=P.usage.prompt_tokens)!=null?r:0,outputTokens:(n=P.usage.completion_tokens)!=null?n:0,totalTokens:((o=P.usage.prompt_tokens)!=null?o:0)+((s=P.usage.completion_tokens)!=null?s:0),reasoningTokens:(i=(a=P.usage.completion_tokens_details)==null?void 0:a.reasoning_tokens)!=null?i:0,cachedInputTokens:(l=(c=P.usage.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?l:0}:{inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0},K=(u=A.message.reasoning_details)!=null?u:[],le=K.length>0?K.map(f=>{switch(f.type){case"reasoning.text":{if(f.text)return{type:"reasoning",text:f.text,providerMetadata:{openrouter:{reasoning_details:[f]}}};break}case"reasoning.summary":{if(f.summary)return{type:"reasoning",text:f.summary,providerMetadata:{openrouter:{reasoning_details:[f]}}};break}case"reasoning.encrypted":{if(f.data)return{type:"reasoning",text:"[REDACTED]",providerMetadata:{openrouter:{reasoning_details:[f]}}};break}}return null}).filter(f=>f!==null):A.message.reasoning?[{type:"reasoning",text:A.message.reasoning}]:[],B=[];if(B.push(...le),A.message.content&&B.push({type:"text",text:A.message.content}),A.message.tool_calls)for(const f of A.message.tool_calls)B.push({type:"tool-call",toolCallId:(p=f.id)!=null?p:q(),toolName:f.function.name,input:f.function.arguments,providerMetadata:{openrouter:{reasoning_details:K}}});if(A.message.images)for(const f of A.message.images)B.push({type:"file",mediaType:Qe(f.image_url.url,"image/jpeg"),data:Pe(f.image_url.url)});if(A.message.annotations)for(const f of A.message.annotations)f.type==="url_citation"&&B.push({type:"source",sourceType:"url",id:f.url_citation.url,url:f.url_citation.url,title:f.url_citation.title,providerMetadata:{openrouter:{content:f.url_citation.content||""}}});const X=(g=A.message.annotations)==null?void 0:g.filter(f=>f.type==="file"),x=A.message.tool_calls&&A.message.tool_calls.length>0,z=K.some(f=>f.type==="reasoning.encrypted"&&f.data),Y=x&&z&&A.finish_reason==="stop"?"tool-calls":ye(A.finish_reason);return{content:B,finishReason:Y,usage:F,warnings:[],providerMetadata:{openrouter:wo.parse({provider:(m=P.provider)!=null?m:"",reasoning_details:(_=A.message.reasoning_details)!=null?_:[],annotations:X&&X.length>0?X:void 0,usage:E(E(E({promptTokens:(h=F.inputTokens)!=null?h:0,completionTokens:(d=F.outputTokens)!=null?d:0,totalTokens:(v=F.totalTokens)!=null?v:0,cost:(y=P.usage)==null?void 0:y.cost},((b=(k=P.usage)==null?void 0:k.prompt_tokens_details)==null?void 0:b.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:P.usage.prompt_tokens_details.cached_tokens}}:{}),((O=(w=P.usage)==null?void 0:w.completion_tokens_details)==null?void 0:O.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:P.usage.completion_tokens_details.reasoning_tokens}}:{}),((C=(I=P.usage)==null?void 0:I.cost_details)==null?void 0:C.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:P.usage.cost_details.upstream_inference_cost}}:{})})},request:{body:D},response:{id:P.id,modelId:P.model,headers:Z}}}async doStream(e){var r;const o=(e.providerOptions||{}).openrouter||{},s=E(E({},this.getArgs(e)),o),{value:a,responseHeaders:i}=await se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:oe(this.config.headers(),e.headers),body:_e(E({},s),{stream:!0,stream_options:this.config.compatibility==="strict"?E({include_usage:!0},(r=this.settings.usage)!=null&&r.include?{include_usage:!0}:{}):void 0}),failedResponseHandler:ae,successfulResponseHandler:nr(jo),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=[];let l="other";const u={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},p={},g=[],m=[];let _=!1,h=!1,d,v,y,k;return{stream:a.pipeThrough(new TransformStream({transform(b,w){var O,I,C,T,H,D,L,Z,P,A,F,K,le,B,X;if(!b.success){l="error",w.enqueue({type:"error",error:b.error});return}const x=b.value;if("error"in x){l="error",w.enqueue({type:"error",error:x.error});return}if(x.provider&&(k=x.provider),x.id&&(y=x.id,w.enqueue({type:"response-metadata",id:x.id})),x.model&&w.enqueue({type:"response-metadata",modelId:x.model}),x.usage!=null){if(u.inputTokens=x.usage.prompt_tokens,u.outputTokens=x.usage.completion_tokens,u.totalTokens=x.usage.prompt_tokens+x.usage.completion_tokens,p.promptTokens=x.usage.prompt_tokens,x.usage.prompt_tokens_details){const S=(O=x.usage.prompt_tokens_details.cached_tokens)!=null?O:0;u.cachedInputTokens=S,p.promptTokensDetails={cachedTokens:S}}if(p.completionTokens=x.usage.completion_tokens,x.usage.completion_tokens_details){const S=(I=x.usage.completion_tokens_details.reasoning_tokens)!=null?I:0;u.reasoningTokens=S,p.completionTokensDetails={reasoningTokens:S}}p.cost=x.usage.cost,p.totalTokens=x.usage.total_tokens;const f=(C=x.usage.cost_details)==null?void 0:C.upstream_inference_cost;f!=null&&(p.costDetails={upstreamInferenceCost:f})}const z=x.choices[0];if(z?.finish_reason!=null&&(l=ye(z.finish_reason)),z?.delta==null)return;const $=z.delta,Y=(f,S)=>{h||(v=y||q(),w.enqueue({providerMetadata:S,type:"reasoning-start",id:v}),h=!0),w.enqueue({providerMetadata:S,type:"reasoning-delta",delta:f,id:v||q()})};if($.reasoning_details&&$.reasoning_details.length>0){for(const S of $.reasoning_details)if(S.type==="reasoning.text"){const j=g[g.length-1];j?.type==="reasoning.text"?(j.text=(j.text||"")+(S.text||""),j.signature=j.signature||S.signature,j.format=j.format||S.format):g.push(E({},S))}else g.push(S);const f={openrouter:{reasoning_details:$.reasoning_details}};for(const S of $.reasoning_details)switch(S.type){case"reasoning.text":{S.text&&Y(S.text,f);break}case"reasoning.encrypted":{S.data&&Y("[REDACTED]",f);break}case"reasoning.summary":{S.summary&&Y(S.summary,f);break}}}else $.reasoning&&Y($.reasoning);if($.content&&(h&&!_&&(w.enqueue({type:"reasoning-end",id:v||q()}),h=!1),_||(d=y||q(),w.enqueue({type:"text-start",id:d}),_=!0),w.enqueue({type:"text-delta",delta:$.content,id:d||q()})),$.annotations){for(const f of $.annotations)if(f.type==="url_citation")w.enqueue({type:"source",sourceType:"url",id:f.url_citation.url,url:f.url_citation.url,title:f.url_citation.title,providerMetadata:{openrouter:{content:f.url_citation.content||""}}});else if(f.type==="file"){const S=f.file;S&&typeof S=="object"&&"hash"in S&&"name"in S&&m.push(f)}}if($.tool_calls!=null)for(const f of $.tool_calls){const S=(T=f.index)!=null?T:c.length-1;if(c[S]==null){if(f.type!=="function")throw new te({data:f,message:"Expected 'function' type."});if(f.id==null)throw new te({data:f,message:"Expected 'id' to be a string."});if(((H=f.function)==null?void 0:H.name)==null)throw new te({data:f,message:"Expected 'function.name' to be a string."});c[S]={id:f.id,type:"function",function:{name:f.function.name,arguments:(D=f.function.arguments)!=null?D:""},inputStarted:!1,sent:!1};const M=c[S];if(M==null)throw new te({data:{index:S,toolCallsLength:c.length},message:`Tool call at index ${S} is missing after creation.`});((L=M.function)==null?void 0:L.name)!=null&&((Z=M.function)==null?void 0:Z.arguments)!=null&&Ee(M.function.arguments)&&(M.inputStarted=!0,w.enqueue({type:"tool-input-start",id:M.id,toolName:M.function.name}),w.enqueue({type:"tool-input-delta",id:M.id,delta:M.function.arguments}),w.enqueue({type:"tool-input-end",id:M.id}),w.enqueue({type:"tool-call",toolCallId:M.id,toolName:M.function.name,input:M.function.arguments,providerMetadata:{openrouter:{reasoning_details:g}}}),M.sent=!0);continue}const j=c[S];if(j==null)throw new te({data:{index:S,toolCallsLength:c.length,toolCallDelta:f},message:`Tool call at index ${S} is missing during merge.`});j.inputStarted||(j.inputStarted=!0,w.enqueue({type:"tool-input-start",id:j.id,toolName:j.function.name})),((P=f.function)==null?void 0:P.arguments)!=null&&(j.function.arguments+=(F=(A=f.function)==null?void 0:A.arguments)!=null?F:""),w.enqueue({type:"tool-input-delta",id:j.id,delta:(K=f.function.arguments)!=null?K:""}),((le=j.function)==null?void 0:le.name)!=null&&((B=j.function)==null?void 0:B.arguments)!=null&&Ee(j.function.arguments)&&(w.enqueue({type:"tool-call",toolCallId:(X=j.id)!=null?X:q(),toolName:j.function.name,input:j.function.arguments,providerMetadata:{openrouter:{reasoning_details:g}}}),j.sent=!0)}if($.images!=null)for(const f of $.images)w.enqueue({type:"file",mediaType:Qe(f.image_url.url,"image/jpeg"),data:Pe(f.image_url.url)})},flush(b){var w;const O=c.length>0,I=g.some(T=>T.type==="reasoning.encrypted"&&T.data);if(O&&I&&l==="stop"&&(l="tool-calls"),l==="tool-calls")for(const T of c)T&&!T.sent&&(b.enqueue({type:"tool-call",toolCallId:(w=T.id)!=null?w:q(),toolName:T.function.name,input:Ee(T.function.arguments)?T.function.arguments:"{}",providerMetadata:{openrouter:{reasoning_details:g}}}),T.sent=!0);h&&b.enqueue({type:"reasoning-end",id:v||q()}),_&&b.enqueue({type:"text-end",id:d||q()});const C={usage:p};k!==void 0&&(C.provider=k),g.length>0&&(C.reasoning_details=g),m.length>0&&(C.annotations=m),b.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:{openrouter:C}})}})),warnings:[],request:{body:s},response:{headers:i}}}};function Ao({prompt:e,inputFormat:r,user:n="user",assistant:o="assistant"}){if(e.length===1&&e[0]&&e[0].role==="user"&&e[0].content.length===1&&e[0].content[0]&&e[0].content[0].type==="text")return{prompt:e[0].content[0].text};let s="";e[0]&&e[0].role==="system"&&(s+=`${e[0].content}
|
|
23
21
|
|
|
24
|
-
`,e=e.slice(1));for(const{role:a,content:
|
|
22
|
+
`,e=e.slice(1));for(const{role:a,content:i}of e)switch(a){case"system":throw new Dn({message:`Unexpected system message in prompt: ${i}`,prompt:e});case"user":{const c=i.map(l=>{switch(l.type){case"text":return l.text;case"file":throw new W({functionality:"file attachments"});default:return""}}).join("");s+=`${n}:
|
|
25
23
|
${c}
|
|
26
24
|
|
|
27
|
-
`;break}case"assistant":{const c=
|
|
25
|
+
`;break}case"assistant":{const c=i.map(l=>{switch(l.type){case"text":return l.text;case"tool-call":throw new W({functionality:"tool-call messages"});case"tool-result":throw new W({functionality:"tool-result messages"});case"reasoning":throw new W({functionality:"reasoning messages"});case"file":throw new W({functionality:"file attachments"});default:return""}}).join("");s+=`${o}:
|
|
28
26
|
${c}
|
|
29
27
|
|
|
30
|
-
`;break}case"tool":throw new
|
|
31
|
-
`,{prompt:s}}var
|
|
28
|
+
`;break}case"tool":throw new W({functionality:"tool messages"})}return s+=`${o}:
|
|
29
|
+
`,{prompt:s}}var et=t.union([t.object({id:t.string().optional(),model:t.string().optional(),choices:t.array(t.object({text:t.string(),reasoning:t.string().nullish().optional(),reasoning_details:qe.nullish(),finish_reason:t.string().nullish(),index:t.number().nullish(),logprobs:t.object({tokens:t.array(t.string()),token_logprobs:t.array(t.number()),top_logprobs:t.array(t.record(t.string(),t.number())).nullable()}).passthrough().nullable().optional()}).passthrough()),usage:t.object({prompt_tokens:t.number(),prompt_tokens_details:t.object({cached_tokens:t.number()}).passthrough().nullish(),completion_tokens:t.number(),completion_tokens_details:t.object({reasoning_tokens:t.number()}).passthrough().nullish(),total_tokens:t.number(),cost:t.number().optional(),cost_details:t.object({upstream_inference_cost:t.number().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),Se]),Uo=class{constructor(e,r,n){this.specificationVersion="v2",this.provider="openrouter",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"text/*":[/^data:text\//,/^https?:\/\/.+$/],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.defaultObjectGenerationMode=void 0,this.modelId=e,this.settings=r,this.config=n}getArgs({prompt:e,maxOutputTokens:r,temperature:n,topP:o,frequencyPenalty:s,presencePenalty:a,seed:i,responseFormat:c,topK:l,stopSequences:u,tools:p,toolChoice:g}){const{prompt:m}=Ao({prompt:e,inputFormat:"prompt"});if(p?.length)throw new W({functionality:"tools"});if(g)throw new W({functionality:"toolChoice"});return E(E({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:r,temperature:n,top_p:o,frequency_penalty:s,presence_penalty:a,seed:i,stop:u,response_format:c,top_k:l,prompt:m,include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning},this.config.extraBody),this.settings.extraBody)}async doGenerate(e){var r,n,o,s,a,i,c,l,u,p,g,m,_,h,d;const y=(e.providerOptions||{}).openrouter||{},k=E(E({},this.getArgs(e)),y),{value:b,responseHeaders:w}=await se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:oe(this.config.headers(),e.headers),body:k,failedResponseHandler:ae,successfulResponseHandler:De(et),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in b){const I=b.error;throw new V({message:I.message,url:this.config.url({path:"/completions",modelId:this.modelId}),requestBodyValues:k,statusCode:200,responseHeaders:w,data:I})}const O=b.choices[0];if(!O)throw new Ft({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:(r=O.text)!=null?r:""}],finishReason:ye(O.finish_reason),usage:{inputTokens:(o=(n=b.usage)==null?void 0:n.prompt_tokens)!=null?o:0,outputTokens:(a=(s=b.usage)==null?void 0:s.completion_tokens)!=null?a:0,totalTokens:((c=(i=b.usage)==null?void 0:i.prompt_tokens)!=null?c:0)+((u=(l=b.usage)==null?void 0:l.completion_tokens)!=null?u:0),reasoningTokens:(m=(g=(p=b.usage)==null?void 0:p.completion_tokens_details)==null?void 0:g.reasoning_tokens)!=null?m:0,cachedInputTokens:(d=(h=(_=b.usage)==null?void 0:_.prompt_tokens_details)==null?void 0:h.cached_tokens)!=null?d:0},warnings:[],response:{headers:w}}}async doStream(e){const n=(e.providerOptions||{}).openrouter||{},o=E(E({},this.getArgs(e)),n),{value:s,responseHeaders:a}=await se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:oe(this.config.headers(),e.headers),body:_e(E({},o),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:ae,successfulResponseHandler:nr(et),abortSignal:e.abortSignal,fetch:this.config.fetch});let i="other";const c={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},l={};return{stream:s.pipeThrough(new TransformStream({transform(u,p){var g,m,_;if(!u.success){i="error",p.enqueue({type:"error",error:u.error});return}const h=u.value;if("error"in h){i="error",p.enqueue({type:"error",error:h.error});return}if(h.usage!=null){if(c.inputTokens=h.usage.prompt_tokens,c.outputTokens=h.usage.completion_tokens,c.totalTokens=h.usage.prompt_tokens+h.usage.completion_tokens,l.promptTokens=h.usage.prompt_tokens,h.usage.prompt_tokens_details){const y=(g=h.usage.prompt_tokens_details.cached_tokens)!=null?g:0;c.cachedInputTokens=y,l.promptTokensDetails={cachedTokens:y}}if(l.completionTokens=h.usage.completion_tokens,h.usage.completion_tokens_details){const y=(m=h.usage.completion_tokens_details.reasoning_tokens)!=null?m:0;c.reasoningTokens=y,l.completionTokensDetails={reasoningTokens:y}}l.cost=h.usage.cost,l.totalTokens=h.usage.total_tokens;const v=(_=h.usage.cost_details)==null?void 0:_.upstream_inference_cost;v!=null&&(l.costDetails={upstreamInferenceCost:v})}const d=h.choices[0];d?.finish_reason!=null&&(i=ye(d.finish_reason)),d?.text!=null&&p.enqueue({type:"text-delta",delta:d.text,id:q()})},flush(u){u.enqueue({type:"finish",finishReason:i,usage:c,providerMetadata:{openrouter:{usage:l}}})}})),response:{headers:a}}}},$o=t.object({prompt_tokens:t.number(),total_tokens:t.number(),cost:t.number().optional()}),Mo=t.object({object:t.literal("embedding"),embedding:t.array(t.number()),index:t.number().optional()}),No=t.object({id:t.string().optional(),object:t.literal("list"),data:t.array(Mo),model:t.string(),usage:$o.optional()}),Do=class{constructor(e,r,n){this.specificationVersion="v2",this.provider="openrouter",this.maxEmbeddingsPerCall=void 0,this.supportsParallelCalls=!0,this.modelId=e,this.settings=r,this.config=n}async doEmbed(e){var r;const{values:n,abortSignal:o,headers:s}=e,a=E(E({model:this.modelId,input:n,user:this.settings.user,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody),{value:i,responseHeaders:c}=await se({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:oe(this.config.headers(),s),body:a,failedResponseHandler:ae,successfulResponseHandler:De(No),abortSignal:o,fetch:this.config.fetch});return{embeddings:i.data.map(l=>l.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,providerMetadata:(r=i.usage)!=null&&r.cost?{openrouter:{usage:{cost:i.usage.cost}}}:void 0,response:{headers:c,body:i}}}};function Ho(e){return Object.fromEntries(Object.entries(e).filter(([,r])=>r!==null))}function Lo(e,...r){const n=Ho(e??{}),s=[n["user-agent"]||"",...r].filter(Boolean).join(" ");return _e(E({},n),{"user-agent":s})}var qo="1.5.4";function lr(e={}){var r,n,o;const s=(n=_o((r=e.baseURL)!=null?r:e.baseUrl))!=null?n:"https://openrouter.ai/api/v1",a=(o=e.compatibility)!=null?o:"compatible",i=()=>Lo(E(E({Authorization:`Bearer ${Qn({apiKey:e.apiKey,environmentVariableName:"OPENROUTER_API_KEY",description:"OpenRouter"})}`},e.headers),e.api_keys&&Object.keys(e.api_keys).length>0&&{"X-Provider-API-Keys":JSON.stringify(e.api_keys)}),`ai-sdk/openrouter/${qo}`),c=(m,_={})=>new Po(m,_,{provider:"openrouter.chat",url:({path:h})=>`${s}${h}`,headers:i,compatibility:a,fetch:e.fetch,extraBody:e.extraBody}),l=(m,_={})=>new Uo(m,_,{provider:"openrouter.completion",url:({path:h})=>`${s}${h}`,headers:i,compatibility:a,fetch:e.fetch,extraBody:e.extraBody}),u=(m,_={})=>new Do(m,_,{provider:"openrouter.embedding",url:({path:h})=>`${s}${h}`,headers:i,fetch:e.fetch,extraBody:e.extraBody}),p=(m,_)=>{if(new.target)throw new Error("The OpenRouter model function cannot be called with the new keyword.");return m==="openai/gpt-3.5-turbo-instruct"?l(m,_):c(m,_)},g=(m,_)=>p(m,_);return g.languageModel=p,g.chat=c,g.completion=l,g.textEmbeddingModel=u,g.embedding=u,g}lr({compatibility:"strict"});const Vo="https://app.getgram.ai",Bo=()=>({chat:zo}),Jo=t.object({mcp:t.union([t.string()]),environment:t.record(t.string(),t.unknown()).optional(),projectSlug:t.string(),model:t._enum$1(t.MODELS)}),zo=async(e,r)=>{if(e.method==="POST")try{const n=[];for await(const _ of e)n.push(_);const o=Buffer.concat(n).toString(),{messages:s,config:a,system:i,tools:c}=JSON.parse(o),l=Jo.parse(a),p=await(await Tn({transport:{type:"http",url:l.mcp,headers:{...Go(l.environment??{}),Authorization:`Bearer ${process.env.GRAM_API_KEY??""}`}}})).tools(),g=lr({baseURL:Vo,apiKey:"must be set",headers:{"Gram-Project":l.projectSlug,"Gram-Key":process.env.GRAM_API_KEY??""}}),m=t.streamText({system:i,model:g.chat(l.model),messages:t.convertToModelMessages(s),tools:{...p,...cr(c)},stopWhen:t.stepCountIs(10)});r.setHeader("Content-Type","text/event-stream"),r.setHeader("Cache-Control","no-cache"),r.setHeader("Connection","keep-alive"),r.setHeader("Transfer-Encoding","chunked"),r.statusCode=200,m.pipeUIMessageStreamToResponse(r,{sendReasoning:!0,sendSources:!0})}catch(n){r.statusCode=500,r.end(JSON.stringify({error:n instanceof Error?n.message:"Unknown error"}))}},tt="MCP-";function Go(e){return typeof e!="object"||e===null?{}:Object.entries(e).reduce((r,[n,o])=>{const s=n.replace(/_/g,"-"),a=s.startsWith(tt)?s:`${tt}${s}`;return r[a]=o,r},{})}exports.createElementsServerHandlers=Bo;
|