@activepieces/piece-ai 0.4.5 → 0.4.6
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/package.json +1 -1
- package/src/index.js +4 -4
package/package.json
CHANGED
package/src/index.js
CHANGED
|
@@ -173,9 +173,9 @@ ${u}
|
|
|
173
173
|
${u}
|
|
174
174
|
|
|
175
175
|
`;break}case"tool":throw new ca({functionality:"tool messages"});default:break}return n+=`${a}:
|
|
176
|
-
`,{prompt:n}}s(Gie,"convertToOpenRouterCompletionPrompt");var z2=r.union([r.object({id:r.string().optional(),model:r.string().optional(),provider:r.string().optional(),choices:r.array(r.object({text:r.string(),reasoning:r.string().nullish().optional(),reasoning_details:SS.nullish(),finish_reason:r.string().nullish(),index:r.number().nullish(),logprobs:r.object({tokens:r.array(r.string()),token_logprobs:r.array(r.number()),top_logprobs:r.array(r.record(r.string(),r.number())).nullable()}).passthrough().nullable().optional()}).passthrough()),usage:r.object({prompt_tokens:r.number(),prompt_tokens_details:r.object({cached_tokens:r.number()}).passthrough().nullish(),completion_tokens:r.number(),completion_tokens_details:r.object({reasoning_tokens:r.number()}).passthrough().nullish(),total_tokens:r.number(),cost:r.number().optional(),cost_details:r.object({upstream_inference_cost:r.number().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),jy]),Kie=class{static{s(this,"OpenRouterCompletionLanguageModel")}constructor(e,t,o){this.specificationVersion="v3",this.provider="openrouter",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"text/*":[/^data:text\//,/^https?:\/\/.+$/],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.defaultObjectGenerationMode=void 0,this.modelId=e,this.settings=t,this.config=o}getArgs({prompt:e,maxOutputTokens:t,temperature:o,topP:a,frequencyPenalty:n,presencePenalty:i,seed:l,responseFormat:u,topK:c,stopSequences:d,tools:p,toolChoice:m}){let{prompt:f}=Gie({prompt:e,inputFormat:"prompt"});if(p?.length)throw new ca({functionality:"tools"});if(m)throw new ca({functionality:"toolChoice"});return ve(ve({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:t,temperature:o,top_p:a,frequency_penalty:n,presence_penalty:i,seed:l,stop:d,response_format:u,top_k:c,prompt:f,include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning},this.config.extraBody),this.settings.extraBody)}async doGenerate(e){var t,o,a,n,i,l,u,c,d,p,m,f,h,g,y,_,v,x,w,S,P,k,I,E,b,M,R,D;let ee=(e.providerOptions||{}).openrouter||{},J=ve(ve({},this.getArgs(e)),ee),{value:W,responseHeaders:j}=await du({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:cu(this.config.headers(),e.headers),body:J,failedResponseHandler:pu,successfulResponseHandler:Ny(z2),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in W){let Z=W.error;throw new jn({message:Z.message,url:this.config.url({path:"/completions",modelId:this.modelId}),requestBodyValues:J,statusCode:200,responseHeaders:j,data:Z})}let O=W.choices[0];if(!O)throw new bS({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:(t=O.text)!=null?t:""}],finishReason:Oy(O.finish_reason),usage:{inputTokens:{total:(a=(o=W.usage)==null?void 0:o.prompt_tokens)!=null?a:0,noCache:void 0,cacheRead:(l=(i=(n=W.usage)==null?void 0:n.prompt_tokens_details)==null?void 0:i.cached_tokens)!=null?l:void 0,cacheWrite:void 0},outputTokens:{total:(c=(u=W.usage)==null?void 0:u.completion_tokens)!=null?c:0,text:void 0,reasoning:(m=(p=(d=W.usage)==null?void 0:d.completion_tokens_details)==null?void 0:p.reasoning_tokens)!=null?m:void 0},raw:(f=W.usage)!=null?f:void 0},warnings:[],providerMetadata:{openrouter:IS.parse({provider:(h=W.provider)!=null?h:"",usage:ve(ve(ve(ve({promptTokens:(y=(g=W.usage)==null?void 0:g.prompt_tokens)!=null?y:0,completionTokens:(v=(_=W.usage)==null?void 0:_.completion_tokens)!=null?v:0,totalTokens:((w=(x=W.usage)==null?void 0:x.prompt_tokens)!=null?w:0)+((P=(S=W.usage)==null?void 0:S.completion_tokens)!=null?P:0)},((k=W.usage)==null?void 0:k.cost)!=null?{cost:W.usage.cost}:{}),((E=(I=W.usage)==null?void 0:I.prompt_tokens_details)==null?void 0:E.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:W.usage.prompt_tokens_details.cached_tokens}}:{}),((M=(b=W.usage)==null?void 0:b.completion_tokens_details)==null?void 0:M.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:W.usage.completion_tokens_details.reasoning_tokens}}:{}),((D=(R=W.usage)==null?void 0:R.cost_details)==null?void 0:D.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:W.usage.cost_details.upstream_inference_cost}}:{})})},response:{headers:j}}}async doStream(e){let o=(e.providerOptions||{}).openrouter||{},a=ve(ve({},this.getArgs(e)),o),{value:n,responseHeaders:i}=await du({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:cu(this.config.headers(),e.headers),body:Pt(ve({},a),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:pu,successfulResponseHandler:wU(z2),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=Ai("other"),u={inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0},c={},d,p;return{stream:n.pipeThrough(new TransformStream({transform(m,f){var h,g,y;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:m.rawValue}),!m.success){l=Ai("error"),f.enqueue({type:"error",error:m.error});return}let _=m.value;if("error"in _){l=Ai("error"),f.enqueue({type:"error",error:_.error});return}if(_.provider&&(d=_.provider),_.usage!=null){if(u.inputTokens.total=_.usage.prompt_tokens,u.outputTokens.total=_.usage.completion_tokens,p=_.usage,c.promptTokens=_.usage.prompt_tokens,_.usage.prompt_tokens_details){let w=(h=_.usage.prompt_tokens_details.cached_tokens)!=null?h:0;u.inputTokens.cacheRead=w,c.promptTokensDetails={cachedTokens:w}}if(c.completionTokens=_.usage.completion_tokens,_.usage.completion_tokens_details){let w=(g=_.usage.completion_tokens_details.reasoning_tokens)!=null?g:0;u.outputTokens.reasoning=w,c.completionTokensDetails={reasoningTokens:w}}_.usage.cost!=null&&(c.cost=_.usage.cost),c.totalTokens=_.usage.total_tokens;let x=(y=_.usage.cost_details)==null?void 0:y.upstream_inference_cost;x!=null&&(c.costDetails={upstreamInferenceCost:x})}let v=_.choices[0];v?.finish_reason!=null&&(l=Oy(v.finish_reason)),v?.text!=null&&f.enqueue({type:"text-delta",delta:v.text,id:Nn()})},flush(m){u.raw=p;let f={usage:c};d!==void 0&&(f.provider=d),m.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:{openrouter:f}})}})),response:{headers:i}}}},Xie=r.object({prompt_tokens:r.number(),total_tokens:r.number(),cost:r.number().optional()}),Yie=r.object({object:r.literal("embedding"),embedding:r.array(r.number()),index:r.number().optional()}),Qie=r.object({id:r.string().optional(),object:r.literal("list"),data:r.array(Yie),model:r.string(),provider:r.string().optional(),usage:Xie.optional()}),ese=class{static{s(this,"OpenRouterEmbeddingModel")}constructor(e,t,o){this.specificationVersion="v3",this.provider="openrouter",this.maxEmbeddingsPerCall=void 0,this.supportsParallelCalls=!0,this.modelId=e,this.settings=t,this.config=o}async doEmbed(e){var t,o,a,n,i,l;let{values:u,abortSignal:c,headers:d}=e,p=ve(ve({model:this.modelId,input:u,user:this.settings.user,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody),{value:m,responseHeaders:f}=await du({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:cu(this.config.headers(),d),body:p,failedResponseHandler:pu,successfulResponseHandler:Ny(Qie),abortSignal:c,fetch:this.config.fetch});return{embeddings:m.data.map(h=>h.embedding),usage:m.usage?{tokens:m.usage.prompt_tokens}:void 0,providerMetadata:{openrouter:IS.parse({provider:(t=m.provider)!=null?t:"",usage:ve({promptTokens:(a=(o=m.usage)==null?void 0:o.prompt_tokens)!=null?a:0,completionTokens:0,totalTokens:(i=(n=m.usage)==null?void 0:n.total_tokens)!=null?i:0},((l=m.usage)==null?void 0:l.cost)!=null?{cost:m.usage.cost}:{})})},response:{headers:f,body:m},warnings:[]}}};var tse=r.object({id:r.string().optional(),object:r.string().optional(),created:r.number().optional(),model:r.string(),choices:r.array(r.object({index:r.number(),message:r.object({role:r.string(),content:r.string().nullable().optional(),images:r.array(r.object({type:r.literal("image_url"),image_url:r.object({url:r.string()})}).passthrough()).optional()}).passthrough(),finish_reason:r.string().nullable().optional()}).passthrough()),usage:r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number()}).passthrough().optional()}).passthrough(),rse=class{static{s(this,"OpenRouterImageModel")}constructor(e,t,o){this.specificationVersion="v3",this.provider="openrouter",this.maxImagesPerCall=1,this.modelId=e,this.settings=t,this.config=o}async doGenerate(e){var t;let{prompt:o,n:a,size:n,aspectRatio:i,seed:l,files:u,mask:c,abortSignal:d,headers:p,providerOptions:m}=e,f=m?.openrouter||{},h=[];if(u!==void 0&&u.length>0)throw new ca({functionality:"image editing (files parameter)"});if(c!==void 0)throw new ca({functionality:"image inpainting (mask parameter)"});a>1&&h.push({type:"unsupported",feature:"n > 1",details:`OpenRouter image generation returns 1 image per call. Requested ${a} images.`}),n!==void 0&&h.push({type:"unsupported",feature:"size",details:"Use aspectRatio instead. Size parameter is not supported by OpenRouter image generation."});let g=i!==void 0?{aspect_ratio:i}:void 0,y=ve(ve(ve(ve(ve(ve(ve({model:this.modelId,messages:[{role:"user",content:o??""}],modalities:["image","text"]},g!==void 0&&{image_config:g}),l!==void 0&&{seed:l}),this.settings.user!==void 0&&{user:this.settings.user}),this.settings.provider!==void 0&&{provider:this.settings.provider}),this.config.extraBody),this.settings.extraBody),f),{value:_,responseHeaders:v}=await du({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:cu(this.config.headers(),p),body:y,failedResponseHandler:pu,successfulResponseHandler:Ny(tse),abortSignal:d,fetch:this.config.fetch}),x=_.choices[0];if(!x)throw new bS({message:"No choice in response"});let w=[];if((t=x.message)!=null&&t.images)for(let P of x.message.images){let k=P.image_url.url;w.push($y(k))}let S=_.usage?{inputTokens:_.usage.prompt_tokens,outputTokens:_.usage.completion_tokens,totalTokens:_.usage.total_tokens}:void 0;return{images:w,warnings:h,response:{timestamp:new Date,modelId:_.model,headers:v},usage:S}}};function ose(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}s(ose,"removeUndefinedEntries");function nse(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):e:{}}s(nse,"normalizeHeaders2");function ase(e,t){let o=t.toLowerCase();return Object.keys(e).find(a=>a.toLowerCase()===o)}s(ase,"findHeaderKey");function ise(e,...t){let o=nse(e),a=ose(o),n=ase(a,"user-agent"),i=n?a[n]:void 0,l=i?.trim()?i:t.filter(Boolean).join(" "),u=Object.fromEntries(Object.entries(a).filter(([c])=>c.toLowerCase()!=="user-agent"));return Pt(ve({},u),{"user-agent":l})}s(ise,"withUserAgentSuffix2");var sse="2.1.1";function My(e={}){var t,o,a;let n=(o=Oie((t=e.baseURL)!=null?t:e.baseUrl))!=null?o:"https://openrouter.ai/api/v1",i=(a=e.compatibility)!=null?a:"compatible",l=s(()=>ise(ve(ve({Authorization:`Bearer ${Eae({apiKey:e.apiKey,environmentVariableName:"OPENROUTER_API_KEY",description:"OpenRouter"})}`},e.headers),e.api_keys&&Object.keys(e.api_keys).length>0&&{"X-Provider-API-Keys":JSON.stringify(e.api_keys)}),`ai-sdk/openrouter/${sse}`),"getHeaders"),u=s((h,g={})=>new Wie(h,g,{provider:"openrouter.chat",url:s(({path:y})=>`${n}${y}`,"url"),headers:l,compatibility:i,fetch:e.fetch,extraBody:e.extraBody}),"createChatModel"),c=s((h,g={})=>new Kie(h,g,{provider:"openrouter.completion",url:s(({path:y})=>`${n}${y}`,"url"),headers:l,compatibility:i,fetch:e.fetch,extraBody:e.extraBody}),"createCompletionModel"),d=s((h,g={})=>new ese(h,g,{provider:"openrouter.embedding",url:s(({path:y})=>`${n}${y}`,"url"),headers:l,fetch:e.fetch,extraBody:e.extraBody}),"createEmbeddingModel"),p=s((h,g={})=>new rse(h,g,{provider:"openrouter.image",url:s(({path:y})=>`${n}${y}`,"url"),headers:l,fetch:e.fetch,extraBody:e.extraBody}),"createImageModel"),m=s((h,g)=>{if(new.target)throw new Error("The OpenRouter model function cannot be called with the new keyword.");return h==="openai/gpt-3.5-turbo-instruct"?c(h,g):u(h,g)},"createLanguageModel"),f=s((h,g)=>m(h,g),"provider");return f.languageModel=m,f.chat=u,f.completion=c,f.textEmbeddingModel=d,f.embedding=d,f.imageModel=p,f}s(My,"createOpenRouter");var vLe=My({compatibility:"strict"});var lse=Object.defineProperty,use=s((e,t,o)=>t in e?lse(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,"__defNormalProp"),$p=s((e,t,o)=>use(e,typeof t!="symbol"?t+"":t,o),"__publicField"),cse="CF_TEMP_TOKEN",dse=[{name:"openai",regex:/^https:\/\/api\.openai\.com\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.openai\.com\//,""),"transformEndpoint")},{name:"deepseek",regex:/^https:\/\/api\.deepseek\.com\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.deepseek\.com\//,""),"transformEndpoint")},{name:"anthropic",regex:/^https:\/\/api\.anthropic\.com\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.anthropic\.com\//,""),"transformEndpoint"),headerKey:"x-api-key"},{name:"google-ai-studio",regex:/^https:\/\/generativelanguage\.googleapis\.com\//,headerKey:"x-goog-api-key",transformEndpoint:s(e=>e.replace(/^https:\/\/generativelanguage\.googleapis\.com\//,""),"transformEndpoint")},{name:"google-vertex-ai",regex:/aiplatform\.googleapis\.com/,transformEndpoint:s(e=>e.replace(/https:\/\/(.*)[-]?aiplatform\.googleapis\.com\//,""),"transformEndpoint")},{name:"grok",regex:/^https:\/\/api\.x\.ai\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.x\.ai\//,""),"transformEndpoint")},{name:"mistral",regex:/^https:\/\/api\.mistral\.ai\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.mistral\.ai\//,""),"transformEndpoint")},{name:"perplexity-ai",regex:/^https:\/\/api\.perplexity\.ai\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.perplexity\.ai\//,""),"transformEndpoint")},{name:"replicate",regex:/^https:\/\/api\.replicate\.com\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.replicate\.com\//,""),"transformEndpoint")},{name:"groq",regex:/^https:\/\/api\.groq\.com\/openai\/v1\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.groq\.com\/openai\/v1\//,""),"transformEndpoint")},{name:"google-vertex-ai",regex:/^https:\/\/(?:[a-z0-9]+-)*aiplatform\.googleapis\.com\//,transformEndpoint:s(e=>e.replace(/^https:\/\/(?:[a-z0-9]+-)*aiplatform\.googleapis\.com\//,""),"transformEndpoint"),headerKey:"authorization"},{name:"azure-openai",regex:/^https:\/\/(?<resource>[^.]+)\.openai\.azure\.com\/openai\/deployments\/(?<deployment>[^/]+)\/(?<rest>.*)$/,transformEndpoint:s(e=>{let t=e.match(/^https:\/\/(?<resource>[^.]+)\.openai\.azure\.com\/openai\/deployments\/(?<deployment>[^/]+)\/(?<rest>.*)$/);if(!t||!t.groups)return e;let{resource:o,deployment:a,rest:n}=t.groups;if(!o||!a||!n)throw new Error("Failed to parse Azure OpenAI endpoint URL.");return`${o}/${a}/${n}`},"transformEndpoint"),headerKey:"api-key"},{name:"openrouter",regex:/^https:\/\/openrouter\.ai\/api\//,transformEndpoint:s(e=>e.replace(/^https:\/\/openrouter\.ai\/api\//,""),"transformEndpoint")},{name:"compat",regex:/^https:\/\/gateway\.ai\.cloudflare\.com\/v1\/compat\//,transformEndpoint:s(e=>e.replace(/^https:\/\/gateway\.ai\.cloudflare\.com\/v1\/compat\//,""),"transformEndpoint")}],EU=class extends Error{static{s(this,"AiGatewayInternalFetchError")}},pse=class extends Error{static{s(this,"AiGatewayDoesNotExist")}},mse=class extends Error{static{s(this,"AiGatewayUnauthorizedError")}};async function fse(e){return await new Response(e).json()}s(fse,"streamToObject");var hse=class{static{s(this,"AiGatewayChatLanguageModel")}constructor(e,t){$p(this,"specificationVersion","v3"),$p(this,"defaultObjectGenerationMode","json"),$p(this,"supportedUrls",{}),$p(this,"models"),$p(this,"config"),this.models=e,this.config=t}get modelId(){if(!this.models[0])throw new Error("models cannot be empty array");return this.models[0].modelId}get provider(){if(!this.models[0])throw new Error("models cannot be empty array");return this.models[0].provider}async processModelRequest(e,t){let o=[];for(let u of this.models){if(!u.config||!Object.keys(u.config).includes("fetch"))throw new Error(`Sorry, but provider "${u.provider}" is currently not supported, please open a issue in the github repo!`);u.config.fetch=(c,d)=>{throw o.push({modelProvider:u.provider,request:d,url:c}),new EU("Stopping provider execution...")};try{await u[t](e)}catch(c){if(!(c instanceof EU))throw c}}let a=await Promise.all(o.map(async u=>{let c=null;for(let m of dse)m.regex.test(u.url)&&(c=m);if(!c)throw new Error(`Sorry, but provider "${u.modelProvider}" is currently not supported, please open a issue in the github repo!`);if(!u.request.body)throw new Error("Ai Gateway provider received an unexpected empty body");let d=c.headerKey??"authorization";return("get"in u.request.headers?u.request.headers.get(d):u.request.headers[d])?.indexOf(cse)!==-1&&("delete"in u.request.headers?u.request.headers.delete(d):delete u.request.headers[d]),{endpoint:c.transformEndpoint(u.url),headers:u.request.headers,provider:c.name,query:await fse(u.request.body)}})),n=gse(this.config.options??{}),i;if("binding"in this.config){let u=a.map(c=>({...c,headers:{...c.headers??{},...Object.fromEntries(n.entries())}}));i=await this.config.binding.run(u)}else n.set("Content-Type","application/json"),n.set("cf-aig-authorization",`Bearer ${this.config.apiKey}`),i=await fetch(`https://gateway.ai.cloudflare.com/v1/${this.config.accountId}/${this.config.gateway}`,{body:JSON.stringify(a),headers:n,method:"POST"});if(i.status===400){let c=await i.clone().json();if(c.success===!1&&c.error&&c.error.length>0&&c.error[0]?.code===2001)throw new pse("This AI gateway does not exist")}else if(i.status===401){let c=await i.clone().json();if(c.success===!1&&c.error&&c.error.length>0&&c.error[0]?.code===2009)throw new mse("Your AI Gateway has authentication active, but you didn't provide a valid apiKey")}let l=Number.parseInt(i.headers.get("cf-aig-step")??"0",10);if(!this.models[l])throw new Error("Unexpected AI Gateway Error");return this.models[l].config={...this.models[l].config,fetch:s((u,c)=>i,"fetch")},this.models[l][t](e)}async doStream(e){return this.processModelRequest(e,"doStream")}async doGenerate(e){return this.processModelRequest(e,"doGenerate")}};function AU(e){let t=s(a=>new hse(Array.isArray(a)?a:[a],e),"createChatModel"),o=s(a=>t(a),"provider");return o.chat=t,o}s(AU,"createAiGateway");function gse(e){let t=new Headers;return e.skipCache===!0&&t.set("cf-skip-cache","true"),e.cacheTtl&&t.set("cf-cache-ttl",e.cacheTtl.toString()),e.metadata&&t.set("cf-aig-metadata",JSON.stringify(e.metadata)),e.cacheKey&&t.set("cf-aig-cache-key",e.cacheKey),e.collectLog!==void 0&&t.set("cf-aig-collect-log",e.collectLog===!0?"true":"false"),e.eventId!==void 0&&t.set("cf-aig-event-id",e.eventId),e.requestTimeoutMs!==void 0&&t.set("cf-aig-request-timeout",e.requestTimeoutMs.toString()),e.retries!==void 0&&(e.retries.maxAttempts!==void 0&&t.set("cf-aig-max-attempts",e.retries.maxAttempts.toString()),e.retries.retryDelayMs!==void 0&&t.set("cf-aig-retry-delay",e.retries.retryDelayMs.toString()),e.retries.backoff!==void 0&&t.set("cf-aig-backoff",e.retries.backoff)),t}s(gse,"parseAiGatewayOptions");var CU="CF_TEMP_TOKEN";function yse(e){return t=>t?(t.apiKey===void 0&&(t.apiKey=CU),e(t)):e({apiKey:CU})}s(yse,"authWrapper");var OU=s((...e)=>yse(gp)(...e),"createAnthropic");var $U="CF_TEMP_TOKEN";function _se(e){return t=>t?(t.apiKey===void 0&&(t.apiKey=$U),e(t)):e({apiKey:$U})}s(_se,"authWrapper");var RU=s((...e)=>_se(ws)(...e),"createGoogleGenerativeAI");async function NU(e){let{body:t}=await ia.sendRequest({method:"GET",url:`${e.apiUrl}v1/ai-providers/${e.provider}/config`,headers:{Authorization:`Bearer ${e.engineToken}`}});return t}s(NU,"fetchProviderConfig");async function Bo({provider:e,modelId:t,engineToken:o,projectId:a,flowId:n,runId:i,apiUrl:l,openaiResponsesModel:u=!1,isImage:c}){let{config:d,auth:p,platformId:m}=await NU({provider:e,engineToken:o,apiUrl:l});switch(e){case"openai":{let{apiKey:f}=p,h=Ip({apiKey:f});return c?h.imageModel(t):u?h.responses(t):h.chat(t)}case"anthropic":{let{apiKey:f}=p,h=gp({apiKey:f});if(c)throw new Error(`Provider ${h} does not support image models`);return h(t)}case"google":{let{apiKey:f}=p;return ws({apiKey:f})(t)}case"azure":{let{apiKey:f}=p,{resourceName:h,apiVersion:g}=d,y=Sy({resourceName:h,apiKey:f,apiVersion:g});return c?y.imageModel(t):y.chat(t)}case"cloudflare-gateway":{let{apiKey:f}=p,{accountId:h,gatewayId:g,vertexProject:y,vertexRegion:_}=d,v=AU({accountId:h,gateway:g,apiKey:f}),{provider:x,model:w,publisher:S}=Dh(t),P={"cf-aig-metadata":JSON.stringify({projectId:a,flowId:n,runId:i})},k={"cf-aig-authorization":`Bearer ${f}`,...P};switch(x){case"anthropic":{let I=OU({headers:k});return v(I(w))}case"google-ai-studio":{let I=RU({headers:k});return v(I(w))}case"google-vertex-ai":return y&&_&&S?ws({apiKey:f,baseURL:`https://gateway.ai.cloudflare.com/v1/${h}/${g}/google-vertex-ai/v1/projects/${y}/locations/${_}/publishers/${S}/`,headers:k})(w):zU({accountId:h,gatewayId:g,headers:k,isImage:c,modelId:t});case"openai":{let I=Ip({apiKey:"no-key",baseURL:`https://gateway.ai.cloudflare.com/v1/${h}/${g}/openai`,headers:k,fetch:s((E,b)=>{let M=new Headers(b?.headers);return M.delete("Authorization"),fetch(E,{...b,headers:M})},"fetch")});return c?I.imageModel(w):u?I.responses(w):I.chat(w)}default:return zU({accountId:h,gatewayId:g,headers:k,isImage:c,modelId:t})}}case"bedrock":{let{accessKeyId:f,secretAccessKey:h}=p,{region:g}=d,y=JT({region:g,accessKeyId:f,secretAccessKey:h});return c?y.imageModel(t):y(t)}case"custom":{let{apiKey:f}=p,{apiKeyHeader:h,baseUrl:g,defaultHeaders:y}=d,x=Ty({name:"openai-compatible",baseURL:g,headers:{...{"x-ap-project-id":a,"x-ap-platform-id":m,"x-ap-flow-id":n,"x-ap-run-id":i},...y??{},[h]:f}});return c?x.imageModel(t):x.chatModel(t)}case"mistral":{let{apiKey:f}=p;if(c)throw new Error("Provider mistral does not support image models");return Ty({name:"mistral",baseURL:"https://api.mistral.ai/v1",apiKey:f}).chatModel(t)}case"activepieces":case"openrouter":{let{apiKey:f}=p;return My({apiKey:f}).chat(t)}default:throw new Error(`Provider ${e} is not supported`)}}s(Bo,"createAIModel");var ES=$N.tools.webSearch_20250305,AS=BD.tools.webSearchPreview,CS=n1.tools.googleSearch,vse=768,bse={openai:"text-embedding-3-small",google:"text-embedding-004",azure:"text-embedding-3-small",activepieces:"text-embedding-3-small",openrouter:"openai/text-embedding-3-small"},PS={openai:{dimensions:vse}};async function OS({provider:e,engineToken:t,apiUrl:o}){let{config:a,auth:n}=await NU({provider:e,engineToken:t,apiUrl:o}),i=bse[e];if(!i)throw new Error(`Provider ${e} does not have a default embedding model configured`);let{apiKey:l}=n;switch(e){case"openai":return{model:Ip({apiKey:l}).embeddingModel(i),embeddingModelId:i,providerOptions:PS};case"google":return{model:ws({apiKey:l}).textEmbeddingModel(i),embeddingModelId:i,providerOptions:{}};case"azure":{let{resourceName:u,apiVersion:c}=a;return{model:Sy({resourceName:u,apiKey:l,apiVersion:c}).embeddingModel(i),embeddingModelId:i,providerOptions:PS}}case"activepieces":case"openrouter":return{model:My({apiKey:l}).textEmbeddingModel(i),embeddingModelId:i,providerOptions:PS};default:throw new Error(`Provider ${e} does not support embedding models`)}}s(OS,"createEmbeddingModel");var zU=s(({accountId:e,gatewayId:t,headers:o,isImage:a,modelId:n})=>{let i=Ty({name:"cloudflare",baseURL:`https://gateway.ai.cloudflare.com/v1/${e}/${t}/compat`,headers:o});return a?i.imageModel(n):i.chatModel(n)},"handleDefaultAiGatewayProvider");function xse(e,t){let o=t?.showIncludeSources??!0,a=e==="openrouter"||e==="activepieces",n=e==="openai"||e==="anthropic"||e==="google",i={maxUses:Te.Number({displayName:"Max Web Search Uses",required:!1,defaultValue:5,description:a?"For OpenRouter/Activepieces, this maps to OpenRouter web plugin max_results (1-10). Default is 5.":"Maximum number of searches to use. Default is 5."})};n&&o&&(i={...i,includeSources:Te.Checkbox({displayName:"Include Sources",description:"Whether to include the sources in the response. Useful for getting web search details (e.g. search queries, searched URLs, etc).",required:!1,defaultValue:!1})});let l={userLocationCity:Te.ShortText({displayName:"User Location - City",required:!1,description:"The city name for localizing search results (e.g., San Francisco)."}),userLocationRegion:Te.ShortText({displayName:"User Location - Region",required:!1,description:"The region or state for localizing search results (e.g., California)."}),userLocationCountry:Te.ShortText({displayName:"User Location - Country",required:!1,description:"The country code for localizing search results (e.g., US)."}),userLocationTimezone:Te.ShortText({displayName:"User Location - Timezone",required:!1,description:"The IANA timezone ID for localizing search results (e.g., America/Los_Angeles)."})};return e==="anthropic"&&(i={...i,allowedDomains:Te.Array({displayName:"Allowed Domains",required:!1,description:"List of domains to search (e.g., example.com, docs.example.com/blog). Domains should not include HTTP/HTTPS scheme. Subdomains are automatically included unless more specific subpaths are provided. Overrides Blocked Domains if both are provided.",properties:{domain:Te.ShortText({displayName:"Domain",required:!0})}}),blockedDomains:Te.Array({displayName:"Blocked Domains",required:!1,description:"List of domains to exclude from search (e.g., example.com, docs.example.com/blog). Domains should not include HTTP/HTTPS scheme. Subdomains are automatically included unless more specific subpaths are provided. Overrided by Allowed Domains if both are provided.",properties:{domain:Te.ShortText({displayName:"Domain",required:!0})}}),...l}),e==="openai"&&(i={...i,searchContextSize:Te.StaticDropdown({displayName:"Search Context Size",required:!1,defaultValue:"medium",options:{options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]},description:"High level guidance for the amount of context window space to use for the search."}),...l}),i}s(xse,"buildWebSearchOptionsProps");function jU(e){if(!(!e.userLocationCity&&!e.userLocationRegion&&!e.userLocationCountry&&!e.userLocationTimezone))return{type:"approximate",...Qr("city",e.userLocationCity),...Qr("region",e.userLocationRegion),...Qr("country",e.userLocationCountry),...Qr("timezone",e.userLocationTimezone)}}s(jU,"buildUserLocation");function wse(e,t={}){switch(e){case"anthropic":{let a=t,n,i;return a.allowedDomains&&a.allowedDomains.length>0&&(n=a.allowedDomains.map(({domain:l})=>l)),a.blockedDomains&&a.blockedDomains.length>0&&(!a.allowedDomains||a.allowedDomains.length===0)&&(i=a.blockedDomains.map(({domain:l})=>l)),{web_search:ES({maxUses:a.maxUses??5,...Qr("userLocation",jU(a)),...Qr("allowedDomains",n),...Qr("blockedDomains",i)})}}case"openai":{let a=t;return{web_search_preview:AS({...Qr("searchContextSize",a.searchContextSize),...Qr("userLocation",jU(a))})}}case"google":return{google_search:CS({})};default:throw new Error(`Provider ${e} is not supported for web search`)}}s(wse,"createWebSearchTool");function Dy(e,t,o){return Te.DynamicProperties({displayName:"Web Search Options",required:!1,auth:_o.None(),refreshers:t,props:s(async a=>{if(!a.webSearch)return{};let{provider:i,model:l}=e(a);if(!i)return{};let{provider:u}=_n({provider:i,model:l});return xse(u??i,o)},"props")})}s(Dy,"buildWebSearchOptionsProperty");function Uy(e){let{provider:t,model:o,webSearchEnabled:a,webSearchOptions:n}=e;if(!a)return{tools:void 0,providerOptions:void 0};let{provider:i}=_n({provider:t,model:o}),l=i??t;return l==="openrouter"||l==="activepieces"?{tools:void 0,providerOptions:{openrouter:{plugins:[{id:"web",max_results:Math.min(Math.max(n?.maxUses??5,1),10)}]}}}:{tools:wse(l,n),providerOptions:void 0}}s(Uy,"buildWebSearchConfig");var MU=Xo({audience:"both",name:"askAi",displayName:"Ask AI",description:"A flexible AI step. ask it to analyze data, explain, draft, or decide based on your flow's data.",props:{provider:Vr({modelType:"text"}).provider,model:Vr({modelType:"text"}).model,prompt:Te.LongText({displayName:"Prompt",required:!0}),conversationKey:Te.ShortText({displayName:"Conversation Key",required:!1}),creativity:Te.Number({displayName:"Creativity",required:!1,defaultValue:100,description:"Controls the creativity of the AI response. A higher value will make the AI more creative and a lower value will make it more deterministic."}),maxOutputTokens:Te.Number({displayName:"Max Tokens",required:!1,defaultValue:2e3}),webSearch:Te.Checkbox({displayName:"Web Search",required:!1,defaultValue:!1,description:"Whether to use web search to find information for the AI to use in its response."}),webSearchOptions:Dy(e=>({provider:e.provider,model:e.model}),["webSearch","provider","model"])},async run(e){let t=e.propsValue.provider,o=e.propsValue.model,a=e.store,n=!!e.propsValue.webSearch,i=e.propsValue.webSearchOptions??{},{tools:l,providerOptions:u}=Uy({provider:t,model:o,webSearchEnabled:n,webSearchOptions:i}),{provider:c}=_n({provider:t,model:o}),d=await Bo({provider:t,modelId:o,engineToken:e.server.token,apiUrl:e.server.apiUrl,projectId:e.project.id,flowId:e.flows.current.id,runId:e.run.id,...Qr("openaiResponsesModel",n&&c==="openai"?!0:void 0)}),p=e.propsValue.conversationKey?`ask-ai-conversation:${e.propsValue.conversationKey}`:null,m=null;p&&(m=await a.get(p)??[],m||await a.put(p,{messages:[]}));let f=l?ou(i?.maxUses??5):void 0,h=await aa({model:d,messages:[...m??[],{role:"user",content:e.propsValue.prompt}],maxOutputTokens:e.propsValue.maxOutputTokens,temperature:(e.propsValue.creativity??100)/100,tools:l,stopWhen:f,providerOptions:u});return m?.push({role:"user",content:e.propsValue.prompt}),m?.push({role:"assistant",content:h.text??""}),p&&await a.put(p,m),l&&i.includeSources?{text:h.text,sources:h.sources}:h.text}});var DU=Xo({audience:"both",name:"summarizeText",displayName:"Summarize Text",description:"Summarize long emails, articles, or documents into what matters.",props:{provider:Vr({modelType:"text"}).provider,model:Vr({modelType:"text"}).model,text:Te.LongText({displayName:"Text",required:!0}),prompt:Te.ShortText({displayName:"Prompt",defaultValue:"Summarize the following text in a clear and concise manner, capturing the key points and main ideas while keeping the summary brief and informative.",required:!0}),maxOutputTokens:Te.Number({displayName:"Max Tokens",required:!1,defaultValue:2e3})},async run(e){let t=e.propsValue.provider,o=e.propsValue.model,a=await Bo({provider:t,modelId:o,engineToken:e.server.token,apiUrl:e.server.apiUrl,projectId:e.project.id,flowId:e.flows.current.id,runId:e.run.id});return(await aa({model:a,messages:[{role:"user",content:`${e.propsValue.prompt} Summarize the following text : ${e.propsValue.text}`}],maxOutputTokens:e.propsValue.maxOutputTokens,temperature:1,providerOptions:{[t]:{...t==="openai"?{reasoning_effort:"minimal"}:{}}}})).text??""}});var VU=mo($S());var ZU=Xo({audience:"both",name:"generateImage",displayName:"Generate Image",description:"Create unique, high-quality images from simple text descriptions using AI.",props:{provider:Vr({modelType:"image"}).provider,model:Vr({modelType:"image"}).model,prompt:Te.LongText({displayName:"Prompt",required:!0}),inputImages:Te.Array({displayName:"Input Images",description:"Provide images for editing, variation, or merging. Support depends on the selected model.",required:!1,properties:{file:Te.File({displayName:"Image File",required:!0})}}),advancedOptions:Te.DynamicProperties({displayName:"Advanced Options",required:!1,auth:_o.None(),refreshers:["provider","model"],props:s(async e=>{let t=e.provider,o=e.model,{provider:a,model:n}=_n({provider:t,model:o}),i=a??t,l=n??o,u={};return i==="openai"&&(u={quality:Te.StaticDropdown({options:{options:l==="dall-e-3"?[{label:"Standard",value:"standard"},{label:"HD",value:"hd"}]:l==="gpt-image-1"?[{label:"High",value:"high"},{label:"Medium",value:"medium"},{label:"Low",value:"low"}]:[],disabled:l==="dall-e-2"},defaultValue:l==="dall-e-3"?"standard":"high",displayName:"Image Quality",required:!1}),size:Te.StaticDropdown({options:{options:l==="dall-e-3"?[{label:"1024x1024",value:"1024x1024"},{label:"1792x1024",value:"1792x1024"},{label:"1024x1792",value:"1024x1792"}]:l==="gpt-image-1"?[{label:"1024x1024",value:"1024x1024"},{label:"1536x1024",value:"1536x1024"},{label:"1024x1536",value:"1024x1536"}]:[{label:"256x256",value:"256x256"},{label:"512x512",value:"512x512"},{label:"1024x1024",value:"1024x1024"}]},displayName:"Image Size",required:!1})},l==="gpt-image-1"&&(u={...u,background:Te.StaticDropdown({options:{options:[{label:"Auto",value:"auto"},{label:"Transparent",value:"transparent"},{label:"Opaque",value:"opaque"}]},defaultValue:"auto",description:"The background of the image.",displayName:"Background",required:!0})})),u},"props")})},async run(e){let t=e.propsValue.provider,o=e.propsValue.model,a=Ase({inputImages:e.propsValue.inputImages,advancedOptions:e.propsValue.advancedOptions}),n=await Cse({provider:t,modelId:o,engineToken:e.server.token,apiUrl:e.server.apiUrl,prompt:e.propsValue.prompt,inputImages:a,projectId:e.project.id,flowId:e.flows.current.id,runId:e.run.id,advancedOptions:e.propsValue.advancedOptions}),i=n.base64&&n.base64.length>0?Buffer.from(n.base64,"base64"):Buffer.from(n.uint8Array);return e.files.write({data:i,fileName:"image.png"})}}),Ase=s(({inputImages:e,advancedOptions:t})=>{let o=BU(e);return o.length>0?o:BU(t?.image)},"collectInputImages"),BU=s(e=>Array.isArray(e)?e.flatMap(t=>t&&typeof t=="object"&&"file"in t&&t.file?[t.file]:[]):[],"extractImageFiles"),Cse=s(async({provider:e,modelId:t,engineToken:o,apiUrl:a,prompt:n,inputImages:i,projectId:l,flowId:u,runId:c,advancedOptions:d})=>{let p=await Bo({provider:e,modelId:t,engineToken:o,apiUrl:a,projectId:l,flowId:u,runId:c,isImage:!0}),{provider:m}=_n({provider:e,model:t}),f=m??e,h=i.length>0;return Ose({modelId:t,hasInputImages:h},async()=>{switch(f){case"google":case"activepieces":case"openrouter":case"cloudflare-gateway":return $se({model:p,prompt:n,inputImages:i});default:{let g=Rse(d),y=i.map(v=>Buffer.from(v.base64,"base64")),{image:_}=await mN({model:p,prompt:h?{text:n,images:y}:n,providerOptions:{[f]:{...g}}});return _}}})},"getGeneratedImage"),Ose=s(async({modelId:e,hasInputImages:t},o)=>{try{return await o()}catch(a){if(!t)throw a;let n=a instanceof Error?a.message:String(a);throw new Error(`Image generation failed for model "${e}". This model may not support input images. Try a model that supports image editing \u2014 for example gpt-image-1, dall-e-2, or a Gemini Nano Banana model \u2014 or remove the input images. Original error: ${n}`)}},"withImageInputErrorContext"),$se=s(async({model:e,prompt:t,inputImages:o})=>{let a=o.map(i=>{let l=i.extension?VU.default.lookup(i.extension):!1;return{type:"image",image:`data:${l&&zse.has(l)?l:"image/jpeg"};base64,${i.base64}`}}),n=await aa({model:e,providerOptions:{google:{responseModalities:["TEXT","IMAGE"]},openrouter:{modalities:["image","text"]}},messages:[{role:"user",content:[{type:"text",text:t},...a]}]});return Nse(n),n.files[0]},"generateImageUsingGenerateText"),Rse=s(e=>{if(Kt(e))return e;let{image:t,...o}=e;return o},"stripLegacyImageField"),zse=new Set(["image/jpeg","image/png","image/gif","image/webp","image/avif"]),Nse=s(e=>{let t=e.response.body&&typeof e.response.body=="object"&&"candidates"in e.response.body?e.response.body:{candidates:[]},o=Array.isArray(t?.candidates)?t?.candidates:[];if(o.forEach(a=>{if(a.finishReason!=="STOP")throw new Error(`Image generation failed Reason:
|
|
177
|
-
`+JSON.stringify(o,null,2))}),Kt(e.files)||e.files.length===0)throw new Error("No image generated")},"assertImageGenerationSuccess");var HU=Xo({audience:"
|
|
178
|
-
Text to classify: "${e.propsValue.text}"`})).text.trim();if(!t.includes(l))throw new Error("Unable to classify the text into the provided categories.");return l}});var bq=mo($S()),xq=mo(vq());var wq=Xo({audience:"
|
|
176
|
+
`,{prompt:n}}s(Gie,"convertToOpenRouterCompletionPrompt");var z2=r.union([r.object({id:r.string().optional(),model:r.string().optional(),provider:r.string().optional(),choices:r.array(r.object({text:r.string(),reasoning:r.string().nullish().optional(),reasoning_details:SS.nullish(),finish_reason:r.string().nullish(),index:r.number().nullish(),logprobs:r.object({tokens:r.array(r.string()),token_logprobs:r.array(r.number()),top_logprobs:r.array(r.record(r.string(),r.number())).nullable()}).passthrough().nullable().optional()}).passthrough()),usage:r.object({prompt_tokens:r.number(),prompt_tokens_details:r.object({cached_tokens:r.number()}).passthrough().nullish(),completion_tokens:r.number(),completion_tokens_details:r.object({reasoning_tokens:r.number()}).passthrough().nullish(),total_tokens:r.number(),cost:r.number().optional(),cost_details:r.object({upstream_inference_cost:r.number().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),jy]),Kie=class{static{s(this,"OpenRouterCompletionLanguageModel")}constructor(e,t,o){this.specificationVersion="v3",this.provider="openrouter",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"text/*":[/^data:text\//,/^https?:\/\/.+$/],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.defaultObjectGenerationMode=void 0,this.modelId=e,this.settings=t,this.config=o}getArgs({prompt:e,maxOutputTokens:t,temperature:o,topP:a,frequencyPenalty:n,presencePenalty:i,seed:l,responseFormat:u,topK:c,stopSequences:d,tools:p,toolChoice:m}){let{prompt:f}=Gie({prompt:e,inputFormat:"prompt"});if(p?.length)throw new ca({functionality:"tools"});if(m)throw new ca({functionality:"toolChoice"});return ve(ve({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:t,temperature:o,top_p:a,frequency_penalty:n,presence_penalty:i,seed:l,stop:d,response_format:u,top_k:c,prompt:f,include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning},this.config.extraBody),this.settings.extraBody)}async doGenerate(e){var t,o,a,n,i,l,u,c,d,p,m,f,h,g,y,_,v,x,w,S,P,k,I,E,b,M,R,D;let ee=(e.providerOptions||{}).openrouter||{},J=ve(ve({},this.getArgs(e)),ee),{value:W,responseHeaders:j}=await du({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:cu(this.config.headers(),e.headers),body:J,failedResponseHandler:pu,successfulResponseHandler:Ny(z2),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in W){let Z=W.error;throw new jn({message:Z.message,url:this.config.url({path:"/completions",modelId:this.modelId}),requestBodyValues:J,statusCode:200,responseHeaders:j,data:Z})}let O=W.choices[0];if(!O)throw new bS({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:(t=O.text)!=null?t:""}],finishReason:Oy(O.finish_reason),usage:{inputTokens:{total:(a=(o=W.usage)==null?void 0:o.prompt_tokens)!=null?a:0,noCache:void 0,cacheRead:(l=(i=(n=W.usage)==null?void 0:n.prompt_tokens_details)==null?void 0:i.cached_tokens)!=null?l:void 0,cacheWrite:void 0},outputTokens:{total:(c=(u=W.usage)==null?void 0:u.completion_tokens)!=null?c:0,text:void 0,reasoning:(m=(p=(d=W.usage)==null?void 0:d.completion_tokens_details)==null?void 0:p.reasoning_tokens)!=null?m:void 0},raw:(f=W.usage)!=null?f:void 0},warnings:[],providerMetadata:{openrouter:IS.parse({provider:(h=W.provider)!=null?h:"",usage:ve(ve(ve(ve({promptTokens:(y=(g=W.usage)==null?void 0:g.prompt_tokens)!=null?y:0,completionTokens:(v=(_=W.usage)==null?void 0:_.completion_tokens)!=null?v:0,totalTokens:((w=(x=W.usage)==null?void 0:x.prompt_tokens)!=null?w:0)+((P=(S=W.usage)==null?void 0:S.completion_tokens)!=null?P:0)},((k=W.usage)==null?void 0:k.cost)!=null?{cost:W.usage.cost}:{}),((E=(I=W.usage)==null?void 0:I.prompt_tokens_details)==null?void 0:E.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:W.usage.prompt_tokens_details.cached_tokens}}:{}),((M=(b=W.usage)==null?void 0:b.completion_tokens_details)==null?void 0:M.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:W.usage.completion_tokens_details.reasoning_tokens}}:{}),((D=(R=W.usage)==null?void 0:R.cost_details)==null?void 0:D.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:W.usage.cost_details.upstream_inference_cost}}:{})})},response:{headers:j}}}async doStream(e){let o=(e.providerOptions||{}).openrouter||{},a=ve(ve({},this.getArgs(e)),o),{value:n,responseHeaders:i}=await du({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:cu(this.config.headers(),e.headers),body:Pt(ve({},a),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:pu,successfulResponseHandler:wU(z2),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=Ai("other"),u={inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0},c={},d,p;return{stream:n.pipeThrough(new TransformStream({transform(m,f){var h,g,y;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:m.rawValue}),!m.success){l=Ai("error"),f.enqueue({type:"error",error:m.error});return}let _=m.value;if("error"in _){l=Ai("error"),f.enqueue({type:"error",error:_.error});return}if(_.provider&&(d=_.provider),_.usage!=null){if(u.inputTokens.total=_.usage.prompt_tokens,u.outputTokens.total=_.usage.completion_tokens,p=_.usage,c.promptTokens=_.usage.prompt_tokens,_.usage.prompt_tokens_details){let w=(h=_.usage.prompt_tokens_details.cached_tokens)!=null?h:0;u.inputTokens.cacheRead=w,c.promptTokensDetails={cachedTokens:w}}if(c.completionTokens=_.usage.completion_tokens,_.usage.completion_tokens_details){let w=(g=_.usage.completion_tokens_details.reasoning_tokens)!=null?g:0;u.outputTokens.reasoning=w,c.completionTokensDetails={reasoningTokens:w}}_.usage.cost!=null&&(c.cost=_.usage.cost),c.totalTokens=_.usage.total_tokens;let x=(y=_.usage.cost_details)==null?void 0:y.upstream_inference_cost;x!=null&&(c.costDetails={upstreamInferenceCost:x})}let v=_.choices[0];v?.finish_reason!=null&&(l=Oy(v.finish_reason)),v?.text!=null&&f.enqueue({type:"text-delta",delta:v.text,id:Nn()})},flush(m){u.raw=p;let f={usage:c};d!==void 0&&(f.provider=d),m.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:{openrouter:f}})}})),response:{headers:i}}}},Xie=r.object({prompt_tokens:r.number(),total_tokens:r.number(),cost:r.number().optional()}),Yie=r.object({object:r.literal("embedding"),embedding:r.array(r.number()),index:r.number().optional()}),Qie=r.object({id:r.string().optional(),object:r.literal("list"),data:r.array(Yie),model:r.string(),provider:r.string().optional(),usage:Xie.optional()}),ese=class{static{s(this,"OpenRouterEmbeddingModel")}constructor(e,t,o){this.specificationVersion="v3",this.provider="openrouter",this.maxEmbeddingsPerCall=void 0,this.supportsParallelCalls=!0,this.modelId=e,this.settings=t,this.config=o}async doEmbed(e){var t,o,a,n,i,l;let{values:u,abortSignal:c,headers:d}=e,p=ve(ve({model:this.modelId,input:u,user:this.settings.user,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody),{value:m,responseHeaders:f}=await du({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:cu(this.config.headers(),d),body:p,failedResponseHandler:pu,successfulResponseHandler:Ny(Qie),abortSignal:c,fetch:this.config.fetch});return{embeddings:m.data.map(h=>h.embedding),usage:m.usage?{tokens:m.usage.prompt_tokens}:void 0,providerMetadata:{openrouter:IS.parse({provider:(t=m.provider)!=null?t:"",usage:ve({promptTokens:(a=(o=m.usage)==null?void 0:o.prompt_tokens)!=null?a:0,completionTokens:0,totalTokens:(i=(n=m.usage)==null?void 0:n.total_tokens)!=null?i:0},((l=m.usage)==null?void 0:l.cost)!=null?{cost:m.usage.cost}:{})})},response:{headers:f,body:m},warnings:[]}}};var tse=r.object({id:r.string().optional(),object:r.string().optional(),created:r.number().optional(),model:r.string(),choices:r.array(r.object({index:r.number(),message:r.object({role:r.string(),content:r.string().nullable().optional(),images:r.array(r.object({type:r.literal("image_url"),image_url:r.object({url:r.string()})}).passthrough()).optional()}).passthrough(),finish_reason:r.string().nullable().optional()}).passthrough()),usage:r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number()}).passthrough().optional()}).passthrough(),rse=class{static{s(this,"OpenRouterImageModel")}constructor(e,t,o){this.specificationVersion="v3",this.provider="openrouter",this.maxImagesPerCall=1,this.modelId=e,this.settings=t,this.config=o}async doGenerate(e){var t;let{prompt:o,n:a,size:n,aspectRatio:i,seed:l,files:u,mask:c,abortSignal:d,headers:p,providerOptions:m}=e,f=m?.openrouter||{},h=[];if(u!==void 0&&u.length>0)throw new ca({functionality:"image editing (files parameter)"});if(c!==void 0)throw new ca({functionality:"image inpainting (mask parameter)"});a>1&&h.push({type:"unsupported",feature:"n > 1",details:`OpenRouter image generation returns 1 image per call. Requested ${a} images.`}),n!==void 0&&h.push({type:"unsupported",feature:"size",details:"Use aspectRatio instead. Size parameter is not supported by OpenRouter image generation."});let g=i!==void 0?{aspect_ratio:i}:void 0,y=ve(ve(ve(ve(ve(ve(ve({model:this.modelId,messages:[{role:"user",content:o??""}],modalities:["image","text"]},g!==void 0&&{image_config:g}),l!==void 0&&{seed:l}),this.settings.user!==void 0&&{user:this.settings.user}),this.settings.provider!==void 0&&{provider:this.settings.provider}),this.config.extraBody),this.settings.extraBody),f),{value:_,responseHeaders:v}=await du({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:cu(this.config.headers(),p),body:y,failedResponseHandler:pu,successfulResponseHandler:Ny(tse),abortSignal:d,fetch:this.config.fetch}),x=_.choices[0];if(!x)throw new bS({message:"No choice in response"});let w=[];if((t=x.message)!=null&&t.images)for(let P of x.message.images){let k=P.image_url.url;w.push($y(k))}let S=_.usage?{inputTokens:_.usage.prompt_tokens,outputTokens:_.usage.completion_tokens,totalTokens:_.usage.total_tokens}:void 0;return{images:w,warnings:h,response:{timestamp:new Date,modelId:_.model,headers:v},usage:S}}};function ose(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}s(ose,"removeUndefinedEntries");function nse(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):e:{}}s(nse,"normalizeHeaders2");function ase(e,t){let o=t.toLowerCase();return Object.keys(e).find(a=>a.toLowerCase()===o)}s(ase,"findHeaderKey");function ise(e,...t){let o=nse(e),a=ose(o),n=ase(a,"user-agent"),i=n?a[n]:void 0,l=i?.trim()?i:t.filter(Boolean).join(" "),u=Object.fromEntries(Object.entries(a).filter(([c])=>c.toLowerCase()!=="user-agent"));return Pt(ve({},u),{"user-agent":l})}s(ise,"withUserAgentSuffix2");var sse="2.1.1";function My(e={}){var t,o,a;let n=(o=Oie((t=e.baseURL)!=null?t:e.baseUrl))!=null?o:"https://openrouter.ai/api/v1",i=(a=e.compatibility)!=null?a:"compatible",l=s(()=>ise(ve(ve({Authorization:`Bearer ${Eae({apiKey:e.apiKey,environmentVariableName:"OPENROUTER_API_KEY",description:"OpenRouter"})}`},e.headers),e.api_keys&&Object.keys(e.api_keys).length>0&&{"X-Provider-API-Keys":JSON.stringify(e.api_keys)}),`ai-sdk/openrouter/${sse}`),"getHeaders"),u=s((h,g={})=>new Wie(h,g,{provider:"openrouter.chat",url:s(({path:y})=>`${n}${y}`,"url"),headers:l,compatibility:i,fetch:e.fetch,extraBody:e.extraBody}),"createChatModel"),c=s((h,g={})=>new Kie(h,g,{provider:"openrouter.completion",url:s(({path:y})=>`${n}${y}`,"url"),headers:l,compatibility:i,fetch:e.fetch,extraBody:e.extraBody}),"createCompletionModel"),d=s((h,g={})=>new ese(h,g,{provider:"openrouter.embedding",url:s(({path:y})=>`${n}${y}`,"url"),headers:l,fetch:e.fetch,extraBody:e.extraBody}),"createEmbeddingModel"),p=s((h,g={})=>new rse(h,g,{provider:"openrouter.image",url:s(({path:y})=>`${n}${y}`,"url"),headers:l,fetch:e.fetch,extraBody:e.extraBody}),"createImageModel"),m=s((h,g)=>{if(new.target)throw new Error("The OpenRouter model function cannot be called with the new keyword.");return h==="openai/gpt-3.5-turbo-instruct"?c(h,g):u(h,g)},"createLanguageModel"),f=s((h,g)=>m(h,g),"provider");return f.languageModel=m,f.chat=u,f.completion=c,f.textEmbeddingModel=d,f.embedding=d,f.imageModel=p,f}s(My,"createOpenRouter");var vLe=My({compatibility:"strict"});var lse=Object.defineProperty,use=s((e,t,o)=>t in e?lse(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,"__defNormalProp"),$p=s((e,t,o)=>use(e,typeof t!="symbol"?t+"":t,o),"__publicField"),cse="CF_TEMP_TOKEN",dse=[{name:"openai",regex:/^https:\/\/api\.openai\.com\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.openai\.com\//,""),"transformEndpoint")},{name:"deepseek",regex:/^https:\/\/api\.deepseek\.com\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.deepseek\.com\//,""),"transformEndpoint")},{name:"anthropic",regex:/^https:\/\/api\.anthropic\.com\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.anthropic\.com\//,""),"transformEndpoint"),headerKey:"x-api-key"},{name:"google-ai-studio",regex:/^https:\/\/generativelanguage\.googleapis\.com\//,headerKey:"x-goog-api-key",transformEndpoint:s(e=>e.replace(/^https:\/\/generativelanguage\.googleapis\.com\//,""),"transformEndpoint")},{name:"google-vertex-ai",regex:/aiplatform\.googleapis\.com/,transformEndpoint:s(e=>e.replace(/https:\/\/(.*)[-]?aiplatform\.googleapis\.com\//,""),"transformEndpoint")},{name:"grok",regex:/^https:\/\/api\.x\.ai\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.x\.ai\//,""),"transformEndpoint")},{name:"mistral",regex:/^https:\/\/api\.mistral\.ai\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.mistral\.ai\//,""),"transformEndpoint")},{name:"perplexity-ai",regex:/^https:\/\/api\.perplexity\.ai\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.perplexity\.ai\//,""),"transformEndpoint")},{name:"replicate",regex:/^https:\/\/api\.replicate\.com\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.replicate\.com\//,""),"transformEndpoint")},{name:"groq",regex:/^https:\/\/api\.groq\.com\/openai\/v1\//,transformEndpoint:s(e=>e.replace(/^https:\/\/api\.groq\.com\/openai\/v1\//,""),"transformEndpoint")},{name:"google-vertex-ai",regex:/^https:\/\/(?:[a-z0-9]+-)*aiplatform\.googleapis\.com\//,transformEndpoint:s(e=>e.replace(/^https:\/\/(?:[a-z0-9]+-)*aiplatform\.googleapis\.com\//,""),"transformEndpoint"),headerKey:"authorization"},{name:"azure-openai",regex:/^https:\/\/(?<resource>[^.]+)\.openai\.azure\.com\/openai\/deployments\/(?<deployment>[^/]+)\/(?<rest>.*)$/,transformEndpoint:s(e=>{let t=e.match(/^https:\/\/(?<resource>[^.]+)\.openai\.azure\.com\/openai\/deployments\/(?<deployment>[^/]+)\/(?<rest>.*)$/);if(!t||!t.groups)return e;let{resource:o,deployment:a,rest:n}=t.groups;if(!o||!a||!n)throw new Error("Failed to parse Azure OpenAI endpoint URL.");return`${o}/${a}/${n}`},"transformEndpoint"),headerKey:"api-key"},{name:"openrouter",regex:/^https:\/\/openrouter\.ai\/api\//,transformEndpoint:s(e=>e.replace(/^https:\/\/openrouter\.ai\/api\//,""),"transformEndpoint")},{name:"compat",regex:/^https:\/\/gateway\.ai\.cloudflare\.com\/v1\/compat\//,transformEndpoint:s(e=>e.replace(/^https:\/\/gateway\.ai\.cloudflare\.com\/v1\/compat\//,""),"transformEndpoint")}],EU=class extends Error{static{s(this,"AiGatewayInternalFetchError")}},pse=class extends Error{static{s(this,"AiGatewayDoesNotExist")}},mse=class extends Error{static{s(this,"AiGatewayUnauthorizedError")}};async function fse(e){return await new Response(e).json()}s(fse,"streamToObject");var hse=class{static{s(this,"AiGatewayChatLanguageModel")}constructor(e,t){$p(this,"specificationVersion","v3"),$p(this,"defaultObjectGenerationMode","json"),$p(this,"supportedUrls",{}),$p(this,"models"),$p(this,"config"),this.models=e,this.config=t}get modelId(){if(!this.models[0])throw new Error("models cannot be empty array");return this.models[0].modelId}get provider(){if(!this.models[0])throw new Error("models cannot be empty array");return this.models[0].provider}async processModelRequest(e,t){let o=[];for(let u of this.models){if(!u.config||!Object.keys(u.config).includes("fetch"))throw new Error(`Sorry, but provider "${u.provider}" is currently not supported, please open a issue in the github repo!`);u.config.fetch=(c,d)=>{throw o.push({modelProvider:u.provider,request:d,url:c}),new EU("Stopping provider execution...")};try{await u[t](e)}catch(c){if(!(c instanceof EU))throw c}}let a=await Promise.all(o.map(async u=>{let c=null;for(let m of dse)m.regex.test(u.url)&&(c=m);if(!c)throw new Error(`Sorry, but provider "${u.modelProvider}" is currently not supported, please open a issue in the github repo!`);if(!u.request.body)throw new Error("Ai Gateway provider received an unexpected empty body");let d=c.headerKey??"authorization";return("get"in u.request.headers?u.request.headers.get(d):u.request.headers[d])?.indexOf(cse)!==-1&&("delete"in u.request.headers?u.request.headers.delete(d):delete u.request.headers[d]),{endpoint:c.transformEndpoint(u.url),headers:u.request.headers,provider:c.name,query:await fse(u.request.body)}})),n=gse(this.config.options??{}),i;if("binding"in this.config){let u=a.map(c=>({...c,headers:{...c.headers??{},...Object.fromEntries(n.entries())}}));i=await this.config.binding.run(u)}else n.set("Content-Type","application/json"),n.set("cf-aig-authorization",`Bearer ${this.config.apiKey}`),i=await fetch(`https://gateway.ai.cloudflare.com/v1/${this.config.accountId}/${this.config.gateway}`,{body:JSON.stringify(a),headers:n,method:"POST"});if(i.status===400){let c=await i.clone().json();if(c.success===!1&&c.error&&c.error.length>0&&c.error[0]?.code===2001)throw new pse("This AI gateway does not exist")}else if(i.status===401){let c=await i.clone().json();if(c.success===!1&&c.error&&c.error.length>0&&c.error[0]?.code===2009)throw new mse("Your AI Gateway has authentication active, but you didn't provide a valid apiKey")}let l=Number.parseInt(i.headers.get("cf-aig-step")??"0",10);if(!this.models[l])throw new Error("Unexpected AI Gateway Error");return this.models[l].config={...this.models[l].config,fetch:s((u,c)=>i,"fetch")},this.models[l][t](e)}async doStream(e){return this.processModelRequest(e,"doStream")}async doGenerate(e){return this.processModelRequest(e,"doGenerate")}};function AU(e){let t=s(a=>new hse(Array.isArray(a)?a:[a],e),"createChatModel"),o=s(a=>t(a),"provider");return o.chat=t,o}s(AU,"createAiGateway");function gse(e){let t=new Headers;return e.skipCache===!0&&t.set("cf-skip-cache","true"),e.cacheTtl&&t.set("cf-cache-ttl",e.cacheTtl.toString()),e.metadata&&t.set("cf-aig-metadata",JSON.stringify(e.metadata)),e.cacheKey&&t.set("cf-aig-cache-key",e.cacheKey),e.collectLog!==void 0&&t.set("cf-aig-collect-log",e.collectLog===!0?"true":"false"),e.eventId!==void 0&&t.set("cf-aig-event-id",e.eventId),e.requestTimeoutMs!==void 0&&t.set("cf-aig-request-timeout",e.requestTimeoutMs.toString()),e.retries!==void 0&&(e.retries.maxAttempts!==void 0&&t.set("cf-aig-max-attempts",e.retries.maxAttempts.toString()),e.retries.retryDelayMs!==void 0&&t.set("cf-aig-retry-delay",e.retries.retryDelayMs.toString()),e.retries.backoff!==void 0&&t.set("cf-aig-backoff",e.retries.backoff)),t}s(gse,"parseAiGatewayOptions");var CU="CF_TEMP_TOKEN";function yse(e){return t=>t?(t.apiKey===void 0&&(t.apiKey=CU),e(t)):e({apiKey:CU})}s(yse,"authWrapper");var OU=s((...e)=>yse(gp)(...e),"createAnthropic");var $U="CF_TEMP_TOKEN";function _se(e){return t=>t?(t.apiKey===void 0&&(t.apiKey=$U),e(t)):e({apiKey:$U})}s(_se,"authWrapper");var RU=s((...e)=>_se(ws)(...e),"createGoogleGenerativeAI");async function NU(e){let{body:t}=await ia.sendRequest({method:"GET",url:`${e.apiUrl}v1/ai-providers/${e.provider}/config`,headers:{Authorization:`Bearer ${e.engineToken}`}});return t}s(NU,"fetchProviderConfig");async function Bo({provider:e,modelId:t,engineToken:o,projectId:a,flowId:n,runId:i,apiUrl:l,openaiResponsesModel:u=!1,isImage:c}){let{config:d,auth:p,platformId:m}=await NU({provider:e,engineToken:o,apiUrl:l});switch(e){case"openai":{let{apiKey:f}=p,h=Ip({apiKey:f});return c?h.imageModel(t):u?h.responses(t):h.chat(t)}case"anthropic":{let{apiKey:f}=p,h=gp({apiKey:f});if(c)throw new Error(`Provider ${h} does not support image models`);return h(t)}case"google":{let{apiKey:f}=p;return ws({apiKey:f})(t)}case"azure":{let{apiKey:f}=p,{resourceName:h,apiVersion:g}=d,y=Sy({resourceName:h,apiKey:f,apiVersion:g});return c?y.imageModel(t):y.chat(t)}case"cloudflare-gateway":{let{apiKey:f}=p,{accountId:h,gatewayId:g,vertexProject:y,vertexRegion:_}=d,v=AU({accountId:h,gateway:g,apiKey:f}),{provider:x,model:w,publisher:S}=Dh(t),P={"cf-aig-metadata":JSON.stringify({projectId:a,flowId:n,runId:i})},k={"cf-aig-authorization":`Bearer ${f}`,...P};switch(x){case"anthropic":{let I=OU({headers:k});return v(I(w))}case"google-ai-studio":{let I=RU({headers:k});return v(I(w))}case"google-vertex-ai":return y&&_&&S?ws({apiKey:f,baseURL:`https://gateway.ai.cloudflare.com/v1/${h}/${g}/google-vertex-ai/v1/projects/${y}/locations/${_}/publishers/${S}/`,headers:k})(w):zU({accountId:h,gatewayId:g,headers:k,isImage:c,modelId:t});case"openai":{let I=Ip({apiKey:"no-key",baseURL:`https://gateway.ai.cloudflare.com/v1/${h}/${g}/openai`,headers:k,fetch:s((E,b)=>{let M=new Headers(b?.headers);return M.delete("Authorization"),fetch(E,{...b,headers:M})},"fetch")});return c?I.imageModel(w):u?I.responses(w):I.chat(w)}default:return zU({accountId:h,gatewayId:g,headers:k,isImage:c,modelId:t})}}case"bedrock":{let{accessKeyId:f,secretAccessKey:h}=p,{region:g}=d,y=JT({region:g,accessKeyId:f,secretAccessKey:h});return c?y.imageModel(t):y(t)}case"custom":{let{apiKey:f}=p,{apiKeyHeader:h,baseUrl:g,defaultHeaders:y}=d,x=Ty({name:"openai-compatible",baseURL:g,headers:{...{"x-ap-project-id":a,"x-ap-platform-id":m,"x-ap-flow-id":n,"x-ap-run-id":i},...y??{},[h]:f}});return c?x.imageModel(t):x.chatModel(t)}case"mistral":{let{apiKey:f}=p;if(c)throw new Error("Provider mistral does not support image models");return Ty({name:"mistral",baseURL:"https://api.mistral.ai/v1",apiKey:f}).chatModel(t)}case"activepieces":case"openrouter":{let{apiKey:f}=p;return My({apiKey:f}).chat(t)}default:throw new Error(`Provider ${e} is not supported`)}}s(Bo,"createAIModel");var ES=$N.tools.webSearch_20250305,AS=BD.tools.webSearchPreview,CS=n1.tools.googleSearch,vse=768,bse={openai:"text-embedding-3-small",google:"text-embedding-004",azure:"text-embedding-3-small",activepieces:"text-embedding-3-small",openrouter:"openai/text-embedding-3-small"},PS={openai:{dimensions:vse}};async function OS({provider:e,engineToken:t,apiUrl:o}){let{config:a,auth:n}=await NU({provider:e,engineToken:t,apiUrl:o}),i=bse[e];if(!i)throw new Error(`Provider ${e} does not have a default embedding model configured`);let{apiKey:l}=n;switch(e){case"openai":return{model:Ip({apiKey:l}).embeddingModel(i),embeddingModelId:i,providerOptions:PS};case"google":return{model:ws({apiKey:l}).textEmbeddingModel(i),embeddingModelId:i,providerOptions:{}};case"azure":{let{resourceName:u,apiVersion:c}=a;return{model:Sy({resourceName:u,apiKey:l,apiVersion:c}).embeddingModel(i),embeddingModelId:i,providerOptions:PS}}case"activepieces":case"openrouter":return{model:My({apiKey:l}).textEmbeddingModel(i),embeddingModelId:i,providerOptions:PS};default:throw new Error(`Provider ${e} does not support embedding models`)}}s(OS,"createEmbeddingModel");var zU=s(({accountId:e,gatewayId:t,headers:o,isImage:a,modelId:n})=>{let i=Ty({name:"cloudflare",baseURL:`https://gateway.ai.cloudflare.com/v1/${e}/${t}/compat`,headers:o});return a?i.imageModel(n):i.chatModel(n)},"handleDefaultAiGatewayProvider");function xse(e,t){let o=t?.showIncludeSources??!0,a=e==="openrouter"||e==="activepieces",n=e==="openai"||e==="anthropic"||e==="google",i={maxUses:Te.Number({displayName:"Max Web Search Uses",required:!1,defaultValue:5,description:a?"For OpenRouter/Activepieces, this maps to OpenRouter web plugin max_results (1-10). Default is 5.":"Maximum number of searches to use. Default is 5."})};n&&o&&(i={...i,includeSources:Te.Checkbox({displayName:"Include Sources",description:"Whether to include the sources in the response. Useful for getting web search details (e.g. search queries, searched URLs, etc).",required:!1,defaultValue:!1})});let l={userLocationCity:Te.ShortText({displayName:"User Location - City",required:!1,description:"The city name for localizing search results (e.g., San Francisco)."}),userLocationRegion:Te.ShortText({displayName:"User Location - Region",required:!1,description:"The region or state for localizing search results (e.g., California)."}),userLocationCountry:Te.ShortText({displayName:"User Location - Country",required:!1,description:"The country code for localizing search results (e.g., US)."}),userLocationTimezone:Te.ShortText({displayName:"User Location - Timezone",required:!1,description:"The IANA timezone ID for localizing search results (e.g., America/Los_Angeles)."})};return e==="anthropic"&&(i={...i,allowedDomains:Te.Array({displayName:"Allowed Domains",required:!1,description:"List of domains to search (e.g., example.com, docs.example.com/blog). Domains should not include HTTP/HTTPS scheme. Subdomains are automatically included unless more specific subpaths are provided. Overrides Blocked Domains if both are provided.",properties:{domain:Te.ShortText({displayName:"Domain",required:!0})}}),blockedDomains:Te.Array({displayName:"Blocked Domains",required:!1,description:"List of domains to exclude from search (e.g., example.com, docs.example.com/blog). Domains should not include HTTP/HTTPS scheme. Subdomains are automatically included unless more specific subpaths are provided. Overrided by Allowed Domains if both are provided.",properties:{domain:Te.ShortText({displayName:"Domain",required:!0})}}),...l}),e==="openai"&&(i={...i,searchContextSize:Te.StaticDropdown({displayName:"Search Context Size",required:!1,defaultValue:"medium",options:{options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]},description:"High level guidance for the amount of context window space to use for the search."}),...l}),i}s(xse,"buildWebSearchOptionsProps");function jU(e){if(!(!e.userLocationCity&&!e.userLocationRegion&&!e.userLocationCountry&&!e.userLocationTimezone))return{type:"approximate",...Qr("city",e.userLocationCity),...Qr("region",e.userLocationRegion),...Qr("country",e.userLocationCountry),...Qr("timezone",e.userLocationTimezone)}}s(jU,"buildUserLocation");function wse(e,t={}){switch(e){case"anthropic":{let a=t,n,i;return a.allowedDomains&&a.allowedDomains.length>0&&(n=a.allowedDomains.map(({domain:l})=>l)),a.blockedDomains&&a.blockedDomains.length>0&&(!a.allowedDomains||a.allowedDomains.length===0)&&(i=a.blockedDomains.map(({domain:l})=>l)),{web_search:ES({maxUses:a.maxUses??5,...Qr("userLocation",jU(a)),...Qr("allowedDomains",n),...Qr("blockedDomains",i)})}}case"openai":{let a=t;return{web_search_preview:AS({...Qr("searchContextSize",a.searchContextSize),...Qr("userLocation",jU(a))})}}case"google":return{google_search:CS({})};default:throw new Error(`Provider ${e} is not supported for web search`)}}s(wse,"createWebSearchTool");function Dy(e,t,o){return Te.DynamicProperties({displayName:"Web Search Options",required:!1,auth:_o.None(),refreshers:t,props:s(async a=>{if(!a.webSearch)return{};let{provider:i,model:l}=e(a);if(!i)return{};let{provider:u}=_n({provider:i,model:l});return xse(u??i,o)},"props")})}s(Dy,"buildWebSearchOptionsProperty");function Uy(e){let{provider:t,model:o,webSearchEnabled:a,webSearchOptions:n}=e;if(!a)return{tools:void 0,providerOptions:void 0};let{provider:i}=_n({provider:t,model:o}),l=i??t;return l==="openrouter"||l==="activepieces"?{tools:void 0,providerOptions:{openrouter:{plugins:[{id:"web",max_results:Math.min(Math.max(n?.maxUses??5,1),10)}]}}}:{tools:wse(l,n),providerOptions:void 0}}s(Uy,"buildWebSearchConfig");var MU=Xo({audience:"human",name:"askAi",displayName:"Ask AI",description:"A flexible AI step. ask it to analyze data, explain, draft, or decide based on your flow's data.",props:{provider:Vr({modelType:"text"}).provider,model:Vr({modelType:"text"}).model,prompt:Te.LongText({displayName:"Prompt",required:!0}),conversationKey:Te.ShortText({displayName:"Conversation Key",required:!1}),creativity:Te.Number({displayName:"Creativity",required:!1,defaultValue:100,description:"Controls the creativity of the AI response. A higher value will make the AI more creative and a lower value will make it more deterministic."}),maxOutputTokens:Te.Number({displayName:"Max Tokens",required:!1,defaultValue:2e3}),webSearch:Te.Checkbox({displayName:"Web Search",required:!1,defaultValue:!1,description:"Whether to use web search to find information for the AI to use in its response."}),webSearchOptions:Dy(e=>({provider:e.provider,model:e.model}),["webSearch","provider","model"])},async run(e){let t=e.propsValue.provider,o=e.propsValue.model,a=e.store,n=!!e.propsValue.webSearch,i=e.propsValue.webSearchOptions??{},{tools:l,providerOptions:u}=Uy({provider:t,model:o,webSearchEnabled:n,webSearchOptions:i}),{provider:c}=_n({provider:t,model:o}),d=await Bo({provider:t,modelId:o,engineToken:e.server.token,apiUrl:e.server.apiUrl,projectId:e.project.id,flowId:e.flows.current.id,runId:e.run.id,...Qr("openaiResponsesModel",n&&c==="openai"?!0:void 0)}),p=e.propsValue.conversationKey?`ask-ai-conversation:${e.propsValue.conversationKey}`:null,m=null;p&&(m=await a.get(p)??[],m||await a.put(p,{messages:[]}));let f=l?ou(i?.maxUses??5):void 0,h=await aa({model:d,messages:[...m??[],{role:"user",content:e.propsValue.prompt}],maxOutputTokens:e.propsValue.maxOutputTokens,temperature:(e.propsValue.creativity??100)/100,tools:l,stopWhen:f,providerOptions:u});return m?.push({role:"user",content:e.propsValue.prompt}),m?.push({role:"assistant",content:h.text??""}),p&&await a.put(p,m),l&&i.includeSources?{text:h.text,sources:h.sources}:h.text}});var DU=Xo({audience:"human",name:"summarizeText",displayName:"Summarize Text",description:"Summarize long emails, articles, or documents into what matters.",props:{provider:Vr({modelType:"text"}).provider,model:Vr({modelType:"text"}).model,text:Te.LongText({displayName:"Text",required:!0}),prompt:Te.ShortText({displayName:"Prompt",defaultValue:"Summarize the following text in a clear and concise manner, capturing the key points and main ideas while keeping the summary brief and informative.",required:!0}),maxOutputTokens:Te.Number({displayName:"Max Tokens",required:!1,defaultValue:2e3})},async run(e){let t=e.propsValue.provider,o=e.propsValue.model,a=await Bo({provider:t,modelId:o,engineToken:e.server.token,apiUrl:e.server.apiUrl,projectId:e.project.id,flowId:e.flows.current.id,runId:e.run.id});return(await aa({model:a,messages:[{role:"user",content:`${e.propsValue.prompt} Summarize the following text : ${e.propsValue.text}`}],maxOutputTokens:e.propsValue.maxOutputTokens,temperature:1,providerOptions:{[t]:{...t==="openai"?{reasoning_effort:"minimal"}:{}}}})).text??""}});var VU=mo($S());var ZU=Xo({audience:"human",name:"generateImage",displayName:"Generate Image",description:"Create unique, high-quality images from simple text descriptions using AI.",props:{provider:Vr({modelType:"image"}).provider,model:Vr({modelType:"image"}).model,prompt:Te.LongText({displayName:"Prompt",required:!0}),inputImages:Te.Array({displayName:"Input Images",description:"Provide images for editing, variation, or merging. Support depends on the selected model.",required:!1,properties:{file:Te.File({displayName:"Image File",required:!0})}}),advancedOptions:Te.DynamicProperties({displayName:"Advanced Options",required:!1,auth:_o.None(),refreshers:["provider","model"],props:s(async e=>{let t=e.provider,o=e.model,{provider:a,model:n}=_n({provider:t,model:o}),i=a??t,l=n??o,u={};return i==="openai"&&(u={quality:Te.StaticDropdown({options:{options:l==="dall-e-3"?[{label:"Standard",value:"standard"},{label:"HD",value:"hd"}]:l==="gpt-image-1"?[{label:"High",value:"high"},{label:"Medium",value:"medium"},{label:"Low",value:"low"}]:[],disabled:l==="dall-e-2"},defaultValue:l==="dall-e-3"?"standard":"high",displayName:"Image Quality",required:!1}),size:Te.StaticDropdown({options:{options:l==="dall-e-3"?[{label:"1024x1024",value:"1024x1024"},{label:"1792x1024",value:"1792x1024"},{label:"1024x1792",value:"1024x1792"}]:l==="gpt-image-1"?[{label:"1024x1024",value:"1024x1024"},{label:"1536x1024",value:"1536x1024"},{label:"1024x1536",value:"1024x1536"}]:[{label:"256x256",value:"256x256"},{label:"512x512",value:"512x512"},{label:"1024x1024",value:"1024x1024"}]},displayName:"Image Size",required:!1})},l==="gpt-image-1"&&(u={...u,background:Te.StaticDropdown({options:{options:[{label:"Auto",value:"auto"},{label:"Transparent",value:"transparent"},{label:"Opaque",value:"opaque"}]},defaultValue:"auto",description:"The background of the image.",displayName:"Background",required:!0})})),u},"props")})},async run(e){let t=e.propsValue.provider,o=e.propsValue.model,a=Ase({inputImages:e.propsValue.inputImages,advancedOptions:e.propsValue.advancedOptions}),n=await Cse({provider:t,modelId:o,engineToken:e.server.token,apiUrl:e.server.apiUrl,prompt:e.propsValue.prompt,inputImages:a,projectId:e.project.id,flowId:e.flows.current.id,runId:e.run.id,advancedOptions:e.propsValue.advancedOptions}),i=n.base64&&n.base64.length>0?Buffer.from(n.base64,"base64"):Buffer.from(n.uint8Array);return e.files.write({data:i,fileName:"image.png"})}}),Ase=s(({inputImages:e,advancedOptions:t})=>{let o=BU(e);return o.length>0?o:BU(t?.image)},"collectInputImages"),BU=s(e=>Array.isArray(e)?e.flatMap(t=>t&&typeof t=="object"&&"file"in t&&t.file?[t.file]:[]):[],"extractImageFiles"),Cse=s(async({provider:e,modelId:t,engineToken:o,apiUrl:a,prompt:n,inputImages:i,projectId:l,flowId:u,runId:c,advancedOptions:d})=>{let p=await Bo({provider:e,modelId:t,engineToken:o,apiUrl:a,projectId:l,flowId:u,runId:c,isImage:!0}),{provider:m}=_n({provider:e,model:t}),f=m??e,h=i.length>0;return Ose({modelId:t,hasInputImages:h},async()=>{switch(f){case"google":case"activepieces":case"openrouter":case"cloudflare-gateway":return $se({model:p,prompt:n,inputImages:i});default:{let g=Rse(d),y=i.map(v=>Buffer.from(v.base64,"base64")),{image:_}=await mN({model:p,prompt:h?{text:n,images:y}:n,providerOptions:{[f]:{...g}}});return _}}})},"getGeneratedImage"),Ose=s(async({modelId:e,hasInputImages:t},o)=>{try{return await o()}catch(a){if(!t)throw a;let n=a instanceof Error?a.message:String(a);throw new Error(`Image generation failed for model "${e}". This model may not support input images. Try a model that supports image editing \u2014 for example gpt-image-1, dall-e-2, or a Gemini Nano Banana model \u2014 or remove the input images. Original error: ${n}`)}},"withImageInputErrorContext"),$se=s(async({model:e,prompt:t,inputImages:o})=>{let a=o.map(i=>{let l=i.extension?VU.default.lookup(i.extension):!1;return{type:"image",image:`data:${l&&zse.has(l)?l:"image/jpeg"};base64,${i.base64}`}}),n=await aa({model:e,providerOptions:{google:{responseModalities:["TEXT","IMAGE"]},openrouter:{modalities:["image","text"]}},messages:[{role:"user",content:[{type:"text",text:t},...a]}]});return Nse(n),n.files[0]},"generateImageUsingGenerateText"),Rse=s(e=>{if(Kt(e))return e;let{image:t,...o}=e;return o},"stripLegacyImageField"),zse=new Set(["image/jpeg","image/png","image/gif","image/webp","image/avif"]),Nse=s(e=>{let t=e.response.body&&typeof e.response.body=="object"&&"candidates"in e.response.body?e.response.body:{candidates:[]},o=Array.isArray(t?.candidates)?t?.candidates:[];if(o.forEach(a=>{if(a.finishReason!=="STOP")throw new Error(`Image generation failed Reason:
|
|
177
|
+
`+JSON.stringify(o,null,2))}),Kt(e.files)||e.files.length===0)throw new Error("No image generated")},"assertImageGenerationSuccess");var HU=Xo({audience:"human",name:"classifyText",displayName:"Classify Text",description:"Categorize any text input using custom labels, so your flow knows what to do next.",props:{provider:Vr({modelType:"text"}).provider,model:Vr({modelType:"text"}).model,text:Te.LongText({displayName:"Text to Classify",required:!0}),categories:Te.Array({displayName:"Categories",description:"Categories to classify text into.",required:!0})},async run(e){let t=e.propsValue.categories??[],o=e.propsValue.provider,a=e.propsValue.model,n=await Bo({provider:o,modelId:a,engineToken:e.server.token,apiUrl:e.server.apiUrl,projectId:e.project.id,flowId:e.flows.current.id,runId:e.run.id}),l=(await aa({model:n,prompt:`As a text classifier, your task is to assign one of the following categories to the provided text: ${t.join(", ")}. Please respond with only the selected category as a single word, and nothing else.
|
|
178
|
+
Text to classify: "${e.propsValue.text}"`})).text.trim();if(!t.includes(l))throw new Error("Unable to classify the text into the provided categories.");return l}});var bq=mo($S()),xq=mo(vq());var wq=Xo({audience:"human",name:"extractStructuredData",displayName:"Extract Structured Data",description:"Accurately Pull names, amounts, and other structured data from emails, invoices, and scanned documents.",props:{provider:Vr({modelType:"text"}).provider,model:Vr({modelType:"text"}).model,text:Te.LongText({displayName:"Text",description:"Text to extract structured data from.",required:!1}),files:Te.Array({displayName:"Files",required:!1,properties:{file:Te.File({displayName:"Image/PDF",description:"Image or PDF to extract structured data from.",required:!1})}}),prompt:Te.LongText({displayName:"Guide Prompt",description:"Prompt to guide the AI.",defaultValue:"Extract the following data from the provided data.",required:!1}),mode:Te.StaticDropdown({displayName:"Data Schema Type",description:"For complex schema, you can use advanced mode.",required:!0,defaultValue:"simple",options:{disabled:!1,options:[{label:"Simple",value:"simple"},{label:"Advanced",value:"advanced"}]}}),schema:Te.DynamicProperties({auth:_o.None(),displayName:"Data Definition",required:!0,refreshers:["mode"],props:s(async e=>e.mode==="advanced"?{fields:Te.Json({displayName:"JSON Schema",description:"Learn more about JSON Schema here: https://json-schema.org/learn/getting-started-step-by-step",required:!0,defaultValue:{type:"object",properties:{name:{type:"string"},age:{type:"number"}},required:["name"]}})}:{fields:Te.Array({displayName:"Data Definition",required:!0,properties:{name:Te.ShortText({displayName:"Name",description:"Provide the name of the value you want to extract from the unstructured text. The name should be unique and short. ",required:!0}),description:Te.LongText({displayName:"Description",description:"Brief description of the data, this hints for the AI on what to look for",required:!1}),type:Te.StaticDropdown({displayName:"Data Type",description:"Type of parameter.",required:!0,defaultValue:"string",options:{disabled:!1,options:[{label:"Text",value:"string"},{label:"Number",value:"number"},{label:"Boolean",value:"boolean"}]}}),isRequired:Te.Checkbox({displayName:"Fail if Not present?",required:!0,defaultValue:!1})}})},"props")}),maxOutputTokens:Te.Number({displayName:"Max Tokens",required:!1,defaultValue:2e3})},async run(e){let t=e.propsValue.provider,o=e.propsValue.model,a=e.propsValue.text,n=e.propsValue.files??[],i=e.propsValue.prompt,l=e.propsValue.schema,u=e.propsValue.maxOutputTokens;if(!a&&!n.length)throw new Error("Please provide text or image/PDF to extract data from.");let c=await Bo({provider:t,modelId:o,engineToken:e.server.token,apiUrl:e.server.apiUrl,projectId:e.project.id,flowId:e.flows.current.id,runId:e.run.id}),d,p={};if(e.propsValue.mode==="advanced"){let y=new xq.default;if(!y.validateSchema(l.fields))throw new Error(JSON.stringify({message:"Invalid JSON schema",errors:y.errors}));d=vi(l.fields)}else{let y=l.fields,_={},v=[];y.forEach(w=>{let S=w.name.replace(/[^a-zA-Z0-9_.-]/g,"_");p[S]=w.name,_[S]={type:w.type,description:w.description},w.isRequired&&v.push(S)}),d=vi({type:"object",properties:_,required:v})}let m={description:"Extract structured data from the provided content",inputSchema:d,execute:s(async y=>y,"execute")},f=[],h=[],g=i||"Extract the following data from the provided data.";if(a&&(g+=`
|
|
179
179
|
|
|
180
180
|
Text to analyze:
|
|
181
181
|
${a}`),h.push({type:"text",text:g}),n.length>0)for(let y of n){let _=y.file;if(!_)continue;let v=_.extension?bq.default.lookup(_.extension):"image/jpeg";v&&v.startsWith("image")&&_.base64?h.push({type:"image",image:`data:${v};base64,${_.base64}`}):v&&v.startsWith("application/pdf")&&_.base64&&h.push({type:"file",data:`data:${v};base64,${_.base64}`,mediaType:v,filename:_.filename})}f.push({role:"user",content:h});try{let _=(await aa({model:c,maxOutputTokens:u,tools:{extractData:m},toolChoice:"required",messages:f})).toolCalls;if(!_||_.length===0)throw new Error("No structured data could be extracted from the input.");let v=_[0].input;if(Object.keys(p).length>0&&v&&typeof v=="object"){let x={};for(let[w,S]of Object.entries(v)){let P=p[w]??w;x[P]=S}return x}return v}catch(y){throw new Error(`Failed to extract structured data: ${y instanceof Error?y.message:"Unknown error"}`)}}});var Tq=s(e=>{let t="IN_PROGRESS",o=[],a,n={};return{setStatus(i){t=i},setToolMap(i){n=i},setStructuredOutput(i){a=i},appendErrorToStructuredOutput(i){a&&(a.errors=[...a.errors||[],i])},fail({message:i}){t="FAILED",Kt(i)||(this.addMarkdown(i),this.appendErrorToStructuredOutput({message:i}))},addMarkdown(i){(o.length===0||o[o.length-1].type!=="MARKDOWN")&&o.push({type:"MARKDOWN",markdown:""}),o[o.length-1].markdown+=i},startToolCall({toolName:i,toolCallId:l,input:u}){let c={toolName:i,toolCallId:l,type:"TOOL_CALL",status:"in-progress",input:u,output:void 0,startTime:new Date().toISOString()};o.push(lme({toolName:i,baseTool:c,toolKeyToAgentTool:n}))},finishToolCall({toolCallId:i,output:l}){let u=o.findIndex(d=>d.type==="TOOL_CALL"&&d.toolCallId===i);if(u===-1)return;let c=o[u];o[u]={...c,status:"completed",endTime:new Date().toISOString(),output:l}},failToolCall({toolCallId:i}){let l=o.findIndex(c=>c.type==="TOOL_CALL"&&c.toolCallId===i);if(l===-1)return;let u=o[l];o[l]={...u,status:"completed",endTime:new Date().toISOString(),output:{status:"FAILED"}}},hasTextContent(){return o.some(i=>i.type==="MARKDOWN"&&i.markdown.trim().length>0)},build(){return{status:t,steps:o,structuredOutput:a,prompt:e}}}},"agentOutputBuilder");function lme({toolName:e,baseTool:t,toolKeyToAgentTool:o}){let a=o[e];if(Kt(a))return{...t,toolCallType:"UNKNOWN",displayName:e};switch(a.type){case"PIECE":return xd(a.pieceMetadata,"Piece metadata is required"),{...t,toolCallType:"PIECE",pieceName:a.pieceMetadata.pieceName,pieceVersion:a.pieceMetadata.pieceVersion,actionName:a.pieceMetadata.actionName};case"FLOW":return xd(a.externalFlowId,"Flow ID is required"),{...t,toolCallType:"FLOW",displayName:a.toolName,externalFlowId:a.externalFlowId};case"MCP":return xd(a.serverUrl,"MCP server URL is required"),{...t,toolCallType:"MCP",displayName:e,serverUrl:a.serverUrl};case"KNOWLEDGE_BASE":return{...t,toolCallType:"KNOWLEDGE_BASE",displayName:a.sourceName,sourceType:a.sourceType};default:return{...t,toolCallType:"UNKNOWN",displayName:e}}}s(lme,"getToolMetadata");var D_=require("util");var zs={isTaskCompletionToolCall:s(e=>e===Ia,"isTaskCompletionToolCall"),structuredOutputSchema(e){let t={};for(let o of e)switch(o.type){case"text":t[o.displayName]=r.string();break;case"number":t[o.displayName]=r.number();break;case"boolean":t[o.displayName]=r.boolean();break;default:t[o.displayName]=r.any()}return Object.keys(t).length>0?r.object(t):void 0},getPrompts(e,t){return{prompt:`
|
|
@@ -233,7 +233,7 @@ Error message: ${JF(o)}`,cause:o}),this[MF]=!0,this.value=t}static isInstance(t)
|
|
|
233
233
|
]))`;continue}else if(n[d]==="$"){i+=`($|(?=[\r
|
|
234
234
|
]))`;continue}}if(a.s&&n[d]==="."){i+=u?`${n[d]}\r
|
|
235
235
|
`:`[${n[d]}\r
|
|
236
|
-
]`;continue}i+=n[d],n[d]==="\\"?l=!0:u&&n[d]==="]"?u=!1:!u&&n[d]==="["&&(u=!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}s(x6,"stringifyRegExpWithFlags");function P6(e,t){var o,a,n,i,l,u;let c={type:"object",additionalProperties:(o=Ut(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?o:t.allowedAdditionalProperties};if(((a=e.keyType)==null?void 0:a._def.typeName)===U.ZodString&&((n=e.keyType._def.checks)!=null&&n.length)){let{type:d,...p}=k6(e.keyType._def,t);return{...c,propertyNames:p}}else{if(((i=e.keyType)==null?void 0:i._def.typeName)===U.ZodEnum)return{...c,propertyNames:{enum:e.keyType._def.values}};if(((l=e.keyType)==null?void 0:l._def.typeName)===U.ZodBranded&&e.keyType._def.type._def.typeName===U.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){let{type:d,...p}=S6(e.keyType._def,t);return{...c,propertyNames:p}}}return c}s(P6,"parseRecordDef");function cge(e,t){if(t.mapStrategy==="record")return P6(e,t);let o=Ut(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Zo(),a=Ut(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Zo();return{type:"array",maxItems:125,items:{type:"array",items:[o,a],minItems:2,maxItems:2}}}s(cge,"parseMapDef");function dge(e){let t=e.values,a=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(a.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}s(dge,"parseNativeEnumDef");function pge(){return{not:Zo()}}s(pge,"parseNeverDef");function mge(){return{type:"null"}}s(mge,"parseNullDef");var Dk={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function fge(e,t){let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(a=>a._def.typeName in Dk&&(!a._def.checks||!a._def.checks.length))){let a=o.reduce((n,i)=>{let l=Dk[i._def.typeName];return l&&!n.includes(l)?[...n,l]:n},[]);return{type:a.length>1?a:a[0]}}else if(o.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){let a=o.reduce((n,i)=>{let l=typeof i._def.value;switch(l){case"string":case"number":case"boolean":return[...n,l];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];default:return n}},[]);if(a.length===o.length){let n=a.filter((i,l,u)=>u.indexOf(i)===l);return{type:n.length>1?n:n[0],enum:o.reduce((i,l)=>i.includes(l._def.value)?i:[...i,l._def.value],[])}}}else if(o.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:o.reduce((a,n)=>[...a,...n._def.values.filter(i=>!a.includes(i))],[])};return hge(e,t)}s(fge,"parseUnionDef");var hge=s((e,t)=>{let o=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((a,n)=>Ut(a._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!t.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return o.length?{anyOf:o}:void 0},"asAnyOf");function gge(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Dk[e.innerType._def.typeName],"null"]};let o=Ut(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}s(gge,"parseNullableDef");function yge(e){let t={type:"number"};if(!e.checks)return t;for(let o of e.checks)switch(o.kind){case"int":t.type="integer";break;case"min":o.inclusive?t.minimum=o.value:t.exclusiveMinimum=o.value;break;case"max":o.inclusive?t.maximum=o.value:t.exclusiveMaximum=o.value;break;case"multipleOf":t.multipleOf=o.value;break}return t}s(yge,"parseNumberDef");function _ge(e,t){let o={type:"object",properties:{}},a=[],n=e.shape();for(let l in n){let u=n[l];if(u===void 0||u._def===void 0)continue;let c=bge(u),d=Ut(u._def,{...t,currentPath:[...t.currentPath,"properties",l],propertyPath:[...t.currentPath,"properties",l]});d!==void 0&&(o.properties[l]=d,c||a.push(l))}a.length&&(o.required=a);let i=vge(e,t);return i!==void 0&&(o.additionalProperties=i),o}s(_ge,"parseObjectDef");function vge(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ut(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}}s(vge,"decideAdditionalProperties");function bge(e){try{return e.isOptional()}catch{return!0}}s(bge,"safeIsOptional");var xge=s((e,t)=>{var o;if(t.currentPath.toString()===((o=t.propertyPath)==null?void 0:o.toString()))return Ut(e.innerType._def,t);let a=Ut(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return a?{anyOf:[{not:Zo()},a]}:Zo()},"parseOptionalDef"),wge=s((e,t)=>{if(t.pipeStrategy==="input")return Ut(e.in._def,t);if(t.pipeStrategy==="output")return Ut(e.out._def,t);let o=Ut(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),a=Ut(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,a].filter(n=>n!==void 0)}},"parsePipelineDef");function Tge(e,t){return Ut(e.type._def,t)}s(Tge,"parsePromiseDef");function Sge(e,t){let a={type:"array",uniqueItems:!0,items:Ut(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(a.minItems=e.minSize.value),e.maxSize&&(a.maxItems=e.maxSize.value),a}s(Sge,"parseSetDef");function Ige(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((o,a)=>Ut(o._def,{...t,currentPath:[...t.currentPath,"items",`${a}`]})).reduce((o,a)=>a===void 0?o:[...o,a],[]),additionalItems:Ut(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((o,a)=>Ut(o._def,{...t,currentPath:[...t.currentPath,"items",`${a}`]})).reduce((o,a)=>a===void 0?o:[...o,a],[])}}s(Ige,"parseTupleDef");function kge(){return{not:Zo()}}s(kge,"parseUndefinedDef");function Pge(){return Zo()}s(Pge,"parseUnknownDef");var Ege=s((e,t)=>Ut(e.innerType._def,t),"parseReadonlyDef"),Age=s((e,t,o)=>{switch(t){case U.ZodString:return k6(e,o);case U.ZodNumber:return yge(e);case U.ZodObject:return _ge(e,o);case U.ZodBigInt:return Yhe(e);case U.ZodBoolean:return Qhe();case U.ZodDate:return I6(e,o);case U.ZodUndefined:return kge();case U.ZodNull:return mge();case U.ZodArray:return Xhe(e,o);case U.ZodUnion:case U.ZodDiscriminatedUnion:return fge(e,o);case U.ZodIntersection:return ige(e,o);case U.ZodTuple:return Ige(e,o);case U.ZodRecord:return P6(e,o);case U.ZodLiteral:return sge(e);case U.ZodEnum:return nge(e);case U.ZodNativeEnum:return dge(e);case U.ZodNullable:return gge(e,o);case U.ZodOptional:return xge(e,o);case U.ZodMap:return cge(e,o);case U.ZodSet:return Sge(e,o);case U.ZodLazy:return()=>e.getter()._def;case U.ZodPromise:return Tge(e,o);case U.ZodNaN:case U.ZodNever:return pge();case U.ZodEffects:return oge(e,o);case U.ZodAny:return Zo();case U.ZodUnknown:return Pge();case U.ZodDefault:return rge(e,o);case U.ZodBranded:return S6(e,o);case U.ZodReadonly:return Ege(e,o);case U.ZodCatch:return ege(e,o);case U.ZodPipeline:return wge(e,o);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(a=>{})(t)}},"selectParser"),Cge=s((e,t)=>{let o=0;for(;o<e.length&&o<t.length&&e[o]===t[o];o++);return[(e.length-o).toString(),...t.slice(o)].join("/")},"getRelativePath");function Ut(e,t,o=!1){var a;let n=t.seen.get(e);if(t.override){let c=(a=t.override)==null?void 0:a.call(t,e,t,n,o);if(c!==Ghe)return c}if(n&&!o){let c=Oge(n,t);if(c!==void 0)return c}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let l=Age(e,e.typeName,t),u=typeof l=="function"?Ut(l(),t):l;if(u&&$ge(e,t,u),t.postProcess){let c=t.postProcess(u,e,t);return i.jsonSchema=u,c}return i.jsonSchema=u,u}s(Ut,"parseDef");var Oge=s((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Cge(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((o,a)=>t.currentPath[a]===o)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Zo()):t.$refStrategy==="seen"?Zo():void 0}},"get$ref"),$ge=s((e,t,o)=>(e.description&&(o.description=e.description),o),"addMeta"),Rge=s(e=>{let t=Khe(e),o=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:o,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([a,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,a],jsonSchema:void 0}]))}},"getRefs"),zge=s((e,t)=>{var o;let a=Rge(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((d,[p,m])=>{var f;return{...d,[p]:(f=Ut(m._def,{...a,currentPath:[...a.basePath,a.definitionPath,p]},!0))!=null?f:Zo()}},{}):void 0,i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,l=(o=Ut(e._def,i===void 0?a:{...a,currentPath:[...a.basePath,a.definitionPath,i]},!1))!=null?o:Zo(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(l.title=u);let c=i===void 0?n?{...l,[a.definitionPath]:n}:l:{$ref:[...a.$refStrategy==="relative"?[]:a.basePath,a.definitionPath,i].join("/"),[a.definitionPath]:{...n,[i]:l}};return c.$schema="http://json-schema.org/draft-07/schema#",c},"zod3ToJsonSchema"),Uk=Symbol.for("vercel.ai.schema");function Ou(e,{validate:t}={}){return{[Uk]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}s(Ou,"jsonSchema");function Nge(e){return typeof e=="object"&&e!==null&&Uk in e&&e[Uk]===!0&&"jsonSchema"in e&&"validate"in e}s(Nge,"isSchema");function qk(e){return e==null?Ou({properties:{},additionalProperties:!1}):Nge(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?Lge(e):jge(e):e()}s(qk,"asSchema");function jge(e){return Ou(()=>Lk(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:s(async t=>{let o=await e["~standard"].validate(t);return"value"in o?{success:!0,value:o.value}:{success:!1,error:new Cu({value:t,cause:o.issues})}},"validate")})}s(jge,"standardSchema");function Mge(e,t){var o;let a=(o=t?.useReferences)!=null?o:!1;return Ou(()=>zge(e,{$refStrategy:a?"root":"none"}),{validate:s(async n=>{let i=await e.safeParseAsync(n);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}},"validate")})}s(Mge,"zod3Schema");function Dge(e,t){var o;let a=(o=t?.useReferences)!=null?o:!1;return Ou(()=>Lk(zo(e,{target:"draft-7",io:"input",reused:a?"ref":"inline"})),{validate:s(async n=>{let i=await wn(e,n);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}},"validate")})}s(Dge,"zod4Schema");function Uge(e){return"_zod"in e}s(Uge,"isZod4Schema");function Lge(e,t){return Uge(e)?Dge(e,t):Mge(e,t)}s(Lge,"zodSchema");async function Fk({value:e,schema:t}){let o=qk(t);try{if(o.validate==null)return{success:!0,value:e,rawValue:e};let a=await o.validate(e);return a.success?{success:!0,value:a.value,rawValue:e}:{success:!1,error:Cu.wrap({value:e,cause:a.error}),rawValue:e}}catch(a){return{success:!1,error:Cu.wrap({value:e,cause:a}),rawValue:e}}}s(Fk,"safeValidateTypes");async function E6({text:e,schema:t}){try{let o=Whe(e);return t==null?{success:!0,value:o,rawValue:o}:await Fk({value:o,schema:t})}catch(o){return{success:!1,error:Nk.isInstance(o)?o:new Nk({text:e,cause:o}),rawValue:void 0}}}s(E6,"safeParseJSON");function A6(e){return{...e,type:"dynamic"}}s(A6,"dynamicTool");var qge="AI_MCPClientError",j6=`vercel.ai.error.${qge}`,Fge=Symbol.for(j6),C6,O6,Et=class extends(O6=wt,C6=Fge,O6){static{s(this,"MCPClientError")}constructor({name:e="MCPClientError",message:t,cause:o,data:a,code:n}){super({name:e,message:t,cause:o}),this[C6]=!0,this.data=a,this.code=n}static isInstance(e){return wt.hasMarker(e,j6)}},Ru="2025-06-18",Bge=[Ru,"2025-03-26","2024-11-05"],Vge=r.optional(r.record(r.string(),r.unknown())),Zge=r.looseObject({name:r.string(),version:r.string()}),j_=r.looseObject({_meta:r.optional(r.object({}).loose())}),Va=j_,M6=r.object({method:r.string(),params:r.optional(j_)}),D6=r.object({applyDefaults:r.optional(r.boolean())}).loose(),Hge=r.looseObject({experimental:r.optional(r.object({}).loose()),logging:r.optional(r.object({}).loose()),prompts:r.optional(r.looseObject({listChanged:r.optional(r.boolean())})),resources:r.optional(r.looseObject({subscribe:r.optional(r.boolean()),listChanged:r.optional(r.boolean())})),tools:r.optional(r.looseObject({listChanged:r.optional(r.boolean())})),elicitation:r.optional(D6)}),DZe=r.object({elicitation:r.optional(D6)}).loose(),Jge=Va.extend({protocolVersion:r.string(),capabilities:Hge,serverInfo:Zge,instructions:r.optional(r.string())}),Vk=Va.extend({nextCursor:r.optional(r.string())}),Wge=r.object({name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),inputSchema:r.object({type:r.literal("object"),properties:r.optional(r.object({}).loose())}).loose(),outputSchema:r.optional(r.object({}).loose()),annotations:r.optional(r.object({title:r.optional(r.string())}).loose()),_meta:Vge}).loose(),Gge=Vk.extend({tools:r.array(Wge)}),U6=r.object({type:r.literal("text"),text:r.string()}).loose(),L6=r.object({type:r.literal("image"),data:r.base64(),mimeType:r.string()}).loose(),Kge=r.object({uri:r.string(),name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),mimeType:r.optional(r.string()),size:r.optional(r.number())}).loose(),Xge=Vk.extend({resources:r.array(Kge)}),q6=r.object({uri:r.string(),name:r.optional(r.string()),title:r.optional(r.string()),mimeType:r.optional(r.string())}).loose(),F6=q6.extend({text:r.string()}),B6=q6.extend({blob:r.base64()}),V6=r.object({type:r.literal("resource"),resource:r.union([F6,B6])}).loose(),Yge=Va.extend({content:r.array(r.union([U6,L6,V6])),structuredContent:r.optional(r.unknown()),isError:r.boolean().default(!1).optional()}).or(Va.extend({toolResult:r.unknown()})),Qge=r.object({uriTemplate:r.string(),name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),mimeType:r.optional(r.string())}).loose(),eye=Va.extend({resourceTemplates:r.array(Qge)}),tye=Va.extend({contents:r.array(r.union([F6,B6]))}),rye=r.object({name:r.string(),description:r.optional(r.string()),required:r.optional(r.boolean())}).loose(),oye=r.object({name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),arguments:r.optional(r.array(rye))}).loose(),nye=Vk.extend({prompts:r.array(oye)}),aye=r.object({role:r.union([r.literal("user"),r.literal("assistant")]),content:r.union([U6,L6,V6])}).loose(),iye=Va.extend({description:r.optional(r.string()),messages:r.array(aye)}),sye=j_.extend({message:r.string(),requestedSchema:r.unknown()}),$6=M6.extend({method:r.literal("elicitation/create"),params:sye}),lye=Va.extend({action:r.union([r.literal("accept"),r.literal("decline"),r.literal("cancel")]),content:r.optional(r.record(r.string(),r.unknown()))}),M_="2.0",uye=r.object({jsonrpc:r.literal(M_),id:r.union([r.string(),r.number().int()])}).merge(M6).strict(),cye=r.object({jsonrpc:r.literal(M_),id:r.union([r.string(),r.number().int()]),result:Va}).strict(),dye=r.object({jsonrpc:r.literal(M_),id:r.union([r.string(),r.number().int()]),error:r.object({code:r.number().int(),message:r.string(),data:r.optional(r.unknown())})}).strict(),pye=r.object({jsonrpc:r.literal(M_)}).merge(r.object({method:r.string(),params:r.optional(j_)})).strict(),km=r.union([uye,pye,cye,dye]),Z6=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",H6=r.object({access_token:r.string(),id_token:r.string().optional(),token_type:r.string(),expires_in:r.number().optional(),scope:r.string().optional(),refresh_token:r.string().optional()}).strip(),Co=r.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:r.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),r.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),mye=r.object({resource:r.string().url(),authorization_servers:r.array(Co).optional(),jwks_uri:r.string().url().optional(),scopes_supported:r.array(r.string()).optional(),bearer_methods_supported:r.array(r.string()).optional(),resource_signing_alg_values_supported:r.array(r.string()).optional(),resource_name:r.string().optional(),resource_documentation:r.string().optional(),resource_policy_uri:r.string().url().optional(),resource_tos_uri:r.string().url().optional(),tls_client_certificate_bound_access_tokens:r.boolean().optional(),authorization_details_types_supported:r.array(r.string()).optional(),dpop_signing_alg_values_supported:r.array(r.string()).optional(),dpop_bound_access_tokens_required:r.boolean().optional()}).passthrough(),J6=r.object({issuer:r.string(),authorization_endpoint:Co,token_endpoint:Co,registration_endpoint:Co.optional(),scopes_supported:r.array(r.string()).optional(),response_types_supported:r.array(r.string()),grant_types_supported:r.array(r.string()).optional(),code_challenge_methods_supported:r.array(r.string()),token_endpoint_auth_methods_supported:r.array(r.string()).optional(),token_endpoint_auth_signing_alg_values_supported:r.array(r.string()).optional()}).passthrough(),fye=r.object({issuer:r.string(),authorization_endpoint:Co,token_endpoint:Co,userinfo_endpoint:Co.optional(),jwks_uri:Co,registration_endpoint:Co.optional(),scopes_supported:r.array(r.string()).optional(),response_types_supported:r.array(r.string()),grant_types_supported:r.array(r.string()).optional(),subject_types_supported:r.array(r.string()),id_token_signing_alg_values_supported:r.array(r.string()),claims_supported:r.array(r.string()).optional(),token_endpoint_auth_methods_supported:r.array(r.string()).optional()}).passthrough(),hye=fye.merge(J6.pick({code_challenge_methods_supported:!0})),gye=r.object({client_id:r.string(),client_secret:r.string().optional(),client_id_issued_at:r.number().optional(),client_secret_expires_at:r.number().optional()}).strip(),yye=r.object({redirect_uris:r.array(Co),token_endpoint_auth_method:r.string().optional(),grant_types:r.array(r.string()).optional(),response_types:r.array(r.string()).optional(),client_name:r.string().optional(),client_uri:Co.optional(),logo_uri:Co.optional(),scope:r.string().optional(),contacts:r.array(r.string()).optional(),tos_uri:Co.optional(),policy_uri:r.string().optional(),jwks_uri:Co.optional(),jwks:r.any().optional(),software_id:r.string().optional(),software_version:r.string().optional(),software_statement:r.string().optional()}).strip(),_ye=r.object({error:r.string(),error_description:r.string().optional(),error_uri:r.string().optional()}),vye=yye.merge(gye),bye="AI_MCPClientOAuthError",W6=`vercel.ai.error.${bye}`,xye=Symbol.for(W6),R6,z6,Pm=class extends(z6=wt,R6=xye,z6){static{s(this,"MCPClientOAuthError")}constructor({name:e="MCPClientOAuthError",message:t,cause:o}){super({name:e,message:t,cause:o}),this[R6]=!0}static isInstance(e){return wt.hasMarker(e,W6)}},$u=class extends Pm{static{s(this,"ServerError")}};$u.errorCode="server_error";var C_=class extends Pm{static{s(this,"InvalidClientError")}};C_.errorCode="invalid_client";var O_=class extends Pm{static{s(this,"InvalidGrantError")}};O_.errorCode="invalid_grant";var $_=class extends Pm{static{s(this,"UnauthorizedClientError")}};$_.errorCode="unauthorized_client";var wye={[$u.errorCode]:$u,[C_.errorCode]:C_,[O_.errorCode]:O_,[$_.errorCode]:$_};function Tye(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}s(Tye,"resourceUrlFromServerUrl");function Sye({requestedResource:e,configuredResource:t}){let o=typeof e=="string"?new URL(e):new URL(e.href),a=typeof t=="string"?new URL(t):new URL(t.href);if(o.origin!==a.origin||o.pathname.length<a.pathname.length)return!1;let n=o.pathname.endsWith("/")?o.pathname:o.pathname+"/",i=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return n.startsWith(i)}s(Sye,"checkResourceAllowed");var R_=class extends Error{static{s(this,"UnauthorizedError")}constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function z_(e){var t;let o=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!o)return;let[a,n]=o.split(" ");if(a.toLowerCase()!=="bearer"||!n)return;let i=/resource_metadata="([^"]*)"/,l=o.match(i);if(l)try{return new URL(l[1])}catch{return}}s(z_,"extractResourceMetadataUrl");function Iye(e,t="",o={}){return t.endsWith("/")&&(t=t.slice(0,-1)),o.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}s(Iye,"buildWellKnownPath");async function Zk(e,t,o=fetch){try{return await o(e,{headers:t})}catch(a){if(a instanceof TypeError)return t?Zk(e,void 0,o):void 0;throw a}}s(Zk,"fetchWithCorsRetry");async function N6(e,t,o=fetch){return await Zk(e,{"MCP-Protocol-Version":t},o)}s(N6,"tryMetadataDiscovery");function kye(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}s(kye,"shouldAttemptFallback");async function Pye(e,t,o,a){var n,i;let l=new URL(e),u=(n=a?.protocolVersion)!=null?n:Ru,c;if(a?.metadataUrl)c=new URL(a.metadataUrl);else{let p=Iye(t,l.pathname);c=new URL(p,(i=a?.metadataServerUrl)!=null?i:l),c.search=l.search}let d=await N6(c,u,o);if(!a?.metadataUrl&&kye(d,l.pathname)){let p=new URL(`/.well-known/${t}`,l);d=await N6(p,u,o)}return d}s(Pye,"discoverMetadataWithFallback");async function Eye(e,t,o=fetch){let a=await Pye(e,"oauth-protected-resource",o,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!a||a.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return mye.parse(await a.json())}s(Eye,"discoverOAuthProtectedResourceMetadata");function Aye(e){let t=typeof e=="string"?new URL(e):e,o=t.pathname!=="/",a=[];if(!o)return a.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),a;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),a.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),a}s(Aye,"buildDiscoveryUrls");async function Cye(e,{fetchFn:t=fetch,protocolVersion:o=Ru}={}){var a;let n={"MCP-Protocol-Version":o},i=Aye(e);for(let{url:l,type:u}of i){let c=await Zk(l,n,t);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${u==="oauth"?"OAuth":"OpenID provider"} metadata from ${l}`)}if(u==="oauth")return J6.parse(await c.json());{let d=hye.parse(await c.json());if(!((a=d.code_challenge_methods_supported)!=null&&a.includes("S256")))throw new Error(`Incompatible OIDC provider at ${l}: does not support S256 code challenge method required by MCP specification`);return d}}}}s(Cye,"discoverAuthorizationServerMetadata");async function Oye(e,{metadata:t,clientInformation:o,redirectUrl:a,scope:n,state:i,resource:l}){let u="code",c="S256",d;if(t){if(d=new URL(t.authorization_endpoint),!t.response_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support response type ${u}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else d=new URL("/authorize",e);let p=await pm(),m=p.code_verifier,f=p.code_challenge;return d.searchParams.set("response_type",u),d.searchParams.set("client_id",o.client_id),d.searchParams.set("code_challenge",f),d.searchParams.set("code_challenge_method",c),d.searchParams.set("redirect_uri",String(a)),i&&d.searchParams.set("state",i),n&&d.searchParams.set("scope",n),n?.includes("offline_access")&&d.searchParams.append("prompt","consent"),l&&d.searchParams.set("resource",l.href),{authorizationUrl:d,codeVerifier:m}}s(Oye,"startAuthorization");function G6(e,t){let o=e.client_secret!==void 0;return t.length===0?o?"client_secret_post":"none":o&&t.includes("client_secret_basic")?"client_secret_basic":o&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":o?"client_secret_post":"none"}s(G6,"selectClientAuthMethod");function K6(e,t,o,a){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":$ye(n,i,o);return;case"client_secret_post":Rye(n,i,a);return;case"none":zye(n,a);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}s(K6,"applyClientAuthentication");function $ye(e,t,o){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let a=btoa(`${e}:${t}`);o.set("Authorization",`Basic ${a}`)}s($ye,"applyBasicAuth");function Rye(e,t,o){o.set("client_id",e),t&&o.set("client_secret",t)}s(Rye,"applyPostAuth");function zye(e,t){t.set("client_id",e)}s(zye,"applyPublicAuth");async function Hk(e){let t=e instanceof Response?e.status:void 0,o=e instanceof Response?await e.text():e;try{let a=_ye.parse(JSON.parse(o)),{error:n,error_description:i,error_uri:l}=a,u=wye[n]||$u;return new u({message:i||"",cause:l})}catch(a){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${a}. Raw body: ${o}`;return new $u({message:n})}}s(Hk,"parseErrorResponse");async function Nye(e,{metadata:t,clientInformation:o,authorizationCode:a,codeVerifier:n,redirectUri:i,resource:l,addClientAuthentication:u,fetchFn:c}){var d;let p="authorization_code",m=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(p))throw new Error(`Incompatible auth server: does not support grant type ${p}`);let f=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:p,code:a,code_verifier:n,redirect_uri:String(i)});if(u)u(f,h,e,t);else{let y=(d=t?.token_endpoint_auth_methods_supported)!=null?d:[],_=G6(o,y);K6(_,o,f,h)}l&&h.set("resource",l.href);let g=await(c??fetch)(m,{method:"POST",headers:f,body:h});if(!g.ok)throw await Hk(g);return H6.parse(await g.json())}s(Nye,"exchangeAuthorization");async function jye(e,{metadata:t,clientInformation:o,refreshToken:a,resource:n,addClientAuthentication:i,fetchFn:l}){var u;let c="refresh_token",d;if(t){if(d=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else d=new URL("/token",e);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),m=new URLSearchParams({grant_type:c,refresh_token:a});if(i)i(p,m,e,t);else{let h=(u=t?.token_endpoint_auth_methods_supported)!=null?u:[],g=G6(o,h);K6(g,o,p,m)}n&&m.set("resource",n.href);let f=await(l??fetch)(d,{method:"POST",headers:p,body:m});if(!f.ok)throw await Hk(f);return H6.parse({refresh_token:a,...await f.json()})}s(jye,"refreshAuthorization");async function Mye(e,{metadata:t,clientMetadata:o,fetchFn:a}){let n;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);let i=await(a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw await Hk(i);return vye.parse(await i.json())}s(Mye,"registerClient");async function N_(e,t){var o,a;try{return await Bk(e,t)}catch(n){if(n instanceof C_||n instanceof $_)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"all")),await Bk(e,t);if(n instanceof O_)return await((a=e.invalidateCredentials)==null?void 0:a.call(e,"tokens")),await Bk(e,t);throw n}}s(N_,"auth");async function Dye(e,t,o){let a=Tye(e);if(t.validateResourceURL)return await t.validateResourceURL(a,o?.resource);if(o){if(!Sye({requestedResource:a,configuredResource:o.resource}))throw new Error(`Protected resource ${o.resource} does not match expected ${a} (or origin)`);return new URL(o.resource)}}s(Dye,"selectResourceURL");async function Bk(e,{serverUrl:t,authorizationCode:o,scope:a,resourceMetadataUrl:n,fetchFn:i}){let l,u;try{l=await Eye(t,{resourceMetadataUrl:n},i),l.authorization_servers&&l.authorization_servers.length>0&&(u=l.authorization_servers[0])}catch{}u||(u=t);let c=await Dye(t,e,l),d=await Cye(u,{fetchFn:i}),p=await Promise.resolve(e.clientInformation());if(!p){if(o!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let y=await Mye(u,{metadata:d,clientMetadata:e.clientMetadata,fetchFn:i});await e.saveClientInformation(y),p=y}if(o!==void 0){let y=await e.codeVerifier(),_=await Nye(u,{metadata:d,clientInformation:p,authorizationCode:o,codeVerifier:y,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(_),"AUTHORIZED"}let m=await e.tokens();if(m?.refresh_token)try{let y=await jye(u,{metadata:d,clientInformation:p,refreshToken:m.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof Pm)||y instanceof $u))throw y}let f=e.state?await e.state():void 0,{authorizationUrl:h,codeVerifier:g}=await Oye(u,{metadata:d,clientInformation:p,state:f,redirectUrl:e.redirectUrl,scope:a||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(h),"REDIRECT"}s(Bk,"authInternal");var Uye=class{static{s(this,"SseMCPTransport")}constructor({url:e,headers:t,authProvider:o}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=o}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":Ru};if(this.authProvider){let o=await this.authProvider.tokens();o?.access_token&&(t.Authorization=`Bearer ${o.access_token}`)}return A_(t,`ai-sdk/${Z6}`,E_())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let o=s(async(a=!1)=>{var n,i,l,u,c;try{let d=await this.commonHeaders({Accept:"text/event-stream"}),p=await fetch(this.url.href,{headers:d,signal:(n=this.abortController)==null?void 0:n.signal});if(p.status===401&&this.authProvider&&!a){this.resourceMetadataUrl=z_(p);try{if(await N_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let y=new R_;return(i=this.onerror)==null||i.call(this,y),t(y)}}catch(g){return(l=this.onerror)==null||l.call(this,g),t(g)}return o(!0)}if(!p.ok||!p.body){let g=`MCP SSE Transport Error: ${p.status} ${p.statusText}`;p.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");let y=new Et({message:g});return(u=this.onerror)==null||u.call(this,y),t(y)}let f=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new en).getReader(),h=s(async()=>{var g,y,_;try{for(;;){let{done:v,value:x}=await f.read();if(v){if(this.connected)throw this.connected=!1,new Et({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}let{event:w,data:S}=x;if(w==="endpoint"){if(this.endpoint=new URL(S,this.url),this.endpoint.origin!==this.url.origin)throw new Et({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(w==="message")try{let P=km.parse(JSON.parse(S));(g=this.onmessage)==null||g.call(this,P)}catch(P){let k=new Et({message:"MCP SSE Transport Error: Failed to parse message",cause:P});(y=this.onerror)==null||y.call(this,k)}}}catch(v){if(v instanceof Error&&v.name==="AbortError")return;(_=this.onerror)==null||_.call(this,v),t(v)}},"processEvents");this.sseConnection={close:s(()=>f.cancel(),"close")},h()}catch(d){if(d instanceof Error&&d.name==="AbortError")return;(c=this.onerror)==null||c.call(this,d),t(d)}},"establishConnection");o()})}async close(){var e,t,o;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(o=this.onclose)==null||o.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new Et({message:"MCP SSE Transport Error: Not connected"});let t=this.endpoint,o=s(async(a=!1)=>{var n,i,l,u,c;try{let p={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},m=await fetch(t,p);if(m.status===401&&this.authProvider&&!a){this.resourceMetadataUrl=z_(m);try{if(await N_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let h=new R_;(i=this.onerror)==null||i.call(this,h);return}}catch(f){(l=this.onerror)==null||l.call(this,f);return}return o(!0)}if(!m.ok){let f=await m.text().catch(()=>null),h=new Et({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${m.status}): ${f}`});(u=this.onerror)==null||u.call(this,h);return}}catch(d){(c=this.onerror)==null||c.call(this,d);return}},"attempt");await o()}},Lye=class{static{s(this,"HttpMCPTransport")}constructor({url:e,headers:t,authProvider:o}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=o}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":Ru};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){let o=await this.authProvider.tokens();o?.access_token&&(t.Authorization=`Bearer ${o.access_token}`)}return A_(t,`ai-sdk/${Z6}`,E_())}async start(){if(this.abortController)throw new Et({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,o;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let a=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:a,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(o=this.onclose)==null||o.call(this)}async send(e){let t=s(async(o=!1)=>{var a,n,i,l,u,c,d;try{let m={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(a=this.abortController)==null?void 0:a.signal},f=await fetch(this.url,m),h=f.headers.get("mcp-session-id");if(h&&(this.sessionId=h),f.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=z_(f);try{if(await N_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new R_}catch(v){throw(n=this.onerror)==null||n.call(this,v),v}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){let v=await f.text().catch(()=>null),x=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${v}`;f.status===404&&(x+=". This server does not support HTTP transport. Try using `sse` transport instead");let w=new Et({message:x});throw(i=this.onerror)==null||i.call(this,w),w}if(!("id"in e))return;let y=f.headers.get("content-type")||"";if(y.includes("application/json")){let v=await f.json(),x=Array.isArray(v)?v.map(w=>km.parse(w)):[km.parse(v)];for(let w of x)(l=this.onmessage)==null||l.call(this,w);return}if(y.includes("text/event-stream")){if(!f.body){let S=new Et({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(u=this.onerror)==null||u.call(this,S),S}let x=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new en).getReader();s(async()=>{var S,P,k;try{for(;;){let{done:I,value:E}=await x.read();if(I)return;let{event:b,data:M}=E;if(b==="message")try{let R=km.parse(JSON.parse(M));(S=this.onmessage)==null||S.call(this,R)}catch(R){let D=new Et({message:"MCP HTTP Transport Error: Failed to parse message",cause:R});(P=this.onerror)==null||P.call(this,D)}}}catch(I){if(I instanceof Error&&I.name==="AbortError")return;(k=this.onerror)==null||k.call(this,I)}},"processEvents")();return}let _=new Et({message:`MCP HTTP Transport Error: Unexpected content type: ${y}`});throw(c=this.onerror)==null||c.call(this,_),_}catch(p){throw(d=this.onerror)==null||d.call(this,p),p}},"attempt");await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:o,maxReconnectionDelay:a}=this.reconnectionOptions;return Math.min(t*Math.pow(o,e),a)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new Et({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let o=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var a;(a=this.abortController)!=null&&a.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},o)}async openInboundSse(e=!1,t){var o,a,n,i,l,u;try{let c=await this.commonHeaders({Accept:"text/event-stream"});t&&(c["last-event-id"]=t);let d=await fetch(this.url.href,{method:"GET",headers:c,signal:(o=this.abortController)==null?void 0:o.signal}),p=d.headers.get("mcp-session-id");if(p&&(this.sessionId=p),d.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=z_(d);try{if(await N_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let y=new R_;(a=this.onerror)==null||a.call(this,y);return}}catch(g){(n=this.onerror)==null||n.call(this,g);return}return this.openInboundSse(!0,t)}if(d.status===405)return;if(!d.ok||!d.body){let g=new Et({message:`MCP HTTP Transport Error: GET SSE failed: ${d.status} ${d.statusText}`});(i=this.onerror)==null||i.call(this,g);return}let f=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new en).getReader(),h=s(async()=>{var g,y,_,v;try{for(;;){let{done:x,value:w}=await f.read();if(x)return;let{event:S,data:P,id:k}=w;if(k&&(this.lastInboundEventId=k),S==="message")try{let I=km.parse(JSON.parse(P));(g=this.onmessage)==null||g.call(this,I)}catch(I){let E=new Et({message:"MCP HTTP Transport Error: Failed to parse message",cause:I});(y=this.onerror)==null||y.call(this,E)}}}catch(x){if(x instanceof Error&&x.name==="AbortError")return;(_=this.onerror)==null||_.call(this,x),(v=this.abortController)!=null&&v.signal.aborted||this.scheduleInboundSseReconnection()}},"processEvents");this.inboundSseConnection={close:s(()=>f.cancel(),"close")},this.inboundReconnectAttempts=0,h()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),(u=this.abortController)!=null&&u.signal.aborted||this.scheduleInboundSseReconnection()}}};function qye(e){switch(e.type){case"sse":return new Uye(e);case"http":return new Lye(e);default:throw new Et({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}s(qye,"createMcpTransport");function Fye(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}s(Fye,"isCustomMcpTransport");var Bye="1.0.0";async function X6(e){let t=new Vye(e);return await t.init(),t}s(X6,"createMCPClient");var Vye=class{static{s(this,"DefaultMCPClient")}constructor({transport:e,name:t="ai-sdk-mcp-client",version:o=Bye,onUncaughtError:a,capabilities:n}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=a,this.clientCapabilities=n??{},Fye(e)?this.transport=e:this.transport=qye(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=i=>this.onError(i),this.transport.onmessage=i=>{if("method"in i){"id"in i?this.onRequestMessage(i):this.onError(new Et({message:"Unsupported message type"}));return}this.onResponse(i)},this.clientInfo={name:t,version:o}}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:"initialize",params:{protocolVersion:Ru,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Jge});if(e===void 0)throw new Et({message:"Server sent invalid initialize result"});if(!Bge.includes(e.protocolVersion))throw new Et({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new Et({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Et({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Et({message:"Server does not support prompts"});break;default:throw new Et({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:o}){return new Promise((a,n)=>{if(this.isClosed)return n(new Et({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);let i=o?.signal;i?.throwIfAborted();let l=this.requestMessageId++,u={...e,jsonrpc:"2.0",id:l},c=s(()=>{this.responseHandlers.delete(l)},"cleanup");this.responseHandlers.set(l,d=>{if(i?.aborted)return n(new Et({message:"Request was aborted",cause:i.reason}));if(d instanceof Error)return n(d);try{let p=t.parse(d.result);a(p)}catch(p){let m=new Et({message:"Failed to parse server response",cause:p});n(m)}}),this.transport.send(u).catch(d=>{c(),n(d)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:Gge,options:t})}catch(o){throw o}}async callTool({name:e,args:t,options:o}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:Yge,options:{signal:o?.abortSignal}})}catch(a){throw a}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:Xge,options:t})}catch(o){throw o}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:tye,options:t})}catch(o){throw o}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:eye,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:nye,options:t})}catch(o){throw o}}async getPromptInternal({name:e,args:t,options:o}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:iye,options:o})}catch(a){throw a}}async notification(e){let t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t,o;let a={};try{let n=await this.listTools();for(let{name:i,title:l,description:u,inputSchema:c,annotations:d,_meta:p}of n.tools){let m=l??d?.title;if(e!=="automatic"&&!(i in e))continue;let f=this,h=e!=="automatic"?(t=e[i])==null?void 0:t.outputSchema:void 0,g=s(async(_,v)=>{var x;(x=v?.abortSignal)==null||x.throwIfAborted();let w=await f.callTool({name:i,args:_,options:v});return h!=null?f.extractStructuredContent(w,h,i):w},"execute"),y=e==="automatic"?A6({description:u,title:m,inputSchema:Ou({...c,properties:(o=c.properties)!=null?o:{},additionalProperties:!1}),execute:g}):{description:u,title:m,inputSchema:e[i].inputSchema,...h!=null?{outputSchema:h}:{},execute:g};a[i]={...y,_meta:p}}return a}catch(n){throw n}}async extractStructuredContent(e,t,o){if("structuredContent"in e&&e.structuredContent!=null){let a=await Fk({value:e.structuredContent,schema:qk(t)});if(!a.success)throw new Et({message:`Tool "${o}" returned structuredContent that does not match the expected outputSchema`,cause:a.error});return a.value}if("content"in e&&Array.isArray(e.content)){let a=e.content.find(n=>n.type==="text");if(a&&"text"in a){let n=await E6({text:a.text,schema:t});if(!n.success)throw new Et({message:`Tool "${o}" returned content that does not match the expected outputSchema`,cause:n.error});return n.value}}throw new Et({message:`Tool "${o}" 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:o}){return this.getPromptInternal({name:e,args:t,options:o})}onElicitationRequest(e,t){if(e!==$6)throw new Et({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}let t=$6.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 o=await this.elicitationRequestHandler(t.data),a=lye.parse(o);await this.transport.send({jsonrpc:"2.0",id:e.id,result:a})}catch(o){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:o instanceof Error?o.message:"Failed to handle elicitation request"}}),this.onError(o)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new Et({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),o=this.responseHandlers.get(t);if(o===void 0)throw new Et({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),o("result"in e?e:new Et({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function Zye(e,t,o={}){let a=new URL(t);switch(e){case"http":return{type:"http",url:t,headers:o};case"streamable-http":return new P_(a,{requestInit:{headers:o}});case"sse":return{type:"sse",url:t,headers:o};default:throw new Error(`Unsupported MCP protocol type: ${e}`)}}s(Zye,"createTransportConfig");var Y6="search_knowledge_base";function Hye(e,t){let o=[],a={},n={};for(let i of e){o.push(i.mcpClient);let l=t.find(u=>u.toolName===i.mcpName);for(let[u,c]of Object.entries(i.tools)){let d=ns.createToolName(`${u}`);a[d]=c,l&&(n[d]=l)}}return{mcpClients:o,tools:a,keyToAgentTool:n}}s(Hye,"flattenMcpServers");async function Jye(e){let t=[];for(let o of e)try{let a=await X6({transport:Zye(o.protocol,o.serverUrl,zx(o.auth))}),n=await a.tools();t.push({mcpName:o.toolName,mcpClient:a,tools:n})}catch(a){console.error(`Failed to connect to MCP server ${o.serverUrl}:`,a)}return t}s(Jye,"constructMcpServersTools");function Wye(e){return{get(t,o){return ia.sendRequest({method:"GET",url:`${e.server.apiUrl}${t}`,...o?{queryParams:o}:{},authentication:{type:"BEARER_TOKEN",token:e.server.token}})},post(t,o){return ia.sendRequest({method:"POST",url:`${e.server.apiUrl}${t}`,authentication:{type:"BEARER_TOKEN",token:e.server.token},body:o})}}}s(Wye,"createServerApiClient");async function Gye(e,t,o){let a={},n={},i=Wye(t),l=e.filter(d=>d.sourceType==="FILE"),u=e.filter(d=>d.sourceType==="TABLE");if(l.length>0&&o){let d=l.map(m=>m.sourceId),p=l.map(m=>m.sourceName).join(", ");for(let m of l)try{let h=(await i.get(`v1/knowledge-base/files/${m.sourceId}/chunks?embedded=false`)).body;if(h.length>0)for(let y=0;y<h.length;y+=50){let _=h.slice(y,y+50),{embeddings:v}=await pN({model:o.model,values:_.map(x=>x.content),providerOptions:o.providerOptions});await i.post(`v1/knowledge-base/files/${m.sourceId}/store-chunks`,{chunks:_.map((x,w)=>({id:x.id,embedding:Array.from(v[w])}))})}}catch(f){console.error(`Failed to embed KB file '${m.sourceName}':`,f)}a[Y6]=ep({description:`Search uploaded documents for relevant information. Available documents: ${p}. Use when you need facts, policies, or content from these knowledge base files.`,inputSchema:wo.object({query:wo.string().describe("Search query to find relevant information")}),execute:s(async m=>{let{query:f}=m,{embedding:h}=await dN({model:o.model,value:f,providerOptions:o.providerOptions}),y=(await i.post("v1/knowledge-base/files/search",{knowledgeBaseFileIds:d,queryEmbedding:Array.from(h),limit:5,similarityThreshold:.5})).body;return!y||y.length===0?{results:"No relevant information found."}:{results:y.map((_,v)=>({rank:v+1,content:_.content,source:_.metadata?.fileName??"unknown",relevanceScore:_.score}))}},"execute")}),n[Y6]=l[0]}let c=await Promise.all(u.map(async d=>{let p=ns.createToolName(`query_table_${d.toolName}`),m,f=[],h="";try{let y=await i.get(`v1/tables/${encodeURIComponent(d.sourceId)}`);y.body.id&&(m=y.body.id,f=(await i.get(`v1/fields?tableId=${m}`)).body,h=f.map(v=>`${v.name} (${v.type})`).join(", "))}catch(y){console.error(`Failed to fetch table metadata for '${d.sourceName}':`,y)}let g=ep({description:`Query the '${d.sourceName}' data table.${h?` Columns: ${h}.`:""} Use to look up records or find specific entries.`,inputSchema:wo.object({filters:wo.array(wo.object({fieldName:wo.string().describe("The name of the field to filter on"),operator:wo.enum(["eq","neq","gt","gte","lt","lte","co","exists","not_exists"]).describe("Filter operator"),value:wo.string().optional().describe("The value to filter by")})).optional().describe("Optional filters to narrow results"),limit:wo.number().optional().default(10).describe("Maximum number of records to return")}),execute:s(async y=>{let{filters:_,limit:v}=y;if(!m)return{error:`Table '${d.sourceName}' not found`};let x;if(_&&_.length>0){let k=new Map(f.map(I=>[I.name.toLowerCase(),I.id]));x=_.flatMap(I=>{let E=k.get(I.fieldName.toLowerCase());return E?[{fieldId:E,operator:I.operator,value:I.value}]:[]})}let w={tableId:m,limit:String(v??10),...Kye("filters",x??[])},P=(await i.get("v1/records",w)).body.data;return{records:P,count:P.length}},"execute")});return{toolName:p,tool:g,agentTool:d}}));for(let{toolName:d,tool:p,agentTool:m}of c)a[d]=p,n[d]=m;return{tools:a,keyToAgentTool:n}}s(Gye,"constructKnowledgeBaseTools");async function Q6(e){let{outputBuilder:t,structuredOutput:o,agentTools:a,context:n,model:i,embeddingConfig:l}=e,u=await n.agent.tools({tools:a.filter(S=>S.type==="PIECE"),model:i}),c=await zs.constructFlowsTools({tools:a.filter(S=>S.type==="FLOW"),fetchFlows:n.flows.list,publicUrl:n.server.publicUrl,token:n.server.token}),d=a.filter(S=>S.type==="MCP"),p=await Jye(d),{mcpClients:m,tools:f,keyToAgentTool:h}=Hye(p,d),g=a.filter(S=>S.type==="KNOWLEDGE_BASE"),{tools:y,keyToAgentTool:_}=await Gye(g,n,l),v={...u,...c,...f,...y},x={};for(let S of a.filter(P=>P.type!=="MCP"&&P.type!=="KNOWLEDGE_BASE")){let P=S.type==="FLOW"?ns.createToolName(S.toolName):S.toolName;x[P]=S}Object.assign(x,h),Object.assign(x,_);let w={[Ia]:ep({description:"This tool must be called as your FINAL ACTION to indicate whether the assigned goal was accomplished. Call it only when you have completed the user's task, or if you are unable to continue. Once you call this tool, you should not take any further actions.",inputSchema:wo.object({success:wo.boolean().describe("Set to true if the assigned goal was achieved, or false if the task was abandoned or failed."),...Kt(o)?{output:wo.string().describe("Your complete response to the user. Always populate this with the full answer, result, or explanation \u2014 even if you already wrote text above. This is the final message that will be shown to the user.")}:{output:wo.object(zs.structuredOutputSchema(o)?.shape??{}).nullable().describe("The structured output of your task. This is optional and can be omitted if you have not achieved the goal.")}}),execute:s(async S=>{let{success:P,output:k}=S;return t.setStatus(P?"COMPLETED":"FAILED"),!Kt(o)&&!Kt(k)&&!bd(k)?t.setStructuredOutput(k):Kt(o)&&!Kt(k)&&!t.hasTextContent()&&t.addMarkdown(k),{}},"execute")})};return{mcpClients:m,toolKeyToAgentTool:x,tools:{...v,...w}}}s(Q6,"constructAgentTools");function Kye(e,t){let o={};return t.forEach((a,n)=>{for(let[i,l]of Object.entries(a))l!==void 0&&(o[`${e}[${n}][${i}]`]=l)}),o}s(Kye,"serializeArrayQuery");var Xye={type:Te.ShortText({displayName:"Tool Type",required:!0}),toolName:Te.ShortText({displayName:"Tool Name",required:!0}),pieceMetadata:Te.Json({displayName:"Piece Metadata",required:!1}),externalFlowId:Te.ShortText({displayName:"Flow External ID",required:!1}),serverUrl:Te.ShortText({displayName:"MCP Server URL",required:!1}),protocol:Te.ShortText({displayName:"Protocol",required:!1}),auth:Te.Json({displayName:"Auth Configuration",required:!1}),sourceType:Te.ShortText({displayName:"Source Type",required:!1}),sourceId:Te.ShortText({displayName:"Source ID",required:!1}),sourceName:Te.ShortText({displayName:"Source Name",required:!1})},eB=Xo({audience:"both",name:"run_agent",displayName:"Run Agent",description:"Handles complex, multi-step tasks by reasoning through problems, using tools accurately, and iterating until the job is done.",auth:_o.None(),props:{prompt:Te.LongText({displayName:"Prompt",description:"Describe what you want the assistant to do.",required:!0}),aiProviderModel:Te.Object({displayName:"AI Model",required:!0}),agentTools:Te.Array({displayName:"Agent Tools",required:!1,properties:Xye}),structuredOutput:Te.Array({displayName:"Structured Output",defaultValue:void 0,required:!1,properties:{displayName:Te.ShortText({displayName:"Display Name",required:!0}),description:Te.ShortText({displayName:"Description",required:!1}),type:Te.ShortText({displayName:"Type",required:!0})}}),maxSteps:Te.Number({displayName:"Max steps",description:"The number of iterations the agent can do",required:!0,defaultValue:20}),webSearch:Te.Checkbox({displayName:"Web Search",required:!1,defaultValue:!1,description:"Whether to use web search to find information for the AI to use."}),webSearchOptions:Dy(e=>{let t=e.aiProviderModel;return{provider:t?.provider,model:t?.model}},["webSearch","aiProviderModel"],{showIncludeSources:!1})},async run(e){let{prompt:t,maxSteps:o,aiProviderModel:a}=e.propsValue,n=a,i=n.provider,l=!!e.propsValue.webSearch,u=e.propsValue.webSearchOptions??{},{tools:c,providerOptions:d}=Uy({provider:i,model:n.model,webSearchEnabled:l,webSearchOptions:u}),{provider:p}=_n({provider:i,model:n.model}),m=await Bo({modelId:n.model,provider:i,engineToken:e.server.token,apiUrl:e.server.apiUrl,projectId:e.project.id,flowId:e.flows.current.id,runId:e.run.id,...Qr("openaiResponsesModel",l&&p==="openai"?!0:void 0)}),f=Tq(t),g=!Kt(e.propsValue.structuredOutput)&&e.propsValue.structuredOutput.length>0?e.propsValue.structuredOutput:void 0,y=e.propsValue.agentTools,_=y.some(b=>b.type==="KNOWLEDGE_BASE"),x=y.filter(b=>b.type==="KNOWLEDGE_BASE"&&b.sourceType==="FILE").length>0,w;if(x)try{let b=await OS({provider:n.provider,engineToken:e.server.token,apiUrl:e.server.apiUrl});w={model:b.model,providerOptions:b.providerOptions}}catch(b){f.addMarkdown(`
|
|
236
|
+
]`;continue}i+=n[d],n[d]==="\\"?l=!0:u&&n[d]==="]"?u=!1:!u&&n[d]==="["&&(u=!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}s(x6,"stringifyRegExpWithFlags");function P6(e,t){var o,a,n,i,l,u;let c={type:"object",additionalProperties:(o=Ut(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?o:t.allowedAdditionalProperties};if(((a=e.keyType)==null?void 0:a._def.typeName)===U.ZodString&&((n=e.keyType._def.checks)!=null&&n.length)){let{type:d,...p}=k6(e.keyType._def,t);return{...c,propertyNames:p}}else{if(((i=e.keyType)==null?void 0:i._def.typeName)===U.ZodEnum)return{...c,propertyNames:{enum:e.keyType._def.values}};if(((l=e.keyType)==null?void 0:l._def.typeName)===U.ZodBranded&&e.keyType._def.type._def.typeName===U.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){let{type:d,...p}=S6(e.keyType._def,t);return{...c,propertyNames:p}}}return c}s(P6,"parseRecordDef");function cge(e,t){if(t.mapStrategy==="record")return P6(e,t);let o=Ut(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Zo(),a=Ut(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Zo();return{type:"array",maxItems:125,items:{type:"array",items:[o,a],minItems:2,maxItems:2}}}s(cge,"parseMapDef");function dge(e){let t=e.values,a=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(a.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}s(dge,"parseNativeEnumDef");function pge(){return{not:Zo()}}s(pge,"parseNeverDef");function mge(){return{type:"null"}}s(mge,"parseNullDef");var Dk={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function fge(e,t){let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(a=>a._def.typeName in Dk&&(!a._def.checks||!a._def.checks.length))){let a=o.reduce((n,i)=>{let l=Dk[i._def.typeName];return l&&!n.includes(l)?[...n,l]:n},[]);return{type:a.length>1?a:a[0]}}else if(o.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){let a=o.reduce((n,i)=>{let l=typeof i._def.value;switch(l){case"string":case"number":case"boolean":return[...n,l];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];default:return n}},[]);if(a.length===o.length){let n=a.filter((i,l,u)=>u.indexOf(i)===l);return{type:n.length>1?n:n[0],enum:o.reduce((i,l)=>i.includes(l._def.value)?i:[...i,l._def.value],[])}}}else if(o.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:o.reduce((a,n)=>[...a,...n._def.values.filter(i=>!a.includes(i))],[])};return hge(e,t)}s(fge,"parseUnionDef");var hge=s((e,t)=>{let o=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((a,n)=>Ut(a._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!t.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return o.length?{anyOf:o}:void 0},"asAnyOf");function gge(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Dk[e.innerType._def.typeName],"null"]};let o=Ut(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}s(gge,"parseNullableDef");function yge(e){let t={type:"number"};if(!e.checks)return t;for(let o of e.checks)switch(o.kind){case"int":t.type="integer";break;case"min":o.inclusive?t.minimum=o.value:t.exclusiveMinimum=o.value;break;case"max":o.inclusive?t.maximum=o.value:t.exclusiveMaximum=o.value;break;case"multipleOf":t.multipleOf=o.value;break}return t}s(yge,"parseNumberDef");function _ge(e,t){let o={type:"object",properties:{}},a=[],n=e.shape();for(let l in n){let u=n[l];if(u===void 0||u._def===void 0)continue;let c=bge(u),d=Ut(u._def,{...t,currentPath:[...t.currentPath,"properties",l],propertyPath:[...t.currentPath,"properties",l]});d!==void 0&&(o.properties[l]=d,c||a.push(l))}a.length&&(o.required=a);let i=vge(e,t);return i!==void 0&&(o.additionalProperties=i),o}s(_ge,"parseObjectDef");function vge(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ut(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}}s(vge,"decideAdditionalProperties");function bge(e){try{return e.isOptional()}catch{return!0}}s(bge,"safeIsOptional");var xge=s((e,t)=>{var o;if(t.currentPath.toString()===((o=t.propertyPath)==null?void 0:o.toString()))return Ut(e.innerType._def,t);let a=Ut(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return a?{anyOf:[{not:Zo()},a]}:Zo()},"parseOptionalDef"),wge=s((e,t)=>{if(t.pipeStrategy==="input")return Ut(e.in._def,t);if(t.pipeStrategy==="output")return Ut(e.out._def,t);let o=Ut(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),a=Ut(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,a].filter(n=>n!==void 0)}},"parsePipelineDef");function Tge(e,t){return Ut(e.type._def,t)}s(Tge,"parsePromiseDef");function Sge(e,t){let a={type:"array",uniqueItems:!0,items:Ut(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(a.minItems=e.minSize.value),e.maxSize&&(a.maxItems=e.maxSize.value),a}s(Sge,"parseSetDef");function Ige(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((o,a)=>Ut(o._def,{...t,currentPath:[...t.currentPath,"items",`${a}`]})).reduce((o,a)=>a===void 0?o:[...o,a],[]),additionalItems:Ut(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((o,a)=>Ut(o._def,{...t,currentPath:[...t.currentPath,"items",`${a}`]})).reduce((o,a)=>a===void 0?o:[...o,a],[])}}s(Ige,"parseTupleDef");function kge(){return{not:Zo()}}s(kge,"parseUndefinedDef");function Pge(){return Zo()}s(Pge,"parseUnknownDef");var Ege=s((e,t)=>Ut(e.innerType._def,t),"parseReadonlyDef"),Age=s((e,t,o)=>{switch(t){case U.ZodString:return k6(e,o);case U.ZodNumber:return yge(e);case U.ZodObject:return _ge(e,o);case U.ZodBigInt:return Yhe(e);case U.ZodBoolean:return Qhe();case U.ZodDate:return I6(e,o);case U.ZodUndefined:return kge();case U.ZodNull:return mge();case U.ZodArray:return Xhe(e,o);case U.ZodUnion:case U.ZodDiscriminatedUnion:return fge(e,o);case U.ZodIntersection:return ige(e,o);case U.ZodTuple:return Ige(e,o);case U.ZodRecord:return P6(e,o);case U.ZodLiteral:return sge(e);case U.ZodEnum:return nge(e);case U.ZodNativeEnum:return dge(e);case U.ZodNullable:return gge(e,o);case U.ZodOptional:return xge(e,o);case U.ZodMap:return cge(e,o);case U.ZodSet:return Sge(e,o);case U.ZodLazy:return()=>e.getter()._def;case U.ZodPromise:return Tge(e,o);case U.ZodNaN:case U.ZodNever:return pge();case U.ZodEffects:return oge(e,o);case U.ZodAny:return Zo();case U.ZodUnknown:return Pge();case U.ZodDefault:return rge(e,o);case U.ZodBranded:return S6(e,o);case U.ZodReadonly:return Ege(e,o);case U.ZodCatch:return ege(e,o);case U.ZodPipeline:return wge(e,o);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(a=>{})(t)}},"selectParser"),Cge=s((e,t)=>{let o=0;for(;o<e.length&&o<t.length&&e[o]===t[o];o++);return[(e.length-o).toString(),...t.slice(o)].join("/")},"getRelativePath");function Ut(e,t,o=!1){var a;let n=t.seen.get(e);if(t.override){let c=(a=t.override)==null?void 0:a.call(t,e,t,n,o);if(c!==Ghe)return c}if(n&&!o){let c=Oge(n,t);if(c!==void 0)return c}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let l=Age(e,e.typeName,t),u=typeof l=="function"?Ut(l(),t):l;if(u&&$ge(e,t,u),t.postProcess){let c=t.postProcess(u,e,t);return i.jsonSchema=u,c}return i.jsonSchema=u,u}s(Ut,"parseDef");var Oge=s((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Cge(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((o,a)=>t.currentPath[a]===o)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Zo()):t.$refStrategy==="seen"?Zo():void 0}},"get$ref"),$ge=s((e,t,o)=>(e.description&&(o.description=e.description),o),"addMeta"),Rge=s(e=>{let t=Khe(e),o=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:o,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([a,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,a],jsonSchema:void 0}]))}},"getRefs"),zge=s((e,t)=>{var o;let a=Rge(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((d,[p,m])=>{var f;return{...d,[p]:(f=Ut(m._def,{...a,currentPath:[...a.basePath,a.definitionPath,p]},!0))!=null?f:Zo()}},{}):void 0,i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,l=(o=Ut(e._def,i===void 0?a:{...a,currentPath:[...a.basePath,a.definitionPath,i]},!1))!=null?o:Zo(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(l.title=u);let c=i===void 0?n?{...l,[a.definitionPath]:n}:l:{$ref:[...a.$refStrategy==="relative"?[]:a.basePath,a.definitionPath,i].join("/"),[a.definitionPath]:{...n,[i]:l}};return c.$schema="http://json-schema.org/draft-07/schema#",c},"zod3ToJsonSchema"),Uk=Symbol.for("vercel.ai.schema");function Ou(e,{validate:t}={}){return{[Uk]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}s(Ou,"jsonSchema");function Nge(e){return typeof e=="object"&&e!==null&&Uk in e&&e[Uk]===!0&&"jsonSchema"in e&&"validate"in e}s(Nge,"isSchema");function qk(e){return e==null?Ou({properties:{},additionalProperties:!1}):Nge(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?Lge(e):jge(e):e()}s(qk,"asSchema");function jge(e){return Ou(()=>Lk(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:s(async t=>{let o=await e["~standard"].validate(t);return"value"in o?{success:!0,value:o.value}:{success:!1,error:new Cu({value:t,cause:o.issues})}},"validate")})}s(jge,"standardSchema");function Mge(e,t){var o;let a=(o=t?.useReferences)!=null?o:!1;return Ou(()=>zge(e,{$refStrategy:a?"root":"none"}),{validate:s(async n=>{let i=await e.safeParseAsync(n);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}},"validate")})}s(Mge,"zod3Schema");function Dge(e,t){var o;let a=(o=t?.useReferences)!=null?o:!1;return Ou(()=>Lk(zo(e,{target:"draft-7",io:"input",reused:a?"ref":"inline"})),{validate:s(async n=>{let i=await wn(e,n);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}},"validate")})}s(Dge,"zod4Schema");function Uge(e){return"_zod"in e}s(Uge,"isZod4Schema");function Lge(e,t){return Uge(e)?Dge(e,t):Mge(e,t)}s(Lge,"zodSchema");async function Fk({value:e,schema:t}){let o=qk(t);try{if(o.validate==null)return{success:!0,value:e,rawValue:e};let a=await o.validate(e);return a.success?{success:!0,value:a.value,rawValue:e}:{success:!1,error:Cu.wrap({value:e,cause:a.error}),rawValue:e}}catch(a){return{success:!1,error:Cu.wrap({value:e,cause:a}),rawValue:e}}}s(Fk,"safeValidateTypes");async function E6({text:e,schema:t}){try{let o=Whe(e);return t==null?{success:!0,value:o,rawValue:o}:await Fk({value:o,schema:t})}catch(o){return{success:!1,error:Nk.isInstance(o)?o:new Nk({text:e,cause:o}),rawValue:void 0}}}s(E6,"safeParseJSON");function A6(e){return{...e,type:"dynamic"}}s(A6,"dynamicTool");var qge="AI_MCPClientError",j6=`vercel.ai.error.${qge}`,Fge=Symbol.for(j6),C6,O6,Et=class extends(O6=wt,C6=Fge,O6){static{s(this,"MCPClientError")}constructor({name:e="MCPClientError",message:t,cause:o,data:a,code:n}){super({name:e,message:t,cause:o}),this[C6]=!0,this.data=a,this.code=n}static isInstance(e){return wt.hasMarker(e,j6)}},Ru="2025-06-18",Bge=[Ru,"2025-03-26","2024-11-05"],Vge=r.optional(r.record(r.string(),r.unknown())),Zge=r.looseObject({name:r.string(),version:r.string()}),j_=r.looseObject({_meta:r.optional(r.object({}).loose())}),Va=j_,M6=r.object({method:r.string(),params:r.optional(j_)}),D6=r.object({applyDefaults:r.optional(r.boolean())}).loose(),Hge=r.looseObject({experimental:r.optional(r.object({}).loose()),logging:r.optional(r.object({}).loose()),prompts:r.optional(r.looseObject({listChanged:r.optional(r.boolean())})),resources:r.optional(r.looseObject({subscribe:r.optional(r.boolean()),listChanged:r.optional(r.boolean())})),tools:r.optional(r.looseObject({listChanged:r.optional(r.boolean())})),elicitation:r.optional(D6)}),DZe=r.object({elicitation:r.optional(D6)}).loose(),Jge=Va.extend({protocolVersion:r.string(),capabilities:Hge,serverInfo:Zge,instructions:r.optional(r.string())}),Vk=Va.extend({nextCursor:r.optional(r.string())}),Wge=r.object({name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),inputSchema:r.object({type:r.literal("object"),properties:r.optional(r.object({}).loose())}).loose(),outputSchema:r.optional(r.object({}).loose()),annotations:r.optional(r.object({title:r.optional(r.string())}).loose()),_meta:Vge}).loose(),Gge=Vk.extend({tools:r.array(Wge)}),U6=r.object({type:r.literal("text"),text:r.string()}).loose(),L6=r.object({type:r.literal("image"),data:r.base64(),mimeType:r.string()}).loose(),Kge=r.object({uri:r.string(),name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),mimeType:r.optional(r.string()),size:r.optional(r.number())}).loose(),Xge=Vk.extend({resources:r.array(Kge)}),q6=r.object({uri:r.string(),name:r.optional(r.string()),title:r.optional(r.string()),mimeType:r.optional(r.string())}).loose(),F6=q6.extend({text:r.string()}),B6=q6.extend({blob:r.base64()}),V6=r.object({type:r.literal("resource"),resource:r.union([F6,B6])}).loose(),Yge=Va.extend({content:r.array(r.union([U6,L6,V6])),structuredContent:r.optional(r.unknown()),isError:r.boolean().default(!1).optional()}).or(Va.extend({toolResult:r.unknown()})),Qge=r.object({uriTemplate:r.string(),name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),mimeType:r.optional(r.string())}).loose(),eye=Va.extend({resourceTemplates:r.array(Qge)}),tye=Va.extend({contents:r.array(r.union([F6,B6]))}),rye=r.object({name:r.string(),description:r.optional(r.string()),required:r.optional(r.boolean())}).loose(),oye=r.object({name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),arguments:r.optional(r.array(rye))}).loose(),nye=Vk.extend({prompts:r.array(oye)}),aye=r.object({role:r.union([r.literal("user"),r.literal("assistant")]),content:r.union([U6,L6,V6])}).loose(),iye=Va.extend({description:r.optional(r.string()),messages:r.array(aye)}),sye=j_.extend({message:r.string(),requestedSchema:r.unknown()}),$6=M6.extend({method:r.literal("elicitation/create"),params:sye}),lye=Va.extend({action:r.union([r.literal("accept"),r.literal("decline"),r.literal("cancel")]),content:r.optional(r.record(r.string(),r.unknown()))}),M_="2.0",uye=r.object({jsonrpc:r.literal(M_),id:r.union([r.string(),r.number().int()])}).merge(M6).strict(),cye=r.object({jsonrpc:r.literal(M_),id:r.union([r.string(),r.number().int()]),result:Va}).strict(),dye=r.object({jsonrpc:r.literal(M_),id:r.union([r.string(),r.number().int()]),error:r.object({code:r.number().int(),message:r.string(),data:r.optional(r.unknown())})}).strict(),pye=r.object({jsonrpc:r.literal(M_)}).merge(r.object({method:r.string(),params:r.optional(j_)})).strict(),km=r.union([uye,pye,cye,dye]),Z6=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",H6=r.object({access_token:r.string(),id_token:r.string().optional(),token_type:r.string(),expires_in:r.number().optional(),scope:r.string().optional(),refresh_token:r.string().optional()}).strip(),Co=r.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:r.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),r.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),mye=r.object({resource:r.string().url(),authorization_servers:r.array(Co).optional(),jwks_uri:r.string().url().optional(),scopes_supported:r.array(r.string()).optional(),bearer_methods_supported:r.array(r.string()).optional(),resource_signing_alg_values_supported:r.array(r.string()).optional(),resource_name:r.string().optional(),resource_documentation:r.string().optional(),resource_policy_uri:r.string().url().optional(),resource_tos_uri:r.string().url().optional(),tls_client_certificate_bound_access_tokens:r.boolean().optional(),authorization_details_types_supported:r.array(r.string()).optional(),dpop_signing_alg_values_supported:r.array(r.string()).optional(),dpop_bound_access_tokens_required:r.boolean().optional()}).passthrough(),J6=r.object({issuer:r.string(),authorization_endpoint:Co,token_endpoint:Co,registration_endpoint:Co.optional(),scopes_supported:r.array(r.string()).optional(),response_types_supported:r.array(r.string()),grant_types_supported:r.array(r.string()).optional(),code_challenge_methods_supported:r.array(r.string()),token_endpoint_auth_methods_supported:r.array(r.string()).optional(),token_endpoint_auth_signing_alg_values_supported:r.array(r.string()).optional()}).passthrough(),fye=r.object({issuer:r.string(),authorization_endpoint:Co,token_endpoint:Co,userinfo_endpoint:Co.optional(),jwks_uri:Co,registration_endpoint:Co.optional(),scopes_supported:r.array(r.string()).optional(),response_types_supported:r.array(r.string()),grant_types_supported:r.array(r.string()).optional(),subject_types_supported:r.array(r.string()),id_token_signing_alg_values_supported:r.array(r.string()),claims_supported:r.array(r.string()).optional(),token_endpoint_auth_methods_supported:r.array(r.string()).optional()}).passthrough(),hye=fye.merge(J6.pick({code_challenge_methods_supported:!0})),gye=r.object({client_id:r.string(),client_secret:r.string().optional(),client_id_issued_at:r.number().optional(),client_secret_expires_at:r.number().optional()}).strip(),yye=r.object({redirect_uris:r.array(Co),token_endpoint_auth_method:r.string().optional(),grant_types:r.array(r.string()).optional(),response_types:r.array(r.string()).optional(),client_name:r.string().optional(),client_uri:Co.optional(),logo_uri:Co.optional(),scope:r.string().optional(),contacts:r.array(r.string()).optional(),tos_uri:Co.optional(),policy_uri:r.string().optional(),jwks_uri:Co.optional(),jwks:r.any().optional(),software_id:r.string().optional(),software_version:r.string().optional(),software_statement:r.string().optional()}).strip(),_ye=r.object({error:r.string(),error_description:r.string().optional(),error_uri:r.string().optional()}),vye=yye.merge(gye),bye="AI_MCPClientOAuthError",W6=`vercel.ai.error.${bye}`,xye=Symbol.for(W6),R6,z6,Pm=class extends(z6=wt,R6=xye,z6){static{s(this,"MCPClientOAuthError")}constructor({name:e="MCPClientOAuthError",message:t,cause:o}){super({name:e,message:t,cause:o}),this[R6]=!0}static isInstance(e){return wt.hasMarker(e,W6)}},$u=class extends Pm{static{s(this,"ServerError")}};$u.errorCode="server_error";var C_=class extends Pm{static{s(this,"InvalidClientError")}};C_.errorCode="invalid_client";var O_=class extends Pm{static{s(this,"InvalidGrantError")}};O_.errorCode="invalid_grant";var $_=class extends Pm{static{s(this,"UnauthorizedClientError")}};$_.errorCode="unauthorized_client";var wye={[$u.errorCode]:$u,[C_.errorCode]:C_,[O_.errorCode]:O_,[$_.errorCode]:$_};function Tye(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}s(Tye,"resourceUrlFromServerUrl");function Sye({requestedResource:e,configuredResource:t}){let o=typeof e=="string"?new URL(e):new URL(e.href),a=typeof t=="string"?new URL(t):new URL(t.href);if(o.origin!==a.origin||o.pathname.length<a.pathname.length)return!1;let n=o.pathname.endsWith("/")?o.pathname:o.pathname+"/",i=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return n.startsWith(i)}s(Sye,"checkResourceAllowed");var R_=class extends Error{static{s(this,"UnauthorizedError")}constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function z_(e){var t;let o=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!o)return;let[a,n]=o.split(" ");if(a.toLowerCase()!=="bearer"||!n)return;let i=/resource_metadata="([^"]*)"/,l=o.match(i);if(l)try{return new URL(l[1])}catch{return}}s(z_,"extractResourceMetadataUrl");function Iye(e,t="",o={}){return t.endsWith("/")&&(t=t.slice(0,-1)),o.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}s(Iye,"buildWellKnownPath");async function Zk(e,t,o=fetch){try{return await o(e,{headers:t})}catch(a){if(a instanceof TypeError)return t?Zk(e,void 0,o):void 0;throw a}}s(Zk,"fetchWithCorsRetry");async function N6(e,t,o=fetch){return await Zk(e,{"MCP-Protocol-Version":t},o)}s(N6,"tryMetadataDiscovery");function kye(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}s(kye,"shouldAttemptFallback");async function Pye(e,t,o,a){var n,i;let l=new URL(e),u=(n=a?.protocolVersion)!=null?n:Ru,c;if(a?.metadataUrl)c=new URL(a.metadataUrl);else{let p=Iye(t,l.pathname);c=new URL(p,(i=a?.metadataServerUrl)!=null?i:l),c.search=l.search}let d=await N6(c,u,o);if(!a?.metadataUrl&&kye(d,l.pathname)){let p=new URL(`/.well-known/${t}`,l);d=await N6(p,u,o)}return d}s(Pye,"discoverMetadataWithFallback");async function Eye(e,t,o=fetch){let a=await Pye(e,"oauth-protected-resource",o,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!a||a.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return mye.parse(await a.json())}s(Eye,"discoverOAuthProtectedResourceMetadata");function Aye(e){let t=typeof e=="string"?new URL(e):e,o=t.pathname!=="/",a=[];if(!o)return a.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),a;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),a.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),a}s(Aye,"buildDiscoveryUrls");async function Cye(e,{fetchFn:t=fetch,protocolVersion:o=Ru}={}){var a;let n={"MCP-Protocol-Version":o},i=Aye(e);for(let{url:l,type:u}of i){let c=await Zk(l,n,t);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${u==="oauth"?"OAuth":"OpenID provider"} metadata from ${l}`)}if(u==="oauth")return J6.parse(await c.json());{let d=hye.parse(await c.json());if(!((a=d.code_challenge_methods_supported)!=null&&a.includes("S256")))throw new Error(`Incompatible OIDC provider at ${l}: does not support S256 code challenge method required by MCP specification`);return d}}}}s(Cye,"discoverAuthorizationServerMetadata");async function Oye(e,{metadata:t,clientInformation:o,redirectUrl:a,scope:n,state:i,resource:l}){let u="code",c="S256",d;if(t){if(d=new URL(t.authorization_endpoint),!t.response_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support response type ${u}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else d=new URL("/authorize",e);let p=await pm(),m=p.code_verifier,f=p.code_challenge;return d.searchParams.set("response_type",u),d.searchParams.set("client_id",o.client_id),d.searchParams.set("code_challenge",f),d.searchParams.set("code_challenge_method",c),d.searchParams.set("redirect_uri",String(a)),i&&d.searchParams.set("state",i),n&&d.searchParams.set("scope",n),n?.includes("offline_access")&&d.searchParams.append("prompt","consent"),l&&d.searchParams.set("resource",l.href),{authorizationUrl:d,codeVerifier:m}}s(Oye,"startAuthorization");function G6(e,t){let o=e.client_secret!==void 0;return t.length===0?o?"client_secret_post":"none":o&&t.includes("client_secret_basic")?"client_secret_basic":o&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":o?"client_secret_post":"none"}s(G6,"selectClientAuthMethod");function K6(e,t,o,a){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":$ye(n,i,o);return;case"client_secret_post":Rye(n,i,a);return;case"none":zye(n,a);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}s(K6,"applyClientAuthentication");function $ye(e,t,o){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let a=btoa(`${e}:${t}`);o.set("Authorization",`Basic ${a}`)}s($ye,"applyBasicAuth");function Rye(e,t,o){o.set("client_id",e),t&&o.set("client_secret",t)}s(Rye,"applyPostAuth");function zye(e,t){t.set("client_id",e)}s(zye,"applyPublicAuth");async function Hk(e){let t=e instanceof Response?e.status:void 0,o=e instanceof Response?await e.text():e;try{let a=_ye.parse(JSON.parse(o)),{error:n,error_description:i,error_uri:l}=a,u=wye[n]||$u;return new u({message:i||"",cause:l})}catch(a){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${a}. Raw body: ${o}`;return new $u({message:n})}}s(Hk,"parseErrorResponse");async function Nye(e,{metadata:t,clientInformation:o,authorizationCode:a,codeVerifier:n,redirectUri:i,resource:l,addClientAuthentication:u,fetchFn:c}){var d;let p="authorization_code",m=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(p))throw new Error(`Incompatible auth server: does not support grant type ${p}`);let f=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:p,code:a,code_verifier:n,redirect_uri:String(i)});if(u)u(f,h,e,t);else{let y=(d=t?.token_endpoint_auth_methods_supported)!=null?d:[],_=G6(o,y);K6(_,o,f,h)}l&&h.set("resource",l.href);let g=await(c??fetch)(m,{method:"POST",headers:f,body:h});if(!g.ok)throw await Hk(g);return H6.parse(await g.json())}s(Nye,"exchangeAuthorization");async function jye(e,{metadata:t,clientInformation:o,refreshToken:a,resource:n,addClientAuthentication:i,fetchFn:l}){var u;let c="refresh_token",d;if(t){if(d=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else d=new URL("/token",e);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),m=new URLSearchParams({grant_type:c,refresh_token:a});if(i)i(p,m,e,t);else{let h=(u=t?.token_endpoint_auth_methods_supported)!=null?u:[],g=G6(o,h);K6(g,o,p,m)}n&&m.set("resource",n.href);let f=await(l??fetch)(d,{method:"POST",headers:p,body:m});if(!f.ok)throw await Hk(f);return H6.parse({refresh_token:a,...await f.json()})}s(jye,"refreshAuthorization");async function Mye(e,{metadata:t,clientMetadata:o,fetchFn:a}){let n;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);let i=await(a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw await Hk(i);return vye.parse(await i.json())}s(Mye,"registerClient");async function N_(e,t){var o,a;try{return await Bk(e,t)}catch(n){if(n instanceof C_||n instanceof $_)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"all")),await Bk(e,t);if(n instanceof O_)return await((a=e.invalidateCredentials)==null?void 0:a.call(e,"tokens")),await Bk(e,t);throw n}}s(N_,"auth");async function Dye(e,t,o){let a=Tye(e);if(t.validateResourceURL)return await t.validateResourceURL(a,o?.resource);if(o){if(!Sye({requestedResource:a,configuredResource:o.resource}))throw new Error(`Protected resource ${o.resource} does not match expected ${a} (or origin)`);return new URL(o.resource)}}s(Dye,"selectResourceURL");async function Bk(e,{serverUrl:t,authorizationCode:o,scope:a,resourceMetadataUrl:n,fetchFn:i}){let l,u;try{l=await Eye(t,{resourceMetadataUrl:n},i),l.authorization_servers&&l.authorization_servers.length>0&&(u=l.authorization_servers[0])}catch{}u||(u=t);let c=await Dye(t,e,l),d=await Cye(u,{fetchFn:i}),p=await Promise.resolve(e.clientInformation());if(!p){if(o!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let y=await Mye(u,{metadata:d,clientMetadata:e.clientMetadata,fetchFn:i});await e.saveClientInformation(y),p=y}if(o!==void 0){let y=await e.codeVerifier(),_=await Nye(u,{metadata:d,clientInformation:p,authorizationCode:o,codeVerifier:y,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(_),"AUTHORIZED"}let m=await e.tokens();if(m?.refresh_token)try{let y=await jye(u,{metadata:d,clientInformation:p,refreshToken:m.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof Pm)||y instanceof $u))throw y}let f=e.state?await e.state():void 0,{authorizationUrl:h,codeVerifier:g}=await Oye(u,{metadata:d,clientInformation:p,state:f,redirectUrl:e.redirectUrl,scope:a||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(h),"REDIRECT"}s(Bk,"authInternal");var Uye=class{static{s(this,"SseMCPTransport")}constructor({url:e,headers:t,authProvider:o}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=o}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":Ru};if(this.authProvider){let o=await this.authProvider.tokens();o?.access_token&&(t.Authorization=`Bearer ${o.access_token}`)}return A_(t,`ai-sdk/${Z6}`,E_())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let o=s(async(a=!1)=>{var n,i,l,u,c;try{let d=await this.commonHeaders({Accept:"text/event-stream"}),p=await fetch(this.url.href,{headers:d,signal:(n=this.abortController)==null?void 0:n.signal});if(p.status===401&&this.authProvider&&!a){this.resourceMetadataUrl=z_(p);try{if(await N_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let y=new R_;return(i=this.onerror)==null||i.call(this,y),t(y)}}catch(g){return(l=this.onerror)==null||l.call(this,g),t(g)}return o(!0)}if(!p.ok||!p.body){let g=`MCP SSE Transport Error: ${p.status} ${p.statusText}`;p.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");let y=new Et({message:g});return(u=this.onerror)==null||u.call(this,y),t(y)}let f=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new en).getReader(),h=s(async()=>{var g,y,_;try{for(;;){let{done:v,value:x}=await f.read();if(v){if(this.connected)throw this.connected=!1,new Et({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}let{event:w,data:S}=x;if(w==="endpoint"){if(this.endpoint=new URL(S,this.url),this.endpoint.origin!==this.url.origin)throw new Et({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(w==="message")try{let P=km.parse(JSON.parse(S));(g=this.onmessage)==null||g.call(this,P)}catch(P){let k=new Et({message:"MCP SSE Transport Error: Failed to parse message",cause:P});(y=this.onerror)==null||y.call(this,k)}}}catch(v){if(v instanceof Error&&v.name==="AbortError")return;(_=this.onerror)==null||_.call(this,v),t(v)}},"processEvents");this.sseConnection={close:s(()=>f.cancel(),"close")},h()}catch(d){if(d instanceof Error&&d.name==="AbortError")return;(c=this.onerror)==null||c.call(this,d),t(d)}},"establishConnection");o()})}async close(){var e,t,o;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(o=this.onclose)==null||o.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new Et({message:"MCP SSE Transport Error: Not connected"});let t=this.endpoint,o=s(async(a=!1)=>{var n,i,l,u,c;try{let p={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},m=await fetch(t,p);if(m.status===401&&this.authProvider&&!a){this.resourceMetadataUrl=z_(m);try{if(await N_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let h=new R_;(i=this.onerror)==null||i.call(this,h);return}}catch(f){(l=this.onerror)==null||l.call(this,f);return}return o(!0)}if(!m.ok){let f=await m.text().catch(()=>null),h=new Et({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${m.status}): ${f}`});(u=this.onerror)==null||u.call(this,h);return}}catch(d){(c=this.onerror)==null||c.call(this,d);return}},"attempt");await o()}},Lye=class{static{s(this,"HttpMCPTransport")}constructor({url:e,headers:t,authProvider:o}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=o}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":Ru};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){let o=await this.authProvider.tokens();o?.access_token&&(t.Authorization=`Bearer ${o.access_token}`)}return A_(t,`ai-sdk/${Z6}`,E_())}async start(){if(this.abortController)throw new Et({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,o;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let a=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:a,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(o=this.onclose)==null||o.call(this)}async send(e){let t=s(async(o=!1)=>{var a,n,i,l,u,c,d;try{let m={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(a=this.abortController)==null?void 0:a.signal},f=await fetch(this.url,m),h=f.headers.get("mcp-session-id");if(h&&(this.sessionId=h),f.status===401&&this.authProvider&&!o){this.resourceMetadataUrl=z_(f);try{if(await N_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new R_}catch(v){throw(n=this.onerror)==null||n.call(this,v),v}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){let v=await f.text().catch(()=>null),x=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${v}`;f.status===404&&(x+=". This server does not support HTTP transport. Try using `sse` transport instead");let w=new Et({message:x});throw(i=this.onerror)==null||i.call(this,w),w}if(!("id"in e))return;let y=f.headers.get("content-type")||"";if(y.includes("application/json")){let v=await f.json(),x=Array.isArray(v)?v.map(w=>km.parse(w)):[km.parse(v)];for(let w of x)(l=this.onmessage)==null||l.call(this,w);return}if(y.includes("text/event-stream")){if(!f.body){let S=new Et({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(u=this.onerror)==null||u.call(this,S),S}let x=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new en).getReader();s(async()=>{var S,P,k;try{for(;;){let{done:I,value:E}=await x.read();if(I)return;let{event:b,data:M}=E;if(b==="message")try{let R=km.parse(JSON.parse(M));(S=this.onmessage)==null||S.call(this,R)}catch(R){let D=new Et({message:"MCP HTTP Transport Error: Failed to parse message",cause:R});(P=this.onerror)==null||P.call(this,D)}}}catch(I){if(I instanceof Error&&I.name==="AbortError")return;(k=this.onerror)==null||k.call(this,I)}},"processEvents")();return}let _=new Et({message:`MCP HTTP Transport Error: Unexpected content type: ${y}`});throw(c=this.onerror)==null||c.call(this,_),_}catch(p){throw(d=this.onerror)==null||d.call(this,p),p}},"attempt");await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:o,maxReconnectionDelay:a}=this.reconnectionOptions;return Math.min(t*Math.pow(o,e),a)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new Et({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let o=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var a;(a=this.abortController)!=null&&a.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},o)}async openInboundSse(e=!1,t){var o,a,n,i,l,u;try{let c=await this.commonHeaders({Accept:"text/event-stream"});t&&(c["last-event-id"]=t);let d=await fetch(this.url.href,{method:"GET",headers:c,signal:(o=this.abortController)==null?void 0:o.signal}),p=d.headers.get("mcp-session-id");if(p&&(this.sessionId=p),d.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=z_(d);try{if(await N_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let y=new R_;(a=this.onerror)==null||a.call(this,y);return}}catch(g){(n=this.onerror)==null||n.call(this,g);return}return this.openInboundSse(!0,t)}if(d.status===405)return;if(!d.ok||!d.body){let g=new Et({message:`MCP HTTP Transport Error: GET SSE failed: ${d.status} ${d.statusText}`});(i=this.onerror)==null||i.call(this,g);return}let f=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new en).getReader(),h=s(async()=>{var g,y,_,v;try{for(;;){let{done:x,value:w}=await f.read();if(x)return;let{event:S,data:P,id:k}=w;if(k&&(this.lastInboundEventId=k),S==="message")try{let I=km.parse(JSON.parse(P));(g=this.onmessage)==null||g.call(this,I)}catch(I){let E=new Et({message:"MCP HTTP Transport Error: Failed to parse message",cause:I});(y=this.onerror)==null||y.call(this,E)}}}catch(x){if(x instanceof Error&&x.name==="AbortError")return;(_=this.onerror)==null||_.call(this,x),(v=this.abortController)!=null&&v.signal.aborted||this.scheduleInboundSseReconnection()}},"processEvents");this.inboundSseConnection={close:s(()=>f.cancel(),"close")},this.inboundReconnectAttempts=0,h()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),(u=this.abortController)!=null&&u.signal.aborted||this.scheduleInboundSseReconnection()}}};function qye(e){switch(e.type){case"sse":return new Uye(e);case"http":return new Lye(e);default:throw new Et({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}s(qye,"createMcpTransport");function Fye(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}s(Fye,"isCustomMcpTransport");var Bye="1.0.0";async function X6(e){let t=new Vye(e);return await t.init(),t}s(X6,"createMCPClient");var Vye=class{static{s(this,"DefaultMCPClient")}constructor({transport:e,name:t="ai-sdk-mcp-client",version:o=Bye,onUncaughtError:a,capabilities:n}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=a,this.clientCapabilities=n??{},Fye(e)?this.transport=e:this.transport=qye(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=i=>this.onError(i),this.transport.onmessage=i=>{if("method"in i){"id"in i?this.onRequestMessage(i):this.onError(new Et({message:"Unsupported message type"}));return}this.onResponse(i)},this.clientInfo={name:t,version:o}}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:"initialize",params:{protocolVersion:Ru,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Jge});if(e===void 0)throw new Et({message:"Server sent invalid initialize result"});if(!Bge.includes(e.protocolVersion))throw new Et({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new Et({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Et({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Et({message:"Server does not support prompts"});break;default:throw new Et({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:o}){return new Promise((a,n)=>{if(this.isClosed)return n(new Et({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);let i=o?.signal;i?.throwIfAborted();let l=this.requestMessageId++,u={...e,jsonrpc:"2.0",id:l},c=s(()=>{this.responseHandlers.delete(l)},"cleanup");this.responseHandlers.set(l,d=>{if(i?.aborted)return n(new Et({message:"Request was aborted",cause:i.reason}));if(d instanceof Error)return n(d);try{let p=t.parse(d.result);a(p)}catch(p){let m=new Et({message:"Failed to parse server response",cause:p});n(m)}}),this.transport.send(u).catch(d=>{c(),n(d)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:Gge,options:t})}catch(o){throw o}}async callTool({name:e,args:t,options:o}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:Yge,options:{signal:o?.abortSignal}})}catch(a){throw a}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:Xge,options:t})}catch(o){throw o}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:tye,options:t})}catch(o){throw o}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:eye,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:nye,options:t})}catch(o){throw o}}async getPromptInternal({name:e,args:t,options:o}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:iye,options:o})}catch(a){throw a}}async notification(e){let t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t,o;let a={};try{let n=await this.listTools();for(let{name:i,title:l,description:u,inputSchema:c,annotations:d,_meta:p}of n.tools){let m=l??d?.title;if(e!=="automatic"&&!(i in e))continue;let f=this,h=e!=="automatic"?(t=e[i])==null?void 0:t.outputSchema:void 0,g=s(async(_,v)=>{var x;(x=v?.abortSignal)==null||x.throwIfAborted();let w=await f.callTool({name:i,args:_,options:v});return h!=null?f.extractStructuredContent(w,h,i):w},"execute"),y=e==="automatic"?A6({description:u,title:m,inputSchema:Ou({...c,properties:(o=c.properties)!=null?o:{},additionalProperties:!1}),execute:g}):{description:u,title:m,inputSchema:e[i].inputSchema,...h!=null?{outputSchema:h}:{},execute:g};a[i]={...y,_meta:p}}return a}catch(n){throw n}}async extractStructuredContent(e,t,o){if("structuredContent"in e&&e.structuredContent!=null){let a=await Fk({value:e.structuredContent,schema:qk(t)});if(!a.success)throw new Et({message:`Tool "${o}" returned structuredContent that does not match the expected outputSchema`,cause:a.error});return a.value}if("content"in e&&Array.isArray(e.content)){let a=e.content.find(n=>n.type==="text");if(a&&"text"in a){let n=await E6({text:a.text,schema:t});if(!n.success)throw new Et({message:`Tool "${o}" returned content that does not match the expected outputSchema`,cause:n.error});return n.value}}throw new Et({message:`Tool "${o}" 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:o}){return this.getPromptInternal({name:e,args:t,options:o})}onElicitationRequest(e,t){if(e!==$6)throw new Et({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}let t=$6.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 o=await this.elicitationRequestHandler(t.data),a=lye.parse(o);await this.transport.send({jsonrpc:"2.0",id:e.id,result:a})}catch(o){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:o instanceof Error?o.message:"Failed to handle elicitation request"}}),this.onError(o)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new Et({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),o=this.responseHandlers.get(t);if(o===void 0)throw new Et({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),o("result"in e?e:new Et({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function Zye(e,t,o={}){let a=new URL(t);switch(e){case"http":return{type:"http",url:t,headers:o};case"streamable-http":return new P_(a,{requestInit:{headers:o}});case"sse":return{type:"sse",url:t,headers:o};default:throw new Error(`Unsupported MCP protocol type: ${e}`)}}s(Zye,"createTransportConfig");var Y6="search_knowledge_base";function Hye(e,t){let o=[],a={},n={};for(let i of e){o.push(i.mcpClient);let l=t.find(u=>u.toolName===i.mcpName);for(let[u,c]of Object.entries(i.tools)){let d=ns.createToolName(`${u}`);a[d]=c,l&&(n[d]=l)}}return{mcpClients:o,tools:a,keyToAgentTool:n}}s(Hye,"flattenMcpServers");async function Jye(e){let t=[];for(let o of e)try{let a=await X6({transport:Zye(o.protocol,o.serverUrl,zx(o.auth))}),n=await a.tools();t.push({mcpName:o.toolName,mcpClient:a,tools:n})}catch(a){console.error(`Failed to connect to MCP server ${o.serverUrl}:`,a)}return t}s(Jye,"constructMcpServersTools");function Wye(e){return{get(t,o){return ia.sendRequest({method:"GET",url:`${e.server.apiUrl}${t}`,...o?{queryParams:o}:{},authentication:{type:"BEARER_TOKEN",token:e.server.token}})},post(t,o){return ia.sendRequest({method:"POST",url:`${e.server.apiUrl}${t}`,authentication:{type:"BEARER_TOKEN",token:e.server.token},body:o})}}}s(Wye,"createServerApiClient");async function Gye(e,t,o){let a={},n={},i=Wye(t),l=e.filter(d=>d.sourceType==="FILE"),u=e.filter(d=>d.sourceType==="TABLE");if(l.length>0&&o){let d=l.map(m=>m.sourceId),p=l.map(m=>m.sourceName).join(", ");for(let m of l)try{let h=(await i.get(`v1/knowledge-base/files/${m.sourceId}/chunks?embedded=false`)).body;if(h.length>0)for(let y=0;y<h.length;y+=50){let _=h.slice(y,y+50),{embeddings:v}=await pN({model:o.model,values:_.map(x=>x.content),providerOptions:o.providerOptions});await i.post(`v1/knowledge-base/files/${m.sourceId}/store-chunks`,{chunks:_.map((x,w)=>({id:x.id,embedding:Array.from(v[w])}))})}}catch(f){console.error(`Failed to embed KB file '${m.sourceName}':`,f)}a[Y6]=ep({description:`Search uploaded documents for relevant information. Available documents: ${p}. Use when you need facts, policies, or content from these knowledge base files.`,inputSchema:wo.object({query:wo.string().describe("Search query to find relevant information")}),execute:s(async m=>{let{query:f}=m,{embedding:h}=await dN({model:o.model,value:f,providerOptions:o.providerOptions}),y=(await i.post("v1/knowledge-base/files/search",{knowledgeBaseFileIds:d,queryEmbedding:Array.from(h),limit:5,similarityThreshold:.5})).body;return!y||y.length===0?{results:"No relevant information found."}:{results:y.map((_,v)=>({rank:v+1,content:_.content,source:_.metadata?.fileName??"unknown",relevanceScore:_.score}))}},"execute")}),n[Y6]=l[0]}let c=await Promise.all(u.map(async d=>{let p=ns.createToolName(`query_table_${d.toolName}`),m,f=[],h="";try{let y=await i.get(`v1/tables/${encodeURIComponent(d.sourceId)}`);y.body.id&&(m=y.body.id,f=(await i.get(`v1/fields?tableId=${m}`)).body,h=f.map(v=>`${v.name} (${v.type})`).join(", "))}catch(y){console.error(`Failed to fetch table metadata for '${d.sourceName}':`,y)}let g=ep({description:`Query the '${d.sourceName}' data table.${h?` Columns: ${h}.`:""} Use to look up records or find specific entries.`,inputSchema:wo.object({filters:wo.array(wo.object({fieldName:wo.string().describe("The name of the field to filter on"),operator:wo.enum(["eq","neq","gt","gte","lt","lte","co","exists","not_exists"]).describe("Filter operator"),value:wo.string().optional().describe("The value to filter by")})).optional().describe("Optional filters to narrow results"),limit:wo.number().optional().default(10).describe("Maximum number of records to return")}),execute:s(async y=>{let{filters:_,limit:v}=y;if(!m)return{error:`Table '${d.sourceName}' not found`};let x;if(_&&_.length>0){let k=new Map(f.map(I=>[I.name.toLowerCase(),I.id]));x=_.flatMap(I=>{let E=k.get(I.fieldName.toLowerCase());return E?[{fieldId:E,operator:I.operator,value:I.value}]:[]})}let w={tableId:m,limit:String(v??10),...Kye("filters",x??[])},P=(await i.get("v1/records",w)).body.data;return{records:P,count:P.length}},"execute")});return{toolName:p,tool:g,agentTool:d}}));for(let{toolName:d,tool:p,agentTool:m}of c)a[d]=p,n[d]=m;return{tools:a,keyToAgentTool:n}}s(Gye,"constructKnowledgeBaseTools");async function Q6(e){let{outputBuilder:t,structuredOutput:o,agentTools:a,context:n,model:i,embeddingConfig:l}=e,u=await n.agent.tools({tools:a.filter(S=>S.type==="PIECE"),model:i}),c=await zs.constructFlowsTools({tools:a.filter(S=>S.type==="FLOW"),fetchFlows:n.flows.list,publicUrl:n.server.publicUrl,token:n.server.token}),d=a.filter(S=>S.type==="MCP"),p=await Jye(d),{mcpClients:m,tools:f,keyToAgentTool:h}=Hye(p,d),g=a.filter(S=>S.type==="KNOWLEDGE_BASE"),{tools:y,keyToAgentTool:_}=await Gye(g,n,l),v={...u,...c,...f,...y},x={};for(let S of a.filter(P=>P.type!=="MCP"&&P.type!=="KNOWLEDGE_BASE")){let P=S.type==="FLOW"?ns.createToolName(S.toolName):S.toolName;x[P]=S}Object.assign(x,h),Object.assign(x,_);let w={[Ia]:ep({description:"This tool must be called as your FINAL ACTION to indicate whether the assigned goal was accomplished. Call it only when you have completed the user's task, or if you are unable to continue. Once you call this tool, you should not take any further actions.",inputSchema:wo.object({success:wo.boolean().describe("Set to true if the assigned goal was achieved, or false if the task was abandoned or failed."),...Kt(o)?{output:wo.string().describe("Your complete response to the user. Always populate this with the full answer, result, or explanation \u2014 even if you already wrote text above. This is the final message that will be shown to the user.")}:{output:wo.object(zs.structuredOutputSchema(o)?.shape??{}).nullable().describe("The structured output of your task. This is optional and can be omitted if you have not achieved the goal.")}}),execute:s(async S=>{let{success:P,output:k}=S;return t.setStatus(P?"COMPLETED":"FAILED"),!Kt(o)&&!Kt(k)&&!bd(k)?t.setStructuredOutput(k):Kt(o)&&!Kt(k)&&!t.hasTextContent()&&t.addMarkdown(k),{}},"execute")})};return{mcpClients:m,toolKeyToAgentTool:x,tools:{...v,...w}}}s(Q6,"constructAgentTools");function Kye(e,t){let o={};return t.forEach((a,n)=>{for(let[i,l]of Object.entries(a))l!==void 0&&(o[`${e}[${n}][${i}]`]=l)}),o}s(Kye,"serializeArrayQuery");var Xye={type:Te.ShortText({displayName:"Tool Type",required:!0}),toolName:Te.ShortText({displayName:"Tool Name",required:!0}),pieceMetadata:Te.Json({displayName:"Piece Metadata",required:!1}),externalFlowId:Te.ShortText({displayName:"Flow External ID",required:!1}),serverUrl:Te.ShortText({displayName:"MCP Server URL",required:!1}),protocol:Te.ShortText({displayName:"Protocol",required:!1}),auth:Te.Json({displayName:"Auth Configuration",required:!1}),sourceType:Te.ShortText({displayName:"Source Type",required:!1}),sourceId:Te.ShortText({displayName:"Source ID",required:!1}),sourceName:Te.ShortText({displayName:"Source Name",required:!1})},eB=Xo({audience:"human",name:"run_agent",displayName:"Run Agent",description:"Handles complex, multi-step tasks by reasoning through problems, using tools accurately, and iterating until the job is done.",auth:_o.None(),props:{prompt:Te.LongText({displayName:"Prompt",description:"Describe what you want the assistant to do.",required:!0}),aiProviderModel:Te.Object({displayName:"AI Model",required:!0}),agentTools:Te.Array({displayName:"Agent Tools",required:!1,properties:Xye}),structuredOutput:Te.Array({displayName:"Structured Output",defaultValue:void 0,required:!1,properties:{displayName:Te.ShortText({displayName:"Display Name",required:!0}),description:Te.ShortText({displayName:"Description",required:!1}),type:Te.ShortText({displayName:"Type",required:!0})}}),maxSteps:Te.Number({displayName:"Max steps",description:"The number of iterations the agent can do",required:!0,defaultValue:20}),webSearch:Te.Checkbox({displayName:"Web Search",required:!1,defaultValue:!1,description:"Whether to use web search to find information for the AI to use."}),webSearchOptions:Dy(e=>{let t=e.aiProviderModel;return{provider:t?.provider,model:t?.model}},["webSearch","aiProviderModel"],{showIncludeSources:!1})},async run(e){let{prompt:t,maxSteps:o,aiProviderModel:a}=e.propsValue,n=a,i=n.provider,l=!!e.propsValue.webSearch,u=e.propsValue.webSearchOptions??{},{tools:c,providerOptions:d}=Uy({provider:i,model:n.model,webSearchEnabled:l,webSearchOptions:u}),{provider:p}=_n({provider:i,model:n.model}),m=await Bo({modelId:n.model,provider:i,engineToken:e.server.token,apiUrl:e.server.apiUrl,projectId:e.project.id,flowId:e.flows.current.id,runId:e.run.id,...Qr("openaiResponsesModel",l&&p==="openai"?!0:void 0)}),f=Tq(t),g=!Kt(e.propsValue.structuredOutput)&&e.propsValue.structuredOutput.length>0?e.propsValue.structuredOutput:void 0,y=e.propsValue.agentTools,_=y.some(b=>b.type==="KNOWLEDGE_BASE"),x=y.filter(b=>b.type==="KNOWLEDGE_BASE"&&b.sourceType==="FILE").length>0,w;if(x)try{let b=await OS({provider:n.provider,engineToken:e.server.token,apiUrl:e.server.apiUrl});w={model:b.model,providerOptions:b.providerOptions}}catch(b){f.addMarkdown(`
|
|
237
237
|
|
|
238
238
|
**Warning:** Could not create embedding model for knowledge base search: ${b instanceof Error?b.message:"Unknown error"}
|
|
239
239
|
|