@activepieces/piece-ai 0.4.8 → 0.4.9

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/index.js +8 -8
package/src/index.js CHANGED
@@ -77,7 +77,7 @@ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
77
77
  Option 2 - OIDC token:
78
78
  Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new aR({message:u,statusCode:n,cause:i,generationId:l})}},iR="GatewayInvalidRequestError",PW=`vercel.ai.gateway.error.${iR}`,R$=Symbol.for(PW),z$,N$,EW=class extends(N$=oo,z$=R$,N$){static{s(this,"GatewayInvalidRequestError")}constructor({message:e="Invalid request",statusCode:t=400,cause:o,generationId:a}={}){super({message:e,statusCode:t,cause:o,generationId:a}),this[z$]=!0,this.name=iR,this.type="invalid_request_error"}static isInstance(e){return oo.hasMarker(e)&&R$ in e}},sR="GatewayRateLimitError",AW=`vercel.ai.gateway.error.${sR}`,j$=Symbol.for(AW),M$,D$,CW=class extends(D$=oo,M$=j$,D$){static{s(this,"GatewayRateLimitError")}constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:o,generationId:a}={}){super({message:e,statusCode:t,cause:o,generationId:a}),this[M$]=!0,this.name=sR,this.type="rate_limit_exceeded"}static isInstance(e){return oo.hasMarker(e)&&j$ in e}},lR="GatewayModelNotFoundError",OW=`vercel.ai.gateway.error.${lR}`,U$=Symbol.for(OW),$W=N(()=>$(r.object({modelId:r.string()}))),L$,q$,RW=class extends(q$=oo,L$=U$,q$){static{s(this,"GatewayModelNotFoundError")}constructor({message:e="Model not found",statusCode:t=404,modelId:o,cause:a,generationId:n}={}){super({message:e,statusCode:t,cause:a,generationId:n}),this[L$]=!0,this.name=lR,this.type="model_not_found",this.modelId=o}static isInstance(e){return oo.hasMarker(e)&&U$ in e}},uR="GatewayInternalServerError",zW=`vercel.ai.gateway.error.${uR}`,F$=Symbol.for(zW),B$,V$,Z$=class extends(V$=oo,B$=F$,V$){static{s(this,"GatewayInternalServerError")}constructor({message:e="Internal server error",statusCode:t=500,cause:o,generationId:a}={}){super({message:e,statusCode:t,cause:o,generationId:a}),this[B$]=!0,this.name=uR,this.type="internal_server_error"}static isInstance(e){return oo.hasMarker(e)&&F$ in e}},cR="GatewayResponseError",NW=`vercel.ai.gateway.error.${cR}`,H$=Symbol.for(NW),J$,W$,jW=class extends(W$=oo,J$=H$,W$){static{s(this,"GatewayResponseError")}constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:o,validationError:a,cause:n,generationId:i}={}){super({message:e,statusCode:t,cause:n,generationId:i}),this[J$]=!0,this.name=cR,this.type="response_error",this.response=o,this.validationError=a}static isInstance(e){return oo.hasMarker(e)&&H$ in e}};async function G$({response:e,statusCode:t,defaultMessage:o="Gateway request failed",cause:a,authMethod:n}){var i;let l=await Br({value:e,schema:MW});if(!l.success){let m=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new jW({message:`Invalid error response format: ${o}`,statusCode:t,response:e,validationError:l.error,cause:a,generationId:m})}let u=l.value,c=u.error.type,d=u.error.message,p=(i=u.generationId)!=null?i:void 0;switch(c){case"authentication_error":return jg.createContextualError({apiKeyProvided:n==="api-key",oidcTokenProvided:n==="oidc",statusCode:t,cause:a,generationId:p});case"invalid_request_error":return new EW({message:d,statusCode:t,cause:a,generationId:p});case"rate_limit_exceeded":return new CW({message:d,statusCode:t,cause:a,generationId:p});case"model_not_found":{let m=await Br({value:u.error.param,schema:$W});return new RW({message:d,statusCode:t,modelId:m.success?m.value.modelId:void 0,cause:a,generationId:p})}case"internal_server_error":return new Z$({message:d,statusCode:t,cause:a,generationId:p});default:return new Z$({message:d,statusCode:t,cause:a,generationId:p})}}s(G$,"createGatewayErrorFromResponse");var MW=N(()=>$(r.object({error:r.object({message:r.string(),type:r.string().nullish(),param:r.unknown().nullish(),code:r.union([r.string(),r.number()]).nullish()}),generationId:r.string().nullish()}))),dR="GatewayTimeoutError",DW=`vercel.ai.gateway.error.${dR}`,K$=Symbol.for(DW),X$,Y$,Q$=class pR extends(Y$=oo,X$=K$,Y$){static{s(this,"_GatewayTimeoutError")}constructor({message:t="Request timed out",statusCode:o=408,cause:a,generationId:n}={}){super({message:t,statusCode:o,cause:a,generationId:n}),this[X$]=!0,this.name=dR,this.type="timeout_error"}static isInstance(t){return oo.hasMarker(t)&&K$ in t}static createTimeoutError({originalMessage:t,statusCode:o=408,cause:a,generationId:n}){let i=`Gateway request timed out: ${t}
79
79
 
80
- This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new pR({message:i,statusCode:o,cause:a,generationId:n})}};function eR(e){if(!(e instanceof Error))return!1;let t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}s(eR,"isTimeoutError");async function To(e,t){var o;return oo.isInstance(e)?e:eR(e)?Q$.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):_t.isInstance(e)?e.cause&&eR(e.cause)?Q$.createTimeoutError({originalMessage:e.message,cause:e}):await G$({response:UW(e),statusCode:(o=e.statusCode)!=null?o:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await G$({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}s(To,"asGatewayError");function UW(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}s(UW,"extractApiCallResponse");var mR="ai-gateway-auth-method";async function ra(e){let t=await Br({value:e[mR],schema:LW});return t.success?t.value:void 0}s(ra,"parseAuthMethod");var LW=N(()=>$(r.union([r.literal("api-key"),r.literal("oidc")]))),qW=["embedding","image","language","reranking","video"],tR=class{static{s(this,"GatewayFetchMetadata")}constructor(e){this.config=e}async getAvailableModels(){try{let{value:e}=await Ra({url:`${this.config.baseURL}/config`,headers:await st(this.config.headers()),successfulResponseHandler:Ce(FW),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(t=>t,"errorToMessage")}),fetch:this.config.fetch});return e}catch(e){throw await To(e)}}async getCredits(){try{let e=new URL(this.config.baseURL),{value:t}=await Ra({url:`${e.origin}/v1/credits`,headers:await st(this.config.headers()),successfulResponseHandler:Ce(BW),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(o=>o,"errorToMessage")}),fetch:this.config.fetch});return t}catch(e){throw await To(e)}}},FW=N(()=>$(r.object({models:r.array(r.object({id:r.string(),name:r.string(),description:r.string().nullish(),pricing:r.object({input:r.string(),output:r.string(),input_cache_read:r.string().nullish(),input_cache_write:r.string().nullish()}).transform(({input:e,output:t,input_cache_read:o,input_cache_write:a})=>({input:e,output:t,...o?{cachedInputTokens:o}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:r.object({specificationVersion:r.literal("v3"),provider:r.string(),modelId:r.string()}),modelType:r.string().nullish()})).transform(e=>e.filter(t=>t.modelType==null||qW.includes(t.modelType)))}))),BW=N(()=>$(r.object({balance:r.string(),total_used:r.string()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),VW=class{static{s(this,"GatewaySpendReport")}constructor(e){this.config=e}async getSpendReport(e){try{let t=new URL(this.config.baseURL),o=new URLSearchParams;o.set("start_date",e.startDate),o.set("end_date",e.endDate),e.groupBy&&o.set("group_by",e.groupBy),e.datePart&&o.set("date_part",e.datePart),e.userId&&o.set("user_id",e.userId),e.model&&o.set("model",e.model),e.provider&&o.set("provider",e.provider),e.credentialType&&o.set("credential_type",e.credentialType),e.tags&&e.tags.length>0&&o.set("tags",e.tags.join(","));let{value:a}=await Ra({url:`${t.origin}/v1/report?${o.toString()}`,headers:await st(this.config.headers()),successfulResponseHandler:Ce(ZW),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(n=>n,"errorToMessage")}),fetch:this.config.fetch});return a}catch(t){throw await To(t)}}},ZW=N(()=>$(r.object({results:r.array(r.object({day:r.string().optional(),hour:r.string().optional(),user:r.string().optional(),model:r.string().optional(),tag:r.string().optional(),provider:r.string().optional(),credential_type:r.enum(["byok","system"]).optional(),total_cost:r.number(),market_cost:r.number().optional(),input_tokens:r.number().optional(),output_tokens:r.number().optional(),cached_input_tokens:r.number().optional(),cache_creation_input_tokens:r.number().optional(),reasoning_tokens:r.number().optional(),request_count:r.number().optional()}).transform(({credential_type:e,total_cost:t,market_cost:o,input_tokens:a,output_tokens:n,cached_input_tokens:i,cache_creation_input_tokens:l,reasoning_tokens:u,request_count:c,...d})=>({...d,...e!==void 0?{credentialType:e}:{},totalCost:t,...o!==void 0?{marketCost:o}:{},...a!==void 0?{inputTokens:a}:{},...n!==void 0?{outputTokens:n}:{},...i!==void 0?{cachedInputTokens:i}:{},...l!==void 0?{cacheCreationInputTokens:l}:{},...u!==void 0?{reasoningTokens:u}:{},...c!==void 0?{requestCount:c}:{}})))}))),HW=class{static{s(this,"GatewayGenerationInfoFetcher")}constructor(e){this.config=e}async getGenerationInfo(e){try{let t=new URL(this.config.baseURL),{value:o}=await Ra({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await st(this.config.headers()),successfulResponseHandler:Ce(JW),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(a=>a,"errorToMessage")}),fetch:this.config.fetch});return o}catch(t){throw await To(t)}}},JW=N(()=>$(r.object({data:r.object({id:r.string(),total_cost:r.number(),upstream_inference_cost:r.number(),usage:r.number(),created_at:r.string(),model:r.string(),is_byok:r.boolean(),provider_name:r.string(),streamed:r.boolean(),finish_reason:r.string(),latency:r.number(),generation_time:r.number(),native_tokens_prompt:r.number(),native_tokens_completion:r.number(),native_tokens_reasoning:r.number(),native_tokens_cached:r.number(),native_tokens_cache_creation:r.number(),billable_web_search_calls:r.number()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:o,is_byok:a,provider_name:n,finish_reason:i,generation_time:l,native_tokens_prompt:u,native_tokens_completion:c,native_tokens_reasoning:d,native_tokens_cached:p,native_tokens_cache_creation:m,billable_web_search_calls:f,...h})=>({...h,totalCost:e,upstreamInferenceCost:t,createdAt:o,isByok:a,providerName:n,finishReason:i,generationTime:l,promptTokens:u,completionTokens:c,reasoningTokens:d,cachedTokens:p,cacheCreationTokens:m,billableWebSearchCalls:f}))}).transform(({data:e})=>e))),WW=class{static{s(this,"GatewayLanguageModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){let{abortSignal:t,...o}=e;return{args:this.maybeEncodeFileParts(o),warnings:[]}}async doGenerate(e){let{args:t,warnings:o}=await this.getArgs(e),{abortSignal:a}=e,n=await st(this.config.headers());try{let{responseHeaders:i,value:l,rawValue:u}=await ke({url:this.getUrl(),headers:Ie(n,e.headers,this.getModelConfigHeaders(this.modelId,!1),await st(this.config.o11yHeaders)),body:t,successfulResponseHandler:Ce(r.any()),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(c=>c,"errorToMessage")}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...l,request:{body:t},response:{headers:i,body:u},warnings:o}}catch(i){throw await To(i,await ra(n))}}async doStream(e){let{args:t,warnings:o}=await this.getArgs(e),{abortSignal:a}=e,n=await st(this.config.headers());try{let{value:i,responseHeaders:l}=await ke({url:this.getUrl(),headers:Ie(n,e.headers,this.getModelConfigHeaders(this.modelId,!0),await st(this.config.o11yHeaders)),body:t,successfulResponseHandler:dr(r.any()),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(u=>u,"errorToMessage")}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:i.pipeThrough(new TransformStream({start(u){o.length>0&&u.enqueue({type:"stream-start",warnings:o})},transform(u,c){if(u.success){let d=u.value;if(d.type==="raw"&&!e.includeRawChunks)return;d.type==="response-metadata"&&d.timestamp&&typeof d.timestamp=="string"&&(d.timestamp=new Date(d.timestamp)),c.enqueue(d)}else c.error(u.error)}})),request:{body:t},response:{headers:l}}}catch(i){throw await To(i,await ra(n))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(let t of e.prompt)for(let o of t.content)if(this.isFilePart(o)){let a=o;if(a.data instanceof Uint8Array){let n=Uint8Array.from(a.data),i=Buffer.from(n).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${i}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},GW=class{static{s(this,"GatewayEmbeddingModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:o,providerOptions:a}){var n;let i=await st(this.config.headers());try{let{responseHeaders:l,value:u,rawValue:c}=await ke({url:this.getUrl(),headers:Ie(i,t??{},this.getModelConfigHeaders(),await st(this.config.o11yHeaders)),body:{values:e,...a?{providerOptions:a}:{}},successfulResponseHandler:Ce(KW),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(d=>d,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{embeddings:u.embeddings,usage:(n=u.usage)!=null?n:void 0,providerMetadata:u.providerMetadata,response:{headers:l,body:c},warnings:[]}}catch(l){throw await To(l,await ra(i))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},KW=N(()=>$(r.object({embeddings:r.array(r.array(r.number())),usage:r.object({tokens:r.number()}).nullish(),providerMetadata:r.record(r.string(),r.record(r.string(),r.unknown())).optional()}))),XW=class{static{s(this,"GatewayImageModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:o,aspectRatio:a,seed:n,files:i,mask:l,providerOptions:u,headers:c,abortSignal:d}){var p,m,f,h;let g=await st(this.config.headers());try{let{responseHeaders:y,value:_,rawValue:v}=await ke({url:this.getUrl(),headers:Ie(g,c??{},this.getModelConfigHeaders(),await st(this.config.o11yHeaders)),body:{prompt:e,n:t,...o&&{size:o},...a&&{aspectRatio:a},...n&&{seed:n},...u&&{providerOptions:u},...i&&{files:i.map(x=>rR(x))},...l&&{mask:rR(l)}},successfulResponseHandler:Ce(tG),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(x=>x,"errorToMessage")}),...d&&{abortSignal:d},fetch:this.config.fetch});return{images:_.images,warnings:(p=_.warnings)!=null?p:[],providerMetadata:_.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:y},..._.usage!=null&&{usage:{inputTokens:(m=_.usage.inputTokens)!=null?m:void 0,outputTokens:(f=_.usage.outputTokens)!=null?f:void 0,totalTokens:(h=_.usage.totalTokens)!=null?h:void 0}}}}catch(y){throw await To(y,await ra(g))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function rR(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:tn(e.data)}:e}s(rR,"maybeEncodeImageFile");var YW=r.object({images:r.array(r.unknown()).optional()}).catchall(r.unknown()),QW=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("other"),message:r.string()})]),eG=r.object({inputTokens:r.number().nullish(),outputTokens:r.number().nullish(),totalTokens:r.number().nullish()}),tG=r.object({images:r.array(r.string()),warnings:r.array(QW).optional(),providerMetadata:r.record(r.string(),YW).optional(),usage:eG.optional()}),rG=class{static{s(this,"GatewayVideoModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:o,resolution:a,duration:n,fps:i,seed:l,image:u,providerOptions:c,headers:d,abortSignal:p}){var m;let f=await st(this.config.headers());try{let{responseHeaders:h,value:g}=await ke({url:this.getUrl(),headers:Ie(f,d??{},this.getModelConfigHeaders(),await st(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...o&&{aspectRatio:o},...a&&{resolution:a},...n&&{duration:n},...i&&{fps:i},...l&&{seed:l},...c&&{providerOptions:c},...u&&{image:oG(u)}},successfulResponseHandler:s(async({response:y,url:_,requestBodyValues:v})=>{if(y.body==null)throw new _t({message:"SSE response body is empty",url:_,requestBodyValues:v,statusCode:y.status});let w=Cg({stream:y.body,schema:sG}).getReader(),{done:S,value:P}=await w.read();if(w.releaseLock(),S||!P)throw new _t({message:"SSE stream ended without a data event",url:_,requestBodyValues:v,statusCode:y.status});if(!P.success)throw new _t({message:"Failed to parse video SSE event",cause:P.error,url:_,requestBodyValues:v,statusCode:y.status});let k=P.value;if(k.type==="error")throw new _t({message:k.message,statusCode:k.statusCode,url:_,requestBodyValues:v,responseHeaders:Object.fromEntries([...y.headers]),responseBody:JSON.stringify(k),data:{error:{message:k.message,type:k.errorType,param:k.param}}});return{value:{videos:k.videos,warnings:k.warnings,providerMetadata:k.providerMetadata},responseHeaders:Object.fromEntries([...y.headers])}},"successfulResponseHandler"),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(y=>y,"errorToMessage")}),...p&&{abortSignal:p},fetch:this.config.fetch});return{videos:g.videos,warnings:(m=g.warnings)!=null?m:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(h){throw await To(h,await ra(f))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function oG(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:tn(e.data)}:e}s(oG,"maybeEncodeVideoFile");var nG=r.object({videos:r.array(r.unknown()).optional()}).catchall(r.unknown()),aG=r.union([r.object({type:r.literal("url"),url:r.string(),mediaType:r.string()}),r.object({type:r.literal("base64"),data:r.string(),mediaType:r.string()})]),iG=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("other"),message:r.string()})]),sG=r.discriminatedUnion("type",[r.object({type:r.literal("result"),videos:r.array(aG),warnings:r.array(iG).optional(),providerMetadata:r.record(r.string(),nG).optional()}),r.object({type:r.literal("error"),message:r.string(),errorType:r.string(),statusCode:r.number(),param:r.unknown().nullable()})]),lG=class{static{s(this,"GatewayRerankingModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doRerank({documents:e,query:t,topN:o,headers:a,abortSignal:n,providerOptions:i}){let l=await st(this.config.headers());try{let{responseHeaders:u,value:c,rawValue:d}=await ke({url:this.getUrl(),headers:Ie(l,a??{},this.getModelConfigHeaders(),await st(this.config.o11yHeaders)),body:{documents:e,query:t,...o!=null?{topN:o}:{},...i?{providerOptions:i}:{}},successfulResponseHandler:Ce(uG),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(p=>p,"errorToMessage")}),...n&&{abortSignal:n},fetch:this.config.fetch});return{ranking:c.ranking,providerMetadata:c.providerMetadata,response:{headers:u,body:d},warnings:[]}}catch(u){throw await To(u,await ra(l))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"3","ai-model-id":this.modelId}}},uG=N(()=>$(r.object({ranking:r.array(r.object({index:r.number(),relevanceScore:r.number()})),providerMetadata:r.record(r.string(),r.record(r.string(),r.unknown())).optional()}))),cG=N(()=>$(r.object({objective:r.string().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:r.array(r.string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:r.enum(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:r.number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:r.object({include_domains:r.array(r.string()).optional().describe("List of domains to include in search results."),exclude_domains:r.array(r.string()).optional().describe("List of domains to exclude from search results."),after_date:r.string().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:r.object({max_chars_per_result:r.number().optional().describe("Maximum characters per result."),max_chars_total:r.number().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:r.object({max_age_seconds:r.number().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),dG=N(()=>$(r.union([r.object({searchId:r.string(),results:r.array(r.object({url:r.string(),title:r.string(),excerpt:r.string(),publishDate:r.string().nullable().optional(),relevanceScore:r.number().optional()}))}),r.object({error:r.enum(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:r.number().optional(),message:r.string()})]))),pG=Pe({id:"gateway.parallel_search",inputSchema:cG,outputSchema:dG}),mG=s((e={})=>pG(e),"parallelSearch"),fG=N(()=>$(r.object({query:r.union([r.string(),r.array(r.string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:r.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:r.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:r.number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:r.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:r.array(r.string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:r.array(r.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:r.string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:r.string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:r.string().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:r.string().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:r.enum(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),hG=N(()=>$(r.union([r.object({results:r.array(r.object({title:r.string(),url:r.string(),snippet:r.string(),date:r.string().optional(),lastUpdated:r.string().optional()})),id:r.string()}),r.object({error:r.enum(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:r.number().optional(),message:r.string()})]))),gG=Pe({id:"gateway.perplexity_search",inputSchema:fG,outputSchema:hG}),yG=s((e={})=>gG(e),"perplexitySearch"),_G={parallelSearch:mG,perplexitySearch:yG};async function vG(){var e;return(e=(0,fR.getContext)().headers)==null?void 0:e["x-vercel-id"]}s(vG,"getVercelRequestId");var bG="3.0.105",xG="0.0.1";function wG(e={}){var t,o;let a=null,n=null,i=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5,l=0,u=(o=ta(e.baseURL))!=null?o:"https://ai-gateway.vercel.sh/v3/ai",c=s(async()=>{try{let x=await TG(e);return Qt({Authorization:`Bearer ${x.token}`,"ai-gateway-protocol-version":xG,[mR]:x.authMethod,...e.headers},`ai-sdk/gateway/${bG}`)}catch(x){throw jg.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:x})}},"getHeaders"),d=s(()=>{let x=Yn({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),w=Yn({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),S=Yn({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),P=Yn({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{let k=await vG();return{...x&&{"ai-o11y-deployment-id":x},...w&&{"ai-o11y-environment":w},...S&&{"ai-o11y-region":S},...k&&{"ai-o11y-request-id":k},...P&&{"ai-o11y-project-id":P}}}},"createO11yHeaders"),p=s(x=>new WW(x,{provider:"gateway",baseURL:u,headers:c,fetch:e.fetch,o11yHeaders:d()}),"createLanguageModel"),m=s(async()=>{var x,w,S;let P=(S=(w=(x=e._internal)==null?void 0:x.currentDate)==null?void 0:w.call(x).getTime())!=null?S:Date.now();return(!a||P-l>i)&&(l=P,a=new tR({baseURL:u,headers:c,fetch:e.fetch}).getAvailableModels().then(k=>(n=k,k)).catch(async k=>{throw await To(k,await ra(await c()))})),n?Promise.resolve(n):a},"getAvailableModels"),f=s(async()=>new tR({baseURL:u,headers:c,fetch:e.fetch}).getCredits().catch(async x=>{throw await To(x,await ra(await c()))}),"getCredits"),h=s(async x=>new VW({baseURL:u,headers:c,fetch:e.fetch}).getSpendReport(x).catch(async w=>{throw await To(w,await ra(await c()))}),"getSpendReport"),g=s(async x=>new HW({baseURL:u,headers:c,fetch:e.fetch}).getGenerationInfo(x).catch(async w=>{throw await To(w,await ra(await c()))}),"getGenerationInfo"),y=s(function(x){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return p(x)},"provider");y.specificationVersion="v3",y.getAvailableModels=m,y.getCredits=f,y.getSpendReport=h,y.getGenerationInfo=g,y.imageModel=x=>new XW(x,{provider:"gateway",baseURL:u,headers:c,fetch:e.fetch,o11yHeaders:d()}),y.languageModel=p;let _=s(x=>new GW(x,{provider:"gateway",baseURL:u,headers:c,fetch:e.fetch,o11yHeaders:d()}),"createEmbeddingModel");y.embeddingModel=_,y.textEmbeddingModel=_,y.videoModel=x=>new rG(x,{provider:"gateway",baseURL:u,headers:c,fetch:e.fetch,o11yHeaders:d()});let v=s(x=>new lG(x,{provider:"gateway",baseURL:u,headers:c,fetch:e.fetch,o11yHeaders:d()}),"createRerankingModel");return y.rerankingModel=v,y.reranking=v,y.chat=y.languageModel,y.embedding=y.embeddingModel,y.image=y.imageModel,y.video=y.videoModel,y.tools=_G,y}s(wG,"createGatewayProvider");var gR=wG();async function TG(e){let t=Yn({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await(0,hR.getVercelOidcToken)(),authMethod:"oidc"}}s(TG,"getGatewayAuthToken");var yR=typeof globalThis=="object"?globalThis:global;var Na="1.9.0";var _R=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function SG(e){var t=new Set([e]),o=new Set,a=e.match(_R);if(!a)return function(){return!1};var n={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(n.prerelease!=null)return s(function(c){return c===e},"isExactmatch");function i(u){return o.add(u),!1}s(i,"_reject");function l(u){return t.add(u),!0}return s(l,"_accept"),s(function(c){if(t.has(c))return!0;if(o.has(c))return!1;var d=c.match(_R);if(!d)return i(c);var p={major:+d[1],minor:+d[2],patch:+d[3],prerelease:d[4]};return p.prerelease!=null||n.major!==p.major?i(c):n.major===0?n.minor===p.minor&&n.patch<=p.patch?l(c):i(c):n.minor<=p.minor?l(c):i(c)},"isCompatible")}s(SG,"_makeCompatibilityCheck");var vR=SG(Na);var IG=Na.split(".")[0],sp=Symbol.for("opentelemetry.js.api."+IG),lp=yR;function Yl(e,t,o,a){var n;a===void 0&&(a=!1);var i=lp[sp]=(n=lp[sp])!==null&&n!==void 0?n:{version:Na};if(!a&&i[e]){var l=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return o.error(l.stack||l.message),!1}if(i.version!==Na){var l=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+e+" does not match previously registered API v"+Na);return o.error(l.stack||l.message),!1}return i[e]=t,o.debug("@opentelemetry/api: Registered a global for "+e+" v"+Na+"."),!0}s(Yl,"registerGlobal");function ja(e){var t,o,a=(t=lp[sp])===null||t===void 0?void 0:t.version;if(!(!a||!vR(a)))return(o=lp[sp])===null||o===void 0?void 0:o[e]}s(ja,"getGlobal");function Ql(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Na+".");var o=lp[sp];o&&delete o[e]}s(Ql,"unregisterGlobal");var kG=function(e,t){var o=typeof Symbol=="function"&&e[Symbol.iterator];if(!o)return e;var a=o.call(e),n,i=[],l;try{for(;(t===void 0||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(u){l={error:u}}finally{try{n&&!n.done&&(o=a.return)&&o.call(a)}finally{if(l)throw l.error}}return i},PG=function(e,t,o){if(o||arguments.length===2)for(var a=0,n=t.length,i;a<n;a++)(i||!(a in t))&&(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))},bR=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return s(e,"DiagComponentLogger"),e.prototype.debug=function(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return up("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return up("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return up("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return up("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return up("verbose",this._namespace,t)},e})();function up(e,t,o){var a=ja("diag");if(a)return o.unshift(t),a[e].apply(a,PG([],kG(o),!1))}s(up,"logProxy");var no;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(no||(no={}));function xR(e,t){e<no.NONE?e=no.NONE:e>no.ALL&&(e=no.ALL),t=t||{};function o(a,n){var i=t[a];return typeof i=="function"&&e>=n?i.bind(t):function(){}}return s(o,"_filterFunc"),{error:o("error",no.ERROR),warn:o("warn",no.WARN),info:o("info",no.INFO),debug:o("debug",no.DEBUG),verbose:o("verbose",no.VERBOSE)}}s(xR,"createLogLevelDiagLogger");var EG=function(e,t){var o=typeof Symbol=="function"&&e[Symbol.iterator];if(!o)return e;var a=o.call(e),n,i=[],l;try{for(;(t===void 0||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(u){l={error:u}}finally{try{n&&!n.done&&(o=a.return)&&o.call(a)}finally{if(l)throw l.error}}return i},AG=function(e,t,o){if(o||arguments.length===2)for(var a=0,n=t.length,i;a<n;a++)(i||!(a in t))&&(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))},CG="diag",eu=(function(){function e(){function t(n){return function(){for(var i=[],l=0;l<arguments.length;l++)i[l]=arguments[l];var u=ja("diag");if(u)return u[n].apply(u,AG([],EG(i),!1))}}s(t,"_logProxy");var o=this,a=s(function(n,i){var l,u,c;if(i===void 0&&(i={logLevel:no.INFO}),n===o){var d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return o.error((l=d.stack)!==null&&l!==void 0?l:d.message),!1}typeof i=="number"&&(i={logLevel:i});var p=ja("diag"),m=xR((u=i.logLevel)!==null&&u!==void 0?u:no.INFO,n);if(p&&!i.suppressOverrideMessage){var f=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";p.warn("Current logger will be overwritten from "+f),m.warn("Current logger will overwrite one already registered from "+f)}return Yl("diag",m,o,!0)},"setLogger");o.setLogger=a,o.disable=function(){Ql(CG,o)},o.createComponentLogger=function(n){return new bR(n)},o.verbose=t("verbose"),o.debug=t("debug"),o.info=t("info"),o.warn=t("warn"),o.error=t("error")}return s(e,"DiagAPI"),e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function wR(e){return Symbol.for(e)}s(wR,"createContextKey");var OG=(function(){function e(t){var o=this;o._currentContext=t?new Map(t):new Map,o.getValue=function(a){return o._currentContext.get(a)},o.setValue=function(a,n){var i=new e(o._currentContext);return i._currentContext.set(a,n),i},o.deleteValue=function(a){var n=new e(o._currentContext);return n._currentContext.delete(a),n}}return s(e,"BaseContext"),e})(),TR=new OG;var $G=function(e,t){var o=typeof Symbol=="function"&&e[Symbol.iterator];if(!o)return e;var a=o.call(e),n,i=[],l;try{for(;(t===void 0||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(u){l={error:u}}finally{try{n&&!n.done&&(o=a.return)&&o.call(a)}finally{if(l)throw l.error}}return i},RG=function(e,t,o){if(o||arguments.length===2)for(var a=0,n=t.length,i;a<n;a++)(i||!(a in t))&&(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))},SR=(function(){function e(){}return s(e,"NoopContextManager"),e.prototype.active=function(){return TR},e.prototype.with=function(t,o,a){for(var n=[],i=3;i<arguments.length;i++)n[i-3]=arguments[i];return o.call.apply(o,RG([a],$G(n),!1))},e.prototype.bind=function(t,o){return o},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})();var zG=function(e,t){var o=typeof Symbol=="function"&&e[Symbol.iterator];if(!o)return e;var a=o.call(e),n,i=[],l;try{for(;(t===void 0||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(u){l={error:u}}finally{try{n&&!n.done&&(o=a.return)&&o.call(a)}finally{if(l)throw l.error}}return i},NG=function(e,t,o){if(o||arguments.length===2)for(var a=0,n=t.length,i;a<n;a++)(i||!(a in t))&&(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))},U0="context",jG=new SR,tu=(function(){function e(){}return s(e,"ContextAPI"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Yl(U0,t,eu.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,o,a){for(var n,i=[],l=3;l<arguments.length;l++)i[l-3]=arguments[l];return(n=this._getContextManager()).with.apply(n,NG([t,o,a],zG(i),!1))},e.prototype.bind=function(t,o){return this._getContextManager().bind(t,o)},e.prototype._getContextManager=function(){return ja(U0)||jG},e.prototype.disable=function(){this._getContextManager().disable(),Ql(U0,eu.instance())},e})();var Mg;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Mg||(Mg={}));var L0="0000000000000000",q0="00000000000000000000000000000000",IR={traceId:q0,spanId:L0,traceFlags:Mg.NONE};var wi=(function(){function e(t){t===void 0&&(t=IR),this._spanContext=t}return s(e,"NonRecordingSpan"),e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,o){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,o){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,o){},e})();var F0=wR("OpenTelemetry Context Key SPAN");function Dg(e){return e.getValue(F0)||void 0}s(Dg,"getSpan");function kR(){return Dg(tu.getInstance().active())}s(kR,"getActiveSpan");function cp(e,t){return e.setValue(F0,t)}s(cp,"setSpan");function PR(e){return e.deleteValue(F0)}s(PR,"deleteSpan");function ER(e,t){return cp(e,new wi(t))}s(ER,"setSpanContext");function Ug(e){var t;return(t=Dg(e))===null||t===void 0?void 0:t.spanContext()}s(Ug,"getSpanContext");var MG=/^([0-9a-f]{32})$/i,DG=/^[0-9a-f]{16}$/i;function UG(e){return MG.test(e)&&e!==q0}s(UG,"isValidTraceId");function LG(e){return DG.test(e)&&e!==L0}s(LG,"isValidSpanId");function Lg(e){return UG(e.traceId)&&LG(e.spanId)}s(Lg,"isSpanContextValid");function AR(e){return new wi(e)}s(AR,"wrapSpanContext");var B0=tu.getInstance(),qg=(function(){function e(){}return s(e,"NoopTracer"),e.prototype.startSpan=function(t,o,a){a===void 0&&(a=B0.active());var n=!!o?.root;if(n)return new wi;var i=a&&Ug(a);return qG(i)&&Lg(i)?new wi(i):new wi},e.prototype.startActiveSpan=function(t,o,a,n){var i,l,u;if(!(arguments.length<2)){arguments.length===2?u=o:arguments.length===3?(i=o,u=a):(i=o,l=a,u=n);var c=l??B0.active(),d=this.startSpan(t,i,c),p=cp(c,d);return B0.with(p,u,void 0,d)}},e})();function qG(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}s(qG,"isSpanContext");var FG=new qg,CR=(function(){function e(t,o,a,n){this._provider=t,this.name=o,this.version=a,this.options=n}return s(e,"ProxyTracer"),e.prototype.startSpan=function(t,o,a){return this._getTracer().startSpan(t,o,a)},e.prototype.startActiveSpan=function(t,o,a,n){var i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):FG},e})();var OR=(function(){function e(){}return s(e,"NoopTracerProvider"),e.prototype.getTracer=function(t,o,a){return new qg},e})();var BG=new OR,V0=(function(){function e(){}return s(e,"ProxyTracerProvider"),e.prototype.getTracer=function(t,o,a){var n;return(n=this.getDelegateTracer(t,o,a))!==null&&n!==void 0?n:new CR(this,t,o,a)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:BG},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,o,a){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(t,o,a)},e})();var ru;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(ru||(ru={}));var Fg=tu.getInstance();var Z0="trace",$R=(function(){function e(){this._proxyTracerProvider=new V0,this.wrapSpanContext=AR,this.isSpanContextValid=Lg,this.deleteSpan=PR,this.getSpan=Dg,this.getActiveSpan=kR,this.getSpanContext=Ug,this.setSpan=cp,this.setSpanContext=ER}return s(e,"TraceAPI"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var o=Yl(Z0,this._proxyTracerProvider,eu.instance());return o&&this._proxyTracerProvider.setDelegate(t),o},e.prototype.getTracerProvider=function(){return ja(Z0)||this._proxyTracerProvider},e.prototype.getTracer=function(t,o){return this.getTracerProvider().getTracer(t,o)},e.prototype.disable=function(){Ql(Z0,eu.instance()),this._proxyTracerProvider=new V0},e})();var H0=$R.getInstance();var ZG=Object.defineProperty,HG=s((e,t)=>{for(var o in t)ZG(e,o,{get:t[o],enumerable:!0})},"__export"),KR="AI_InvalidArgumentError",XR=`vercel.ai.error.${KR}`,JG=Symbol.for(XR),YR,oa=class extends ge{static{s(this,"InvalidArgumentError")}constructor({parameter:e,value:t,message:o}){super({name:KR,message:`Invalid argument for parameter ${e}: ${o}`}),this[YR]=!0,this.parameter=e,this.value=t}static isInstance(e){return ge.hasMarker(e,XR)}};YR=JG;var WG="AI_InvalidStreamPartError",GG=`vercel.ai.error.${WG}`,KG=Symbol.for(GG),XG;XG=KG;var QR="AI_InvalidToolApprovalError",ez=`vercel.ai.error.${QR}`,YG=Symbol.for(ez),tz,QG=class extends ge{static{s(this,"InvalidToolApprovalError")}constructor({approvalId:e}){super({name:QR,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[tz]=!0,this.approvalId=e}static isInstance(e){return ge.hasMarker(e,ez)}};tz=YG;var rz="AI_InvalidToolInputError",oz=`vercel.ai.error.${rz}`,e8=Symbol.for(oz),nz,Q0=class extends ge{static{s(this,"InvalidToolInputError")}constructor({toolInput:e,toolName:t,cause:o,message:a=`Invalid input for tool ${t}: ${vn(o)}`}){super({name:rz,message:a,cause:o}),this[nz]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ge.hasMarker(e,oz)}};nz=e8;var az="AI_ToolCallNotFoundForApprovalError",iz=`vercel.ai.error.${az}`,t8=Symbol.for(iz),sz,eT=class extends ge{static{s(this,"ToolCallNotFoundForApprovalError")}constructor({toolCallId:e,approvalId:t}){super({name:az,message:`Tool call "${e}" not found for approval request "${t}".`}),this[sz]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ge.hasMarker(e,iz)}};sz=t8;var lz="AI_MissingToolResultsError",uz=`vercel.ai.error.${lz}`,r8=Symbol.for(uz),cz,RR=class extends ge{static{s(this,"MissingToolResultsError")}constructor({toolCallIds:e}){super({name:lz,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[cz]=!0,this.toolCallIds=e}static isInstance(e){return ge.hasMarker(e,uz)}};cz=r8;var dz="AI_NoImageGeneratedError",pz=`vercel.ai.error.${dz}`,o8=Symbol.for(pz),mz,n8=class extends ge{static{s(this,"NoImageGeneratedError")}constructor({message:e="No image generated.",cause:t,responses:o}){super({name:dz,message:e,cause:t}),this[mz]=!0,this.responses=o}static isInstance(e){return ge.hasMarker(e,pz)}};mz=o8;var fz="AI_NoObjectGeneratedError",hz=`vercel.ai.error.${fz}`,a8=Symbol.for(hz),gz,Ti=class extends ge{static{s(this,"NoObjectGeneratedError")}constructor({message:e="No object generated.",cause:t,text:o,response:a,usage:n,finishReason:i}){super({name:fz,message:e,cause:t}),this[gz]=!0,this.text=o,this.response=a,this.usage=n,this.finishReason=i}static isInstance(e){return ge.hasMarker(e,hz)}};gz=a8;var yz="AI_NoOutputGeneratedError",_z=`vercel.ai.error.${yz}`,i8=Symbol.for(_z),vz,bz=class extends ge{static{s(this,"NoOutputGeneratedError")}constructor({message:e="No output generated.",cause:t}={}){super({name:yz,message:e,cause:t}),this[vz]=!0}static isInstance(e){return ge.hasMarker(e,_z)}};vz=i8;var s8="AI_NoSpeechGeneratedError",l8=`vercel.ai.error.${s8}`,u8=Symbol.for(l8),c8;c8=u8;var d8="AI_NoTranscriptGeneratedError",p8=`vercel.ai.error.${d8}`,m8=Symbol.for(p8),f8;f8=m8;var h8="AI_NoVideoGeneratedError",g8=`vercel.ai.error.${h8}`,y8=Symbol.for(g8),_8;_8=y8;var xz="AI_NoSuchToolError",wz=`vercel.ai.error.${xz}`,v8=Symbol.for(wz),Tz,W0=class extends ge{static{s(this,"NoSuchToolError")}constructor({toolName:e,availableTools:t=void 0,message:o=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:xz,message:o}),this[Tz]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ge.hasMarker(e,wz)}};Tz=v8;var Sz="AI_ToolCallRepairError",Iz=`vercel.ai.error.${Sz}`,b8=Symbol.for(Iz),kz,x8=class extends ge{static{s(this,"ToolCallRepairError")}constructor({cause:e,originalError:t,message:o=`Error repairing tool call: ${vn(e)}`}){super({name:Sz,message:o,cause:e}),this[kz]=!0,this.originalError=t}static isInstance(e){return ge.hasMarker(e,Iz)}};kz=b8;var tT=class extends ge{static{s(this,"UnsupportedModelVersionError")}constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},Pz="AI_UIMessageStreamError",Ez=`vercel.ai.error.${Pz}`,w8=Symbol.for(Ez),Az,ou=class extends ge{static{s(this,"UIMessageStreamError")}constructor({chunkType:e,chunkId:t,message:o}){super({name:Pz,message:o}),this[Az]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ge.hasMarker(e,Ez)}};Az=w8;var Cz="AI_InvalidDataContentError",Oz=`vercel.ai.error.${Cz}`,T8=Symbol.for(Oz),$z,zR=class extends ge{static{s(this,"InvalidDataContentError")}constructor({content:e,cause:t,message:o=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof e}.`}){super({name:Cz,message:o,cause:t}),this[$z]=!0,this.content=e}static isInstance(e){return ge.hasMarker(e,Oz)}};$z=T8;var Rz="AI_InvalidMessageRoleError",zz=`vercel.ai.error.${Rz}`,S8=Symbol.for(zz),Nz,I8=class extends ge{static{s(this,"InvalidMessageRoleError")}constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Rz,message:t}),this[Nz]=!0,this.role=e}static isInstance(e){return ge.hasMarker(e,zz)}};Nz=S8;var k8="AI_MessageConversionError",P8=`vercel.ai.error.${k8}`,E8=Symbol.for(P8),A8;A8=E8;var jz="AI_RetryError",Mz=`vercel.ai.error.${jz}`,C8=Symbol.for(Mz),Dz,NR=class extends ge{static{s(this,"RetryError")}constructor({message:e,reason:t,errors:o}){super({name:jz,message:e}),this[Dz]=!0,this.reason=t,this.errors=o,this.lastError=o[o.length-1]}static isInstance(e){return ge.hasMarker(e,Mz)}};Dz=C8;function hs(e){return e===void 0?[]:Array.isArray(e)?e:[e]}s(hs,"asArray");async function Pn(e){for(let t of hs(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}s(Pn,"notify");function O8({warning:e,provider:t,model:o}){let a=`AI SDK Warning (${t} / ${o}):`;switch(e.type){case"unsupported":{let n=`${a} The feature "${e.feature}" is not supported.`;return e.details&&(n+=` ${e.details}`),n}case"compatibility":{let n=`${a} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(n+=` ${e.details}`),n}case"other":return`${a} ${e.message}`;default:return`${a} ${JSON.stringify(e,null,2)}`}}s(O8,"formatWarning");var $8="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",jR=!1,gs=s(e=>{if(e.warnings.length===0)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}jR||(jR=!0,console.info($8));for(let o of e.warnings)console.warn(O8({warning:o,provider:e.provider,model:e.model}))}},"logWarnings");function rT({provider:e,modelId:t}){gs({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}s(rT,"logV2CompatibilityWarning");function R8(e){return e.specificationVersion==="v3"?e:(rT({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,o){return o==="specificationVersion"?"v3":t[o]}}))}s(R8,"asEmbeddingModelV3");function z8(e){return e.specificationVersion==="v3"?e:(rT({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,o){return o==="specificationVersion"?"v3":t[o]}}))}s(z8,"asImageModelV3");function N8(e){return e.specificationVersion==="v3"?e:(rT({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,o){switch(o){case"specificationVersion":return"v3";case"doGenerate":return async(...a)=>{let n=await t.doGenerate(...a);return{...n,finishReason:Uz(n.finishReason),usage:Lz(n.usage)}};case"doStream":return async(...a)=>{let n=await t.doStream(...a);return{...n,stream:j8(n.stream)}};default:return t[o]}}}))}s(N8,"asLanguageModelV3");function j8(e){return e.pipeThrough(new TransformStream({transform(t,o){t.type==="finish"?o.enqueue({...t,finishReason:Uz(t.finishReason),usage:Lz(t.usage)}):o.enqueue(t)}}))}s(j8,"convertV2StreamToV3");function Uz(e){return{unified:e==="unknown"?"other":e,raw:void 0}}s(Uz,"convertV2FinishReasonToV3");function Lz(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}s(Lz,"convertV2UsageToV3");function Zg(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new tT({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return N8(e)}return oT().languageModel(e)}s(Zg,"resolveLanguageModel");function qz(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new tT({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return R8(e)}return oT().embeddingModel(e)}s(qz,"resolveEmbeddingModel");function M8(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new tT({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return z8(e)}return oT().imageModel(e)}s(M8,"resolveImageModel");function oT(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:gR}s(oT,"getGlobalProvider");function nT(e){if(e!=null)return typeof e=="number"?e:e.totalMs}s(nT,"getTotalTimeoutMs");function Fz(e){if(!(e==null||typeof e=="number"))return e.stepMs}s(Fz,"getStepTimeoutMs");function D8(e){if(!(e==null||typeof e=="number"))return e.chunkMs}s(D8,"getChunkTimeoutMs");var Hg=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}];var U8=s(e=>{let t=typeof e=="string"?Yt(e):e,o=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(o+10)},"stripID3");function L8(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?U8(e):e}s(L8,"stripID3TagsIfPresent");function Jg({data:e,signatures:t}){let o=L8(e),a=typeof o=="string"?Yt(o.substring(0,Math.min(o.length,24))):o;for(let n of t)if(a.length>=n.bytesPrefix.length&&n.bytesPrefix.every((i,l)=>i===null||a[l]===i))return n.mediaType}s(Jg,"detectMediaType");var fp="6.0.170",Bz=s(async({url:e,maxBytes:t,abortSignal:o})=>{var a;let n=e.toString();Qd(n);try{let i=await fetch(n,{headers:Qt({},`ai-sdk/${fp}`,Eg()),signal:o});if(i.redirected&&Qd(i.url),!i.ok)throw new ro({url:n,statusCode:i.status,statusText:i.statusText});return{data:await g0({response:i,url:n,maxBytes:t??Pg}),mediaType:(a=i.headers.get("content-type"))!=null?a:void 0}}catch(i){throw ro.isInstance(i)?i:new ro({url:n,cause:i})}},"download"),q8=s((e=Bz)=>t=>Promise.all(t.map(async o=>o.isUrlSupportedByModel?null:e(o))),"createDefaultDownloadFunction");function Vz(e){try{let[t,o]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:o}}catch{return{mediaType:void 0,base64Content:void 0}}}s(Vz,"splitDataUrl");var Zz=r.union([r.string(),r.instanceof(Uint8Array),r.instanceof(ArrayBuffer),r.custom(e=>{var t,o;return(o=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?o:!1},{message:"Must be a Buffer"})]);function Hz(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){let{mediaType:t,base64Content:o}=Vz(e.toString());if(t==null||o==null)throw new ge({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:o,mediaType:t}}return{data:e,mediaType:void 0}}s(Hz,"convertToLanguageModelV3DataContent");function F8(e){return typeof e=="string"?e:e instanceof ArrayBuffer?tn(new Uint8Array(e)):tn(e)}s(F8,"convertDataContentToBase64String");function B8(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")try{return Yt(e)}catch(t){throw new zR({message:"Invalid data content. Content string is not a base64-encoded media.",content:e,cause:t})}if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new zR({content:e})}s(B8,"convertDataContentToUint8Array");async function Jz({prompt:e,supportedUrls:t,download:o=q8()}){let a=await Z8(e.messages,o,t),n=new Map;for(let d of e.messages)if(d.role==="assistant"&&Array.isArray(d.content))for(let p of d.content)p.type==="tool-approval-request"&&"approvalId"in p&&"toolCallId"in p&&n.set(p.approvalId,p.toolCallId);let i=new Set;for(let d of e.messages)if(d.role==="tool"){for(let p of d.content)if(p.type==="tool-approval-response"){let m=n.get(p.approvalId);m&&i.add(m)}}let l=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:hs(e.system).map(d=>({role:"system",content:d.content,providerOptions:d.providerOptions})):[],...e.messages.map(d=>V8({message:d,downloadedAssets:a}))],u=[];for(let d of l){if(d.role!=="tool"){u.push(d);continue}let p=u.at(-1);p?.role==="tool"?p.content.push(...d.content):u.push(d)}let c=new Set;for(let d of u)switch(d.role){case"assistant":{for(let p of d.content)p.type==="tool-call"&&!p.providerExecuted&&c.add(p.toolCallId);break}case"tool":{for(let p of d.content)p.type==="tool-result"&&c.delete(p.toolCallId);break}case"user":case"system":for(let p of i)c.delete(p);if(c.size>0)throw new RR({toolCallIds:Array.from(c)});break}for(let d of i)c.delete(d);if(c.size>0)throw new RR({toolCallIds:Array.from(c)});return u.filter(d=>d.role!=="tool"||d.content.length>0)}s(Jz,"convertToLanguageModelPrompt");function V8({message:e,downloadedAssets:t}){let o=e.role;switch(o){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(a=>H8(a,t)).filter(a=>a.type!=="text"||a.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(a=>a.type!=="text"||a.text!==""||a.providerOptions!=null).filter(a=>a.type!=="tool-approval-request").map(a=>{let n=a.providerOptions;switch(a.type){case"file":{let{data:i,mediaType:l}=Hz(a.data);return{type:"file",data:i,filename:a.filename,mediaType:l??a.mediaType,providerOptions:n}}case"reasoning":return{type:"reasoning",text:a.text,providerOptions:n};case"text":return{type:"text",text:a.text,providerOptions:n};case"tool-call":return{type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:n};case"tool-result":return{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:MR(a.output),providerOptions:n}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(a=>a.type!=="tool-approval-response"||a.providerExecuted).map(a=>{switch(a.type){case"tool-result":return{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:MR(a.output),providerOptions:a.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:a.approvalId,approved:a.approved,reason:a.reason}}}),providerOptions:e.providerOptions};default:{let a=o;throw new I8({role:a})}}}s(V8,"convertToLanguageModelMessage");async function Z8(e,t,o){let a=e.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").map(i=>{var l;let u=(l=i.mediaType)!=null?l:i.type==="image"?"image/*":void 0,c=i.type==="image"?i.image:i.data;if(typeof c=="string")try{c=new URL(c)}catch{}return{mediaType:u,data:c}}).filter(i=>i.data instanceof URL).map(i=>({url:i.data,isUrlSupportedByModel:i.mediaType!=null&&jO({url:i.data.toString(),mediaType:i.mediaType,supportedUrls:o})})),n=await t(a);return Object.fromEntries(n.map((i,l)=>i==null?null:[a[l].url.toString(),{data:i.data,mediaType:i.mediaType}]).filter(i=>i!=null))}s(Z8,"downloadAssets");function H8(e,t){var o;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let a,n=e.type;switch(n){case"image":a=e.image;break;case"file":a=e.data;break;default:throw new Error(`Unsupported part type: ${n}`)}let{data:i,mediaType:l}=Hz(a),u=l??e.mediaType,c=i;if(c instanceof URL){let d=t[c.toString()];d&&(c=d.data,u??(u=d.mediaType))}switch(n){case"image":return(c instanceof Uint8Array||typeof c=="string")&&(u=(o=Jg({data:c,signatures:Hg}))!=null?o:u),{type:"file",mediaType:u??"image/*",filename:void 0,data:c,providerOptions:e.providerOptions};case"file":{if(u==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:u,filename:e.filename,data:c,providerOptions:e.providerOptions}}}}s(H8,"convertPartToLanguageModelPart");function MR(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}s(MR,"mapToolResultOutput");async function pp({toolCallId:e,input:t,output:o,tool:a,errorMode:n}){return n==="text"?{type:"error-text",value:vn(o)}:n==="json"?{type:"error-json",value:DR(o)}:a?.toModelOutput?await a.toModelOutput({toolCallId:e,input:t,output:o}):typeof o=="string"?{type:"text",value:o}:{type:"json",value:DR(o)}}s(pp,"createToolModelOutput");function DR(e){return e===void 0?null:e}s(DR,"toJSONValue");function G0({maxOutputTokens:e,temperature:t,topP:o,topK:a,presencePenalty:n,frequencyPenalty:i,seed:l,stopSequences:u}){if(e!=null){if(!Number.isInteger(e))throw new oa({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new oa({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new oa({parameter:"temperature",value:t,message:"temperature must be a number"});if(o!=null&&typeof o!="number")throw new oa({parameter:"topP",value:o,message:"topP must be a number"});if(a!=null&&typeof a!="number")throw new oa({parameter:"topK",value:a,message:"topK must be a number"});if(n!=null&&typeof n!="number")throw new oa({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(i!=null&&typeof i!="number")throw new oa({parameter:"frequencyPenalty",value:i,message:"frequencyPenalty must be a number"});if(l!=null&&!Number.isInteger(l))throw new oa({parameter:"seed",value:l,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:o,topK:a,presencePenalty:n,frequencyPenalty:i,stopSequences:u,seed:l}}s(G0,"prepareCallSettings");function J8(e){return e!=null&&Object.keys(e).length>0}s(J8,"isNonEmptyObject");async function Wz({tools:e,toolChoice:t,activeTools:o}){if(!J8(e))return{tools:void 0,toolChoice:void 0};let a=o!=null?Object.entries(e).filter(([i])=>o.includes(i)):Object.entries(e),n=[];for(let[i,l]of a){let u=l.type;switch(u){case void 0:case"dynamic":case"function":n.push({type:"function",name:i,description:l.description,inputSchema:await Qn(l.inputSchema).jsonSchema,...l.inputExamples!=null?{inputExamples:l.inputExamples}:{},providerOptions:l.providerOptions,...l.strict!=null?{strict:l.strict}:{}});break;case"provider":n.push({type:"provider",name:i,id:l.id,args:l.args});break;default:{let c=u;throw new Error(`Unsupported tool type: ${c}`)}}}return{tools:n,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}s(Wz,"prepareToolsAndToolChoice");var mp=r.lazy(()=>r.union([r.null(),r.string(),r.number(),r.boolean(),r.record(r.string(),mp.optional()),r.array(mp)])),ze=r.record(r.string(),r.record(r.string(),mp.optional())),Gz=r.object({type:r.literal("text"),text:r.string(),providerOptions:ze.optional()}),W8=r.object({type:r.literal("image"),image:r.union([Zz,r.instanceof(URL)]),mediaType:r.string().optional(),providerOptions:ze.optional()}),Kz=r.object({type:r.literal("file"),data:r.union([Zz,r.instanceof(URL)]),filename:r.string().optional(),mediaType:r.string(),providerOptions:ze.optional()}),G8=r.object({type:r.literal("reasoning"),text:r.string(),providerOptions:ze.optional()}),K8=r.object({type:r.literal("tool-call"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerOptions:ze.optional(),providerExecuted:r.boolean().optional()}),X8=r.discriminatedUnion("type",[r.object({type:r.literal("text"),value:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("json"),value:mp,providerOptions:ze.optional()}),r.object({type:r.literal("execution-denied"),reason:r.string().optional(),providerOptions:ze.optional()}),r.object({type:r.literal("error-text"),value:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("error-json"),value:mp,providerOptions:ze.optional()}),r.object({type:r.literal("content"),value:r.array(r.union([r.object({type:r.literal("text"),text:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("media"),data:r.string(),mediaType:r.string()}),r.object({type:r.literal("file-data"),data:r.string(),mediaType:r.string(),filename:r.string().optional(),providerOptions:ze.optional()}),r.object({type:r.literal("file-url"),url:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("file-id"),fileId:r.union([r.string(),r.record(r.string(),r.string())]),providerOptions:ze.optional()}),r.object({type:r.literal("image-data"),data:r.string(),mediaType:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("image-url"),url:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("image-file-id"),fileId:r.union([r.string(),r.record(r.string(),r.string())]),providerOptions:ze.optional()}),r.object({type:r.literal("custom"),providerOptions:ze.optional()})]))})]),Xz=r.object({type:r.literal("tool-result"),toolCallId:r.string(),toolName:r.string(),output:X8,providerOptions:ze.optional()}),Y8=r.object({type:r.literal("tool-approval-request"),approvalId:r.string(),toolCallId:r.string()}),Q8=r.object({type:r.literal("tool-approval-response"),approvalId:r.string(),approved:r.boolean(),reason:r.string().optional()}),eK=r.object({role:r.literal("system"),content:r.string(),providerOptions:ze.optional()}),tK=r.object({role:r.literal("user"),content:r.union([r.string(),r.array(r.union([Gz,W8,Kz]))]),providerOptions:ze.optional()}),rK=r.object({role:r.literal("assistant"),content:r.union([r.string(),r.array(r.union([Gz,Kz,G8,K8,Xz,Y8]))]),providerOptions:ze.optional()}),oK=r.object({role:r.literal("tool"),content:r.array(r.union([Xz,Q8])),providerOptions:ze.optional()}),nK=r.union([eK,tK,rK,oK]);async function Yz({allowSystemInMessages:e,system:t,prompt:o,messages:a}){if(o==null&&a==null)throw new vo({prompt:o,message:"prompt or messages must be defined"});if(o!=null&&a!=null)throw new vo({prompt:o,message:"prompt and messages cannot be defined at the same time"});if(typeof t!="string"&&!hs(t).every(i=>i.role==="system"))throw new vo({prompt:o,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});if(o!=null&&typeof o=="string")a=[{role:"user",content:o}];else if(o!=null&&Array.isArray(o))a=o;else if(a==null)throw new vo({prompt:o,message:"prompt or messages must be defined"});if(a.length===0)throw new vo({prompt:o,message:"messages must not be empty"});if(a.some(i=>i.role==="system")){if(e===!1)throw new vo({prompt:o,message:"System messages are not allowed in the prompt or messages fields. Use the system option instead."});e===void 0&&console.warn("AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.")}let n=await Br({value:a,schema:r.array(nK)});if(!n.success)throw new vo({prompt:o,message:"The messages do not match the ModelMessage[] schema.",cause:n.error});return{messages:a,system:t}}s(Yz,"standardizePrompt");function Qz(e){if(!jg.isInstance(e))return e;let t=(process==null?void 0:process.env.NODE_ENV)==="production",o="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new ge({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${o}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
80
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new pR({message:i,statusCode:o,cause:a,generationId:n})}};function eR(e){if(!(e instanceof Error))return!1;let t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}s(eR,"isTimeoutError");async function To(e,t){var o;return oo.isInstance(e)?e:eR(e)?Q$.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):_t.isInstance(e)?e.cause&&eR(e.cause)?Q$.createTimeoutError({originalMessage:e.message,cause:e}):await G$({response:UW(e),statusCode:(o=e.statusCode)!=null?o:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await G$({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}s(To,"asGatewayError");function UW(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}s(UW,"extractApiCallResponse");var mR="ai-gateway-auth-method";async function ra(e){let t=await Br({value:e[mR],schema:LW});return t.success?t.value:void 0}s(ra,"parseAuthMethod");var LW=N(()=>$(r.union([r.literal("api-key"),r.literal("oidc")]))),qW=["embedding","image","language","reranking","video"],tR=class{static{s(this,"GatewayFetchMetadata")}constructor(e){this.config=e}async getAvailableModels(){try{let{value:e}=await Ra({url:`${this.config.baseURL}/config`,headers:await st(this.config.headers()),successfulResponseHandler:Ce(FW),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(t=>t,"errorToMessage")}),fetch:this.config.fetch});return e}catch(e){throw await To(e)}}async getCredits(){try{let e=new URL(this.config.baseURL),{value:t}=await Ra({url:`${e.origin}/v1/credits`,headers:await st(this.config.headers()),successfulResponseHandler:Ce(BW),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(o=>o,"errorToMessage")}),fetch:this.config.fetch});return t}catch(e){throw await To(e)}}},FW=N(()=>$(r.object({models:r.array(r.object({id:r.string(),name:r.string(),description:r.string().nullish(),pricing:r.object({input:r.string(),output:r.string(),input_cache_read:r.string().nullish(),input_cache_write:r.string().nullish()}).transform(({input:e,output:t,input_cache_read:o,input_cache_write:a})=>({input:e,output:t,...o?{cachedInputTokens:o}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:r.object({specificationVersion:r.literal("v3"),provider:r.string(),modelId:r.string()}),modelType:r.string().nullish()})).transform(e=>e.filter(t=>t.modelType==null||qW.includes(t.modelType)))}))),BW=N(()=>$(r.object({balance:r.string(),total_used:r.string()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),VW=class{static{s(this,"GatewaySpendReport")}constructor(e){this.config=e}async getSpendReport(e){try{let t=new URL(this.config.baseURL),o=new URLSearchParams;o.set("start_date",e.startDate),o.set("end_date",e.endDate),e.groupBy&&o.set("group_by",e.groupBy),e.datePart&&o.set("date_part",e.datePart),e.userId&&o.set("user_id",e.userId),e.model&&o.set("model",e.model),e.provider&&o.set("provider",e.provider),e.credentialType&&o.set("credential_type",e.credentialType),e.tags&&e.tags.length>0&&o.set("tags",e.tags.join(","));let{value:a}=await Ra({url:`${t.origin}/v1/report?${o.toString()}`,headers:await st(this.config.headers()),successfulResponseHandler:Ce(ZW),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(n=>n,"errorToMessage")}),fetch:this.config.fetch});return a}catch(t){throw await To(t)}}},ZW=N(()=>$(r.object({results:r.array(r.object({day:r.string().optional(),hour:r.string().optional(),user:r.string().optional(),model:r.string().optional(),tag:r.string().optional(),provider:r.string().optional(),credential_type:r.enum(["byok","system"]).optional(),total_cost:r.number(),market_cost:r.number().optional(),input_tokens:r.number().optional(),output_tokens:r.number().optional(),cached_input_tokens:r.number().optional(),cache_creation_input_tokens:r.number().optional(),reasoning_tokens:r.number().optional(),request_count:r.number().optional()}).transform(({credential_type:e,total_cost:t,market_cost:o,input_tokens:a,output_tokens:n,cached_input_tokens:i,cache_creation_input_tokens:l,reasoning_tokens:u,request_count:c,...d})=>({...d,...e!==void 0?{credentialType:e}:{},totalCost:t,...o!==void 0?{marketCost:o}:{},...a!==void 0?{inputTokens:a}:{},...n!==void 0?{outputTokens:n}:{},...i!==void 0?{cachedInputTokens:i}:{},...l!==void 0?{cacheCreationInputTokens:l}:{},...u!==void 0?{reasoningTokens:u}:{},...c!==void 0?{requestCount:c}:{}})))}))),HW=class{static{s(this,"GatewayGenerationInfoFetcher")}constructor(e){this.config=e}async getGenerationInfo(e){try{let t=new URL(this.config.baseURL),{value:o}=await Ra({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await st(this.config.headers()),successfulResponseHandler:Ce(JW),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(a=>a,"errorToMessage")}),fetch:this.config.fetch});return o}catch(t){throw await To(t)}}},JW=N(()=>$(r.object({data:r.object({id:r.string(),total_cost:r.number(),upstream_inference_cost:r.number(),usage:r.number(),created_at:r.string(),model:r.string(),is_byok:r.boolean(),provider_name:r.string(),streamed:r.boolean(),finish_reason:r.string(),latency:r.number(),generation_time:r.number(),native_tokens_prompt:r.number(),native_tokens_completion:r.number(),native_tokens_reasoning:r.number(),native_tokens_cached:r.number(),native_tokens_cache_creation:r.number(),billable_web_search_calls:r.number()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:o,is_byok:a,provider_name:n,finish_reason:i,generation_time:l,native_tokens_prompt:u,native_tokens_completion:c,native_tokens_reasoning:d,native_tokens_cached:p,native_tokens_cache_creation:m,billable_web_search_calls:f,...h})=>({...h,totalCost:e,upstreamInferenceCost:t,createdAt:o,isByok:a,providerName:n,finishReason:i,generationTime:l,promptTokens:u,completionTokens:c,reasoningTokens:d,cachedTokens:p,cacheCreationTokens:m,billableWebSearchCalls:f}))}).transform(({data:e})=>e))),WW=class{static{s(this,"GatewayLanguageModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){let{abortSignal:t,...o}=e;return{args:this.maybeEncodeFileParts(o),warnings:[]}}async doGenerate(e){let{args:t,warnings:o}=await this.getArgs(e),{abortSignal:a}=e,n=await st(this.config.headers());try{let{responseHeaders:i,value:l,rawValue:u}=await ke({url:this.getUrl(),headers:Ie(n,e.headers,this.getModelConfigHeaders(this.modelId,!1),await st(this.config.o11yHeaders)),body:t,successfulResponseHandler:Ce(r.any()),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(c=>c,"errorToMessage")}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...l,request:{body:t},response:{headers:i,body:u},warnings:o}}catch(i){throw await To(i,await ra(n))}}async doStream(e){let{args:t,warnings:o}=await this.getArgs(e),{abortSignal:a}=e,n=await st(this.config.headers());try{let{value:i,responseHeaders:l}=await ke({url:this.getUrl(),headers:Ie(n,e.headers,this.getModelConfigHeaders(this.modelId,!0),await st(this.config.o11yHeaders)),body:t,successfulResponseHandler:dr(r.any()),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(u=>u,"errorToMessage")}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:i.pipeThrough(new TransformStream({start(u){o.length>0&&u.enqueue({type:"stream-start",warnings:o})},transform(u,c){if(u.success){let d=u.value;if(d.type==="raw"&&!e.includeRawChunks)return;d.type==="response-metadata"&&d.timestamp&&typeof d.timestamp=="string"&&(d.timestamp=new Date(d.timestamp)),c.enqueue(d)}else c.error(u.error)}})),request:{body:t},response:{headers:l}}}catch(i){throw await To(i,await ra(n))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(let t of e.prompt)for(let o of t.content)if(this.isFilePart(o)){let a=o;if(a.data instanceof Uint8Array){let n=Uint8Array.from(a.data),i=Buffer.from(n).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${i}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},GW=class{static{s(this,"GatewayEmbeddingModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:o,providerOptions:a}){var n;let i=await st(this.config.headers());try{let{responseHeaders:l,value:u,rawValue:c}=await ke({url:this.getUrl(),headers:Ie(i,t??{},this.getModelConfigHeaders(),await st(this.config.o11yHeaders)),body:{values:e,...a?{providerOptions:a}:{}},successfulResponseHandler:Ce(KW),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(d=>d,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{embeddings:u.embeddings,usage:(n=u.usage)!=null?n:void 0,providerMetadata:u.providerMetadata,response:{headers:l,body:c},warnings:[]}}catch(l){throw await To(l,await ra(i))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},KW=N(()=>$(r.object({embeddings:r.array(r.array(r.number())),usage:r.object({tokens:r.number()}).nullish(),providerMetadata:r.record(r.string(),r.record(r.string(),r.unknown())).optional()}))),XW=class{static{s(this,"GatewayImageModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:o,aspectRatio:a,seed:n,files:i,mask:l,providerOptions:u,headers:c,abortSignal:d}){var p,m,f,h;let g=await st(this.config.headers());try{let{responseHeaders:y,value:_,rawValue:v}=await ke({url:this.getUrl(),headers:Ie(g,c??{},this.getModelConfigHeaders(),await st(this.config.o11yHeaders)),body:{prompt:e,n:t,...o&&{size:o},...a&&{aspectRatio:a},...n&&{seed:n},...u&&{providerOptions:u},...i&&{files:i.map(x=>rR(x))},...l&&{mask:rR(l)}},successfulResponseHandler:Ce(tG),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(x=>x,"errorToMessage")}),...d&&{abortSignal:d},fetch:this.config.fetch});return{images:_.images,warnings:(p=_.warnings)!=null?p:[],providerMetadata:_.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:y},..._.usage!=null&&{usage:{inputTokens:(m=_.usage.inputTokens)!=null?m:void 0,outputTokens:(f=_.usage.outputTokens)!=null?f:void 0,totalTokens:(h=_.usage.totalTokens)!=null?h:void 0}}}}catch(y){throw await To(y,await ra(g))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function rR(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:tn(e.data)}:e}s(rR,"maybeEncodeImageFile");var YW=r.object({images:r.array(r.unknown()).optional()}).catchall(r.unknown()),QW=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("other"),message:r.string()})]),eG=r.object({inputTokens:r.number().nullish(),outputTokens:r.number().nullish(),totalTokens:r.number().nullish()}),tG=r.object({images:r.array(r.string()),warnings:r.array(QW).optional(),providerMetadata:r.record(r.string(),YW).optional(),usage:eG.optional()}),rG=class{static{s(this,"GatewayVideoModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:o,resolution:a,duration:n,fps:i,seed:l,image:u,providerOptions:c,headers:d,abortSignal:p}){var m;let f=await st(this.config.headers());try{let{responseHeaders:h,value:g}=await ke({url:this.getUrl(),headers:Ie(f,d??{},this.getModelConfigHeaders(),await st(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...o&&{aspectRatio:o},...a&&{resolution:a},...n&&{duration:n},...i&&{fps:i},...l&&{seed:l},...c&&{providerOptions:c},...u&&{image:oG(u)}},successfulResponseHandler:s(async({response:y,url:_,requestBodyValues:v})=>{if(y.body==null)throw new _t({message:"SSE response body is empty",url:_,requestBodyValues:v,statusCode:y.status});let w=Cg({stream:y.body,schema:sG}).getReader(),{done:S,value:P}=await w.read();if(w.releaseLock(),S||!P)throw new _t({message:"SSE stream ended without a data event",url:_,requestBodyValues:v,statusCode:y.status});if(!P.success)throw new _t({message:"Failed to parse video SSE event",cause:P.error,url:_,requestBodyValues:v,statusCode:y.status});let k=P.value;if(k.type==="error")throw new _t({message:k.message,statusCode:k.statusCode,url:_,requestBodyValues:v,responseHeaders:Object.fromEntries([...y.headers]),responseBody:JSON.stringify(k),data:{error:{message:k.message,type:k.errorType,param:k.param}}});return{value:{videos:k.videos,warnings:k.warnings,providerMetadata:k.providerMetadata},responseHeaders:Object.fromEntries([...y.headers])}},"successfulResponseHandler"),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(y=>y,"errorToMessage")}),...p&&{abortSignal:p},fetch:this.config.fetch});return{videos:g.videos,warnings:(m=g.warnings)!=null?m:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(h){throw await To(h,await ra(f))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function oG(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:tn(e.data)}:e}s(oG,"maybeEncodeVideoFile");var nG=r.object({videos:r.array(r.unknown()).optional()}).catchall(r.unknown()),aG=r.union([r.object({type:r.literal("url"),url:r.string(),mediaType:r.string()}),r.object({type:r.literal("base64"),data:r.string(),mediaType:r.string()})]),iG=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("other"),message:r.string()})]),sG=r.discriminatedUnion("type",[r.object({type:r.literal("result"),videos:r.array(aG),warnings:r.array(iG).optional(),providerMetadata:r.record(r.string(),nG).optional()}),r.object({type:r.literal("error"),message:r.string(),errorType:r.string(),statusCode:r.number(),param:r.unknown().nullable()})]),lG=class{static{s(this,"GatewayRerankingModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doRerank({documents:e,query:t,topN:o,headers:a,abortSignal:n,providerOptions:i}){let l=await st(this.config.headers());try{let{responseHeaders:u,value:c,rawValue:d}=await ke({url:this.getUrl(),headers:Ie(l,a??{},this.getModelConfigHeaders(),await st(this.config.o11yHeaders)),body:{documents:e,query:t,...o!=null?{topN:o}:{},...i?{providerOptions:i}:{}},successfulResponseHandler:Ce(uG),failedResponseHandler:bt({errorSchema:r.any(),errorToMessage:s(p=>p,"errorToMessage")}),...n&&{abortSignal:n},fetch:this.config.fetch});return{ranking:c.ranking,providerMetadata:c.providerMetadata,response:{headers:u,body:d},warnings:[]}}catch(u){throw await To(u,await ra(l))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"3","ai-model-id":this.modelId}}},uG=N(()=>$(r.object({ranking:r.array(r.object({index:r.number(),relevanceScore:r.number()})),providerMetadata:r.record(r.string(),r.record(r.string(),r.unknown())).optional()}))),cG=N(()=>$(r.object({objective:r.string().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:r.array(r.string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:r.enum(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:r.number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:r.object({include_domains:r.array(r.string()).optional().describe("List of domains to include in search results."),exclude_domains:r.array(r.string()).optional().describe("List of domains to exclude from search results."),after_date:r.string().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:r.object({max_chars_per_result:r.number().optional().describe("Maximum characters per result."),max_chars_total:r.number().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:r.object({max_age_seconds:r.number().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),dG=N(()=>$(r.union([r.object({searchId:r.string(),results:r.array(r.object({url:r.string(),title:r.string(),excerpt:r.string(),publishDate:r.string().nullable().optional(),relevanceScore:r.number().optional()}))}),r.object({error:r.enum(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:r.number().optional(),message:r.string()})]))),pG=Pe({id:"gateway.parallel_search",inputSchema:cG,outputSchema:dG}),mG=s((e={})=>pG(e),"parallelSearch"),fG=N(()=>$(r.object({query:r.union([r.string(),r.array(r.string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:r.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:r.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:r.number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:r.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:r.array(r.string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:r.array(r.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:r.string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:r.string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:r.string().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:r.string().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:r.enum(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),hG=N(()=>$(r.union([r.object({results:r.array(r.object({title:r.string(),url:r.string(),snippet:r.string(),date:r.string().optional(),lastUpdated:r.string().optional()})),id:r.string()}),r.object({error:r.enum(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:r.number().optional(),message:r.string()})]))),gG=Pe({id:"gateway.perplexity_search",inputSchema:fG,outputSchema:hG}),yG=s((e={})=>gG(e),"perplexitySearch"),_G={parallelSearch:mG,perplexitySearch:yG};async function vG(){var e;return(e=(0,fR.getContext)().headers)==null?void 0:e["x-vercel-id"]}s(vG,"getVercelRequestId");var bG="3.0.105",xG="0.0.1";function wG(e={}){var t,o;let a=null,n=null,i=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5,l=0,u=(o=ta(e.baseURL))!=null?o:"https://ai-gateway.vercel.sh/v3/ai",c=s(async()=>{try{let x=await TG(e);return Qt({Authorization:`Bearer ${x.token}`,"ai-gateway-protocol-version":xG,[mR]:x.authMethod,...e.headers},`ai-sdk/gateway/${bG}`)}catch(x){throw jg.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:x})}},"getHeaders"),d=s(()=>{let x=Yn({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),w=Yn({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),S=Yn({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),P=Yn({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{let k=await vG();return{...x&&{"ai-o11y-deployment-id":x},...w&&{"ai-o11y-environment":w},...S&&{"ai-o11y-region":S},...k&&{"ai-o11y-request-id":k},...P&&{"ai-o11y-project-id":P}}}},"createO11yHeaders"),p=s(x=>new WW(x,{provider:"gateway",baseURL:u,headers:c,fetch:e.fetch,o11yHeaders:d()}),"createLanguageModel"),m=s(async()=>{var x,w,S;let P=(S=(w=(x=e._internal)==null?void 0:x.currentDate)==null?void 0:w.call(x).getTime())!=null?S:Date.now();return(!a||P-l>i)&&(l=P,a=new tR({baseURL:u,headers:c,fetch:e.fetch}).getAvailableModels().then(k=>(n=k,k)).catch(async k=>{throw await To(k,await ra(await c()))})),n?Promise.resolve(n):a},"getAvailableModels"),f=s(async()=>new tR({baseURL:u,headers:c,fetch:e.fetch}).getCredits().catch(async x=>{throw await To(x,await ra(await c()))}),"getCredits"),h=s(async x=>new VW({baseURL:u,headers:c,fetch:e.fetch}).getSpendReport(x).catch(async w=>{throw await To(w,await ra(await c()))}),"getSpendReport"),g=s(async x=>new HW({baseURL:u,headers:c,fetch:e.fetch}).getGenerationInfo(x).catch(async w=>{throw await To(w,await ra(await c()))}),"getGenerationInfo"),y=s(function(x){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return p(x)},"provider");y.specificationVersion="v3",y.getAvailableModels=m,y.getCredits=f,y.getSpendReport=h,y.getGenerationInfo=g,y.imageModel=x=>new XW(x,{provider:"gateway",baseURL:u,headers:c,fetch:e.fetch,o11yHeaders:d()}),y.languageModel=p;let _=s(x=>new GW(x,{provider:"gateway",baseURL:u,headers:c,fetch:e.fetch,o11yHeaders:d()}),"createEmbeddingModel");y.embeddingModel=_,y.textEmbeddingModel=_,y.videoModel=x=>new rG(x,{provider:"gateway",baseURL:u,headers:c,fetch:e.fetch,o11yHeaders:d()});let v=s(x=>new lG(x,{provider:"gateway",baseURL:u,headers:c,fetch:e.fetch,o11yHeaders:d()}),"createRerankingModel");return y.rerankingModel=v,y.reranking=v,y.chat=y.languageModel,y.embedding=y.embeddingModel,y.image=y.imageModel,y.video=y.videoModel,y.tools=_G,y}s(wG,"createGatewayProvider");var gR=wG();async function TG(e){let t=Yn({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await(0,hR.getVercelOidcToken)(),authMethod:"oidc"}}s(TG,"getGatewayAuthToken");var yR=typeof globalThis=="object"?globalThis:global;var Na="1.9.0";var _R=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function SG(e){var t=new Set([e]),o=new Set,a=e.match(_R);if(!a)return function(){return!1};var n={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(n.prerelease!=null)return s(function(c){return c===e},"isExactmatch");function i(u){return o.add(u),!1}s(i,"_reject");function l(u){return t.add(u),!0}return s(l,"_accept"),s(function(c){if(t.has(c))return!0;if(o.has(c))return!1;var d=c.match(_R);if(!d)return i(c);var p={major:+d[1],minor:+d[2],patch:+d[3],prerelease:d[4]};return p.prerelease!=null||n.major!==p.major?i(c):n.major===0?n.minor===p.minor&&n.patch<=p.patch?l(c):i(c):n.minor<=p.minor?l(c):i(c)},"isCompatible")}s(SG,"_makeCompatibilityCheck");var vR=SG(Na);var IG=Na.split(".")[0],sp=Symbol.for("opentelemetry.js.api."+IG),lp=yR;function Yl(e,t,o,a){var n;a===void 0&&(a=!1);var i=lp[sp]=(n=lp[sp])!==null&&n!==void 0?n:{version:Na};if(!a&&i[e]){var l=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return o.error(l.stack||l.message),!1}if(i.version!==Na){var l=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+e+" does not match previously registered API v"+Na);return o.error(l.stack||l.message),!1}return i[e]=t,o.debug("@opentelemetry/api: Registered a global for "+e+" v"+Na+"."),!0}s(Yl,"registerGlobal");function ja(e){var t,o,a=(t=lp[sp])===null||t===void 0?void 0:t.version;if(!(!a||!vR(a)))return(o=lp[sp])===null||o===void 0?void 0:o[e]}s(ja,"getGlobal");function Ql(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Na+".");var o=lp[sp];o&&delete o[e]}s(Ql,"unregisterGlobal");var kG=function(e,t){var o=typeof Symbol=="function"&&e[Symbol.iterator];if(!o)return e;var a=o.call(e),n,i=[],l;try{for(;(t===void 0||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(u){l={error:u}}finally{try{n&&!n.done&&(o=a.return)&&o.call(a)}finally{if(l)throw l.error}}return i},PG=function(e,t,o){if(o||arguments.length===2)for(var a=0,n=t.length,i;a<n;a++)(i||!(a in t))&&(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))},bR=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return s(e,"DiagComponentLogger"),e.prototype.debug=function(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return up("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return up("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return up("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return up("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return up("verbose",this._namespace,t)},e})();function up(e,t,o){var a=ja("diag");if(a)return o.unshift(t),a[e].apply(a,PG([],kG(o),!1))}s(up,"logProxy");var no;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(no||(no={}));function xR(e,t){e<no.NONE?e=no.NONE:e>no.ALL&&(e=no.ALL),t=t||{};function o(a,n){var i=t[a];return typeof i=="function"&&e>=n?i.bind(t):function(){}}return s(o,"_filterFunc"),{error:o("error",no.ERROR),warn:o("warn",no.WARN),info:o("info",no.INFO),debug:o("debug",no.DEBUG),verbose:o("verbose",no.VERBOSE)}}s(xR,"createLogLevelDiagLogger");var EG=function(e,t){var o=typeof Symbol=="function"&&e[Symbol.iterator];if(!o)return e;var a=o.call(e),n,i=[],l;try{for(;(t===void 0||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(u){l={error:u}}finally{try{n&&!n.done&&(o=a.return)&&o.call(a)}finally{if(l)throw l.error}}return i},AG=function(e,t,o){if(o||arguments.length===2)for(var a=0,n=t.length,i;a<n;a++)(i||!(a in t))&&(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))},CG="diag",eu=(function(){function e(){function t(n){return function(){for(var i=[],l=0;l<arguments.length;l++)i[l]=arguments[l];var u=ja("diag");if(u)return u[n].apply(u,AG([],EG(i),!1))}}s(t,"_logProxy");var o=this,a=s(function(n,i){var l,u,c;if(i===void 0&&(i={logLevel:no.INFO}),n===o){var d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return o.error((l=d.stack)!==null&&l!==void 0?l:d.message),!1}typeof i=="number"&&(i={logLevel:i});var p=ja("diag"),m=xR((u=i.logLevel)!==null&&u!==void 0?u:no.INFO,n);if(p&&!i.suppressOverrideMessage){var f=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";p.warn("Current logger will be overwritten from "+f),m.warn("Current logger will overwrite one already registered from "+f)}return Yl("diag",m,o,!0)},"setLogger");o.setLogger=a,o.disable=function(){Ql(CG,o)},o.createComponentLogger=function(n){return new bR(n)},o.verbose=t("verbose"),o.debug=t("debug"),o.info=t("info"),o.warn=t("warn"),o.error=t("error")}return s(e,"DiagAPI"),e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function wR(e){return Symbol.for(e)}s(wR,"createContextKey");var OG=(function(){function e(t){var o=this;o._currentContext=t?new Map(t):new Map,o.getValue=function(a){return o._currentContext.get(a)},o.setValue=function(a,n){var i=new e(o._currentContext);return i._currentContext.set(a,n),i},o.deleteValue=function(a){var n=new e(o._currentContext);return n._currentContext.delete(a),n}}return s(e,"BaseContext"),e})(),TR=new OG;var $G=function(e,t){var o=typeof Symbol=="function"&&e[Symbol.iterator];if(!o)return e;var a=o.call(e),n,i=[],l;try{for(;(t===void 0||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(u){l={error:u}}finally{try{n&&!n.done&&(o=a.return)&&o.call(a)}finally{if(l)throw l.error}}return i},RG=function(e,t,o){if(o||arguments.length===2)for(var a=0,n=t.length,i;a<n;a++)(i||!(a in t))&&(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))},SR=(function(){function e(){}return s(e,"NoopContextManager"),e.prototype.active=function(){return TR},e.prototype.with=function(t,o,a){for(var n=[],i=3;i<arguments.length;i++)n[i-3]=arguments[i];return o.call.apply(o,RG([a],$G(n),!1))},e.prototype.bind=function(t,o){return o},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})();var zG=function(e,t){var o=typeof Symbol=="function"&&e[Symbol.iterator];if(!o)return e;var a=o.call(e),n,i=[],l;try{for(;(t===void 0||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(u){l={error:u}}finally{try{n&&!n.done&&(o=a.return)&&o.call(a)}finally{if(l)throw l.error}}return i},NG=function(e,t,o){if(o||arguments.length===2)for(var a=0,n=t.length,i;a<n;a++)(i||!(a in t))&&(i||(i=Array.prototype.slice.call(t,0,a)),i[a]=t[a]);return e.concat(i||Array.prototype.slice.call(t))},U0="context",jG=new SR,tu=(function(){function e(){}return s(e,"ContextAPI"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Yl(U0,t,eu.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,o,a){for(var n,i=[],l=3;l<arguments.length;l++)i[l-3]=arguments[l];return(n=this._getContextManager()).with.apply(n,NG([t,o,a],zG(i),!1))},e.prototype.bind=function(t,o){return this._getContextManager().bind(t,o)},e.prototype._getContextManager=function(){return ja(U0)||jG},e.prototype.disable=function(){this._getContextManager().disable(),Ql(U0,eu.instance())},e})();var Mg;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Mg||(Mg={}));var L0="0000000000000000",q0="00000000000000000000000000000000",IR={traceId:q0,spanId:L0,traceFlags:Mg.NONE};var wi=(function(){function e(t){t===void 0&&(t=IR),this._spanContext=t}return s(e,"NonRecordingSpan"),e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,o){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,o){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,o){},e})();var F0=wR("OpenTelemetry Context Key SPAN");function Dg(e){return e.getValue(F0)||void 0}s(Dg,"getSpan");function kR(){return Dg(tu.getInstance().active())}s(kR,"getActiveSpan");function cp(e,t){return e.setValue(F0,t)}s(cp,"setSpan");function PR(e){return e.deleteValue(F0)}s(PR,"deleteSpan");function ER(e,t){return cp(e,new wi(t))}s(ER,"setSpanContext");function Ug(e){var t;return(t=Dg(e))===null||t===void 0?void 0:t.spanContext()}s(Ug,"getSpanContext");var MG=/^([0-9a-f]{32})$/i,DG=/^[0-9a-f]{16}$/i;function UG(e){return MG.test(e)&&e!==q0}s(UG,"isValidTraceId");function LG(e){return DG.test(e)&&e!==L0}s(LG,"isValidSpanId");function Lg(e){return UG(e.traceId)&&LG(e.spanId)}s(Lg,"isSpanContextValid");function AR(e){return new wi(e)}s(AR,"wrapSpanContext");var B0=tu.getInstance(),qg=(function(){function e(){}return s(e,"NoopTracer"),e.prototype.startSpan=function(t,o,a){a===void 0&&(a=B0.active());var n=!!o?.root;if(n)return new wi;var i=a&&Ug(a);return qG(i)&&Lg(i)?new wi(i):new wi},e.prototype.startActiveSpan=function(t,o,a,n){var i,l,u;if(!(arguments.length<2)){arguments.length===2?u=o:arguments.length===3?(i=o,u=a):(i=o,l=a,u=n);var c=l??B0.active(),d=this.startSpan(t,i,c),p=cp(c,d);return B0.with(p,u,void 0,d)}},e})();function qG(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}s(qG,"isSpanContext");var FG=new qg,CR=(function(){function e(t,o,a,n){this._provider=t,this.name=o,this.version=a,this.options=n}return s(e,"ProxyTracer"),e.prototype.startSpan=function(t,o,a){return this._getTracer().startSpan(t,o,a)},e.prototype.startActiveSpan=function(t,o,a,n){var i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):FG},e})();var OR=(function(){function e(){}return s(e,"NoopTracerProvider"),e.prototype.getTracer=function(t,o,a){return new qg},e})();var BG=new OR,V0=(function(){function e(){}return s(e,"ProxyTracerProvider"),e.prototype.getTracer=function(t,o,a){var n;return(n=this.getDelegateTracer(t,o,a))!==null&&n!==void 0?n:new CR(this,t,o,a)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:BG},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,o,a){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(t,o,a)},e})();var ru;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(ru||(ru={}));var Fg=tu.getInstance();var Z0="trace",$R=(function(){function e(){this._proxyTracerProvider=new V0,this.wrapSpanContext=AR,this.isSpanContextValid=Lg,this.deleteSpan=PR,this.getSpan=Dg,this.getActiveSpan=kR,this.getSpanContext=Ug,this.setSpan=cp,this.setSpanContext=ER}return s(e,"TraceAPI"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var o=Yl(Z0,this._proxyTracerProvider,eu.instance());return o&&this._proxyTracerProvider.setDelegate(t),o},e.prototype.getTracerProvider=function(){return ja(Z0)||this._proxyTracerProvider},e.prototype.getTracer=function(t,o){return this.getTracerProvider().getTracer(t,o)},e.prototype.disable=function(){Ql(Z0,eu.instance()),this._proxyTracerProvider=new V0},e})();var H0=$R.getInstance();var ZG=Object.defineProperty,HG=s((e,t)=>{for(var o in t)ZG(e,o,{get:t[o],enumerable:!0})},"__export"),KR="AI_InvalidArgumentError",XR=`vercel.ai.error.${KR}`,JG=Symbol.for(XR),YR,oa=class extends ge{static{s(this,"InvalidArgumentError")}constructor({parameter:e,value:t,message:o}){super({name:KR,message:`Invalid argument for parameter ${e}: ${o}`}),this[YR]=!0,this.parameter=e,this.value=t}static isInstance(e){return ge.hasMarker(e,XR)}};YR=JG;var WG="AI_InvalidStreamPartError",GG=`vercel.ai.error.${WG}`,KG=Symbol.for(GG),XG;XG=KG;var QR="AI_InvalidToolApprovalError",ez=`vercel.ai.error.${QR}`,YG=Symbol.for(ez),tz,QG=class extends ge{static{s(this,"InvalidToolApprovalError")}constructor({approvalId:e}){super({name:QR,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[tz]=!0,this.approvalId=e}static isInstance(e){return ge.hasMarker(e,ez)}};tz=YG;var rz="AI_InvalidToolInputError",oz=`vercel.ai.error.${rz}`,eK=Symbol.for(oz),nz,Q0=class extends ge{static{s(this,"InvalidToolInputError")}constructor({toolInput:e,toolName:t,cause:o,message:a=`Invalid input for tool ${t}: ${vn(o)}`}){super({name:rz,message:a,cause:o}),this[nz]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ge.hasMarker(e,oz)}};nz=eK;var az="AI_ToolCallNotFoundForApprovalError",iz=`vercel.ai.error.${az}`,tK=Symbol.for(iz),sz,eT=class extends ge{static{s(this,"ToolCallNotFoundForApprovalError")}constructor({toolCallId:e,approvalId:t}){super({name:az,message:`Tool call "${e}" not found for approval request "${t}".`}),this[sz]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ge.hasMarker(e,iz)}};sz=tK;var lz="AI_MissingToolResultsError",uz=`vercel.ai.error.${lz}`,rK=Symbol.for(uz),cz,RR=class extends ge{static{s(this,"MissingToolResultsError")}constructor({toolCallIds:e}){super({name:lz,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[cz]=!0,this.toolCallIds=e}static isInstance(e){return ge.hasMarker(e,uz)}};cz=rK;var dz="AI_NoImageGeneratedError",pz=`vercel.ai.error.${dz}`,oK=Symbol.for(pz),mz,nK=class extends ge{static{s(this,"NoImageGeneratedError")}constructor({message:e="No image generated.",cause:t,responses:o}){super({name:dz,message:e,cause:t}),this[mz]=!0,this.responses=o}static isInstance(e){return ge.hasMarker(e,pz)}};mz=oK;var fz="AI_NoObjectGeneratedError",hz=`vercel.ai.error.${fz}`,aK=Symbol.for(hz),gz,Ti=class extends ge{static{s(this,"NoObjectGeneratedError")}constructor({message:e="No object generated.",cause:t,text:o,response:a,usage:n,finishReason:i}){super({name:fz,message:e,cause:t}),this[gz]=!0,this.text=o,this.response=a,this.usage=n,this.finishReason=i}static isInstance(e){return ge.hasMarker(e,hz)}};gz=aK;var yz="AI_NoOutputGeneratedError",_z=`vercel.ai.error.${yz}`,iK=Symbol.for(_z),vz,bz=class extends ge{static{s(this,"NoOutputGeneratedError")}constructor({message:e="No output generated.",cause:t}={}){super({name:yz,message:e,cause:t}),this[vz]=!0}static isInstance(e){return ge.hasMarker(e,_z)}};vz=iK;var sK="AI_NoSpeechGeneratedError",lK=`vercel.ai.error.${sK}`,uK=Symbol.for(lK),cK;cK=uK;var dK="AI_NoTranscriptGeneratedError",pK=`vercel.ai.error.${dK}`,mK=Symbol.for(pK),fK;fK=mK;var hK="AI_NoVideoGeneratedError",gK=`vercel.ai.error.${hK}`,yK=Symbol.for(gK),_K;_K=yK;var xz="AI_NoSuchToolError",wz=`vercel.ai.error.${xz}`,vK=Symbol.for(wz),Tz,W0=class extends ge{static{s(this,"NoSuchToolError")}constructor({toolName:e,availableTools:t=void 0,message:o=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:xz,message:o}),this[Tz]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ge.hasMarker(e,wz)}};Tz=vK;var Sz="AI_ToolCallRepairError",Iz=`vercel.ai.error.${Sz}`,bK=Symbol.for(Iz),kz,xK=class extends ge{static{s(this,"ToolCallRepairError")}constructor({cause:e,originalError:t,message:o=`Error repairing tool call: ${vn(e)}`}){super({name:Sz,message:o,cause:e}),this[kz]=!0,this.originalError=t}static isInstance(e){return ge.hasMarker(e,Iz)}};kz=bK;var tT=class extends ge{static{s(this,"UnsupportedModelVersionError")}constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},Pz="AI_UIMessageStreamError",Ez=`vercel.ai.error.${Pz}`,wK=Symbol.for(Ez),Az,ou=class extends ge{static{s(this,"UIMessageStreamError")}constructor({chunkType:e,chunkId:t,message:o}){super({name:Pz,message:o}),this[Az]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ge.hasMarker(e,Ez)}};Az=wK;var Cz="AI_InvalidDataContentError",Oz=`vercel.ai.error.${Cz}`,TK=Symbol.for(Oz),$z,zR=class extends ge{static{s(this,"InvalidDataContentError")}constructor({content:e,cause:t,message:o=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof e}.`}){super({name:Cz,message:o,cause:t}),this[$z]=!0,this.content=e}static isInstance(e){return ge.hasMarker(e,Oz)}};$z=TK;var Rz="AI_InvalidMessageRoleError",zz=`vercel.ai.error.${Rz}`,SK=Symbol.for(zz),Nz,IK=class extends ge{static{s(this,"InvalidMessageRoleError")}constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Rz,message:t}),this[Nz]=!0,this.role=e}static isInstance(e){return ge.hasMarker(e,zz)}};Nz=SK;var kK="AI_MessageConversionError",PK=`vercel.ai.error.${kK}`,EK=Symbol.for(PK),AK;AK=EK;var jz="AI_RetryError",Mz=`vercel.ai.error.${jz}`,CK=Symbol.for(Mz),Dz,NR=class extends ge{static{s(this,"RetryError")}constructor({message:e,reason:t,errors:o}){super({name:jz,message:e}),this[Dz]=!0,this.reason=t,this.errors=o,this.lastError=o[o.length-1]}static isInstance(e){return ge.hasMarker(e,Mz)}};Dz=CK;function hs(e){return e===void 0?[]:Array.isArray(e)?e:[e]}s(hs,"asArray");async function Pn(e){for(let t of hs(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}s(Pn,"notify");function OK({warning:e,provider:t,model:o}){let a=`AI SDK Warning (${t} / ${o}):`;switch(e.type){case"unsupported":{let n=`${a} The feature "${e.feature}" is not supported.`;return e.details&&(n+=` ${e.details}`),n}case"compatibility":{let n=`${a} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(n+=` ${e.details}`),n}case"other":return`${a} ${e.message}`;default:return`${a} ${JSON.stringify(e,null,2)}`}}s(OK,"formatWarning");var $K="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",jR=!1,gs=s(e=>{if(e.warnings.length===0)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}jR||(jR=!0,console.info($K));for(let o of e.warnings)console.warn(OK({warning:o,provider:e.provider,model:e.model}))}},"logWarnings");function rT({provider:e,modelId:t}){gs({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}s(rT,"logV2CompatibilityWarning");function RK(e){return e.specificationVersion==="v3"?e:(rT({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,o){return o==="specificationVersion"?"v3":t[o]}}))}s(RK,"asEmbeddingModelV3");function zK(e){return e.specificationVersion==="v3"?e:(rT({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,o){return o==="specificationVersion"?"v3":t[o]}}))}s(zK,"asImageModelV3");function NK(e){return e.specificationVersion==="v3"?e:(rT({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,o){switch(o){case"specificationVersion":return"v3";case"doGenerate":return async(...a)=>{let n=await t.doGenerate(...a);return{...n,finishReason:Uz(n.finishReason),usage:Lz(n.usage)}};case"doStream":return async(...a)=>{let n=await t.doStream(...a);return{...n,stream:jK(n.stream)}};default:return t[o]}}}))}s(NK,"asLanguageModelV3");function jK(e){return e.pipeThrough(new TransformStream({transform(t,o){t.type==="finish"?o.enqueue({...t,finishReason:Uz(t.finishReason),usage:Lz(t.usage)}):o.enqueue(t)}}))}s(jK,"convertV2StreamToV3");function Uz(e){return{unified:e==="unknown"?"other":e,raw:void 0}}s(Uz,"convertV2FinishReasonToV3");function Lz(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}s(Lz,"convertV2UsageToV3");function Zg(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new tT({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return NK(e)}return oT().languageModel(e)}s(Zg,"resolveLanguageModel");function qz(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new tT({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return RK(e)}return oT().embeddingModel(e)}s(qz,"resolveEmbeddingModel");function MK(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new tT({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return zK(e)}return oT().imageModel(e)}s(MK,"resolveImageModel");function oT(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:gR}s(oT,"getGlobalProvider");function nT(e){if(e!=null)return typeof e=="number"?e:e.totalMs}s(nT,"getTotalTimeoutMs");function Fz(e){if(!(e==null||typeof e=="number"))return e.stepMs}s(Fz,"getStepTimeoutMs");function DK(e){if(!(e==null||typeof e=="number"))return e.chunkMs}s(DK,"getChunkTimeoutMs");var Hg=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}];var UK=s(e=>{let t=typeof e=="string"?Yt(e):e,o=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(o+10)},"stripID3");function LK(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?UK(e):e}s(LK,"stripID3TagsIfPresent");function Jg({data:e,signatures:t}){let o=LK(e),a=typeof o=="string"?Yt(o.substring(0,Math.min(o.length,24))):o;for(let n of t)if(a.length>=n.bytesPrefix.length&&n.bytesPrefix.every((i,l)=>i===null||a[l]===i))return n.mediaType}s(Jg,"detectMediaType");var fp="6.0.170",Bz=s(async({url:e,maxBytes:t,abortSignal:o})=>{var a;let n=e.toString();Qd(n);try{let i=await fetch(n,{headers:Qt({},`ai-sdk/${fp}`,Eg()),signal:o});if(i.redirected&&Qd(i.url),!i.ok)throw new ro({url:n,statusCode:i.status,statusText:i.statusText});return{data:await g0({response:i,url:n,maxBytes:t??Pg}),mediaType:(a=i.headers.get("content-type"))!=null?a:void 0}}catch(i){throw ro.isInstance(i)?i:new ro({url:n,cause:i})}},"download"),qK=s((e=Bz)=>t=>Promise.all(t.map(async o=>o.isUrlSupportedByModel?null:e(o))),"createDefaultDownloadFunction");function Vz(e){try{let[t,o]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:o}}catch{return{mediaType:void 0,base64Content:void 0}}}s(Vz,"splitDataUrl");var Zz=r.union([r.string(),r.instanceof(Uint8Array),r.instanceof(ArrayBuffer),r.custom(e=>{var t,o;return(o=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?o:!1},{message:"Must be a Buffer"})]);function Hz(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){let{mediaType:t,base64Content:o}=Vz(e.toString());if(t==null||o==null)throw new ge({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:o,mediaType:t}}return{data:e,mediaType:void 0}}s(Hz,"convertToLanguageModelV3DataContent");function FK(e){return typeof e=="string"?e:e instanceof ArrayBuffer?tn(new Uint8Array(e)):tn(e)}s(FK,"convertDataContentToBase64String");function BK(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")try{return Yt(e)}catch(t){throw new zR({message:"Invalid data content. Content string is not a base64-encoded media.",content:e,cause:t})}if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new zR({content:e})}s(BK,"convertDataContentToUint8Array");async function Jz({prompt:e,supportedUrls:t,download:o=qK()}){let a=await ZK(e.messages,o,t),n=new Map;for(let d of e.messages)if(d.role==="assistant"&&Array.isArray(d.content))for(let p of d.content)p.type==="tool-approval-request"&&"approvalId"in p&&"toolCallId"in p&&n.set(p.approvalId,p.toolCallId);let i=new Set;for(let d of e.messages)if(d.role==="tool"){for(let p of d.content)if(p.type==="tool-approval-response"){let m=n.get(p.approvalId);m&&i.add(m)}}let l=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:hs(e.system).map(d=>({role:"system",content:d.content,providerOptions:d.providerOptions})):[],...e.messages.map(d=>VK({message:d,downloadedAssets:a}))],u=[];for(let d of l){if(d.role!=="tool"){u.push(d);continue}let p=u.at(-1);p?.role==="tool"?p.content.push(...d.content):u.push(d)}let c=new Set;for(let d of u)switch(d.role){case"assistant":{for(let p of d.content)p.type==="tool-call"&&!p.providerExecuted&&c.add(p.toolCallId);break}case"tool":{for(let p of d.content)p.type==="tool-result"&&c.delete(p.toolCallId);break}case"user":case"system":for(let p of i)c.delete(p);if(c.size>0)throw new RR({toolCallIds:Array.from(c)});break}for(let d of i)c.delete(d);if(c.size>0)throw new RR({toolCallIds:Array.from(c)});return u.filter(d=>d.role!=="tool"||d.content.length>0)}s(Jz,"convertToLanguageModelPrompt");function VK({message:e,downloadedAssets:t}){let o=e.role;switch(o){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(a=>HK(a,t)).filter(a=>a.type!=="text"||a.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(a=>a.type!=="text"||a.text!==""||a.providerOptions!=null).filter(a=>a.type!=="tool-approval-request").map(a=>{let n=a.providerOptions;switch(a.type){case"file":{let{data:i,mediaType:l}=Hz(a.data);return{type:"file",data:i,filename:a.filename,mediaType:l??a.mediaType,providerOptions:n}}case"reasoning":return{type:"reasoning",text:a.text,providerOptions:n};case"text":return{type:"text",text:a.text,providerOptions:n};case"tool-call":return{type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:n};case"tool-result":return{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:MR(a.output),providerOptions:n}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(a=>a.type!=="tool-approval-response"||a.providerExecuted).map(a=>{switch(a.type){case"tool-result":return{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:MR(a.output),providerOptions:a.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:a.approvalId,approved:a.approved,reason:a.reason}}}),providerOptions:e.providerOptions};default:{let a=o;throw new IK({role:a})}}}s(VK,"convertToLanguageModelMessage");async function ZK(e,t,o){let a=e.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").map(i=>{var l;let u=(l=i.mediaType)!=null?l:i.type==="image"?"image/*":void 0,c=i.type==="image"?i.image:i.data;if(typeof c=="string")try{c=new URL(c)}catch{}return{mediaType:u,data:c}}).filter(i=>i.data instanceof URL).map(i=>({url:i.data,isUrlSupportedByModel:i.mediaType!=null&&jO({url:i.data.toString(),mediaType:i.mediaType,supportedUrls:o})})),n=await t(a);return Object.fromEntries(n.map((i,l)=>i==null?null:[a[l].url.toString(),{data:i.data,mediaType:i.mediaType}]).filter(i=>i!=null))}s(ZK,"downloadAssets");function HK(e,t){var o;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let a,n=e.type;switch(n){case"image":a=e.image;break;case"file":a=e.data;break;default:throw new Error(`Unsupported part type: ${n}`)}let{data:i,mediaType:l}=Hz(a),u=l??e.mediaType,c=i;if(c instanceof URL){let d=t[c.toString()];d&&(c=d.data,u??(u=d.mediaType))}switch(n){case"image":return(c instanceof Uint8Array||typeof c=="string")&&(u=(o=Jg({data:c,signatures:Hg}))!=null?o:u),{type:"file",mediaType:u??"image/*",filename:void 0,data:c,providerOptions:e.providerOptions};case"file":{if(u==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:u,filename:e.filename,data:c,providerOptions:e.providerOptions}}}}s(HK,"convertPartToLanguageModelPart");function MR(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}s(MR,"mapToolResultOutput");async function pp({toolCallId:e,input:t,output:o,tool:a,errorMode:n}){return n==="text"?{type:"error-text",value:vn(o)}:n==="json"?{type:"error-json",value:DR(o)}:a?.toModelOutput?await a.toModelOutput({toolCallId:e,input:t,output:o}):typeof o=="string"?{type:"text",value:o}:{type:"json",value:DR(o)}}s(pp,"createToolModelOutput");function DR(e){return e===void 0?null:e}s(DR,"toJSONValue");function G0({maxOutputTokens:e,temperature:t,topP:o,topK:a,presencePenalty:n,frequencyPenalty:i,seed:l,stopSequences:u}){if(e!=null){if(!Number.isInteger(e))throw new oa({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new oa({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new oa({parameter:"temperature",value:t,message:"temperature must be a number"});if(o!=null&&typeof o!="number")throw new oa({parameter:"topP",value:o,message:"topP must be a number"});if(a!=null&&typeof a!="number")throw new oa({parameter:"topK",value:a,message:"topK must be a number"});if(n!=null&&typeof n!="number")throw new oa({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(i!=null&&typeof i!="number")throw new oa({parameter:"frequencyPenalty",value:i,message:"frequencyPenalty must be a number"});if(l!=null&&!Number.isInteger(l))throw new oa({parameter:"seed",value:l,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:o,topK:a,presencePenalty:n,frequencyPenalty:i,stopSequences:u,seed:l}}s(G0,"prepareCallSettings");function JK(e){return e!=null&&Object.keys(e).length>0}s(JK,"isNonEmptyObject");async function Wz({tools:e,toolChoice:t,activeTools:o}){if(!JK(e))return{tools:void 0,toolChoice:void 0};let a=o!=null?Object.entries(e).filter(([i])=>o.includes(i)):Object.entries(e),n=[];for(let[i,l]of a){let u=l.type;switch(u){case void 0:case"dynamic":case"function":n.push({type:"function",name:i,description:l.description,inputSchema:await Qn(l.inputSchema).jsonSchema,...l.inputExamples!=null?{inputExamples:l.inputExamples}:{},providerOptions:l.providerOptions,...l.strict!=null?{strict:l.strict}:{}});break;case"provider":n.push({type:"provider",name:i,id:l.id,args:l.args});break;default:{let c=u;throw new Error(`Unsupported tool type: ${c}`)}}}return{tools:n,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}s(Wz,"prepareToolsAndToolChoice");var mp=r.lazy(()=>r.union([r.null(),r.string(),r.number(),r.boolean(),r.record(r.string(),mp.optional()),r.array(mp)])),ze=r.record(r.string(),r.record(r.string(),mp.optional())),Gz=r.object({type:r.literal("text"),text:r.string(),providerOptions:ze.optional()}),WK=r.object({type:r.literal("image"),image:r.union([Zz,r.instanceof(URL)]),mediaType:r.string().optional(),providerOptions:ze.optional()}),Kz=r.object({type:r.literal("file"),data:r.union([Zz,r.instanceof(URL)]),filename:r.string().optional(),mediaType:r.string(),providerOptions:ze.optional()}),GK=r.object({type:r.literal("reasoning"),text:r.string(),providerOptions:ze.optional()}),KK=r.object({type:r.literal("tool-call"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerOptions:ze.optional(),providerExecuted:r.boolean().optional()}),XK=r.discriminatedUnion("type",[r.object({type:r.literal("text"),value:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("json"),value:mp,providerOptions:ze.optional()}),r.object({type:r.literal("execution-denied"),reason:r.string().optional(),providerOptions:ze.optional()}),r.object({type:r.literal("error-text"),value:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("error-json"),value:mp,providerOptions:ze.optional()}),r.object({type:r.literal("content"),value:r.array(r.union([r.object({type:r.literal("text"),text:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("media"),data:r.string(),mediaType:r.string()}),r.object({type:r.literal("file-data"),data:r.string(),mediaType:r.string(),filename:r.string().optional(),providerOptions:ze.optional()}),r.object({type:r.literal("file-url"),url:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("file-id"),fileId:r.union([r.string(),r.record(r.string(),r.string())]),providerOptions:ze.optional()}),r.object({type:r.literal("image-data"),data:r.string(),mediaType:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("image-url"),url:r.string(),providerOptions:ze.optional()}),r.object({type:r.literal("image-file-id"),fileId:r.union([r.string(),r.record(r.string(),r.string())]),providerOptions:ze.optional()}),r.object({type:r.literal("custom"),providerOptions:ze.optional()})]))})]),Xz=r.object({type:r.literal("tool-result"),toolCallId:r.string(),toolName:r.string(),output:XK,providerOptions:ze.optional()}),YK=r.object({type:r.literal("tool-approval-request"),approvalId:r.string(),toolCallId:r.string()}),QK=r.object({type:r.literal("tool-approval-response"),approvalId:r.string(),approved:r.boolean(),reason:r.string().optional()}),e8=r.object({role:r.literal("system"),content:r.string(),providerOptions:ze.optional()}),t8=r.object({role:r.literal("user"),content:r.union([r.string(),r.array(r.union([Gz,WK,Kz]))]),providerOptions:ze.optional()}),r8=r.object({role:r.literal("assistant"),content:r.union([r.string(),r.array(r.union([Gz,Kz,GK,KK,Xz,YK]))]),providerOptions:ze.optional()}),o8=r.object({role:r.literal("tool"),content:r.array(r.union([Xz,QK])),providerOptions:ze.optional()}),n8=r.union([e8,t8,r8,o8]);async function Yz({allowSystemInMessages:e,system:t,prompt:o,messages:a}){if(o==null&&a==null)throw new vo({prompt:o,message:"prompt or messages must be defined"});if(o!=null&&a!=null)throw new vo({prompt:o,message:"prompt and messages cannot be defined at the same time"});if(typeof t!="string"&&!hs(t).every(i=>i.role==="system"))throw new vo({prompt:o,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});if(o!=null&&typeof o=="string")a=[{role:"user",content:o}];else if(o!=null&&Array.isArray(o))a=o;else if(a==null)throw new vo({prompt:o,message:"prompt or messages must be defined"});if(a.length===0)throw new vo({prompt:o,message:"messages must not be empty"});if(a.some(i=>i.role==="system")){if(e===!1)throw new vo({prompt:o,message:"System messages are not allowed in the prompt or messages fields. Use the system option instead."});e===void 0&&console.warn("AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.")}let n=await Br({value:a,schema:r.array(n8)});if(!n.success)throw new vo({prompt:o,message:"The messages do not match the ModelMessage[] schema.",cause:n.error});return{messages:a,system:t}}s(Yz,"standardizePrompt");function Qz(e){if(!jg.isInstance(e))return e;let t=(process==null?void 0:process.env.NODE_ENV)==="production",o="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new ge({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${o}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
81
81
 
82
82
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
83
83
 
@@ -85,12 +85,12 @@ Alternatively, you can use a provider module instead of the AI Gateway.
85
85
 
86
86
  Learn more: \x1B[34m${o}\x1B[0m
87
87
 
88
- `),{name:"GatewayAuthenticationError"})}s(Qz,"wrapGatewayError");function na({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}s(na,"assembleOperationName");function Gg({model:e,settings:t,telemetry:o,headers:a}){var n;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((i,[l,u])=>{if(l==="timeout"){let c=nT(u);c!=null&&(i[`ai.settings.${l}`]=c)}else i[`ai.settings.${l}`]=u;return i},{}),...Object.entries((n=o?.metadata)!=null?n:{}).reduce((i,[l,u])=>(i[`ai.telemetry.metadata.${l}`]=u,i),{}),...Object.entries(a??{}).reduce((i,[l,u])=>(u!==void 0&&(i[`ai.request.headers.${l}`]=u),i),{})}}s(Gg,"getBaseTelemetryAttributes");var aK={startSpan(){return Bg},startActiveSpan(e,t,o,a){if(typeof t=="function")return t(Bg);if(typeof o=="function")return o(Bg);if(typeof a=="function")return a(Bg)}},Bg={spanContext(){return iK},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},iK={traceId:"",spanId:"",traceFlags:0};function Kg({isEnabled:e=!1,tracer:t}={}){return e?t||H0.getTracer("ai"):aK}s(Kg,"getTracer");async function aa({name:e,tracer:t,attributes:o,fn:a,endWhenDone:n=!0}){return t.startActiveSpan(e,{attributes:await o},async i=>{let l=Fg.active();try{let u=await Fg.with(l,()=>a(i));return n&&i.end(),u}catch(u){try{eN(i,u)}finally{i.end()}throw u}})}s(aa,"recordSpan");function eN(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:ru.ERROR,message:t.message})):e.setStatus({code:ru.ERROR})}s(eN,"recordErrorOnSpan");async function sr({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};let o={};for(let[a,n]of Object.entries(t))if(n!=null){if(typeof n=="object"&&"input"in n&&typeof n.input=="function"){if(e?.recordInputs===!1)continue;let i=await n.input();i!=null&&(o[a]=i);continue}if(typeof n=="object"&&"output"in n&&typeof n.output=="function"){if(e?.recordOutputs===!1)continue;let i=await n.output();i!=null&&(o[a]=i);continue}o[a]=n}return o}s(sr,"selectTelemetryAttributes");function tN(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(o=>o.type==="file"?{...o,data:o.data instanceof Uint8Array?F8(o.data):o.data}:o)})))}s(tN,"stringifyForTelemetry");function sK(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}s(sK,"getGlobalTelemetryIntegrations");function rN(){let e=sK();return t=>{let o=hs(t),a=[...e,...o];function n(i){let l=a.map(i).filter(Boolean);return async u=>{for(let c of l)try{await c(u)}catch{}}}return s(n,"createTelemetryComposite"),{onStart:n(i=>i.onStart),onStepStart:n(i=>i.onStepStart),onToolCallStart:n(i=>i.onToolCallStart),onToolCallFinish:n(i=>i.onToolCallFinish),onStepFinish:n(i=>i.onStepFinish),onFinish:n(i=>i.onFinish)}}}s(rN,"getGlobalTelemetryIntegration");function K0(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:So(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}s(K0,"asLanguageModelUsage");function J0(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}s(J0,"createNullLanguageModelUsage");function oN(e,t){var o,a,n,i,l,u,c,d,p,m;return{inputTokens:So(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:So((o=e.inputTokenDetails)==null?void 0:o.noCacheTokens,(a=t.inputTokenDetails)==null?void 0:a.noCacheTokens),cacheReadTokens:So((n=e.inputTokenDetails)==null?void 0:n.cacheReadTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheReadTokens),cacheWriteTokens:So((l=e.inputTokenDetails)==null?void 0:l.cacheWriteTokens,(u=t.inputTokenDetails)==null?void 0:u.cacheWriteTokens)},outputTokens:So(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:So((c=e.outputTokenDetails)==null?void 0:c.textTokens,(d=t.outputTokenDetails)==null?void 0:d.textTokens),reasoningTokens:So((p=e.outputTokenDetails)==null?void 0:p.reasoningTokens,(m=t.outputTokenDetails)==null?void 0:m.reasoningTokens)},totalTokens:So(e.totalTokens,t.totalTokens),reasoningTokens:So(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:So(e.cachedInputTokens,t.cachedInputTokens)}}s(oN,"addLanguageModelUsage");function So(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}s(So,"addTokenCounts");function lK(e,t){return{inputTokens:So(e.inputTokens,t.inputTokens),outputTokens:So(e.outputTokens,t.outputTokens),totalTokens:So(e.totalTokens,t.totalTokens)}}s(lK,"addImageModelUsage");function Xg(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let o={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let n=t[a];if(n===void 0)continue;let i=a in e?e[a]:void 0,l=n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),u=i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp);l&&u?o[a]=Xg(i,n):o[a]=n}return o}s(Xg,"mergeObjects");function uK({error:e,exponentialBackoffDelay:t}){let o=e.responseHeaders;if(!o)return t;let a,n=o["retry-after-ms"];if(n){let l=parseFloat(n);Number.isNaN(l)||(a=l)}let i=o["retry-after"];if(i&&a===void 0){let l=parseFloat(i);Number.isNaN(l)?a=Date.parse(i)-Date.now():a=l*1e3}return a!=null&&!Number.isNaN(a)&&0<=a&&(a<60*1e3||a<t)?a:t}s(uK,"getRetryDelayInMs");var cK=s(({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:o=2,abortSignal:a}={})=>async n=>nN(n,{maxRetries:e,delayInMs:t,backoffFactor:o,abortSignal:a}),"retryWithExponentialBackoffRespectingRetryHeaders");async function nN(e,{maxRetries:t,delayInMs:o,backoffFactor:a,abortSignal:n},i=[]){try{return await e()}catch(l){if($a(l)||t===0)throw l;let u=Wl(l),c=[...i,l],d=c.length;if(d>t)throw new NR({message:`Failed after ${d} attempts. Last error: ${u}`,reason:"maxRetriesExceeded",errors:c});if(l instanceof Error&&_t.isInstance(l)&&l.isRetryable===!0&&d<=t)return await kg(uK({error:l,exponentialBackoffDelay:o}),{abortSignal:n}),nN(e,{maxRetries:t,delayInMs:a*o,backoffFactor:a,abortSignal:n},c);throw d===1?l:new NR({message:`Failed after ${d} attempts with non-retryable error: '${u}'`,reason:"errorNotRetryable",errors:c})}}s(nN,"_retryWithExponentialBackoff");function hp({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new oa({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new oa({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}let o=e??2;return{maxRetries:o,retry:cK({maxRetries:o,abortSignal:t})}}s(hp,"prepareRetries");function aN({messages:e}){let t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};let o={};for(let c of e)if(c.role==="assistant"&&typeof c.content!="string"){let d=c.content;for(let p of d)p.type==="tool-call"&&(o[p.toolCallId]=p)}let a={};for(let c of e)if(c.role==="assistant"&&typeof c.content!="string"){let d=c.content;for(let p of d)p.type==="tool-approval-request"&&(a[p.approvalId]=p)}let n={};for(let c of t.content)c.type==="tool-result"&&(n[c.toolCallId]=c);let i=[],l=[],u=t.content.filter(c=>c.type==="tool-approval-response");for(let c of u){let d=a[c.approvalId];if(d==null)throw new QG({approvalId:c.approvalId});if(n[d.toolCallId]!=null)continue;let p=o[d.toolCallId];if(p==null)throw new eT({toolCallId:d.toolCallId,approvalId:d.approvalId});let m={approvalRequest:d,approvalResponse:c,toolCall:p};c.approved?i.push(m):l.push(m)}return{approvedToolApprovals:i,deniedToolApprovals:l}}s(aN,"collectToolApprovals");function Vg(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}s(Vg,"now");async function aT({toolCall:e,tools:t,tracer:o,telemetry:a,messages:n,abortSignal:i,experimental_context:l,stepNumber:u,model:c,onPreliminaryToolResult:d,onToolCallStart:p,onToolCallFinish:m}){let{toolName:f,toolCallId:h,input:g}=e,y=t?.[f];if(y?.execute==null)return;let _={stepNumber:u,model:c,toolCall:e,messages:n,abortSignal:i,functionId:a?.functionId,metadata:a?.metadata,experimental_context:l};return aa({name:"ai.toolCall",attributes:sr({telemetry:a,attributes:{...na({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":f,"ai.toolCall.id":h,"ai.toolCall.args":{output:s(()=>JSON.stringify(g),"output")}}}),tracer:o,fn:s(async v=>{let x;await Pn({event:_,callbacks:p});let w=Vg();try{let P=BO({execute:y.execute.bind(y),input:g,options:{toolCallId:h,messages:n,abortSignal:i,experimental_context:l}});for await(let k of P)k.type==="preliminary"?d?.({...e,type:"tool-result",output:k.output,preliminary:!0}):x=k.output}catch(P){let k=Vg()-w;return await Pn({event:{..._,success:!1,error:P,durationMs:k},callbacks:m}),eN(v,P),{type:"tool-error",toolCallId:h,toolName:f,input:g,error:P,dynamic:y.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}let S=Vg()-w;await Pn({event:{..._,success:!0,output:x,durationMs:S},callbacks:m});try{v.setAttributes(await sr({telemetry:a,attributes:{"ai.toolCall.result":{output:s(()=>JSON.stringify(x),"output")}}}))}catch{}return{type:"tool-result",toolCallId:h,toolName:f,input:g,output:x,dynamic:y.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}},"fn")})}s(aT,"executeToolCall");function UR(e){let t=e.filter(o=>o.type==="reasoning");return t.length===0?void 0:t.map(o=>o.text).join(`
89
- `)}s(UR,"extractReasoningContent");function LR(e){let t=e.filter(o=>o.type==="text");if(t.length!==0)return t.map(o=>o.text).join("")}s(LR,"extractTextContent");var iT=class{static{s(this,"DefaultGeneratedFile")}constructor({data:e,mediaType:t}){let o=e instanceof Uint8Array;this.base64Data=o?void 0:e,this.uint8ArrayData=o?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=tn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Yt(this.base64Data)),this.uint8ArrayData}},dK=class extends iT{static{s(this,"DefaultGeneratedFileWithType")}constructor(e){super(e),this.type="file"}};async function iN({tool:e,toolCall:t,messages:o,experimental_context:a}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:o,experimental_context:a})}s(iN,"isApprovalNeeded");var pK={};HG(pK,{array:s(()=>hK,"array"),choice:s(()=>gK,"choice"),json:s(()=>yK,"json"),object:s(()=>fK,"object"),text:s(()=>Wg,"text")});function mK(e){let t=["ROOT"],o=-1,a=null;function n(c,d,p){switch(c){case'"':{o=d,t.pop(),t.push(p),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{o=d,a=d,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{o=d,t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"{":{o=d,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START");break}case"[":{o=d,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START");break}}}s(n,"processValueStart");function i(c,d){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{o=d,t.pop();break}}}s(i,"processAfterObjectValue");function l(c,d){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{o=d,t.pop();break}}}s(l,"processAfterArrayValue");for(let c=0;c<e.length;c++){let d=e[c];switch(t[t.length-1]){case"ROOT":n(d,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(d){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{o=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{d==='"'&&(t.pop(),t.push("INSIDE_OBJECT_KEY"));break}case"INSIDE_OBJECT_KEY":{d==='"'&&(t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY"));break}case"INSIDE_OBJECT_AFTER_KEY":{d===":"&&(t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE"));break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(d,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(d,c);break}case"INSIDE_STRING":{switch(d){case'"':{t.pop(),o=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:o=c}break}case"INSIDE_ARRAY_START":{d==="]"?(o=c,t.pop()):(o=c,n(d,c,"INSIDE_ARRAY_AFTER_VALUE"));break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(d){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{o=c,t.pop();break}default:{o=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(d,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),o=c;break}case"INSIDE_NUMBER":{switch(d){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{o=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(d,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(d,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(d,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(d,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{let m=e.substring(a,c+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(d,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(d,c)):o=c;break}}}let u=e.slice(0,o+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{u+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{u+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{u+="]";break}case"INSIDE_LITERAL":{let p=e.substring(a,e.length);"true".startsWith(p)?u+="true".slice(p.length):"false".startsWith(p)?u+="false".slice(p.length):"null".startsWith(p)&&(u+="null".slice(p.length))}}return u}s(mK,"fixJson");async function gp(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await xo({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await xo({text:mK(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}s(gp,"parsePartialJson");var Wg=s(()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),"text"),fK=s(({schema:e,name:t,description:o})=>{let a=Qn(e);return{name:"object",responseFormat:st(a.jsonSchema).then(n=>({type:"json",schema:n,...t!=null&&{name:t},...o!=null&&{description:o}})),async parseCompleteOutput({text:n},i){let l=await xo({text:n});if(!l.success)throw new Ti({message:"No object generated: could not parse the response.",cause:l.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});let u=await Br({value:l.value,schema:a});if(!u.success)throw new Ti({message:"No object generated: response did not match schema.",cause:u.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});return u.value},async parsePartialOutput({text:n}){let i=await gp(n);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:i.value}}},createElementStreamTransform(){}}},"object"),hK=s(({element:e,name:t,description:o})=>{let a=Qn(e);return{name:"array",responseFormat:st(a.jsonSchema).then(n=>{let{$schema:i,...l}=n;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:l}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...o!=null&&{description:o}}}),async parseCompleteOutput({text:n},i){let l=await xo({text:n});if(!l.success)throw new Ti({message:"No object generated: could not parse the response.",cause:l.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});let u=l.value;if(u==null||typeof u!="object"||!("elements"in u)||!Array.isArray(u.elements))throw new Ti({message:"No object generated: response did not match schema.",cause:new xn({value:u,cause:"response must be an object with an elements array"}),text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});for(let c of u.elements){let d=await Br({value:c,schema:a});if(!d.success)throw new Ti({message:"No object generated: response did not match schema.",cause:d.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason})}return u.elements},async parsePartialOutput({text:n}){let i=await gp(n);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let l=i.value;if(l==null||typeof l!="object"||!("elements"in l)||!Array.isArray(l.elements))return;let u=i.state==="repaired-parse"&&l.elements.length>0?l.elements.slice(0,-1):l.elements,c=[];for(let d of u){let p=await Br({value:d,schema:a});p.success&&c.push(p.value)}return{partial:c}}}},createElementStreamTransform(){let n=0;return new TransformStream({transform({partialOutput:i},l){if(i!=null)for(;n<i.length;n++)l.enqueue(i[n])}})}}},"array"),gK=s(({options:e,name:t,description:o})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...o!=null&&{description:o}}),async parseCompleteOutput({text:a},n){let i=await xo({text:a});if(!i.success)throw new Ti({message:"No object generated: could not parse the response.",cause:i.error,text:a,response:n.response,usage:n.usage,finishReason:n.finishReason});let l=i.value;if(l==null||typeof l!="object"||!("result"in l)||typeof l.result!="string"||!e.includes(l.result))throw new Ti({message:"No object generated: response did not match schema.",cause:new xn({value:l,cause:"response must be an object that contains a choice value."}),text:a,response:n.response,usage:n.usage,finishReason:n.finishReason});return l.result},async parsePartialOutput({text:a}){let n=await gp(a);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let i=n.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string")return;let l=e.filter(u=>u.startsWith(i.result));return n.state==="successful-parse"?l.includes(i.result)?{partial:i.result}:void 0:l.length===1?{partial:l[0]}:void 0}}},createElementStreamTransform(){}}),"choice"),yK=s(({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:o},a){let n=await xo({text:o});if(!n.success)throw new Ti({message:"No object generated: could not parse the response.",cause:n.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});return n.value},async parsePartialOutput({text:o}){let a=await gp(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return a.value===void 0?void 0:{partial:a.value}}},createElementStreamTransform(){}}),"json");async function sN({toolCall:e,tools:t,repairToolCall:o,system:a,messages:n}){var i;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await lN(e);throw new W0({toolName:e.toolName})}try{return await qR({toolCall:e,tools:t})}catch(l){if(o==null||!(W0.isInstance(l)||Q0.isInstance(l)))throw l;let u=null;try{u=await o({toolCall:e,tools:t,inputSchema:s(async({toolName:c})=>{let{inputSchema:d}=t[c];return await Qn(d).jsonSchema},"inputSchema"),system:a,messages:n,error:l})}catch(c){throw new x8({cause:c,originalError:l})}if(u==null)throw l;return await qR({toolCall:u,tools:t})}}catch(l){let u=await xo({text:e.input}),c=u.success?u.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:c,dynamic:!0,invalid:!0,error:l,title:(i=t?.[e.toolName])==null?void 0:i.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}s(sN,"parseToolCall");async function lN(e){let t=e.input.trim()===""?{success:!0,value:{}}:await xo({text:e.input});if(t.success===!1)throw new Q0({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}s(lN,"parseProviderExecutedDynamicToolCall");async function qR({toolCall:e,tools:t}){let o=e.toolName,a=t[o];if(a==null){if(e.providerExecuted&&e.dynamic)return await lN(e);throw new W0({toolName:e.toolName,availableTools:Object.keys(t)})}let n=Qn(a.inputSchema),i=e.input.trim()===""?await Br({value:{},schema:n}):await xo({text:e.input,schema:n});if(i.success===!1)throw new Q0({toolName:o,toolInput:e.input,cause:i.error});return a.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:a.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:o,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:a.title}}s(qR,"doParseToolCall");var uN=class{static{s(this,"DefaultStepResult")}constructor({stepNumber:e,model:t,functionId:o,metadata:a,experimental_context:n,content:i,finishReason:l,rawFinishReason:u,usage:c,warnings:d,request:p,response:m,providerMetadata:f}){this.stepNumber=e,this.model=t,this.functionId=o,this.metadata=a,this.experimental_context=n,this.content=i,this.finishReason=l,this.rawFinishReason=u,this.usage=c,this.warnings=d,this.request=p,this.response=m,this.providerMetadata=f}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function nu(e){return({steps:t})=>t.length===e}s(nu,"stepCountIs");function cN(e){return({steps:t})=>{var o,a,n;return(n=(a=(o=t[t.length-1])==null?void 0:o.toolCalls)==null?void 0:a.some(i=>i.toolName===e))!=null?n:!1}}s(cN,"hasToolCall");async function dN({stopConditions:e,steps:t}){return(await Promise.all(e.map(o=>o({steps:t})))).some(o=>o)}s(dN,"isStopConditionMet");async function X0({content:e,tools:t}){let o=[],a=[];for(let i of e)if(i.type!=="source"&&!((i.type==="tool-result"||i.type==="tool-error")&&!i.providerExecuted)&&!(i.type==="text"&&i.text.length===0))switch(i.type){case"text":a.push({type:"text",text:i.text,providerOptions:i.providerMetadata});break;case"reasoning":a.push({type:"reasoning",text:i.text,providerOptions:i.providerMetadata});break;case"file":a.push({type:"file",data:i.file.base64,mediaType:i.file.mediaType,providerOptions:i.providerMetadata});break;case"tool-call":a.push({type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.invalid&&typeof i.input!="object"?{}:i.input,providerExecuted:i.providerExecuted,providerOptions:i.providerMetadata});break;case"tool-result":{let l=await pp({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.output,errorMode:"none"});a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:l,providerOptions:i.providerMetadata});break}case"tool-error":{let l=await pp({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.error,errorMode:"json"});a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:l,providerOptions:i.providerMetadata});break}case"tool-approval-request":a.push({type:"tool-approval-request",approvalId:i.approvalId,toolCallId:i.toolCall.toolCallId});break}a.length>0&&o.push({role:"assistant",content:a});let n=[];for(let i of e){if(!(i.type==="tool-result"||i.type==="tool-error")||i.providerExecuted)continue;let l=await pp({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.type==="tool-result"?i.output:i.error,errorMode:i.type==="tool-error"?"text":"none"});n.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:l,...i.providerMetadata!=null?{providerOptions:i.providerMetadata}:{}})}return n.length>0&&o.push({role:"tool",content:n}),o}s(X0,"toResponseMessages");function pN(...e){let t=e.filter(a=>a!=null);if(t.length===0)return;if(t.length===1)return t[0];let o=new AbortController;for(let a of t){if(a.aborted)return o.abort(a.reason),o.signal;a.addEventListener("abort",()=>{o.abort(a.reason)},{once:!0})}return o.signal}s(pN,"mergeAbortSignals");var _K=Xn({prefix:"aitxt",size:24});async function ia({model:e,tools:t,toolChoice:o,system:a,prompt:n,messages:i,allowSystemInMessages:l,maxRetries:u,abortSignal:c,timeout:d,headers:p,stopWhen:m=nu(1),experimental_output:f,output:h=f,experimental_telemetry:g,providerOptions:y,experimental_activeTools:_,activeTools:v=_,experimental_prepareStep:x,prepareStep:w=x,experimental_repairToolCall:S,experimental_download:P,experimental_context:k,experimental_include:I,_internal:{generateId:E=_K}={},experimental_onStart:b,experimental_onStepStart:M,experimental_onToolCallStart:R,experimental_onToolCallFinish:D,onStepFinish:te,onFinish:ee,...J}){let W=Zg(e),j=rN(),O=hs(m),Z=nT(d),F=Fz(d),z=F!=null?new AbortController:void 0,Y=pN(c,Z!=null?AbortSignal.timeout(Z):void 0,z?.signal),{maxRetries:ae,retry:K}=hp({maxRetries:u,abortSignal:Y}),he=G0(J),L=Qt(p??{},`ai/${fp}`),le=Gg({model:W,telemetry:g,headers:L,settings:{...he,maxRetries:ae}}),oe={provider:W.provider,modelId:W.modelId},ne=await Yz({system:a,prompt:n,messages:i,allowSystemInMessages:l}),C=j(g?.integrations);await Pn({event:{model:oe,system:a,prompt:n,messages:i,tools:t,toolChoice:o,activeTools:v,maxOutputTokens:he.maxOutputTokens,temperature:he.temperature,topP:he.topP,topK:he.topK,presencePenalty:he.presencePenalty,frequencyPenalty:he.frequencyPenalty,stopSequences:he.stopSequences,seed:he.seed,maxRetries:ae,timeout:d,headers:p,providerOptions:y,stopWhen:m,output:h,abortSignal:c,include:I,functionId:g?.functionId,metadata:g?.metadata,experimental_context:k},callbacks:[b,C.onStart]});let G=Kg(g);try{return await aa({name:"ai.generateText",attributes:sr({telemetry:g,attributes:{...na({operationId:"ai.generateText",telemetry:g}),...le,"ai.model.provider":W.provider,"ai.model.id":W.modelId,"ai.prompt":{input:s(()=>JSON.stringify({system:a,prompt:n,messages:i}),"input")}}}),tracer:G,fn:s(async X=>{var q,Me,fe,at,rr,Tr,gr,Ho,Mr,De,Wr,dn,Bn,Oo,Kt,T,B,Ee,He,Rt;let lr=ne.messages,br=[],{approvedToolApprovals:$o,deniedToolApprovals:pn}=aN({messages:lr}),Jo=$o.filter(Er=>!Er.toolCall.providerExecuted);if(pn.length>0||Jo.length>0){let Er=await FR({toolCalls:Jo.map(ut=>ut.toolCall),tools:t,tracer:G,telemetry:g,messages:lr,abortSignal:Y,experimental_context:k,stepNumber:0,model:oe,onToolCallStart:[R,C.onToolCallStart],onToolCallFinish:[D,C.onToolCallFinish]}),Ur=[];for(let ut of Er){let co=await pp({toolCallId:ut.toolCallId,input:ut.input,tool:t?.[ut.toolName],output:ut.type==="tool-result"?ut.output:ut.error,errorMode:ut.type==="tool-error"?"text":"none"});Ur.push({type:"tool-result",toolCallId:ut.toolCallId,toolName:ut.toolName,output:co})}for(let ut of pn)Ur.push({type:"tool-result",toolCallId:ut.toolCall.toolCallId,toolName:ut.toolCall.toolName,output:{type:"execution-denied",reason:ut.approvalResponse.reason,...ut.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:ut.approvalResponse.approvalId}}}}});br.push({role:"tool",content:Ur})}let be=G0(J),Ve,yr=[],ur=[],je=[],Dr=new Map;do{let Er=F!=null?setTimeout(()=>z.abort(),F):void 0;try{let Ur=[...lr,...br],ut=await w?.({model:W,steps:je,stepNumber:je.length,messages:Ur,experimental_context:k}),co=Zg((q=ut?.model)!=null?q:W),Ha={provider:co.provider,modelId:co.modelId},Nu=await Jz({prompt:{system:(Me=ut?.system)!=null?Me:ne.system,messages:(fe=ut?.messages)!=null?fe:Ur},supportedUrls:await co.supportedUrls,download:P});k=(at=ut?.experimental_context)!=null?at:k;let ga=(rr=ut?.activeTools)!=null?rr:v,{toolChoice:qs,tools:Fs}=await Wz({tools:t,toolChoice:(Tr=ut?.toolChoice)!=null?Tr:o,activeTools:ga}),Am=(gr=ut?.messages)!=null?gr:Ur,Ja=(Ho=ut?.system)!=null?Ho:ne.system,pr=Xg(y,ut?.providerOptions);await Pn({event:{stepNumber:je.length,model:Ha,system:Ja,messages:Am,tools:t,toolChoice:qs,activeTools:ga,steps:[...je],providerOptions:pr,timeout:d,headers:p,stopWhen:m,output:h,abortSignal:c,include:I,functionId:g?.functionId,metadata:g?.metadata,experimental_context:k},callbacks:[M,C.onStepStart]}),Ve=await K(()=>{var ct;return aa({name:"ai.generateText.doGenerate",attributes:sr({telemetry:g,attributes:{...na({operationId:"ai.generateText.doGenerate",telemetry:g}),...le,"ai.model.provider":co.provider,"ai.model.id":co.modelId,"ai.prompt.messages":{input:s(()=>tN(Nu),"input")},"ai.prompt.tools":{input:s(()=>Fs?.map(Gr=>JSON.stringify(Gr)),"input")},"ai.prompt.toolChoice":{input:s(()=>qs!=null?JSON.stringify(qs):void 0,"input")},"gen_ai.system":co.provider,"gen_ai.request.model":co.modelId,"gen_ai.request.frequency_penalty":J.frequencyPenalty,"gen_ai.request.max_tokens":J.maxOutputTokens,"gen_ai.request.presence_penalty":J.presencePenalty,"gen_ai.request.stop_sequences":J.stopSequences,"gen_ai.request.temperature":(ct=J.temperature)!=null?ct:void 0,"gen_ai.request.top_k":J.topK,"gen_ai.request.top_p":J.topP}}),tracer:G,fn:s(async Gr=>{var Zs,ya,Vn,Du,$m,Rm,Wa,Ga;let Lt=await co.doGenerate({...be,tools:Fs,toolChoice:qs,responseFormat:await h?.responseFormat,prompt:Nu,providerOptions:pr,abortSignal:Y,headers:L}),Zn={id:(ya=(Zs=Lt.response)==null?void 0:Zs.id)!=null?ya:E(),timestamp:(Du=(Vn=Lt.response)==null?void 0:Vn.timestamp)!=null?Du:new Date,modelId:(Rm=($m=Lt.response)==null?void 0:$m.modelId)!=null?Rm:co.modelId,headers:(Wa=Lt.response)==null?void 0:Wa.headers,body:(Ga=Lt.response)==null?void 0:Ga.body},Ka=K0(Lt.usage);return Gr.setAttributes(await sr({telemetry:g,attributes:{"ai.response.finishReason":Lt.finishReason.unified,"ai.response.text":{output:s(()=>LR(Lt.content),"output")},"ai.response.reasoning":{output:s(()=>UR(Lt.content),"output")},"ai.response.toolCalls":{output:s(()=>{let Hs=BR(Lt.content);return Hs==null?void 0:JSON.stringify(Hs)},"output")},"ai.response.id":Zn.id,"ai.response.model":Zn.modelId,"ai.response.timestamp":Zn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Lt.providerMetadata),"ai.usage.inputTokens":Lt.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":Lt.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":Lt.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":Lt.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":Lt.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":Lt.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":Lt.usage.outputTokens.reasoning,"ai.usage.totalTokens":Ka.totalTokens,"ai.usage.reasoningTokens":Lt.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":Lt.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[Lt.finishReason.unified],"gen_ai.response.id":Zn.id,"gen_ai.response.model":Zn.modelId,"gen_ai.usage.input_tokens":Lt.usage.inputTokens.total,"gen_ai.usage.output_tokens":Lt.usage.outputTokens.total}})),{...Lt,response:Zn}},"fn")})});let po=await Promise.all(Ve.content.filter(ct=>ct.type==="tool-call").map(ct=>sN({toolCall:ct,tools:t,repairToolCall:S,system:a,messages:Ur}))),Bs={};for(let ct of po){if(ct.invalid)continue;let Gr=t?.[ct.toolName];Gr!=null&&(Gr?.onInputAvailable!=null&&await Gr.onInputAvailable({input:ct.input,toolCallId:ct.toolCallId,messages:Ur,abortSignal:Y,experimental_context:k}),await iN({tool:Gr,toolCall:ct,messages:Ur,experimental_context:k})&&(Bs[ct.toolCallId]={type:"tool-approval-request",approvalId:E(),toolCall:ct}))}let Cm=po.filter(ct=>ct.invalid&&ct.dynamic);ur=[];for(let ct of Cm)ur.push({type:"tool-error",toolCallId:ct.toolCallId,toolName:ct.toolName,input:ct.input,error:Wl(ct.error),dynamic:!0});yr=po.filter(ct=>!ct.providerExecuted),t!=null&&ur.push(...await FR({toolCalls:yr.filter(ct=>!ct.invalid&&Bs[ct.toolCallId]==null),tools:t,tracer:G,telemetry:g,messages:Ur,abortSignal:Y,experimental_context:k,stepNumber:je.length,model:Ha,onToolCallStart:[R,C.onToolCallStart],onToolCallFinish:[D,C.onToolCallFinish]}));for(let ct of po){if(!ct.providerExecuted)continue;let Gr=t?.[ct.toolName];Gr?.type==="provider"&&Gr.supportsDeferredResults&&(Ve.content.some(ya=>ya.type==="tool-result"&&ya.toolCallId===ct.toolCallId)||Dr.set(ct.toolCallId,{toolName:ct.toolName}))}for(let ct of Ve.content)ct.type==="tool-result"&&Dr.delete(ct.toolCallId);let ju=bK({content:Ve.content,toolCalls:po,toolOutputs:ur,toolApprovalRequests:Object.values(Bs),tools:t});br.push(...await X0({content:ju,tools:t}));let Vs=(Mr=I?.requestBody)==null||Mr?(De=Ve.request)!=null?De:{}:{...Ve.request,body:void 0},Mu={...Ve.response,messages:structuredClone(br),body:(Wr=I?.responseBody)==null||Wr?(dn=Ve.response)==null?void 0:dn.body:void 0},q_=je.length,Om=new uN({stepNumber:q_,model:Ha,functionId:g?.functionId,metadata:g?.metadata,experimental_context:k,content:ju,finishReason:Ve.finishReason.unified,rawFinishReason:Ve.finishReason.raw,usage:K0(Ve.usage),warnings:Ve.warnings,providerMetadata:Ve.providerMetadata,request:Vs,response:Mu});gs({warnings:(Bn=Ve.warnings)!=null?Bn:[],provider:Ha.provider,model:Ha.modelId}),je.push(Om),await Pn({event:Om,callbacks:[te,C.onStepFinish]})}finally{Er!=null&&clearTimeout(Er)}}while((yr.length>0&&ur.length===yr.length||Dr.size>0)&&!await dN({stopConditions:O,steps:je}));X.setAttributes(await sr({telemetry:g,attributes:{"ai.response.finishReason":Ve.finishReason.unified,"ai.response.text":{output:s(()=>LR(Ve.content),"output")},"ai.response.reasoning":{output:s(()=>UR(Ve.content),"output")},"ai.response.toolCalls":{output:s(()=>{let Er=BR(Ve.content);return Er==null?void 0:JSON.stringify(Er)},"output")},"ai.response.providerMetadata":JSON.stringify(Ve.providerMetadata)}}));let Xe=je[je.length-1],or=je.reduce((Er,Ur)=>oN(Er,Ur.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});X.setAttributes(await sr({telemetry:g,attributes:{"ai.usage.inputTokens":or.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Oo=or.inputTokenDetails)==null?void 0:Oo.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Kt=or.inputTokenDetails)==null?void 0:Kt.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(T=or.inputTokenDetails)==null?void 0:T.cacheWriteTokens,"ai.usage.outputTokens":or.outputTokens,"ai.usage.outputTokenDetails.textTokens":(B=or.outputTokenDetails)==null?void 0:B.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Ee=or.outputTokenDetails)==null?void 0:Ee.reasoningTokens,"ai.usage.totalTokens":or.totalTokens,"ai.usage.reasoningTokens":(He=or.outputTokenDetails)==null?void 0:He.reasoningTokens,"ai.usage.cachedInputTokens":(Rt=or.inputTokenDetails)==null?void 0:Rt.cacheReadTokens}})),await Pn({event:{stepNumber:Xe.stepNumber,model:Xe.model,functionId:Xe.functionId,metadata:Xe.metadata,experimental_context:Xe.experimental_context,finishReason:Xe.finishReason,rawFinishReason:Xe.rawFinishReason,usage:Xe.usage,content:Xe.content,text:Xe.text,reasoningText:Xe.reasoningText,reasoning:Xe.reasoning,files:Xe.files,sources:Xe.sources,toolCalls:Xe.toolCalls,staticToolCalls:Xe.staticToolCalls,dynamicToolCalls:Xe.dynamicToolCalls,toolResults:Xe.toolResults,staticToolResults:Xe.staticToolResults,dynamicToolResults:Xe.dynamicToolResults,request:Xe.request,response:Xe.response,warnings:Xe.warnings,providerMetadata:Xe.providerMetadata,steps:je,totalUsage:or},callbacks:[ee,C.onFinish]});let nr;return Xe.finishReason==="stop"&&(nr=await(h??Wg()).parseCompleteOutput({text:Xe.text},{response:Xe.response,usage:Xe.usage,finishReason:Xe.finishReason})),new vK({steps:je,totalUsage:or,output:nr})},"fn")})}catch(X){throw Qz(X)}}s(ia,"generateText");async function FR({toolCalls:e,tools:t,tracer:o,telemetry:a,messages:n,abortSignal:i,experimental_context:l,stepNumber:u,model:c,onToolCallStart:d,onToolCallFinish:p}){return(await Promise.all(e.map(async f=>aT({toolCall:f,tools:t,tracer:o,telemetry:a,messages:n,abortSignal:i,experimental_context:l,stepNumber:u,model:c,onToolCallStart:d,onToolCallFinish:p})))).filter(f=>f!=null)}s(FR,"executeTools");var vK=class{static{s(this,"DefaultGenerateTextResult")}constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new bz;return this._output}};function BR(e){let t=e.filter(o=>o.type==="tool-call");if(t.length!==0)return t.map(o=>({toolCallId:o.toolCallId,toolName:o.toolName,input:o.input}))}s(BR,"asToolCalls");function bK({content:e,toolCalls:t,toolOutputs:o,toolApprovalRequests:a,tools:n}){let i=[];for(let l of e)switch(l.type){case"text":case"reasoning":case"source":i.push(l);break;case"file":{i.push({type:"file",file:new iT(l),...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}});break}case"tool-call":{i.push(t.find(u=>u.toolCallId===l.toolCallId));break}case"tool-result":{let u=t.find(c=>c.toolCallId===l.toolCallId);if(u==null){let c=n?.[l.toolName];if(!(c?.type==="provider"&&c.supportsDeferredResults))throw new Error(`Tool call ${l.toolCallId} not found.`);l.isError?i.push({type:"tool-error",toolCallId:l.toolCallId,toolName:l.toolName,input:void 0,error:l.result,providerExecuted:!0,dynamic:l.dynamic,...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}}):i.push({type:"tool-result",toolCallId:l.toolCallId,toolName:l.toolName,input:void 0,output:l.result,providerExecuted:!0,dynamic:l.dynamic,...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}});break}l.isError?i.push({type:"tool-error",toolCallId:l.toolCallId,toolName:l.toolName,input:u.input,error:l.result,providerExecuted:!0,dynamic:u.dynamic,...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}}):i.push({type:"tool-result",toolCallId:l.toolCallId,toolName:l.toolName,input:u.input,output:l.result,providerExecuted:!0,dynamic:u.dynamic,...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}});break}case"tool-approval-request":{let u=t.find(c=>c.toolCallId===l.toolCallId);if(u==null)throw new eT({toolCallId:l.toolCallId,approvalId:l.approvalId});i.push({type:"tool-approval-request",approvalId:l.approvalId,toolCall:u});break}}return[...i,...o,...a]}s(bK,"asContent");function Yg(e,t){let o=new Headers(e??{});for(let[a,n]of Object.entries(t))o.has(a)||o.set(a,n);return o}s(Yg,"prepareHeaders");function xK({status:e,statusText:t,headers:o,textStream:a}){return new Response(a.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Yg(o,{"content-type":"text/plain; charset=utf-8"})})}s(xK,"createTextStreamResponse");function mN({response:e,status:t,statusText:o,headers:a,stream:n}){let i=t??200;o!==void 0?e.writeHead(i,o,a):e.writeHead(i,a);let l=n.getReader();s(async()=>{try{for(;;){let{done:c,value:d}=await l.read();if(c)break;e.write(d)||await new Promise(m=>{e.once("drain",m)})}}catch(c){throw c}finally{e.end()}},"read")()}s(mN,"writeToServerResponse");function wK({response:e,status:t,statusText:o,headers:a,textStream:n}){mN({response:e,status:t,statusText:o,headers:Object.fromEntries(Yg(a,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})}s(wK,"pipeTextStreamToResponse");var fN=class extends TransformStream{static{s(this,"JsonToSseTransformStream")}constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
88
+ `),{name:"GatewayAuthenticationError"})}s(Qz,"wrapGatewayError");function na({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}s(na,"assembleOperationName");function Gg({model:e,settings:t,telemetry:o,headers:a}){var n;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((i,[l,u])=>{if(l==="timeout"){let c=nT(u);c!=null&&(i[`ai.settings.${l}`]=c)}else i[`ai.settings.${l}`]=u;return i},{}),...Object.entries((n=o?.metadata)!=null?n:{}).reduce((i,[l,u])=>(i[`ai.telemetry.metadata.${l}`]=u,i),{}),...Object.entries(a??{}).reduce((i,[l,u])=>(u!==void 0&&(i[`ai.request.headers.${l}`]=u),i),{})}}s(Gg,"getBaseTelemetryAttributes");var a8={startSpan(){return Bg},startActiveSpan(e,t,o,a){if(typeof t=="function")return t(Bg);if(typeof o=="function")return o(Bg);if(typeof a=="function")return a(Bg)}},Bg={spanContext(){return i8},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},i8={traceId:"",spanId:"",traceFlags:0};function Kg({isEnabled:e=!1,tracer:t}={}){return e?t||H0.getTracer("ai"):a8}s(Kg,"getTracer");async function aa({name:e,tracer:t,attributes:o,fn:a,endWhenDone:n=!0}){return t.startActiveSpan(e,{attributes:await o},async i=>{let l=Fg.active();try{let u=await Fg.with(l,()=>a(i));return n&&i.end(),u}catch(u){try{eN(i,u)}finally{i.end()}throw u}})}s(aa,"recordSpan");function eN(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:ru.ERROR,message:t.message})):e.setStatus({code:ru.ERROR})}s(eN,"recordErrorOnSpan");async function sr({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};let o={};for(let[a,n]of Object.entries(t))if(n!=null){if(typeof n=="object"&&"input"in n&&typeof n.input=="function"){if(e?.recordInputs===!1)continue;let i=await n.input();i!=null&&(o[a]=i);continue}if(typeof n=="object"&&"output"in n&&typeof n.output=="function"){if(e?.recordOutputs===!1)continue;let i=await n.output();i!=null&&(o[a]=i);continue}o[a]=n}return o}s(sr,"selectTelemetryAttributes");function tN(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(o=>o.type==="file"?{...o,data:o.data instanceof Uint8Array?FK(o.data):o.data}:o)})))}s(tN,"stringifyForTelemetry");function s8(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}s(s8,"getGlobalTelemetryIntegrations");function rN(){let e=s8();return t=>{let o=hs(t),a=[...e,...o];function n(i){let l=a.map(i).filter(Boolean);return async u=>{for(let c of l)try{await c(u)}catch{}}}return s(n,"createTelemetryComposite"),{onStart:n(i=>i.onStart),onStepStart:n(i=>i.onStepStart),onToolCallStart:n(i=>i.onToolCallStart),onToolCallFinish:n(i=>i.onToolCallFinish),onStepFinish:n(i=>i.onStepFinish),onFinish:n(i=>i.onFinish)}}}s(rN,"getGlobalTelemetryIntegration");function K0(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:So(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}s(K0,"asLanguageModelUsage");function J0(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}s(J0,"createNullLanguageModelUsage");function oN(e,t){var o,a,n,i,l,u,c,d,p,m;return{inputTokens:So(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:So((o=e.inputTokenDetails)==null?void 0:o.noCacheTokens,(a=t.inputTokenDetails)==null?void 0:a.noCacheTokens),cacheReadTokens:So((n=e.inputTokenDetails)==null?void 0:n.cacheReadTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheReadTokens),cacheWriteTokens:So((l=e.inputTokenDetails)==null?void 0:l.cacheWriteTokens,(u=t.inputTokenDetails)==null?void 0:u.cacheWriteTokens)},outputTokens:So(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:So((c=e.outputTokenDetails)==null?void 0:c.textTokens,(d=t.outputTokenDetails)==null?void 0:d.textTokens),reasoningTokens:So((p=e.outputTokenDetails)==null?void 0:p.reasoningTokens,(m=t.outputTokenDetails)==null?void 0:m.reasoningTokens)},totalTokens:So(e.totalTokens,t.totalTokens),reasoningTokens:So(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:So(e.cachedInputTokens,t.cachedInputTokens)}}s(oN,"addLanguageModelUsage");function So(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}s(So,"addTokenCounts");function l8(e,t){return{inputTokens:So(e.inputTokens,t.inputTokens),outputTokens:So(e.outputTokens,t.outputTokens),totalTokens:So(e.totalTokens,t.totalTokens)}}s(l8,"addImageModelUsage");function Xg(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let o={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let n=t[a];if(n===void 0)continue;let i=a in e?e[a]:void 0,l=n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),u=i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp);l&&u?o[a]=Xg(i,n):o[a]=n}return o}s(Xg,"mergeObjects");function u8({error:e,exponentialBackoffDelay:t}){let o=e.responseHeaders;if(!o)return t;let a,n=o["retry-after-ms"];if(n){let l=parseFloat(n);Number.isNaN(l)||(a=l)}let i=o["retry-after"];if(i&&a===void 0){let l=parseFloat(i);Number.isNaN(l)?a=Date.parse(i)-Date.now():a=l*1e3}return a!=null&&!Number.isNaN(a)&&0<=a&&(a<60*1e3||a<t)?a:t}s(u8,"getRetryDelayInMs");var c8=s(({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:o=2,abortSignal:a}={})=>async n=>nN(n,{maxRetries:e,delayInMs:t,backoffFactor:o,abortSignal:a}),"retryWithExponentialBackoffRespectingRetryHeaders");async function nN(e,{maxRetries:t,delayInMs:o,backoffFactor:a,abortSignal:n},i=[]){try{return await e()}catch(l){if($a(l)||t===0)throw l;let u=Wl(l),c=[...i,l],d=c.length;if(d>t)throw new NR({message:`Failed after ${d} attempts. Last error: ${u}`,reason:"maxRetriesExceeded",errors:c});if(l instanceof Error&&_t.isInstance(l)&&l.isRetryable===!0&&d<=t)return await kg(u8({error:l,exponentialBackoffDelay:o}),{abortSignal:n}),nN(e,{maxRetries:t,delayInMs:a*o,backoffFactor:a,abortSignal:n},c);throw d===1?l:new NR({message:`Failed after ${d} attempts with non-retryable error: '${u}'`,reason:"errorNotRetryable",errors:c})}}s(nN,"_retryWithExponentialBackoff");function hp({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new oa({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new oa({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}let o=e??2;return{maxRetries:o,retry:c8({maxRetries:o,abortSignal:t})}}s(hp,"prepareRetries");function aN({messages:e}){let t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};let o={};for(let c of e)if(c.role==="assistant"&&typeof c.content!="string"){let d=c.content;for(let p of d)p.type==="tool-call"&&(o[p.toolCallId]=p)}let a={};for(let c of e)if(c.role==="assistant"&&typeof c.content!="string"){let d=c.content;for(let p of d)p.type==="tool-approval-request"&&(a[p.approvalId]=p)}let n={};for(let c of t.content)c.type==="tool-result"&&(n[c.toolCallId]=c);let i=[],l=[],u=t.content.filter(c=>c.type==="tool-approval-response");for(let c of u){let d=a[c.approvalId];if(d==null)throw new QG({approvalId:c.approvalId});if(n[d.toolCallId]!=null)continue;let p=o[d.toolCallId];if(p==null)throw new eT({toolCallId:d.toolCallId,approvalId:d.approvalId});let m={approvalRequest:d,approvalResponse:c,toolCall:p};c.approved?i.push(m):l.push(m)}return{approvedToolApprovals:i,deniedToolApprovals:l}}s(aN,"collectToolApprovals");function Vg(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}s(Vg,"now");async function aT({toolCall:e,tools:t,tracer:o,telemetry:a,messages:n,abortSignal:i,experimental_context:l,stepNumber:u,model:c,onPreliminaryToolResult:d,onToolCallStart:p,onToolCallFinish:m}){let{toolName:f,toolCallId:h,input:g}=e,y=t?.[f];if(y?.execute==null)return;let _={stepNumber:u,model:c,toolCall:e,messages:n,abortSignal:i,functionId:a?.functionId,metadata:a?.metadata,experimental_context:l};return aa({name:"ai.toolCall",attributes:sr({telemetry:a,attributes:{...na({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":f,"ai.toolCall.id":h,"ai.toolCall.args":{output:s(()=>JSON.stringify(g),"output")}}}),tracer:o,fn:s(async v=>{let x;await Pn({event:_,callbacks:p});let w=Vg();try{let P=BO({execute:y.execute.bind(y),input:g,options:{toolCallId:h,messages:n,abortSignal:i,experimental_context:l}});for await(let k of P)k.type==="preliminary"?d?.({...e,type:"tool-result",output:k.output,preliminary:!0}):x=k.output}catch(P){let k=Vg()-w;return await Pn({event:{..._,success:!1,error:P,durationMs:k},callbacks:m}),eN(v,P),{type:"tool-error",toolCallId:h,toolName:f,input:g,error:P,dynamic:y.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}let S=Vg()-w;await Pn({event:{..._,success:!0,output:x,durationMs:S},callbacks:m});try{v.setAttributes(await sr({telemetry:a,attributes:{"ai.toolCall.result":{output:s(()=>JSON.stringify(x),"output")}}}))}catch{}return{type:"tool-result",toolCallId:h,toolName:f,input:g,output:x,dynamic:y.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}},"fn")})}s(aT,"executeToolCall");function UR(e){let t=e.filter(o=>o.type==="reasoning");return t.length===0?void 0:t.map(o=>o.text).join(`
89
+ `)}s(UR,"extractReasoningContent");function LR(e){let t=e.filter(o=>o.type==="text");if(t.length!==0)return t.map(o=>o.text).join("")}s(LR,"extractTextContent");var iT=class{static{s(this,"DefaultGeneratedFile")}constructor({data:e,mediaType:t}){let o=e instanceof Uint8Array;this.base64Data=o?void 0:e,this.uint8ArrayData=o?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=tn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Yt(this.base64Data)),this.uint8ArrayData}},d8=class extends iT{static{s(this,"DefaultGeneratedFileWithType")}constructor(e){super(e),this.type="file"}};async function iN({tool:e,toolCall:t,messages:o,experimental_context:a}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:o,experimental_context:a})}s(iN,"isApprovalNeeded");var p8={};HG(p8,{array:s(()=>h8,"array"),choice:s(()=>g8,"choice"),json:s(()=>y8,"json"),object:s(()=>f8,"object"),text:s(()=>Wg,"text")});function m8(e){let t=["ROOT"],o=-1,a=null;function n(c,d,p){switch(c){case'"':{o=d,t.pop(),t.push(p),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{o=d,a=d,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{o=d,t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"{":{o=d,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START");break}case"[":{o=d,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START");break}}}s(n,"processValueStart");function i(c,d){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{o=d,t.pop();break}}}s(i,"processAfterObjectValue");function l(c,d){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{o=d,t.pop();break}}}s(l,"processAfterArrayValue");for(let c=0;c<e.length;c++){let d=e[c];switch(t[t.length-1]){case"ROOT":n(d,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(d){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{o=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{d==='"'&&(t.pop(),t.push("INSIDE_OBJECT_KEY"));break}case"INSIDE_OBJECT_KEY":{d==='"'&&(t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY"));break}case"INSIDE_OBJECT_AFTER_KEY":{d===":"&&(t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE"));break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(d,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(d,c);break}case"INSIDE_STRING":{switch(d){case'"':{t.pop(),o=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:o=c}break}case"INSIDE_ARRAY_START":{d==="]"?(o=c,t.pop()):(o=c,n(d,c,"INSIDE_ARRAY_AFTER_VALUE"));break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(d){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{o=c,t.pop();break}default:{o=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(d,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),o=c;break}case"INSIDE_NUMBER":{switch(d){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{o=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(d,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(d,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(d,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(d,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{let m=e.substring(a,c+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(d,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(d,c)):o=c;break}}}let u=e.slice(0,o+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{u+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{u+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{u+="]";break}case"INSIDE_LITERAL":{let p=e.substring(a,e.length);"true".startsWith(p)?u+="true".slice(p.length):"false".startsWith(p)?u+="false".slice(p.length):"null".startsWith(p)&&(u+="null".slice(p.length))}}return u}s(m8,"fixJson");async function gp(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await xo({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await xo({text:m8(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}s(gp,"parsePartialJson");var Wg=s(()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),"text"),f8=s(({schema:e,name:t,description:o})=>{let a=Qn(e);return{name:"object",responseFormat:st(a.jsonSchema).then(n=>({type:"json",schema:n,...t!=null&&{name:t},...o!=null&&{description:o}})),async parseCompleteOutput({text:n},i){let l=await xo({text:n});if(!l.success)throw new Ti({message:"No object generated: could not parse the response.",cause:l.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});let u=await Br({value:l.value,schema:a});if(!u.success)throw new Ti({message:"No object generated: response did not match schema.",cause:u.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});return u.value},async parsePartialOutput({text:n}){let i=await gp(n);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:i.value}}},createElementStreamTransform(){}}},"object"),h8=s(({element:e,name:t,description:o})=>{let a=Qn(e);return{name:"array",responseFormat:st(a.jsonSchema).then(n=>{let{$schema:i,...l}=n;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:l}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...o!=null&&{description:o}}}),async parseCompleteOutput({text:n},i){let l=await xo({text:n});if(!l.success)throw new Ti({message:"No object generated: could not parse the response.",cause:l.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});let u=l.value;if(u==null||typeof u!="object"||!("elements"in u)||!Array.isArray(u.elements))throw new Ti({message:"No object generated: response did not match schema.",cause:new xn({value:u,cause:"response must be an object with an elements array"}),text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});for(let c of u.elements){let d=await Br({value:c,schema:a});if(!d.success)throw new Ti({message:"No object generated: response did not match schema.",cause:d.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason})}return u.elements},async parsePartialOutput({text:n}){let i=await gp(n);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let l=i.value;if(l==null||typeof l!="object"||!("elements"in l)||!Array.isArray(l.elements))return;let u=i.state==="repaired-parse"&&l.elements.length>0?l.elements.slice(0,-1):l.elements,c=[];for(let d of u){let p=await Br({value:d,schema:a});p.success&&c.push(p.value)}return{partial:c}}}},createElementStreamTransform(){let n=0;return new TransformStream({transform({partialOutput:i},l){if(i!=null)for(;n<i.length;n++)l.enqueue(i[n])}})}}},"array"),g8=s(({options:e,name:t,description:o})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...o!=null&&{description:o}}),async parseCompleteOutput({text:a},n){let i=await xo({text:a});if(!i.success)throw new Ti({message:"No object generated: could not parse the response.",cause:i.error,text:a,response:n.response,usage:n.usage,finishReason:n.finishReason});let l=i.value;if(l==null||typeof l!="object"||!("result"in l)||typeof l.result!="string"||!e.includes(l.result))throw new Ti({message:"No object generated: response did not match schema.",cause:new xn({value:l,cause:"response must be an object that contains a choice value."}),text:a,response:n.response,usage:n.usage,finishReason:n.finishReason});return l.result},async parsePartialOutput({text:a}){let n=await gp(a);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let i=n.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string")return;let l=e.filter(u=>u.startsWith(i.result));return n.state==="successful-parse"?l.includes(i.result)?{partial:i.result}:void 0:l.length===1?{partial:l[0]}:void 0}}},createElementStreamTransform(){}}),"choice"),y8=s(({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:o},a){let n=await xo({text:o});if(!n.success)throw new Ti({message:"No object generated: could not parse the response.",cause:n.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});return n.value},async parsePartialOutput({text:o}){let a=await gp(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return a.value===void 0?void 0:{partial:a.value}}},createElementStreamTransform(){}}),"json");async function sN({toolCall:e,tools:t,repairToolCall:o,system:a,messages:n}){var i;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await lN(e);throw new W0({toolName:e.toolName})}try{return await qR({toolCall:e,tools:t})}catch(l){if(o==null||!(W0.isInstance(l)||Q0.isInstance(l)))throw l;let u=null;try{u=await o({toolCall:e,tools:t,inputSchema:s(async({toolName:c})=>{let{inputSchema:d}=t[c];return await Qn(d).jsonSchema},"inputSchema"),system:a,messages:n,error:l})}catch(c){throw new xK({cause:c,originalError:l})}if(u==null)throw l;return await qR({toolCall:u,tools:t})}}catch(l){let u=await xo({text:e.input}),c=u.success?u.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:c,dynamic:!0,invalid:!0,error:l,title:(i=t?.[e.toolName])==null?void 0:i.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}s(sN,"parseToolCall");async function lN(e){let t=e.input.trim()===""?{success:!0,value:{}}:await xo({text:e.input});if(t.success===!1)throw new Q0({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}s(lN,"parseProviderExecutedDynamicToolCall");async function qR({toolCall:e,tools:t}){let o=e.toolName,a=t[o];if(a==null){if(e.providerExecuted&&e.dynamic)return await lN(e);throw new W0({toolName:e.toolName,availableTools:Object.keys(t)})}let n=Qn(a.inputSchema),i=e.input.trim()===""?await Br({value:{},schema:n}):await xo({text:e.input,schema:n});if(i.success===!1)throw new Q0({toolName:o,toolInput:e.input,cause:i.error});return a.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:a.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:o,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:a.title}}s(qR,"doParseToolCall");var uN=class{static{s(this,"DefaultStepResult")}constructor({stepNumber:e,model:t,functionId:o,metadata:a,experimental_context:n,content:i,finishReason:l,rawFinishReason:u,usage:c,warnings:d,request:p,response:m,providerMetadata:f}){this.stepNumber=e,this.model=t,this.functionId=o,this.metadata=a,this.experimental_context=n,this.content=i,this.finishReason=l,this.rawFinishReason=u,this.usage=c,this.warnings=d,this.request=p,this.response=m,this.providerMetadata=f}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function nu(e){return({steps:t})=>t.length===e}s(nu,"stepCountIs");function cN(e){return({steps:t})=>{var o,a,n;return(n=(a=(o=t[t.length-1])==null?void 0:o.toolCalls)==null?void 0:a.some(i=>i.toolName===e))!=null?n:!1}}s(cN,"hasToolCall");async function dN({stopConditions:e,steps:t}){return(await Promise.all(e.map(o=>o({steps:t})))).some(o=>o)}s(dN,"isStopConditionMet");async function X0({content:e,tools:t}){let o=[],a=[];for(let i of e)if(i.type!=="source"&&!((i.type==="tool-result"||i.type==="tool-error")&&!i.providerExecuted)&&!(i.type==="text"&&i.text.length===0))switch(i.type){case"text":a.push({type:"text",text:i.text,providerOptions:i.providerMetadata});break;case"reasoning":a.push({type:"reasoning",text:i.text,providerOptions:i.providerMetadata});break;case"file":a.push({type:"file",data:i.file.base64,mediaType:i.file.mediaType,providerOptions:i.providerMetadata});break;case"tool-call":a.push({type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.invalid&&typeof i.input!="object"?{}:i.input,providerExecuted:i.providerExecuted,providerOptions:i.providerMetadata});break;case"tool-result":{let l=await pp({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.output,errorMode:"none"});a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:l,providerOptions:i.providerMetadata});break}case"tool-error":{let l=await pp({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.error,errorMode:"json"});a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:l,providerOptions:i.providerMetadata});break}case"tool-approval-request":a.push({type:"tool-approval-request",approvalId:i.approvalId,toolCallId:i.toolCall.toolCallId});break}a.length>0&&o.push({role:"assistant",content:a});let n=[];for(let i of e){if(!(i.type==="tool-result"||i.type==="tool-error")||i.providerExecuted)continue;let l=await pp({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.type==="tool-result"?i.output:i.error,errorMode:i.type==="tool-error"?"text":"none"});n.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:l,...i.providerMetadata!=null?{providerOptions:i.providerMetadata}:{}})}return n.length>0&&o.push({role:"tool",content:n}),o}s(X0,"toResponseMessages");function pN(...e){let t=e.filter(a=>a!=null);if(t.length===0)return;if(t.length===1)return t[0];let o=new AbortController;for(let a of t){if(a.aborted)return o.abort(a.reason),o.signal;a.addEventListener("abort",()=>{o.abort(a.reason)},{once:!0})}return o.signal}s(pN,"mergeAbortSignals");var _8=Xn({prefix:"aitxt",size:24});async function ia({model:e,tools:t,toolChoice:o,system:a,prompt:n,messages:i,allowSystemInMessages:l,maxRetries:u,abortSignal:c,timeout:d,headers:p,stopWhen:m=nu(1),experimental_output:f,output:h=f,experimental_telemetry:g,providerOptions:y,experimental_activeTools:_,activeTools:v=_,experimental_prepareStep:x,prepareStep:w=x,experimental_repairToolCall:S,experimental_download:P,experimental_context:k,experimental_include:I,_internal:{generateId:E=_8}={},experimental_onStart:b,experimental_onStepStart:M,experimental_onToolCallStart:R,experimental_onToolCallFinish:D,onStepFinish:te,onFinish:ee,...J}){let W=Zg(e),j=rN(),O=hs(m),Z=nT(d),F=Fz(d),z=F!=null?new AbortController:void 0,Y=pN(c,Z!=null?AbortSignal.timeout(Z):void 0,z?.signal),{maxRetries:ae,retry:K}=hp({maxRetries:u,abortSignal:Y}),he=G0(J),L=Qt(p??{},`ai/${fp}`),le=Gg({model:W,telemetry:g,headers:L,settings:{...he,maxRetries:ae}}),oe={provider:W.provider,modelId:W.modelId},ne=await Yz({system:a,prompt:n,messages:i,allowSystemInMessages:l}),C=j(g?.integrations);await Pn({event:{model:oe,system:a,prompt:n,messages:i,tools:t,toolChoice:o,activeTools:v,maxOutputTokens:he.maxOutputTokens,temperature:he.temperature,topP:he.topP,topK:he.topK,presencePenalty:he.presencePenalty,frequencyPenalty:he.frequencyPenalty,stopSequences:he.stopSequences,seed:he.seed,maxRetries:ae,timeout:d,headers:p,providerOptions:y,stopWhen:m,output:h,abortSignal:c,include:I,functionId:g?.functionId,metadata:g?.metadata,experimental_context:k},callbacks:[b,C.onStart]});let G=Kg(g);try{return await aa({name:"ai.generateText",attributes:sr({telemetry:g,attributes:{...na({operationId:"ai.generateText",telemetry:g}),...le,"ai.model.provider":W.provider,"ai.model.id":W.modelId,"ai.prompt":{input:s(()=>JSON.stringify({system:a,prompt:n,messages:i}),"input")}}}),tracer:G,fn:s(async X=>{var q,Me,fe,at,rr,Tr,gr,Ho,Mr,De,Wr,dn,Bn,Oo,Kt,T,B,Ee,He,Rt;let lr=ne.messages,br=[],{approvedToolApprovals:$o,deniedToolApprovals:pn}=aN({messages:lr}),Jo=$o.filter(Er=>!Er.toolCall.providerExecuted);if(pn.length>0||Jo.length>0){let Er=await FR({toolCalls:Jo.map(ut=>ut.toolCall),tools:t,tracer:G,telemetry:g,messages:lr,abortSignal:Y,experimental_context:k,stepNumber:0,model:oe,onToolCallStart:[R,C.onToolCallStart],onToolCallFinish:[D,C.onToolCallFinish]}),Ur=[];for(let ut of Er){let co=await pp({toolCallId:ut.toolCallId,input:ut.input,tool:t?.[ut.toolName],output:ut.type==="tool-result"?ut.output:ut.error,errorMode:ut.type==="tool-error"?"text":"none"});Ur.push({type:"tool-result",toolCallId:ut.toolCallId,toolName:ut.toolName,output:co})}for(let ut of pn)Ur.push({type:"tool-result",toolCallId:ut.toolCall.toolCallId,toolName:ut.toolCall.toolName,output:{type:"execution-denied",reason:ut.approvalResponse.reason,...ut.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:ut.approvalResponse.approvalId}}}}});br.push({role:"tool",content:Ur})}let be=G0(J),Ve,yr=[],ur=[],je=[],Dr=new Map;do{let Er=F!=null?setTimeout(()=>z.abort(),F):void 0;try{let Ur=[...lr,...br],ut=await w?.({model:W,steps:je,stepNumber:je.length,messages:Ur,experimental_context:k}),co=Zg((q=ut?.model)!=null?q:W),Ha={provider:co.provider,modelId:co.modelId},Nu=await Jz({prompt:{system:(Me=ut?.system)!=null?Me:ne.system,messages:(fe=ut?.messages)!=null?fe:Ur},supportedUrls:await co.supportedUrls,download:P});k=(at=ut?.experimental_context)!=null?at:k;let ga=(rr=ut?.activeTools)!=null?rr:v,{toolChoice:qs,tools:Fs}=await Wz({tools:t,toolChoice:(Tr=ut?.toolChoice)!=null?Tr:o,activeTools:ga}),Am=(gr=ut?.messages)!=null?gr:Ur,Ja=(Ho=ut?.system)!=null?Ho:ne.system,pr=Xg(y,ut?.providerOptions);await Pn({event:{stepNumber:je.length,model:Ha,system:Ja,messages:Am,tools:t,toolChoice:qs,activeTools:ga,steps:[...je],providerOptions:pr,timeout:d,headers:p,stopWhen:m,output:h,abortSignal:c,include:I,functionId:g?.functionId,metadata:g?.metadata,experimental_context:k},callbacks:[M,C.onStepStart]}),Ve=await K(()=>{var ct;return aa({name:"ai.generateText.doGenerate",attributes:sr({telemetry:g,attributes:{...na({operationId:"ai.generateText.doGenerate",telemetry:g}),...le,"ai.model.provider":co.provider,"ai.model.id":co.modelId,"ai.prompt.messages":{input:s(()=>tN(Nu),"input")},"ai.prompt.tools":{input:s(()=>Fs?.map(Gr=>JSON.stringify(Gr)),"input")},"ai.prompt.toolChoice":{input:s(()=>qs!=null?JSON.stringify(qs):void 0,"input")},"gen_ai.system":co.provider,"gen_ai.request.model":co.modelId,"gen_ai.request.frequency_penalty":J.frequencyPenalty,"gen_ai.request.max_tokens":J.maxOutputTokens,"gen_ai.request.presence_penalty":J.presencePenalty,"gen_ai.request.stop_sequences":J.stopSequences,"gen_ai.request.temperature":(ct=J.temperature)!=null?ct:void 0,"gen_ai.request.top_k":J.topK,"gen_ai.request.top_p":J.topP}}),tracer:G,fn:s(async Gr=>{var Zs,ya,Vn,Du,$m,Rm,Wa,Ga;let Lt=await co.doGenerate({...be,tools:Fs,toolChoice:qs,responseFormat:await h?.responseFormat,prompt:Nu,providerOptions:pr,abortSignal:Y,headers:L}),Zn={id:(ya=(Zs=Lt.response)==null?void 0:Zs.id)!=null?ya:E(),timestamp:(Du=(Vn=Lt.response)==null?void 0:Vn.timestamp)!=null?Du:new Date,modelId:(Rm=($m=Lt.response)==null?void 0:$m.modelId)!=null?Rm:co.modelId,headers:(Wa=Lt.response)==null?void 0:Wa.headers,body:(Ga=Lt.response)==null?void 0:Ga.body},Ka=K0(Lt.usage);return Gr.setAttributes(await sr({telemetry:g,attributes:{"ai.response.finishReason":Lt.finishReason.unified,"ai.response.text":{output:s(()=>LR(Lt.content),"output")},"ai.response.reasoning":{output:s(()=>UR(Lt.content),"output")},"ai.response.toolCalls":{output:s(()=>{let Hs=BR(Lt.content);return Hs==null?void 0:JSON.stringify(Hs)},"output")},"ai.response.id":Zn.id,"ai.response.model":Zn.modelId,"ai.response.timestamp":Zn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Lt.providerMetadata),"ai.usage.inputTokens":Lt.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":Lt.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":Lt.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":Lt.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":Lt.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":Lt.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":Lt.usage.outputTokens.reasoning,"ai.usage.totalTokens":Ka.totalTokens,"ai.usage.reasoningTokens":Lt.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":Lt.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[Lt.finishReason.unified],"gen_ai.response.id":Zn.id,"gen_ai.response.model":Zn.modelId,"gen_ai.usage.input_tokens":Lt.usage.inputTokens.total,"gen_ai.usage.output_tokens":Lt.usage.outputTokens.total}})),{...Lt,response:Zn}},"fn")})});let po=await Promise.all(Ve.content.filter(ct=>ct.type==="tool-call").map(ct=>sN({toolCall:ct,tools:t,repairToolCall:S,system:a,messages:Ur}))),Bs={};for(let ct of po){if(ct.invalid)continue;let Gr=t?.[ct.toolName];Gr!=null&&(Gr?.onInputAvailable!=null&&await Gr.onInputAvailable({input:ct.input,toolCallId:ct.toolCallId,messages:Ur,abortSignal:Y,experimental_context:k}),await iN({tool:Gr,toolCall:ct,messages:Ur,experimental_context:k})&&(Bs[ct.toolCallId]={type:"tool-approval-request",approvalId:E(),toolCall:ct}))}let Cm=po.filter(ct=>ct.invalid&&ct.dynamic);ur=[];for(let ct of Cm)ur.push({type:"tool-error",toolCallId:ct.toolCallId,toolName:ct.toolName,input:ct.input,error:Wl(ct.error),dynamic:!0});yr=po.filter(ct=>!ct.providerExecuted),t!=null&&ur.push(...await FR({toolCalls:yr.filter(ct=>!ct.invalid&&Bs[ct.toolCallId]==null),tools:t,tracer:G,telemetry:g,messages:Ur,abortSignal:Y,experimental_context:k,stepNumber:je.length,model:Ha,onToolCallStart:[R,C.onToolCallStart],onToolCallFinish:[D,C.onToolCallFinish]}));for(let ct of po){if(!ct.providerExecuted)continue;let Gr=t?.[ct.toolName];Gr?.type==="provider"&&Gr.supportsDeferredResults&&(Ve.content.some(ya=>ya.type==="tool-result"&&ya.toolCallId===ct.toolCallId)||Dr.set(ct.toolCallId,{toolName:ct.toolName}))}for(let ct of Ve.content)ct.type==="tool-result"&&Dr.delete(ct.toolCallId);let ju=b8({content:Ve.content,toolCalls:po,toolOutputs:ur,toolApprovalRequests:Object.values(Bs),tools:t});br.push(...await X0({content:ju,tools:t}));let Vs=(Mr=I?.requestBody)==null||Mr?(De=Ve.request)!=null?De:{}:{...Ve.request,body:void 0},Mu={...Ve.response,messages:structuredClone(br),body:(Wr=I?.responseBody)==null||Wr?(dn=Ve.response)==null?void 0:dn.body:void 0},q_=je.length,Om=new uN({stepNumber:q_,model:Ha,functionId:g?.functionId,metadata:g?.metadata,experimental_context:k,content:ju,finishReason:Ve.finishReason.unified,rawFinishReason:Ve.finishReason.raw,usage:K0(Ve.usage),warnings:Ve.warnings,providerMetadata:Ve.providerMetadata,request:Vs,response:Mu});gs({warnings:(Bn=Ve.warnings)!=null?Bn:[],provider:Ha.provider,model:Ha.modelId}),je.push(Om),await Pn({event:Om,callbacks:[te,C.onStepFinish]})}finally{Er!=null&&clearTimeout(Er)}}while((yr.length>0&&ur.length===yr.length||Dr.size>0)&&!await dN({stopConditions:O,steps:je}));X.setAttributes(await sr({telemetry:g,attributes:{"ai.response.finishReason":Ve.finishReason.unified,"ai.response.text":{output:s(()=>LR(Ve.content),"output")},"ai.response.reasoning":{output:s(()=>UR(Ve.content),"output")},"ai.response.toolCalls":{output:s(()=>{let Er=BR(Ve.content);return Er==null?void 0:JSON.stringify(Er)},"output")},"ai.response.providerMetadata":JSON.stringify(Ve.providerMetadata)}}));let Xe=je[je.length-1],or=je.reduce((Er,Ur)=>oN(Er,Ur.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});X.setAttributes(await sr({telemetry:g,attributes:{"ai.usage.inputTokens":or.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Oo=or.inputTokenDetails)==null?void 0:Oo.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Kt=or.inputTokenDetails)==null?void 0:Kt.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(T=or.inputTokenDetails)==null?void 0:T.cacheWriteTokens,"ai.usage.outputTokens":or.outputTokens,"ai.usage.outputTokenDetails.textTokens":(B=or.outputTokenDetails)==null?void 0:B.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Ee=or.outputTokenDetails)==null?void 0:Ee.reasoningTokens,"ai.usage.totalTokens":or.totalTokens,"ai.usage.reasoningTokens":(He=or.outputTokenDetails)==null?void 0:He.reasoningTokens,"ai.usage.cachedInputTokens":(Rt=or.inputTokenDetails)==null?void 0:Rt.cacheReadTokens}})),await Pn({event:{stepNumber:Xe.stepNumber,model:Xe.model,functionId:Xe.functionId,metadata:Xe.metadata,experimental_context:Xe.experimental_context,finishReason:Xe.finishReason,rawFinishReason:Xe.rawFinishReason,usage:Xe.usage,content:Xe.content,text:Xe.text,reasoningText:Xe.reasoningText,reasoning:Xe.reasoning,files:Xe.files,sources:Xe.sources,toolCalls:Xe.toolCalls,staticToolCalls:Xe.staticToolCalls,dynamicToolCalls:Xe.dynamicToolCalls,toolResults:Xe.toolResults,staticToolResults:Xe.staticToolResults,dynamicToolResults:Xe.dynamicToolResults,request:Xe.request,response:Xe.response,warnings:Xe.warnings,providerMetadata:Xe.providerMetadata,steps:je,totalUsage:or},callbacks:[ee,C.onFinish]});let nr;return Xe.finishReason==="stop"&&(nr=await(h??Wg()).parseCompleteOutput({text:Xe.text},{response:Xe.response,usage:Xe.usage,finishReason:Xe.finishReason})),new v8({steps:je,totalUsage:or,output:nr})},"fn")})}catch(X){throw Qz(X)}}s(ia,"generateText");async function FR({toolCalls:e,tools:t,tracer:o,telemetry:a,messages:n,abortSignal:i,experimental_context:l,stepNumber:u,model:c,onToolCallStart:d,onToolCallFinish:p}){return(await Promise.all(e.map(async f=>aT({toolCall:f,tools:t,tracer:o,telemetry:a,messages:n,abortSignal:i,experimental_context:l,stepNumber:u,model:c,onToolCallStart:d,onToolCallFinish:p})))).filter(f=>f!=null)}s(FR,"executeTools");var v8=class{static{s(this,"DefaultGenerateTextResult")}constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new bz;return this._output}};function BR(e){let t=e.filter(o=>o.type==="tool-call");if(t.length!==0)return t.map(o=>({toolCallId:o.toolCallId,toolName:o.toolName,input:o.input}))}s(BR,"asToolCalls");function b8({content:e,toolCalls:t,toolOutputs:o,toolApprovalRequests:a,tools:n}){let i=[];for(let l of e)switch(l.type){case"text":case"reasoning":case"source":i.push(l);break;case"file":{i.push({type:"file",file:new iT(l),...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}});break}case"tool-call":{i.push(t.find(u=>u.toolCallId===l.toolCallId));break}case"tool-result":{let u=t.find(c=>c.toolCallId===l.toolCallId);if(u==null){let c=n?.[l.toolName];if(!(c?.type==="provider"&&c.supportsDeferredResults))throw new Error(`Tool call ${l.toolCallId} not found.`);l.isError?i.push({type:"tool-error",toolCallId:l.toolCallId,toolName:l.toolName,input:void 0,error:l.result,providerExecuted:!0,dynamic:l.dynamic,...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}}):i.push({type:"tool-result",toolCallId:l.toolCallId,toolName:l.toolName,input:void 0,output:l.result,providerExecuted:!0,dynamic:l.dynamic,...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}});break}l.isError?i.push({type:"tool-error",toolCallId:l.toolCallId,toolName:l.toolName,input:u.input,error:l.result,providerExecuted:!0,dynamic:u.dynamic,...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}}):i.push({type:"tool-result",toolCallId:l.toolCallId,toolName:l.toolName,input:u.input,output:l.result,providerExecuted:!0,dynamic:u.dynamic,...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}});break}case"tool-approval-request":{let u=t.find(c=>c.toolCallId===l.toolCallId);if(u==null)throw new eT({toolCallId:l.toolCallId,approvalId:l.approvalId});i.push({type:"tool-approval-request",approvalId:l.approvalId,toolCall:u});break}}return[...i,...o,...a]}s(b8,"asContent");function Yg(e,t){let o=new Headers(e??{});for(let[a,n]of Object.entries(t))o.has(a)||o.set(a,n);return o}s(Yg,"prepareHeaders");function x8({status:e,statusText:t,headers:o,textStream:a}){return new Response(a.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Yg(o,{"content-type":"text/plain; charset=utf-8"})})}s(x8,"createTextStreamResponse");function mN({response:e,status:t,statusText:o,headers:a,stream:n}){let i=t??200;o!==void 0?e.writeHead(i,o,a):e.writeHead(i,a);let l=n.getReader();s(async()=>{try{for(;;){let{done:c,value:d}=await l.read();if(c)break;e.write(d)||await new Promise(m=>{e.once("drain",m)})}}catch(c){throw c}finally{e.end()}},"read")()}s(mN,"writeToServerResponse");function w8({response:e,status:t,statusText:o,headers:a,textStream:n}){mN({response:e,status:t,statusText:o,headers:Object.fromEntries(Yg(a,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})}s(w8,"pipeTextStreamToResponse");var fN=class extends TransformStream{static{s(this,"JsonToSseTransformStream")}constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
90
90
 
91
91
  `)},flush(e){e.enqueue(`data: [DONE]
92
92
 
93
- `)}})}},hN={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function TK({status:e,statusText:t,headers:o,stream:a,consumeSseStream:n}){let i=a.pipeThrough(new fN);if(n){let[l,u]=i.tee();i=l,n({stream:u})}return new Response(i.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Yg(o,hN)})}s(TK,"createUIMessageStreamResponse");function SK({originalMessages:e,responseMessageId:t}){if(e==null)return;let o=e[e.length-1];return o?.role==="assistant"?o.id:typeof t=="function"?t():t}s(SK,"getResponseUIMessageId");var lze=N(()=>$(r.union([r.strictObject({type:r.literal("text-start"),id:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("text-delta"),id:r.string(),delta:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("text-end"),id:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("error"),errorText:r.string()}),r.strictObject({type:r.literal("tool-input-start"),toolCallId:r.string(),toolName:r.string(),providerExecuted:r.boolean().optional(),providerMetadata:ze.optional(),dynamic:r.boolean().optional(),title:r.string().optional()}),r.strictObject({type:r.literal("tool-input-delta"),toolCallId:r.string(),inputTextDelta:r.string()}),r.strictObject({type:r.literal("tool-input-available"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerExecuted:r.boolean().optional(),providerMetadata:ze.optional(),dynamic:r.boolean().optional(),title:r.string().optional()}),r.strictObject({type:r.literal("tool-input-error"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerExecuted:r.boolean().optional(),providerMetadata:ze.optional(),dynamic:r.boolean().optional(),errorText:r.string(),title:r.string().optional()}),r.strictObject({type:r.literal("tool-approval-request"),approvalId:r.string(),toolCallId:r.string()}),r.strictObject({type:r.literal("tool-output-available"),toolCallId:r.string(),output:r.unknown(),providerExecuted:r.boolean().optional(),providerMetadata:ze.optional(),dynamic:r.boolean().optional(),preliminary:r.boolean().optional()}),r.strictObject({type:r.literal("tool-output-error"),toolCallId:r.string(),errorText:r.string(),providerExecuted:r.boolean().optional(),providerMetadata:ze.optional(),dynamic:r.boolean().optional()}),r.strictObject({type:r.literal("tool-output-denied"),toolCallId:r.string()}),r.strictObject({type:r.literal("reasoning-start"),id:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("reasoning-delta"),id:r.string(),delta:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("reasoning-end"),id:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("source-url"),sourceId:r.string(),url:r.string(),title:r.string().optional(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("source-document"),sourceId:r.string(),mediaType:r.string(),title:r.string(),filename:r.string().optional(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("file"),url:r.string(),mediaType:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.custom(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:r.string().optional(),data:r.unknown(),transient:r.boolean().optional()}),r.strictObject({type:r.literal("start-step")}),r.strictObject({type:r.literal("finish-step")}),r.strictObject({type:r.literal("start"),messageId:r.string().optional(),messageMetadata:r.unknown().optional()}),r.strictObject({type:r.literal("finish"),finishReason:r.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:r.unknown().optional()}),r.strictObject({type:r.literal("abort"),reason:r.string().optional()}),r.strictObject({type:r.literal("message-metadata"),messageMetadata:r.unknown()})])));function IK(e){return e.type.startsWith("data-")}s(IK,"isDataUIMessageChunk");function Y0(e){return e.type.startsWith("tool-")}s(Y0,"isStaticToolUIPart");function kK(e){return e.type==="dynamic-tool"}s(kK,"isDynamicToolUIPart");function VR(e){return Y0(e)||kK(e)}s(VR,"isToolUIPart");function ZR(e){return e.type.split("-").slice(1).join("-")}s(ZR,"getStaticToolName");function PK({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}s(PK,"createStreamingUIMessageState");function EK({stream:e,messageMetadataSchema:t,dataPartSchemas:o,runUpdateMessageJob:a,onError:n,onToolCall:i,onData:l}){return e.pipeThrough(new TransformStream({async transform(u,c){await a(async({state:d,write:p})=>{var m,f,h,g;function y(w){let P=d.message.parts.filter(VR).find(k=>k.toolCallId===w);if(P==null)throw new ou({chunkType:"tool-invocation",chunkId:w,message:`No tool invocation found for tool call ID "${w}".`});return P}s(y,"getToolInvocation");function _(w){var S;let P=d.message.parts.find(E=>Y0(E)&&E.toolCallId===w.toolCallId),k=w,I=P;if(P!=null){P.state=w.state,I.input=k.input,I.output=k.output,I.errorText=k.errorText,I.rawInput=k.rawInput,I.preliminary=k.preliminary,w.title!==void 0&&(I.title=w.title),I.providerExecuted=(S=k.providerExecuted)!=null?S:P.providerExecuted;let E=k.providerMetadata;if(E!=null)if(w.state==="output-available"||w.state==="output-error"){let b=P;b.resultProviderMetadata=E}else P.callProviderMetadata=E}else d.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,title:w.title,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null&&(w.state==="output-available"||w.state==="output-error")?{resultProviderMetadata:k.providerMetadata}:{},...k.providerMetadata!=null&&!(w.state==="output-available"||w.state==="output-error")?{callProviderMetadata:k.providerMetadata}:{}})}s(_,"updateToolPart");function v(w){var S,P;let k=d.message.parts.find(b=>b.type==="dynamic-tool"&&b.toolCallId===w.toolCallId),I=w,E=k;if(k!=null){k.state=w.state,E.toolName=w.toolName,E.input=I.input,E.output=I.output,E.errorText=I.errorText,E.rawInput=(S=I.rawInput)!=null?S:E.rawInput,E.preliminary=I.preliminary,w.title!==void 0&&(E.title=w.title),E.providerExecuted=(P=I.providerExecuted)!=null?P:k.providerExecuted;let b=I.providerMetadata;if(b!=null)if(w.state==="output-available"||w.state==="output-error"){let M=k;M.resultProviderMetadata=b}else k.callProviderMetadata=b}else d.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:I.input,output:I.output,errorText:I.errorText,preliminary:I.preliminary,providerExecuted:I.providerExecuted,title:w.title,...I.providerMetadata!=null&&(w.state==="output-available"||w.state==="output-error")?{resultProviderMetadata:I.providerMetadata}:{},...I.providerMetadata!=null&&!(w.state==="output-available"||w.state==="output-error")?{callProviderMetadata:I.providerMetadata}:{}})}s(v,"updateDynamicToolPart");async function x(w){if(w!=null){let S=d.message.metadata!=null?Xg(d.message.metadata,w):w;t!=null&&await $e({value:S,schema:t,context:{field:"message.metadata",entityId:d.message.id}}),d.message.metadata=S}}switch(s(x,"updateMessageMetadata"),u.type){case"text-start":{let w={type:"text",text:"",providerMetadata:u.providerMetadata,state:"streaming"};d.activeTextParts[u.id]=w,d.message.parts.push(w),p();break}case"text-delta":{let w=d.activeTextParts[u.id];if(w==null)throw new ou({chunkType:"text-delta",chunkId:u.id,message:`Received text-delta for missing text part with ID "${u.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});w.text+=u.delta,w.providerMetadata=(m=u.providerMetadata)!=null?m:w.providerMetadata,p();break}case"text-end":{let w=d.activeTextParts[u.id];if(w==null)throw new ou({chunkType:"text-end",chunkId:u.id,message:`Received text-end for missing text part with ID "${u.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});w.state="done",w.providerMetadata=(f=u.providerMetadata)!=null?f:w.providerMetadata,delete d.activeTextParts[u.id],p();break}case"reasoning-start":{let w={type:"reasoning",text:"",providerMetadata:u.providerMetadata,state:"streaming"};d.activeReasoningParts[u.id]=w,d.message.parts.push(w),p();break}case"reasoning-delta":{let w=d.activeReasoningParts[u.id];if(w==null)throw new ou({chunkType:"reasoning-delta",chunkId:u.id,message:`Received reasoning-delta for missing reasoning part with ID "${u.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});w.text+=u.delta,w.providerMetadata=(h=u.providerMetadata)!=null?h:w.providerMetadata,p();break}case"reasoning-end":{let w=d.activeReasoningParts[u.id];if(w==null)throw new ou({chunkType:"reasoning-end",chunkId:u.id,message:`Received reasoning-end for missing reasoning part with ID "${u.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});w.providerMetadata=(g=u.providerMetadata)!=null?g:w.providerMetadata,w.state="done",delete d.activeReasoningParts[u.id],p();break}case"file":{d.message.parts.push({type:"file",mediaType:u.mediaType,url:u.url,...u.providerMetadata!=null?{providerMetadata:u.providerMetadata}:{}}),p();break}case"source-url":{d.message.parts.push({type:"source-url",sourceId:u.sourceId,url:u.url,title:u.title,providerMetadata:u.providerMetadata}),p();break}case"source-document":{d.message.parts.push({type:"source-document",sourceId:u.sourceId,mediaType:u.mediaType,title:u.title,filename:u.filename,providerMetadata:u.providerMetadata}),p();break}case"tool-input-start":{let w=d.message.parts.filter(Y0);d.partialToolCalls[u.toolCallId]={text:"",toolName:u.toolName,index:w.length,dynamic:u.dynamic,title:u.title},u.dynamic?v({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-streaming",input:void 0,providerExecuted:u.providerExecuted,title:u.title,providerMetadata:u.providerMetadata}):_({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-streaming",input:void 0,providerExecuted:u.providerExecuted,title:u.title,providerMetadata:u.providerMetadata}),p();break}case"tool-input-delta":{let w=d.partialToolCalls[u.toolCallId];if(w==null)throw new ou({chunkType:"tool-input-delta",chunkId:u.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${u.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});w.text+=u.inputTextDelta;let{value:S}=await gp(w.text);w.dynamic?v({toolCallId:u.toolCallId,toolName:w.toolName,state:"input-streaming",input:S,title:w.title}):_({toolCallId:u.toolCallId,toolName:w.toolName,state:"input-streaming",input:S,title:w.title}),p();break}case"tool-input-available":{u.dynamic?v({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-available",input:u.input,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata,title:u.title}):_({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-available",input:u.input,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata,title:u.title}),p(),i&&!u.providerExecuted&&await i({toolCall:u});break}case"tool-input-error":{let w=d.message.parts.filter(VR).find(P=>P.toolCallId===u.toolCallId);(w!=null?w.type==="dynamic-tool":!!u.dynamic)?v({toolCallId:u.toolCallId,toolName:u.toolName,state:"output-error",input:u.input,errorText:u.errorText,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata}):_({toolCallId:u.toolCallId,toolName:u.toolName,state:"output-error",input:void 0,rawInput:u.input,errorText:u.errorText,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata}),p();break}case"tool-approval-request":{let w=y(u.toolCallId);w.state="approval-requested",w.approval={id:u.approvalId},p();break}case"tool-output-denied":{let w=y(u.toolCallId);w.state="output-denied",p();break}case"tool-output-available":{let w=y(u.toolCallId);w.type==="dynamic-tool"?v({toolCallId:u.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:u.output,preliminary:u.preliminary,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata,title:w.title}):_({toolCallId:u.toolCallId,toolName:ZR(w),state:"output-available",input:w.input,output:u.output,providerExecuted:u.providerExecuted,preliminary:u.preliminary,providerMetadata:u.providerMetadata,title:w.title}),p();break}case"tool-output-error":{let w=y(u.toolCallId);w.type==="dynamic-tool"?v({toolCallId:u.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:u.errorText,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata,title:w.title}):_({toolCallId:u.toolCallId,toolName:ZR(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:u.errorText,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata,title:w.title}),p();break}case"start-step":{d.message.parts.push({type:"step-start"});break}case"finish-step":{d.activeTextParts={},d.activeReasoningParts={};break}case"start":{u.messageId!=null&&(d.message.id=u.messageId),await x(u.messageMetadata),(u.messageId!=null||u.messageMetadata!=null)&&p();break}case"finish":{u.finishReason!=null&&(d.finishReason=u.finishReason),await x(u.messageMetadata),u.messageMetadata!=null&&p();break}case"message-metadata":{await x(u.messageMetadata),u.messageMetadata!=null&&p();break}case"error":{n?.(new Error(u.errorText));break}default:if(IK(u)){if(o?.[u.type]!=null){let P=d.message.parts.findIndex(I=>"id"in I&&"data"in I&&I.id===u.id&&I.type===u.type),k=P>=0?P:d.message.parts.length;await $e({value:u.data,schema:o[u.type],context:{field:`message.parts[${k}].data`,entityName:u.type,entityId:u.id}})}let w=u;if(w.transient){l?.(w);break}let S=w.id!=null?d.message.parts.find(P=>w.type===P.type&&w.id===P.id):void 0;S!=null?S.data=w.data:d.message.parts.push(w),l?.(w),p()}}c.enqueue(u)})}}))}s(EK,"processUIMessageStream");function AK({messageId:e,originalMessages:t=[],onStepFinish:o,onFinish:a,onError:n,stream:i}){let l=t?.[t.length-1];l?.role!=="assistant"?l=void 0:e=l.id;let u=!1,c=i.pipeThrough(new TransformStream({transform(g,y){if(g.type==="start"){let _=g;_.messageId==null&&e!=null&&(_.messageId=e)}g.type==="abort"&&(u=!0),y.enqueue(g)}}));if(a==null&&o==null)return c;let d=PK({lastMessage:l?structuredClone(l):void 0,messageId:e??""}),p=s(async g=>{await g({state:d,write:s(()=>{},"write")})},"runUpdateMessageJob"),m=!1,f=s(async()=>{if(m||!a)return;m=!0;let g=d.message.id===l?.id;await a({isAborted:u,isContinuation:g,responseMessage:d.message,messages:[...g?t.slice(0,-1):t,d.message],finishReason:d.finishReason})},"callOnFinish"),h=s(async()=>{if(!o)return;let g=d.message.id===l?.id;try{await o({isContinuation:g,responseMessage:structuredClone(d.message),messages:[...g?t.slice(0,-1):t,structuredClone(d.message)]})}catch(y){n(y)}},"callOnStepFinish");return EK({stream:c,runUpdateMessageJob:p,onError:n}).pipeThrough(new TransformStream({async transform(g,y){g.type==="finish-step"&&await h(),y.enqueue(g)},async cancel(){await f()},async flush(){await f()}}))}s(AK,"handleUIMessageStreamFinish");function CK({response:e,status:t,statusText:o,headers:a,stream:n,consumeSseStream:i}){let l=n.pipeThrough(new fN);if(i){let[u,c]=l.tee();l=u,i({stream:c})}mN({response:e,status:t,statusText:o,headers:Object.fromEntries(Yg(a,hN).entries()),stream:l.pipeThrough(new TextEncoderStream)})}s(CK,"pipeUIMessageStreamToResponse");function dp(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let o=this.getReader(),a=!1;async function n(i){var l;if(!a){a=!0;try{i&&await((l=o.cancel)==null?void 0:l.call(o))}finally{try{o.releaseLock()}catch{}}}}return s(n,"cleanup"),{async next(){if(a)return{done:!0,value:void 0};let{done:i,value:l}=await o.read();return i?(await n(!0),{done:!0,value:void 0}):{done:!1,value:l}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(i){throw await n(!0),i}}},t}s(dp,"createAsyncIterableStream");async function OK({stream:e,onError:t}){let o=e.getReader();try{for(;;){let{done:a}=await o.read();if(a)break}}catch(a){t?.(a)}finally{o.releaseLock()}}s(OK,"consumeStream");function HR(){let e,t;return{promise:new Promise((a,n)=>{e=a,t=n}),resolve:e,reject:t}}s(HR,"createResolvablePromise");function $K(){let e=[],t=null,o=!1,a=HR(),n=s(()=>{o=!0,a.resolve(),e.forEach(l=>l.cancel()),e=[],t?.close()},"terminate"),i=s(async()=>{if(o&&e.length===0){t?.close();return}if(e.length===0)return a=HR(),await a.promise,i();try{let{value:l,done:u}=await e[0].read();u?(e.shift(),e.length===0&&o?t?.close():await i()):t?.enqueue(l)}catch(l){t?.error(l),e.shift(),n()}},"processPull");return{stream:new ReadableStream({start(l){t=l},pull:i,async cancel(){for(let l of e)await l.cancel();e=[],o=!0}}),addStream:s(l=>{if(o)throw new Error("Cannot add inner stream: outer stream is closed");e.push(l.getReader()),a.resolve()},"addStream"),close:s(()=>{o=!0,a.resolve(),e.length===0&&t?.close()},"close"),terminate:n}}s($K,"createStitchableStream");function RK({tools:e,generatorStream:t,tracer:o,telemetry:a,system:n,messages:i,abortSignal:l,repairToolCall:u,experimental_context:c,generateId:d,stepNumber:p,model:m,onToolCallStart:f,onToolCallFinish:h}){let g=null,y=new ReadableStream({start(I){g=I}}),_=new Set,v=new Map,x=new Map,w=!1,S;function P(){w&&_.size===0&&(S!=null&&g.enqueue(S),g.close())}s(P,"attemptClose");let k=new TransformStream({async transform(I,E){let b=I.type;switch(b){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{E.enqueue(I);break}case"file":{E.enqueue({type:"file",file:new dK({data:I.data,mediaType:I.mediaType}),...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}});break}case"finish":{S={type:"finish",finishReason:I.finishReason.unified,rawFinishReason:I.finishReason.raw,usage:K0(I.usage),providerMetadata:I.providerMetadata};break}case"tool-approval-request":{let M=x.get(I.toolCallId);if(M==null){g.enqueue({type:"error",error:new eT({toolCallId:I.toolCallId,approvalId:I.approvalId})});break}E.enqueue({type:"tool-approval-request",approvalId:I.approvalId,toolCall:M});break}case"tool-call":{try{let M=await sN({toolCall:I,tools:e,repairToolCall:u,system:n,messages:i});if(x.set(M.toolCallId,M),E.enqueue(M),M.invalid){g.enqueue({type:"tool-error",toolCallId:M.toolCallId,toolName:M.toolName,input:M.input,error:Wl(M.error),dynamic:!0,title:M.title});break}let R=e?.[M.toolName];if(R==null)break;if(R.onInputAvailable!=null&&await R.onInputAvailable({input:M.input,toolCallId:M.toolCallId,messages:i,abortSignal:l,experimental_context:c}),await iN({tool:R,toolCall:M,messages:i,experimental_context:c})){g.enqueue({type:"tool-approval-request",approvalId:d(),toolCall:M});break}if(v.set(M.toolCallId,M.input),R.execute!=null&&M.providerExecuted!==!0){let D=d();_.add(D),aT({toolCall:M,tools:e,tracer:o,telemetry:a,messages:i,abortSignal:l,experimental_context:c,stepNumber:p,model:m,onToolCallStart:f,onToolCallFinish:h,onPreliminaryToolResult:s(te=>{g.enqueue(te)},"onPreliminaryToolResult")}).then(te=>{g.enqueue(te)}).catch(te=>{g.enqueue({type:"error",error:te})}).finally(()=>{_.delete(D),P()})}}catch(M){g.enqueue({type:"error",error:M})}break}case"tool-result":{let M=I.toolName;I.isError?g.enqueue({type:"tool-error",toolCallId:I.toolCallId,toolName:M,input:v.get(I.toolCallId),providerExecuted:!0,error:I.result,dynamic:I.dynamic,...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}}):E.enqueue({type:"tool-result",toolCallId:I.toolCallId,toolName:M,input:v.get(I.toolCallId),output:I.result,providerExecuted:!0,dynamic:I.dynamic,...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}});break}default:{let M=b;throw new Error(`Unhandled chunk type: ${M}`)}}},flush(){w=!0,P()}});return new ReadableStream({async start(I){return Promise.all([t.pipeThrough(k).pipeTo(new WritableStream({write(E){I.enqueue(E)},close(){}})),y.pipeTo(new WritableStream({write(E){I.enqueue(E)},close(){I.close()}}))])}})}s(RK,"runToolsTransformation");var zK=Xn({prefix:"aitxt",size:24});function gN({model:e,tools:t,toolChoice:o,system:a,prompt:n,messages:i,allowSystemInMessages:l,maxRetries:u,abortSignal:c,timeout:d,headers:p,stopWhen:m=nu(1),experimental_output:f,output:h=f,experimental_telemetry:g,prepareStep:y,providerOptions:_,experimental_activeTools:v,activeTools:x=v,experimental_repairToolCall:w,experimental_transform:S,experimental_download:P,includeRawChunks:k=!1,onChunk:I,onError:E=s(({error:z})=>{console.error(z)},"onError"),onFinish:b,onAbort:M,onStepFinish:R,experimental_onStart:D,experimental_onStepStart:te,experimental_onToolCallStart:ee,experimental_onToolCallFinish:J,experimental_context:W,experimental_include:j,_internal:{now:O=Vg,generateId:Z=zK}={},...F}){let z=nT(d),Y=Fz(d),ae=D8(d),K=Y!=null?new AbortController:void 0,he=ae!=null?new AbortController:void 0;return new jK({model:Zg(e),telemetry:g,headers:p,settings:F,maxRetries:u,abortSignal:pN(c,z!=null?AbortSignal.timeout(z):void 0,K?.signal,he?.signal),stepTimeoutMs:Y,stepAbortController:K,chunkTimeoutMs:ae,chunkAbortController:he,system:a,prompt:n,messages:i,allowSystemInMessages:l,tools:t,toolChoice:o,transforms:hs(S),activeTools:x,repairToolCall:w,stopConditions:hs(m),output:h,providerOptions:_,prepareStep:y,includeRawChunks:k,timeout:d,stopWhen:m,originalAbortSignal:c,onChunk:I,onError:E,onFinish:b,onAbort:M,onStepFinish:R,onStart:D,onStepStart:te,onToolCallStart:ee,onToolCallFinish:J,now:O,generateId:Z,experimental_context:W,download:P,include:j})}s(gN,"streamText");function NK(e){let t,o="",a="",n,i="";function l({controller:u,partialOutput:c=void 0}){u.enqueue({part:{type:"text-delta",id:t,text:a,providerMetadata:n},partialOutput:c}),a=""}return s(l,"publishTextChunk"),new TransformStream({async transform(u,c){var d;if(u.type==="finish-step"&&a.length>0&&l({controller:c}),u.type!=="text-delta"&&u.type!=="text-start"&&u.type!=="text-end"){c.enqueue({part:u,partialOutput:void 0});return}if(t==null)t=u.id;else if(u.id!==t){c.enqueue({part:u,partialOutput:void 0});return}if(u.type==="text-start"){c.enqueue({part:u,partialOutput:void 0});return}if(u.type==="text-end"){a.length>0&&l({controller:c}),c.enqueue({part:u,partialOutput:void 0});return}o+=u.text,a+=u.text,n=(d=u.providerMetadata)!=null?d:n;let p=await e.parsePartialOutput({text:o});if(p!==void 0){let m=typeof p.partial=="string"?p.partial:JSON.stringify(p.partial);m!==i&&(l({controller:c,partialOutput:p.partial}),i=m)}}})}s(NK,"createOutputTransformStream");var jK=class{static{s(this,"DefaultStreamTextResult")}constructor({model:e,telemetry:t,headers:o,settings:a,maxRetries:n,abortSignal:i,stepTimeoutMs:l,stepAbortController:u,chunkTimeoutMs:c,chunkAbortController:d,system:p,prompt:m,messages:f,allowSystemInMessages:h,tools:g,toolChoice:y,transforms:_,activeTools:v,repairToolCall:x,stopConditions:w,output:S,providerOptions:P,prepareStep:k,includeRawChunks:I,now:E,generateId:b,timeout:M,stopWhen:R,originalAbortSignal:D,onChunk:te,onError:ee,onFinish:J,onAbort:W,onStepFinish:j,onStart:O,onStepStart:Z,onToolCallStart:F,onToolCallFinish:z,experimental_context:Y,download:ae,include:K}){this._totalUsage=new ms,this._finishReason=new ms,this._rawFinishReason=new ms,this._steps=new ms,this.outputSpecification=S,this.includeRawChunks=I,this.tools=g;let L=rN()(t?.integrations),le,oe=[],ne=[],C,G,X,q={},Me=[],fe=[],at=new Map,rr,Tr={},gr={},Ho=new TransformStream({async transform(Rt,lr){var br,$o,pn,Jo;lr.enqueue(Rt);let{part:be}=Rt;if((be.type==="text-delta"||be.type==="reasoning-delta"||be.type==="source"||be.type==="tool-call"||be.type==="tool-result"||be.type==="tool-input-start"||be.type==="tool-input-delta"||be.type==="raw")&&await te?.({chunk:be}),be.type==="error"&&await ee({error:Qz(be.error)}),be.type==="text-start"&&(Tr[be.id]={type:"text",text:"",providerMetadata:be.providerMetadata},oe.push(Tr[be.id])),be.type==="text-delta"){let Ve=Tr[be.id];if(Ve==null){lr.enqueue({part:{type:"error",error:`text part ${be.id} not found`},partialOutput:void 0});return}Ve.text+=be.text,Ve.providerMetadata=(br=be.providerMetadata)!=null?br:Ve.providerMetadata}if(be.type==="text-end"){let Ve=Tr[be.id];if(Ve==null){lr.enqueue({part:{type:"error",error:`text part ${be.id} not found`},partialOutput:void 0});return}Ve.providerMetadata=($o=be.providerMetadata)!=null?$o:Ve.providerMetadata,delete Tr[be.id]}if(be.type==="reasoning-start"&&(gr[be.id]={type:"reasoning",text:"",providerMetadata:be.providerMetadata},oe.push(gr[be.id])),be.type==="reasoning-delta"){let Ve=gr[be.id];if(Ve==null){lr.enqueue({part:{type:"error",error:`reasoning part ${be.id} not found`},partialOutput:void 0});return}Ve.text+=be.text,Ve.providerMetadata=(pn=be.providerMetadata)!=null?pn:Ve.providerMetadata}if(be.type==="reasoning-end"){let Ve=gr[be.id];if(Ve==null){lr.enqueue({part:{type:"error",error:`reasoning part ${be.id} not found`},partialOutput:void 0});return}Ve.providerMetadata=(Jo=be.providerMetadata)!=null?Jo:Ve.providerMetadata,delete gr[be.id]}if(be.type==="file"&&oe.push({type:"file",file:be.file,...be.providerMetadata!=null?{providerMetadata:be.providerMetadata}:{}}),be.type==="source"&&oe.push(be),be.type==="tool-call"&&oe.push(be),be.type==="tool-result"&&!be.preliminary&&oe.push(be),be.type==="tool-approval-request"&&oe.push(be),be.type==="tool-error"&&oe.push(be),be.type==="start-step"&&(oe=[],gr={},Tr={},q=be.request,Me=be.warnings),be.type==="finish-step"){let Ve=await X0({content:oe,tools:g}),yr=new uN({stepNumber:fe.length,model:Ee,...He,experimental_context:Y,content:oe,finishReason:be.finishReason,rawFinishReason:be.rawFinishReason,usage:be.usage,warnings:Me,request:q,response:{...be.response,messages:[...ne,...Ve]},providerMetadata:be.providerMetadata});await Pn({event:yr,callbacks:[j,L.onStepFinish]}),gs({warnings:Me,provider:Ee.provider,model:Ee.modelId}),fe.push(yr),ne.push(...Ve),le.resolve()}be.type==="finish"&&(X=be.totalUsage,C=be.finishReason,G=be.rawFinishReason)},async flush(Rt){var lr,br,$o,pn,Jo,be,Ve;try{if(fe.length===0){let Dr=i?.aborted?i.reason:new bz({message:"No output generated. Check the stream for errors."});B._finishReason.reject(Dr),B._rawFinishReason.reject(Dr),B._totalUsage.reject(Dr),B._steps.reject(Dr);return}let yr=C??"other",ur=X??J0();B._finishReason.resolve(yr),B._rawFinishReason.resolve(G),B._totalUsage.resolve(ur),B._steps.resolve(fe);let je=fe[fe.length-1];await Pn({event:{stepNumber:je.stepNumber,model:je.model,functionId:je.functionId,metadata:je.metadata,experimental_context:je.experimental_context,finishReason:je.finishReason,rawFinishReason:je.rawFinishReason,totalUsage:ur,usage:je.usage,content:je.content,text:je.text,reasoningText:je.reasoningText,reasoning:je.reasoning,files:je.files,sources:je.sources,toolCalls:je.toolCalls,staticToolCalls:je.staticToolCalls,dynamicToolCalls:je.dynamicToolCalls,toolResults:je.toolResults,staticToolResults:je.staticToolResults,dynamicToolResults:je.dynamicToolResults,request:je.request,response:je.response,warnings:je.warnings,providerMetadata:je.providerMetadata,steps:fe},callbacks:[J,L.onFinish]}),rr.setAttributes(await sr({telemetry:t,attributes:{"ai.response.finishReason":yr,"ai.response.text":{output:s(()=>je.text,"output")},"ai.response.reasoning":{output:s(()=>je.reasoningText,"output")},"ai.response.toolCalls":{output:s(()=>{var Dr;return(Dr=je.toolCalls)!=null&&Dr.length?JSON.stringify(je.toolCalls):void 0},"output")},"ai.response.providerMetadata":JSON.stringify(je.providerMetadata),"ai.usage.inputTokens":ur.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(lr=ur.inputTokenDetails)==null?void 0:lr.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(br=ur.inputTokenDetails)==null?void 0:br.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":($o=ur.inputTokenDetails)==null?void 0:$o.cacheWriteTokens,"ai.usage.outputTokens":ur.outputTokens,"ai.usage.outputTokenDetails.textTokens":(pn=ur.outputTokenDetails)==null?void 0:pn.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Jo=ur.outputTokenDetails)==null?void 0:Jo.reasoningTokens,"ai.usage.totalTokens":ur.totalTokens,"ai.usage.reasoningTokens":(be=ur.outputTokenDetails)==null?void 0:be.reasoningTokens,"ai.usage.cachedInputTokens":(Ve=ur.inputTokenDetails)==null?void 0:Ve.cacheReadTokens}}))}catch(yr){Rt.error(yr)}finally{rr.end()}}}),Mr=$K();this.addStream=Mr.addStream,this.closeStream=Mr.close;let De=Mr.stream.getReader(),Wr=new ReadableStream({async start(Rt){Rt.enqueue({type:"start"})},async pull(Rt){function lr(){W?.({steps:fe}),Rt.enqueue({type:"abort",...i?.reason!==void 0?{reason:vn(i.reason)}:{}}),Rt.close()}s(lr,"abort");try{let{done:br,value:$o}=await De.read();if(br){Rt.close();return}if(i?.aborted){lr();return}Rt.enqueue($o)}catch(br){$a(br)&&i?.aborted?lr():Rt.error(br)}},cancel(Rt){return Mr.stream.cancel(Rt)}});for(let Rt of _)Wr=Wr.pipeThrough(Rt({tools:g,stopStream(){Mr.terminate()}}));this.baseStream=Wr.pipeThrough(NK(S??Wg())).pipeThrough(Ho);let{maxRetries:dn,retry:Bn}=hp({maxRetries:n,abortSignal:i}),Oo=Kg(t),Kt=G0(a),T=Gg({model:e,telemetry:t,headers:o,settings:{...Kt,maxRetries:dn}}),B=this,Ee={provider:e.provider,modelId:e.modelId},He={functionId:t?.functionId,metadata:t?.metadata};aa({name:"ai.streamText",attributes:sr({telemetry:t,attributes:{...na({operationId:"ai.streamText",telemetry:t}),...T,"ai.prompt":{input:s(()=>JSON.stringify({system:p,prompt:m,messages:f}),"input")}}}),tracer:Oo,endWhenDone:!1,fn:s(async Rt=>{rr=Rt;let lr=await Yz({system:p,prompt:m,messages:f,allowSystemInMessages:h});await Pn({event:{model:Ee,system:p,prompt:m,messages:f,tools:g,toolChoice:y,activeTools:v,maxOutputTokens:Kt.maxOutputTokens,temperature:Kt.temperature,topP:Kt.topP,topK:Kt.topK,presencePenalty:Kt.presencePenalty,frequencyPenalty:Kt.frequencyPenalty,stopSequences:Kt.stopSequences,seed:Kt.seed,maxRetries:dn,timeout:M,headers:o,providerOptions:P,stopWhen:R,output:S,abortSignal:D,include:K,...He,experimental_context:Y},callbacks:[O,L.onStart]});let br=lr.messages,$o=[],{approvedToolApprovals:pn,deniedToolApprovals:Jo}=aN({messages:br});if(Jo.length>0||pn.length>0){let Ve=pn.filter(Xe=>!Xe.toolCall.providerExecuted),yr=Jo.filter(Xe=>!Xe.toolCall.providerExecuted),ur=Jo.filter(Xe=>Xe.toolCall.providerExecuted),je,Dr=new ReadableStream({start(Xe){je=Xe}});B.addStream(Dr);try{for(let or of[...yr,...ur])je?.enqueue({type:"tool-output-denied",toolCallId:or.toolCall.toolCallId,toolName:or.toolCall.toolName});let Xe=[];if(await Promise.all(Ve.map(async or=>{let nr=await aT({toolCall:or.toolCall,tools:g,tracer:Oo,telemetry:t,messages:br,abortSignal:i,experimental_context:Y,stepNumber:fe.length,model:Ee,onToolCallStart:[F,L.onToolCallStart],onToolCallFinish:[z,L.onToolCallFinish],onPreliminaryToolResult:s(Er=>{je?.enqueue(Er)},"onPreliminaryToolResult")});nr!=null&&(je?.enqueue(nr),Xe.push(nr))})),Xe.length>0||yr.length>0){let or=[];for(let nr of Xe)or.push({type:"tool-result",toolCallId:nr.toolCallId,toolName:nr.toolName,output:await pp({toolCallId:nr.toolCallId,input:nr.input,tool:g?.[nr.toolName],output:nr.type==="tool-result"?nr.output:nr.error,errorMode:nr.type==="tool-error"?"text":"none"})});for(let nr of yr)or.push({type:"tool-result",toolCallId:nr.toolCall.toolCallId,toolName:nr.toolCall.toolName,output:{type:"execution-denied",reason:nr.approvalResponse.reason}});$o.push({role:"tool",content:or})}}finally{je?.close()}}ne.push(...$o);async function be({currentStep:Ve,responseMessages:yr,usage:ur}){var je,Dr,Xe,or,nr,Er,Ur,ut,co;let Ha=B.includeRawChunks,Nu=l!=null?setTimeout(()=>u.abort(),l):void 0,ga;function qs(){c!=null&&(ga!=null&&clearTimeout(ga),ga=setTimeout(()=>d.abort(),c))}s(qs,"resetChunkTimeout");function Fs(){ga!=null&&(clearTimeout(ga),ga=void 0)}s(Fs,"clearChunkTimeout");function Am(){Nu!=null&&clearTimeout(Nu)}s(Am,"clearStepTimeout");try{le=new ms;let Ja=[...br,...yr],pr=await k?.({model:e,steps:fe,stepNumber:fe.length,messages:Ja,experimental_context:Y}),po=Zg((je=pr?.model)!=null?je:e),Bs={provider:po.provider,modelId:po.modelId},Cm=await Jz({prompt:{system:(Dr=pr?.system)!=null?Dr:lr.system,messages:(Xe=pr?.messages)!=null?Xe:Ja},supportedUrls:await po.supportedUrls,download:ae}),ju=(or=pr?.activeTools)!=null?or:v,{toolChoice:Vs,tools:Mu}=await Wz({tools:g,toolChoice:(nr=pr?.toolChoice)!=null?nr:y,activeTools:ju});Y=(Er=pr?.experimental_context)!=null?Er:Y;let q_=(Ur=pr?.messages)!=null?Ur:Ja,Om=(ut=pr?.system)!=null?ut:lr.system,ct=Xg(P,pr?.providerOptions);await Pn({event:{stepNumber:fe.length,model:Bs,system:Om,messages:q_,tools:g,toolChoice:Vs,activeTools:ju,steps:[...fe],providerOptions:ct,timeout:M,headers:o,stopWhen:R,output:S,abortSignal:D,include:K,...He,experimental_context:Y},callbacks:[Z,L.onStepStart]});let{result:{stream:Gr,response:Zs,request:ya},doStreamSpan:Vn,startTimestampMs:Du}=await Bn(()=>aa({name:"ai.streamText.doStream",attributes:sr({telemetry:t,attributes:{...na({operationId:"ai.streamText.doStream",telemetry:t}),...T,"ai.model.provider":po.provider,"ai.model.id":po.modelId,"ai.prompt.messages":{input:s(()=>tN(Cm),"input")},"ai.prompt.tools":{input:s(()=>Mu?.map(qe=>JSON.stringify(qe)),"input")},"ai.prompt.toolChoice":{input:s(()=>Vs!=null?JSON.stringify(Vs):void 0,"input")},"gen_ai.system":po.provider,"gen_ai.request.model":po.modelId,"gen_ai.request.frequency_penalty":Kt.frequencyPenalty,"gen_ai.request.max_tokens":Kt.maxOutputTokens,"gen_ai.request.presence_penalty":Kt.presencePenalty,"gen_ai.request.stop_sequences":Kt.stopSequences,"gen_ai.request.temperature":Kt.temperature,"gen_ai.request.top_k":Kt.topK,"gen_ai.request.top_p":Kt.topP}}),tracer:Oo,endWhenDone:!1,fn:s(async qe=>({startTimestampMs:E(),doStreamSpan:qe,result:await po.doStream({...Kt,tools:Mu,toolChoice:Vs,responseFormat:await S?.responseFormat,prompt:Cm,providerOptions:ct,abortSignal:i,headers:o,includeRawChunks:Ha})}),"fn")})),$m=RK({tools:g,generatorStream:Gr,tracer:Oo,telemetry:t,system:p,messages:Ja,repairToolCall:x,abortSignal:i,experimental_context:Y,generateId:b,stepNumber:fe.length,model:Bs,onToolCallStart:[F,L.onToolCallStart],onToolCallFinish:[z,L.onToolCallFinish]}),Rm=(co=K?.requestBody)==null||co?ya??{}:{...ya,body:void 0},Wa=[],Ga=[],Lt,Zn={},Ka="other",Hs,Lr=J0(),Gk,Kk=!0,Hn={id:b(),timestamp:new Date,modelId:Ee.modelId},sB="";B.addStream($m.pipeThrough(new TransformStream({async transform(qe,Sr){var Uu,Lu,qu,Fu,Bu;if(qs(),qe.type==="stream-start"){Lt=qe.warnings;return}if(Kk){let xr=E()-Du;Kk=!1,Vn.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":xr}),Vn.setAttributes({"ai.response.msToFirstChunk":xr}),Sr.enqueue({type:"start-step",request:Rm,warnings:Lt??[]})}let Vu=qe.type;switch(Vu){case"tool-approval-request":case"text-start":case"text-end":{Sr.enqueue(qe);break}case"text-delta":{qe.delta.length>0&&(Sr.enqueue({type:"text-delta",id:qe.id,text:qe.delta,providerMetadata:qe.providerMetadata}),sB+=qe.delta);break}case"reasoning-start":case"reasoning-end":{Sr.enqueue(qe);break}case"reasoning-delta":{Sr.enqueue({type:"reasoning-delta",id:qe.id,text:qe.delta,providerMetadata:qe.providerMetadata});break}case"tool-call":{Sr.enqueue(qe),Wa.push(qe);break}case"tool-result":{Sr.enqueue(qe),qe.preliminary||Ga.push(qe);break}case"tool-error":{Sr.enqueue(qe),Ga.push(qe);break}case"response-metadata":{Hn={id:(Uu=qe.id)!=null?Uu:Hn.id,timestamp:(Lu=qe.timestamp)!=null?Lu:Hn.timestamp,modelId:(qu=qe.modelId)!=null?qu:Hn.modelId};break}case"finish":{Lr=qe.usage,Ka=qe.finishReason,Hs=qe.rawFinishReason,Gk=qe.providerMetadata;let xr=E()-Du;Vn.addEvent("ai.stream.finish"),Vn.setAttributes({"ai.response.msToFinish":xr,"ai.response.avgOutputTokensPerSecond":1e3*((Fu=Lr.outputTokens)!=null?Fu:0)/xr});break}case"file":{Sr.enqueue(qe);break}case"source":{Sr.enqueue(qe);break}case"tool-input-start":{Zn[qe.id]=qe.toolName;let xr=g?.[qe.toolName];xr?.onInputStart!=null&&await xr.onInputStart({toolCallId:qe.id,messages:Ja,abortSignal:i,experimental_context:Y}),Sr.enqueue({...qe,dynamic:(Bu=qe.dynamic)!=null?Bu:xr?.type==="dynamic",title:xr?.title});break}case"tool-input-end":{delete Zn[qe.id],Sr.enqueue(qe);break}case"tool-input-delta":{let xr=Zn[qe.id],Js=g?.[xr];Js?.onInputDelta!=null&&await Js.onInputDelta({inputTextDelta:qe.delta,toolCallId:qe.id,messages:Ja,abortSignal:i,experimental_context:Y}),Sr.enqueue(qe);break}case"error":{Sr.enqueue(qe),Ka="error";break}case"raw":{Ha&&Sr.enqueue(qe);break}default:{let xr=Vu;throw new Error(`Unknown chunk type: ${xr}`)}}},async flush(qe){var Sr,Uu,Lu,qu,Fu,Bu,Vu;let xr=Wa.length>0?JSON.stringify(Wa):void 0;try{Vn.setAttributes(await sr({telemetry:t,attributes:{"ai.response.finishReason":Ka,"ai.response.toolCalls":{output:s(()=>xr,"output")},"ai.response.id":Hn.id,"ai.response.model":Hn.modelId,"ai.response.timestamp":Hn.timestamp.toISOString(),"ai.usage.inputTokens":Lr.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Sr=Lr.inputTokenDetails)==null?void 0:Sr.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Uu=Lr.inputTokenDetails)==null?void 0:Uu.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Lu=Lr.inputTokenDetails)==null?void 0:Lu.cacheWriteTokens,"ai.usage.outputTokens":Lr.outputTokens,"ai.usage.outputTokenDetails.textTokens":(qu=Lr.outputTokenDetails)==null?void 0:qu.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Fu=Lr.outputTokenDetails)==null?void 0:Fu.reasoningTokens,"ai.usage.totalTokens":Lr.totalTokens,"ai.usage.reasoningTokens":(Bu=Lr.outputTokenDetails)==null?void 0:Bu.reasoningTokens,"ai.usage.cachedInputTokens":(Vu=Lr.inputTokenDetails)==null?void 0:Vu.cacheReadTokens,"gen_ai.response.finish_reasons":[Ka],"gen_ai.response.id":Hn.id,"gen_ai.response.model":Hn.modelId,"gen_ai.usage.input_tokens":Lr.inputTokens,"gen_ai.usage.output_tokens":Lr.outputTokens}}))}catch{}qe.enqueue({type:"finish-step",finishReason:Ka,rawFinishReason:Hs,usage:Lr,providerMetadata:Gk,response:{...Hn,headers:Zs?.headers}});let Js=oN(ur,Lr);await le.promise;let F_=fe[fe.length-1];try{Vn.setAttributes(await sr({telemetry:t,attributes:{"ai.response.text":{output:s(()=>F_.text,"output")},"ai.response.reasoning":{output:s(()=>F_.reasoningText,"output")},"ai.response.providerMetadata":JSON.stringify(F_.providerMetadata)}}))}catch{}finally{Vn.end()}let Xk=Wa.filter(Ar=>Ar.providerExecuted!==!0),lB=Ga.filter(Ar=>Ar.providerExecuted!==!0);for(let Ar of Wa){if(Ar.providerExecuted!==!0)continue;let B_=g?.[Ar.toolName];B_?.type==="provider"&&B_.supportsDeferredResults&&(Ga.some(V_=>(V_.type==="tool-result"||V_.type==="tool-error")&&V_.toolCallId===Ar.toolCallId)||at.set(Ar.toolCallId,{toolName:Ar.toolName}))}for(let Ar of Ga)(Ar.type==="tool-result"||Ar.type==="tool-error")&&at.delete(Ar.toolCallId);if(Am(),Fs(),(Xk.length>0&&lB.length===Xk.length||at.size>0)&&!await dN({stopConditions:w,steps:fe})){yr.push(...await X0({content:fe[fe.length-1].content,tools:g}));try{await be({currentStep:Ve+1,responseMessages:yr,usage:Js})}catch(Ar){qe.enqueue({type:"error",error:Ar}),B.closeStream()}}else qe.enqueue({type:"finish",finishReason:Ka,rawFinishReason:Hs,totalUsage:Js}),B.closeStream()}})))}finally{Am(),Fs()}}s(be,"streamStep"),await be({currentStep:0,responseMessages:$o,usage:J0()})},"fn")}).catch(Rt=>{B.addStream(new ReadableStream({start(lr){lr.enqueue({type:"error",error:Rt}),lr.close()}})),B.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return dp(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return dp(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await OK({stream:this.fullStream,onError:e?.onError})}catch(o){(t=e?.onError)==null||t.call(e,o)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return dp(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,o;let a=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(a==null)throw new Le({functionality:`element streams in ${(o=(t=this.outputSpecification)==null?void 0:t.name)!=null?o:"text"} mode`});return dp(this.teeStream().pipeThrough(a))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:Wg()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:o,messageMetadata:a,sendReasoning:n=!0,sendSources:i=!1,sendStart:l=!0,sendFinish:u=!0,onError:c=vn}={}){let d=t!=null?SK({originalMessages:e,responseMessageId:t}):void 0,p=s(f=>{var h;let g=(h=this.tools)==null?void 0:h[f.toolName];return g==null?f.dynamic:g?.type==="dynamic"?!0:void 0},"isDynamic"),m=this.fullStream.pipeThrough(new TransformStream({transform:s(async(f,h)=>{let g=a?.({part:f}),y=f.type;switch(y){case"text-start":{h.enqueue({type:"text-start",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-start":case"reasoning-end":{n&&h.enqueue({type:y,id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-delta":{n&&h.enqueue({type:"reasoning-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:f.file.mediaType,url:`data:${f.file.mediaType};base64,${f.file.base64}`,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"source":{i&&f.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:f.id,url:f.url,title:f.title,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}}),i&&f.sourceType==="document"&&h.enqueue({type:"source-document",sourceId:f.id,mediaType:f.mediaType,title:f.title,filename:f.filename,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"tool-input-start":{let _=p(f);h.enqueue({type:"tool-input-start",toolCallId:f.id,toolName:f.toolName,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},..._!=null?{dynamic:_}:{},...f.title!=null?{title:f.title}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:f.id,inputTextDelta:f.delta});break}case"tool-call":{let _=p(f);f.invalid?h.enqueue({type:"tool-input-error",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},..._!=null?{dynamic:_}:{},errorText:c(f.error),...f.title!=null?{title:f.title}:{}}):h.enqueue({type:"tool-input-available",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},..._!=null?{dynamic:_}:{},...f.title!=null?{title:f.title}:{}});break}case"tool-approval-request":{h.enqueue({type:"tool-approval-request",approvalId:f.approvalId,toolCallId:f.toolCall.toolCallId});break}case"tool-result":{let _=p(f);h.enqueue({type:"tool-output-available",toolCallId:f.toolCallId,output:f.output,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},...f.preliminary!=null?{preliminary:f.preliminary}:{},..._!=null?{dynamic:_}:{}});break}case"tool-error":{let _=p(f);h.enqueue({type:"tool-output-error",toolCallId:f.toolCallId,errorText:f.providerExecuted?typeof f.error=="string"?f.error:JSON.stringify(f.error):c(f.error),...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},..._!=null?{dynamic:_}:{}});break}case"tool-output-denied":{h.enqueue({type:"tool-output-denied",toolCallId:f.toolCallId});break}case"error":{h.enqueue({type:"error",errorText:c(f.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{l&&h.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...d!=null?{messageId:d}:{}});break}case"finish":{u&&h.enqueue({type:"finish",finishReason:f.finishReason,...g!=null?{messageMetadata:g}:{}});break}case"abort":{h.enqueue(f);break}case"tool-input-end":break;case"raw":break;default:{let _=y;throw new Error(`Unknown chunk type: ${_}`)}}g!=null&&y!=="start"&&y!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:g})},"transform")}));return dp(AK({stream:m,messageId:d??t?.(),originalMessages:e,onFinish:o,onError:c}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:o,onFinish:a,messageMetadata:n,sendReasoning:i,sendSources:l,sendFinish:u,sendStart:c,onError:d,...p}={}){CK({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:o,onFinish:a,messageMetadata:n,sendReasoning:i,sendSources:l,sendFinish:u,sendStart:c,onError:d}),...p})}pipeTextStreamToResponse(e,t){wK({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:o,messageMetadata:a,sendReasoning:n,sendSources:i,sendFinish:l,sendStart:u,onError:c,...d}={}){return TK({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:o,messageMetadata:a,sendReasoning:n,sendSources:i,sendFinish:l,sendStart:u,onError:c}),...d})}toTextStreamResponse(e){return xK({textStream:this.textStream,...e})}};var pze=N(()=>$(r.array(r.object({id:r.string(),role:r.enum(["system","user","assistant"]),metadata:r.unknown().optional(),parts:r.array(r.union([r.object({type:r.literal("text"),text:r.string(),state:r.enum(["streaming","done"]).optional(),providerMetadata:ze.optional()}),r.object({type:r.literal("reasoning"),text:r.string(),state:r.enum(["streaming","done"]).optional(),providerMetadata:ze.optional()}),r.object({type:r.literal("source-url"),sourceId:r.string(),url:r.string(),title:r.string().optional(),providerMetadata:ze.optional()}),r.object({type:r.literal("source-document"),sourceId:r.string(),mediaType:r.string(),title:r.string(),filename:r.string().optional(),providerMetadata:ze.optional()}),r.object({type:r.literal("file"),mediaType:r.string(),filename:r.string().optional(),url:r.string(),providerMetadata:ze.optional()}),r.object({type:r.literal("step-start")}),r.object({type:r.string().startsWith("data-"),id:r.string().optional(),data:r.unknown()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("input-streaming"),input:r.unknown().optional(),providerExecuted:r.boolean().optional(),callProviderMetadata:ze.optional(),output:r.never().optional(),errorText:r.never().optional(),approval:r.never().optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("input-available"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.never().optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("approval-requested"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.never().optional(),reason:r.never().optional()})}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("approval-responded"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.boolean(),reason:r.string().optional()})}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("output-available"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.unknown(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),resultProviderMetadata:ze.optional(),preliminary:r.boolean().optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional()}).optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("output-error"),input:r.unknown(),rawInput:r.unknown().optional(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.string(),callProviderMetadata:ze.optional(),resultProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional()}).optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("output-denied"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.literal(!1),reason:r.string().optional()})}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("input-streaming"),providerExecuted:r.boolean().optional(),callProviderMetadata:ze.optional(),input:r.unknown().optional(),output:r.never().optional(),errorText:r.never().optional(),approval:r.never().optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("input-available"),providerExecuted:r.boolean().optional(),input:r.unknown(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.never().optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("approval-requested"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.never().optional(),reason:r.never().optional()})}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("approval-responded"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.boolean(),reason:r.string().optional()})}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("output-available"),providerExecuted:r.boolean().optional(),input:r.unknown(),output:r.unknown(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),resultProviderMetadata:ze.optional(),preliminary:r.boolean().optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional()}).optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("output-error"),providerExecuted:r.boolean().optional(),input:r.unknown(),rawInput:r.unknown().optional(),output:r.never().optional(),errorText:r.string(),callProviderMetadata:ze.optional(),resultProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional()}).optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("output-denied"),providerExecuted:r.boolean().optional(),input:r.unknown(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.literal(!1),reason:r.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));async function yN({model:e,value:t,providerOptions:o,maxRetries:a,abortSignal:n,headers:i,experimental_telemetry:l}){let u=qz(e),{maxRetries:c,retry:d}=hp({maxRetries:a,abortSignal:n}),p=Qt(i??{},`ai/${fp}`),m=Gg({model:u,telemetry:l,headers:p,settings:{maxRetries:c}}),f=Kg(l);return aa({name:"ai.embed",attributes:sr({telemetry:l,attributes:{...na({operationId:"ai.embed",telemetry:l}),...m,"ai.value":{input:s(()=>JSON.stringify(t),"input")}}}),tracer:f,fn:s(async h=>{let{embedding:g,usage:y,warnings:_,response:v,providerMetadata:x}=await d(()=>aa({name:"ai.embed.doEmbed",attributes:sr({telemetry:l,attributes:{...na({operationId:"ai.embed.doEmbed",telemetry:l}),...m,"ai.values":{input:s(()=>[JSON.stringify(t)],"input")}}}),tracer:f,fn:s(async w=>{var S;let P=await u.doEmbed({values:[t],abortSignal:n,headers:p,providerOptions:o}),k=P.embeddings[0],I=(S=P.usage)!=null?S:{tokens:NaN};return w.setAttributes(await sr({telemetry:l,attributes:{"ai.embeddings":{output:s(()=>P.embeddings.map(E=>JSON.stringify(E)),"output")},"ai.usage.tokens":I.tokens}})),{embedding:k,usage:I,warnings:P.warnings,providerMetadata:P.providerMetadata,response:P.response}},"fn")}));return h.setAttributes(await sr({telemetry:l,attributes:{"ai.embedding":{output:s(()=>JSON.stringify(g),"output")},"ai.usage.tokens":y.tokens}})),gs({warnings:_,provider:u.provider,model:u.modelId}),new MK({value:t,embedding:g,usage:y,warnings:_,providerMetadata:x,response:v})},"fn")})}s(yN,"embed");var MK=class{static{s(this,"DefaultEmbedResult")}constructor(e){this.value=e.value,this.embedding=e.embedding,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.response=e.response}};function JR(e,t){if(t<=0)throw new Error("chunkSize must be greater than 0");let o=[];for(let a=0;a<e.length;a+=t)o.push(e.slice(a,a+t));return o}s(JR,"splitArray");async function _N({model:e,values:t,maxParallelCalls:o=1/0,maxRetries:a,abortSignal:n,headers:i,providerOptions:l,experimental_telemetry:u}){let c=qz(e),{maxRetries:d,retry:p}=hp({maxRetries:a,abortSignal:n}),m=Qt(i??{},`ai/${fp}`),f=Gg({model:c,telemetry:u,headers:m,settings:{maxRetries:d}}),h=Kg(u);return aa({name:"ai.embedMany",attributes:sr({telemetry:u,attributes:{...na({operationId:"ai.embedMany",telemetry:u}),...f,"ai.values":{input:s(()=>t.map(g=>JSON.stringify(g)),"input")}}}),tracer:h,fn:s(async g=>{var y;let[_,v]=await Promise.all([c.maxEmbeddingsPerCall,c.supportsParallelCalls]);if(_==null||_===1/0){let{embeddings:b,usage:M,warnings:R,response:D,providerMetadata:te}=await p(()=>aa({name:"ai.embedMany.doEmbed",attributes:sr({telemetry:u,attributes:{...na({operationId:"ai.embedMany.doEmbed",telemetry:u}),...f,"ai.values":{input:s(()=>t.map(ee=>JSON.stringify(ee)),"input")}}}),tracer:h,fn:s(async ee=>{var J;let W=await c.doEmbed({values:t,abortSignal:n,headers:m,providerOptions:l}),j=W.embeddings,O=(J=W.usage)!=null?J:{tokens:NaN};return ee.setAttributes(await sr({telemetry:u,attributes:{"ai.embeddings":{output:s(()=>j.map(Z=>JSON.stringify(Z)),"output")},"ai.usage.tokens":O.tokens}})),{embeddings:j,usage:O,warnings:W.warnings,providerMetadata:W.providerMetadata,response:W.response}},"fn")}));return g.setAttributes(await sr({telemetry:u,attributes:{"ai.embeddings":{output:s(()=>b.map(ee=>JSON.stringify(ee)),"output")},"ai.usage.tokens":M.tokens}})),gs({warnings:R,provider:c.provider,model:c.modelId}),new WR({values:t,embeddings:b,usage:M,warnings:R,providerMetadata:te,responses:[D]})}let x=JR(t,_),w=[],S=[],P=[],k=0,I,E=JR(x,v?o:1);for(let b of E){let M=await Promise.all(b.map(R=>p(()=>aa({name:"ai.embedMany.doEmbed",attributes:sr({telemetry:u,attributes:{...na({operationId:"ai.embedMany.doEmbed",telemetry:u}),...f,"ai.values":{input:s(()=>R.map(D=>JSON.stringify(D)),"input")}}}),tracer:h,fn:s(async D=>{var te;let ee=await c.doEmbed({values:R,abortSignal:n,headers:m,providerOptions:l}),J=ee.embeddings,W=(te=ee.usage)!=null?te:{tokens:NaN};return D.setAttributes(await sr({telemetry:u,attributes:{"ai.embeddings":{output:s(()=>J.map(j=>JSON.stringify(j)),"output")},"ai.usage.tokens":W.tokens}})),{embeddings:J,usage:W,warnings:ee.warnings,providerMetadata:ee.providerMetadata,response:ee.response}},"fn")}))));for(let R of M)if(w.push(...R.embeddings),S.push(...R.warnings),P.push(R.response),k+=R.usage.tokens,R.providerMetadata)if(!I)I={...R.providerMetadata};else for(let[D,te]of Object.entries(R.providerMetadata))I[D]={...(y=I[D])!=null?y:{},...te}}return g.setAttributes(await sr({telemetry:u,attributes:{"ai.embeddings":{output:s(()=>w.map(b=>JSON.stringify(b)),"output")},"ai.usage.tokens":k}})),gs({warnings:S,provider:c.provider,model:c.modelId}),new WR({values:t,embeddings:w,usage:{tokens:k},warnings:S,providerMetadata:I,responses:P})},"fn")})}s(_N,"embedMany");var WR=class{static{s(this,"DefaultEmbedManyResult")}constructor(e){this.values=e.values,this.embeddings=e.embeddings,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.responses=e.responses}};async function vN({model:e,prompt:t,n:o=1,maxImagesPerCall:a,size:n,aspectRatio:i,seed:l,providerOptions:u,maxRetries:c,abortSignal:d,headers:p}){var m,f;let h=M8(e),g=Qt(p??{},`ai/${fp}`),{retry:y}=hp({maxRetries:c,abortSignal:d}),_=(m=a??await UK(h))!=null?m:1,v=Math.ceil(o/_),x=Array.from({length:v},(b,M)=>{if(M<v-1)return _;let R=o%_;return R===0?_:R}),w=await Promise.all(x.map(async b=>y(()=>{let{prompt:M,files:R,mask:D}=LK(t);return h.doGenerate({prompt:M,files:R,mask:D,n:b,abortSignal:d,headers:g,size:n,aspectRatio:i,seed:l,providerOptions:u??{}})}))),S=[],P=[],k=[],I={},E={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};for(let b of w){if(S.push(...b.images.map(M=>{var R;return new iT({data:M,mediaType:(R=Jg({data:M,signatures:Hg}))!=null?R:"image/png"})})),P.push(...b.warnings),b.usage!=null&&(E=lK(E,b.usage)),b.providerMetadata)for(let[M,R]of Object.entries(b.providerMetadata))if(M==="gateway"){let D=I[M];D!=null&&typeof D=="object"?I[M]={...D,...R}:I[M]=R;let te=I[M].images;Array.isArray(te)&&te.length===0&&delete I[M].images}else(f=I[M])!=null||(I[M]={images:[]}),I[M].images.push(...b.providerMetadata[M].images);k.push(b.response)}if(gs({warnings:P,provider:h.provider,model:h.modelId}),!S.length)throw new n8({responses:k});return new DK({images:S,warnings:P,responses:k,providerMetadata:I,usage:E})}s(vN,"generateImage");var DK=class{static{s(this,"DefaultGenerateImageResult")}constructor(e){this.images=e.images,this.warnings=e.warnings,this.responses=e.responses,this.providerMetadata=e.providerMetadata,this.usage=e.usage}get image(){return this.images[0]}};async function UK(e){return e.maxImagesPerCall instanceof Function?e.maxImagesPerCall({modelId:e.modelId}):e.maxImagesPerCall}s(UK,"invokeModelMaxImagesPerCall");function LK(e){return typeof e=="string"?{prompt:e,files:void 0,mask:void 0}:{prompt:e.text,files:e.images.map(GR),mask:e.mask?GR(e.mask):void 0}}s(LK,"normalizePrompt");function GR(e){if(typeof e=="string"&&e.startsWith("http"))return{type:"url",url:e};if(typeof e=="string"&&e.startsWith("data:")){let{mediaType:o,base64Content:a}=Vz(e);if(a!=null){let n=Yt(a);return{type:"file",data:n,mediaType:o||Jg({data:n,signatures:Hg})||"image/png"}}}let t=B8(e);return{type:"file",data:t,mediaType:Jg({data:t,signatures:Hg})||"image/png"}}s(GR,"toImageModelV3File");var yze=Xn({prefix:"aiobj",size:24});function bN(e){return({url:t,abortSignal:o})=>Bz({url:t,maxBytes:e?.maxBytes,abortSignal:o})}s(bN,"createDownload");var vze=Xn({prefix:"aiobj",size:24});var bze=bN();var qK="AI_NoSuchProviderError",FK=`vercel.ai.error.${qK}`,BK=Symbol.for(FK),VK;VK=BK;var xze=bN();var TN=require("node:stream");var Qg=class{constructor(t,o){this.baseUrl=t;this.authenticationConverter=o}static{s(this,"BaseHttpClient")}getUrl(t){let o=new URL(`${this.baseUrl}${t.url}`),a=`${o.origin}${o.pathname}`,n=new URLSearchParams;return o.searchParams.forEach((i,l)=>{n.append(l,i)}),{urlWithoutQueryParams:a,queryParams:n}}getHeaders(t){let o={Accept:"application/json"};return t.authentication&&this.populateAuthentication(t.authentication,o),t.body&&(t.headers?.["Content-Type"]==="text/csv"?o["Content-Type"]="text/csv":o["Content-Type"]="application/json"),t.headers&&(o={...o,...t.headers}),o}populateAuthentication(t,o){this.authenticationConverter.convert(t,o)}};var ey=class{static{s(this,"DelegatingAuthenticationConverter")}constructor(t=new sT,o=new lT){this.converters={BEARER_TOKEN:t,BASIC:o}}convert(t,o){return this.converters[t.type].convert(t,o)}},sT=class{static{s(this,"BearerTokenAuthenticationConverter")}convert(t,o){return o.Authorization=`Bearer ${t.token}`,o}},lT=class{static{s(this,"BasicTokenAuthenticationConverter")}convert(t,o){let a=`${t.username}:${t.password}`,n=Buffer.from(a).toString("base64");return o.Authorization=`Basic ${n}`,o}};var ty=class extends Error{constructor(o,a){let n=a.status||500,i=Buffer.isBuffer(a.responseBody)?a.responseBody.toString():a.responseBody;super(JSON.stringify({response:{status:n,body:i},request:{body:o}}));this.requestBody=o;this.status=n,this.responseBody=i}static{s(this,"HttpError")}errorMessage(){return{response:{status:this.status,body:this.responseBody},request:{body:this.requestBody}}}get response(){return{status:this.status,body:this.responseBody}}get request(){return{body:this.requestBody}}};var ry=class extends Qg{static{s(this,"FetchHttpClient")}constructor(t="",o=new ey){super(t,o)}async sendRequest(t,o){process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";let{urlWithoutQueryParams:a,queryParams:n}=this.getUrl(t),i=this.getHeaders(t),l=t.queryParams??{};for(let[w,S]of Object.entries(l))n.append(w,S);let u=n.toString(),c=u?`${a}?${u}`:a,d=t.responseType??"json",p=t.followRedirects??!0,m=t.retries??0,{body:f,extraHeaders:h,isStream:g}=ZK(t.body,i),y=JK({...i,...h}),_=await HK(async()=>{let w=new AbortController,S=t.timeout&&t.timeout>0?setTimeout(()=>w.abort(),t.timeout):void 0;try{let P={method:t.method.toString(),headers:y,body:f,redirect:p?"follow":"manual",signal:w.signal};return g&&(P.duplex="half"),o?.dispatcher!==void 0&&(P.dispatcher=o.dispatcher),await fetch(c,P)}finally{S!==void 0&&clearTimeout(S)}},m),v=p?300:400;if(_.status<200||_.status>=v){let w=await xN(_,d),S=new ty(t.body,{status:_.status,responseBody:w});throw console.error("[HttpClient#(sanitized error message)] Request failed:",S),S}let x=await xN(_,d);return{status:_.status,headers:WK(_.headers),body:x}}};function ZK(e,t){if(KK(e))return{body:void 0,extraHeaders:{},isStream:!1};if(GK(e)){let a=new TN.PassThrough;return e.on("error",n=>a.destroy(n)),e.pipe(a),{body:a,extraHeaders:e.getHeaders(),isStream:!0}}return typeof e=="string"||Buffer.isBuffer(e)||e instanceof URLSearchParams||e instanceof ArrayBuffer||typeof FormData<"u"&&e instanceof FormData||typeof Blob<"u"&&e instanceof Blob?{body:e,extraHeaders:{},isStream:!1}:(t["Content-Type"]??t["content-type"]??"").includes("application/x-www-form-urlencoded")?{body:new URLSearchParams(e).toString(),extraHeaders:{},isStream:!1}:{body:JSON.stringify(e),extraHeaders:{},isStream:!1}}s(ZK,"serializeBody");async function xN(e,t){switch(t){case"arraybuffer":return Buffer.from(await e.arrayBuffer());case"blob":return await e.blob();case"text":return await e.text();default:{let o=await e.text();if(o.length===0)return;try{return JSON.parse(o)}catch{return o}}}}s(xN,"parseResponseBody");async function HK(e,t){let o;for(let a=0;a<=t;a++)try{let n=await e();if(n.status>=500&&a<t){await wN(a);continue}return n}catch(n){if(o=n,a<t){await wN(a);continue}throw n}throw o}s(HK,"sendWithRetries");function wN(e){let t=Math.min(1e3*2**e,3e4);return new Promise(o=>setTimeout(o,t))}s(wN,"backoff");function JK(e){let t={};for(let[o,a]of Object.entries(e))a!==void 0&&(t[o.toLowerCase()]=Array.isArray(a)?a.join(", "):a);return t}s(JK,"normalizeHeaders");function WK(e){let t={};return e.forEach((o,a)=>{t[a]=o}),t}s(WK,"toHttpHeaders");function GK(e){return typeof e=="object"&&e!==null&&typeof e.getHeaders=="function"&&typeof e.pipe=="function"&&typeof e.on=="function"}s(GK,"isNodeFormData");function KK(e){return e==null}s(KK,"isNil");var sa=new ry;var Vr=s(({modelType:e,allowedProviders:t})=>({provider:Te.Dropdown({auth:_o.None(),displayName:"Provider",required:!0,refreshers:[],options:s(async(o,a)=>{let{body:n}=await sa.sendRequest({method:"GET",url:`${a.server.apiUrl}v1/ai-providers`,headers:{Authorization:`Bearer ${a.server.token}`}});return{placeholder:"Select AI Provider",disabled:!1,options:n.map(i=>({label:i.name,value:i.provider})).filter(i=>t?t.includes(i.value):!0)}},"options")}),model:Te.Dropdown({auth:_o.None(),displayName:"Model",required:!0,refreshers:["provider"],options:s(async(o,a)=>{let n=o.provider;if(Ft(n))return{disabled:!0,options:[],placeholder:"Select AI Provider"};let{body:i}=await sa.sendRequest({method:"GET",url:`${a.server.apiUrl}v1/ai-providers/${n}/models`,headers:{Authorization:`Bearer ${a.server.token}`}});return{placeholder:"Select AI Model",disabled:!1,options:i.filter(l=>l.type===e).map(l=>({label:l.name,value:l.id}))}},"options")})}),"aiProps");var XK="3.0.72",YK=N(()=>$(r.object({type:r.literal("error"),error:r.object({type:r.string(),message:r.string()})}))),SN=bt({errorSchema:YK,errorToMessage:s(e=>e.error.message,"errorToMessage")}),QK=N(()=>$(r.object({type:r.literal("message"),id:r.string().nullish(),model:r.string().nullish(),content:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("text"),text:r.string(),citations:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("web_search_result_location"),cited_text:r.string(),url:r.string(),title:r.string(),encrypted_index:r.string()}),r.object({type:r.literal("page_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_page_number:r.number(),end_page_number:r.number()}),r.object({type:r.literal("char_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_char_index:r.number(),end_char_index:r.number()})])).optional()}),r.object({type:r.literal("thinking"),thinking:r.string(),signature:r.string()}),r.object({type:r.literal("redacted_thinking"),data:r.string()}),r.object({type:r.literal("compaction"),content:r.string()}),r.object({type:r.literal("tool_use"),id:r.string(),name:r.string(),input:r.unknown(),caller:r.union([r.object({type:r.literal("code_execution_20250825"),tool_id:r.string()}),r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("server_tool_use"),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish(),caller:r.union([r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("mcp_tool_use"),id:r.string(),name:r.string(),input:r.unknown(),server_name:r.string()}),r.object({type:r.literal("mcp_tool_result"),tool_use_id:r.string(),is_error:r.boolean(),content:r.array(r.union([r.string(),r.object({type:r.literal("text"),text:r.string()})]))}),r.object({type:r.literal("web_fetch_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("web_fetch_result"),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),media_type:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),media_type:r.literal("text/plain"),data:r.string()})])})}),r.object({type:r.literal("web_fetch_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("web_search_tool_result"),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal("web_search_result"),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal("web_search_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("code_execution_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("encrypted_code_execution_result"),encrypted_stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("bash_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("text_editor_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})])}),r.object({type:r.literal("tool_search_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("tool_search_tool_search_result"),tool_references:r.array(r.object({type:r.literal("tool_reference"),tool_name:r.string()}))}),r.object({type:r.literal("tool_search_tool_result_error"),error_code:r.string()})])})])),stop_reason:r.string().nullish(),stop_sequence:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish(),iterations:r.array(r.object({type:r.union([r.literal("compaction"),r.literal("message")]),input_tokens:r.number(),output_tokens:r.number()})).nullish()}),container:r.object({expires_at:r.string(),id:r.string(),skills:r.array(r.object({type:r.union([r.literal("anthropic"),r.literal("custom")]),skill_id:r.string(),version:r.string()})).nullish()}).nullish(),context_management:r.object({applied_edits:r.array(r.union([r.object({type:r.literal("clear_tool_uses_20250919"),cleared_tool_uses:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("clear_thinking_20251015"),cleared_thinking_turns:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("compact_20260112")})]))}).nullish()}))),e7=N(()=>$(r.discriminatedUnion("type",[r.object({type:r.literal("message_start"),message:r.object({id:r.string().nullish(),model:r.string().nullish(),role:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()}),content:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("tool_use"),id:r.string(),name:r.string(),input:r.unknown(),caller:r.union([r.object({type:r.literal("code_execution_20250825"),tool_id:r.string()}),r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()})])).nullish(),stop_reason:r.string().nullish(),container:r.object({expires_at:r.string(),id:r.string()}).nullish()})}),r.object({type:r.literal("content_block_start"),index:r.number(),content_block:r.discriminatedUnion("type",[r.object({type:r.literal("text"),text:r.string()}),r.object({type:r.literal("thinking"),thinking:r.string()}),r.object({type:r.literal("tool_use"),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).optional(),caller:r.union([r.object({type:r.literal("code_execution_20250825"),tool_id:r.string()}),r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("redacted_thinking"),data:r.string()}),r.object({type:r.literal("compaction"),content:r.string().nullish()}),r.object({type:r.literal("server_tool_use"),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish(),caller:r.union([r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("mcp_tool_use"),id:r.string(),name:r.string(),input:r.unknown(),server_name:r.string()}),r.object({type:r.literal("mcp_tool_result"),tool_use_id:r.string(),is_error:r.boolean(),content:r.array(r.union([r.string(),r.object({type:r.literal("text"),text:r.string()})]))}),r.object({type:r.literal("web_fetch_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("web_fetch_result"),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),media_type:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),media_type:r.literal("text/plain"),data:r.string()})])})}),r.object({type:r.literal("web_fetch_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("web_search_tool_result"),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal("web_search_result"),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal("web_search_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("code_execution_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("encrypted_code_execution_result"),encrypted_stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("bash_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("text_editor_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})])}),r.object({type:r.literal("tool_search_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("tool_search_tool_search_result"),tool_references:r.array(r.object({type:r.literal("tool_reference"),tool_name:r.string()}))}),r.object({type:r.literal("tool_search_tool_result_error"),error_code:r.string()})])})])}),r.object({type:r.literal("content_block_delta"),index:r.number(),delta:r.discriminatedUnion("type",[r.object({type:r.literal("input_json_delta"),partial_json:r.string()}),r.object({type:r.literal("text_delta"),text:r.string()}),r.object({type:r.literal("thinking_delta"),thinking:r.string()}),r.object({type:r.literal("signature_delta"),signature:r.string()}),r.object({type:r.literal("compaction_delta"),content:r.string().nullish()}),r.object({type:r.literal("citations_delta"),citation:r.discriminatedUnion("type",[r.object({type:r.literal("web_search_result_location"),cited_text:r.string(),url:r.string(),title:r.string(),encrypted_index:r.string()}),r.object({type:r.literal("page_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_page_number:r.number(),end_page_number:r.number()}),r.object({type:r.literal("char_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_char_index:r.number(),end_char_index:r.number()})])})])}),r.object({type:r.literal("content_block_stop"),index:r.number()}),r.object({type:r.literal("error"),error:r.object({type:r.string(),message:r.string()})}),r.object({type:r.literal("message_delta"),delta:r.object({stop_reason:r.string().nullish(),stop_sequence:r.string().nullish(),container:r.object({expires_at:r.string(),id:r.string(),skills:r.array(r.object({type:r.union([r.literal("anthropic"),r.literal("custom")]),skill_id:r.string(),version:r.string()})).nullish()}).nullish()}),usage:r.looseObject({input_tokens:r.number().nullish(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish(),iterations:r.array(r.object({type:r.union([r.literal("compaction"),r.literal("message")]),input_tokens:r.number(),output_tokens:r.number()})).nullish()}),context_management:r.object({applied_edits:r.array(r.union([r.object({type:r.literal("clear_tool_uses_20250919"),cleared_tool_uses:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("clear_thinking_20251015"),cleared_thinking_turns:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("compact_20260112")})]))}).nullish()}),r.object({type:r.literal("message_stop")}),r.object({type:r.literal("ping")})]))),t7=N(()=>$(r.object({signature:r.string().optional(),redactedData:r.string().optional()}))),IN=r.object({citations:r.object({enabled:r.boolean()}).optional(),title:r.string().optional(),context:r.string().optional()}),kN=r.object({sendReasoning:r.boolean().optional(),structuredOutputMode:r.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:r.discriminatedUnion("type",[r.object({type:r.literal("adaptive"),display:r.enum(["omitted","summarized"]).optional()}),r.object({type:r.literal("enabled"),budgetTokens:r.number().optional()}),r.object({type:r.literal("disabled")})]).optional(),disableParallelToolUse:r.boolean().optional(),cacheControl:r.object({type:r.literal("ephemeral"),ttl:r.union([r.literal("5m"),r.literal("1h")]).optional()}).optional(),metadata:r.object({userId:r.string().optional()}).optional(),mcpServers:r.array(r.object({type:r.literal("url"),name:r.string(),url:r.string(),authorizationToken:r.string().nullish(),toolConfiguration:r.object({enabled:r.boolean().nullish(),allowedTools:r.array(r.string()).nullish()}).nullish()})).optional(),container:r.object({id:r.string().optional(),skills:r.array(r.object({type:r.union([r.literal("anthropic"),r.literal("custom")]),skillId:r.string(),version:r.string().optional()})).optional()}).optional(),toolStreaming:r.boolean().optional(),effort:r.enum(["low","medium","high","xhigh","max"]).optional(),taskBudget:r.object({type:r.literal("tokens"),total:r.number().int().min(2e4),remaining:r.number().int().min(0).optional()}).optional(),speed:r.enum(["fast","standard"]).optional(),inferenceGeo:r.enum(["us","global"]).optional(),anthropicBeta:r.array(r.string()).optional(),contextManagement:r.object({edits:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("clear_tool_uses_20250919"),trigger:r.discriminatedUnion("type",[r.object({type:r.literal("input_tokens"),value:r.number()}),r.object({type:r.literal("tool_uses"),value:r.number()})]).optional(),keep:r.object({type:r.literal("tool_uses"),value:r.number()}).optional(),clearAtLeast:r.object({type:r.literal("input_tokens"),value:r.number()}).optional(),clearToolInputs:r.boolean().optional(),excludeTools:r.array(r.string()).optional()}),r.object({type:r.literal("clear_thinking_20251015"),keep:r.union([r.literal("all"),r.object({type:r.literal("thinking_turns"),value:r.number()})]).optional()}),r.object({type:r.literal("compact_20260112"),trigger:r.object({type:r.literal("input_tokens"),value:r.number()}).optional(),pauseAfterCompaction:r.boolean().optional(),instructions:r.string().optional()})]))}).optional()}),PN=4;function r7(e){var t;let o=e?.anthropic;return(t=o?.cacheControl)!=null?t:o?.cache_control}s(r7,"getCacheControl");var mT=class{static{s(this,"CacheControlValidator")}constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let o=r7(e);if(o){if(!t.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${t.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>PN){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${PN} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return o}}getWarnings(){return this.warnings}},o7=N(()=>$(r.object({maxCharacters:r.number().optional()}))),n7=N(()=>$(r.object({command:r.enum(["view","create","str_replace","insert"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),a7=yt({id:"anthropic.text_editor_20250728",inputSchema:n7}),i7=s((e={})=>a7(e),"textEditor_20250728"),s7=N(()=>$(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),userLocation:r.object({type:r.literal("approximate"),city:r.string().optional(),region:r.string().optional(),country:r.string().optional(),timezone:r.string().optional()}).optional()}))),l7=N(()=>$(r.array(r.object({url:r.string(),title:r.string().nullable(),pageAge:r.string().nullable(),encryptedContent:r.string(),type:r.literal("web_search_result")})))),u7=N(()=>$(r.object({query:r.string()}))),c7=Pe({id:"anthropic.web_search_20260209",inputSchema:u7,outputSchema:l7,supportsDeferredResults:!0}),d7=s((e={})=>c7(e),"webSearch_20260209"),p7=N(()=>$(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),userLocation:r.object({type:r.literal("approximate"),city:r.string().optional(),region:r.string().optional(),country:r.string().optional(),timezone:r.string().optional()}).optional()}))),$N=N(()=>$(r.array(r.object({url:r.string(),title:r.string().nullable(),pageAge:r.string().nullable(),encryptedContent:r.string(),type:r.literal("web_search_result")})))),m7=N(()=>$(r.object({query:r.string()}))),f7=Pe({id:"anthropic.web_search_20250305",inputSchema:m7,outputSchema:$N,supportsDeferredResults:!0}),h7=s((e={})=>f7(e),"webSearch_20250305"),g7=N(()=>$(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),citations:r.object({enabled:r.boolean()}).optional(),maxContentTokens:r.number().optional()}))),y7=N(()=>$(r.object({type:r.literal("web_fetch_result"),url:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),mediaType:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),mediaType:r.literal("text/plain"),data:r.string()})])}),retrievedAt:r.string().nullable()}))),_7=N(()=>$(r.object({url:r.string()}))),v7=Pe({id:"anthropic.web_fetch_20260209",inputSchema:_7,outputSchema:y7,supportsDeferredResults:!0}),b7=s((e={})=>v7(e),"webFetch_20260209"),x7=N(()=>$(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),citations:r.object({enabled:r.boolean()}).optional(),maxContentTokens:r.number().optional()}))),RN=N(()=>$(r.object({type:r.literal("web_fetch_result"),url:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),mediaType:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),mediaType:r.literal("text/plain"),data:r.string()})])}),retrievedAt:r.string().nullable()}))),w7=N(()=>$(r.object({url:r.string()}))),T7=Pe({id:"anthropic.web_fetch_20250910",inputSchema:w7,outputSchema:RN,supportsDeferredResults:!0}),S7=s((e={})=>T7(e),"webFetch_20250910");async function I7({tools:e,toolChoice:t,disableParallelToolUse:o,cacheControlValidator:a,supportsStructuredOutput:n,supportsStrictTools:i,defaultEagerInputStreaming:l=!1}){var u,c;e=e?.length?e:void 0;let d=[],p=new Set,m=a||new mT;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:d,betas:p};let f=[];for(let g of e)switch(g.type){case"function":{let y=m.getCacheControl(g.providerOptions,{type:"tool definition",canCache:!0}),_=(u=g.providerOptions)==null?void 0:u.anthropic,v=(c=_?.eagerInputStreaming)!=null?c:l,x=_?.deferLoading,w=_?.allowedCallers;!i&&g.strict!=null&&d.push({type:"unsupported",feature:"strict",details:`Tool '${g.name}' has strict: ${g.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),f.push({name:g.name,description:g.description,input_schema:g.inputSchema,cache_control:y,...v?{eager_input_streaming:!0}:{},...i===!0&&g.strict!=null?{strict:g.strict}:{},...x!=null?{defer_loading:x}:{},...w!=null?{allowed_callers:w}:{},...g.inputExamples!=null?{input_examples:g.inputExamples.map(S=>S.input)}:{}}),n===!0&&p.add("structured-outputs-2025-11-13"),(g.inputExamples!=null||w!=null)&&p.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(g.id){case"anthropic.code_execution_20250522":{p.add("code-execution-2025-05-22"),f.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{p.add("code-execution-2025-08-25"),f.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{f.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{p.add("computer-use-2025-01-24"),f.push({name:"computer",type:"computer_20250124",display_width_px:g.args.displayWidthPx,display_height_px:g.args.displayHeightPx,display_number:g.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20251124":{p.add("computer-use-2025-11-24"),f.push({name:"computer",type:"computer_20251124",display_width_px:g.args.displayWidthPx,display_height_px:g.args.displayHeightPx,display_number:g.args.displayNumber,enable_zoom:g.args.enableZoom,cache_control:void 0});break}case"anthropic.computer_20241022":{p.add("computer-use-2024-10-22"),f.push({name:"computer",type:"computer_20241022",display_width_px:g.args.displayWidthPx,display_height_px:g.args.displayHeightPx,display_number:g.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{p.add("computer-use-2025-01-24"),f.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{p.add("computer-use-2024-10-22"),f.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{p.add("computer-use-2025-01-24"),f.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let y=await $e({value:g.args,schema:o7});f.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:y.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{p.add("computer-use-2025-01-24"),f.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{p.add("computer-use-2024-10-22"),f.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{p.add("context-management-2025-06-27"),f.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{p.add("web-fetch-2025-09-10");let y=await $e({value:g.args,schema:x7});f.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:y.maxUses,allowed_domains:y.allowedDomains,blocked_domains:y.blockedDomains,citations:y.citations,max_content_tokens:y.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{p.add("code-execution-web-tools-2026-02-09");let y=await $e({value:g.args,schema:g7});f.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:y.maxUses,allowed_domains:y.allowedDomains,blocked_domains:y.blockedDomains,citations:y.citations,max_content_tokens:y.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let y=await $e({value:g.args,schema:p7});f.push({type:"web_search_20250305",name:"web_search",max_uses:y.maxUses,allowed_domains:y.allowedDomains,blocked_domains:y.blockedDomains,user_location:y.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{p.add("code-execution-web-tools-2026-02-09");let y=await $e({value:g.args,schema:s7});f.push({type:"web_search_20260209",name:"web_search",max_uses:y.maxUses,allowed_domains:y.allowedDomains,blocked_domains:y.blockedDomains,user_location:y.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{f.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{f.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}default:{d.push({type:"unsupported",feature:`provider-defined tool ${g.id}`});break}}break}default:{d.push({type:"unsupported",feature:`tool ${g}`});break}}if(t==null)return{tools:f,toolChoice:o?{type:"auto",disable_parallel_tool_use:o}:void 0,toolWarnings:d,betas:p};let h=t.type;switch(h){case"auto":return{tools:f,toolChoice:{type:"auto",disable_parallel_tool_use:o},toolWarnings:d,betas:p};case"required":return{tools:f,toolChoice:{type:"any",disable_parallel_tool_use:o},toolWarnings:d,betas:p};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:d,betas:p};case"tool":return{tools:f,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:o},toolWarnings:d,betas:p};default:{let g=h;throw new Le({functionality:`tool choice type: ${g}`})}}}s(I7,"prepareTools");function EN({usage:e,rawUsage:t}){var o,a;let n=(o=e.cache_creation_input_tokens)!=null?o:0,i=(a=e.cache_read_input_tokens)!=null?a:0,l,u;if(e.iterations&&e.iterations.length>0){let c=e.iterations.reduce((d,p)=>({input:d.input+p.input_tokens,output:d.output+p.output_tokens}),{input:0,output:0});l=c.input,u=c.output}else l=e.input_tokens,u=e.output_tokens;return{inputTokens:{total:l+n+i,noCache:l,cacheRead:i,cacheWrite:n},outputTokens:{total:u,text:void 0,reasoning:void 0},raw:t??e}}s(EN,"convertAnthropicMessagesUsage");var zN=N(()=>$(r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}))),k7=N(()=>$(r.object({code:r.string()}))),P7=Pe({id:"anthropic.code_execution_20250522",inputSchema:k7,outputSchema:zN}),E7=s((e={})=>P7(e),"codeExecution_20250522"),NN=N(()=>$(r.discriminatedUnion("type",[r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})]))),A7=N(()=>$(r.discriminatedUnion("type",[r.object({type:r.literal("programmatic-tool-call"),code:r.string()}),r.object({type:r.literal("bash_code_execution"),command:r.string()}),r.discriminatedUnion("command",[r.object({type:r.literal("text_editor_code_execution"),command:r.literal("view"),path:r.string()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("create"),path:r.string(),file_text:r.string().nullish()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("str_replace"),path:r.string(),old_str:r.string(),new_str:r.string()})])]))),C7=Pe({id:"anthropic.code_execution_20250825",inputSchema:A7,outputSchema:NN,supportsDeferredResults:!0}),O7=s((e={})=>C7(e),"codeExecution_20250825"),jN=N(()=>$(r.discriminatedUnion("type",[r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("encrypted_code_execution_result"),encrypted_stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})]))),$7=N(()=>$(r.discriminatedUnion("type",[r.object({type:r.literal("programmatic-tool-call"),code:r.string()}),r.object({type:r.literal("bash_code_execution"),command:r.string()}),r.discriminatedUnion("command",[r.object({type:r.literal("text_editor_code_execution"),command:r.literal("view"),path:r.string()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("create"),path:r.string(),file_text:r.string().nullish()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("str_replace"),path:r.string(),old_str:r.string(),new_str:r.string()})])]))),R7=Pe({id:"anthropic.code_execution_20260120",inputSchema:$7,outputSchema:jN,supportsDeferredResults:!0}),z7=s((e={})=>R7(e),"codeExecution_20260120"),MN=N(()=>$(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),N7=N(()=>$(r.object({pattern:r.string(),limit:r.number().optional()}))),j7=Pe({id:"anthropic.tool_search_regex_20251119",inputSchema:N7,outputSchema:MN,supportsDeferredResults:!0}),M7=s((e={})=>j7(e),"toolSearchRegex_20251119");function D7(e){if(typeof e=="string")return new TextDecoder().decode(Yt(e));if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new Le({functionality:"URL-based text documents are not supported for citations"}):new Le({functionality:`unsupported data type for text documents: ${typeof e}`})}s(D7,"convertToString");function cT(e){return e instanceof URL||U7(e)}s(cT,"isUrlData");function U7(e){return typeof e=="string"&&/^https?:\/\//i.test(e)}s(U7,"isUrlString");function dT(e){return e instanceof URL?e.toString():e}s(dT,"getUrlString");async function L7({prompt:e,sendReasoning:t,warnings:o,cacheControlValidator:a,toolNameMapping:n}){var i,l,u,c,d,p,m,f,h,g,y,_,v,x,w,S,P,k,I;let E=new Set,b=q7(e),M=a||new mT,R,D=[];async function te(J){var W,j;let O=await Re({provider:"anthropic",providerOptions:J,schema:IN});return(j=(W=O?.citations)==null?void 0:W.enabled)!=null?j:!1}s(te,"shouldEnableCitations");async function ee(J){let W=await Re({provider:"anthropic",providerOptions:J,schema:IN});return{title:W?.title,context:W?.context}}s(ee,"getDocumentMetadata");for(let J=0;J<b.length;J++){let W=b[J],j=J===b.length-1,O=W.type;switch(O){case"system":{if(R!=null)throw new Le({functionality:"Multiple system messages that are separated by user/assistant messages"});R=W.messages.map(({content:Z,providerOptions:F})=>({type:"text",text:Z,cache_control:M.getCacheControl(F,{type:"system message",canCache:!0})}));break}case"user":{let Z=[];for(let F of W.messages){let{role:z,content:Y}=F;switch(z){case"user":{for(let ae=0;ae<Y.length;ae++){let K=Y[ae],he=ae===Y.length-1,L=(i=M.getCacheControl(K.providerOptions,{type:"user message part",canCache:!0}))!=null?i:he?M.getCacheControl(F.providerOptions,{type:"user message",canCache:!0}):void 0;switch(K.type){case"text":{Z.push({type:"text",text:K.text,cache_control:L});break}case"file":{if(K.mediaType.startsWith("image/"))Z.push({type:"image",source:cT(K.data)?{type:"url",url:dT(K.data)}:{type:"base64",media_type:K.mediaType==="image/*"?"image/jpeg":K.mediaType,data:Zt(K.data)},cache_control:L});else if(K.mediaType==="application/pdf"){E.add("pdfs-2024-09-25");let le=await te(K.providerOptions),oe=await ee(K.providerOptions);Z.push({type:"document",source:cT(K.data)?{type:"url",url:dT(K.data)}:{type:"base64",media_type:"application/pdf",data:Zt(K.data)},title:(l=oe.title)!=null?l:K.filename,...oe.context&&{context:oe.context},...le&&{citations:{enabled:!0}},cache_control:L})}else if(K.mediaType==="text/plain"){let le=await te(K.providerOptions),oe=await ee(K.providerOptions);Z.push({type:"document",source:cT(K.data)?{type:"url",url:dT(K.data)}:{type:"text",media_type:"text/plain",data:D7(K.data)},title:(u=oe.title)!=null?u:K.filename,...oe.context&&{context:oe.context},...le&&{citations:{enabled:!0}},cache_control:L})}else throw new Le({functionality:`media type: ${K.mediaType}`});break}}}break}case"tool":{for(let ae=0;ae<Y.length;ae++){let K=Y[ae];if(K.type==="tool-approval-response")continue;let he=ae===Y.length-1,L=(c=M.getCacheControl(K.providerOptions,{type:"tool result part",canCache:!0}))!=null?c:he?M.getCacheControl(F.providerOptions,{type:"tool result message",canCache:!0}):void 0,le=K.output,oe;switch(le.type){case"content":oe=le.value.map(ne=>{var C;switch(ne.type){case"text":return{type:"text",text:ne.text};case"image-data":return{type:"image",source:{type:"base64",media_type:ne.mediaType,data:ne.data}};case"image-url":return{type:"image",source:{type:"url",url:ne.url}};case"file-url":return{type:"document",source:{type:"url",url:ne.url}};case"file-data":{if(ne.mediaType==="application/pdf")return E.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:ne.mediaType,data:ne.data}};o.push({type:"other",message:`unsupported tool content part type: ${ne.type} with media type: ${ne.mediaType}`});return}case"custom":{let G=(C=ne.providerOptions)==null?void 0:C.anthropic;if(G?.type==="tool-reference")return{type:"tool_reference",tool_name:G.toolName};o.push({type:"other",message:"unsupported custom tool content part"});return}default:{o.push({type:"other",message:`unsupported tool content part type: ${ne.type}`});return}}}).filter(_i);break;case"text":case"error-text":oe=le.value;break;case"execution-denied":oe=(d=le.reason)!=null?d:"Tool execution denied.";break;default:oe=JSON.stringify(le.value);break}Z.push({type:"tool_result",tool_use_id:K.toolCallId,content:oe,is_error:le.type==="error-text"||le.type==="error-json"?!0:void 0,cache_control:L})}break}default:{let ae=z;throw new Error(`Unsupported role: ${ae}`)}}}D.push({role:"user",content:Z});break}case"assistant":{let Z=[],F=new Set;for(let z=0;z<W.messages.length;z++){let Y=W.messages[z],ae=z===W.messages.length-1,{content:K}=Y;for(let he=0;he<K.length;he++){let L=K[he],le=he===K.length-1,oe=(p=M.getCacheControl(L.providerOptions,{type:"assistant message part",canCache:!0}))!=null?p:le?M.getCacheControl(Y.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(L.type){case"text":{let ne=(m=L.providerOptions)==null?void 0:m.anthropic;ne?.type==="compaction"?Z.push({type:"compaction",content:L.text,cache_control:oe}):Z.push({type:"text",text:j&&ae&&le?L.text.trim():L.text,cache_control:oe});break}case"reasoning":{if(t){let ne=await Re({provider:"anthropic",providerOptions:L.providerOptions,schema:t7});ne!=null?ne.signature!=null?(M.getCacheControl(L.providerOptions,{type:"thinking block",canCache:!1}),Z.push({type:"thinking",thinking:L.text,signature:ne.signature})):ne.redactedData!=null?(M.getCacheControl(L.providerOptions,{type:"redacted thinking block",canCache:!1}),Z.push({type:"redacted_thinking",data:ne.redactedData})):o.push({type:"other",message:"unsupported reasoning metadata"}):o.push({type:"other",message:"unsupported reasoning metadata"})}else o.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(L.providerExecuted){let G=n.toProviderToolName(L.toolName);if(((h=(f=L.providerOptions)==null?void 0:f.anthropic)==null?void 0:h.type)==="mcp-tool-use"){F.add(L.toolCallId);let q=(y=(g=L.providerOptions)==null?void 0:g.anthropic)==null?void 0:y.serverName;if(q==null||typeof q!="string"){o.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}Z.push({type:"mcp_tool_use",id:L.toolCallId,name:L.toolName,input:L.input,server_name:q,cache_control:oe})}else if(G==="code_execution"&&L.input!=null&&typeof L.input=="object"&&"type"in L.input&&typeof L.input.type=="string"&&(L.input.type==="bash_code_execution"||L.input.type==="text_editor_code_execution"))Z.push({type:"server_tool_use",id:L.toolCallId,name:L.input.type,input:L.input,cache_control:oe});else if(G==="code_execution"&&L.input!=null&&typeof L.input=="object"&&"type"in L.input&&L.input.type==="programmatic-tool-call"){let{type:q,...Me}=L.input;Z.push({type:"server_tool_use",id:L.toolCallId,name:"code_execution",input:Me,cache_control:oe})}else G==="code_execution"||G==="web_fetch"||G==="web_search"?Z.push({type:"server_tool_use",id:L.toolCallId,name:G,input:L.input,cache_control:oe}):G==="tool_search_tool_regex"||G==="tool_search_tool_bm25"?Z.push({type:"server_tool_use",id:L.toolCallId,name:G,input:L.input,cache_control:oe}):o.push({type:"other",message:`provider executed tool call for tool ${L.toolName} is not supported`});break}let ne=(_=L.providerOptions)==null?void 0:_.anthropic,C=ne?.caller?(ne.caller.type==="code_execution_20250825"||ne.caller.type==="code_execution_20260120")&&ne.caller.toolId?{type:ne.caller.type,tool_id:ne.caller.toolId}:ne.caller.type==="direct"?{type:"direct"}:void 0:void 0;Z.push({type:"tool_use",id:L.toolCallId,name:L.toolName,input:L.input,...C&&{caller:C},cache_control:oe});break}case"tool-result":{let ne=n.toProviderToolName(L.toolName);if(F.has(L.toolCallId)){let C=L.output;if(C.type!=="json"&&C.type!=="error-json"){o.push({type:"other",message:`provider executed tool result output type ${C.type} for tool ${L.toolName} is not supported`});break}Z.push({type:"mcp_tool_result",tool_use_id:L.toolCallId,is_error:C.type==="error-json",content:C.value,cache_control:oe})}else if(ne==="code_execution"){let C=L.output;if(C.type==="error-text"||C.type==="error-json"){let G={};try{typeof C.value=="string"?G=JSON.parse(C.value):typeof C.value=="object"&&C.value!==null&&(G=C.value)}catch{}G.type==="code_execution_tool_result_error"?Z.push({type:"code_execution_tool_result",tool_use_id:L.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(v=G.errorCode)!=null?v:"unknown"},cache_control:oe}):Z.push({type:"bash_code_execution_tool_result",tool_use_id:L.toolCallId,cache_control:oe,content:{type:"bash_code_execution_tool_result_error",error_code:(x=G.errorCode)!=null?x:"unknown"}});break}if(C.type!=="json"){o.push({type:"other",message:`provider executed tool result output type ${C.type} for tool ${L.toolName} is not supported`});break}if(C.value==null||typeof C.value!="object"||!("type"in C.value)||typeof C.value.type!="string"){o.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${L.toolName}`});break}if(C.value.type==="code_execution_result"){let G=await $e({value:C.value,schema:zN});Z.push({type:"code_execution_tool_result",tool_use_id:L.toolCallId,content:{type:G.type,stdout:G.stdout,stderr:G.stderr,return_code:G.return_code,content:(w=G.content)!=null?w:[]},cache_control:oe})}else if(C.value.type==="encrypted_code_execution_result"){let G=await $e({value:C.value,schema:jN});G.type==="encrypted_code_execution_result"&&Z.push({type:"code_execution_tool_result",tool_use_id:L.toolCallId,content:{type:G.type,encrypted_stdout:G.encrypted_stdout,stderr:G.stderr,return_code:G.return_code,content:(S=G.content)!=null?S:[]},cache_control:oe})}else{let G=await $e({value:C.value,schema:NN});G.type==="code_execution_result"?Z.push({type:"code_execution_tool_result",tool_use_id:L.toolCallId,content:{type:G.type,stdout:G.stdout,stderr:G.stderr,return_code:G.return_code,content:(P=G.content)!=null?P:[]},cache_control:oe}):G.type==="bash_code_execution_result"||G.type==="bash_code_execution_tool_result_error"?Z.push({type:"bash_code_execution_tool_result",tool_use_id:L.toolCallId,cache_control:oe,content:G}):Z.push({type:"text_editor_code_execution_tool_result",tool_use_id:L.toolCallId,cache_control:oe,content:G})}break}if(ne==="web_fetch"){let C=L.output;if(C.type==="error-json"){let X={};try{typeof C.value=="string"?X=JSON.parse(C.value):typeof C.value=="object"&&C.value!==null&&(X=C.value)}catch{let Me=(k=C.value)==null?void 0:k.errorCode;X={errorCode:typeof Me=="string"?Me:"unavailable"}}Z.push({type:"web_fetch_tool_result",tool_use_id:L.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(I=X.errorCode)!=null?I:"unavailable"},cache_control:oe});break}if(C.type!=="json"){o.push({type:"other",message:`provider executed tool result output type ${C.type} for tool ${L.toolName} is not supported`});break}let G=await $e({value:C.value,schema:RN});Z.push({type:"web_fetch_tool_result",tool_use_id:L.toolCallId,content:{type:"web_fetch_result",url:G.url,retrieved_at:G.retrievedAt,content:{type:"document",title:G.content.title,citations:G.content.citations,source:{type:G.content.source.type,media_type:G.content.source.mediaType,data:G.content.source.data}}},cache_control:oe});break}if(ne==="web_search"){let C=L.output;if(C.type!=="json"){o.push({type:"other",message:`provider executed tool result output type ${C.type} for tool ${L.toolName} is not supported`});break}let G=await $e({value:C.value,schema:$N});Z.push({type:"web_search_tool_result",tool_use_id:L.toolCallId,content:G.map(X=>({url:X.url,title:X.title,page_age:X.pageAge,encrypted_content:X.encryptedContent,type:X.type})),cache_control:oe});break}if(ne==="tool_search_tool_regex"||ne==="tool_search_tool_bm25"){let C=L.output;if(C.type!=="json"){o.push({type:"other",message:`provider executed tool result output type ${C.type} for tool ${L.toolName} is not supported`});break}let X=(await $e({value:C.value,schema:MN})).map(q=>({type:"tool_reference",tool_name:q.toolName}));Z.push({type:"tool_search_tool_result",tool_use_id:L.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:X},cache_control:oe});break}o.push({type:"other",message:`provider executed tool result for tool ${L.toolName} is not supported`});break}}}}D.push({role:"assistant",content:Z});break}default:{let Z=O;throw new Error(`content type: ${Z}`)}}}return{prompt:{system:R,messages:D},betas:E}}s(L7,"convertToAnthropicMessagesPrompt");function q7(e){let t=[],o;for(let a of e){let{role:n}=a;switch(n){case"system":{o?.type!=="system"&&(o={type:"system",messages:[]},t.push(o)),o.messages.push(a);break}case"assistant":{o?.type!=="assistant"&&(o={type:"assistant",messages:[]},t.push(o)),o.messages.push(a);break}case"user":{o?.type!=="user"&&(o={type:"user",messages:[]},t.push(o)),o.messages.push(a);break}case"tool":{o?.type!=="user"&&(o={type:"user",messages:[]},t.push(o)),o.messages.push(a);break}default:{let i=n;throw new Error(`Unsupported role: ${i}`)}}}return t}s(q7,"groupIntoBlocks");function pT({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}s(pT,"mapAnthropicStopReason");function AN(e,t,o){var a;if(e.type==="web_search_result_location")return{type:"source",sourceType:"url",id:o(),url:e.url,title:e.title,providerMetadata:{anthropic:{citedText:e.cited_text,encryptedIndex:e.encrypted_index}}};if(e.type!=="page_location"&&e.type!=="char_location")return;let n=t[e.document_index];if(n)return{type:"source",sourceType:"document",id:o(),mediaType:n.mediaType,title:(a=e.document_title)!=null?a:n.title,filename:n.filename,providerMetadata:{anthropic:e.type==="page_location"?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index}}}}s(AN,"createCitationSource");var F7=class{static{s(this,"AnthropicMessagesLanguageModel")}constructor(e,t){this.specificationVersion="v3";var o;this.modelId=e,this.config=t,this.generateId=(o=t.generateId)!=null?o:Fe}supportsUrl(e){return e.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let e=this.config.provider,t=e.indexOf(".");return t===-1?e:e.substring(0,t)}get supportedUrls(){var e,t,o;return(o=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?o:{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:o,temperature:a,topP:n,topK:i,frequencyPenalty:l,presencePenalty:u,stopSequences:c,responseFormat:d,seed:p,tools:m,toolChoice:f,providerOptions:h,stream:g}){var y,_,v,x,w,S,P,k,I,E;let b=[];l!=null&&b.push({type:"unsupported",feature:"frequencyPenalty"}),u!=null&&b.push({type:"unsupported",feature:"presencePenalty"}),p!=null&&b.push({type:"unsupported",feature:"seed"}),a!=null&&a>1?(b.push({type:"unsupported",feature:"temperature",details:`${a} exceeds anthropic maximum of 1.0. clamped to 1.0`}),a=1):a!=null&&a<0&&(b.push({type:"unsupported",feature:"temperature",details:`${a} is below anthropic minimum of 0. clamped to 0`}),a=0),d?.type==="json"&&d.schema==null&&b.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let M=this.providerOptionsName,R=await Re({provider:"anthropic",providerOptions:h,schema:kN}),D=M!=="anthropic"?await Re({provider:M,providerOptions:h,schema:kN}):null,te=D!=null,ee=Object.assign({},R??{},D??{}),{maxOutputTokens:J,supportsStructuredOutput:W,rejectsSamplingParameters:j,isKnownModel:O}=B7(this.modelId);j&&(a!=null&&(b.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),a=void 0),i!=null&&(b.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),i=void 0),n!=null&&(b.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),n=void 0));let Z=O||this.modelId.startsWith("claude-"),F=((y=this.config.supportsNativeStructuredOutput)!=null?y:!0)&&W,z=((_=this.config.supportsStrictTools)!=null?_:!0)&&W,Y=(v=ee?.structuredOutputMode)!=null?v:"auto",ae=Y==="outputFormat"||Y==="auto"&&F,K=d?.type==="json"&&d.schema!=null&&!ae?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:d.schema}:void 0,he=ee?.contextManagement,L=new mT,le=Zl({tools:m,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:oe,betas:ne}=await L7({prompt:t,sendReasoning:(x=ee?.sendReasoning)!=null?x:!0,warnings:b,cacheControlValidator:L,toolNameMapping:le}),C=(w=ee?.thinking)==null?void 0:w.type,G=C==="enabled"||C==="adaptive",X=C==="enabled"?(S=ee?.thinking)==null?void 0:S.budgetTokens:void 0,q=C==="adaptive"?(P=ee?.thinking)==null?void 0:P.display:void 0,Me=o??J,fe={model:this.modelId,max_tokens:Me,temperature:a,top_k:i,top_p:n,stop_sequences:c,...G&&{thinking:{type:C,...X!=null&&{budget_tokens:X},...q!=null&&{display:q}}},...(ee?.effort||ee?.taskBudget||ae&&d?.type==="json"&&d.schema!=null)&&{output_config:{...ee?.effort&&{effort:ee.effort},...ee?.taskBudget&&{task_budget:{type:ee.taskBudget.type,total:ee.taskBudget.total,...ee.taskBudget.remaining!=null&&{remaining:ee.taskBudget.remaining}}},...ae&&d?.type==="json"&&d.schema!=null&&{format:{type:"json_schema",schema:d.schema}}}},...ee?.speed&&{speed:ee.speed},...ee?.inferenceGeo&&{inference_geo:ee.inferenceGeo},...ee?.cacheControl&&{cache_control:ee.cacheControl},...((k=ee?.metadata)==null?void 0:k.userId)!=null&&{metadata:{user_id:ee.metadata.userId}},...ee?.mcpServers&&ee.mcpServers.length>0&&{mcp_servers:ee.mcpServers.map(De=>({type:De.type,name:De.name,url:De.url,authorization_token:De.authorizationToken,tool_configuration:De.toolConfiguration?{allowed_tools:De.toolConfiguration.allowedTools,enabled:De.toolConfiguration.enabled}:void 0}))},...ee?.container&&{container:ee.container.skills&&ee.container.skills.length>0?{id:ee.container.id,skills:ee.container.skills.map(De=>({type:De.type,skill_id:De.skillId,version:De.version}))}:ee.container.id},system:oe.system,messages:oe.messages,...he&&{context_management:{edits:he.edits.map(De=>{let Wr=De.type;switch(Wr){case"clear_tool_uses_20250919":return{type:De.type,...De.trigger!==void 0&&{trigger:De.trigger},...De.keep!==void 0&&{keep:De.keep},...De.clearAtLeast!==void 0&&{clear_at_least:De.clearAtLeast},...De.clearToolInputs!==void 0&&{clear_tool_inputs:De.clearToolInputs},...De.excludeTools!==void 0&&{exclude_tools:De.excludeTools}};case"clear_thinking_20251015":return{type:De.type,...De.keep!==void 0&&{keep:De.keep}};case"compact_20260112":return{type:De.type,...De.trigger!==void 0&&{trigger:De.trigger},...De.pauseAfterCompaction!==void 0&&{pause_after_compaction:De.pauseAfterCompaction},...De.instructions!==void 0&&{instructions:De.instructions}};default:b.push({type:"other",message:`Unknown context management strategy: ${Wr}`});return}}).filter(De=>De!==void 0)}}};G?(C==="enabled"&&X==null&&(b.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),fe.thinking={type:"enabled",budget_tokens:1024},X=1024),fe.temperature!=null&&(fe.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),i!=null&&(fe.top_k=void 0,b.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),n!=null&&(fe.top_p=void 0,b.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),fe.max_tokens=Me+(X??0)):Z&&n!=null&&a!=null&&(b.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),fe.top_p=void 0),O&&fe.max_tokens>J&&(o!=null&&b.push({type:"unsupported",feature:"maxOutputTokens",details:`${fe.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${J} max output tokens. The max output tokens have been limited to ${J}.`}),fe.max_tokens=J),ee?.mcpServers&&ee.mcpServers.length>0&&ne.add("mcp-client-2025-04-04"),he&&(ne.add("context-management-2025-06-27"),he.edits.some(De=>De.type==="compact_20260112")&&ne.add("compact-2026-01-12")),ee?.container&&ee.container.skills&&ee.container.skills.length>0&&(ne.add("code-execution-2025-08-25"),ne.add("skills-2025-10-02"),ne.add("files-api-2025-04-14"),m?.some(De=>De.type==="provider"&&(De.id==="anthropic.code_execution_20250825"||De.id==="anthropic.code_execution_20260120"))||b.push({type:"other",message:"code execution tool is required when using skills"})),ee?.effort&&ne.add("effort-2025-11-24"),ee?.taskBudget&&ne.add("task-budgets-2026-03-13"),ee?.speed==="fast"&&ne.add("fast-mode-2026-02-01");let at=g&&((I=ee?.toolStreaming)!=null?I:!0),{tools:rr,toolChoice:Tr,toolWarnings:gr,betas:Ho}=await I7(K!=null?{tools:[...m??[],K],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:L,supportsStructuredOutput:!1,supportsStrictTools:z,defaultEagerInputStreaming:at}:{tools:m??[],toolChoice:f,disableParallelToolUse:ee?.disableParallelToolUse,cacheControlValidator:L,supportsStructuredOutput:F,supportsStrictTools:z,defaultEagerInputStreaming:at}),Mr=L.getWarnings();return{args:{...fe,tools:rr,tool_choice:Tr,stream:g===!0?!0:void 0},warnings:[...b,...gr,...Mr],betas:new Set([...ne,...Ho,...e,...(E=ee?.anthropicBeta)!=null?E:[]]),usesJsonResponseTool:K!=null,toolNameMapping:le,providerOptionsName:M,usedCustomProviderKey:te}}async getHeaders({betas:e,headers:t}){return Ie(await st(this.config.headers),t,e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{})}async getBetasFromHeaders(e){var t,o;let n=(t=(await st(this.config.headers))["anthropic-beta"])!=null?t:"",i=(o=e?.["anthropic-beta"])!=null?o:"";return new Set([...n.toLowerCase().split(","),...i.toLowerCase().split(",")].map(l=>l.trim()).filter(l=>l!==""))}buildRequestUrl(e){var t,o,a;return(a=(o=(t=this.config).buildRequestUrl)==null?void 0:o.call(t,this.config.baseURL,e))!=null?a:`${this.config.baseURL}/messages`}transformRequestBody(e,t){var o,a,n;return(n=(a=(o=this.config).transformRequestBody)==null?void 0:a.call(o,e,t))!=null?n:e}extractCitationDocuments(e){let t=s(o=>{var a,n;if(o.type!=="file"||o.mediaType!=="application/pdf"&&o.mediaType!=="text/plain")return!1;let i=(a=o.providerOptions)==null?void 0:a.anthropic,l=i?.citations;return(n=l?.enabled)!=null?n:!1},"isCitationPart");return e.filter(o=>o.role==="user").flatMap(o=>o.content).filter(t).map(o=>{var a;let n=o;return{title:(a=n.filename)!=null?a:"Untitled Document",filename:n.filename,mediaType:n.mediaType}})}async doGenerate(e){var t,o,a,n,i,l,u;let{args:c,warnings:d,betas:p,usesJsonResponseTool:m,toolNameMapping:f,providerOptionsName:h,usedCustomProviderKey:g}=await this.getArgs({...e,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),y=[...this.extractCitationDocuments(e.prompt)],_=CN(c.tools),{responseHeaders:v,value:x,rawValue:w}=await ke({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:p,headers:e.headers}),body:this.transformRequestBody(c,p),failedResponseHandler:SN,successfulResponseHandler:Ce(QK),abortSignal:e.abortSignal,fetch:this.config.fetch}),S=[],P={},k={},I=!1;for(let E of x.content)switch(E.type){case"text":{if(!m&&(S.push({type:"text",text:E.text}),E.citations))for(let b of E.citations){let M=AN(b,y,this.generateId);M&&S.push(M)}break}case"thinking":{S.push({type:"reasoning",text:E.thinking,providerMetadata:{anthropic:{signature:E.signature}}});break}case"redacted_thinking":{S.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:E.data}}});break}case"compaction":{S.push({type:"text",text:E.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(m&&E.name==="json")I=!0,S.push({type:"text",text:JSON.stringify(E.input)});else{let M=E.caller,R=M?{type:M.type,toolId:"tool_id"in M?M.tool_id:void 0}:void 0;S.push({type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),...R&&{providerMetadata:{anthropic:{caller:R}}}})}break}case"server_tool_use":{if(E.name==="text_editor_code_execution"||E.name==="bash_code_execution")S.push({type:"tool-call",toolCallId:E.id,toolName:f.toCustomToolName("code_execution"),input:JSON.stringify({type:E.name,...E.input}),providerExecuted:!0});else if(E.name==="web_search"||E.name==="code_execution"||E.name==="web_fetch"){let b=E.name==="code_execution"&&E.input!=null&&typeof E.input=="object"&&"code"in E.input&&!("type"in E.input)?{type:"programmatic-tool-call",...E.input}:E.input;S.push({type:"tool-call",toolCallId:E.id,toolName:f.toCustomToolName(E.name),input:JSON.stringify(b),providerExecuted:!0,..._&&E.name==="code_execution"?{dynamic:!0}:{}})}else(E.name==="tool_search_tool_regex"||E.name==="tool_search_tool_bm25")&&(k[E.id]=E.name,S.push({type:"tool-call",toolCallId:E.id,toolName:f.toCustomToolName(E.name),input:JSON.stringify(E.input),providerExecuted:!0}));break}case"mcp_tool_use":{P[E.id]={type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:E.server_name}}},S.push(P[E.id]);break}case"mcp_tool_result":{S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:P[E.tool_use_id].toolName,isError:E.is_error,result:E.content,dynamic:!0,providerMetadata:P[E.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{E.content.type==="web_fetch_result"?(y.push({title:(t=E.content.content.title)!=null?t:E.content.url,mediaType:E.content.content.source.media_type}),S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:E.content.url,retrievedAt:E.content.retrieved_at,content:{type:E.content.content.type,title:E.content.content.title,citations:E.content.content.citations,source:{type:E.content.content.source.type,mediaType:E.content.content.source.media_type,data:E.content.content.source.data}}}})):E.content.type==="web_fetch_tool_result_error"&&S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:E.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(E.content)){S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("web_search"),result:E.content.map(b=>{var M;return{url:b.url,title:b.title,pageAge:(M=b.page_age)!=null?M:null,encryptedContent:b.encrypted_content,type:b.type}})});for(let b of E.content)S.push({type:"source",sourceType:"url",id:this.generateId(),url:b.url,title:b.title,providerMetadata:{anthropic:{pageAge:(o=b.page_age)!=null?o:null}}})}else S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:E.content.error_code}});break}case"code_execution_tool_result":{E.content.type==="code_execution_result"?S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:{type:E.content.type,stdout:E.content.stdout,stderr:E.content.stderr,return_code:E.content.return_code,content:(a=E.content.content)!=null?a:[]}}):E.content.type==="encrypted_code_execution_result"?S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:{type:E.content.type,encrypted_stdout:E.content.encrypted_stdout,stderr:E.content.stderr,return_code:E.content.return_code,content:(n=E.content.content)!=null?n:[]}}):E.content.type==="code_execution_tool_result_error"&&S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:E.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:E.content});break}case"tool_search_tool_result":{let b=k[E.tool_use_id];if(b==null){let M=f.toCustomToolName("tool_search_tool_bm25"),R=f.toCustomToolName("tool_search_tool_regex");M!=="tool_search_tool_bm25"?b="tool_search_tool_bm25":b="tool_search_tool_regex"}E.content.type==="tool_search_tool_search_result"?S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName(b),result:E.content.tool_references.map(M=>({type:M.type,toolName:M.tool_name}))}):S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName(b),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:E.content.error_code}});break}}return{content:S,finishReason:{unified:pT({finishReason:x.stop_reason,isJsonResponseFromTool:I}),raw:(i=x.stop_reason)!=null?i:void 0},usage:EN({usage:x.usage}),request:{body:c},response:{id:(l=x.id)!=null?l:void 0,modelId:(u=x.model)!=null?u:void 0,headers:v,body:w},warnings:d,providerMetadata:(()=>{var E,b,M,R,D;let te={usage:x.usage,cacheCreationInputTokens:(E=x.usage.cache_creation_input_tokens)!=null?E:null,stopSequence:(b=x.stop_sequence)!=null?b:null,iterations:x.usage.iterations?x.usage.iterations.map(J=>({type:J.type,inputTokens:J.input_tokens,outputTokens:J.output_tokens})):null,container:x.container?{expiresAt:x.container.expires_at,id:x.container.id,skills:(R=(M=x.container.skills)==null?void 0:M.map(J=>({type:J.type,skillId:J.skill_id,version:J.version})))!=null?R:null}:null,contextManagement:(D=ON(x.context_management))!=null?D:null},ee={anthropic:te};return g&&h!=="anthropic"&&(ee[h]=te),ee})()}}async doStream(e){var t,o;let{args:a,warnings:n,betas:i,usesJsonResponseTool:l,toolNameMapping:u,providerOptionsName:c,usedCustomProviderKey:d}=await this.getArgs({...e,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),p=[...this.extractCitationDocuments(e.prompt)],m=CN(a.tools),f=this.buildRequestUrl(!0),{responseHeaders:h,value:g}=await ke({url:f,headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(a,i),failedResponseHandler:SN,successfulResponseHandler:dr(e7),abortSignal:e.abortSignal,fetch:this.config.fetch}),y={unified:"other",raw:void 0},_={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},v={},x={},w={},S=null,P,k=null,I=null,E=null,b=!1,M,R=this.generateId,D=g.pipeThrough(new TransformStream({start(W){W.enqueue({type:"stream-start",warnings:n})},transform(W,j){var O,Z,F,z,Y,ae,K,he,L,le,oe,ne,C,G;if(e.includeRawChunks&&j.enqueue({type:"raw",rawValue:W.rawValue}),!W.success){j.enqueue({type:"error",error:W.error});return}let X=W.value;switch(X.type){case"ping":return;case"content_block_start":{let q=X.content_block,Me=q.type;switch(M=Me,Me){case"text":{if(l)return;v[X.index]={type:"text"},j.enqueue({type:"text-start",id:String(X.index)});return}case"thinking":{v[X.index]={type:"reasoning"},j.enqueue({type:"reasoning-start",id:String(X.index)});return}case"redacted_thinking":{v[X.index]={type:"reasoning"},j.enqueue({type:"reasoning-start",id:String(X.index),providerMetadata:{anthropic:{redactedData:q.data}}});return}case"compaction":{v[X.index]={type:"text"},j.enqueue({type:"text-start",id:String(X.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(l&&q.name==="json")b=!0,v[X.index]={type:"text"},j.enqueue({type:"text-start",id:String(X.index)});else{let at=q.caller,rr=at?{type:at.type,toolId:"tool_id"in at?at.tool_id:void 0}:void 0,gr=q.input&&Object.keys(q.input).length>0?JSON.stringify(q.input):"";v[X.index]={type:"tool-call",toolCallId:q.id,toolName:q.name,input:gr,firstDelta:gr.length===0,...rr&&{caller:rr}},j.enqueue({type:"tool-input-start",id:q.id,toolName:q.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(q.name)){let fe=q.name==="text_editor_code_execution"||q.name==="bash_code_execution"?"code_execution":q.name,at=u.toCustomToolName(fe),rr=q.input!=null&&typeof q.input=="object"&&Object.keys(q.input).length>0?JSON.stringify(q.input):"";v[X.index]={type:"tool-call",toolCallId:q.id,toolName:at,input:rr,providerExecuted:!0,...m&&fe==="code_execution"?{dynamic:!0}:{},firstDelta:!0,providerToolName:q.name},j.enqueue({type:"tool-input-start",id:q.id,toolName:at,providerExecuted:!0,...m&&fe==="code_execution"?{dynamic:!0}:{}})}else if(q.name==="tool_search_tool_regex"||q.name==="tool_search_tool_bm25"){w[q.id]=q.name;let fe=u.toCustomToolName(q.name);v[X.index]={type:"tool-call",toolCallId:q.id,toolName:fe,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:q.name},j.enqueue({type:"tool-input-start",id:q.id,toolName:fe,providerExecuted:!0})}return}case"web_fetch_tool_result":{q.content.type==="web_fetch_result"?(p.push({title:(O=q.content.content.title)!=null?O:q.content.url,mediaType:q.content.content.source.media_type}),j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:q.content.url,retrievedAt:q.content.retrieved_at,content:{type:q.content.content.type,title:q.content.content.title,citations:q.content.content.citations,source:{type:q.content.content.source.type,mediaType:q.content.content.source.media_type,data:q.content.content.source.data}}}})):q.content.type==="web_fetch_tool_result_error"&&j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:q.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(q.content)){j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("web_search"),result:q.content.map(fe=>{var at;return{url:fe.url,title:fe.title,pageAge:(at=fe.page_age)!=null?at:null,encryptedContent:fe.encrypted_content,type:fe.type}})});for(let fe of q.content)j.enqueue({type:"source",sourceType:"url",id:R(),url:fe.url,title:fe.title,providerMetadata:{anthropic:{pageAge:(Z=fe.page_age)!=null?Z:null}}})}else j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:q.content.error_code}});return}case"code_execution_tool_result":{q.content.type==="code_execution_result"?j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("code_execution"),result:{type:q.content.type,stdout:q.content.stdout,stderr:q.content.stderr,return_code:q.content.return_code,content:(F=q.content.content)!=null?F:[]}}):q.content.type==="encrypted_code_execution_result"?j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("code_execution"),result:{type:q.content.type,encrypted_stdout:q.content.encrypted_stdout,stderr:q.content.stderr,return_code:q.content.return_code,content:(z=q.content.content)!=null?z:[]}}):q.content.type==="code_execution_tool_result_error"&&j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:q.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("code_execution"),result:q.content});return}case"tool_search_tool_result":{let fe=w[q.tool_use_id];if(fe==null){let at=u.toCustomToolName("tool_search_tool_bm25"),rr=u.toCustomToolName("tool_search_tool_regex");at!=="tool_search_tool_bm25"?fe="tool_search_tool_bm25":fe="tool_search_tool_regex"}q.content.type==="tool_search_tool_search_result"?j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName(fe),result:q.content.tool_references.map(at=>({type:at.type,toolName:at.tool_name}))}):j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName(fe),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:q.content.error_code}});return}case"mcp_tool_use":{x[q.id]={type:"tool-call",toolCallId:q.id,toolName:q.name,input:JSON.stringify(q.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:q.server_name}}},j.enqueue(x[q.id]);return}case"mcp_tool_result":{j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:x[q.tool_use_id].toolName,isError:q.is_error,result:q.content,dynamic:!0,providerMetadata:x[q.tool_use_id].providerMetadata});return}default:{let fe=Me;throw new Error(`Unsupported content block type: ${fe}`)}}}case"content_block_stop":{if(v[X.index]!=null){let q=v[X.index];switch(q.type){case"text":{j.enqueue({type:"text-end",id:String(X.index)});break}case"reasoning":{j.enqueue({type:"reasoning-end",id:String(X.index)});break}case"tool-call":if(!(l&&q.toolName==="json")){j.enqueue({type:"tool-input-end",id:q.toolCallId});let fe=q.input===""?"{}":q.input;if(q.providerToolName==="code_execution")try{let at=JSON.parse(fe);at!=null&&typeof at=="object"&&"code"in at&&!("type"in at)&&(fe=JSON.stringify({type:"programmatic-tool-call",...at}))}catch{}j.enqueue({type:"tool-call",toolCallId:q.toolCallId,toolName:q.toolName,input:fe,providerExecuted:q.providerExecuted,...m&&q.providerToolName==="code_execution"?{dynamic:!0}:{},...q.caller&&{providerMetadata:{anthropic:{caller:q.caller}}}})}break}delete v[X.index]}M=void 0;return}case"content_block_delta":{let q=X.delta.type;switch(q){case"text_delta":{if(l)return;j.enqueue({type:"text-delta",id:String(X.index),delta:X.delta.text});return}case"thinking_delta":{j.enqueue({type:"reasoning-delta",id:String(X.index),delta:X.delta.thinking});return}case"signature_delta":{M==="thinking"&&j.enqueue({type:"reasoning-delta",id:String(X.index),delta:"",providerMetadata:{anthropic:{signature:X.delta.signature}}});return}case"compaction_delta":{X.delta.content!=null&&j.enqueue({type:"text-delta",id:String(X.index),delta:X.delta.content});return}case"input_json_delta":{let Me=v[X.index],fe=X.delta.partial_json;if(fe.length===0)return;if(b){if(Me?.type!=="text")return;j.enqueue({type:"text-delta",id:String(X.index),delta:fe})}else{if(Me?.type!=="tool-call")return;Me.firstDelta&&(Me.providerToolName==="bash_code_execution"||Me.providerToolName==="text_editor_code_execution")&&(fe=`{"type": "${Me.providerToolName}",${fe.substring(1)}`),j.enqueue({type:"tool-input-delta",id:Me.toolCallId,delta:fe}),Me.input+=fe,Me.firstDelta=!1}return}case"citations_delta":{let Me=X.delta.citation,fe=AN(Me,p,R);fe&&j.enqueue(fe);return}default:{let Me=q;throw new Error(`Unsupported delta type: ${Me}`)}}}case"message_start":{if(_.input_tokens=X.message.usage.input_tokens,_.cache_read_input_tokens=(Y=X.message.usage.cache_read_input_tokens)!=null?Y:0,_.cache_creation_input_tokens=(ae=X.message.usage.cache_creation_input_tokens)!=null?ae:0,P={...X.message.usage},k=(K=X.message.usage.cache_creation_input_tokens)!=null?K:null,X.message.container!=null&&(E={expiresAt:X.message.container.expires_at,id:X.message.container.id,skills:null}),X.message.stop_reason!=null&&(y={unified:pT({finishReason:X.message.stop_reason,isJsonResponseFromTool:b}),raw:X.message.stop_reason}),j.enqueue({type:"response-metadata",id:(he=X.message.id)!=null?he:void 0,modelId:(L=X.message.model)!=null?L:void 0}),X.message.content!=null)for(let q=0;q<X.message.content.length;q++){let Me=X.message.content[q];if(Me.type==="tool_use"){let fe=Me.caller,at=fe?{type:fe.type,toolId:"tool_id"in fe?fe.tool_id:void 0}:void 0;j.enqueue({type:"tool-input-start",id:Me.id,toolName:Me.name});let rr=JSON.stringify((le=Me.input)!=null?le:{});j.enqueue({type:"tool-input-delta",id:Me.id,delta:rr}),j.enqueue({type:"tool-input-end",id:Me.id}),j.enqueue({type:"tool-call",toolCallId:Me.id,toolName:Me.name,input:rr,...at&&{providerMetadata:{anthropic:{caller:at}}}})}}return}case"message_delta":{X.usage.input_tokens!=null&&_.input_tokens!==X.usage.input_tokens&&(_.input_tokens=X.usage.input_tokens),_.output_tokens=X.usage.output_tokens,X.usage.cache_read_input_tokens!=null&&(_.cache_read_input_tokens=X.usage.cache_read_input_tokens),X.usage.cache_creation_input_tokens!=null&&(_.cache_creation_input_tokens=X.usage.cache_creation_input_tokens,k=X.usage.cache_creation_input_tokens),X.usage.iterations!=null&&(_.iterations=X.usage.iterations),y={unified:pT({finishReason:X.delta.stop_reason,isJsonResponseFromTool:b}),raw:(oe=X.delta.stop_reason)!=null?oe:void 0},I=(ne=X.delta.stop_sequence)!=null?ne:null,E=X.delta.container!=null?{expiresAt:X.delta.container.expires_at,id:X.delta.container.id,skills:(G=(C=X.delta.container.skills)==null?void 0:C.map(q=>({type:q.type,skillId:q.skill_id,version:q.version})))!=null?G:null}:null,X.context_management&&(S=ON(X.context_management)),P={...P,...X.usage};return}case"message_stop":{let q={usage:P??null,cacheCreationInputTokens:k,stopSequence:I,iterations:_.iterations?_.iterations.map(fe=>({type:fe.type,inputTokens:fe.input_tokens,outputTokens:fe.output_tokens})):null,container:E,contextManagement:S},Me={anthropic:q};d&&c!=="anthropic"&&(Me[c]=q),j.enqueue({type:"finish",finishReason:y,usage:EN({usage:_,rawUsage:P}),providerMetadata:Me});return}case"error":{j.enqueue({type:"error",error:X.error});return}default:{let q=X;throw new Error(`Unsupported chunk type: ${q}`)}}}})),[te,ee]=D.tee(),J=te.getReader();try{await J.read();let W=await J.read();if(((t=W.value)==null?void 0:t.type)==="raw"&&(W=await J.read()),((o=W.value)==null?void 0:o.type)==="error"){let j=W.value.error;throw new _t({message:j.message,url:f,requestBodyValues:a,statusCode:j.type==="overloaded_error"?529:500,responseHeaders:h,responseBody:JSON.stringify(j),isRetryable:j.type==="overloaded_error"})}}finally{J.cancel().catch(()=>{}),J.releaseLock()}return{stream:ee,request:{body:a},response:{headers:h}}}};function B7(e){return e.includes("claude-opus-4-7")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,isKnownModel:!0}:e.includes("claude-sonnet-4-6")||e.includes("claude-opus-4-6")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-sonnet-4-5")||e.includes("claude-opus-4-5")||e.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-sonnet-4-")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!1}}s(B7,"getModelCapabilities");function CN(e){if(!e)return!1;let t=!1,o=!1;for(let a of e){if("type"in a&&(a.type==="web_fetch_20260209"||a.type==="web_search_20260209")){t=!0;continue}if(a.name==="code_execution"){o=!0;break}}return t&&!o}s(CN,"hasWebTool20260209WithoutCodeExecution");function ON(e){return e?{appliedEdits:e.applied_edits.map(t=>{switch(t.type){case"clear_tool_uses_20250919":return{type:t.type,clearedToolUses:t.cleared_tool_uses,clearedInputTokens:t.cleared_input_tokens};case"clear_thinking_20251015":return{type:t.type,clearedThinkingTurns:t.cleared_thinking_turns,clearedInputTokens:t.cleared_input_tokens};case"compact_20260112":return{type:t.type}}}).filter(t=>t!==void 0)}:null}s(ON,"mapAnthropicResponseContextManagement");var V7=N(()=>$(r.object({command:r.string(),restart:r.boolean().optional()}))),Z7=yt({id:"anthropic.bash_20241022",inputSchema:V7}),H7=N(()=>$(r.object({command:r.string(),restart:r.boolean().optional()}))),J7=yt({id:"anthropic.bash_20250124",inputSchema:H7}),W7=N(()=>$(r.object({action:r.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:r.array(r.number().int()).optional(),text:r.string().optional()}))),G7=yt({id:"anthropic.computer_20241022",inputSchema:W7}),K7=N(()=>$(r.object({action:r.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),duration:r.number().optional(),scroll_amount:r.number().optional(),scroll_direction:r.enum(["up","down","left","right"]).optional(),start_coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),text:r.string().optional()}))),X7=yt({id:"anthropic.computer_20250124",inputSchema:K7}),Y7=N(()=>$(r.object({action:r.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),duration:r.number().optional(),region:r.tuple([r.number().int(),r.number().int(),r.number().int(),r.number().int()]).optional(),scroll_amount:r.number().optional(),scroll_direction:r.enum(["up","down","left","right"]).optional(),start_coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),text:r.string().optional()}))),Q7=yt({id:"anthropic.computer_20251124",inputSchema:Y7}),eX=N(()=>$(r.discriminatedUnion("command",[r.object({command:r.literal("view"),path:r.string(),view_range:r.tuple([r.number(),r.number()]).optional()}),r.object({command:r.literal("create"),path:r.string(),file_text:r.string()}),r.object({command:r.literal("str_replace"),path:r.string(),old_str:r.string(),new_str:r.string()}),r.object({command:r.literal("insert"),path:r.string(),insert_line:r.number(),insert_text:r.string()}),r.object({command:r.literal("delete"),path:r.string()}),r.object({command:r.literal("rename"),old_path:r.string(),new_path:r.string()})]))),tX=yt({id:"anthropic.memory_20250818",inputSchema:eX}),rX=N(()=>$(r.object({command:r.enum(["view","create","str_replace","insert","undo_edit"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),oX=yt({id:"anthropic.text_editor_20241022",inputSchema:rX}),nX=N(()=>$(r.object({command:r.enum(["view","create","str_replace","insert","undo_edit"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),aX=yt({id:"anthropic.text_editor_20250124",inputSchema:nX}),iX=N(()=>$(r.object({command:r.enum(["view","create","str_replace","insert"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),sX=yt({id:"anthropic.text_editor_20250429",inputSchema:iX}),lX=N(()=>$(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),uX=N(()=>$(r.object({query:r.string(),limit:r.number().optional()}))),cX=Pe({id:"anthropic.tool_search_bm25_20251119",inputSchema:uX,outputSchema:lX,supportsDeferredResults:!0}),dX=s((e={})=>cX(e),"toolSearchBm25_20251119"),pX={bash_20241022:Z7,bash_20250124:J7,codeExecution_20250522:E7,codeExecution_20250825:O7,codeExecution_20260120:z7,computer_20241022:G7,computer_20250124:X7,computer_20251124:Q7,memory_20250818:tX,textEditor_20241022:oX,textEditor_20250124:aX,textEditor_20250429:sX,textEditor_20250728:i7,webFetch_20250910:S7,webFetch_20260209:b7,webSearch_20250305:h7,webSearch_20260209:d7,toolSearchRegex_20251119:M7,toolSearchBm25_20251119:dX};function yp(e={}){var t,o;let a=(t=ta(Yn({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?t:"https://api.anthropic.com/v1",n=(o=e.name)!=null?o:"anthropic.messages";if(e.apiKey&&e.authToken)throw new xl({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let i=s(()=>{let c=e.authToken?{Authorization:`Bearer ${e.authToken}`}:{"x-api-key":vi({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return Qt({"anthropic-version":"2023-06-01",...c,...e.headers},`ai-sdk/anthropic/${XK}`)},"getHeaders"),l=s(c=>{var d;return new F7(c,{provider:n,baseURL:a,headers:i,fetch:e.fetch,generateId:(d=e.generateId)!=null?d:Fe,supportedUrls:s(()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]}),"supportedUrls")})},"createChatModel"),u=s(function(c){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return l(c)},"provider");return u.specificationVersion="v3",u.languageModel=l,u.chat=l,u.messages=l,u.embeddingModel=c=>{throw new Qx({modelId:c,modelType:"embeddingModel"})},u.textEmbeddingModel=u.embeddingModel,u.imageModel=c=>{throw new Qx({modelId:c,modelType:"imageModel"})},u.tools=pX,u}s(yp,"createAnthropic");var DN=yp();var mj="vercel.ai.error",mX=Symbol.for(mj),UN,LN,jt=class fj extends(LN=Error,UN=mX,LN){static{s(this,"_AISDKError")}constructor({name:t,message:o,cause:a}){super(o),this[UN]=!0,this.name=t,this.cause=a}static isInstance(t){return fj.hasMarker(t,mj)}static hasMarker(t,o){let a=Symbol.for(o);return t!=null&&typeof t=="object"&&a in t&&typeof t[a]=="boolean"&&t[a]===!0}},hj="AI_APICallError",gj=`vercel.ai.error.${hj}`,fX=Symbol.for(gj),qN,FN,rn=class extends(FN=jt,qN=fX,FN){static{s(this,"APICallError")}constructor({message:e,url:t,requestBodyValues:o,statusCode:a,responseHeaders:n,responseBody:i,cause:l,isRetryable:u=a!=null&&(a===408||a===409||a===429||a>=500),data:c}){super({name:hj,message:e,cause:l}),this[qN]=!0,this.url=t,this.requestBodyValues=o,this.statusCode=a,this.responseHeaders=n,this.responseBody=i,this.isRetryable=u,this.data=c}static isInstance(e){return jt.hasMarker(e,gj)}},yj="AI_EmptyResponseBodyError",_j=`vercel.ai.error.${yj}`,hX=Symbol.for(_j),BN,VN,hT=class extends(VN=jt,BN=hX,VN){static{s(this,"EmptyResponseBodyError")}constructor({message:e="Empty response body"}={}){super({name:yj,message:e}),this[BN]=!0}static isInstance(e){return jt.hasMarker(e,_j)}};function vj(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}s(vj,"getErrorMessage");var bj="AI_InvalidArgumentError",xj=`vercel.ai.error.${bj}`,gX=Symbol.for(xj),ZN,HN,oy=class extends(HN=jt,ZN=gX,HN){static{s(this,"InvalidArgumentError")}constructor({message:e,cause:t,argument:o}){super({name:bj,message:e,cause:t}),this[ZN]=!0,this.argument=o}static isInstance(e){return jt.hasMarker(e,xj)}},wj="AI_InvalidPromptError",Tj=`vercel.ai.error.${wj}`,yX=Symbol.for(Tj),JN,WN,hje=class extends(WN=jt,JN=yX,WN){static{s(this,"InvalidPromptError")}constructor({prompt:e,message:t,cause:o}){super({name:wj,message:`Invalid prompt: ${t}`,cause:o}),this[JN]=!0,this.prompt=e}static isInstance(e){return jt.hasMarker(e,Tj)}},Sj="AI_InvalidResponseDataError",Ij=`vercel.ai.error.${Sj}`,_X=Symbol.for(Ij),GN,KN,gje=class extends(KN=jt,GN=_X,KN){static{s(this,"InvalidResponseDataError")}constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Sj,message:t}),this[GN]=!0,this.data=e}static isInstance(e){return jt.hasMarker(e,Ij)}},kj="AI_JSONParseError",Pj=`vercel.ai.error.${kj}`,vX=Symbol.for(Pj),XN,YN,_p=class extends(YN=jt,XN=vX,YN){static{s(this,"JSONParseError")}constructor({text:e,cause:t}){super({name:kj,message:`JSON parsing failed: Text: ${e}.
93
+ `)}})}},hN={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function T8({status:e,statusText:t,headers:o,stream:a,consumeSseStream:n}){let i=a.pipeThrough(new fN);if(n){let[l,u]=i.tee();i=l,n({stream:u})}return new Response(i.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Yg(o,hN)})}s(T8,"createUIMessageStreamResponse");function S8({originalMessages:e,responseMessageId:t}){if(e==null)return;let o=e[e.length-1];return o?.role==="assistant"?o.id:typeof t=="function"?t():t}s(S8,"getResponseUIMessageId");var lze=N(()=>$(r.union([r.strictObject({type:r.literal("text-start"),id:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("text-delta"),id:r.string(),delta:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("text-end"),id:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("error"),errorText:r.string()}),r.strictObject({type:r.literal("tool-input-start"),toolCallId:r.string(),toolName:r.string(),providerExecuted:r.boolean().optional(),providerMetadata:ze.optional(),dynamic:r.boolean().optional(),title:r.string().optional()}),r.strictObject({type:r.literal("tool-input-delta"),toolCallId:r.string(),inputTextDelta:r.string()}),r.strictObject({type:r.literal("tool-input-available"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerExecuted:r.boolean().optional(),providerMetadata:ze.optional(),dynamic:r.boolean().optional(),title:r.string().optional()}),r.strictObject({type:r.literal("tool-input-error"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerExecuted:r.boolean().optional(),providerMetadata:ze.optional(),dynamic:r.boolean().optional(),errorText:r.string(),title:r.string().optional()}),r.strictObject({type:r.literal("tool-approval-request"),approvalId:r.string(),toolCallId:r.string()}),r.strictObject({type:r.literal("tool-output-available"),toolCallId:r.string(),output:r.unknown(),providerExecuted:r.boolean().optional(),providerMetadata:ze.optional(),dynamic:r.boolean().optional(),preliminary:r.boolean().optional()}),r.strictObject({type:r.literal("tool-output-error"),toolCallId:r.string(),errorText:r.string(),providerExecuted:r.boolean().optional(),providerMetadata:ze.optional(),dynamic:r.boolean().optional()}),r.strictObject({type:r.literal("tool-output-denied"),toolCallId:r.string()}),r.strictObject({type:r.literal("reasoning-start"),id:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("reasoning-delta"),id:r.string(),delta:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("reasoning-end"),id:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("source-url"),sourceId:r.string(),url:r.string(),title:r.string().optional(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("source-document"),sourceId:r.string(),mediaType:r.string(),title:r.string(),filename:r.string().optional(),providerMetadata:ze.optional()}),r.strictObject({type:r.literal("file"),url:r.string(),mediaType:r.string(),providerMetadata:ze.optional()}),r.strictObject({type:r.custom(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:r.string().optional(),data:r.unknown(),transient:r.boolean().optional()}),r.strictObject({type:r.literal("start-step")}),r.strictObject({type:r.literal("finish-step")}),r.strictObject({type:r.literal("start"),messageId:r.string().optional(),messageMetadata:r.unknown().optional()}),r.strictObject({type:r.literal("finish"),finishReason:r.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:r.unknown().optional()}),r.strictObject({type:r.literal("abort"),reason:r.string().optional()}),r.strictObject({type:r.literal("message-metadata"),messageMetadata:r.unknown()})])));function I8(e){return e.type.startsWith("data-")}s(I8,"isDataUIMessageChunk");function Y0(e){return e.type.startsWith("tool-")}s(Y0,"isStaticToolUIPart");function k8(e){return e.type==="dynamic-tool"}s(k8,"isDynamicToolUIPart");function VR(e){return Y0(e)||k8(e)}s(VR,"isToolUIPart");function ZR(e){return e.type.split("-").slice(1).join("-")}s(ZR,"getStaticToolName");function P8({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}s(P8,"createStreamingUIMessageState");function E8({stream:e,messageMetadataSchema:t,dataPartSchemas:o,runUpdateMessageJob:a,onError:n,onToolCall:i,onData:l}){return e.pipeThrough(new TransformStream({async transform(u,c){await a(async({state:d,write:p})=>{var m,f,h,g;function y(w){let P=d.message.parts.filter(VR).find(k=>k.toolCallId===w);if(P==null)throw new ou({chunkType:"tool-invocation",chunkId:w,message:`No tool invocation found for tool call ID "${w}".`});return P}s(y,"getToolInvocation");function _(w){var S;let P=d.message.parts.find(E=>Y0(E)&&E.toolCallId===w.toolCallId),k=w,I=P;if(P!=null){P.state=w.state,I.input=k.input,I.output=k.output,I.errorText=k.errorText,I.rawInput=k.rawInput,I.preliminary=k.preliminary,w.title!==void 0&&(I.title=w.title),I.providerExecuted=(S=k.providerExecuted)!=null?S:P.providerExecuted;let E=k.providerMetadata;if(E!=null)if(w.state==="output-available"||w.state==="output-error"){let b=P;b.resultProviderMetadata=E}else P.callProviderMetadata=E}else d.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,title:w.title,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null&&(w.state==="output-available"||w.state==="output-error")?{resultProviderMetadata:k.providerMetadata}:{},...k.providerMetadata!=null&&!(w.state==="output-available"||w.state==="output-error")?{callProviderMetadata:k.providerMetadata}:{}})}s(_,"updateToolPart");function v(w){var S,P;let k=d.message.parts.find(b=>b.type==="dynamic-tool"&&b.toolCallId===w.toolCallId),I=w,E=k;if(k!=null){k.state=w.state,E.toolName=w.toolName,E.input=I.input,E.output=I.output,E.errorText=I.errorText,E.rawInput=(S=I.rawInput)!=null?S:E.rawInput,E.preliminary=I.preliminary,w.title!==void 0&&(E.title=w.title),E.providerExecuted=(P=I.providerExecuted)!=null?P:k.providerExecuted;let b=I.providerMetadata;if(b!=null)if(w.state==="output-available"||w.state==="output-error"){let M=k;M.resultProviderMetadata=b}else k.callProviderMetadata=b}else d.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:I.input,output:I.output,errorText:I.errorText,preliminary:I.preliminary,providerExecuted:I.providerExecuted,title:w.title,...I.providerMetadata!=null&&(w.state==="output-available"||w.state==="output-error")?{resultProviderMetadata:I.providerMetadata}:{},...I.providerMetadata!=null&&!(w.state==="output-available"||w.state==="output-error")?{callProviderMetadata:I.providerMetadata}:{}})}s(v,"updateDynamicToolPart");async function x(w){if(w!=null){let S=d.message.metadata!=null?Xg(d.message.metadata,w):w;t!=null&&await $e({value:S,schema:t,context:{field:"message.metadata",entityId:d.message.id}}),d.message.metadata=S}}switch(s(x,"updateMessageMetadata"),u.type){case"text-start":{let w={type:"text",text:"",providerMetadata:u.providerMetadata,state:"streaming"};d.activeTextParts[u.id]=w,d.message.parts.push(w),p();break}case"text-delta":{let w=d.activeTextParts[u.id];if(w==null)throw new ou({chunkType:"text-delta",chunkId:u.id,message:`Received text-delta for missing text part with ID "${u.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});w.text+=u.delta,w.providerMetadata=(m=u.providerMetadata)!=null?m:w.providerMetadata,p();break}case"text-end":{let w=d.activeTextParts[u.id];if(w==null)throw new ou({chunkType:"text-end",chunkId:u.id,message:`Received text-end for missing text part with ID "${u.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});w.state="done",w.providerMetadata=(f=u.providerMetadata)!=null?f:w.providerMetadata,delete d.activeTextParts[u.id],p();break}case"reasoning-start":{let w={type:"reasoning",text:"",providerMetadata:u.providerMetadata,state:"streaming"};d.activeReasoningParts[u.id]=w,d.message.parts.push(w),p();break}case"reasoning-delta":{let w=d.activeReasoningParts[u.id];if(w==null)throw new ou({chunkType:"reasoning-delta",chunkId:u.id,message:`Received reasoning-delta for missing reasoning part with ID "${u.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});w.text+=u.delta,w.providerMetadata=(h=u.providerMetadata)!=null?h:w.providerMetadata,p();break}case"reasoning-end":{let w=d.activeReasoningParts[u.id];if(w==null)throw new ou({chunkType:"reasoning-end",chunkId:u.id,message:`Received reasoning-end for missing reasoning part with ID "${u.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});w.providerMetadata=(g=u.providerMetadata)!=null?g:w.providerMetadata,w.state="done",delete d.activeReasoningParts[u.id],p();break}case"file":{d.message.parts.push({type:"file",mediaType:u.mediaType,url:u.url,...u.providerMetadata!=null?{providerMetadata:u.providerMetadata}:{}}),p();break}case"source-url":{d.message.parts.push({type:"source-url",sourceId:u.sourceId,url:u.url,title:u.title,providerMetadata:u.providerMetadata}),p();break}case"source-document":{d.message.parts.push({type:"source-document",sourceId:u.sourceId,mediaType:u.mediaType,title:u.title,filename:u.filename,providerMetadata:u.providerMetadata}),p();break}case"tool-input-start":{let w=d.message.parts.filter(Y0);d.partialToolCalls[u.toolCallId]={text:"",toolName:u.toolName,index:w.length,dynamic:u.dynamic,title:u.title},u.dynamic?v({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-streaming",input:void 0,providerExecuted:u.providerExecuted,title:u.title,providerMetadata:u.providerMetadata}):_({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-streaming",input:void 0,providerExecuted:u.providerExecuted,title:u.title,providerMetadata:u.providerMetadata}),p();break}case"tool-input-delta":{let w=d.partialToolCalls[u.toolCallId];if(w==null)throw new ou({chunkType:"tool-input-delta",chunkId:u.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${u.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});w.text+=u.inputTextDelta;let{value:S}=await gp(w.text);w.dynamic?v({toolCallId:u.toolCallId,toolName:w.toolName,state:"input-streaming",input:S,title:w.title}):_({toolCallId:u.toolCallId,toolName:w.toolName,state:"input-streaming",input:S,title:w.title}),p();break}case"tool-input-available":{u.dynamic?v({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-available",input:u.input,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata,title:u.title}):_({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-available",input:u.input,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata,title:u.title}),p(),i&&!u.providerExecuted&&await i({toolCall:u});break}case"tool-input-error":{let w=d.message.parts.filter(VR).find(P=>P.toolCallId===u.toolCallId);(w!=null?w.type==="dynamic-tool":!!u.dynamic)?v({toolCallId:u.toolCallId,toolName:u.toolName,state:"output-error",input:u.input,errorText:u.errorText,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata}):_({toolCallId:u.toolCallId,toolName:u.toolName,state:"output-error",input:void 0,rawInput:u.input,errorText:u.errorText,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata}),p();break}case"tool-approval-request":{let w=y(u.toolCallId);w.state="approval-requested",w.approval={id:u.approvalId},p();break}case"tool-output-denied":{let w=y(u.toolCallId);w.state="output-denied",p();break}case"tool-output-available":{let w=y(u.toolCallId);w.type==="dynamic-tool"?v({toolCallId:u.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:u.output,preliminary:u.preliminary,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata,title:w.title}):_({toolCallId:u.toolCallId,toolName:ZR(w),state:"output-available",input:w.input,output:u.output,providerExecuted:u.providerExecuted,preliminary:u.preliminary,providerMetadata:u.providerMetadata,title:w.title}),p();break}case"tool-output-error":{let w=y(u.toolCallId);w.type==="dynamic-tool"?v({toolCallId:u.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:u.errorText,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata,title:w.title}):_({toolCallId:u.toolCallId,toolName:ZR(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:u.errorText,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata,title:w.title}),p();break}case"start-step":{d.message.parts.push({type:"step-start"});break}case"finish-step":{d.activeTextParts={},d.activeReasoningParts={};break}case"start":{u.messageId!=null&&(d.message.id=u.messageId),await x(u.messageMetadata),(u.messageId!=null||u.messageMetadata!=null)&&p();break}case"finish":{u.finishReason!=null&&(d.finishReason=u.finishReason),await x(u.messageMetadata),u.messageMetadata!=null&&p();break}case"message-metadata":{await x(u.messageMetadata),u.messageMetadata!=null&&p();break}case"error":{n?.(new Error(u.errorText));break}default:if(I8(u)){if(o?.[u.type]!=null){let P=d.message.parts.findIndex(I=>"id"in I&&"data"in I&&I.id===u.id&&I.type===u.type),k=P>=0?P:d.message.parts.length;await $e({value:u.data,schema:o[u.type],context:{field:`message.parts[${k}].data`,entityName:u.type,entityId:u.id}})}let w=u;if(w.transient){l?.(w);break}let S=w.id!=null?d.message.parts.find(P=>w.type===P.type&&w.id===P.id):void 0;S!=null?S.data=w.data:d.message.parts.push(w),l?.(w),p()}}c.enqueue(u)})}}))}s(E8,"processUIMessageStream");function A8({messageId:e,originalMessages:t=[],onStepFinish:o,onFinish:a,onError:n,stream:i}){let l=t?.[t.length-1];l?.role!=="assistant"?l=void 0:e=l.id;let u=!1,c=i.pipeThrough(new TransformStream({transform(g,y){if(g.type==="start"){let _=g;_.messageId==null&&e!=null&&(_.messageId=e)}g.type==="abort"&&(u=!0),y.enqueue(g)}}));if(a==null&&o==null)return c;let d=P8({lastMessage:l?structuredClone(l):void 0,messageId:e??""}),p=s(async g=>{await g({state:d,write:s(()=>{},"write")})},"runUpdateMessageJob"),m=!1,f=s(async()=>{if(m||!a)return;m=!0;let g=d.message.id===l?.id;await a({isAborted:u,isContinuation:g,responseMessage:d.message,messages:[...g?t.slice(0,-1):t,d.message],finishReason:d.finishReason})},"callOnFinish"),h=s(async()=>{if(!o)return;let g=d.message.id===l?.id;try{await o({isContinuation:g,responseMessage:structuredClone(d.message),messages:[...g?t.slice(0,-1):t,structuredClone(d.message)]})}catch(y){n(y)}},"callOnStepFinish");return E8({stream:c,runUpdateMessageJob:p,onError:n}).pipeThrough(new TransformStream({async transform(g,y){g.type==="finish-step"&&await h(),y.enqueue(g)},async cancel(){await f()},async flush(){await f()}}))}s(A8,"handleUIMessageStreamFinish");function C8({response:e,status:t,statusText:o,headers:a,stream:n,consumeSseStream:i}){let l=n.pipeThrough(new fN);if(i){let[u,c]=l.tee();l=u,i({stream:c})}mN({response:e,status:t,statusText:o,headers:Object.fromEntries(Yg(a,hN).entries()),stream:l.pipeThrough(new TextEncoderStream)})}s(C8,"pipeUIMessageStreamToResponse");function dp(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let o=this.getReader(),a=!1;async function n(i){var l;if(!a){a=!0;try{i&&await((l=o.cancel)==null?void 0:l.call(o))}finally{try{o.releaseLock()}catch{}}}}return s(n,"cleanup"),{async next(){if(a)return{done:!0,value:void 0};let{done:i,value:l}=await o.read();return i?(await n(!0),{done:!0,value:void 0}):{done:!1,value:l}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(i){throw await n(!0),i}}},t}s(dp,"createAsyncIterableStream");async function O8({stream:e,onError:t}){let o=e.getReader();try{for(;;){let{done:a}=await o.read();if(a)break}}catch(a){t?.(a)}finally{o.releaseLock()}}s(O8,"consumeStream");function HR(){let e,t;return{promise:new Promise((a,n)=>{e=a,t=n}),resolve:e,reject:t}}s(HR,"createResolvablePromise");function $8(){let e=[],t=null,o=!1,a=HR(),n=s(()=>{o=!0,a.resolve(),e.forEach(l=>l.cancel()),e=[],t?.close()},"terminate"),i=s(async()=>{if(o&&e.length===0){t?.close();return}if(e.length===0)return a=HR(),await a.promise,i();try{let{value:l,done:u}=await e[0].read();u?(e.shift(),e.length===0&&o?t?.close():await i()):t?.enqueue(l)}catch(l){t?.error(l),e.shift(),n()}},"processPull");return{stream:new ReadableStream({start(l){t=l},pull:i,async cancel(){for(let l of e)await l.cancel();e=[],o=!0}}),addStream:s(l=>{if(o)throw new Error("Cannot add inner stream: outer stream is closed");e.push(l.getReader()),a.resolve()},"addStream"),close:s(()=>{o=!0,a.resolve(),e.length===0&&t?.close()},"close"),terminate:n}}s($8,"createStitchableStream");function R8({tools:e,generatorStream:t,tracer:o,telemetry:a,system:n,messages:i,abortSignal:l,repairToolCall:u,experimental_context:c,generateId:d,stepNumber:p,model:m,onToolCallStart:f,onToolCallFinish:h}){let g=null,y=new ReadableStream({start(I){g=I}}),_=new Set,v=new Map,x=new Map,w=!1,S;function P(){w&&_.size===0&&(S!=null&&g.enqueue(S),g.close())}s(P,"attemptClose");let k=new TransformStream({async transform(I,E){let b=I.type;switch(b){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{E.enqueue(I);break}case"file":{E.enqueue({type:"file",file:new d8({data:I.data,mediaType:I.mediaType}),...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}});break}case"finish":{S={type:"finish",finishReason:I.finishReason.unified,rawFinishReason:I.finishReason.raw,usage:K0(I.usage),providerMetadata:I.providerMetadata};break}case"tool-approval-request":{let M=x.get(I.toolCallId);if(M==null){g.enqueue({type:"error",error:new eT({toolCallId:I.toolCallId,approvalId:I.approvalId})});break}E.enqueue({type:"tool-approval-request",approvalId:I.approvalId,toolCall:M});break}case"tool-call":{try{let M=await sN({toolCall:I,tools:e,repairToolCall:u,system:n,messages:i});if(x.set(M.toolCallId,M),E.enqueue(M),M.invalid){g.enqueue({type:"tool-error",toolCallId:M.toolCallId,toolName:M.toolName,input:M.input,error:Wl(M.error),dynamic:!0,title:M.title});break}let R=e?.[M.toolName];if(R==null)break;if(R.onInputAvailable!=null&&await R.onInputAvailable({input:M.input,toolCallId:M.toolCallId,messages:i,abortSignal:l,experimental_context:c}),await iN({tool:R,toolCall:M,messages:i,experimental_context:c})){g.enqueue({type:"tool-approval-request",approvalId:d(),toolCall:M});break}if(v.set(M.toolCallId,M.input),R.execute!=null&&M.providerExecuted!==!0){let D=d();_.add(D),aT({toolCall:M,tools:e,tracer:o,telemetry:a,messages:i,abortSignal:l,experimental_context:c,stepNumber:p,model:m,onToolCallStart:f,onToolCallFinish:h,onPreliminaryToolResult:s(te=>{g.enqueue(te)},"onPreliminaryToolResult")}).then(te=>{g.enqueue(te)}).catch(te=>{g.enqueue({type:"error",error:te})}).finally(()=>{_.delete(D),P()})}}catch(M){g.enqueue({type:"error",error:M})}break}case"tool-result":{let M=I.toolName;I.isError?g.enqueue({type:"tool-error",toolCallId:I.toolCallId,toolName:M,input:v.get(I.toolCallId),providerExecuted:!0,error:I.result,dynamic:I.dynamic,...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}}):E.enqueue({type:"tool-result",toolCallId:I.toolCallId,toolName:M,input:v.get(I.toolCallId),output:I.result,providerExecuted:!0,dynamic:I.dynamic,...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}});break}default:{let M=b;throw new Error(`Unhandled chunk type: ${M}`)}}},flush(){w=!0,P()}});return new ReadableStream({async start(I){return Promise.all([t.pipeThrough(k).pipeTo(new WritableStream({write(E){I.enqueue(E)},close(){}})),y.pipeTo(new WritableStream({write(E){I.enqueue(E)},close(){I.close()}}))])}})}s(R8,"runToolsTransformation");var z8=Xn({prefix:"aitxt",size:24});function gN({model:e,tools:t,toolChoice:o,system:a,prompt:n,messages:i,allowSystemInMessages:l,maxRetries:u,abortSignal:c,timeout:d,headers:p,stopWhen:m=nu(1),experimental_output:f,output:h=f,experimental_telemetry:g,prepareStep:y,providerOptions:_,experimental_activeTools:v,activeTools:x=v,experimental_repairToolCall:w,experimental_transform:S,experimental_download:P,includeRawChunks:k=!1,onChunk:I,onError:E=s(({error:z})=>{console.error(z)},"onError"),onFinish:b,onAbort:M,onStepFinish:R,experimental_onStart:D,experimental_onStepStart:te,experimental_onToolCallStart:ee,experimental_onToolCallFinish:J,experimental_context:W,experimental_include:j,_internal:{now:O=Vg,generateId:Z=z8}={},...F}){let z=nT(d),Y=Fz(d),ae=DK(d),K=Y!=null?new AbortController:void 0,he=ae!=null?new AbortController:void 0;return new j8({model:Zg(e),telemetry:g,headers:p,settings:F,maxRetries:u,abortSignal:pN(c,z!=null?AbortSignal.timeout(z):void 0,K?.signal,he?.signal),stepTimeoutMs:Y,stepAbortController:K,chunkTimeoutMs:ae,chunkAbortController:he,system:a,prompt:n,messages:i,allowSystemInMessages:l,tools:t,toolChoice:o,transforms:hs(S),activeTools:x,repairToolCall:w,stopConditions:hs(m),output:h,providerOptions:_,prepareStep:y,includeRawChunks:k,timeout:d,stopWhen:m,originalAbortSignal:c,onChunk:I,onError:E,onFinish:b,onAbort:M,onStepFinish:R,onStart:D,onStepStart:te,onToolCallStart:ee,onToolCallFinish:J,now:O,generateId:Z,experimental_context:W,download:P,include:j})}s(gN,"streamText");function N8(e){let t,o="",a="",n,i="";function l({controller:u,partialOutput:c=void 0}){u.enqueue({part:{type:"text-delta",id:t,text:a,providerMetadata:n},partialOutput:c}),a=""}return s(l,"publishTextChunk"),new TransformStream({async transform(u,c){var d;if(u.type==="finish-step"&&a.length>0&&l({controller:c}),u.type!=="text-delta"&&u.type!=="text-start"&&u.type!=="text-end"){c.enqueue({part:u,partialOutput:void 0});return}if(t==null)t=u.id;else if(u.id!==t){c.enqueue({part:u,partialOutput:void 0});return}if(u.type==="text-start"){c.enqueue({part:u,partialOutput:void 0});return}if(u.type==="text-end"){a.length>0&&l({controller:c}),c.enqueue({part:u,partialOutput:void 0});return}o+=u.text,a+=u.text,n=(d=u.providerMetadata)!=null?d:n;let p=await e.parsePartialOutput({text:o});if(p!==void 0){let m=typeof p.partial=="string"?p.partial:JSON.stringify(p.partial);m!==i&&(l({controller:c,partialOutput:p.partial}),i=m)}}})}s(N8,"createOutputTransformStream");var j8=class{static{s(this,"DefaultStreamTextResult")}constructor({model:e,telemetry:t,headers:o,settings:a,maxRetries:n,abortSignal:i,stepTimeoutMs:l,stepAbortController:u,chunkTimeoutMs:c,chunkAbortController:d,system:p,prompt:m,messages:f,allowSystemInMessages:h,tools:g,toolChoice:y,transforms:_,activeTools:v,repairToolCall:x,stopConditions:w,output:S,providerOptions:P,prepareStep:k,includeRawChunks:I,now:E,generateId:b,timeout:M,stopWhen:R,originalAbortSignal:D,onChunk:te,onError:ee,onFinish:J,onAbort:W,onStepFinish:j,onStart:O,onStepStart:Z,onToolCallStart:F,onToolCallFinish:z,experimental_context:Y,download:ae,include:K}){this._totalUsage=new ms,this._finishReason=new ms,this._rawFinishReason=new ms,this._steps=new ms,this.outputSpecification=S,this.includeRawChunks=I,this.tools=g;let L=rN()(t?.integrations),le,oe=[],ne=[],C,G,X,q={},Me=[],fe=[],at=new Map,rr,Tr={},gr={},Ho=new TransformStream({async transform(Rt,lr){var br,$o,pn,Jo;lr.enqueue(Rt);let{part:be}=Rt;if((be.type==="text-delta"||be.type==="reasoning-delta"||be.type==="source"||be.type==="tool-call"||be.type==="tool-result"||be.type==="tool-input-start"||be.type==="tool-input-delta"||be.type==="raw")&&await te?.({chunk:be}),be.type==="error"&&await ee({error:Qz(be.error)}),be.type==="text-start"&&(Tr[be.id]={type:"text",text:"",providerMetadata:be.providerMetadata},oe.push(Tr[be.id])),be.type==="text-delta"){let Ve=Tr[be.id];if(Ve==null){lr.enqueue({part:{type:"error",error:`text part ${be.id} not found`},partialOutput:void 0});return}Ve.text+=be.text,Ve.providerMetadata=(br=be.providerMetadata)!=null?br:Ve.providerMetadata}if(be.type==="text-end"){let Ve=Tr[be.id];if(Ve==null){lr.enqueue({part:{type:"error",error:`text part ${be.id} not found`},partialOutput:void 0});return}Ve.providerMetadata=($o=be.providerMetadata)!=null?$o:Ve.providerMetadata,delete Tr[be.id]}if(be.type==="reasoning-start"&&(gr[be.id]={type:"reasoning",text:"",providerMetadata:be.providerMetadata},oe.push(gr[be.id])),be.type==="reasoning-delta"){let Ve=gr[be.id];if(Ve==null){lr.enqueue({part:{type:"error",error:`reasoning part ${be.id} not found`},partialOutput:void 0});return}Ve.text+=be.text,Ve.providerMetadata=(pn=be.providerMetadata)!=null?pn:Ve.providerMetadata}if(be.type==="reasoning-end"){let Ve=gr[be.id];if(Ve==null){lr.enqueue({part:{type:"error",error:`reasoning part ${be.id} not found`},partialOutput:void 0});return}Ve.providerMetadata=(Jo=be.providerMetadata)!=null?Jo:Ve.providerMetadata,delete gr[be.id]}if(be.type==="file"&&oe.push({type:"file",file:be.file,...be.providerMetadata!=null?{providerMetadata:be.providerMetadata}:{}}),be.type==="source"&&oe.push(be),be.type==="tool-call"&&oe.push(be),be.type==="tool-result"&&!be.preliminary&&oe.push(be),be.type==="tool-approval-request"&&oe.push(be),be.type==="tool-error"&&oe.push(be),be.type==="start-step"&&(oe=[],gr={},Tr={},q=be.request,Me=be.warnings),be.type==="finish-step"){let Ve=await X0({content:oe,tools:g}),yr=new uN({stepNumber:fe.length,model:Ee,...He,experimental_context:Y,content:oe,finishReason:be.finishReason,rawFinishReason:be.rawFinishReason,usage:be.usage,warnings:Me,request:q,response:{...be.response,messages:[...ne,...Ve]},providerMetadata:be.providerMetadata});await Pn({event:yr,callbacks:[j,L.onStepFinish]}),gs({warnings:Me,provider:Ee.provider,model:Ee.modelId}),fe.push(yr),ne.push(...Ve),le.resolve()}be.type==="finish"&&(X=be.totalUsage,C=be.finishReason,G=be.rawFinishReason)},async flush(Rt){var lr,br,$o,pn,Jo,be,Ve;try{if(fe.length===0){let Dr=i?.aborted?i.reason:new bz({message:"No output generated. Check the stream for errors."});B._finishReason.reject(Dr),B._rawFinishReason.reject(Dr),B._totalUsage.reject(Dr),B._steps.reject(Dr);return}let yr=C??"other",ur=X??J0();B._finishReason.resolve(yr),B._rawFinishReason.resolve(G),B._totalUsage.resolve(ur),B._steps.resolve(fe);let je=fe[fe.length-1];await Pn({event:{stepNumber:je.stepNumber,model:je.model,functionId:je.functionId,metadata:je.metadata,experimental_context:je.experimental_context,finishReason:je.finishReason,rawFinishReason:je.rawFinishReason,totalUsage:ur,usage:je.usage,content:je.content,text:je.text,reasoningText:je.reasoningText,reasoning:je.reasoning,files:je.files,sources:je.sources,toolCalls:je.toolCalls,staticToolCalls:je.staticToolCalls,dynamicToolCalls:je.dynamicToolCalls,toolResults:je.toolResults,staticToolResults:je.staticToolResults,dynamicToolResults:je.dynamicToolResults,request:je.request,response:je.response,warnings:je.warnings,providerMetadata:je.providerMetadata,steps:fe},callbacks:[J,L.onFinish]}),rr.setAttributes(await sr({telemetry:t,attributes:{"ai.response.finishReason":yr,"ai.response.text":{output:s(()=>je.text,"output")},"ai.response.reasoning":{output:s(()=>je.reasoningText,"output")},"ai.response.toolCalls":{output:s(()=>{var Dr;return(Dr=je.toolCalls)!=null&&Dr.length?JSON.stringify(je.toolCalls):void 0},"output")},"ai.response.providerMetadata":JSON.stringify(je.providerMetadata),"ai.usage.inputTokens":ur.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(lr=ur.inputTokenDetails)==null?void 0:lr.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(br=ur.inputTokenDetails)==null?void 0:br.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":($o=ur.inputTokenDetails)==null?void 0:$o.cacheWriteTokens,"ai.usage.outputTokens":ur.outputTokens,"ai.usage.outputTokenDetails.textTokens":(pn=ur.outputTokenDetails)==null?void 0:pn.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Jo=ur.outputTokenDetails)==null?void 0:Jo.reasoningTokens,"ai.usage.totalTokens":ur.totalTokens,"ai.usage.reasoningTokens":(be=ur.outputTokenDetails)==null?void 0:be.reasoningTokens,"ai.usage.cachedInputTokens":(Ve=ur.inputTokenDetails)==null?void 0:Ve.cacheReadTokens}}))}catch(yr){Rt.error(yr)}finally{rr.end()}}}),Mr=$8();this.addStream=Mr.addStream,this.closeStream=Mr.close;let De=Mr.stream.getReader(),Wr=new ReadableStream({async start(Rt){Rt.enqueue({type:"start"})},async pull(Rt){function lr(){W?.({steps:fe}),Rt.enqueue({type:"abort",...i?.reason!==void 0?{reason:vn(i.reason)}:{}}),Rt.close()}s(lr,"abort");try{let{done:br,value:$o}=await De.read();if(br){Rt.close();return}if(i?.aborted){lr();return}Rt.enqueue($o)}catch(br){$a(br)&&i?.aborted?lr():Rt.error(br)}},cancel(Rt){return Mr.stream.cancel(Rt)}});for(let Rt of _)Wr=Wr.pipeThrough(Rt({tools:g,stopStream(){Mr.terminate()}}));this.baseStream=Wr.pipeThrough(N8(S??Wg())).pipeThrough(Ho);let{maxRetries:dn,retry:Bn}=hp({maxRetries:n,abortSignal:i}),Oo=Kg(t),Kt=G0(a),T=Gg({model:e,telemetry:t,headers:o,settings:{...Kt,maxRetries:dn}}),B=this,Ee={provider:e.provider,modelId:e.modelId},He={functionId:t?.functionId,metadata:t?.metadata};aa({name:"ai.streamText",attributes:sr({telemetry:t,attributes:{...na({operationId:"ai.streamText",telemetry:t}),...T,"ai.prompt":{input:s(()=>JSON.stringify({system:p,prompt:m,messages:f}),"input")}}}),tracer:Oo,endWhenDone:!1,fn:s(async Rt=>{rr=Rt;let lr=await Yz({system:p,prompt:m,messages:f,allowSystemInMessages:h});await Pn({event:{model:Ee,system:p,prompt:m,messages:f,tools:g,toolChoice:y,activeTools:v,maxOutputTokens:Kt.maxOutputTokens,temperature:Kt.temperature,topP:Kt.topP,topK:Kt.topK,presencePenalty:Kt.presencePenalty,frequencyPenalty:Kt.frequencyPenalty,stopSequences:Kt.stopSequences,seed:Kt.seed,maxRetries:dn,timeout:M,headers:o,providerOptions:P,stopWhen:R,output:S,abortSignal:D,include:K,...He,experimental_context:Y},callbacks:[O,L.onStart]});let br=lr.messages,$o=[],{approvedToolApprovals:pn,deniedToolApprovals:Jo}=aN({messages:br});if(Jo.length>0||pn.length>0){let Ve=pn.filter(Xe=>!Xe.toolCall.providerExecuted),yr=Jo.filter(Xe=>!Xe.toolCall.providerExecuted),ur=Jo.filter(Xe=>Xe.toolCall.providerExecuted),je,Dr=new ReadableStream({start(Xe){je=Xe}});B.addStream(Dr);try{for(let or of[...yr,...ur])je?.enqueue({type:"tool-output-denied",toolCallId:or.toolCall.toolCallId,toolName:or.toolCall.toolName});let Xe=[];if(await Promise.all(Ve.map(async or=>{let nr=await aT({toolCall:or.toolCall,tools:g,tracer:Oo,telemetry:t,messages:br,abortSignal:i,experimental_context:Y,stepNumber:fe.length,model:Ee,onToolCallStart:[F,L.onToolCallStart],onToolCallFinish:[z,L.onToolCallFinish],onPreliminaryToolResult:s(Er=>{je?.enqueue(Er)},"onPreliminaryToolResult")});nr!=null&&(je?.enqueue(nr),Xe.push(nr))})),Xe.length>0||yr.length>0){let or=[];for(let nr of Xe)or.push({type:"tool-result",toolCallId:nr.toolCallId,toolName:nr.toolName,output:await pp({toolCallId:nr.toolCallId,input:nr.input,tool:g?.[nr.toolName],output:nr.type==="tool-result"?nr.output:nr.error,errorMode:nr.type==="tool-error"?"text":"none"})});for(let nr of yr)or.push({type:"tool-result",toolCallId:nr.toolCall.toolCallId,toolName:nr.toolCall.toolName,output:{type:"execution-denied",reason:nr.approvalResponse.reason}});$o.push({role:"tool",content:or})}}finally{je?.close()}}ne.push(...$o);async function be({currentStep:Ve,responseMessages:yr,usage:ur}){var je,Dr,Xe,or,nr,Er,Ur,ut,co;let Ha=B.includeRawChunks,Nu=l!=null?setTimeout(()=>u.abort(),l):void 0,ga;function qs(){c!=null&&(ga!=null&&clearTimeout(ga),ga=setTimeout(()=>d.abort(),c))}s(qs,"resetChunkTimeout");function Fs(){ga!=null&&(clearTimeout(ga),ga=void 0)}s(Fs,"clearChunkTimeout");function Am(){Nu!=null&&clearTimeout(Nu)}s(Am,"clearStepTimeout");try{le=new ms;let Ja=[...br,...yr],pr=await k?.({model:e,steps:fe,stepNumber:fe.length,messages:Ja,experimental_context:Y}),po=Zg((je=pr?.model)!=null?je:e),Bs={provider:po.provider,modelId:po.modelId},Cm=await Jz({prompt:{system:(Dr=pr?.system)!=null?Dr:lr.system,messages:(Xe=pr?.messages)!=null?Xe:Ja},supportedUrls:await po.supportedUrls,download:ae}),ju=(or=pr?.activeTools)!=null?or:v,{toolChoice:Vs,tools:Mu}=await Wz({tools:g,toolChoice:(nr=pr?.toolChoice)!=null?nr:y,activeTools:ju});Y=(Er=pr?.experimental_context)!=null?Er:Y;let q_=(Ur=pr?.messages)!=null?Ur:Ja,Om=(ut=pr?.system)!=null?ut:lr.system,ct=Xg(P,pr?.providerOptions);await Pn({event:{stepNumber:fe.length,model:Bs,system:Om,messages:q_,tools:g,toolChoice:Vs,activeTools:ju,steps:[...fe],providerOptions:ct,timeout:M,headers:o,stopWhen:R,output:S,abortSignal:D,include:K,...He,experimental_context:Y},callbacks:[Z,L.onStepStart]});let{result:{stream:Gr,response:Zs,request:ya},doStreamSpan:Vn,startTimestampMs:Du}=await Bn(()=>aa({name:"ai.streamText.doStream",attributes:sr({telemetry:t,attributes:{...na({operationId:"ai.streamText.doStream",telemetry:t}),...T,"ai.model.provider":po.provider,"ai.model.id":po.modelId,"ai.prompt.messages":{input:s(()=>tN(Cm),"input")},"ai.prompt.tools":{input:s(()=>Mu?.map(qe=>JSON.stringify(qe)),"input")},"ai.prompt.toolChoice":{input:s(()=>Vs!=null?JSON.stringify(Vs):void 0,"input")},"gen_ai.system":po.provider,"gen_ai.request.model":po.modelId,"gen_ai.request.frequency_penalty":Kt.frequencyPenalty,"gen_ai.request.max_tokens":Kt.maxOutputTokens,"gen_ai.request.presence_penalty":Kt.presencePenalty,"gen_ai.request.stop_sequences":Kt.stopSequences,"gen_ai.request.temperature":Kt.temperature,"gen_ai.request.top_k":Kt.topK,"gen_ai.request.top_p":Kt.topP}}),tracer:Oo,endWhenDone:!1,fn:s(async qe=>({startTimestampMs:E(),doStreamSpan:qe,result:await po.doStream({...Kt,tools:Mu,toolChoice:Vs,responseFormat:await S?.responseFormat,prompt:Cm,providerOptions:ct,abortSignal:i,headers:o,includeRawChunks:Ha})}),"fn")})),$m=R8({tools:g,generatorStream:Gr,tracer:Oo,telemetry:t,system:p,messages:Ja,repairToolCall:x,abortSignal:i,experimental_context:Y,generateId:b,stepNumber:fe.length,model:Bs,onToolCallStart:[F,L.onToolCallStart],onToolCallFinish:[z,L.onToolCallFinish]}),Rm=(co=K?.requestBody)==null||co?ya??{}:{...ya,body:void 0},Wa=[],Ga=[],Lt,Zn={},Ka="other",Hs,Lr=J0(),Gk,Kk=!0,Hn={id:b(),timestamp:new Date,modelId:Ee.modelId},sB="";B.addStream($m.pipeThrough(new TransformStream({async transform(qe,Sr){var Uu,Lu,qu,Fu,Bu;if(qs(),qe.type==="stream-start"){Lt=qe.warnings;return}if(Kk){let xr=E()-Du;Kk=!1,Vn.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":xr}),Vn.setAttributes({"ai.response.msToFirstChunk":xr}),Sr.enqueue({type:"start-step",request:Rm,warnings:Lt??[]})}let Vu=qe.type;switch(Vu){case"tool-approval-request":case"text-start":case"text-end":{Sr.enqueue(qe);break}case"text-delta":{qe.delta.length>0&&(Sr.enqueue({type:"text-delta",id:qe.id,text:qe.delta,providerMetadata:qe.providerMetadata}),sB+=qe.delta);break}case"reasoning-start":case"reasoning-end":{Sr.enqueue(qe);break}case"reasoning-delta":{Sr.enqueue({type:"reasoning-delta",id:qe.id,text:qe.delta,providerMetadata:qe.providerMetadata});break}case"tool-call":{Sr.enqueue(qe),Wa.push(qe);break}case"tool-result":{Sr.enqueue(qe),qe.preliminary||Ga.push(qe);break}case"tool-error":{Sr.enqueue(qe),Ga.push(qe);break}case"response-metadata":{Hn={id:(Uu=qe.id)!=null?Uu:Hn.id,timestamp:(Lu=qe.timestamp)!=null?Lu:Hn.timestamp,modelId:(qu=qe.modelId)!=null?qu:Hn.modelId};break}case"finish":{Lr=qe.usage,Ka=qe.finishReason,Hs=qe.rawFinishReason,Gk=qe.providerMetadata;let xr=E()-Du;Vn.addEvent("ai.stream.finish"),Vn.setAttributes({"ai.response.msToFinish":xr,"ai.response.avgOutputTokensPerSecond":1e3*((Fu=Lr.outputTokens)!=null?Fu:0)/xr});break}case"file":{Sr.enqueue(qe);break}case"source":{Sr.enqueue(qe);break}case"tool-input-start":{Zn[qe.id]=qe.toolName;let xr=g?.[qe.toolName];xr?.onInputStart!=null&&await xr.onInputStart({toolCallId:qe.id,messages:Ja,abortSignal:i,experimental_context:Y}),Sr.enqueue({...qe,dynamic:(Bu=qe.dynamic)!=null?Bu:xr?.type==="dynamic",title:xr?.title});break}case"tool-input-end":{delete Zn[qe.id],Sr.enqueue(qe);break}case"tool-input-delta":{let xr=Zn[qe.id],Js=g?.[xr];Js?.onInputDelta!=null&&await Js.onInputDelta({inputTextDelta:qe.delta,toolCallId:qe.id,messages:Ja,abortSignal:i,experimental_context:Y}),Sr.enqueue(qe);break}case"error":{Sr.enqueue(qe),Ka="error";break}case"raw":{Ha&&Sr.enqueue(qe);break}default:{let xr=Vu;throw new Error(`Unknown chunk type: ${xr}`)}}},async flush(qe){var Sr,Uu,Lu,qu,Fu,Bu,Vu;let xr=Wa.length>0?JSON.stringify(Wa):void 0;try{Vn.setAttributes(await sr({telemetry:t,attributes:{"ai.response.finishReason":Ka,"ai.response.toolCalls":{output:s(()=>xr,"output")},"ai.response.id":Hn.id,"ai.response.model":Hn.modelId,"ai.response.timestamp":Hn.timestamp.toISOString(),"ai.usage.inputTokens":Lr.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Sr=Lr.inputTokenDetails)==null?void 0:Sr.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Uu=Lr.inputTokenDetails)==null?void 0:Uu.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Lu=Lr.inputTokenDetails)==null?void 0:Lu.cacheWriteTokens,"ai.usage.outputTokens":Lr.outputTokens,"ai.usage.outputTokenDetails.textTokens":(qu=Lr.outputTokenDetails)==null?void 0:qu.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Fu=Lr.outputTokenDetails)==null?void 0:Fu.reasoningTokens,"ai.usage.totalTokens":Lr.totalTokens,"ai.usage.reasoningTokens":(Bu=Lr.outputTokenDetails)==null?void 0:Bu.reasoningTokens,"ai.usage.cachedInputTokens":(Vu=Lr.inputTokenDetails)==null?void 0:Vu.cacheReadTokens,"gen_ai.response.finish_reasons":[Ka],"gen_ai.response.id":Hn.id,"gen_ai.response.model":Hn.modelId,"gen_ai.usage.input_tokens":Lr.inputTokens,"gen_ai.usage.output_tokens":Lr.outputTokens}}))}catch{}qe.enqueue({type:"finish-step",finishReason:Ka,rawFinishReason:Hs,usage:Lr,providerMetadata:Gk,response:{...Hn,headers:Zs?.headers}});let Js=oN(ur,Lr);await le.promise;let F_=fe[fe.length-1];try{Vn.setAttributes(await sr({telemetry:t,attributes:{"ai.response.text":{output:s(()=>F_.text,"output")},"ai.response.reasoning":{output:s(()=>F_.reasoningText,"output")},"ai.response.providerMetadata":JSON.stringify(F_.providerMetadata)}}))}catch{}finally{Vn.end()}let Xk=Wa.filter(Ar=>Ar.providerExecuted!==!0),lB=Ga.filter(Ar=>Ar.providerExecuted!==!0);for(let Ar of Wa){if(Ar.providerExecuted!==!0)continue;let B_=g?.[Ar.toolName];B_?.type==="provider"&&B_.supportsDeferredResults&&(Ga.some(V_=>(V_.type==="tool-result"||V_.type==="tool-error")&&V_.toolCallId===Ar.toolCallId)||at.set(Ar.toolCallId,{toolName:Ar.toolName}))}for(let Ar of Ga)(Ar.type==="tool-result"||Ar.type==="tool-error")&&at.delete(Ar.toolCallId);if(Am(),Fs(),(Xk.length>0&&lB.length===Xk.length||at.size>0)&&!await dN({stopConditions:w,steps:fe})){yr.push(...await X0({content:fe[fe.length-1].content,tools:g}));try{await be({currentStep:Ve+1,responseMessages:yr,usage:Js})}catch(Ar){qe.enqueue({type:"error",error:Ar}),B.closeStream()}}else qe.enqueue({type:"finish",finishReason:Ka,rawFinishReason:Hs,totalUsage:Js}),B.closeStream()}})))}finally{Am(),Fs()}}s(be,"streamStep"),await be({currentStep:0,responseMessages:$o,usage:J0()})},"fn")}).catch(Rt=>{B.addStream(new ReadableStream({start(lr){lr.enqueue({type:"error",error:Rt}),lr.close()}})),B.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return dp(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return dp(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await O8({stream:this.fullStream,onError:e?.onError})}catch(o){(t=e?.onError)==null||t.call(e,o)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return dp(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,o;let a=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(a==null)throw new Le({functionality:`element streams in ${(o=(t=this.outputSpecification)==null?void 0:t.name)!=null?o:"text"} mode`});return dp(this.teeStream().pipeThrough(a))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:Wg()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:o,messageMetadata:a,sendReasoning:n=!0,sendSources:i=!1,sendStart:l=!0,sendFinish:u=!0,onError:c=vn}={}){let d=t!=null?S8({originalMessages:e,responseMessageId:t}):void 0,p=s(f=>{var h;let g=(h=this.tools)==null?void 0:h[f.toolName];return g==null?f.dynamic:g?.type==="dynamic"?!0:void 0},"isDynamic"),m=this.fullStream.pipeThrough(new TransformStream({transform:s(async(f,h)=>{let g=a?.({part:f}),y=f.type;switch(y){case"text-start":{h.enqueue({type:"text-start",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-start":case"reasoning-end":{n&&h.enqueue({type:y,id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-delta":{n&&h.enqueue({type:"reasoning-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:f.file.mediaType,url:`data:${f.file.mediaType};base64,${f.file.base64}`,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"source":{i&&f.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:f.id,url:f.url,title:f.title,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}}),i&&f.sourceType==="document"&&h.enqueue({type:"source-document",sourceId:f.id,mediaType:f.mediaType,title:f.title,filename:f.filename,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"tool-input-start":{let _=p(f);h.enqueue({type:"tool-input-start",toolCallId:f.id,toolName:f.toolName,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},..._!=null?{dynamic:_}:{},...f.title!=null?{title:f.title}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:f.id,inputTextDelta:f.delta});break}case"tool-call":{let _=p(f);f.invalid?h.enqueue({type:"tool-input-error",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},..._!=null?{dynamic:_}:{},errorText:c(f.error),...f.title!=null?{title:f.title}:{}}):h.enqueue({type:"tool-input-available",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},..._!=null?{dynamic:_}:{},...f.title!=null?{title:f.title}:{}});break}case"tool-approval-request":{h.enqueue({type:"tool-approval-request",approvalId:f.approvalId,toolCallId:f.toolCall.toolCallId});break}case"tool-result":{let _=p(f);h.enqueue({type:"tool-output-available",toolCallId:f.toolCallId,output:f.output,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},...f.preliminary!=null?{preliminary:f.preliminary}:{},..._!=null?{dynamic:_}:{}});break}case"tool-error":{let _=p(f);h.enqueue({type:"tool-output-error",toolCallId:f.toolCallId,errorText:f.providerExecuted?typeof f.error=="string"?f.error:JSON.stringify(f.error):c(f.error),...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},..._!=null?{dynamic:_}:{}});break}case"tool-output-denied":{h.enqueue({type:"tool-output-denied",toolCallId:f.toolCallId});break}case"error":{h.enqueue({type:"error",errorText:c(f.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{l&&h.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...d!=null?{messageId:d}:{}});break}case"finish":{u&&h.enqueue({type:"finish",finishReason:f.finishReason,...g!=null?{messageMetadata:g}:{}});break}case"abort":{h.enqueue(f);break}case"tool-input-end":break;case"raw":break;default:{let _=y;throw new Error(`Unknown chunk type: ${_}`)}}g!=null&&y!=="start"&&y!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:g})},"transform")}));return dp(A8({stream:m,messageId:d??t?.(),originalMessages:e,onFinish:o,onError:c}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:o,onFinish:a,messageMetadata:n,sendReasoning:i,sendSources:l,sendFinish:u,sendStart:c,onError:d,...p}={}){C8({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:o,onFinish:a,messageMetadata:n,sendReasoning:i,sendSources:l,sendFinish:u,sendStart:c,onError:d}),...p})}pipeTextStreamToResponse(e,t){w8({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:o,messageMetadata:a,sendReasoning:n,sendSources:i,sendFinish:l,sendStart:u,onError:c,...d}={}){return T8({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:o,messageMetadata:a,sendReasoning:n,sendSources:i,sendFinish:l,sendStart:u,onError:c}),...d})}toTextStreamResponse(e){return x8({textStream:this.textStream,...e})}};var pze=N(()=>$(r.array(r.object({id:r.string(),role:r.enum(["system","user","assistant"]),metadata:r.unknown().optional(),parts:r.array(r.union([r.object({type:r.literal("text"),text:r.string(),state:r.enum(["streaming","done"]).optional(),providerMetadata:ze.optional()}),r.object({type:r.literal("reasoning"),text:r.string(),state:r.enum(["streaming","done"]).optional(),providerMetadata:ze.optional()}),r.object({type:r.literal("source-url"),sourceId:r.string(),url:r.string(),title:r.string().optional(),providerMetadata:ze.optional()}),r.object({type:r.literal("source-document"),sourceId:r.string(),mediaType:r.string(),title:r.string(),filename:r.string().optional(),providerMetadata:ze.optional()}),r.object({type:r.literal("file"),mediaType:r.string(),filename:r.string().optional(),url:r.string(),providerMetadata:ze.optional()}),r.object({type:r.literal("step-start")}),r.object({type:r.string().startsWith("data-"),id:r.string().optional(),data:r.unknown()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("input-streaming"),input:r.unknown().optional(),providerExecuted:r.boolean().optional(),callProviderMetadata:ze.optional(),output:r.never().optional(),errorText:r.never().optional(),approval:r.never().optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("input-available"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.never().optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("approval-requested"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.never().optional(),reason:r.never().optional()})}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("approval-responded"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.boolean(),reason:r.string().optional()})}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("output-available"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.unknown(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),resultProviderMetadata:ze.optional(),preliminary:r.boolean().optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional()}).optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("output-error"),input:r.unknown(),rawInput:r.unknown().optional(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.string(),callProviderMetadata:ze.optional(),resultProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional()}).optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),state:r.literal("output-denied"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.literal(!1),reason:r.string().optional()})}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("input-streaming"),providerExecuted:r.boolean().optional(),callProviderMetadata:ze.optional(),input:r.unknown().optional(),output:r.never().optional(),errorText:r.never().optional(),approval:r.never().optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("input-available"),providerExecuted:r.boolean().optional(),input:r.unknown(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.never().optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("approval-requested"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.never().optional(),reason:r.never().optional()})}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("approval-responded"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.boolean(),reason:r.string().optional()})}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("output-available"),providerExecuted:r.boolean().optional(),input:r.unknown(),output:r.unknown(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),resultProviderMetadata:ze.optional(),preliminary:r.boolean().optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional()}).optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("output-error"),providerExecuted:r.boolean().optional(),input:r.unknown(),rawInput:r.unknown().optional(),output:r.never().optional(),errorText:r.string(),callProviderMetadata:ze.optional(),resultProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional()}).optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),state:r.literal("output-denied"),providerExecuted:r.boolean().optional(),input:r.unknown(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:ze.optional(),approval:r.object({id:r.string(),approved:r.literal(!1),reason:r.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));async function yN({model:e,value:t,providerOptions:o,maxRetries:a,abortSignal:n,headers:i,experimental_telemetry:l}){let u=qz(e),{maxRetries:c,retry:d}=hp({maxRetries:a,abortSignal:n}),p=Qt(i??{},`ai/${fp}`),m=Gg({model:u,telemetry:l,headers:p,settings:{maxRetries:c}}),f=Kg(l);return aa({name:"ai.embed",attributes:sr({telemetry:l,attributes:{...na({operationId:"ai.embed",telemetry:l}),...m,"ai.value":{input:s(()=>JSON.stringify(t),"input")}}}),tracer:f,fn:s(async h=>{let{embedding:g,usage:y,warnings:_,response:v,providerMetadata:x}=await d(()=>aa({name:"ai.embed.doEmbed",attributes:sr({telemetry:l,attributes:{...na({operationId:"ai.embed.doEmbed",telemetry:l}),...m,"ai.values":{input:s(()=>[JSON.stringify(t)],"input")}}}),tracer:f,fn:s(async w=>{var S;let P=await u.doEmbed({values:[t],abortSignal:n,headers:p,providerOptions:o}),k=P.embeddings[0],I=(S=P.usage)!=null?S:{tokens:NaN};return w.setAttributes(await sr({telemetry:l,attributes:{"ai.embeddings":{output:s(()=>P.embeddings.map(E=>JSON.stringify(E)),"output")},"ai.usage.tokens":I.tokens}})),{embedding:k,usage:I,warnings:P.warnings,providerMetadata:P.providerMetadata,response:P.response}},"fn")}));return h.setAttributes(await sr({telemetry:l,attributes:{"ai.embedding":{output:s(()=>JSON.stringify(g),"output")},"ai.usage.tokens":y.tokens}})),gs({warnings:_,provider:u.provider,model:u.modelId}),new M8({value:t,embedding:g,usage:y,warnings:_,providerMetadata:x,response:v})},"fn")})}s(yN,"embed");var M8=class{static{s(this,"DefaultEmbedResult")}constructor(e){this.value=e.value,this.embedding=e.embedding,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.response=e.response}};function JR(e,t){if(t<=0)throw new Error("chunkSize must be greater than 0");let o=[];for(let a=0;a<e.length;a+=t)o.push(e.slice(a,a+t));return o}s(JR,"splitArray");async function _N({model:e,values:t,maxParallelCalls:o=1/0,maxRetries:a,abortSignal:n,headers:i,providerOptions:l,experimental_telemetry:u}){let c=qz(e),{maxRetries:d,retry:p}=hp({maxRetries:a,abortSignal:n}),m=Qt(i??{},`ai/${fp}`),f=Gg({model:c,telemetry:u,headers:m,settings:{maxRetries:d}}),h=Kg(u);return aa({name:"ai.embedMany",attributes:sr({telemetry:u,attributes:{...na({operationId:"ai.embedMany",telemetry:u}),...f,"ai.values":{input:s(()=>t.map(g=>JSON.stringify(g)),"input")}}}),tracer:h,fn:s(async g=>{var y;let[_,v]=await Promise.all([c.maxEmbeddingsPerCall,c.supportsParallelCalls]);if(_==null||_===1/0){let{embeddings:b,usage:M,warnings:R,response:D,providerMetadata:te}=await p(()=>aa({name:"ai.embedMany.doEmbed",attributes:sr({telemetry:u,attributes:{...na({operationId:"ai.embedMany.doEmbed",telemetry:u}),...f,"ai.values":{input:s(()=>t.map(ee=>JSON.stringify(ee)),"input")}}}),tracer:h,fn:s(async ee=>{var J;let W=await c.doEmbed({values:t,abortSignal:n,headers:m,providerOptions:l}),j=W.embeddings,O=(J=W.usage)!=null?J:{tokens:NaN};return ee.setAttributes(await sr({telemetry:u,attributes:{"ai.embeddings":{output:s(()=>j.map(Z=>JSON.stringify(Z)),"output")},"ai.usage.tokens":O.tokens}})),{embeddings:j,usage:O,warnings:W.warnings,providerMetadata:W.providerMetadata,response:W.response}},"fn")}));return g.setAttributes(await sr({telemetry:u,attributes:{"ai.embeddings":{output:s(()=>b.map(ee=>JSON.stringify(ee)),"output")},"ai.usage.tokens":M.tokens}})),gs({warnings:R,provider:c.provider,model:c.modelId}),new WR({values:t,embeddings:b,usage:M,warnings:R,providerMetadata:te,responses:[D]})}let x=JR(t,_),w=[],S=[],P=[],k=0,I,E=JR(x,v?o:1);for(let b of E){let M=await Promise.all(b.map(R=>p(()=>aa({name:"ai.embedMany.doEmbed",attributes:sr({telemetry:u,attributes:{...na({operationId:"ai.embedMany.doEmbed",telemetry:u}),...f,"ai.values":{input:s(()=>R.map(D=>JSON.stringify(D)),"input")}}}),tracer:h,fn:s(async D=>{var te;let ee=await c.doEmbed({values:R,abortSignal:n,headers:m,providerOptions:l}),J=ee.embeddings,W=(te=ee.usage)!=null?te:{tokens:NaN};return D.setAttributes(await sr({telemetry:u,attributes:{"ai.embeddings":{output:s(()=>J.map(j=>JSON.stringify(j)),"output")},"ai.usage.tokens":W.tokens}})),{embeddings:J,usage:W,warnings:ee.warnings,providerMetadata:ee.providerMetadata,response:ee.response}},"fn")}))));for(let R of M)if(w.push(...R.embeddings),S.push(...R.warnings),P.push(R.response),k+=R.usage.tokens,R.providerMetadata)if(!I)I={...R.providerMetadata};else for(let[D,te]of Object.entries(R.providerMetadata))I[D]={...(y=I[D])!=null?y:{},...te}}return g.setAttributes(await sr({telemetry:u,attributes:{"ai.embeddings":{output:s(()=>w.map(b=>JSON.stringify(b)),"output")},"ai.usage.tokens":k}})),gs({warnings:S,provider:c.provider,model:c.modelId}),new WR({values:t,embeddings:w,usage:{tokens:k},warnings:S,providerMetadata:I,responses:P})},"fn")})}s(_N,"embedMany");var WR=class{static{s(this,"DefaultEmbedManyResult")}constructor(e){this.values=e.values,this.embeddings=e.embeddings,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.responses=e.responses}};async function vN({model:e,prompt:t,n:o=1,maxImagesPerCall:a,size:n,aspectRatio:i,seed:l,providerOptions:u,maxRetries:c,abortSignal:d,headers:p}){var m,f;let h=MK(e),g=Qt(p??{},`ai/${fp}`),{retry:y}=hp({maxRetries:c,abortSignal:d}),_=(m=a??await U8(h))!=null?m:1,v=Math.ceil(o/_),x=Array.from({length:v},(b,M)=>{if(M<v-1)return _;let R=o%_;return R===0?_:R}),w=await Promise.all(x.map(async b=>y(()=>{let{prompt:M,files:R,mask:D}=L8(t);return h.doGenerate({prompt:M,files:R,mask:D,n:b,abortSignal:d,headers:g,size:n,aspectRatio:i,seed:l,providerOptions:u??{}})}))),S=[],P=[],k=[],I={},E={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};for(let b of w){if(S.push(...b.images.map(M=>{var R;return new iT({data:M,mediaType:(R=Jg({data:M,signatures:Hg}))!=null?R:"image/png"})})),P.push(...b.warnings),b.usage!=null&&(E=l8(E,b.usage)),b.providerMetadata)for(let[M,R]of Object.entries(b.providerMetadata))if(M==="gateway"){let D=I[M];D!=null&&typeof D=="object"?I[M]={...D,...R}:I[M]=R;let te=I[M].images;Array.isArray(te)&&te.length===0&&delete I[M].images}else(f=I[M])!=null||(I[M]={images:[]}),I[M].images.push(...b.providerMetadata[M].images);k.push(b.response)}if(gs({warnings:P,provider:h.provider,model:h.modelId}),!S.length)throw new nK({responses:k});return new D8({images:S,warnings:P,responses:k,providerMetadata:I,usage:E})}s(vN,"generateImage");var D8=class{static{s(this,"DefaultGenerateImageResult")}constructor(e){this.images=e.images,this.warnings=e.warnings,this.responses=e.responses,this.providerMetadata=e.providerMetadata,this.usage=e.usage}get image(){return this.images[0]}};async function U8(e){return e.maxImagesPerCall instanceof Function?e.maxImagesPerCall({modelId:e.modelId}):e.maxImagesPerCall}s(U8,"invokeModelMaxImagesPerCall");function L8(e){return typeof e=="string"?{prompt:e,files:void 0,mask:void 0}:{prompt:e.text,files:e.images.map(GR),mask:e.mask?GR(e.mask):void 0}}s(L8,"normalizePrompt");function GR(e){if(typeof e=="string"&&e.startsWith("http"))return{type:"url",url:e};if(typeof e=="string"&&e.startsWith("data:")){let{mediaType:o,base64Content:a}=Vz(e);if(a!=null){let n=Yt(a);return{type:"file",data:n,mediaType:o||Jg({data:n,signatures:Hg})||"image/png"}}}let t=BK(e);return{type:"file",data:t,mediaType:Jg({data:t,signatures:Hg})||"image/png"}}s(GR,"toImageModelV3File");var yze=Xn({prefix:"aiobj",size:24});function bN(e){return({url:t,abortSignal:o})=>Bz({url:t,maxBytes:e?.maxBytes,abortSignal:o})}s(bN,"createDownload");var vze=Xn({prefix:"aiobj",size:24});var bze=bN();var q8="AI_NoSuchProviderError",F8=`vercel.ai.error.${q8}`,B8=Symbol.for(F8),V8;V8=B8;var xze=bN();var TN=require("node:stream");var Qg=class{constructor(t,o){this.baseUrl=t;this.authenticationConverter=o}static{s(this,"BaseHttpClient")}getUrl(t){let o=new URL(`${this.baseUrl}${t.url}`),a=`${o.origin}${o.pathname}`,n=new URLSearchParams;return o.searchParams.forEach((i,l)=>{n.append(l,i)}),{urlWithoutQueryParams:a,queryParams:n}}getHeaders(t){let o={Accept:"application/json"};return t.authentication&&this.populateAuthentication(t.authentication,o),t.body&&(t.headers?.["Content-Type"]==="text/csv"?o["Content-Type"]="text/csv":o["Content-Type"]="application/json"),t.headers&&(o={...o,...t.headers}),o}populateAuthentication(t,o){this.authenticationConverter.convert(t,o)}};var ey=class{static{s(this,"DelegatingAuthenticationConverter")}constructor(t=new sT,o=new lT){this.converters={BEARER_TOKEN:t,BASIC:o}}convert(t,o){return this.converters[t.type].convert(t,o)}},sT=class{static{s(this,"BearerTokenAuthenticationConverter")}convert(t,o){return o.Authorization=`Bearer ${t.token}`,o}},lT=class{static{s(this,"BasicTokenAuthenticationConverter")}convert(t,o){let a=`${t.username}:${t.password}`,n=Buffer.from(a).toString("base64");return o.Authorization=`Basic ${n}`,o}};var ty=class extends Error{constructor(o,a){let n=a.status||500,i=Buffer.isBuffer(a.responseBody)?a.responseBody.toString():a.responseBody;super(JSON.stringify({response:{status:n,body:i},request:{body:o}}));this.requestBody=o;this.status=n,this.responseBody=i}static{s(this,"HttpError")}errorMessage(){return{response:{status:this.status,body:this.responseBody},request:{body:this.requestBody}}}get response(){return{status:this.status,body:this.responseBody}}get request(){return{body:this.requestBody}}};var ry=class extends Qg{static{s(this,"FetchHttpClient")}constructor(t="",o=new ey){super(t,o)}async sendRequest(t,o){process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";let{urlWithoutQueryParams:a,queryParams:n}=this.getUrl(t),i=this.getHeaders(t),l=t.queryParams??{};for(let[w,S]of Object.entries(l))n.append(w,S);let u=n.toString(),c=u?`${a}?${u}`:a,d=t.responseType??"json",p=t.followRedirects??!0,m=t.retries??0,{body:f,extraHeaders:h,isStream:g}=Z8(t.body,i),y=J8({...i,...h}),_=await H8(async()=>{let w=new AbortController,S=t.timeout&&t.timeout>0?setTimeout(()=>w.abort(),t.timeout):void 0;try{let P={method:t.method.toString(),headers:y,body:f,redirect:p?"follow":"manual",signal:w.signal};return g&&(P.duplex="half"),o?.dispatcher!==void 0&&(P.dispatcher=o.dispatcher),await fetch(c,P)}finally{S!==void 0&&clearTimeout(S)}},m),v=p?300:400;if(_.status<200||_.status>=v){let w=await xN(_,d),S=new ty(t.body,{status:_.status,responseBody:w});throw console.error("[HttpClient#(sanitized error message)] Request failed:",S),S}let x=await xN(_,d);return{status:_.status,headers:W8(_.headers),body:x}}};function Z8(e,t){if(K8(e))return{body:void 0,extraHeaders:{},isStream:!1};if(G8(e)){let a=new TN.PassThrough;return e.on("error",n=>a.destroy(n)),e.pipe(a),{body:a,extraHeaders:e.getHeaders(),isStream:!0}}return typeof e=="string"||Buffer.isBuffer(e)||e instanceof URLSearchParams||e instanceof ArrayBuffer||typeof FormData<"u"&&e instanceof FormData||typeof Blob<"u"&&e instanceof Blob?{body:e,extraHeaders:{},isStream:!1}:(t["Content-Type"]??t["content-type"]??"").includes("application/x-www-form-urlencoded")?{body:new URLSearchParams(e).toString(),extraHeaders:{},isStream:!1}:{body:JSON.stringify(e),extraHeaders:{},isStream:!1}}s(Z8,"serializeBody");async function xN(e,t){switch(t){case"arraybuffer":return Buffer.from(await e.arrayBuffer());case"blob":return await e.blob();case"text":return await e.text();default:{let o=await e.text();if(o.length===0)return;try{return JSON.parse(o)}catch{return o}}}}s(xN,"parseResponseBody");async function H8(e,t){let o;for(let a=0;a<=t;a++)try{let n=await e();if(n.status>=500&&a<t){await wN(a);continue}return n}catch(n){if(o=n,a<t){await wN(a);continue}throw n}throw o}s(H8,"sendWithRetries");function wN(e){let t=Math.min(1e3*2**e,3e4);return new Promise(o=>setTimeout(o,t))}s(wN,"backoff");function J8(e){let t={};for(let[o,a]of Object.entries(e))a!==void 0&&(t[o.toLowerCase()]=Array.isArray(a)?a.join(", "):a);return t}s(J8,"normalizeHeaders");function W8(e){let t={};return e.forEach((o,a)=>{t[a]=o}),t}s(W8,"toHttpHeaders");function G8(e){return typeof e=="object"&&e!==null&&typeof e.getHeaders=="function"&&typeof e.pipe=="function"&&typeof e.on=="function"}s(G8,"isNodeFormData");function K8(e){return e==null}s(K8,"isNil");var sa=new ry;var Vr=s(({modelType:e,allowedProviders:t})=>({provider:Te.Dropdown({auth:_o.None(),displayName:"Provider",required:!0,refreshers:[],options:s(async(o,a)=>{let{body:n}=await sa.sendRequest({method:"GET",url:`${a.server.apiUrl}v1/ai-providers`,headers:{Authorization:`Bearer ${a.server.token}`}});return{placeholder:"Select AI Provider",disabled:!1,options:n.map(i=>({label:i.name,value:i.provider})).filter(i=>t?t.includes(i.value):!0)}},"options")}),model:Te.Dropdown({auth:_o.None(),displayName:"Model",required:!0,refreshers:["provider"],options:s(async(o,a)=>{let n=o.provider;if(Ft(n))return{disabled:!0,options:[],placeholder:"Select AI Provider"};let{body:i}=await sa.sendRequest({method:"GET",url:`${a.server.apiUrl}v1/ai-providers/${n}/models`,headers:{Authorization:`Bearer ${a.server.token}`}});return{placeholder:"Select AI Model",disabled:!1,options:i.filter(l=>l.type===e).map(l=>({label:l.name,value:l.id}))}},"options")})}),"aiProps");var X8="3.0.72",Y8=N(()=>$(r.object({type:r.literal("error"),error:r.object({type:r.string(),message:r.string()})}))),SN=bt({errorSchema:Y8,errorToMessage:s(e=>e.error.message,"errorToMessage")}),Q8=N(()=>$(r.object({type:r.literal("message"),id:r.string().nullish(),model:r.string().nullish(),content:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("text"),text:r.string(),citations:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("web_search_result_location"),cited_text:r.string(),url:r.string(),title:r.string(),encrypted_index:r.string()}),r.object({type:r.literal("page_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_page_number:r.number(),end_page_number:r.number()}),r.object({type:r.literal("char_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_char_index:r.number(),end_char_index:r.number()})])).optional()}),r.object({type:r.literal("thinking"),thinking:r.string(),signature:r.string()}),r.object({type:r.literal("redacted_thinking"),data:r.string()}),r.object({type:r.literal("compaction"),content:r.string()}),r.object({type:r.literal("tool_use"),id:r.string(),name:r.string(),input:r.unknown(),caller:r.union([r.object({type:r.literal("code_execution_20250825"),tool_id:r.string()}),r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("server_tool_use"),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish(),caller:r.union([r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("mcp_tool_use"),id:r.string(),name:r.string(),input:r.unknown(),server_name:r.string()}),r.object({type:r.literal("mcp_tool_result"),tool_use_id:r.string(),is_error:r.boolean(),content:r.array(r.union([r.string(),r.object({type:r.literal("text"),text:r.string()})]))}),r.object({type:r.literal("web_fetch_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("web_fetch_result"),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),media_type:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),media_type:r.literal("text/plain"),data:r.string()})])})}),r.object({type:r.literal("web_fetch_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("web_search_tool_result"),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal("web_search_result"),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal("web_search_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("code_execution_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("encrypted_code_execution_result"),encrypted_stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("bash_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("text_editor_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})])}),r.object({type:r.literal("tool_search_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("tool_search_tool_search_result"),tool_references:r.array(r.object({type:r.literal("tool_reference"),tool_name:r.string()}))}),r.object({type:r.literal("tool_search_tool_result_error"),error_code:r.string()})])})])),stop_reason:r.string().nullish(),stop_sequence:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish(),iterations:r.array(r.object({type:r.union([r.literal("compaction"),r.literal("message")]),input_tokens:r.number(),output_tokens:r.number()})).nullish()}),container:r.object({expires_at:r.string(),id:r.string(),skills:r.array(r.object({type:r.union([r.literal("anthropic"),r.literal("custom")]),skill_id:r.string(),version:r.string()})).nullish()}).nullish(),context_management:r.object({applied_edits:r.array(r.union([r.object({type:r.literal("clear_tool_uses_20250919"),cleared_tool_uses:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("clear_thinking_20251015"),cleared_thinking_turns:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("compact_20260112")})]))}).nullish()}))),e7=N(()=>$(r.discriminatedUnion("type",[r.object({type:r.literal("message_start"),message:r.object({id:r.string().nullish(),model:r.string().nullish(),role:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()}),content:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("tool_use"),id:r.string(),name:r.string(),input:r.unknown(),caller:r.union([r.object({type:r.literal("code_execution_20250825"),tool_id:r.string()}),r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()})])).nullish(),stop_reason:r.string().nullish(),container:r.object({expires_at:r.string(),id:r.string()}).nullish()})}),r.object({type:r.literal("content_block_start"),index:r.number(),content_block:r.discriminatedUnion("type",[r.object({type:r.literal("text"),text:r.string()}),r.object({type:r.literal("thinking"),thinking:r.string()}),r.object({type:r.literal("tool_use"),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).optional(),caller:r.union([r.object({type:r.literal("code_execution_20250825"),tool_id:r.string()}),r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("redacted_thinking"),data:r.string()}),r.object({type:r.literal("compaction"),content:r.string().nullish()}),r.object({type:r.literal("server_tool_use"),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish(),caller:r.union([r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("mcp_tool_use"),id:r.string(),name:r.string(),input:r.unknown(),server_name:r.string()}),r.object({type:r.literal("mcp_tool_result"),tool_use_id:r.string(),is_error:r.boolean(),content:r.array(r.union([r.string(),r.object({type:r.literal("text"),text:r.string()})]))}),r.object({type:r.literal("web_fetch_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("web_fetch_result"),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),media_type:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),media_type:r.literal("text/plain"),data:r.string()})])})}),r.object({type:r.literal("web_fetch_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("web_search_tool_result"),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal("web_search_result"),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal("web_search_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("code_execution_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("encrypted_code_execution_result"),encrypted_stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("bash_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("text_editor_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})])}),r.object({type:r.literal("tool_search_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("tool_search_tool_search_result"),tool_references:r.array(r.object({type:r.literal("tool_reference"),tool_name:r.string()}))}),r.object({type:r.literal("tool_search_tool_result_error"),error_code:r.string()})])})])}),r.object({type:r.literal("content_block_delta"),index:r.number(),delta:r.discriminatedUnion("type",[r.object({type:r.literal("input_json_delta"),partial_json:r.string()}),r.object({type:r.literal("text_delta"),text:r.string()}),r.object({type:r.literal("thinking_delta"),thinking:r.string()}),r.object({type:r.literal("signature_delta"),signature:r.string()}),r.object({type:r.literal("compaction_delta"),content:r.string().nullish()}),r.object({type:r.literal("citations_delta"),citation:r.discriminatedUnion("type",[r.object({type:r.literal("web_search_result_location"),cited_text:r.string(),url:r.string(),title:r.string(),encrypted_index:r.string()}),r.object({type:r.literal("page_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_page_number:r.number(),end_page_number:r.number()}),r.object({type:r.literal("char_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_char_index:r.number(),end_char_index:r.number()})])})])}),r.object({type:r.literal("content_block_stop"),index:r.number()}),r.object({type:r.literal("error"),error:r.object({type:r.string(),message:r.string()})}),r.object({type:r.literal("message_delta"),delta:r.object({stop_reason:r.string().nullish(),stop_sequence:r.string().nullish(),container:r.object({expires_at:r.string(),id:r.string(),skills:r.array(r.object({type:r.union([r.literal("anthropic"),r.literal("custom")]),skill_id:r.string(),version:r.string()})).nullish()}).nullish()}),usage:r.looseObject({input_tokens:r.number().nullish(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish(),iterations:r.array(r.object({type:r.union([r.literal("compaction"),r.literal("message")]),input_tokens:r.number(),output_tokens:r.number()})).nullish()}),context_management:r.object({applied_edits:r.array(r.union([r.object({type:r.literal("clear_tool_uses_20250919"),cleared_tool_uses:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("clear_thinking_20251015"),cleared_thinking_turns:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("compact_20260112")})]))}).nullish()}),r.object({type:r.literal("message_stop")}),r.object({type:r.literal("ping")})]))),t7=N(()=>$(r.object({signature:r.string().optional(),redactedData:r.string().optional()}))),IN=r.object({citations:r.object({enabled:r.boolean()}).optional(),title:r.string().optional(),context:r.string().optional()}),kN=r.object({sendReasoning:r.boolean().optional(),structuredOutputMode:r.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:r.discriminatedUnion("type",[r.object({type:r.literal("adaptive"),display:r.enum(["omitted","summarized"]).optional()}),r.object({type:r.literal("enabled"),budgetTokens:r.number().optional()}),r.object({type:r.literal("disabled")})]).optional(),disableParallelToolUse:r.boolean().optional(),cacheControl:r.object({type:r.literal("ephemeral"),ttl:r.union([r.literal("5m"),r.literal("1h")]).optional()}).optional(),metadata:r.object({userId:r.string().optional()}).optional(),mcpServers:r.array(r.object({type:r.literal("url"),name:r.string(),url:r.string(),authorizationToken:r.string().nullish(),toolConfiguration:r.object({enabled:r.boolean().nullish(),allowedTools:r.array(r.string()).nullish()}).nullish()})).optional(),container:r.object({id:r.string().optional(),skills:r.array(r.object({type:r.union([r.literal("anthropic"),r.literal("custom")]),skillId:r.string(),version:r.string().optional()})).optional()}).optional(),toolStreaming:r.boolean().optional(),effort:r.enum(["low","medium","high","xhigh","max"]).optional(),taskBudget:r.object({type:r.literal("tokens"),total:r.number().int().min(2e4),remaining:r.number().int().min(0).optional()}).optional(),speed:r.enum(["fast","standard"]).optional(),inferenceGeo:r.enum(["us","global"]).optional(),anthropicBeta:r.array(r.string()).optional(),contextManagement:r.object({edits:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("clear_tool_uses_20250919"),trigger:r.discriminatedUnion("type",[r.object({type:r.literal("input_tokens"),value:r.number()}),r.object({type:r.literal("tool_uses"),value:r.number()})]).optional(),keep:r.object({type:r.literal("tool_uses"),value:r.number()}).optional(),clearAtLeast:r.object({type:r.literal("input_tokens"),value:r.number()}).optional(),clearToolInputs:r.boolean().optional(),excludeTools:r.array(r.string()).optional()}),r.object({type:r.literal("clear_thinking_20251015"),keep:r.union([r.literal("all"),r.object({type:r.literal("thinking_turns"),value:r.number()})]).optional()}),r.object({type:r.literal("compact_20260112"),trigger:r.object({type:r.literal("input_tokens"),value:r.number()}).optional(),pauseAfterCompaction:r.boolean().optional(),instructions:r.string().optional()})]))}).optional()}),PN=4;function r7(e){var t;let o=e?.anthropic;return(t=o?.cacheControl)!=null?t:o?.cache_control}s(r7,"getCacheControl");var mT=class{static{s(this,"CacheControlValidator")}constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let o=r7(e);if(o){if(!t.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${t.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>PN){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${PN} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return o}}getWarnings(){return this.warnings}},o7=N(()=>$(r.object({maxCharacters:r.number().optional()}))),n7=N(()=>$(r.object({command:r.enum(["view","create","str_replace","insert"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),a7=yt({id:"anthropic.text_editor_20250728",inputSchema:n7}),i7=s((e={})=>a7(e),"textEditor_20250728"),s7=N(()=>$(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),userLocation:r.object({type:r.literal("approximate"),city:r.string().optional(),region:r.string().optional(),country:r.string().optional(),timezone:r.string().optional()}).optional()}))),l7=N(()=>$(r.array(r.object({url:r.string(),title:r.string().nullable(),pageAge:r.string().nullable(),encryptedContent:r.string(),type:r.literal("web_search_result")})))),u7=N(()=>$(r.object({query:r.string()}))),c7=Pe({id:"anthropic.web_search_20260209",inputSchema:u7,outputSchema:l7,supportsDeferredResults:!0}),d7=s((e={})=>c7(e),"webSearch_20260209"),p7=N(()=>$(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),userLocation:r.object({type:r.literal("approximate"),city:r.string().optional(),region:r.string().optional(),country:r.string().optional(),timezone:r.string().optional()}).optional()}))),$N=N(()=>$(r.array(r.object({url:r.string(),title:r.string().nullable(),pageAge:r.string().nullable(),encryptedContent:r.string(),type:r.literal("web_search_result")})))),m7=N(()=>$(r.object({query:r.string()}))),f7=Pe({id:"anthropic.web_search_20250305",inputSchema:m7,outputSchema:$N,supportsDeferredResults:!0}),h7=s((e={})=>f7(e),"webSearch_20250305"),g7=N(()=>$(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),citations:r.object({enabled:r.boolean()}).optional(),maxContentTokens:r.number().optional()}))),y7=N(()=>$(r.object({type:r.literal("web_fetch_result"),url:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),mediaType:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),mediaType:r.literal("text/plain"),data:r.string()})])}),retrievedAt:r.string().nullable()}))),_7=N(()=>$(r.object({url:r.string()}))),v7=Pe({id:"anthropic.web_fetch_20260209",inputSchema:_7,outputSchema:y7,supportsDeferredResults:!0}),b7=s((e={})=>v7(e),"webFetch_20260209"),x7=N(()=>$(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),citations:r.object({enabled:r.boolean()}).optional(),maxContentTokens:r.number().optional()}))),RN=N(()=>$(r.object({type:r.literal("web_fetch_result"),url:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),mediaType:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),mediaType:r.literal("text/plain"),data:r.string()})])}),retrievedAt:r.string().nullable()}))),w7=N(()=>$(r.object({url:r.string()}))),T7=Pe({id:"anthropic.web_fetch_20250910",inputSchema:w7,outputSchema:RN,supportsDeferredResults:!0}),S7=s((e={})=>T7(e),"webFetch_20250910");async function I7({tools:e,toolChoice:t,disableParallelToolUse:o,cacheControlValidator:a,supportsStructuredOutput:n,supportsStrictTools:i,defaultEagerInputStreaming:l=!1}){var u,c;e=e?.length?e:void 0;let d=[],p=new Set,m=a||new mT;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:d,betas:p};let f=[];for(let g of e)switch(g.type){case"function":{let y=m.getCacheControl(g.providerOptions,{type:"tool definition",canCache:!0}),_=(u=g.providerOptions)==null?void 0:u.anthropic,v=(c=_?.eagerInputStreaming)!=null?c:l,x=_?.deferLoading,w=_?.allowedCallers;!i&&g.strict!=null&&d.push({type:"unsupported",feature:"strict",details:`Tool '${g.name}' has strict: ${g.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),f.push({name:g.name,description:g.description,input_schema:g.inputSchema,cache_control:y,...v?{eager_input_streaming:!0}:{},...i===!0&&g.strict!=null?{strict:g.strict}:{},...x!=null?{defer_loading:x}:{},...w!=null?{allowed_callers:w}:{},...g.inputExamples!=null?{input_examples:g.inputExamples.map(S=>S.input)}:{}}),n===!0&&p.add("structured-outputs-2025-11-13"),(g.inputExamples!=null||w!=null)&&p.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(g.id){case"anthropic.code_execution_20250522":{p.add("code-execution-2025-05-22"),f.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{p.add("code-execution-2025-08-25"),f.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{f.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{p.add("computer-use-2025-01-24"),f.push({name:"computer",type:"computer_20250124",display_width_px:g.args.displayWidthPx,display_height_px:g.args.displayHeightPx,display_number:g.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20251124":{p.add("computer-use-2025-11-24"),f.push({name:"computer",type:"computer_20251124",display_width_px:g.args.displayWidthPx,display_height_px:g.args.displayHeightPx,display_number:g.args.displayNumber,enable_zoom:g.args.enableZoom,cache_control:void 0});break}case"anthropic.computer_20241022":{p.add("computer-use-2024-10-22"),f.push({name:"computer",type:"computer_20241022",display_width_px:g.args.displayWidthPx,display_height_px:g.args.displayHeightPx,display_number:g.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{p.add("computer-use-2025-01-24"),f.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{p.add("computer-use-2024-10-22"),f.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{p.add("computer-use-2025-01-24"),f.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let y=await $e({value:g.args,schema:o7});f.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:y.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{p.add("computer-use-2025-01-24"),f.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{p.add("computer-use-2024-10-22"),f.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{p.add("context-management-2025-06-27"),f.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{p.add("web-fetch-2025-09-10");let y=await $e({value:g.args,schema:x7});f.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:y.maxUses,allowed_domains:y.allowedDomains,blocked_domains:y.blockedDomains,citations:y.citations,max_content_tokens:y.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{p.add("code-execution-web-tools-2026-02-09");let y=await $e({value:g.args,schema:g7});f.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:y.maxUses,allowed_domains:y.allowedDomains,blocked_domains:y.blockedDomains,citations:y.citations,max_content_tokens:y.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let y=await $e({value:g.args,schema:p7});f.push({type:"web_search_20250305",name:"web_search",max_uses:y.maxUses,allowed_domains:y.allowedDomains,blocked_domains:y.blockedDomains,user_location:y.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{p.add("code-execution-web-tools-2026-02-09");let y=await $e({value:g.args,schema:s7});f.push({type:"web_search_20260209",name:"web_search",max_uses:y.maxUses,allowed_domains:y.allowedDomains,blocked_domains:y.blockedDomains,user_location:y.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{f.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{f.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}default:{d.push({type:"unsupported",feature:`provider-defined tool ${g.id}`});break}}break}default:{d.push({type:"unsupported",feature:`tool ${g}`});break}}if(t==null)return{tools:f,toolChoice:o?{type:"auto",disable_parallel_tool_use:o}:void 0,toolWarnings:d,betas:p};let h=t.type;switch(h){case"auto":return{tools:f,toolChoice:{type:"auto",disable_parallel_tool_use:o},toolWarnings:d,betas:p};case"required":return{tools:f,toolChoice:{type:"any",disable_parallel_tool_use:o},toolWarnings:d,betas:p};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:d,betas:p};case"tool":return{tools:f,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:o},toolWarnings:d,betas:p};default:{let g=h;throw new Le({functionality:`tool choice type: ${g}`})}}}s(I7,"prepareTools");function EN({usage:e,rawUsage:t}){var o,a;let n=(o=e.cache_creation_input_tokens)!=null?o:0,i=(a=e.cache_read_input_tokens)!=null?a:0,l,u;if(e.iterations&&e.iterations.length>0){let c=e.iterations.reduce((d,p)=>({input:d.input+p.input_tokens,output:d.output+p.output_tokens}),{input:0,output:0});l=c.input,u=c.output}else l=e.input_tokens,u=e.output_tokens;return{inputTokens:{total:l+n+i,noCache:l,cacheRead:i,cacheWrite:n},outputTokens:{total:u,text:void 0,reasoning:void 0},raw:t??e}}s(EN,"convertAnthropicMessagesUsage");var zN=N(()=>$(r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}))),k7=N(()=>$(r.object({code:r.string()}))),P7=Pe({id:"anthropic.code_execution_20250522",inputSchema:k7,outputSchema:zN}),E7=s((e={})=>P7(e),"codeExecution_20250522"),NN=N(()=>$(r.discriminatedUnion("type",[r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})]))),A7=N(()=>$(r.discriminatedUnion("type",[r.object({type:r.literal("programmatic-tool-call"),code:r.string()}),r.object({type:r.literal("bash_code_execution"),command:r.string()}),r.discriminatedUnion("command",[r.object({type:r.literal("text_editor_code_execution"),command:r.literal("view"),path:r.string()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("create"),path:r.string(),file_text:r.string().nullish()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("str_replace"),path:r.string(),old_str:r.string(),new_str:r.string()})])]))),C7=Pe({id:"anthropic.code_execution_20250825",inputSchema:A7,outputSchema:NN,supportsDeferredResults:!0}),O7=s((e={})=>C7(e),"codeExecution_20250825"),jN=N(()=>$(r.discriminatedUnion("type",[r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("encrypted_code_execution_result"),encrypted_stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})]))),$7=N(()=>$(r.discriminatedUnion("type",[r.object({type:r.literal("programmatic-tool-call"),code:r.string()}),r.object({type:r.literal("bash_code_execution"),command:r.string()}),r.discriminatedUnion("command",[r.object({type:r.literal("text_editor_code_execution"),command:r.literal("view"),path:r.string()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("create"),path:r.string(),file_text:r.string().nullish()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("str_replace"),path:r.string(),old_str:r.string(),new_str:r.string()})])]))),R7=Pe({id:"anthropic.code_execution_20260120",inputSchema:$7,outputSchema:jN,supportsDeferredResults:!0}),z7=s((e={})=>R7(e),"codeExecution_20260120"),MN=N(()=>$(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),N7=N(()=>$(r.object({pattern:r.string(),limit:r.number().optional()}))),j7=Pe({id:"anthropic.tool_search_regex_20251119",inputSchema:N7,outputSchema:MN,supportsDeferredResults:!0}),M7=s((e={})=>j7(e),"toolSearchRegex_20251119");function D7(e){if(typeof e=="string")return new TextDecoder().decode(Yt(e));if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new Le({functionality:"URL-based text documents are not supported for citations"}):new Le({functionality:`unsupported data type for text documents: ${typeof e}`})}s(D7,"convertToString");function cT(e){return e instanceof URL||U7(e)}s(cT,"isUrlData");function U7(e){return typeof e=="string"&&/^https?:\/\//i.test(e)}s(U7,"isUrlString");function dT(e){return e instanceof URL?e.toString():e}s(dT,"getUrlString");async function L7({prompt:e,sendReasoning:t,warnings:o,cacheControlValidator:a,toolNameMapping:n}){var i,l,u,c,d,p,m,f,h,g,y,_,v,x,w,S,P,k,I;let E=new Set,b=q7(e),M=a||new mT,R,D=[];async function te(J){var W,j;let O=await Re({provider:"anthropic",providerOptions:J,schema:IN});return(j=(W=O?.citations)==null?void 0:W.enabled)!=null?j:!1}s(te,"shouldEnableCitations");async function ee(J){let W=await Re({provider:"anthropic",providerOptions:J,schema:IN});return{title:W?.title,context:W?.context}}s(ee,"getDocumentMetadata");for(let J=0;J<b.length;J++){let W=b[J],j=J===b.length-1,O=W.type;switch(O){case"system":{if(R!=null)throw new Le({functionality:"Multiple system messages that are separated by user/assistant messages"});R=W.messages.map(({content:Z,providerOptions:F})=>({type:"text",text:Z,cache_control:M.getCacheControl(F,{type:"system message",canCache:!0})}));break}case"user":{let Z=[];for(let F of W.messages){let{role:z,content:Y}=F;switch(z){case"user":{for(let ae=0;ae<Y.length;ae++){let K=Y[ae],he=ae===Y.length-1,L=(i=M.getCacheControl(K.providerOptions,{type:"user message part",canCache:!0}))!=null?i:he?M.getCacheControl(F.providerOptions,{type:"user message",canCache:!0}):void 0;switch(K.type){case"text":{Z.push({type:"text",text:K.text,cache_control:L});break}case"file":{if(K.mediaType.startsWith("image/"))Z.push({type:"image",source:cT(K.data)?{type:"url",url:dT(K.data)}:{type:"base64",media_type:K.mediaType==="image/*"?"image/jpeg":K.mediaType,data:Zt(K.data)},cache_control:L});else if(K.mediaType==="application/pdf"){E.add("pdfs-2024-09-25");let le=await te(K.providerOptions),oe=await ee(K.providerOptions);Z.push({type:"document",source:cT(K.data)?{type:"url",url:dT(K.data)}:{type:"base64",media_type:"application/pdf",data:Zt(K.data)},title:(l=oe.title)!=null?l:K.filename,...oe.context&&{context:oe.context},...le&&{citations:{enabled:!0}},cache_control:L})}else if(K.mediaType==="text/plain"){let le=await te(K.providerOptions),oe=await ee(K.providerOptions);Z.push({type:"document",source:cT(K.data)?{type:"url",url:dT(K.data)}:{type:"text",media_type:"text/plain",data:D7(K.data)},title:(u=oe.title)!=null?u:K.filename,...oe.context&&{context:oe.context},...le&&{citations:{enabled:!0}},cache_control:L})}else throw new Le({functionality:`media type: ${K.mediaType}`});break}}}break}case"tool":{for(let ae=0;ae<Y.length;ae++){let K=Y[ae];if(K.type==="tool-approval-response")continue;let he=ae===Y.length-1,L=(c=M.getCacheControl(K.providerOptions,{type:"tool result part",canCache:!0}))!=null?c:he?M.getCacheControl(F.providerOptions,{type:"tool result message",canCache:!0}):void 0,le=K.output,oe;switch(le.type){case"content":oe=le.value.map(ne=>{var C;switch(ne.type){case"text":return{type:"text",text:ne.text};case"image-data":return{type:"image",source:{type:"base64",media_type:ne.mediaType,data:ne.data}};case"image-url":return{type:"image",source:{type:"url",url:ne.url}};case"file-url":return{type:"document",source:{type:"url",url:ne.url}};case"file-data":{if(ne.mediaType==="application/pdf")return E.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:ne.mediaType,data:ne.data}};o.push({type:"other",message:`unsupported tool content part type: ${ne.type} with media type: ${ne.mediaType}`});return}case"custom":{let G=(C=ne.providerOptions)==null?void 0:C.anthropic;if(G?.type==="tool-reference")return{type:"tool_reference",tool_name:G.toolName};o.push({type:"other",message:"unsupported custom tool content part"});return}default:{o.push({type:"other",message:`unsupported tool content part type: ${ne.type}`});return}}}).filter(_i);break;case"text":case"error-text":oe=le.value;break;case"execution-denied":oe=(d=le.reason)!=null?d:"Tool execution denied.";break;default:oe=JSON.stringify(le.value);break}Z.push({type:"tool_result",tool_use_id:K.toolCallId,content:oe,is_error:le.type==="error-text"||le.type==="error-json"?!0:void 0,cache_control:L})}break}default:{let ae=z;throw new Error(`Unsupported role: ${ae}`)}}}D.push({role:"user",content:Z});break}case"assistant":{let Z=[],F=new Set;for(let z=0;z<W.messages.length;z++){let Y=W.messages[z],ae=z===W.messages.length-1,{content:K}=Y;for(let he=0;he<K.length;he++){let L=K[he],le=he===K.length-1,oe=(p=M.getCacheControl(L.providerOptions,{type:"assistant message part",canCache:!0}))!=null?p:le?M.getCacheControl(Y.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(L.type){case"text":{let ne=(m=L.providerOptions)==null?void 0:m.anthropic;ne?.type==="compaction"?Z.push({type:"compaction",content:L.text,cache_control:oe}):Z.push({type:"text",text:j&&ae&&le?L.text.trim():L.text,cache_control:oe});break}case"reasoning":{if(t){let ne=await Re({provider:"anthropic",providerOptions:L.providerOptions,schema:t7});ne!=null?ne.signature!=null?(M.getCacheControl(L.providerOptions,{type:"thinking block",canCache:!1}),Z.push({type:"thinking",thinking:L.text,signature:ne.signature})):ne.redactedData!=null?(M.getCacheControl(L.providerOptions,{type:"redacted thinking block",canCache:!1}),Z.push({type:"redacted_thinking",data:ne.redactedData})):o.push({type:"other",message:"unsupported reasoning metadata"}):o.push({type:"other",message:"unsupported reasoning metadata"})}else o.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(L.providerExecuted){let G=n.toProviderToolName(L.toolName);if(((h=(f=L.providerOptions)==null?void 0:f.anthropic)==null?void 0:h.type)==="mcp-tool-use"){F.add(L.toolCallId);let q=(y=(g=L.providerOptions)==null?void 0:g.anthropic)==null?void 0:y.serverName;if(q==null||typeof q!="string"){o.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}Z.push({type:"mcp_tool_use",id:L.toolCallId,name:L.toolName,input:L.input,server_name:q,cache_control:oe})}else if(G==="code_execution"&&L.input!=null&&typeof L.input=="object"&&"type"in L.input&&typeof L.input.type=="string"&&(L.input.type==="bash_code_execution"||L.input.type==="text_editor_code_execution"))Z.push({type:"server_tool_use",id:L.toolCallId,name:L.input.type,input:L.input,cache_control:oe});else if(G==="code_execution"&&L.input!=null&&typeof L.input=="object"&&"type"in L.input&&L.input.type==="programmatic-tool-call"){let{type:q,...Me}=L.input;Z.push({type:"server_tool_use",id:L.toolCallId,name:"code_execution",input:Me,cache_control:oe})}else G==="code_execution"||G==="web_fetch"||G==="web_search"?Z.push({type:"server_tool_use",id:L.toolCallId,name:G,input:L.input,cache_control:oe}):G==="tool_search_tool_regex"||G==="tool_search_tool_bm25"?Z.push({type:"server_tool_use",id:L.toolCallId,name:G,input:L.input,cache_control:oe}):o.push({type:"other",message:`provider executed tool call for tool ${L.toolName} is not supported`});break}let ne=(_=L.providerOptions)==null?void 0:_.anthropic,C=ne?.caller?(ne.caller.type==="code_execution_20250825"||ne.caller.type==="code_execution_20260120")&&ne.caller.toolId?{type:ne.caller.type,tool_id:ne.caller.toolId}:ne.caller.type==="direct"?{type:"direct"}:void 0:void 0;Z.push({type:"tool_use",id:L.toolCallId,name:L.toolName,input:L.input,...C&&{caller:C},cache_control:oe});break}case"tool-result":{let ne=n.toProviderToolName(L.toolName);if(F.has(L.toolCallId)){let C=L.output;if(C.type!=="json"&&C.type!=="error-json"){o.push({type:"other",message:`provider executed tool result output type ${C.type} for tool ${L.toolName} is not supported`});break}Z.push({type:"mcp_tool_result",tool_use_id:L.toolCallId,is_error:C.type==="error-json",content:C.value,cache_control:oe})}else if(ne==="code_execution"){let C=L.output;if(C.type==="error-text"||C.type==="error-json"){let G={};try{typeof C.value=="string"?G=JSON.parse(C.value):typeof C.value=="object"&&C.value!==null&&(G=C.value)}catch{}G.type==="code_execution_tool_result_error"?Z.push({type:"code_execution_tool_result",tool_use_id:L.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(v=G.errorCode)!=null?v:"unknown"},cache_control:oe}):Z.push({type:"bash_code_execution_tool_result",tool_use_id:L.toolCallId,cache_control:oe,content:{type:"bash_code_execution_tool_result_error",error_code:(x=G.errorCode)!=null?x:"unknown"}});break}if(C.type!=="json"){o.push({type:"other",message:`provider executed tool result output type ${C.type} for tool ${L.toolName} is not supported`});break}if(C.value==null||typeof C.value!="object"||!("type"in C.value)||typeof C.value.type!="string"){o.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${L.toolName}`});break}if(C.value.type==="code_execution_result"){let G=await $e({value:C.value,schema:zN});Z.push({type:"code_execution_tool_result",tool_use_id:L.toolCallId,content:{type:G.type,stdout:G.stdout,stderr:G.stderr,return_code:G.return_code,content:(w=G.content)!=null?w:[]},cache_control:oe})}else if(C.value.type==="encrypted_code_execution_result"){let G=await $e({value:C.value,schema:jN});G.type==="encrypted_code_execution_result"&&Z.push({type:"code_execution_tool_result",tool_use_id:L.toolCallId,content:{type:G.type,encrypted_stdout:G.encrypted_stdout,stderr:G.stderr,return_code:G.return_code,content:(S=G.content)!=null?S:[]},cache_control:oe})}else{let G=await $e({value:C.value,schema:NN});G.type==="code_execution_result"?Z.push({type:"code_execution_tool_result",tool_use_id:L.toolCallId,content:{type:G.type,stdout:G.stdout,stderr:G.stderr,return_code:G.return_code,content:(P=G.content)!=null?P:[]},cache_control:oe}):G.type==="bash_code_execution_result"||G.type==="bash_code_execution_tool_result_error"?Z.push({type:"bash_code_execution_tool_result",tool_use_id:L.toolCallId,cache_control:oe,content:G}):Z.push({type:"text_editor_code_execution_tool_result",tool_use_id:L.toolCallId,cache_control:oe,content:G})}break}if(ne==="web_fetch"){let C=L.output;if(C.type==="error-json"){let X={};try{typeof C.value=="string"?X=JSON.parse(C.value):typeof C.value=="object"&&C.value!==null&&(X=C.value)}catch{let Me=(k=C.value)==null?void 0:k.errorCode;X={errorCode:typeof Me=="string"?Me:"unavailable"}}Z.push({type:"web_fetch_tool_result",tool_use_id:L.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(I=X.errorCode)!=null?I:"unavailable"},cache_control:oe});break}if(C.type!=="json"){o.push({type:"other",message:`provider executed tool result output type ${C.type} for tool ${L.toolName} is not supported`});break}let G=await $e({value:C.value,schema:RN});Z.push({type:"web_fetch_tool_result",tool_use_id:L.toolCallId,content:{type:"web_fetch_result",url:G.url,retrieved_at:G.retrievedAt,content:{type:"document",title:G.content.title,citations:G.content.citations,source:{type:G.content.source.type,media_type:G.content.source.mediaType,data:G.content.source.data}}},cache_control:oe});break}if(ne==="web_search"){let C=L.output;if(C.type!=="json"){o.push({type:"other",message:`provider executed tool result output type ${C.type} for tool ${L.toolName} is not supported`});break}let G=await $e({value:C.value,schema:$N});Z.push({type:"web_search_tool_result",tool_use_id:L.toolCallId,content:G.map(X=>({url:X.url,title:X.title,page_age:X.pageAge,encrypted_content:X.encryptedContent,type:X.type})),cache_control:oe});break}if(ne==="tool_search_tool_regex"||ne==="tool_search_tool_bm25"){let C=L.output;if(C.type!=="json"){o.push({type:"other",message:`provider executed tool result output type ${C.type} for tool ${L.toolName} is not supported`});break}let X=(await $e({value:C.value,schema:MN})).map(q=>({type:"tool_reference",tool_name:q.toolName}));Z.push({type:"tool_search_tool_result",tool_use_id:L.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:X},cache_control:oe});break}o.push({type:"other",message:`provider executed tool result for tool ${L.toolName} is not supported`});break}}}}D.push({role:"assistant",content:Z});break}default:{let Z=O;throw new Error(`content type: ${Z}`)}}}return{prompt:{system:R,messages:D},betas:E}}s(L7,"convertToAnthropicMessagesPrompt");function q7(e){let t=[],o;for(let a of e){let{role:n}=a;switch(n){case"system":{o?.type!=="system"&&(o={type:"system",messages:[]},t.push(o)),o.messages.push(a);break}case"assistant":{o?.type!=="assistant"&&(o={type:"assistant",messages:[]},t.push(o)),o.messages.push(a);break}case"user":{o?.type!=="user"&&(o={type:"user",messages:[]},t.push(o)),o.messages.push(a);break}case"tool":{o?.type!=="user"&&(o={type:"user",messages:[]},t.push(o)),o.messages.push(a);break}default:{let i=n;throw new Error(`Unsupported role: ${i}`)}}}return t}s(q7,"groupIntoBlocks");function pT({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}s(pT,"mapAnthropicStopReason");function AN(e,t,o){var a;if(e.type==="web_search_result_location")return{type:"source",sourceType:"url",id:o(),url:e.url,title:e.title,providerMetadata:{anthropic:{citedText:e.cited_text,encryptedIndex:e.encrypted_index}}};if(e.type!=="page_location"&&e.type!=="char_location")return;let n=t[e.document_index];if(n)return{type:"source",sourceType:"document",id:o(),mediaType:n.mediaType,title:(a=e.document_title)!=null?a:n.title,filename:n.filename,providerMetadata:{anthropic:e.type==="page_location"?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index}}}}s(AN,"createCitationSource");var F7=class{static{s(this,"AnthropicMessagesLanguageModel")}constructor(e,t){this.specificationVersion="v3";var o;this.modelId=e,this.config=t,this.generateId=(o=t.generateId)!=null?o:Fe}supportsUrl(e){return e.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let e=this.config.provider,t=e.indexOf(".");return t===-1?e:e.substring(0,t)}get supportedUrls(){var e,t,o;return(o=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?o:{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:o,temperature:a,topP:n,topK:i,frequencyPenalty:l,presencePenalty:u,stopSequences:c,responseFormat:d,seed:p,tools:m,toolChoice:f,providerOptions:h,stream:g}){var y,_,v,x,w,S,P,k,I,E;let b=[];l!=null&&b.push({type:"unsupported",feature:"frequencyPenalty"}),u!=null&&b.push({type:"unsupported",feature:"presencePenalty"}),p!=null&&b.push({type:"unsupported",feature:"seed"}),a!=null&&a>1?(b.push({type:"unsupported",feature:"temperature",details:`${a} exceeds anthropic maximum of 1.0. clamped to 1.0`}),a=1):a!=null&&a<0&&(b.push({type:"unsupported",feature:"temperature",details:`${a} is below anthropic minimum of 0. clamped to 0`}),a=0),d?.type==="json"&&d.schema==null&&b.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let M=this.providerOptionsName,R=await Re({provider:"anthropic",providerOptions:h,schema:kN}),D=M!=="anthropic"?await Re({provider:M,providerOptions:h,schema:kN}):null,te=D!=null,ee=Object.assign({},R??{},D??{}),{maxOutputTokens:J,supportsStructuredOutput:W,rejectsSamplingParameters:j,isKnownModel:O}=B7(this.modelId);j&&(a!=null&&(b.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),a=void 0),i!=null&&(b.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),i=void 0),n!=null&&(b.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),n=void 0));let Z=O||this.modelId.startsWith("claude-"),F=((y=this.config.supportsNativeStructuredOutput)!=null?y:!0)&&W,z=((_=this.config.supportsStrictTools)!=null?_:!0)&&W,Y=(v=ee?.structuredOutputMode)!=null?v:"auto",ae=Y==="outputFormat"||Y==="auto"&&F,K=d?.type==="json"&&d.schema!=null&&!ae?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:d.schema}:void 0,he=ee?.contextManagement,L=new mT,le=Zl({tools:m,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:oe,betas:ne}=await L7({prompt:t,sendReasoning:(x=ee?.sendReasoning)!=null?x:!0,warnings:b,cacheControlValidator:L,toolNameMapping:le}),C=(w=ee?.thinking)==null?void 0:w.type,G=C==="enabled"||C==="adaptive",X=C==="enabled"?(S=ee?.thinking)==null?void 0:S.budgetTokens:void 0,q=C==="adaptive"?(P=ee?.thinking)==null?void 0:P.display:void 0,Me=o??J,fe={model:this.modelId,max_tokens:Me,temperature:a,top_k:i,top_p:n,stop_sequences:c,...G&&{thinking:{type:C,...X!=null&&{budget_tokens:X},...q!=null&&{display:q}}},...(ee?.effort||ee?.taskBudget||ae&&d?.type==="json"&&d.schema!=null)&&{output_config:{...ee?.effort&&{effort:ee.effort},...ee?.taskBudget&&{task_budget:{type:ee.taskBudget.type,total:ee.taskBudget.total,...ee.taskBudget.remaining!=null&&{remaining:ee.taskBudget.remaining}}},...ae&&d?.type==="json"&&d.schema!=null&&{format:{type:"json_schema",schema:d.schema}}}},...ee?.speed&&{speed:ee.speed},...ee?.inferenceGeo&&{inference_geo:ee.inferenceGeo},...ee?.cacheControl&&{cache_control:ee.cacheControl},...((k=ee?.metadata)==null?void 0:k.userId)!=null&&{metadata:{user_id:ee.metadata.userId}},...ee?.mcpServers&&ee.mcpServers.length>0&&{mcp_servers:ee.mcpServers.map(De=>({type:De.type,name:De.name,url:De.url,authorization_token:De.authorizationToken,tool_configuration:De.toolConfiguration?{allowed_tools:De.toolConfiguration.allowedTools,enabled:De.toolConfiguration.enabled}:void 0}))},...ee?.container&&{container:ee.container.skills&&ee.container.skills.length>0?{id:ee.container.id,skills:ee.container.skills.map(De=>({type:De.type,skill_id:De.skillId,version:De.version}))}:ee.container.id},system:oe.system,messages:oe.messages,...he&&{context_management:{edits:he.edits.map(De=>{let Wr=De.type;switch(Wr){case"clear_tool_uses_20250919":return{type:De.type,...De.trigger!==void 0&&{trigger:De.trigger},...De.keep!==void 0&&{keep:De.keep},...De.clearAtLeast!==void 0&&{clear_at_least:De.clearAtLeast},...De.clearToolInputs!==void 0&&{clear_tool_inputs:De.clearToolInputs},...De.excludeTools!==void 0&&{exclude_tools:De.excludeTools}};case"clear_thinking_20251015":return{type:De.type,...De.keep!==void 0&&{keep:De.keep}};case"compact_20260112":return{type:De.type,...De.trigger!==void 0&&{trigger:De.trigger},...De.pauseAfterCompaction!==void 0&&{pause_after_compaction:De.pauseAfterCompaction},...De.instructions!==void 0&&{instructions:De.instructions}};default:b.push({type:"other",message:`Unknown context management strategy: ${Wr}`});return}}).filter(De=>De!==void 0)}}};G?(C==="enabled"&&X==null&&(b.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),fe.thinking={type:"enabled",budget_tokens:1024},X=1024),fe.temperature!=null&&(fe.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),i!=null&&(fe.top_k=void 0,b.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),n!=null&&(fe.top_p=void 0,b.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),fe.max_tokens=Me+(X??0)):Z&&n!=null&&a!=null&&(b.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),fe.top_p=void 0),O&&fe.max_tokens>J&&(o!=null&&b.push({type:"unsupported",feature:"maxOutputTokens",details:`${fe.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${J} max output tokens. The max output tokens have been limited to ${J}.`}),fe.max_tokens=J),ee?.mcpServers&&ee.mcpServers.length>0&&ne.add("mcp-client-2025-04-04"),he&&(ne.add("context-management-2025-06-27"),he.edits.some(De=>De.type==="compact_20260112")&&ne.add("compact-2026-01-12")),ee?.container&&ee.container.skills&&ee.container.skills.length>0&&(ne.add("code-execution-2025-08-25"),ne.add("skills-2025-10-02"),ne.add("files-api-2025-04-14"),m?.some(De=>De.type==="provider"&&(De.id==="anthropic.code_execution_20250825"||De.id==="anthropic.code_execution_20260120"))||b.push({type:"other",message:"code execution tool is required when using skills"})),ee?.effort&&ne.add("effort-2025-11-24"),ee?.taskBudget&&ne.add("task-budgets-2026-03-13"),ee?.speed==="fast"&&ne.add("fast-mode-2026-02-01");let at=g&&((I=ee?.toolStreaming)!=null?I:!0),{tools:rr,toolChoice:Tr,toolWarnings:gr,betas:Ho}=await I7(K!=null?{tools:[...m??[],K],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:L,supportsStructuredOutput:!1,supportsStrictTools:z,defaultEagerInputStreaming:at}:{tools:m??[],toolChoice:f,disableParallelToolUse:ee?.disableParallelToolUse,cacheControlValidator:L,supportsStructuredOutput:F,supportsStrictTools:z,defaultEagerInputStreaming:at}),Mr=L.getWarnings();return{args:{...fe,tools:rr,tool_choice:Tr,stream:g===!0?!0:void 0},warnings:[...b,...gr,...Mr],betas:new Set([...ne,...Ho,...e,...(E=ee?.anthropicBeta)!=null?E:[]]),usesJsonResponseTool:K!=null,toolNameMapping:le,providerOptionsName:M,usedCustomProviderKey:te}}async getHeaders({betas:e,headers:t}){return Ie(await st(this.config.headers),t,e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{})}async getBetasFromHeaders(e){var t,o;let n=(t=(await st(this.config.headers))["anthropic-beta"])!=null?t:"",i=(o=e?.["anthropic-beta"])!=null?o:"";return new Set([...n.toLowerCase().split(","),...i.toLowerCase().split(",")].map(l=>l.trim()).filter(l=>l!==""))}buildRequestUrl(e){var t,o,a;return(a=(o=(t=this.config).buildRequestUrl)==null?void 0:o.call(t,this.config.baseURL,e))!=null?a:`${this.config.baseURL}/messages`}transformRequestBody(e,t){var o,a,n;return(n=(a=(o=this.config).transformRequestBody)==null?void 0:a.call(o,e,t))!=null?n:e}extractCitationDocuments(e){let t=s(o=>{var a,n;if(o.type!=="file"||o.mediaType!=="application/pdf"&&o.mediaType!=="text/plain")return!1;let i=(a=o.providerOptions)==null?void 0:a.anthropic,l=i?.citations;return(n=l?.enabled)!=null?n:!1},"isCitationPart");return e.filter(o=>o.role==="user").flatMap(o=>o.content).filter(t).map(o=>{var a;let n=o;return{title:(a=n.filename)!=null?a:"Untitled Document",filename:n.filename,mediaType:n.mediaType}})}async doGenerate(e){var t,o,a,n,i,l,u;let{args:c,warnings:d,betas:p,usesJsonResponseTool:m,toolNameMapping:f,providerOptionsName:h,usedCustomProviderKey:g}=await this.getArgs({...e,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),y=[...this.extractCitationDocuments(e.prompt)],_=CN(c.tools),{responseHeaders:v,value:x,rawValue:w}=await ke({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:p,headers:e.headers}),body:this.transformRequestBody(c,p),failedResponseHandler:SN,successfulResponseHandler:Ce(Q8),abortSignal:e.abortSignal,fetch:this.config.fetch}),S=[],P={},k={},I=!1;for(let E of x.content)switch(E.type){case"text":{if(!m&&(S.push({type:"text",text:E.text}),E.citations))for(let b of E.citations){let M=AN(b,y,this.generateId);M&&S.push(M)}break}case"thinking":{S.push({type:"reasoning",text:E.thinking,providerMetadata:{anthropic:{signature:E.signature}}});break}case"redacted_thinking":{S.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:E.data}}});break}case"compaction":{S.push({type:"text",text:E.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(m&&E.name==="json")I=!0,S.push({type:"text",text:JSON.stringify(E.input)});else{let M=E.caller,R=M?{type:M.type,toolId:"tool_id"in M?M.tool_id:void 0}:void 0;S.push({type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),...R&&{providerMetadata:{anthropic:{caller:R}}}})}break}case"server_tool_use":{if(E.name==="text_editor_code_execution"||E.name==="bash_code_execution")S.push({type:"tool-call",toolCallId:E.id,toolName:f.toCustomToolName("code_execution"),input:JSON.stringify({type:E.name,...E.input}),providerExecuted:!0});else if(E.name==="web_search"||E.name==="code_execution"||E.name==="web_fetch"){let b=E.name==="code_execution"&&E.input!=null&&typeof E.input=="object"&&"code"in E.input&&!("type"in E.input)?{type:"programmatic-tool-call",...E.input}:E.input;S.push({type:"tool-call",toolCallId:E.id,toolName:f.toCustomToolName(E.name),input:JSON.stringify(b),providerExecuted:!0,..._&&E.name==="code_execution"?{dynamic:!0}:{}})}else(E.name==="tool_search_tool_regex"||E.name==="tool_search_tool_bm25")&&(k[E.id]=E.name,S.push({type:"tool-call",toolCallId:E.id,toolName:f.toCustomToolName(E.name),input:JSON.stringify(E.input),providerExecuted:!0}));break}case"mcp_tool_use":{P[E.id]={type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:E.server_name}}},S.push(P[E.id]);break}case"mcp_tool_result":{S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:P[E.tool_use_id].toolName,isError:E.is_error,result:E.content,dynamic:!0,providerMetadata:P[E.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{E.content.type==="web_fetch_result"?(y.push({title:(t=E.content.content.title)!=null?t:E.content.url,mediaType:E.content.content.source.media_type}),S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:E.content.url,retrievedAt:E.content.retrieved_at,content:{type:E.content.content.type,title:E.content.content.title,citations:E.content.content.citations,source:{type:E.content.content.source.type,mediaType:E.content.content.source.media_type,data:E.content.content.source.data}}}})):E.content.type==="web_fetch_tool_result_error"&&S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:E.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(E.content)){S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("web_search"),result:E.content.map(b=>{var M;return{url:b.url,title:b.title,pageAge:(M=b.page_age)!=null?M:null,encryptedContent:b.encrypted_content,type:b.type}})});for(let b of E.content)S.push({type:"source",sourceType:"url",id:this.generateId(),url:b.url,title:b.title,providerMetadata:{anthropic:{pageAge:(o=b.page_age)!=null?o:null}}})}else S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:E.content.error_code}});break}case"code_execution_tool_result":{E.content.type==="code_execution_result"?S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:{type:E.content.type,stdout:E.content.stdout,stderr:E.content.stderr,return_code:E.content.return_code,content:(a=E.content.content)!=null?a:[]}}):E.content.type==="encrypted_code_execution_result"?S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:{type:E.content.type,encrypted_stdout:E.content.encrypted_stdout,stderr:E.content.stderr,return_code:E.content.return_code,content:(n=E.content.content)!=null?n:[]}}):E.content.type==="code_execution_tool_result_error"&&S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:E.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:E.content});break}case"tool_search_tool_result":{let b=k[E.tool_use_id];if(b==null){let M=f.toCustomToolName("tool_search_tool_bm25"),R=f.toCustomToolName("tool_search_tool_regex");M!=="tool_search_tool_bm25"?b="tool_search_tool_bm25":b="tool_search_tool_regex"}E.content.type==="tool_search_tool_search_result"?S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName(b),result:E.content.tool_references.map(M=>({type:M.type,toolName:M.tool_name}))}):S.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:f.toCustomToolName(b),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:E.content.error_code}});break}}return{content:S,finishReason:{unified:pT({finishReason:x.stop_reason,isJsonResponseFromTool:I}),raw:(i=x.stop_reason)!=null?i:void 0},usage:EN({usage:x.usage}),request:{body:c},response:{id:(l=x.id)!=null?l:void 0,modelId:(u=x.model)!=null?u:void 0,headers:v,body:w},warnings:d,providerMetadata:(()=>{var E,b,M,R,D;let te={usage:x.usage,cacheCreationInputTokens:(E=x.usage.cache_creation_input_tokens)!=null?E:null,stopSequence:(b=x.stop_sequence)!=null?b:null,iterations:x.usage.iterations?x.usage.iterations.map(J=>({type:J.type,inputTokens:J.input_tokens,outputTokens:J.output_tokens})):null,container:x.container?{expiresAt:x.container.expires_at,id:x.container.id,skills:(R=(M=x.container.skills)==null?void 0:M.map(J=>({type:J.type,skillId:J.skill_id,version:J.version})))!=null?R:null}:null,contextManagement:(D=ON(x.context_management))!=null?D:null},ee={anthropic:te};return g&&h!=="anthropic"&&(ee[h]=te),ee})()}}async doStream(e){var t,o;let{args:a,warnings:n,betas:i,usesJsonResponseTool:l,toolNameMapping:u,providerOptionsName:c,usedCustomProviderKey:d}=await this.getArgs({...e,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),p=[...this.extractCitationDocuments(e.prompt)],m=CN(a.tools),f=this.buildRequestUrl(!0),{responseHeaders:h,value:g}=await ke({url:f,headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(a,i),failedResponseHandler:SN,successfulResponseHandler:dr(e7),abortSignal:e.abortSignal,fetch:this.config.fetch}),y={unified:"other",raw:void 0},_={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},v={},x={},w={},S=null,P,k=null,I=null,E=null,b=!1,M,R=this.generateId,D=g.pipeThrough(new TransformStream({start(W){W.enqueue({type:"stream-start",warnings:n})},transform(W,j){var O,Z,F,z,Y,ae,K,he,L,le,oe,ne,C,G;if(e.includeRawChunks&&j.enqueue({type:"raw",rawValue:W.rawValue}),!W.success){j.enqueue({type:"error",error:W.error});return}let X=W.value;switch(X.type){case"ping":return;case"content_block_start":{let q=X.content_block,Me=q.type;switch(M=Me,Me){case"text":{if(l)return;v[X.index]={type:"text"},j.enqueue({type:"text-start",id:String(X.index)});return}case"thinking":{v[X.index]={type:"reasoning"},j.enqueue({type:"reasoning-start",id:String(X.index)});return}case"redacted_thinking":{v[X.index]={type:"reasoning"},j.enqueue({type:"reasoning-start",id:String(X.index),providerMetadata:{anthropic:{redactedData:q.data}}});return}case"compaction":{v[X.index]={type:"text"},j.enqueue({type:"text-start",id:String(X.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(l&&q.name==="json")b=!0,v[X.index]={type:"text"},j.enqueue({type:"text-start",id:String(X.index)});else{let at=q.caller,rr=at?{type:at.type,toolId:"tool_id"in at?at.tool_id:void 0}:void 0,gr=q.input&&Object.keys(q.input).length>0?JSON.stringify(q.input):"";v[X.index]={type:"tool-call",toolCallId:q.id,toolName:q.name,input:gr,firstDelta:gr.length===0,...rr&&{caller:rr}},j.enqueue({type:"tool-input-start",id:q.id,toolName:q.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(q.name)){let fe=q.name==="text_editor_code_execution"||q.name==="bash_code_execution"?"code_execution":q.name,at=u.toCustomToolName(fe),rr=q.input!=null&&typeof q.input=="object"&&Object.keys(q.input).length>0?JSON.stringify(q.input):"";v[X.index]={type:"tool-call",toolCallId:q.id,toolName:at,input:rr,providerExecuted:!0,...m&&fe==="code_execution"?{dynamic:!0}:{},firstDelta:!0,providerToolName:q.name},j.enqueue({type:"tool-input-start",id:q.id,toolName:at,providerExecuted:!0,...m&&fe==="code_execution"?{dynamic:!0}:{}})}else if(q.name==="tool_search_tool_regex"||q.name==="tool_search_tool_bm25"){w[q.id]=q.name;let fe=u.toCustomToolName(q.name);v[X.index]={type:"tool-call",toolCallId:q.id,toolName:fe,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:q.name},j.enqueue({type:"tool-input-start",id:q.id,toolName:fe,providerExecuted:!0})}return}case"web_fetch_tool_result":{q.content.type==="web_fetch_result"?(p.push({title:(O=q.content.content.title)!=null?O:q.content.url,mediaType:q.content.content.source.media_type}),j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:q.content.url,retrievedAt:q.content.retrieved_at,content:{type:q.content.content.type,title:q.content.content.title,citations:q.content.content.citations,source:{type:q.content.content.source.type,mediaType:q.content.content.source.media_type,data:q.content.content.source.data}}}})):q.content.type==="web_fetch_tool_result_error"&&j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:q.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(q.content)){j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("web_search"),result:q.content.map(fe=>{var at;return{url:fe.url,title:fe.title,pageAge:(at=fe.page_age)!=null?at:null,encryptedContent:fe.encrypted_content,type:fe.type}})});for(let fe of q.content)j.enqueue({type:"source",sourceType:"url",id:R(),url:fe.url,title:fe.title,providerMetadata:{anthropic:{pageAge:(Z=fe.page_age)!=null?Z:null}}})}else j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:q.content.error_code}});return}case"code_execution_tool_result":{q.content.type==="code_execution_result"?j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("code_execution"),result:{type:q.content.type,stdout:q.content.stdout,stderr:q.content.stderr,return_code:q.content.return_code,content:(F=q.content.content)!=null?F:[]}}):q.content.type==="encrypted_code_execution_result"?j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("code_execution"),result:{type:q.content.type,encrypted_stdout:q.content.encrypted_stdout,stderr:q.content.stderr,return_code:q.content.return_code,content:(z=q.content.content)!=null?z:[]}}):q.content.type==="code_execution_tool_result_error"&&j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:q.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName("code_execution"),result:q.content});return}case"tool_search_tool_result":{let fe=w[q.tool_use_id];if(fe==null){let at=u.toCustomToolName("tool_search_tool_bm25"),rr=u.toCustomToolName("tool_search_tool_regex");at!=="tool_search_tool_bm25"?fe="tool_search_tool_bm25":fe="tool_search_tool_regex"}q.content.type==="tool_search_tool_search_result"?j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName(fe),result:q.content.tool_references.map(at=>({type:at.type,toolName:at.tool_name}))}):j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:u.toCustomToolName(fe),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:q.content.error_code}});return}case"mcp_tool_use":{x[q.id]={type:"tool-call",toolCallId:q.id,toolName:q.name,input:JSON.stringify(q.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:q.server_name}}},j.enqueue(x[q.id]);return}case"mcp_tool_result":{j.enqueue({type:"tool-result",toolCallId:q.tool_use_id,toolName:x[q.tool_use_id].toolName,isError:q.is_error,result:q.content,dynamic:!0,providerMetadata:x[q.tool_use_id].providerMetadata});return}default:{let fe=Me;throw new Error(`Unsupported content block type: ${fe}`)}}}case"content_block_stop":{if(v[X.index]!=null){let q=v[X.index];switch(q.type){case"text":{j.enqueue({type:"text-end",id:String(X.index)});break}case"reasoning":{j.enqueue({type:"reasoning-end",id:String(X.index)});break}case"tool-call":if(!(l&&q.toolName==="json")){j.enqueue({type:"tool-input-end",id:q.toolCallId});let fe=q.input===""?"{}":q.input;if(q.providerToolName==="code_execution")try{let at=JSON.parse(fe);at!=null&&typeof at=="object"&&"code"in at&&!("type"in at)&&(fe=JSON.stringify({type:"programmatic-tool-call",...at}))}catch{}j.enqueue({type:"tool-call",toolCallId:q.toolCallId,toolName:q.toolName,input:fe,providerExecuted:q.providerExecuted,...m&&q.providerToolName==="code_execution"?{dynamic:!0}:{},...q.caller&&{providerMetadata:{anthropic:{caller:q.caller}}}})}break}delete v[X.index]}M=void 0;return}case"content_block_delta":{let q=X.delta.type;switch(q){case"text_delta":{if(l)return;j.enqueue({type:"text-delta",id:String(X.index),delta:X.delta.text});return}case"thinking_delta":{j.enqueue({type:"reasoning-delta",id:String(X.index),delta:X.delta.thinking});return}case"signature_delta":{M==="thinking"&&j.enqueue({type:"reasoning-delta",id:String(X.index),delta:"",providerMetadata:{anthropic:{signature:X.delta.signature}}});return}case"compaction_delta":{X.delta.content!=null&&j.enqueue({type:"text-delta",id:String(X.index),delta:X.delta.content});return}case"input_json_delta":{let Me=v[X.index],fe=X.delta.partial_json;if(fe.length===0)return;if(b){if(Me?.type!=="text")return;j.enqueue({type:"text-delta",id:String(X.index),delta:fe})}else{if(Me?.type!=="tool-call")return;Me.firstDelta&&(Me.providerToolName==="bash_code_execution"||Me.providerToolName==="text_editor_code_execution")&&(fe=`{"type": "${Me.providerToolName}",${fe.substring(1)}`),j.enqueue({type:"tool-input-delta",id:Me.toolCallId,delta:fe}),Me.input+=fe,Me.firstDelta=!1}return}case"citations_delta":{let Me=X.delta.citation,fe=AN(Me,p,R);fe&&j.enqueue(fe);return}default:{let Me=q;throw new Error(`Unsupported delta type: ${Me}`)}}}case"message_start":{if(_.input_tokens=X.message.usage.input_tokens,_.cache_read_input_tokens=(Y=X.message.usage.cache_read_input_tokens)!=null?Y:0,_.cache_creation_input_tokens=(ae=X.message.usage.cache_creation_input_tokens)!=null?ae:0,P={...X.message.usage},k=(K=X.message.usage.cache_creation_input_tokens)!=null?K:null,X.message.container!=null&&(E={expiresAt:X.message.container.expires_at,id:X.message.container.id,skills:null}),X.message.stop_reason!=null&&(y={unified:pT({finishReason:X.message.stop_reason,isJsonResponseFromTool:b}),raw:X.message.stop_reason}),j.enqueue({type:"response-metadata",id:(he=X.message.id)!=null?he:void 0,modelId:(L=X.message.model)!=null?L:void 0}),X.message.content!=null)for(let q=0;q<X.message.content.length;q++){let Me=X.message.content[q];if(Me.type==="tool_use"){let fe=Me.caller,at=fe?{type:fe.type,toolId:"tool_id"in fe?fe.tool_id:void 0}:void 0;j.enqueue({type:"tool-input-start",id:Me.id,toolName:Me.name});let rr=JSON.stringify((le=Me.input)!=null?le:{});j.enqueue({type:"tool-input-delta",id:Me.id,delta:rr}),j.enqueue({type:"tool-input-end",id:Me.id}),j.enqueue({type:"tool-call",toolCallId:Me.id,toolName:Me.name,input:rr,...at&&{providerMetadata:{anthropic:{caller:at}}}})}}return}case"message_delta":{X.usage.input_tokens!=null&&_.input_tokens!==X.usage.input_tokens&&(_.input_tokens=X.usage.input_tokens),_.output_tokens=X.usage.output_tokens,X.usage.cache_read_input_tokens!=null&&(_.cache_read_input_tokens=X.usage.cache_read_input_tokens),X.usage.cache_creation_input_tokens!=null&&(_.cache_creation_input_tokens=X.usage.cache_creation_input_tokens,k=X.usage.cache_creation_input_tokens),X.usage.iterations!=null&&(_.iterations=X.usage.iterations),y={unified:pT({finishReason:X.delta.stop_reason,isJsonResponseFromTool:b}),raw:(oe=X.delta.stop_reason)!=null?oe:void 0},I=(ne=X.delta.stop_sequence)!=null?ne:null,E=X.delta.container!=null?{expiresAt:X.delta.container.expires_at,id:X.delta.container.id,skills:(G=(C=X.delta.container.skills)==null?void 0:C.map(q=>({type:q.type,skillId:q.skill_id,version:q.version})))!=null?G:null}:null,X.context_management&&(S=ON(X.context_management)),P={...P,...X.usage};return}case"message_stop":{let q={usage:P??null,cacheCreationInputTokens:k,stopSequence:I,iterations:_.iterations?_.iterations.map(fe=>({type:fe.type,inputTokens:fe.input_tokens,outputTokens:fe.output_tokens})):null,container:E,contextManagement:S},Me={anthropic:q};d&&c!=="anthropic"&&(Me[c]=q),j.enqueue({type:"finish",finishReason:y,usage:EN({usage:_,rawUsage:P}),providerMetadata:Me});return}case"error":{j.enqueue({type:"error",error:X.error});return}default:{let q=X;throw new Error(`Unsupported chunk type: ${q}`)}}}})),[te,ee]=D.tee(),J=te.getReader();try{await J.read();let W=await J.read();if(((t=W.value)==null?void 0:t.type)==="raw"&&(W=await J.read()),((o=W.value)==null?void 0:o.type)==="error"){let j=W.value.error;throw new _t({message:j.message,url:f,requestBodyValues:a,statusCode:j.type==="overloaded_error"?529:500,responseHeaders:h,responseBody:JSON.stringify(j),isRetryable:j.type==="overloaded_error"})}}finally{J.cancel().catch(()=>{}),J.releaseLock()}return{stream:ee,request:{body:a},response:{headers:h}}}};function B7(e){return e.includes("claude-opus-4-7")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,isKnownModel:!0}:e.includes("claude-sonnet-4-6")||e.includes("claude-opus-4-6")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-sonnet-4-5")||e.includes("claude-opus-4-5")||e.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-sonnet-4-")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!1}}s(B7,"getModelCapabilities");function CN(e){if(!e)return!1;let t=!1,o=!1;for(let a of e){if("type"in a&&(a.type==="web_fetch_20260209"||a.type==="web_search_20260209")){t=!0;continue}if(a.name==="code_execution"){o=!0;break}}return t&&!o}s(CN,"hasWebTool20260209WithoutCodeExecution");function ON(e){return e?{appliedEdits:e.applied_edits.map(t=>{switch(t.type){case"clear_tool_uses_20250919":return{type:t.type,clearedToolUses:t.cleared_tool_uses,clearedInputTokens:t.cleared_input_tokens};case"clear_thinking_20251015":return{type:t.type,clearedThinkingTurns:t.cleared_thinking_turns,clearedInputTokens:t.cleared_input_tokens};case"compact_20260112":return{type:t.type}}}).filter(t=>t!==void 0)}:null}s(ON,"mapAnthropicResponseContextManagement");var V7=N(()=>$(r.object({command:r.string(),restart:r.boolean().optional()}))),Z7=yt({id:"anthropic.bash_20241022",inputSchema:V7}),H7=N(()=>$(r.object({command:r.string(),restart:r.boolean().optional()}))),J7=yt({id:"anthropic.bash_20250124",inputSchema:H7}),W7=N(()=>$(r.object({action:r.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:r.array(r.number().int()).optional(),text:r.string().optional()}))),G7=yt({id:"anthropic.computer_20241022",inputSchema:W7}),K7=N(()=>$(r.object({action:r.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),duration:r.number().optional(),scroll_amount:r.number().optional(),scroll_direction:r.enum(["up","down","left","right"]).optional(),start_coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),text:r.string().optional()}))),X7=yt({id:"anthropic.computer_20250124",inputSchema:K7}),Y7=N(()=>$(r.object({action:r.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),duration:r.number().optional(),region:r.tuple([r.number().int(),r.number().int(),r.number().int(),r.number().int()]).optional(),scroll_amount:r.number().optional(),scroll_direction:r.enum(["up","down","left","right"]).optional(),start_coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),text:r.string().optional()}))),Q7=yt({id:"anthropic.computer_20251124",inputSchema:Y7}),eX=N(()=>$(r.discriminatedUnion("command",[r.object({command:r.literal("view"),path:r.string(),view_range:r.tuple([r.number(),r.number()]).optional()}),r.object({command:r.literal("create"),path:r.string(),file_text:r.string()}),r.object({command:r.literal("str_replace"),path:r.string(),old_str:r.string(),new_str:r.string()}),r.object({command:r.literal("insert"),path:r.string(),insert_line:r.number(),insert_text:r.string()}),r.object({command:r.literal("delete"),path:r.string()}),r.object({command:r.literal("rename"),old_path:r.string(),new_path:r.string()})]))),tX=yt({id:"anthropic.memory_20250818",inputSchema:eX}),rX=N(()=>$(r.object({command:r.enum(["view","create","str_replace","insert","undo_edit"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),oX=yt({id:"anthropic.text_editor_20241022",inputSchema:rX}),nX=N(()=>$(r.object({command:r.enum(["view","create","str_replace","insert","undo_edit"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),aX=yt({id:"anthropic.text_editor_20250124",inputSchema:nX}),iX=N(()=>$(r.object({command:r.enum(["view","create","str_replace","insert"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),sX=yt({id:"anthropic.text_editor_20250429",inputSchema:iX}),lX=N(()=>$(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),uX=N(()=>$(r.object({query:r.string(),limit:r.number().optional()}))),cX=Pe({id:"anthropic.tool_search_bm25_20251119",inputSchema:uX,outputSchema:lX,supportsDeferredResults:!0}),dX=s((e={})=>cX(e),"toolSearchBm25_20251119"),pX={bash_20241022:Z7,bash_20250124:J7,codeExecution_20250522:E7,codeExecution_20250825:O7,codeExecution_20260120:z7,computer_20241022:G7,computer_20250124:X7,computer_20251124:Q7,memory_20250818:tX,textEditor_20241022:oX,textEditor_20250124:aX,textEditor_20250429:sX,textEditor_20250728:i7,webFetch_20250910:S7,webFetch_20260209:b7,webSearch_20250305:h7,webSearch_20260209:d7,toolSearchRegex_20251119:M7,toolSearchBm25_20251119:dX};function yp(e={}){var t,o;let a=(t=ta(Yn({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?t:"https://api.anthropic.com/v1",n=(o=e.name)!=null?o:"anthropic.messages";if(e.apiKey&&e.authToken)throw new xl({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let i=s(()=>{let c=e.authToken?{Authorization:`Bearer ${e.authToken}`}:{"x-api-key":vi({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return Qt({"anthropic-version":"2023-06-01",...c,...e.headers},`ai-sdk/anthropic/${X8}`)},"getHeaders"),l=s(c=>{var d;return new F7(c,{provider:n,baseURL:a,headers:i,fetch:e.fetch,generateId:(d=e.generateId)!=null?d:Fe,supportedUrls:s(()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]}),"supportedUrls")})},"createChatModel"),u=s(function(c){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return l(c)},"provider");return u.specificationVersion="v3",u.languageModel=l,u.chat=l,u.messages=l,u.embeddingModel=c=>{throw new Qx({modelId:c,modelType:"embeddingModel"})},u.textEmbeddingModel=u.embeddingModel,u.imageModel=c=>{throw new Qx({modelId:c,modelType:"imageModel"})},u.tools=pX,u}s(yp,"createAnthropic");var DN=yp();var mj="vercel.ai.error",mX=Symbol.for(mj),UN,LN,jt=class fj extends(LN=Error,UN=mX,LN){static{s(this,"_AISDKError")}constructor({name:t,message:o,cause:a}){super(o),this[UN]=!0,this.name=t,this.cause=a}static isInstance(t){return fj.hasMarker(t,mj)}static hasMarker(t,o){let a=Symbol.for(o);return t!=null&&typeof t=="object"&&a in t&&typeof t[a]=="boolean"&&t[a]===!0}},hj="AI_APICallError",gj=`vercel.ai.error.${hj}`,fX=Symbol.for(gj),qN,FN,rn=class extends(FN=jt,qN=fX,FN){static{s(this,"APICallError")}constructor({message:e,url:t,requestBodyValues:o,statusCode:a,responseHeaders:n,responseBody:i,cause:l,isRetryable:u=a!=null&&(a===408||a===409||a===429||a>=500),data:c}){super({name:hj,message:e,cause:l}),this[qN]=!0,this.url=t,this.requestBodyValues=o,this.statusCode=a,this.responseHeaders=n,this.responseBody=i,this.isRetryable=u,this.data=c}static isInstance(e){return jt.hasMarker(e,gj)}},yj="AI_EmptyResponseBodyError",_j=`vercel.ai.error.${yj}`,hX=Symbol.for(_j),BN,VN,hT=class extends(VN=jt,BN=hX,VN){static{s(this,"EmptyResponseBodyError")}constructor({message:e="Empty response body"}={}){super({name:yj,message:e}),this[BN]=!0}static isInstance(e){return jt.hasMarker(e,_j)}};function vj(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}s(vj,"getErrorMessage");var bj="AI_InvalidArgumentError",xj=`vercel.ai.error.${bj}`,gX=Symbol.for(xj),ZN,HN,oy=class extends(HN=jt,ZN=gX,HN){static{s(this,"InvalidArgumentError")}constructor({message:e,cause:t,argument:o}){super({name:bj,message:e,cause:t}),this[ZN]=!0,this.argument=o}static isInstance(e){return jt.hasMarker(e,xj)}},wj="AI_InvalidPromptError",Tj=`vercel.ai.error.${wj}`,yX=Symbol.for(Tj),JN,WN,hje=class extends(WN=jt,JN=yX,WN){static{s(this,"InvalidPromptError")}constructor({prompt:e,message:t,cause:o}){super({name:wj,message:`Invalid prompt: ${t}`,cause:o}),this[JN]=!0,this.prompt=e}static isInstance(e){return jt.hasMarker(e,Tj)}},Sj="AI_InvalidResponseDataError",Ij=`vercel.ai.error.${Sj}`,_X=Symbol.for(Ij),GN,KN,gje=class extends(KN=jt,GN=_X,KN){static{s(this,"InvalidResponseDataError")}constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Sj,message:t}),this[GN]=!0,this.data=e}static isInstance(e){return jt.hasMarker(e,Ij)}},kj="AI_JSONParseError",Pj=`vercel.ai.error.${kj}`,vX=Symbol.for(Pj),XN,YN,_p=class extends(YN=jt,XN=vX,YN){static{s(this,"JSONParseError")}constructor({text:e,cause:t}){super({name:kj,message:`JSON parsing failed: Text: ${e}.
94
94
  Error message: ${vj(t)}`,cause:t}),this[XN]=!0,this.text=e}static isInstance(e){return jt.hasMarker(e,Pj)}},Ej="AI_LoadAPIKeyError",Aj=`vercel.ai.error.${Ej}`,bX=Symbol.for(Aj),QN,ej,yje=class extends(ej=jt,QN=bX,ej){static{s(this,"LoadAPIKeyError")}constructor({message:e}){super({name:Ej,message:e}),this[QN]=!0}static isInstance(e){return jt.hasMarker(e,Aj)}},Cj="AI_LoadSettingError",Oj=`vercel.ai.error.${Cj}`,xX=Symbol.for(Oj),tj,rj,vp=class extends(rj=jt,tj=xX,rj){static{s(this,"LoadSettingError")}constructor({message:e}){super({name:Cj,message:e}),this[tj]=!0}static isInstance(e){return jt.hasMarker(e,Oj)}},$j="AI_NoContentGeneratedError",Rj=`vercel.ai.error.${$j}`,wX=Symbol.for(Rj),oj,nj,_je=class extends(nj=jt,oj=wX,nj){static{s(this,"NoContentGeneratedError")}constructor({message:e="No content generated."}={}){super({name:$j,message:e}),this[oj]=!0}static isInstance(e){return jt.hasMarker(e,Rj)}},zj="AI_NoSuchModelError",Nj=`vercel.ai.error.${zj}`,TX=Symbol.for(Nj),aj,ij,vje=class extends(ij=jt,aj=TX,ij){static{s(this,"NoSuchModelError")}constructor({errorName:e=zj,modelId:t,modelType:o,message:a=`No such ${o}: ${t}`}){super({name:e,message:a}),this[aj]=!0,this.modelId=t,this.modelType=o}static isInstance(e){return jt.hasMarker(e,Nj)}},jj="AI_TooManyEmbeddingValuesForCallError",Mj=`vercel.ai.error.${jj}`,SX=Symbol.for(Mj),sj,lj,Dj=class extends(lj=jt,sj=SX,lj){static{s(this,"TooManyEmbeddingValuesForCallError")}constructor(e){super({name:jj,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[sj]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return jt.hasMarker(e,Mj)}},Uj="AI_TypeValidationError",Lj=`vercel.ai.error.${Uj}`,IX=Symbol.for(Lj),uj,cj,Si=class fT extends(cj=jt,uj=IX,cj){static{s(this,"_TypeValidationError")}constructor({value:t,cause:o}){super({name:Uj,message:`Type validation failed: Value: ${JSON.stringify(t)}.
95
95
  Error message: ${vj(o)}`,cause:o}),this[uj]=!0,this.value=t}static isInstance(t){return jt.hasMarker(t,Lj)}static wrap({value:t,cause:o}){return fT.isInstance(o)&&o.value===t?o:new fT({value:t,cause:o})}},qj="AI_UnsupportedFunctionalityError",Fj=`vercel.ai.error.${qj}`,kX=Symbol.for(Fj),dj,pj,on=class extends(pj=jt,dj=kX,pj){static{s(this,"UnsupportedFunctionalityError")}constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:qj,message:t}),this[dj]=!0,this.functionality=e}static isInstance(e){return jt.hasMarker(e,Fj)}};function la(...e){return e.reduce((t,o)=>({...t,...o??{}}),{})}s(la,"combineHeaders");function bp(e){return Object.fromEntries([...e.headers])}s(bp,"extractResponseHeaders");var Wj="AI_DownloadError",Gj=`vercel.ai.error.${Wj}`,PX=Symbol.for(Gj),Bj,Vj,Nje=class extends(Vj=jt,Bj=PX,Vj){static{s(this,"DownloadError")}constructor({url:e,statusCode:t,statusText:o,cause:a,message:n=a==null?`Failed to download ${e}: ${t} ${o}`:`Failed to download ${e}: ${a}`}){super({name:Wj,message:n,cause:a}),this[Bj]=!0,this.url=e,this.statusCode=t,this.statusText=o}static isInstance(e){return jt.hasMarker(e,Gj)}},jje=2*1024*1024*1024;var EX=s(({prefix:e,size:t=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{let n=s(()=>{let i=o.length,l=new Array(t);for(let u=0;u<t;u++)l[u]=o[Math.random()*i|0];return l.join("")},"generator");if(e==null)return n;if(o.includes(a))throw new oy({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${o}".`});return()=>`${e}${a}${n()}`},"createIdGenerator"),Kj=EX();function _T(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}s(_T,"isAbortError");var AX=["fetch failed","failed to fetch"];function CX({error:e,url:t,requestBodyValues:o}){if(_T(e))return e;if(e instanceof TypeError&&AX.includes(e.message.toLowerCase())){let a=e.cause;if(a!=null)return new rn({message:`Cannot connect to API: ${a.message}`,cause:a,url:t,requestBodyValues:o,isRetryable:!0})}return e}s(CX,"handleFetchError");function iy(e=globalThis){var t,o,a;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(a=(o=e.process)==null?void 0:o.versions)!=null&&a.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}s(iy,"getRuntimeEnvironmentUserAgent");function au(e){if(e==null)return{};let t={};if(e instanceof Headers)e.forEach((o,a)=>{t[a.toLowerCase()]=o});else{Array.isArray(e)||(e=Object.entries(e));for(let[o,a]of e)a!=null&&(t[o.toLowerCase()]=a)}return t}s(au,"normalizeHeaders");function iu(e,...t){let o=new Headers(au(e)),a=o.get("user-agent")||"";return o.set("user-agent",[a,...t].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}s(iu,"withUserAgentSuffix");var OX="3.0.23";function xT({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}s(xT,"loadOptionalSetting");function xp({settingValue:e,environmentVariableName:t,settingName:o,description:a}){if(typeof e=="string")return e;if(e!=null)throw new vp({message:`${a} setting must be a string.`});if(typeof process>"u")throw new vp({message:`${a} setting is missing. Pass it using the '${o}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new vp({message:`${a} setting is missing. Pass it using the '${o}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new vp({message:`${a} setting must be a string. The value of the ${t} environment variable is not a string.`});return e}s(xp,"loadSetting");var $X=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,RX=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Zj(e){let t=JSON.parse(e);return t===null||typeof t!="object"||$X.test(e)===!1&&RX.test(e)===!1?t:zX(t)}s(Zj,"_parse");function zX(e){let t=[e];for(;t.length;){let o=t;t=[];for(let a of o){if(Object.prototype.hasOwnProperty.call(a,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(a,"constructor")&&a.constructor!==null&&typeof a.constructor=="object"&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(let n in a){let i=a[n];i&&typeof i=="object"&&t.push(i)}}}return e}s(zX,"filter");function Xj(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Zj(e)}try{return Zj(e)}finally{Error.stackTraceLimit=t}}s(Xj,"secureJsonParse");var ay=Symbol.for("vercel.ai.validator");function NX(e){return{[ay]:!0,validate:e}}s(NX,"validator");function jX(e){return typeof e=="object"&&e!==null&&ay in e&&e[ay]===!0&&"validate"in e}s(jX,"isValidator");function MX(e){return jX(e)?e:typeof e=="function"?e():DX(e)}s(MX,"asValidator");function DX(e){return NX(async t=>{let o=await e["~standard"].validate(t);return o.issues==null?{success:!0,value:o.value}:{success:!1,error:new Si({value:t,cause:o.issues})}})}s(DX,"standardSchemaValidator");async function wp({value:e,schema:t}){let o=await Tp({value:e,schema:t});if(!o.success)throw Si.wrap({value:e,cause:o.error});return o.value}s(wp,"validateTypes");async function Tp({value:e,schema:t}){let o=MX(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:Si.wrap({value:e,cause:a.error}),rawValue:e}}catch(a){return{success:!1,error:Si.wrap({value:e,cause:a}),rawValue:e}}}s(Tp,"safeValidateTypes");async function UX({text:e,schema:t}){try{let o=Xj(e);return t==null?o:wp({value:o,schema:t})}catch(o){throw _p.isInstance(o)||Si.isInstance(o)?o:new _p({text:e,cause:o})}}s(UX,"parseJSON");async function wT({text:e,schema:t}){try{let o=Xj(e);return t==null?{success:!0,value:o,rawValue:o}:await Tp({value:o,schema:t})}catch(o){return{success:!1,error:_p.isInstance(o)?o:new _p({text:e,cause:o}),rawValue:void 0}}}s(wT,"safeParseJSON");async function ys({provider:e,providerOptions:t,schema:o}){if(t?.[e]==null)return;let a=await Tp({value:t[e],schema:o});if(!a.success)throw new oy({argument:"providerOptions",message:`invalid ${e} provider options`,cause:a.error});return a.value}s(ys,"parseProviderOptions");var LX=s(()=>globalThis.fetch,"getOriginalFetch2"),_s=s(async({url:e,headers:t,body:o,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:i,fetch:l})=>qX({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(o),values:o},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:i,fetch:l}),"postJsonToApi");var qX=s(async({url:e,headers:t={},body:o,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:i,fetch:l=LX()})=>{try{let u=await l(e,{method:"POST",headers:iu(t,`ai-sdk/provider-utils/${OX}`,iy()),body:o.content,signal:i}),c=bp(u);if(!u.ok){let d;try{d=await n({response:u,url:e,requestBodyValues:o.values})}catch(p){throw _T(p)||rn.isInstance(p)?p:new rn({message:"Failed to process error response",cause:p,statusCode:u.status,url:e,responseHeaders:c,requestBodyValues:o.values})}throw d.value}try{return await a({response:u,url:e,requestBodyValues:o.values})}catch(d){throw d instanceof Error&&(_T(d)||rn.isInstance(d))?d:new rn({message:"Failed to process successful response",cause:d,statusCode:u.status,url:e,responseHeaders:c,requestBodyValues:o.values})}}catch(u){throw CX({error:u,url:e,requestBodyValues:o.values})}},"postToApi");function Pr({id:e,name:t,inputSchema:o}){return({execute:a,outputSchema:n,toModelOutput:i,onInputStart:l,onInputDelta:u,onInputAvailable:c,...d})=>({type:"provider-defined",id:e,name:t,args:d,inputSchema:o,outputSchema:n,execute:a,toModelOutput:i,onInputStart:l,onInputDelta:u,onInputAvailable:c})}s(Pr,"createProviderDefinedToolFactory");function ua({id:e,name:t,inputSchema:o,outputSchema:a}){return({execute:n,toModelOutput:i,onInputStart:l,onInputDelta:u,onInputAvailable:c,...d})=>({type:"provider-defined",id:e,name:t,args:d,inputSchema:o,outputSchema:a,execute:n,toModelOutput:i,onInputStart:l,onInputDelta:u,onInputAvailable:c})}s(ua,"createProviderDefinedToolFactoryWithOutputSchema");async function Ii(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}s(Ii,"resolve");var Ma=s(({errorSchema:e,errorToMessage:t,isRetryable:o})=>async({response:a,url:n,requestBodyValues:i})=>{let l=await a.text(),u=bp(a);if(l.trim()==="")return{responseHeaders:u,value:new rn({message:a.statusText,url:n,requestBodyValues:i,statusCode:a.status,responseHeaders:u,responseBody:l,isRetryable:o?.(a)})};try{let c=await UX({text:l,schema:e});return{responseHeaders:u,value:new rn({message:t(c),url:n,requestBodyValues:i,statusCode:a.status,responseHeaders:u,responseBody:l,data:c,isRetryable:o?.(a,c)})}}catch{return{responseHeaders:u,value:new rn({message:a.statusText,url:n,requestBodyValues:i,statusCode:a.status,responseHeaders:u,responseBody:l,isRetryable:o?.(a)})}}},"createJsonErrorResponseHandler");var su=s(e=>async({response:t,url:o,requestBodyValues:a})=>{let n=await t.text(),i=await wT({text:n,schema:e}),l=bp(t);if(!i.success)throw new rn({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:l,responseBody:n,url:o,requestBodyValues:a});return{responseHeaders:l,value:i.value,rawValue:i.rawValue}},"createJsonResponseHandler");function ny(e){if(e.type==="object"){e.additionalProperties=!1;let t=e.properties;if(t!=null)for(let o in t)t[o]=ny(t[o])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>ny(t)):e.items=ny(e.items)),e}s(ny,"addAdditionalPropertiesToJsonSchema");var FX=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"),BX=Symbol("Let zodToJsonSchema decide on which parser to use"),Hj={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},VX=s(e=>typeof e=="string"?{...Hj,name:e}:{...Hj,...e},"getDefaultOptions");function qo(){return{}}s(qo,"parseAnyDef");function ZX(e,t){var o,a,n;let i={type:"array"};return(o=e.type)!=null&&o._def&&((n=(a=e.type)==null?void 0:a._def)==null?void 0:n.typeName)!==U.ZodAny&&(i.items=Mt(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(i.minItems=e.minLength.value),e.maxLength&&(i.maxItems=e.maxLength.value),e.exactLength&&(i.minItems=e.exactLength.value,i.maxItems=e.exactLength.value),i}s(ZX,"parseArrayDef");function HX(e){let t={type:"integer",format:"int64"};if(!e.checks)return t;for(let o of e.checks)switch(o.kind){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(HX,"parseBigintDef");function JX(){return{type:"boolean"}}s(JX,"parseBooleanDef");function Yj(e,t){return Mt(e.type._def,t)}s(Yj,"parseBrandedDef");var WX=s((e,t)=>Mt(e.innerType._def,t),"parseCatchDef");function Qj(e,t,o){let a=o??t.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,i)=>Qj(e,t,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return GX(e)}}s(Qj,"parseDateDef");var GX=s(e=>{let t={type:"integer",format:"unix-time"};for(let o of e.checks)switch(o.kind){case"min":t.minimum=o.value;break;case"max":t.maximum=o.value;break}return t},"integerDateParser");function KX(e,t){return{...Mt(e.innerType._def,t),default:e.defaultValue()}}s(KX,"parseDefaultDef");function XX(e,t){return t.effectStrategy==="input"?Mt(e.schema._def,t):qo()}s(XX,"parseEffectsDef");function YX(e){return{type:"string",enum:Array.from(e.values)}}s(YX,"parseEnumDef");var QX=s(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function eY(e,t){let o=[Mt(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Mt(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(n=>!!n),a=[];return o.forEach(n=>{if(QX(n))a.push(...n.allOf);else{let i=n;if("additionalProperties"in n&&n.additionalProperties===!1){let{additionalProperties:l,...u}=n;i=u}a.push(i)}}),a.length?{allOf:a}:void 0}s(eY,"parseIntersectionDef");function tY(e){let t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}s(tY,"parseLiteralDef");var gT=void 0,En={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:s(()=>(gT===void 0&&(gT=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gT),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function eM(e,t){let o={type:"string"};if(e.checks)for(let a of e.checks)switch(a.kind){case"min":o.minLength=typeof o.minLength=="number"?Math.max(o.minLength,a.value):a.value;break;case"max":o.maxLength=typeof o.maxLength=="number"?Math.min(o.maxLength,a.value):a.value;break;case"email":switch(t.emailStrategy){case"format:email":An(o,"email",a.message,t);break;case"format:idn-email":An(o,"idn-email",a.message,t);break;case"pattern:zod":ao(o,En.email,a.message,t);break}break;case"url":An(o,"uri",a.message,t);break;case"uuid":An(o,"uuid",a.message,t);break;case"regex":ao(o,a.regex,a.message,t);break;case"cuid":ao(o,En.cuid,a.message,t);break;case"cuid2":ao(o,En.cuid2,a.message,t);break;case"startsWith":ao(o,RegExp(`^${yT(a.value,t)}`),a.message,t);break;case"endsWith":ao(o,RegExp(`${yT(a.value,t)}$`),a.message,t);break;case"datetime":An(o,"date-time",a.message,t);break;case"date":An(o,"date",a.message,t);break;case"time":An(o,"time",a.message,t);break;case"duration":An(o,"duration",a.message,t);break;case"length":o.minLength=typeof o.minLength=="number"?Math.max(o.minLength,a.value):a.value,o.maxLength=typeof o.maxLength=="number"?Math.min(o.maxLength,a.value):a.value;break;case"includes":{ao(o,RegExp(yT(a.value,t)),a.message,t);break}case"ip":{a.version!=="v6"&&An(o,"ipv4",a.message,t),a.version!=="v4"&&An(o,"ipv6",a.message,t);break}case"base64url":ao(o,En.base64url,a.message,t);break;case"jwt":ao(o,En.jwt,a.message,t);break;case"cidr":{a.version!=="v6"&&ao(o,En.ipv4Cidr,a.message,t),a.version!=="v4"&&ao(o,En.ipv6Cidr,a.message,t);break}case"emoji":ao(o,En.emoji(),a.message,t);break;case"ulid":{ao(o,En.ulid,a.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{An(o,"binary",a.message,t);break}case"contentEncoding:base64":{o.contentEncoding="base64";break}case"pattern:zod":{ao(o,En.base64,a.message,t);break}}break}case"nanoid":ao(o,En.nanoid,a.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return o}s(eM,"parseStringDef");function yT(e,t){return t.patternStrategy==="escape"?oY(e):e}s(yT,"escapeLiteralCheckValue");var rY=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function oY(e){let t="";for(let o=0;o<e.length;o++)rY.has(e[o])||(t+="\\"),t+=e[o];return t}s(oY,"escapeNonAlphaNumeric");function An(e,t,o,a){var n;e.format||(n=e.anyOf)!=null&&n.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...o&&a.errorMessages&&{errorMessage:{format:o}}})):e.format=t}s(An,"addFormat");function ao(e,t,o,a){var n;e.pattern||(n=e.allOf)!=null&&n.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Jj(t,a),...o&&a.errorMessages&&{errorMessage:{pattern:o}}})):e.pattern=Jj(t,a)}s(ao,"addPattern");function Jj(e,t){var o;if(!t.applyRegexFlags||!e.flags)return e.source;let a={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=a.i?e.source.toLowerCase():e.source,i="",l=!1,u=!1,c=!1;for(let d=0;d<n.length;d++){if(l){i+=n[d],l=!1;continue}if(a.i){if(u){if(n[d].match(/[a-z]/)){c?(i+=n[d],i+=`${n[d-2]}-${n[d]}`.toUpperCase(),c=!1):n[d+1]==="-"&&((o=n[d+2])!=null&&o.match(/[a-z]/))?(i+=n[d],c=!0):i+=`${n[d]}${n[d].toUpperCase()}`;continue}}else if(n[d].match(/[a-z]/)){i+=`[${n[d]}${n[d].toUpperCase()}]`;continue}}if(a.m){if(n[d]==="^"){i+=`(^|(?<=[\r
96
96
  ]))`;continue}else if(n[d]==="$"){i+=`($|(?=[\r
@@ -173,9 +173,9 @@ ${u}
173
173
  ${u}
174
174
 
175
175
  `;break}case"tool":throw new da({functionality:"tool messages"});default:break}return n+=`${a}:
176
- `,{prompt:n}}s(use,"convertToOpenRouterCompletionPrompt");var L2=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:kS.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(),Dy]),cse=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}=use({prompt:e,inputFormat:"prompt"});if(p?.length)throw new da({functionality:"tools"});if(m)throw new da({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 pu({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:du(this.config.headers(),e.headers),body:J,failedResponseHandler:mu,successfulResponseHandler:My(L2),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 wS({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:(t=O.text)!=null?t:""}],finishReason:Ry(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:PS.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 pu({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:du(this.config.headers(),e.headers),body:Pt(ve({},a),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:mu,successfulResponseHandler:EU(L2),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=Ci("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=Ci("error"),f.enqueue({type:"error",error:m.error});return}let _=m.value;if("error"in _){l=Ci("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=Ry(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}}}},dse=r.object({prompt_tokens:r.number(),total_tokens:r.number(),cost:r.number().optional()}),pse=r.object({object:r.literal("embedding"),embedding:r.array(r.number()),index:r.number().optional()}),mse=r.object({id:r.string().optional(),object:r.literal("list"),data:r.array(pse),model:r.string(),provider:r.string().optional(),usage:dse.optional()}),fse=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 pu({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:du(this.config.headers(),d),body:p,failedResponseHandler:mu,successfulResponseHandler:My(mse),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:PS.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 hse=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(),gse=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 da({functionality:"image editing (files parameter)"});if(c!==void 0)throw new da({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 pu({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:du(this.config.headers(),p),body:y,failedResponseHandler:mu,successfulResponseHandler:My(hse),abortSignal:d,fetch:this.config.fetch}),x=_.choices[0];if(!x)throw new wS({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(zy(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 yse(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}s(yse,"removeUndefinedEntries");function _se(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):e:{}}s(_se,"normalizeHeaders2");function vse(e,t){let o=t.toLowerCase();return Object.keys(e).find(a=>a.toLowerCase()===o)}s(vse,"findHeaderKey");function bse(e,...t){let o=_se(e),a=yse(o),n=vse(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(bse,"withUserAgentSuffix2");var xse="2.1.1";function Uy(e={}){var t,o,a;let n=(o=Zie((t=e.baseURL)!=null?t:e.baseUrl))!=null?o:"https://openrouter.ai/api/v1",i=(a=e.compatibility)!=null?a:"compatible",l=s(()=>bse(ve(ve({Authorization:`Bearer ${Fae({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/${xse}`),"getHeaders"),u=s((h,g={})=>new lse(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 cse(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 fse(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 gse(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(Uy,"createOpenRouter");var jLe=Uy({compatibility:"strict"});var wse=Object.defineProperty,Tse=s((e,t,o)=>t in e?wse(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,"__defNormalProp"),Rp=s((e,t,o)=>Tse(e,typeof t!="symbol"?t+"":t,o),"__publicField"),Sse="CF_TEMP_TOKEN",Ise=[{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")}],zU=class extends Error{static{s(this,"AiGatewayInternalFetchError")}},kse=class extends Error{static{s(this,"AiGatewayDoesNotExist")}},Pse=class extends Error{static{s(this,"AiGatewayUnauthorizedError")}};async function Ese(e){return await new Response(e).json()}s(Ese,"streamToObject");var Ase=class{static{s(this,"AiGatewayChatLanguageModel")}constructor(e,t){Rp(this,"specificationVersion","v3"),Rp(this,"defaultObjectGenerationMode","json"),Rp(this,"supportedUrls",{}),Rp(this,"models"),Rp(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 zU("Stopping provider execution...")};try{await u[t](e)}catch(c){if(!(c instanceof zU))throw c}}let a=await Promise.all(o.map(async u=>{let c=null;for(let m of Ise)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(Sse)!==-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 Ese(u.request.body)}})),n=Cse(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 kse("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 Pse("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 NU(e){let t=s(a=>new Ase(Array.isArray(a)?a:[a],e),"createChatModel"),o=s(a=>t(a),"provider");return o.chat=t,o}s(NU,"createAiGateway");function Cse(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(Cse,"parseAiGatewayOptions");var jU="CF_TEMP_TOKEN";function Ose(e){return t=>t?(t.apiKey===void 0&&(t.apiKey=jU),e(t)):e({apiKey:jU})}s(Ose,"authWrapper");var MU=s((...e)=>Ose(yp)(...e),"createAnthropic");var DU="CF_TEMP_TOKEN";function $se(e){return t=>t?(t.apiKey===void 0&&(t.apiKey=DU),e(t)):e({apiKey:DU})}s($se,"authWrapper");var UU=s((...e)=>$se(Ts)(...e),"createGoogleGenerativeAI");async function qU(e){let{body:t}=await sa.sendRequest({method:"GET",url:`${e.apiUrl}v1/ai-providers/${e.provider}/config`,headers:{Authorization:`Bearer ${e.engineToken}`}});return t}s(qU,"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 qU({provider:e,engineToken:o,apiUrl:l});if(c&&!Lh[e].supportsImageGeneration)throw new Error(`Provider ${e} does not support image models`);switch(e){case"openai":{let{apiKey:f}=p,h=kp({apiKey:f});return c?h.imageModel(t):u?h.responses(t):h.chat(t)}case"anthropic":{let{apiKey:f}=p;return yp({apiKey:f})(t)}case"google":{let{apiKey:f}=p;return Ts({apiKey:f})(t)}case"azure":{let{apiKey:f}=p,{resourceName:h,apiVersion:g}=d,y=ky({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=NU({accountId:h,gateway:g,apiKey:f}),{provider:x,model:w,publisher:S}=Uh(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=MU({headers:k});return v(I(w))}case"google-ai-studio":{let I=UU({headers:k});return v(I(w))}case"google-vertex-ai":return y&&_&&S?Ts({apiKey:f,baseURL:`https://gateway.ai.cloudflare.com/v1/${h}/${g}/google-vertex-ai/v1/projects/${y}/locations/${_}/publishers/${S}/`,headers:k})(w):LU({accountId:h,gatewayId:g,headers:k,isImage:c,modelId:t});case"openai":{let I=kp({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 LU({accountId:h,gatewayId:g,headers:k,isImage:c,modelId:t})}}case"bedrock":{let{accessKeyId:f,secretAccessKey:h}=p,{region:g}=d,y=GT({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=Iy({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;return Iy({name:"mistral",baseURL:"https://api.mistral.ai/v1",apiKey:f}).chatModel(t)}case"activepieces":case"openrouter":{let{apiKey:f}=p;return Uy({apiKey:f}).chat(t)}default:throw new Error(`Provider ${e} is not supported`)}}s(Bo,"createAIModel");var CS=DN.tools.webSearch_20250305,OS=GD.tools.webSearchPreview,$S=c1.tools.googleSearch,Rse=768,AS={openai:{dimensions:Rse}};async function RS({provider:e,engineToken:t,apiUrl:o}){let{config:a,auth:n}=await qU({provider:e,engineToken:t,apiUrl:o}),i=Lh[e].defaultEmbeddingModel;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:kp({apiKey:l}).embeddingModel(i),embeddingModelId:i,providerOptions:AS};case"google":return{model:Ts({apiKey:l}).textEmbeddingModel(i),embeddingModelId:i,providerOptions:{}};case"azure":{let{resourceName:u,apiVersion:c}=a;return{model:ky({resourceName:u,apiKey:l,apiVersion:c}).embeddingModel(i),embeddingModelId:i,providerOptions:AS}}case"activepieces":case"openrouter":return{model:Uy({apiKey:l}).textEmbeddingModel(i),embeddingModelId:i,providerOptions:AS};default:throw new Error(`Provider ${e} does not support embedding models`)}}s(RS,"createEmbeddingModel");var LU=s(({accountId:e,gatewayId:t,headers:o,isImage:a,modelId:n})=>{let i=Iy({name:"cloudflare",baseURL:`https://gateway.ai.cloudflare.com/v1/${e}/${t}/compat`,headers:o});return a?i.imageModel(n):i.chatModel(n)},"handleDefaultAiGatewayProvider");function zse(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(zse,"buildWebSearchOptionsProps");function FU(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(FU,"buildUserLocation");function Nse(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:CS({maxUses:a.maxUses??5,...Qr("userLocation",FU(a)),...Qr("allowedDomains",n),...Qr("blockedDomains",i)})}}case"openai":{let a=t;return{web_search_preview:OS({...Qr("searchContextSize",a.searchContextSize),...Qr("userLocation",FU(a))})}}case"google":return{google_search:$S({})};default:throw new Error(`Provider ${e} is not supported for web search`)}}s(Nse,"createWebSearchTool");function Ly(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 zse(u??i,o)},"props")})}s(Ly,"buildWebSearchOptionsProperty");function qy(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:Nse(l,n),providerOptions:void 0}}s(qy,"buildWebSearchConfig");var BU=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:Ly(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}=qy({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?nu(i?.maxUses??5):void 0,h=await ia({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 VU=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 ia({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 KU=mo(zS());var XU=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=Fse({inputImages:e.propsValue.inputImages,advancedOptions:e.propsValue.advancedOptions}),n=await Bse({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"})}}),Fse=s(({inputImages:e,advancedOptions:t})=>{let o=GU(e);return o.length>0?o:GU(t?.image)},"collectInputImages"),GU=s(e=>Array.isArray(e)?e.flatMap(t=>t&&typeof t=="object"&&"file"in t&&t.file?[t.file]:[]):[],"extractImageFiles"),Bse=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 Vse({modelId:t,hasInputImages:h},async()=>{switch(f){case"google":case"activepieces":case"openrouter":case"cloudflare-gateway":return Zse({model:p,prompt:n,inputImages:i});default:{let g=Hse(d),y=i.map(v=>Buffer.from(v.base64,"base64")),{image:_}=await vN({model:p,prompt:h?{text:n,images:y}:n,providerOptions:{[f]:{...g}}});return _}}})},"getGeneratedImage"),Vse=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"),Zse=s(async({model:e,prompt:t,inputImages:o})=>{let a=o.map(i=>{let l=i.extension?KU.default.lookup(i.extension):!1;return{type:"image",image:`data:${l&&Jse.has(l)?l:"image/jpeg"};base64,${i.base64}`}}),n=await ia({model:e,providerOptions:{google:{responseModalities:["TEXT","IMAGE"]},openrouter:{modalities:["image","text"]}},messages:[{role:"user",content:[{type:"text",text:t},...a]}]});return Wse(n),n.files[0]},"generateImageUsingGenerateText"),Hse=s(e=>{if(Ft(e))return e;let{image:t,...o}=e;return o},"stripLegacyImageField"),Jse=new Set(["image/jpeg","image/png","image/gif","image/webp","image/avif"]),Wse=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))}),Ft(e.files)||e.files.length===0)throw new Error("No image generated")},"assertImageGenerationSuccess");var YU=Xo({audience:"both",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 ia({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 kq=mo(zS()),Pq=mo(Iq());var Eq=Xo({audience:"both",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 Pq.default;if(!y.validateSchema(l.fields))throw new Error(JSON.stringify({message:"Invalid JSON schema",errors:y.errors}));d=bi(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=bi({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+=`
176
+ `,{prompt:n}}s(use,"convertToOpenRouterCompletionPrompt");var L2=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:kS.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(),Dy]),cse=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}=use({prompt:e,inputFormat:"prompt"});if(p?.length)throw new da({functionality:"tools"});if(m)throw new da({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 pu({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:du(this.config.headers(),e.headers),body:J,failedResponseHandler:mu,successfulResponseHandler:My(L2),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 wS({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:(t=O.text)!=null?t:""}],finishReason:Ry(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:PS.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 pu({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:du(this.config.headers(),e.headers),body:Pt(ve({},a),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:mu,successfulResponseHandler:EU(L2),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=Ci("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=Ci("error"),f.enqueue({type:"error",error:m.error});return}let _=m.value;if("error"in _){l=Ci("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=Ry(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}}}},dse=r.object({prompt_tokens:r.number(),total_tokens:r.number(),cost:r.number().optional()}),pse=r.object({object:r.literal("embedding"),embedding:r.array(r.number()),index:r.number().optional()}),mse=r.object({id:r.string().optional(),object:r.literal("list"),data:r.array(pse),model:r.string(),provider:r.string().optional(),usage:dse.optional()}),fse=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 pu({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:du(this.config.headers(),d),body:p,failedResponseHandler:mu,successfulResponseHandler:My(mse),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:PS.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 hse=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(),gse=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 da({functionality:"image editing (files parameter)"});if(c!==void 0)throw new da({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 pu({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:du(this.config.headers(),p),body:y,failedResponseHandler:mu,successfulResponseHandler:My(hse),abortSignal:d,fetch:this.config.fetch}),x=_.choices[0];if(!x)throw new wS({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(zy(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 yse(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}s(yse,"removeUndefinedEntries");function _se(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):e:{}}s(_se,"normalizeHeaders2");function vse(e,t){let o=t.toLowerCase();return Object.keys(e).find(a=>a.toLowerCase()===o)}s(vse,"findHeaderKey");function bse(e,...t){let o=_se(e),a=yse(o),n=vse(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(bse,"withUserAgentSuffix2");var xse="2.1.1";function Uy(e={}){var t,o,a;let n=(o=Zie((t=e.baseURL)!=null?t:e.baseUrl))!=null?o:"https://openrouter.ai/api/v1",i=(a=e.compatibility)!=null?a:"compatible",l=s(()=>bse(ve(ve({Authorization:`Bearer ${Fae({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/${xse}`),"getHeaders"),u=s((h,g={})=>new lse(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 cse(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 fse(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 gse(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(Uy,"createOpenRouter");var jLe=Uy({compatibility:"strict"});var wse=Object.defineProperty,Tse=s((e,t,o)=>t in e?wse(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,"__defNormalProp"),Rp=s((e,t,o)=>Tse(e,typeof t!="symbol"?t+"":t,o),"__publicField"),Sse="CF_TEMP_TOKEN",Ise=[{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")}],zU=class extends Error{static{s(this,"AiGatewayInternalFetchError")}},kse=class extends Error{static{s(this,"AiGatewayDoesNotExist")}},Pse=class extends Error{static{s(this,"AiGatewayUnauthorizedError")}};async function Ese(e){return await new Response(e).json()}s(Ese,"streamToObject");var Ase=class{static{s(this,"AiGatewayChatLanguageModel")}constructor(e,t){Rp(this,"specificationVersion","v3"),Rp(this,"defaultObjectGenerationMode","json"),Rp(this,"supportedUrls",{}),Rp(this,"models"),Rp(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 zU("Stopping provider execution...")};try{await u[t](e)}catch(c){if(!(c instanceof zU))throw c}}let a=await Promise.all(o.map(async u=>{let c=null;for(let m of Ise)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(Sse)!==-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 Ese(u.request.body)}})),n=Cse(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 kse("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 Pse("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 NU(e){let t=s(a=>new Ase(Array.isArray(a)?a:[a],e),"createChatModel"),o=s(a=>t(a),"provider");return o.chat=t,o}s(NU,"createAiGateway");function Cse(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(Cse,"parseAiGatewayOptions");var jU="CF_TEMP_TOKEN";function Ose(e){return t=>t?(t.apiKey===void 0&&(t.apiKey=jU),e(t)):e({apiKey:jU})}s(Ose,"authWrapper");var MU=s((...e)=>Ose(yp)(...e),"createAnthropic");var DU="CF_TEMP_TOKEN";function $se(e){return t=>t?(t.apiKey===void 0&&(t.apiKey=DU),e(t)):e({apiKey:DU})}s($se,"authWrapper");var UU=s((...e)=>$se(Ts)(...e),"createGoogleGenerativeAI");async function qU(e){let{body:t}=await sa.sendRequest({method:"GET",url:`${e.apiUrl}v1/ai-providers/${e.provider}/config`,headers:{Authorization:`Bearer ${e.engineToken}`}});return t}s(qU,"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 qU({provider:e,engineToken:o,apiUrl:l});if(c&&!Lh[e].supportsImageGeneration)throw new Error(`Provider ${e} does not support image models`);switch(e){case"openai":{let{apiKey:f}=p,h=kp({apiKey:f});return c?h.imageModel(t):u?h.responses(t):h.chat(t)}case"anthropic":{let{apiKey:f}=p;return yp({apiKey:f})(t)}case"google":{let{apiKey:f}=p;return Ts({apiKey:f})(t)}case"azure":{let{apiKey:f}=p,{resourceName:h,apiVersion:g}=d,y=ky({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=NU({accountId:h,gateway:g,apiKey:f}),{provider:x,model:w,publisher:S}=Uh(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=MU({headers:k});return v(I(w))}case"google-ai-studio":{let I=UU({headers:k});return v(I(w))}case"google-vertex-ai":return y&&_&&S?Ts({apiKey:f,baseURL:`https://gateway.ai.cloudflare.com/v1/${h}/${g}/google-vertex-ai/v1/projects/${y}/locations/${_}/publishers/${S}/`,headers:k})(w):LU({accountId:h,gatewayId:g,headers:k,isImage:c,modelId:t});case"openai":{let I=kp({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 LU({accountId:h,gatewayId:g,headers:k,isImage:c,modelId:t})}}case"bedrock":{let{accessKeyId:f,secretAccessKey:h}=p,{region:g}=d,y=GT({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=Iy({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;return Iy({name:"mistral",baseURL:"https://api.mistral.ai/v1",apiKey:f}).chatModel(t)}case"activepieces":case"openrouter":{let{apiKey:f}=p;return Uy({apiKey:f}).chat(t)}default:throw new Error(`Provider ${e} is not supported`)}}s(Bo,"createAIModel");var CS=DN.tools.webSearch_20250305,OS=GD.tools.webSearchPreview,$S=c1.tools.googleSearch,Rse=768,AS={openai:{dimensions:Rse}};async function RS({provider:e,engineToken:t,apiUrl:o}){let{config:a,auth:n}=await qU({provider:e,engineToken:t,apiUrl:o}),i=Lh[e].defaultEmbeddingModel;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:kp({apiKey:l}).embeddingModel(i),embeddingModelId:i,providerOptions:AS};case"google":return{model:Ts({apiKey:l}).textEmbeddingModel(i),embeddingModelId:i,providerOptions:{}};case"azure":{let{resourceName:u,apiVersion:c}=a;return{model:ky({resourceName:u,apiKey:l,apiVersion:c}).embeddingModel(i),embeddingModelId:i,providerOptions:AS}}case"activepieces":case"openrouter":return{model:Uy({apiKey:l}).textEmbeddingModel(i),embeddingModelId:i,providerOptions:AS};default:throw new Error(`Provider ${e} does not support embedding models`)}}s(RS,"createEmbeddingModel");var LU=s(({accountId:e,gatewayId:t,headers:o,isImage:a,modelId:n})=>{let i=Iy({name:"cloudflare",baseURL:`https://gateway.ai.cloudflare.com/v1/${e}/${t}/compat`,headers:o});return a?i.imageModel(n):i.chatModel(n)},"handleDefaultAiGatewayProvider");function zse(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(zse,"buildWebSearchOptionsProps");function FU(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(FU,"buildUserLocation");function Nse(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:CS({maxUses:a.maxUses??5,...Qr("userLocation",FU(a)),...Qr("allowedDomains",n),...Qr("blockedDomains",i)})}}case"openai":{let a=t;return{web_search_preview:OS({...Qr("searchContextSize",a.searchContextSize),...Qr("userLocation",FU(a))})}}case"google":return{google_search:$S({})};default:throw new Error(`Provider ${e} is not supported for web search`)}}s(Nse,"createWebSearchTool");function Ly(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 zse(u??i,o)},"props")})}s(Ly,"buildWebSearchOptionsProperty");function qy(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:Nse(l,n),providerOptions:void 0}}s(qy,"buildWebSearchConfig");var BU=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.",aiMetadata:{description:"Sends a free-form prompt to a text model and returns its answer, optionally continuing a multi-turn thread via a Conversation Key or grounding the reply with web search. Pick it for open-ended reasoning, drafting, or judgement over flow data; prefer summarizeText to condense text, classifyText for a fixed label set, extractStructuredData for typed fields, or run_agent when the task needs tools and multiple steps. Requires a provider/model plus a prompt; not idempotent, since each call generates a fresh answer and a Conversation Key appends the exchange to stored history.",idempotent:!1},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:Ly(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}=qy({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?nu(i?.maxUses??5):void 0,h=await ia({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 VU=Xo({audience:"both",name:"summarizeText",displayName:"Summarize Text",description:"Summarize long emails, articles, or documents into what matters.",aiMetadata:{description:"Condenses one block of supplied text into a shorter summary using a chosen text model. Pick it when the goal is a shorter version of text you already have; use extractStructuredData for specific typed fields, classifyText for a label, or askAi for open-ended questions. Requires a provider/model, the text inline (it fetches no URLs and reads no files) and the Prompt prop, which carries a default guide instruction but is still required; not idempotent, as generation runs at temperature 1, so identical text returns differently worded summaries.",idempotent:!1},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 ia({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 KU=mo(zS());var XU=Xo({audience:"both",name:"generateImage",displayName:"Generate Image",description:"Create unique, high-quality images from simple text descriptions using AI.",aiMetadata:{description:"Generates an image from a text prompt with an image-capable model and writes it out as a flow file; when Input Images are attached and the model supports editing, it edits, varies, or merges those images instead of generating from scratch. Pick it for any image creation or edit step; use askAi or run_agent when you need text output. Requires a prompt plus an image-capable provider/model, and input images fail on a model that cannot accept them; not idempotent, as each call generates and stores a new image file.",idempotent:!1},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=Fse({inputImages:e.propsValue.inputImages,advancedOptions:e.propsValue.advancedOptions}),n=await Bse({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"})}}),Fse=s(({inputImages:e,advancedOptions:t})=>{let o=GU(e);return o.length>0?o:GU(t?.image)},"collectInputImages"),GU=s(e=>Array.isArray(e)?e.flatMap(t=>t&&typeof t=="object"&&"file"in t&&t.file?[t.file]:[]):[],"extractImageFiles"),Bse=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 Vse({modelId:t,hasInputImages:h},async()=>{switch(f){case"google":case"activepieces":case"openrouter":case"cloudflare-gateway":return Zse({model:p,prompt:n,inputImages:i});default:{let g=Hse(d),y=i.map(v=>Buffer.from(v.base64,"base64")),{image:_}=await vN({model:p,prompt:h?{text:n,images:y}:n,providerOptions:{[f]:{...g}}});return _}}})},"getGeneratedImage"),Vse=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"),Zse=s(async({model:e,prompt:t,inputImages:o})=>{let a=o.map(i=>{let l=i.extension?KU.default.lookup(i.extension):!1;return{type:"image",image:`data:${l&&Jse.has(l)?l:"image/jpeg"};base64,${i.base64}`}}),n=await ia({model:e,providerOptions:{google:{responseModalities:["TEXT","IMAGE"]},openrouter:{modalities:["image","text"]}},messages:[{role:"user",content:[{type:"text",text:t},...a]}]});return Wse(n),n.files[0]},"generateImageUsingGenerateText"),Hse=s(e=>{if(Ft(e))return e;let{image:t,...o}=e;return o},"stripLegacyImageField"),Jse=new Set(["image/jpeg","image/png","image/gif","image/webp","image/avif"]),Wse=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))}),Ft(e.files)||e.files.length===0)throw new Error("No image generated")},"assertImageGenerationSuccess");var YU=Xo({audience:"both",name:"classifyText",displayName:"Classify Text",description:"Categorize any text input using custom labels, so your flow knows what to do next.",aiMetadata:{description:"Assigns exactly one label from a caller-supplied Categories list to a block of text using a text model, and errors if the model answers with anything outside that list. Pick it for routing or branching where the outcomes are known up front; use extractStructuredData for multiple typed fields, summarizeText to shorten text, or askAi when the answer is not one of a fixed set. Requires the text plus a non-empty Categories array matched by exact string, so keep labels short; read-only and idempotent.",idempotent:!0},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 ia({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 kq=mo(zS()),Pq=mo(Iq());var Eq=Xo({audience:"both",name:"extractStructuredData",displayName:"Extract Structured Data",description:"Accurately Pull names, amounts, and other structured data from emails, invoices, and scanned documents.",aiMetadata:{description:"Pulls typed fields out of unstructured input (text, images or PDFs) against a schema supplied either in simple mode, a list of field definitions, or advanced mode, a raw JSON Schema. Pick it when you need specific named values from documents such as invoices, receipts or emails; use classifyText for a single label, summarizeText for prose condensation, or askAi for open-ended analysis. At least one of Text or Files is required or the step throws; read-only and idempotent.",idempotent:!0},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 Pq.default;if(!y.validateSchema(l.fields))throw new Error(JSON.stringify({message:"Invalid JSON schema",errors:y.errors}));d=bi(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=bi({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?kq.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 ia({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 Aq=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",Ft(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(xme({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 xme({toolName:e,baseTool:t,toolKeyToAgentTool:o}){let a=o[e];if(Ft(a))return{...t,toolCallType:"UNKNOWN",displayName:e};switch(a.type){case"PIECE":return wd(a.pieceMetadata,"Piece metadata is required"),{...t,toolCallType:"PIECE",pieceName:a.pieceMetadata.pieceName,pieceVersion:a.pieceMetadata.pieceVersion,actionName:a.pieceMetadata.actionName};case"FLOW":return wd(a.externalFlowId,"Flow ID is required"),{...t,toolCallType:"FLOW",displayName:a.toolName,externalFlowId:a.externalFlowId};case"MCP":return wd(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(xme,"getToolMetadata");var L_=require("util");var Ns={isTaskCompletionToolCall:s(e=>e===ka,"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: ${QF(o)}`,cause:o}),this[BF]=!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(P6,"stringifyRegExpWithFlags");function R6(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}=$6(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}=C6(e.keyType._def,t);return{...c,propertyNames:p}}}return c}s(R6,"parseRecordDef");function Tge(e,t){if(t.mapStrategy==="record")return R6(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(Tge,"parseMapDef");function Sge(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(Sge,"parseNativeEnumDef");function Ige(){return{not:Zo()}}s(Ige,"parseNeverDef");function kge(){return{type:"null"}}s(kge,"parseNullDef");var Lk={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Pge(e,t){let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(a=>a._def.typeName in Lk&&(!a._def.checks||!a._def.checks.length))){let a=o.reduce((n,i)=>{let l=Lk[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 Ege(e,t)}s(Pge,"parseUnionDef");var Ege=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 Age(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Lk[e.innerType._def.typeName],"null"]};let o=Ut(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}s(Age,"parseNullableDef");function Cge(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(Cge,"parseNumberDef");function Oge(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=Rge(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=$ge(e,t);return i!==void 0&&(o.additionalProperties=i),o}s(Oge,"parseObjectDef");function $ge(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($ge,"decideAdditionalProperties");function Rge(e){try{return e.isOptional()}catch{return!0}}s(Rge,"safeIsOptional");var zge=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"),Nge=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 jge(e,t){return Ut(e.type._def,t)}s(jge,"parsePromiseDef");function Mge(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(Mge,"parseSetDef");function Dge(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(Dge,"parseTupleDef");function Uge(){return{not:Zo()}}s(Uge,"parseUndefinedDef");function Lge(){return Zo()}s(Lge,"parseUnknownDef");var qge=s((e,t)=>Ut(e.innerType._def,t),"parseReadonlyDef"),Fge=s((e,t,o)=>{switch(t){case U.ZodString:return $6(e,o);case U.ZodNumber:return Cge(e);case U.ZodObject:return Oge(e,o);case U.ZodBigInt:return dge(e);case U.ZodBoolean:return pge();case U.ZodDate:return O6(e,o);case U.ZodUndefined:return Uge();case U.ZodNull:return kge();case U.ZodArray:return cge(e,o);case U.ZodUnion:case U.ZodDiscriminatedUnion:return Pge(e,o);case U.ZodIntersection:return vge(e,o);case U.ZodTuple:return Dge(e,o);case U.ZodRecord:return R6(e,o);case U.ZodLiteral:return bge(e);case U.ZodEnum:return yge(e);case U.ZodNativeEnum:return Sge(e);case U.ZodNullable:return Age(e,o);case U.ZodOptional:return zge(e,o);case U.ZodMap:return Tge(e,o);case U.ZodSet:return Mge(e,o);case U.ZodLazy:return()=>e.getter()._def;case U.ZodPromise:return jge(e,o);case U.ZodNaN:case U.ZodNever:return Ige();case U.ZodEffects:return gge(e,o);case U.ZodAny:return Zo();case U.ZodUnknown:return Lge();case U.ZodDefault:return hge(e,o);case U.ZodBranded:return C6(e,o);case U.ZodReadonly:return qge(e,o);case U.ZodCatch:return mge(e,o);case U.ZodPipeline:return Nge(e,o);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(a=>{})(t)}},"selectParser"),Bge=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!==lge)return c}if(n&&!o){let c=Vge(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=Fge(e,e.typeName,t),u=typeof l=="function"?Ut(l(),t):l;if(u&&Zge(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 Vge=s((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Bge(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"),Zge=s((e,t,o)=>(e.description&&(o.description=e.description),o),"addMeta"),Hge=s(e=>{let t=uge(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"),Jge=s((e,t)=>{var o;let a=Hge(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"),qk=Symbol.for("vercel.ai.schema");function $u(e,{validate:t}={}){return{[qk]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}s($u,"jsonSchema");function Wge(e){return typeof e=="object"&&e!==null&&qk in e&&e[qk]===!0&&"jsonSchema"in e&&"validate"in e}s(Wge,"isSchema");function Bk(e){return e==null?$u({properties:{},additionalProperties:!1}):Wge(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?Qge(e):Gge(e):e()}s(Bk,"asSchema");function Gge(e){return $u(()=>Fk(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 Ou({value:t,cause:o.issues})}},"validate")})}s(Gge,"standardSchema");function Kge(e,t){var o;let a=(o=t?.useReferences)!=null?o:!1;return $u(()=>Jge(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(Kge,"zod3Schema");function Xge(e,t){var o;let a=(o=t?.useReferences)!=null?o:!1;return $u(()=>Fk(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(Xge,"zod4Schema");function Yge(e){return"_zod"in e}s(Yge,"isZod4Schema");function Qge(e,t){return Yge(e)?Xge(e,t):Kge(e,t)}s(Qge,"zodSchema");async function Vk({value:e,schema:t}){let o=Bk(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:Ou.wrap({value:e,cause:a.error}),rawValue:e}}catch(a){return{success:!1,error:Ou.wrap({value:e,cause:a}),rawValue:e}}}s(Vk,"safeValidateTypes");async function z6({text:e,schema:t}){try{let o=sge(e);return t==null?{success:!0,value:o,rawValue:o}:await Vk({value:o,schema:t})}catch(o){return{success:!1,error:Mk.isInstance(o)?o:new Mk({text:e,cause:o}),rawValue:void 0}}}s(z6,"safeParseJSON");function N6(e){return{...e,type:"dynamic"}}s(N6,"dynamicTool");var eye="AI_MCPClientError",F6=`vercel.ai.error.${eye}`,tye=Symbol.for(F6),j6,M6,Et=class extends(M6=wt,j6=tye,M6){static{s(this,"MCPClientError")}constructor({name:e="MCPClientError",message:t,cause:o,data:a,code:n}){super({name:e,message:t,cause:o}),this[j6]=!0,this.data=a,this.code=n}static isInstance(e){return wt.hasMarker(e,F6)}},zu="2025-06-18",rye=[zu,"2025-03-26","2024-11-05"],oye=r.optional(r.record(r.string(),r.unknown())),nye=r.looseObject({name:r.string(),version:r.string()}),D_=r.looseObject({_meta:r.optional(r.object({}).loose())}),Za=D_,B6=r.object({method:r.string(),params:r.optional(D_)}),V6=r.object({applyDefaults:r.optional(r.boolean())}).loose(),aye=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(V6)}),tHe=r.object({elicitation:r.optional(V6)}).loose(),iye=Za.extend({protocolVersion:r.string(),capabilities:aye,serverInfo:nye,instructions:r.optional(r.string())}),Hk=Za.extend({nextCursor:r.optional(r.string())}),sye=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:oye}).loose(),lye=Hk.extend({tools:r.array(sye)}),Z6=r.object({type:r.literal("text"),text:r.string()}).loose(),H6=r.object({type:r.literal("image"),data:r.base64(),mimeType:r.string()}).loose(),uye=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(),cye=Hk.extend({resources:r.array(uye)}),J6=r.object({uri:r.string(),name:r.optional(r.string()),title:r.optional(r.string()),mimeType:r.optional(r.string())}).loose(),W6=J6.extend({text:r.string()}),G6=J6.extend({blob:r.base64()}),K6=r.object({type:r.literal("resource"),resource:r.union([W6,G6])}).loose(),dye=Za.extend({content:r.array(r.union([Z6,H6,K6])),structuredContent:r.optional(r.unknown()),isError:r.boolean().default(!1).optional()}).or(Za.extend({toolResult:r.unknown()})),pye=r.object({uriTemplate:r.string(),name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),mimeType:r.optional(r.string())}).loose(),mye=Za.extend({resourceTemplates:r.array(pye)}),fye=Za.extend({contents:r.array(r.union([W6,G6]))}),hye=r.object({name:r.string(),description:r.optional(r.string()),required:r.optional(r.boolean())}).loose(),gye=r.object({name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),arguments:r.optional(r.array(hye))}).loose(),yye=Hk.extend({prompts:r.array(gye)}),_ye=r.object({role:r.union([r.literal("user"),r.literal("assistant")]),content:r.union([Z6,H6,K6])}).loose(),vye=Za.extend({description:r.optional(r.string()),messages:r.array(_ye)}),bye=D_.extend({message:r.string(),requestedSchema:r.unknown()}),D6=B6.extend({method:r.literal("elicitation/create"),params:bye}),xye=Za.extend({action:r.union([r.literal("accept"),r.literal("decline"),r.literal("cancel")]),content:r.optional(r.record(r.string(),r.unknown()))}),U_="2.0",wye=r.object({jsonrpc:r.literal(U_),id:r.union([r.string(),r.number().int()])}).merge(B6).strict(),Tye=r.object({jsonrpc:r.literal(U_),id:r.union([r.string(),r.number().int()]),result:Za}).strict(),Sye=r.object({jsonrpc:r.literal(U_),id:r.union([r.string(),r.number().int()]),error:r.object({code:r.number().int(),message:r.string(),data:r.optional(r.unknown())})}).strict(),Iye=r.object({jsonrpc:r.literal(U_)}).merge(r.object({method:r.string(),params:r.optional(D_)})).strict(),Pm=r.union([wye,Iye,Tye,Sye]),X6=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Y6=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"}),kye=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(),Q6=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(),Pye=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(),Eye=Pye.merge(Q6.pick({code_challenge_methods_supported:!0})),Aye=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(),Cye=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(),Oye=r.object({error:r.string(),error_description:r.string().optional(),error_uri:r.string().optional()}),$ye=Cye.merge(Aye),Rye="AI_MCPClientOAuthError",eB=`vercel.ai.error.${Rye}`,zye=Symbol.for(eB),U6,L6,Em=class extends(L6=wt,U6=zye,L6){static{s(this,"MCPClientOAuthError")}constructor({name:e="MCPClientOAuthError",message:t,cause:o}){super({name:e,message:t,cause:o}),this[U6]=!0}static isInstance(e){return wt.hasMarker(e,eB)}},Ru=class extends Em{static{s(this,"ServerError")}};Ru.errorCode="server_error";var $_=class extends Em{static{s(this,"InvalidClientError")}};$_.errorCode="invalid_client";var R_=class extends Em{static{s(this,"InvalidGrantError")}};R_.errorCode="invalid_grant";var z_=class extends Em{static{s(this,"UnauthorizedClientError")}};z_.errorCode="unauthorized_client";var Nye={[Ru.errorCode]:Ru,[$_.errorCode]:$_,[R_.errorCode]:R_,[z_.errorCode]:z_};function jye(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}s(jye,"resourceUrlFromServerUrl");function Mye({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(Mye,"checkResourceAllowed");var N_=class extends Error{static{s(this,"UnauthorizedError")}constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function j_(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(j_,"extractResourceMetadataUrl");function Dye(e,t="",o={}){return t.endsWith("/")&&(t=t.slice(0,-1)),o.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}s(Dye,"buildWellKnownPath");async function Jk(e,t,o=fetch){try{return await o(e,{headers:t})}catch(a){if(a instanceof TypeError)return t?Jk(e,void 0,o):void 0;throw a}}s(Jk,"fetchWithCorsRetry");async function q6(e,t,o=fetch){return await Jk(e,{"MCP-Protocol-Version":t},o)}s(q6,"tryMetadataDiscovery");function Uye(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}s(Uye,"shouldAttemptFallback");async function Lye(e,t,o,a){var n,i;let l=new URL(e),u=(n=a?.protocolVersion)!=null?n:zu,c;if(a?.metadataUrl)c=new URL(a.metadataUrl);else{let p=Dye(t,l.pathname);c=new URL(p,(i=a?.metadataServerUrl)!=null?i:l),c.search=l.search}let d=await q6(c,u,o);if(!a?.metadataUrl&&Uye(d,l.pathname)){let p=new URL(`/.well-known/${t}`,l);d=await q6(p,u,o)}return d}s(Lye,"discoverMetadataWithFallback");async function qye(e,t,o=fetch){let a=await Lye(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 kye.parse(await a.json())}s(qye,"discoverOAuthProtectedResourceMetadata");function Fye(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(Fye,"buildDiscoveryUrls");async function Bye(e,{fetchFn:t=fetch,protocolVersion:o=zu}={}){var a;let n={"MCP-Protocol-Version":o},i=Fye(e);for(let{url:l,type:u}of i){let c=await Jk(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 Q6.parse(await c.json());{let d=Eye.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(Bye,"discoverAuthorizationServerMetadata");async function Vye(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 mm(),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(Vye,"startAuthorization");function tB(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(tB,"selectClientAuthMethod");function rB(e,t,o,a){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":Zye(n,i,o);return;case"client_secret_post":Hye(n,i,a);return;case"none":Jye(n,a);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}s(rB,"applyClientAuthentication");function Zye(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(Zye,"applyBasicAuth");function Hye(e,t,o){o.set("client_id",e),t&&o.set("client_secret",t)}s(Hye,"applyPostAuth");function Jye(e,t){t.set("client_id",e)}s(Jye,"applyPublicAuth");async function Wk(e){let t=e instanceof Response?e.status:void 0,o=e instanceof Response?await e.text():e;try{let a=Oye.parse(JSON.parse(o)),{error:n,error_description:i,error_uri:l}=a,u=Nye[n]||Ru;return new u({message:i||"",cause:l})}catch(a){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${a}. Raw body: ${o}`;return new Ru({message:n})}}s(Wk,"parseErrorResponse");async function Wye(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:[],_=tB(o,y);rB(_,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 Wk(g);return Y6.parse(await g.json())}s(Wye,"exchangeAuthorization");async function Gye(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=tB(o,h);rB(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 Wk(f);return Y6.parse({refresh_token:a,...await f.json()})}s(Gye,"refreshAuthorization");async function Kye(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 Wk(i);return $ye.parse(await i.json())}s(Kye,"registerClient");async function M_(e,t){var o,a;try{return await Zk(e,t)}catch(n){if(n instanceof $_||n instanceof z_)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"all")),await Zk(e,t);if(n instanceof R_)return await((a=e.invalidateCredentials)==null?void 0:a.call(e,"tokens")),await Zk(e,t);throw n}}s(M_,"auth");async function Xye(e,t,o){let a=jye(e);if(t.validateResourceURL)return await t.validateResourceURL(a,o?.resource);if(o){if(!Mye({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(Xye,"selectResourceURL");async function Zk(e,{serverUrl:t,authorizationCode:o,scope:a,resourceMetadataUrl:n,fetchFn:i}){let l,u;try{l=await qye(t,{resourceMetadataUrl:n},i),l.authorization_servers&&l.authorization_servers.length>0&&(u=l.authorization_servers[0])}catch{}u||(u=t);let c=await Xye(t,e,l),d=await Bye(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 Kye(u,{metadata:d,clientMetadata:e.clientMetadata,fetchFn:i});await e.saveClientInformation(y),p=y}if(o!==void 0){let y=await e.codeVerifier(),_=await Wye(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 Gye(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 Em)||y instanceof Ru))throw y}let f=e.state?await e.state():void 0,{authorizationUrl:h,codeVerifier:g}=await Vye(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(Zk,"authInternal");var Yye=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":zu};if(this.authProvider){let o=await this.authProvider.tokens();o?.access_token&&(t.Authorization=`Bearer ${o.access_token}`)}return O_(t,`ai-sdk/${X6}`,C_())}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=j_(p);try{if(await M_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let y=new N_;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=Pm.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=j_(m);try{if(await M_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let h=new N_;(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()}},Qye=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":zu};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 O_(t,`ai-sdk/${X6}`,C_())}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=j_(f);try{if(await M_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new N_}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=>Pm.parse(w)):[Pm.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=Pm.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=j_(d);try{if(await M_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let y=new N_;(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=Pm.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 e_e(e){switch(e.type){case"sse":return new Yye(e);case"http":return new Qye(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(e_e,"createMcpTransport");function t_e(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}s(t_e,"isCustomMcpTransport");var r_e="1.0.0";async function oB(e){let t=new o_e(e);return await t.init(),t}s(oB,"createMCPClient");var o_e=class{static{s(this,"DefaultMCPClient")}constructor({transport:e,name:t="ai-sdk-mcp-client",version:o=r_e,onUncaughtError:a,capabilities:n}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=a,this.clientCapabilities=n??{},t_e(e)?this.transport=e:this.transport=e_e(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:zu,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:iye});if(e===void 0)throw new Et({message:"Server sent invalid initialize result"});if(!rye.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:lye,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:dye,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:cye,options:t})}catch(o){throw o}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:fye,options:t})}catch(o){throw o}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:mye,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:yye,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:vye,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"?N6({description:u,title:m,inputSchema:$u({...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 Vk({value:e.structuredContent,schema:Bk(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 z6({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!==D6)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=D6.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=xye.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 n_e(e,t,o={}){let a=new URL(t);switch(e){case"http":return{type:"http",url:t,headers:o};case"streamable-http":return new A_(a,{requestInit:{headers:o}});case"sse":return{type:"sse",url:t,headers:o};default:throw new Error(`Unsupported MCP protocol type: ${e}`)}}s(n_e,"createTransportConfig");var nB="search_knowledge_base";function a_e(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=as.createToolName(`${u}`);a[d]=c,l&&(n[d]=l)}}return{mcpClients:o,tools:a,keyToAgentTool:n}}s(a_e,"flattenMcpServers");async function i_e(e){let t=[];for(let o of e)try{let a=await oB({transport:n_e(o.protocol,o.serverUrl,jx(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(i_e,"constructMcpServersTools");function s_e(e){return{get(t,o){return sa.sendRequest({method:"GET",url:`${e.server.apiUrl}${t}`,...o?{queryParams:o}:{},authentication:{type:"BEARER_TOKEN",token:e.server.token}})},post(t,o){return sa.sendRequest({method:"POST",url:`${e.server.apiUrl}${t}`,authentication:{type:"BEARER_TOKEN",token:e.server.token},body:o})}}}s(s_e,"createServerApiClient");async function l_e(e,t,o){let a={},n={},i=s_e(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 _N({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[nB]=tp({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 yN({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[nB]=l[0]}let c=await Promise.all(u.map(async d=>{let p=as.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=tp({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),...u_e("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(l_e,"constructKnowledgeBaseTools");async function aB(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 Ns.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 i_e(d),{mcpClients:m,tools:f,keyToAgentTool:h}=a_e(p,d),g=a.filter(S=>S.type==="KNOWLEDGE_BASE"),{tools:y,keyToAgentTool:_}=await l_e(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"?as.createToolName(S.toolName):S.toolName;x[P]=S}Object.assign(x,h),Object.assign(x,_);let w={[ka]:tp({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."),...Ft(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(Ns.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"),!Ft(o)&&!Ft(k)&&!xd(k)?t.setStructuredOutput(k):Ft(o)&&!Ft(k)&&!t.hasTextContent()&&t.addMarkdown(k),{}},"execute")})};return{mcpClients:m,toolKeyToAgentTool:x,tools:{...v,...w}}}s(aB,"constructAgentTools");function u_e(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(u_e,"serializeArrayQuery");var c_e={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})},iB=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:c_e}),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:Ly(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}=qy({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=Aq(t),g=!Ft(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 RS({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(P6,"stringifyRegExpWithFlags");function R6(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}=$6(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}=C6(e.keyType._def,t);return{...c,propertyNames:p}}}return c}s(R6,"parseRecordDef");function Tge(e,t){if(t.mapStrategy==="record")return R6(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(Tge,"parseMapDef");function Sge(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(Sge,"parseNativeEnumDef");function Ige(){return{not:Zo()}}s(Ige,"parseNeverDef");function kge(){return{type:"null"}}s(kge,"parseNullDef");var Lk={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Pge(e,t){let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(a=>a._def.typeName in Lk&&(!a._def.checks||!a._def.checks.length))){let a=o.reduce((n,i)=>{let l=Lk[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 Ege(e,t)}s(Pge,"parseUnionDef");var Ege=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 Age(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Lk[e.innerType._def.typeName],"null"]};let o=Ut(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}s(Age,"parseNullableDef");function Cge(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(Cge,"parseNumberDef");function Oge(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=Rge(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=$ge(e,t);return i!==void 0&&(o.additionalProperties=i),o}s(Oge,"parseObjectDef");function $ge(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($ge,"decideAdditionalProperties");function Rge(e){try{return e.isOptional()}catch{return!0}}s(Rge,"safeIsOptional");var zge=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"),Nge=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 jge(e,t){return Ut(e.type._def,t)}s(jge,"parsePromiseDef");function Mge(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(Mge,"parseSetDef");function Dge(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(Dge,"parseTupleDef");function Uge(){return{not:Zo()}}s(Uge,"parseUndefinedDef");function Lge(){return Zo()}s(Lge,"parseUnknownDef");var qge=s((e,t)=>Ut(e.innerType._def,t),"parseReadonlyDef"),Fge=s((e,t,o)=>{switch(t){case U.ZodString:return $6(e,o);case U.ZodNumber:return Cge(e);case U.ZodObject:return Oge(e,o);case U.ZodBigInt:return dge(e);case U.ZodBoolean:return pge();case U.ZodDate:return O6(e,o);case U.ZodUndefined:return Uge();case U.ZodNull:return kge();case U.ZodArray:return cge(e,o);case U.ZodUnion:case U.ZodDiscriminatedUnion:return Pge(e,o);case U.ZodIntersection:return vge(e,o);case U.ZodTuple:return Dge(e,o);case U.ZodRecord:return R6(e,o);case U.ZodLiteral:return bge(e);case U.ZodEnum:return yge(e);case U.ZodNativeEnum:return Sge(e);case U.ZodNullable:return Age(e,o);case U.ZodOptional:return zge(e,o);case U.ZodMap:return Tge(e,o);case U.ZodSet:return Mge(e,o);case U.ZodLazy:return()=>e.getter()._def;case U.ZodPromise:return jge(e,o);case U.ZodNaN:case U.ZodNever:return Ige();case U.ZodEffects:return gge(e,o);case U.ZodAny:return Zo();case U.ZodUnknown:return Lge();case U.ZodDefault:return hge(e,o);case U.ZodBranded:return C6(e,o);case U.ZodReadonly:return qge(e,o);case U.ZodCatch:return mge(e,o);case U.ZodPipeline:return Nge(e,o);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(a=>{})(t)}},"selectParser"),Bge=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!==lge)return c}if(n&&!o){let c=Vge(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=Fge(e,e.typeName,t),u=typeof l=="function"?Ut(l(),t):l;if(u&&Zge(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 Vge=s((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Bge(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"),Zge=s((e,t,o)=>(e.description&&(o.description=e.description),o),"addMeta"),Hge=s(e=>{let t=uge(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"),Jge=s((e,t)=>{var o;let a=Hge(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"),qk=Symbol.for("vercel.ai.schema");function $u(e,{validate:t}={}){return{[qk]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}s($u,"jsonSchema");function Wge(e){return typeof e=="object"&&e!==null&&qk in e&&e[qk]===!0&&"jsonSchema"in e&&"validate"in e}s(Wge,"isSchema");function Bk(e){return e==null?$u({properties:{},additionalProperties:!1}):Wge(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?Qge(e):Gge(e):e()}s(Bk,"asSchema");function Gge(e){return $u(()=>Fk(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 Ou({value:t,cause:o.issues})}},"validate")})}s(Gge,"standardSchema");function Kge(e,t){var o;let a=(o=t?.useReferences)!=null?o:!1;return $u(()=>Jge(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(Kge,"zod3Schema");function Xge(e,t){var o;let a=(o=t?.useReferences)!=null?o:!1;return $u(()=>Fk(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(Xge,"zod4Schema");function Yge(e){return"_zod"in e}s(Yge,"isZod4Schema");function Qge(e,t){return Yge(e)?Xge(e,t):Kge(e,t)}s(Qge,"zodSchema");async function Vk({value:e,schema:t}){let o=Bk(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:Ou.wrap({value:e,cause:a.error}),rawValue:e}}catch(a){return{success:!1,error:Ou.wrap({value:e,cause:a}),rawValue:e}}}s(Vk,"safeValidateTypes");async function z6({text:e,schema:t}){try{let o=sge(e);return t==null?{success:!0,value:o,rawValue:o}:await Vk({value:o,schema:t})}catch(o){return{success:!1,error:Mk.isInstance(o)?o:new Mk({text:e,cause:o}),rawValue:void 0}}}s(z6,"safeParseJSON");function N6(e){return{...e,type:"dynamic"}}s(N6,"dynamicTool");var eye="AI_MCPClientError",F6=`vercel.ai.error.${eye}`,tye=Symbol.for(F6),j6,M6,Et=class extends(M6=wt,j6=tye,M6){static{s(this,"MCPClientError")}constructor({name:e="MCPClientError",message:t,cause:o,data:a,code:n}){super({name:e,message:t,cause:o}),this[j6]=!0,this.data=a,this.code=n}static isInstance(e){return wt.hasMarker(e,F6)}},zu="2025-06-18",rye=[zu,"2025-03-26","2024-11-05"],oye=r.optional(r.record(r.string(),r.unknown())),nye=r.looseObject({name:r.string(),version:r.string()}),D_=r.looseObject({_meta:r.optional(r.object({}).loose())}),Za=D_,B6=r.object({method:r.string(),params:r.optional(D_)}),V6=r.object({applyDefaults:r.optional(r.boolean())}).loose(),aye=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(V6)}),tHe=r.object({elicitation:r.optional(V6)}).loose(),iye=Za.extend({protocolVersion:r.string(),capabilities:aye,serverInfo:nye,instructions:r.optional(r.string())}),Hk=Za.extend({nextCursor:r.optional(r.string())}),sye=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:oye}).loose(),lye=Hk.extend({tools:r.array(sye)}),Z6=r.object({type:r.literal("text"),text:r.string()}).loose(),H6=r.object({type:r.literal("image"),data:r.base64(),mimeType:r.string()}).loose(),uye=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(),cye=Hk.extend({resources:r.array(uye)}),J6=r.object({uri:r.string(),name:r.optional(r.string()),title:r.optional(r.string()),mimeType:r.optional(r.string())}).loose(),W6=J6.extend({text:r.string()}),G6=J6.extend({blob:r.base64()}),K6=r.object({type:r.literal("resource"),resource:r.union([W6,G6])}).loose(),dye=Za.extend({content:r.array(r.union([Z6,H6,K6])),structuredContent:r.optional(r.unknown()),isError:r.boolean().default(!1).optional()}).or(Za.extend({toolResult:r.unknown()})),pye=r.object({uriTemplate:r.string(),name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),mimeType:r.optional(r.string())}).loose(),mye=Za.extend({resourceTemplates:r.array(pye)}),fye=Za.extend({contents:r.array(r.union([W6,G6]))}),hye=r.object({name:r.string(),description:r.optional(r.string()),required:r.optional(r.boolean())}).loose(),gye=r.object({name:r.string(),title:r.optional(r.string()),description:r.optional(r.string()),arguments:r.optional(r.array(hye))}).loose(),yye=Hk.extend({prompts:r.array(gye)}),_ye=r.object({role:r.union([r.literal("user"),r.literal("assistant")]),content:r.union([Z6,H6,K6])}).loose(),vye=Za.extend({description:r.optional(r.string()),messages:r.array(_ye)}),bye=D_.extend({message:r.string(),requestedSchema:r.unknown()}),D6=B6.extend({method:r.literal("elicitation/create"),params:bye}),xye=Za.extend({action:r.union([r.literal("accept"),r.literal("decline"),r.literal("cancel")]),content:r.optional(r.record(r.string(),r.unknown()))}),U_="2.0",wye=r.object({jsonrpc:r.literal(U_),id:r.union([r.string(),r.number().int()])}).merge(B6).strict(),Tye=r.object({jsonrpc:r.literal(U_),id:r.union([r.string(),r.number().int()]),result:Za}).strict(),Sye=r.object({jsonrpc:r.literal(U_),id:r.union([r.string(),r.number().int()]),error:r.object({code:r.number().int(),message:r.string(),data:r.optional(r.unknown())})}).strict(),Iye=r.object({jsonrpc:r.literal(U_)}).merge(r.object({method:r.string(),params:r.optional(D_)})).strict(),Pm=r.union([wye,Iye,Tye,Sye]),X6=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Y6=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"}),kye=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(),Q6=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(),Pye=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(),Eye=Pye.merge(Q6.pick({code_challenge_methods_supported:!0})),Aye=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(),Cye=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(),Oye=r.object({error:r.string(),error_description:r.string().optional(),error_uri:r.string().optional()}),$ye=Cye.merge(Aye),Rye="AI_MCPClientOAuthError",eB=`vercel.ai.error.${Rye}`,zye=Symbol.for(eB),U6,L6,Em=class extends(L6=wt,U6=zye,L6){static{s(this,"MCPClientOAuthError")}constructor({name:e="MCPClientOAuthError",message:t,cause:o}){super({name:e,message:t,cause:o}),this[U6]=!0}static isInstance(e){return wt.hasMarker(e,eB)}},Ru=class extends Em{static{s(this,"ServerError")}};Ru.errorCode="server_error";var $_=class extends Em{static{s(this,"InvalidClientError")}};$_.errorCode="invalid_client";var R_=class extends Em{static{s(this,"InvalidGrantError")}};R_.errorCode="invalid_grant";var z_=class extends Em{static{s(this,"UnauthorizedClientError")}};z_.errorCode="unauthorized_client";var Nye={[Ru.errorCode]:Ru,[$_.errorCode]:$_,[R_.errorCode]:R_,[z_.errorCode]:z_};function jye(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}s(jye,"resourceUrlFromServerUrl");function Mye({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(Mye,"checkResourceAllowed");var N_=class extends Error{static{s(this,"UnauthorizedError")}constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function j_(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(j_,"extractResourceMetadataUrl");function Dye(e,t="",o={}){return t.endsWith("/")&&(t=t.slice(0,-1)),o.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}s(Dye,"buildWellKnownPath");async function Jk(e,t,o=fetch){try{return await o(e,{headers:t})}catch(a){if(a instanceof TypeError)return t?Jk(e,void 0,o):void 0;throw a}}s(Jk,"fetchWithCorsRetry");async function q6(e,t,o=fetch){return await Jk(e,{"MCP-Protocol-Version":t},o)}s(q6,"tryMetadataDiscovery");function Uye(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}s(Uye,"shouldAttemptFallback");async function Lye(e,t,o,a){var n,i;let l=new URL(e),u=(n=a?.protocolVersion)!=null?n:zu,c;if(a?.metadataUrl)c=new URL(a.metadataUrl);else{let p=Dye(t,l.pathname);c=new URL(p,(i=a?.metadataServerUrl)!=null?i:l),c.search=l.search}let d=await q6(c,u,o);if(!a?.metadataUrl&&Uye(d,l.pathname)){let p=new URL(`/.well-known/${t}`,l);d=await q6(p,u,o)}return d}s(Lye,"discoverMetadataWithFallback");async function qye(e,t,o=fetch){let a=await Lye(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 kye.parse(await a.json())}s(qye,"discoverOAuthProtectedResourceMetadata");function Fye(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(Fye,"buildDiscoveryUrls");async function Bye(e,{fetchFn:t=fetch,protocolVersion:o=zu}={}){var a;let n={"MCP-Protocol-Version":o},i=Fye(e);for(let{url:l,type:u}of i){let c=await Jk(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 Q6.parse(await c.json());{let d=Eye.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(Bye,"discoverAuthorizationServerMetadata");async function Vye(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 mm(),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(Vye,"startAuthorization");function tB(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(tB,"selectClientAuthMethod");function rB(e,t,o,a){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":Zye(n,i,o);return;case"client_secret_post":Hye(n,i,a);return;case"none":Jye(n,a);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}s(rB,"applyClientAuthentication");function Zye(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(Zye,"applyBasicAuth");function Hye(e,t,o){o.set("client_id",e),t&&o.set("client_secret",t)}s(Hye,"applyPostAuth");function Jye(e,t){t.set("client_id",e)}s(Jye,"applyPublicAuth");async function Wk(e){let t=e instanceof Response?e.status:void 0,o=e instanceof Response?await e.text():e;try{let a=Oye.parse(JSON.parse(o)),{error:n,error_description:i,error_uri:l}=a,u=Nye[n]||Ru;return new u({message:i||"",cause:l})}catch(a){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${a}. Raw body: ${o}`;return new Ru({message:n})}}s(Wk,"parseErrorResponse");async function Wye(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:[],_=tB(o,y);rB(_,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 Wk(g);return Y6.parse(await g.json())}s(Wye,"exchangeAuthorization");async function Gye(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=tB(o,h);rB(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 Wk(f);return Y6.parse({refresh_token:a,...await f.json()})}s(Gye,"refreshAuthorization");async function Kye(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 Wk(i);return $ye.parse(await i.json())}s(Kye,"registerClient");async function M_(e,t){var o,a;try{return await Zk(e,t)}catch(n){if(n instanceof $_||n instanceof z_)return await((o=e.invalidateCredentials)==null?void 0:o.call(e,"all")),await Zk(e,t);if(n instanceof R_)return await((a=e.invalidateCredentials)==null?void 0:a.call(e,"tokens")),await Zk(e,t);throw n}}s(M_,"auth");async function Xye(e,t,o){let a=jye(e);if(t.validateResourceURL)return await t.validateResourceURL(a,o?.resource);if(o){if(!Mye({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(Xye,"selectResourceURL");async function Zk(e,{serverUrl:t,authorizationCode:o,scope:a,resourceMetadataUrl:n,fetchFn:i}){let l,u;try{l=await qye(t,{resourceMetadataUrl:n},i),l.authorization_servers&&l.authorization_servers.length>0&&(u=l.authorization_servers[0])}catch{}u||(u=t);let c=await Xye(t,e,l),d=await Bye(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 Kye(u,{metadata:d,clientMetadata:e.clientMetadata,fetchFn:i});await e.saveClientInformation(y),p=y}if(o!==void 0){let y=await e.codeVerifier(),_=await Wye(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 Gye(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 Em)||y instanceof Ru))throw y}let f=e.state?await e.state():void 0,{authorizationUrl:h,codeVerifier:g}=await Vye(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(Zk,"authInternal");var Yye=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":zu};if(this.authProvider){let o=await this.authProvider.tokens();o?.access_token&&(t.Authorization=`Bearer ${o.access_token}`)}return O_(t,`ai-sdk/${X6}`,C_())}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=j_(p);try{if(await M_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let y=new N_;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=Pm.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=j_(m);try{if(await M_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let h=new N_;(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()}},Qye=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":zu};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 O_(t,`ai-sdk/${X6}`,C_())}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=j_(f);try{if(await M_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new N_}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=>Pm.parse(w)):[Pm.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=Pm.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=j_(d);try{if(await M_(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){let y=new N_;(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=Pm.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 e_e(e){switch(e.type){case"sse":return new Yye(e);case"http":return new Qye(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(e_e,"createMcpTransport");function t_e(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}s(t_e,"isCustomMcpTransport");var r_e="1.0.0";async function oB(e){let t=new o_e(e);return await t.init(),t}s(oB,"createMCPClient");var o_e=class{static{s(this,"DefaultMCPClient")}constructor({transport:e,name:t="ai-sdk-mcp-client",version:o=r_e,onUncaughtError:a,capabilities:n}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=a,this.clientCapabilities=n??{},t_e(e)?this.transport=e:this.transport=e_e(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:zu,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:iye});if(e===void 0)throw new Et({message:"Server sent invalid initialize result"});if(!rye.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:lye,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:dye,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:cye,options:t})}catch(o){throw o}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:fye,options:t})}catch(o){throw o}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:mye,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:yye,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:vye,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"?N6({description:u,title:m,inputSchema:$u({...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 Vk({value:e.structuredContent,schema:Bk(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 z6({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!==D6)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=D6.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=xye.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 n_e(e,t,o={}){let a=new URL(t);switch(e){case"http":return{type:"http",url:t,headers:o};case"streamable-http":return new A_(a,{requestInit:{headers:o}});case"sse":return{type:"sse",url:t,headers:o};default:throw new Error(`Unsupported MCP protocol type: ${e}`)}}s(n_e,"createTransportConfig");var nB="search_knowledge_base";function a_e(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=as.createToolName(`${u}`);a[d]=c,l&&(n[d]=l)}}return{mcpClients:o,tools:a,keyToAgentTool:n}}s(a_e,"flattenMcpServers");async function i_e(e){let t=[];for(let o of e)try{let a=await oB({transport:n_e(o.protocol,o.serverUrl,jx(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(i_e,"constructMcpServersTools");function s_e(e){return{get(t,o){return sa.sendRequest({method:"GET",url:`${e.server.apiUrl}${t}`,...o?{queryParams:o}:{},authentication:{type:"BEARER_TOKEN",token:e.server.token}})},post(t,o){return sa.sendRequest({method:"POST",url:`${e.server.apiUrl}${t}`,authentication:{type:"BEARER_TOKEN",token:e.server.token},body:o})}}}s(s_e,"createServerApiClient");async function l_e(e,t,o){let a={},n={},i=s_e(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 _N({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[nB]=tp({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 yN({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[nB]=l[0]}let c=await Promise.all(u.map(async d=>{let p=as.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=tp({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),...u_e("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(l_e,"constructKnowledgeBaseTools");async function aB(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 Ns.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 i_e(d),{mcpClients:m,tools:f,keyToAgentTool:h}=a_e(p,d),g=a.filter(S=>S.type==="KNOWLEDGE_BASE"),{tools:y,keyToAgentTool:_}=await l_e(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"?as.createToolName(S.toolName):S.toolName;x[P]=S}Object.assign(x,h),Object.assign(x,_);let w={[ka]:tp({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."),...Ft(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(Ns.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"),!Ft(o)&&!Ft(k)&&!xd(k)?t.setStructuredOutput(k):Ft(o)&&!Ft(k)&&!t.hasTextContent()&&t.addMarkdown(k),{}},"execute")})};return{mcpClients:m,toolKeyToAgentTool:x,tools:{...v,...w}}}s(aB,"constructAgentTools");function u_e(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(u_e,"serializeArrayQuery");var c_e={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})},iB=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.",aiMetadata:{description:"Runs an agent loop where the model reasons over your prompt and calls the tools you attach (piece actions, sub-flows, MCP servers, knowledge bases, optional web search), iterating until the task completes or Max Steps is reached. Pick it when the work needs tool use or an unknown number of steps; prefer askAi for a single prompt-in/answer-out call, or classifyText and extractStructuredData for one narrow analysis. Requires a prompt, an AI Model and a Max Steps cap; not idempotent, as the agent performs side effects through its tools.",idempotent:!1},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:c_e}),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:Ly(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}=qy({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=Aq(t),g=!Ft(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 RS({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