// @bun
import{Cu as yZ,Eu as R,Ju as u,Ku as U,Lu as B,Mu as hZ,Nu as G,Qu as fZ,Ut as O,_t as g,mu as vZ,nu as y,ru as h,tu as L,wu as V,yu as f}from"./chunk-m9a3r7rv.js";import{Tu as v}from"./chunk-qze335a6.js";import{Iv as Z}from"./chunk-0dcnzv90.js";import{LG as kZ,MG as _}from"./chunk-xyhgvt88.js";var s=_((G4,t)=>{var{defineProperty:l,getOwnPropertyDescriptor:sZ,getOwnPropertyNames:aZ}=Object,oZ=Object.prototype.hasOwnProperty,rZ=($,W)=>{for(var j in W)l($,j,{get:W[j],enumerable:!0})},eZ=($,W,j,Q)=>{if(W&&typeof W==="object"||typeof W==="function"){for(let X of aZ(W))if(!oZ.call($,X)&&X!==j)l($,X,{get:()=>W[X],enumerable:!(Q=sZ(W,X))||Q.enumerable})}return $},Z0=($)=>eZ(l({},"__esModule",{value:!0}),$),d={};rZ(d,{SYMBOL_FOR_REQ_CONTEXT:()=>n,getContext:()=>$0});t.exports=Z0(d);var n=Symbol.for("@vercel/request-context");function $0(){return globalThis[n]?.get?.()??{}}});var ZZ=_((z4,e)=>{var{defineProperty:c,getOwnPropertyDescriptor:W0,getOwnPropertyNames:j0}=Object,Q0=Object.prototype.hasOwnProperty,X0=($,W)=>{for(var j in W)c($,j,{get:W[j],enumerable:!0})},Y0=($,W,j,Q)=>{if(W&&typeof W==="object"||typeof W==="function"){for(let X of j0(W))if(!Q0.call($,X)&&X!==j)c($,X,{get:()=>W[X],enumerable:!(Q=W0(W,X))||Q.enumerable})}return $},D0=($)=>Y0(c({},"__esModule",{value:!0}),$),a={};X0(a,{AccessTokenMissingError:()=>o,RefreshAccessTokenFailedError:()=>r});e.exports=D0(a);class o extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login).");this.name="AccessTokenMissingError"}}class r extends Error{constructor($){super("Failed to refresh authentication token.",{cause:$});this.name="RefreshAccessTokenFailedError"}}});var p=_((H4,jZ)=>{var{defineProperty:m,getOwnPropertyDescriptor:K0,getOwnPropertyNames:J0}=Object,F0=Object.prototype.hasOwnProperty,N0=($,W)=>{for(var j in W)m($,j,{get:W[j],enumerable:!0})},A0=($,W,j,Q)=>{if(W&&typeof W==="object"||typeof W==="function"){for(let X of J0(W))if(!F0.call($,X)&&X!==j)m($,X,{get:()=>W[X],enumerable:!(Q=K0(W,X))||Q.enumerable})}return $},U0=($)=>A0(m({},"__esModule",{value:!0}),$),WZ={};N0(WZ,{AccessTokenMissingError:()=>$Z.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>$Z.RefreshAccessTokenFailedError,getContext:()=>L0.getContext,getVercelOidcToken:()=>V0,getVercelOidcTokenSync:()=>q0,getVercelToken:()=>T0});jZ.exports=U0(WZ);var L0=s(),$Z=ZZ();async function V0(){return""}function q0(){return""}async function T0(){throw Error("getVercelToken is not supported in browser environments")}});var x4=Z;var nZ=kZ(p(),1),tZ=kZ(p(),1);var B0="vercel.ai.gateway.error",i=Symbol.for(B0),QZ,XZ,z=class $ extends(XZ=Error,QZ=i,XZ){constructor({message:W,statusCode:j=500,cause:Q,generationId:X}){super(X?`${W} [${X}]`:W);this[QZ]=!0,this.statusCode=j,this.cause=Q,this.generationId=X}static isInstance(W){return $.hasMarker(W)}static hasMarker(W){return typeof W==="object"&&W!==null&&i in W&&W[i]===!0}},gZ="GatewayAuthenticationError",x0=`vercel.ai.gateway.error.${gZ}`,YZ=Symbol.for(x0),DZ,KZ,uZ=class $ extends(KZ=z,DZ=YZ,KZ){constructor({message:W="Authentication failed",statusCode:j=401,cause:Q,generationId:X}={}){super({message:W,statusCode:j,cause:Q,generationId:X});this[DZ]=!0,this.name=gZ,this.type="authentication_error"}static isInstance(W){return z.hasMarker(W)&&YZ in W}static createContextualError({apiKeyProvided:W,oidcTokenProvided:j,message:Q="Authentication failed",statusCode:X=401,cause:D,generationId:A}){let Y;if(W)Y=`AI Gateway authentication failed: Invalid API key.

Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys

Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;else if(j)Y=`AI Gateway authentication failed: Invalid OIDC token.

Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.

Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`;else Y=`AI Gateway authentication failed: No authentication provided.

Option 1 - API key:
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.

Option 2 - OIDC token:
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;return new $({message:Y,statusCode:X,cause:D,generationId:A})}},_Z="GatewayInvalidRequestError",G0=`vercel.ai.gateway.error.${_Z}`,JZ=Symbol.for(G0),FZ,NZ,z0=class extends(NZ=z,FZ=JZ,NZ){constructor({message:$="Invalid request",statusCode:W=400,cause:j,generationId:Q}={}){super({message:$,statusCode:W,cause:j,generationId:Q});this[FZ]=!0,this.name=_Z,this.type="invalid_request_error"}static isInstance($){return z.hasMarker($)&&JZ in $}},lZ="GatewayRateLimitError",H0=`vercel.ai.gateway.error.${lZ}`,AZ=Symbol.for(H0),UZ,LZ,M0=class extends(LZ=z,UZ=AZ,LZ){constructor({message:$="Rate limit exceeded",statusCode:W=429,cause:j,generationId:Q}={}){super({message:$,statusCode:W,cause:j,generationId:Q});this[UZ]=!0,this.name=lZ,this.type="rate_limit_exceeded"}static isInstance($){return z.hasMarker($)&&AZ in $}},cZ="GatewayModelNotFoundError",E0=`vercel.ai.gateway.error.${cZ}`,VZ=Symbol.for(E0),O0=L(()=>V(Z.object({modelId:Z.string()}))),qZ,TZ,R0=class extends(TZ=z,qZ=VZ,TZ){constructor({message:$="Model not found",statusCode:W=404,modelId:j,cause:Q,generationId:X}={}){super({message:$,statusCode:W,cause:Q,generationId:X});this[qZ]=!0,this.name=cZ,this.type="model_not_found",this.modelId=j}static isInstance($){return z.hasMarker($)&&VZ in $}},mZ="GatewayInternalServerError",P0=`vercel.ai.gateway.error.${mZ}`,BZ=Symbol.for(P0),xZ,GZ,zZ=class extends(GZ=z,xZ=BZ,GZ){constructor({message:$="Internal server error",statusCode:W=500,cause:j,generationId:Q}={}){super({message:$,statusCode:W,cause:j,generationId:Q});this[xZ]=!0,this.name=mZ,this.type="internal_server_error"}static isInstance($){return z.hasMarker($)&&BZ in $}},pZ="GatewayResponseError",S0=`vercel.ai.gateway.error.${pZ}`,HZ=Symbol.for(S0),MZ,EZ,C0=class extends(EZ=z,MZ=HZ,EZ){constructor({message:$="Invalid response from Gateway",statusCode:W=502,response:j,validationError:Q,cause:X,generationId:D}={}){super({message:$,statusCode:W,cause:X,generationId:D});this[MZ]=!0,this.name=pZ,this.type="response_error",this.response=j,this.validationError=Q}static isInstance($){return z.hasMarker($)&&HZ in $}};async function OZ({response:$,statusCode:W,defaultMessage:j="Gateway request failed",cause:Q,authMethod:X}){var D;let A=await f({value:$,schema:w0});if(!A.success){let H=typeof $==="object"&&$!==null&&"generationId"in $?$.generationId:void 0;return new C0({message:`Invalid error response format: ${j}`,statusCode:W,response:$,validationError:A.error,cause:Q,generationId:H})}let Y=A.value,K=Y.error.type,N=Y.error.message,q=(D=Y.generationId)!=null?D:void 0;switch(K){case"authentication_error":return uZ.createContextualError({apiKeyProvided:X==="api-key",oidcTokenProvided:X==="oidc",statusCode:W,cause:Q,generationId:q});case"invalid_request_error":return new z0({message:N,statusCode:W,cause:Q,generationId:q});case"rate_limit_exceeded":return new M0({message:N,statusCode:W,cause:Q,generationId:q});case"model_not_found":{let H=await f({value:Y.error.param,schema:O0});return new R0({message:N,statusCode:W,modelId:H.success?H.value.modelId:void 0,cause:Q,generationId:q})}case"internal_server_error":return new zZ({message:N,statusCode:W,cause:Q,generationId:q});default:return new zZ({message:N,statusCode:W,cause:Q,generationId:q})}}var w0=L(()=>V(Z.object({error:Z.object({message:Z.string(),type:Z.string().nullish(),param:Z.unknown().nullish(),code:Z.union([Z.string(),Z.number()]).nullish()}),generationId:Z.string().nullish()}))),iZ="GatewayTimeoutError",b0=`vercel.ai.gateway.error.${iZ}`,RZ=Symbol.for(b0),PZ,SZ,CZ=class $ extends(SZ=z,PZ=RZ,SZ){constructor({message:W="Request timed out",statusCode:j=408,cause:Q,generationId:X}={}){super({message:W,statusCode:j,cause:Q,generationId:X});this[PZ]=!0,this.name=iZ,this.type="timeout_error"}static isInstance(W){return z.hasMarker(W)&&RZ in W}static createTimeoutError({originalMessage:W,statusCode:j=408,cause:Q,generationId:X}){let D=`Gateway request timed out: ${W}

    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 $({message:D,statusCode:j,cause:Q,generationId:X})}};function wZ($){if(!($ instanceof Error))return!1;let W=$.code;if(typeof W==="string")return["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(W);return!1}async function M($,W){var j;if(z.isInstance($))return $;if(wZ($))return CZ.createTimeoutError({originalMessage:$ instanceof Error?$.message:"Unknown error",cause:$});if(v.isInstance($)){if($.cause&&wZ($.cause))return CZ.createTimeoutError({originalMessage:$.message,cause:$});return await OZ({response:I0($),statusCode:(j=$.statusCode)!=null?j:500,defaultMessage:"Gateway request failed",cause:$,authMethod:W})}return await OZ({response:{},statusCode:500,defaultMessage:$ instanceof Error?`Gateway request failed: ${$.message}`:"Unknown Gateway error",cause:$,authMethod:W})}function I0($){if($.data!==void 0)return $.data;if($.responseBody!=null)try{return JSON.parse($.responseBody)}catch(W){return $.responseBody}return{}}var dZ="ai-gateway-auth-method";async function C($){let W=await f({value:$[dZ],schema:k0});return W.success?W.value:void 0}var k0=L(()=>V(Z.union([Z.literal("api-key"),Z.literal("oidc")]))),v0=["embedding","image","language","reranking","video"],bZ=class{constructor($){this.config=$}async getAvailableModels(){try{let{value:$}=await y({url:`${this.config.baseURL}/config`,headers:await U(this.config.headers()),successfulResponseHandler:G(y0),failedResponseHandler:B({errorSchema:Z.any(),errorToMessage:(W)=>W}),fetch:this.config.fetch});return $}catch($){throw await M($)}}async getCredits(){try{let $=new URL(this.config.baseURL),{value:W}=await y({url:`${$.origin}/v1/credits`,headers:await U(this.config.headers()),successfulResponseHandler:G(h0),failedResponseHandler:B({errorSchema:Z.any(),errorToMessage:(j)=>j}),fetch:this.config.fetch});return W}catch($){throw await M($)}}},y0=L(()=>V(Z.object({models:Z.array(Z.object({id:Z.string(),name:Z.string(),description:Z.string().nullish(),pricing:Z.object({input:Z.string(),output:Z.string(),input_cache_read:Z.string().nullish(),input_cache_write:Z.string().nullish()}).transform(({input:$,output:W,input_cache_read:j,input_cache_write:Q})=>({input:$,output:W,...j?{cachedInputTokens:j}:{},...Q?{cacheCreationInputTokens:Q}:{}})).nullish(),specification:Z.object({specificationVersion:Z.literal("v3"),provider:Z.string(),modelId:Z.string()}),modelType:Z.string().nullish()})).transform(($)=>$.filter((W)=>W.modelType==null||v0.includes(W.modelType)))}))),h0=L(()=>V(Z.object({balance:Z.string(),total_used:Z.string()}).transform(({balance:$,total_used:W})=>({balance:$,totalUsed:W})))),f0=class{constructor($){this.config=$}async getSpendReport($){try{let W=new URL(this.config.baseURL),j=new URLSearchParams;if(j.set("start_date",$.startDate),j.set("end_date",$.endDate),$.groupBy)j.set("group_by",$.groupBy);if($.datePart)j.set("date_part",$.datePart);if($.userId)j.set("user_id",$.userId);if($.model)j.set("model",$.model);if($.provider)j.set("provider",$.provider);if($.credentialType)j.set("credential_type",$.credentialType);if($.tags&&$.tags.length>0)j.set("tags",$.tags.join(","));let{value:Q}=await y({url:`${W.origin}/v1/report?${j.toString()}`,headers:await U(this.config.headers()),successfulResponseHandler:G(g0),failedResponseHandler:B({errorSchema:Z.any(),errorToMessage:(X)=>X}),fetch:this.config.fetch});return Q}catch(W){throw await M(W)}}},g0=L(()=>V(Z.object({results:Z.array(Z.object({day:Z.string().optional(),hour:Z.string().optional(),user:Z.string().optional(),model:Z.string().optional(),tag:Z.string().optional(),provider:Z.string().optional(),credential_type:Z.enum(["byok","system"]).optional(),total_cost:Z.number(),market_cost:Z.number().optional(),input_tokens:Z.number().optional(),output_tokens:Z.number().optional(),cached_input_tokens:Z.number().optional(),cache_creation_input_tokens:Z.number().optional(),reasoning_tokens:Z.number().optional(),request_count:Z.number().optional()}).transform(({credential_type:$,total_cost:W,market_cost:j,input_tokens:Q,output_tokens:X,cached_input_tokens:D,cache_creation_input_tokens:A,reasoning_tokens:Y,request_count:K,...N})=>({...N,...$!==void 0?{credentialType:$}:{},totalCost:W,...j!==void 0?{marketCost:j}:{},...Q!==void 0?{inputTokens:Q}:{},...X!==void 0?{outputTokens:X}:{},...D!==void 0?{cachedInputTokens:D}:{},...A!==void 0?{cacheCreationInputTokens:A}:{},...Y!==void 0?{reasoningTokens:Y}:{},...K!==void 0?{requestCount:K}:{}})))}))),u0=class{constructor($){this.config=$}async getGenerationInfo($){try{let W=new URL(this.config.baseURL),{value:j}=await y({url:`${W.origin}/v1/generation?id=${encodeURIComponent($.id)}`,headers:await U(this.config.headers()),successfulResponseHandler:G(_0),failedResponseHandler:B({errorSchema:Z.any(),errorToMessage:(Q)=>Q}),fetch:this.config.fetch});return j}catch(W){throw await M(W)}}},_0=L(()=>V(Z.object({data:Z.object({id:Z.string(),total_cost:Z.number(),upstream_inference_cost:Z.number(),usage:Z.number(),created_at:Z.string(),model:Z.string(),is_byok:Z.boolean(),provider_name:Z.string(),streamed:Z.boolean(),finish_reason:Z.string(),latency:Z.number(),generation_time:Z.number(),native_tokens_prompt:Z.number(),native_tokens_completion:Z.number(),native_tokens_reasoning:Z.number(),native_tokens_cached:Z.number(),native_tokens_cache_creation:Z.number(),billable_web_search_calls:Z.number()}).transform(({total_cost:$,upstream_inference_cost:W,created_at:j,is_byok:Q,provider_name:X,finish_reason:D,generation_time:A,native_tokens_prompt:Y,native_tokens_completion:K,native_tokens_reasoning:N,native_tokens_cached:q,native_tokens_cache_creation:H,billable_web_search_calls:w,...P})=>({...P,totalCost:$,upstreamInferenceCost:W,createdAt:j,isByok:Q,providerName:X,finishReason:D,generationTime:A,promptTokens:Y,completionTokens:K,reasoningTokens:N,cachedTokens:q,cacheCreationTokens:H,billableWebSearchCalls:w}))}).transform(({data:$})=>$))),l0=class{constructor($,W){this.modelId=$,this.config=W,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs($){let{abortSignal:W,...j}=$;return{args:this.maybeEncodeFileParts(j),warnings:[]}}async doGenerate($){let{args:W,warnings:j}=await this.getArgs($),{abortSignal:Q}=$,X=await U(this.config.headers());try{let{responseHeaders:D,value:A,rawValue:Y}=await R({url:this.getUrl(),headers:O(X,$.headers,this.getModelConfigHeaders(this.modelId,!1),await U(this.config.o11yHeaders)),body:W,successfulResponseHandler:G(Z.any()),failedResponseHandler:B({errorSchema:Z.any(),errorToMessage:(K)=>K}),...Q&&{abortSignal:Q},fetch:this.config.fetch});return{...A,request:{body:W},response:{headers:D,body:Y},warnings:j}}catch(D){throw await M(D,await C(X))}}async doStream($){let{args:W,warnings:j}=await this.getArgs($),{abortSignal:Q}=$,X=await U(this.config.headers());try{let{value:D,responseHeaders:A}=await R({url:this.getUrl(),headers:O(X,$.headers,this.getModelConfigHeaders(this.modelId,!0),await U(this.config.o11yHeaders)),body:W,successfulResponseHandler:hZ(Z.any()),failedResponseHandler:B({errorSchema:Z.any(),errorToMessage:(Y)=>Y}),...Q&&{abortSignal:Q},fetch:this.config.fetch});return{stream:D.pipeThrough(new TransformStream({start(Y){if(j.length>0)Y.enqueue({type:"stream-start",warnings:j})},transform(Y,K){if(Y.success){let N=Y.value;if(N.type==="raw"&&!$.includeRawChunks)return;if(N.type==="response-metadata"&&N.timestamp&&typeof N.timestamp==="string")N.timestamp=new Date(N.timestamp);K.enqueue(N)}else K.error(Y.error)}})),request:{body:W},response:{headers:A}}}catch(D){throw await M(D,await C(X))}}isFilePart($){return $&&typeof $==="object"&&"type"in $&&$.type==="file"}maybeEncodeFileParts($){for(let W of $.prompt)for(let j of W.content)if(this.isFilePart(j)){let Q=j;if(Q.data instanceof Uint8Array){let X=Uint8Array.from(Q.data),D=Buffer.from(X).toString("base64");Q.data=new URL(`data:${Q.mediaType||"application/octet-stream"};base64,${D}`)}}return $}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders($,W){return{"ai-language-model-specification-version":"3","ai-language-model-id":$,"ai-language-model-streaming":String(W)}}},c0=class{constructor($,W){this.modelId=$,this.config=W,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:$,headers:W,abortSignal:j,providerOptions:Q}){var X;let D=await U(this.config.headers());try{let{responseHeaders:A,value:Y,rawValue:K}=await R({url:this.getUrl(),headers:O(D,W!=null?W:{},this.getModelConfigHeaders(),await U(this.config.o11yHeaders)),body:{values:$,...Q?{providerOptions:Q}:{}},successfulResponseHandler:G(m0),failedResponseHandler:B({errorSchema:Z.any(),errorToMessage:(N)=>N}),...j&&{abortSignal:j},fetch:this.config.fetch});return{embeddings:Y.embeddings,usage:(X=Y.usage)!=null?X:void 0,providerMetadata:Y.providerMetadata,response:{headers:A,body:K},warnings:[]}}catch(A){throw await M(A,await C(D))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},m0=L(()=>V(Z.object({embeddings:Z.array(Z.array(Z.number())),usage:Z.object({tokens:Z.number()}).nullish(),providerMetadata:Z.record(Z.string(),Z.record(Z.string(),Z.unknown())).optional()}))),p0=class{constructor($,W){this.modelId=$,this.config=W,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:$,n:W,size:j,aspectRatio:Q,seed:X,files:D,mask:A,providerOptions:Y,headers:K,abortSignal:N}){var q,H,w,P;let b=await U(this.config.headers());try{let{responseHeaders:J,value:x,rawValue:I}=await R({url:this.getUrl(),headers:O(b,K!=null?K:{},this.getModelConfigHeaders(),await U(this.config.o11yHeaders)),body:{prompt:$,n:W,...j&&{size:j},...Q&&{aspectRatio:Q},...X&&{seed:X},...Y&&{providerOptions:Y},...D&&{files:D.map((F)=>IZ(F))},...A&&{mask:IZ(A)}},successfulResponseHandler:G(t0),failedResponseHandler:B({errorSchema:Z.any(),errorToMessage:(F)=>F}),...N&&{abortSignal:N},fetch:this.config.fetch});return{images:x.images,warnings:(q=x.warnings)!=null?q:[],providerMetadata:x.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:J},...x.usage!=null&&{usage:{inputTokens:(H=x.usage.inputTokens)!=null?H:void 0,outputTokens:(w=x.usage.outputTokens)!=null?w:void 0,totalTokens:(P=x.usage.totalTokens)!=null?P:void 0}}}}catch(J){throw await M(J,await C(b))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function IZ($){if($.type==="file"&&$.data instanceof Uint8Array)return{...$,data:g($.data)};return $}var i0=Z.object({images:Z.array(Z.unknown()).optional()}).catchall(Z.unknown()),d0=Z.discriminatedUnion("type",[Z.object({type:Z.literal("unsupported"),feature:Z.string(),details:Z.string().optional()}),Z.object({type:Z.literal("compatibility"),feature:Z.string(),details:Z.string().optional()}),Z.object({type:Z.literal("other"),message:Z.string()})]),n0=Z.object({inputTokens:Z.number().nullish(),outputTokens:Z.number().nullish(),totalTokens:Z.number().nullish()}),t0=Z.object({images:Z.array(Z.string()),warnings:Z.array(d0).optional(),providerMetadata:Z.record(Z.string(),i0).optional(),usage:n0.optional()}),s0=class{constructor($,W){this.modelId=$,this.config=W,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:$,n:W,aspectRatio:j,resolution:Q,duration:X,fps:D,seed:A,image:Y,providerOptions:K,headers:N,abortSignal:q}){var H;let w=await U(this.config.headers());try{let{responseHeaders:P,value:b}=await R({url:this.getUrl(),headers:O(w,N!=null?N:{},this.getModelConfigHeaders(),await U(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:$,n:W,...j&&{aspectRatio:j},...Q&&{resolution:Q},...X&&{duration:X},...D&&{fps:D},...A&&{seed:A},...K&&{providerOptions:K},...Y&&{image:a0(Y)}},successfulResponseHandler:async({response:J,url:x,requestBodyValues:I})=>{if(J.body==null)throw new v({message:"SSE response body is empty",url:x,requestBodyValues:I,statusCode:J.status});let E=yZ({stream:J.body,schema:Z4}).getReader(),{done:k,value:S}=await E.read();if(E.releaseLock(),k||!S)throw new v({message:"SSE stream ended without a data event",url:x,requestBodyValues:I,statusCode:J.status});if(!S.success)throw new v({message:"Failed to parse video SSE event",cause:S.error,url:x,requestBodyValues:I,statusCode:J.status});let T=S.value;if(T.type==="error")throw new v({message:T.message,statusCode:T.statusCode,url:x,requestBodyValues:I,responseHeaders:Object.fromEntries([...J.headers]),responseBody:JSON.stringify(T),data:{error:{message:T.message,type:T.errorType,param:T.param}}});return{value:{videos:T.videos,warnings:T.warnings,providerMetadata:T.providerMetadata},responseHeaders:Object.fromEntries([...J.headers])}},failedResponseHandler:B({errorSchema:Z.any(),errorToMessage:(J)=>J}),...q&&{abortSignal:q},fetch:this.config.fetch});return{videos:b.videos,warnings:(H=b.warnings)!=null?H:[],providerMetadata:b.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:P}}}catch(P){throw await M(P,await C(w))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function a0($){if($.type==="file"&&$.data instanceof Uint8Array)return{...$,data:g($.data)};return $}var o0=Z.object({videos:Z.array(Z.unknown()).optional()}).catchall(Z.unknown()),r0=Z.union([Z.object({type:Z.literal("url"),url:Z.string(),mediaType:Z.string()}),Z.object({type:Z.literal("base64"),data:Z.string(),mediaType:Z.string()})]),e0=Z.discriminatedUnion("type",[Z.object({type:Z.literal("unsupported"),feature:Z.string(),details:Z.string().optional()}),Z.object({type:Z.literal("compatibility"),feature:Z.string(),details:Z.string().optional()}),Z.object({type:Z.literal("other"),message:Z.string()})]),Z4=Z.discriminatedUnion("type",[Z.object({type:Z.literal("result"),videos:Z.array(r0),warnings:Z.array(e0).optional(),providerMetadata:Z.record(Z.string(),o0).optional()}),Z.object({type:Z.literal("error"),message:Z.string(),errorType:Z.string(),statusCode:Z.number(),param:Z.unknown().nullable()})]),$4=class{constructor($,W){this.modelId=$,this.config=W,this.specificationVersion="v3"}get provider(){return this.config.provider}async doRerank({documents:$,query:W,topN:j,headers:Q,abortSignal:X,providerOptions:D}){let A=await U(this.config.headers());try{let{responseHeaders:Y,value:K,rawValue:N}=await R({url:this.getUrl(),headers:O(A,Q!=null?Q:{},this.getModelConfigHeaders(),await U(this.config.o11yHeaders)),body:{documents:$,query:W,...j!=null?{topN:j}:{},...D?{providerOptions:D}:{}},successfulResponseHandler:G(W4),failedResponseHandler:B({errorSchema:Z.any(),errorToMessage:(q)=>q}),...X&&{abortSignal:X},fetch:this.config.fetch});return{ranking:K.ranking,providerMetadata:K.providerMetadata,response:{headers:Y,body:N},warnings:[]}}catch(Y){throw await M(Y,await C(A))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"3","ai-model-id":this.modelId}}},W4=L(()=>V(Z.object({ranking:Z.array(Z.object({index:Z.number(),relevanceScore:Z.number()})),providerMetadata:Z.record(Z.string(),Z.record(Z.string(),Z.unknown())).optional()}))),j4=L(()=>V(Z.object({objective:Z.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:Z.array(Z.string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Z.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:Z.number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:Z.object({include_domains:Z.array(Z.string()).optional().describe("List of domains to include in search results."),exclude_domains:Z.array(Z.string()).optional().describe("List of domains to exclude from search results."),after_date:Z.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:Z.object({max_chars_per_result:Z.number().optional().describe("Maximum characters per result."),max_chars_total:Z.number().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:Z.object({max_age_seconds:Z.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.")}))),Q4=L(()=>V(Z.union([Z.object({searchId:Z.string(),results:Z.array(Z.object({url:Z.string(),title:Z.string(),excerpt:Z.string(),publishDate:Z.string().nullable().optional(),relevanceScore:Z.number().optional()}))}),Z.object({error:Z.enum(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:Z.number().optional(),message:Z.string()})]))),X4=u({id:"gateway.parallel_search",inputSchema:j4,outputSchema:Q4}),Y4=($={})=>X4($),D4=L(()=>V(Z.object({query:Z.union([Z.string(),Z.array(Z.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:Z.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Z.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Z.number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Z.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Z.array(Z.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:Z.array(Z.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Z.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:Z.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:Z.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:Z.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:Z.enum(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),K4=L(()=>V(Z.union([Z.object({results:Z.array(Z.object({title:Z.string(),url:Z.string(),snippet:Z.string(),date:Z.string().optional(),lastUpdated:Z.string().optional()})),id:Z.string()}),Z.object({error:Z.enum(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Z.number().optional(),message:Z.string()})]))),J4=u({id:"gateway.perplexity_search",inputSchema:D4,outputSchema:K4}),F4=($={})=>J4($),N4={parallelSearch:Y4,perplexitySearch:F4};async function A4(){var $;return($=nZ.getContext().headers)==null?void 0:$["x-vercel-id"]}var U4="3.0.104",L4="0.0.1";function V4($={}){var W,j;let Q=null,X=null,D=(W=$.metadataCacheRefreshMillis)!=null?W:300000,A=0,Y=(j=fZ($.baseURL))!=null?j:"https://ai-gateway.vercel.sh/v3/ai",K=async()=>{try{let F=await q4($);return vZ({Authorization:`Bearer ${F.token}`,"ai-gateway-protocol-version":L4,[dZ]:F.authMethod,...$.headers},`ai-sdk/gateway/${U4}`)}catch(F){throw uZ.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:F})}},N=()=>{let F=h({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),E=h({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),k=h({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),S=h({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{let T=await A4();return{...F&&{"ai-o11y-deployment-id":F},...E&&{"ai-o11y-environment":E},...k&&{"ai-o11y-region":k},...T&&{"ai-o11y-request-id":T},...S&&{"ai-o11y-project-id":S}}}},q=(F)=>{return new l0(F,{provider:"gateway",baseURL:Y,headers:K,fetch:$.fetch,o11yHeaders:N()})},H=async()=>{var F,E,k;let S=(k=(E=(F=$._internal)==null?void 0:F.currentDate)==null?void 0:E.call(F).getTime())!=null?k:Date.now();if(!Q||S-A>D)A=S,Q=new bZ({baseURL:Y,headers:K,fetch:$.fetch}).getAvailableModels().then((T)=>{return X=T,T}).catch(async(T)=>{throw await M(T,await C(await K()))});return X?Promise.resolve(X):Q},w=async()=>{return new bZ({baseURL:Y,headers:K,fetch:$.fetch}).getCredits().catch(async(F)=>{throw await M(F,await C(await K()))})},P=async(F)=>{return new f0({baseURL:Y,headers:K,fetch:$.fetch}).getSpendReport(F).catch(async(E)=>{throw await M(E,await C(await K()))})},b=async(F)=>{return new u0({baseURL:Y,headers:K,fetch:$.fetch}).getGenerationInfo(F).catch(async(E)=>{throw await M(E,await C(await K()))})},J=function(F){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return q(F)};J.specificationVersion="v3",J.getAvailableModels=H,J.getCredits=w,J.getSpendReport=P,J.getGenerationInfo=b,J.imageModel=(F)=>{return new p0(F,{provider:"gateway",baseURL:Y,headers:K,fetch:$.fetch,o11yHeaders:N()})},J.languageModel=q;let x=(F)=>{return new c0(F,{provider:"gateway",baseURL:Y,headers:K,fetch:$.fetch,o11yHeaders:N()})};J.embeddingModel=x,J.textEmbeddingModel=x,J.videoModel=(F)=>{return new s0(F,{provider:"gateway",baseURL:Y,headers:K,fetch:$.fetch,o11yHeaders:N()})};let I=(F)=>{return new $4(F,{provider:"gateway",baseURL:Y,headers:K,fetch:$.fetch,o11yHeaders:N()})};return J.rerankingModel=I,J.reranking=I,J.chat=J.languageModel,J.embedding=J.embeddingModel,J.image=J.imageModel,J.video=J.videoModel,J.tools=N4,J}var e4=V4();async function q4($){let W=h({settingValue:$.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(W)return{token:W,authMethod:"api-key"};return{token:await tZ.getVercelOidcToken(),authMethod:"oidc"}}export{x4 as Dt,z as Et,uZ as Ft,z0 as Gt,M0 as Ht,R0 as It,zZ as Jt,C0 as Kt,V4 as Lt,e4 as Mt};
