@uigraph/ai-sdk 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -4796,9 +4796,9 @@ interface MCPClient {
|
|
|
4796
4796
|
type McpClient = Awaited<ReturnType<typeof createMCPClient>>;
|
|
4797
4797
|
type ConnectMcpToolsConfig = {
|
|
4798
4798
|
url: string;
|
|
4799
|
-
orgId
|
|
4799
|
+
orgId?: string;
|
|
4800
4800
|
accessToken: string;
|
|
4801
|
-
authType: 'user' | '
|
|
4801
|
+
authType: 'user' | 'service_account';
|
|
4802
4802
|
};
|
|
4803
4803
|
declare function connectMcpTools(config: ConnectMcpToolsConfig): Promise<{
|
|
4804
4804
|
client: McpClient;
|
package/dist/index.mjs
CHANGED
|
@@ -77,7 +77,7 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
|
|
|
77
77
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
78
78
|
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r
|
|
79
79
|
`:`[${r[e]}\r
|
|
80
|
-
]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function es(e,t){let n={type:`object`,additionalProperties:vs(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===U.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Yo(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===U.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===U.ZodBranded&&e.keyType._def.type._def.typeName===U.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Go(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Gae(e,t){return t.mapStrategy===`record`?es(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[vs(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Wo(),vs(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Wo()],minItems:2,maxItems:2}}}function Kae(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function qae(){return{not:Wo()}}function Jae(){return{type:`null`}}var ts={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Yae(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in ts&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=ts[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return ns(e,t)}var ns=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>vs(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function rs(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[ts[e.innerType._def.typeName],`null`]};let n=vs(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function is(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function as(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=ss(a),s=vs(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=os(e,t);return a!==void 0&&(n.additionalProperties=a),n}function os(e,t){if(e.catchall._def.typeName!==`ZodNever`)return vs(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function ss(e){try{return e.isOptional()}catch{return!0}}var cs=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return vs(e.innerType._def,t);let n=vs(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:Wo()},n]}:Wo()},ls=(e,t)=>{if(t.pipeStrategy===`input`)return vs(e.in._def,t);if(t.pipeStrategy===`output`)return vs(e.out._def,t);let n=vs(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,vs(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function us(e,t){return vs(e.type._def,t)}function ds(e,t){let n={type:`array`,uniqueItems:!0,items:vs(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function fs(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>vs(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:vs(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>vs(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function ps(){return{not:Wo()}}function ms(){return Wo()}var hs=(e,t)=>vs(e.innerType._def,t),gs=(e,t,n)=>{switch(t){case U.ZodString:return Yo(e,n);case U.ZodNumber:return is(e);case U.ZodObject:return as(e,n);case U.ZodBigInt:return Nae(e);case U.ZodBoolean:return Pae();case U.ZodDate:return Ko(e,n);case U.ZodUndefined:return ps();case U.ZodNull:return Jae();case U.ZodArray:return Mae(e,n);case U.ZodUnion:case U.ZodDiscriminatedUnion:return Yae(e,n);case U.ZodIntersection:return Vae(e,n);case U.ZodTuple:return fs(e,n);case U.ZodRecord:return es(e,n);case U.ZodLiteral:return Hae(e);case U.ZodEnum:return zae(e);case U.ZodNativeEnum:return Kae(e);case U.ZodNullable:return rs(e,n);case U.ZodOptional:return cs(e,n);case U.ZodMap:return Gae(e,n);case U.ZodSet:return ds(e,n);case U.ZodLazy:return()=>e.getter()._def;case U.ZodPromise:return us(e,n);case U.ZodNaN:case U.ZodNever:return qae();case U.ZodEffects:return Rae(e,n);case U.ZodAny:return Wo();case U.ZodUnknown:return ms();case U.ZodDefault:return Lae(e,n);case U.ZodBranded:return Go(e,n);case U.ZodReadonly:return hs(e,n);case U.ZodCatch:return Fae(e,n);case U.ZodPipeline:return ls(e,n);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(e=>void 0)(t)}},_s=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function vs(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==Aae)return i}if(r&&!n){let e=ys(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=gs(e,e.typeName,t),o=typeof a==`function`?vs(a(),t):a;if(o&&bs(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var ys=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:_s(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Wo()):t.$refStrategy===`seen`?Wo():void 0}},bs=(e,t,n)=>(e.description&&(n.description=e.description),n),xs=e=>{let t=jae(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Ss=(e,t)=>{let n=xs(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:vs(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Wo()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=vs(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Wo(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},Cs=Symbol.for(`vercel.ai.schema`);function G(e){let t;return()=>(t??=e(),t)}function ws(e,{validate:t}={}){return{[Cs]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function Ts(e){return typeof e==`object`&&!!e&&Cs in e&&e[Cs]===!0&&`jsonSchema`in e&&`validate`in e}function Es(e){return e==null?ws({type:`object`,properties:{},additionalProperties:!1}):Ts(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?K(e):Ds(e):e()}function Ds(e){return ws(()=>Vo(e[`~standard`].jsonSchema.input({target:`draft-07`})),{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new ht({value:t,cause:n.issues})}}})}function Os(e,t){let n=t?.useReferences??!1;return ws(()=>Ss(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function ks(e,t){let n=t?.useReferences??!1;return ws(()=>Vo(Ur(e,{target:`draft-7`,io:`input`,reused:n?`ref`:`inline`})),{validate:async t=>{let n=await Kr(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function As(e){return`_zod`in e}function K(e,t){return As(e)?ks(e,t):Os(e,t)}async function js({value:e,schema:t,context:n}){let r=await Ms({value:e,schema:t,context:n});if(!r.success)throw ht.wrap({value:e,cause:r.error,context:n});return r.value}async function Ms({value:e,schema:t,context:n}){let r=Es(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let t=await r.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:ht.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:ht.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function Ns({text:e,schema:t}){try{let n=Bo(e);return t==null?n:await js({value:n,schema:t})}catch(t){throw Ne.isInstance(t)||ht.isInstance(t)?t:new Ne({text:e,cause:t})}}async function Ps({text:e,schema:t}){try{let n=Bo(e);return t==null?{success:!0,value:n,rawValue:n}:await Ms({value:n,schema:t})}catch(t){return{success:!1,error:Ne.isInstance(t)?t:new Ne({text:e,cause:t}),rawValue:void 0}}}function Fs({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Ba).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await Ps({text:e,schema:t}))}}))}async function q({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Ms({value:t[e],schema:n});if(!r.success)throw new he({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Is=()=>globalThis.fetch,Ls=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>await zs({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Rs=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>await zs({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),zs=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Is()})=>{try{let s=await o(e,{method:`POST`,headers:Oo(t,`ai-sdk/provider-utils/${ko}`,Eo()),body:n.content,signal:a}),c=So(s);if(!s.ok){let t;try{t=await i({response:s,url:e,requestBodyValues:n.values})}catch(t){throw wo(t)||E.isInstance(t)?t:new E({message:`Failed to process error response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:s,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(wo(t)||E.isInstance(t))?t:new E({message:`Failed to process successful response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(t){throw To({error:t,url:e,requestBodyValues:n.values})}};function Bs(e){return e}function Vs(e){return{...e,type:`dynamic`}}function Hs({id:e,inputSchema:t}){return({execute:n,outputSchema:r,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Bs({type:`provider`,isProviderExecuted:!1,id:e,args:l,inputSchema:t,outputSchema:r,execute:n,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Us({id:e,inputSchema:t,outputSchema:n}){return({execute:r,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Bs({type:`provider`,isProviderExecuted:!1,id:e,args:l,inputSchema:t,outputSchema:n,execute:r,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Ws({id:e,inputSchema:t,outputSchema:n,supportsDeferredResults:r}){return({onInputStart:i,onInputDelta:a,onInputAvailable:o,...s})=>Bs({type:`provider`,isProviderExecuted:!0,id:e,args:s,inputSchema:t,outputSchema:n,onInputStart:i,onInputDelta:a,onInputAvailable:o,supportsDeferredResults:r})}async function Gs(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}function Ks({part:e}){if(so(e.mediaType))return e.mediaType;if(e.data.type===`data`){let t=sae({data:e.data.data,topLevelType:oo(e.mediaType)});if(t)return t;throw new k({functionality:`file of media type "${e.mediaType}" must specify subtype since it could not be auto-detected`})}throw new k({functionality:`file of media type "${e.mediaType}" must specify subtype since it is not passed as inline bytes`})}function qs({reference:e,provider:t}){let n=e[t];if(n!=null)return n;throw new rt({provider:t,reference:e})}var Xae=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r,shouldRetry:i,getDelayInMs:a=({exponentialBackoffDelay:e})=>e,createRetryError:o=({message:e})=>Error(e)})=>async s=>Js(s,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r,shouldRetry:i,getDelayInMs:a,createRetryError:o});async function Js(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:i,shouldRetry:a,getDelayInMs:o,createRetryError:s},c=[]){try{return await e()}catch(l){if(wo(l)||t===0)throw l;let u=le(l),d=[...c,l],f=d.length;if(f>t)throw s({message:`Failed after ${f} attempts. Last error: ${u}`,reason:`maxRetriesExceeded`,errors:d});if(await a(l)&&f<=t)return await Ua(o({error:l,exponentialBackoffDelay:n}),{abortSignal:i}),Js(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:i,shouldRetry:a,getDelayInMs:o,createRetryError:s},d);throw f===1?l:s({message:`Failed after ${f} attempts with non-retryable error: '${u}'`,reason:`errorNotRetryable`,errors:d})}}var Zae=new TextDecoder;async function Ys({response:e,url:t}){return Zae.decode(await bo({response:e,url:t}))}var Xs=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await Ys({response:r,url:i}),s=So(r);if(o.trim()===``)return{responseHeaders:s,value:new E({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})};try{let c=await Ns({text:o,schema:e});return{responseHeaders:s,value:new E({message:t(c),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,data:c,isRetryable:n?.(r,c)})}}catch{return{responseHeaders:s,value:new E({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})}}},Zs=e=>async({response:t})=>{let n=So(t);if(t.body==null)throw new O({});return{responseHeaders:n,value:Fs({stream:t.body,schema:e})}},Qs=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await Ys({response:t,url:n}),a=await Ps({text:i,schema:e}),o=So(t);if(!a.success)throw new E({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},$s=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=So(e);if(!e.body)throw new E({message:`Response body is empty`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new E({message:`Failed to read response as array buffer`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},ec=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=So(e),i=await Ys({response:e,url:t});return{responseHeaders:r,value:new E({message:e.statusText,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:i})}};function tc(e){if(e==null)return!0;let t=typeof e;return t===`string`||t===`number`||t===`boolean`?!0:t===`function`||t===`symbol`||t===`bigint`?!1:Array.isArray(e)?e.every(tc):Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(tc)}function nc(e){let t={};for(let[n,r]of Object.entries(e.config))if(n===`headers`){let e=Qae(r);tc(e)&&(t[n]=e)}else tc(r)&&(t[n]=r);return{modelId:e.modelId,config:t}}function Qae(e){let t=e;if(typeof e==`function`&&(t=e()),t instanceof Promise)throw Error(`Promise returned from resolveSync`);return t}var rc=class{constructor(e,t={}){this.toolCalls=[],this.controller=e,this._generateId=t.generateId??Co,this.typeValidation=t.typeValidation??`none`,this.extractMetadata=t.extractMetadata,this.buildToolCallProviderMetadata=t.buildToolCallProviderMetadata}processDelta(e){let t=e.index??this.toolCalls.length;this.toolCalls[t]==null?this.processNewToolCall(t,e):this.processExistingToolCall(t,e)}flush(){for(let e of this.toolCalls)e.hasFinished||this.finishToolCall(e)}processNewToolCall(e,t){if(this.typeValidation===`required`){if(t.type!==`function`)throw new De({data:t,message:`Expected 'function' type.`})}else if(this.typeValidation===`if-present`&&t.type!=null&&t.type!==`function`)throw new De({data:t,message:`Expected 'function' type.`});if(t.id==null)throw new De({data:t,message:`Expected 'id' to be a string.`});if(t.function?.name==null)throw new De({data:t,message:`Expected 'function.name' to be a string.`});this.controller.enqueue({type:`tool-input-start`,id:t.id,toolName:t.function.name});let n=this.extractMetadata?.call(this,t);this.toolCalls[e]={id:t.id,type:`function`,function:{name:t.function.name,arguments:t.function.arguments??``},hasFinished:!1,metadata:n};let r=this.toolCalls[e];r.function.arguments.length>0&&this.controller.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments})}processExistingToolCall(e,t){let n=this.toolCalls[e];n.hasFinished||t.function?.arguments!=null&&(n.function.arguments+=t.function.arguments,this.controller.enqueue({type:`tool-input-delta`,id:n.id,delta:t.function.arguments}))}finishToolCall(e){this.controller.enqueue({type:`tool-input-end`,id:e.id});let t=this.buildToolCallProviderMetadata?.call(this,e.metadata);this.controller.enqueue({type:`tool-call`,toolCallId:e.id??this._generateId(),toolName:e.function.name,input:e.function.arguments,...t?{providerMetadata:t}:{}}),e.hasFinished=!0}};function ic(e){let t=e.indexOf(`.`);return t===-1?e:e.slice(0,t)}function ac(e){if(e?.trim()===``)throw new he({argument:`baseURL`,message:`baseURL must be a non-empty string.`});return e}function oc(e){return e?.replace(/\/$/,``)}let sc;sc=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function $ae(e){return(await sc).getRandomValues(new Uint8Array(e))}async function eoe(e){let t=``;for(;t.length<e;){let n=await $ae(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function toe(e){return await eoe(e)}async function noe(e){let t=await(await sc).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function cc(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await toe(e);return{code_verifier:t,code_challenge:await noe(t)}}var lc=`2025-11-25`,roe=[lc,`2025-06-18`,`2025-03-26`,`2024-11-05`],ioe=_i(z(j(),P())),aoe=li({name:j(),version:j(),title:_i(j())}),uc=li({_meta:_i(I({}).loose())}),dc=uc,fc=I({method:j(),params:_i(uc)}),pc=I({applyDefaults:_i(N())}).loose(),ooe=li({experimental:_i(I({}).loose()),logging:_i(I({}).loose()),completions:_i(I({}).loose()),prompts:_i(li({listChanged:_i(N())})),resources:_i(li({subscribe:_i(N()),listChanged:_i(N())})),tools:_i(li({listChanged:_i(N())})),elicitation:_i(pc)});I({elicitation:_i(pc)}).loose();var mc=dc.extend({protocolVersion:j(),capabilities:ooe,serverInfo:aoe,instructions:_i(j())}),hc=dc.extend({nextCursor:_i(j())}),soe=I({name:j(),title:_i(j()),description:_i(j()),inputSchema:I({type:V(`object`),properties:_i(I({}).loose())}).loose(),outputSchema:_i(I({}).loose()),annotations:_i(I({title:_i(j())}).loose()),_meta:ioe}).loose(),coe=hc.extend({tools:F(soe)}),gc=I({type:V(`text`),text:j()}).loose(),_c=I({type:V(`image`),data:ni(),mimeType:j()}).loose(),loe=I({uri:j(),name:j(),title:_i(j()),description:_i(j()),mimeType:_i(j()),size:_i(M())}).loose(),uoe=hc.extend({resources:F(loe)}),vc=I({uri:j(),name:_i(j()),title:_i(j()),mimeType:_i(j())}).loose(),yc=vc.extend({text:j()}),bc=vc.extend({blob:ni()}),xc=I({type:V(`resource`),resource:L([yc,bc])}).loose(),Sc=I({type:V(`resource_link`),uri:j(),name:j(),description:_i(j()),mimeType:_i(j())}).loose(),doe=dc.extend({content:F(L([gc,_c,xc,Sc])),structuredContent:_i(P()),isError:N().default(!1).optional()}).or(dc.extend({toolResult:P()})),foe=I({uriTemplate:j(),name:j(),title:_i(j()),description:_i(j()),mimeType:_i(j())}).loose(),poe=dc.extend({resourceTemplates:F(foe)}),moe=dc.extend({contents:F(L([yc,bc]))}),hoe=I({type:V(`ref/prompt`),name:j()}).loose(),goe=I({type:V(`ref/resource`),uri:j()}).loose(),_oe=I({name:j(),value:j()}).loose();uc.extend({ref:L([hoe,goe]),argument:_oe,context:_i(I({arguments:z(j(),j())}).loose())});var voe=dc.extend({completion:I({values:F(j()).max(100),total:_i(M().int()),hasMore:_i(N())}).loose()}),yoe=I({name:j(),description:_i(j()),required:_i(N())}).loose(),boe=I({name:j(),title:_i(j()),description:_i(j()),arguments:_i(F(yoe))}).loose(),xoe=hc.extend({prompts:F(boe)}),Soe=I({role:L([V(`user`),V(`assistant`)]),content:L([gc,_c,xc,Sc])}).loose(),Coe=dc.extend({description:_i(j()),messages:F(Soe)}),woe=uc.extend({message:j(),requestedSchema:P()}),Cc=fc.extend({method:V(`elicitation/create`),params:woe}),Toe=dc.extend({action:L([V(`accept`),V(`decline`),V(`cancel`)]),content:_i(z(j(),P()))}),wc=`2.0`,Eoe=I({jsonrpc:V(wc),id:L([j(),M().int()])}).merge(fc).strict(),Doe=I({jsonrpc:V(wc),id:L([j(),M().int()]),result:dc}).strict(),Ooe=I({jsonrpc:V(wc),id:L([j(),M().int()]),error:I({code:M().int(),message:j(),data:_i(P())})}).strict(),koe=L([Eoe,I({jsonrpc:V(wc)}).merge(I({method:j(),params:_i(uc)})).strict(),Doe,Ooe]);function Tc(e){return koe.parse(e)}async function Ec(e){return Tc(await Ns({text:e}))}var Dc=`vercel.ai.error.AI_MCPClientError`,Aoe=Symbol.for(Dc),Oc,kc,Ac=class extends (kc=w,Oc=Aoe,kc){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[Oc]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(e){return w.hasMarker(e,Dc)}},jc=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,Mc=j().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ti.custom,message:`URL must be parseable`,fatal:!0}),wt}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),Nc=I({access_token:j(),id_token:j().optional(),token_type:j(),expires_in:M().optional(),scope:j().optional(),refresh_token:j().optional(),authorization_server:Mc.optional(),token_endpoint:Mc.optional()}).strip(),joe=li({resource:j().url(),authorization_servers:F(Mc).optional(),jwks_uri:j().url().optional(),scopes_supported:F(j()).optional(),bearer_methods_supported:F(j()).optional(),resource_signing_alg_values_supported:F(j()).optional(),resource_name:j().optional(),resource_documentation:j().optional(),resource_policy_uri:j().url().optional(),resource_tos_uri:j().url().optional(),tls_client_certificate_bound_access_tokens:N().optional(),authorization_details_types_supported:F(j()).optional(),dpop_signing_alg_values_supported:F(j()).optional(),dpop_bound_access_tokens_required:N().optional()}),Pc=li({issuer:j(),authorization_endpoint:Mc,token_endpoint:Mc,registration_endpoint:Mc.optional(),scopes_supported:F(j()).optional(),response_types_supported:F(j()),grant_types_supported:F(j()).optional(),code_challenge_methods_supported:F(j()),token_endpoint_auth_methods_supported:F(j()).optional(),token_endpoint_auth_signing_alg_values_supported:F(j()).optional()}),Moe=li({issuer:j(),authorization_endpoint:Mc,token_endpoint:Mc,userinfo_endpoint:Mc.optional(),jwks_uri:Mc,registration_endpoint:Mc.optional(),scopes_supported:F(j()).optional(),response_types_supported:F(j()),grant_types_supported:F(j()).optional(),subject_types_supported:F(j()),id_token_signing_alg_values_supported:F(j()),claims_supported:F(j()).optional(),token_endpoint_auth_methods_supported:F(j()).optional()}).merge(Pc.pick({code_challenge_methods_supported:!0})),Noe=I({client_id:j(),client_secret:j().optional(),client_id_issued_at:M().optional(),client_secret_expires_at:M().optional(),authorization_server:Mc.optional(),token_endpoint:Mc.optional()}).strip(),Poe=I({redirect_uris:F(Mc),token_endpoint_auth_method:j().optional(),grant_types:F(j()).optional(),response_types:F(j()).optional(),client_name:j().optional(),client_uri:Mc.optional(),logo_uri:Mc.optional(),scope:j().optional(),contacts:F(j()).optional(),tos_uri:Mc.optional(),policy_uri:j().optional(),jwks_uri:Mc.optional(),jwks:si().optional(),software_id:j().optional(),software_version:j().optional(),software_statement:j().optional()}).strip(),Foe=I({error:j(),error_description:j().optional(),error_uri:j().optional()}),Ioe=Poe.merge(Noe),Fc=`vercel.ai.error.AI_MCPClientOAuthError`,Loe=Symbol.for(Fc),Ic,Lc,Rc=class extends (Lc=w,Ic=Loe,Lc){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[Ic]=!0}static isInstance(e){return w.hasMarker(e,Fc)}},zc=class extends Rc{};zc.errorCode=`server_error`;var Bc=class extends Rc{};Bc.errorCode=`invalid_client`;var Vc=class extends Rc{};Vc.errorCode=`invalid_grant`;var Hc=class extends Rc{};Hc.errorCode=`unauthorized_client`;var Roe={[zc.errorCode]:zc,[Bc.errorCode]:Bc,[Vc.errorCode]:Vc,[Hc.errorCode]:Hc};function zoe(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Uc(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function Boe({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var Wc=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function Gc(e){return new URL(e).href}function Voe(e,t){return{authorizationServerUrl:Gc(e),tokenEndpoint:Gc(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function Kc(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function qc(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Jc(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:Gc(e.authorization_server),tokenEndpoint:Gc(e.token_endpoint)}}async function Yc({provider:e,clientInformation:t,tokens:n}){let r=Jc(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:Gc(i.authorizationServerUrl),tokenEndpoint:Gc(i.tokenEndpoint)}:Jc(t)}async function Hoe({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(qc(t,n)),!0):!1}function Uoe(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new Rc({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function Xc({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new Rc({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function Zc(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function Woe(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Qc(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Qc(e,void 0,n):void 0;throw r}}async function $c(e,t,n=fetch){return await Qc(e,{"MCP-Protocol-Version":t},n)}function Goe(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Koe(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??lc,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Woe(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await $c(o,a,n);return!r?.metadataUrl&&Goe(s,i.pathname)&&(s=await $c(new URL(`/.well-known/${t}`,i),a,n)),s}async function qoe(e,t,n=fetch){let r=await Koe(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return joe.parse(await r.json())}function Joe(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function el(e,t){if(e.issuer!==t)throw new Rc({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Yoe(e,{fetchFn:t=fetch,protocolVersion:n=lc}={}){let r={"MCP-Protocol-Version":n},i=Joe(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await Qc(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=Pc.parse(await i.json());return el(e,a),e}else{let t=Moe.parse(await i.json());if(el(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Xoe(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await cc(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,Uc(o)),{authorizationUrl:l,codeVerifier:d}}function tl(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function nl(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Zoe(i,a,n);return;case`client_secret_post`:Qoe(i,a,r);return;case`none`:$oe(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Zoe(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Qoe(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function $oe(e,t){t.set(`client_id`,e)}async function rl(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=Foe.parse(await Ns({text:n}));return new(Roe[e]||zc)({message:t||``,cause:r})}catch(e){return new zc({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function ese(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):nl(tl(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,Uc(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await rl(p);return Nc.parse(await p.json())}async function tse(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):nl(tl(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,Uc(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await rl(d);return Nc.parse({refresh_token:r,...await d.json()})}async function nse(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await rl(a);return Ioe.parse(await a.json())}async function il(e,t){try{return await al(e,t)}catch(n){if(n instanceof Bc||n instanceof Hc)return await e.invalidateCredentials?.call(e,`all`),await al(e,t);if(n instanceof Vc)return await e.invalidateCredentials?.call(e,`tokens`),await al(e,t);throw n}}async function rse(e,t,n){let r=zoe(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Boe({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function al(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;Uoe(t,a);try{s=await qoe(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await rse(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await Yoe(c,{fetchFn:o}),d=Voe(c,u),f=await Promise.resolve(e.clientInformation());if(!f){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);f=qc(await nse(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o}),d),await e.saveClientInformation(f)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await Yc({provider:e,clientInformation:f});if(!t)throw new Rc({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});Xc({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await ese(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(Kc(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await Yc({provider:e,clientInformation:f,tokens:p});t?Xc({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await tse(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(Kc(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof Rc)||e instanceof zc))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:h,codeVerifier:g}=await Xoe(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await Hoe({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new Rc({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(h),`REDIRECT`}function ise(e){return e===void 0||e===`message`}var ase=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??lc};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return Oo(t,`ai-sdk/${jc}`,Eo())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Zc(c);try{if(await il(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new Wc;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new Ac({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Ba).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new Ac({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new Ac({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(ise(s))try{let e=await Ec(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new Ac({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new Ac({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Zc(c);try{if(await il(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new Wc;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new Ac({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}};function ol(e){return e===void 0||e===`message`}var ose=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??lc};if(t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return Oo(n,`ai-sdk/${jc}`,Eo())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e){return this.authProvider?(this.authPromise||=il(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new Ac({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.startInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.terminateSessionOnClose&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({base:{}});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c=`method`in e&&e.method===`initialize`,l=c?void 0:this.sessionId,u={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`},includeSessionId:!c}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},d=await this.fetchFn(this.url.href,u);if(this.applySessionIdFromResponse(d),d.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Zc(d);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new Wc}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(d.status===202){this.inboundSseConnection||this.startInboundSse();return}if(!d.ok){let e=await d.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${d.status}): ${e}`;d.status===404&&(l?(this.expireSessionId(l),t+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new Ac({message:t,statusCode:d.status,url:this.url.href,responseBody:e??void 0});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let f=d.headers.get(`content-type`)||``;if(f.includes(`application/json`)){let e=await d.json(),t=Array.isArray(e)?e.map(e=>Tc(e)):[Tc(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(f.includes(`text/event-stream`)){if(!d.body){let e=new Ac({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:d.status,url:this.url.href});throw(o=this.onerror)==null||o.call(this,e),e}let e=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new Ba).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(ol(a))try{let e=await Ec(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new Ac({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)});return}let p=new Ac({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`,statusCode:d.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,p),p}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new Ac({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.openInboundSse(e,t).catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=this.sessionId,o=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(s),s.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=Zc(s);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new Wc;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){s.status===404&&a&&this.expireSessionId(a);let e=new Ac({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new Ba).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),ol(i))try{let t=await Ec(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new Ac({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{c.cancel().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,l().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||((t=this.onerror)==null||t.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function sse(e){switch(e.type){case`sse`:return new ase(e);case`http`:return new ose(e);default:throw new Ac({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function cse(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var lse=`text/html;profile=mcp-app`,use=`ui/resourceUri`;function dse(e){let t=e?.ui;return St(t)?t:void 0}function fse(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function pse(e){let t=dse(e._meta),n=t?.resourceUri??e._meta?.[use],r=fse(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}var mse=`1.0.0`,hse=0,gse=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function _se(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function vse(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function yse(e){let t=_se(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(Ac.isInstance(e)&&e.code!=null)return!1;let n=vse(e);return n!=null&&gse.includes(n)}function bse(e){if(e==null)return hse;if(!Number.isInteger(e))throw new Ac({message:`maxRetries must be an integer`});if(e<0)throw new Ac({message:`maxRetries must be >= 0`});return e}function sl({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function xse(e){let t=new Sse(e);return await t.init(),t}var Sse=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=mse,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:lc,capabilities:{},serverInfo:this._serverInfo},this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=bse(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,cse(e)?this.transport=e:this.transport=sse(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new Ac({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){try{if(await this.transport.start(),this.isClosed=!1,this.initialInitializeResult){let e=mc.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}let e=await this.request({request:{method:`initialize`,params:{protocolVersion:lc,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:mc});if(e===void 0)throw new Ac({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}applyInitializeResult(e){if(!roe.includes(e.protocolVersion))throw new Ac({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this._initializeResult=e,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new Ac({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new Ac({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new Ac({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new Ac({message:`Server does not support prompts`});break;default:throw new Ac({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new Ac({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{i(new Ac({message:`Request was aborted`,cause:a?.reason}))},l=()=>{this.responseHandlers.delete(o),a?.removeEventListener(`abort`,d)},u=e=>{l(),i(e)},d=()=>{l(),c()};this.responseHandlers.set(o,e=>{if(a?.aborted)return l(),c();if(e instanceof Error)return u(e);try{let n=t.parse(e.result);l(),r(n)}catch(e){let t=new Ac({message:`Failed to parse server response`,cause:e});u(t)}}),a?.addEventListener(`abort`,d,{once:!0}),this.transport.send(s).catch(e=>{u(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:coe,options:t})}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():Xae({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:yse,createRetryError:({message:e,errors:t})=>new Ac({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:doe,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:uoe,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:moe,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:poe,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:xoe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Coe,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:voe,options:e})}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=pse({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...d?.resourceUri==null?{}:{app:{...d,mimeType:lse}}},p=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await l.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||u==null?i:l.extractStructuredContent(i,u,r)};n[r]={...t===`automatic`?Vs({description:a,title:e,metadata:f,inputSchema:ws({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:sl}):Bs({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:sl}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await Ms({value:e.structuredContent,schema:Es(t)});if(!r.success)throw new Ac({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await Ps({text:r.text,schema:t});if(!e.success)throw new Ac({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new Ac({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==Cc)throw new Ac({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=Cc.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=Toe.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new Ac({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new Ac({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new Ac({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function cl(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Cse(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...cl(t.headers),...cl(r.headers)}:t.headers}):e}const ll=Sie(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),ul=L([j(),M().int()]),dl=j();li({ttl:M().optional(),pollInterval:M().optional()});const wse=I({ttl:M().optional()}),Tse=I({taskId:j()}),fl=li({progressToken:ul.optional(),"io.modelcontextprotocol/related-task":Tse.optional()}),pl=I({_meta:fl.optional()}),ml=pl.extend({task:wse.optional()}),hl=I({method:j(),params:pl.loose().optional()}),gl=I({_meta:fl.optional()}),_l=I({method:j(),params:gl.loose().optional()}),vl=li({_meta:fl.optional()}),yl=L([j(),M().int()]),bl=I({jsonrpc:V(`2.0`),id:yl,...hl.shape}).strict(),Ese=e=>bl.safeParse(e).success,Dse=I({jsonrpc:V(`2.0`),..._l.shape}).strict(),xl=I({jsonrpc:V(`2.0`),id:yl,result:vl}).strict(),Ose=e=>xl.safeParse(e).success;var kse;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(kse||={});const Sl=I({jsonrpc:V(`2.0`),id:yl.optional(),error:I({code:M().int(),message:j(),data:P().optional()})}).strict(),Cl=L([bl,Dse,xl,Sl]);L([xl,Sl]);const wl=vl.strict(),Ase=gl.extend({requestId:yl.optional(),reason:j().optional()}),Tl=_l.extend({method:V(`notifications/cancelled`),params:Ase}),El=I({icons:F(I({src:j(),mimeType:j().optional(),sizes:F(j()).optional(),theme:B([`light`,`dark`]).optional()})).optional()}),Dl=I({name:j(),title:j().optional()}),Ol=Dl.extend({...Dl.shape,...El.shape,version:j(),websiteUrl:j().optional(),description:j().optional()}),jse=wi(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,di(I({form:di(I({applyDefaults:N().optional()}),z(j(),P())).optional(),url:ll.optional()}),z(j(),P()).optional())),Mse=li({list:ll.optional(),cancel:ll.optional(),requests:li({sampling:li({createMessage:ll.optional()}).optional(),elicitation:li({create:ll.optional()}).optional()}).optional()}),Nse=li({list:ll.optional(),cancel:ll.optional(),requests:li({tools:li({call:ll.optional()}).optional()}).optional()}),Pse=I({experimental:z(j(),ll).optional(),sampling:I({context:ll.optional(),tools:ll.optional()}).optional(),elicitation:jse.optional(),roots:I({listChanged:N().optional()}).optional(),tasks:Mse.optional(),extensions:z(j(),ll).optional()}),Fse=pl.extend({protocolVersion:j(),capabilities:Pse,clientInfo:Ol}),Ise=hl.extend({method:V(`initialize`),params:Fse}),Lse=I({experimental:z(j(),ll).optional(),logging:ll.optional(),completions:ll.optional(),prompts:I({listChanged:N().optional()}).optional(),resources:I({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:I({listChanged:N().optional()}).optional(),tasks:Nse.optional(),extensions:z(j(),ll).optional()}),Rse=vl.extend({protocolVersion:j(),capabilities:Lse,serverInfo:Ol,instructions:j().optional()}),kl=_l.extend({method:V(`notifications/initialized`),params:gl.optional()}),zse=e=>kl.safeParse(e).success,Al=hl.extend({method:V(`ping`),params:pl.optional()}),Bse=I({progress:M(),total:_i(M()),message:_i(j())}),Vse=I({...gl.shape,...Bse.shape,progressToken:ul}),jl=_l.extend({method:V(`notifications/progress`),params:Vse}),Hse=pl.extend({cursor:dl.optional()}),Ml=hl.extend({params:Hse.optional()}),Nl=vl.extend({nextCursor:dl.optional()}),Use=B([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Pl=I({taskId:j(),status:Use,ttl:L([M(),oi()]),createdAt:j(),lastUpdatedAt:j(),pollInterval:_i(M()),statusMessage:_i(j())}),Fl=vl.extend({task:Pl}),Wse=gl.merge(Pl),Il=_l.extend({method:V(`notifications/tasks/status`),params:Wse}),Ll=hl.extend({method:V(`tasks/get`),params:pl.extend({taskId:j()})}),Rl=vl.merge(Pl),zl=hl.extend({method:V(`tasks/result`),params:pl.extend({taskId:j()})});vl.loose();const Bl=Ml.extend({method:V(`tasks/list`)}),Vl=Nl.extend({tasks:F(Pl)}),Hl=hl.extend({method:V(`tasks/cancel`),params:pl.extend({taskId:j()})});vl.merge(Pl);const Ul=I({uri:j(),mimeType:_i(j()),_meta:z(j(),P()).optional()}),Wl=Ul.extend({text:j()}),Gl=j().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Kl=Ul.extend({blob:Gl}),ql=B([`user`,`assistant`]),Jl=I({audience:F(ql).optional(),priority:M().min(0).max(1).optional(),lastModified:Wr({offset:!0}).optional()}),Yl=I({...Dl.shape,...El.shape,uri:j(),description:_i(j()),mimeType:_i(j()),size:_i(M()),annotations:Jl.optional(),_meta:_i(li({}))}),Gse=I({...Dl.shape,...El.shape,uriTemplate:j(),description:_i(j()),mimeType:_i(j()),annotations:Jl.optional(),_meta:_i(li({}))}),Kse=Ml.extend({method:V(`resources/list`)}),qse=Nl.extend({resources:F(Yl)}),Jse=Ml.extend({method:V(`resources/templates/list`)}),Yse=Nl.extend({resourceTemplates:F(Gse)}),Xl=pl.extend({uri:j()}),Xse=Xl,Zse=hl.extend({method:V(`resources/read`),params:Xse}),Qse=vl.extend({contents:F(L([Wl,Kl]))}),$se=_l.extend({method:V(`notifications/resources/list_changed`),params:gl.optional()}),ece=Xl,tce=hl.extend({method:V(`resources/subscribe`),params:ece}),nce=Xl,rce=hl.extend({method:V(`resources/unsubscribe`),params:nce}),ice=gl.extend({uri:j()}),ace=_l.extend({method:V(`notifications/resources/updated`),params:ice}),oce=I({name:j(),description:_i(j()),required:_i(N())}),sce=I({...Dl.shape,...El.shape,description:_i(j()),arguments:_i(F(oce)),_meta:_i(li({}))}),cce=Ml.extend({method:V(`prompts/list`)}),lce=Nl.extend({prompts:F(sce)}),uce=pl.extend({name:j(),arguments:z(j(),j()).optional()}),dce=hl.extend({method:V(`prompts/get`),params:uce}),Zl=I({type:V(`text`),text:j(),annotations:Jl.optional(),_meta:z(j(),P()).optional()}),Ql=I({type:V(`image`),data:Gl,mimeType:j(),annotations:Jl.optional(),_meta:z(j(),P()).optional()}),$l=I({type:V(`audio`),data:Gl,mimeType:j(),annotations:Jl.optional(),_meta:z(j(),P()).optional()}),fce=I({type:V(`tool_use`),name:j(),id:j(),input:z(j(),P()),_meta:z(j(),P()).optional()}),pce=I({type:V(`resource`),resource:L([Wl,Kl]),annotations:Jl.optional(),_meta:z(j(),P()).optional()}),eu=L([Zl,Ql,$l,Yl.extend({type:V(`resource_link`)}),pce]),mce=I({role:ql,content:eu}),hce=vl.extend({description:j().optional(),messages:F(mce)}),gce=_l.extend({method:V(`notifications/prompts/list_changed`),params:gl.optional()}),_ce=I({title:j().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),vce=I({taskSupport:B([`required`,`optional`,`forbidden`]).optional()}),tu=I({...Dl.shape,...El.shape,description:j().optional(),inputSchema:I({type:V(`object`),properties:z(j(),ll).optional(),required:F(j()).optional()}).catchall(P()),outputSchema:I({type:V(`object`),properties:z(j(),ll).optional(),required:F(j()).optional()}).catchall(P()).optional(),annotations:_ce.optional(),execution:vce.optional(),_meta:z(j(),P()).optional()}),yce=Ml.extend({method:V(`tools/list`)}),bce=Nl.extend({tools:F(tu)}),nu=vl.extend({content:F(eu).default([]),structuredContent:z(j(),P()).optional(),isError:N().optional()});nu.or(vl.extend({toolResult:P()}));const xce=ml.extend({name:j(),arguments:z(j(),P()).optional()}),Sce=hl.extend({method:V(`tools/call`),params:xce}),Cce=_l.extend({method:V(`notifications/tools/list_changed`),params:gl.optional()});I({autoRefresh:N().default(!0),debounceMs:M().int().nonnegative().default(300)});const ru=B([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),wce=pl.extend({level:ru}),Tce=hl.extend({method:V(`logging/setLevel`),params:wce}),Ece=gl.extend({level:ru,logger:j().optional(),data:P()}),Dce=_l.extend({method:V(`notifications/message`),params:Ece}),Oce=I({hints:F(I({name:j().optional()})).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),kce=I({mode:B([`auto`,`required`,`none`]).optional()}),Ace=I({type:V(`tool_result`),toolUseId:j().describe(`The unique identifier for the corresponding tool call.`),content:F(eu).default([]),structuredContent:I({}).loose().optional(),isError:N().optional(),_meta:z(j(),P()).optional()}),jce=R(`type`,[Zl,Ql,$l]),iu=R(`type`,[Zl,Ql,$l,fce,Ace]),Mce=I({role:ql,content:L([iu,F(iu)]),_meta:z(j(),P()).optional()}),Nce=ml.extend({messages:F(Mce),modelPreferences:Oce.optional(),systemPrompt:j().optional(),includeContext:B([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:F(j()).optional(),metadata:ll.optional(),tools:F(tu).optional(),toolChoice:kce.optional()}),Pce=hl.extend({method:V(`sampling/createMessage`),params:Nce}),Fce=vl.extend({model:j(),stopReason:_i(B([`endTurn`,`stopSequence`,`maxTokens`]).or(j())),role:ql,content:jce}),Ice=vl.extend({model:j(),stopReason:_i(B([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(j())),role:ql,content:L([iu,F(iu)])}),Lce=I({type:V(`boolean`),title:j().optional(),description:j().optional(),default:N().optional()}),Rce=I({type:V(`string`),title:j().optional(),description:j().optional(),minLength:M().optional(),maxLength:M().optional(),format:B([`email`,`uri`,`date`,`date-time`]).optional(),default:j().optional()}),zce=I({type:B([`number`,`integer`]),title:j().optional(),description:j().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),Bce=I({type:V(`string`),title:j().optional(),description:j().optional(),enum:F(j()),default:j().optional()}),Vce=I({type:V(`string`),title:j().optional(),description:j().optional(),oneOf:F(I({const:j(),title:j()})),default:j().optional()}),Hce=L([L([I({type:V(`string`),title:j().optional(),description:j().optional(),enum:F(j()),enumNames:F(j()).optional(),default:j().optional()}),L([Bce,Vce]),L([I({type:V(`array`),title:j().optional(),description:j().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({type:V(`string`),enum:F(j())}),default:F(j()).optional()}),I({type:V(`array`),title:j().optional(),description:j().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({anyOf:F(I({const:j(),title:j()}))}),default:F(j()).optional()})])]),Lce,Rce,zce]),Uce=L([ml.extend({mode:V(`form`).optional(),message:j(),requestedSchema:I({type:V(`object`),properties:z(j(),Hce),required:F(j()).optional()})}),ml.extend({mode:V(`url`),message:j(),elicitationId:j(),url:j().url()})]),Wce=hl.extend({method:V(`elicitation/create`),params:Uce}),Gce=gl.extend({elicitationId:j()}),Kce=_l.extend({method:V(`notifications/elicitation/complete`),params:Gce}),qce=vl.extend({action:B([`accept`,`decline`,`cancel`]),content:wi(e=>e===null?void 0:e,z(j(),L([j(),M(),N(),F(j())])).optional())}),Jce=I({type:V(`ref/resource`),uri:j()}),Yce=I({type:V(`ref/prompt`),name:j()}),Xce=pl.extend({ref:L([Yce,Jce]),argument:I({name:j(),value:j()}),context:I({arguments:z(j(),j()).optional()}).optional()}),Zce=hl.extend({method:V(`completion/complete`),params:Xce}),Qce=vl.extend({completion:li({values:F(j()).max(100),total:_i(M().int()),hasMore:_i(N())})}),$ce=I({uri:j().startsWith(`file://`),name:j().optional(),_meta:z(j(),P()).optional()}),ele=hl.extend({method:V(`roots/list`),params:pl.optional()}),tle=vl.extend({roots:F($ce)}),nle=_l.extend({method:V(`notifications/roots/list_changed`),params:gl.optional()});L([Al,Ise,Zce,Tce,dce,cce,Kse,Jse,Zse,tce,rce,Sce,yce,Ll,zl,Bl,Hl]),L([Tl,jl,kl,nle,Il]),L([wl,Fce,Ice,qce,tle,Rl,Vl,Fl]),L([Al,Pce,Wce,ele,Ll,zl,Bl,Hl]),L([Tl,jl,Dce,ace,$se,Cce,gce,Il,Kce]),L([wl,Rse,Qce,hce,lce,qse,Yse,Qse,nu,bce,Rl,Vl,Fl]);const au=Nre().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ti.custom,message:`URL must be parseable`,fatal:!0}),wt}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),rle=li({resource:j().url(),authorization_servers:F(au).optional(),jwks_uri:j().url().optional(),scopes_supported:F(j()).optional(),bearer_methods_supported:F(j()).optional(),resource_signing_alg_values_supported:F(j()).optional(),resource_name:j().optional(),resource_documentation:j().optional(),resource_policy_uri:j().url().optional(),resource_tos_uri:j().url().optional(),tls_client_certificate_bound_access_tokens:N().optional(),authorization_details_types_supported:F(j()).optional(),dpop_signing_alg_values_supported:F(j()).optional(),dpop_bound_access_tokens_required:N().optional()}),ou=li({issuer:j(),authorization_endpoint:au,token_endpoint:au,registration_endpoint:au.optional(),scopes_supported:F(j()).optional(),response_types_supported:F(j()),response_modes_supported:F(j()).optional(),grant_types_supported:F(j()).optional(),token_endpoint_auth_methods_supported:F(j()).optional(),token_endpoint_auth_signing_alg_values_supported:F(j()).optional(),service_documentation:au.optional(),revocation_endpoint:au.optional(),revocation_endpoint_auth_methods_supported:F(j()).optional(),revocation_endpoint_auth_signing_alg_values_supported:F(j()).optional(),introspection_endpoint:j().optional(),introspection_endpoint_auth_methods_supported:F(j()).optional(),introspection_endpoint_auth_signing_alg_values_supported:F(j()).optional(),code_challenge_methods_supported:F(j()).optional(),client_id_metadata_document_supported:N().optional()}),ile=I({...li({issuer:j(),authorization_endpoint:au,token_endpoint:au,userinfo_endpoint:au.optional(),jwks_uri:au,registration_endpoint:au.optional(),scopes_supported:F(j()).optional(),response_types_supported:F(j()),response_modes_supported:F(j()).optional(),grant_types_supported:F(j()).optional(),acr_values_supported:F(j()).optional(),subject_types_supported:F(j()),id_token_signing_alg_values_supported:F(j()),id_token_encryption_alg_values_supported:F(j()).optional(),id_token_encryption_enc_values_supported:F(j()).optional(),userinfo_signing_alg_values_supported:F(j()).optional(),userinfo_encryption_alg_values_supported:F(j()).optional(),userinfo_encryption_enc_values_supported:F(j()).optional(),request_object_signing_alg_values_supported:F(j()).optional(),request_object_encryption_alg_values_supported:F(j()).optional(),request_object_encryption_enc_values_supported:F(j()).optional(),token_endpoint_auth_methods_supported:F(j()).optional(),token_endpoint_auth_signing_alg_values_supported:F(j()).optional(),display_values_supported:F(j()).optional(),claim_types_supported:F(j()).optional(),claims_supported:F(j()).optional(),service_documentation:j().optional(),claims_locales_supported:F(j()).optional(),ui_locales_supported:F(j()).optional(),claims_parameter_supported:N().optional(),request_parameter_supported:N().optional(),request_uri_parameter_supported:N().optional(),require_request_uri_registration:N().optional(),op_policy_uri:au.optional(),op_tos_uri:au.optional(),client_id_metadata_document_supported:N().optional()}).shape,...ou.pick({code_challenge_methods_supported:!0}).shape}),ale=I({access_token:j(),id_token:j().optional(),token_type:j(),expires_in:Ei().optional(),scope:j().optional(),refresh_token:j().optional()}).strip(),ole=I({error:j(),error_description:j().optional(),error_uri:j().optional()}),su=au.optional().or(V(``).transform(()=>void 0)),sle=I({redirect_uris:F(au),token_endpoint_auth_method:j().optional(),grant_types:F(j()).optional(),response_types:F(j()).optional(),client_name:j().optional(),client_uri:au.optional(),logo_uri:su,scope:j().optional(),contacts:F(j()).optional(),tos_uri:su,policy_uri:j().optional(),jwks_uri:au.optional(),jwks:si().optional(),software_id:j().optional(),software_version:j().optional(),software_statement:j().optional()}).strip(),cle=I({client_id:j(),client_secret:j().optional(),client_id_issued_at:M().optional(),client_secret_expires_at:M().optional()}).strip(),lle=sle.merge(cle);I({error:j(),error_description:j().optional()}).strip(),I({token:j(),token_type_hint:j().optional()}).strip();function ule(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function dle({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var cu=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},lu=class extends cu{};lu.errorCode=`invalid_request`;var uu=class extends cu{};uu.errorCode=`invalid_client`;var du=class extends cu{};du.errorCode=`invalid_grant`;var fu=class extends cu{};fu.errorCode=`unauthorized_client`;var pu=class extends cu{};pu.errorCode=`unsupported_grant_type`;var mu=class extends cu{};mu.errorCode=`invalid_scope`;var hu=class extends cu{};hu.errorCode=`access_denied`;var gu=class extends cu{};gu.errorCode=`server_error`;var _u=class extends cu{};_u.errorCode=`temporarily_unavailable`;var vu=class extends cu{};vu.errorCode=`unsupported_response_type`;var yu=class extends cu{};yu.errorCode=`unsupported_token_type`;var bu=class extends cu{};bu.errorCode=`invalid_token`;var xu=class extends cu{};xu.errorCode=`method_not_allowed`;var Su=class extends cu{};Su.errorCode=`too_many_requests`;var Cu=class extends cu{};Cu.errorCode=`invalid_client_metadata`;var wu=class extends cu{};wu.errorCode=`insufficient_scope`;var Tu=class extends cu{};Tu.errorCode=`invalid_target`;const fle={[lu.errorCode]:lu,[uu.errorCode]:uu,[du.errorCode]:du,[fu.errorCode]:fu,[pu.errorCode]:pu,[mu.errorCode]:mu,[hu.errorCode]:hu,[gu.errorCode]:gu,[_u.errorCode]:_u,[vu.errorCode]:vu,[yu.errorCode]:yu,[bu.errorCode]:bu,[xu.errorCode]:xu,[Su.errorCode]:Su,[Cu.errorCode]:Cu,[wu.errorCode]:wu,[Tu.errorCode]:Tu};var Eu=class extends Error{constructor(e){super(e??`Unauthorized`)}};function ple(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const Du=`code`,Ou=`S256`;function mle(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&ple(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function hle(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:gle(i,a,n);return;case`client_secret_post`:_le(i,a,r);return;case`none`:vle(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function gle(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function _le(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function vle(e,t){t.set(`client_id`,e)}async function ku(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ole.parse(JSON.parse(n));return new(fle[e]||gu)(t||``,r)}catch(e){return new gu(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function Au(e,t){try{return await ju(e,t)}catch(n){if(n instanceof uu||n instanceof fu)return await e.invalidateCredentials?.(`all`),await ju(e,t);if(n instanceof du)return await e.invalidateCredentials?.(`tokens`),await ju(e,t);throw n}}async function ju(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await Lu(c,{fetchFn:a}),!s)try{s=await Pu(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await Tle(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await ble(t,e,s),f=r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,p=await Promise.resolve(e.clientInformation());if(!p){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!yle(r))throw new Cu(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)p={client_id:r},await e.saveClientInformation?.(p);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await Ale(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:a});await e.saveClientInformation(t),p=t}}let m=!e.redirectUrl;if(n!==void 0||m){let t=await kle(e,c,{metadata:l,resource:d,authorizationCode:n,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let h=await e.tokens();if(h?.refresh_token)try{let t=await Ole(c,{metadata:l,clientInformation:p,refreshToken:h.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof cu)||e instanceof gu))throw e}let g=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:v}=await Ele(c,{metadata:l,clientInformation:p,state:g,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(_),`REDIRECT`}function yle(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function ble(e,t,n){let r=ule(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!dle({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function Mu(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=Nu(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=Nu(e,`scope`)||void 0,s=Nu(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function Nu(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function Pu(e,t,n=fetch){let r=await Cle(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return rle.parse(await r.json())}async function Fu(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Fu(e,void 0,n):void 0;throw r}}function xle(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Iu(e,t,n=fetch){return await Fu(e,{"MCP-Protocol-Version":t},n)}function Sle(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Cle(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=xle(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await Iu(o,a,n);return!r?.metadataUrl&&Sle(s,i.pathname)&&(s=await Iu(new URL(`/.well-known/${t}`,i),a,n)),s}function wle(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function Lu(e,{fetchFn:t=fetch,protocolVersion:n=`2025-11-25`}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=wle(e);for(let{url:e,type:n}of i){let i=await Fu(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?ou.parse(await i.json()):ile.parse(await i.json())}}}async function Tle(e,t){let n,r;try{n=await Pu(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await Lu(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function Ele(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Du))throw Error(`Incompatible auth server: does not support response type ${Du}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ou))throw Error(`Incompatible auth server: does not support code challenge method ${Ou}`)}else s=new URL(`/authorize`,e);let c=await cc(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Du),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,Ou),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function Dle(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function Ru(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&hle(mle(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await ku(l);return ale.parse(await l.json())}async function Ole(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await Ru(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function kle(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);s=Dle(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return Ru(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function Ale(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await ku(o);return lle.parse(await o.json())}const jle={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var zu=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Mle=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Cse(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??jle}async _authThenStart(){if(!this._authProvider)throw new Eu(`No auth provider`);let e;try{e=await Au(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new Eu;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=cl(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new zu(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Ba({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=Cl.parse(JSON.parse(e.data));Ose(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Eu(`No auth provider`);if(await Au(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Eu(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Ese(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new zu(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Mu(o);if(this._resourceMetadataUrl=t,this._scope=n,await Au(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Eu;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Mu(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new zu(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await Au(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Eu;return this.send(e)}}throw new zu(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),zse(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>Cl.parse(e)):[Cl.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new zu(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new zu(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};async function Nle(e){let t;if(e.authType===`service-account`)t={"X-API-Key":e.accessToken};else if(e.authType===`user`)t={Authorization:`Bearer ${e.accessToken}`};else throw Error(`unknown authType: ${e.authType}`);let n=await xse({transport:new Mle(new URL(e.url),{requestInit:{headers:{"X-UIGraph-Org-Id":e.orgId,...t}}})});return{client:n,tools:await n.tools()}}Xs({errorSchema:G(()=>K(I({type:V(`error`),error:I({type:j(),message:j()})}))),errorToMessage:e=>e.error.message}),I({type:j(),category:j().nullish(),explanation:j().nullish(),recommended_model:j().nullish()}),I({containerUpload:N().optional(),citations:I({enabled:N()}).optional(),title:j().optional(),context:j().optional()}),I({sendReasoning:N().optional(),structuredOutputMode:B([`outputFormat`,`jsonTool`,`auto`]).optional(),thinking:R(`type`,[I({type:V(`adaptive`),display:B([`omitted`,`summarized`]).optional()}),I({type:V(`enabled`),budgetTokens:M().optional()}),I({type:V(`disabled`)})]).optional(),disableParallelToolUse:N().optional(),cacheControl:I({type:V(`ephemeral`),ttl:L([V(`5m`),V(`1h`)]).optional()}).optional(),metadata:I({userId:j().optional()}).optional(),mcpServers:F(I({type:V(`url`),name:j(),url:j(),authorizationToken:j().nullish(),toolConfiguration:I({enabled:N().nullish(),allowedTools:F(j()).nullish()}).nullish()})).optional(),container:I({id:j().optional(),skills:F(R(`type`,[I({type:V(`anthropic`),skillId:j(),version:j().optional()}),I({type:V(`custom`),providerReference:z(j(),j()),version:j().optional()})])).optional()}).optional(),toolStreaming:N().optional(),effort:B([`low`,`medium`,`high`,`xhigh`,`max`]).optional(),taskBudget:I({type:V(`tokens`),total:M().int().min(2e4),remaining:M().int().min(0).optional()}).optional(),speed:B([`fast`,`standard`]).optional(),inferenceGeo:B([`us`,`global`]).optional(),fallbacks:F(I({model:j(),max_tokens:M().int().optional(),thinking:z(j(),P()).optional(),output_config:z(j(),P()).optional(),speed:B([`fast`,`standard`]).optional()})).optional(),anthropicBeta:F(j()).optional(),contextManagement:I({edits:F(R(`type`,[I({type:V(`clear_tool_uses_20250919`),trigger:R(`type`,[I({type:V(`input_tokens`),value:M()}),I({type:V(`tool_uses`),value:M()})]).optional(),keep:I({type:V(`tool_uses`),value:M()}).optional(),clearAtLeast:I({type:V(`input_tokens`),value:M()}).optional(),clearToolInputs:N().optional(),excludeTools:F(j()).optional()}),I({type:V(`clear_thinking_20251015`),keep:L([V(`all`),I({type:V(`thinking_turns`),value:M()})]).optional()}),I({type:V(`compact_20260112`),trigger:I({type:V(`input_tokens`),value:M()}).optional(),pauseAfterCompaction:N().optional(),instructions:j().optional()})]))}).optional()});var Bu=4;function Ple(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Fle=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let n=Ple(e);if(n){if(!t.canCache){this.warnings.push({type:`unsupported`,feature:`cache_control on non-cacheable context`,details:`cache_control cannot be set on ${t.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>Bu){this.warnings.push({type:`unsupported`,feature:`cacheControl breakpoint limit`,details:`Maximum ${Bu} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}}getWarnings(){return this.warnings}},Ile=G(()=>K(I({model:j(),maxUses:M().optional(),caching:I({type:V(`ephemeral`),ttl:L([V(`5m`),V(`1h`)])}).optional()}))),Lle=G(()=>K(R(`type`,[I({type:V(`advisor_result`),text:j()}),I({type:V(`advisor_redacted_result`),encryptedContent:j()}),I({type:V(`advisor_tool_result_error`),errorCode:j()})]))),Rle=Ws({id:`anthropic.advisor_20260301`,inputSchema:G(()=>K(I({}).strict())),outputSchema:Lle,supportsDeferredResults:!0}),zle=e=>Rle(e),Ble=G(()=>K(I({maxCharacters:M().optional()}))),Vle=Hs({id:`anthropic.text_editor_20250728`,inputSchema:G(()=>K(I({command:B([`view`,`create`,`str_replace`,`insert`]),path:j(),file_text:j().optional(),insert_line:M().int().optional(),new_str:j().optional(),insert_text:j().optional(),old_str:j().optional(),view_range:F(M().int()).optional()})))}),Hle=(e={})=>Vle(e),Ule=G(()=>K(I({maxUses:M().optional(),allowedDomains:F(j()).optional(),blockedDomains:F(j()).optional(),userLocation:I({type:V(`approximate`),city:j().optional(),region:j().optional(),country:j().optional(),timezone:j().optional()}).optional()}))),Wle=G(()=>K(F(I({url:j(),title:j().nullable(),pageAge:j().nullable(),encryptedContent:j(),type:V(`web_search_result`)})))),Vu=Ws({id:`anthropic.web_search_20260209`,inputSchema:G(()=>K(I({query:j()}))),outputSchema:Wle,supportsDeferredResults:!0}),Gle=(e={})=>Vu(e),Kle=G(()=>K(I({maxUses:M().optional(),allowedDomains:F(j()).optional(),blockedDomains:F(j()).optional(),userLocation:I({type:V(`approximate`),city:j().optional(),region:j().optional(),country:j().optional(),timezone:j().optional()}).optional()}))),qle=G(()=>K(F(I({url:j(),title:j().nullable(),pageAge:j().nullable(),encryptedContent:j(),type:V(`web_search_result`)})))),Jle=Ws({id:`anthropic.web_search_20250305`,inputSchema:G(()=>K(I({query:j()}))),outputSchema:qle,supportsDeferredResults:!0}),Yle=(e={})=>Jle(e),Xle=G(()=>K(I({maxUses:M().optional(),allowedDomains:F(j()).optional(),blockedDomains:F(j()).optional(),citations:I({enabled:N()}).optional(),maxContentTokens:M().optional()}))),Zle=G(()=>K(I({type:V(`web_fetch_result`),url:j(),content:I({type:V(`document`),title:j().nullable(),citations:I({enabled:N()}).optional(),source:L([I({type:V(`base64`),mediaType:V(`application/pdf`),data:j()}),I({type:V(`text`),mediaType:V(`text/plain`),data:j()})])}),retrievedAt:j().nullable()}))),Qle=Ws({id:`anthropic.web_fetch_20260209`,inputSchema:G(()=>K(I({url:j()}))),outputSchema:Zle,supportsDeferredResults:!0}),$le=(e={})=>Qle(e),eue=G(()=>K(I({maxUses:M().optional(),allowedDomains:F(j()).optional(),blockedDomains:F(j()).optional(),citations:I({enabled:N()}).optional(),maxContentTokens:M().optional()}))),tue=G(()=>K(I({type:V(`web_fetch_result`),url:j(),content:I({type:V(`document`),title:j().nullable(),citations:I({enabled:N()}).optional(),source:L([I({type:V(`base64`),mediaType:V(`application/pdf`),data:j()}),I({type:V(`text`),mediaType:V(`text/plain`),data:j()})])}),retrievedAt:j().nullable()}))),nue=Ws({id:`anthropic.web_fetch_20250910`,inputSchema:G(()=>K(I({url:j()}))),outputSchema:tue,supportsDeferredResults:!0}),rue=(e={})=>nue(e);async function iue({tools:e,toolChoice:t,disableParallelToolUse:n,cacheControlValidator:r,supportsStructuredOutput:i,supportsStrictTools:a,defaultEagerInputStreaming:o=!1}){e=e?.length?e:void 0;let s=[],c=new Set,l=r||new Fle;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s,betas:c};let u=[];for(let t of e)switch(t.type){case`function`:{let e=l.getCacheControl(t.providerOptions,{type:`tool definition`,canCache:!0}),n=t.providerOptions?.anthropic,r=n?.eagerInputStreaming??o,d=n?.deferLoading,f=n?.allowedCallers;!a&&t.strict!=null&&s.push({type:`unsupported`,feature:`strict`,details:`Tool '${t.name}' has strict: ${t.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),u.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e,...r?{eager_input_streaming:!0}:{},...a===!0&&t.strict!=null?{strict:t.strict}:{},...d==null?{}:{defer_loading:d},...f==null?{}:{allowed_callers:f},...t.inputExamples==null?{}:{input_examples:t.inputExamples.map(e=>e.input)}}),i===!0&&c.add(`structured-outputs-2025-11-13`),(t.inputExamples!=null||f!=null)&&c.add(`advanced-tool-use-2025-11-20`);break}case`provider`:switch(t.id){case`anthropic.code_execution_20250522`:c.add(`code-execution-2025-05-22`),u.push({type:`code_execution_20250522`,name:`code_execution`,cache_control:void 0});break;case`anthropic.code_execution_20250825`:c.add(`code-execution-2025-08-25`),u.push({type:`code_execution_20250825`,name:`code_execution`});break;case`anthropic.code_execution_20260120`:u.push({type:`code_execution_20260120`,name:`code_execution`});break;case`anthropic.computer_20250124`:c.add(`computer-use-2025-01-24`),u.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case`anthropic.computer_20251124`:c.add(`computer-use-2025-11-24`),u.push({name:`computer`,type:`computer_20251124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,enable_zoom:t.args.enableZoom,cache_control:void 0});break;case`anthropic.computer_20241022`:c.add(`computer-use-2024-10-22`),u.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case`anthropic.text_editor_20250124`:c.add(`computer-use-2025-01-24`),u.push({name:`str_replace_editor`,type:`text_editor_20250124`,cache_control:void 0});break;case`anthropic.text_editor_20241022`:c.add(`computer-use-2024-10-22`),u.push({name:`str_replace_editor`,type:`text_editor_20241022`,cache_control:void 0});break;case`anthropic.text_editor_20250429`:c.add(`computer-use-2025-01-24`),u.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`,cache_control:void 0});break;case`anthropic.text_editor_20250728`:{let e=await js({value:t.args,schema:Ble});u.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters,cache_control:void 0});break}case`anthropic.bash_20250124`:c.add(`computer-use-2025-01-24`),u.push({name:`bash`,type:`bash_20250124`,cache_control:void 0});break;case`anthropic.bash_20241022`:c.add(`computer-use-2024-10-22`),u.push({name:`bash`,type:`bash_20241022`,cache_control:void 0});break;case`anthropic.memory_20250818`:c.add(`context-management-2025-06-27`),u.push({name:`memory`,type:`memory_20250818`});break;case`anthropic.web_fetch_20250910`:{c.add(`web-fetch-2025-09-10`);let e=await js({value:t.args,schema:eue});u.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case`anthropic.web_fetch_20260209`:{c.add(`code-execution-web-tools-2026-02-09`);let e=await js({value:t.args,schema:Xle});u.push({type:`web_fetch_20260209`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case`anthropic.web_search_20250305`:{let e=await js({value:t.args,schema:Kle});u.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case`anthropic.web_search_20260209`:{c.add(`code-execution-web-tools-2026-02-09`);let e=await js({value:t.args,schema:Ule});u.push({type:`web_search_20260209`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case`anthropic.tool_search_regex_20251119`:u.push({type:`tool_search_tool_regex_20251119`,name:`tool_search_tool_regex`});break;case`anthropic.tool_search_bm25_20251119`:u.push({type:`tool_search_tool_bm25_20251119`,name:`tool_search_tool_bm25`});break;case`anthropic.advisor_20260301`:{c.add(`advisor-tool-2026-03-01`);let e=await js({value:t.args,schema:Ile});u.push({type:`advisor_20260301`,name:`advisor`,model:e.model,...e.maxUses!==void 0&&{max_uses:e.maxUses},...e.caching!==void 0&&{caching:e.caching}});break}default:s.push({type:`unsupported`,feature:`provider-defined tool ${t.id}`});break}break;default:s.push({type:`unsupported`,feature:`tool ${t}`});break}if(t==null)return{tools:u,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:s,betas:c};let d=t.type;switch(d){case`auto`:return{tools:u,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:s,betas:c};case`required`:return{tools:u,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:s,betas:c};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:s,betas:c};case`tool`:return{tools:u,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:s,betas:c};default:throw new k({functionality:`tool choice type: ${d}`})}}var aue=G(()=>K(I({type:V(`code_execution_result`),stdout:j(),stderr:j(),return_code:M(),content:F(I({type:V(`code_execution_output`),file_id:j()})).optional().default([])}))),oue=Ws({id:`anthropic.code_execution_20250522`,inputSchema:G(()=>K(I({code:j()}))),outputSchema:aue}),sue=(e={})=>oue(e),cue=G(()=>K(R(`type`,[I({type:V(`code_execution_result`),stdout:j(),stderr:j(),return_code:M(),content:F(I({type:V(`code_execution_output`),file_id:j()})).optional().default([])}),I({type:V(`bash_code_execution_result`),content:F(I({type:V(`bash_code_execution_output`),file_id:j()})),stdout:j(),stderr:j(),return_code:M()}),I({type:V(`bash_code_execution_tool_result_error`),error_code:j()}),I({type:V(`text_editor_code_execution_tool_result_error`),error_code:j()}),I({type:V(`text_editor_code_execution_view_result`),content:j(),file_type:j(),num_lines:M().nullable(),start_line:M().nullable(),total_lines:M().nullable()}),I({type:V(`text_editor_code_execution_create_result`),is_file_update:N()}),I({type:V(`text_editor_code_execution_str_replace_result`),lines:F(j()).nullable(),new_lines:M().nullable(),new_start:M().nullable(),old_lines:M().nullable(),old_start:M().nullable()})]))),lue=Ws({id:`anthropic.code_execution_20250825`,inputSchema:G(()=>K(R(`type`,[I({type:V(`programmatic-tool-call`),code:j()}),I({type:V(`bash_code_execution`),command:j()}),R(`command`,[I({type:V(`text_editor_code_execution`),command:V(`view`),path:j()}),I({type:V(`text_editor_code_execution`),command:V(`create`),path:j(),file_text:j().nullish()}),I({type:V(`text_editor_code_execution`),command:V(`str_replace`),path:j(),old_str:j(),new_str:j()})])]))),outputSchema:cue,supportsDeferredResults:!0}),uue=(e={})=>lue(e),due=G(()=>K(R(`type`,[I({type:V(`code_execution_result`),stdout:j(),stderr:j(),return_code:M(),content:F(I({type:V(`code_execution_output`),file_id:j()})).optional().default([])}),I({type:V(`encrypted_code_execution_result`),encrypted_stdout:j(),stderr:j(),return_code:M(),content:F(I({type:V(`code_execution_output`),file_id:j()})).optional().default([])}),I({type:V(`bash_code_execution_result`),content:F(I({type:V(`bash_code_execution_output`),file_id:j()})),stdout:j(),stderr:j(),return_code:M()}),I({type:V(`bash_code_execution_tool_result_error`),error_code:j()}),I({type:V(`text_editor_code_execution_tool_result_error`),error_code:j()}),I({type:V(`text_editor_code_execution_view_result`),content:j(),file_type:j(),num_lines:M().nullable(),start_line:M().nullable(),total_lines:M().nullable()}),I({type:V(`text_editor_code_execution_create_result`),is_file_update:N()}),I({type:V(`text_editor_code_execution_str_replace_result`),lines:F(j()).nullable(),new_lines:M().nullable(),new_start:M().nullable(),old_lines:M().nullable(),old_start:M().nullable()})]))),fue=Ws({id:`anthropic.code_execution_20260120`,inputSchema:G(()=>K(R(`type`,[I({type:V(`programmatic-tool-call`),code:j()}),I({type:V(`bash_code_execution`),command:j()}),R(`command`,[I({type:V(`text_editor_code_execution`),command:V(`view`),path:j()}),I({type:V(`text_editor_code_execution`),command:V(`create`),path:j(),file_text:j().nullish()}),I({type:V(`text_editor_code_execution`),command:V(`str_replace`),path:j(),old_str:j(),new_str:j()})])]))),outputSchema:due,supportsDeferredResults:!0}),pue=(e={})=>fue(e),mue=G(()=>K(F(I({type:V(`tool_reference`),toolName:j()})))),hue=Ws({id:`anthropic.tool_search_regex_20251119`,inputSchema:G(()=>K(I({pattern:j(),limit:M().optional()}))),outputSchema:mue,supportsDeferredResults:!0}),gue=(e={})=>hue(e);function Hu(e){return e.includes(`claude-opus-4-8`)||e.includes(`claude-opus-4-7`)||e.includes(`claude-fable-5`)||e.includes(`claude-sonnet-5`)?{maxOutputTokens:128e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,isKnownModel:!0}:e.includes(`claude-sonnet-4-6`)||e.includes(`claude-opus-4-6`)?{maxOutputTokens:128e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-sonnet-4-5`)||e.includes(`claude-opus-4-5`)||e.includes(`claude-haiku-4-5`)?{maxOutputTokens:64e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-opus-4-1`)?{maxOutputTokens:32e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-sonnet-4-`)?{maxOutputTokens:64e3,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-opus-4-`)?{maxOutputTokens:32e3,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-3-haiku`)?{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!1}}var _ue=Hs({id:`anthropic.bash_20241022`,inputSchema:G(()=>K(I({command:j(),restart:N().optional()})))});function vue(e={}){let{execute:t,...n}=e;return _ue(t===void 0?{...n,execute:async({command:e},{abortSignal:t,experimental_sandbox:n})=>{if(!n)throw Error(`Sandbox session is not available`);return await n.run({command:e,abortSignal:t})}}:{...n,...t===null?{}:{execute:t}})}var yue=Hs({id:`anthropic.bash_20250124`,inputSchema:G(()=>K(I({command:j(),restart:N().optional()})))});function bue(e={}){let{execute:t,...n}=e;return yue(t===void 0?{...n,execute:async({command:e},{abortSignal:t,experimental_sandbox:n})=>{if(!n)throw Error(`Sandbox session is not available`);return await n.run({command:e,abortSignal:t})}}:{...n,...t===null?{}:{execute:t}})}var xue=Hs({id:`anthropic.computer_20241022`,inputSchema:G(()=>K(I({action:B([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:F(M().int()).optional(),text:j().optional()})))}),Sue=Hs({id:`anthropic.computer_20250124`,inputSchema:G(()=>K(I({action:B([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:fi([M().int(),M().int()]).optional(),duration:M().optional(),scroll_amount:M().optional(),scroll_direction:B([`up`,`down`,`left`,`right`]).optional(),start_coordinate:fi([M().int(),M().int()]).optional(),text:j().optional()})))}),Cue=Hs({id:`anthropic.computer_20251124`,inputSchema:G(()=>K(I({action:B([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`,`zoom`]),coordinate:fi([M().int(),M().int()]).optional(),duration:M().optional(),region:fi([M().int(),M().int(),M().int(),M().int()]).optional(),scroll_amount:M().optional(),scroll_direction:B([`up`,`down`,`left`,`right`]).optional(),start_coordinate:fi([M().int(),M().int()]).optional(),text:j().optional()})))}),wue=Hs({id:`anthropic.memory_20250818`,inputSchema:G(()=>K(R(`command`,[I({command:V(`view`),path:j(),view_range:fi([M(),M()]).optional()}),I({command:V(`create`),path:j(),file_text:j()}),I({command:V(`str_replace`),path:j(),old_str:j(),new_str:j()}),I({command:V(`insert`),path:j(),insert_line:M(),insert_text:j()}),I({command:V(`delete`),path:j()}),I({command:V(`rename`),old_path:j(),new_path:j()})])))}),Tue=Hs({id:`anthropic.text_editor_20241022`,inputSchema:G(()=>K(I({command:B([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:j(),file_text:j().optional(),insert_line:M().int().optional(),new_str:j().optional(),insert_text:j().optional(),old_str:j().optional(),view_range:F(M().int()).optional()})))}),Eue=Hs({id:`anthropic.text_editor_20250124`,inputSchema:G(()=>K(I({command:B([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:j(),file_text:j().optional(),insert_line:M().int().optional(),new_str:j().optional(),insert_text:j().optional(),old_str:j().optional(),view_range:F(M().int()).optional()})))}),Due=Hs({id:`anthropic.text_editor_20250429`,inputSchema:G(()=>K(I({command:B([`view`,`create`,`str_replace`,`insert`]),path:j(),file_text:j().optional(),insert_line:M().int().optional(),new_str:j().optional(),insert_text:j().optional(),old_str:j().optional(),view_range:F(M().int()).optional()})))}),Oue=G(()=>K(F(I({type:V(`tool_reference`),toolName:j()})))),kue=Ws({id:`anthropic.tool_search_bm25_20251119`,inputSchema:G(()=>K(I({query:j(),limit:M().optional()}))),outputSchema:Oue,supportsDeferredResults:!0}),Uu={advisor_20260301:zle,bash_20241022:vue,bash_20250124:bue,codeExecution_20250522:sue,codeExecution_20250825:uue,codeExecution_20260120:pue,computer_20241022:xue,computer_20250124:Sue,computer_20251124:Cue,memory_20250818:wue,textEditor_20241022:Tue,textEditor_20250124:Eue,textEditor_20250429:Due,textEditor_20250728:Hle,webFetch_20250910:rue,webFetch_20260209:$le,webSearch_20250305:Yle,webSearch_20260209:Gle,toolSearchRegex_20251119:gue,toolSearchBm25_20251119:(e={})=>kue(e)},Wu,Gu=n((()=>{Wu=e=>typeof ArrayBuffer==`function`&&e instanceof ArrayBuffer||Object.prototype.toString.call(e)===`[object ArrayBuffer]`})),Ku,qu,Ju=n((()=>{Gu(),Ku=(e,t=0,n=e.byteLength-t)=>{if(!Wu(e))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof e} (${e})`);return Buffer.from(e,t,n)},qu=(e,t)=>{if(typeof e!=`string`)throw TypeError(`The "input" argument must be of type string. Received type ${typeof e} (${e})`);return t?Buffer.from(e,t):Buffer.from(e)}})),Yu,Xu,Aue=n((()=>{Ju(),Yu=/^[A-Za-z0-9+/]*={0,2}$/,Xu=e=>{if(e.length*3%4!=0)throw TypeError(`Incorrect padding on base64 string.`);if(!Yu.exec(e))throw TypeError(`Invalid base64 string.`);let t=qu(e,`base64`);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}})),Zu,Qu=n((()=>{Ju(),Zu=e=>{let t=qu(e,`utf8`);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)}})),$u,ed=n((()=>{Ju(),Qu(),$u=e=>{let t;if(t=typeof e==`string`?Zu(e):e,typeof t!=`object`||typeof t.byteOffset!=`number`||typeof t.byteLength!=`number`)throw Error(`@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.`);return Ku(t.buffer,t.byteOffset,t.byteLength).toString(`base64`)}}));function jue(e,t,n,r){return class i extends Uint8Array{static fromString(e,n=`utf-8`){if(typeof e==`string`)return n===`base64`?i.mutate(r(e)):i.mutate(t(e));throw Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,i.prototype),e}transformToString(t=`utf-8`){return t===`base64`?n(this):e(this)}}}var Mue=n((()=>{})),td,Nue=n((()=>{Ju(),td=e=>{if(typeof e==`string`)return e;if(typeof e!=`object`||typeof e.byteOffset!=`number`||typeof e.byteLength!=`number`)throw Error(`@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.`);return Ku(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`)}}));function Pue(e){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?()=>crypto.randomUUID():()=>{let t=new Uint8Array(16);return e(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128,nd[t[0]]+nd[t[1]]+nd[t[2]]+nd[t[3]]+`-`+nd[t[4]]+nd[t[5]]+`-`+nd[t[6]]+nd[t[7]]+`-`+nd[t[8]]+nd[t[9]]+`-`+nd[t[10]]+nd[t[11]]+nd[t[12]]+nd[t[13]]+nd[t[14]]+nd[t[15]]}}var nd,Fue=n((()=>{nd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`))})),rd,Iue=n((()=>{rd=(e,t,n=e=>e)=>e})),id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd,gd,_d,vd,yd,bd,xd,Sd,Cd,wd,Td,Ed,Dd,Od,kd,Ad,jd,Md,Nd,Pd,Fd,Id,Ld=n((()=>{id=e=>{switch(e){case`true`:return!0;case`false`:return!1;default:throw Error(`Unable to parse boolean value "${e}"`)}},ad=e=>{if(e!=null){if(typeof e==`number`){if((e===0||e===1)&&Id.warn(Fd(`Expected boolean, got ${typeof e}: ${e}`)),e===0)return!1;if(e===1)return!0}if(typeof e==`string`){let t=e.toLowerCase();if((t===`false`||t===`true`)&&Id.warn(Fd(`Expected boolean, got ${typeof e}: ${e}`)),t===`false`)return!1;if(t===`true`)return!0}if(typeof e==`boolean`)return e;throw TypeError(`Expected boolean, got ${typeof e}: ${e}`)}},od=e=>{if(e!=null){if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&Id.warn(Fd(`Expected number but observed string: ${e}`)),t}if(typeof e==`number`)return e;throw TypeError(`Expected number, got ${typeof e}: ${e}`)}},sd=Math.ceil(2**127*(2-2**-23)),cd=e=>{let t=od(e);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0&&Math.abs(t)>sd)throw TypeError(`Expected 32-bit float, got ${e}`);return t},ld=e=>{if(e!=null){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw TypeError(`Expected integer, got ${typeof e}: ${e}`)}},ud=ld,dd=e=>md(e,32),fd=e=>md(e,16),pd=e=>md(e,8),md=(e,t)=>{let n=ld(e);if(n!==void 0&&hd(n,t)!==n)throw TypeError(`Expected ${t}-bit integer, got ${e}`);return n},hd=(e,t)=>{switch(t){case 32:return Int32Array.of(e)[0];case 16:return Int16Array.of(e)[0];case 8:return Int8Array.of(e)[0]}},gd=(e,t)=>{if(e==null)throw TypeError(t?`Expected a non-null value for ${t}`:`Expected a non-null value`);return e},_d=e=>{if(e!=null){if(typeof e==`object`&&!Array.isArray(e))return e;throw TypeError(`Expected object, got ${Array.isArray(e)?`array`:typeof e}: ${e}`)}},vd=e=>{if(e!=null){if(typeof e==`string`)return e;if([`boolean`,`number`,`bigint`].includes(typeof e))return Id.warn(Fd(`Expected string, got ${typeof e}: ${e}`)),String(e);throw TypeError(`Expected string, got ${typeof e}: ${e}`)}},yd=e=>{if(e==null)return;let t=_d(e),n=[];for(let e in t)t[e]!=null&&n.push(e);if(n.length===0)throw TypeError(`Unions must have exactly one non-null member. None were found.`);if(n.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${n} were not null.`);return t},bd=e=>od(typeof e==`string`?wd(e):e),xd=bd,Sd=e=>cd(typeof e==`string`?wd(e):e),Cd=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,wd=e=>{let t=e.match(Cd);if(t===null||t[0].length!==e.length)throw TypeError(`Expected real number, got implicit NaN`);return parseFloat(e)},Td=e=>typeof e==`string`?kd(e):od(e),Ed=Td,Dd=Td,Od=e=>typeof e==`string`?kd(e):cd(e),kd=e=>{switch(e){case`NaN`:return NaN;case`Infinity`:return 1/0;case`-Infinity`:return-1/0;default:throw Error(`Unable to parse float value: ${e}`)}},Ad=e=>ld(typeof e==`string`?wd(e):e),jd=Ad,Md=e=>dd(typeof e==`string`?wd(e):e),Nd=e=>fd(typeof e==`string`?wd(e):e),Pd=e=>pd(typeof e==`string`?wd(e):e),Fd=e=>String(TypeError(e).stack||e).split(`
|
|
80
|
+
]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function es(e,t){let n={type:`object`,additionalProperties:vs(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===U.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Yo(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===U.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===U.ZodBranded&&e.keyType._def.type._def.typeName===U.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Go(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Gae(e,t){return t.mapStrategy===`record`?es(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[vs(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Wo(),vs(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Wo()],minItems:2,maxItems:2}}}function Kae(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function qae(){return{not:Wo()}}function Jae(){return{type:`null`}}var ts={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Yae(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in ts&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=ts[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return ns(e,t)}var ns=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>vs(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function rs(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[ts[e.innerType._def.typeName],`null`]};let n=vs(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function is(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function as(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=ss(a),s=vs(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=os(e,t);return a!==void 0&&(n.additionalProperties=a),n}function os(e,t){if(e.catchall._def.typeName!==`ZodNever`)return vs(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function ss(e){try{return e.isOptional()}catch{return!0}}var cs=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return vs(e.innerType._def,t);let n=vs(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:Wo()},n]}:Wo()},ls=(e,t)=>{if(t.pipeStrategy===`input`)return vs(e.in._def,t);if(t.pipeStrategy===`output`)return vs(e.out._def,t);let n=vs(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,vs(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function us(e,t){return vs(e.type._def,t)}function ds(e,t){let n={type:`array`,uniqueItems:!0,items:vs(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function fs(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>vs(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:vs(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>vs(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function ps(){return{not:Wo()}}function ms(){return Wo()}var hs=(e,t)=>vs(e.innerType._def,t),gs=(e,t,n)=>{switch(t){case U.ZodString:return Yo(e,n);case U.ZodNumber:return is(e);case U.ZodObject:return as(e,n);case U.ZodBigInt:return Nae(e);case U.ZodBoolean:return Pae();case U.ZodDate:return Ko(e,n);case U.ZodUndefined:return ps();case U.ZodNull:return Jae();case U.ZodArray:return Mae(e,n);case U.ZodUnion:case U.ZodDiscriminatedUnion:return Yae(e,n);case U.ZodIntersection:return Vae(e,n);case U.ZodTuple:return fs(e,n);case U.ZodRecord:return es(e,n);case U.ZodLiteral:return Hae(e);case U.ZodEnum:return zae(e);case U.ZodNativeEnum:return Kae(e);case U.ZodNullable:return rs(e,n);case U.ZodOptional:return cs(e,n);case U.ZodMap:return Gae(e,n);case U.ZodSet:return ds(e,n);case U.ZodLazy:return()=>e.getter()._def;case U.ZodPromise:return us(e,n);case U.ZodNaN:case U.ZodNever:return qae();case U.ZodEffects:return Rae(e,n);case U.ZodAny:return Wo();case U.ZodUnknown:return ms();case U.ZodDefault:return Lae(e,n);case U.ZodBranded:return Go(e,n);case U.ZodReadonly:return hs(e,n);case U.ZodCatch:return Fae(e,n);case U.ZodPipeline:return ls(e,n);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(e=>void 0)(t)}},_s=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function vs(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==Aae)return i}if(r&&!n){let e=ys(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=gs(e,e.typeName,t),o=typeof a==`function`?vs(a(),t):a;if(o&&bs(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var ys=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:_s(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Wo()):t.$refStrategy===`seen`?Wo():void 0}},bs=(e,t,n)=>(e.description&&(n.description=e.description),n),xs=e=>{let t=jae(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Ss=(e,t)=>{let n=xs(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:vs(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Wo()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=vs(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Wo(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},Cs=Symbol.for(`vercel.ai.schema`);function G(e){let t;return()=>(t??=e(),t)}function ws(e,{validate:t}={}){return{[Cs]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function Ts(e){return typeof e==`object`&&!!e&&Cs in e&&e[Cs]===!0&&`jsonSchema`in e&&`validate`in e}function Es(e){return e==null?ws({type:`object`,properties:{},additionalProperties:!1}):Ts(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?K(e):Ds(e):e()}function Ds(e){return ws(()=>Vo(e[`~standard`].jsonSchema.input({target:`draft-07`})),{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new ht({value:t,cause:n.issues})}}})}function Os(e,t){let n=t?.useReferences??!1;return ws(()=>Ss(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function ks(e,t){let n=t?.useReferences??!1;return ws(()=>Vo(Ur(e,{target:`draft-7`,io:`input`,reused:n?`ref`:`inline`})),{validate:async t=>{let n=await Kr(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function As(e){return`_zod`in e}function K(e,t){return As(e)?ks(e,t):Os(e,t)}async function js({value:e,schema:t,context:n}){let r=await Ms({value:e,schema:t,context:n});if(!r.success)throw ht.wrap({value:e,cause:r.error,context:n});return r.value}async function Ms({value:e,schema:t,context:n}){let r=Es(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let t=await r.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:ht.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:ht.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function Ns({text:e,schema:t}){try{let n=Bo(e);return t==null?n:await js({value:n,schema:t})}catch(t){throw Ne.isInstance(t)||ht.isInstance(t)?t:new Ne({text:e,cause:t})}}async function Ps({text:e,schema:t}){try{let n=Bo(e);return t==null?{success:!0,value:n,rawValue:n}:await Ms({value:n,schema:t})}catch(t){return{success:!1,error:Ne.isInstance(t)?t:new Ne({text:e,cause:t}),rawValue:void 0}}}function Fs({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Ba).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await Ps({text:e,schema:t}))}}))}async function q({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Ms({value:t[e],schema:n});if(!r.success)throw new he({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Is=()=>globalThis.fetch,Ls=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>await zs({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Rs=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>await zs({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),zs=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Is()})=>{try{let s=await o(e,{method:`POST`,headers:Oo(t,`ai-sdk/provider-utils/${ko}`,Eo()),body:n.content,signal:a}),c=So(s);if(!s.ok){let t;try{t=await i({response:s,url:e,requestBodyValues:n.values})}catch(t){throw wo(t)||E.isInstance(t)?t:new E({message:`Failed to process error response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:s,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(wo(t)||E.isInstance(t))?t:new E({message:`Failed to process successful response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(t){throw To({error:t,url:e,requestBodyValues:n.values})}};function Bs(e){return e}function Vs(e){return{...e,type:`dynamic`}}function Hs({id:e,inputSchema:t}){return({execute:n,outputSchema:r,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Bs({type:`provider`,isProviderExecuted:!1,id:e,args:l,inputSchema:t,outputSchema:r,execute:n,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Us({id:e,inputSchema:t,outputSchema:n}){return({execute:r,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Bs({type:`provider`,isProviderExecuted:!1,id:e,args:l,inputSchema:t,outputSchema:n,execute:r,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Ws({id:e,inputSchema:t,outputSchema:n,supportsDeferredResults:r}){return({onInputStart:i,onInputDelta:a,onInputAvailable:o,...s})=>Bs({type:`provider`,isProviderExecuted:!0,id:e,args:s,inputSchema:t,outputSchema:n,onInputStart:i,onInputDelta:a,onInputAvailable:o,supportsDeferredResults:r})}async function Gs(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}function Ks({part:e}){if(so(e.mediaType))return e.mediaType;if(e.data.type===`data`){let t=sae({data:e.data.data,topLevelType:oo(e.mediaType)});if(t)return t;throw new k({functionality:`file of media type "${e.mediaType}" must specify subtype since it could not be auto-detected`})}throw new k({functionality:`file of media type "${e.mediaType}" must specify subtype since it is not passed as inline bytes`})}function qs({reference:e,provider:t}){let n=e[t];if(n!=null)return n;throw new rt({provider:t,reference:e})}var Xae=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r,shouldRetry:i,getDelayInMs:a=({exponentialBackoffDelay:e})=>e,createRetryError:o=({message:e})=>Error(e)})=>async s=>Js(s,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r,shouldRetry:i,getDelayInMs:a,createRetryError:o});async function Js(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:i,shouldRetry:a,getDelayInMs:o,createRetryError:s},c=[]){try{return await e()}catch(l){if(wo(l)||t===0)throw l;let u=le(l),d=[...c,l],f=d.length;if(f>t)throw s({message:`Failed after ${f} attempts. Last error: ${u}`,reason:`maxRetriesExceeded`,errors:d});if(await a(l)&&f<=t)return await Ua(o({error:l,exponentialBackoffDelay:n}),{abortSignal:i}),Js(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:i,shouldRetry:a,getDelayInMs:o,createRetryError:s},d);throw f===1?l:s({message:`Failed after ${f} attempts with non-retryable error: '${u}'`,reason:`errorNotRetryable`,errors:d})}}var Zae=new TextDecoder;async function Ys({response:e,url:t}){return Zae.decode(await bo({response:e,url:t}))}var Xs=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await Ys({response:r,url:i}),s=So(r);if(o.trim()===``)return{responseHeaders:s,value:new E({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})};try{let c=await Ns({text:o,schema:e});return{responseHeaders:s,value:new E({message:t(c),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,data:c,isRetryable:n?.(r,c)})}}catch{return{responseHeaders:s,value:new E({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})}}},Zs=e=>async({response:t})=>{let n=So(t);if(t.body==null)throw new O({});return{responseHeaders:n,value:Fs({stream:t.body,schema:e})}},Qs=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await Ys({response:t,url:n}),a=await Ps({text:i,schema:e}),o=So(t);if(!a.success)throw new E({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},$s=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=So(e);if(!e.body)throw new E({message:`Response body is empty`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new E({message:`Failed to read response as array buffer`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},ec=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=So(e),i=await Ys({response:e,url:t});return{responseHeaders:r,value:new E({message:e.statusText,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:i})}};function tc(e){if(e==null)return!0;let t=typeof e;return t===`string`||t===`number`||t===`boolean`?!0:t===`function`||t===`symbol`||t===`bigint`?!1:Array.isArray(e)?e.every(tc):Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(tc)}function nc(e){let t={};for(let[n,r]of Object.entries(e.config))if(n===`headers`){let e=Qae(r);tc(e)&&(t[n]=e)}else tc(r)&&(t[n]=r);return{modelId:e.modelId,config:t}}function Qae(e){let t=e;if(typeof e==`function`&&(t=e()),t instanceof Promise)throw Error(`Promise returned from resolveSync`);return t}var rc=class{constructor(e,t={}){this.toolCalls=[],this.controller=e,this._generateId=t.generateId??Co,this.typeValidation=t.typeValidation??`none`,this.extractMetadata=t.extractMetadata,this.buildToolCallProviderMetadata=t.buildToolCallProviderMetadata}processDelta(e){let t=e.index??this.toolCalls.length;this.toolCalls[t]==null?this.processNewToolCall(t,e):this.processExistingToolCall(t,e)}flush(){for(let e of this.toolCalls)e.hasFinished||this.finishToolCall(e)}processNewToolCall(e,t){if(this.typeValidation===`required`){if(t.type!==`function`)throw new De({data:t,message:`Expected 'function' type.`})}else if(this.typeValidation===`if-present`&&t.type!=null&&t.type!==`function`)throw new De({data:t,message:`Expected 'function' type.`});if(t.id==null)throw new De({data:t,message:`Expected 'id' to be a string.`});if(t.function?.name==null)throw new De({data:t,message:`Expected 'function.name' to be a string.`});this.controller.enqueue({type:`tool-input-start`,id:t.id,toolName:t.function.name});let n=this.extractMetadata?.call(this,t);this.toolCalls[e]={id:t.id,type:`function`,function:{name:t.function.name,arguments:t.function.arguments??``},hasFinished:!1,metadata:n};let r=this.toolCalls[e];r.function.arguments.length>0&&this.controller.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments})}processExistingToolCall(e,t){let n=this.toolCalls[e];n.hasFinished||t.function?.arguments!=null&&(n.function.arguments+=t.function.arguments,this.controller.enqueue({type:`tool-input-delta`,id:n.id,delta:t.function.arguments}))}finishToolCall(e){this.controller.enqueue({type:`tool-input-end`,id:e.id});let t=this.buildToolCallProviderMetadata?.call(this,e.metadata);this.controller.enqueue({type:`tool-call`,toolCallId:e.id??this._generateId(),toolName:e.function.name,input:e.function.arguments,...t?{providerMetadata:t}:{}}),e.hasFinished=!0}};function ic(e){let t=e.indexOf(`.`);return t===-1?e:e.slice(0,t)}function ac(e){if(e?.trim()===``)throw new he({argument:`baseURL`,message:`baseURL must be a non-empty string.`});return e}function oc(e){return e?.replace(/\/$/,``)}let sc;sc=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function $ae(e){return(await sc).getRandomValues(new Uint8Array(e))}async function eoe(e){let t=``;for(;t.length<e;){let n=await $ae(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function toe(e){return await eoe(e)}async function noe(e){let t=await(await sc).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function cc(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await toe(e);return{code_verifier:t,code_challenge:await noe(t)}}var lc=`2025-11-25`,roe=[lc,`2025-06-18`,`2025-03-26`,`2024-11-05`],ioe=_i(z(j(),P())),aoe=li({name:j(),version:j(),title:_i(j())}),uc=li({_meta:_i(I({}).loose())}),dc=uc,fc=I({method:j(),params:_i(uc)}),pc=I({applyDefaults:_i(N())}).loose(),ooe=li({experimental:_i(I({}).loose()),logging:_i(I({}).loose()),completions:_i(I({}).loose()),prompts:_i(li({listChanged:_i(N())})),resources:_i(li({subscribe:_i(N()),listChanged:_i(N())})),tools:_i(li({listChanged:_i(N())})),elicitation:_i(pc)});I({elicitation:_i(pc)}).loose();var mc=dc.extend({protocolVersion:j(),capabilities:ooe,serverInfo:aoe,instructions:_i(j())}),hc=dc.extend({nextCursor:_i(j())}),soe=I({name:j(),title:_i(j()),description:_i(j()),inputSchema:I({type:V(`object`),properties:_i(I({}).loose())}).loose(),outputSchema:_i(I({}).loose()),annotations:_i(I({title:_i(j())}).loose()),_meta:ioe}).loose(),coe=hc.extend({tools:F(soe)}),gc=I({type:V(`text`),text:j()}).loose(),_c=I({type:V(`image`),data:ni(),mimeType:j()}).loose(),loe=I({uri:j(),name:j(),title:_i(j()),description:_i(j()),mimeType:_i(j()),size:_i(M())}).loose(),uoe=hc.extend({resources:F(loe)}),vc=I({uri:j(),name:_i(j()),title:_i(j()),mimeType:_i(j())}).loose(),yc=vc.extend({text:j()}),bc=vc.extend({blob:ni()}),xc=I({type:V(`resource`),resource:L([yc,bc])}).loose(),Sc=I({type:V(`resource_link`),uri:j(),name:j(),description:_i(j()),mimeType:_i(j())}).loose(),doe=dc.extend({content:F(L([gc,_c,xc,Sc])),structuredContent:_i(P()),isError:N().default(!1).optional()}).or(dc.extend({toolResult:P()})),foe=I({uriTemplate:j(),name:j(),title:_i(j()),description:_i(j()),mimeType:_i(j())}).loose(),poe=dc.extend({resourceTemplates:F(foe)}),moe=dc.extend({contents:F(L([yc,bc]))}),hoe=I({type:V(`ref/prompt`),name:j()}).loose(),goe=I({type:V(`ref/resource`),uri:j()}).loose(),_oe=I({name:j(),value:j()}).loose();uc.extend({ref:L([hoe,goe]),argument:_oe,context:_i(I({arguments:z(j(),j())}).loose())});var voe=dc.extend({completion:I({values:F(j()).max(100),total:_i(M().int()),hasMore:_i(N())}).loose()}),yoe=I({name:j(),description:_i(j()),required:_i(N())}).loose(),boe=I({name:j(),title:_i(j()),description:_i(j()),arguments:_i(F(yoe))}).loose(),xoe=hc.extend({prompts:F(boe)}),Soe=I({role:L([V(`user`),V(`assistant`)]),content:L([gc,_c,xc,Sc])}).loose(),Coe=dc.extend({description:_i(j()),messages:F(Soe)}),woe=uc.extend({message:j(),requestedSchema:P()}),Cc=fc.extend({method:V(`elicitation/create`),params:woe}),Toe=dc.extend({action:L([V(`accept`),V(`decline`),V(`cancel`)]),content:_i(z(j(),P()))}),wc=`2.0`,Eoe=I({jsonrpc:V(wc),id:L([j(),M().int()])}).merge(fc).strict(),Doe=I({jsonrpc:V(wc),id:L([j(),M().int()]),result:dc}).strict(),Ooe=I({jsonrpc:V(wc),id:L([j(),M().int()]),error:I({code:M().int(),message:j(),data:_i(P())})}).strict(),koe=L([Eoe,I({jsonrpc:V(wc)}).merge(I({method:j(),params:_i(uc)})).strict(),Doe,Ooe]);function Tc(e){return koe.parse(e)}async function Ec(e){return Tc(await Ns({text:e}))}var Dc=`vercel.ai.error.AI_MCPClientError`,Aoe=Symbol.for(Dc),Oc,kc,Ac=class extends (kc=w,Oc=Aoe,kc){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[Oc]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(e){return w.hasMarker(e,Dc)}},jc=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,Mc=j().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ti.custom,message:`URL must be parseable`,fatal:!0}),wt}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),Nc=I({access_token:j(),id_token:j().optional(),token_type:j(),expires_in:M().optional(),scope:j().optional(),refresh_token:j().optional(),authorization_server:Mc.optional(),token_endpoint:Mc.optional()}).strip(),joe=li({resource:j().url(),authorization_servers:F(Mc).optional(),jwks_uri:j().url().optional(),scopes_supported:F(j()).optional(),bearer_methods_supported:F(j()).optional(),resource_signing_alg_values_supported:F(j()).optional(),resource_name:j().optional(),resource_documentation:j().optional(),resource_policy_uri:j().url().optional(),resource_tos_uri:j().url().optional(),tls_client_certificate_bound_access_tokens:N().optional(),authorization_details_types_supported:F(j()).optional(),dpop_signing_alg_values_supported:F(j()).optional(),dpop_bound_access_tokens_required:N().optional()}),Pc=li({issuer:j(),authorization_endpoint:Mc,token_endpoint:Mc,registration_endpoint:Mc.optional(),scopes_supported:F(j()).optional(),response_types_supported:F(j()),grant_types_supported:F(j()).optional(),code_challenge_methods_supported:F(j()),token_endpoint_auth_methods_supported:F(j()).optional(),token_endpoint_auth_signing_alg_values_supported:F(j()).optional()}),Moe=li({issuer:j(),authorization_endpoint:Mc,token_endpoint:Mc,userinfo_endpoint:Mc.optional(),jwks_uri:Mc,registration_endpoint:Mc.optional(),scopes_supported:F(j()).optional(),response_types_supported:F(j()),grant_types_supported:F(j()).optional(),subject_types_supported:F(j()),id_token_signing_alg_values_supported:F(j()),claims_supported:F(j()).optional(),token_endpoint_auth_methods_supported:F(j()).optional()}).merge(Pc.pick({code_challenge_methods_supported:!0})),Noe=I({client_id:j(),client_secret:j().optional(),client_id_issued_at:M().optional(),client_secret_expires_at:M().optional(),authorization_server:Mc.optional(),token_endpoint:Mc.optional()}).strip(),Poe=I({redirect_uris:F(Mc),token_endpoint_auth_method:j().optional(),grant_types:F(j()).optional(),response_types:F(j()).optional(),client_name:j().optional(),client_uri:Mc.optional(),logo_uri:Mc.optional(),scope:j().optional(),contacts:F(j()).optional(),tos_uri:Mc.optional(),policy_uri:j().optional(),jwks_uri:Mc.optional(),jwks:si().optional(),software_id:j().optional(),software_version:j().optional(),software_statement:j().optional()}).strip(),Foe=I({error:j(),error_description:j().optional(),error_uri:j().optional()}),Ioe=Poe.merge(Noe),Fc=`vercel.ai.error.AI_MCPClientOAuthError`,Loe=Symbol.for(Fc),Ic,Lc,Rc=class extends (Lc=w,Ic=Loe,Lc){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[Ic]=!0}static isInstance(e){return w.hasMarker(e,Fc)}},zc=class extends Rc{};zc.errorCode=`server_error`;var Bc=class extends Rc{};Bc.errorCode=`invalid_client`;var Vc=class extends Rc{};Vc.errorCode=`invalid_grant`;var Hc=class extends Rc{};Hc.errorCode=`unauthorized_client`;var Roe={[zc.errorCode]:zc,[Bc.errorCode]:Bc,[Vc.errorCode]:Vc,[Hc.errorCode]:Hc};function zoe(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Uc(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function Boe({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var Wc=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function Gc(e){return new URL(e).href}function Voe(e,t){return{authorizationServerUrl:Gc(e),tokenEndpoint:Gc(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function Kc(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function qc(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Jc(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:Gc(e.authorization_server),tokenEndpoint:Gc(e.token_endpoint)}}async function Yc({provider:e,clientInformation:t,tokens:n}){let r=Jc(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:Gc(i.authorizationServerUrl),tokenEndpoint:Gc(i.tokenEndpoint)}:Jc(t)}async function Hoe({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(qc(t,n)),!0):!1}function Uoe(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new Rc({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function Xc({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new Rc({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function Zc(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function Woe(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Qc(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Qc(e,void 0,n):void 0;throw r}}async function $c(e,t,n=fetch){return await Qc(e,{"MCP-Protocol-Version":t},n)}function Goe(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Koe(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??lc,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Woe(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await $c(o,a,n);return!r?.metadataUrl&&Goe(s,i.pathname)&&(s=await $c(new URL(`/.well-known/${t}`,i),a,n)),s}async function qoe(e,t,n=fetch){let r=await Koe(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return joe.parse(await r.json())}function Joe(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function el(e,t){if(e.issuer!==t)throw new Rc({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Yoe(e,{fetchFn:t=fetch,protocolVersion:n=lc}={}){let r={"MCP-Protocol-Version":n},i=Joe(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await Qc(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=Pc.parse(await i.json());return el(e,a),e}else{let t=Moe.parse(await i.json());if(el(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Xoe(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await cc(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,Uc(o)),{authorizationUrl:l,codeVerifier:d}}function tl(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function nl(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Zoe(i,a,n);return;case`client_secret_post`:Qoe(i,a,r);return;case`none`:$oe(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Zoe(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Qoe(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function $oe(e,t){t.set(`client_id`,e)}async function rl(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=Foe.parse(await Ns({text:n}));return new(Roe[e]||zc)({message:t||``,cause:r})}catch(e){return new zc({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function ese(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):nl(tl(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,Uc(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await rl(p);return Nc.parse(await p.json())}async function tse(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):nl(tl(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,Uc(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await rl(d);return Nc.parse({refresh_token:r,...await d.json()})}async function nse(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await rl(a);return Ioe.parse(await a.json())}async function il(e,t){try{return await al(e,t)}catch(n){if(n instanceof Bc||n instanceof Hc)return await e.invalidateCredentials?.call(e,`all`),await al(e,t);if(n instanceof Vc)return await e.invalidateCredentials?.call(e,`tokens`),await al(e,t);throw n}}async function rse(e,t,n){let r=zoe(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Boe({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function al(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;Uoe(t,a);try{s=await qoe(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await rse(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await Yoe(c,{fetchFn:o}),d=Voe(c,u),f=await Promise.resolve(e.clientInformation());if(!f){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);f=qc(await nse(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o}),d),await e.saveClientInformation(f)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await Yc({provider:e,clientInformation:f});if(!t)throw new Rc({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});Xc({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await ese(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(Kc(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await Yc({provider:e,clientInformation:f,tokens:p});t?Xc({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await tse(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(Kc(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof Rc)||e instanceof zc))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:h,codeVerifier:g}=await Xoe(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await Hoe({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new Rc({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(h),`REDIRECT`}function ise(e){return e===void 0||e===`message`}var ase=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??lc};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return Oo(t,`ai-sdk/${jc}`,Eo())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Zc(c);try{if(await il(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new Wc;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new Ac({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Ba).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new Ac({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new Ac({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(ise(s))try{let e=await Ec(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new Ac({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new Ac({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Zc(c);try{if(await il(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new Wc;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new Ac({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}};function ol(e){return e===void 0||e===`message`}var ose=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??lc};if(t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return Oo(n,`ai-sdk/${jc}`,Eo())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e){return this.authProvider?(this.authPromise||=il(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new Ac({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.startInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.terminateSessionOnClose&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({base:{}});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c=`method`in e&&e.method===`initialize`,l=c?void 0:this.sessionId,u={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`},includeSessionId:!c}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},d=await this.fetchFn(this.url.href,u);if(this.applySessionIdFromResponse(d),d.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Zc(d);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new Wc}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(d.status===202){this.inboundSseConnection||this.startInboundSse();return}if(!d.ok){let e=await d.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${d.status}): ${e}`;d.status===404&&(l?(this.expireSessionId(l),t+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new Ac({message:t,statusCode:d.status,url:this.url.href,responseBody:e??void 0});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let f=d.headers.get(`content-type`)||``;if(f.includes(`application/json`)){let e=await d.json(),t=Array.isArray(e)?e.map(e=>Tc(e)):[Tc(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(f.includes(`text/event-stream`)){if(!d.body){let e=new Ac({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:d.status,url:this.url.href});throw(o=this.onerror)==null||o.call(this,e),e}let e=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new Ba).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(ol(a))try{let e=await Ec(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new Ac({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)});return}let p=new Ac({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`,statusCode:d.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,p),p}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new Ac({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.openInboundSse(e,t).catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=this.sessionId,o=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(s),s.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=Zc(s);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new Wc;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){s.status===404&&a&&this.expireSessionId(a);let e=new Ac({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new Ba).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),ol(i))try{let t=await Ec(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new Ac({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{c.cancel().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,l().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||((t=this.onerror)==null||t.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function sse(e){switch(e.type){case`sse`:return new ase(e);case`http`:return new ose(e);default:throw new Ac({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function cse(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var lse=`text/html;profile=mcp-app`,use=`ui/resourceUri`;function dse(e){let t=e?.ui;return St(t)?t:void 0}function fse(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function pse(e){let t=dse(e._meta),n=t?.resourceUri??e._meta?.[use],r=fse(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}var mse=`1.0.0`,hse=0,gse=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function _se(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function vse(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function yse(e){let t=_se(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(Ac.isInstance(e)&&e.code!=null)return!1;let n=vse(e);return n!=null&&gse.includes(n)}function bse(e){if(e==null)return hse;if(!Number.isInteger(e))throw new Ac({message:`maxRetries must be an integer`});if(e<0)throw new Ac({message:`maxRetries must be >= 0`});return e}function sl({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function xse(e){let t=new Sse(e);return await t.init(),t}var Sse=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=mse,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:lc,capabilities:{},serverInfo:this._serverInfo},this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=bse(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,cse(e)?this.transport=e:this.transport=sse(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new Ac({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){try{if(await this.transport.start(),this.isClosed=!1,this.initialInitializeResult){let e=mc.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}let e=await this.request({request:{method:`initialize`,params:{protocolVersion:lc,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:mc});if(e===void 0)throw new Ac({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}applyInitializeResult(e){if(!roe.includes(e.protocolVersion))throw new Ac({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this._initializeResult=e,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new Ac({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new Ac({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new Ac({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new Ac({message:`Server does not support prompts`});break;default:throw new Ac({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new Ac({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{i(new Ac({message:`Request was aborted`,cause:a?.reason}))},l=()=>{this.responseHandlers.delete(o),a?.removeEventListener(`abort`,d)},u=e=>{l(),i(e)},d=()=>{l(),c()};this.responseHandlers.set(o,e=>{if(a?.aborted)return l(),c();if(e instanceof Error)return u(e);try{let n=t.parse(e.result);l(),r(n)}catch(e){let t=new Ac({message:`Failed to parse server response`,cause:e});u(t)}}),a?.addEventListener(`abort`,d,{once:!0}),this.transport.send(s).catch(e=>{u(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:coe,options:t})}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():Xae({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:yse,createRetryError:({message:e,errors:t})=>new Ac({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:doe,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:uoe,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:moe,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:poe,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:xoe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Coe,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:voe,options:e})}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=pse({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...d?.resourceUri==null?{}:{app:{...d,mimeType:lse}}},p=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await l.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||u==null?i:l.extractStructuredContent(i,u,r)};n[r]={...t===`automatic`?Vs({description:a,title:e,metadata:f,inputSchema:ws({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:sl}):Bs({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:sl}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await Ms({value:e.structuredContent,schema:Es(t)});if(!r.success)throw new Ac({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await Ps({text:r.text,schema:t});if(!e.success)throw new Ac({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new Ac({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==Cc)throw new Ac({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=Cc.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=Toe.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new Ac({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new Ac({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new Ac({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function cl(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Cse(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...cl(t.headers),...cl(r.headers)}:t.headers}):e}const ll=Sie(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),ul=L([j(),M().int()]),dl=j();li({ttl:M().optional(),pollInterval:M().optional()});const wse=I({ttl:M().optional()}),Tse=I({taskId:j()}),fl=li({progressToken:ul.optional(),"io.modelcontextprotocol/related-task":Tse.optional()}),pl=I({_meta:fl.optional()}),ml=pl.extend({task:wse.optional()}),hl=I({method:j(),params:pl.loose().optional()}),gl=I({_meta:fl.optional()}),_l=I({method:j(),params:gl.loose().optional()}),vl=li({_meta:fl.optional()}),yl=L([j(),M().int()]),bl=I({jsonrpc:V(`2.0`),id:yl,...hl.shape}).strict(),Ese=e=>bl.safeParse(e).success,Dse=I({jsonrpc:V(`2.0`),..._l.shape}).strict(),xl=I({jsonrpc:V(`2.0`),id:yl,result:vl}).strict(),Ose=e=>xl.safeParse(e).success;var kse;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(kse||={});const Sl=I({jsonrpc:V(`2.0`),id:yl.optional(),error:I({code:M().int(),message:j(),data:P().optional()})}).strict(),Cl=L([bl,Dse,xl,Sl]);L([xl,Sl]);const wl=vl.strict(),Ase=gl.extend({requestId:yl.optional(),reason:j().optional()}),Tl=_l.extend({method:V(`notifications/cancelled`),params:Ase}),El=I({icons:F(I({src:j(),mimeType:j().optional(),sizes:F(j()).optional(),theme:B([`light`,`dark`]).optional()})).optional()}),Dl=I({name:j(),title:j().optional()}),Ol=Dl.extend({...Dl.shape,...El.shape,version:j(),websiteUrl:j().optional(),description:j().optional()}),jse=wi(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,di(I({form:di(I({applyDefaults:N().optional()}),z(j(),P())).optional(),url:ll.optional()}),z(j(),P()).optional())),Mse=li({list:ll.optional(),cancel:ll.optional(),requests:li({sampling:li({createMessage:ll.optional()}).optional(),elicitation:li({create:ll.optional()}).optional()}).optional()}),Nse=li({list:ll.optional(),cancel:ll.optional(),requests:li({tools:li({call:ll.optional()}).optional()}).optional()}),Pse=I({experimental:z(j(),ll).optional(),sampling:I({context:ll.optional(),tools:ll.optional()}).optional(),elicitation:jse.optional(),roots:I({listChanged:N().optional()}).optional(),tasks:Mse.optional(),extensions:z(j(),ll).optional()}),Fse=pl.extend({protocolVersion:j(),capabilities:Pse,clientInfo:Ol}),Ise=hl.extend({method:V(`initialize`),params:Fse}),Lse=I({experimental:z(j(),ll).optional(),logging:ll.optional(),completions:ll.optional(),prompts:I({listChanged:N().optional()}).optional(),resources:I({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:I({listChanged:N().optional()}).optional(),tasks:Nse.optional(),extensions:z(j(),ll).optional()}),Rse=vl.extend({protocolVersion:j(),capabilities:Lse,serverInfo:Ol,instructions:j().optional()}),kl=_l.extend({method:V(`notifications/initialized`),params:gl.optional()}),zse=e=>kl.safeParse(e).success,Al=hl.extend({method:V(`ping`),params:pl.optional()}),Bse=I({progress:M(),total:_i(M()),message:_i(j())}),Vse=I({...gl.shape,...Bse.shape,progressToken:ul}),jl=_l.extend({method:V(`notifications/progress`),params:Vse}),Hse=pl.extend({cursor:dl.optional()}),Ml=hl.extend({params:Hse.optional()}),Nl=vl.extend({nextCursor:dl.optional()}),Use=B([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Pl=I({taskId:j(),status:Use,ttl:L([M(),oi()]),createdAt:j(),lastUpdatedAt:j(),pollInterval:_i(M()),statusMessage:_i(j())}),Fl=vl.extend({task:Pl}),Wse=gl.merge(Pl),Il=_l.extend({method:V(`notifications/tasks/status`),params:Wse}),Ll=hl.extend({method:V(`tasks/get`),params:pl.extend({taskId:j()})}),Rl=vl.merge(Pl),zl=hl.extend({method:V(`tasks/result`),params:pl.extend({taskId:j()})});vl.loose();const Bl=Ml.extend({method:V(`tasks/list`)}),Vl=Nl.extend({tasks:F(Pl)}),Hl=hl.extend({method:V(`tasks/cancel`),params:pl.extend({taskId:j()})});vl.merge(Pl);const Ul=I({uri:j(),mimeType:_i(j()),_meta:z(j(),P()).optional()}),Wl=Ul.extend({text:j()}),Gl=j().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Kl=Ul.extend({blob:Gl}),ql=B([`user`,`assistant`]),Jl=I({audience:F(ql).optional(),priority:M().min(0).max(1).optional(),lastModified:Wr({offset:!0}).optional()}),Yl=I({...Dl.shape,...El.shape,uri:j(),description:_i(j()),mimeType:_i(j()),size:_i(M()),annotations:Jl.optional(),_meta:_i(li({}))}),Gse=I({...Dl.shape,...El.shape,uriTemplate:j(),description:_i(j()),mimeType:_i(j()),annotations:Jl.optional(),_meta:_i(li({}))}),Kse=Ml.extend({method:V(`resources/list`)}),qse=Nl.extend({resources:F(Yl)}),Jse=Ml.extend({method:V(`resources/templates/list`)}),Yse=Nl.extend({resourceTemplates:F(Gse)}),Xl=pl.extend({uri:j()}),Xse=Xl,Zse=hl.extend({method:V(`resources/read`),params:Xse}),Qse=vl.extend({contents:F(L([Wl,Kl]))}),$se=_l.extend({method:V(`notifications/resources/list_changed`),params:gl.optional()}),ece=Xl,tce=hl.extend({method:V(`resources/subscribe`),params:ece}),nce=Xl,rce=hl.extend({method:V(`resources/unsubscribe`),params:nce}),ice=gl.extend({uri:j()}),ace=_l.extend({method:V(`notifications/resources/updated`),params:ice}),oce=I({name:j(),description:_i(j()),required:_i(N())}),sce=I({...Dl.shape,...El.shape,description:_i(j()),arguments:_i(F(oce)),_meta:_i(li({}))}),cce=Ml.extend({method:V(`prompts/list`)}),lce=Nl.extend({prompts:F(sce)}),uce=pl.extend({name:j(),arguments:z(j(),j()).optional()}),dce=hl.extend({method:V(`prompts/get`),params:uce}),Zl=I({type:V(`text`),text:j(),annotations:Jl.optional(),_meta:z(j(),P()).optional()}),Ql=I({type:V(`image`),data:Gl,mimeType:j(),annotations:Jl.optional(),_meta:z(j(),P()).optional()}),$l=I({type:V(`audio`),data:Gl,mimeType:j(),annotations:Jl.optional(),_meta:z(j(),P()).optional()}),fce=I({type:V(`tool_use`),name:j(),id:j(),input:z(j(),P()),_meta:z(j(),P()).optional()}),pce=I({type:V(`resource`),resource:L([Wl,Kl]),annotations:Jl.optional(),_meta:z(j(),P()).optional()}),eu=L([Zl,Ql,$l,Yl.extend({type:V(`resource_link`)}),pce]),mce=I({role:ql,content:eu}),hce=vl.extend({description:j().optional(),messages:F(mce)}),gce=_l.extend({method:V(`notifications/prompts/list_changed`),params:gl.optional()}),_ce=I({title:j().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),vce=I({taskSupport:B([`required`,`optional`,`forbidden`]).optional()}),tu=I({...Dl.shape,...El.shape,description:j().optional(),inputSchema:I({type:V(`object`),properties:z(j(),ll).optional(),required:F(j()).optional()}).catchall(P()),outputSchema:I({type:V(`object`),properties:z(j(),ll).optional(),required:F(j()).optional()}).catchall(P()).optional(),annotations:_ce.optional(),execution:vce.optional(),_meta:z(j(),P()).optional()}),yce=Ml.extend({method:V(`tools/list`)}),bce=Nl.extend({tools:F(tu)}),nu=vl.extend({content:F(eu).default([]),structuredContent:z(j(),P()).optional(),isError:N().optional()});nu.or(vl.extend({toolResult:P()}));const xce=ml.extend({name:j(),arguments:z(j(),P()).optional()}),Sce=hl.extend({method:V(`tools/call`),params:xce}),Cce=_l.extend({method:V(`notifications/tools/list_changed`),params:gl.optional()});I({autoRefresh:N().default(!0),debounceMs:M().int().nonnegative().default(300)});const ru=B([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),wce=pl.extend({level:ru}),Tce=hl.extend({method:V(`logging/setLevel`),params:wce}),Ece=gl.extend({level:ru,logger:j().optional(),data:P()}),Dce=_l.extend({method:V(`notifications/message`),params:Ece}),Oce=I({hints:F(I({name:j().optional()})).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),kce=I({mode:B([`auto`,`required`,`none`]).optional()}),Ace=I({type:V(`tool_result`),toolUseId:j().describe(`The unique identifier for the corresponding tool call.`),content:F(eu).default([]),structuredContent:I({}).loose().optional(),isError:N().optional(),_meta:z(j(),P()).optional()}),jce=R(`type`,[Zl,Ql,$l]),iu=R(`type`,[Zl,Ql,$l,fce,Ace]),Mce=I({role:ql,content:L([iu,F(iu)]),_meta:z(j(),P()).optional()}),Nce=ml.extend({messages:F(Mce),modelPreferences:Oce.optional(),systemPrompt:j().optional(),includeContext:B([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:F(j()).optional(),metadata:ll.optional(),tools:F(tu).optional(),toolChoice:kce.optional()}),Pce=hl.extend({method:V(`sampling/createMessage`),params:Nce}),Fce=vl.extend({model:j(),stopReason:_i(B([`endTurn`,`stopSequence`,`maxTokens`]).or(j())),role:ql,content:jce}),Ice=vl.extend({model:j(),stopReason:_i(B([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(j())),role:ql,content:L([iu,F(iu)])}),Lce=I({type:V(`boolean`),title:j().optional(),description:j().optional(),default:N().optional()}),Rce=I({type:V(`string`),title:j().optional(),description:j().optional(),minLength:M().optional(),maxLength:M().optional(),format:B([`email`,`uri`,`date`,`date-time`]).optional(),default:j().optional()}),zce=I({type:B([`number`,`integer`]),title:j().optional(),description:j().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),Bce=I({type:V(`string`),title:j().optional(),description:j().optional(),enum:F(j()),default:j().optional()}),Vce=I({type:V(`string`),title:j().optional(),description:j().optional(),oneOf:F(I({const:j(),title:j()})),default:j().optional()}),Hce=L([L([I({type:V(`string`),title:j().optional(),description:j().optional(),enum:F(j()),enumNames:F(j()).optional(),default:j().optional()}),L([Bce,Vce]),L([I({type:V(`array`),title:j().optional(),description:j().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({type:V(`string`),enum:F(j())}),default:F(j()).optional()}),I({type:V(`array`),title:j().optional(),description:j().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({anyOf:F(I({const:j(),title:j()}))}),default:F(j()).optional()})])]),Lce,Rce,zce]),Uce=L([ml.extend({mode:V(`form`).optional(),message:j(),requestedSchema:I({type:V(`object`),properties:z(j(),Hce),required:F(j()).optional()})}),ml.extend({mode:V(`url`),message:j(),elicitationId:j(),url:j().url()})]),Wce=hl.extend({method:V(`elicitation/create`),params:Uce}),Gce=gl.extend({elicitationId:j()}),Kce=_l.extend({method:V(`notifications/elicitation/complete`),params:Gce}),qce=vl.extend({action:B([`accept`,`decline`,`cancel`]),content:wi(e=>e===null?void 0:e,z(j(),L([j(),M(),N(),F(j())])).optional())}),Jce=I({type:V(`ref/resource`),uri:j()}),Yce=I({type:V(`ref/prompt`),name:j()}),Xce=pl.extend({ref:L([Yce,Jce]),argument:I({name:j(),value:j()}),context:I({arguments:z(j(),j()).optional()}).optional()}),Zce=hl.extend({method:V(`completion/complete`),params:Xce}),Qce=vl.extend({completion:li({values:F(j()).max(100),total:_i(M().int()),hasMore:_i(N())})}),$ce=I({uri:j().startsWith(`file://`),name:j().optional(),_meta:z(j(),P()).optional()}),ele=hl.extend({method:V(`roots/list`),params:pl.optional()}),tle=vl.extend({roots:F($ce)}),nle=_l.extend({method:V(`notifications/roots/list_changed`),params:gl.optional()});L([Al,Ise,Zce,Tce,dce,cce,Kse,Jse,Zse,tce,rce,Sce,yce,Ll,zl,Bl,Hl]),L([Tl,jl,kl,nle,Il]),L([wl,Fce,Ice,qce,tle,Rl,Vl,Fl]),L([Al,Pce,Wce,ele,Ll,zl,Bl,Hl]),L([Tl,jl,Dce,ace,$se,Cce,gce,Il,Kce]),L([wl,Rse,Qce,hce,lce,qse,Yse,Qse,nu,bce,Rl,Vl,Fl]);const au=Nre().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ti.custom,message:`URL must be parseable`,fatal:!0}),wt}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),rle=li({resource:j().url(),authorization_servers:F(au).optional(),jwks_uri:j().url().optional(),scopes_supported:F(j()).optional(),bearer_methods_supported:F(j()).optional(),resource_signing_alg_values_supported:F(j()).optional(),resource_name:j().optional(),resource_documentation:j().optional(),resource_policy_uri:j().url().optional(),resource_tos_uri:j().url().optional(),tls_client_certificate_bound_access_tokens:N().optional(),authorization_details_types_supported:F(j()).optional(),dpop_signing_alg_values_supported:F(j()).optional(),dpop_bound_access_tokens_required:N().optional()}),ou=li({issuer:j(),authorization_endpoint:au,token_endpoint:au,registration_endpoint:au.optional(),scopes_supported:F(j()).optional(),response_types_supported:F(j()),response_modes_supported:F(j()).optional(),grant_types_supported:F(j()).optional(),token_endpoint_auth_methods_supported:F(j()).optional(),token_endpoint_auth_signing_alg_values_supported:F(j()).optional(),service_documentation:au.optional(),revocation_endpoint:au.optional(),revocation_endpoint_auth_methods_supported:F(j()).optional(),revocation_endpoint_auth_signing_alg_values_supported:F(j()).optional(),introspection_endpoint:j().optional(),introspection_endpoint_auth_methods_supported:F(j()).optional(),introspection_endpoint_auth_signing_alg_values_supported:F(j()).optional(),code_challenge_methods_supported:F(j()).optional(),client_id_metadata_document_supported:N().optional()}),ile=I({...li({issuer:j(),authorization_endpoint:au,token_endpoint:au,userinfo_endpoint:au.optional(),jwks_uri:au,registration_endpoint:au.optional(),scopes_supported:F(j()).optional(),response_types_supported:F(j()),response_modes_supported:F(j()).optional(),grant_types_supported:F(j()).optional(),acr_values_supported:F(j()).optional(),subject_types_supported:F(j()),id_token_signing_alg_values_supported:F(j()),id_token_encryption_alg_values_supported:F(j()).optional(),id_token_encryption_enc_values_supported:F(j()).optional(),userinfo_signing_alg_values_supported:F(j()).optional(),userinfo_encryption_alg_values_supported:F(j()).optional(),userinfo_encryption_enc_values_supported:F(j()).optional(),request_object_signing_alg_values_supported:F(j()).optional(),request_object_encryption_alg_values_supported:F(j()).optional(),request_object_encryption_enc_values_supported:F(j()).optional(),token_endpoint_auth_methods_supported:F(j()).optional(),token_endpoint_auth_signing_alg_values_supported:F(j()).optional(),display_values_supported:F(j()).optional(),claim_types_supported:F(j()).optional(),claims_supported:F(j()).optional(),service_documentation:j().optional(),claims_locales_supported:F(j()).optional(),ui_locales_supported:F(j()).optional(),claims_parameter_supported:N().optional(),request_parameter_supported:N().optional(),request_uri_parameter_supported:N().optional(),require_request_uri_registration:N().optional(),op_policy_uri:au.optional(),op_tos_uri:au.optional(),client_id_metadata_document_supported:N().optional()}).shape,...ou.pick({code_challenge_methods_supported:!0}).shape}),ale=I({access_token:j(),id_token:j().optional(),token_type:j(),expires_in:Ei().optional(),scope:j().optional(),refresh_token:j().optional()}).strip(),ole=I({error:j(),error_description:j().optional(),error_uri:j().optional()}),su=au.optional().or(V(``).transform(()=>void 0)),sle=I({redirect_uris:F(au),token_endpoint_auth_method:j().optional(),grant_types:F(j()).optional(),response_types:F(j()).optional(),client_name:j().optional(),client_uri:au.optional(),logo_uri:su,scope:j().optional(),contacts:F(j()).optional(),tos_uri:su,policy_uri:j().optional(),jwks_uri:au.optional(),jwks:si().optional(),software_id:j().optional(),software_version:j().optional(),software_statement:j().optional()}).strip(),cle=I({client_id:j(),client_secret:j().optional(),client_id_issued_at:M().optional(),client_secret_expires_at:M().optional()}).strip(),lle=sle.merge(cle);I({error:j(),error_description:j().optional()}).strip(),I({token:j(),token_type_hint:j().optional()}).strip();function ule(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function dle({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var cu=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},lu=class extends cu{};lu.errorCode=`invalid_request`;var uu=class extends cu{};uu.errorCode=`invalid_client`;var du=class extends cu{};du.errorCode=`invalid_grant`;var fu=class extends cu{};fu.errorCode=`unauthorized_client`;var pu=class extends cu{};pu.errorCode=`unsupported_grant_type`;var mu=class extends cu{};mu.errorCode=`invalid_scope`;var hu=class extends cu{};hu.errorCode=`access_denied`;var gu=class extends cu{};gu.errorCode=`server_error`;var _u=class extends cu{};_u.errorCode=`temporarily_unavailable`;var vu=class extends cu{};vu.errorCode=`unsupported_response_type`;var yu=class extends cu{};yu.errorCode=`unsupported_token_type`;var bu=class extends cu{};bu.errorCode=`invalid_token`;var xu=class extends cu{};xu.errorCode=`method_not_allowed`;var Su=class extends cu{};Su.errorCode=`too_many_requests`;var Cu=class extends cu{};Cu.errorCode=`invalid_client_metadata`;var wu=class extends cu{};wu.errorCode=`insufficient_scope`;var Tu=class extends cu{};Tu.errorCode=`invalid_target`;const fle={[lu.errorCode]:lu,[uu.errorCode]:uu,[du.errorCode]:du,[fu.errorCode]:fu,[pu.errorCode]:pu,[mu.errorCode]:mu,[hu.errorCode]:hu,[gu.errorCode]:gu,[_u.errorCode]:_u,[vu.errorCode]:vu,[yu.errorCode]:yu,[bu.errorCode]:bu,[xu.errorCode]:xu,[Su.errorCode]:Su,[Cu.errorCode]:Cu,[wu.errorCode]:wu,[Tu.errorCode]:Tu};var Eu=class extends Error{constructor(e){super(e??`Unauthorized`)}};function ple(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const Du=`code`,Ou=`S256`;function mle(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&ple(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function hle(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:gle(i,a,n);return;case`client_secret_post`:_le(i,a,r);return;case`none`:vle(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function gle(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function _le(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function vle(e,t){t.set(`client_id`,e)}async function ku(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ole.parse(JSON.parse(n));return new(fle[e]||gu)(t||``,r)}catch(e){return new gu(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function Au(e,t){try{return await ju(e,t)}catch(n){if(n instanceof uu||n instanceof fu)return await e.invalidateCredentials?.(`all`),await ju(e,t);if(n instanceof du)return await e.invalidateCredentials?.(`tokens`),await ju(e,t);throw n}}async function ju(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await Lu(c,{fetchFn:a}),!s)try{s=await Pu(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await Tle(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await ble(t,e,s),f=r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,p=await Promise.resolve(e.clientInformation());if(!p){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!yle(r))throw new Cu(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)p={client_id:r},await e.saveClientInformation?.(p);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await Ale(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:a});await e.saveClientInformation(t),p=t}}let m=!e.redirectUrl;if(n!==void 0||m){let t=await kle(e,c,{metadata:l,resource:d,authorizationCode:n,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let h=await e.tokens();if(h?.refresh_token)try{let t=await Ole(c,{metadata:l,clientInformation:p,refreshToken:h.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof cu)||e instanceof gu))throw e}let g=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:v}=await Ele(c,{metadata:l,clientInformation:p,state:g,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(_),`REDIRECT`}function yle(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function ble(e,t,n){let r=ule(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!dle({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function Mu(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=Nu(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=Nu(e,`scope`)||void 0,s=Nu(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function Nu(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function Pu(e,t,n=fetch){let r=await Cle(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return rle.parse(await r.json())}async function Fu(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Fu(e,void 0,n):void 0;throw r}}function xle(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Iu(e,t,n=fetch){return await Fu(e,{"MCP-Protocol-Version":t},n)}function Sle(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Cle(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=xle(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await Iu(o,a,n);return!r?.metadataUrl&&Sle(s,i.pathname)&&(s=await Iu(new URL(`/.well-known/${t}`,i),a,n)),s}function wle(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function Lu(e,{fetchFn:t=fetch,protocolVersion:n=`2025-11-25`}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=wle(e);for(let{url:e,type:n}of i){let i=await Fu(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?ou.parse(await i.json()):ile.parse(await i.json())}}}async function Tle(e,t){let n,r;try{n=await Pu(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await Lu(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function Ele(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Du))throw Error(`Incompatible auth server: does not support response type ${Du}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ou))throw Error(`Incompatible auth server: does not support code challenge method ${Ou}`)}else s=new URL(`/authorize`,e);let c=await cc(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Du),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,Ou),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function Dle(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function Ru(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&hle(mle(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await ku(l);return ale.parse(await l.json())}async function Ole(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await Ru(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function kle(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);s=Dle(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return Ru(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function Ale(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await ku(o);return lle.parse(await o.json())}const jle={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var zu=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Mle=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Cse(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??jle}async _authThenStart(){if(!this._authProvider)throw new Eu(`No auth provider`);let e;try{e=await Au(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new Eu;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=cl(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new zu(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Ba({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=Cl.parse(JSON.parse(e.data));Ose(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Eu(`No auth provider`);if(await Au(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Eu(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Ese(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new zu(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Mu(o);if(this._resourceMetadataUrl=t,this._scope=n,await Au(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Eu;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Mu(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new zu(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await Au(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Eu;return this.send(e)}}throw new zu(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),zse(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>Cl.parse(e)):[Cl.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new zu(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new zu(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};async function Nle(e){let t;if(e.authType===`service_account`)t={"X-API-Key":e.accessToken};else if(e.authType===`user`){if(!e.orgId)throw Error(`orgId is required for user authentication`);t={Authorization:`Bearer ${e.accessToken}`}}else throw Error(`unknown authType: ${e.authType}`);let n={...t};e.authType===`user`&&e.orgId&&(n[`X-UIGraph-Org-Id`]=e.orgId);let r=await xse({transport:new Mle(new URL(e.url),{requestInit:{headers:n}})});return{client:r,tools:await r.tools()}}Xs({errorSchema:G(()=>K(I({type:V(`error`),error:I({type:j(),message:j()})}))),errorToMessage:e=>e.error.message}),I({type:j(),category:j().nullish(),explanation:j().nullish(),recommended_model:j().nullish()}),I({containerUpload:N().optional(),citations:I({enabled:N()}).optional(),title:j().optional(),context:j().optional()}),I({sendReasoning:N().optional(),structuredOutputMode:B([`outputFormat`,`jsonTool`,`auto`]).optional(),thinking:R(`type`,[I({type:V(`adaptive`),display:B([`omitted`,`summarized`]).optional()}),I({type:V(`enabled`),budgetTokens:M().optional()}),I({type:V(`disabled`)})]).optional(),disableParallelToolUse:N().optional(),cacheControl:I({type:V(`ephemeral`),ttl:L([V(`5m`),V(`1h`)]).optional()}).optional(),metadata:I({userId:j().optional()}).optional(),mcpServers:F(I({type:V(`url`),name:j(),url:j(),authorizationToken:j().nullish(),toolConfiguration:I({enabled:N().nullish(),allowedTools:F(j()).nullish()}).nullish()})).optional(),container:I({id:j().optional(),skills:F(R(`type`,[I({type:V(`anthropic`),skillId:j(),version:j().optional()}),I({type:V(`custom`),providerReference:z(j(),j()),version:j().optional()})])).optional()}).optional(),toolStreaming:N().optional(),effort:B([`low`,`medium`,`high`,`xhigh`,`max`]).optional(),taskBudget:I({type:V(`tokens`),total:M().int().min(2e4),remaining:M().int().min(0).optional()}).optional(),speed:B([`fast`,`standard`]).optional(),inferenceGeo:B([`us`,`global`]).optional(),fallbacks:F(I({model:j(),max_tokens:M().int().optional(),thinking:z(j(),P()).optional(),output_config:z(j(),P()).optional(),speed:B([`fast`,`standard`]).optional()})).optional(),anthropicBeta:F(j()).optional(),contextManagement:I({edits:F(R(`type`,[I({type:V(`clear_tool_uses_20250919`),trigger:R(`type`,[I({type:V(`input_tokens`),value:M()}),I({type:V(`tool_uses`),value:M()})]).optional(),keep:I({type:V(`tool_uses`),value:M()}).optional(),clearAtLeast:I({type:V(`input_tokens`),value:M()}).optional(),clearToolInputs:N().optional(),excludeTools:F(j()).optional()}),I({type:V(`clear_thinking_20251015`),keep:L([V(`all`),I({type:V(`thinking_turns`),value:M()})]).optional()}),I({type:V(`compact_20260112`),trigger:I({type:V(`input_tokens`),value:M()}).optional(),pauseAfterCompaction:N().optional(),instructions:j().optional()})]))}).optional()});var Bu=4;function Ple(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Fle=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let n=Ple(e);if(n){if(!t.canCache){this.warnings.push({type:`unsupported`,feature:`cache_control on non-cacheable context`,details:`cache_control cannot be set on ${t.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>Bu){this.warnings.push({type:`unsupported`,feature:`cacheControl breakpoint limit`,details:`Maximum ${Bu} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}}getWarnings(){return this.warnings}},Ile=G(()=>K(I({model:j(),maxUses:M().optional(),caching:I({type:V(`ephemeral`),ttl:L([V(`5m`),V(`1h`)])}).optional()}))),Lle=G(()=>K(R(`type`,[I({type:V(`advisor_result`),text:j()}),I({type:V(`advisor_redacted_result`),encryptedContent:j()}),I({type:V(`advisor_tool_result_error`),errorCode:j()})]))),Rle=Ws({id:`anthropic.advisor_20260301`,inputSchema:G(()=>K(I({}).strict())),outputSchema:Lle,supportsDeferredResults:!0}),zle=e=>Rle(e),Ble=G(()=>K(I({maxCharacters:M().optional()}))),Vle=Hs({id:`anthropic.text_editor_20250728`,inputSchema:G(()=>K(I({command:B([`view`,`create`,`str_replace`,`insert`]),path:j(),file_text:j().optional(),insert_line:M().int().optional(),new_str:j().optional(),insert_text:j().optional(),old_str:j().optional(),view_range:F(M().int()).optional()})))}),Hle=(e={})=>Vle(e),Ule=G(()=>K(I({maxUses:M().optional(),allowedDomains:F(j()).optional(),blockedDomains:F(j()).optional(),userLocation:I({type:V(`approximate`),city:j().optional(),region:j().optional(),country:j().optional(),timezone:j().optional()}).optional()}))),Wle=G(()=>K(F(I({url:j(),title:j().nullable(),pageAge:j().nullable(),encryptedContent:j(),type:V(`web_search_result`)})))),Vu=Ws({id:`anthropic.web_search_20260209`,inputSchema:G(()=>K(I({query:j()}))),outputSchema:Wle,supportsDeferredResults:!0}),Gle=(e={})=>Vu(e),Kle=G(()=>K(I({maxUses:M().optional(),allowedDomains:F(j()).optional(),blockedDomains:F(j()).optional(),userLocation:I({type:V(`approximate`),city:j().optional(),region:j().optional(),country:j().optional(),timezone:j().optional()}).optional()}))),qle=G(()=>K(F(I({url:j(),title:j().nullable(),pageAge:j().nullable(),encryptedContent:j(),type:V(`web_search_result`)})))),Jle=Ws({id:`anthropic.web_search_20250305`,inputSchema:G(()=>K(I({query:j()}))),outputSchema:qle,supportsDeferredResults:!0}),Yle=(e={})=>Jle(e),Xle=G(()=>K(I({maxUses:M().optional(),allowedDomains:F(j()).optional(),blockedDomains:F(j()).optional(),citations:I({enabled:N()}).optional(),maxContentTokens:M().optional()}))),Zle=G(()=>K(I({type:V(`web_fetch_result`),url:j(),content:I({type:V(`document`),title:j().nullable(),citations:I({enabled:N()}).optional(),source:L([I({type:V(`base64`),mediaType:V(`application/pdf`),data:j()}),I({type:V(`text`),mediaType:V(`text/plain`),data:j()})])}),retrievedAt:j().nullable()}))),Qle=Ws({id:`anthropic.web_fetch_20260209`,inputSchema:G(()=>K(I({url:j()}))),outputSchema:Zle,supportsDeferredResults:!0}),$le=(e={})=>Qle(e),eue=G(()=>K(I({maxUses:M().optional(),allowedDomains:F(j()).optional(),blockedDomains:F(j()).optional(),citations:I({enabled:N()}).optional(),maxContentTokens:M().optional()}))),tue=G(()=>K(I({type:V(`web_fetch_result`),url:j(),content:I({type:V(`document`),title:j().nullable(),citations:I({enabled:N()}).optional(),source:L([I({type:V(`base64`),mediaType:V(`application/pdf`),data:j()}),I({type:V(`text`),mediaType:V(`text/plain`),data:j()})])}),retrievedAt:j().nullable()}))),nue=Ws({id:`anthropic.web_fetch_20250910`,inputSchema:G(()=>K(I({url:j()}))),outputSchema:tue,supportsDeferredResults:!0}),rue=(e={})=>nue(e);async function iue({tools:e,toolChoice:t,disableParallelToolUse:n,cacheControlValidator:r,supportsStructuredOutput:i,supportsStrictTools:a,defaultEagerInputStreaming:o=!1}){e=e?.length?e:void 0;let s=[],c=new Set,l=r||new Fle;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s,betas:c};let u=[];for(let t of e)switch(t.type){case`function`:{let e=l.getCacheControl(t.providerOptions,{type:`tool definition`,canCache:!0}),n=t.providerOptions?.anthropic,r=n?.eagerInputStreaming??o,d=n?.deferLoading,f=n?.allowedCallers;!a&&t.strict!=null&&s.push({type:`unsupported`,feature:`strict`,details:`Tool '${t.name}' has strict: ${t.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),u.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e,...r?{eager_input_streaming:!0}:{},...a===!0&&t.strict!=null?{strict:t.strict}:{},...d==null?{}:{defer_loading:d},...f==null?{}:{allowed_callers:f},...t.inputExamples==null?{}:{input_examples:t.inputExamples.map(e=>e.input)}}),i===!0&&c.add(`structured-outputs-2025-11-13`),(t.inputExamples!=null||f!=null)&&c.add(`advanced-tool-use-2025-11-20`);break}case`provider`:switch(t.id){case`anthropic.code_execution_20250522`:c.add(`code-execution-2025-05-22`),u.push({type:`code_execution_20250522`,name:`code_execution`,cache_control:void 0});break;case`anthropic.code_execution_20250825`:c.add(`code-execution-2025-08-25`),u.push({type:`code_execution_20250825`,name:`code_execution`});break;case`anthropic.code_execution_20260120`:u.push({type:`code_execution_20260120`,name:`code_execution`});break;case`anthropic.computer_20250124`:c.add(`computer-use-2025-01-24`),u.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case`anthropic.computer_20251124`:c.add(`computer-use-2025-11-24`),u.push({name:`computer`,type:`computer_20251124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,enable_zoom:t.args.enableZoom,cache_control:void 0});break;case`anthropic.computer_20241022`:c.add(`computer-use-2024-10-22`),u.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case`anthropic.text_editor_20250124`:c.add(`computer-use-2025-01-24`),u.push({name:`str_replace_editor`,type:`text_editor_20250124`,cache_control:void 0});break;case`anthropic.text_editor_20241022`:c.add(`computer-use-2024-10-22`),u.push({name:`str_replace_editor`,type:`text_editor_20241022`,cache_control:void 0});break;case`anthropic.text_editor_20250429`:c.add(`computer-use-2025-01-24`),u.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`,cache_control:void 0});break;case`anthropic.text_editor_20250728`:{let e=await js({value:t.args,schema:Ble});u.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters,cache_control:void 0});break}case`anthropic.bash_20250124`:c.add(`computer-use-2025-01-24`),u.push({name:`bash`,type:`bash_20250124`,cache_control:void 0});break;case`anthropic.bash_20241022`:c.add(`computer-use-2024-10-22`),u.push({name:`bash`,type:`bash_20241022`,cache_control:void 0});break;case`anthropic.memory_20250818`:c.add(`context-management-2025-06-27`),u.push({name:`memory`,type:`memory_20250818`});break;case`anthropic.web_fetch_20250910`:{c.add(`web-fetch-2025-09-10`);let e=await js({value:t.args,schema:eue});u.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case`anthropic.web_fetch_20260209`:{c.add(`code-execution-web-tools-2026-02-09`);let e=await js({value:t.args,schema:Xle});u.push({type:`web_fetch_20260209`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case`anthropic.web_search_20250305`:{let e=await js({value:t.args,schema:Kle});u.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case`anthropic.web_search_20260209`:{c.add(`code-execution-web-tools-2026-02-09`);let e=await js({value:t.args,schema:Ule});u.push({type:`web_search_20260209`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case`anthropic.tool_search_regex_20251119`:u.push({type:`tool_search_tool_regex_20251119`,name:`tool_search_tool_regex`});break;case`anthropic.tool_search_bm25_20251119`:u.push({type:`tool_search_tool_bm25_20251119`,name:`tool_search_tool_bm25`});break;case`anthropic.advisor_20260301`:{c.add(`advisor-tool-2026-03-01`);let e=await js({value:t.args,schema:Ile});u.push({type:`advisor_20260301`,name:`advisor`,model:e.model,...e.maxUses!==void 0&&{max_uses:e.maxUses},...e.caching!==void 0&&{caching:e.caching}});break}default:s.push({type:`unsupported`,feature:`provider-defined tool ${t.id}`});break}break;default:s.push({type:`unsupported`,feature:`tool ${t}`});break}if(t==null)return{tools:u,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:s,betas:c};let d=t.type;switch(d){case`auto`:return{tools:u,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:s,betas:c};case`required`:return{tools:u,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:s,betas:c};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:s,betas:c};case`tool`:return{tools:u,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:s,betas:c};default:throw new k({functionality:`tool choice type: ${d}`})}}var aue=G(()=>K(I({type:V(`code_execution_result`),stdout:j(),stderr:j(),return_code:M(),content:F(I({type:V(`code_execution_output`),file_id:j()})).optional().default([])}))),oue=Ws({id:`anthropic.code_execution_20250522`,inputSchema:G(()=>K(I({code:j()}))),outputSchema:aue}),sue=(e={})=>oue(e),cue=G(()=>K(R(`type`,[I({type:V(`code_execution_result`),stdout:j(),stderr:j(),return_code:M(),content:F(I({type:V(`code_execution_output`),file_id:j()})).optional().default([])}),I({type:V(`bash_code_execution_result`),content:F(I({type:V(`bash_code_execution_output`),file_id:j()})),stdout:j(),stderr:j(),return_code:M()}),I({type:V(`bash_code_execution_tool_result_error`),error_code:j()}),I({type:V(`text_editor_code_execution_tool_result_error`),error_code:j()}),I({type:V(`text_editor_code_execution_view_result`),content:j(),file_type:j(),num_lines:M().nullable(),start_line:M().nullable(),total_lines:M().nullable()}),I({type:V(`text_editor_code_execution_create_result`),is_file_update:N()}),I({type:V(`text_editor_code_execution_str_replace_result`),lines:F(j()).nullable(),new_lines:M().nullable(),new_start:M().nullable(),old_lines:M().nullable(),old_start:M().nullable()})]))),lue=Ws({id:`anthropic.code_execution_20250825`,inputSchema:G(()=>K(R(`type`,[I({type:V(`programmatic-tool-call`),code:j()}),I({type:V(`bash_code_execution`),command:j()}),R(`command`,[I({type:V(`text_editor_code_execution`),command:V(`view`),path:j()}),I({type:V(`text_editor_code_execution`),command:V(`create`),path:j(),file_text:j().nullish()}),I({type:V(`text_editor_code_execution`),command:V(`str_replace`),path:j(),old_str:j(),new_str:j()})])]))),outputSchema:cue,supportsDeferredResults:!0}),uue=(e={})=>lue(e),due=G(()=>K(R(`type`,[I({type:V(`code_execution_result`),stdout:j(),stderr:j(),return_code:M(),content:F(I({type:V(`code_execution_output`),file_id:j()})).optional().default([])}),I({type:V(`encrypted_code_execution_result`),encrypted_stdout:j(),stderr:j(),return_code:M(),content:F(I({type:V(`code_execution_output`),file_id:j()})).optional().default([])}),I({type:V(`bash_code_execution_result`),content:F(I({type:V(`bash_code_execution_output`),file_id:j()})),stdout:j(),stderr:j(),return_code:M()}),I({type:V(`bash_code_execution_tool_result_error`),error_code:j()}),I({type:V(`text_editor_code_execution_tool_result_error`),error_code:j()}),I({type:V(`text_editor_code_execution_view_result`),content:j(),file_type:j(),num_lines:M().nullable(),start_line:M().nullable(),total_lines:M().nullable()}),I({type:V(`text_editor_code_execution_create_result`),is_file_update:N()}),I({type:V(`text_editor_code_execution_str_replace_result`),lines:F(j()).nullable(),new_lines:M().nullable(),new_start:M().nullable(),old_lines:M().nullable(),old_start:M().nullable()})]))),fue=Ws({id:`anthropic.code_execution_20260120`,inputSchema:G(()=>K(R(`type`,[I({type:V(`programmatic-tool-call`),code:j()}),I({type:V(`bash_code_execution`),command:j()}),R(`command`,[I({type:V(`text_editor_code_execution`),command:V(`view`),path:j()}),I({type:V(`text_editor_code_execution`),command:V(`create`),path:j(),file_text:j().nullish()}),I({type:V(`text_editor_code_execution`),command:V(`str_replace`),path:j(),old_str:j(),new_str:j()})])]))),outputSchema:due,supportsDeferredResults:!0}),pue=(e={})=>fue(e),mue=G(()=>K(F(I({type:V(`tool_reference`),toolName:j()})))),hue=Ws({id:`anthropic.tool_search_regex_20251119`,inputSchema:G(()=>K(I({pattern:j(),limit:M().optional()}))),outputSchema:mue,supportsDeferredResults:!0}),gue=(e={})=>hue(e);function Hu(e){return e.includes(`claude-opus-4-8`)||e.includes(`claude-opus-4-7`)||e.includes(`claude-fable-5`)||e.includes(`claude-sonnet-5`)?{maxOutputTokens:128e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,isKnownModel:!0}:e.includes(`claude-sonnet-4-6`)||e.includes(`claude-opus-4-6`)?{maxOutputTokens:128e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-sonnet-4-5`)||e.includes(`claude-opus-4-5`)||e.includes(`claude-haiku-4-5`)?{maxOutputTokens:64e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-opus-4-1`)?{maxOutputTokens:32e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-sonnet-4-`)?{maxOutputTokens:64e3,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-opus-4-`)?{maxOutputTokens:32e3,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-3-haiku`)?{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!1}}var _ue=Hs({id:`anthropic.bash_20241022`,inputSchema:G(()=>K(I({command:j(),restart:N().optional()})))});function vue(e={}){let{execute:t,...n}=e;return _ue(t===void 0?{...n,execute:async({command:e},{abortSignal:t,experimental_sandbox:n})=>{if(!n)throw Error(`Sandbox session is not available`);return await n.run({command:e,abortSignal:t})}}:{...n,...t===null?{}:{execute:t}})}var yue=Hs({id:`anthropic.bash_20250124`,inputSchema:G(()=>K(I({command:j(),restart:N().optional()})))});function bue(e={}){let{execute:t,...n}=e;return yue(t===void 0?{...n,execute:async({command:e},{abortSignal:t,experimental_sandbox:n})=>{if(!n)throw Error(`Sandbox session is not available`);return await n.run({command:e,abortSignal:t})}}:{...n,...t===null?{}:{execute:t}})}var xue=Hs({id:`anthropic.computer_20241022`,inputSchema:G(()=>K(I({action:B([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:F(M().int()).optional(),text:j().optional()})))}),Sue=Hs({id:`anthropic.computer_20250124`,inputSchema:G(()=>K(I({action:B([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:fi([M().int(),M().int()]).optional(),duration:M().optional(),scroll_amount:M().optional(),scroll_direction:B([`up`,`down`,`left`,`right`]).optional(),start_coordinate:fi([M().int(),M().int()]).optional(),text:j().optional()})))}),Cue=Hs({id:`anthropic.computer_20251124`,inputSchema:G(()=>K(I({action:B([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`,`zoom`]),coordinate:fi([M().int(),M().int()]).optional(),duration:M().optional(),region:fi([M().int(),M().int(),M().int(),M().int()]).optional(),scroll_amount:M().optional(),scroll_direction:B([`up`,`down`,`left`,`right`]).optional(),start_coordinate:fi([M().int(),M().int()]).optional(),text:j().optional()})))}),wue=Hs({id:`anthropic.memory_20250818`,inputSchema:G(()=>K(R(`command`,[I({command:V(`view`),path:j(),view_range:fi([M(),M()]).optional()}),I({command:V(`create`),path:j(),file_text:j()}),I({command:V(`str_replace`),path:j(),old_str:j(),new_str:j()}),I({command:V(`insert`),path:j(),insert_line:M(),insert_text:j()}),I({command:V(`delete`),path:j()}),I({command:V(`rename`),old_path:j(),new_path:j()})])))}),Tue=Hs({id:`anthropic.text_editor_20241022`,inputSchema:G(()=>K(I({command:B([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:j(),file_text:j().optional(),insert_line:M().int().optional(),new_str:j().optional(),insert_text:j().optional(),old_str:j().optional(),view_range:F(M().int()).optional()})))}),Eue=Hs({id:`anthropic.text_editor_20250124`,inputSchema:G(()=>K(I({command:B([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:j(),file_text:j().optional(),insert_line:M().int().optional(),new_str:j().optional(),insert_text:j().optional(),old_str:j().optional(),view_range:F(M().int()).optional()})))}),Due=Hs({id:`anthropic.text_editor_20250429`,inputSchema:G(()=>K(I({command:B([`view`,`create`,`str_replace`,`insert`]),path:j(),file_text:j().optional(),insert_line:M().int().optional(),new_str:j().optional(),insert_text:j().optional(),old_str:j().optional(),view_range:F(M().int()).optional()})))}),Oue=G(()=>K(F(I({type:V(`tool_reference`),toolName:j()})))),kue=Ws({id:`anthropic.tool_search_bm25_20251119`,inputSchema:G(()=>K(I({query:j(),limit:M().optional()}))),outputSchema:Oue,supportsDeferredResults:!0}),Uu={advisor_20260301:zle,bash_20241022:vue,bash_20250124:bue,codeExecution_20250522:sue,codeExecution_20250825:uue,codeExecution_20260120:pue,computer_20241022:xue,computer_20250124:Sue,computer_20251124:Cue,memory_20250818:wue,textEditor_20241022:Tue,textEditor_20250124:Eue,textEditor_20250429:Due,textEditor_20250728:Hle,webFetch_20250910:rue,webFetch_20260209:$le,webSearch_20250305:Yle,webSearch_20260209:Gle,toolSearchRegex_20251119:gue,toolSearchBm25_20251119:(e={})=>kue(e)},Wu,Gu=n((()=>{Wu=e=>typeof ArrayBuffer==`function`&&e instanceof ArrayBuffer||Object.prototype.toString.call(e)===`[object ArrayBuffer]`})),Ku,qu,Ju=n((()=>{Gu(),Ku=(e,t=0,n=e.byteLength-t)=>{if(!Wu(e))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof e} (${e})`);return Buffer.from(e,t,n)},qu=(e,t)=>{if(typeof e!=`string`)throw TypeError(`The "input" argument must be of type string. Received type ${typeof e} (${e})`);return t?Buffer.from(e,t):Buffer.from(e)}})),Yu,Xu,Aue=n((()=>{Ju(),Yu=/^[A-Za-z0-9+/]*={0,2}$/,Xu=e=>{if(e.length*3%4!=0)throw TypeError(`Incorrect padding on base64 string.`);if(!Yu.exec(e))throw TypeError(`Invalid base64 string.`);let t=qu(e,`base64`);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}})),Zu,Qu=n((()=>{Ju(),Zu=e=>{let t=qu(e,`utf8`);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)}})),$u,ed=n((()=>{Ju(),Qu(),$u=e=>{let t;if(t=typeof e==`string`?Zu(e):e,typeof t!=`object`||typeof t.byteOffset!=`number`||typeof t.byteLength!=`number`)throw Error(`@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.`);return Ku(t.buffer,t.byteOffset,t.byteLength).toString(`base64`)}}));function jue(e,t,n,r){return class i extends Uint8Array{static fromString(e,n=`utf-8`){if(typeof e==`string`)return n===`base64`?i.mutate(r(e)):i.mutate(t(e));throw Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,i.prototype),e}transformToString(t=`utf-8`){return t===`base64`?n(this):e(this)}}}var Mue=n((()=>{})),td,Nue=n((()=>{Ju(),td=e=>{if(typeof e==`string`)return e;if(typeof e!=`object`||typeof e.byteOffset!=`number`||typeof e.byteLength!=`number`)throw Error(`@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.`);return Ku(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`)}}));function Pue(e){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?()=>crypto.randomUUID():()=>{let t=new Uint8Array(16);return e(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128,nd[t[0]]+nd[t[1]]+nd[t[2]]+nd[t[3]]+`-`+nd[t[4]]+nd[t[5]]+`-`+nd[t[6]]+nd[t[7]]+`-`+nd[t[8]]+nd[t[9]]+`-`+nd[t[10]]+nd[t[11]]+nd[t[12]]+nd[t[13]]+nd[t[14]]+nd[t[15]]}}var nd,Fue=n((()=>{nd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`))})),rd,Iue=n((()=>{rd=(e,t,n=e=>e)=>e})),id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd,gd,_d,vd,yd,bd,xd,Sd,Cd,wd,Td,Ed,Dd,Od,kd,Ad,jd,Md,Nd,Pd,Fd,Id,Ld=n((()=>{id=e=>{switch(e){case`true`:return!0;case`false`:return!1;default:throw Error(`Unable to parse boolean value "${e}"`)}},ad=e=>{if(e!=null){if(typeof e==`number`){if((e===0||e===1)&&Id.warn(Fd(`Expected boolean, got ${typeof e}: ${e}`)),e===0)return!1;if(e===1)return!0}if(typeof e==`string`){let t=e.toLowerCase();if((t===`false`||t===`true`)&&Id.warn(Fd(`Expected boolean, got ${typeof e}: ${e}`)),t===`false`)return!1;if(t===`true`)return!0}if(typeof e==`boolean`)return e;throw TypeError(`Expected boolean, got ${typeof e}: ${e}`)}},od=e=>{if(e!=null){if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&Id.warn(Fd(`Expected number but observed string: ${e}`)),t}if(typeof e==`number`)return e;throw TypeError(`Expected number, got ${typeof e}: ${e}`)}},sd=Math.ceil(2**127*(2-2**-23)),cd=e=>{let t=od(e);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0&&Math.abs(t)>sd)throw TypeError(`Expected 32-bit float, got ${e}`);return t},ld=e=>{if(e!=null){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw TypeError(`Expected integer, got ${typeof e}: ${e}`)}},ud=ld,dd=e=>md(e,32),fd=e=>md(e,16),pd=e=>md(e,8),md=(e,t)=>{let n=ld(e);if(n!==void 0&&hd(n,t)!==n)throw TypeError(`Expected ${t}-bit integer, got ${e}`);return n},hd=(e,t)=>{switch(t){case 32:return Int32Array.of(e)[0];case 16:return Int16Array.of(e)[0];case 8:return Int8Array.of(e)[0]}},gd=(e,t)=>{if(e==null)throw TypeError(t?`Expected a non-null value for ${t}`:`Expected a non-null value`);return e},_d=e=>{if(e!=null){if(typeof e==`object`&&!Array.isArray(e))return e;throw TypeError(`Expected object, got ${Array.isArray(e)?`array`:typeof e}: ${e}`)}},vd=e=>{if(e!=null){if(typeof e==`string`)return e;if([`boolean`,`number`,`bigint`].includes(typeof e))return Id.warn(Fd(`Expected string, got ${typeof e}: ${e}`)),String(e);throw TypeError(`Expected string, got ${typeof e}: ${e}`)}},yd=e=>{if(e==null)return;let t=_d(e),n=[];for(let e in t)t[e]!=null&&n.push(e);if(n.length===0)throw TypeError(`Unions must have exactly one non-null member. None were found.`);if(n.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${n} were not null.`);return t},bd=e=>od(typeof e==`string`?wd(e):e),xd=bd,Sd=e=>cd(typeof e==`string`?wd(e):e),Cd=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,wd=e=>{let t=e.match(Cd);if(t===null||t[0].length!==e.length)throw TypeError(`Expected real number, got implicit NaN`);return parseFloat(e)},Td=e=>typeof e==`string`?kd(e):od(e),Ed=Td,Dd=Td,Od=e=>typeof e==`string`?kd(e):cd(e),kd=e=>{switch(e){case`NaN`:return NaN;case`Infinity`:return 1/0;case`-Infinity`:return-1/0;default:throw Error(`Unable to parse float value: ${e}`)}},Ad=e=>ld(typeof e==`string`?wd(e):e),jd=Ad,Md=e=>dd(typeof e==`string`?wd(e):e),Nd=e=>fd(typeof e==`string`?wd(e):e),Pd=e=>pd(typeof e==`string`?wd(e):e),Fd=e=>String(TypeError(e).stack||e).split(`
|
|
81
81
|
`).slice(0,5).filter(e=>!e.includes(`stackTraceWarning`)).join(`
|
|
82
82
|
`),Id={warn:console.warn}}));function Lue(e){let t=e.getUTCFullYear(),n=e.getUTCMonth(),r=e.getUTCDay(),i=e.getUTCDate(),a=e.getUTCHours(),o=e.getUTCMinutes(),s=e.getUTCSeconds(),c=i<10?`0${i}`:`${i}`,l=a<10?`0${a}`:`${a}`,u=o<10?`0${o}`:`${o}`,d=s<10?`0${s}`:`${s}`;return`${Rd[r]}, ${c} ${zd[n]} ${t} ${l}:${u}:${d} GMT`}var Rd,zd,Bd,Vd,Hd,Ud,Wd,Gd,Kd,qd,Jd,Yd,Xd,Zd,Qd,$d,ef,tf,nf,rf,af,of,sf,Rue=n((()=>{Ld(),Rd=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],zd=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Bd=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),Vd=e=>{if(e==null)return;if(typeof e!=`string`)throw TypeError(`RFC-3339 date-times must be expressed as strings`);let t=Bd.exec(e);if(!t)throw TypeError(`Invalid RFC-3339 date-time value`);let[n,r,i,a,o,s,c,l]=t,u=Nd(sf(r)),d=rf(i,`month`,1,12),f=rf(a,`day`,1,31);return Yd(u,d,f,{hours:o,minutes:s,seconds:c,fractionalMilliseconds:l})},Hd=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),Ud=e=>{if(e==null)return;if(typeof e!=`string`)throw TypeError(`RFC-3339 date-times must be expressed as strings`);let t=Hd.exec(e);if(!t)throw TypeError(`Invalid RFC-3339 date-time value`);let[n,r,i,a,o,s,c,l,u]=t,d=Nd(sf(r)),f=rf(i,`month`,1,12),p=rf(a,`day`,1,31),m=Yd(d,f,p,{hours:o,minutes:s,seconds:c,fractionalMilliseconds:l});return u.toUpperCase()!=`Z`&&m.setTime(m.getTime()-of(u)),m},Wd=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Gd=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Kd=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),qd=e=>{if(e==null)return;if(typeof e!=`string`)throw TypeError(`RFC-7231 date-times must be expressed as strings`);let t=Wd.exec(e);if(t){let[e,n,r,i,a,o,s,c]=t;return Yd(Nd(sf(i)),$d(r),rf(n,`day`,1,31),{hours:a,minutes:o,seconds:s,fractionalMilliseconds:c})}if(t=Gd.exec(e),t){let[e,n,r,i,a,o,s,c]=t;return Qd(Yd(Xd(i),$d(r),rf(n,`day`,1,31),{hours:a,minutes:o,seconds:s,fractionalMilliseconds:c}))}if(t=Kd.exec(e),t){let[e,n,r,i,a,o,s,c]=t;return Yd(Nd(sf(c)),$d(n),rf(r.trimLeft(),`day`,1,31),{hours:i,minutes:a,seconds:o,fractionalMilliseconds:s})}throw TypeError(`Invalid RFC-7231 date-time value`)},Jd=e=>{if(e==null)return;let t;if(typeof e==`number`)t=e;else if(typeof e==`string`)t=bd(e);else if(typeof e==`object`&&e.tag===1)t=e.value;else throw TypeError(`Epoch timestamps must be expressed as floating point numbers or their string representation`);if(Number.isNaN(t)||t===1/0||t===-1/0)throw TypeError(`Epoch timestamps must be valid, non-Infinite, non-NaN numerics`);return new Date(Math.round(t*1e3))},Yd=(e,t,n,r)=>{let i=t-1;return tf(e,i,n),new Date(Date.UTC(e,i,n,rf(r.hours,`hour`,0,23),rf(r.minutes,`minute`,0,59),rf(r.seconds,`seconds`,0,60),af(r.fractionalMilliseconds)))},Xd=e=>{let t=new Date().getUTCFullYear(),n=Math.floor(t/100)*100+Nd(sf(e));return n<t?n+100:n},Zd=50*365*24*60*60*1e3,Qd=e=>e.getTime()-new Date().getTime()>Zd?new Date(Date.UTC(e.getUTCFullYear()-100,e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())):e,$d=e=>{let t=zd.indexOf(e);if(t<0)throw TypeError(`Invalid month: ${e}`);return t+1},ef=[31,28,31,30,31,30,31,31,30,31,30,31],tf=(e,t,n)=>{let r=ef[t];if(t===1&&nf(e)&&(r=29),n>r)throw TypeError(`Invalid day for ${zd[t]} in ${e}: ${n}`)},nf=e=>e%4==0&&(e%100!=0||e%400==0),rf=(e,t,n,r)=>{let i=Pd(sf(e));if(i<n||i>r)throw TypeError(`${t} must be between ${n} and ${r}, inclusive`);return i},af=e=>e==null?0:Sd(`0.`+e)*1e3,of=e=>{let t=e[0],n=1;if(t==`+`)n=1;else if(t==`-`)n=-1;else throw TypeError(`Offset direction, ${t}, must be "+" or "-"`);let r=Number(e.substring(1,3)),i=Number(e.substring(4,6));return n*(r*60+i)*60*1e3},sf=e=>{let t=0;for(;t<e.length-1&&e.charAt(t)===`0`;)t++;return t===0?e:e.slice(t)}})),cf,zue=n((()=>{cf=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})},cf.from=e=>e&&typeof e==`object`&&(e instanceof cf||`deserializeJSON`in e)?e:typeof e==`string`||Object.getPrototypeOf(e)===String.prototype?cf(String(e)):cf(JSON.stringify(e)),cf.fromObject=cf.from}));function Bue(e){return(e.includes(`,`)||e.includes(`"`))&&(e=`"${e.replace(/"/g,`\\"`)}"`),e}var Vue=n((()=>{}));function lf(e,t,n){let r=Number(e);if(r<t||r>n)throw Error(`Value ${r} out of range [${t}, ${n}]`)}var uf,df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Hue=n((()=>{uf=`(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`,df=`(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`,ff=`(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`,pf=`(\\d?\\d)`,mf=`(\\d{4})`,hf=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),gf=RegExp(`^${uf}, ${pf} ${df} ${mf} ${ff} GMT$`),_f=RegExp(`^${uf}, ${pf}-${df}-(\\d\\d) ${ff} GMT$`),vf=RegExp(`^${uf} ${df} ( [1-9]|\\d\\d) ${ff} ${mf}$`),yf=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],bf=e=>{if(e==null)return;let t=NaN;if(typeof e==`number`)t=e;else if(typeof e==`string`){if(!/^-?\d*\.?\d+$/.test(e))throw TypeError(`parseEpochTimestamp - numeric string invalid.`);t=Number.parseFloat(e)}else typeof e==`object`&&e.tag===1&&(t=e.value);if(isNaN(t)||Math.abs(t)===1/0)throw TypeError(`Epoch timestamps must be valid finite numbers.`);return new Date(Math.round(t*1e3))},xf=e=>{if(e==null)return;if(typeof e!=`string`)throw TypeError(`RFC3339 timestamps must be strings`);let t=hf.exec(e);if(!t)throw TypeError(`Invalid RFC3339 timestamp format ${e}`);let[,n,r,i,a,o,s,,c,l]=t;lf(r,1,12),lf(i,1,31),lf(a,0,23),lf(o,0,59),lf(s,0,60);let u=new Date(Date.UTC(Number(n),Number(r)-1,Number(i),Number(a),Number(o),Number(s),Number(c)?Math.round(parseFloat(`0.${c}`)*1e3):0));if(u.setUTCFullYear(Number(n)),l.toUpperCase()!=`Z`){let[,e,t,n]=/([+-])(\d\d):(\d\d)/.exec(l)||[void 0,`+`,0,0],r=e===`-`?1:-1;u.setTime(u.getTime()+r*(Number(t)*60*60*1e3+Number(n)*60*1e3))}return u},Sf=e=>{if(e==null)return;if(typeof e!=`string`)throw TypeError(`RFC7231 timestamps must be strings.`);let t,n,r,i,a,o,s,c;if((c=gf.exec(e))?[,t,n,r,i,a,o,s]=c:(c=_f.exec(e))?([,t,n,r,i,a,o,s]=c,r=(Number(r)+1900).toString()):(c=vf.exec(e))&&([,n,t,i,a,o,s,r]=c),r&&o){let e=Date.UTC(Number(r),yf.indexOf(n),Number(t),Number(i),Number(a),Number(o),s?Math.round(parseFloat(`0.${s}`)*1e3):0);lf(t,1,31),lf(i,0,23),lf(a,0,59),lf(o,0,60);let c=new Date(e);return c.setUTCFullYear(Number(r)),c}throw TypeError(`Invalid RFC7231 date-time value ${e}.`)}}));function Uue(e,t,n){if(n<=0||!Number.isInteger(n))throw Error(`Invalid number of delimiters (`+n+`) for splitEvery.`);let r=e.split(t);if(n===1)return r;let i=[],a=``;for(let e=0;e<r.length;e++)a===``?a=r[e]:a+=t+r[e],(e+1)%n===0&&(i.push(a),a=``);return a!==``&&i.push(a),i}var Wue=n((()=>{})),Cf,Gue=n((()=>{Cf=e=>{let t=e.length,n=[],r=!1,i,a=0;for(let o=0;o<t;++o){let t=e[o];switch(t){case`"`:i!==`\\`&&(r=!r);break;case`,`:r||(n.push(e.slice(a,o)),a=o+1);break;default:}i=t}return n.push(e.slice(a)),n.map(e=>{e=e.trim();let t=e.length;return t<2?e:(e[0]===`"`&&e[t-1]===`"`&&(e=e.slice(1,t-1)),e.replace(/\\"/g,`"`))})}}));function Kue(e){return new Tf(String(e),`bigDecimal`)}var wf,Tf,que=n((()=>{wf=/^-?\d*(\.\d+)?$/,Tf=class e{string;type;constructor(e,t){if(this.string=e,this.type=t,!wf.test(e))throw Error(`@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".`)}toString(){return this.string}static[Symbol.hasInstance](t){if(!t||typeof t!=`object`)return!1;let n=t;return e.prototype.isPrototypeOf(t)||n.type===`bigDecimal`&&wf.test(n.string)}}}));function Ef(e){if(e.length%2!=0)throw Error(`Hex encoded strings must have an even number length`);let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2){let r=e.slice(n,n+2).toLowerCase();if(r in kf)t[n/2]=kf[r];else throw Error(`Cannot decode unrecognized sequence ${r} as hexadecimal`)}return t}function Df(e){let t=``;for(let n=0;n<e.byteLength;n++)t+=Of[e[n]];return t}var Of,kf,Af=n((()=>{Of={},kf={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();t.length===1&&(t=`0${t}`),Of[e]=t,kf[t]=e}})),jf,Jue=n((()=>{jf=e=>{if(!e)return 0;if(typeof e==`string`)return Buffer.byteLength(e);if(typeof e.byteLength==`number`)return e.byteLength;if(typeof e.size==`number`)return e.size;if(typeof e.start==`number`&&typeof e.end==`number`)return e.end+1-e.start;if(e instanceof s){if(e.path!=null)return l(e.path).size;if(typeof e.fd==`number`)return c(e.fd).size}throw Error(`Body Length computation failed for ${e}`)}})),Mf,Nf=n((()=>{Qu(),Mf=e=>e instanceof Uint8Array?e:typeof e==`string`?Zu(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}));function Pf(e,t){if(t===void 0){t=0;for(let n of e)t+=n.byteLength}let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}var Ff=n((()=>{})),If,Yue=n((()=>{If=class{statusCode;reason;headers;body;constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;let t=e;return typeof t.statusCode==`number`&&typeof t.headers==`object`}}}));function Xue(e){let t={};if(e=e.replace(/^\?/,``),e)for(let n of e.split(`&`)){let[e,r=null]=n.split(`=`);e=decodeURIComponent(e),r&&=decodeURIComponent(r),e in t?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:t[e]=r}return t}var Zue=n((()=>{})),Lf,Rf=n((()=>{Zue(),Lf=e=>{if(typeof e==`string`)return Lf(new URL(e));let{hostname:t,pathname:n,port:r,protocol:i,search:a}=e,o;return a&&(o=Xue(a)),{hostname:t,port:r?parseInt(r):void 0,protocol:i,path:n,query:o}}})),zf,Que=n((()=>{Rf(),zf=e=>{if(typeof e==`object`){if(`url`in e){let t=Lf(e.url);if(e.headers){t.headers={};for(let n in e.headers)t.headers[n.toLowerCase()]=e.headers[n].join(`, `)}return t}return e}return Lf(e)}})),Bf=n((()=>{Yue(),Rf(),Que()})),Vf,Hf,Uf=n((()=>{Bf(),Vf=(e,t)=>(n,r)=>async i=>{let{response:a}=await n(i);try{return{response:a,output:await t(a,e)}}catch(e){if(Object.defineProperty(e,"$response",{value:a,enumerable:!1,writable:!1,configurable:!1}),!(`$metadata`in e)){let t=`Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;try{e.message+=`
|
|
83
83
|
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch{!r.logger||r.logger?.constructor?.name===`NoOpLogger`?console.warn(t):r.logger?.warn?.(t)}e.$responseBodyText!==void 0&&e.$response&&(e.$response.body=e.$responseBodyText);try{if(If.isInstance(a)){let{headers:t={}}=a,n=Object.entries(t);e.$metadata={httpStatusCode:a.statusCode,requestId:Hf(/^x-[\w-]+-request-?id$/,n),extendedRequestId:Hf(/^x-[\w-]+-id-2$/,n),cfId:Hf(/^x-[\w-]+-cf-id$/,n)}}}catch{}}throw e}},Hf=(e,t)=>(t.find(([t])=>t.match(e))||[void 0,void 0])[1]})),$ue=n((()=>{Bf()})),Wf,Gf=n((()=>{$ue(),Wf=(e,t)=>(n,r)=>async i=>{let a=e,o=r.endpointV2?async()=>zf(r.endpointV2):a.endpoint;if(!o)throw Error(`No valid endpoint provider available.`);let s=await t(i.input,{...e,endpoint:o});return n({...i,request:s})}}));function ede(e,t,n){return{applyToStack:r=>{r.add(Vf(e,n),Kf),r.add(Wf(e,t),qf)}}}var Kf,qf,tde=n((()=>{Uf(),Gf(),Kf={name:`deserializerMiddleware`,step:`deserialize`,tags:[`DESERIALIZER`],override:!0},qf={name:`serializerMiddleware`,step:`serialize`,tags:[`SERIALIZER`],override:!0}}));function Jf(e,t){return Buffer.isBuffer(e)?e:typeof e==`string`?qu(e,t):ArrayBuffer.isView(e)?Ku(e.buffer,e.byteOffset,e.byteLength):Ku(e)}var Yf,nde=n((()=>{Ju(),Nf(),Yf=class{algorithmIdentifier;secret;hash;constructor(e,t){this.algorithmIdentifier=e,this.secret=t,this.reset()}update(e,t){this.hash.update(Mf(Jf(e,t)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?h(this.algorithmIdentifier,Jf(this.secret)):m(this.algorithmIdentifier)}}})),Xf,Zf=n((()=>{ed(),Xf=class extends f{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:e,checksum:t,source:n,checksumSourceLocation:r,base64Encoder:i}){if(super(),typeof n.pipe!=`function`)throw Error(`@smithy/util-stream: unsupported source type ${n?.constructor?.name??n} in ChecksumStream.`);this.source=n,this.base64Encoder=i??$u,this.expectedChecksum=e,this.checksum=t,this.checksumSourceLocation=r,this.source.on(`data`,this.onSourceData),this.source.on(`end`,this.onSourceEnd),this.source.on(`error`,this.onSourceError),this.source.pause()}onSourceData=e=>{if(!this.destroyed){try{this.checksum.update(e)}catch(e){this.destroy(e);return}this.push(e)||this.source.pause()}};onSourceEnd=async()=>{if(!this.destroyed){try{let e=await this.checksum.digest(),t=this.base64Encoder(e);if(this.expectedChecksum!==t){this.destroy(Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${t}" in response header "${this.checksumSourceLocation}".`));return}}catch(e){this.destroy(e);return}this.push(null)}};onSourceError=e=>{this.destroy(e)};_read(e){this.source.resume()}_destroy(e,t){this.source?.destroy(),t(e)}}})),Qf,$f,ep=n((()=>{Qf=e=>typeof ReadableStream==`function`&&(e?.constructor?.name===ReadableStream.name||e instanceof ReadableStream),$f=e=>typeof Blob==`function`&&(e?.constructor?.name===Blob.name||e instanceof Blob)})),tp,rde=n((()=>{tp=e=>new TextEncoder().encode(e)})),np,rp,ide=n((()=>{np=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Object.entries(np).reduce((e,[t,n])=>(e[n]=Number(t),e),{}),rp=np.split(``)}));function ip(e){let t;t=typeof e==`string`?tp(e):e;let n=typeof t==`object`&&typeof t.length==`number`,r=typeof t==`object`&&typeof t.byteOffset==`number`&&typeof t.byteLength==`number`;if(!n&&!r)throw Error(`@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.`);let i=``;for(let e=0;e<t.length;e+=3){let n=0,r=0;for(let i=e,a=Math.min(e+3,t.length);i<a;i++)n|=t[i]<<(a-i-1)*8,r+=8;let a=Math.ceil(r/6);n<<=a*6-r;for(let e=1;e<=a;e++){let t=(a-e)*6;i+=rp[(n&63<<t)>>t]}i+=`==`.slice(0,4-a)}return i}var ap=n((()=>{rde(),ide()})),op,sp,ade=n((()=>{op=typeof ReadableStream==`function`?ReadableStream:function(){},sp=class extends op{}})),cp,ode=n((()=>{ap(),ep(),ade(),cp=({expectedChecksum:e,checksum:t,source:n,checksumSourceLocation:r,base64Encoder:i})=>{if(!Qf(n))throw Error(`@smithy/util-stream: unsupported source type ${n?.constructor?.name??n} in ChecksumStream.`);let a=i??ip;if(typeof TransformStream!=`function`)throw Error(`@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.`);let o=new TransformStream({start(){},async transform(e,n){t.update(e),n.enqueue(e)},async flush(n){let i=await t.digest(),o=a(i);if(e!==o){let t=Error(`Checksum mismatch: expected "${e}" but received "${o}" in response header "${r}".`);n.error(t)}else n.terminate()}});n.pipeThrough(o);let s=o.readable;return Object.setPrototypeOf(s,sp.prototype),s}}));function sde(e){return typeof ReadableStream==`function`&&Qf(e.source)?cp(e):new Xf(e)}var cde=n((()=>{ep(),Zf(),ode()})),lp,up=n((()=>{lp=class{allocByteArray;byteLength=0;byteArrays=[];constructor(e){this.allocByteArray=e}push(e){this.byteArrays.push(e),this.byteLength+=e.byteLength}flush(){if(this.byteArrays.length===1){let e=this.byteArrays[0];return this.reset(),e}let e=this.allocByteArray(this.byteLength),t=0;for(let n=0;n<this.byteArrays.length;++n){let r=this.byteArrays[n];e.set(r,t),t+=r.byteLength}return this.reset(),e}reset(){this.byteArrays=[],this.byteLength=0}}}));function lde(e,t,n){let r=e.getReader(),i=!1,a=0,o=[``,new lp(e=>new Uint8Array(e))],s=-1,c=async e=>{let{value:l,done:u}=await r.read(),d=l;if(u){if(s!==-1){let t=fp(o,s);pp(t)>0&&e.enqueue(t)}e.close()}else{let r=mp(d,!1);if(s!==r&&(s>=0&&e.enqueue(fp(o,s)),s=r),s===-1){e.enqueue(d);return}let l=pp(d);a+=l;let u=pp(o[s]);if(l>=t&&u===0)e.enqueue(d);else{let r=dp(o,s,d);!i&&a>t*2&&(i=!0,n?.warn(`@smithy/util-stream - stream chunk size ${l} is below threshold of ${t}, automatically buffering.`)),r>=t?e.enqueue(fp(o,s)):await c(e)}}};return new ReadableStream({pull:c})}function dp(e,t,n){switch(t){case 0:return e[0]+=n,pp(e[0]);case 1:case 2:return e[t].push(n),pp(e[t])}}function fp(e,t){switch(t){case 0:let n=e[0];return e[0]=``,n;case 1:case 2:return e[t].flush()}throw Error(`@smithy/util-stream - invalid index ${t} given to flush()`)}function pp(e){return e?.byteLength??e?.length??0}function mp(e,t=!0){return t&&typeof Buffer<`u`&&e instanceof Buffer?2:e instanceof Uint8Array?1:typeof e==`string`?0:-1}var ude=n((()=>{up()}));function dde(e,t,n){if(Qf(e))return lde(e,t,n);let r=new f({read(){}}),i=!1,a=0,o=[``,new lp(e=>new Uint8Array(e)),new lp(e=>Buffer.from(new Uint8Array(e)))],s=-1;return e.on(`data`,e=>{let c=mp(e,!0);if(s!==c&&(s>=0&&r.push(fp(o,s)),s=c),s===-1){r.push(e);return}let l=pp(e);a+=l;let u=pp(o[s]);if(l>=t&&u===0)r.push(e);else{let c=dp(o,s,e);!i&&a>t*2&&(i=!0,n?.warn(`@smithy/util-stream - stream chunk size ${l} is below threshold of ${t}, automatically buffering.`)),c>=t&&r.push(fp(o,s))}}),e.on(`end`,()=>{if(s!==-1){let e=fp(o,s);pp(e)>0&&r.push(e)}r.push(null)}),r}var fde=n((()=>{up(),ude(),ep()})),hp,pde=n((()=>{hp=(e,t)=>{let{base64Encoder:n,bodyLengthChecker:r,checksumAlgorithmFn:i,checksumLocationName:a,streamHasher:o}=t,s=n!==void 0&&r!==void 0&&i!==void 0&&a!==void 0&&o!==void 0,c=s?o(i,e):void 0,l=e.getReader();return new ReadableStream({async pull(e){let{value:t,done:i}=await l.read();if(i){if(e.enqueue(`0\r
|