import{s as e,t}from"./DrKWWDpL.js";import{t as n}from"./DYP3EJMY.js";import{Cn as r,Fn as i,In as a,It as o,Jn as s,Sn as c,Tt as l,Yn as u,bt as d,cn as f,jn as p,kt as m,ln as h,vn as g,vt as _,wt as v,xt as ee,zt as y}from"./D7w7HllH.js";import{t as b}from"./DTkg6Mnx.js";import{$ as x,B as te,E as S,F as C,G as w,H as T,I as E,L as ne,M as D,N as O,O as k,P as A,Q as re,S as ie,T as ae,U as j,V as M,X as N,Z as oe,a as se,b as ce,c as le,d as P,f as F,g as ue,i as I,k as de,l as fe,m as pe,n as me,q as he,r as L,t as ge,u as R,x as _e,y as ve,z as ye}from"./BSRD1o6J.js";import"./X_DUeLZp2.js";import"./H8RQGUV9.js";import{t as be}from"./BcRT_Mkt.js";import"./C5cNeu21.js";var xe=t(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);var u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}})),Se=t(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{getContext:()=>u.getContext,getVercelOidcToken:()=>d,getVercelOidcTokenSync:()=>f}),t.exports=c(l);var u=xe();async function d(){return``}function f(){return``}})),z=e(n(),1),Ce=Se(),we=Symbol.for(`vercel.ai.gateway.error`),Te,Ee,B=class e extends (Ee=Error,Te=we,Ee){constructor({message:e,statusCode:t=500,cause:n,generationId:r}){super(r?`${e} [${r}]`:e),this[Te]=!0,this.statusCode=t,this.cause=n,this.generationId=r}static isInstance(t){return e.hasMarker(t)}static hasMarker(e){return typeof e==`object`&&!!e&&we in e&&e[we]===!0}},De=`GatewayAuthenticationError`,Oe=`vercel.ai.gateway.error.${De}`,ke=Symbol.for(Oe),Ae,je,Me=class e extends (je=B,Ae=ke,je){constructor({message:e=`Authentication failed`,statusCode:t=401,cause:n,generationId:r}={}){super({message:e,statusCode:t,cause:n,generationId:r}),this[Ae]=!0,this.name=De,this.type=`authentication_error`}static isInstance(e){return B.hasMarker(e)&&ke in e}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r=`Authentication failed`,statusCode:i=401,cause:a,generationId:o}){let s;return s=t?`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.`:n?`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`:`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.`,new e({message:s,statusCode:i,cause:a,generationId:o})}},Ne=`GatewayInvalidRequestError`,Pe=`vercel.ai.gateway.error.${Ne}`,Fe=Symbol.for(Pe),Ie,Le,Re=class extends (Le=B,Ie=Fe,Le){constructor({message:e=`Invalid request`,statusCode:t=400,cause:n,generationId:r}={}){super({message:e,statusCode:t,cause:n,generationId:r}),this[Ie]=!0,this.name=Ne,this.type=`invalid_request_error`}static isInstance(e){return B.hasMarker(e)&&Fe in e}},ze=`GatewayRateLimitError`,Be=`vercel.ai.gateway.error.${ze}`,Ve=Symbol.for(Be),He,Ue,We=class extends (Ue=B,He=Ve,Ue){constructor({message:e=`Rate limit exceeded`,statusCode:t=429,cause:n,generationId:r}={}){super({message:e,statusCode:t,cause:n,generationId:r}),this[He]=!0,this.name=ze,this.type=`rate_limit_exceeded`}static isInstance(e){return B.hasMarker(e)&&Ve in e}},Ge=`GatewayModelNotFoundError`,Ke=`vercel.ai.gateway.error.${Ge}`,qe=Symbol.for(Ke),Je=S(()=>M(r({modelId:a()}))),Ye,Xe,Ze=class extends (Xe=B,Ye=qe,Xe){constructor({message:e=`Model not found`,statusCode:t=404,modelId:n,cause:r,generationId:i}={}){super({message:e,statusCode:t,cause:r,generationId:i}),this[Ye]=!0,this.name=Ge,this.type=`model_not_found`,this.modelId=n}static isInstance(e){return B.hasMarker(e)&&qe in e}},Qe=`GatewayInternalServerError`,$e=`vercel.ai.gateway.error.${Qe}`,et=Symbol.for($e),tt,nt,rt=class extends (nt=B,tt=et,nt){constructor({message:e=`Internal server error`,statusCode:t=500,cause:n,generationId:r}={}){super({message:e,statusCode:t,cause:n,generationId:r}),this[tt]=!0,this.name=Qe,this.type=`internal_server_error`}static isInstance(e){return B.hasMarker(e)&&et in e}},it=`GatewayResponseError`,at=`vercel.ai.gateway.error.${it}`,ot=Symbol.for(at),st,ct,lt=class extends (ct=B,st=ot,ct){constructor({message:e=`Invalid response from Gateway`,statusCode:t=502,response:n,validationError:r,cause:i,generationId:a}={}){super({message:e,statusCode:t,cause:i,generationId:a}),this[st]=!0,this.name=it,this.type=`response_error`,this.response=n,this.validationError=r}static isInstance(e){return B.hasMarker(e)&&ot in e}};async function ut({response:e,statusCode:t,defaultMessage:n=`Gateway request failed`,cause:r,authMethod:i}){let a=await E({value:e,schema:dt});if(!a.success){let i=typeof e==`object`&&e&&`generationId`in e?e.generationId:void 0;return new lt({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:a.error,cause:r,generationId:i})}let o=a.value,s=o.error.type,c=o.error.message,l=o.generationId??void 0;switch(s){case`authentication_error`:return Me.createContextualError({apiKeyProvided:i===`api-key`,oidcTokenProvided:i===`oidc`,statusCode:t,cause:r,generationId:l});case`invalid_request_error`:return new Re({message:c,statusCode:t,cause:r,generationId:l});case`rate_limit_exceeded`:return new We({message:c,statusCode:t,cause:r,generationId:l});case`model_not_found`:{let e=await E({value:o.error.param,schema:Je});return new Ze({message:c,statusCode:t,modelId:e.success?e.value.modelId:void 0,cause:r,generationId:l})}case`internal_server_error`:return new rt({message:c,statusCode:t,cause:r,generationId:l});default:return new rt({message:c,statusCode:t,cause:r,generationId:l})}}var dt=S(()=>M(r({error:r({message:a(),type:a().nullish(),param:u().nullish(),code:s([a(),c()]).nullish()}),generationId:a().nullish()}))),ft=`GatewayTimeoutError`,pt=`vercel.ai.gateway.error.${ft}`,mt=Symbol.for(pt),ht,gt,_t=class e extends (gt=B,ht=mt,gt){constructor({message:e=`Request timed out`,statusCode:t=408,cause:n,generationId:r}={}){super({message:e,statusCode:t,cause:n,generationId:r}),this[ht]=!0,this.name=ft,this.type=`timeout_error`}static isInstance(e){return B.hasMarker(e)&&mt in e}static createTimeoutError({originalMessage:t,statusCode:n=408,cause:r,generationId:i}){return new e({message:`Gateway request timed out: ${t}

    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`,statusCode:n,cause:r,generationId:i})}};function vt(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}async function V(e,t){return B.isInstance(e)?e:vt(e)?_t.createTimeoutError({originalMessage:e instanceof Error?e.message:`Unknown error`,cause:e}):j.isInstance(e)?e.cause&&vt(e.cause)?_t.createTimeoutError({originalMessage:e.message,cause:e}):await ut({response:yt(e),statusCode:e.statusCode??500,defaultMessage:`Gateway request failed`,cause:e,authMethod:t}):await ut({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:`Unknown Gateway error`,cause:e,authMethod:t})}function yt(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var bt=`ai-gateway-auth-method`;async function H(e){let t=await E({value:e[bt],schema:xt});return t.success?t.value:void 0}var xt=S(()=>M(s([h(`api-key`),h(`oidc`)]))),St=class{constructor(e){this.config=e}async getAvailableModels(){try{let{value:e}=await ce({url:`${this.config.baseURL}/config`,headers:await A(this.config.headers()),successfulResponseHandler:F(Ct),failedResponseHandler:P({errorSchema:v(),errorToMessage:e=>e}),fetch:this.config.fetch});return e}catch(e){throw await V(e)}}async getCredits(){try{let{value:e}=await ce({url:`${new URL(this.config.baseURL).origin}/v1/credits`,headers:await A(this.config.headers()),successfulResponseHandler:F(wt),failedResponseHandler:P({errorSchema:v(),errorToMessage:e=>e}),fetch:this.config.fetch});return e}catch(e){throw await V(e)}}},Ct=S(()=>M(r({models:l(r({id:a(),name:a(),description:a().nullish(),pricing:r({input:a(),output:a(),input_cache_read:a().nullish(),input_cache_write:a().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:r({specificationVersion:h(`v3`),provider:a(),modelId:a()}),modelType:_([`embedding`,`image`,`language`,`reranking`,`video`]).nullish()}))}))),wt=S(()=>M(r({balance:a(),total_used:a()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),Tt=class{constructor(e){this.config=e}async getSpendReport(e){try{let t=new URL(this.config.baseURL),n=new URLSearchParams;n.set(`start_date`,e.startDate),n.set(`end_date`,e.endDate),e.groupBy&&n.set(`group_by`,e.groupBy),e.datePart&&n.set(`date_part`,e.datePart),e.userId&&n.set(`user_id`,e.userId),e.model&&n.set(`model`,e.model),e.provider&&n.set(`provider`,e.provider),e.credentialType&&n.set(`credential_type`,e.credentialType),e.tags&&e.tags.length>0&&n.set(`tags`,e.tags.join(`,`));let{value:r}=await ce({url:`${t.origin}/v1/report?${n.toString()}`,headers:await A(this.config.headers()),successfulResponseHandler:F(Et),failedResponseHandler:P({errorSchema:v(),errorToMessage:e=>e}),fetch:this.config.fetch});return r}catch(e){throw await V(e)}}},Et=S(()=>M(r({results:l(r({day:a().optional(),hour:a().optional(),user:a().optional(),model:a().optional(),tag:a().optional(),provider:a().optional(),credential_type:_([`byok`,`system`]).optional(),total_cost:c(),market_cost:c().optional(),input_tokens:c().optional(),output_tokens:c().optional(),cached_input_tokens:c().optional(),cache_creation_input_tokens:c().optional(),reasoning_tokens:c().optional(),request_count:c().optional()}).transform(({credential_type:e,total_cost:t,market_cost:n,input_tokens:r,output_tokens:i,cached_input_tokens:a,cache_creation_input_tokens:o,reasoning_tokens:s,request_count:c,...l})=>({...l,...e===void 0?{}:{credentialType:e},totalCost:t,...n===void 0?{}:{marketCost:n},...r===void 0?{}:{inputTokens:r},...i===void 0?{}:{outputTokens:i},...a===void 0?{}:{cachedInputTokens:a},...o===void 0?{}:{cacheCreationInputTokens:o},...s===void 0?{}:{reasoningTokens:s},...c===void 0?{}:{requestCount:c}})))}))),Dt=class{constructor(e){this.config=e}async getGenerationInfo(e){try{let{value:t}=await ce({url:`${new URL(this.config.baseURL).origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await A(this.config.headers()),successfulResponseHandler:F(Ot),failedResponseHandler:P({errorSchema:v(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(e){throw await V(e)}}},Ot=S(()=>M(r({data:r({id:a(),total_cost:c(),upstream_inference_cost:c(),usage:c(),created_at:a(),model:a(),is_byok:m(),provider_name:a(),streamed:m(),finish_reason:a(),latency:c(),generation_time:c(),native_tokens_prompt:c(),native_tokens_completion:c(),native_tokens_reasoning:c(),native_tokens_cached:c(),native_tokens_cache_creation:c(),billable_web_search_calls:c()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:n,is_byok:r,provider_name:i,finish_reason:a,generation_time:o,native_tokens_prompt:s,native_tokens_completion:c,native_tokens_reasoning:l,native_tokens_cached:u,native_tokens_cache_creation:d,billable_web_search_calls:f,...p})=>({...p,totalCost:e,upstreamInferenceCost:t,createdAt:n,isByok:r,providerName:i,finishReason:a,generationTime:o,promptTokens:s,completionTokens:c,reasoningTokens:l,cachedTokens:u,cacheCreationTokens:d,billableWebSearchCalls:f}))}).transform(({data:e})=>e))),kt=class{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,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,i=await A(this.config.headers());try{let{responseHeaders:a,value:o,rawValue:s}=await D({url:this.getUrl(),headers:I(i,e.headers,this.getModelConfigHeaders(this.modelId,!1),await A(this.config.o11yHeaders)),body:t,successfulResponseHandler:F(v()),failedResponseHandler:P({errorSchema:v(),errorToMessage:e=>e}),...r&&{abortSignal:r},fetch:this.config.fetch});return{...o,request:{body:t},response:{headers:a,body:s},warnings:n}}catch(e){throw await V(e,await H(i))}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,i=await A(this.config.headers());try{let{value:a,responseHeaders:o}=await D({url:this.getUrl(),headers:I(i,e.headers,this.getModelConfigHeaders(this.modelId,!0),await A(this.config.o11yHeaders)),body:t,successfulResponseHandler:fe(v()),failedResponseHandler:P({errorSchema:v(),errorToMessage:e=>e}),...r&&{abortSignal:r},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(e){n.length>0&&e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(t.success){let r=t.value;if(r.type===`raw`&&!e.includeRawChunks)return;r.type===`response-metadata`&&r.timestamp&&typeof r.timestamp==`string`&&(r.timestamp=new Date(r.timestamp)),n.enqueue(r)}else n.error(t.error)}})),request:{body:t},response:{headers:o}}}catch(e){throw await V(e,await H(i))}}isFilePart(e){return e&&typeof e==`object`&&`type`in e&&e.type===`file`}maybeEncodeFileParts(e){for(let t of e.prompt)for(let e of t.content)if(this.isFilePart(e)){let t=e;if(t.data instanceof Uint8Array){let e=Uint8Array.from(t.data),n=Buffer.from(e).toString(`base64`);t.data=new URL(`data:${t.mediaType||`application/octet-stream`};base64,${n}`)}}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)}}},At=class{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:n,providerOptions:r}){let i=await A(this.config.headers());try{let{responseHeaders:a,value:o,rawValue:s}=await D({url:this.getUrl(),headers:I(i,t??{},this.getModelConfigHeaders(),await A(this.config.o11yHeaders)),body:{values:e,...r?{providerOptions:r}:{}},successfulResponseHandler:F(jt),failedResponseHandler:P({errorSchema:v(),errorToMessage:e=>e}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:o.embeddings,usage:o.usage??void 0,providerMetadata:o.providerMetadata,response:{headers:a,body:s},warnings:[]}}catch(e){throw await V(e,await H(i))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":`3`,"ai-model-id":this.modelId}}},jt=S(()=>M(r({embeddings:l(l(c())),usage:r({tokens:c()}).nullish(),providerMetadata:p(a(),p(a(),u())).optional()}))),Mt=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v3`,this.maxImagesPerCall=2**53-1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,files:a,mask:o,providerOptions:s,headers:c,abortSignal:l}){let u=await A(this.config.headers());try{let{responseHeaders:d,value:f,rawValue:p}=await D({url:this.getUrl(),headers:I(u,c??{},this.getModelConfigHeaders(),await A(this.config.o11yHeaders)),body:{prompt:e,n:t,...n&&{size:n},...r&&{aspectRatio:r},...i&&{seed:i},...s&&{providerOptions:s},...a&&{files:a.map(e=>Nt(e))},...o&&{mask:Nt(o)}},successfulResponseHandler:F(Lt),failedResponseHandler:P({errorSchema:v(),errorToMessage:e=>e}),...l&&{abortSignal:l},fetch:this.config.fetch});return{images:f.images,warnings:f.warnings??[],providerMetadata:f.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:d},...f.usage!=null&&{usage:{inputTokens:f.usage.inputTokens??void 0,outputTokens:f.usage.outputTokens??void 0,totalTokens:f.usage.totalTokens??void 0}}}}catch(e){throw await V(e,await H(u))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":`3`,"ai-model-id":this.modelId}}};function Nt(e){return e.type===`file`&&e.data instanceof Uint8Array?{...e,data:le(e.data)}:e}var Pt=r({images:l(u()).optional()}).catchall(u()),Ft=y(`type`,[r({type:h(`unsupported`),feature:a(),details:a().optional()}),r({type:h(`compatibility`),feature:a(),details:a().optional()}),r({type:h(`other`),message:a()})]),It=r({inputTokens:c().nullish(),outputTokens:c().nullish(),totalTokens:c().nullish()}),Lt=r({images:l(a()),warnings:l(Ft).optional(),providerMetadata:p(a(),Pt).optional(),usage:It.optional()}),Rt=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v3`,this.maxVideosPerCall=2**53-1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:n,resolution:r,duration:i,fps:a,seed:o,image:s,providerOptions:c,headers:l,abortSignal:u}){let d=await A(this.config.headers());try{let{responseHeaders:f,value:p}=await D({url:this.getUrl(),headers:I(d,l??{},this.getModelConfigHeaders(),await A(this.config.o11yHeaders),{accept:`text/event-stream`}),body:{prompt:e,n:t,...n&&{aspectRatio:n},...r&&{resolution:r},...i&&{duration:i},...a&&{fps:a},...o&&{seed:o},...c&&{providerOptions:c},...s&&{image:zt(s)}},successfulResponseHandler:async({response:e,url:t,requestBodyValues:n})=>{if(e.body==null)throw new j({message:`SSE response body is empty`,url:t,requestBodyValues:n,statusCode:e.status});let r=de({stream:e.body,schema:Ut}).getReader(),{done:i,value:a}=await r.read();if(r.releaseLock(),i||!a)throw new j({message:`SSE stream ended without a data event`,url:t,requestBodyValues:n,statusCode:e.status});if(!a.success)throw new j({message:`Failed to parse video SSE event`,cause:a.error,url:t,requestBodyValues:n,statusCode:e.status});let o=a.value;if(o.type===`error`)throw new j({message:o.message,statusCode:o.statusCode,url:t,requestBodyValues:n,responseHeaders:Object.fromEntries([...e.headers]),responseBody:JSON.stringify(o),data:{error:{message:o.message,type:o.errorType,param:o.param}}});return{value:{videos:o.videos,warnings:o.warnings,providerMetadata:o.providerMetadata},responseHeaders:Object.fromEntries([...e.headers])}},failedResponseHandler:P({errorSchema:v(),errorToMessage:e=>e}),...u&&{abortSignal:u},fetch:this.config.fetch});return{videos:p.videos,warnings:p.warnings??[],providerMetadata:p.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:f}}}catch(e){throw await V(e,await H(d))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":`3`,"ai-model-id":this.modelId}}};function zt(e){return e.type===`file`&&e.data instanceof Uint8Array?{...e,data:le(e.data)}:e}var Bt=r({videos:l(u()).optional()}).catchall(u()),Vt=s([r({type:h(`url`),url:a(),mediaType:a()}),r({type:h(`base64`),data:a(),mediaType:a()})]),Ht=y(`type`,[r({type:h(`unsupported`),feature:a(),details:a().optional()}),r({type:h(`compatibility`),feature:a(),details:a().optional()}),r({type:h(`other`),message:a()})]),Ut=y(`type`,[r({type:h(`result`),videos:l(Vt),warnings:l(Ht).optional(),providerMetadata:p(a(),Bt).optional()}),r({type:h(`error`),message:a(),errorType:a(),statusCode:c(),param:u().nullable()})]),Wt=class{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:n,headers:r,abortSignal:i,providerOptions:a}){let o=await A(this.config.headers());try{let{responseHeaders:s,value:c,rawValue:l}=await D({url:this.getUrl(),headers:I(o,r??{},this.getModelConfigHeaders(),await A(this.config.o11yHeaders)),body:{documents:e,query:t,...n==null?{}:{topN:n},...a?{providerOptions:a}:{}},successfulResponseHandler:F(Gt),failedResponseHandler:P({errorSchema:v(),errorToMessage:e=>e}),...i&&{abortSignal:i},fetch:this.config.fetch});return{ranking:c.ranking,providerMetadata:c.providerMetadata,response:{headers:s,body:l},warnings:[]}}catch(e){throw await V(e,await H(o))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":`3`,"ai-model-id":this.modelId}}},Gt=S(()=>M(r({ranking:l(r({index:c(),relevanceScore:c()})),providerMetadata:p(a(),p(a(),u())).optional()}))),Kt=pe({id:`gateway.parallel_search`,inputSchema:S(()=>M(r({objective:a().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:l(a()).optional().describe(`Optional search queries to supplement the objective. Maximum 200 characters per query.`),mode:_([`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:c().optional().describe(`Maximum number of results to return (1-20). Defaults to 10 if not specified.`),source_policy:r({include_domains:l(a()).optional().describe(`List of domains to include in search results.`),exclude_domains:l(a()).optional().describe(`List of domains to exclude from search results.`),after_date:a().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({max_chars_per_result:c().optional().describe(`Maximum characters per result.`),max_chars_total:c().optional().describe(`Maximum total characters across all results.`)}).optional().describe(`Excerpt configuration for controlling result length.`),fetch_policy:r({max_age_seconds:c().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.`)}))),outputSchema:S(()=>M(s([r({searchId:a(),results:l(r({url:a(),title:a(),excerpt:a(),publishDate:a().nullable().optional(),relevanceScore:c().optional()}))}),r({error:_([`api_error`,`rate_limit`,`timeout`,`invalid_input`,`configuration_error`,`unknown`]),statusCode:c().optional(),message:a()})])))}),qt=(e={})=>Kt(e),Jt=pe({id:`gateway.perplexity_search`,inputSchema:S(()=>M(r({query:s([a(),l(a())]).describe(`Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries.`),max_results:c().optional().describe(`Maximum number of search results to return (1-20, default: 10)`),max_tokens_per_page:c().optional().describe(`Maximum number of tokens to extract per search result page (256-2048, default: 2048)`),max_tokens:c().optional().describe(`Maximum total tokens across all search results (default: 25000, max: 1000000)`),country:a().optional().describe(`Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')`),search_domain_filter:l(a()).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:l(a()).optional().describe(`List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']`),search_after_date:a().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:a().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:a().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:a().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:_([`day`,`week`,`month`,`year`]).optional().describe(`Filter results by relative time period. Cannot be used with search_after_date or search_before_date.`)}))),outputSchema:S(()=>M(s([r({results:l(r({title:a(),url:a(),snippet:a(),date:a().optional(),lastUpdated:a().optional()})),id:a()}),r({error:_([`api_error`,`rate_limit`,`timeout`,`invalid_input`,`unknown`]),statusCode:c().optional(),message:a()})])))}),Yt={parallelSearch:qt,perplexitySearch:(e={})=>Jt(e)};async function Xt(){return(0,Ce.getContext)().headers?.[`x-vercel-id`]}var Zt=`3.0.99`,Qt=`0.0.1`;function $t(e={}){let t=null,n=null,r=e.metadataCacheRefreshMillis??1e3*60*5,i=0,a=te(e.baseURL)??`https://ai-gateway.vercel.sh/v3/ai`,o=async()=>{try{let t=await tn(e);return ye({Authorization:`Bearer ${t.token}`,"ai-gateway-protocol-version":Qt,[bt]:t.authMethod,...e.headers},`ai-sdk/gateway/${Zt}`)}catch(e){throw Me.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:e})}},s=()=>{let e=k({settingValue:void 0,environmentVariableName:`VERCEL_DEPLOYMENT_ID`}),t=k({settingValue:void 0,environmentVariableName:`VERCEL_ENV`}),n=k({settingValue:void 0,environmentVariableName:`VERCEL_REGION`}),r=k({settingValue:void 0,environmentVariableName:`VERCEL_PROJECT_ID`});return async()=>{let i=await Xt();return{...e&&{"ai-o11y-deployment-id":e},...t&&{"ai-o11y-environment":t},...n&&{"ai-o11y-region":n},...i&&{"ai-o11y-request-id":i},...r&&{"ai-o11y-project-id":r}}}},c=t=>new kt(t,{provider:`gateway`,baseURL:a,headers:o,fetch:e.fetch,o11yHeaders:s()}),l=async()=>{var s;let c=((s=e._internal)?.currentDate)?.call(s).getTime()??Date.now();return(!t||c-i>r)&&(i=c,t=new St({baseURL:a,headers:o,fetch:e.fetch}).getAvailableModels().then(e=>(n=e,e)).catch(async e=>{throw await V(e,await H(await o()))})),n?Promise.resolve(n):t},u=async()=>new St({baseURL:a,headers:o,fetch:e.fetch}).getCredits().catch(async e=>{throw await V(e,await H(await o()))}),d=async t=>new Tt({baseURL:a,headers:o,fetch:e.fetch}).getSpendReport(t).catch(async e=>{throw await V(e,await H(await o()))}),f=async t=>new Dt({baseURL:a,headers:o,fetch:e.fetch}).getGenerationInfo(t).catch(async e=>{throw await V(e,await H(await o()))}),p=function(e){if(new.target)throw Error(`The Gateway Provider model function cannot be called with the new keyword.`);return c(e)};p.specificationVersion=`v3`,p.getAvailableModels=l,p.getCredits=u,p.getSpendReport=d,p.getGenerationInfo=f,p.imageModel=t=>new Mt(t,{provider:`gateway`,baseURL:a,headers:o,fetch:e.fetch,o11yHeaders:s()}),p.languageModel=c;let m=t=>new At(t,{provider:`gateway`,baseURL:a,headers:o,fetch:e.fetch,o11yHeaders:s()});p.embeddingModel=m,p.textEmbeddingModel=m,p.videoModel=t=>new Rt(t,{provider:`gateway`,baseURL:a,headers:o,fetch:e.fetch,o11yHeaders:s()});let h=t=>new Wt(t,{provider:`gateway`,baseURL:a,headers:o,fetch:e.fetch,o11yHeaders:s()});return p.rerankingModel=h,p.reranking=h,p.chat=p.languageModel,p.embedding=p.embeddingModel,p.image=p.imageModel,p.video=p.videoModel,p.tools=Yt,p}var en=$t();async function tn(e){let t=k({settingValue:e.apiKey,environmentVariableName:`AI_GATEWAY_API_KEY`});return t?{token:t,authMethod:`api-key`}:{token:await(0,Ce.getVercelOidcToken)(),authMethod:`oidc`}}var nn=typeof globalThis==`object`?globalThis:typeof self==`object`?self:typeof window==`object`?window:typeof global==`object`?global:{},U=`1.9.0`,rn=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function an(e){var t=new Set([e]),n=new Set,r=e.match(rn);if(!r)return function(){return!1};var i={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(i.prerelease!=null)return function(t){return t===e};function a(e){return n.add(e),!1}function o(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(n.has(e))return!1;var r=e.match(rn);if(!r)return a(e);var s={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};return s.prerelease!=null||i.major!==s.major?a(e):i.major===0?i.minor===s.minor&&i.patch<=s.patch?o(e):a(e):i.minor<=s.minor?o(e):a(e)}}var on=an(U),sn=U.split(`.`)[0],W=Symbol.for(`opentelemetry.js.api.`+sn),G=nn;function cn(e,t,n,r){r===void 0&&(r=!1);var i=G[W]=G[W]??{version:U};if(!r&&i[e]){var a=Error(`@opentelemetry/api: Attempted duplicate registration of API: `+e);return n.error(a.stack||a.message),!1}if(i.version!==`1.9.0`){var a=Error(`@opentelemetry/api: Registration of version v`+i.version+` for `+e+` does not match previously registered API v`+U);return n.error(a.stack||a.message),!1}return i[e]=t,n.debug(`@opentelemetry/api: Registered a global for `+e+` v`+U+`.`),!0}function K(e){var t=G[W]?.version;if(!(!t||!on(t)))return G[W]?.[e]}function ln(e,t){t.debug(`@opentelemetry/api: Unregistering a global for `+e+` v`+U+`.`);var n=G[W];n&&delete n[e]}var un=function(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a},dn=function(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))},fn=function(){function e(e){this._namespace=e.namespace||`DiagComponentLogger`}return e.prototype.debug=function(){var e=[...arguments];return q(`debug`,this._namespace,e)},e.prototype.error=function(){var e=[...arguments];return q(`error`,this._namespace,e)},e.prototype.info=function(){var e=[...arguments];return q(`info`,this._namespace,e)},e.prototype.warn=function(){var e=[...arguments];return q(`warn`,this._namespace,e)},e.prototype.verbose=function(){var e=[...arguments];return q(`verbose`,this._namespace,e)},e}();function q(e,t,n){var r=K(`diag`);if(r)return n.unshift(t),r[e].apply(r,dn([],un(n),!1))}var J;(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`})(J||={});function pn(e,t){e<J.NONE?e=J.NONE:e>J.ALL&&(e=J.ALL),t||={};function n(n,r){var i=t[n];return typeof i==`function`&&e>=r?i.bind(t):function(){}}return{error:n(`error`,J.ERROR),warn:n(`warn`,J.WARN),info:n(`info`,J.INFO),debug:n(`debug`,J.DEBUG),verbose:n(`verbose`,J.VERBOSE)}}var mn=function(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a},hn=function(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))},gn=`diag`,_n=function(){function e(){function e(e){return function(){var t=[...arguments],n=K(`diag`);if(n)return n[e].apply(n,hn([],mn(t),!1))}}var t=this;t.setLogger=function(e,n){if(n===void 0&&(n={logLevel:J.INFO}),e===t){var r=Error(`Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation`);return t.error(r.stack??r.message),!1}typeof n==`number`&&(n={logLevel:n});var i=K(`diag`),a=pn(n.logLevel??J.INFO,e);if(i&&!n.suppressOverrideMessage){var o=Error().stack??`<failed to generate stacktrace>`;i.warn(`Current logger will be overwritten from `+o),a.warn(`Current logger will overwrite one already registered from `+o)}return cn(`diag`,a,t,!0)},t.disable=function(){ln(gn,t)},t.createComponentLogger=function(e){return new fn(e)},t.verbose=e(`verbose`),t.debug=e(`debug`),t.info=e(`info`),t.warn=e(`warn`),t.error=e(`error`)}return e.instance=function(){return this._instance||=new e,this._instance},e}();function vn(e){return Symbol.for(e)}var yn=new(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(e){return n._currentContext.get(e)},n.setValue=function(t,r){var i=new e(n._currentContext);return i._currentContext.set(t,r),i},n.deleteValue=function(t){var r=new e(n._currentContext);return r._currentContext.delete(t),r}}return e}()),bn=function(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a},xn=function(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))},Sn=function(){function e(){}return e.prototype.active=function(){return yn},e.prototype.with=function(e,t,n){var r=[...arguments].slice(3);return t.call.apply(t,xn([n],bn(r),!1))},e.prototype.bind=function(e,t){return t},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}(),Cn=function(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a},wn=function(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))},Tn=`context`,En=new Sn,Dn=function(){function e(){}return e.getInstance=function(){return this._instance||=new e,this._instance},e.prototype.setGlobalContextManager=function(e){return cn(Tn,e,_n.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(e,t,n){for(var r,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(r=this._getContextManager()).with.apply(r,wn([e,t,n],Cn(i),!1))},e.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},e.prototype._getContextManager=function(){return K(Tn)||En},e.prototype.disable=function(){this._getContextManager().disable(),ln(Tn,_n.instance())},e}(),On;(function(e){e[e.NONE=0]=`NONE`,e[e.SAMPLED=1]=`SAMPLED`})(On||={});var kn={traceId:`00000000000000000000000000000000`,spanId:`0000000000000000`,traceFlags:On.NONE},Y=function(){function e(e){e===void 0&&(e=kn),this._spanContext=e}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(e,t){return this},e.prototype.setAttributes=function(e){return this},e.prototype.addEvent=function(e,t){return this},e.prototype.addLink=function(e){return this},e.prototype.addLinks=function(e){return this},e.prototype.setStatus=function(e){return this},e.prototype.updateName=function(e){return this},e.prototype.end=function(e){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(e,t){},e}(),An=vn(`OpenTelemetry Context Key SPAN`);function jn(e){return e.getValue(An)||void 0}function Mn(){return jn(Dn.getInstance().active())}function Nn(e,t){return e.setValue(An,t)}function Pn(e){return e.deleteValue(An)}function Fn(e,t){return Nn(e,new Y(t))}function In(e){return jn(e)?.spanContext()}var Ln=/^([0-9a-f]{32})$/i,Rn=/^[0-9a-f]{16}$/i;function zn(e){return Ln.test(e)&&e!==`00000000000000000000000000000000`}function Bn(e){return Rn.test(e)&&e!==`0000000000000000`}function Vn(e){return zn(e.traceId)&&Bn(e.spanId)}function Hn(e){return new Y(e)}var Un=Dn.getInstance(),Wn=function(){function e(){}return e.prototype.startSpan=function(e,t,n){if(n===void 0&&(n=Un.active()),t?.root)return new Y;var r=n&&In(n);return Gn(r)&&Vn(r)?new Y(r):new Y},e.prototype.startActiveSpan=function(e,t,n,r){var i,a,o;if(!(arguments.length<2)){arguments.length===2?o=t:arguments.length===3?(i=t,o=n):(i=t,a=n,o=r);var s=a??Un.active(),c=this.startSpan(e,i,s),l=Nn(s,c);return Un.with(l,o,void 0,c)}},e}();function Gn(e){return typeof e==`object`&&typeof e.spanId==`string`&&typeof e.traceId==`string`&&typeof e.traceFlags==`number`}var Kn=new Wn,qn=function(){function e(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return e.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},e.prototype.startActiveSpan=function(e,t,n,r){var i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):Kn},e}(),Jn=new(function(){function e(){}return e.prototype.getTracer=function(e,t,n){return new Wn},e}()),Yn=function(){function e(){}return e.prototype.getTracer=function(e,t,n){return this.getDelegateTracer(e,t,n)??new qn(this,e,t,n)},e.prototype.getDelegate=function(){return this._delegate??Jn},e.prototype.setDelegate=function(e){this._delegate=e},e.prototype.getDelegateTracer=function(e,t,n){return this._delegate?.getTracer(e,t,n)},e}(),Xn;(function(e){e[e.UNSET=0]=`UNSET`,e[e.OK=1]=`OK`,e[e.ERROR=2]=`ERROR`})(Xn||={});var Zn=Dn.getInstance(),Qn=`trace`,$n=function(){function e(){this._proxyTracerProvider=new Yn,this.wrapSpanContext=Hn,this.isSpanContextValid=Vn,this.deleteSpan=Pn,this.getSpan=jn,this.getActiveSpan=Mn,this.getSpanContext=In,this.setSpan=Nn,this.setSpanContext=Fn}return e.getInstance=function(){return this._instance||=new e,this._instance},e.prototype.setGlobalTracerProvider=function(e){var t=cn(Qn,this._proxyTracerProvider,_n.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},e.prototype.getTracerProvider=function(){return K(Qn)||this._proxyTracerProvider},e.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},e.prototype.disable=function(){ln(Qn,_n.instance()),this._proxyTracerProvider=new Yn},e}().getInstance(),er=Object.defineProperty,tr=(e,t)=>{for(var n in t)er(e,n,{get:t[n],enumerable:!0})},nr=`AI_InvalidArgumentError`,rr=`vercel.ai.error.${nr}`,ir=Symbol.for(rr),ar,X=class extends T{constructor({parameter:e,value:t,message:n}){super({name:nr,message:`Invalid argument for parameter ${e}: ${n}`}),this[ar]=!0,this.parameter=e,this.value=t}static isInstance(e){return T.hasMarker(e,rr)}};ar=ir;var or=`AI_MissingToolResultsError`,sr=`vercel.ai.error.${or}`,cr=Symbol.for(sr),lr,ur=class extends T{constructor({toolCallIds:e}){super({name:or,message:`Tool result${e.length>1?`s are`:` is`} missing for tool call${e.length>1?`s`:``} ${e.join(`, `)}.`}),this[lr]=!0,this.toolCallIds=e}static isInstance(e){return T.hasMarker(e,sr)}};lr=cr;var dr=`AI_NoObjectGeneratedError`,fr=`vercel.ai.error.${dr}`,pr=Symbol.for(fr),mr,Z=class extends T{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:dr,message:e,cause:t}),this[mr]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return T.hasMarker(e,fr)}};mr=pr;var hr=class extends T{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}},gr=`AI_InvalidMessageRoleError`,_r=`vercel.ai.error.${gr}`,vr=Symbol.for(_r),yr,br=class extends T{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:gr,message:t}),this[yr]=!0,this.role=e}static isInstance(e){return T.hasMarker(e,_r)}};yr=vr;var xr=`AI_RetryError`,Sr=`vercel.ai.error.${xr}`,Cr=Symbol.for(Sr),wr,Tr=class extends T{constructor({message:e,reason:t,errors:n}){super({name:xr,message:e}),this[wr]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return T.hasMarker(e,Sr)}};wr=Cr;function Er(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function Dr({warning:e,provider:t,model:n}){let r=`AI SDK Warning (${t} / ${n}):`;switch(e.type){case`unsupported`:{let t=`${r} The feature "${e.feature}" is not supported.`;return e.details&&(t+=` ${e.details}`),t}case`compatibility`:{let t=`${r} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(t+=` ${e.details}`),t}case`other`:return`${r} ${e.message}`;default:return`${r} ${JSON.stringify(e,null,2)}`}}var Or=`AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.`,kr=!1,Ar=e=>{if(e.warnings.length===0)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t==`function`){t(e);return}kr||(kr=!0,console.info(Or));for(let t of e.warnings)console.warn(Dr({warning:t,provider:e.provider,model:e.model}))}};function jr({provider:e,modelId:t}){Ar({warnings:[{type:`compatibility`,feature:`specificationVersion`,details:`Using v2 specification compatibility mode. Some features may not be available.`}],provider:e,model:t})}function Mr(e){return e.specificationVersion===`v3`?e:(jr({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(e,t){switch(t){case`specificationVersion`:return`v3`;case`doGenerate`:return async(...t)=>{let n=await e.doGenerate(...t);return{...n,finishReason:Pr(n.finishReason),usage:Fr(n.usage)}};case`doStream`:return async(...t)=>{let n=await e.doStream(...t);return{...n,stream:Nr(n.stream)}};default:return e[t]}}}))}function Nr(e){return e.pipeThrough(new TransformStream({transform(e,t){switch(e.type){case`finish`:t.enqueue({...e,finishReason:Pr(e.finishReason),usage:Fr(e.usage)});break;default:t.enqueue(e);break}}}))}function Pr(e){return{unified:e===`unknown`?`other`:e,raw:void 0}}function Fr(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}}}function Ir(e){if(typeof e!=`string`){if(e.specificationVersion!==`v3`&&e.specificationVersion!==`v2`){let t=e;throw new hr({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return Mr(e)}return Lr().languageModel(e)}function Lr(){return globalThis.AI_SDK_DEFAULT_PROVIDER??en}function Rr(e){if(e!=null)return typeof e==`number`?e:e.totalMs}var zr=[{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]}],Br=e=>{let t=typeof e==`string`?se(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function Vr(e){return typeof e==`string`&&e.startsWith(`SUQz`)||typeof e!=`string`&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Br(e):e}function Hr({data:e,signatures:t}){let n=Vr(e),r=typeof n==`string`?se(n.substring(0,Math.min(n.length,24))):n;for(let e of t)if(r.length>=e.bytesPrefix.length&&e.bytesPrefix.every((e,t)=>e===null||r[t]===e))return e.mediaType}var Ur=`6.0.162`,Wr=async({url:e,maxBytes:t,abortSignal:n})=>{let r=e.toString();ne(r);try{let e=await fetch(r,{headers:ye({},`ai-sdk/${Ur}`,_e()),signal:n});if(e.redirected&&ne(e.url),!e.ok)throw new me({url:r,statusCode:e.status,statusText:e.statusText});return{data:await O({response:e,url:r,maxBytes:t??ge}),mediaType:e.headers.get(`content-type`)??void 0}}catch(e){throw me.isInstance(e)?e:new me({url:r,cause:e})}},Gr=(e=Wr)=>t=>Promise.all(t.map(async t=>t.isUrlSupportedByModel?null:e(t)));function Kr(e){try{let[t,n]=e.split(`,`);return{mediaType:t.split(`;`)[0].split(`:`)[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var qr=s([a(),d(Uint8Array),d(ArrayBuffer),o(e=>globalThis.Buffer?.isBuffer(e)??!1,{message:`Must be a Buffer`})]);function Jr(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:n}=Kr(e.toString());if(t==null||n==null)throw new T({name:`InvalidDataContentError`,message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function Yr(e){return typeof e==`string`?e:e instanceof ArrayBuffer?le(new Uint8Array(e)):le(e)}async function Xr({prompt:e,supportedUrls:t,download:n=Gr()}){let r=await Qr(e.messages,n,t),i=new Map;for(let t of e.messages)if(t.role===`assistant`&&Array.isArray(t.content))for(let e of t.content)e.type===`tool-approval-request`&&`approvalId`in e&&`toolCallId`in e&&i.set(e.approvalId,e.toolCallId);let a=new Set;for(let t of e.messages)if(t.role===`tool`){for(let e of t.content)if(e.type===`tool-approval-response`){let t=i.get(e.approvalId);t&&a.add(t)}}let o=[...e.system==null?[]:typeof e.system==`string`?[{role:`system`,content:e.system}]:Er(e.system).map(e=>({role:`system`,content:e.content,providerOptions:e.providerOptions})),...e.messages.map(e=>Zr({message:e,downloadedAssets:r}))],s=[];for(let e of o){if(e.role!==`tool`){s.push(e);continue}let t=s.at(-1);t?.role===`tool`?t.content.push(...e.content):s.push(e)}let c=new Set;for(let e of s)switch(e.role){case`assistant`:for(let t of e.content)t.type===`tool-call`&&!t.providerExecuted&&c.add(t.toolCallId);break;case`tool`:for(let t of e.content)t.type===`tool-result`&&c.delete(t.toolCallId);break;case`user`:case`system`:for(let e of a)c.delete(e);if(c.size>0)throw new ur({toolCallIds:Array.from(c)});break}for(let e of a)c.delete(e);if(c.size>0)throw new ur({toolCallIds:Array.from(c)});return s.filter(e=>e.role!==`tool`||e.content.length>0)}function Zr({message:e,downloadedAssets:t}){let n=e.role;switch(n){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(e=>$r(e,t)).filter(e=>e.type!==`text`||e.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(e=>e.type!==`text`||e.text!==``||e.providerOptions!=null).filter(e=>e.type!==`tool-approval-request`).map(e=>{let t=e.providerOptions;switch(e.type){case`file`:{let{data:n,mediaType:r}=Jr(e.data);return{type:`file`,data:n,filename:e.filename,mediaType:r??e.mediaType,providerOptions:t}}case`reasoning`:return{type:`reasoning`,text:e.text,providerOptions:t};case`text`:return{type:`text`,text:e.text,providerOptions:t};case`tool-call`:return{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:t};case`tool-result`:return{type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:ei(e.output),providerOptions:t}}}),providerOptions:e.providerOptions};case`tool`:return{role:`tool`,content:e.content.filter(e=>e.type!==`tool-approval-response`||e.providerExecuted).map(e=>{switch(e.type){case`tool-result`:return{type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:ei(e.output),providerOptions:e.providerOptions};case`tool-approval-response`:return{type:`tool-approval-response`,approvalId:e.approvalId,approved:e.approved,reason:e.reason}}}),providerOptions:e.providerOptions};default:throw new br({role:n})}}async function Qr(e,t,n){let r=e.filter(e=>e.role===`user`).map(e=>e.content).filter(e=>Array.isArray(e)).flat().filter(e=>e.type===`image`||e.type===`file`).map(e=>{let t=e.mediaType??(e.type===`image`?`image/*`:void 0),n=e.type===`image`?e.image:e.data;if(typeof n==`string`)try{n=new URL(n)}catch{}return{mediaType:t,data:n}}).filter(e=>e.data instanceof URL).map(e=>({url:e.data,isUrlSupportedByModel:e.mediaType!=null&&ae({url:e.data.toString(),mediaType:e.mediaType,supportedUrls:n})})),i=await t(r);return Object.fromEntries(i.map((e,t)=>e==null?null:[r[t].url.toString(),{data:e.data,mediaType:e.mediaType}]).filter(e=>e!=null))}function $r(e,t){if(e.type===`text`)return{type:`text`,text:e.text,providerOptions:e.providerOptions};let n,r=e.type;switch(r){case`image`:n=e.image;break;case`file`:n=e.data;break;default:throw Error(`Unsupported part type: ${r}`)}let{data:i,mediaType:a}=Jr(n),o=a??e.mediaType,s=i;if(s instanceof URL){let e=t[s.toString()];e&&(s=e.data,o??=e.mediaType)}switch(r){case`image`:return(s instanceof Uint8Array||typeof s==`string`)&&(o=Hr({data:s,signatures:zr})??o),{type:`file`,mediaType:o??`image/*`,filename:void 0,data:s,providerOptions:e.providerOptions};case`file`:if(o==null)throw Error(`Media type is missing for file part`);return{type:`file`,mediaType:o,filename:e.filename,data:s,providerOptions:e.providerOptions}}}function ei(e){return e.type===`content`?{type:`content`,value:e.value.map(e=>e.type===`media`?e.mediaType.startsWith(`image/`)?{type:`image-data`,data:e.data,mediaType:e.mediaType}:{type:`file-data`,data:e.data,mediaType:e.mediaType}:e)}:e}function ti({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:i,frequencyPenalty:a,seed:o,stopSequences:s}){if(e!=null){if(!Number.isInteger(e))throw new X({parameter:`maxOutputTokens`,value:e,message:`maxOutputTokens must be an integer`});if(e<1)throw new X({parameter:`maxOutputTokens`,value:e,message:`maxOutputTokens must be >= 1`})}if(t!=null&&typeof t!=`number`)throw new X({parameter:`temperature`,value:t,message:`temperature must be a number`});if(n!=null&&typeof n!=`number`)throw new X({parameter:`topP`,value:n,message:`topP must be a number`});if(r!=null&&typeof r!=`number`)throw new X({parameter:`topK`,value:r,message:`topK must be a number`});if(i!=null&&typeof i!=`number`)throw new X({parameter:`presencePenalty`,value:i,message:`presencePenalty must be a number`});if(a!=null&&typeof a!=`number`)throw new X({parameter:`frequencyPenalty`,value:a,message:`frequencyPenalty must be a number`});if(o!=null&&!Number.isInteger(o))throw new X({parameter:`seed`,value:o,message:`seed must be an integer`});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:i,frequencyPenalty:a,stopSequences:s,seed:o}}var Q=f(()=>s([ee(),a(),c(),m(),p(a(),Q.optional()),l(Q)])),$=p(a(),p(a(),Q.optional())),ni=r({type:h(`text`),text:a(),providerOptions:$.optional()}),ri=r({type:h(`image`),image:s([qr,d(URL)]),mediaType:a().optional(),providerOptions:$.optional()}),ii=r({type:h(`file`),data:s([qr,d(URL)]),filename:a().optional(),mediaType:a(),providerOptions:$.optional()}),ai=r({type:h(`reasoning`),text:a(),providerOptions:$.optional()}),oi=r({type:h(`tool-call`),toolCallId:a(),toolName:a(),input:u(),providerOptions:$.optional(),providerExecuted:m().optional()}),si=y(`type`,[r({type:h(`text`),value:a(),providerOptions:$.optional()}),r({type:h(`json`),value:Q,providerOptions:$.optional()}),r({type:h(`execution-denied`),reason:a().optional(),providerOptions:$.optional()}),r({type:h(`error-text`),value:a(),providerOptions:$.optional()}),r({type:h(`error-json`),value:Q,providerOptions:$.optional()}),r({type:h(`content`),value:l(s([r({type:h(`text`),text:a(),providerOptions:$.optional()}),r({type:h(`media`),data:a(),mediaType:a()}),r({type:h(`file-data`),data:a(),mediaType:a(),filename:a().optional(),providerOptions:$.optional()}),r({type:h(`file-url`),url:a(),providerOptions:$.optional()}),r({type:h(`file-id`),fileId:s([a(),p(a(),a())]),providerOptions:$.optional()}),r({type:h(`image-data`),data:a(),mediaType:a(),providerOptions:$.optional()}),r({type:h(`image-url`),url:a(),providerOptions:$.optional()}),r({type:h(`image-file-id`),fileId:s([a(),p(a(),a())]),providerOptions:$.optional()}),r({type:h(`custom`),providerOptions:$.optional()})]))})]),ci=r({type:h(`tool-result`),toolCallId:a(),toolName:a(),output:si,providerOptions:$.optional()}),li=r({type:h(`tool-approval-request`),approvalId:a(),toolCallId:a()}),ui=r({type:h(`tool-approval-response`),approvalId:a(),approved:m(),reason:a().optional()}),di=s([r({role:h(`system`),content:a(),providerOptions:$.optional()}),r({role:h(`user`),content:s([a(),l(s([ni,ri,ii]))]),providerOptions:$.optional()}),r({role:h(`assistant`),content:s([a(),l(s([ni,ii,ai,oi,ci,li]))]),providerOptions:$.optional()}),r({role:h(`tool`),content:l(s([ci,ui])),providerOptions:$.optional()})]);async function fi(e){if(e.prompt==null&&e.messages==null)throw new w({prompt:e,message:`prompt or messages must be defined`});if(e.prompt!=null&&e.messages!=null)throw new w({prompt:e,message:`prompt and messages cannot be defined at the same time`});if(e.system!=null&&typeof e.system!=`string`&&!Er(e.system).every(e=>typeof e==`object`&&!!e&&`role`in e&&e.role===`system`))throw new w({prompt:e,message:`system must be a string, SystemModelMessage, or array of SystemModelMessage`});let t;if(e.prompt!=null&&typeof e.prompt==`string`)t=[{role:`user`,content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new w({prompt:e,message:`prompt or messages must be defined`});if(t.length===0)throw new w({prompt:e,message:`messages must not be empty`});let n=await E({value:t,schema:l(di)});if(!n.success)throw new w({prompt:e,message:`The messages do not match the ModelMessage[] schema.`,cause:n.error});return{messages:t,system:e.system}}function pi(e){if(!Me.isInstance(e))return e;let t=(process==null?void 0:`production`)===`production`,n=`https://ai-sdk.dev/unauthenticated-ai-gateway`;return t?new T({name:`GatewayError`,message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`}):Object.assign(Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m

To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.

Alternatively, you can use a provider module instead of the AI Gateway.

Learn more: \x1B[34m${n}\x1B[0m

`),{name:`GatewayAuthenticationError`})}function mi({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}}function hi({model:e,settings:t,telemetry:n,headers:r}){return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,n])=>{if(t===`timeout`){let r=Rr(n);r!=null&&(e[`ai.settings.${t}`]=r)}else e[`ai.settings.${t}`]=n;return e},{}),...Object.entries(n?.metadata??{}).reduce((e,[t,n])=>(e[`ai.telemetry.metadata.${t}`]=n,e),{}),...Object.entries(r??{}).reduce((e,[t,n])=>(n!==void 0&&(e[`ai.request.headers.${t}`]=n),e),{})}}var gi={startSpan(){return _i},startActiveSpan(e,t,n,r){if(typeof t==`function`)return t(_i);if(typeof n==`function`)return n(_i);if(typeof r==`function`)return r(_i)}},_i={spanContext(){return vi},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}},vi={traceId:``,spanId:``,traceFlags:0};function yi({isEnabled:e=!1,tracer:t}={}){return e?t||$n.getTracer(`ai`):gi}async function bi({name:e,tracer:t,attributes:n,fn:r,endWhenDone:i=!0}){return t.startActiveSpan(e,{attributes:await n},async e=>{let t=Zn.active();try{let n=await Zn.with(t,()=>r(e));return i&&e.end(),n}catch(t){try{xi(e,t)}finally{e.end()}throw t}})}function xi(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Xn.ERROR,message:t.message})):e.setStatus({code:Xn.ERROR})}async function Si({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=await i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=await i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}function Ci(e){return JSON.stringify(e.map(e=>({...e,content:typeof e.content==`string`?e.content:e.content.map(e=>e.type===`file`?{...e,data:e.data instanceof Uint8Array?Yr(e.data):e.data}:e)})))}function wi(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:Ti(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function Ti(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Ei({error:e,exponentialBackoffDelay:t}){let n=e.responseHeaders;if(!n)return t;let r,i=n[`retry-after-ms`];if(i){let e=parseFloat(i);Number.isNaN(e)||(r=e)}let a=n[`retry-after`];if(a&&r===void 0){let e=parseFloat(a);r=Number.isNaN(e)?Date.parse(a)-Date.now():e*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}var Di=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async i=>Oi(i,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r});async function Oi(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:i},a=[]){try{return await e()}catch(o){if(ie(o)||t===0)throw o;let s=ve(o),c=[...a,o],l=c.length;if(l>t)throw new Tr({message:`Failed after ${l} attempts. Last error: ${s}`,reason:`maxRetriesExceeded`,errors:c});if(o instanceof Error&&j.isInstance(o)&&o.isRetryable===!0&&l<=t)return await ue(Ei({error:o,exponentialBackoffDelay:n}),{abortSignal:i}),Oi(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:i},c);throw l===1?o:new Tr({message:`Failed after ${l} attempts with non-retryable error: '${s}'`,reason:`errorNotRetryable`,errors:c})}}function ki({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new X({parameter:`maxRetries`,value:e,message:`maxRetries must be an integer`});if(e<0)throw new X({parameter:`maxRetries`,value:e,message:`maxRetries must be >= 0`})}let n=e??2;return{maxRetries:n,retry:Di({maxRetries:n,abortSignal:t})}}function Ai(e){let t=e.filter(e=>e.type===`reasoning`);return t.length===0?void 0:t.map(e=>e.text).join(`
`)}function ji(e){let t=e.filter(e=>e.type===`text`);if(t.length!==0)return t.map(e=>e.text).join(``)}tr({},{array:()=>Ii,choice:()=>Li,json:()=>Ri,object:()=>Fi,text:()=>Pi});function Mi(e){let t=[`ROOT`],n=-1,r=null;function i(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),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`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`);break}}function a(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop();break}}function o(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop();break}}for(let s=0;s<e.length;s++){let c=e[s];switch(t[t.length-1]){case`ROOT`:i(c,s,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=s,t.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break}break;case`INSIDE_OBJECT_KEY`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(c){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:i(c,s,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:a(c,s);break;case`INSIDE_STRING`:switch(c){case`"`:t.pop(),n=s;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=s}break;case`INSIDE_ARRAY_START`:switch(c){case`]`:n=s,t.pop();break;default:n=s,i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(c){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=s,t.pop();break;default:n=s;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),n=s;break;case`INSIDE_NUMBER`:switch(c){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=s;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s);break;default:t.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,s+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?a(c,s):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s)):n=s;break}}}let s=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:s+=`"`;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`:s+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:s+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?s+=`true`.slice(t.length):`false`.startsWith(t)?s+=`false`.slice(t.length):`null`.startsWith(t)&&(s+=`null`.slice(t.length))}}return s}async function Ni(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await C({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await C({text:Mi(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var Pi=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),Fi=({schema:e,name:t,description:n})=>{let r=L(e);return{name:`object`,responseFormat:A(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await C({text:e});if(!n.success)throw new Z({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=await E({value:n.value,schema:r});if(!i.success)throw new Z({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return i.value},async parsePartialOutput({text:e}){let t=await Ni(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},Ii=({element:e,name:t,description:n})=>{let r=L(e);return{name:`array`,responseFormat:A(r.jsonSchema).then(e=>{let{$schema:r,...i}=e;return{type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{elements:{type:`array`,items:i}},required:[`elements`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:e},t){let n=await C({text:e});if(!n.success)throw new Z({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=n.value;if(typeof i!=`object`||!i||!(`elements`in i)||!Array.isArray(i.elements))throw new Z({message:`No object generated: response did not match schema.`,cause:new N({value:i,cause:`response must be an object with an elements array`}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});for(let n of i.elements){let i=await E({value:n,schema:r});if(!i.success)throw new Z({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason})}return i.elements},async parsePartialOutput({text:e}){let t=await Ni(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let e=t.value;if(typeof e!=`object`||!e||!(`elements`in e)||!Array.isArray(e.elements))return;let n=t.state===`repaired-parse`&&e.elements.length>0?e.elements.slice(0,-1):e.elements,i=[];for(let e of n){let t=await E({value:e,schema:r});t.success&&i.push(t.value)}return{partial:i}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},n){if(t!=null)for(;e<t.length;e++)n.enqueue(t[e])}})}}},Li=({options:e,name:t,description:n})=>({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},...n!=null&&{description:n}}),async parseCompleteOutput({text:t},n){let r=await C({text:t});if(!r.success)throw new Z({message:`No object generated: could not parse the response.`,cause:r.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=r.value;if(typeof i!=`object`||!i||!(`result`in i)||typeof i.result!=`string`||!e.includes(i.result))throw new Z({message:`No object generated: response did not match schema.`,cause:new N({value:i,cause:`response must be an object that contains a choice value.`}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.result},async parsePartialOutput({text:t}){let n=await Ni(t);switch(n.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let t=n.value;if(typeof t!=`object`||!t||!(`result`in t)||typeof t.result!=`string`)return;let r=e.filter(e=>e.startsWith(t.result));return n.state===`successful-parse`?r.includes(t.result)?{partial:t.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),Ri=({name:e,description:t}={})=>({name:`json`,responseFormat:Promise.resolve({type:`json`,...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:e},t){let n=await C({text:e});if(!n.success)throw new Z({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await Ni(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return t.value===void 0?void 0:{partial:t.value}}},createElementStreamTransform(){}});R({prefix:`aitxt`,size:24});function zi(e,t){let n=new Headers(e??{});for(let[e,r]of Object.entries(t))n.has(e)||n.set(e,r);return n}TransformStream,S(()=>M(s([i({type:h(`text-start`),id:a(),providerMetadata:$.optional()}),i({type:h(`text-delta`),id:a(),delta:a(),providerMetadata:$.optional()}),i({type:h(`text-end`),id:a(),providerMetadata:$.optional()}),i({type:h(`error`),errorText:a()}),i({type:h(`tool-input-start`),toolCallId:a(),toolName:a(),providerExecuted:m().optional(),providerMetadata:$.optional(),dynamic:m().optional(),title:a().optional()}),i({type:h(`tool-input-delta`),toolCallId:a(),inputTextDelta:a()}),i({type:h(`tool-input-available`),toolCallId:a(),toolName:a(),input:u(),providerExecuted:m().optional(),providerMetadata:$.optional(),dynamic:m().optional(),title:a().optional()}),i({type:h(`tool-input-error`),toolCallId:a(),toolName:a(),input:u(),providerExecuted:m().optional(),providerMetadata:$.optional(),dynamic:m().optional(),errorText:a(),title:a().optional()}),i({type:h(`tool-approval-request`),approvalId:a(),toolCallId:a()}),i({type:h(`tool-output-available`),toolCallId:a(),output:u(),providerExecuted:m().optional(),providerMetadata:$.optional(),dynamic:m().optional(),preliminary:m().optional()}),i({type:h(`tool-output-error`),toolCallId:a(),errorText:a(),providerExecuted:m().optional(),providerMetadata:$.optional(),dynamic:m().optional()}),i({type:h(`tool-output-denied`),toolCallId:a()}),i({type:h(`reasoning-start`),id:a(),providerMetadata:$.optional()}),i({type:h(`reasoning-delta`),id:a(),delta:a(),providerMetadata:$.optional()}),i({type:h(`reasoning-end`),id:a(),providerMetadata:$.optional()}),i({type:h(`source-url`),sourceId:a(),url:a(),title:a().optional(),providerMetadata:$.optional()}),i({type:h(`source-document`),sourceId:a(),mediaType:a(),title:a(),filename:a().optional(),providerMetadata:$.optional()}),i({type:h(`file`),url:a(),mediaType:a(),providerMetadata:$.optional()}),i({type:o(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:a().optional(),data:u(),transient:m().optional()}),i({type:h(`start-step`)}),i({type:h(`finish-step`)}),i({type:h(`start`),messageId:a().optional(),messageMetadata:u().optional()}),i({type:h(`finish`),finishReason:_([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:u().optional()}),i({type:h(`abort`),reason:a().optional()}),i({type:h(`message-metadata`),messageMetadata:u()})])));function Bi(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){if(!t){t=!0;try{n&&await e.cancel?.call(e)}finally{try{e.releaseLock()}catch{}}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}R({prefix:`aitxt`,size:24}),S(()=>M(l(r({id:a(),role:_([`system`,`user`,`assistant`]),metadata:u().optional(),parts:l(s([r({type:h(`text`),text:a(),state:_([`streaming`,`done`]).optional(),providerMetadata:$.optional()}),r({type:h(`reasoning`),text:a(),state:_([`streaming`,`done`]).optional(),providerMetadata:$.optional()}),r({type:h(`source-url`),sourceId:a(),url:a(),title:a().optional(),providerMetadata:$.optional()}),r({type:h(`source-document`),sourceId:a(),mediaType:a(),title:a(),filename:a().optional(),providerMetadata:$.optional()}),r({type:h(`file`),mediaType:a(),filename:a().optional(),url:a(),providerMetadata:$.optional()}),r({type:h(`step-start`)}),r({type:a().startsWith(`data-`),id:a().optional(),data:u()}),r({type:h(`dynamic-tool`),toolName:a(),toolCallId:a(),state:h(`input-streaming`),input:u().optional(),providerExecuted:m().optional(),callProviderMetadata:$.optional(),output:g().optional(),errorText:g().optional(),approval:g().optional()}),r({type:h(`dynamic-tool`),toolName:a(),toolCallId:a(),state:h(`input-available`),input:u(),providerExecuted:m().optional(),output:g().optional(),errorText:g().optional(),callProviderMetadata:$.optional(),approval:g().optional()}),r({type:h(`dynamic-tool`),toolName:a(),toolCallId:a(),state:h(`approval-requested`),input:u(),providerExecuted:m().optional(),output:g().optional(),errorText:g().optional(),callProviderMetadata:$.optional(),approval:r({id:a(),approved:g().optional(),reason:g().optional()})}),r({type:h(`dynamic-tool`),toolName:a(),toolCallId:a(),state:h(`approval-responded`),input:u(),providerExecuted:m().optional(),output:g().optional(),errorText:g().optional(),callProviderMetadata:$.optional(),approval:r({id:a(),approved:m(),reason:a().optional()})}),r({type:h(`dynamic-tool`),toolName:a(),toolCallId:a(),state:h(`output-available`),input:u(),providerExecuted:m().optional(),output:u(),errorText:g().optional(),callProviderMetadata:$.optional(),resultProviderMetadata:$.optional(),preliminary:m().optional(),approval:r({id:a(),approved:h(!0),reason:a().optional()}).optional()}),r({type:h(`dynamic-tool`),toolName:a(),toolCallId:a(),state:h(`output-error`),input:u(),rawInput:u().optional(),providerExecuted:m().optional(),output:g().optional(),errorText:a(),callProviderMetadata:$.optional(),resultProviderMetadata:$.optional(),approval:r({id:a(),approved:h(!0),reason:a().optional()}).optional()}),r({type:h(`dynamic-tool`),toolName:a(),toolCallId:a(),state:h(`output-denied`),input:u(),providerExecuted:m().optional(),output:g().optional(),errorText:g().optional(),callProviderMetadata:$.optional(),approval:r({id:a(),approved:h(!1),reason:a().optional()})}),r({type:a().startsWith(`tool-`),toolCallId:a(),state:h(`input-streaming`),providerExecuted:m().optional(),callProviderMetadata:$.optional(),input:u().optional(),output:g().optional(),errorText:g().optional(),approval:g().optional()}),r({type:a().startsWith(`tool-`),toolCallId:a(),state:h(`input-available`),providerExecuted:m().optional(),input:u(),output:g().optional(),errorText:g().optional(),callProviderMetadata:$.optional(),approval:g().optional()}),r({type:a().startsWith(`tool-`),toolCallId:a(),state:h(`approval-requested`),input:u(),providerExecuted:m().optional(),output:g().optional(),errorText:g().optional(),callProviderMetadata:$.optional(),approval:r({id:a(),approved:g().optional(),reason:g().optional()})}),r({type:a().startsWith(`tool-`),toolCallId:a(),state:h(`approval-responded`),input:u(),providerExecuted:m().optional(),output:g().optional(),errorText:g().optional(),callProviderMetadata:$.optional(),approval:r({id:a(),approved:m(),reason:a().optional()})}),r({type:a().startsWith(`tool-`),toolCallId:a(),state:h(`output-available`),providerExecuted:m().optional(),input:u(),output:u(),errorText:g().optional(),callProviderMetadata:$.optional(),resultProviderMetadata:$.optional(),preliminary:m().optional(),approval:r({id:a(),approved:h(!0),reason:a().optional()}).optional()}),r({type:a().startsWith(`tool-`),toolCallId:a(),state:h(`output-error`),providerExecuted:m().optional(),input:u(),rawInput:u().optional(),output:g().optional(),errorText:a(),callProviderMetadata:$.optional(),resultProviderMetadata:$.optional(),approval:r({id:a(),approved:h(!0),reason:a().optional()}).optional()}),r({type:a().startsWith(`tool-`),toolCallId:a(),state:h(`output-denied`),providerExecuted:m().optional(),input:u(),output:g().optional(),errorText:g().optional(),callProviderMetadata:$.optional(),approval:r({id:a(),approved:h(!1),reason:a().optional()})})])).nonempty(`Message must contain at least one part`)})).nonempty(`Messages array must not be empty`)));var Vi={type:`no-schema`,jsonSchema:async()=>void 0,async validatePartialResult({value:e,textDelta:t}){return{success:!0,value:{partial:e,textDelta:t}}},async validateFinalResult(e,t){return e===void 0?{success:!1,error:new Z({message:`No object generated: response did not match schema.`,text:t.text,response:t.response,usage:t.usage,finishReason:t.finishReason})}:{success:!0,value:e}},createElementStream(){throw new oe({functionality:`element streams in no-schema mode`})}},Hi=e=>({type:`object`,jsonSchema:async()=>await e.jsonSchema,async validatePartialResult({value:e,textDelta:t}){return{success:!0,value:{partial:e,textDelta:t}}},async validateFinalResult(t){return E({value:t,schema:e})},createElementStream(){throw new oe({functionality:`element streams in object mode`})}}),Ui=e=>({type:`array`,jsonSchema:async()=>{let{$schema:t,...n}=await e.jsonSchema;return{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{elements:{type:`array`,items:n}},required:[`elements`],additionalProperties:!1}},async validatePartialResult({value:t,latestObject:n,isFirstDelta:r,isFinalDelta:i}){if(!x(t)||!re(t.elements))return{success:!1,error:new N({value:t,cause:`value must be an object that contains an array of elements`})};let a=t.elements,o=[];for(let t=0;t<a.length;t++){let n=a[t],r=await E({value:n,schema:e});if(!(t===a.length-1&&!i)){if(!r.success)return r;o.push(r.value)}}let s=n?.length??0,c=``;return r&&(c+=`[`),s>0&&(c+=`,`),c+=o.slice(s).map(e=>JSON.stringify(e)).join(`,`),i&&(c+=`]`),{success:!0,value:{partial:o,textDelta:c}}},async validateFinalResult(t){if(!x(t)||!re(t.elements))return{success:!1,error:new N({value:t,cause:`value must be an object that contains an array of elements`})};let n=t.elements;for(let t of n){let n=await E({value:t,schema:e});if(!n.success)return n}return{success:!0,value:n}},createElementStream(e){let t=0;return Bi(e.pipeThrough(new TransformStream({transform(e,n){switch(e.type){case`object`:{let r=e.object;for(;t<r.length;t++)n.enqueue(r[t]);break}case`text-delta`:case`finish`:case`error`:break;default:throw Error(`Unsupported chunk type: ${e}`)}}})))}}),Wi=e=>({type:`enum`,jsonSchema:async()=>({$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{result:{type:`string`,enum:e}},required:[`result`],additionalProperties:!1}),async validateFinalResult(t){if(!x(t)||typeof t.result!=`string`)return{success:!1,error:new N({value:t,cause:`value must be an object that contains a string in the "result" property.`})};let n=t.result;return e.includes(n)?{success:!0,value:n}:{success:!1,error:new N({value:t,cause:`value must be a string in the enum`})}},async validatePartialResult({value:t,textDelta:n}){if(!x(t)||typeof t.result!=`string`)return{success:!1,error:new N({value:t,cause:`value must be an object that contains a string in the "result" property.`})};let r=t.result,i=e.filter(e=>e.startsWith(r));return t.result.length===0||i.length===0?{success:!1,error:new N({value:t,cause:`value must be a string in the enum`})}:{success:!0,value:{partial:i.length>1?r:i[0],textDelta:n}}},createElementStream(){throw new oe({functionality:`element streams in enum mode`})}});function Gi({output:e,schema:t,enumValues:n}){switch(e){case`object`:return Hi(L(t));case`array`:return Ui(L(t));case`enum`:return Wi(n);case`no-schema`:return Vi;default:throw Error(`Unsupported output: ${e}`)}}async function Ki(e,t,n){let r=await C({text:e});if(!r.success)throw new Z({message:`No object generated: could not parse the response.`,cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=await t.validateFinalResult(r.value,{text:e,response:n.response,usage:n.usage});if(!i.success)throw new Z({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.value}async function qi(e,t,n,r){try{return await Ki(e,t,r)}catch(i){if(n!=null&&Z.isInstance(i)&&(he.isInstance(i.cause)||N.isInstance(i.cause))){let a=await n({text:e,error:i.cause});if(a===null)throw i;return await Ki(a,t,r)}throw i}}function Ji({output:e,schema:t,schemaName:n,schemaDescription:r,enumValues:i}){if(e!=null&&e!==`object`&&e!==`array`&&e!==`enum`&&e!==`no-schema`)throw new X({parameter:`output`,value:e,message:`Invalid output type.`});if(e===`no-schema`){if(t!=null)throw new X({parameter:`schema`,value:t,message:`Schema is not supported for no-schema output.`});if(r!=null)throw new X({parameter:`schemaDescription`,value:r,message:`Schema description is not supported for no-schema output.`});if(n!=null)throw new X({parameter:`schemaName`,value:n,message:`Schema name is not supported for no-schema output.`});if(i!=null)throw new X({parameter:`enumValues`,value:i,message:`Enum values are not supported for no-schema output.`})}if(e===`object`){if(t==null)throw new X({parameter:`schema`,value:t,message:`Schema is required for object output.`});if(i!=null)throw new X({parameter:`enumValues`,value:i,message:`Enum values are not supported for object output.`})}if(e===`array`){if(t==null)throw new X({parameter:`schema`,value:t,message:`Element schema is required for array output.`});if(i!=null)throw new X({parameter:`enumValues`,value:i,message:`Enum values are not supported for array output.`})}if(e===`enum`){if(t!=null)throw new X({parameter:`schema`,value:t,message:`Schema is not supported for enum output.`});if(r!=null)throw new X({parameter:`schemaDescription`,value:r,message:`Schema description is not supported for enum output.`});if(n!=null)throw new X({parameter:`schemaName`,value:n,message:`Schema name is not supported for enum output.`});if(i==null)throw new X({parameter:`enumValues`,value:i,message:`Enum values are required for enum output.`});for(let e of i)if(typeof e!=`string`)throw new X({parameter:`enumValues`,value:e,message:`Enum values must be strings.`})}}var Yi=R({prefix:`aiobj`,size:24});async function Xi(e){let{model:t,output:n=`object`,system:r,prompt:i,messages:a,maxRetries:o,abortSignal:s,headers:c,experimental_repairText:l,experimental_telemetry:u,experimental_download:d,providerOptions:f,_internal:{generateId:p=Yi,currentDate:m=()=>new Date}={},...h}=e,g=Ir(t),_=`enum`in e?e.enum:void 0,{schema:v,schemaDescription:ee,schemaName:y}=`schema`in e?e:{};Ji({output:n,schema:v,schemaName:y,schemaDescription:ee,enumValues:_});let{maxRetries:b,retry:x}=ki({maxRetries:o,abortSignal:s}),te=Gi({output:n,schema:v,enumValues:_}),S=ti(h),C=ye(c??{},`ai/${Ur}`),w=hi({model:g,telemetry:u,headers:C,settings:{...S,maxRetries:b}}),T=yi(u),E=await te.jsonSchema();try{return await bi({name:`ai.generateObject`,attributes:Si({telemetry:u,attributes:{...mi({operationId:`ai.generateObject`,telemetry:u}),...w,"ai.prompt":{input:()=>JSON.stringify({system:r,prompt:i,messages:a})},"ai.schema":E==null?void 0:{input:()=>JSON.stringify(E)},"ai.schema.name":y,"ai.schema.description":ee,"ai.settings.output":te.type}}),tracer:T,fn:async e=>{let t,n,o,c,_,v,b,ne,D=await Xr({prompt:await fi({system:r,prompt:i,messages:a}),supportedUrls:await g.supportedUrls,download:d}),O=await x(()=>bi({name:`ai.generateObject.doGenerate`,attributes:Si({telemetry:u,attributes:{...mi({operationId:`ai.generateObject.doGenerate`,telemetry:u}),...w,"ai.prompt.messages":{input:()=>Ci(D)},"gen_ai.system":g.provider,"gen_ai.request.model":g.modelId,"gen_ai.request.frequency_penalty":S.frequencyPenalty,"gen_ai.request.max_tokens":S.maxOutputTokens,"gen_ai.request.presence_penalty":S.presencePenalty,"gen_ai.request.temperature":S.temperature,"gen_ai.request.top_k":S.topK,"gen_ai.request.top_p":S.topP}}),tracer:T,fn:async e=>{let t=await g.doGenerate({responseFormat:{type:`json`,schema:E,name:y,description:ee},...ti(h),prompt:D,providerOptions:f,abortSignal:s,headers:C}),n={id:t.response?.id??p(),timestamp:t.response?.timestamp??m(),modelId:t.response?.modelId??g.modelId,headers:t.response?.headers,body:t.response?.body},r=ji(t.content),i=Ai(t.content);if(r===void 0)throw new Z({message:`No object generated: the model did not return a response.`,response:n,usage:wi(t.usage),finishReason:t.finishReason.unified});return e.setAttributes(await Si({telemetry:u,attributes:{"ai.response.finishReason":t.finishReason.unified,"ai.response.object":{output:()=>r},"ai.response.id":n.id,"ai.response.model":n.modelId,"ai.response.timestamp":n.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(t.providerMetadata),"ai.usage.promptTokens":t.usage.inputTokens.total,"ai.usage.completionTokens":t.usage.outputTokens.total,"gen_ai.response.finish_reasons":[t.finishReason.unified],"gen_ai.response.id":n.id,"gen_ai.response.model":n.modelId,"gen_ai.usage.input_tokens":t.usage.inputTokens.total,"gen_ai.usage.output_tokens":t.usage.outputTokens.total}})),{...t,objectText:r,reasoning:i,responseData:n}}}));t=O.objectText,n=O.finishReason.unified,o=wi(O.usage),c=O.warnings,b=O.providerMetadata,v=O.request??{},_=O.responseData,ne=O.reasoning,Ar({warnings:c,provider:g.provider,model:g.modelId});let k=await qi(t,te,l,{response:_,usage:o,finishReason:n});return e.setAttributes(await Si({telemetry:u,attributes:{"ai.response.finishReason":n,"ai.response.object":{output:()=>JSON.stringify(k)},"ai.response.providerMetadata":JSON.stringify(b),"ai.usage.promptTokens":o.inputTokens,"ai.usage.completionTokens":o.outputTokens}})),new Zi({object:k,reasoning:ne,finishReason:n,usage:o,warnings:c,request:v,response:_,providerMetadata:b})}})}catch(e){throw pi(e)}}var Zi=class{constructor(e){this.object=e.object,this.finishReason=e.finishReason,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.response=e.response,this.request=e.request,this.reasoning=e.reasoning}toJsonResponse(e){return new Response(JSON.stringify(this.object),{status:e?.status??200,headers:zi(e?.headers,{"content-type":`application/json; charset=utf-8`})})}};R({prefix:`aiobj`,size:24});var Qi=b(`dialectic`),$i=r({key:a().min(1).max(100).describe(`Stable semantic key (kebab-case). E.g. "prefers-zero-deps".`),value:a().min(1).max(500).describe(`JSON-serialisable value string.`),confidence:c().min(0).max(1).describe(`Bayesian confidence in [0.0, 1.0].`)}),ea=r({key:a().min(1).max(100).describe(`Short observation title (kebab-case or sentence).`),value:a().min(1).max(300).describe(`Observation detail text.`),peerId:a().min(1).describe(`The peer ID that produced this insight.`),confidence:c().min(0).max(1).describe(`Confidence level in [0.0, 1.0].`)}),ta=r({globalTraits:l($i).max(10).describe(`Persistent user-level traits extracted from this turn. Only include traits that can be inferred with reasonable confidence. Omit when there is no clear signal.`),peerInsights:l(ea).max(10).describe(`Agent-scoped observations relevant only to the active peer. Include implementation details, task-specific findings, and agent-level patterns.`),sessionNarrativeDelta:a().max(500).optional().describe(`One-to-two sentence summary of what happened in this turn. Omit for short acks or low-signal exchanges.`)}),na=.6,ra=.5;function ia(e){return`You are a structured insight extractor for an AI coding assistant.

Your task is to analyse a single conversational turn (user message + system response) and extract:

1. **Global traits** — persistent, session-independent facts about the USER's preferences,
   style, and constraints.
   - Only record a trait when the signal is **clear and unambiguous** and the confidence is ≥ 0.6.
   - Ambiguous phrasing, one-off requests, or rhetorical language must NOT produce traits.
   - Examples of stable trait keys (kebab-case): "prefers-zero-deps", "verbose-git-logs",
     "strict-typescript", "prefers-dark-mode", "always-squash-merges".

2. **Peer insights** — observations relevant to the active agent ("${e}") in the
   current task context. These include implementation findings, task-specific patterns,
   and agent-level notes. Scoped to this peer; not globally visible.
   - Confidence ≥ 0.5 required for peer insights (lower bar than global traits).

3. **Session narrative delta** — a 1–2 sentence summary of what was decided or accomplished
   in this turn. Omit if the turn is a short ack or has no meaningful narrative content.

Be concise and precise. Only extract what can be directly inferred from the messages.
Do not hallucinate traits or insights. Return empty arrays when there is no clear signal.

---

## Few-shot examples

### Example 1 — Clear global trait (confidence ≥ 0.6, EMIT trait)

**User message**: "I never want to see \`any\` in this codebase. Every type must be explicit."

**System response**: "Understood. I'll ensure all types are explicitly declared and will not
use \`any\` or unsafe casts in any code I generate."

**Expected output**:
\`\`\`json
{
  "globalTraits": [
    {
      "key": "strict-typescript",
      "value": "never use any; all types must be explicit",
      "confidence": 0.95
    }
  ],
  "peerInsights": [],
  "sessionNarrativeDelta": "User stated a blanket prohibition on the any type; assistant acknowledged."
}
\`\`\`

**Why confidence 0.95**: The user said "never" and "every" — absolute, unambiguous language
with no hedging. This is a core stylistic constraint worth persisting globally.

---

### Example 2 — Ambiguous signal (confidence < 0.6, DO NOT emit trait)

**User message**: "Maybe avoid heavy frameworks for this one? I'm not sure yet."

**System response**: "Sure, I'll keep the implementation lightweight for now — we can add a
framework later if needed."

**Expected output**:
\`\`\`json
{
  "globalTraits": [],
  "peerInsights": [
    {
      "key": "lightweight-preferred-for-current-task",
      "value": "User expressed tentative preference for no heavy framework; subject to change.",
      "peerId": "${e}",
      "confidence": 0.55
    }
  ],
  "sessionNarrativeDelta": "User requested a lightweight approach for the current task with uncertainty."
}
\`\`\`

**Why no global trait**: "Maybe" and "I'm not sure yet" signal uncertainty. Emitting a
persistent "prefers-zero-frameworks" trait from this turn would over-generalise a tentative,
task-scoped remark. The information is preserved as a lower-confidence peer insight instead.

---

### Example 3 — Peer insight vs global trait disambiguation

**User message**: "For T1532, please add TSDoc to every exported symbol in dialectic-evaluator.ts."

**System response**: "Done — I've added TSDoc comments to all 4 exported functions and the
2 exported constants in packages/core/src/memory/dialectic-evaluator.ts."

**Expected output**:
\`\`\`json
{
  "globalTraits": [
    {
      "key": "requires-tsdoc-on-exports",
      "value": "all exported symbols must have TSDoc comments",
      "confidence": 0.72
    }
  ],
  "peerInsights": [
    {
      "key": "tsdoc-applied-dialectic-evaluator",
      "value": "TSDoc added to 4 functions and 2 constants in dialectic-evaluator.ts for T1532.",
      "peerId": "${e}",
      "confidence": 0.9
    }
  ],
  "sessionNarrativeDelta": "User requested TSDoc on all exports in dialectic-evaluator.ts; assistant confirmed completion."
}
\`\`\`

**Why both**: The user's request implies a general documentation standard (global trait,
confidence 0.72 — stated as a direct instruction, but only in this file context, so modest
confidence). The task-specific outcome (which file, which symbols) is a peer insight with
higher confidence because it describes a concrete, verifiable result.`}async function aa(e){let t={globalTraits:[],peerInsights:[]};if(!e.userMessage.trim()&&!e.systemResponse.trim())return t;let n=await be(`warm`);if(!n||n.name===`none`)return Qi.warn({event:`dialectic.no_backend`,backend:n?.name??`none`,sessionId:e.sessionId,activePeerId:e.activePeerId},`evaluateDialectic: no LLM backend available — skipping extraction`),t;let r=`<user_message>\n${e.userMessage}\n</user_message>\n\n<system_response>\n${e.systemResponse}\n</system_response>\n\nActive peer: ${e.activePeerId}\nSession: ${e.sessionId}`;try{let{object:t}=await Xi({model:n.model,schema:ta,system:ia(e.activePeerId),prompt:r});return{globalTraits:t.globalTraits.filter(e=>e.confidence>=na),peerInsights:t.peerInsights.filter(e=>e.confidence>=ra).map(t=>({...t,peerId:t.peerId||e.activePeerId})),sessionNarrativeDelta:t.sessionNarrativeDelta}}catch(r){let i=r instanceof Error?r.code??r.name??`UNKNOWN`:`UNKNOWN`,a=ca(`${n.name}|${n.modelId}|${i}`),o={event:`dialectic.generate_object_failed`,errorCode:i,modelId:n.modelId,backendName:n.name,sessionId:e.sessionId,activePeerId:e.activePeerId,firstOccurrence:a};return a?Qi.warn(o,`evaluateDialectic: generateObject failed — returning empty insights (subsequent identical failures silenced for 24h via state cache)`):Qi.debug(o,`evaluateDialectic: generateObject failed (repeat — silenced)`),t}}function oa(){return(0,z.join)({}.XDG_STATE_HOME||(0,z.join)((0,z.homedir)(),`.local`,`state`),`cleo`,`dialectic-failures.json`)}var sa=1440*60*1e3;function ca(e){if(la.has(e))return!1;la.add(e);let t=oa(),n={};try{if((0,z.existsSync)(t)){let e=(0,z.readFileSync)(t,`utf8`);n=JSON.parse(e)}}catch{n={}}let r=Date.now();for(let[e,t]of Object.entries(n))(typeof t!=`number`||r-t>sa)&&delete n[e];let i=n[e],a=!i||r-i>sa;if(a){n[e]=r;try{(0,z.mkdirSync)((0,z.dirname)(t),{recursive:!0}),(0,z.writeFileSync)(t,JSON.stringify(n))}catch{}}return a}var la=new Set;export{ra as n,aa as r,na as t};